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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Ztiany/Repository | Kotlin/Kotlin-Basic/src/main/BennyHuo/chapter05/TailRec.kt | 2 | 934 | package chapter05
data class ListNode(val value: Int, var next: ListNode? = null)
/**尾递归优化*/
tailrec fun findListNode(head: ListNode?, value: Int): ListNode? {
head ?: return null
if (head.value == value) return head
return findListNode(head.next, value)
}
private const val MAX_NODE_COUNT = 100000
fun main(args: Array<String>) {
val head = ListNode(0)
var p = head
for (i in 1..MAX_NODE_COUNT) {
p.next = ListNode(i)
p = p.next!!
}
println(findListNode(head, MAX_NODE_COUNT - 2)?.value)
}
fun factorial(n: Long): Long {
return n * factorial(n - 1)
}
data class TreeNode(val value: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun findTreeNode(root: TreeNode?, value: Int): TreeNode? {
root ?: return null
if (root.value == value) return root
return findTreeNode(root.left, value) ?: return findTreeNode(root.right, value)
} | apache-2.0 | 50c0c896e5fe8cc998627fb27d1ce5af | 23.342105 | 83 | 0.649351 | 3.347826 | false | false | false | false |
shlusiak/Freebloks-Android | themes/src/main/java/de/saschahlusiak/freebloks/theme/ColorThemes.kt | 1 | 533 | package de.saschahlusiak.freebloks.theme
import android.graphics.Color
/**
* Some plain color themes
*/
object ColorThemes {
val Green = ColorTheme("green", label = R.string.theme_green, r = 0, g = 64, b = 0)
val Blue = ColorTheme("blue", label = R.string.theme_blue, colorRes = R.color.theme_background_blue)
// only added in Debug builds
val Black = ColorTheme("black", label = R.string.theme_black, color = Color.BLACK)
val White = ColorTheme("white", label = R.string.theme_white, color = Color.WHITE)
}
| gpl-2.0 | 6f77632b156e63fd078fe5db71b94adb | 34.533333 | 104 | 0.690432 | 3.577181 | false | false | false | false |
ToxicBakery/ViewPagerTransforms | library/src/main/java/com/ToxicBakery/viewpager/transforms/ZoomInTransformer.kt | 1 | 1095 | /*
* Copyright 2014 Toxic Bakery
*
* 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.ToxicBakery.viewpager.transforms
import android.view.View
open class ZoomInTransformer : ABaseTransformer() {
override fun onTransform(page: View, position: Float) {
val scale = if (position < 0) position + 1f else Math.abs(1f - position)
page.scaleX = scale
page.scaleY = scale
page.pivotX = page.width * 0.5f
page.pivotY = page.height * 0.5f
page.alpha = if (position < -1f || position > 1f) 0f else 1f - (scale - 1f)
}
}
| apache-2.0 | e3ff9b87ae47e200f2f831b6b155a204 | 33.21875 | 83 | 0.691324 | 3.775862 | false | false | false | false |
runjia1987/crawler-client-kt | src/main/java/org/jackJew/biz/engine/util/GsonUtils.kt | 1 | 1187 | package org.jackJew.biz.engine.util
import com.google.gson.GsonBuilder
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.nio.charset.Charset
class GsonUtils {
companion object {
private val GSON = GsonBuilder().disableHtmlEscaping().create()
fun <T> fromJson(content: String, cls: Class<T>) = GSON.fromJson(content, cls)
fun toJson(obj: Any) = GSON.toJson(obj)
}
}
class IOUtils {
companion object {
fun toString(ins: InputStream, charset: Charset) =
StringBuilder(1 shl 8).also {
val buff = ByteArray(1 shl 8)
var count: Int
while (ins.read(buff).let { count = it; count != -1 }) {
it.append(String(buff, 0, count, charset))
}
}.toString()
fun getBytes(ins: InputStream) =
ByteArrayOutputStream(1 shl 8).also {
val buff = ByteArray(1 shl 8)
var count: Int
while (ins.read(buff).let { count = it; count != -1 }) {
it.write(buff, 0, count)
}
}.toByteArray()
}
}
class ValidationException(message: String): RuntimeException(message) {
@Synchronized override fun fillInStackTrace(): Throwable = this
} | apache-2.0 | 59266786c322d7b94fce58ab470af258 | 25.4 | 82 | 0.6369 | 3.917492 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/TwitterCardUtils.kt | 1 | 3179 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util
import android.graphics.Point
import android.text.TextUtils
import de.vanita5.twittnuker.extension.model.getAsInteger
import de.vanita5.twittnuker.extension.model.getString
import de.vanita5.twittnuker.model.ParcelableCardEntity
import de.vanita5.twittnuker.model.ParcelableStatus
import java.util.regex.Pattern
object TwitterCardUtils {
val PATTERN_POLL_TEXT_ONLY: Pattern = Pattern.compile("poll([\\d]+)choice_text_only")
const val CARD_NAME_PLAYER = "player"
const val CARD_NAME_AUDIO = "audio"
const val CARD_NAME_ANIMATED_GIF = "animated_gif"
fun getCardSize(card: ParcelableCardEntity): Point? {
val playerWidth = card.getAsInteger("player_width", -1)
val playerHeight = card.getAsInteger("player_height", -1)
if (playerWidth > 0 && playerHeight > 0) {
return Point(playerWidth, playerHeight)
}
return null
}
fun isCardSupported(status: ParcelableStatus): Boolean {
val card = status.card ?: return false
when (status.card_name) {
CARD_NAME_PLAYER -> {
status.media?.let { mediaArray ->
val appUrlResolved = card.getString("app_url_resolved")
val cardUrl = card.url
mediaArray.forEach {
if (it.url == appUrlResolved || it.url == cardUrl) {
return false
}
}
}
return TextUtils.isEmpty(card.getString("player_stream_url"))
}
CARD_NAME_AUDIO -> {
return true
}
}
if (isPoll(card)) {
return true
}
return false
}
fun getChoicesCount(card: ParcelableCardEntity): Int {
val matcher = PATTERN_POLL_TEXT_ONLY.matcher(card.name)
if (!matcher.matches()) throw IllegalStateException()
return matcher.group(1).toInt()
}
fun isPoll(card: ParcelableCardEntity): Boolean {
return PATTERN_POLL_TEXT_ONLY.matcher(card.name).matches() && !TextUtils.isEmpty(card.url)
}
fun isPoll(status: ParcelableStatus): Boolean {
val card = status.card ?: return false
return isPoll(card)
}
} | gpl-3.0 | 74e55dfe50e06ce4eccaf9922d04790a | 34.730337 | 98 | 0.641082 | 4.267114 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/EditHistoryStatsView.kt | 1 | 2824 | package org.wikipedia.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import org.wikipedia.R
import org.wikipedia.databinding.ViewEditHistoryStatsBinding
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.page.PageActivity
import org.wikipedia.page.PageTitle
import org.wikipedia.page.edithistory.EditHistoryListViewModel
import org.wikipedia.richtext.RichTextUtil
import org.wikipedia.util.DateUtil
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.StringUtil
import java.util.*
class EditHistoryStatsView constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) {
val binding = ViewEditHistoryStatsBinding.inflate(LayoutInflater.from(context), this)
init {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val padding = DimenUtil.roundedDpToPx(16f)
setPadding(padding, 0, padding, 0)
}
fun setup(pageTitle: PageTitle, editHistoryStats: EditHistoryListViewModel.EditHistoryStats?) {
binding.articleTitleView.text = StringUtil.fromHtml(context.getString(R.string.page_edit_history_activity_title,
"<a href=\"#\">${pageTitle.displayText}</a>"))
RichTextUtil.removeUnderlinesFromLinks(binding.articleTitleView)
editHistoryStats?.let { stats ->
val timestamp = stats.revision.timeStamp
if (timestamp.isNotBlank()) {
val createdYear = DateUtil.getYearOnlyDateString(DateUtil.iso8601DateParse(timestamp))
val calendar = Calendar.getInstance()
val today = DateUtil.getShortDateString(calendar.time)
calendar.add(Calendar.YEAR, -1)
val lastYear = DateUtil.getShortDateString(calendar.time)
binding.editCountsView.text = context.resources.getQuantityString(R.plurals.page_edit_history_article_edits_since_year,
stats.allEdits.count, stats.allEdits.count, createdYear)
binding.statsGraphView.setData(stats.metrics.map { it.edits.toFloat() })
binding.statsGraphView.contentDescription = context.getString(R.string.page_edit_history_metrics_content_description, lastYear, today)
FeedbackUtil.setButtonLongPressToast(binding.statsGraphView)
}
}
binding.articleTitleView.movementMethod = LinkMovementMethodExt { _ ->
context.startActivity(PageActivity.newIntentForNewTab(context, HistoryEntry(pageTitle, HistoryEntry.SOURCE_EDIT_HISTORY), pageTitle))
}
}
}
| apache-2.0 | db1e65fa0c07cf4e308921fb9559b89e | 50.345455 | 150 | 0.742918 | 4.660066 | false | true | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/theme/ThemeFittingRoomActivity.kt | 1 | 1716 | package org.wikipedia.theme
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import org.wikipedia.Constants
import org.wikipedia.activity.SingleFragmentActivity
import org.wikipedia.page.ExclusiveBottomSheetPresenter
class ThemeFittingRoomActivity : SingleFragmentActivity<ThemeFittingRoomFragment>(), ThemeChooserDialog.Callback {
private var themeChooserDialog: ThemeChooserDialog? = null
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
themeChooserDialog = ThemeChooserDialog.newInstance(Constants.InvokeSource.SETTINGS)
bottomSheetPresenter.show(supportFragmentManager, themeChooserDialog!!)
}
// Don't let changed theme affect the status bar color and navigation bar color
setStatusBarColor(ContextCompat.getColor(this, android.R.color.black))
setNavigationBarColor(ContextCompat.getColor(this, android.R.color.black))
}
override fun createFragment(): ThemeFittingRoomFragment {
return ThemeFittingRoomFragment.newInstance()
}
override fun onToggleDimImages() {
ActivityCompat.recreate(this)
}
override fun onToggleReadingFocusMode() {
}
override fun onCancelThemeChooser() {
finish()
}
override fun onEditingPrefsChanged() { }
companion object {
fun newIntent(context: Context): Intent {
return Intent(context, ThemeFittingRoomActivity::class.java)
}
}
}
| apache-2.0 | a55680df56de1667fa1518c2961099f7 | 33.32 | 114 | 0.745338 | 5.231707 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/ui/verification/VerificationViewModel.kt | 1 | 6279 | package com.stripe.android.link.ui.verification
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.stripe.android.core.Logger
import com.stripe.android.core.injection.NonFallbackInjectable
import com.stripe.android.core.injection.NonFallbackInjector
import com.stripe.android.link.LinkScreen
import com.stripe.android.link.account.LinkAccountManager
import com.stripe.android.link.analytics.LinkEventsReporter
import com.stripe.android.link.model.AccountStatus
import com.stripe.android.link.model.LinkAccount
import com.stripe.android.link.model.Navigator
import com.stripe.android.link.ui.ErrorMessage
import com.stripe.android.link.ui.getErrorMessage
import com.stripe.android.ui.core.elements.OTPSpec
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
internal data class VerificationViewState(
val isProcessing: Boolean = false,
val requestFocus: Boolean = true,
val errorMessage: ErrorMessage? = null,
val isSendingNewCode: Boolean = false,
val didSendNewCode: Boolean = false,
)
/**
* ViewModel that handles user verification confirmation logic.
*/
@Suppress("TooManyFunctions")
internal class VerificationViewModel @Inject constructor(
private val linkAccountManager: LinkAccountManager,
private val linkEventsReporter: LinkEventsReporter,
private val navigator: Navigator,
private val logger: Logger
) : ViewModel() {
lateinit var linkAccount: LinkAccount
private val _viewState = MutableStateFlow(VerificationViewState())
val viewState: StateFlow<VerificationViewState> = _viewState
/**
* Callback when user has successfully verified their account. If not overridden, defaults to
* navigating to the Wallet screen using [Navigator].
*/
var onVerificationCompleted: () -> Unit = {
navigator.navigateTo(LinkScreen.Wallet, clearBackStack = true)
}
val otpElement = OTPSpec.transform()
private val otpCode: StateFlow<String?> =
otpElement.getFormFieldValueFlow().map { formFieldsList ->
// formFieldsList contains only one element, for the OTP. Take the second value of
// the pair, which is the FormFieldEntry containing the value entered by the user.
formFieldsList.firstOrNull()?.second?.takeIf { it.isComplete }?.value
}.stateIn(viewModelScope, SharingStarted.Lazily, null)
@VisibleForTesting
internal fun init(linkAccount: LinkAccount) {
this.linkAccount = linkAccount
if (linkAccount.accountStatus != AccountStatus.VerificationStarted) {
startVerification()
}
linkEventsReporter.on2FAStart()
viewModelScope.launch {
otpCode.collect { code ->
code?.let { onVerificationCodeEntered(code) }
}
}
}
fun onVerificationCodeEntered(code: String) {
updateViewState {
it.copy(
isProcessing = true,
errorMessage = null,
)
}
viewModelScope.launch {
linkAccountManager.confirmVerification(code).fold(
onSuccess = {
updateViewState {
it.copy(isProcessing = false)
}
linkEventsReporter.on2FAComplete()
onVerificationCompleted()
},
onFailure = {
linkEventsReporter.on2FAFailure()
for (i in 0 until otpElement.controller.otpLength) {
otpElement.controller.onValueChanged(i, "")
}
onError(it)
}
)
}
}
fun startVerification() {
updateViewState {
it.copy(errorMessage = null)
}
viewModelScope.launch {
val result = linkAccountManager.startVerification()
val error = result.exceptionOrNull()
updateViewState {
it.copy(
isSendingNewCode = false,
didSendNewCode = error == null,
errorMessage = error?.getErrorMessage(),
)
}
}
}
fun resendCode() {
updateViewState { it.copy(isSendingNewCode = true) }
startVerification()
}
fun didShowCodeSentNotification() {
updateViewState {
it.copy(didSendNewCode = false)
}
}
fun onBack() {
clearError()
navigator.onBack(userInitiated = true)
linkEventsReporter.on2FACancel()
linkAccountManager.logout()
}
fun onChangeEmailClicked() {
clearError()
navigator.navigateTo(LinkScreen.SignUp, clearBackStack = true)
linkAccountManager.logout()
}
fun onFocusRequested() {
updateViewState {
it.copy(requestFocus = false)
}
}
private fun clearError() {
updateViewState {
it.copy(errorMessage = null)
}
}
private fun onError(error: Throwable) = error.getErrorMessage().let { message ->
logger.error("Error: ", error)
updateViewState {
it.copy(
isProcessing = false,
errorMessage = message,
)
}
}
private fun updateViewState(block: (VerificationViewState) -> VerificationViewState) {
_viewState.update(block)
}
internal class Factory(
private val account: LinkAccount,
private val injector: NonFallbackInjector
) : ViewModelProvider.Factory, NonFallbackInjectable {
@Inject
lateinit var viewModel: VerificationViewModel
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
injector.inject(this)
return viewModel.apply {
init(account)
} as T
}
}
}
| mit | 4273716c5dd49b58f5dbb2a332a1ab01 | 30.552764 | 97 | 0.638955 | 5.03125 | false | false | false | false |
kkorolyov/Pancake | killstreek/src/main/kotlin/dev/kkorolyov/killstreek/Launcher.kt | 1 | 8120 | package dev.kkorolyov.killstreek
import dev.kkorolyov.flopple.data.WeightedDistribution
import dev.kkorolyov.killstreek.component.Damage
import dev.kkorolyov.killstreek.component.Health
import dev.kkorolyov.killstreek.media.HealthBar
import dev.kkorolyov.killstreek.media.Sprite
import dev.kkorolyov.pancake.core.component.ActionQueue
import dev.kkorolyov.pancake.core.component.AudioEmitter
import dev.kkorolyov.pancake.core.component.Bounds
import dev.kkorolyov.pancake.core.component.Chain
import dev.kkorolyov.pancake.core.component.Input
import dev.kkorolyov.pancake.core.component.Spawner
import dev.kkorolyov.pancake.core.component.Transform
import dev.kkorolyov.pancake.core.component.media.Animation
import dev.kkorolyov.pancake.core.component.media.Graphic
import dev.kkorolyov.pancake.core.component.movement.Damping
import dev.kkorolyov.pancake.core.component.movement.Force
import dev.kkorolyov.pancake.core.component.movement.Mass
import dev.kkorolyov.pancake.core.component.movement.Velocity
import dev.kkorolyov.pancake.core.component.movement.VelocityCap
import dev.kkorolyov.pancake.core.event.EntitiesCollided
import dev.kkorolyov.pancake.core.input.HandlerReader
import dev.kkorolyov.pancake.platform.GameEngine
import dev.kkorolyov.pancake.platform.GameLoop
import dev.kkorolyov.pancake.platform.Resources
import dev.kkorolyov.pancake.platform.action.Action
import dev.kkorolyov.pancake.platform.application.Application.Config
import dev.kkorolyov.pancake.platform.entity.Component
import dev.kkorolyov.pancake.platform.entity.EntityPool
import dev.kkorolyov.pancake.platform.event.EntityCreated
import dev.kkorolyov.pancake.platform.event.EntityDestroyed
import dev.kkorolyov.pancake.platform.event.EventLoop.Broadcasting
import dev.kkorolyov.pancake.platform.math.Vector1
import dev.kkorolyov.pancake.platform.math.Vector2
import dev.kkorolyov.pancake.platform.math.Vector3
import dev.kkorolyov.pancake.platform.math.Vectors
import dev.kkorolyov.pancake.platform.media.audio.Audio
import dev.kkorolyov.pancake.platform.media.audio.Audio.State.PLAY
import dev.kkorolyov.pancake.platform.media.graphic.CompositeRenderable
import dev.kkorolyov.pancake.platform.media.graphic.Image
import dev.kkorolyov.pancake.platform.media.graphic.Renderable
import dev.kkorolyov.pancake.platform.media.graphic.Viewport
import dev.kkorolyov.pancake.platform.registry.DeferredConverterFactory
import dev.kkorolyov.pancake.platform.registry.Registry
import dev.kkorolyov.pancake.platform.registry.ResourceReader
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.ThreadLocalRandom
import java.util.function.Supplier
import kotlin.math.sqrt
private val log: Logger = LoggerFactory.getLogger("main")
private val renderables: Registry<String, Renderable> by lazy {
Resources.inStream("config/renderables.yaml").use {
Registry<String, Renderable>().apply {
load(ResourceReader(DeferredConverterFactory.get(DeferredConverterFactory.RenderableStrat::class.java)).fromYaml(it))
}
}
}
private val audio: Registry<String, Audio> by lazy {
Resources.inStream("config/audio.yaml").use {
Registry<String, Audio>().apply {
load(ResourceReader(DeferredConverterFactory.get(DeferredConverterFactory.AudioStrat::class.java)).fromYaml(it))
}
}
}
private val actions: Registry<String, Action> by lazy {
Resources.inStream("config/actions.yaml").use {
Registry<String, Action>().apply {
put("animate", Action { it.get(Animation::class.java).isActive = true })
put("stopAnimate", Action { it.get(Animation::class.java).isActive = false })
put("toggleAnimate", Action { it.get(Animation::class.java).toggle() })
put("toggleSpawner", Action { it.get(Spawner::class.java).toggle() })
load(ResourceReader(DeferredConverterFactory.get(DeferredConverterFactory.ActionStrat::class.java)).fromYaml(it))
}
}
}
private val events: Broadcasting = Broadcasting()
private val healthBarSize: Vector2 = Vectors.create(1.0, 0.25)
private val playerTransform = Transform(Vectors.create(0.0, 0.0, 0.0), randRotation())
private val entities: EntityPool by lazy {
EntityPool(events).apply {
val groundGraphic = Graphic((renderables.get("ground") as Image).apply { viewport = Viewport(3, 2) })
val boxGraphic = Graphic(renderables.get("box"))
val sphereGraphic = Graphic(renderables.get("sphere"))
// Ground
for (i in -15..15 step 2) {
for (j in -15..15 step 2) {
create().apply {
add(
Transform(Vectors.create(i.toDouble(), j.toDouble(), -1.0)),
groundGraphic
)
}
}
}
// Wall
create().apply {
add(
Transform(Vectors.create(-3.0, 0.0, 0.0), randRotation()),
Bounds(Vectors.create(3.0, 3.0, 0.0)),
boxGraphic,
AudioEmitter().apply {
enqueue(audio.get("wall"))
}
)
}
val line = sqrt(200.0).toInt()
// Boxes
for (i in 1..line) {
for (j in 1..line) {
createObject(
Vectors.create(i.toDouble(), -j.toDouble(), 0.0),
Bounds(BOX),
boxGraphic
)
}
}
// Spheres
for (i in 1..line) {
for (j in 1..line) {
createObject(
Vectors.create(i.toDouble(), j.toDouble(), 0.0),
Bounds(RADIUS),
sphereGraphic
)
}
}
// Camera
create().apply {
add(
Transform(Vectors.create(0.0, 0.0, 0.0)).apply { Resources.RENDER_MEDIUM.camera.position = position },
Chain(playerTransform.position, 1.0)
)
}
val health = Health(20)
// Player
create().also {
val sprite =
Sprite(renderables.get("player") as CompositeRenderable<Image>, Viewport(4, 3), (1e9 / 60).toLong()).apply {
isActive = false
}
it.add(
playerTransform,
Velocity(Vectors.create(0.0, 0.0, 0.0)),
VelocityCap(MAX_SPEED),
Force(Vectors.create(0.0, 0.0, 0.0)),
Mass(PLAYER_MASS),
Damping(PLAYER_DAMPING),
Bounds(BOX, RADIUS),
Spawner(
1.0,
4.0,
.1,
WeightedDistribution<Supplier<Iterable<Component>>>().apply {
add(
Supplier {
listOf(
Transform(Vectors.create(1.0, 1.0, 0.0), randRotation()),
Velocity(Vectors.create(0.0, 0.0, 0.0)),
Force(Vectors.create(0.0, 0.0, 0.0)),
Mass(OBJECT_MASS),
Damping(OBJECT_DAMPING),
Bounds(BOX, RADIUS),
sphereGraphic
)
},
1
)
}
).apply { isActive = false },
Animation(sprite),
Graphic(sprite),
Input(
true,
Resources.inStream("config/inputs.yaml").use {
HandlerReader(actions).fromYaml(it)
}
),
health,
ActionQueue()
)
events.register(EntitiesCollided::class.java) { e ->
if (it.id == e.collided[0]) {
get(e.collided[1])?.let {
it.get(Damage::class.java)?.reset() ?: it.add(Damage(1))
}
}
}
events.register(EntityCreated::class.java) { e ->
if (it.id == e.id) audio.get("spawn").state(PLAY)
}
events.register(EntityDestroyed::class.java) {
audio.get("spawn").state(PLAY)
}
}
// Player health
create().apply {
add(
Transform(Vectors.create(0.0, .5, 1.0), playerTransform, false),
Graphic(HealthBar(health, healthBarSize, Resources.RENDER_MEDIUM))
)
}
}
}
private fun EntityPool.createObject(position: Vector3, bounds: Bounds, graphic: Graphic) {
val transform = Transform(position, randRotation())
val health = Health(20)
// Object
create()
.add(
transform,
Velocity(Vectors.create(0.0, 0.0, 0.0)),
Force(Vectors.create(0.0, 0.0, 0.0)),
Mass(OBJECT_MASS),
Damping(OBJECT_DAMPING),
Chain(null, 0.0, playerTransform.position),
bounds,
graphic,
health
)
// Its health bar
create()
.add(
Transform(Vectors.create(0.0, .3, 1.0), transform, false),
Graphic(HealthBar(health, healthBarSize, Resources.RENDER_MEDIUM)),
health
)
}
private fun randRotation(): Vector1 = Vectors.create(ThreadLocalRandom.current().nextDouble())
/**
* Executes the game.
*/
fun main() {
log.info("Starting thing")
Resources.APPLICATION.execute(
Config(
"Killstreek Functional Test",
"pancake-icon.png",
640.0,
640.0
),
GameLoop(GameEngine(events, entities))
)
}
| bsd-3-clause | b862708578bb41478053c1da5558c531 | 29.298507 | 120 | 0.71367 | 3.082764 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/RowElementUI.kt | 1 | 2889 | package com.stripe.android.ui.core.elements
import android.content.res.Resources
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.dp
import com.stripe.android.ui.core.paymentsColors
import com.stripe.android.ui.core.paymentsShapes
@Composable
internal fun RowElementUI(
enabled: Boolean,
controller: RowController,
hiddenIdentifiers: Set<IdentifierSpec>,
lastTextFieldIdentifier: IdentifierSpec?
) {
val visibleFields = controller.fields.filter { !hiddenIdentifiers.contains(it.identifier) }
val dividerHeight = remember { mutableStateOf(0.dp) }
// Only draw the row if there are items in the row that are not hidden, otherwise the entire
// section will fail to draw
if (visibleFields.isNotEmpty()) {
Row(modifier = Modifier.fillMaxWidth()) {
visibleFields.forEachIndexed { index, field ->
val nextFocusDirection = if (index == visibleFields.lastIndex) {
FocusDirection.Down
} else {
FocusDirection.Right
}
val previousFocusDirection = if (index == 0) {
FocusDirection.Up
} else {
FocusDirection.Left
}
SectionFieldElementUI(
enabled,
field,
hiddenIdentifiers = hiddenIdentifiers,
lastTextFieldIdentifier = lastTextFieldIdentifier,
modifier = Modifier
.weight(1.0f / visibleFields.size.toFloat())
.onSizeChanged {
dividerHeight.value =
(it.height / Resources.getSystem().displayMetrics.density).dp
},
nextFocusDirection = nextFocusDirection,
previousFocusDirection = previousFocusDirection
)
if (index != visibleFields.lastIndex) {
Divider(
modifier = Modifier
.height(dividerHeight.value)
.width(MaterialTheme.paymentsShapes.borderStrokeWidth.dp),
color = MaterialTheme.paymentsColors.componentDivider
)
}
}
}
}
}
| mit | 3090256b34b3a81e5ca8214984550e00 | 39.125 | 96 | 0.611284 | 5.534483 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/css/Domain.kt | 1 | 44471 | package pl.wendigo.chrome.api.css
import kotlinx.serialization.json.Json
/**
* This domain exposes CSS read/write operations. All CSS objects (stylesheets, rules, and styles)
have an associated `id` used in subsequent operations on the related object. Each object type has
a specific `id` structure, and those are not interchangeable between objects of different kinds.
CSS objects can be loaded using the `get*ForNode()` calls (which accept a DOM node id). A client
can also keep track of stylesheets via the `styleSheetAdded`/`styleSheetRemoved` events and
subsequently load the required stylesheet contents using the `getStyleSheet[Text]()` methods.
*
* This API is marked as experimental in protocol definition and can change in the future.
* @link Protocol [CSS](https://chromedevtools.github.io/devtools-protocol/tot/CSS) domain documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
class CSSDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) :
pl.wendigo.chrome.protocol.Domain(
"CSS",
"""This domain exposes CSS read/write operations. All CSS objects (stylesheets, rules, and styles)
have an associated `id` used in subsequent operations on the related object. Each object type has
a specific `id` structure, and those are not interchangeable between objects of different kinds.
CSS objects can be loaded using the `get*ForNode()` calls (which accept a DOM node id). A client
can also keep track of stylesheets via the `styleSheetAdded`/`styleSheetRemoved` events and
subsequently load the required stylesheet contents using the `getStyleSheet[Text]()` methods.""",
connection
) {
/**
* Inserts a new rule with the given `ruleText` in a stylesheet with given `styleSheetId`, at the
position specified by `location`.
*
* @link Protocol [CSS#addRule](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-addRule) method documentation.
*/
fun addRule(input: AddRuleRequest): io.reactivex.rxjava3.core.Single<AddRuleResponse> = connection.request("CSS.addRule", Json.encodeToJsonElement(AddRuleRequest.serializer(), input), AddRuleResponse.serializer())
/**
* Returns all class names from specified stylesheet.
*
* @link Protocol [CSS#collectClassNames](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-collectClassNames) method documentation.
*/
fun collectClassNames(input: CollectClassNamesRequest): io.reactivex.rxjava3.core.Single<CollectClassNamesResponse> = connection.request("CSS.collectClassNames", Json.encodeToJsonElement(CollectClassNamesRequest.serializer(), input), CollectClassNamesResponse.serializer())
/**
* Creates a new special "via-inspector" stylesheet in the frame with given `frameId`.
*
* @link Protocol [CSS#createStyleSheet](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-createStyleSheet) method documentation.
*/
fun createStyleSheet(input: CreateStyleSheetRequest): io.reactivex.rxjava3.core.Single<CreateStyleSheetResponse> = connection.request("CSS.createStyleSheet", Json.encodeToJsonElement(CreateStyleSheetRequest.serializer(), input), CreateStyleSheetResponse.serializer())
/**
* Disables the CSS agent for the given page.
*
* @link Protocol [CSS#disable](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-disable) method documentation.
*/
fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CSS.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Enables the CSS agent for the given page. Clients should not assume that the CSS agent has been
enabled until the result of this command is received.
*
* @link Protocol [CSS#enable](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-enable) method documentation.
*/
fun enable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CSS.enable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Ensures that the given node will have specified pseudo-classes whenever its style is computed by
the browser.
*
* @link Protocol [CSS#forcePseudoState](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-forcePseudoState) method documentation.
*/
fun forcePseudoState(input: ForcePseudoStateRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CSS.forcePseudoState", Json.encodeToJsonElement(ForcePseudoStateRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
*
*
* @link Protocol [CSS#getBackgroundColors](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getBackgroundColors) method documentation.
*/
fun getBackgroundColors(input: GetBackgroundColorsRequest): io.reactivex.rxjava3.core.Single<GetBackgroundColorsResponse> = connection.request("CSS.getBackgroundColors", Json.encodeToJsonElement(GetBackgroundColorsRequest.serializer(), input), GetBackgroundColorsResponse.serializer())
/**
* Returns the computed style for a DOM node identified by `nodeId`.
*
* @link Protocol [CSS#getComputedStyleForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getComputedStyleForNode) method documentation.
*/
fun getComputedStyleForNode(input: GetComputedStyleForNodeRequest): io.reactivex.rxjava3.core.Single<GetComputedStyleForNodeResponse> = connection.request("CSS.getComputedStyleForNode", Json.encodeToJsonElement(GetComputedStyleForNodeRequest.serializer(), input), GetComputedStyleForNodeResponse.serializer())
/**
* Returns the styles defined inline (explicitly in the "style" attribute and implicitly, using DOM
attributes) for a DOM node identified by `nodeId`.
*
* @link Protocol [CSS#getInlineStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getInlineStylesForNode) method documentation.
*/
fun getInlineStylesForNode(input: GetInlineStylesForNodeRequest): io.reactivex.rxjava3.core.Single<GetInlineStylesForNodeResponse> = connection.request("CSS.getInlineStylesForNode", Json.encodeToJsonElement(GetInlineStylesForNodeRequest.serializer(), input), GetInlineStylesForNodeResponse.serializer())
/**
* Returns requested styles for a DOM node identified by `nodeId`.
*
* @link Protocol [CSS#getMatchedStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMatchedStylesForNode) method documentation.
*/
fun getMatchedStylesForNode(input: GetMatchedStylesForNodeRequest): io.reactivex.rxjava3.core.Single<GetMatchedStylesForNodeResponse> = connection.request("CSS.getMatchedStylesForNode", Json.encodeToJsonElement(GetMatchedStylesForNodeRequest.serializer(), input), GetMatchedStylesForNodeResponse.serializer())
/**
* Returns all media queries parsed by the rendering engine.
*
* @link Protocol [CSS#getMediaQueries](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMediaQueries) method documentation.
*/
fun getMediaQueries(): io.reactivex.rxjava3.core.Single<GetMediaQueriesResponse> = connection.request("CSS.getMediaQueries", null, GetMediaQueriesResponse.serializer())
/**
* Requests information about platform fonts which we used to render child TextNodes in the given
node.
*
* @link Protocol [CSS#getPlatformFontsForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getPlatformFontsForNode) method documentation.
*/
fun getPlatformFontsForNode(input: GetPlatformFontsForNodeRequest): io.reactivex.rxjava3.core.Single<GetPlatformFontsForNodeResponse> = connection.request("CSS.getPlatformFontsForNode", Json.encodeToJsonElement(GetPlatformFontsForNodeRequest.serializer(), input), GetPlatformFontsForNodeResponse.serializer())
/**
* Returns the current textual content for a stylesheet.
*
* @link Protocol [CSS#getStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getStyleSheetText) method documentation.
*/
fun getStyleSheetText(input: GetStyleSheetTextRequest): io.reactivex.rxjava3.core.Single<GetStyleSheetTextResponse> = connection.request("CSS.getStyleSheetText", Json.encodeToJsonElement(GetStyleSheetTextRequest.serializer(), input), GetStyleSheetTextResponse.serializer())
/**
* Starts tracking the given computed styles for updates. The specified array of properties
replaces the one previously specified. Pass empty array to disable tracking.
Use takeComputedStyleUpdates to retrieve the list of nodes that had properties modified.
The changes to computed style properties are only tracked for nodes pushed to the front-end
by the DOM agent. If no changes to the tracked properties occur after the node has been pushed
to the front-end, no updates will be issued for the node.
*
* @link Protocol [CSS#trackComputedStyleUpdates](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-trackComputedStyleUpdates) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun trackComputedStyleUpdates(input: TrackComputedStyleUpdatesRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CSS.trackComputedStyleUpdates", Json.encodeToJsonElement(TrackComputedStyleUpdatesRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Polls the next batch of computed style updates.
*
* @link Protocol [CSS#takeComputedStyleUpdates](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeComputedStyleUpdates) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun takeComputedStyleUpdates(): io.reactivex.rxjava3.core.Single<TakeComputedStyleUpdatesResponse> = connection.request("CSS.takeComputedStyleUpdates", null, TakeComputedStyleUpdatesResponse.serializer())
/**
* Find a rule with the given active property for the given node and set the new value for this
property
*
* @link Protocol [CSS#setEffectivePropertyValueForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setEffectivePropertyValueForNode) method documentation.
*/
fun setEffectivePropertyValueForNode(input: SetEffectivePropertyValueForNodeRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CSS.setEffectivePropertyValueForNode", Json.encodeToJsonElement(SetEffectivePropertyValueForNodeRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Modifies the keyframe rule key text.
*
* @link Protocol [CSS#setKeyframeKey](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setKeyframeKey) method documentation.
*/
fun setKeyframeKey(input: SetKeyframeKeyRequest): io.reactivex.rxjava3.core.Single<SetKeyframeKeyResponse> = connection.request("CSS.setKeyframeKey", Json.encodeToJsonElement(SetKeyframeKeyRequest.serializer(), input), SetKeyframeKeyResponse.serializer())
/**
* Modifies the rule selector.
*
* @link Protocol [CSS#setMediaText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setMediaText) method documentation.
*/
fun setMediaText(input: SetMediaTextRequest): io.reactivex.rxjava3.core.Single<SetMediaTextResponse> = connection.request("CSS.setMediaText", Json.encodeToJsonElement(SetMediaTextRequest.serializer(), input), SetMediaTextResponse.serializer())
/**
* Modifies the rule selector.
*
* @link Protocol [CSS#setRuleSelector](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setRuleSelector) method documentation.
*/
fun setRuleSelector(input: SetRuleSelectorRequest): io.reactivex.rxjava3.core.Single<SetRuleSelectorResponse> = connection.request("CSS.setRuleSelector", Json.encodeToJsonElement(SetRuleSelectorRequest.serializer(), input), SetRuleSelectorResponse.serializer())
/**
* Sets the new stylesheet text.
*
* @link Protocol [CSS#setStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleSheetText) method documentation.
*/
fun setStyleSheetText(input: SetStyleSheetTextRequest): io.reactivex.rxjava3.core.Single<SetStyleSheetTextResponse> = connection.request("CSS.setStyleSheetText", Json.encodeToJsonElement(SetStyleSheetTextRequest.serializer(), input), SetStyleSheetTextResponse.serializer())
/**
* Applies specified style edits one after another in the given order.
*
* @link Protocol [CSS#setStyleTexts](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleTexts) method documentation.
*/
fun setStyleTexts(input: SetStyleTextsRequest): io.reactivex.rxjava3.core.Single<SetStyleTextsResponse> = connection.request("CSS.setStyleTexts", Json.encodeToJsonElement(SetStyleTextsRequest.serializer(), input), SetStyleTextsResponse.serializer())
/**
* Enables the selector recording.
*
* @link Protocol [CSS#startRuleUsageTracking](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-startRuleUsageTracking) method documentation.
*/
fun startRuleUsageTracking(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CSS.startRuleUsageTracking", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Stop tracking rule usage and return the list of rules that were used since last call to
`takeCoverageDelta` (or since start of coverage instrumentation)
*
* @link Protocol [CSS#stopRuleUsageTracking](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-stopRuleUsageTracking) method documentation.
*/
fun stopRuleUsageTracking(): io.reactivex.rxjava3.core.Single<StopRuleUsageTrackingResponse> = connection.request("CSS.stopRuleUsageTracking", null, StopRuleUsageTrackingResponse.serializer())
/**
* Obtain list of rules that became used since last call to this method (or since start of coverage
instrumentation)
*
* @link Protocol [CSS#takeCoverageDelta](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeCoverageDelta) method documentation.
*/
fun takeCoverageDelta(): io.reactivex.rxjava3.core.Single<TakeCoverageDeltaResponse> = connection.request("CSS.takeCoverageDelta", null, TakeCoverageDeltaResponse.serializer())
/**
* Enables/disables rendering of local CSS fonts (enabled by default).
*
* @link Protocol [CSS#setLocalFontsEnabled](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setLocalFontsEnabled) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setLocalFontsEnabled(input: SetLocalFontsEnabledRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CSS.setLocalFontsEnabled", Json.encodeToJsonElement(SetLocalFontsEnabledRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Fires whenever a web font is updated. A non-empty font parameter indicates a successfully loaded
web font
*/
fun fontsUpdated(): io.reactivex.rxjava3.core.Flowable<FontsUpdatedEvent> = connection.events("CSS.fontsUpdated", FontsUpdatedEvent.serializer())
/**
* Fires whenever a MediaQuery result changes (for example, after a browser window has been
resized.) The current implementation considers only viewport-dependent media features.
*/
fun mediaQueryResultChanged(): io.reactivex.rxjava3.core.Flowable<pl.wendigo.chrome.protocol.RawEvent> = connection.events("CSS.mediaQueryResultChanged", pl.wendigo.chrome.protocol.RawEvent.serializer())
/**
* Fired whenever an active document stylesheet is added.
*/
fun styleSheetAdded(): io.reactivex.rxjava3.core.Flowable<StyleSheetAddedEvent> = connection.events("CSS.styleSheetAdded", StyleSheetAddedEvent.serializer())
/**
* Fired whenever a stylesheet is changed as a result of the client operation.
*/
fun styleSheetChanged(): io.reactivex.rxjava3.core.Flowable<StyleSheetChangedEvent> = connection.events("CSS.styleSheetChanged", StyleSheetChangedEvent.serializer())
/**
* Fired whenever an active document stylesheet is removed.
*/
fun styleSheetRemoved(): io.reactivex.rxjava3.core.Flowable<StyleSheetRemovedEvent> = connection.events("CSS.styleSheetRemoved", StyleSheetRemovedEvent.serializer())
/**
* Returns list of dependant domains that should be enabled prior to enabling this domain.
*/
override fun getDependencies(): List<pl.wendigo.chrome.protocol.Domain> {
return arrayListOf(
pl.wendigo.chrome.api.dom.DOMDomain(connection),
pl.wendigo.chrome.api.page.PageDomain(connection),
)
}
}
/**
* Represents request frame that can be used with [CSS#addRule](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-addRule) operation call.
*
* Inserts a new rule with the given `ruleText` in a stylesheet with given `styleSheetId`, at the
position specified by `location`.
* @link [CSS#addRule](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-addRule) method documentation.
* @see [CSSDomain.addRule]
*/
@kotlinx.serialization.Serializable
data class AddRuleRequest(
/**
* The css style sheet identifier where a new rule should be inserted.
*/
val styleSheetId: StyleSheetId,
/**
* The text of a new rule.
*/
val ruleText: String,
/**
* Text position of a new rule in the target style sheet.
*/
val location: SourceRange
)
/**
* Represents response frame that is returned from [CSS#addRule](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-addRule) operation call.
* Inserts a new rule with the given `ruleText` in a stylesheet with given `styleSheetId`, at the
position specified by `location`.
*
* @link [CSS#addRule](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-addRule) method documentation.
* @see [CSSDomain.addRule]
*/
@kotlinx.serialization.Serializable
data class AddRuleResponse(
/**
* The newly created rule.
*/
val rule: CSSRule
)
/**
* Represents request frame that can be used with [CSS#collectClassNames](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-collectClassNames) operation call.
*
* Returns all class names from specified stylesheet.
* @link [CSS#collectClassNames](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-collectClassNames) method documentation.
* @see [CSSDomain.collectClassNames]
*/
@kotlinx.serialization.Serializable
data class CollectClassNamesRequest(
/**
*
*/
val styleSheetId: StyleSheetId
)
/**
* Represents response frame that is returned from [CSS#collectClassNames](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-collectClassNames) operation call.
* Returns all class names from specified stylesheet.
*
* @link [CSS#collectClassNames](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-collectClassNames) method documentation.
* @see [CSSDomain.collectClassNames]
*/
@kotlinx.serialization.Serializable
data class CollectClassNamesResponse(
/**
* Class name list.
*/
val classNames: List<String>
)
/**
* Represents request frame that can be used with [CSS#createStyleSheet](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-createStyleSheet) operation call.
*
* Creates a new special "via-inspector" stylesheet in the frame with given `frameId`.
* @link [CSS#createStyleSheet](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-createStyleSheet) method documentation.
* @see [CSSDomain.createStyleSheet]
*/
@kotlinx.serialization.Serializable
data class CreateStyleSheetRequest(
/**
* Identifier of the frame where "via-inspector" stylesheet should be created.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId
)
/**
* Represents response frame that is returned from [CSS#createStyleSheet](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-createStyleSheet) operation call.
* Creates a new special "via-inspector" stylesheet in the frame with given `frameId`.
*
* @link [CSS#createStyleSheet](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-createStyleSheet) method documentation.
* @see [CSSDomain.createStyleSheet]
*/
@kotlinx.serialization.Serializable
data class CreateStyleSheetResponse(
/**
* Identifier of the created "via-inspector" stylesheet.
*/
val styleSheetId: StyleSheetId
)
/**
* Represents request frame that can be used with [CSS#forcePseudoState](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-forcePseudoState) operation call.
*
* Ensures that the given node will have specified pseudo-classes whenever its style is computed by
the browser.
* @link [CSS#forcePseudoState](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-forcePseudoState) method documentation.
* @see [CSSDomain.forcePseudoState]
*/
@kotlinx.serialization.Serializable
data class ForcePseudoStateRequest(
/**
* The element id for which to force the pseudo state.
*/
val nodeId: pl.wendigo.chrome.api.dom.NodeId,
/**
* Element pseudo classes to force when computing the element's style.
*/
val forcedPseudoClasses: List<String>
)
/**
* Represents request frame that can be used with [CSS#getBackgroundColors](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getBackgroundColors) operation call.
*
*
* @link [CSS#getBackgroundColors](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getBackgroundColors) method documentation.
* @see [CSSDomain.getBackgroundColors]
*/
@kotlinx.serialization.Serializable
data class GetBackgroundColorsRequest(
/**
* Id of the node to get background colors for.
*/
val nodeId: pl.wendigo.chrome.api.dom.NodeId
)
/**
* Represents response frame that is returned from [CSS#getBackgroundColors](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getBackgroundColors) operation call.
*
*
* @link [CSS#getBackgroundColors](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getBackgroundColors) method documentation.
* @see [CSSDomain.getBackgroundColors]
*/
@kotlinx.serialization.Serializable
data class GetBackgroundColorsResponse(
/**
* The range of background colors behind this element, if it contains any visible text. If no
visible text is present, this will be undefined. In the case of a flat background color,
this will consist of simply that color. In the case of a gradient, this will consist of each
of the color stops. For anything more complicated, this will be an empty array. Images will
be ignored (as if the image had failed to load).
*/
val backgroundColors: List<String>? = null,
/**
* The computed font size for this node, as a CSS computed value string (e.g. '12px').
*/
val computedFontSize: String? = null,
/**
* The computed font weight for this node, as a CSS computed value string (e.g. 'normal' or
'100').
*/
val computedFontWeight: String? = null
)
/**
* Represents request frame that can be used with [CSS#getComputedStyleForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getComputedStyleForNode) operation call.
*
* Returns the computed style for a DOM node identified by `nodeId`.
* @link [CSS#getComputedStyleForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getComputedStyleForNode) method documentation.
* @see [CSSDomain.getComputedStyleForNode]
*/
@kotlinx.serialization.Serializable
data class GetComputedStyleForNodeRequest(
/**
*
*/
val nodeId: pl.wendigo.chrome.api.dom.NodeId
)
/**
* Represents response frame that is returned from [CSS#getComputedStyleForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getComputedStyleForNode) operation call.
* Returns the computed style for a DOM node identified by `nodeId`.
*
* @link [CSS#getComputedStyleForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getComputedStyleForNode) method documentation.
* @see [CSSDomain.getComputedStyleForNode]
*/
@kotlinx.serialization.Serializable
data class GetComputedStyleForNodeResponse(
/**
* Computed style for the specified DOM node.
*/
val computedStyle: List<CSSComputedStyleProperty>
)
/**
* Represents request frame that can be used with [CSS#getInlineStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getInlineStylesForNode) operation call.
*
* Returns the styles defined inline (explicitly in the "style" attribute and implicitly, using DOM
attributes) for a DOM node identified by `nodeId`.
* @link [CSS#getInlineStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getInlineStylesForNode) method documentation.
* @see [CSSDomain.getInlineStylesForNode]
*/
@kotlinx.serialization.Serializable
data class GetInlineStylesForNodeRequest(
/**
*
*/
val nodeId: pl.wendigo.chrome.api.dom.NodeId
)
/**
* Represents response frame that is returned from [CSS#getInlineStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getInlineStylesForNode) operation call.
* Returns the styles defined inline (explicitly in the "style" attribute and implicitly, using DOM
attributes) for a DOM node identified by `nodeId`.
*
* @link [CSS#getInlineStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getInlineStylesForNode) method documentation.
* @see [CSSDomain.getInlineStylesForNode]
*/
@kotlinx.serialization.Serializable
data class GetInlineStylesForNodeResponse(
/**
* Inline style for the specified DOM node.
*/
val inlineStyle: CSSStyle? = null,
/**
* Attribute-defined element style (e.g. resulting from "width=20 height=100%").
*/
val attributesStyle: CSSStyle? = null
)
/**
* Represents request frame that can be used with [CSS#getMatchedStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMatchedStylesForNode) operation call.
*
* Returns requested styles for a DOM node identified by `nodeId`.
* @link [CSS#getMatchedStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMatchedStylesForNode) method documentation.
* @see [CSSDomain.getMatchedStylesForNode]
*/
@kotlinx.serialization.Serializable
data class GetMatchedStylesForNodeRequest(
/**
*
*/
val nodeId: pl.wendigo.chrome.api.dom.NodeId
)
/**
* Represents response frame that is returned from [CSS#getMatchedStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMatchedStylesForNode) operation call.
* Returns requested styles for a DOM node identified by `nodeId`.
*
* @link [CSS#getMatchedStylesForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMatchedStylesForNode) method documentation.
* @see [CSSDomain.getMatchedStylesForNode]
*/
@kotlinx.serialization.Serializable
data class GetMatchedStylesForNodeResponse(
/**
* Inline style for the specified DOM node.
*/
val inlineStyle: CSSStyle? = null,
/**
* Attribute-defined element style (e.g. resulting from "width=20 height=100%").
*/
val attributesStyle: CSSStyle? = null,
/**
* CSS rules matching this node, from all applicable stylesheets.
*/
val matchedCSSRules: List<RuleMatch>? = null,
/**
* Pseudo style matches for this node.
*/
val pseudoElements: List<PseudoElementMatches>? = null,
/**
* A chain of inherited styles (from the immediate node parent up to the DOM tree root).
*/
val inherited: List<InheritedStyleEntry>? = null,
/**
* A list of CSS keyframed animations matching this node.
*/
val cssKeyframesRules: List<CSSKeyframesRule>? = null
)
/**
* Represents response frame that is returned from [CSS#getMediaQueries](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMediaQueries) operation call.
* Returns all media queries parsed by the rendering engine.
*
* @link [CSS#getMediaQueries](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMediaQueries) method documentation.
* @see [CSSDomain.getMediaQueries]
*/
@kotlinx.serialization.Serializable
data class GetMediaQueriesResponse(
/**
*
*/
val medias: List<CSSMedia>
)
/**
* Represents request frame that can be used with [CSS#getPlatformFontsForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getPlatformFontsForNode) operation call.
*
* Requests information about platform fonts which we used to render child TextNodes in the given
node.
* @link [CSS#getPlatformFontsForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getPlatformFontsForNode) method documentation.
* @see [CSSDomain.getPlatformFontsForNode]
*/
@kotlinx.serialization.Serializable
data class GetPlatformFontsForNodeRequest(
/**
*
*/
val nodeId: pl.wendigo.chrome.api.dom.NodeId
)
/**
* Represents response frame that is returned from [CSS#getPlatformFontsForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getPlatformFontsForNode) operation call.
* Requests information about platform fonts which we used to render child TextNodes in the given
node.
*
* @link [CSS#getPlatformFontsForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getPlatformFontsForNode) method documentation.
* @see [CSSDomain.getPlatformFontsForNode]
*/
@kotlinx.serialization.Serializable
data class GetPlatformFontsForNodeResponse(
/**
* Usage statistics for every employed platform font.
*/
val fonts: List<PlatformFontUsage>
)
/**
* Represents request frame that can be used with [CSS#getStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getStyleSheetText) operation call.
*
* Returns the current textual content for a stylesheet.
* @link [CSS#getStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getStyleSheetText) method documentation.
* @see [CSSDomain.getStyleSheetText]
*/
@kotlinx.serialization.Serializable
data class GetStyleSheetTextRequest(
/**
*
*/
val styleSheetId: StyleSheetId
)
/**
* Represents response frame that is returned from [CSS#getStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getStyleSheetText) operation call.
* Returns the current textual content for a stylesheet.
*
* @link [CSS#getStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getStyleSheetText) method documentation.
* @see [CSSDomain.getStyleSheetText]
*/
@kotlinx.serialization.Serializable
data class GetStyleSheetTextResponse(
/**
* The stylesheet text.
*/
val text: String
)
/**
* Represents request frame that can be used with [CSS#trackComputedStyleUpdates](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-trackComputedStyleUpdates) operation call.
*
* Starts tracking the given computed styles for updates. The specified array of properties
replaces the one previously specified. Pass empty array to disable tracking.
Use takeComputedStyleUpdates to retrieve the list of nodes that had properties modified.
The changes to computed style properties are only tracked for nodes pushed to the front-end
by the DOM agent. If no changes to the tracked properties occur after the node has been pushed
to the front-end, no updates will be issued for the node.
* @link [CSS#trackComputedStyleUpdates](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-trackComputedStyleUpdates) method documentation.
* @see [CSSDomain.trackComputedStyleUpdates]
*/
@kotlinx.serialization.Serializable
data class TrackComputedStyleUpdatesRequest(
/**
*
*/
val propertiesToTrack: List<CSSComputedStyleProperty>
)
/**
* Represents response frame that is returned from [CSS#takeComputedStyleUpdates](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeComputedStyleUpdates) operation call.
* Polls the next batch of computed style updates.
*
* @link [CSS#takeComputedStyleUpdates](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeComputedStyleUpdates) method documentation.
* @see [CSSDomain.takeComputedStyleUpdates]
*/
@kotlinx.serialization.Serializable
data class TakeComputedStyleUpdatesResponse(
/**
* The list of node Ids that have their tracked computed styles updated
*/
val nodeIds: List<pl.wendigo.chrome.api.dom.NodeId>
)
/**
* Represents request frame that can be used with [CSS#setEffectivePropertyValueForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setEffectivePropertyValueForNode) operation call.
*
* Find a rule with the given active property for the given node and set the new value for this
property
* @link [CSS#setEffectivePropertyValueForNode](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setEffectivePropertyValueForNode) method documentation.
* @see [CSSDomain.setEffectivePropertyValueForNode]
*/
@kotlinx.serialization.Serializable
data class SetEffectivePropertyValueForNodeRequest(
/**
* The element id for which to set property.
*/
val nodeId: pl.wendigo.chrome.api.dom.NodeId,
/**
*
*/
val propertyName: String,
/**
*
*/
val value: String
)
/**
* Represents request frame that can be used with [CSS#setKeyframeKey](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setKeyframeKey) operation call.
*
* Modifies the keyframe rule key text.
* @link [CSS#setKeyframeKey](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setKeyframeKey) method documentation.
* @see [CSSDomain.setKeyframeKey]
*/
@kotlinx.serialization.Serializable
data class SetKeyframeKeyRequest(
/**
*
*/
val styleSheetId: StyleSheetId,
/**
*
*/
val range: SourceRange,
/**
*
*/
val keyText: String
)
/**
* Represents response frame that is returned from [CSS#setKeyframeKey](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setKeyframeKey) operation call.
* Modifies the keyframe rule key text.
*
* @link [CSS#setKeyframeKey](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setKeyframeKey) method documentation.
* @see [CSSDomain.setKeyframeKey]
*/
@kotlinx.serialization.Serializable
data class SetKeyframeKeyResponse(
/**
* The resulting key text after modification.
*/
val keyText: Value
)
/**
* Represents request frame that can be used with [CSS#setMediaText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setMediaText) operation call.
*
* Modifies the rule selector.
* @link [CSS#setMediaText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setMediaText) method documentation.
* @see [CSSDomain.setMediaText]
*/
@kotlinx.serialization.Serializable
data class SetMediaTextRequest(
/**
*
*/
val styleSheetId: StyleSheetId,
/**
*
*/
val range: SourceRange,
/**
*
*/
val text: String
)
/**
* Represents response frame that is returned from [CSS#setMediaText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setMediaText) operation call.
* Modifies the rule selector.
*
* @link [CSS#setMediaText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setMediaText) method documentation.
* @see [CSSDomain.setMediaText]
*/
@kotlinx.serialization.Serializable
data class SetMediaTextResponse(
/**
* The resulting CSS media rule after modification.
*/
val media: CSSMedia
)
/**
* Represents request frame that can be used with [CSS#setRuleSelector](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setRuleSelector) operation call.
*
* Modifies the rule selector.
* @link [CSS#setRuleSelector](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setRuleSelector) method documentation.
* @see [CSSDomain.setRuleSelector]
*/
@kotlinx.serialization.Serializable
data class SetRuleSelectorRequest(
/**
*
*/
val styleSheetId: StyleSheetId,
/**
*
*/
val range: SourceRange,
/**
*
*/
val selector: String
)
/**
* Represents response frame that is returned from [CSS#setRuleSelector](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setRuleSelector) operation call.
* Modifies the rule selector.
*
* @link [CSS#setRuleSelector](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setRuleSelector) method documentation.
* @see [CSSDomain.setRuleSelector]
*/
@kotlinx.serialization.Serializable
data class SetRuleSelectorResponse(
/**
* The resulting selector list after modification.
*/
val selectorList: SelectorList
)
/**
* Represents request frame that can be used with [CSS#setStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleSheetText) operation call.
*
* Sets the new stylesheet text.
* @link [CSS#setStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleSheetText) method documentation.
* @see [CSSDomain.setStyleSheetText]
*/
@kotlinx.serialization.Serializable
data class SetStyleSheetTextRequest(
/**
*
*/
val styleSheetId: StyleSheetId,
/**
*
*/
val text: String
)
/**
* Represents response frame that is returned from [CSS#setStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleSheetText) operation call.
* Sets the new stylesheet text.
*
* @link [CSS#setStyleSheetText](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleSheetText) method documentation.
* @see [CSSDomain.setStyleSheetText]
*/
@kotlinx.serialization.Serializable
data class SetStyleSheetTextResponse(
/**
* URL of source map associated with script (if any).
*/
val sourceMapURL: String? = null
)
/**
* Represents request frame that can be used with [CSS#setStyleTexts](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleTexts) operation call.
*
* Applies specified style edits one after another in the given order.
* @link [CSS#setStyleTexts](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleTexts) method documentation.
* @see [CSSDomain.setStyleTexts]
*/
@kotlinx.serialization.Serializable
data class SetStyleTextsRequest(
/**
*
*/
val edits: List<StyleDeclarationEdit>
)
/**
* Represents response frame that is returned from [CSS#setStyleTexts](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleTexts) operation call.
* Applies specified style edits one after another in the given order.
*
* @link [CSS#setStyleTexts](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleTexts) method documentation.
* @see [CSSDomain.setStyleTexts]
*/
@kotlinx.serialization.Serializable
data class SetStyleTextsResponse(
/**
* The resulting styles after modification.
*/
val styles: List<CSSStyle>
)
/**
* Represents response frame that is returned from [CSS#stopRuleUsageTracking](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-stopRuleUsageTracking) operation call.
* Stop tracking rule usage and return the list of rules that were used since last call to
`takeCoverageDelta` (or since start of coverage instrumentation)
*
* @link [CSS#stopRuleUsageTracking](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-stopRuleUsageTracking) method documentation.
* @see [CSSDomain.stopRuleUsageTracking]
*/
@kotlinx.serialization.Serializable
data class StopRuleUsageTrackingResponse(
/**
*
*/
val ruleUsage: List<RuleUsage>
)
/**
* Represents response frame that is returned from [CSS#takeCoverageDelta](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeCoverageDelta) operation call.
* Obtain list of rules that became used since last call to this method (or since start of coverage
instrumentation)
*
* @link [CSS#takeCoverageDelta](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeCoverageDelta) method documentation.
* @see [CSSDomain.takeCoverageDelta]
*/
@kotlinx.serialization.Serializable
data class TakeCoverageDeltaResponse(
/**
*
*/
val coverage: List<RuleUsage>,
/**
* Monotonically increasing time, in seconds.
*/
val timestamp: Double
)
/**
* Represents request frame that can be used with [CSS#setLocalFontsEnabled](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setLocalFontsEnabled) operation call.
*
* Enables/disables rendering of local CSS fonts (enabled by default).
* @link [CSS#setLocalFontsEnabled](https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setLocalFontsEnabled) method documentation.
* @see [CSSDomain.setLocalFontsEnabled]
*/
@kotlinx.serialization.Serializable
data class SetLocalFontsEnabledRequest(
/**
* Whether rendering of local fonts is enabled.
*/
val enabled: Boolean
)
/**
* Fires whenever a web font is updated. A non-empty font parameter indicates a successfully loaded
web font
*
* @link [CSS#fontsUpdated](https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-fontsUpdated) event documentation.
*/
@kotlinx.serialization.Serializable
data class FontsUpdatedEvent(
/**
* The web font that has loaded.
*/
val font: FontFace? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "CSS"
override fun eventName() = "fontsUpdated"
}
/**
* Fired whenever an active document stylesheet is added.
*
* @link [CSS#styleSheetAdded](https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-styleSheetAdded) event documentation.
*/
@kotlinx.serialization.Serializable
data class StyleSheetAddedEvent(
/**
* Added stylesheet metainfo.
*/
val header: CSSStyleSheetHeader
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "CSS"
override fun eventName() = "styleSheetAdded"
}
/**
* Fired whenever a stylesheet is changed as a result of the client operation.
*
* @link [CSS#styleSheetChanged](https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-styleSheetChanged) event documentation.
*/
@kotlinx.serialization.Serializable
data class StyleSheetChangedEvent(
/**
*
*/
val styleSheetId: StyleSheetId
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "CSS"
override fun eventName() = "styleSheetChanged"
}
/**
* Fired whenever an active document stylesheet is removed.
*
* @link [CSS#styleSheetRemoved](https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-styleSheetRemoved) event documentation.
*/
@kotlinx.serialization.Serializable
data class StyleSheetRemovedEvent(
/**
* Identifier of the removed stylesheet.
*/
val styleSheetId: StyleSheetId
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "CSS"
override fun eventName() = "styleSheetRemoved"
}
| apache-2.0 | 73bac6d861e0faf69788039d44f55209 | 40.756808 | 401 | 0.752176 | 4.218459 | false | false | false | false |
afollestad/photo-affix | app/src/main/java/com/afollestad/photoaffix/adapters/PhotoGridAdapter.kt | 1 | 5618 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.photoaffix.adapters
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.dragselectrecyclerview.DragSelectReceiver
import com.afollestad.dragselectrecyclerview.DragSelectTouchListener
import com.afollestad.photoaffix.R
import com.afollestad.photoaffix.engine.photos.Photo
import com.afollestad.photoaffix.engine.photos.PhotoHolder
import com.afollestad.photoaffix.utilities.ext.loadImage
import com.afollestad.photoaffix.views.MainActivity
import kotlinx.android.synthetic.main.griditem_photo.view.check
import kotlinx.android.synthetic.main.griditem_photo.view.circle
import kotlinx.android.synthetic.main.griditem_photo.view.image
typealias SelectionListener = (position: Int, count: Int) -> Unit
class PhotoViewHolder(
itemView: View,
private val adapter: PhotoGridAdapter
) : RecyclerView.ViewHolder(itemView) {
init {
val context = itemView.context as MainActivity
itemView.setOnClickListener {
if (adapterPosition == 0) {
context.browseExternalPhotos()
} else {
adapter.toggleSelected(adapterPosition)
}
}
if (itemView.image != null) {
itemView.setOnLongClickListener {
adapter.toggleSelected(adapterPosition)
adapter.dragListener?.setIsActive(true, adapterPosition)
false
}
}
}
fun bind(photo: Photo) {
itemView.image.loadImage(photo.uri)
if (adapter.isSelected(adapterPosition)) {
itemView.check.visibility = VISIBLE
itemView.circle.isActivated = true
itemView.image.isActivated = true
} else {
itemView.check.visibility = GONE
itemView.circle.isActivated = false
itemView.image.isActivated = false
}
}
}
/** @author Aidan Follestad (afollestad) */
class PhotoGridAdapter(val context: MainActivity) : RecyclerView.Adapter<PhotoViewHolder>(),
DragSelectReceiver {
companion object {
private const val KEY_PHOTOS = "photos"
private const val KEY_SELECTED_INDICES = "selectedIndices"
}
val selectedPhotos: List<Photo>
get() {
return selectedIndices.map { photos[it - 1] }
}
var dragListener: DragSelectTouchListener? = null
private var photos = listOf<Photo>()
private var selectedIndices = mutableListOf<Int>()
private var selectionListener: SelectionListener? = null
fun onSelection(selection: SelectionListener) {
this.selectionListener = selection
}
fun hasSelection() = selectedIndices.isNotEmpty()
fun toggleSelected(index: Int) = setSelected(index, !isSelected(index))
fun shiftSelections() {
var i = 1
while (i < itemCount - 1) {
val currentSelected = isSelected(i)
if (currentSelected) {
setSelected(i + 1, true)
setSelected(i, false)
i++
}
i++
}
}
fun clearSelected() {
selectedIndices.clear()
this.selectionListener?.invoke(0, 0)
notifyDataSetChanged()
}
fun setPhotos(photos: List<Photo>) {
this.photos = photos
notifyDataSetChanged()
}
fun saveInstanceState(out: Bundle) {
if (photos.isNotEmpty()) {
out.putSerializable(KEY_PHOTOS, PhotoHolder(photos))
out.putIntArray(KEY_SELECTED_INDICES, selectedIndices.toIntArray())
}
}
fun restoreInstanceState(savedState: Bundle?) {
if (savedState?.containsKey(KEY_PHOTOS) == true) {
val ph = savedState.getSerializable(KEY_PHOTOS) as? PhotoHolder
?: return
setPhotos(ph.photos)
}
savedState?.getIntArray(KEY_SELECTED_INDICES)
?.let {
this.selectedIndices = it.toMutableList()
notifyDataSetChanged()
}
}
override fun isSelected(index: Int) = selectedIndices.contains(index)
override fun isIndexSelectable(index: Int) = index > 0
override fun setSelected(
index: Int,
selected: Boolean
) {
if (selected && !isSelected(index) && isIndexSelectable(index)) {
selectedIndices.add(index)
} else if (!selected) {
selectedIndices.remove(index)
}
this.selectionListener?.invoke(index, selectedIndices.size)
notifyItemChanged(index)
}
override fun getItemViewType(position: Int): Int {
return if (position == 0) 0 else 1
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): PhotoViewHolder {
val res =
if (viewType == 0) R.layout.griditem_browse
else R.layout.griditem_photo
val view = LayoutInflater.from(parent.context)
.inflate(res, parent, false)
return PhotoViewHolder(view, this)
}
override fun onBindViewHolder(
holder: PhotoViewHolder,
position: Int
) {
if (context.isFinishing || position == 0) return
val photo = photos[position - 1]
holder.bind(photo)
}
override fun getItemCount() = photos.size + 1
fun hasPhotos() = photos.isNotEmpty()
}
| apache-2.0 | 0e40eed91d0af2483151f5be101d327d | 28.108808 | 92 | 0.707547 | 4.308282 | false | false | false | false |
twilio/video-quickstart-android | quickstartKotlin/src/main/java/com/twilio/video/quickstart/kotlin/CameraCapturerCompat.kt | 1 | 7139 | package com.twilio.video.quickstart.kotlin
import android.annotation.TargetApi
import android.content.Context
import android.graphics.ImageFormat
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CameraMetadata
import android.os.Build
import com.twilio.video.Camera2Capturer
import com.twilio.video.CameraCapturer
import com.twilio.video.VideoCapturer
import java.util.EnumMap
import kotlin.collections.HashMap
import tvi.webrtc.Camera1Enumerator
import tvi.webrtc.Camera2Enumerator
import tvi.webrtc.CapturerObserver
import tvi.webrtc.SurfaceTextureHelper
/*
* Simple wrapper class that uses Camera2Capturer with supported devices.
*/
class CameraCapturerCompat(context: Context, cameraSource: Source) : VideoCapturer {
private val camera1Capturer: CameraCapturer?
private val camera2Capturer: Camera2Capturer?
private val activeCapturer: VideoCapturer
private val camera1IdMap: MutableMap<Source, String> = EnumMap(Source::class.java)
private val camera1SourceMap: MutableMap<String, Source> = HashMap()
private val camera2IdMap: MutableMap<Source, String> = EnumMap(Source::class.java)
private val camera2SourceMap: MutableMap<String, Source> = HashMap()
enum class Source {
FRONT_CAMERA, BACK_CAMERA
}
val cameraSource: Source
get() {
val source = if (usingCamera1()) {
requireNotNull(camera1Capturer)
camera1SourceMap[camera1Capturer.cameraId]
} else {
requireNotNull(camera2Capturer)
camera2SourceMap[camera2Capturer.cameraId]
}
requireNotNull(source)
return source
}
override fun initialize(
surfaceTextureHelper: SurfaceTextureHelper,
context: Context,
capturerObserver: CapturerObserver
) {
activeCapturer.initialize(surfaceTextureHelper, context, capturerObserver)
}
override fun startCapture(width: Int, height: Int, framerate: Int) {
activeCapturer.startCapture(width, height, framerate)
}
@Throws(InterruptedException::class)
override fun stopCapture() {
activeCapturer.stopCapture()
}
override fun isScreencast(): Boolean {
return activeCapturer.isScreencast
}
override fun dispose() {
activeCapturer.dispose()
}
fun switchCamera() {
val cameraSource = cameraSource
val idMap: Map<Source, String> = if (usingCamera1()) camera1IdMap else camera2IdMap
val newCameraId =
if (cameraSource == Source.FRONT_CAMERA) idMap[Source.BACK_CAMERA] else idMap[Source.FRONT_CAMERA]
if (usingCamera1()) {
newCameraId?.let { camera1Capturer?.switchCamera(it) }
} else {
newCameraId?.let { camera2Capturer?.switchCamera(it) }
}
}
private fun usingCamera1(): Boolean {
return camera1Capturer != null
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun setCamera2Maps(context: Context) {
val camera2Enumerator = Camera2Enumerator(context)
for (cameraId in camera2Enumerator.deviceNames) {
if (isCameraIdSupported(context, cameraId)) {
if (camera2Enumerator.isFrontFacing(cameraId)) {
camera2IdMap[Source.FRONT_CAMERA] = cameraId
camera2SourceMap[cameraId] = Source.FRONT_CAMERA
}
if (camera2Enumerator.isBackFacing(cameraId)) {
camera2IdMap[Source.BACK_CAMERA] = cameraId
camera2SourceMap[cameraId] = Source.BACK_CAMERA
}
}
}
}
private fun setCamera1Maps() {
val camera1Enumerator = Camera1Enumerator()
for (deviceName in camera1Enumerator.deviceNames) {
if (camera1Enumerator.isFrontFacing(deviceName)) {
camera1IdMap[Source.FRONT_CAMERA] = deviceName
camera1SourceMap[deviceName] = Source.FRONT_CAMERA
}
if (camera1Enumerator.isBackFacing(deviceName)) {
camera1IdMap[Source.BACK_CAMERA] = deviceName
camera1SourceMap[deviceName] = Source.BACK_CAMERA
}
}
}
private val isLollipopApiSupported: Boolean
get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun isCameraIdSupported(context: Context, cameraId: String): Boolean {
var isMonoChromeSupported = false
var isPrivateImageFormatSupported = false
val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraCharacteristics: CameraCharacteristics
cameraCharacteristics = try {
cameraManager.getCameraCharacteristics(cameraId)
} catch (e: Exception) {
e.printStackTrace()
return false
}
/*
* This is a temporary work around for a RuntimeException that occurs on devices which contain cameras
* that do not support ImageFormat.PRIVATE output formats. A long term fix is currently in development.
* https://github.com/twilio/video-quickstart-android/issues/431
*/
val streamMap =
cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
if (streamMap != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
isPrivateImageFormatSupported = streamMap.isOutputSupportedFor(ImageFormat.PRIVATE)
}
/*
* Read the color filter arrangements of the camera to filter out the ones that support
* SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_MONO or SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_NIR.
* Visit this link for details on supported values - https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics#SENSOR_INFO_COLOR_FILTER_ARRANGEMENT
*/
val colorFilterArrangement = cameraCharacteristics.get(
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && colorFilterArrangement != null) {
isMonoChromeSupported = (colorFilterArrangement
== CameraMetadata.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_MONO ||
colorFilterArrangement
== CameraMetadata.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_NIR)
}
return isPrivateImageFormatSupported && !isMonoChromeSupported
}
init {
if (Camera2Capturer.isSupported(context) && isLollipopApiSupported) {
setCamera2Maps(context)
camera2Capturer = Camera2Capturer(context, camera2IdMap[cameraSource]!!)
activeCapturer = camera2Capturer
camera1Capturer = null
} else {
setCamera1Maps()
camera1Capturer = CameraCapturer(context, camera1IdMap[cameraSource]!!)
activeCapturer = camera1Capturer
camera2Capturer = null
}
}
}
| mit | 747af6be9f0b10b75548d5badd946923 | 39.333333 | 184 | 0.671383 | 4.810647 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/import/AutoImportFix.kt | 2 | 8003 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.import
import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.intention.PriorityAction
import com.intellij.codeInspection.BatchQuickFix
import com.intellij.codeInspection.CommonProblemDescriptor
import com.intellij.codeInspection.HintAction
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.inspections.import.AutoImportFix.Type.*
import org.rust.ide.settings.RsCodeInsightSettings
import org.rust.ide.utils.import.ImportCandidate
import org.rust.ide.utils.import.ImportCandidatesCollector
import org.rust.ide.utils.import.ImportContext
import org.rust.ide.utils.import.import
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.infer.ResolvedPath
import org.rust.lang.core.types.inference
import org.rust.openapiext.Testmark
import org.rust.openapiext.checkWriteAccessNotAllowed
import org.rust.openapiext.runWriteCommandAction
class AutoImportFix(element: RsElement, private val context: Context) :
LocalQuickFixOnPsiElement(element), BatchQuickFix, PriorityAction, HintAction {
private var isConsumed: Boolean = false
override fun getFamilyName(): String = NAME
override fun getText(): String = familyName
public override fun isAvailable(): Boolean = super.isAvailable() && !isConsumed
override fun getPriority(): PriorityAction.Priority = PriorityAction.Priority.TOP
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
invoke(project)
}
fun invoke(project: Project) {
checkWriteAccessNotAllowed()
val element = startElement as? RsElement ?: return
val candidates = context.candidates
if (candidates.size == 1) {
project.runWriteCommandAction {
candidates.first().import(element)
}
} else {
DataManager.getInstance().dataContextFromFocusAsync.onSuccess {
chooseItemAndImport(project, it, candidates, element)
}
}
isConsumed = true
}
override fun applyFix(
project: Project,
descriptors: Array<CommonProblemDescriptor>,
psiElementsToIgnore: List<PsiElement>,
refreshViews: Runnable?
) {
project.runWriteCommandAction {
for (descriptor in descriptors) {
val fix = descriptor.fixes?.filterIsInstance<AutoImportFix>()?.singleOrNull() ?: continue
val candidate = fix.context.candidates.singleOrNull() ?: continue
val context = fix.startElement as? RsElement ?: continue
candidate.import(context)
}
}
refreshViews?.run()
}
private fun chooseItemAndImport(
project: Project,
dataContext: DataContext,
items: List<ImportCandidate>,
context: RsElement
) {
showItemsToImportChooser(project, dataContext, items) { selectedValue ->
project.runWriteCommandAction {
selectedValue.import(context)
}
}
}
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = isAvailable
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) = invoke(project)
override fun startInWriteAction(): Boolean = false
override fun getElementToMakeWritable(currentFile: PsiFile): PsiFile = currentFile
override fun showHint(editor: Editor): Boolean {
if (!RsCodeInsightSettings.getInstance().showImportPopup) return false
if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) return false
val candidates = context.candidates
val hint = candidates[0].info.usePath
val multiple = candidates.size > 1
val message = ShowAutoImportPass.getMessage(multiple, hint)
val element = startElement
HintManager.getInstance().showQuestionHint(editor, message, element.textOffset, element.endOffset) {
invoke(element.project)
true
}
return true
}
override fun fixSilently(editor: Editor): Boolean {
if (!RsCodeInsightSettings.getInstance().addUnambiguousImportsOnTheFly) return false
val candidates = context.candidates
if (candidates.size != 1) return false
val project = editor.project ?: return false
invoke(project)
return true
}
companion object {
const val NAME = "Import"
fun findApplicableContext(path: RsPath): Context? {
if (path.reference == null) return null
// `impl Future<Output=i32>`
// ~~~~~~ path
val parent = path.parent
if (parent is RsAssocTypeBinding && parent.eq != null && parent.path == path) return null
val basePath = path.basePath()
if (basePath.resolveStatus != PathResolveStatus.UNRESOLVED) return null
if (path.ancestorStrict<RsUseSpeck>() != null) {
// Don't try to import path in use item
Testmarks.PathInUseItem.hit()
return null
}
val referenceName = basePath.referenceName ?: return null
val importContext = ImportContext.from(path, ImportContext.Type.AUTO_IMPORT) ?: return null
val candidates = ImportCandidatesCollector.getImportCandidates(importContext, referenceName)
return Context(GENERAL_PATH, candidates)
}
fun findApplicableContext(pat: RsPatBinding): Context? {
val importContext = ImportContext.from(pat, ImportContext.Type.AUTO_IMPORT) ?: return null
val candidates = ImportCandidatesCollector.getImportCandidates(importContext, pat.referenceName)
if (candidates.isEmpty()) return null
return Context(GENERAL_PATH, candidates)
}
fun findApplicableContext(methodCall: RsMethodCall): Context? {
val results = methodCall.inference?.getResolvedMethod(methodCall) ?: emptyList()
if (results.isEmpty()) return Context(METHOD, emptyList())
val candidates = ImportCandidatesCollector.getImportCandidates(methodCall, results) ?: return null
return Context(METHOD, candidates)
}
/** Import traits for type-related UFCS method calls and assoc items */
fun findApplicableContextForAssocItemPath(path: RsPath): Context? {
val parent = path.parent as? RsPathExpr ?: return null
// `std::default::Default::default()`
val qualifierElement = path.qualifier?.reference?.resolve()
if (qualifierElement is RsTraitItem) return null
// `<Foo as bar::Baz>::qux()`
val typeQual = path.typeQual
if (typeQual != null && typeQual.traitRef != null) return null
val resolved = path.inference?.getResolvedPath(parent) ?: return null
val sources = resolved.map {
if (it !is ResolvedPath.AssocItem) return null
it.source
}
val candidates = ImportCandidatesCollector.getTraitImportCandidates(path, sources) ?: return null
return Context(ASSOC_ITEM_PATH, candidates)
}
}
data class Context(
val type: Type,
val candidates: List<ImportCandidate>
)
enum class Type {
GENERAL_PATH,
ASSOC_ITEM_PATH,
METHOD
}
object Testmarks {
object PathInUseItem : Testmark()
}
}
| mit | 229af5b122cb18811684abe60ff01526 | 37.475962 | 110 | 0.671748 | 5.023854 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/MaintenanceActivity.kt | 1 | 3364 | package com.habitrpg.android.habitica.ui.activities
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import androidx.core.net.toUri
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.api.MaintenanceApiService
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.databinding.ActivityMaintenanceBinding
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.ui.helpers.setMarkdown
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import javax.inject.Inject
class MaintenanceActivity : BaseActivity() {
private lateinit var binding: ActivityMaintenanceBinding
@Inject
lateinit var maintenanceService: MaintenanceApiService
@Inject
lateinit var apiClient: ApiClient
private var isDeprecationNotice: Boolean = false
override fun getLayoutResId(): Int {
return R.layout.activity_maintenance
}
override fun getContentView(): View {
binding = ActivityMaintenanceBinding.inflate(layoutInflater)
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val data = intent.extras ?: return
binding.titleTextView.text = data.getString("title")
@Suppress("DEPRECATION")
binding.imageView.setImageURI(data.getString("imageUrl")?.toUri())
binding.descriptionTextView.setMarkdown(data.getString("description"))
binding.descriptionTextView.movementMethod = LinkMovementMethod.getInstance()
isDeprecationNotice = data.getBoolean("deprecationNotice")
if (isDeprecationNotice) {
binding.playStoreButton.visibility = View.VISIBLE
} else {
binding.playStoreButton.visibility = View.GONE
}
binding.playStoreButton.setOnClickListener { openInPlayStore() }
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onResume() {
super.onResume()
if (!isDeprecationNotice) {
compositeSubscription.add(
this.maintenanceService.maintenanceStatus
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ maintenanceResponse ->
if (!maintenanceResponse.activeMaintenance) {
finish()
}
},
RxErrorHandler.handleEmptyError()
)
)
}
}
private fun openInPlayStore() {
val appPackageName = packageName
try {
startActivity(Intent(Intent.ACTION_VIEW, "market://details?id=$appPackageName".toUri()))
} catch (anfe: android.content.ActivityNotFoundException) {
startActivity(Intent(Intent.ACTION_VIEW, "https://play.google.com/store/apps/details?id=$appPackageName".toUri()))
}
}
}
| gpl-3.0 | bb098bb08dae61600d2860e73f1c93bb | 34.172043 | 126 | 0.656659 | 5.305994 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/safety/SafetyNumberBucketRowItem.kt | 1 | 4903 | package org.thoughtcrime.securesms.safety
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import org.signal.core.util.DimensionUnit
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.menu.ActionItem
import org.thoughtcrime.securesms.components.menu.SignalContextMenu
import org.thoughtcrime.securesms.database.model.DistributionListId
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import org.thoughtcrime.securesms.util.visible
object SafetyNumberBucketRowItem {
fun register(mappingAdapter: MappingAdapter) {
mappingAdapter.registerFactory(DistributionListModel::class.java, LayoutFactory(::DistributionListViewHolder, R.layout.safety_number_bucket_row_item))
mappingAdapter.registerFactory(GroupModel::class.java, LayoutFactory(::GroupViewHolder, R.layout.safety_number_bucket_row_item))
mappingAdapter.registerFactory(ContactsModel::class.java, LayoutFactory(::ContactsViewHolder, R.layout.safety_number_bucket_row_item))
}
fun createModel(
safetyNumberBucket: SafetyNumberBucket,
actionItemsProvider: (SafetyNumberBucket) -> List<ActionItem>
): MappingModel<*> {
return when (safetyNumberBucket) {
SafetyNumberBucket.ContactsBucket -> ContactsModel()
is SafetyNumberBucket.DistributionListBucket -> DistributionListModel(safetyNumberBucket, actionItemsProvider)
is SafetyNumberBucket.GroupBucket -> GroupModel(safetyNumberBucket)
}
}
private class DistributionListModel(
val distributionListBucket: SafetyNumberBucket.DistributionListBucket,
val actionItemsProvider: (SafetyNumberBucket) -> List<ActionItem>
) : MappingModel<DistributionListModel> {
override fun areItemsTheSame(newItem: DistributionListModel): Boolean {
return distributionListBucket.distributionListId == newItem.distributionListBucket.distributionListId
}
override fun areContentsTheSame(newItem: DistributionListModel): Boolean {
return distributionListBucket == newItem.distributionListBucket
}
}
private class GroupModel(val groupBucket: SafetyNumberBucket.GroupBucket) : MappingModel<GroupModel> {
override fun areItemsTheSame(newItem: GroupModel): Boolean {
return groupBucket.recipient.id == newItem.groupBucket.recipient.id
}
override fun areContentsTheSame(newItem: GroupModel): Boolean {
return groupBucket.recipient.hasSameContent(newItem.groupBucket.recipient)
}
}
private class ContactsModel : MappingModel<ContactsModel> {
override fun areItemsTheSame(newItem: ContactsModel): Boolean = true
override fun areContentsTheSame(newItem: ContactsModel): Boolean = true
}
private class DistributionListViewHolder(itemView: View) : BaseViewHolder<DistributionListModel>(itemView) {
override fun getTitle(model: DistributionListModel): String {
return if (model.distributionListBucket.distributionListId == DistributionListId.MY_STORY) {
context.getString(R.string.Recipient_my_story)
} else {
model.distributionListBucket.name
}
}
override fun bindMenuListener(model: DistributionListModel, menuView: View) {
menuView.setOnClickListener {
SignalContextMenu.Builder(menuView, menuView.rootView as ViewGroup)
.offsetX(DimensionUnit.DP.toPixels(16f).toInt())
.offsetY(DimensionUnit.DP.toPixels(16f).toInt())
.show(model.actionItemsProvider(model.distributionListBucket))
}
}
}
private class GroupViewHolder(itemView: View) : BaseViewHolder<GroupModel>(itemView) {
override fun getTitle(model: GroupModel): String {
return model.groupBucket.recipient.getDisplayName(context)
}
override fun bindMenuListener(model: GroupModel, menuView: View) {
menuView.visible = false
}
}
private class ContactsViewHolder(itemView: View) : BaseViewHolder<ContactsModel>(itemView) {
override fun getTitle(model: ContactsModel): String {
return context.getString(R.string.SafetyNumberBucketRowItem__contacts)
}
override fun bindMenuListener(model: ContactsModel, menuView: View) {
menuView.visible = false
}
}
private abstract class BaseViewHolder<T : MappingModel<*>>(itemView: View) : MappingViewHolder<T>(itemView) {
private val titleView: TextView = findViewById(R.id.safety_number_bucket_header)
private val menuView: View = findViewById(R.id.safety_number_bucket_menu)
override fun bind(model: T) {
titleView.text = getTitle(model)
bindMenuListener(model, menuView)
}
abstract fun getTitle(model: T): String
abstract fun bindMenuListener(model: T, menuView: View)
}
}
| gpl-3.0 | 5fcb167bc5c90738db6bfd3255e6165a | 41.267241 | 154 | 0.77218 | 4.792766 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui-test/testData/refactoring/rename/automaticRenamer/after/main.kt | 1 | 662 | open class Bar : Throwable()
val foo: Bar = Bar()
val foo1: Bar = Bar()
val foos: List<Bar> = listOf()
val foos1: Array<Bar> = array()
fun main(args: Array<String>) {
val foo: Bar = Bar()
val someVerySpecialFoo: Bar = Bar()
val fooAnother: Bar = Bar()
val anonymous = object : Bar() {
}
val (foo1: Bar, foos: List<Bar>) = Pair(Bar(), listOf<Bar>())
try {
for (foo2: Bar in listOf<Bar>()) {
}
} catch (foo: Bar) {
}
fun local(foo: Bar) {
}
}
fun topLevel(foo: Bar) {
}
fun collectionLikes(foos: List<Array<Bar>>, foos: List<Map<Bar, Bar>>) {
}
class FooImpl : Bar()
object FooObj : Bar() | apache-2.0 | 3c58eb9ee8e44ab9a29570fa8b6c8cac | 14.785714 | 72 | 0.561934 | 2.942222 | false | false | false | false |
Gazer/localshare | app/src/main/java/ar/com/p39/localshare/sharer/ShareActivity.kt | 1 | 4248 | package ar.com.p39.localshare.sharer
import android.content.Intent
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Bundle
import android.provider.OpenableColumns
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TextView
import ar.com.p39.localshare.BuildConfig
import ar.com.p39.localshare.MyApplication
import ar.com.p39.localshare.R
import ar.com.p39.localshare.common.IpAddress
import ar.com.p39.localshare.common.network.WifiSSIDProvider
import ar.com.p39.localshare.common.ui.QRImageView
import ar.com.p39.localshare.sharer.models.FileShare
import ar.com.p39.localshare.sharer.presenters.SharePresenter
import ar.com.p39.localshare.sharer.views.ShareView
import butterknife.bindView
import com.crashlytics.android.answers.Answers
import com.crashlytics.android.answers.CustomEvent
import dagger.Module
import dagger.Provides
import dagger.Subcomponent
import java.io.IOException
import java.util.*
import javax.inject.Inject
class ShareActivity : AppCompatActivity(), ShareView {
val qr: QRImageView by bindView(R.id.qr)
val help: TextView by bindView(R.id.help)
val helpWifi: TextView by bindView(R.id.help_wifi)
@Inject
lateinit var presenter: SharePresenter
@Inject
lateinit var bssidProvider: WifiSSIDProvider
@Inject
lateinit var wifiManager: WifiManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_share)
MyApplication.graph.plus(ShareActivityModule(intent)).inject(this)
val toolbar = findViewById(R.id.toolbar) as Toolbar?
setSupportActionBar(toolbar)
supportActionBar?.title = getString(R.string.title_activity_share)
presenter.bindView(this)
presenter.checkWifiStatus(bssidProvider.isConnected(), bssidProvider.getBSSID())
helpWifi.text = getString(R.string.help_network, bssidProvider.getBSSID())
}
override fun showUriData(uri: Uri) {
showUriData(listOf(uri))
}
override fun showUriData(uris: List<Uri>) {
val files = ArrayList<FileShare>()
for (uri in uris) {
val returnCursor = contentResolver.query(uri, null, null, null, null)
val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE)
returnCursor.moveToFirst()
try {
val share = FileShare(
returnCursor.getString(nameIndex),
returnCursor.getLong(sizeIndex),
contentResolver.getType(uri),
uri
)
files.add(share)
} catch (e: IOException) {
} finally {
returnCursor.close()
}
}
shareFiles(files)
}
private fun shareFiles(files: List<FileShare>) {
val ip = wifiManager.IpAddress()
if (ip != null) {
presenter.startSharing(contentResolver, ip, files)
qr.setData("http://$ip:8080/sharer")
trackFiles(files.size)
} else {
showWifiError()
}
}
private fun trackFiles(size: Int) {
// TODO : DI!
if (!BuildConfig.DEBUG) {
Answers.getInstance().logCustom(CustomEvent("Files Shared").putCustomAttribute("Count", size));
}
}
override fun showWifiError() {
Snackbar.make(help, R.string.connect_to_wifi , Snackbar.LENGTH_INDEFINITE).show()
help.visibility = View.GONE
qr.visibility = View.GONE
}
override fun onStop() {
super.onStop()
presenter.stopSharing()
}
@Subcomponent(modules = arrayOf(ShareActivityModule::class))
interface ShareActivityComponent {
fun inject(shareActivity: ShareActivity);
}
@Module
class ShareActivityModule(private var intent: Intent) {
@Provides
fun provideSharePresenter(): SharePresenter {
return SharePresenter(intent)
}
}
}
| apache-2.0 | 871c39d44de785742663188ccc6740d8 | 29.561151 | 107 | 0.672787 | 4.286579 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-lunch-tray | app/src/main/java/com/example/lunchtray/ui/CheckoutScreen.kt | 1 | 4556 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.lunchtray.ui
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Divider
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.lunchtray.R
import com.example.lunchtray.datasource.DataSource
import com.example.lunchtray.model.MenuItem
import com.example.lunchtray.model.OrderUiState
@Composable
fun CheckoutScreen(
orderUiState: OrderUiState,
onNextButtonClicked: () -> Unit,
onCancelButtonClicked: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.padding(16.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = stringResource(R.string.order_summary),
fontWeight = FontWeight.Bold
)
ItemSummary(item = orderUiState.entree)
ItemSummary(item = orderUiState.sideDish)
ItemSummary(item = orderUiState.accompaniment)
Divider(thickness = 1.dp, modifier = Modifier.padding(bottom = 8.dp))
OrderSubCost(
resourceId = R.string.subtotal,
price = orderUiState.itemTotalPrice.formatPrice(),
Modifier.align(Alignment.End)
)
OrderSubCost(
resourceId = R.string.tax,
price = orderUiState.orderTax.formatPrice(),
Modifier.align(Alignment.End)
)
Text(
text = stringResource(R.string.total, orderUiState.orderTotalPrice.formatPrice()),
modifier = Modifier.align(Alignment.End),
fontWeight = FontWeight.Bold
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
){
OutlinedButton(modifier = Modifier.weight(1f), onClick = onCancelButtonClicked) {
Text(stringResource(R.string.cancel).uppercase())
}
Button(
modifier = Modifier.weight(1f),
onClick = onNextButtonClicked
) {
Text(stringResource(R.string.submit).uppercase())
}
}
}
}
@Composable
fun ItemSummary(
item: MenuItem?,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(item?.name ?: "")
Text(item?.getFormattedPrice() ?: "")
}
}
@Composable
fun OrderSubCost(
@StringRes resourceId: Int,
price: String,
modifier: Modifier = Modifier
) {
Text(
text = stringResource(resourceId, price),
modifier = modifier
)
}
@Preview
@Composable
fun CheckoutScreenPreview() {
CheckoutScreen(
orderUiState = OrderUiState(
entree = DataSource.entreeMenuItems[0],
sideDish = DataSource.sideDishMenuItems[0],
accompaniment = DataSource.accompanimentMenuItems[0],
itemTotalPrice = 15.00,
orderTax = 1.00,
orderTotalPrice = 16.00
),
onNextButtonClicked = {},
onCancelButtonClicked = {}
)
}
| apache-2.0 | 0714f91c3b33a8a62e4323df03a18a92 | 30.638889 | 94 | 0.668569 | 4.588117 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/ovr/OVRTypes.kt | 1 | 37279 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.ovr
import org.lwjgl.generator.*
// We include the OVR headers from the Oculus SDK directly, so handle warnings on use-site
fun GeneratorTargetNative.includeOVRCAPI() = nativeDirective(
"""DISABLE_WARNINGS()
#include "OVR_CAPI.h"
ENABLE_WARNINGS()""")
fun GeneratorTargetNative.includeOVRCAPI_GL() = nativeDirective(
"""DISABLE_WARNINGS()
#include "OVR_CAPI_GL.h"
ENABLE_WARNINGS()""")
val OVR_PACKAGE = "org.lwjgl.ovr"
val OVR_LIBRARY = "LibOVR.initialize();"
val long_long = IntegerType("long long", PrimitiveMapping.LONG)
val ovrBool = IntegerType("ovrBool", PrimitiveMapping.BOOLEAN)
val ovrBool_p = ovrBool.p
val ovrResult = IntegerType("ovrResult", PrimitiveMapping.INT)
val ovrSession = "ovrSession".opaque_p
val ovrSession_p = ovrSession.p
val ovrHmdType = "ovrHmdType".enumType
val ovrEyeType = "ovrEyeType".enumType
val ovrLayerType = "ovrLayerType".enumType
val ovrLogCallback = "ovrLogCallback".callback(
OVR_PACKAGE, void, "OVRLogCallback",
"The logging callback.",
uintptr_t.IN("userData", "an arbitrary value specified by the user of ovrInitParams"),
int.IN("level", "one of the {@code ovrLogLevel} constants"),
NullTerminated..const..charUTF8_p.IN("message", "a UTF8-encoded null-terminated string")
) {
documentation = "Instances of this interface may be passed to the {@code LogCallback} member of the ##OVRInitParams struct."
additionalCode = """
/**
* Converts the specified {@link OVRLogCallback} argument to a String.
*
* <p>This method may only be used inside a OVRLogCallback invocation.</p>
*
* @param message the OVRLogCallback {@code message} argument
*
* @return the message as a String
*/
public static String getMessage(long message) {
return memUTF8(message);
}
"""
}
val ovrErrorInfo_p = struct(OVR_PACKAGE, "OVRErrorInfo", nativeName = "ovrErrorInfo", mutable = false) {
documentation = "Provides information about the last error."
ovrResult.member("Result", "the result from the last API call that generated an error {@code ovrResult}")
charUTF8.array(
"ErrorString",
"a UTF8-encoded null-terminated English string describing the problem. The format of this string is subject to change in future versions",
size = 512
)
}.p
val ovrSessionStatus_p = struct(OVR_PACKAGE, "OVRSessionStatus", nativeName = "ovrSessionStatus", mutable = false) {
documentation = "Specifies status information for the current session."
ovrBool.member("IsVisible", "True if the process has VR focus and thus is visible in the HMD.")
ovrBool.member("HmdPresent", "True if an HMD is present.")
ovrBool.member("HmdMounted", "True if the HMD is on the user's head.")
ovrBool.member("DisplayLost", "True if the session is in a display-lost state. See OVR#ovr_SubmitFrame().")
ovrBool.member("ShouldQuit", "True if the application should initiate shutdown. ")
ovrBool.member("ShouldRecenter", "True if UX has requested re-centering. Must call OVR#ovr_ClearShouldRecenterFlag() or OVR#ovr_RecenterTrackingOrigin().")
}.p
val ovrInitParams_p = struct(OVR_PACKAGE, "OVRInitParams", nativeName = "ovrInitParams") {
documentation = "Parameters for OVR#ovr_Initialize()."
uint32_t.member("Flags", "flags from {@code ovrInitFlags} to override default behavior. Use 0 for the defaults.")
uint32_t.member(
"RequestedMinorVersion",
"""
requests a specific minor version of the LibOVR runtime. Flags must include #Init_RequestVersion or this will be ignored and #MINOR_VERSION will
be used. If you are directly calling the LibOVRRT version of #Initialize() in the LibOVRRT DLL then this must be valid and include
#Init_RequestVersion.
"""
)
nullable..ovrLogCallback.member(
"LogCallback",
"""
user-supplied log callback function, which may be called at any time asynchronously from multiple threads until OVR#ovr_Shutdown() completes. Use $NULL
to specify no log callback.
"""
)
uintptr_t.member(
"UserData",
"""
user-supplied data which is passed as-is to {@code LogCallback}. Typically this is used to store an application-specific pointer which is read in the
callback function.
"""
)
uint32_t.member(
"ConnectionTimeoutMS",
"relative number of milliseconds to wait for a connection to the server before failing. Use 0 for the default timeout."
)
padding(4, condition = "Pointer.BITS64")
}.p
val ovrColorf = struct(OVR_PACKAGE, "OVRColorf", nativeName = "ovrColorf") {
documentation = "An RGBA color with normalized float components."
float.member("r", "the R component")
float.member("g", "the G component")
float.member("b", "the B component")
float.member("a", "the A component")
}
val ovrVector2i = struct(OVR_PACKAGE, "OVRVector2i", nativeName = "ovrVector2i") {
documentation = "A 2D vector with integer components."
int.member("x", "the vector x component")
int.member("y", "the vector y component")
}
val ovrSizei = struct(OVR_PACKAGE, "OVRSizei", nativeName = "ovrSizei") {
documentation = "A 2D size with integer components."
int.member("w", "the width")
int.member("h", "the height")
}
val ovrRecti = struct(OVR_PACKAGE, "OVRRecti", nativeName = "ovrRecti") {
documentation = "A 2D rectangle with a position and size. All components are integers."
ovrVector2i.member("Pos", "the rectangle position")
ovrSizei.member("Size", "the rectangle size")
}
val ovrQuatf = struct(OVR_PACKAGE, "OVRQuatf", nativeName = "ovrQuatf") {
documentation = "A quaternion rotation."
float.member("x", "the vector x component")
float.member("y", "the vector y component")
float.member("z", "the vector z component")
float.member("w", "the vector w component")
}
val ovrVector2f = struct(OVR_PACKAGE, "OVRVector2f", nativeName = "ovrVector2f") {
documentation = "A 2D vector with float components."
float.member("x", "the vector x component")
float.member("y", "the vector y component")
}
val ovrVector3f = struct(OVR_PACKAGE, "OVRVector3f", nativeName = "ovrVector3f") {
documentation = "A 3D vector with float components."
float.member("x", "the vector x component")
float.member("y", "the vector y component")
float.member("z", "the vector z component")
}
val ovrVector3f_p = ovrVector3f.p
val ovrMatrix4f = struct(OVR_PACKAGE, "OVRMatrix4f", nativeName = "ovrMatrix4f") {
documentation = "A 4x4 matrix with float components."
float.array("M", "the matrix components", 16)
}
val ovrPosef = struct(OVR_PACKAGE, "OVRPosef", nativeName = "ovrPosef") {
documentation = "Position and orientation together."
ovrQuatf.member("Orientation", "the pose orientation")
ovrVector3f.member("Position", "the pose position")
}
val ovrPosef_p = ovrPosef.p
val ovrPoseStatef = struct(OVR_PACKAGE, "OVRPoseStatef", nativeName = "ovrPoseStatef", mutable = false) {
documentation =
"""
A full pose (rigid body) configuration with first and second derivatives.
Body refers to any object for which ovrPoseStatef is providing data. It can be the HMD, Touch controller, sensor or something else. The context
depends on the usage of the struct.
"""
ovrPosef.member("ThePose", "position and orientation")
ovrVector3f.member("AngularVelocity", "angular velocity in radians per second")
ovrVector3f.member("LinearVelocity", "velocity in meters per second")
ovrVector3f.member("AngularAcceleration", "angular acceleration in radians per second per second")
ovrVector3f.member("LinearAcceleration", "acceleration in meters per second per second")
double.member("TimeInSeconds", "absolute time that this pose refers to. See OVR#ovr_GetTimeInSeconds()")
}
val ovrFovPort = struct(OVR_PACKAGE, "OVRFovPort", nativeName = "ovrFovPort") {
documentation =
"""
Field Of View (FOV) in tangent of the angle units. As an example, for a standard 90 degree vertical FOV, we would have:
${codeBlock("{ UpTan = tan(90 degrees / 2), DownTan = tan(90 degrees / 2) }")}
"""
float.member("UpTan", "the tangent of the angle between the viewing vector and the top edge of the field of view")
float.member("DownTan", "the tangent of the angle between the viewing vector and the bottom edge of the field of view")
float.member("LeftTan", "the tangent of the angle between the viewing vector and the left edge of the field of view")
float.member("RightTan", "the tangent of the angle between the viewing vector and the right edge of the field of view")
}
val ovrTrackingOrigin = "ovrTrackingOrigin".enumType
val ovrGraphicsLuid_p = struct(OVR_PACKAGE, "OVRGraphicsLuid", nativeName = "ovrGraphicsLuid", mutable = false) {
documentation =
"""
Identifies a graphics device in a platform-specific way.
For Windows this is a LUID type.
"""
char.array("Reserved", "public definition reserves space for graphics API-specific implementation.", size = 8)
}.p
val ovrHmdDesc = struct(OVR_PACKAGE, "OVRHmdDesc", nativeName = "ovrHmdDesc", mutable = false) {
javaImport("static org.lwjgl.ovr.OVR.ovrEye_Count")
documentation = "A complete descriptor of the HMD."
ovrHmdType.member("Type", "this HMD's type").links("Hmd_\\w+")
padding(4, "Pointer.BITS64")
charUTF8.array("ProductName", "name string describing the product: \"Oculus Rift DK1\", etc.", size = 64)
charUTF8.array("Manufacturer", "string describing the manufacturer. Usually \"Oculus\".", size = 64)
short.member("VendorId", "HID Vendor ID of the device")
short.member("ProductId", "HID Product ID of the device")
charASCII.array("SerialNumber", "HMD serial number", size = 24)
short.member("FirmwareMajor", "HMD firmware major version number")
short.member("FirmwareMinor", "HMD firmware minor version number")
unsigned_int.member("AvailableHmdCaps", "capability bits described by {@code ovrHmdCaps} which the HMD currently supports")
unsigned_int.member("DefaultHmdCaps", "capability bits described by {@code ovrHmdCaps} which are default for the current {@code Hmd}")
unsigned_int.member("AvailableTrackingCaps", "capability bits described by {@code ovrTrackingCaps} which the system currently supports")
unsigned_int.member("DefaultTrackingCaps", "capability bits described by {@code ovrTrackingCaps} which are default for the current system")
ovrFovPort.array("DefaultEyeFov", "the recommended optical FOV for the HMD", size = "ovrEye_Count")
ovrFovPort.array("MaxEyeFov", "the maximum optical FOV for the HMD", size = "ovrEye_Count")
ovrSizei.member("Resolution", "resolution of the full HMD screen (both eyes) in pixels")
float.member("DisplayRefreshRate", "nominal refresh rate of the display in cycles per second at the time of HMD creation")
padding(4, "Pointer.BITS64")
}
val ovrTrackerDesc = struct(OVR_PACKAGE, "OVRTrackerDesc", nativeName = "ovrTrackerDesc", mutable = false) {
documentation = "Specifies the description of a single sensor."
float.member("FrustumHFovInRadians", "sensor frustum horizontal field-of-view (if present).")
float.member("FrustumVFovInRadians", "sensor frustum vertical field-of-view (if present).")
float.member("FrustumNearZInMeters", "sensor frustum near Z (if present).")
float.member("FrustumFarZInMeters", "sensor frustum far Z (if present).")
}
val ovrTrackerPose = struct(OVR_PACKAGE, "OVRTrackerPose", nativeName = "ovrTrackerPose", mutable = false) {
documentation = "Specifies the pose for a single sensor."
unsigned_int.member("TrackerFlags", "{@code ovrTrackerFlags}.")
ovrPosef.member("Pose", "the sensor's pose. This pose includes sensor tilt (roll and pitch). For a leveled coordinate system use {@code LeveledPose}.")
ovrPosef.member(
"LeveledPose",
"""t
the sensor's leveled pose, aligned with gravity. This value includes position and yaw of the sensor, but not roll and pitch. It can be used as a
reference point to render real-world objects in the correct location.
"""
)
padding(4)
}
val ovrTrackingState = struct(OVR_PACKAGE, "OVRTrackingState", nativeName = "ovrTrackingState", mutable = false) {
documentation = "Tracking state at a given absolute time (describes predicted HMD pose etc). Returned by OVR#ovr_GetTrackingState()."
ovrPoseStatef.member(
"HeadPose",
"""
Predicted head pose (and derivatives) at the requested absolute time. The look-ahead interval is equal to
{@code (HeadPose.TimeInSeconds - RawSensorData.TimeInSeconds)}.
"""
)
unsigned_int.member("StatusFlags", "{@code HeadPose} tracking status described by {@code ovrStatusBits}.")
ovrPoseStatef.array(
"HandPoses",
"""
The most recent calculated pose for each hand when hand controller tracking is present. {@code HandPoses[ovrHand_Left]} refers to the left hand and
{@code HandPoses[ovrHand_Right]} to the right hand. These values can be combined with {@code ovrInputState} for complete hand controller information.
""",
size = 2
)
unsigned_int.array(
"HandStatusFlags",
"{@code HandPoses} status flags described by {@code ovrStatusBits}. Only OVR#ovrStatus_OrientationTracked and OVR#ovrStatus_PositionTracked are reported.",
size = 2
)
ovrPosef.member(
"CalibratedOrigin",
"""
the pose of the origin captured during calibration.
Like all other poses here, this is expressed in the space set by #RecenterTrackingOrigin(), and so will change every time that is called. This pose can
be used to calculate where the calibrated origin lands in the new recentered space. If an application never calls #RecenterTrackingOrigin(), expect
this value to be the identity pose and as such will point respective origin based on {@code ovrTrackingOrigin} requested when calling
#GetTrackingState().
""")
}
val ovrEyeRenderDesc = struct(OVR_PACKAGE, "OVREyeRenderDesc", nativeName = "ovrEyeRenderDesc", mutable = false) {
documentation =
"""
rendering information for each eye. Computed by either OVR#ovr_GetRenderDesc() based on the specified FOV. Note that the rendering viewport is not
included here as it can be specified separately and modified per frame by passing different viewport values in the layer structure.
"""
ovrEyeType.member("Eye", "the eye index this instance corresponds to").links("Eye_(?!Count)\\w+")
ovrFovPort.member("Fov", "the field of view")
ovrRecti.member("DistortedViewport", "distortion viewport")
ovrVector2f.member("PixelsPerTanAngleAtCenter", "wow many display pixels will fit in tan(angle) = 1")
ovrVector3f.member("HmdToEyeOffset", "translation of each eye, in meters.")
}
val ovrTimewarpProjectionDesc = struct(OVR_PACKAGE, "OVRTimewarpProjectionDesc", nativeName = "ovrTimewarpProjectionDesc", mutable = false) {
documentation =
"""
Projection information for ##OVRLayerEyeFovDepth.
Use the utility function OVRUtil#ovrTimewarpProjectionDesc_FromProjection() to generate this structure from the application's projection matrix.
"""
float.member("Projection22", "projection matrix element [2][2]")
float.member("Projection23", "projection matrix element [2][3]")
float.member("Projection32", "projection matrix element [3][2]")
}
val ovrViewScaleDesc_p = struct(OVR_PACKAGE, "OVRViewScaleDesc", nativeName = "ovrViewScaleDesc") {
javaImport("static org.lwjgl.ovr.OVR.ovrEye_Count")
documentation =
"""
Contains the data necessary to properly calculate position info for various layer types.
${ul(
"{@code HmdToEyeOffset} is the same value pair provided in ##OVREyeRenderDesc.",
"{@code HmdSpaceToWorldScaleInMeters} is used to scale player motion into in-application units."
)}
In other words, it is how big an in-application unit is in the player's physical meters. For example, if the application uses inches as its units then
{@code HmdSpaceToWorldScaleInMeters} would be 0.0254. Note that if you are scaling the player in size, this must also scale. So if your application
units are inches, but you're shrinking the player to half their normal size, then {@code HmdSpaceToWorldScaleInMeters} would be {@code 0.0254*2.0}.
"""
ovrVector3f.array("HmdToEyeOffset", "translation of each eye", size = "ovrEye_Count")
float.member("HmdSpaceToWorldScaleInMeters", "ratio of viewer units to meter units")
}.p
val ovrTextureType = "ovrTextureType".enumType
val ovrTextureFormat = "ovrTextureFormat".enumType
val ovrTextureSwapChainDesc_p = struct(OVR_PACKAGE, "OVRTextureSwapChainDesc", nativeName = "ovrTextureSwapChainDesc") {
documentation = "Description used to create a texture swap chain."
ovrTextureType.member("Type", "").links("Texture_\\w+")
ovrTextureFormat.member("Format", "").links("OVR_FORMAT_\\w+")
int.member("ArraySize", "only supported with OVR#ovrTexture_2D. Not supported on PC at this time.")
int.member("Width", "")
int.member("Height", "")
int.member("MipLevels", "")
int.member("SampleCount", "current only supported on depth textures")
ovrBool.member("StaticImage", "not buffered in a chain. For images that don't change")
unsigned_int.member("MiscFlags", "{@code ovrTextureFlags}").links("TextureMisc_\\w+", LinkMode.BITFIELD)
unsigned_int.member("BindFlags", "{@code ovrTextureBindFlags}. Not used for GL.").links("TextureBind_\\w+", LinkMode.BITFIELD)
}.p
val ovrMirrorTextureDesc_p = struct(OVR_PACKAGE, "OVRMirrorTextureDesc", nativeName = "ovrMirrorTextureDesc") {
documentation = "Description used to create a mirror texture."
ovrTextureFormat.member("Format", "").links("OVR_FORMAT_\\w+")
int.member("Width", "")
int.member("Height", "")
unsigned_int.member("MiscFlags", "{@code ovrTextureFlags}").links("TextureMisc_\\w+", LinkMode.BITFIELD)
}.p
val ovrTextureSwapChain = "ovrTextureSwapChain".opaque_p
val ovrTextureSwapChain_p = ovrTextureSwapChain.p
val ovrMirrorTexture = "ovrMirrorTexture".opaque_p
val ovrMirrorTexture_p = ovrMirrorTexture.p
val ovrTouchHapticsDesc = struct(OVR_PACKAGE, "OVRTouchHapticsDesc", nativeName = "ovrTouchHapticsDesc", mutable = false) {
documentation = "Describes the Touch Haptics engine."
int.member("SampleRateHz", "Haptics engine frequency/sample-rate, sample time in seconds equals {@code 1.0/sampleRateHz}")
int.member("SampleSizeInBytes", "Size of each Haptics sample, sample value range is {@code [0, 2^(Bytes*8)-1]}")
int.member(
"QueueMinSizeToAvoidStarvation",
"Queue size that would guarantee Haptics engine would not starve for data. Make sure size doesn't drop below it for best results."
)
int.member("SubmitMinSamples", "Minimum number of samples that can be sent to Haptics through #SubmitControllerVibration()")
int.member("SubmitMaxSamples", "Maximum number of samples that can be sent to Haptics through #SubmitControllerVibration()")
int.member("SubmitOptimalSamples", "Optimal number of samples that can be sent to Haptics through #SubmitControllerVibration()")
}
val ovrHapticsBufferSubmitMode = "ovrHapticsBufferSubmitMode".enumType
val ovrHapticsBuffer_p = struct(OVR_PACKAGE, "OVRHapticsBuffer", nativeName = "ovrHapticsBuffer") {
documentation = "Haptics buffer descriptor, contains amplitude samples used for Touch vibration."
void_p.member("Samples", "")
int.member("SamplesCount", "")
ovrHapticsBufferSubmitMode.member("SubmitMode", "")
}.p
val ovrHapticsPlaybackState_p = struct(OVR_PACKAGE, "OVRHapticsPlaybackState", nativeName = "ovrHapticsPlaybackState", mutable = false) {
documentation = "State of the Haptics playback for Touch vibration."
int.member("RemainingQueueSpace", "Remaining space available to queue more samples")
int.member("SamplesQueued", "Number of samples currently queued")
}.p
val ovrControllerType = "ovrControllerType".enumType
val ovrTrackedDeviceType = "ovrTrackedDeviceType".enumType
val ovrBoundaryType = "ovrBoundaryType".enumType
val ovrBoundaryLookAndFeel_p = struct(OVR_PACKAGE, "OVRBoundaryLookAndFeel", nativeName = "ovrBoundaryLookAndFeel") {
documentation = "Boundary system look and feel."
ovrColorf.member("Color", "Boundary color (alpha channel is ignored)")
}.p
val ovrBoundaryTestResult_p = struct(OVR_PACKAGE, "OVRBoundaryTestResult", nativeName = "ovrBoundaryTestResult", mutable = false) {
documentation = "Provides boundary test information."
ovrBool.member("IsTriggering", "True, if the boundary system is being triggered and visible")
float.member("ClosestDistance", "Distance to the closest play area or outer boundary surface")
ovrVector3f.member("ClosestPoint", "Closest point in the surface")
ovrVector3f.member("ClosestPointNormal", "Normal of the closest point")
}.p
val ovrInputState_p = struct(OVR_PACKAGE, "OVRInputState", nativeName = "ovrInputState", mutable = false) {
javaImport("static org.lwjgl.ovr.OVR.ovrHand_Count")
documentation =
"""
Describes the complete controller input state, including Oculus Touch, and XBox gamepad. If multiple inputs are connected and used at the same time,
their inputs are combined.
"""
double.member("TimeInSeconds", "system type when the controller state was last updated")
unsigned_int.member("ConnectedControllerTypes", "described by {@code ovrControllerType}. Indicates which ControllerTypes are present.")
unsigned_int.member("Buttons", "values for buttons described by {@code ovrButton}")
unsigned_int.member("Touches", "touch values for buttons and sensors as described by {@code ovrTouch}.")
float.array(
"IndexTrigger",
"left and right finger trigger values (OVR#ovrHand_Left and OVR#ovrHand_Right), in the range 0.0 to 1.0f.",
size = "ovrHand_Count"
)
float.array(
"HandTrigger",
"left and right hand trigger values (OVR#ovrHand_Left and OVR#ovrHand_Right), in the range 0.0 to 1.0f.",
size = "ovrHand_Count"
)
ovrVector2f.array(
"Thumbstick",
"horizontal and vertical thumbstick axis values (OVR#ovrHand_Left and OVR#ovrHand_Right), in the range -1.0f to 1.0f.",
size = "ovrHand_Count"
)
ovrControllerType.member("ControllerType", "The type of the controller this state is for.").links("ControllerType_\\w+")
float.array(
"IndexTriggerNoDeadzone",
"Left and right finger trigger values (#Hand_Left and #Hand_Right), in the range 0.0 to 1.0f. Does not apply a deadzone",
size = "ovrHand_Count"
)
float.array(
"HandTriggerNoDeadzone",
"Left and right hand trigger values (#Hand_Left and #Hand_Right), in the range 0.0 to 1.0f. Does not apply a deadzone.",
size = "ovrHand_Count"
)
float.array(
"ThumbstickNoDeadzone",
"Horizontal and vertical thumbstick axis values (#Hand_Left and #Hand_Right), in the range -1.0f to 1.0f. Does not apply a deadzone.",
size = "ovrHand_Count"
)
}.p
val ovrLayerHeader = struct(OVR_PACKAGE, "OVRLayerHeader", nativeName = "ovrLayerHeader") {
documentation =
"""
Defines properties shared by all ovrLayer structs, such as ##OVRLayerEyeFov.
{@code ovrLayerHeader} is used as a base member in these larger structs. This struct cannot be used by itself except for the case that {@code Type} is
OVR#ovrLayerType_Disabled.
"""
ovrLayerType.member("Type", "described by {@code ovrLayerType}").links("LayerType_\\w+")
unsigned_int.member("Flags", "described by {@code ovrLayerFlags}")
}
val ovrLayerHeader_p = ovrLayerHeader.p
val ovrLayerHeader_p_const_p = ovrLayerHeader_p.p_const_p
val ovrLayerEyeFov = struct(OVR_PACKAGE, "OVRLayerEyeFov", nativeName = "ovrLayerEyeFov") {
javaImport("static org.lwjgl.ovr.OVR.ovrEye_Count")
documentation =
"""
Describes a layer that specifies a monoscopic or stereoscopic view. This is the kind of layer that's typically used as layer 0 to
OVR#ovr_SubmitFrame(), as it is the kind of layer used to render a 3D stereoscopic view.
"""
ovrLayerHeader.member("Header", "{@code Header.Type} must be OVR#ovrLayerType_EyeFov.")
ovrTextureSwapChain.array(
"ColorTexture",
"{@code ovrTextureSwapChains} for the left and right eye respectively. The second one of which can be $NULL.",
size = "ovrEye_Count",
validSize = "1"
)
ovrRecti.array(
"Viewport",
"specifies the ColorTexture sub-rect UV coordinates. Both {@code Viewport[0]} and {@code Viewport[1]} must be valid.",
size = "ovrEye_Count"
)
ovrFovPort.array("Fov", "the viewport field of view", size = "ovrEye_Count")
ovrPosef.array(
"RenderPose",
"""
specifies the position and orientation of each eye view, with the position specified in meters. RenderPose will typically be the value returned from
OVRUtil#ovr_CalcEyePoses(), but can be different in special cases if a different head pose is used for rendering.
""",
size = "ovrEye_Count"
)
double.member(
"SensorSampleTime",
"""
specifies the timestamp when the source ##OVRPosef (used in calculating RenderPose) was sampled from the SDK. Typically retrieved by calling
OVR#ovr_GetTimeInSeconds() around the instant the application calls OVR#ovr_GetTrackingState(). The main purpose for this is to accurately track app
tracking latency.
"""
)
}
val ovrLayerQuad = struct(OVR_PACKAGE, "OVRLayerQuad", nativeName = "ovrLayerQuad") {
documentation =
"""
Describes a layer of Quad type, which is a single quad in world or viewer space. It is used for both OVR#ovrLayerType_Quad. This type of layer
represents a single object placed in the world and not a stereo view of the world itself.
A typical use of OVR#ovrLayerType_Quad is to draw a television screen in a room that for some reason is more convenient to draw as a layer than
as part of the main view in layer 0. For example, it could implement a 3D popup GUI that is drawn at a higher resolution than layer 0 to improve
fidelity of the GUI.
Quad layers are visible from both sides; they are not back-face culled.
"""
ovrLayerHeader.member("Header", "{@code Header.Type} must be OVR#ovrLayerType_Quad")
ovrTextureSwapChain.member("ColorTexture", "contains a single image, never with any stereo view")
ovrRecti.member("Viewport", "specifies the ColorTexture sub-rect UV coordinates")
ovrPosef.member(
"QuadPoseCenter",
"""
specifies the orientation and position of the center point of a Quad layer type.
The supplied direction is the vector perpendicular to the quad. The position is in real-world meters (not the application's virtual world, the physical
world the user is in) and is relative to the "zero" position set by OVR#ovr_RecenterTrackingOrigin() unless the OVR#ovrLayerFlag_HeadLocked flag is
used.
"""
)
ovrVector2f.member("QuadSize", "width and height (respectively) of the quad in meters")
}
val ovrPerfStatsPerCompositorFrame = struct(OVR_PACKAGE, "OVRPerfStatsPerCompositorFrame", nativeName = "ovrPerfStatsPerCompositorFrame", mutable = false) {
documentation =
"""
Contains the performance stats for a given SDK compositor frame.
All of the int fields can be reset via the #ResetPerfStats() call.
"""
int.member(
"HmdVsyncIndex",
"""
Vsync Frame Index - increments with each HMD vertical synchronization signal (i.e. vsync or refresh rate).
If the compositor drops a frame, expect this value to increment more than 1 at a time.
"""
)
///
/// Application stats
///
int.member("AppFrameIndex", "index that increments with each successive #SubmitFrame() call")
int.member("AppDroppedFrameCount", "if the app fails to call #SubmitFrame() on time, then expect this value to increment with each missed frame")
float.member(
"AppMotionToPhotonLatency",
"""
motion-to-photon latency for the application
This value is calculated by either using the {@code SensorSampleTime} provided for the ##OVRLayerEyeFov or if that is not available, then the call to
#GetTrackingState() which has {@code latencyMarker} set to #True.
"""
)
float.member(
"AppQueueAheadTime",
"""
amount of queue-ahead in seconds provided to the app based on performance and overlap of CPU & GPU utilization
A value of 0.0 would mean the CPU & GPU workload is being completed in 1 frame's worth of time, while 11 ms (on the CV1) of queue ahead would indicate
that the app's CPU workload for the next frame is overlapping the app's GPU workload for the current frame.
"""
)
float.member(
"AppCpuElapsedTime",
"""
amount of time in seconds spent on the CPU by the app's render-thread that calls #SubmitFrame().
Measured as elapsed time between from when app regains control from #SubmitFrame() to the next time the app calls #SubmitFrame().
"""
)
float.member(
"AppGpuElapsedTime",
"""
amount of time in seconds spent on the GPU by the app.
Measured as elapsed time between each #SubmitFrame() call using GPU timing queries.
"""
)
///
/// SDK Compositor stats
///
int.member(
"CompositorFrameIndex",
"""
index that increments each time the SDK compositor completes a distortion and timewarp pass.
Since the compositor operates asynchronously, even if the app calls #SubmitFrame() too late, the compositor will kick off for each vsync.
"""
)
int.member(
"CompositorDroppedFrameCount",
"""
increments each time the SDK compositor fails to complete in time.
This is not tied to the app's performance, but failure to complete can be tied to other factors such as OS capabilities, overall available hardware
cycles to execute the compositor in time and other factors outside of the app's control.
"""
)
float.member(
"CompositorLatency",
"""
motion-to-photon latency of the SDK compositor in seconds.
This is the latency of timewarp which corrects the higher app latency as well as dropped app frames.
"""
)
float.member(
"CompositorCpuElapsedTime",
"""
the amount of time in seconds spent on the CPU by the SDK compositor.
Unless the VR app is utilizing all of the CPU cores at their peak performance, there is a good chance the compositor CPU times will not affect the
app's CPU performance in a major way.
"""
)
float.member(
"CompositorGpuElapsedTime",
"""
the amount of time in seconds spent on the GPU by the SDK compositor. Any time spent on the compositor will eat away from the available GPU time for
the app.
"""
)
float.member(
"CompositorCpuStartToGpuEndElapsedTime",
"""
the amount of time in seconds spent from the point the CPU kicks off the compositor to the point in time the compositor completes the distortion &
timewarp on the GPU.
In the event the GPU time is not available, expect this value to be -1.0f.
"""
)
float.member(
"CompositorGpuEndToVsyncElapsedTime",
"""
the amount of time in seconds left after the compositor is done on the GPU to the associated V-Sync time.
In the event the GPU time is not available, expect this value to be -1.0f.
"""
)
}
val ovrPerfStats_p = struct(OVR_PACKAGE, "OVRPerfStats", nativeName = "ovrPerfStats", mutable = false) {
javaImport("static org.lwjgl.ovr.OVR.ovrMaxProvidedFrameStats")
documentation =
"""
This is a complete descriptor of the performance stats provided by the SDK.
{@code FrameStatsCount} will have a maximum value set by #MaxProvidedFrameStats.
If the application calls #GetPerfStats() at the native refresh rate of the HMD then {@code FrameStatsCount} will be 1. If the app's workload happens to
force #GetPerfStats() to be called at a lower rate, then {@code FrameStatsCount} will be 2 or more.
If the app does not want to miss any performance data for any frame, it needs to ensure that it is calling #SubmitFrame() and #GetPerfStats() at a rate
that is at least: {@code HMD_refresh_rate / ovrMaxProvidedFrameStats}. On the Oculus Rift CV1 HMD, this will be equal to 18 times per second.
If the app calls #SubmitFrame() at a rate less than 18 fps, then when calling #GetPerfStats(), expect {@code AnyFrameStatsDropped} to become #True while
{@code FrameStatsCount} is equal to #MaxProvidedFrameStats.
The performance entries will be ordered in reverse chronological order such that the first entry will be the most recent one.
{@code AdaptiveGpuPerformanceScale} is an edge-filtered value that a caller can use to adjust the graphics quality of the application to keep the GPU
utilization in check. The value is calculated as: {@code (desired_GPU_utilization / current_GPU_utilization)}
As such, when this value is 1.0, the GPU is doing the right amount of work for the app. Lower values mean the app needs to pull back on the GPU
utilization. If the app is going to directly drive render-target resolution using this value, then be sure to take the square-root of the value before
scaling the resolution with it. Changing render target resolutions however is one of the many things an app can do increase or decrease the amount of GPU
utilization. Since {@code AdaptiveGpuPerformanceScale} is edge-filtered and does not change rapidly (i.e. reports non-1.0 values once every couple of
seconds) the app can make the necessary adjustments and then keep watching the value to see if it has been satisfied.
"""
ovrPerfStatsPerCompositorFrame.array("FrameStats", "an array of performance stats", size = "ovrMaxProvidedFrameStats")
AutoSize("FrameStats")..int.member("FrameStatsCount", "the number of performance stats available in {@code FrameStats}")
ovrBool.member("AnyFrameStatsDropped", "if performance stats have been dropped")
float.member("AdaptiveGpuPerformanceScale", "the GPU performance scale")
}.p
// OVR_CAPI_Util.h
val ovrDetectResult = struct(OVR_PACKAGE, "OVRDetectResult", nativeName = "ovrDetectResult", mutable = false) {
documentation = "Return values for OVRUtil##ovr_Detect()"
ovrBool.member(
"IsOculusServiceRunning",
"""
is OVR#ovrFalse when the Oculus Service is not running. This means that the Oculus Service is either uninstalled or stopped.
{@code IsOculusHMDConnected} will be OVR#ovrFalse in this case.
is OVR#ovrTrue when the Oculus Service is running. This means that the Oculus Service is installed and running. {@code IsOculusHMDConnected} will
reflect the state of the HMD.
"""
)
ovrBool.member(
"IsOculusHMDConnected",
"""
is OVR#ovrFalse when an Oculus HMD is not detected. If the Oculus Service is not running, this will be OVR#ovrFalse.
is OVR#ovrTrue when an Oculus HMD is detected. This implies that the Oculus Service is also installed and running.
"""
)
padding(6)
}
fun config() {
packageInfo(
OVR_PACKAGE,
"""
Contains bindings to LibOVR, the <a href="https://developer.oculus.com/">Oculus SDK</a> library.
Documentation on how to get started with the Oculus SDK can be found <a href="https://developer.oculus.com/documentation/">here</a>.
"""
)
Generator.registerLibraryInit(OVR_PACKAGE, "LibOVR", "ovr")
struct(OVR_PACKAGE, "OVRLayerEyeMatrix", nativeName = "ovrLayerEyeMatrix") {
javaImport("static org.lwjgl.ovr.OVR.ovrEye_Count")
documentation =
"""
Describes a layer that specifies a monoscopic or stereoscopic view. This uses a direct 3x4 matrix to map from view space to the UV coordinates. It
is essentially the same thing as ##OVRLayerEyeFov but using a much lower level. This is mainly to provide compatibility with specific apps. Unless
the application really requires this flexibility, it is usually better to use ##OVRLayerEyeFov.
Three options exist with respect to mono/stereo texture usage:
${ul(
"""
ColorTexture[0] and ColorTexture[1] contain the left and right stereo renderings, respectively. Viewport[0] and Viewport[1] refer to
ColorTexture[0] and ColorTexture[1], respectively.
""",
"""
ColorTexture[0] contains both the left and right renderings, ColorTexture[1] is $NULL, and Viewport[0] and Viewport[1] refer to sub-rects with
ColorTexture[0].
""",
"ColorTexture[0] contains a single monoscopic rendering, and Viewport[0] and Viewport[1] both refer to that rendering."
)}
"""
ovrLayerHeader.member("Header", "{@code Header.Type} must be OVR#ovrLayerType_EyeMatrix")
ovrTextureSwapChain.array(
"ColorTexture",
"{@code ovrTextureSwapChains} for the left and right eye respectively. The second one of which can be $NULL",
size = "ovrEye_Count",
validSize = "1"
)
ovrRecti.array(
"Viewport",
"specifies the {@code ColorTexture} sub-rect UV coordinates. Both {@code Viewport[0]} and {@code Viewport[1]} must be valid.",
size = "ovrEye_Count"
)
ovrPosef.array(
"RenderPose",
"""
specifies the position and orientation of each eye view, with the position specified in meters. RenderPose will typically be the value returned
from OVRUtil#ovr_CalcEyePoses(), but can be different in special cases if a different head pose is used for rendering.
""",
size = "ovrEye_Count"
)
ovrMatrix4f.array(
"Matrix",
"""
specifies the mapping from a view-space vector to a UV coordinate on the textures given above.
${codeBlock("""
P = (x,y,z,1)*Matrix
TexU = P.x/P.z
TexV = P.y/P.z""")}
""",
size = "ovrEye_Count"
)
double.member(
"SensorSampleTime",
"""
specifies the timestamp when the source ##OVRPosef (used in calculating RenderPose) was sampled from the SDK. Typically retrieved by calling
OVR#ovr_GetTimeInSeconds() around the instant the application calls OVR#ovr_GetTrackingState(). The main purpose for this is to accurately track
app tracking latency.
"""
)
}
union(OVR_PACKAGE, "OVRLayerUnion", nativeName = "ovrLayer_Union") {
documentation = "Union that combines {@code ovrLayer} types in a way that allows them to be used in a polymorphic way."
ovrLayerHeader.member("Header", "the layer header")
ovrLayerEyeFov.member("EyeFov", "")
ovrLayerQuad.member("Quad", "")
}
} | bsd-3-clause | 1406927ba100dbd0bb02378e0e26b288 | 43.118343 | 157 | 0.745272 | 3.576266 | false | false | false | false |
SimpleMobileTools/Simple-Calculator | app/src/main/kotlin/com/simplemobiletools/calculator/models/History.kt | 1 | 490 | package com.simplemobiletools.calculator.models
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(tableName = "history", indices = [(Index(value = ["id"], unique = true))])
data class History(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "formula") var formula: String,
@ColumnInfo(name = "result") var result: String,
@ColumnInfo(name = "timestamp") var timestamp: Long
)
| gpl-3.0 | ccbba3940d284e9cf4861817479e2e46 | 34 | 82 | 0.732653 | 3.951613 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/fabric/creator/FabricTemplate.kt | 1 | 4940 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.fabric.creator
import com.demonwav.mcdev.creator.buildsystem.BuildSystem
import com.demonwav.mcdev.platform.BaseTemplate
import com.demonwav.mcdev.platform.forge.inspections.sideonly.Side
import com.demonwav.mcdev.util.License
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_BUILD_GRADLE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_GRADLE_PROPERTIES_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_MIXINS_JSON_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_MOD_JSON_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_SETTINGS_GRADLE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_SUBMODULE_BUILD_GRADLE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.FABRIC_SUBMODULE_GRADLE_PROPERTIES_TEMPLATE
import com.demonwav.mcdev.util.toPackageName
import com.intellij.openapi.project.Project
object FabricTemplate : BaseTemplate() {
private fun Project.applyGradleTemplate(
templateName: String,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
val props = mutableMapOf<String, Any>(
"GROUP_ID" to buildSystem.groupId,
"ARTIFACT_ID" to buildSystem.artifactId,
"VERSION" to buildSystem.version,
"MC_VERSION" to config.mcVersion,
"YARN_MAPPINGS" to config.yarnVersion,
"LOADER_VERSION" to config.loaderVersion.toString(),
"LOOM_VERSION" to config.loomVersion.toString(),
"JAVA_VERSION" to config.javaVersion.feature
)
config.yarnClassifier?.let {
props["YARN_CLASSIFIER"] = it
}
config.apiVersion?.let {
props["API_VERSION"] = it.toString()
}
config.apiMavenLocation?.let {
props["API_MAVEN_LOCATION"] = it
}
return applyTemplate(templateName, props)
}
fun applyBuildGradle(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_BUILD_GRADLE_TEMPLATE, buildSystem, config)
}
fun applyMultiModuleBuildGradle(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_SUBMODULE_BUILD_GRADLE_TEMPLATE, buildSystem, config)
}
fun applySettingsGradle(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_SETTINGS_GRADLE_TEMPLATE, buildSystem, config)
}
fun applyGradleProp(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_GRADLE_PROPERTIES_TEMPLATE, buildSystem, config)
}
fun applyMultiModuleGradleProp(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
return project.applyGradleTemplate(FABRIC_SUBMODULE_GRADLE_PROPERTIES_TEMPLATE, buildSystem, config)
}
fun applyFabricModJsonTemplate(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
val props = mutableMapOf<String, Any>(
"ARTIFACT_ID" to buildSystem.artifactId,
"MOD_NAME" to config.pluginName,
"MOD_DESCRIPTION" to (config.description ?: ""),
"MOD_ENVIRONMENT" to when (config.environment) {
Side.CLIENT -> "client"
Side.SERVER -> "server"
else -> "*"
},
"LOADER_VERSION" to config.loaderVersion.toString(),
"MC_VERSION" to config.semanticMcVersion.toString(),
"JAVA_VERSION" to config.javaVersion.feature,
"LICENSE" to ((config.license ?: License.ALL_RIGHTS_RESERVED).id)
)
config.apiVersion?.let {
props["API_VERSION"] = it.toString()
}
if (config.mixins) {
props["MIXINS"] = "true"
}
return project.applyTemplate(FABRIC_MOD_JSON_TEMPLATE, props)
}
fun applyMixinConfigTemplate(
project: Project,
buildSystem: BuildSystem,
config: FabricProjectConfig
): String {
val packageName = "${buildSystem.groupId.toPackageName()}.${buildSystem.artifactId.toPackageName()}.mixin"
val props = mapOf(
"PACKAGE_NAME" to packageName,
"JAVA_VERSION" to config.javaVersion.feature
)
return project.applyTemplate(FABRIC_MIXINS_JSON_TEMPLATE, props)
}
}
| mit | 78aedbcb2a0b1db97e79e10b0c8102f0 | 34.797101 | 114 | 0.668219 | 4.718243 | false | true | false | false |
world-federation-of-advertisers/panel-exchange-client | src/main/kotlin/org/wfanet/panelmatch/tools/ExchangeWorkflowToGraphvizMain.kt | 1 | 2405 | // Copyright 2021 The Cross-Media Measurement Authors
//
// 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.wfanet.panelmatch.tools
import com.google.protobuf.TextFormat
import java.nio.charset.StandardCharsets
import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow
import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow.Party.DATA_PROVIDER
import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow.Party.MODEL_PROVIDER
import org.wfanet.measurement.common.graphviz.digraph
private val PARTY_COLOR = mapOf(DATA_PROVIDER to "blue", MODEL_PROVIDER to "red")
private const val BLOB_SHAPE = "egg"
private const val STEP_SHAPE = "box"
fun main() {
val workflow =
System.`in`.bufferedReader(StandardCharsets.UTF_8).use { reader ->
ExchangeWorkflow.newBuilder().apply { TextFormat.merge(reader, this) }.build()
}
val steps = workflow.stepsList
val graph = digraph {
attributes { set("splines" to "ortho") }
for ((party, partySteps) in steps.groupBy { it.party }) {
val color = PARTY_COLOR.getValue(party)
val outputs = mutableSetOf<String>()
for (step in partySteps) {
val nodeName = step.stepId.toNodeName()
node(nodeName) {
set("color" to color)
set("shape" to STEP_SHAPE)
set("label" to step.stepId)
}
for (label in step.outputLabelsMap.values) {
edge(nodeName to label.toNodeName())
}
for (label in step.inputLabelsMap.values) {
edge(label.toNodeName() to nodeName)
}
outputs.addAll(step.outputLabelsMap.values)
}
for (output in outputs) {
node(output.toNodeName()) {
set("color" to color)
set("shape" to BLOB_SHAPE)
set("label" to output)
}
}
}
}
println(graph)
}
private fun String.toNodeName(): String {
return replace('-', '_')
}
| apache-2.0 | f7d1835879ee7962f774e2b77dffcc04 | 30.233766 | 84 | 0.679418 | 4.008333 | false | false | false | false |
esofthead/mycollab | mycollab-web/src/main/java/com/mycollab/module/project/view/StandupUrlResolver.kt | 3 | 2190 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.view
import com.mycollab.core.utils.StringUtils
import com.mycollab.db.arguments.DateSearchField
import com.mycollab.module.project.domain.criteria.StandupReportSearchCriteria
import com.mycollab.module.project.event.StandUpEvent
import com.mycollab.vaadin.EventBusFactory
import java.time.LocalDate
import java.time.format.DateTimeFormatter
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
class StandupUrlResolver : ProjectUrlResolver() {
init {
this.addSubResolver("list", ListUrlResolver())
}
private class ListUrlResolver : ProjectUrlResolver() {
private val dateFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy")
override fun handlePage(vararg params: String) {
val searchCriteria = StandupReportSearchCriteria()
if (params.isEmpty()) {
searchCriteria.onDate = DateSearchField(LocalDate.now(), DateSearchField.EQUAL)
} else {
val date = parseDate(params[0])
searchCriteria.onDate = DateSearchField(date, DateSearchField.EQUAL)
}
EventBusFactory.getInstance().post(StandUpEvent.GotoList(this, searchCriteria))
}
/**
* @param dateVal
* @return
*/
private fun parseDate(dateVal: String?): LocalDate = when {
StringUtils.isBlank(dateVal) -> LocalDate.now()
else -> LocalDate.parse(dateVal, dateFormatter)
}
}
} | agpl-3.0 | ec10c82dea9f4bf2ea47f05c4975012e | 35.5 | 95 | 0.693467 | 4.532091 | false | false | false | false |
handstandsam/ShoppingApp | multiplatform/src/jsMain/kotlin/Main.kt | 1 | 3083 | import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import com.handstandsam.shoppingapp.cart.InMemoryShoppingCartDao
import com.handstandsam.shoppingapp.cart.ShoppingCart
import com.handstandsam.shoppingapp.models.ItemWithQuantity
import com.handstandsam.shoppingapp.models.totalItemCount
import com.handstandsam.shoppingapp.multiplatform.ui.ButtonType
import com.handstandsam.shoppingapp.multiplatform.ui.CartViewModel
import com.handstandsam.shoppingapp.multiplatform.ui.CategoryDetailViewModel
import com.handstandsam.shoppingapp.multiplatform.ui.HomeViewModel
import com.handstandsam.shoppingapp.multiplatform.ui.ItemDetailViewModel
import com.handstandsam.shoppingapp.multiplatform.ui.NavRoute
import com.handstandsam.shoppingapp.multiplatform.ui.ShoppingAppButton
import com.handstandsam.shoppingapp.multiplatform.ui.WrappedPreformattedText
import com.handstandsam.shoppingapp.multiplatform.ui.navController
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import org.jetbrains.compose.web.dom.Button
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.Text
import org.jetbrains.compose.web.renderComposable
fun main() {
val scope = CoroutineScope(Dispatchers.Unconfined)
val shoppingCart = ShoppingCart(InMemoryShoppingCartDao())
val homeViewModel = HomeViewModel()
val categoryDetailViewModel = CategoryDetailViewModel()
val cartViewModel = CartViewModel(shoppingCart = shoppingCart)
val itemDetailViewModel = ItemDetailViewModel(shoppingCart = shoppingCart)
@Composable
fun ShoppingApp() {
val itemsInCartFlow: Flow<List<ItemWithQuantity>> = shoppingCart.itemsInCart
val itemsInCartCount: List<ItemWithQuantity> by itemsInCartFlow.collectAsState(listOf())
val collectedNavRoute: NavRoute by navController.collectAsState()
Div {
Text("${itemsInCartCount.totalItemCount()} Item(s) in Cart")
ShoppingAppButton(label = "View Cart", buttonType = ButtonType.PRIMARY) {
scope.launch {
navController.tryEmit(NavRoute.CartScreen(shoppingCart.latestItemsInCart()))
}
}
WrappedPreformattedText(itemsInCartCount.toString())
}
when (val navRoute = collectedNavRoute) {
NavRoute.HomeScreen -> {
homeViewModel.HomeScreen()
}
is NavRoute.CategoryDetailScreen -> {
categoryDetailViewModel.CategoryDetailScreen(navRoute.category)
}
is NavRoute.ItemDetailScreen -> {
itemDetailViewModel.ItemDetailScreen(navRoute.item)
}
is NavRoute.CartScreen -> {
cartViewModel.CartScreen(navRoute.itemsWithQuantity)
}
}
}
/** Entry Point */
renderComposable(rootElementId = "root") {
ShoppingApp()
}
Backstack.init()
} | apache-2.0 | 54c35fef81f3bb00b2f5a5bec0ad9311 | 40.12 | 96 | 0.742783 | 5.00487 | false | false | false | false |
ZieIony/Carbon | component/src/main/java/carbon/component/ImageTextSubtextItem.kt | 1 | 1118 | package carbon.component
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import carbon.component.databinding.CarbonRowImagetextsubtextBinding
import java.io.Serializable
interface ImageTextSubtextItem : Serializable {
val image: Drawable?
val text: String?
val subtext: String?
}
open class DefaultImageTextSubtextItem : ImageTextSubtextItem {
override var image: Drawable? = null
override var text: String? = null
override var subtext: String? = null
constructor()
constructor(image: Drawable?, text: String?, subtext: String?) {
this.image = image
this.text = text
this.subtext = subtext
}
}
open class ImageTextSubtextRow<Type : ImageTextSubtextItem>(parent: ViewGroup)
: LayoutComponent<Type>(parent, R.layout.carbon_row_imagetextsubtext) {
private val binding = CarbonRowImagetextsubtextBinding.bind(view)
override fun bind(data: Type) {
binding.carbonAvatar.setImageDrawable(data.image)
binding.carbonText.text = data.text ?: ""
binding.carbonSubtext.text = data.subtext ?: ""
}
}
| apache-2.0 | 1b647bb24c61740eb8c02608f6b3fad9 | 29.216216 | 78 | 0.724508 | 3.909091 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/stats/StatsSliderView.kt | 1 | 3646 | package com.habitrpg.android.habitica.ui.views.stats
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.SeekBar
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.StatsSliderViewBinding
import com.habitrpg.android.habitica.extensions.AfterChangeTextWatcher
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.extensions.setTintWith
import com.habitrpg.android.habitica.extensions.styledAttributes
class StatsSliderView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
private val binding = StatsSliderViewBinding.inflate(context.layoutInflater, this)
var previousValue = 0
set(value) {
field = value
binding.previousValueTextView.text = value.toString()
}
var maxValue = 0
set(value) {
field = value
binding.statsSeekBar.max = field
}
var currentValue = 0
set(value) {
field = value
binding.statsSeekBar.progress = value
binding.valueEditText.setText(value.toString())
if (binding.valueEditText.isFocused) {
binding.valueEditText.setSelection(binding.valueEditText.length())
}
}
var allocateAction: ((Int) -> Unit)? = null
init {
gravity = Gravity.CENTER_VERTICAL
val attributes = attrs?.styledAttributes(context, R.styleable.StatsSliderView)
if (attributes != null) {
binding.statTypeTitle.text = attributes.getString(R.styleable.StatsSliderView_statsTitle)
val statColor = attributes.getColor(R.styleable.StatsSliderView_statsColor, 0)
binding.statTypeTitle.setTextColor(attributes.getColor(R.styleable.StatsSliderView_statsTextColor, 0))
binding.statsSeekBar.progressTintList = ColorStateList.valueOf(statColor)
val thumbDrawable = ContextCompat.getDrawable(context, R.drawable.seekbar_thumb)
thumbDrawable?.setTintWith(statColor, PorterDuff.Mode.MULTIPLY)
binding.statsSeekBar.thumb = thumbDrawable
}
binding.valueEditText.addTextChangedListener(
AfterChangeTextWatcher { s ->
val newValue = try {
s.toString().toInt()
} catch (e: NumberFormatException) {
0
}
if (newValue != currentValue && newValue <= maxValue && newValue > 0) {
currentValue = newValue
allocateAction?.invoke(currentValue)
} else if (newValue > maxValue || newValue < 0) {
binding.valueEditText.setText(currentValue.toString())
binding.valueEditText.setSelection(binding.valueEditText.length())
}
}
)
binding.statsSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
currentValue = progress
if (fromUser) {
allocateAction?.invoke(currentValue)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) { /* no-on */ }
override fun onStopTrackingTouch(seekBar: SeekBar?) { /* no-on */ }
})
currentValue = 0
}
}
| gpl-3.0 | eaf6601c54ad20708238eb12678c883e | 38.630435 | 114 | 0.650576 | 5.113604 | false | false | false | false |
PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ActionListAdapter.kt | 3 | 2552 | package info.nightscout.androidaps.plugins.general.automation.dialogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.automation.actions.Action
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui
class ActionListAdapter(private val fragmentManager: FragmentManager, private val actionList: MutableList<Action>) : RecyclerView.Adapter<ActionListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.automation_action_item, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val action = actionList[position]
holder.bind(action, fragmentManager, this, position, actionList)
}
override fun getItemCount(): Int {
return actionList.size
}
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(action: Action, fragmentManager: FragmentManager, recyclerView: RecyclerView.Adapter<ViewHolder>, position: Int, actionList: MutableList<Action>) {
view.findViewById<LinearLayout>(R.id.automation_layoutText).setOnClickListener {
if (action.hasDialog()) {
val args = Bundle()
args.putInt("actionPosition", position)
args.putString("action", action.toJSON())
val dialog = EditActionDialog()
dialog.arguments = args
dialog.show(fragmentManager, "EditActionDialog")
}
}
view.findViewById<ImageView>(R.id.automation_iconTrash).setOnClickListener {
actionList.remove(action)
recyclerView.notifyDataSetChanged()
RxBus.send(EventAutomationUpdateGui())
}
if (action.icon().isPresent) view.findViewById<ImageView>(R.id.automation_action_image).setImageResource(action.icon().get())
view.findViewById<TextView>(R.id.automation_viewActionTitle).text = action.shortDescription()
}
}
}
| agpl-3.0 | 7c29be8d9db73bb97745ca7f20a1f65b | 45.4 | 171 | 0.705721 | 5.003922 | false | false | false | false |
InsertKoinIO/koin | core/koin-core/src/jsMain/kotlin/org/koin/mp/PlatformTools.kt | 1 | 1539 | package org.koin.mp
import org.koin.core.context.GlobalContext
import org.koin.core.context.KoinContext
import org.koin.core.logger.*
import kotlin.random.Random
import kotlin.reflect.KClass
//actual object PlatformTools {
// actual fun getClassName(kClass: KClass<*>): String {
// return kClass.simpleName ?: "KClass@${hashCode()}"
// }
//
// actual fun printStackTrace(throwable: Throwable) {
// throwable.printStackTrace()
// }
//
// actual fun stackTrace(): List<String> = Exception().toString().split("\n")
//
// actual fun printLog(level: Level, msg: MESSAGE) {
// println("[$level] $KOIN_TAG $msg")
// }
//}
//internal actual fun Any.ensureNeverFrozen() {}
//internal actual fun <R> mpsynchronized(lock: Any, block: () -> R): R = block()
actual object KoinPlatformTools {
actual fun getStackTrace(e: Exception): String = e.toString() + Exception().toString().split("\n")
actual fun getClassName(kClass: KClass<*>): String = kClass.simpleName ?: "KClass@${kClass.hashCode()}"
// TODO Better Id generation?
actual fun generateId(): String = Random.nextDouble().hashCode().toString()
actual fun defaultLazyMode(): LazyThreadSafetyMode = LazyThreadSafetyMode.NONE
actual fun defaultLogger(level: Level): Logger = PrintLogger(level)
actual fun defaultContext(): KoinContext = GlobalContext
actual fun <R> synchronized(lock: Lockable, block: () -> R) = block()
actual fun <K, V> safeHashMap(): MutableMap<K, V> = HashMap()
}
actual typealias Lockable = Any | apache-2.0 | 1eed2a9fdcbe23167465b2ed1f9d537f | 38.487179 | 107 | 0.688109 | 4.028796 | false | false | false | false |
apollostack/apollo-android | apollo-graphql-ast/src/main/kotlin/com/apollographql/apollo3/graphql/ast/GraphQLParser.kt | 1 | 8711 | package com.apollographql.apollo3.graphql.ast
import com.apollographql.apollo3.compiler.parser.antlr.GraphQLLexer
import com.apollographql.apollo3.compiler.parser.antlr.GraphQLParser as AntlrGraphQLParser
import okio.BufferedSource
import okio.buffer
import okio.source
import org.antlr.v4.runtime.BaseErrorListener
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
import org.antlr.v4.runtime.ParserRuleContext
import org.antlr.v4.runtime.RecognitionException
import org.antlr.v4.runtime.Recognizer
import org.antlr.v4.runtime.Token
import org.antlr.v4.runtime.atn.PredictionMode
import java.io.File
/**
* Entry point for parsing and validating GraphQL objects
*/
object GraphQLParser {
/**
* Parses and validates the given SDL schema document
*
* This voluntarily returns a [Schema] and not a [GQLDocument] in order to explicitly distinguish between operations and schemas
* throws if the schema has errors or is not a schema file
*/
fun parseSchema(source: BufferedSource, filePath: String? = null): Schema {
return parseSchemaInternal(source, filePath)
.mapValue {
it.toSchema()
}.orThrow()
}
/**
* Parses and validates the given SDL schema document
*
* This voluntarily returns a [Schema] and not a [GQLDocument] in order to explicitly distinguish between operations and schemas
* throws if the schema has errors or is not a schema file
*/
fun parseSchema(string: String) = parseSchema(string.byteInputStream().source().buffer())
/**
* Parses and validates the given SDL schema document
*
* This voluntarily does not return a GQLDocument in order to explicitly distinguish between operations and schemas
* throws if the schema has errors or is not a schema file
*/
fun parseSchema(file: File) = parseSchema(file.source().buffer(), file.absolutePath)
/**
* Parses and validates the given SDL executable document, containing operations and/or fragments
*/
fun parseOperations(source: BufferedSource, filePath: String? = null, schema: Schema): ParseResult<GQLDocument> {
return parseDocument(source, filePath).appendIssues {
it.validateAsOperations(schema)
}
}
/**
* Parse the given SDL document
*/
fun parseOperations(string: String, schema: Schema) = parseOperations(string.byteInputStream().source().buffer(), null, schema)
/**
* Parse the given SDL document
*/
fun parseOperations(file: File, schema: Schema) = file.source().buffer().use {
parseOperations(it, file.absolutePath, schema)
}
/**
* A specialized version that works on multiple files and can also inject fragments from another
* compilation unit
*/
fun parseExecutableFiles(files: Set<File>, schema: Schema, injectedFragmentDefinitions: List<GQLFragmentDefinition>): Pair<List<GQLDocument>, List<Issue>> {
val (documents, parsingIssues) = files.map { parseDocument(it) }
.fold(Pair<List<GQLDocument>, List<Issue>>(emptyList(), emptyList())) { acc, item ->
Pair(
acc.first + (item.value?.let { listOf(it) } ?: emptyList()),
acc.second + item.issues
)
}
val allDefinitions = documents.flatMap { it.definitions } + injectedFragmentDefinitions
val duplicateIssues = allDefinitions.checkDuplicates()
/**
* Collect all fragments as operations might use fragments from different files
*/
val allFragments = allDefinitions.filterIsInstance<GQLFragmentDefinition>().associateBy {
it.name
}
val validationIssues = documents.flatMap { document ->
document.definitions.flatMap { definition ->
when (definition) {
is GQLFragmentDefinition -> {
// This will catch unused fragments that are invalid. It might not be strictly needed
definition.validate(schema, allFragments)
}
is GQLOperationDefinition -> {
definition.validate(schema, allFragments)
}
else -> {
listOf(
Issue.ValidationError(
message = "Non-executable definition found",
sourceLocation = definition.sourceLocation,
)
)
}
}
}
}
return documents to (parsingIssues + duplicateIssues + validationIssues)
}
/**
* Parses a GraphQL document without doing any kind of validation besides the grammar parsing.
*
* Use [parseOperations] to parse operations and [parseSchema] to have proper validation
*
* @return a [ParseResult] with either a non-null [GQLDocument] or a list of issues
*/
fun parseDocument(source: BufferedSource, filePath: String?): ParseResult<GQLDocument> = source.use { _ ->
val parseResult = antlrParse(source, filePath) {
it.document()
}
if (parseResult.issues.isNotEmpty()) {
// If there are issues, return now. We cannot parse a document with errors.
ParseResult(null, parseResult.issues)
} else {
ParseResult(parseResult.value!!.toGQLDocument(filePath), parseResult.issues)
}
}
fun parseDocument(file: File) = parseDocument(file.source().buffer(), file.absolutePath)
fun parseDocument(string: String) = parseDocument(string.byteInputStream().source().buffer(), null)
fun parseValue(string: String): ParseResult<GQLValue> {
return antlrParse(string.byteInputStream().source().buffer(), null) {
it.value()
}.mapValue {
it.toGQLValue()
}
}
fun builtinTypes(): GQLDocument {
val source = GQLDocument::class.java.getResourceAsStream("/builtins.graphqls")
.source()
.buffer()
return antlrParse(source, null) { it.document() }
.orThrow()
.toGQLDocument(null)
}
internal fun parseSchemaInternal(source: BufferedSource, filePath: String? = null): ParseResult<GQLDocument> {
return parseDocument(source, filePath)
.flatMap {
it.mergeTypeExtensions()
}
.appendIssues {
// Validation as to be done before adding the built in types else validation fail on names starting with '__'
// This means that it's impossible to add type extensions on built in types at the moment
it.validateAsSchema()
}.mapValue {
it.withBuiltinDefinitions()
}
}
internal fun parseSchemaInternal(string: String) = parseSchemaInternal(string.byteInputStream().source().buffer())
fun parseSchemaInternal(file: File) = parseSchemaInternal(file.source().buffer(), file.absolutePath)
/**
* Plain parsing, without validation or adding the builtin types
*/
private fun <T : ParserRuleContext> antlrParse(
source: BufferedSource,
filePath: String? = null,
startRule: (AntlrGraphQLParser) -> T
): ParseResult<T> {
val parser = AntlrGraphQLParser(
CommonTokenStream(
GraphQLLexer(
CharStreams.fromStream(source.inputStream())
)
)
)
val issues = mutableListOf<Issue>()
return parser.apply {
removeErrorListeners()
interpreter.predictionMode = PredictionMode.SLL
addErrorListener(
object : BaseErrorListener() {
override fun syntaxError(
recognizer: Recognizer<*, *>?,
offendingSymbol: Any?,
line: Int,
position: Int,
msg: String?,
e: RecognitionException?
) {
issues.add(Issue.ParsingError(
message = "Unsupported token `${(offendingSymbol as? Token)?.text ?: offendingSymbol.toString()}`",
sourceLocation = SourceLocation(line, position, filePath)
))
}
}
)
}.let { startRule(it) }
.also {
parser.checkEOF(it, filePath)
}
.let {
ParseResult(it, issues)
}
}
private fun AntlrGraphQLParser.checkEOF(parserRuleContext: ParserRuleContext, filePath: String?) {
val documentStopToken = parserRuleContext.getStop()
val allTokens = (tokenStream as CommonTokenStream).tokens
if (documentStopToken != null && !allTokens.isNullOrEmpty()) {
val lastToken = allTokens[allTokens.size - 1]
val eof = lastToken.type == Token.EOF
val sameChannel = lastToken.channel == documentStopToken.channel
if (!eof && lastToken.tokenIndex > documentStopToken.tokenIndex && sameChannel) {
throw AntlrParseException(
error = "Unsupported token `${lastToken.text}`",
sourceLocation = SourceLocation(lastToken.line, lastToken.charPositionInLine, filePath)
)
}
}
}
}
| mit | e08def3065327a79567b8535acfc8f55 | 35.295833 | 158 | 0.664218 | 4.582325 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/category/components/CategoryContent.kt | 1 | 1622 | package eu.kanade.presentation.category.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.kanade.domain.category.model.Category
import eu.kanade.presentation.category.CategoryState
import eu.kanade.presentation.components.LazyColumn
import eu.kanade.tachiyomi.ui.category.CategoryPresenter.Dialog
@Composable
fun CategoryContent(
state: CategoryState,
lazyListState: LazyListState,
paddingValues: PaddingValues,
onMoveUp: (Category) -> Unit,
onMoveDown: (Category) -> Unit,
) {
val categories = state.categories
LazyColumn(
state = lazyListState,
contentPadding = paddingValues,
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
itemsIndexed(
items = categories,
key = { _, category -> "category-${category.id}" },
) { index, category ->
CategoryListItem(
modifier = Modifier.animateItemPlacement(),
category = category,
canMoveUp = index != 0,
canMoveDown = index != categories.lastIndex,
onMoveUp = onMoveUp,
onMoveDown = onMoveDown,
onRename = { state.dialog = Dialog.Rename(category) },
onDelete = { state.dialog = Dialog.Delete(category) },
)
}
}
}
| apache-2.0 | 8ff329c38feebce3390929eaf02bd1e4 | 35.044444 | 70 | 0.672626 | 4.827381 | false | false | false | false |
A-Zaiats/Kotlinextensions | buildSrc/src/main/java/io/github/azaiats/kotlinextensions/Versions.kt | 1 | 416 | @file:JvmName("Versions")
package io.github.azaiats.kotlinextensions
const val MIN_SDK = 14
const val TARGET_SDK = 26
const val BUILD_TOOLS = "26.0.2"
const val KOTLIN_VERSION = "1.1.51"
const val DOKKA_VERSION = "0.9.15"
const val GRADLE_PLUGIN_VERSION = "3.0.0-beta7"
const val BINTRAY_PLUGIN_VERSION = "0.5.0"
const val ANDROID_SUPPORT_VERSION = "26.1.0"
const val ANDROID_SUPPORT_ARCH_VERSION = "1.0.0-beta2" | apache-2.0 | 85fb8ca051222266f3e7a5cb65f11eff | 26.8 | 54 | 0.728365 | 2.666667 | false | false | false | false |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/storage/notifications/K9NotificationStore.kt | 2 | 3118 | package com.fsck.k9.storage.notifications
import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.controller.MessageReference
import com.fsck.k9.mailstore.LockableDatabase
import com.fsck.k9.notification.NotificationStore
import com.fsck.k9.notification.NotificationStoreOperation
class K9NotificationStore(private val lockableDatabase: LockableDatabase) : NotificationStore {
override fun persistNotificationChanges(operations: List<NotificationStoreOperation>) {
lockableDatabase.execute(true) { db ->
for (operation in operations) {
when (operation) {
is NotificationStoreOperation.Add -> {
addNotification(db, operation.messageReference, operation.notificationId, operation.timestamp)
}
is NotificationStoreOperation.ChangeToActive -> {
setNotificationId(db, operation.messageReference, operation.notificationId)
}
is NotificationStoreOperation.ChangeToInactive -> {
clearNotificationId(db, operation.messageReference)
}
is NotificationStoreOperation.Remove -> {
removeNotification(db, operation.messageReference)
}
}
}
}
}
override fun clearNotifications() {
lockableDatabase.execute(false) { db ->
db.delete("notifications", null, null)
}
}
private fun addNotification(
database: SQLiteDatabase,
messageReference: MessageReference,
notificationId: Int,
timestamp: Long
) {
database.execSQL(
"INSERT INTO notifications(message_id, notification_id, timestamp) " +
"SELECT id, ?, ? FROM messages WHERE folder_id = ? AND uid = ?",
arrayOf(notificationId, timestamp, messageReference.folderId, messageReference.uid)
)
}
private fun setNotificationId(database: SQLiteDatabase, messageReference: MessageReference, notificationId: Int) {
database.execSQL(
"UPDATE notifications SET notification_id = ? WHERE message_id IN " +
"(SELECT id FROM messages WHERE folder_id = ? AND uid = ?)",
arrayOf(notificationId, messageReference.folderId, messageReference.uid)
)
}
private fun clearNotificationId(database: SQLiteDatabase, messageReference: MessageReference) {
database.execSQL(
"UPDATE notifications SET notification_id = NULL WHERE message_id IN " +
"(SELECT id FROM messages WHERE folder_id = ? AND uid = ?)",
arrayOf(messageReference.folderId, messageReference.uid)
)
}
private fun removeNotification(database: SQLiteDatabase, messageReference: MessageReference) {
database.execSQL(
"DELETE FROM notifications WHERE message_id IN (SELECT id FROM messages WHERE folder_id = ? AND uid = ?)",
arrayOf(messageReference.folderId, messageReference.uid)
)
}
}
| apache-2.0 | 766870a38ce2e9314671bb4f35a8166c | 42.305556 | 118 | 0.637588 | 5.366609 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/util/CP437Utils.kt | 1 | 7767 | package org.hexworks.zircon.internal.util
import org.hexworks.zircon.internal.tileset.impl.CP437TextureMetadata
object CP437Utils {
private val UNICODE_TO_CP437_LOOKUP = mapOf(
Pair(0x263A, 1),
Pair(0x263B, 2),
Pair(0x2665, 3),
Pair(0x2666, 4),
Pair(0x2663, 5),
Pair(0x2660, 6),
Pair(0x2022, 7),
Pair(0x25D8, 8),
Pair(0x25CB, 9),
Pair(0x25D9, 10),
Pair(0x2642, 11),
Pair(0x2640, 12),
Pair(0x266A, 13),
Pair(0x266B, 14),
Pair(0x263C, 15),
Pair(0x25BA, 16),
Pair(0x25C4, 17),
Pair(0x2195, 18),
Pair(0x203C, 19),
Pair(0xB6, 20),
Pair(0xA7, 21),
Pair(0x25AC, 22),
Pair(0x21A8, 23),
Pair(0x2191, 24),
Pair(0x2193, 25),
Pair(0x2192, 26),
Pair(0x2190, 27),
Pair(0x221F, 28),
Pair(0x2194, 29),
Pair(0x25B2, 30),
Pair(0x25BC, 31),
Pair(0x20, 32),
Pair(0x21, 33),
Pair(0x22, 34),
Pair(0x23, 35),
Pair(0x24, 36),
Pair(0x25, 37),
Pair(0x26, 38),
Pair(0x27, 39),
Pair(0x28, 40),
Pair(0x29, 41),
Pair(0x2A, 42),
Pair(0x2B, 43),
Pair(0x2C, 44),
Pair(0x2D, 45),
Pair(0x2E, 46),
Pair(0x2F, 47),
Pair(0x30, 48),
Pair(0x31, 49),
Pair(0x32, 50),
Pair(0x33, 51),
Pair(0x34, 52),
Pair(0x35, 53),
Pair(0x36, 54),
Pair(0x37, 55),
Pair(0x38, 56),
Pair(0x39, 57),
Pair(0x3A, 58),
Pair(0x3B, 59),
Pair(0x3C, 60),
Pair(0x3D, 61),
Pair(0x3E, 62),
Pair(0x3F, 63),
Pair(0x40, 64),
Pair(0x41, 65),
Pair(0x42, 66),
Pair(0x43, 67),
Pair(0x44, 68),
Pair(0x45, 69),
Pair(0x46, 70),
Pair(0x47, 71),
Pair(0x48, 72),
Pair(0x49, 73),
Pair(0x4A, 74),
Pair(0x4B, 75),
Pair(0x4C, 76),
Pair(0x4D, 77),
Pair(0x4E, 78),
Pair(0x4F, 79),
Pair(0x50, 80),
Pair(0x51, 81),
Pair(0x52, 82),
Pair(0x53, 83),
Pair(0x54, 84),
Pair(0x55, 85),
Pair(0x56, 86),
Pair(0x57, 87),
Pair(0x58, 88),
Pair(0x59, 89),
Pair(0x5A, 90),
Pair(0x5B, 91),
Pair(0x5C, 92),
Pair(0x5D, 93),
Pair(0x5E, 94),
Pair(0x5F, 95),
Pair(0x60, 96),
Pair(0x61, 97),
Pair(0x62, 98),
Pair(0x63, 99),
Pair(0x64, 100),
Pair(0x65, 101),
Pair(0x66, 102),
Pair(0x67, 103),
Pair(0x68, 104),
Pair(0x69, 105),
Pair(0x6A, 106),
Pair(0x6B, 107),
Pair(0x6C, 108),
Pair(0x6D, 109),
Pair(0x6E, 110),
Pair(0x6F, 111),
Pair(0x70, 112),
Pair(0x71, 113),
Pair(0x72, 114),
Pair(0x73, 115),
Pair(0x74, 116),
Pair(0x75, 117),
Pair(0x76, 118),
Pair(0x77, 119),
Pair(0x78, 120),
Pair(0x79, 121),
Pair(0x7A, 122),
Pair(0x7B, 123),
Pair(0x7C, 124),
Pair(0x7D, 125),
Pair(0x7E, 126),
Pair(0x2302, 127),
Pair(0xC7, 128),
Pair(0xFC, 129),
Pair(0xE9, 130),
Pair(0xE2, 131),
Pair(0xE4, 132),
Pair(0xE0, 133),
Pair(0xE5, 134),
Pair(0xE7, 135),
Pair(0xEA, 136),
Pair(0xEB, 137),
Pair(0xE8, 138),
Pair(0xEF, 139),
Pair(0xEE, 140),
Pair(0xEC, 141),
Pair(0xC4, 142),
Pair(0xC5, 143),
Pair(0xC9, 144),
Pair(0xE6, 145),
Pair(0xC6, 146),
Pair(0xF4, 147),
Pair(0xF6, 148),
Pair(0xF2, 149),
Pair(0xFB, 150),
Pair(0xF9, 151),
Pair(0xFF, 152),
Pair(0xD6, 153),
Pair(0xDC, 154),
Pair(0xA2, 155),
Pair(0xA3, 156),
Pair(0xA5, 157),
Pair(0x20A7, 158),
Pair(0x192, 159),
Pair(0xE1, 160),
Pair(0xED, 161),
Pair(0xF3, 162),
Pair(0xFA, 163),
Pair(0xF1, 164),
Pair(0xD1, 165),
Pair(0xAA, 166),
Pair(0xBA, 167),
Pair(0xBF, 168),
Pair(0x2310, 169),
Pair(0xAC, 170),
Pair(0xBD, 171),
Pair(0xBC, 172),
Pair(0xA1, 173),
Pair(0xAB, 174),
Pair(0xBB, 175),
Pair(0x2591, 176),
Pair(0x2592, 177),
Pair(0x2593, 178),
Pair(0x2502, 179),
Pair(0x2524, 180),
Pair(0x2561, 181),
Pair(0x2562, 182),
Pair(0x2556, 183),
Pair(0x2555, 184),
Pair(0x2563, 185),
Pair(0x2551, 186),
Pair(0x2557, 187),
Pair(0x255D, 188),
Pair(0x255C, 189),
Pair(0x255B, 190),
Pair(0x2510, 191),
Pair(0x2514, 192),
Pair(0x2534, 193),
Pair(0x252C, 194),
Pair(0x251C, 195),
Pair(0x2500, 196),
Pair(0x253C, 197),
Pair(0x255E, 198),
Pair(0x255F, 199),
Pair(0x255A, 200),
Pair(0x2554, 201),
Pair(0x2569, 202),
Pair(0x2566, 203),
Pair(0x2560, 204),
Pair(0x2550, 205),
Pair(0x256C, 206),
Pair(0x2567, 207),
Pair(0x2568, 208),
Pair(0x2564, 209),
Pair(0x2565, 210),
Pair(0x2559, 211),
Pair(0x2558, 212),
Pair(0x2552, 213),
Pair(0x2553, 214),
Pair(0x256B, 215),
Pair(0x256A, 216),
Pair(0x2518, 217),
Pair(0x250C, 218),
Pair(0x2588, 219),
Pair(0x2584, 220),
Pair(0x258C, 221),
Pair(0x2590, 222),
Pair(0x2580, 223),
Pair(0x3B1, 224),
Pair(0xDF, 225),
Pair(0x393, 226),
Pair(0x3C0, 227),
Pair(0x3A3, 228),
Pair(0x3C3, 229),
Pair(0xB5, 230),
Pair(0x3C4, 231),
Pair(0x3A6, 232),
Pair(0x398, 233),
Pair(0x3A9, 234),
Pair(0x3B4, 235),
Pair(0x221E, 236),
Pair(0x3C6, 237),
Pair(0x3B5, 238),
Pair(0x2229, 239),
Pair(0x2261, 240),
Pair(0xB1, 241),
Pair(0x2265, 242),
Pair(0x2264, 243),
Pair(0x2320, 244),
Pair(0x2321, 245),
Pair(0xF7, 246),
Pair(0x2248, 247),
Pair(0xB0, 248),
Pair(0x2219, 249),
Pair(0xB7, 250),
Pair(0x221A, 251),
Pair(0x207F, 252),
Pair(0xB2, 253),
Pair(0x25A0, 254),
Pair(0xA0, 255)
)
private val CP437_TO_UNICODE_LOOKUP = UNICODE_TO_CP437_LOOKUP.map { Pair(it.value, it.key) }.toMap()
val CP437_METADATA = UNICODE_TO_CP437_LOOKUP.map { (char, index) ->
val x = index.rem(16)
val y = index.div(16)
Pair(
char.toChar(), listOf(
CP437TextureMetadata(
character = char.toChar(),
x = x,
y = y,
width = 1,
height = 1
)
)
)
}.toMap()
/**
* Converts a cp437 index to its `char` representation.
*/
fun convertCp437toUnicode(cpIdx: Int): Char = CP437_TO_UNICODE_LOOKUP[cpIdx]?.toChar() ?: ' '
/**
* Fetches the cp437 index of a [Char].
*/
fun fetchCP437IndexForChar(char: Char): Int {
return UNICODE_TO_CP437_LOOKUP[char.code]
?: throw IllegalArgumentException(
"No CP437 character found for char: '$char'. " +
"Did you try to use a character which has no Code Page 437 representation?"
)
}
}
| apache-2.0 | 19c976678a4637b549654a4d9cdf0179 | 25.151515 | 104 | 0.463499 | 2.818215 | false | false | false | false |
nearbydelta/KoreanAnalyzer | kkma/src/test/kotlin/kr/bydelta/koala/test/tests.kt | 1 | 4486 | package kr.bydelta.koala.test
import kr.bydelta.koala.*
import kr.bydelta.koala.data.DepEdge
import kr.bydelta.koala.kkma.*
import org.snu.ids.kkma.ma.MorphemeAnalyzer
import org.snu.ids.kkma.sp.ParseTreeEdge
import org.snu.ids.kkma.sp.ParseTreeNode
import org.spekframework.spek2.Spek
object KKMATagConversionTest : Spek(TagConversionSpek(
to = { it.fromSejongPOS() },
from = { it.toSejongPOS() },
getMapping = {
when (it) {
POS.VX -> listOf(Conversion("VXV"),
Conversion("VXA", toTagger = false))
POS.MM -> listOf(Conversion("MDT")
, Conversion("MDN", toTagger = false))
POS.MAJ -> listOf(Conversion("MAC"))
POS.JKB -> listOf(Conversion("JKM"))
POS.JKV -> listOf(Conversion("JKI"))
POS.EP ->
listOf(Conversion("EPT"),
Conversion("EPH", toTagger = false),
Conversion("EPP", toTagger = false))
POS.EF ->
listOf(Conversion("EFN"),
Conversion("EFQ", toTagger = false),
Conversion("EFO", toTagger = false),
Conversion("EFA", toTagger = false),
Conversion("EFI", toTagger = false),
Conversion("EFR", toTagger = false))
POS.EC ->
listOf(Conversion("ECE"),
Conversion("ECD", toTagger = false),
Conversion("ECS", toTagger = false))
POS.ETM -> listOf(Conversion("ETD"))
POS.SL -> listOf(Conversion("OL"))
POS.SH -> listOf(Conversion("OH"))
POS.SN -> listOf(Conversion("ON"))
POS.NF -> listOf(Conversion("UN"))
POS.NV -> listOf(Conversion("UV"))
POS.NA -> listOf(Conversion("UE"))
else -> listOf(Conversion(it.toString()))
}
}
))
object KKMADictTest : Spek(DictSpek(Dictionary, getTagger = { Tagger() }))
object KKMATaggerTest : Spek(TaggerSpek(
getTagger = { Tagger() },
tagSentByOrig = {
val kkma = MorphemeAnalyzer()
val original = kkma.divideToSentences(kkma.leaveJustBest(
kkma.postProcess(kkma.analyze(it)))).flatten()
val tag = original.joinToString(" ") { s ->
s.joinToString("+") { m -> "${m.string}/${m.tag}" }
}
val surface = original.joinToString(" ") { s -> s.exp }
surface to tag
},
tagParaByOrig = {
val kkma = MorphemeAnalyzer()
val original = kkma.divideToSentences(kkma.leaveJustBest(
kkma.postProcess(kkma.analyze(it))))
original.map { s ->
s.joinToString(" ") { e ->
e.joinToString("+") { m -> m.string }
}
}
},
isSentenceSplitterImplemented = false
))
fun DepEdge.getOriginalString() = "${this.originalLabel}(${this.governor?.id ?: -1}, ${this.dependent.id})"
fun ParseTreeEdge.getOriginalString(nodes: List<ParseTreeNode>) =
"${this.relation}(${nodes.getOrNull(this.fromId)?.eojeol?.firstMorp?.index
?: -1}, ${nodes[this.toId].eojeol?.firstMorp?.index})"
object KKMAParserTest : Spek(ParserSpek(
getParser = { Parser() },
parseSentByOrig = {
val kkma = MorphemeAnalyzer()
val kkpa = org.snu.ids.kkma.sp.Parser()
val trees = kkma.divideToSentences(
kkma.leaveJustBest(kkma.postProcess(kkma.analyze(it)))
).map { x ->
x.forEachIndexed { index, eojeol ->
eojeol.firstMorp.index = index
}
kkpa.parse(x)
}
trees.map {
it.sentenec to it.edgeList.map { edge -> edge.getOriginalString(it.nodeList) }.sorted().joinToString()
}
},
parseSentByKoala = { sent, parser ->
val result = parser.analyze(sent)
result.map { s ->
val deps = s.getDependencies()
val depStr = deps?.asSequence()?.map { it.getOriginalString() }?.sorted()?.joinToString() ?: ""
s.surfaceString() to depStr
}
}
)) | gpl-3.0 | 7bd5c003e7c3928f581b524757e6eb4b | 36.705882 | 118 | 0.502452 | 4.276454 | false | false | false | false |
yole/faguirra | src/ru/yole/faguirra/FaguirraTab.kt | 1 | 4068 | package ru.yole.faguirra
import java.awt.BorderLayout
import com.intellij.openapi.ui.Splitter
import javax.swing.JPanel
import javax.swing.JComponent
import com.intellij.openapi.project.Project
import com.intellij.openapi.Disposable
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.plugins.terminal.LocalTerminalDirectRunner
import com.pty4j.PtyProcess
import com.jediterm.terminal.TtyConnector
import org.jetbrains.plugins.terminal.JBTabbedTerminalWidget
import com.intellij.openapi.wm.IdeFocusManager
import com.jediterm.terminal.ui.TerminalActionProvider
import com.jediterm.terminal.ui.TerminalAction
import javax.swing.KeyStroke
import java.awt.event.KeyEvent
import com.intellij.openapi.vfs.LocalFileSystem
class FaguirraTerminalRunner(project: Project): LocalTerminalDirectRunner(project) {
var ttyConnector: TtyConnector? = null
override fun createTtyConnector(process: PtyProcess?): TtyConnector? {
ttyConnector = super<LocalTerminalDirectRunner>.createTtyConnector(process)
return ttyConnector
}
}
public class FaguirraTab(val project: Project): JPanel(BorderLayout()), Disposable {
val leftPanel = FaguirraPanel(project, this)
val rightPanel = FaguirraPanel(project, this)
val splitter = Splitter(true, 0.8)
val panelSplitter = Splitter(false)
var lastActivePanel: FaguirraPanel = leftPanel
var terminalWidget: JBTabbedTerminalWidget? = null
val terminalRunner = FaguirraTerminalRunner(project);
{
val handler: (FaguirraPanel, VirtualFile) -> Unit = {(panel, dir) -> currentDirChanged(panel, dir) }
leftPanel.directoryChangeListeners.add(handler)
rightPanel.directoryChangeListeners.add(handler)
panelSplitter.setFirstComponent(leftPanel)
panelSplitter.setSecondComponent(rightPanel)
splitter.setFirstComponent(panelSplitter)
terminalWidget = terminalRunner.createTerminalWidget()!!
splitter.setSecondComponent(terminalWidget)
add(splitter, BorderLayout.CENTER)
val focusPanelsAction = TerminalAction("Focus panels",
array(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)!!), {
val focusTarget = lastActivePanel.getPreferredFocusComponent()
IdeFocusManager.getInstance(project)!!.requestFocus(focusTarget, false)
true
})
terminalWidget!!.setNextProvider(object: TerminalActionProvider {
private var myNextProvider: TerminalActionProvider? = null
override fun getActions() = arrayListOf(focusPanelsAction)
override fun getNextProvider() = myNextProvider
override fun setNextProvider(p0: TerminalActionProvider?) { myNextProvider = p0 }
})
}
public fun getPreferredFocusComponent(): JComponent = lastActivePanel
public override fun dispose() {
}
private fun currentDirChanged(panel: FaguirraPanel, dir: VirtualFile) {
lastActivePanel = panel
val input = terminalRunner.ttyConnector
if (dir.getFileSystem() is LocalFileSystem) {
val path = dir.getPath()
if (input != null && path != null) {
input.write("cd " + path.replace(" ", "\\ ").replace("(", "\\(").replace(")", "\\)") + "\n")
}
}
}
public fun getState(): FaguirraEditorState {
return FaguirraEditorState(leftPanel.getState(), rightPanel.getState(), false)
}
public fun setState(state: FaguirraEditorState) {
leftPanel.setState(state.leftPanelState)
rightPanel.setState(state.rightPanelState)
lastActivePanel = if (state.rightPanelActive) rightPanel else leftPanel
}
public val rightPanelActive: Boolean
get() = lastActivePanel == rightPanel
public fun getOppositePanel(panel: FaguirraPanel): FaguirraPanel =
when(panel) {
leftPanel -> rightPanel
rightPanel -> leftPanel
else -> throw IllegalArgumentException("panel from wrong tab")
}
} | apache-2.0 | b42987fd3db46973e63939ef9c5efe9a | 39.287129 | 108 | 0.704277 | 4.530067 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/sitecreation/domains/SiteCreationDomainsFragment.kt | 1 | 6756 | package org.wordpress.android.ui.sitecreation.domains
import android.content.Context
import android.os.Bundle
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import dagger.hilt.android.AndroidEntryPoint
import org.wordpress.android.R
import org.wordpress.android.databinding.SiteCreationDomainsScreenBinding
import org.wordpress.android.databinding.SiteCreationFormScreenBinding
import org.wordpress.android.ui.accounts.HelpActivity
import org.wordpress.android.ui.sitecreation.SiteCreationBaseFormFragment
import org.wordpress.android.ui.sitecreation.domains.SiteCreationDomainsViewModel.DomainsUiState.DomainsUiContentState
import org.wordpress.android.ui.sitecreation.misc.OnHelpClickedListener
import org.wordpress.android.ui.sitecreation.misc.SearchInputWithHeader
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.DisplayUtilsWrapper
import javax.inject.Inject
@AndroidEntryPoint
class SiteCreationDomainsFragment : SiteCreationBaseFormFragment() {
private var searchInputWithHeader: SearchInputWithHeader? = null
private val viewModel: SiteCreationDomainsViewModel by activityViewModels()
@Inject internal lateinit var uiHelpers: UiHelpers
@Inject internal lateinit var displayUtils: DisplayUtilsWrapper
private var binding: SiteCreationDomainsScreenBinding? = null
@Suppress("UseCheckOrError")
override fun onAttach(context: Context) {
super.onAttach(context)
if (context !is DomainsScreenListener) {
throw IllegalStateException("Parent activity must implement DomainsScreenListener.")
}
if (context !is OnHelpClickedListener) {
throw IllegalStateException("Parent activity must implement OnHelpClickedListener.")
}
}
override fun getContentLayout(): Int {
return R.layout.site_creation_domains_screen
}
@Suppress("UseCheckOrError") override val screenTitle: String
get() = arguments?.getString(EXTRA_SCREEN_TITLE)
?: throw IllegalStateException("Required argument screen title is missing.")
override fun setBindingViewStubListener(parentBinding: SiteCreationFormScreenBinding) {
parentBinding.siteCreationFormContentStub.setOnInflateListener { _, inflated ->
binding = SiteCreationDomainsScreenBinding.bind(inflated)
}
}
override fun setupContent() {
binding?.let {
searchInputWithHeader = SearchInputWithHeader(
uiHelpers = uiHelpers,
rootView = it.root as ViewGroup,
onClear = { viewModel.onClearTextBtnClicked() }
)
it.createSiteButton.setOnClickListener { viewModel.createSiteBtnClicked() }
it.initRecyclerView()
it.initViewModel()
}
}
private fun SiteCreationDomainsScreenBinding.initRecyclerView() {
recyclerView.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
initAdapter()
}
private fun SiteCreationDomainsScreenBinding.initAdapter() {
val adapter = SiteCreationDomainsAdapter(uiHelpers)
recyclerView.adapter = adapter
}
private fun SiteCreationDomainsScreenBinding.initViewModel() {
viewModel.uiState.observe(this@SiteCreationDomainsFragment, { uiState ->
uiState?.let {
searchInputWithHeader?.updateHeader(requireActivity(), uiState.headerUiState)
searchInputWithHeader?.updateSearchInput(requireActivity(), uiState.searchInputUiState)
updateContentUiState(uiState.contentState)
uiHelpers.updateVisibility(createSiteButtonContainer, uiState.createSiteButtonContainerVisibility)
uiHelpers.updateVisibility(createSiteButtonShadow, uiState.createSiteButtonContainerVisibility)
updateTitleVisibility(uiState.headerUiState == null)
}
})
viewModel.clearBtnClicked.observe(this@SiteCreationDomainsFragment, {
searchInputWithHeader?.setInputText("")
})
viewModel.createSiteBtnClicked.observe(this@SiteCreationDomainsFragment, { domain ->
domain?.let { (requireActivity() as DomainsScreenListener).onDomainSelected(domain) }
})
viewModel.onHelpClicked.observe(this@SiteCreationDomainsFragment, {
(requireActivity() as OnHelpClickedListener).onHelpClicked(HelpActivity.Origin.SITE_CREATION_DOMAINS)
})
viewModel.start()
}
private fun SiteCreationDomainsScreenBinding.updateContentUiState(contentState: DomainsUiContentState) {
uiHelpers.updateVisibility(domainListEmptyView, contentState.emptyViewVisibility)
if (contentState is DomainsUiContentState.Empty && contentState.message != null) {
domainListEmptyViewMessage.text = uiHelpers.getTextOfUiString(requireContext(), contentState.message)
}
uiHelpers.updateVisibility(siteCreationDomainsScreenExample.root, contentState.exampleViewVisibility)
(recyclerView.adapter as SiteCreationDomainsAdapter).update(contentState.items)
if (contentState.items.isNotEmpty()) {
view?.announceForAccessibility(getString(R.string.suggestions_updated_content_description))
}
}
private fun updateTitleVisibility(visible: Boolean) {
val actionBar = (requireActivity() as? AppCompatActivity)?.supportActionBar
actionBar?.setDisplayShowTitleEnabled(displayUtils.isLandscapeBySize() || visible)
}
override fun onHelp() {
viewModel.onHelpClicked()
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
// we need to set the `onTextChanged` after the viewState has been restored otherwise the viewModel.updateQuery
// is called when the system sets the restored value to the EditText which results in an unnecessary request
searchInputWithHeader?.onTextChanged = { viewModel.updateQuery(it) }
}
override fun onDestroyView() {
super.onDestroyView()
searchInputWithHeader = null
binding = null
}
companion object {
const val TAG = "site_creation_domains_fragment_tag"
fun newInstance(screenTitle: String): SiteCreationDomainsFragment {
val fragment = SiteCreationDomainsFragment()
val bundle = Bundle()
bundle.putString(EXTRA_SCREEN_TITLE, screenTitle)
fragment.arguments = bundle
return fragment
}
}
}
| gpl-2.0 | bb61a663d54699f6144924a7391f481c | 44.04 | 119 | 0.732386 | 5.38756 | false | false | false | false |
75py/Aplin | app/src/main/java/com/nagopy/android/aplin/ui/main/compose/MainAppBar.kt | 1 | 8223 | package com.nagopy.android.aplin.ui.main.compose
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Share
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.nagopy.android.aplin.R
import com.nagopy.android.aplin.domain.model.PackageModel
import com.nagopy.android.aplin.ui.main.MainUiState
import com.nagopy.android.aplin.ui.main.Screen
import com.nagopy.android.aplin.ui.main.SearchWidgetState
import com.nagopy.android.aplin.ui.theme.AplinTheme
@Composable
fun MainAppBar(
navController: NavController,
state: MainUiState,
currentScreen: Screen,
sharePackages: (List<PackageModel>) -> Unit,
onTextChanged: (String) -> Unit,
onCloseClicked: () -> Unit,
onSearchTriggered: () -> Unit,
) {
when (state.searchWidgetState) {
SearchWidgetState.CLOSED -> {
DefaultAppBar(
navController = navController,
state = state,
currentScreen = currentScreen,
sharePackages = sharePackages,
onSearchTriggered = onSearchTriggered,
)
}
SearchWidgetState.OPENED -> {
SearchAppBar(
navController = navController,
currentScreen = currentScreen,
text = state.searchText,
onTextChanged = onTextChanged,
onCloseClicked = onCloseClicked,
)
}
}
}
@Composable
fun DefaultAppBar(
navController: NavController,
state: MainUiState,
currentScreen: Screen,
sharePackages: (List<PackageModel>) -> Unit,
onSearchTriggered: () -> Unit,
) {
TopAppBar(
title = {
Text(text = stringResource(id = currentScreen.resourceId))
},
actions = {
if (state.isLoading && state.packagesModel != null) {
CircularProgressIndicator(color = Color.LightGray)
}
if (currentScreen is Screen.AppListScreen && state.packagesModel != null) {
IconButton(onClick = {
sharePackages.invoke(
currentScreen.getAppList(
state.packagesModel,
state.searchText,
)
)
}) {
Icon(
imageVector = Icons.Default.Share,
contentDescription = stringResource(id = R.string.share)
)
}
}
if (currentScreen !is Screen.Preferences) {
IconButton(onClick = {
onSearchTriggered()
}) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = stringResource(id = R.string.search)
)
}
IconButton(onClick = {
navController.navigate(Screen.Preferences.route)
}) {
Icon(
imageVector = Icons.Default.Settings,
contentDescription = stringResource(id = R.string.preferences),
)
}
}
},
navigationIcon = if (currentScreen != Screen.Top) {
{
IconButton(onClick = {
navController.popBackStack()
}) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "Back"
)
}
}
} else {
null
},
)
}
@Composable
fun SearchAppBar(
navController: NavController,
currentScreen: Screen,
text: String,
onTextChanged: (String) -> Unit,
onCloseClicked: () -> Unit,
) {
val focusRequester = remember { FocusRequester() }
TopAppBar {
TextField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
value = text,
onValueChange = onTextChanged,
placeholder = {
Text(
modifier = Modifier.alpha(ContentAlpha.medium),
text = stringResource(id = R.string.search_hint),
color = Color.White
)
},
textStyle = TextStyle(
fontSize = MaterialTheme.typography.subtitle1.fontSize,
),
singleLine = true,
maxLines = 1,
leadingIcon = if (currentScreen != Screen.Top) {
{
IconButton(onClick = {
navController.popBackStack()
}) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "Back"
)
}
}
} else {
null
},
trailingIcon = {
IconButton(
onClick = {
if (text.isNotEmpty()) {
onTextChanged("")
} else {
onCloseClicked()
}
}
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Close Icon",
)
}
},
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Search,
),
keyboardActions = KeyboardActions(
onSearch = {
// onSearchClicked(text)
},
),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
cursorColor = Color.White.copy(alpha = ContentAlpha.medium),
disabledTextColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
)
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
@Preview
@Composable
fun SearchAppBarPreview() {
AplinTheme {
Scaffold(
topBar = {
SearchAppBar(
navController = rememberNavController(),
currentScreen = Screen.Top,
text = "text",
onTextChanged = {},
onCloseClicked = {},
)
}
) {}
}
}
| apache-2.0 | fd46445943e88c68a075c201e2552c7b | 32.839506 | 87 | 0.544448 | 5.722338 | false | false | false | false |
mdaniel/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/javaUCallExpressions.kt | 7 | 9927 | /*
* Copyright 2000-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.uast.java
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTypesUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import org.jetbrains.uast.java.expressions.JavaUExpressionList
import org.jetbrains.uast.java.internal.PsiArrayToUElementListMappingView
import org.jetbrains.uast.psi.UElementWithLocation
@ApiStatus.Internal
class JavaUCallExpression(
override val sourcePsi: PsiMethodCallExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpression, UElementWithLocation, UMultiResolvable {
override val kind: UastCallKind
get() {
val element = nameReferenceElement
if (element is PsiKeyword && (element.text == PsiKeyword.THIS || element.text == PsiKeyword.SUPER))
return UastCallKind.CONSTRUCTOR_CALL
return UastCallKind.METHOD_CALL
}
override val methodIdentifier: UIdentifier? by lz {
nameReferenceElement?.let { UIdentifier(it, this) }
}
private val nameReferenceElement: PsiElement?
get() = sourcePsi.methodExpression.referenceNameElement
override val classReference: UReferenceExpression?
get() = null
override val valueArgumentCount: Int
get() = sourcePsi.argumentList.expressionCount
override val valueArguments: List<UExpression> by lz {
PsiArrayToUElementListMappingView(sourcePsi.argumentList.expressions) { JavaConverter.convertOrEmpty(it, this@JavaUCallExpression) }
}
override fun getArgumentForParameter(i: Int): UExpression? {
val resolved = multiResolve().mapNotNull { it.element as? PsiMethod }
for (psiMethod in resolved) {
val isVarArgs = psiMethod.parameterList.parameters.getOrNull(i)?.isVarArgs ?: continue
if (isVarArgs) {
return JavaUExpressionList(null, UastSpecialExpressionKind.VARARGS, this) {
valueArguments.subList(i, valueArguments.size)
}
}
return valueArguments.getOrNull(i)
}
return null
}
override val typeArgumentCount: Int by lz { sourcePsi.typeArguments.size }
override val typeArguments: List<PsiType>
get() = sourcePsi.typeArguments.toList()
override val returnType: PsiType?
get() = sourcePsi.type
override val methodName: String?
get() = sourcePsi.methodExpression.referenceName
override fun resolve(): PsiMethod? = sourcePsi.resolveMethod()
override fun multiResolve(): Iterable<ResolveResult> =
sourcePsi.methodExpression.multiResolve(false).asIterable()
override fun getStartOffset(): Int =
sourcePsi.methodExpression.referenceNameElement?.textOffset ?: sourcePsi.methodExpression.textOffset
override fun getEndOffset(): Int = sourcePsi.textRange.endOffset
override val receiver: UExpression?
get() {
uastParent.let { uastParent ->
return if (uastParent is UQualifiedReferenceExpression && uastParent.selector == this)
uastParent.receiver
else
null
}
}
override val receiverType: PsiType?
get() {
val qualifierType = sourcePsi.methodExpression.qualifierExpression?.type
if (qualifierType != null) {
return qualifierType
}
val method = resolve() ?: return null
if (method.hasModifierProperty(PsiModifier.STATIC)) return null
val psiManager = sourcePsi.manager
val containingClassForMethod = method.containingClass ?: return null
val containingClass = PsiTreeUtil.getParentOfType(sourcePsi, PsiClass::class.java)
val containingClassSequence = generateSequence(containingClass) {
if (it.hasModifierProperty(PsiModifier.STATIC))
null
else
PsiTreeUtil.getParentOfType(it, PsiClass::class.java)
}
val receiverClass = containingClassSequence.find { containingClassForExpression ->
psiManager.areElementsEquivalent(containingClassForMethod, containingClassForExpression) ||
containingClassForExpression.isInheritor(containingClassForMethod, true)
}
return receiverClass?.let { PsiTypesUtil.getClassType(it) }
}
}
@ApiStatus.Internal
class JavaConstructorUCallExpression(
override val sourcePsi: PsiNewExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpression, UMultiResolvable {
override val kind: UastCallKind by lz {
when {
sourcePsi.arrayInitializer != null -> UastCallKind.NEW_ARRAY_WITH_INITIALIZER
sourcePsi.arrayDimensions.isNotEmpty() -> UastCallKind.NEW_ARRAY_WITH_DIMENSIONS
else -> UastCallKind.CONSTRUCTOR_CALL
}
}
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression? by lz {
sourcePsi.classReference?.let { ref ->
JavaConverter.convertReference(ref, this, UElement::class.java) as? UReferenceExpression
}
}
override val valueArgumentCount: Int
get() {
val initializer = sourcePsi.arrayInitializer
return when {
initializer != null -> initializer.initializers.size
sourcePsi.arrayDimensions.isNotEmpty() -> sourcePsi.arrayDimensions.size
else -> sourcePsi.argumentList?.expressions?.size ?: 0
}
}
override val valueArguments: List<UExpression> by lz {
val initializer = sourcePsi.arrayInitializer
when {
initializer != null -> initializer.initializers.map { JavaConverter.convertOrEmpty(it, this) }
sourcePsi.arrayDimensions.isNotEmpty() -> sourcePsi.arrayDimensions.map { JavaConverter.convertOrEmpty(it, this) }
else -> sourcePsi.argumentList?.expressions?.map { JavaConverter.convertOrEmpty(it, this) } ?: emptyList()
}
}
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val typeArgumentCount: Int by lz { sourcePsi.classReference?.typeParameters?.size ?: 0 }
override val typeArguments: List<PsiType>
get() = sourcePsi.classReference?.typeParameters?.toList() ?: emptyList()
override val returnType: PsiType?
get() = (sourcePsi.classReference?.resolve() as? PsiClass)?.let { PsiTypesUtil.getClassType(it) } ?: sourcePsi.type
override val methodName: String?
get() = null
override fun resolve(): PsiMethod? = sourcePsi.resolveMethod()
override fun multiResolve(): Iterable<ResolveResult> {
val methodResolve = sourcePsi.resolveMethodGenerics()
if (methodResolve != JavaResolveResult.EMPTY) {
// if there is a non-default constructor
return listOf<ResolveResult>(methodResolve)
}
// unable to resolve constructor method - resolve to class
val classResolve = sourcePsi.classReference?.multiResolve(false) ?: emptyArray()
return classResolve.asIterable()
}
}
@ApiStatus.Internal
class JavaArrayInitializerUCallExpression(
override val sourcePsi: PsiArrayInitializerExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpression, UMultiResolvable {
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val valueArgumentCount: Int by lz { sourcePsi.initializers.size }
override val valueArguments: List<UExpression> by lz { sourcePsi.initializers.map { JavaConverter.convertOrEmpty(it, this) } }
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = sourcePsi.type
override val kind: UastCallKind
get() = UastCallKind.NESTED_ARRAY_INITIALIZER
override fun resolve(): Nothing? = null
override fun multiResolve(): Iterable<ResolveResult> = emptyList()
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
}
@ApiStatus.Internal
class JavaAnnotationArrayInitializerUCallExpression(
override val sourcePsi: PsiArrayInitializerMemberValue,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpression, UMultiResolvable {
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val kind: UastCallKind
get() = UastCallKind.NESTED_ARRAY_INITIALIZER
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val valueArgumentCount: Int by lz { sourcePsi.initializers.size }
override val valueArguments: List<UExpression> by lz {
sourcePsi.initializers.map {
JavaConverter.convertPsiElement(it, this, UElement::class.java) as? UExpression ?: UnknownJavaExpression(it, this)
}
}
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = null
override fun resolve(): Nothing? = null
override fun multiResolve(): Iterable<ResolveResult> = emptyList()
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
}
| apache-2.0 | 6c121d41e3ff226deaa118257ab7f0ca | 33.113402 | 136 | 0.737383 | 5.075153 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm-decompiler/src/org/jetbrains/kotlin/idea/jvmDecompiler/DecompileKotlinToJavaAction.kt | 5 | 2596 | // 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.jvmDecompiler
import com.intellij.codeInsight.AttachSourcesProvider
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.util.ActionCallback
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils
import org.jetbrains.kotlin.psi.KtFile
class DecompileKotlinToJavaAction : AnAction(KotlinJvmDecompilerBundle.message("action.decompile.java.name")) {
override fun actionPerformed(e: AnActionEvent) {
val binaryFile = getBinaryKotlinFile(e) ?: return
KotlinJvmDecompilerFacadeImpl.showDecompiledCode(binaryFile)
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
when {
KotlinPlatformUtils.isCidr -> e.presentation.isEnabledAndVisible = false
else -> e.presentation.isEnabled = getBinaryKotlinFile(e) != null
}
}
private fun getBinaryKotlinFile(e: AnActionEvent): KtFile? {
val file = e.getData(CommonDataKeys.PSI_FILE) as? KtFile ?: return null
if (!file.canBeDecompiledToJava()) return null
return file
}
}
fun KtFile.canBeDecompiledToJava() = isCompiled && virtualFile?.fileType == JavaClassFileType.INSTANCE
// Add action to "Attach sources" notification panel
internal class DecompileKotlinToJavaActionProvider : AttachSourcesProvider {
override fun getActions(
orderEntries: List<LibraryOrderEntry>,
psiFile: PsiFile
): Collection<AttachSourcesProvider.AttachSourcesAction> {
if (psiFile !is KtFile || !psiFile.canBeDecompiledToJava()) return emptyList()
return listOf(object : AttachSourcesProvider.AttachSourcesAction {
override fun getName() = KotlinJvmDecompilerBundle.message("action.decompile.java.name")
override fun perform(orderEntriesContainingFile: List<LibraryOrderEntry>): ActionCallback {
KotlinJvmDecompilerFacadeImpl.showDecompiledCode(psiFile)
return ActionCallback.DONE
}
override fun getBusyText() = KotlinJvmDecompilerBundle.message("action.decompile.busy.text")
})
}
}
| apache-2.0 | 2f30d433fd7617055027bff118f27385 | 39.5625 | 120 | 0.751156 | 4.963671 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/j2k/new/tests/testData/inference/nullability/classTypeParameters.kt | 13 | 676 | open class A<T> {
open fun foo(): /*T3@*/Map</*T0@*/T, /*T2@*/List</*T1@*/T>?>? {
TODO()
}
open fun bar(): /*T4@*/T? {
return null/*NULL!!U*/
}
}
class B : A</*T10@*/Int>() {
override fun foo(): /*T8@*/Map</*T5@*/Int, /*T7@*/List</*T6@*/Int>?>? {
return null/*NULL!!U*/
}
override fun bar(): /*T9@*/Int {
return 42/*LIT*/
}
}
//UPPER <: T4 due to 'RETURN'
//UPPER <: T8 due to 'RETURN'
//T5 := T10 due to 'SUPER_DECLARATION'
//T6 := T10 due to 'SUPER_DECLARATION'
//T2 := T7 due to 'SUPER_DECLARATION'
//T3 := T8 due to 'SUPER_DECLARATION'
//LOWER <: T9 due to 'RETURN'
//T9 := T10 due to 'SUPER_DECLARATION'
| apache-2.0 | 41b6b5e442593048d2d570ae1b794cf0 | 24.037037 | 75 | 0.510355 | 2.781893 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/lax_tap/LaxTapTransitData.kt | 1 | 4431 | /*
* LaxTapTransitData.kt
*
* Copyright 2015-2016 Michael Farrell <[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 au.id.micolous.metrodroid.transit.lax_tap
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory
import au.id.micolous.metrodroid.card.classic.ClassicSector
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.transit.CardInfo
import au.id.micolous.metrodroid.transit.TransitCurrency.Companion.USD
import au.id.micolous.metrodroid.transit.TransitData
import au.id.micolous.metrodroid.transit.TransitIdentity
import au.id.micolous.metrodroid.transit.TransitRegion
import au.id.micolous.metrodroid.transit.nextfare.NextfareTransitData
import au.id.micolous.metrodroid.transit.nextfare.NextfareTransitDataCapsule
import au.id.micolous.metrodroid.transit.nextfare.NextfareTripCapsule
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.StationTableReader
/**
* Los Angeles Transit Access Pass (LAX TAP) card.
* https://github.com/micolous/metrodroid/wiki/Transit-Access-Pass
*/
@Parcelize
class LaxTapTransitData (override val capsule: NextfareTransitDataCapsule): NextfareTransitData() {
override val cardName: String
get() = NAME
override val onlineServicesPage: String?
get() = "https://www.taptogo.net/"
override val timezone: MetroTimeZone
get() = TIME_ZONE
override val currency
get() = ::USD
companion object {
private const val NAME = "TAP"
private const val LONG_NAME = "Transit Access Pass"
private val BLOCK1 = ImmutableByteArray.fromHex(
"16181A1B1C1D1E1F010101010101"
)
val BLOCK2 = ImmutableByteArray(4)
private val CARD_INFO = CardInfo(
imageId = R.drawable.laxtap_card,
imageAlphaId = R.drawable.iso7810_id1_alpha,
// Using the short name (TAP) may be ambiguous
name = LONG_NAME,
locationId = R.string.location_los_angeles,
cardType = CardType.MifareClassic,
keysRequired = true,
region = TransitRegion.USA,
preview = true)
private val TIME_ZONE = MetroTimeZone.LOS_ANGELES
val FACTORY: ClassicCardTransitFactory = object : NextfareTransitData.NextFareTransitFactory() {
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO)
override fun parseTransitIdentity(card: ClassicCard): TransitIdentity {
return super.parseTransitIdentity(card, NAME)
}
override fun earlyCheck(sectors: List<ClassicSector>): Boolean {
val sector0 = sectors[0]
val block1 = sector0.getBlock(1).data
if (!block1.copyOfRange(1, 15).contentEquals(BLOCK1)) {
return false
}
val block2 = sector0.getBlock(2).data
return block2.copyOfRange(0, 4).contentEquals(BLOCK2)
}
override fun parseTransitData(card: ClassicCard): TransitData {
val capsule = parse(card = card, timeZone = TIME_ZONE,
newTrip = ::LaxTapTrip,
newRefill = { LaxTapTrip(NextfareTripCapsule(it))},
shouldMergeJourneys = false)
return LaxTapTransitData(capsule)
}
override val notice: String?
get() = StationTableReader.getNotice(LaxTapData.LAX_TAP_STR)
}
}
}
| gpl-3.0 | fceea1dd473522e687a2aab4351ad735 | 38.5625 | 104 | 0.676371 | 4.36122 | false | false | false | false |
iPoli/iPoli-android | app/src/test/java/io/ipoli/android/habit/usecase/SaveHabitUseCaseSpek.kt | 1 | 9327 | package io.ipoli.android.habit.usecase
import com.nhaarman.mockito_kotlin.mock
import io.ipoli.android.TestUtil
import io.ipoli.android.common.Reward
import io.ipoli.android.common.datetime.Time
import io.ipoli.android.habit.data.CompletedEntry
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.usecase.RemoveRewardFromPlayerUseCase
import io.ipoli.android.player.usecase.RewardPlayerUseCase
import io.ipoli.android.quest.Color
import io.ipoli.android.quest.Icon
import io.ipoli.android.quest.Quest
import org.amshove.kluent.*
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.threeten.bp.DayOfWeek
import org.threeten.bp.LocalDate
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 8/21/18.
*/
class SaveHabitUseCaseSpek : Spek({
describe("SaveHabitUseCase") {
fun executeUseCase(
params: SaveHabitUseCase.Params,
habit: Habit,
rewardPlayerUseCase: RewardPlayerUseCase = mock(),
removeRewardFromPlayerUseCase: RemoveRewardFromPlayerUseCase = mock(),
player: Player = TestUtil.player
) =
SaveHabitUseCase(
TestUtil.habitRepoMock(
habit
),
TestUtil.playerRepoMock(player),
rewardPlayerUseCase,
removeRewardFromPlayerUseCase,
mock()
).execute(
params
)
it("should remove reward from player") {
val removeRewardFromPlayerUseCaseMock = mock<RemoveRewardFromPlayerUseCase>()
val r = Reward(
attributePoints = emptyMap(),
healthPoints = 0,
experience = 10,
coins = 1,
bounty = Quest.Bounty.None
)
executeUseCase(
params = SaveHabitUseCase.Params(
id = "AAA",
timesADay = 2,
name = "",
color = Color.LIME,
icon = Icon.DROP,
days = DayOfWeek.values().toSet(),
isGood = true,
reminders = emptyList()
),
habit = TestUtil.habit.copy(
id = "AAA",
days = DayOfWeek.values().toSet(),
timesADay = 1,
history = mapOf(
LocalDate.now() to
CompletedEntry().copy(
completedAtTimes = listOf(Time.at(12, 45)),
reward = r
)
)
),
player = TestUtil.player.copy(
preferences = TestUtil.player.preferences.copy(
resetDayTime = Time.at(12, 30)
)
),
removeRewardFromPlayerUseCase = removeRewardFromPlayerUseCaseMock
)
Verify on removeRewardFromPlayerUseCaseMock that removeRewardFromPlayerUseCaseMock.execute(
RemoveRewardFromPlayerUseCase.Params(
RemoveRewardFromPlayerUseCase.Params.RewardType.GOOD_HABIT,
r
)
) was called
}
it("should not remove reward from player") {
val removeRewardFromPlayerUseCaseMock = mock<RemoveRewardFromPlayerUseCase>()
executeUseCase(
params = SaveHabitUseCase.Params(
id = "AAA",
timesADay = 3,
name = "",
color = Color.LIME,
icon = Icon.DROP,
days = DayOfWeek.values().toSet(),
isGood = true,
reminders = emptyList()
),
habit = TestUtil.habit.copy(
id = "AAA",
days = DayOfWeek.values().toSet(),
timesADay = 8,
history = mapOf()
),
player = TestUtil.player.copy(
preferences = TestUtil.player.preferences.copy(
resetDayTime = Time.at(12, 30)
)
),
removeRewardFromPlayerUseCase = removeRewardFromPlayerUseCaseMock
)
val expectedReward =
Reward(emptyMap(), 0, 10, 1, Quest.Bounty.None)
`Verify not called` on removeRewardFromPlayerUseCaseMock that removeRewardFromPlayerUseCaseMock.execute(
RemoveRewardFromPlayerUseCase.Params(
RemoveRewardFromPlayerUseCase.Params.RewardType.GOOD_HABIT,
expectedReward
)
)
}
it("should not change reward for player") {
val removeRewardFromPlayerUseCaseMock = mock<RemoveRewardFromPlayerUseCase>()
val rewardPlayerUseCaseMock = mock<RewardPlayerUseCase>()
executeUseCase(
params = SaveHabitUseCase.Params(
id = "AAA",
timesADay = 2,
name = "",
color = Color.LIME,
icon = Icon.DROP,
days = DayOfWeek.values().toSet(),
isGood = true,
reminders = emptyList()
),
habit = TestUtil.habit.copy(
id = "AAA",
days = DayOfWeek.values().toSet(),
timesADay = 3,
history = mapOf(
LocalDate.now() to CompletedEntry(listOf(Time.atHours(12)))
)
),
player = TestUtil.player.copy(
preferences = TestUtil.player.preferences.copy(
resetDayTime = Time.at(0, 30)
)
),
removeRewardFromPlayerUseCase = removeRewardFromPlayerUseCaseMock,
rewardPlayerUseCase = rewardPlayerUseCaseMock
)
val expectedReward =
Reward(emptyMap(), 0, 10, 1, Quest.Bounty.None)
`Verify not called` on removeRewardFromPlayerUseCaseMock that removeRewardFromPlayerUseCaseMock.execute(
RemoveRewardFromPlayerUseCase.Params(
RemoveRewardFromPlayerUseCase.Params.RewardType.GOOD_HABIT,
expectedReward
)
)
// `Verify not called` on rewardPlayerUseCaseMock that rewardPlayerUseCaseMock.execute(
// expectedReward
// )
}
it("should update preferenceHistory when timesADay changes") {
val newTimesADay = 2
val h = executeUseCase(
params = SaveHabitUseCase.Params(
id = "AAA",
timesADay = newTimesADay,
name = "",
color = Color.LIME,
icon = Icon.DROP,
days = DayOfWeek.values().toSet(),
isGood = true,
reminders = emptyList()
),
habit = TestUtil.habit.copy(
id = "AAA",
days = DayOfWeek.values().toSet(),
timesADay = 3,
preferenceHistory = TestUtil.habit.preferenceHistory.copy(
timesADay = sortedMapOf(LocalDate.now().minusDays(1) to 3)
)
)
)
h.preferenceHistory.timesADay.size.`should be equal to`(2)
val expectedTimesADayHistory = sortedMapOf(
LocalDate.now().minusDays(1) to 3,
LocalDate.now() to newTimesADay
)
h.preferenceHistory.timesADay.`should equal`(expectedTimesADayHistory)
}
it("should update preferenceHistory when days changes") {
val newDays = setOf(DayOfWeek.MONDAY, DayOfWeek.TUESDAY)
val h = executeUseCase(
params = SaveHabitUseCase.Params(
id = "AAA",
timesADay = 2,
name = "",
color = Color.LIME,
icon = Icon.DROP,
days = newDays,
isGood = true,
reminders = emptyList()
),
habit = TestUtil.habit.copy(
id = "AAA",
days = DayOfWeek.values().toSet(),
preferenceHistory = TestUtil.habit.preferenceHistory.copy(
days = sortedMapOf(LocalDate.now().minusDays(1) to DayOfWeek.values().toSet())
)
)
)
h.preferenceHistory.days.size.`should be equal to`(2)
val expectedDayHistory = sortedMapOf(
LocalDate.now().minusDays(1) to DayOfWeek.values().toSet(),
LocalDate.now() to newDays
)
h.preferenceHistory.days.`should equal`(expectedDayHistory)
}
}
}) | gpl-3.0 | 4e94e3f3c0794d19176c1414aacc8f57 | 37.866667 | 116 | 0.500161 | 5.457578 | false | true | false | false |
hellenxu/TipsProject | DroidDailyProject/sixlint/src/main/java/six/ca/sixlint/SensitiveInfoDetector.kt | 1 | 3940 |
package six.ca.sixlint
import com.android.resources.ResourceFolderType
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.*
import org.jetbrains.uast.*
import org.w3c.dom.Attr
import java.util.*
/**
* @author hellenxu
* @date 2020-09-01
* Copyright 2020 Six. All rights reserved.
*/
@Suppress("UnstableApiUsage")
class SensitiveInfoDetector:
Detector(),
Detector.UastScanner,
Detector.XmlScanner,
Detector.ResourceFolderScanner
{
private lateinit var lintConfigReader: LintConfigurationReader
private lateinit var whiteListVisitor: WhiteListVisitor
override fun beforeCheckEachProject(context: Context) {
super.beforeCheckEachProject(context)
if (!this::lintConfigReader.isInitialized) {
lintConfigReader = LintConfigurationReader(context)
whiteListVisitor = WhiteListVisitor(lintConfigReader.javaWhiteList)
}
}
// need to return ULiteralExpression as visitLiteralExpression() will be override in method createUastHandler
override fun getApplicableUastTypes(): List<Class<out UElement>>? {
return listOf(UClass::class.java, ULiteralExpression::class.java)
}
override fun getApplicableFiles(): EnumSet<Scope> {
return EnumSet.of(Scope.JAVA_FILE)
}
override fun createUastHandler(context: JavaContext): UElementHandler? {
return object: UElementHandler() {
override fun visitLiteralExpression(node: ULiteralExpression) {
val evaluatedString = node.evaluateString() ?: return
if (evaluatedString.matches(idReg) or evaluatedString.matches(phoneNumReg)) {
println("xxl-createUastHandler: $evaluatedString")
context.report(JAVA_FILE_ISSUE, node, context.getLocation(node), hintMessage)
}
}
override fun visitClass(node: UClass) {
println("xxl-handler-visitClass")
node.accept(WhiteListVisitor(lintConfigReader.javaWhiteList))
}
}
}
override fun getApplicableAttributes(): Collection<String>? {
return XmlScannerConstants.ALL
}
override fun visitAttribute(context: XmlContext, attribute: Attr) {
val attrName = attribute.name
val attrValue = attribute.value
if (attrValue.matches(idReg) or attrValue.matches(phoneNumReg)) {
println("xxl-attr: $attrName; $attrValue")
context.report(RESOURCE_FILE_ISSUE, context.getValueLocation(attribute), hintMessage)
}
}
override fun appliesTo(folderType: ResourceFolderType): Boolean {
val whiteList = listOf(ResourceFolderType.VALUES, ResourceFolderType.DRAWABLE, ResourceFolderType.MIPMAP)
return folderType !in whiteList
}
companion object {
private val phoneNumReg = Regex(".*(\\d{3}[-.]?){2}\\d{4}.*")
private val idReg = Regex(".*\\d{8,9}.*")
@JvmField
val JAVA_FILE_ISSUE = Issue.create(
id = "id00",
briefDescription = "Hardcoded id",
explanation = "replace with dump string",
category = Category.SECURITY,
priority = 7,
severity = Severity.ERROR,
implementation = Implementation(SensitiveInfoDetector::class.java,
Scope.JAVA_FILE_SCOPE
)
)
@JvmField
val RESOURCE_FILE_ISSUE = Issue.create(
id = "id00",
briefDescription = "Hardcoded id",
explanation = "replace with dump string",
category = Category.SECURITY,
priority = 7,
severity = Severity.ERROR,
implementation = Implementation(SensitiveInfoDetector::class.java,
Scope.RESOURCE_FILE_SCOPE
)
)
private const val hintMessage = "found out sensitive info: id"
}
} | apache-2.0 | 4a51bb6675e013ff16bab140d2b27301 | 33.876106 | 113 | 0.647208 | 4.816626 | false | true | false | false |
GunoH/intellij-community | plugins/gradle/java/src/service/resolve/util.kt | 2 | 3756 | // 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.gradle.service.resolve
import com.intellij.lang.properties.psi.PropertiesFile
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.patterns.PatternCondition
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiUtilCore
import com.intellij.util.ProcessingContext
import com.intellij.util.asSafely
import org.jetbrains.plugins.gradle.settings.GradleLocalSettings
import org.jetbrains.plugins.gradle.util.GradleConstants.EXTENSION
import org.jetbrains.plugins.gradle.util.PROPERTIES_FILE_NAME
import org.jetbrains.plugins.gradle.util.getGradleUserHomePropertiesPath
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass
import java.nio.file.Path
val projectTypeKey: Key<GradleProjectAwareType> = Key.create("gradle.current.project")
val saveProjectType: PatternCondition<GroovyMethodResult> = object : PatternCondition<GroovyMethodResult>("saveProjectContext") {
override fun accepts(result: GroovyMethodResult, context: ProcessingContext?): Boolean {
// Given the closure matched some method,
// we want to determine what we know about this Project.
// This PatternCondition just saves the info into the ProcessingContext.
context?.put(projectTypeKey, result.candidate?.receiverType as? GradleProjectAwareType)
return true
}
}
val DELEGATED_TYPE: Key<Boolean> = Key.create("gradle.delegated.type")
@JvmField
val DECLARATION_ALTERNATIVES: Key<List<String>> = Key.create("gradle.declaration.alternatives")
/**
* @author Vladislav.Soroka
*/
internal fun PsiClass?.isResolvedInGradleScript() = this is GroovyScriptClass && this.containingFile.isGradleScript()
internal fun PsiFile?.isGradleScript() = this?.originalFile?.virtualFile?.extension == EXTENSION
private val PsiElement.module get() = containingFile?.originalFile?.virtualFile?.let {
ProjectFileIndex.getInstance(project).getModuleForFile(it)
}
internal fun PsiElement.getLinkedGradleProjectPath() : String? {
return ExternalSystemApiUtil.getExternalProjectPath(module)
}
internal fun PsiElement.getRootGradleProjectPath() : String? {
return ExternalSystemApiUtil.getExternalRootProjectPath(module)
}
internal fun gradlePropertiesStream(place: PsiElement): Sequence<PropertiesFile> = sequence {
val externalRootProjectPath = place.getRootGradleProjectPath() ?: return@sequence
val userHomePropertiesFile = getGradleUserHomePropertiesPath()?.parent?.toString()?.getGradlePropertiesFile(place.project)
if (userHomePropertiesFile != null) {
yield(userHomePropertiesFile)
}
val projectRootPropertiesFile = externalRootProjectPath.getGradlePropertiesFile(place.project)
if (projectRootPropertiesFile != null) {
yield(projectRootPropertiesFile)
}
val localSettings = GradleLocalSettings.getInstance(place.project)
val installationDirectoryPropertiesFile = localSettings.getGradleHome(externalRootProjectPath)?.getGradlePropertiesFile(place.project)
if (installationDirectoryPropertiesFile != null) {
yield(installationDirectoryPropertiesFile)
}
}
private fun String.getGradlePropertiesFile(project: Project): PropertiesFile? {
val file = VfsUtil.findFile(Path.of(this), false)?.findChild(PROPERTIES_FILE_NAME)
return file?.let { PsiUtilCore.getPsiFile(project, it) }.asSafely<PropertiesFile>()
}
| apache-2.0 | f1c4d317fb897c4bebc1746437d258fa | 45.95 | 136 | 0.817093 | 4.637037 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/propertyDetection.kt | 4 | 22366 | // 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.j2k
import com.intellij.psi.*
import com.intellij.psi.util.MethodSignatureUtil
import com.intellij.psi.util.PsiUtil
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.j2k.ast.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.propertyNameByGetMethodName
import org.jetbrains.kotlin.load.java.propertyNameBySetMethodName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.utils.addIfNotNull
class PropertyInfo(
val identifier: Identifier,
val isVar: Boolean,
val psiType: PsiType,
val field: PsiField?,
val getMethod: PsiMethod?,
val setMethod: PsiMethod?,
val isGetMethodBodyFieldAccess: Boolean,
val isSetMethodBodyFieldAccess: Boolean,
val modifiers: Modifiers,
val specialSetterAccess: Modifier?,
val superInfo: SuperInfo?
) {
init {
assert(field != null || getMethod != null || setMethod != null)
if (isGetMethodBodyFieldAccess) {
assert(field != null && getMethod != null)
}
if (isSetMethodBodyFieldAccess) {
assert(field != null && setMethod != null)
}
}
val name: String
get() = identifier.name
//TODO: what if annotations are not empty?
val needExplicitGetter: Boolean
get() {
if (getMethod != null) {
if (getMethod.hasModifierProperty(PsiModifier.NATIVE))
return true
if (getMethod.body != null && !isGetMethodBodyFieldAccess)
return true
}
return modifiers.contains(Modifier.OVERRIDE) && this.field == null && !modifiers.contains(Modifier.ABSTRACT)
}
//TODO: what if annotations are not empty?
val needExplicitSetter: Boolean
get() {
if (!isVar) return false
if (specialSetterAccess != null) return true
if (setMethod != null) {
if (setMethod.hasModifierProperty(PsiModifier.NATIVE))
return true
if (setMethod.body != null && !isSetMethodBodyFieldAccess)
return true
}
return modifiers.contains(Modifier.EXTERNAL) ||
modifiers.contains(Modifier.OVERRIDE) && this.field == null && !modifiers.contains(Modifier.ABSTRACT)
}
companion object {
fun fromFieldWithNoAccessors(field: PsiField, converter: Converter): PropertyInfo {
val isVar = field.isVar(converter.referenceSearcher)
val isInObject = field.containingClass?.let { converter.shouldConvertIntoObject(it) } == true
val modifiers = converter.convertModifiers(field, false, isInObject)
return PropertyInfo(
field.declarationIdentifier(), isVar, field.type, field,
getMethod = null,
setMethod = null,
isGetMethodBodyFieldAccess = false,
isSetMethodBodyFieldAccess = false,
modifiers = modifiers,
specialSetterAccess = null,
superInfo = null
)
}
}
}
class PropertyDetectionCache(private val converter: Converter) {
private val cache = HashMap<PsiClass, Map<PsiMember, PropertyInfo>>()
operator fun get(psiClass: PsiClass): Map<PsiMember, PropertyInfo> {
cache[psiClass]?.let { return it }
assert(converter.inConversionScope(psiClass))
val detected = PropertyDetector(psiClass, converter).detectProperties()
cache[psiClass] = detected
return detected
}
}
sealed class SuperInfo {
class Property(
val isVar: Boolean,
val name: String,
val hasAbstractModifier: Boolean
//TODO: add visibility
) : SuperInfo()
object Function : SuperInfo()
fun isAbstract(): Boolean {
return if (this is Property) hasAbstractModifier else false
}
}
private class PropertyDetector(
private val psiClass: PsiClass,
private val converter: Converter
) {
private val isOpenClass = converter.needOpenModifier(psiClass)
fun detectProperties(): Map<PsiMember, PropertyInfo> {
val propertyInfos = detectPropertyCandidates()
val memberToPropertyInfo = buildMemberToPropertyInfoMap(propertyInfos)
dropPropertiesWithConflictingAccessors(memberToPropertyInfo)
dropPropertiesConflictingWithFields(memberToPropertyInfo)
val mappedFields = memberToPropertyInfo.values
.mapNotNull { it.field }
.toSet()
// map all other fields
for (field in psiClass.fields) {
if (field !in mappedFields) {
memberToPropertyInfo[field] = PropertyInfo.fromFieldWithNoAccessors(field, converter)
}
}
return memberToPropertyInfo
}
private fun detectPropertyCandidates(): List<PropertyInfo> {
val methodsToCheck = ArrayList<Pair<PsiMethod, SuperInfo.Property?>>()
for (method in psiClass.methods) {
val name = method.name
if (!name.startsWith("get") && !name.startsWith("set") && !name.startsWith("is")) continue
val superInfo = superInfo(method)
if (superInfo is SuperInfo.Function) continue
methodsToCheck.add(method to (superInfo as SuperInfo.Property?))
}
val propertyNamesWithConflict = HashSet<String>()
val propertyNameToGetterInfo = detectGetters(methodsToCheck, propertyNamesWithConflict)
val propertyNameToSetterInfo = detectSetters(methodsToCheck, propertyNameToGetterInfo.keys, propertyNamesWithConflict)
val propertyNames = propertyNameToGetterInfo.keys + propertyNameToSetterInfo.keys
val propertyInfos = ArrayList<PropertyInfo>()
for (propertyName in propertyNames) {
val getterInfo = propertyNameToGetterInfo[propertyName]
var setterInfo = propertyNameToSetterInfo[propertyName]
// no property without getter except for overrides
if (getterInfo == null && setterInfo!!.method.hierarchicalMethodSignature.superSignatures.isEmpty()) continue
if (setterInfo != null && getterInfo != null && setterInfo.method.parameterList.parameters.single().type != getterInfo.method.returnType) {
setterInfo = null
}
var field = getterInfo?.field ?: setterInfo?.field
if (field != null) {
fun PsiReferenceExpression.canBeReplacedWithFieldAccess(): Boolean {
if (getterInfo?.method?.isAncestor(this) != true && setterInfo?.method?.isAncestor(this) != true) return false // not inside property
return qualifier == null || qualifier is PsiThisExpression //TODO: check it's correct this
}
if (getterInfo != null && getterInfo.field == null) {
if (!field.hasModifierProperty(PsiModifier.PRIVATE)
|| converter.referenceSearcher.findVariableUsages(field, psiClass).any {
PsiUtil.isAccessedForReading(it) && !it.canBeReplacedWithFieldAccess()
}
) {
field = null
}
} else if (setterInfo != null && setterInfo.field == null) {
if (!field.hasModifierProperty(PsiModifier.PRIVATE)
|| converter.referenceSearcher.findVariableUsages(field, psiClass).any {
PsiUtil.isAccessedForWriting(it) && !it.canBeReplacedWithFieldAccess()
}
) {
field = null
}
}
}
//TODO: no body for getter OR setter
val isVar = if (setterInfo != null)
true
else if (getterInfo!!.superProperty != null && getterInfo.superProperty!!.isVar)
true
else
field != null && field.isVar(converter.referenceSearcher)
val type = getterInfo?.method?.returnType ?: setterInfo!!.method.parameterList.parameters.single()?.type!!
val superProperty = getterInfo?.superProperty ?: setterInfo?.superProperty
val isOverride = superProperty != null
val modifiers = convertModifiers(field, getterInfo?.method, setterInfo?.method, isOverride)
val propertyAccess = modifiers.accessModifier()
val setterAccess = if (setterInfo != null)
converter.convertModifiers(setterInfo.method, isMethodInOpenClass = false, isInObject = false).accessModifier()
else if (field != null && field.isVar(converter.referenceSearcher))
converter.convertModifiers(field, isMethodInOpenClass = false, isInObject = false).accessModifier()
else
propertyAccess
val specialSetterAccess = setterAccess?.takeIf { it != propertyAccess }
val propertyInfo = PropertyInfo(
Identifier.withNoPrototype(propertyName),
isVar,
type,
field,
getterInfo?.method,
setterInfo?.method,
field != null && getterInfo?.field == field,
field != null && setterInfo?.field == field,
modifiers,
specialSetterAccess,
superProperty
)
propertyInfos.add(propertyInfo)
}
return propertyInfos
}
private fun buildMemberToPropertyInfoMap(propertyInfos: List<PropertyInfo>): MutableMap<PsiMember, PropertyInfo> {
val memberToPropertyInfo = HashMap<PsiMember, PropertyInfo>()
for (propertyInfo in propertyInfos) {
val field = propertyInfo.field
if (field != null) {
if (memberToPropertyInfo.containsKey(field)) { // field already in use by other property
continue
} else {
memberToPropertyInfo[field] = propertyInfo
}
}
propertyInfo.getMethod?.let { memberToPropertyInfo[it] = propertyInfo }
propertyInfo.setMethod?.let { memberToPropertyInfo[it] = propertyInfo }
}
return memberToPropertyInfo
}
private fun detectGetters(
methodsToCheck: List<Pair<PsiMethod, SuperInfo.Property?>>,
propertyNamesWithConflict: MutableSet<String>
): Map<String, AccessorInfo> {
val propertyNameToGetterInfo = LinkedHashMap<String, AccessorInfo>()
for ((method, superInfo) in methodsToCheck) {
val info = getGetterInfo(method, superInfo) ?: continue
val prevInfo = propertyNameToGetterInfo[info.propertyName]
if (prevInfo != null) {
propertyNamesWithConflict.add(info.propertyName)
continue
}
propertyNameToGetterInfo[info.propertyName] = info
}
return propertyNameToGetterInfo
}
private fun detectSetters(
methodsToCheck: List<Pair<PsiMethod, SuperInfo.Property?>>,
propertyNamesFromGetters: Set<String>,
propertyNamesWithConflict: MutableSet<String>
): Map<String, AccessorInfo> {
val propertyNameToSetterInfo = LinkedHashMap<String, AccessorInfo>()
for ((method, superInfo) in methodsToCheck) {
val info = getSetterInfo(method, superInfo, propertyNamesFromGetters) ?: continue
val prevInfo = propertyNameToSetterInfo[info.propertyName]
if (prevInfo != null) {
propertyNamesWithConflict.add(info.propertyName)
continue
}
propertyNameToSetterInfo[info.propertyName] = info
}
return propertyNameToSetterInfo
}
private fun dropPropertiesWithConflictingAccessors(memberToPropertyInfo: MutableMap<PsiMember, PropertyInfo>) {
val propertyInfos = memberToPropertyInfo.values.distinct()
val mappedMethods = propertyInfos.mapNotNull { it.getMethod }.toSet() + propertyInfos.mapNotNull { it.setMethod }.toSet()
//TODO: bases
val prohibitedSignatures = psiClass.methods
.filter { it !in mappedMethods }
.map { it.getSignature(PsiSubstitutor.EMPTY) }
.toSet()
for (propertyInfo in propertyInfos) {
if (propertyInfo.modifiers.contains(Modifier.OVERRIDE)) continue // cannot drop override
//TODO: test this case
val getterName = JvmAbi.getterName(propertyInfo.name)
val getterSignature = MethodSignatureUtil.createMethodSignature(getterName, emptyArray(), emptyArray(), PsiSubstitutor.EMPTY)
if (getterSignature in prohibitedSignatures) {
memberToPropertyInfo.dropProperty(propertyInfo)
continue
}
if (propertyInfo.isVar) {
val setterName = JvmAbi.setterName(propertyInfo.name)
val setterSignature = MethodSignatureUtil.createMethodSignature(
setterName, arrayOf(propertyInfo.psiType), emptyArray(), PsiSubstitutor.EMPTY
)
if (setterSignature in prohibitedSignatures) {
memberToPropertyInfo.dropProperty(propertyInfo)
continue
}
}
}
}
private fun dropPropertiesConflictingWithFields(memberToPropertyInfo: MutableMap<PsiMember, PropertyInfo>) {
val fieldsByName = psiClass.fields.associateBy { it.name } //TODO: fields from base
fun isPropertyNameInUse(name: String): Boolean {
val field = fieldsByName[name] ?: return false
return !memberToPropertyInfo.containsKey(field)
}
var repeatLoop: Boolean
do {
repeatLoop = false
for (propertyInfo in memberToPropertyInfo.values.distinct()) {
if (isPropertyNameInUse(propertyInfo.name)) {
//TODO: what about overrides in this case?
memberToPropertyInfo.dropProperty(propertyInfo)
if (propertyInfo.field != null) {
repeatLoop = true // need to repeat loop because a new field appeared
}
}
}
} while (repeatLoop)
}
private fun MutableMap<PsiMember, PropertyInfo>.dropProperty(propertyInfo: PropertyInfo) {
propertyInfo.field?.let { remove(it) }
propertyInfo.getMethod?.let { remove(it) }
propertyInfo.setMethod?.let { remove(it) }
}
private fun convertModifiers(field: PsiField?, getMethod: PsiMethod?, setMethod: PsiMethod?, isOverride: Boolean): Modifiers {
val fieldModifiers = field?.let {
converter.convertModifiers(it, isMethodInOpenClass = false, isInObject = false)
} ?: Modifiers.Empty
val getterModifiers = getMethod?.let { converter.convertModifiers(it, isOpenClass, false) } ?: Modifiers.Empty
val setterModifiers = setMethod?.let { converter.convertModifiers(it, isOpenClass, false) } ?: Modifiers.Empty
val modifiers = ArrayList<Modifier>()
//TODO: what if one is abstract and another is not?
val isGetterAbstract = getMethod?.hasModifierProperty(PsiModifier.ABSTRACT) ?: true
val isSetterAbstract = setMethod?.hasModifierProperty(PsiModifier.ABSTRACT) ?: true
if (field == null && isGetterAbstract && isSetterAbstract) {
modifiers.add(Modifier.ABSTRACT)
}
if (getterModifiers.contains(Modifier.OPEN) || setterModifiers.contains(Modifier.OPEN)) {
modifiers.add(Modifier.OPEN)
}
if (isOverride) {
modifiers.add(Modifier.OVERRIDE)
}
when {
getMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier())
setMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier())
else -> modifiers.addIfNotNull(fieldModifiers.accessModifier())
}
val prototypes = listOfNotNull<PsiElement>(field, getMethod, setMethod)
.map { PrototypeInfo(it, CommentsAndSpacesInheritance.NO_SPACES) }
return Modifiers(modifiers).assignPrototypes(*prototypes.toTypedArray())
}
private class AccessorInfo(
val method: PsiMethod,
val field: PsiField?,
val kind: AccessorKind,
val propertyName: String,
val superProperty: SuperInfo.Property?
)
private fun getGetterInfo(method: PsiMethod, superProperty: SuperInfo.Property?): AccessorInfo? {
val propertyName = propertyNameByGetMethod(method) ?: return null
val field = fieldFromGetterBody(method)
return AccessorInfo(method, field, AccessorKind.GETTER, propertyName, superProperty)
}
private fun getSetterInfo(method: PsiMethod, superProperty: SuperInfo.Property?, propertyNamesFromGetters: Set<String>): AccessorInfo? {
val allowedPropertyNames = if (superProperty != null)
setOf(superProperty.name)
else
propertyNamesFromGetters
val propertyName = propertyNameBySetMethod(method, allowedPropertyNames) ?: return null
val field = fieldFromSetterBody(method)
return AccessorInfo(method, field, AccessorKind.SETTER, propertyName, superProperty)
}
private fun superInfo(getOrSetMethod: PsiMethod): SuperInfo? {
//TODO: multiple
val superMethod = converter.services.superMethodsSearcher.findDeepestSuperMethods(getOrSetMethod).firstOrNull() ?: return null
val containingClass = superMethod.containingClass!!
return when {
converter.inConversionScope(containingClass) -> {
val propertyInfo = converter.propertyDetectionCache[containingClass][superMethod]
if (propertyInfo != null) {
SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT))
} else {
SuperInfo.Function
}
}
superMethod is KtLightMethod -> {
val origin = superMethod.kotlinOrigin
if (origin is KtProperty) SuperInfo.Property(origin.isVar, origin.name ?: "", origin.hasModifier(KtTokens.ABSTRACT_KEYWORD))
else SuperInfo.Function
}
else -> {
SuperInfo.Function
}
}
}
private fun propertyNameByGetMethod(method: PsiMethod): String? {
if (method.isConstructor) return null
if (method.parameterList.parametersCount != 0) return null
val name = method.name
if (!Name.isValidIdentifier(name)) return null
val propertyName = propertyNameByGetMethodName(Name.identifier(name))?.identifier ?: return null
val returnType = method.returnType ?: return null
if (returnType.canonicalText == "void") return null
if (method.typeParameters.isNotEmpty()) return null
return propertyName
}
private fun propertyNameBySetMethod(method: PsiMethod, allowedNames: Set<String>): String? {
if (method.isConstructor) return null
if (method.parameterList.parametersCount != 1) return null
val name = method.name
if (!Name.isValidIdentifier(name)) return null
val propertyName1 = propertyNameBySetMethodName(Name.identifier(name), false)?.identifier
val propertyName2 = propertyNameBySetMethodName(Name.identifier(name), true)?.identifier
val propertyName = if (propertyName1 != null && propertyName1 in allowedNames)
propertyName1
else if (propertyName2 != null && propertyName2 in allowedNames)
propertyName2
else
return null
if (method.returnType?.canonicalText != "void") return null
if (method.typeParameters.isNotEmpty()) return null
return propertyName
}
private fun fieldFromGetterBody(getter: PsiMethod): PsiField? {
val body = getter.body ?: return null
val returnStatement = (body.statements.singleOrNull() as? PsiReturnStatement) ?: return null
val isStatic = getter.hasModifierProperty(PsiModifier.STATIC)
val field = fieldByExpression(returnStatement.returnValue, isStatic) ?: return null
if (field.type != getter.returnType) return null
if (converter.typeConverter.variableMutability(field) != converter.typeConverter.methodMutability(getter)) return null
return field
}
private fun fieldFromSetterBody(setter: PsiMethod): PsiField? {
val body = setter.body ?: return null
val statement = (body.statements.singleOrNull() as? PsiExpressionStatement) ?: return null
val assignment = statement.expression as? PsiAssignmentExpression ?: return null
if (assignment.operationTokenType != JavaTokenType.EQ) return null
val isStatic = setter.hasModifierProperty(PsiModifier.STATIC)
val field = fieldByExpression(assignment.lExpression, isStatic) ?: return null
val parameter = setter.parameterList.parameters.single()
if ((assignment.rExpression as? PsiReferenceExpression)?.resolve() != parameter) return null
if (field.type != parameter.type) return null
return field
}
private fun fieldByExpression(expression: PsiExpression?, static: Boolean): PsiField? {
val refExpr = expression as? PsiReferenceExpression ?: return null
if (static) {
if (!refExpr.isQualifierEmptyOrClass(psiClass)) return null
} else {
if (!refExpr.isQualifierEmptyOrThis()) return null
}
val field = refExpr.resolve() as? PsiField ?: return null
if (field.containingClass != psiClass || field.hasModifierProperty(PsiModifier.STATIC) != static) return null
return field
}
} | apache-2.0 | 83beb4495392e44d6af56c150e64a22b | 41.281664 | 158 | 0.63914 | 5.25764 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationRequest.kt | 1 | 1851 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.netty
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.request.*
import io.ktor.utils.io.*
import io.netty.channel.*
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http.multipart.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
public abstract class NettyApplicationRequest(
call: ApplicationCall,
override val coroutineContext: CoroutineContext,
public val context: ChannelHandlerContext,
private val requestBodyChannel: ByteReadChannel,
protected val uri: String,
internal val keepAlive: Boolean
) : BaseApplicationRequest(call), CoroutineScope {
public final override val queryParameters: Parameters = object : Parameters {
private val decoder = QueryStringDecoder(uri, HttpConstants.DEFAULT_CHARSET, true, 1024, true)
override val caseInsensitiveName: Boolean get() = true
override fun getAll(name: String) = decoder.parameters()[name]
override fun names() = decoder.parameters().keys
override fun entries() = decoder.parameters().entries
override fun isEmpty() = decoder.parameters().isEmpty()
}
override val rawQueryParameters: Parameters by lazy(LazyThreadSafetyMode.NONE) {
val queryStartIndex = uri.indexOf('?').takeIf { it != -1 } ?: return@lazy Parameters.Empty
parseQueryString(uri, startIndex = queryStartIndex + 1, decode = false)
}
override val cookies: RequestCookies = NettyApplicationRequestCookies(this)
override fun receiveChannel(): ByteReadChannel = requestBodyChannel
protected abstract fun newDecoder(): HttpPostMultipartRequestDecoder
public fun close() {}
}
| apache-2.0 | eb3b031d618e93721706489a16bec3cb | 37.5625 | 118 | 0.741761 | 4.662469 | false | false | false | false |
neva-dev/javarel-framework | processing/scheduler/src/main/kotlin/com/neva/javarel/processing/scheduler/impl/QuartzScheduler.kt | 1 | 1160 | package com.neva.javarel.processing.scheduler.impl
import com.neva.javarel.processing.scheduler.api.Schedule
import org.apache.felix.scr.annotations.*
import org.quartz.impl.StdSchedulerFactory
import org.quartz.Scheduler as BaseScheduler
@Component(immediate = true)
@Service
class QuartzScheduler : com.neva.javarel.processing.scheduler.api.Scheduler {
@Reference(
referenceInterface = Schedule::class,
cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE,
policy = ReferencePolicy.DYNAMIC
)
private lateinit var schedules: Set<Schedule>
override val scheduler: BaseScheduler by lazy {
val result = StdSchedulerFactory().scheduler
result.setJobFactory(OsgiJobFactory())
result
}
@Activate
protected fun start() {
scheduler.start()
}
@Deactivate
protected fun stop() {
scheduler.shutdown()
}
protected fun bindSchedule(schedule: Schedule) {
scheduler.scheduleJob(schedule.job, schedule.trigger)
}
protected fun unbindSchedule(schedule: Schedule) {
scheduler.unscheduleJob(schedule.trigger.key)
}
} | apache-2.0 | 800302ed98f0105bb05270cfc3ab171f | 25.386364 | 77 | 0.70431 | 4.478764 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/ProjectConfiguration.kt | 1 | 2036 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform
import com.demonwav.mcdev.buildsystem.BuildSystem
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.isNullOrEmpty
import org.jetbrains.annotations.Contract
abstract class ProjectConfiguration {
lateinit var pluginName: String
lateinit var pluginVersion: String
lateinit var mainClass: String
lateinit var description: String
var website: String? = null
lateinit var type: PlatformType
val authors = mutableListOf<String>()
lateinit var module: Module
var isFirst = false
abstract fun create(project: Project, buildSystem: BuildSystem, indicator: ProgressIndicator)
fun hasAuthors() = listContainsAtLeastOne(authors)
fun setAuthors(string: String) {
authors.clear()
authors.addAll(commaSplit(string))
}
fun hasDescription() = description.isNotBlank()
protected fun commaSplit(string: String) =
string.trim().replace("[\\[\\]]".toRegex(), "").split("\\s*,\\s*".toRegex()).toTypedArray()
@Contract("null -> false")
fun listContainsAtLeastOne(list: MutableList<String>?): Boolean {
if (list.isNullOrEmpty()) {
return false
}
list?.removeIf(String::isBlank)
return list?.size != 0
}
protected fun getMainClassDirectory(files: Array<String>, file: VirtualFile): VirtualFile {
var movingFile = file
for (i in 0 until (files.size - 1)) {
val s = files[i]
val temp = movingFile.findChild(s)
movingFile = if (temp != null && temp.isDirectory) {
temp
} else {
movingFile.createChildDirectory(this, s)
}
}
return movingFile
}
}
| mit | b9cc91b184f04f03278b2c573b8ba3d0 | 26.513514 | 99 | 0.662083 | 4.585586 | false | false | false | false |
neva-dev/javarel-framework | storage/store/src/main/kotlin/com/neva/javarel/storage/store/impl/StoreFileResourceProvider.kt | 1 | 1913 | package com.neva.javarel.storage.store.impl
import com.mongodb.gridfs.GridFS
import com.neva.javarel.resource.api.Resource
import com.neva.javarel.resource.api.ResourceDescriptor
import com.neva.javarel.resource.api.ResourceProvider
import com.neva.javarel.resource.api.ResourceResolver
import com.neva.javarel.storage.store.api.StoreAdmin
import com.neva.javarel.storage.store.api.StoreFileResource
import org.apache.felix.scr.annotations.Component
import org.apache.felix.scr.annotations.Reference
import org.apache.felix.scr.annotations.Service
import org.bson.types.ObjectId
@Component(immediate = true)
@Service
class StoreFileResourceProvider : ResourceProvider {
@Reference
private lateinit var repoAdmin: StoreAdmin
override fun handles(descriptor: ResourceDescriptor): Boolean {
return descriptor.protocol == StoreFileResource.PROTOCOL
}
override fun provide(resolver: ResourceResolver, descriptor: ResourceDescriptor): Resource? {
var result: Resource? = null
val file = repoAdmin.store(getConnectionName(descriptor))
.fileStore(getFileStore(descriptor))
.findOne(ObjectId(getFileId(descriptor)))
if (file != null) {
result = StoreFileResource(file, descriptor, resolver)
}
return result
}
private fun getConnectionName(descriptor: ResourceDescriptor) = when (descriptor.parts.size) {
3 -> descriptor.parts[0]
else -> repoAdmin.connectionDefault
}
private fun getFileStore(descriptor: ResourceDescriptor) = when (descriptor.parts.size) {
3 -> descriptor.parts[1]
2 -> descriptor.parts[0]
else -> GridFS.DEFAULT_BUCKET
}
private fun getFileId(descriptor: ResourceDescriptor) = when (descriptor.parts.size) {
3 -> descriptor.parts[2]
2 -> descriptor.parts[1]
else -> descriptor.parts[0]
}
} | apache-2.0 | 76c344979ba4d2e6a9fd064a2cfcc896 | 33.178571 | 98 | 0.720335 | 4.347727 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/androidTest/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/ProgramIndicatorEvaluatorIntegrationShould.kt | 1 | 8844 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator
import com.google.common.truth.Truth.assertThat
import org.hisp.dhis.android.core.analytics.aggregated.DimensionItem
import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem
import org.hisp.dhis.android.core.analytics.aggregated.internal.AnalyticsServiceEvaluationItem
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.dataElement1
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.day20191101
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.generator
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.orgunitChild1
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.program
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.programStage1
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.trackedEntity1
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.trackedEntity2
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.BaseEvaluatorSamples.trackedEntityType
import org.hisp.dhis.android.core.common.AggregationType
import org.hisp.dhis.android.core.common.AnalyticsType
import org.hisp.dhis.android.core.common.ObjectWithUid
import org.hisp.dhis.android.core.common.RelativePeriod
import org.hisp.dhis.android.core.enrollment.internal.EnrollmentStoreImpl
import org.hisp.dhis.android.core.event.internal.EventStoreImpl
import org.hisp.dhis.android.core.program.AnalyticsPeriodBoundary
import org.hisp.dhis.android.core.program.AnalyticsPeriodBoundaryType
import org.hisp.dhis.android.core.program.ProgramIndicator
import org.hisp.dhis.android.core.program.programindicatorengine.BaseTrackerDataIntegrationHelper
import org.hisp.dhis.android.core.program.programindicatorengine.BaseTrackerDataIntegrationHelper.Companion.de
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(D2JunitRunner::class)
internal class ProgramIndicatorEvaluatorIntegrationShould : BaseEvaluatorIntegrationShould() {
private val programIndicatorEvaluator = ProgramIndicatorEvaluator(
EventStoreImpl.create(databaseAdapter),
EnrollmentStoreImpl.create(databaseAdapter),
d2.programModule().programIndicatorEngine()
)
private val helper = BaseTrackerDataIntegrationHelper(databaseAdapter)
@Test
fun should_aggregate_data_from_multiple_teis() {
createSampleData()
val valueSum = evaluateIndicator(
setProgramIndicator(
expression = de(programStage1.uid(), dataElement1.uid())
)
)
assertThat(valueSum).isEqualTo("30.0")
val valueAvg = evaluateIndicator(
setProgramIndicator(
expression = de(programStage1.uid(), dataElement1.uid()),
aggregationType = AggregationType.AVERAGE
)
)
assertThat(valueAvg).isEqualTo("15.0")
}
@Test
fun should_override_aggregation_type() {
createSampleData()
val defaultValue = evaluateIndicator(
setProgramIndicator(
expression = de(programStage1.uid(), dataElement1.uid())
)
)
assertThat(defaultValue).isEqualTo("30.0")
val overrideValue = evaluateIndicator(
setProgramIndicator(
expression = de(programStage1.uid(), dataElement1.uid())
),
overrideAggregationType = AggregationType.AVERAGE
)
assertThat(overrideValue).isEqualTo("15.0")
}
private fun createSampleData() {
helper.createTrackedEntity(trackedEntity1.uid(), orgunitChild1.uid(), trackedEntityType.uid())
val enrollment1 = generator.generate()
helper.createEnrollment(trackedEntity1.uid(), enrollment1, program.uid(), orgunitChild1.uid())
val event1 = generator.generate()
helper.createTrackerEvent(
event1, enrollment1, program.uid(), programStage1.uid(), orgunitChild1.uid(),
eventDate = day20191101
)
helper.createTrackedEntity(trackedEntity2.uid(), orgunitChild1.uid(), trackedEntityType.uid())
val enrollment2 = generator.generate()
helper.createEnrollment(trackedEntity2.uid(), enrollment2, program.uid(), orgunitChild1.uid())
val event2 = generator.generate()
helper.createTrackerEvent(
event2, enrollment2, program.uid(), programStage1.uid(), orgunitChild1.uid(),
eventDate = day20191101
)
helper.insertTrackedEntityDataValue(event1, dataElement1.uid(), "10")
helper.insertTrackedEntityDataValue(event2, dataElement1.uid(), "20")
}
private fun evaluateIndicator(
programIndicator: ProgramIndicator,
overrideAggregationType: AggregationType = AggregationType.DEFAULT
): String? {
val evaluationItemSum = AnalyticsServiceEvaluationItem(
dimensionItems = listOf(
DimensionItem.DataItem.ProgramIndicatorItem(programIndicator.uid())
),
filters = listOf(
DimensionItem.OrganisationUnitItem.Absolute(BaseEvaluatorSamples.orgunitParent.uid()),
DimensionItem.PeriodItem.Relative(RelativePeriod.LAST_MONTH)
),
aggregationType = overrideAggregationType
)
return programIndicatorEvaluator.evaluate(
evaluationItemSum,
metadata + (programIndicator.uid() to MetadataItem.ProgramIndicatorItem(programIndicator))
)
}
private fun setProgramIndicator(
expression: String,
filter: String? = null,
analyticsType: AnalyticsType? = AnalyticsType.EVENT,
aggregationType: AggregationType? = AggregationType.SUM
): ProgramIndicator {
val boundaryTarget = if (analyticsType == AnalyticsType.EVENT) {
"EVENT_DATE"
} else {
"ENROLLMENT_DATE"
}
val boundaries = listOf(
AnalyticsPeriodBoundary.builder()
.boundaryTarget(boundaryTarget)
.analyticsPeriodBoundaryType(AnalyticsPeriodBoundaryType.AFTER_START_OF_REPORTING_PERIOD)
.build(),
AnalyticsPeriodBoundary.builder()
.boundaryTarget(boundaryTarget)
.analyticsPeriodBoundaryType(AnalyticsPeriodBoundaryType.BEFORE_END_OF_REPORTING_PERIOD)
.build()
)
val programIndicator = ProgramIndicator.builder()
.uid(generator.generate())
.displayName("Program indicator")
.program(ObjectWithUid.create(program.uid()))
.aggregationType(aggregationType)
.analyticsType(analyticsType)
.expression(expression)
.filter(filter)
.analyticsPeriodBoundaries(boundaries)
.build()
helper.setProgramIndicator(programIndicator)
return programIndicator
}
}
| bsd-3-clause | 73130cfa0f3cef9268714768bfe51fa6 | 45.547368 | 112 | 0.723428 | 4.830147 | false | false | false | false |
mdanielwork/intellij-community | plugins/devkit/devkit-core/src/inspections/ComponentModuleRegistrationChecker.kt | 5 | 9236 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("ComponentModuleRegistrationChecker")
package org.jetbrains.idea.devkit.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.UsageSearchContext
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.xml.XmlFile
import com.intellij.psi.xml.XmlTag
import com.intellij.util.xml.DomElement
import com.intellij.util.xml.DomUtil
import com.intellij.util.xml.highlighting.DomElementAnnotationHolder
import com.siyeh.ig.psiutils.TypeUtils
import org.jetbrains.annotations.Nls
import org.jetbrains.idea.devkit.dom.Extension
import org.jetbrains.idea.devkit.dom.ExtensionPoint
import org.jetbrains.idea.devkit.dom.impl.PluginPsiClassConverter
import org.jetbrains.idea.devkit.util.PsiUtil
import org.jetbrains.jps.model.serialization.PathMacroUtil
fun checkProperModule(extensionPoint: ExtensionPoint, holder: DomElementAnnotationHolder, ignoreClassList: List<String>) {
val interfacePsiClass = extensionPoint.`interface`.value
if (shouldCheckExtensionPointClassAttribute(interfacePsiClass) &&
checkProperXmlFileForClass(extensionPoint, holder, interfacePsiClass, ignoreClassList)) {
return
}
val beanClassPsiClass = extensionPoint.beanClass.value
if (shouldCheckExtensionPointClassAttribute(beanClassPsiClass) &&
checkProperXmlFileForClass(extensionPoint, holder, beanClassPsiClass, ignoreClassList)) {
return
}
for (withElement in extensionPoint.withElements) {
if (checkProperXmlFileForClass(extensionPoint, holder, withElement.implements.value, ignoreClassList)) return
}
val shortName = extensionPoint.effectiveQualifiedName.substringAfterLast('.')
val module = extensionPoint.module
val project = module!!.project
val psiSearchHelper = PsiSearchHelper.getInstance(project)
val scope = GlobalSearchScope.projectScope(project)
if (psiSearchHelper.isCheapEnoughToSearch(shortName, scope, null, null) == PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES) {
var epRegistration: Module? = null
psiSearchHelper.processElementsWithWord(
{ element, _ ->
epRegistration = getRegisteringModule(element)
epRegistration == null
},
scope,
shortName,
UsageSearchContext.IN_STRINGS,
true,
false)
epRegistration?.let { checkProperXmlFileForDefinition(extensionPoint, holder, it) }
}
}
private fun getRegisteringModule(element: PsiElement): Module? {
val epName = PsiTreeUtil.getParentOfType(element, PsiField::class.java) ?: return null
val psiClass = (epName.type as? PsiClassType)?.resolve() ?: return null
if (psiClass.qualifiedName == "com.intellij.openapi.extensions.ExtensionPointName") {
return ModuleUtilCore.findModuleForPsiElement(epName)
}
return null
}
fun checkProperXmlFileForExtension(element: Extension,
holder: DomElementAnnotationHolder,
ignoreClassList: List<String>) {
for (attributeDescription in element.genericInfo.attributeChildrenDescriptions) {
val attributeName = attributeDescription.name
if (attributeName == "interfaceClass" || attributeName == "serviceInterface" || attributeName == "forClass") continue
val attributeValue = attributeDescription.getDomAttributeValue(element)
if (attributeValue == null || !DomUtil.hasXml(attributeValue)) continue
if (attributeValue.converter is PluginPsiClassConverter) {
val psiClass = attributeValue.value as PsiClass? ?: continue
if (checkProperXmlFileForClass(element, holder, psiClass, ignoreClassList)) return
}
}
for (childDescription in element.genericInfo.fixedChildrenDescriptions) {
val domElement = childDescription.getValues(element).firstOrNull() ?: continue
val tag = domElement.xmlTag ?: continue
val project = tag.project
val psiClass = JavaPsiFacade.getInstance(project).findClass(tag.value.text, GlobalSearchScope.projectScope(project))
if (psiClass != null && checkProperXmlFileForClass(element, holder, psiClass, ignoreClassList)) return
}
}
private fun shouldCheckExtensionPointClassAttribute(psiClass: PsiClass?): Boolean {
psiClass?.fields?.forEach { field ->
if (TypeUtils.typeEquals(ExtensionPointName::class.java.canonicalName, field.type)) return true
}
return false
}
fun checkProperXmlFileForClass(element: DomElement,
holder: DomElementAnnotationHolder,
psiClass: PsiClass?,
ignoreClassList : List<String>): Boolean {
if (ignoreClassList.contains(psiClass?.qualifiedName)) return false
val definingModule = psiClass?.let { ModuleUtilCore.findModuleForPsiElement(it) } ?: return false
return checkProperXmlFileForDefinition(element, holder, definingModule)
}
private fun checkProperXmlFileForDefinition(element: DomElement,
holder: DomElementAnnotationHolder,
definingModule: Module): Boolean {
var definingModule = definingModule
var modulePluginXmlFile = findModulePluginXmlFile(definingModule)
if (modulePluginXmlFile == null) {
val implModule = findMatchingImplModule(definingModule)
if (implModule != null) {
definingModule = implModule
modulePluginXmlFile = findModulePluginXmlFile(implModule)
}
}
if (modulePluginXmlFile != null && element.module !== definingModule) {
holder.createProblem(element, ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
"Element should be registered in ${modulePluginXmlFile.name}", null,
MoveRegistrationQuickFix(definingModule, modulePluginXmlFile.name))
return true
}
return false
}
fun isIdeaPlatformModule(module: Module?): Boolean {
if (ApplicationManager.getApplication().isUnitTestMode) {
return true
}
if (module == null || !PsiUtil.isIdeaProject(module.project)) {
return false
}
val contentRoots = ModuleRootManager.getInstance(module).contentRoots
if (contentRoots.isEmpty()) return false
var parent: VirtualFile? = contentRoots[0].parent
while (parent != null) {
if (parent.name == "plugins") {
return false
}
if (parent.findChild(PathMacroUtil.DIRECTORY_STORE_NAME) != null) {
return true
}
parent = parent.parent
}
return true
}
private fun findMatchingImplModule(module: Module): Module? {
return ModuleManager.getInstance(module.project).findModuleByName(module.name + ".impl")
}
private fun findModulePluginXmlFile(module: Module): XmlFile? {
for (sourceRoot in ModuleRootManager.getInstance(module).sourceRoots) {
val metaInf = sourceRoot.findChild("META-INF")
if (metaInf != null && metaInf.isDirectory) {
for (file in metaInf.children) {
if (file.name.endsWith("Plugin.xml")) {
val psiFile = PsiManager.getInstance(module.project).findFile(file)
if (psiFile is XmlFile) {
return psiFile
}
}
}
}
}
return null
}
class MoveRegistrationQuickFix(private val myTargetModule: Module,
private val myTargetFileName: String) : LocalQuickFix {
@Nls
override fun getName(): String = "Move registration to " + myTargetFileName
@Nls
override fun getFamilyName(): String = "Move registration to correct module"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val tag = PsiTreeUtil.getParentOfType(descriptor.psiElement, XmlTag::class.java, false) ?: return
val parentTag = tag.parentTag ?: return
val targetFile = findModulePluginXmlFile(myTargetModule) ?: return
val rootTag = targetFile.rootTag ?: return
val subTags = rootTag.findSubTags(tag.parentTag!!.name)
val newParentTag = subTags.firstOrNull()
?: rootTag.addSubTag(rootTag.createChildTag(parentTag.localName, "", null, false), false)
.apply {
for (attribute in parentTag.attributes) {
setAttribute(attribute.name, attribute.value)
}
}
val anchor = newParentTag.subTags.lastOrNull { it.name == tag.name }
val newTag = anchor?.let { newParentTag.addAfter(tag, anchor) } ?: newParentTag.addSubTag(tag, false)
tag.delete()
(newTag as? Navigatable)?.navigate(true)
}
}
| apache-2.0 | a8591a96a0540259e52739f9248866fb | 41.173516 | 140 | 0.727588 | 4.822977 | false | false | false | false |
mdanielwork/intellij-community | python/src/com/jetbrains/python/console/PythonConsoleClientUtil.kt | 4 | 3830 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("PythonConsoleClientUtil")
package com.jetbrains.python.console
import com.intellij.util.ConcurrencyUtil
import com.jetbrains.python.console.protocol.PythonConsoleBackendService
import java.lang.reflect.InvocationHandler
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.Callable
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
private const val PYTHON_CONSOLE_COMMAND_THREAD_FACTORY_NAME: String = "Python Console Command Executor"
fun synchronizedPythonConsoleClient(loader: ClassLoader,
delegate: PythonConsoleBackendService.Iface,
pythonConsoleProcess: Process): PythonConsoleBackendServiceDisposable {
val executorService = ConcurrencyUtil.newSingleThreadExecutor(PYTHON_CONSOLE_COMMAND_THREAD_FACTORY_NAME)
// make the `PythonConsoleBackendService.Iface` process-aware and thread-safe
val proxy = Proxy.newProxyInstance(loader, arrayOf<Class<*>>(
PythonConsoleBackendService.Iface::class.java),
InvocationHandler { _, method, args ->
// we evaluate the original method in the other thread in order to control it
val future = executorService.submit(Callable {
return@Callable invokeOriginalMethod(args, method, delegate)
})
while (true) {
try {
return@InvocationHandler future.get(10L, TimeUnit.MILLISECONDS)
}
catch (e: TimeoutException) {
if (!pythonConsoleProcess.isAlive) {
val exitValue = pythonConsoleProcess.exitValue()
throw PyConsoleProcessFinishedException(exitValue)
}
// continue waiting for the end of the operation execution
}
catch (e: ExecutionException) {
if (!pythonConsoleProcess.isAlive) {
val exitValue = pythonConsoleProcess.exitValue()
throw PyConsoleProcessFinishedException(exitValue)
}
throw e.cause ?: e
}
}
}) as PythonConsoleBackendService.Iface
// make the `proxy` disposable
return object : PythonConsoleBackendServiceDisposable, PythonConsoleBackendService.Iface by proxy {
override fun dispose() {
executorService.shutdownNow()
try {
while (!executorService.awaitTermination(1L, TimeUnit.SECONDS)) Unit
}
catch (e: InterruptedException) {
Thread.currentThread().interrupt()
}
}
}
}
private fun invokeOriginalMethod(args: Array<out Any>?, method: Method, delegate: Any): Any? {
return try {
if (args != null) {
method.invoke(delegate, *args)
}
else {
method.invoke(delegate)
}
}
catch (e: InvocationTargetException) {
throw e.cause ?: e
}
} | apache-2.0 | 68dae34313fc54a5a5247ebce8098467 | 48.115385 | 140 | 0.551436 | 6.383333 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinSourceSetDataService.kt | 1 | 13463 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.externalSystem.service.project.manage.SourceFolderManager
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExportableOrderEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.idea.base.platforms.tooling.tooling
import org.jetbrains.kotlin.idea.facet.*
import org.jetbrains.kotlin.idea.gradle.configuration.KotlinSourceSetInfo
import org.jetbrains.kotlin.idea.gradle.configuration.findChildModuleById
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinAndroidSourceSets
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinSourceSetData
import org.jetbrains.kotlin.idea.gradleJava.KotlinGradleFacadeImpl
import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation
import org.jetbrains.kotlin.idea.projectModel.KotlinComponent
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform
import org.jetbrains.kotlin.idea.projectModel.KotlinSourceSet
import org.jetbrains.kotlin.idea.roots.migrateNonJvmSourceFolders
import org.jetbrains.kotlin.idea.roots.pathAsUrl
import org.jetbrains.kotlin.platform.IdePlatformKind
import org.jetbrains.kotlin.platform.SimplePlatform
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.platform.js.JsPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.platform.konan.NativePlatform
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.util.GradleConstants
class KotlinSourceSetDataService : AbstractProjectDataService<GradleSourceSetData, Void>() {
override fun getTargetDataKey() = GradleSourceSetData.KEY
private fun getProjectPlatforms(toImport: MutableCollection<out DataNode<GradleSourceSetData>>): List<KotlinPlatform> {
val platforms = HashSet<KotlinPlatform>()
for (nodeToImport in toImport) {
nodeToImport.kotlinSourceSetData?.sourceSetInfo?.also {
platforms += it.actualPlatforms.platforms
}
if (nodeToImport.parent?.children?.any { it.key.dataType.contains("Android") } == true) {
platforms += KotlinPlatform.ANDROID
}
}
return platforms.toList()
}
override fun postProcess(
toImport: MutableCollection<out DataNode<GradleSourceSetData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
val projectPlatforms = getProjectPlatforms(toImport)
for (nodeToImport in toImport) {
val mainModuleData = ExternalSystemApiUtil.findParent(
nodeToImport,
ProjectKeys.MODULE
) ?: continue
val sourceSetData = nodeToImport.data
val kotlinSourceSet = nodeToImport.kotlinSourceSetData?.sourceSetInfo ?: continue
val ideModule = modelsProvider.findIdeModule(sourceSetData) ?: continue
val platform = kotlinSourceSet.actualPlatforms
val rootModel = modelsProvider.getModifiableRootModel(ideModule)
if (platform.platforms.any { it != KotlinPlatform.JVM && it != KotlinPlatform.ANDROID }) {
migrateNonJvmSourceFolders(rootModel)
populateNonJvmSourceRootTypes(nodeToImport, ideModule)
}
configureFacet(sourceSetData, kotlinSourceSet, mainModuleData, ideModule, modelsProvider, projectPlatforms).let { facet ->
GradleProjectImportHandler.getInstances(project).forEach { it.importBySourceSet(facet, nodeToImport) }
}
if (kotlinSourceSet.isTestModule) {
assignTestScope(rootModel)
}
}
}
private fun assignTestScope(rootModel: ModifiableRootModel) {
rootModel
.orderEntries
.asSequence()
.filterIsInstance<ExportableOrderEntry>()
.filter { it.scope == DependencyScope.COMPILE }
.forEach { it.scope = DependencyScope.TEST }
}
companion object {
private val KotlinComponent.kind
get() = when (this) {
is KotlinCompilation -> KotlinModuleKind.COMPILATION_AND_SOURCE_SET_HOLDER
is KotlinSourceSet -> KotlinModuleKind.SOURCE_SET_HOLDER
else -> KotlinModuleKind.DEFAULT
}
private fun SimplePlatform.isRelevantFor(projectPlatforms: List<KotlinPlatform>): Boolean {
val jvmPlatforms = listOf(KotlinPlatform.ANDROID, KotlinPlatform.JVM, KotlinPlatform.COMMON)
return when (this) {
is JvmPlatform -> projectPlatforms.intersect(jvmPlatforms).isNotEmpty()
is JsPlatform -> KotlinPlatform.JS in projectPlatforms
is NativePlatform -> KotlinPlatform.NATIVE in projectPlatforms
else -> true
}
}
private fun IdePlatformKind.toSimplePlatforms(
moduleData: ModuleData,
isHmppModule: Boolean,
projectPlatforms: List<KotlinPlatform>
): Collection<SimplePlatform> {
if (this is JvmIdePlatformKind) {
val jvmTarget = JvmTarget.fromString(moduleData.targetCompatibility ?: "") ?: JvmTarget.DEFAULT
return JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget)
}
if (this is NativeIdePlatformKind) {
return NativePlatforms.nativePlatformByTargetNames(moduleData.konanTargets)
}
return if (isHmppModule) {
this.defaultPlatform.filter { it.isRelevantFor(projectPlatforms) }
} else {
this.defaultPlatform
}
}
fun configureFacet(
moduleData: ModuleData,
kotlinSourceSet: KotlinSourceSetInfo,
mainModuleNode: DataNode<ModuleData>,
ideModule: Module,
modelsProvider: IdeModifiableModelsProvider
) {
// TODO Review this code after AS Chipmunk released and merged to master
// In https://android.googlesource.com/platform/tools/adt/idea/+/ab31cd294775b7914ddefbe417a828b5c18acc81%5E%21/#F1
// creation of KotlinAndroidSourceSetData node was dropped, all tasks must be stored in corresponding KotlinSourceSetData nodes
val additionalRunTasks = mainModuleNode.kotlinAndroidSourceSets
?.filter { it.isTestModule }
?.flatMap { it.externalSystemRunTasks }
?.toSet()
configureFacet(
moduleData,
kotlinSourceSet,
mainModuleNode,
ideModule,
modelsProvider,
enumValues<KotlinPlatform>().toList(),
additionalRunTasks
)
}
@OptIn(ExperimentalStdlibApi::class)
fun configureFacet(
moduleData: ModuleData,
kotlinSourceSet: KotlinSourceSetInfo,
mainModuleNode: DataNode<ModuleData>,
ideModule: Module,
modelsProvider: IdeModifiableModelsProvider,
projectPlatforms: List<KotlinPlatform>,
additionalRunTasks: Collection<ExternalSystemRunTask>? = null
): KotlinFacet {
val compilerVersion = KotlinGradleFacadeImpl.findKotlinPluginVersion(mainModuleNode)
// ?: return null TODO: Fix in CLion or our plugin KT-27623
val platformKinds = kotlinSourceSet.actualPlatforms.platforms //TODO(auskov): fix calculation of jvm target
.map { it.tooling.kind }
.flatMap { it.toSimplePlatforms(moduleData, mainModuleNode.kotlinGradleProjectDataOrFail.isHmpp, projectPlatforms) }
.distinct()
.toSet()
val platform = TargetPlatform(platformKinds)
val compilerArguments = kotlinSourceSet.lazyCompilerArguments?.value
// Used ID is the same as used in org/jetbrains/kotlin/idea/configuration/KotlinGradleSourceSetDataService.kt:280
// because this DataService was separated from KotlinGradleSourceSetDataService for MPP projects only
val id = if (compilerArguments?.multiPlatform == true) GradleConstants.SYSTEM_ID.id else null
val kotlinFacet = ideModule.getOrCreateFacet(modelsProvider, false, id)
val kotlinGradleProjectData = mainModuleNode.kotlinGradleProjectDataOrFail
kotlinFacet.configureFacet(
compilerVersion = compilerVersion,
platform = platform,
modelsProvider = modelsProvider,
hmppEnabled = kotlinGradleProjectData.isHmpp,
pureKotlinSourceFolders = if (platform.isJvm()) kotlinGradleProjectData.pureKotlinSourceFolders.toList() else emptyList(),
dependsOnList = kotlinSourceSet.dependsOn,
additionalVisibleModuleNames = kotlinSourceSet.additionalVisible
)
val defaultCompilerArguments = kotlinSourceSet.lazyDefaultCompilerArguments?.value
if (compilerArguments != null) {
applyCompilerArgumentsToFacet(
compilerArguments,
defaultCompilerArguments,
kotlinFacet,
modelsProvider
)
}
adjustClasspath(kotlinFacet, kotlinSourceSet.lazyDependencyClasspath.value)
kotlinFacet.noVersionAutoAdvance()
with(kotlinFacet.configuration.settings) {
kind = kotlinSourceSet.kotlinComponent.kind
isTestModule = kotlinSourceSet.isTestModule
externalSystemRunTasks = buildList {
addAll(kotlinSourceSet.externalSystemRunTasks)
additionalRunTasks?.let(::addAll)
}
externalProjectId = kotlinSourceSet.gradleModuleId
sourceSetNames = kotlinSourceSet.sourceSetIdsByName.values.mapNotNull { sourceSetId ->
val node = mainModuleNode.findChildModuleById(sourceSetId) ?: return@mapNotNull null
val data = node.data as? ModuleData ?: return@mapNotNull null
modelsProvider.findIdeModule(data)?.name
}
if (kotlinSourceSet.isTestModule) {
testOutputPath = (kotlinSourceSet.lazyCompilerArguments?.value as? K2JSCompilerArguments)?.outputFile
productionOutputPath = null
} else {
productionOutputPath = (kotlinSourceSet.lazyCompilerArguments?.value as? K2JSCompilerArguments)?.outputFile
testOutputPath = null
}
}
return kotlinFacet
}
}
}
private const val KOTLIN_NATIVE_TARGETS_PROPERTY = "konanTargets"
var ModuleData.konanTargets: Set<String>
get() {
val value = getProperty(KOTLIN_NATIVE_TARGETS_PROPERTY) ?: return emptySet()
return if (value.isNotEmpty()) value.split(',').toSet() else emptySet()
}
set(value) = setProperty(KOTLIN_NATIVE_TARGETS_PROPERTY, value.takeIf { it.isNotEmpty() }?.joinToString(","))
private fun populateNonJvmSourceRootTypes(sourceSetNode: DataNode<GradleSourceSetData>, module: Module) {
val sourceFolderManager = SourceFolderManager.getInstance(module.project)
val contentRootDataNodes = ExternalSystemApiUtil.findAll(sourceSetNode, ProjectKeys.CONTENT_ROOT)
val contentRootDataList = contentRootDataNodes.mapNotNull { it.data }
if (contentRootDataList.isEmpty()) return
val externalToKotlinSourceTypes = mapOf(
ExternalSystemSourceType.SOURCE to SourceKotlinRootType,
ExternalSystemSourceType.TEST to TestSourceKotlinRootType
)
externalToKotlinSourceTypes.forEach { (externalType, kotlinType) ->
val sourcesRoots = contentRootDataList.flatMap { it.getPaths(externalType) }
sourcesRoots.forEach {
if (!FileUtil.exists(it.path)) {
sourceFolderManager.addSourceFolder(module, it.pathAsUrl, kotlinType)
}
}
}
} | apache-2.0 | a82bdbbac83d6d300c42046a59b0195d | 46.076923 | 139 | 0.688925 | 5.738704 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/GroovyMapPropertyImpl.kt | 9 | 1738 | // 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.plugins.groovy.lang.resolve.impl
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.JAVA_UTIL_MAP
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.util.recursionSafeLazy
import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyMapProperty
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyPropertyBase
/**
* @param name name of a key in a map
* @param context element to obtain project and resolve scope
*/
class GroovyMapPropertyImpl(
private val type: PsiClassType,
name: String,
context: PsiElement
) : GroovyPropertyBase(name, context), GroovyMapProperty {
private val scope = context.resolveScope
override fun isValid(): Boolean = type.isValid
private fun computePropertyType(): PsiType? {
if (type is GrMapType) {
val typeByKey = type.getTypeByStringKey(name)
if (typeByKey != null) {
return typeByKey
}
}
val clazz = type.resolve() ?: return null
val mapClass = JavaPsiFacade.getInstance(project).findClass(JAVA_UTIL_MAP, scope) ?: return null
if (mapClass.typeParameters.size != 2) return null
val mapSubstitutor = TypeConversionUtil.getClassSubstitutor(mapClass, clazz, PsiSubstitutor.EMPTY)
return mapSubstitutor?.substitute(mapClass.typeParameters[1])
}
private val myPropertyType by recursionSafeLazy(initializer = ::computePropertyType)
override fun getPropertyType(): PsiType? = myPropertyType
override fun toString(): String = "Groovy Map Property"
}
| apache-2.0 | 023b6a9d18691b7c1aeb638504a42e19 | 37.622222 | 158 | 0.764672 | 4.259804 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/itemviewholder/ItemViewHolderActions.kt | 1 | 11896 | package jp.juggler.subwaytooter.itemviewholder
import android.app.AlertDialog
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.EditText
import android.widget.TextView
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.ActMediaViewer
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.action.*
import jp.juggler.subwaytooter.actmain.nextPosition
import jp.juggler.subwaytooter.api.entity.*
import jp.juggler.subwaytooter.column.Column
import jp.juggler.subwaytooter.column.startGap
import jp.juggler.subwaytooter.pref.PrefB
import jp.juggler.subwaytooter.table.ContentWarning
import jp.juggler.subwaytooter.table.MediaShown
import jp.juggler.subwaytooter.util.openCustomTab
import jp.juggler.subwaytooter.view.MyTextView
import jp.juggler.util.*
val defaultBoostedAction: ItemViewHolder.() -> Unit = {
val pos = activity.nextPosition(column)
val notification = (item as? TootNotification)
boostAccount?.let { whoRef ->
if (accessInfo.isPseudo) {
DlgContextMenu(activity, column, whoRef, null, notification, tvContent).show()
} else {
activity.userProfileLocal(pos, accessInfo, whoRef.get())
}
}
}
fun ItemViewHolder.onClickImpl(v: View?) {
v ?: return
val pos = activity.nextPosition(column)
val item = this.item
with(activity) {
when (v) {
btnHideMedia, btnCardImageHide -> showHideMediaViews(false)
btnShowMedia, btnCardImageShow -> showHideMediaViews(true)
btnContentWarning -> toggleContentWarning()
ivAvatar -> clickAvatar(pos)
llBoosted -> boostedAction()
llReply -> clickReplyInfo(pos, accessInfo, column.type, statusReply, statusShowing)
llFollow -> clickFollowInfo(pos, accessInfo, followAccount) { whoRef ->
DlgContextMenu(
this,
column,
whoRef,
null,
(item as? TootNotification),
tvContent
).show()
}
btnFollow -> clickFollowInfo(
pos,
accessInfo,
followAccount,
forceMenu = true
) { whoRef ->
DlgContextMenu(
this,
column,
whoRef,
null,
(item as? TootNotification),
tvContent
).show()
}
btnGapHead -> column.startGap(item.cast(), isHead = true)
btnGapTail -> column.startGap(item.cast(), isHead = false)
btnSearchTag, llTrendTag -> clickTag(pos, item)
btnListTL -> clickListTl(pos, accessInfo, item)
btnListMore -> clickListMoreButton(pos, accessInfo, item)
btnFollowRequestAccept -> clickFollowRequestAccept(
accessInfo,
followAccount,
accept = true
)
btnFollowRequestDeny -> clickFollowRequestAccept(
accessInfo,
followAccount,
accept = false
)
llFilter -> openFilterMenu(accessInfo, item.cast())
ivCardImage -> clickCardImage(pos, accessInfo, statusShowing?.card)
llConversationIcons -> clickConversation(
pos,
accessInfo,
listAdapter,
summary = item.cast()
)
else -> {
ivMediaThumbnails.indexOfFirst { it == v }
.takeIf { it >= 0 }?.let {
clickMedia(it)
return
}
tvMediaDescriptions.find { it == v }?.let {
clickMediaDescription(it)
return
}
}
}
}
}
fun ItemViewHolder.onLongClickImpl(v: View?): Boolean {
v ?: return false
with(activity) {
val pos = activity.nextPosition(column)
when (v) {
ivAvatar ->
clickAvatar(pos, longClick = true)
llBoosted ->
longClickBoostedInfo(boostAccount)
llReply ->
clickReplyInfo(
pos,
accessInfo,
column.type,
statusReply,
statusShowing,
longClick = true
) { status ->
DlgContextMenu(
this,
column,
status.accountRef,
status,
item.cast(),
tvContent
).show()
}
llFollow ->
followAccount?.let {
DlgContextMenu(activity, column, it, null, item.cast(), tvContent).show()
}
btnFollow ->
followAccount?.get()?.let { followFromAnotherAccount(pos, accessInfo, it) }
ivCardImage ->
clickCardImage(pos, accessInfo, statusShowing?.card, longClick = true)
btnSearchTag, llTrendTag ->
longClickTag(pos, item)
else ->
return false
}
}
return true
}
private fun ItemViewHolder.longClickBoostedInfo(who: TootAccountRef?) {
who ?: return
DlgContextMenu(activity, column, who, null, item.cast(), tvContent).show()
}
private fun ItemViewHolder.longClickTag(pos: Int, item: TimelineItem?): Boolean {
when (item) {
// is TootGap -> column.startGap(item)
//
// is TootDomainBlock -> {
// val domain = item.domain
// AlertDialog.Builder(activity)
// .setMessage(activity.getString(R.string.confirm_unblock_domain, domain))
// .setNegativeButton(R.string.cancel, null)
// .setPositiveButton(R.string.ok) { _, _ -> Action_Instance.blockDomain(activity, access_info, domain, false) }
// .show()
// }
is TootTag -> activity.longClickTootTag(pos, accessInfo, item)
}
return true
}
private fun ItemViewHolder.clickMedia(i: Int) {
try {
val mediaAttachments =
statusShowing?.media_attachments ?: (item as? TootScheduled)?.mediaAttachments
?: return
when (val item = if (i < mediaAttachments.size) mediaAttachments[i] else return) {
is TootAttachmentMSP -> {
// マストドン検索ポータルのデータではmedia_attachmentsが簡略化されている
// 会話の流れを表示する
activity.conversationOtherInstance(
activity.nextPosition(column),
statusShowing
)
}
is TootAttachment -> when {
// unknownが1枚だけなら内蔵ビューアを使わずにインテントを投げる
item.type == TootAttachmentType.Unknown && mediaAttachments.size == 1 -> {
// https://github.com/tateisu/SubwayTooter/pull/119
// メディアタイプがunknownの場合、そのほとんどはリモートから来たURLである
// PrefB.bpPriorLocalURL の状態に関わらずリモートURLがあればそれをブラウザで開く
when (val remoteUrl = item.remote_url.notEmpty()) {
null -> activity.openCustomTab(item)
else -> activity.openCustomTab(remoteUrl)
}
}
// 内蔵メディアビューアを使う
PrefB.bpUseInternalMediaViewer() ->
ActMediaViewer.open(
activity,
column.showMediaDescription,
when (accessInfo.isMisskey) {
true -> ServiceType.MISSKEY
else -> ServiceType.MASTODON
},
mediaAttachments,
i
)
// ブラウザで開く
else -> activity.openCustomTab(item)
}
}
} catch (ex: Throwable) {
ItemViewHolder.log.trace(ex)
}
}
private fun ItemViewHolder.clickMediaDescription(tv: View) {
val desc = tv.getTag(R.id.text)
?.cast<CharSequence>()
?: return
AlertDialog.Builder(activity)
.setMessage(desc.toString().ellipsizeDot3(2000))
.setPositiveButton(R.string.ok, null)
.setNeutralButton(android.R.string.copy) { _, _ ->
desc.copyToClipboard(activity)
}
.show()
}
private fun ItemViewHolder.showHideMediaViews(show: Boolean) {
llMedia.vg(show)
llCardImage.vg(show)
btnShowMedia.vg(!show)
btnCardImageShow.vg(!show)
statusShowing?.let { MediaShown.save(it, show) }
item.cast<TootScheduled>()?.let { MediaShown.save(it.uri, show) }
}
private fun ItemViewHolder.toggleContentWarning() {
// トグル動作
val show = llContents.visibility == View.GONE
statusShowing?.let { ContentWarning.save(it, show) }
item.cast<TootScheduled>()?.let { ContentWarning.save(it.uri, show) }
// 1個だけ開閉するのではなく、例えば通知TLにある複数の要素をまとめて開閉するなどある
listAdapter.notifyChange(reason = "ContentWarning onClick", reset = true)
}
private fun ItemViewHolder.clickAvatar(pos: Int, longClick: Boolean = false) {
statusAccount?.let { whoRef ->
when {
longClick || accessInfo.isNA ->
DlgContextMenu(activity, column, whoRef, null, item.cast(), tvContent).show()
// 2018/12/26 疑似アカウントでもプロフカラムを表示する https://github.com/tootsuite/mastodon/commit/108b2139cd87321f6c0aec63ef93db85ce30bfec
else -> activity.userProfileLocal(pos, accessInfo, whoRef.get())
}
}
}
private fun ItemViewHolder.clickTag(pos: Int, item: TimelineItem?) {
with(activity) {
when (item) {
is TootTag -> when (item.type) {
TootTag.TagType.Tag ->
tagDialog(
accessInfo,
pos,
item.url!!,
accessInfo.apiHost,
item.name,
tagInfo = item,
)
TootTag.TagType.Link ->
openCustomTab(item.url)
}
is TootSearchGap -> column.startGap(item, isHead = true)
is TootConversationSummary -> clickConversation(
pos,
accessInfo,
listAdapter,
summary = item
)
is TootGap -> clickTootGap(column, item)
is TootDomainBlock -> clickDomainBlock(accessInfo, item)
is TootScheduled -> clickScheduledToot(accessInfo, item, column)
}
}
}
fun ActMain.clickTootGap(column: Column, item: TootGap) {
when {
column.type.gapDirection(column, true) -> column.startGap(item, isHead = true)
column.type.gapDirection(column, false) -> column.startGap(item, isHead = false)
else -> showToast(true, "This column can't support gap reading.")
}
}
| apache-2.0 | 058c1d3bbbf1ab16bde08a36c1354d72 | 33.578947 | 132 | 0.527758 | 4.643232 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/polly/src/main/kotlin/com/kotlin/polly/DescribeVoices.kt | 1 | 1629 | // snippet-sourcedescription:[DescribeVoices.kt produces a list of all voices available for use when requesting speech synthesis with Amazon Polly.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Polly]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.polly
// snippet-start:[polly.kotlin.describe_voice.import]
import aws.sdk.kotlin.services.polly.PollyClient
import aws.sdk.kotlin.services.polly.model.DescribeVoicesRequest
import aws.sdk.kotlin.services.polly.model.LanguageCode
// snippet-end:[polly.kotlin.describe_voice.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() {
describeVoice()
}
// snippet-start:[polly.kotlin.describe_voice.main]
suspend fun describeVoice() {
PollyClient { region = "us-west-2" }.use { polly ->
val enUsVoicesResult = polly.describeVoices(
DescribeVoicesRequest {
languageCode = LanguageCode.fromValue("en-US")
}
)
val voices = enUsVoicesResult.voices
if (voices != null) {
for (voice in voices) {
println("The ID of the voice is ${voice.id}")
println("The gender of the voice is ${voice.gender}")
}
}
}
}
// snippet-end:[polly.kotlin.describe_voice.main]
| apache-2.0 | 0a471856116871112c1d4575ebcf8b49 | 31.9375 | 148 | 0.672805 | 3.897129 | false | false | false | false |
airbnb/epoxy | epoxy-adapter/src/main/java/com/airbnb/epoxy/ModelGroupHolder.kt | 1 | 8928 | package com.airbnb.epoxy
import android.view.View
import android.view.ViewGroup
import android.view.ViewParent
import android.view.ViewStub
import androidx.annotation.VisibleForTesting
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.viewmodeladapter.R
import java.util.ArrayList
class ModelGroupHolder(private val modelGroupParent: ViewParent) : EpoxyHolder() {
val viewHolders = ArrayList<EpoxyViewHolder>(4)
/** Use parent pool or create a local pool */
@VisibleForTesting
val viewPool = findViewPool(modelGroupParent)
/**
* Get the root view group (aka
* [androidx.recyclerview.widget.RecyclerView.ViewHolder.itemView].
* You can override [EpoxyModelGroup.bind] and use this method to make custom
* changes to the root view.
*/
lateinit var rootView: ViewGroup
private set
private lateinit var childContainer: ViewGroup
private lateinit var stubs: List<ViewStubData>
private var boundGroup: EpoxyModelGroup? = null
private fun usingStubs(): Boolean = stubs.isNotEmpty()
override fun bindView(itemView: View) {
if (itemView !is ViewGroup) {
throw IllegalStateException(
"The layout provided to EpoxyModelGroup must be a ViewGroup"
)
}
rootView = itemView
childContainer = findChildContainer(rootView)
stubs = if (childContainer.childCount != 0) {
createViewStubData(childContainer)
} else {
emptyList()
}
}
/**
* By default the outermost viewgroup is used as the container that views are added to. However,
* users can specify a different, nested view group to use as the child container by marking it
* with a special id.
*/
private fun findChildContainer(outermostRoot: ViewGroup): ViewGroup {
val customRoot = outermostRoot.findViewById<View>(R.id.epoxy_model_group_child_container)
return customRoot as? ViewGroup ?: outermostRoot
}
private fun createViewStubData(viewGroup: ViewGroup): List<ViewStubData> {
return ArrayList<ViewStubData>(4).apply {
collectViewStubs(viewGroup, this)
if (isEmpty()) {
throw IllegalStateException(
"No view stubs found. If viewgroup is not empty it must contain ViewStubs."
)
}
}
}
private fun collectViewStubs(
viewGroup: ViewGroup,
stubs: ArrayList<ViewStubData>
) {
for (i in 0 until viewGroup.childCount) {
val child = viewGroup.getChildAt(i)
if (child is ViewGroup) {
collectViewStubs(child, stubs)
} else if (child is ViewStub) {
stubs.add(ViewStubData(viewGroup, child, i))
}
}
}
fun bindGroupIfNeeded(group: EpoxyModelGroup) {
val previouslyBoundGroup = this.boundGroup
if (previouslyBoundGroup === group) {
return
} else if (previouslyBoundGroup != null) {
// A different group is being bound; this can happen when an onscreen model is changed.
// The models or their layouts could have changed, so views may need to be updated
if (previouslyBoundGroup.models.size > group.models.size) {
for (i in previouslyBoundGroup.models.size - 1 downTo group.models.size) {
removeAndRecycleView(i)
}
}
}
this.boundGroup = group
val models = group.models
val modelCount = models.size
if (usingStubs() && stubs.size < modelCount) {
throw IllegalStateException(
"Insufficient view stubs for EpoxyModelGroup. $modelCount models were provided but only ${stubs.size} view stubs exist."
)
}
viewHolders.ensureCapacity(modelCount)
for (i in 0 until modelCount) {
val model = models[i]
val previouslyBoundModel = previouslyBoundGroup?.models?.getOrNull(i)
val stubData = stubs.getOrNull(i)
val parent = stubData?.viewGroup ?: childContainer
if (previouslyBoundModel != null) {
if (areSameViewType(previouslyBoundModel, model)) {
continue
}
removeAndRecycleView(i)
}
val holder = getViewHolder(parent, model)
if (stubData == null) {
childContainer.addView(holder.itemView, i)
} else {
stubData.setView(holder.itemView, group.useViewStubLayoutParams(model, i))
}
viewHolders.add(i, holder)
}
}
private fun areSameViewType(model1: EpoxyModel<*>, model2: EpoxyModel<*>?): Boolean {
return ViewTypeManager.getViewType(model1) == ViewTypeManager.getViewType(model2)
}
private fun getViewHolder(parent: ViewGroup, model: EpoxyModel<*>): EpoxyViewHolder {
val viewType = ViewTypeManager.getViewType(model)
val recycledView = viewPool.getRecycledView(viewType)
return recycledView as? EpoxyViewHolder
?: HELPER_ADAPTER.createViewHolder(
modelGroupParent,
model,
parent,
viewType
)
}
fun unbindGroup() {
if (boundGroup == null) {
throw IllegalStateException("Group is not bound")
}
repeat(viewHolders.size) {
// Remove from the end for more efficient list actions
removeAndRecycleView(viewHolders.size - 1)
}
boundGroup = null
}
private fun removeAndRecycleView(modelPosition: Int) {
if (usingStubs()) {
stubs[modelPosition].resetStub()
} else {
childContainer.removeViewAt(modelPosition)
}
val viewHolder = viewHolders.removeAt(modelPosition)
viewHolder.unbind()
viewPool.putRecycledView(viewHolder)
}
companion object {
private val HELPER_ADAPTER = HelperAdapter()
private fun findViewPool(view: ViewParent): RecyclerView.RecycledViewPool {
var viewPool: RecyclerView.RecycledViewPool? = null
while (viewPool == null) {
viewPool = if (view is RecyclerView) {
view.recycledViewPool
} else {
val parent = view.parent
if (parent is ViewParent) {
findViewPool(parent)
} else {
// This model group is is not in a RecyclerView
LocalGroupRecycledViewPool()
}
}
}
return viewPool
}
}
}
private class ViewStubData(
val viewGroup: ViewGroup,
val viewStub: ViewStub,
val position: Int
) {
fun setView(view: View, useStubLayoutParams: Boolean) {
removeCurrentView()
// Carry over the stub id manually since we aren't inflating via the stub
val inflatedId = viewStub.inflatedId
if (inflatedId != View.NO_ID) {
view.id = inflatedId
}
if (useStubLayoutParams) {
viewGroup.addView(view, position, viewStub.layoutParams)
} else {
viewGroup.addView(view, position)
}
}
fun resetStub() {
removeCurrentView()
viewGroup.addView(viewStub, position)
}
private fun removeCurrentView() {
val view = viewGroup.getChildAt(position)
?: throw IllegalStateException("No view exists at position $position")
viewGroup.removeView(view)
}
}
/**
* Local pool to the [ModelGroupHolder]
*/
private class LocalGroupRecycledViewPool : RecyclerView.RecycledViewPool()
/**
* A viewholder's viewtype can only be set internally in an adapter when the viewholder
* is created. To work around that we do the creation in an adapter.
*/
private class HelperAdapter : RecyclerView.Adapter<EpoxyViewHolder>() {
private var model: EpoxyModel<*>? = null
private var modelGroupParent: ViewParent? = null
fun createViewHolder(
modelGroupParent: ViewParent,
model: EpoxyModel<*>,
parent: ViewGroup,
viewType: Int
): EpoxyViewHolder {
this.model = model
this.modelGroupParent = modelGroupParent
val viewHolder = createViewHolder(parent, viewType)
this.model = null
this.modelGroupParent = null
return viewHolder
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EpoxyViewHolder {
return EpoxyViewHolder(modelGroupParent, model!!.buildView(parent), model!!.shouldSaveViewState())
}
override fun onBindViewHolder(holder: EpoxyViewHolder, position: Int) {
}
override fun getItemCount() = 1
}
| apache-2.0 | 16cde4881a2c53b7614749c825389214 | 31 | 136 | 0.614695 | 4.973816 | false | false | false | false |
nibarius/opera-park-android | app/src/main/java/se/barsk/park/analytics/AnalyticsEvent.kt | 1 | 598 | package se.barsk.park.analytics
import android.os.Bundle
/**
* Base class for all analytics events
* https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event
* There can be up to 500 different events and each event can have up to 25 unique parameters.
*/
abstract class AnalyticsEvent {
object Param {
const val ACTION = "action"
const val EXCEPTION = "exception"
const val CARS_SHARED = "cars_shared"
const val MESSAGE = "message"
}
val parameters: Bundle = Bundle()
abstract val name: String
} | mit | 7ea6e95ecd005148b0fa2c540ac25d18 | 28.95 | 107 | 0.704013 | 4.241135 | false | false | false | false |
google/intellij-community | build/tasks/src/org/jetbrains/intellij/build/io/process.kt | 1 | 13474 | // 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.intellij.build.io
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.diagnostic.telemetry.use
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.StatusCode
import org.jetbrains.intellij.build.BuildScriptsLoggedError
import org.jetbrains.intellij.build.tracer
import java.io.File
import java.io.InputStream
import java.lang.System.Logger
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* Executes a Java class in a forked JVM.
*/
fun runJava(mainClass: String,
args: Iterable<String>,
jvmArgs: List<String> = emptyList(),
classPath: List<String>,
javaExe: Path,
logger: Logger = System.getLogger(mainClass),
timeoutMillis: Long = Timeout.DEFAULT,
workingDir: Path? = null,
onError: (() -> Unit)? = null) {
val timeout = Timeout(timeoutMillis)
var errorReader: CompletableFuture<Void>? = null
val classpathFile = Files.createTempFile("classpath-", ".txt")
val jvmArgsWithJson = jvmArgs + "-Dintellij.log.to.json.stdout=true"
tracer.spanBuilder("runJava")
.setAttribute("mainClass", mainClass)
.setAttribute(AttributeKey.stringArrayKey("args"), args.toList())
.setAttribute(AttributeKey.stringArrayKey("jvmArgs"), jvmArgsWithJson.toList())
.setAttribute("workingDir", workingDir?.toString() ?: "")
.setAttribute("timeoutMillis", timeoutMillis)
.use { span ->
try {
val classPathStringBuilder = createClassPathFile(classPath, classpathFile)
val processArgs = createProcessArgs(javaExe = javaExe, jvmArgs = jvmArgsWithJson, classpathFile = classpathFile, mainClass = mainClass, args = args)
span.setAttribute(AttributeKey.stringArrayKey("processArgs"), processArgs)
val process = ProcessBuilder(processArgs).directory(workingDir?.toFile()).start()
val firstError = AtomicReference<String>()
errorReader = readErrorOutput(process, timeout, logger)
readOutputAndBlock(process, timeout, logger, firstError)
fun javaRunFailed(reason: String) {
Span.current().setAttribute("classPath", classPathStringBuilder.substring("-classpath".length))
val message = "$reason\nCannot execute $mainClass (pid=${process.pid()} args=$args, vmOptions=$jvmArgsWithJson)"
span.setStatus(StatusCode.ERROR, message)
onError?.invoke()
throw RuntimeException(message)
}
val errorMessage = firstError.get()
if (errorMessage != null) {
javaRunFailed("Error reported from child process logger: $errorMessage")
}
if (!process.waitFor(timeout.remainingTime, TimeUnit.MILLISECONDS)) {
try {
dumpThreads(process.pid())
}
catch (e: Exception) {
span.addEvent("cannot dump threads: ${e.message}")
}
process.destroyForcibly().waitFor()
javaRunFailed("$timeout timeout")
}
val exitCode = process.exitValue()
if (exitCode != 0) {
javaRunFailed("exitCode=${process.exitValue()}")
}
}
finally {
Files.deleteIfExists(classpathFile)
errorReader?.join()
}
}
}
fun runJavaWithOutputToFile(mainClass: String,
args: List<String>,
jvmArgs: List<String>,
classPath: List<String>,
javaExe: Path,
timeoutMillis: Long = Timeout.DEFAULT,
outputFile: Path,
workingDir: Path? = null) {
Files.createDirectories(outputFile.parent)
val timeout = Timeout(timeoutMillis)
val classpathFile = Files.createTempFile("classpath-", ".txt")
tracer.spanBuilder("runJava")
.setAttribute("mainClass", mainClass)
.setAttribute(AttributeKey.stringArrayKey("args"), args)
.setAttribute(AttributeKey.stringArrayKey("jvmArgs"), jvmArgs)
.setAttribute("outputFile", outputFile.toString())
.setAttribute("workingDir", workingDir?.toString() ?: "")
.setAttribute("timeoutMillis", timeoutMillis)
.use { span ->
try {
createClassPathFile(classPath, classpathFile)
val processArgs = createProcessArgs(javaExe = javaExe, jvmArgs = jvmArgs, classpathFile = classpathFile, mainClass = mainClass,
args = args)
span.setAttribute(AttributeKey.stringArrayKey("processArgs"), processArgs)
val process = ProcessBuilder(processArgs)
.directory(workingDir?.toFile())
.redirectErrorStream(true)
.redirectOutput(outputFile.toFile())
.start()
fun javaRunFailed(exception: (String) -> Exception = ::RuntimeException) {
val message = "Cannot execute $mainClass, see details in ${outputFile.fileName} (published to TeamCity build artifacts), exitCode=${process.exitValue()}, pid=${process.pid()}, args=$args, vmOptions=$jvmArgs"
span.setStatus(StatusCode.ERROR, message)
if (Files.exists(outputFile)) {
span.setAttribute("processOutput", Files.readString(outputFile))
}
throw exception(message)
}
if (!process.waitFor(timeout.remainingTime, TimeUnit.MILLISECONDS)) {
process.destroyForcibly().waitFor()
javaRunFailed { message ->
ProcessRunTimedOut("$message: $timeout timeout")
}
}
val exitCode = process.exitValue()
if (exitCode != 0) {
javaRunFailed()
}
}
finally {
Files.deleteIfExists(classpathFile)
}
}
}
private fun createProcessArgs(javaExe: Path,
jvmArgs: Iterable<String>,
classpathFile: Path?,
mainClass: String,
args: Iterable<String>): MutableList<String> {
val processArgs = mutableListOf<String>()
// FIXME: enforce JBR
processArgs.add(javaExe.toString())
processArgs.add("-Djava.awt.headless=true")
processArgs.add("-Dapple.awt.UIElement=true")
processArgs.addAll(jvmArgs)
processArgs.add("@$classpathFile")
processArgs.add(mainClass)
processArgs.addAll(args)
return processArgs
}
private fun createClassPathFile(classPath: List<String>, classpathFile: Path): StringBuilder {
val classPathStringBuilder = StringBuilder()
classPathStringBuilder.append("-classpath").append('\n')
for (s in classPath) {
appendArg(s, classPathStringBuilder)
classPathStringBuilder.append(File.pathSeparator)
}
classPathStringBuilder.setLength(classPathStringBuilder.length - 1)
Files.writeString(classpathFile, classPathStringBuilder)
return classPathStringBuilder
}
@JvmOverloads
fun runProcess(vararg args: String, workingDir: Path? = null,
logger: Logger? = null,
timeoutMillis: Long = Timeout.DEFAULT) {
runProcess(args.toList(), workingDir, logger, timeoutMillis)
}
@JvmOverloads
fun runProcess(args: List<String>,
workingDir: Path? = null,
logger: Logger? = null,
timeoutMillis: Long = Timeout.DEFAULT,
additionalEnvVariables: Map<String, String> = emptyMap()) {
tracer.spanBuilder("runProcess")
.setAttribute(AttributeKey.stringArrayKey("args"), args)
.setAttribute("timeoutMillis", timeoutMillis)
.use {
val timeout = Timeout(timeoutMillis)
val process = ProcessBuilder(args)
.directory(workingDir?.toFile())
.also { builder -> additionalEnvVariables.entries.forEach { (k, v) -> builder.environment()[k] = v } }
.let { if (logger == null) it.inheritIO() else it }
.start()
val pid = process.pid()
val errorReader = logger?.let { readErrorOutput(process, timeout, it) }
try {
if (logger != null) {
readOutputAndBlock(process, timeout, logger)
}
if (!process.waitFor(timeout.remainingTime, TimeUnit.MILLISECONDS)) {
process.destroyForcibly().waitFor()
throw ProcessRunTimedOut("Cannot execute [$pid] $args: $timeout timeout")
}
val exitCode = process.exitValue()
if (exitCode != 0) {
throw RuntimeException("Cannot execute [$pid] $args (exitCode=$exitCode)")
}
}
finally {
errorReader?.join()
}
}
}
private fun readOutputAndBlock(process: Process,
timeout: Timeout,
logger: Logger,
firstError: AtomicReference<String>? = null) {
val mapper = ObjectMapper()
// join on CompletableFuture will help to process other tasks in FJP
runAsync {
consume(process.inputStream, process, timeout) {
if (it.startsWith("{")) {
try {
val jObject = mapper.readTree(it)
val message = jObject.get("message")?.asText() ?: error("Missing field: 'message'")
when (val level = jObject.get("level")?.asText() ?: error("Missing field: 'level'")) {
"SEVERE" -> {
firstError?.compareAndSet(null, message)
try {
logger.error(message)
} catch (_: BuildScriptsLoggedError) {
// skip exception thrown by logger.error
// we want to continue consuming stream
}
}
"WARNING" -> {
logger.warn(message)
}
"INFO" -> {
logger.info(message)
}
"CONFIG" -> {
logger.debug(message)
}
"FINE" -> {
logger.debug(message)
}
"FINEST" -> {
logger.debug(message)
}
"FINER" -> {
logger.debug(message)
}
else -> {
error("Unable parse log level: $level")
}
}
} catch (e: Throwable) {
try {
val message = "Unable to parse line: ${it}, error: ${e.message}\n${e.stackTraceToString()}"
firstError?.compareAndSet(null, message)
logger.error(message)
}
catch (_: BuildScriptsLoggedError) {
// skip exception thrown by logger.error
// we want to continue consuming stream
}
}
} else {
logger.info("[${process.pid()}] $it")
}
}
}.join()
}
private fun readErrorOutput(process: Process, timeout: Timeout, logger: Logger): CompletableFuture<Void> {
return runAsync {
consume(process.errorStream, process, timeout) { logger.warn("[${process.pid()}] $it") }
}
}
internal fun consume(inputStream: InputStream, process: Process, timeout: Timeout, consume: (String) -> Unit) {
inputStream.bufferedReader().use { reader ->
val lines = mutableListOf<String>()
val lineBuffer = StringBuilder()
val flushTimeoutMs = 5000L
var lastCharReceived = System.nanoTime() * 1_000_000
while (!timeout.isElapsed && (process.isAlive || reader.ready())) {
if (reader.ready()) {
val char = reader.read().takeIf { it != -1 }?.toChar()
if (char != null) {
if (char == '\n' || char == '\r') {
if (lineBuffer.isNotEmpty()) {
lines.add(lineBuffer.toString())
lineBuffer.clear()
}
} else {
lineBuffer.append(char)
}
lastCharReceived = System.nanoTime() * 1_000_000
}
if (char == null || !reader.ready() || lines.size > 100 || (System.nanoTime() * 1_000_000 - lastCharReceived) > flushTimeoutMs) {
for (line in lines) {
consume(line)
}
lines.clear()
}
}
else {
Thread.sleep(100L)
}
}
if (lineBuffer.isNotBlank()) {
consume(lineBuffer.toString())
}
}
}
private fun appendArg(value: String, builder: StringBuilder) {
if (!value.any(" #'\"\n\r\t"::contains)) {
builder.append(value)
return
}
for (c in value) {
when (c) {
' ', '#', '\'' -> builder.append('"').append(c).append('"')
'"' -> builder.append("\"\\\"\"")
'\n' -> builder.append("\"\\n\"")
'\r' -> builder.append("\"\\r\"")
'\t' -> builder.append("\"\\t\"")
else -> builder.append(c)
}
}
}
class ProcessRunTimedOut(message: String) : RuntimeException(message)
internal class Timeout(private val millis: Long) {
companion object {
val DEFAULT = TimeUnit.MINUTES.toMillis(10L)
}
private val start = System.currentTimeMillis()
val remainingTime: Long
get() = start.plus(millis).minus(System.currentTimeMillis()).takeIf { it > 0 } ?: 0
val isElapsed: Boolean
get() = remainingTime == 0L
override fun toString() = "${millis}ms"
}
internal fun dumpThreads(pid: Long) {
val jstack = System.getenv("JAVA_HOME")
?.removeSuffix("/")
?.removeSuffix("\\")
?.let { "$it/bin/jstack" }
?: "jstack"
runProcess(jstack, "$pid")
} | apache-2.0 | 1aa9aafd988e29dd8d951147072d094d | 35.320755 | 217 | 0.601529 | 4.606496 | false | false | false | false |
google/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/components/service.kt | 1 | 2732 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.components
import com.intellij.codeWithMe.ClientId
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.impl.stores.IComponentStore
/**
* This is primarily intended to be used by the service implementation. When introducing a new service,
* please add a static `getInstance()` method. For better tooling performance, it is always advised
* to keep an explicit method return type.
*
* @Service
* class MyApplicationService {
* companion object {
* @JvmStatic
* fun getInstance(): MyApplicationService = service()
* }
* }
*
* Using a `getInstance()` method is preferred over a property, because:
*
* - It makes it more clear on the call site that it can involve loading the service, which might not be cheap.
*
* - Loading the service can throw an exception, and having an exception thrown by a method call is less surprising
* than if it was caused by property access.
*
* - (Over-)using properties may be error-prone in a way that it might be accidentally changed to a property with an initializer
* instead of the correct (but more verbose) property with a getter, and that change can easily be overlooked.
*
* - Using the method instead of a property keeps `MyApplicationService.getInstance()` calls consistent
* when used both in Kotlin, and Java.
*
* - Using the method keeps `MyApplicationService.getInstance()` consistent with `MyProjectService.getInstance(project)`,
* both on the declaration and call sites.
*/
inline fun <reified T : Any> service(): T {
val serviceClass = T::class.java
return ApplicationManager.getApplication().getService(serviceClass)
?: throw RuntimeException("Cannot find service ${serviceClass.name} (classloader=${serviceClass.classLoader}, client=${ClientId.currentOrNull})")
}
/**
* Contrary to [serviceIfCreated], tries to initialize the service if not yet initialized
*/
inline fun <reified T : Any> serviceOrNull(): T? = ApplicationManager.getApplication().getService(T::class.java)
/**
* Contrary to [serviceOrNull], doesn't try to initialize the service if not yet initialized
*/
inline fun <reified T : Any> serviceIfCreated(): T? = ApplicationManager.getApplication().getServiceIfCreated(T::class.java)
inline fun <reified T : Any> services(includeLocal: Boolean): List<T> = ApplicationManager.getApplication().getServices(T::class.java, includeLocal)
val ComponentManager.stateStore: IComponentStore
get() = if (this is ComponentStoreOwner) this.componentStore else service() | apache-2.0 | 4118092bd2d81fbb6f3350a490203ff9 | 47.803571 | 154 | 0.742679 | 4.45677 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/KotlinAddImportAction.kt | 1 | 16858 | // 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.actions
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass
import com.intellij.codeInsight.daemon.impl.actions.AddImportAction
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.hint.QuestionAction
import com.intellij.ide.util.DefaultPsiElementCellRenderer
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.WeighingService
import com.intellij.psi.statistics.StatisticsManager
import com.intellij.psi.util.ProximityLocation
import com.intellij.psi.util.proximity.PsiProximityComparator
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.completion.ImportableFqNameClassifier
import org.jetbrains.kotlin.idea.completion.KotlinStatisticsInfo
import org.jetbrains.kotlin.idea.completion.isDeprecatedAtCallSite
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference.ShorteningMode
import org.jetbrains.kotlin.idea.util.application.underModalProgressOrUnderWriteActionWithNonCancellableProgressInDispatchThread
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.isOneSegmentFQN
import org.jetbrains.kotlin.name.parentOrNull
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.ImportPath
import java.awt.BorderLayout
import java.util.*
import javax.swing.Icon
import javax.swing.JPanel
import javax.swing.ListCellRenderer
internal fun createSingleImportAction(
project: Project,
editor: Editor,
element: KtElement,
fqNames: Collection<FqName>
): KotlinAddImportAction {
val file = element.containingKtFile
val prioritizer = Prioritizer(file)
val variants = fqNames.asSequence().mapNotNull {fqName ->
val sameFqNameDescriptors = file.resolveImportReference(fqName)
val priority = sameFqNameDescriptors.minOfOrNull {
prioritizer.priority(it, file.languageVersionSettings)
} ?: return@mapNotNull null
VariantWithPriority(SingleImportVariant(fqName, sameFqNameDescriptors, project), priority)
}.sortedWith(compareBy({ it.priority }, { it.variant.hint }))
return KotlinAddImportAction(project, editor, element, variants)
}
internal fun createSingleImportActionForConstructor(
project: Project,
editor: Editor,
element: KtElement,
fqNames: Collection<FqName>
): KotlinAddImportAction {
val file = element.containingKtFile
val prioritizer = Prioritizer(file)
val variants = fqNames.asSequence().mapNotNull { fqName ->
val sameFqNameDescriptors = file.resolveImportReference(fqName.parent())
.filterIsInstance<ClassDescriptor>()
.flatMap { it.constructors }
val priority = sameFqNameDescriptors.minOfOrNull {
prioritizer.priority(it, file.languageVersionSettings)
} ?: return@mapNotNull null
VariantWithPriority(SingleImportVariant(fqName, sameFqNameDescriptors, project), priority)
}
return KotlinAddImportAction(project, editor, element, variants)
}
internal fun createGroupedImportsAction(
project: Project,
editor: Editor,
element: KtElement,
autoImportDescription: String,
fqNames: Collection<FqName>
): KotlinAddImportAction {
val file = element.containingKtFile
val prioritizer = DescriptorGroupPrioritizer(file)
val variants = fqNames.groupBy { it.parentOrNull() ?: FqName.ROOT }.asSequence().map {
val samePackageFqNames = it.value
val descriptors = samePackageFqNames.flatMap { fqName -> file.resolveImportReference(fqName) }
val variant = if (samePackageFqNames.size > 1) {
GroupedImportVariant(autoImportDescription, descriptors, project)
} else {
SingleImportVariant(samePackageFqNames.first(), descriptors, project)
}
val priority = prioritizer.priority(descriptors, file.languageVersionSettings)
VariantWithPriority(variant, priority)
}
return KotlinAddImportAction(project, editor, element, variants)
}
/**
* Automatically adds import directive to the file for resolving reference.
* Based on {@link AddImportAction}
*/
class KotlinAddImportAction internal constructor(
private val project: Project,
private val editor: Editor,
private val element: KtElement,
private val variants: Sequence<VariantWithPriority>
) : QuestionAction {
private var singleImportVariant: AutoImportVariant? = null
private fun variantsList(): List<AutoImportVariant> {
if (singleImportVariant != null && !isUnitTestMode()) return listOf(singleImportVariant!!)
val variantsList = {
runReadAction {
variants.sortedBy { it.priority }.map { it.variant }.toList()
}
}
return if (isUnitTestMode()) {
variantsList()
} else {
project.runSynchronouslyWithProgress(KotlinBundle.message("import.progress.text.resolve.imports"), true) {
variantsList()
}.orEmpty()
}
}
fun showHint(): Boolean {
val iterator = variants.iterator()
if (!iterator.hasNext()) return false
val first = iterator.next().variant
val multiple = if (iterator.hasNext()) {
true
} else {
singleImportVariant = first
false
}
val hintText = ShowAutoImportPass.getMessage(multiple, first.hint)
HintManager.getInstance().showQuestionHint(editor, hintText, element.startOffset, element.endOffset, this)
return true
}
override fun execute(): Boolean {
PsiDocumentManager.getInstance(project).commitAllDocuments()
if (!element.isValid) return false
val variantsList = variantsList()
if (variantsList.isEmpty()) return false
if (variantsList.size == 1 || isUnitTestMode()) {
addImport(variantsList.first())
return true
}
JBPopupFactory.getInstance().createListPopup(project, getVariantSelectionPopup(variantsList)) {
val psiRenderer = DefaultPsiElementCellRenderer()
ListCellRenderer<AutoImportVariant> { list, value, index, isSelected, cellHasFocus ->
JPanel(BorderLayout()).apply {
add(
psiRenderer.getListCellRendererComponent(
list,
value.declarationToImport,
index,
isSelected,
cellHasFocus
)
)
}
}
}.showInBestPositionFor(editor)
return true
}
private fun getVariantSelectionPopup(variants: List<AutoImportVariant>): BaseListPopupStep<AutoImportVariant> {
return object : BaseListPopupStep<AutoImportVariant>(KotlinBundle.message("action.add.import.chooser.title"), variants) {
override fun isAutoSelectionEnabled() = false
override fun isSpeedSearchEnabled() = true
override fun onChosen(selectedValue: AutoImportVariant?, finalChoice: Boolean): PopupStep<String>? {
if (selectedValue == null || project.isDisposed) return null
if (finalChoice) {
addImport(selectedValue)
return null
}
val toExclude = AddImportAction.getAllExcludableStrings(selectedValue.excludeFqNameCheck.asString())
return object : BaseListPopupStep<String>(null, toExclude) {
override fun getTextFor(value: String): String {
return KotlinBundle.message("fix.import.exclude", value)
}
override fun onChosen(selectedValue: String, finalChoice: Boolean): PopupStep<Any>? {
if (finalChoice && !project.isDisposed) {
AddImportAction.excludeFromImport(project, selectedValue)
}
return null
}
}
}
override fun hasSubstep(selectedValue: AutoImportVariant?) = true
override fun getTextFor(value: AutoImportVariant) = value.hint
override fun getIconFor(value: AutoImportVariant) = value.icon
}
}
private fun addImport(variant: AutoImportVariant) {
val psiDocumentManager = PsiDocumentManager.getInstance(project)
psiDocumentManager.commitAllDocuments()
project.executeWriteCommand(QuickFixBundle.message("add.import")) {
if (!element.isValid) return@executeWriteCommand
val file = element.containingKtFile
val statisticsManager = StatisticsManager.getInstance()
variant.descriptorsToImport.forEach { descriptor ->
val statisticsInfo = KotlinStatisticsInfo.forDescriptor(descriptor)
statisticsManager.incUseCount(statisticsInfo)
// for class or package we use ShortenReferences because we not necessary insert an import but may want to
// insert partly qualified name
val importableFqName = descriptor.importableFqName
val importAlias = importableFqName?.let { file.findAliasByFqName(it) }
if (importableFqName?.isOneSegmentFQN() != true &&
(importAlias != null || descriptor is ClassDescriptor || descriptor is PackageViewDescriptor)
) {
if (element is KtSimpleNameExpression) {
if (importAlias != null) {
importAlias.nameIdentifier?.copy()?.let { element.getIdentifier()?.replace(it) }
val resultDescriptor = element.resolveMainReferenceToDescriptors().firstOrNull()
if (importableFqName == resultDescriptor?.importableFqName) {
return@forEach
}
}
if (importableFqName != null) {
underModalProgressOrUnderWriteActionWithNonCancellableProgressInDispatchThread(
project,
progressTitle = KotlinBundle.message("add.import.for.0", importableFqName.asString()),
computable = { element.mainReference.bindToFqName(importableFqName, ShorteningMode.FORCED_SHORTENING) }
)
}
}
} else {
ImportInsertHelper.getInstance(project).importDescriptor(file, descriptor)
}
}
}
}
}
internal interface ComparablePriority : Comparable<ComparablePriority>
internal data class VariantWithPriority(val variant: AutoImportVariant, val priority: ComparablePriority)
internal class Prioritizer(private val file: KtFile, private val compareNames: Boolean = true) {
private val classifier = ImportableFqNameClassifier(file){
ImportInsertHelper.getInstance(file.project).isImportedWithDefault(ImportPath(it, false), file)
}
private val statsManager = StatisticsManager.getInstance()
private val proximityLocation = ProximityLocation(file, file.module)
inner class Priority(descriptor: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings) : ComparablePriority {
private val isDeprecated = isDeprecatedAtCallSite(descriptor) { languageVersionSettings }
private val fqName = descriptor.importableFqName!!
private val classification = classifier.classify(fqName, false)
private val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(file.project, descriptor)
private val lastUseRecency = statsManager.getLastUseRecency(KotlinStatisticsInfo.forDescriptor(descriptor))
private val proximityWeight = WeighingService.weigh(PsiProximityComparator.WEIGHER_KEY, declaration, proximityLocation)
override fun compareTo(other: ComparablePriority): Int {
other as Priority
if (isDeprecated != other.isDeprecated) {
return if (isDeprecated) +1 else -1
}
val c1 = classification.compareTo(other.classification)
if (c1 != 0) return c1
val c2 = lastUseRecency.compareTo(other.lastUseRecency)
if (c2 != 0) return c2
val c3 = proximityWeight.compareTo(other.proximityWeight)
if (c3 != 0) return -c3 // n.b. reversed
if (compareNames) {
return fqName.asString().compareTo(other.fqName.asString())
}
return 0
}
}
fun priority(
descriptor: DeclarationDescriptor,
languageVersionSettings: LanguageVersionSettings,
) = Priority(descriptor, languageVersionSettings)
}
private class DescriptorGroupPrioritizer(file: KtFile) {
private val prioritizer = Prioritizer(file, false)
inner class Priority(
val descriptors: List<DeclarationDescriptor>,
languageVersionSettings: LanguageVersionSettings
) : ComparablePriority {
val ownDescriptorsPriority = descriptors.maxOf { prioritizer.priority(it, languageVersionSettings) }
override fun compareTo(other: ComparablePriority): Int {
other as Priority
val c1 = ownDescriptorsPriority.compareTo(other.ownDescriptorsPriority)
if (c1 != 0) return c1
return other.descriptors.size - descriptors.size
}
}
fun priority(
descriptors: List<DeclarationDescriptor>,
languageVersionSettings: LanguageVersionSettings
) = Priority(descriptors, languageVersionSettings)
}
internal abstract class AutoImportVariant(
val descriptorsToImport: Collection<DeclarationDescriptor>,
val excludeFqNameCheck: FqName,
project: Project,
) {
abstract val hint: String
val declarationToImport: PsiElement? = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptorsToImport.first())
val icon: Icon? = KotlinDescriptorIconProvider.getIcon(descriptorsToImport.first(), declarationToImport, 0)
}
private class GroupedImportVariant(
val autoImportDescription: String,
descriptors: Collection<DeclarationDescriptor>,
project: Project
) : AutoImportVariant(
descriptorsToImport = descriptors,
excludeFqNameCheck = descriptors.first().importableFqName!!.parent(),
project = project,
) {
override val hint: String get() = KotlinBundle.message("0.from.1", autoImportDescription, excludeFqNameCheck)
}
private class SingleImportVariant(
excludeFqNameCheck: FqName,
descriptors: Collection<DeclarationDescriptor>,
project: Project
) : AutoImportVariant(
descriptorsToImport = listOf(
descriptors.singleOrNull()
?: descriptors.minByOrNull { if (it is ClassDescriptor) 0 else 1 }
?: error("we create the class with not-empty descriptors always")
),
excludeFqNameCheck = excludeFqNameCheck,
project = project,
) {
override val hint: String get() = excludeFqNameCheck.asString()
}
| apache-2.0 | 093ff41a9f309720d79bd81651c3a807 | 41.145 | 158 | 0.690414 | 5.346654 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ucache/ScriptClassRootsUpdater.kt | 1 | 12634 | // 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.core.script.ucache
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.AdditionalLibraryRootsListener
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiElementFinder
import com.intellij.psi.PsiManager
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle
import org.jetbrains.kotlin.idea.base.util.CheckCanceledLock
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.KotlinScriptDependenciesClassFinder
import org.jetbrains.kotlin.idea.core.script.ScriptDependenciesModificationTracker
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.dependencies.hasGradleDependency
import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog
import org.jetbrains.kotlin.idea.core.util.EDT
import org.jetbrains.kotlin.idea.util.FirPluginOracleService
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
import java.nio.file.Paths
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
/**
* Holder for [ScriptClassRootsCache].
*
* Updates of [classpathRoots] performed asynchronously using the copy-on-write strategy.
* [gatherRoots] called when updating is required. Cache will built from the scratch.
*
* Updates can be coalesced by using `update { invalidate() }` transaction.
* As an alternative you can just call [invalidateAndCommit].
*
* After update roots changed event will be triggered if there are new root.
* This will start indexing.
* Also analysis cache will be cleared and changed opened script files will be reanalyzed.
*/
abstract class ScriptClassRootsUpdater(
val project: Project,
val manager: CompositeScriptConfigurationManager
) {
private var lastSeen: ScriptClassRootsCache? = null
private var invalidated: Boolean = false
private var syncUpdateRequired: Boolean = false
private val concurrentUpdates = AtomicInteger()
private val lock = CheckCanceledLock()
abstract fun gatherRoots(builder: ScriptClassRootsBuilder)
abstract fun afterUpdate()
private fun recreateRootsCache(): ScriptClassRootsCache {
val builder = ScriptClassRootsBuilder(project)
gatherRoots(builder)
return builder.build()
}
/**
* We need CAS due to concurrent unblocking sync update in [checkInvalidSdks]
*/
private val cache: AtomicReference<ScriptClassRootsCache> = AtomicReference(ScriptClassRootsCache.EMPTY)
init {
ProjectManager.getInstance().addProjectManagerListener(project, object : ProjectManagerListener {
override fun projectClosing(project: Project) {
scheduledUpdate?.apply {
cancel()
awaitCompletion()
}
}
})
ensureUpdateScheduled()
}
val classpathRoots: ScriptClassRootsCache
get() = cache.get()
/**
* @param synchronous Used from legacy FS cache only, don't use
*/
@Suppress("UNUSED_PARAMETER")
fun invalidate(file: VirtualFile, synchronous: Boolean = false) {
lock.withLock {
// todo: record invalided files for some optimisations in update
invalidate(synchronous)
}
}
/**
* @param synchronous Used from legacy FS cache only, don't use
*/
fun invalidate(synchronous: Boolean = false) {
lock.withLock {
checkInTransaction()
invalidated = true
if (synchronous) {
syncUpdateRequired = true
}
}
}
fun invalidateAndCommit() {
update { invalidate() }
}
fun isInTransaction(): Boolean {
return concurrentUpdates.get() > 0
}
fun checkInTransaction() {
check(isInTransaction())
}
inline fun <T> update(body: () -> T): T {
beginUpdating()
return try {
body()
} finally {
commit()
}
}
fun beginUpdating() {
concurrentUpdates.incrementAndGet()
}
fun commit() {
concurrentUpdates.decrementAndGet()
// run update even in inner transaction
// (outer transaction may be async, so it would be better to not wait it)
scheduleUpdateIfInvalid()
}
fun addConfiguration(vFile: VirtualFile, configuration: ScriptCompilationConfigurationWrapper) {
update {
val builder = classpathRoots.builder(project)
builder.dontWarnAboutDependenciesExistence()
builder.add(vFile, configuration)
cache.set(builder.build())
}
}
private fun scheduleUpdateIfInvalid() {
lock.withLock {
if (!invalidated) return
invalidated = false
if (syncUpdateRequired || isUnitTestMode()) {
syncUpdateRequired = false
updateSynchronously()
} else {
ensureUpdateScheduled()
}
}
}
private var scheduledUpdate: BackgroundTaskUtil.BackgroundTask<*>? = null
private fun ensureUpdateScheduled() {
val disposable = KotlinPluginDisposable.getInstance(project)
lock.withLock {
scheduledUpdate?.cancel()
if (!disposable.disposed) {
scheduledUpdate = BackgroundTaskUtil.submitTask(disposable) {
doUpdate()
}
}
}
}
private fun updateSynchronously() {
lock.withLock {
scheduledUpdate?.cancel()
doUpdate(false)
}
}
private fun doUpdate(underProgressManager: Boolean = true) {
val disposable = KotlinPluginDisposable.getInstance(project)
try {
val updates = recreateRootsCacheAndDiff()
if (!updates.changed) return
if (underProgressManager) {
ProgressManager.checkCanceled()
}
if (disposable.disposed) return
runInEdt(ModalityState.NON_MODAL) {
runWriteAction {
if (scriptsAsEntities) { // (updates.changed && !updates.hasNewRoots)
val manager = VirtualFileManager.getInstance()
updates.cache.scriptsPaths().takeUnless { it.isEmpty() }?.asSequence()
?.map { checkNotNull(manager.findFileByNioPath(Paths.get(it))) { "Couldn't find script as a VFS file: $it" } }
?.let { project.syncScriptEntities(it) }
}
}
}
if (updates.hasNewRoots) {
runInEdt(ModalityState.NON_MODAL) {
runWriteAction {
if (project.isDisposed) return@runWriteAction
if (!scriptsAsEntities) {
scriptingDebugLog { "kotlin.script.dependencies from ${updates.oldRoots} to ${updates.newRoots}" }
val hasGradleDependency = updates.newSdkRoots.hasGradleDependency() || updates.newRoots.hasGradleDependency()
val dependencySdkLibraryName = if (hasGradleDependency) {
KotlinBaseScriptingBundle.message("script.name.gradle.script.sdk.dependencies")
} else {
KotlinBaseScriptingBundle.message("script.name.kotlin.script.sdk.dependencies")
}
AdditionalLibraryRootsListener.fireAdditionalLibraryChanged(
project,
dependencySdkLibraryName,
updates.oldSdkRoots,
updates.newSdkRoots,
dependencySdkLibraryName
)
val dependencyLibraryName = if (hasGradleDependency) {
KotlinBaseScriptingBundle.message("script.name.gradle.script.dependencies")
} else {
KotlinBaseScriptingBundle.message("script.name.kotlin.script.dependencies")
}
AdditionalLibraryRootsListener.fireAdditionalLibraryChanged(
project,
dependencyLibraryName,
updates.oldRoots,
updates.newRoots,
dependencyLibraryName
)
}
ScriptDependenciesModificationTracker.getInstance(project).incModificationCount()
}
}
}
runReadAction {
if (project.isDisposed) return@runReadAction
if (!scriptsAsEntities) {
PsiElementFinder.EP.findExtensionOrFail(KotlinScriptDependenciesClassFinder::class.java, project).clearCache()
ScriptDependenciesModificationTracker.getInstance(project).incModificationCount()
}
if (updates.hasUpdatedScripts) {
updateHighlighting(project) { file -> updates.isScriptChanged(file.path) }
}
val scriptClassRootsCache = updates.cache
lastSeen = scriptClassRootsCache
}
} finally {
scheduledUpdate = null
}
}
private fun recreateRootsCacheAndDiff(): ScriptClassRootsCache.Updates {
while (true) {
val old = cache.get()
val new = recreateRootsCache()
if (cache.compareAndSet(old, new)) {
afterUpdate()
return new.diff(project, lastSeen)
}
}
}
internal fun checkInvalidSdks(remove: Sdk? = null) {
// sdks should be updated synchronously to avoid disposed roots usage
do {
val old = cache.get()
val actualSdks = old.sdks.rebuild(project, remove = remove)
if (actualSdks == old.sdks) return
val new = old.withUpdatedSdks(actualSdks)
} while (!cache.compareAndSet(old, new))
ensureUpdateScheduled()
}
private fun updateHighlighting(project: Project, filter: (VirtualFile) -> Boolean) {
if (!project.isOpen) return
val openFiles = FileEditorManager.getInstance(project).allEditors.mapNotNull { it.file }
val openedScripts = openFiles.filter(filter)
if (openedScripts.isEmpty()) return
/**
* Scripts guts are everywhere in the plugin code, without them some functionality does not work,
* And with them some other fir plugin related is broken
* As FIR plugin does not have scripts support yet, just disabling not working one for now
*/
@Suppress("DEPRECATION")
if (project.service<FirPluginOracleService>().isFirPlugin()) return
GlobalScope.launch(EDT(project)) {
if (project.isDisposed) return@launch
openedScripts.forEach {
if (!it.isValid) return@forEach
PsiManager.getInstance(project).findFile(it)?.let { psiFile ->
if (psiFile is KtFile) {
DaemonCodeAnalyzer.getInstance(project).restart(psiFile)
}
}
}
}
}
}
| apache-2.0 | 79253dda03cc1df2f91d7232e69072ba | 36.60119 | 138 | 0.620627 | 5.59274 | false | false | false | false |
vvv1559/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestCase.kt | 1 | 36876 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.impl
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testGuiFramework.cellReader.ExtendedJComboboxCellReader
import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader
import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader
import com.intellij.testGuiFramework.fixtures.*
import com.intellij.testGuiFramework.fixtures.extended.ExtendedButtonFixture
import com.intellij.testGuiFramework.fixtures.extended.ExtendedTreeFixture
import com.intellij.testGuiFramework.fixtures.newProjectWizard.NewProjectWizardFixture
import com.intellij.testGuiFramework.framework.GuiTestLocalRunner
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.framework.GuiTestUtil.waitUntilFound
import com.intellij.testGuiFramework.framework.IdeTestApplication.getTestScreenshotDirPath
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.findBoundedComponentByText
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.getComponentText
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.isTextComponent
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.typeMatcher
import com.intellij.testGuiFramework.launcher.system.SystemInfo.isMac
import com.intellij.ui.CheckboxTree
import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.components.labels.LinkLabel
import org.fest.swing.exception.ActionFailedException
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.exception.WaitTimedOutError
import org.fest.swing.fixture.AbstractComponentFixture
import org.fest.swing.fixture.JListFixture
import org.fest.swing.fixture.JTableFixture
import org.fest.swing.fixture.JTextComponentFixture
import org.fest.swing.image.ScreenshotTaker
import org.fest.swing.timing.Condition
import org.fest.swing.timing.Pause
import org.fest.swing.timing.Timeout
import org.fest.swing.timing.Timeout.timeout
import org.junit.Rule
import org.junit.runner.RunWith
import java.awt.Component
import java.awt.Container
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.*
import javax.swing.text.JTextComponent
/**
* The main base class that should be extended for writing GUI tests.
*
* GuiTestCase contains methods of TestCase class like setUp() and tearDown() but also has a set of methods allows to use Kotlin DSL for
* writing GUI tests (starts from comment KOTLIN DSL FOR GUI TESTING). The main concept of this DSL is using contexts of the current
* component. Kotlin language gives us an opportunity to omit fixture instances to perform their methods, therefore code looks simpler and
* more clear. Just use contexts functions to find appropriate fixtures and to operate with them:
*
* {@code <code>
* welcomeFrame { // <- context of WelcomeFrameFixture
* createNewProject()
* dialog("New Project Wizard") {
* // context of DialogFixture of dialog with title "New Project Wizard"
* }
* }
* </code>}
*
* All fixtures (or DSL methods for theese fixtures) has a timeout to find component on screen and equals to #defaultTimeout. To check existence
* of specific component by its fixture use exists lambda function with receiver.
*
* The more descriptive documentation about entire framework could be found in the root of testGuiFramework (HowToUseFramework.md)
*
*/
@RunWith(GuiTestLocalRunner::class)
open class GuiTestCase {
@Rule @JvmField
val guiTestRule = GuiTestRule()
/**
* default timeout to find target component for fixture. Using seconds as time unit.
*/
var defaultTimeout = 120L
private val screenshotTaker = ScreenshotTaker()
private var pathToSaveScreenshots = getTestScreenshotDirPath()
val settingsTitle: String = if (isMac()) "Preferences" else "Settings"
val defaultSettingsTitle: String = if (isMac()) "Default Preferences" else "Default Settings"
val IS_UNDER_TEAMCITY = System.getenv("TEAMCITY_VERSION") != null
val slash: String = File.separator
fun robot() = guiTestRule.robot()
//********************KOTLIN DSL FOR GUI TESTING*************************
//*********CONTEXT LAMBDA FUNCTIONS WITH RECEIVERS***********************
/**
* Context function: finds welcome frame and creates WelcomeFrameFixture instance as receiver object. Code block after it call methods on
* the receiver object (WelcomeFrameFixture instance).
*/
open fun welcomeFrame(func: WelcomeFrameFixture.() -> Unit) {
func(guiTestRule.findWelcomeFrame())
}
/**
* Context function: finds IDE frame and creates IdeFrameFixture instance as receiver object. Code block after it call methods on the
* receiver object (IdeFrameFixture instance).
*/
fun ideFrame(func: IdeFrameFixture.() -> Unit) {
func(guiTestRule.findIdeFrame())
}
/**
* Context function: finds dialog with specified title and creates JDialogFixture instance as receiver object. Code block after it call
* methods on the receiver object (JDialogFixture instance).
*
* @title title of searching dialog window. If dialog should be only one title could be omitted or set to null.
* @timeout time in seconds to find dialog in GUI hierarchy.
*/
fun dialog(title: String? = null, ignoreCaseTitle: Boolean = false, timeout: Long = defaultTimeout, func: JDialogFixture.() -> Unit) {
val dialog = dialog(title, ignoreCaseTitle, timeout)
func(dialog)
dialog.waitTillGone()
}
/**
* Context function: imports a simple project to skip steps of creation, creates IdeFrameFixture instance as receiver object when project
* is loaded. Code block after it call methods on the receiver object (IdeFrameFixture instance).
*/
fun simpleProject(func: IdeFrameFixture.() -> Unit) {
func(guiTestRule.importSimpleProject())
}
/**
* Context function: finds dialog "New Project Wizard" and creates NewProjectWizardFixture instance as receiver object. Code block after
* it call methods on the receiver object (NewProjectWizardFixture instance).
*/
fun projectWizard(func: NewProjectWizardFixture.() -> Unit) {
func(guiTestRule.findNewProjectWizard())
}
/**
* Context function for IdeFrame: activates project view in IDE and creates ProjectViewFixture instance as receiver object. Code block after
* it call methods on the receiver object (ProjectViewFixture instance).
*/
fun IdeFrameFixture.projectView(func: ProjectViewFixture.() -> Unit) {
func(this.projectView)
}
/**
* Context function for IdeFrame: activates toolwindow view in IDE and creates CustomToolWindowFixture instance as receiver object. Code
* block after it call methods on the receiver object (CustomToolWindowFixture instance).
*
* @id - a toolwindow id.
*/
fun IdeFrameFixture.toolwindow(id: String, func: CustomToolWindowFixture.() -> Unit) {
func(CustomToolWindowFixture(id, this))
}
//*********FIXTURES METHODS WITHOUT ROBOT and TARGET; KOTLIN ONLY
/**
* Finds a JList component in hierarchy of context component with a containingItem and returns JListFixture.
*
* @timeout in seconds to find JList component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.jList(containingItem: String? = null,
timeout: Long = defaultTimeout): JListFixture = if (target() is Container) jList(
target() as Container, containingItem, timeout)
else throw UnsupportedOperationException("Sorry, unable to find JList component with ${target().toString()} as a Container")
/**
* Finds a JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture.
*
* @timeout in seconds to find JButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.button(name: String,
timeout: Long = defaultTimeout): ExtendedButtonFixture = if (target() is Container) button(
target() as Container, name, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find JButton component named by \"${name}\" with ${target().toString()} as a Container")
/**
* Finds a ComponentWithBrowseButton component in hierarchy of context component with a name and returns ComponentWithBrowseButtonFixture.
*
* @timeout in seconds to find ComponentWithBrowseButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.componentWithBrowseButton(comboboxClass: Class<out ComponentWithBrowseButton<out JComponent>>,
timeout: Long = defaultTimeout): ComponentWithBrowseButtonFixture
= if (target() is Container) componentWithBrowseButton(target() as Container, comboboxClass, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find ComponentWithBrowseButton component with ${target().toString()} as a Container")
/**
* Finds a JComboBox component in hierarchy of context component by text of label and returns ComboBoxFixture.
*
* @timeout in seconds to find JComboBox component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.combobox(labelText: String,
timeout: Long = defaultTimeout): ComboBoxFixture = if (target() is Container) combobox(
target() as Container, labelText, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find JComboBox component near label by \"${labelText}\" with ${target().toString()} as a Container")
/**
* Finds a JCheckBox component in hierarchy of context component by text of label and returns CheckBoxFixture.
*
* @timeout in seconds to find JCheckBox component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.checkbox(labelText: String,
timeout: Long = defaultTimeout): CheckBoxFixture = if (target() is Container) checkbox(
target() as Container, labelText, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find JCheckBox component near label by \"${labelText}\" with ${target().toString()} as a Container")
/**
* Finds a ActionLink component in hierarchy of context component by name and returns ActionLinkFixture.
*
* @timeout in seconds to find ActionLink component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.actionLink(name: String,
timeout: Long = defaultTimeout): ActionLinkFixture = if (target() is Container) actionLink(
target() as Container, name, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find ActionLink component by name \"${name}\" with ${target().toString()} as a Container")
/**
* Finds a ActionButton component in hierarchy of context component by action name and returns ActionButtonFixture.
*
* @actionName text or action id of an action button (@see com.intellij.openapi.actionSystem.ActionManager#getId())
* @timeout in seconds to find ActionButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.actionButton(actionName: String,
timeout: Long = defaultTimeout): ActionButtonFixture = if (target() is Container) actionButton(
target() as Container, actionName, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find ActionButton component by action name \"${actionName}\" with ${target().toString()} as a Container")
/**
* Finds a ActionButton component in hierarchy of context component by action class name and returns ActionButtonFixture.
*
* @actionClassName qualified name of class for action
* @timeout in seconds to find ActionButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.actionButtonByClass(actionClassName: String,
timeout: Long = defaultTimeout): ActionButtonFixture = if (target() is Container) actionButtonByClass(
target() as Container, actionClassName, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find ActionButton component by action class name \"${actionClassName}\" with ${target().toString()} as a Container")
/**
* Finds a JRadioButton component in hierarchy of context component by label text and returns JRadioButtonFixture.
*
* @timeout in seconds to find JRadioButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.radioButton(textLabel: String,
timeout: Long = defaultTimeout): RadioButtonFixture = if (target() is Container) radioButton(
target() as Container, textLabel, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find RadioButton component by label \"${textLabel}\" with ${target().toString()} as a Container")
/**
* Finds a JTextComponent component (JTextField) in hierarchy of context component by text of label and returns JTextComponentFixture.
*
* @textLabel could be a null if label is absent
* @timeout in seconds to find JTextComponent component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.textfield(textLabel: String?,
timeout: Long = defaultTimeout): JTextComponentFixture = if (target() is Container) textfield(
target() as Container, textLabel, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find JTextComponent (JTextField) component by label \"${textLabel}\" with ${target().toString()} as a Container")
/**
* Finds a JTree component in hierarchy of context component by a path and returns ExtendedTreeFixture.
*
* @pathStrings comma separated array of Strings, representing path items: jTree("myProject", "src", "Main.java")
* @timeout in seconds to find JTree component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.jTree(vararg pathStrings: String,
timeout: Long = defaultTimeout): ExtendedTreeFixture = if (target() is Container) jTreePath(
target() as Container, timeout, *pathStrings)
else throw UnsupportedOperationException(
"Sorry, unable to find JTree component \"${if (pathStrings.isNotEmpty()) "by path ${pathStrings}" else ""}\" with ${target().toString()} as a Container")
/**
* Finds a CheckboxTree component in hierarchy of context component by a path and returns CheckboxTreeFixture.
*
* @pathStrings comma separated array of Strings, representing path items: checkboxTree("JBoss", "JBoss Drools")
* @timeout in seconds to find JTree component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.checkboxTree(vararg pathStrings: String,
timeout: Long = defaultTimeout): CheckboxTreeFixture = if (target() is Container) checkboxTree(
target() as Container, timeout, *pathStrings)
else throw UnsupportedOperationException(
"Sorry, unable to find CheckboxTree component \"${if (pathStrings.isNotEmpty()) "by path ${pathStrings}" else ""}\" with ${target().toString()} as a Container")
/**
* Finds a JTable component in hierarchy of context component by a cellText and returns JTableFixture.
*
* @timeout in seconds to find JTable component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.table(cellText: String,
timeout: Long = defaultTimeout): JTableFixture = if (target() is Container) table(
target() as Container, cellText, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find JTable component with cell text \"$cellText\" with ${target().toString()} as a Container")
/**
* Finds popup on screen with item (itemName) and clicks on it item
*
* @timeout timeout in seconds to find JTextComponent component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.popupClick(itemName: String,
timeout: Long = defaultTimeout) = if (target() is Container) popupClick(
target() as Container, itemName, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find Popup component with ${target().toString()} as a Container")
/**
* Finds a LinkLabel component in hierarchy of context component by a link name and returns fixture for it.
*
* @timeout in seconds to find LinkLabel component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.linkLabel(linkName: String, /*timeout in seconds*/
timeout: Long = defaultTimeout) = if (target() is Container) linkLabel(
target() as Container, linkName, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find LinkLabel component with ${target().toString()} as a Container")
fun <S, C : Component> ComponentFixture<S, C>.hyperlinkLabel(labelText: String, /*timeout in seconds*/
timeout: Long = defaultTimeout): HyperlinkLabelFixture
= if (target() is Container) hyperlinkLabel(target() as Container, labelText, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find HyperlinkLabel component by label text: \"$labelText\" with ${target().toString()} as a Container")
/**
* Finds a table of plugins component in hierarchy of context component by a link name and returns fixture for it.
*
* @timeout in seconds to find table of plugins component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.pluginTable(timeout: Long = defaultTimeout)
= if (target() is Container) pluginTable(target() as Container, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find PluginTable component with ${target().toString()} as a Container")
/**
* Finds a Message component in hierarchy of context component by a title MessageFixture.
*
* @timeout in seconds to find component for Message
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.message(title: String, timeout: Long = defaultTimeout)
= if (target() is Container) message(target() as Container, title, timeout)
else throw UnsupportedOperationException(
"Sorry, unable to find PluginTable component with ${target().toString()} as a Container")
/**
* Finds a Message component in hierarchy of context component by a title MessageFixture.
*
* @timeout in seconds to find component for Message
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.message(title: String, timeout: Long = defaultTimeout, func: MessagesFixture.() -> Unit) {
if (target() is Container) {
val messagesFixture = message(target() as Container, title, timeout)
func(messagesFixture)
}
else throw UnsupportedOperationException(
"Sorry, unable to find PluginTable component with ${target().toString()} as a Container")
}
//*********FIXTURES METHODS FOR IDEFRAME WITHOUT ROBOT and TARGET
/**
* Context function for IdeFrame: get current editor and create EditorFixture instance as a receiver object. Code block after
* it call methods on the receiver object (EditorFixture instance).
*/
fun IdeFrameFixture.editor(func: EditorFixture.() -> Unit) {
func(this.editor)
}
/**
* Context function for IdeFrame: get the tab with specific opened file and create EditorFixture instance as a receiver object. Code block after
* it call methods on the receiver object (EditorFixture instance).
*/
fun IdeFrameFixture.editor(tabName: String, func: EditorFixture.() -> Unit) {
val editorFixture = this.editor.selectTab(tabName)
func(editorFixture)
}
/**
* Context function for IdeFrame: creates a MainToolbarFixture instance as receiver object. Code block after
* it call methods on the receiver object (MainToolbarFixture instance).
*/
fun IdeFrameFixture.toolbar(func: MainToolbarFixture.() -> Unit) {
func(this.toolbar)
}
/**
* Context function for IdeFrame: creates a NavigationBarFixture instance as receiver object. Code block after
* it call methods on the receiver object (NavigationBarFixture instance).
*/
fun IdeFrameFixture.navigationBar(func: NavigationBarFixture.() -> Unit) {
func(this.navigationBar)
}
/**
* Extension function for IDE to iterate through the menu.
*
* @path items like: popup("New", "File")
*/
fun IdeFrameFixture.popup(vararg path: String)
= this.invokeMenuPath(*path)
//*********COMMON FUNCTIONS WITHOUT CONTEXT
/**
* Type text by symbol with a constant delay. Generate system key events, so entered text will aply to a focused component.
*/
fun typeText(text: String) = GuiTestUtil.typeText(text, guiTestRule.robot(), 10)
/**
* @param keyStroke should follow {@link KeyStrokeAdapter#getKeyStroke(String)} instructions and be generated by {@link KeyStrokeAdapter#toString(KeyStroke)} preferably
*
* examples: shortcut("meta comma"), shortcut("ctrl alt s"), shortcut("alt f11")
* modifiers order: shift | ctrl | control | meta | alt | altGr | altGraph
*/
fun shortcut(keyStroke: String) = GuiTestUtil.invokeActionViaShortcut(guiTestRule.robot(), keyStroke)
/**
* Invoke action by actionId through its keystroke
*/
fun invokeAction(actionId: String) = GuiTestUtil.invokeAction(guiTestRule.robot(), actionId)
/**
* Take a screenshot for a specific component. Screenshot remain scaling and represent it in name of file.
*/
fun screenshot(component: Component, screenshotName: String): Unit {
val extension = "${getScaleSuffix()}.png"
val pathWithTestFolder = pathToSaveScreenshots.path / this.guiTestRule.getTestName()
val fileWithTestFolder = File(pathWithTestFolder)
FileUtil.ensureExists(fileWithTestFolder)
var screenshotFilePath = File(fileWithTestFolder, screenshotName + extension)
if (screenshotFilePath.isFile) {
val format = SimpleDateFormat("MM-dd-yyyy.HH.mm.ss")
val now = format.format(GregorianCalendar().time)
screenshotFilePath = File(fileWithTestFolder, screenshotName + "." + now + extension)
}
screenshotTaker.saveComponentAsPng(component, screenshotFilePath.path)
println(message = "Screenshot for a component \"${component.toString()}\" taken and stored at ${screenshotFilePath.path}")
}
/**
* Finds JDialog with a specific title (if title is null showing dialog should be only one) and returns created JDialogFixture
*/
fun dialog(title: String? = null, ignoreCaseTitle: Boolean, timeoutInSeconds: Long): JDialogFixture {
if (title == null) {
val jDialog = waitUntilFound(null, JDialog::class.java, timeoutInSeconds) { true }
return JDialogFixture(guiTestRule.robot(), jDialog)
}
else {
try {
val dialog = GuiTestUtilKt.withPauseWhenNull(timeoutInSeconds.toInt()) {
val allMatchedDialogs = guiTestRule.robot().finder().findAll(typeMatcher(JDialog::class.java) {
if (ignoreCaseTitle) it.title.toLowerCase() == title.toLowerCase() else it.title == title
}).filter { it.isShowing && it.isEnabled && it.isVisible }
if (allMatchedDialogs.size > 1) throw Exception("Found more than one (${allMatchedDialogs.size}) dialogs matched title \"$title\"")
allMatchedDialogs.firstOrNull()
}
return JDialogFixture(guiTestRule.robot(), dialog)
} catch (timeoutError: WaitTimedOutError) {
throw ComponentLookupException("Timeout error for finding JDialog by title \"$title\" for $timeoutInSeconds seconds")
}
}
}
//*********PRIVATE WRAPPER FUNCTIONS FOR FIXTURES
private fun Long.toFestTimeout(): Timeout = if (this == 0L) timeout(50, TimeUnit.MILLISECONDS) else timeout(this, TimeUnit.SECONDS)
private fun message(container: Container, title: String, timeout: Long): MessagesFixture
= MessagesFixture.findByTitle(guiTestRule.robot(), container, title, timeout.toFestTimeout())
private fun jList(container: Container, containingItem: String? = null, timeout: Long): JListFixture {
val extCellReader = ExtendedJListCellReader()
val myJList = waitUntilFound(container, JList::class.java, timeout) { jList ->
if (containingItem == null) true //if were searching for any jList()
else {
val elements = (0..jList.model.size - 1).map { it -> extCellReader.valueAt(jList, it) }
elements.any { it.toString() == containingItem } && jList.isShowing
}
}
val jListFixture = JListFixture(guiTestRule.robot(), myJList)
jListFixture.replaceCellReader(extCellReader)
return jListFixture
}
private fun button(container: Container, name: String, timeout: Long): ExtendedButtonFixture {
val jButton = waitUntilFound(container, JButton::class.java, timeout) {
it.flags {
isShowing && isVisible && text == name
}
}
return ExtendedButtonFixture(guiTestRule.robot(), jButton)
}
private fun componentWithBrowseButton(container: Container,
foo: Class<out ComponentWithBrowseButton<out JComponent>>,
timeout: Long): ComponentWithBrowseButtonFixture {
val component = waitUntilFound(container, ComponentWithBrowseButton::class.java, timeout) {
component ->
component.isShowing && foo.isInstance(component)
}
return ComponentWithBrowseButtonFixture(component, guiTestRule.robot())
}
private fun combobox(container: Container, text: String, timeout: Long): ComboBoxFixture {
//wait until label has appeared
try {
waitUntilFound(container, Component::class.java,
timeout) { it.flags { isShowing && isTextComponent() && getComponentText() == text } }
} catch (e: WaitTimedOutError) { throw ComponentLookupException("Unable to find label for a combobox with text \"$text\" in $timeout seconds")}
val comboBox = findBoundedComponentByText(guiTestRule.robot(), container, text, JComboBox::class.java)
val comboboxFixture = ComboBoxFixture(guiTestRule.robot(), comboBox)
comboboxFixture.replaceCellReader(ExtendedJComboboxCellReader())
return comboboxFixture
}
private fun checkbox(container: Container, labelText: String, timeout: Long): CheckBoxFixture {
//wait until label has appeared
val jCheckBox = waitUntilFound(container, JCheckBox::class.java,
timeout) { it.flags { isShowing && isVisible && text == labelText } }
return CheckBoxFixture(guiTestRule.robot(), jCheckBox)
}
private fun actionLink(container: Container, name: String, timeout: Long) = ActionLinkFixture.findActionLinkByName(name, guiTestRule.robot(),
container,
timeout.toFestTimeout())
private fun actionButton(container: Container, actionName: String, timeout: Long): ActionButtonFixture {
return try {
ActionButtonFixture.findByText(actionName, guiTestRule.robot(), container, timeout.toFestTimeout())
}
catch (componentLookupException: ComponentLookupException) {
ActionButtonFixture.findByActionId(actionName, guiTestRule.robot(), container, timeout.toFestTimeout())
}
}
private fun actionButtonByClass(container: Container, actionClassName: String, timeout: Long): ActionButtonFixture =
ActionButtonFixture.findByActionClassName(actionClassName, guiTestRule.robot(), container, timeout.toFestTimeout())
private fun editor(ideFrameFixture: IdeFrameFixture, timeout: Long): EditorFixture = EditorFixture(guiTestRule.robot(), ideFrameFixture)
private fun radioButton(container: Container, labelText: String, timeout: Long) = GuiTestUtil.findRadioButton(guiTestRule.robot(), container,
labelText,
timeout.toFestTimeout())
private fun textfield(container: Container, labelText: String?, timeout: Long): JTextComponentFixture {
//if 'textfield()' goes without label
if (labelText.isNullOrEmpty()) {
val jTextField = waitUntilFound(container, JTextField::class.java, timeout) { jTextField -> jTextField.isShowing }
return JTextComponentFixture(guiTestRule.robot(), jTextField)
}
//wait until label has appeared
waitUntilFound(container, Component::class.java, timeout) {
it.flags { isShowing && isVisible && isTextComponent() && getComponentText() == labelText }
}
val jTextComponent = findBoundedComponentByText(guiTestRule.robot(), container, labelText!!, JTextComponent::class.java)
return JTextComponentFixture(guiTestRule.robot(), jTextComponent)
}
private fun linkLabel(container: Container, labelText: String, timeout: Long): ComponentFixture<ComponentFixture<*, *>, LinkLabel<*>> {
val myLinkLabel = waitUntilFound(guiTestRule.robot(), container, typeMatcher(LinkLabel::class.java) { it.isShowing && (it.text == labelText) },
timeout.toFestTimeout())
return ComponentFixture<ComponentFixture<*, *>, LinkLabel<*>>(ComponentFixture::class.java, guiTestRule.robot(), myLinkLabel)
}
private fun hyperlinkLabel(container: Container, labelText: String, timeout: Long): HyperlinkLabelFixture {
val hyperlinkLabel = waitUntilFound(guiTestRule.robot(), container, typeMatcher(HyperlinkLabel::class.java) {
(it.isShowing && (it.text == labelText))
}, timeout.toFestTimeout())
return HyperlinkLabelFixture(guiTestRule.robot(), hyperlinkLabel)
}
private fun table(container: Container, cellText: String, timeout: Long): JTableFixture {
return waitUntilFoundFixture(container, JTable::class.java, timeout) {
val jTableFixture = JTableFixture(guiTestRule.robot(), it)
jTableFixture.replaceCellReader(ExtendedJTableCellReader())
val hasCellWithText = try {
jTableFixture.cell(cellText); true
}
catch (e: ActionFailedException) {
false
}
Pair(hasCellWithText, jTableFixture)
}
}
private fun pluginTable(container: Container, timeout: Long) = PluginTableFixture.find(guiTestRule.robot(), container, timeout.toFestTimeout())
private fun popupClick(container: Container, itemName: String, timeout: Long) {
GuiTestUtil.clickPopupMenuItem(itemName, false, container, guiTestRule.robot(), timeout.toFestTimeout())
}
private fun jTreePath(container: Container, timeout: Long, vararg pathStrings: String): ExtendedTreeFixture {
val myTree: JTree?
val pathList = pathStrings.toList()
if (pathList.isEmpty()) {
myTree = waitUntilFound(guiTestRule.robot(), container, typeMatcher(JTree::class.java) { true }, timeout.toFestTimeout())
}
else {
myTree = waitUntilFound(guiTestRule.robot(), container, typeMatcher(JTree::class.java) { ExtendedTreeFixture(guiTestRule.robot(), it).hasPath(pathList) },
timeout.toFestTimeout())
}
val treeFixture: ExtendedTreeFixture = ExtendedTreeFixture(guiTestRule.robot(), myTree)
return treeFixture
}
private fun checkboxTree(container: Container, timeout: Long, vararg pathStrings: String): CheckboxTreeFixture {
val extendedTreeFixture = jTreePath(container, timeout, *pathStrings)
if (extendedTreeFixture.tree !is CheckboxTree) throw ComponentLookupException("Found JTree but not a CheckboxTree")
return CheckboxTreeFixture(guiTestRule.robot(), extendedTreeFixture.tree)
}
fun ComponentFixture<*, *>.exists(fixture: () -> AbstractComponentFixture<*, *, *>): Boolean {
val tmp = defaultTimeout
defaultTimeout = 0
try {
fixture.invoke()
defaultTimeout = tmp
}
catch(ex: Exception) {
when (ex) {
is ComponentLookupException,
is WaitTimedOutError -> {
defaultTimeout = tmp; return false
}
else -> throw ex
}
}
return true
}
//*********SOME EXTENSION FUNCTIONS FOR FIXTURES
fun JListFixture.doubleClickItem(itemName: String) {
this.item(itemName).doubleClick()
}
//necessary only for Windows
fun getScaleSuffix(): String? {
val scaleEnabled: Boolean = (GuiTestUtil.getSystemPropertyOrEnvironmentVariable("sun.java2d.uiScale.enabled")?.toLowerCase().equals(
"true"))
if (!scaleEnabled) return ""
val uiScaleVal = GuiTestUtil.getSystemPropertyOrEnvironmentVariable("sun.java2d.uiScale") ?: return ""
return "@${uiScaleVal}x"
}
fun <ComponentType : Component> waitUntilFound(container: Container?,
componentClass: Class<ComponentType>,
timeout: Long,
matcher: (ComponentType) -> Boolean): ComponentType {
return GuiTestUtil.waitUntilFound(guiTestRule.robot(), container, typeMatcher(componentClass) { matcher(it) }, timeout.toFestTimeout())
}
fun <Fixture, ComponentType : Component> waitUntilFoundFixture(container: Container?,
componentClass: Class<ComponentType>,
timeout: Long,
matcher: (ComponentType) -> Pair<Boolean, Fixture>): Fixture {
val ref = Ref<Fixture>()
GuiTestUtil.waitUntilFound(guiTestRule.robot(), container, typeMatcher(componentClass)
{
val (matched, fixture) = matcher(it)
if (matched) ref.set(fixture)
matched
}, timeout.toFestTimeout())
return ref.get()
}
fun pause(condition: String = "Unspecified condition", timeoutSeconds: Long = 120, testFunction: () -> Boolean) {
Pause.pause(object : Condition(condition) {
override fun test() = testFunction()
}, Timeout.timeout(timeoutSeconds, TimeUnit.SECONDS))
}
inline fun <ExtendingType> ExtendingType.flags(flagCheckFunction: ExtendingType.() -> Boolean): Boolean {
with(this) {
return flagCheckFunction()
}
}
}
private operator fun String.div(path: String): String {
return "$this${File.separator}$path"
}
| apache-2.0 | 879907e0d6abc6ec00a3a335c84483f7 | 49.239782 | 170 | 0.701025 | 5.059824 | false | true | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/course_purchase/reducer/CoursePurchaseReducer.kt | 1 | 19994 | package org.stepik.android.presentation.course_purchase.reducer
import com.android.billingclient.api.Purchase
import org.stepik.android.domain.course_payments.model.PromoCodeSku
import org.stepik.android.domain.course_purchase.analytic.BuyCourseIAPFlowFailureAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.BuyCourseIAPFlowStartAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.BuyCourseIAPFlowSuccessAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.BuyCoursePromoFailureAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.BuyCoursePromoStartPressedAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.BuyCoursePromoSuccessAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.BuyCourseVerificationFailureAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.BuyCourseVerificationSuccessAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.RestoreCoursePurchaseFailureAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.RestoreCoursePurchasePressedAnalyticEvent
import org.stepik.android.domain.course_purchase.analytic.RestoreCoursePurchaseSuccessAnalyticEvent
import org.stepik.android.presentation.course.mapper.toEnrollmentError
import org.stepik.android.presentation.course.model.EnrollmentError
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature.State
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature.Message
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature.Action
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature
import org.stepik.android.presentation.wishlist.WishlistOperationFeature
import org.stepik.android.presentation.wishlist.reducer.WishlistOperationReducer
import ru.nobird.app.presentation.redux.reducer.StateReducer
import javax.inject.Inject
class CoursePurchaseReducer
@Inject
constructor(
private val wishlistOperationReducer: WishlistOperationReducer
) : StateReducer<State, Message, Action> {
override fun reduce(state: State, message: Message): Pair<State, Set<Action>> =
when (message) {
is Message.InitMessage -> {
if (state is State.Idle) {
val promoCodeState = if (message.coursePurchaseData.promoCodeSku != PromoCodeSku.EMPTY) {
CoursePurchaseFeature.PromoCodeState.Valid(message.coursePurchaseData.promoCodeSku.name, message.coursePurchaseData.promoCodeSku)
} else {
CoursePurchaseFeature.PromoCodeState.Idle
}
val wishlistState = if (message.coursePurchaseData.isWishlisted) {
WishlistOperationFeature.State.Wishlisted
} else {
WishlistOperationFeature.State.Idle
}
State.Content(message.coursePurchaseData, message.coursePurchaseSource, CoursePurchaseFeature.PaymentState.Idle, promoCodeState, wishlistState) to emptySet()
} else {
null
}
}
is Message.LaunchPurchaseFlow -> {
if (state is State.Content) {
val skuId = if (state.promoCodeState is CoursePurchaseFeature.PromoCodeState.Valid) {
requireNotNull(state.promoCodeState.promoCodeSku.lightSku?.id)
} else {
state.coursePurchaseData.primarySku.id
}
state.copy(paymentState = CoursePurchaseFeature.PaymentState.ProcessingInitialCheck) to
setOf(Action.FetchLaunchFlowData(state.coursePurchaseData.course.id, skuId))
} else {
null
}
}
is Message.LaunchPurchaseFlowSuccess -> {
if (state is State.Content && state.paymentState is CoursePurchaseFeature.PaymentState.ProcessingInitialCheck) {
state.copy(
paymentState = CoursePurchaseFeature.PaymentState.ProcessingBillingPayment(
message.purchaseFlowData
)
) to setOf(
Action.ViewAction.LaunchPurchaseFlowBilling(message.purchaseFlowData.obfuscatedParams, message.purchaseFlowData.skuDetails),
Action.LogAnalyticEvent(
BuyCourseIAPFlowStartAnalyticEvent(
state.coursePurchaseData.course.id,
state.coursePurchaseSource,
state.coursePurchaseData.isWishlisted,
(state.promoCodeState as? CoursePurchaseFeature.PromoCodeState.Valid)?.text
)
)
)
} else {
null
}
}
is Message.LaunchPurchaseFlowFailure -> {
if (state is State.Content && state.paymentState is CoursePurchaseFeature.PaymentState.ProcessingInitialCheck) {
state.copy(paymentState = CoursePurchaseFeature.PaymentState.Idle) to
setOf(Action.ViewAction.Error(message.throwable.toEnrollmentError()))
} else {
null
}
}
is Message.PurchaseFlowBillingSuccess -> {
if (state is State.Content) {
when (state.paymentState) {
is CoursePurchaseFeature.PaymentState.ProcessingBillingPayment -> {
val promoCode = if (state.promoCodeState is CoursePurchaseFeature.PromoCodeState.Valid) {
state.promoCodeState.promoCodeSku.name
} else {
null
}
val (obfuscatedAccountId, obfuscatedProfileId) = state.paymentState.purchaseFlowData.obfuscatedParams
val purchase = message.purchases.find {
it.accountIdentifiers?.obfuscatedAccountId == obfuscatedAccountId &&
it.accountIdentifiers?.obfuscatedProfileId == obfuscatedProfileId
}
requireNotNull(purchase)
when (purchase.purchaseState) {
Purchase.PurchaseState.PENDING -> {
state.copy(
paymentState = CoursePurchaseFeature.PaymentState.PaymentPending
) to setOf(
Action.SaveBillingPurchasePayload(
state.coursePurchaseData.course.id,
state.paymentState.purchaseFlowData.coursePurchasePayload.profileId,
state.paymentState.purchaseFlowData.skuDetails,
purchase,
promoCode
)
)
}
Purchase.PurchaseState.PURCHASED -> {
state.copy(
paymentState = CoursePurchaseFeature.PaymentState.ProcessingConsume(
state.paymentState.purchaseFlowData.skuDetails, purchase
)
) to
setOf(
Action.ConsumePurchaseAction(
state.coursePurchaseData.course.id,
state.paymentState.purchaseFlowData.coursePurchasePayload.profileId,
state.paymentState.purchaseFlowData.skuDetails,
purchase,
promoCode
),
Action.LogAnalyticEvent(
BuyCourseIAPFlowSuccessAnalyticEvent(
state.coursePurchaseData.course.id,
state.coursePurchaseSource,
state.coursePurchaseData.isWishlisted,
promoCode
)
)
)
}
else ->
state to emptySet()
}
}
is CoursePurchaseFeature.PaymentState.PaymentPending -> {
state to setOf(
Action.ViewAction.ShowLoading,
Action.RestorePurchase(state.coursePurchaseData.course.id)
)
}
else ->
null
}
} else {
null
}
}
is Message.PurchaseFlowBillingFailure -> {
if (state is State.Content && state.paymentState is CoursePurchaseFeature.PaymentState.ProcessingBillingPayment) {
state.copy(paymentState = CoursePurchaseFeature.PaymentState.Idle) to
setOf(
Action.ViewAction.Error(message.billingException.toEnrollmentError()),
Action.LogAnalyticEvent(
BuyCourseIAPFlowFailureAnalyticEvent(
state.coursePurchaseData.course.id,
message.billingException.responseCode,
message.billingException.errorMessage
)
)
)
} else {
null
}
}
is Message.ConsumePurchaseSuccess -> {
if (state is State.Content && (state.paymentState is CoursePurchaseFeature.PaymentState.ProcessingConsume || state.paymentState is CoursePurchaseFeature.PaymentState.PaymentPending)) {
state.copy(paymentState = CoursePurchaseFeature.PaymentState.PaymentSuccess) to
setOf(
Action.ViewAction.ShowConsumeSuccess,
Action.LogAnalyticEvent(
BuyCourseVerificationSuccessAnalyticEvent(
state.coursePurchaseData.course.id,
state.coursePurchaseSource,
state.coursePurchaseData.isWishlisted,
(state.promoCodeState as? CoursePurchaseFeature.PromoCodeState.Valid)?.text
)
)
)
} else {
null
}
}
is Message.ConsumePurchaseFailure -> {
if (state is State.Content && state.paymentState is CoursePurchaseFeature.PaymentState.ProcessingConsume) {
state.copy(paymentState = CoursePurchaseFeature.PaymentState.PaymentFailure) to
setOf(
Action.LogAnalyticEvent(
BuyCourseVerificationFailureAnalyticEvent(
state.coursePurchaseData.course.id,
message.throwable.toEnrollmentError().name,
message.throwable
)
)
)
} else {
null
}
}
is Message.LaunchRestorePurchaseFlow -> {
if (state is State.Content) {
state to setOf(
Action.ViewAction.ShowLoading,
Action.RestorePurchase(state.coursePurchaseData.course.id),
Action.LogAnalyticEvent(
RestoreCoursePurchasePressedAnalyticEvent(
state.coursePurchaseData.course.id,
message.restoreCoursePurchaseSource
)
)
)
} else {
null
}
}
is Message.RestorePurchaseSuccess -> {
if (state is State.Content) {
state.copy(paymentState = CoursePurchaseFeature.PaymentState.PaymentSuccess) to
setOf(
Action.ViewAction.ShowConsumeSuccess,
Action.LogAnalyticEvent(
RestoreCoursePurchaseSuccessAnalyticEvent(
state.coursePurchaseData.course.id
)
)
)
} else {
null
}
}
is Message.RestorePurchaseFailure -> {
if (state is State.Content) {
val enrollmentError = message.throwable.toEnrollmentError()
val analyticEventAction = Action.LogAnalyticEvent(
RestoreCoursePurchaseFailureAnalyticEvent(
state.coursePurchaseData.course.id,
enrollmentError.name,
message.throwable
)
)
if (enrollmentError == EnrollmentError.BILLING_NO_PURCHASES_TO_RESTORE) {
state to setOf(Action.ViewAction.ShowConsumeFailure, Action.ViewAction.Error(enrollmentError), analyticEventAction)
} else {
state.copy(paymentState = CoursePurchaseFeature.PaymentState.PaymentFailure) to setOf(Action.ViewAction.ShowConsumeFailure, analyticEventAction)
}
} else {
null
}
}
is Message.LaunchPendingPurchaseFlow -> {
if (state is State.Content) {
state.copy(paymentState = CoursePurchaseFeature.PaymentState.PaymentPending) to emptySet()
} else {
null
}
}
is Message.StartLearningMessage -> {
if (state is State.Content && state.paymentState is CoursePurchaseFeature.PaymentState.PaymentSuccess) {
state to setOf(Action.ViewAction.StartStudyAction)
} else {
null
}
}
is Message.SetupFeedback -> {
if (state is State.Content && state.paymentState is CoursePurchaseFeature.PaymentState.PaymentFailure) {
state to setOf(Action.GenerateSupportEmailData(message.subject, message.deviceInfo))
} else {
null
}
}
is Message.SetupFeedbackSuccess -> {
if (state is State.Content && state.paymentState is CoursePurchaseFeature.PaymentState.PaymentFailure) {
state to setOf(Action.ViewAction.ShowContactSupport(message.supportEmailData))
} else {
null
}
}
is Message.HavePromoCodeMessage -> {
if (state is State.Content) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Editing) to
setOf(
Action.LogAnalyticEvent(
BuyCoursePromoStartPressedAnalyticEvent(
state.coursePurchaseData.course
)
)
)
} else {
null
}
}
is Message.PromoCodeEditingMessage -> {
if (state is State.Content) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Editing) to emptySet()
} else {
null
}
}
is Message.PromoCodeCheckMessage -> {
if (state is State.Content && state.promoCodeState is CoursePurchaseFeature.PromoCodeState.Editing) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Checking(message.text)) to
setOf(Action.CheckPromoCode(state.coursePurchaseData.course.id, message.text))
} else {
null
}
}
is Message.PromoCodeValidMessage -> {
if (state is State.Content && state.promoCodeState is CoursePurchaseFeature.PromoCodeState.Checking) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Valid(state.promoCodeState.text, message.promoCodeSku)) to
setOf(
Action.LogAnalyticEvent(
BuyCoursePromoSuccessAnalyticEvent(
state.coursePurchaseData.course,
state.promoCodeState.text
)
)
)
} else {
null
}
}
is Message.PromoCodeInvalidMessage -> {
if (state is State.Content && state.promoCodeState is CoursePurchaseFeature.PromoCodeState.Checking) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Invalid) to
setOf(
Action.LogAnalyticEvent(
BuyCoursePromoFailureAnalyticEvent(
state.coursePurchaseData.course,
state.promoCodeState.text
)
)
)
} else {
null
}
}
is Message.WishlistMessage -> {
if (state is State.Content) {
val (wishlistState, wishlistAction) = wishlistOperationReducer.reduce(state.wishlistState, message.wishlistMessage)
val newState = if (message.wishlistMessage is WishlistOperationFeature.Message.WishlistAddSuccess) {
state.copy(
coursePurchaseData = state.coursePurchaseData.copy(isWishlisted = true),
wishlistState = wishlistState
)
} else {
state.copy(wishlistState = wishlistState)
}
newState to wishlistAction.map(Action::WishlistAction).toSet()
} else {
null
}
}
} ?: state to emptySet()
} | apache-2.0 | 66b6c8f00a8306cab9f44531e7f42145 | 52.605898 | 200 | 0.5001 | 6.478937 | false | false | false | false |
glodanif/BluetoothChat | app/src/main/kotlin/com/glodanif/bluetoothchat/ui/presenter/ScanPresenter.kt | 1 | 5682 | package com.glodanif.bluetoothchat.ui.presenter
import android.bluetooth.BluetoothDevice
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.OnLifecycleEvent
import com.glodanif.bluetoothchat.data.model.*
import com.glodanif.bluetoothchat.ui.view.ScanView
import com.glodanif.bluetoothchat.utils.withPotentiallyInstalledApplication
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ScanPresenter(private val view: ScanView,
private val scanner: BluetoothScanner,
private val connection: BluetoothConnector,
private val fileManager: FileManager,
private val preferences: UserPreferences,
private val uiContext: CoroutineDispatcher = Dispatchers.Main,
private val bgContext: CoroutineDispatcher = Dispatchers.IO): BasePresenter(uiContext) {
companion object {
const val SCAN_DURATION_SECONDS = 30
}
init {
scanner.setScanningListener(object : BluetoothScanner.ScanningListener {
override fun onDiscoverableFinish() {
view.showDiscoverableFinished()
}
override fun onDiscoverableStart() {
view.showDiscoverableProcess()
}
override fun onDiscoveryStart(seconds: Int) {
view.showScanningStarted(seconds)
}
override fun onDiscoveryFinish() {
view.showScanningStopped()
}
override fun onDeviceFind(device: BluetoothDevice) {
if (!preferences.isClassificationEnabled() || device.bluetoothClass.withPotentiallyInstalledApplication()) {
view.addFoundDevice(device)
}
}
})
}
fun onDevicePicked(address: String) {
val device = scanner.getDeviceByAddress(address)
if (connection.isConnectionPrepared()) {
connection.addOnConnectListener(connectionListener)
connectDevice(device)
return
}
connection.addOnPrepareListener(object : OnPrepareListener {
override fun onPrepared() {
connectDevice(device)
connection.removeOnPrepareListener(this)
}
override fun onError() {
view.showServiceUnavailable()
connection.removeOnPrepareListener(this)
}
})
connection.prepare()
}
private fun connectDevice(device: BluetoothDevice?) {
if (device != null) {
connection.connect(device)
} else {
view.showServiceUnavailable()
}
}
private val connectionListener = object : SimpleConnectionListener() {
override fun onConnected(device: BluetoothDevice) {
view.openChat(device)
connection.removeOnConnectListener(this)
}
override fun onConnectionLost() {
view.showUnableToConnect()
connection.removeOnConnectListener(this)
}
override fun onConnectionFailed() {
view.showUnableToConnect()
connection.removeOnConnectListener(this)
}
}
fun checkBluetoothAvailability() {
if (scanner.isBluetoothAvailable()) {
view.showBluetoothScanner()
} else {
view.showBluetoothIsNotAvailableMessage()
}
}
fun checkBluetoothEnabling() {
if (scanner.isBluetoothEnabled()) {
onPairedDevicesReady()
if (scanner.isDiscoverable()) {
scanner.listenDiscoverableStatus()
view.showDiscoverableProcess()
} else {
view.showDiscoverableFinished()
}
} else {
view.showBluetoothEnablingRequest()
}
}
fun turnOnBluetooth() {
if (!scanner.isBluetoothEnabled()) {
view.requestBluetoothEnabling()
}
}
fun onPairedDevicesReady() {
val devices = scanner.getBondedDevices().filter {
!preferences.isClassificationEnabled() || it.bluetoothClass.withPotentiallyInstalledApplication()
}
view.showPairedDevices(devices)
}
fun onBluetoothEnablingFailed() {
view.showBluetoothEnablingFailed()
}
fun onMadeDiscoverable() {
scanner.listenDiscoverableStatus()
view.showDiscoverableProcess()
}
fun makeDiscoverable() {
if (!scanner.isDiscoverable()) {
view.requestMakingDiscoverable()
}
}
fun scanForDevices() {
if (!scanner.isDiscovering()) {
scanner.scanForDevices(SCAN_DURATION_SECONDS)
} else {
cancelScanning()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun listenDiscoverableStatus() {
if (scanner.isDiscoverable()) {
scanner.listenDiscoverableStatus()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun cancelScanning() {
view.showScanningStopped()
scanner.stopScanning()
connection.removeOnConnectListener(connectionListener)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun cancelDiscoveryStatusListening() {
scanner.stopListeningDiscoverableStatus()
}
fun shareApk() = this.launch {
val uri = withContext(bgContext) { fileManager.extractApkFile() }
if (uri != null) {
view.shareApk(uri)
} else {
view.showExtractionApkFailureMessage()
}
}
}
| apache-2.0 | f9d4a4a0961cd62761c5b361be6ba74a | 28.440415 | 124 | 0.616332 | 5.285581 | false | false | false | false |
rightfromleft/weather-app | remote/src/main/java/com/rightfromleftsw/weather/remote/WuDeserializer.kt | 1 | 1026 | package com.rightfromleftsw.weather.remote
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.rightfromleftsw.weather.domain.model.Location
import com.rightfromleftsw.weather.remote.model.WeatherModel
import java.lang.reflect.Type
/**
* Created by clivelee on 9/22/17.
*/
class WuDeserializer : JsonDeserializer<WeatherModel> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): WeatherModel {
val currObsv = json.asJsonObject.get("current_observation").asJsonObject
val temperature = currObsv.get("temperatur_string").asString
val locationObj = currObsv.get("display_location").asJsonObject
val longitude = locationObj.get("longitude").asFloat
val latitude = locationObj.get("latitude").asFloat
val timeEpoch = currObsv.get("local_epoch").asLong
return WeatherModel(temperature, Location(longitude, latitude), timeEpoch)
}
} | mit | 2eb10c62078e71469a01d26b0f30f193 | 40.08 | 115 | 0.766082 | 4.46087 | false | false | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/MuzeiApplication.kt | 1 | 3460 | /*
* Copyright 2019 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.google.android.apps.muzei
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.edit
import androidx.fragment.app.strictmode.FragmentReuseViolation
import androidx.fragment.app.strictmode.FragmentStrictMode
import androidx.multidex.MultiDexApplication
import com.google.android.apps.muzei.settings.EffectsScreenFragment
import com.google.android.apps.muzei.settings.Prefs
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase
import net.nurik.roman.muzei.BuildConfig
class MuzeiApplication : MultiDexApplication(), SharedPreferences.OnSharedPreferenceChangeListener {
companion object {
private const val ALWAYS_DARK_KEY = "always_dark"
fun setAlwaysDark(context: Context, alwaysDark: Boolean) {
Prefs.getSharedPreferences(context).edit {
putBoolean(ALWAYS_DARK_KEY, alwaysDark)
}
}
fun getAlwaysDark(context: Context) =
Prefs.getSharedPreferences(context).getBoolean(ALWAYS_DARK_KEY, false)
}
override fun onCreate() {
super.onCreate()
FragmentStrictMode.defaultPolicy = FragmentStrictMode.Policy.Builder()
.detectFragmentReuse()
.detectFragmentTagUsage()
.detectRetainInstanceUsage()
.detectSetUserVisibleHint()
.detectTargetFragmentUsage()
.detectWrongFragmentContainer()
.allowViolation(
EffectsScreenFragment::class.java,
FragmentReuseViolation::class.java
) // https://issuetracker.google.com/issues/191698791
.apply {
if (BuildConfig.DEBUG) {
// Log locally on debug builds
penaltyLog()
} else {
// Log to Crashlytics on release builds
penaltyListener {
Firebase.crashlytics.recordException(it)
}
}
}
.build()
updateNightMode()
val sharedPreferences = Prefs.getSharedPreferences(this)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key == ALWAYS_DARK_KEY) {
updateNightMode()
}
}
private fun updateNightMode() {
val alwaysDark = getAlwaysDark(this)
AppCompatDelegate.setDefaultNightMode(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !alwaysDark)
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
else
AppCompatDelegate.MODE_NIGHT_YES
)
}
} | apache-2.0 | 6ca1da1edda3c75cf9bbb3dda13859be | 36.215054 | 100 | 0.662717 | 5.02907 | false | false | false | false |
leafclick/intellij-community | platform/platform-api/src/com/intellij/openapi/rd/RdIdea.kt | 1 | 2381 | // 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.openapi.rd
import com.intellij.openapi.wm.IdeGlassPane
import com.intellij.ui.paint.LinePainter2D
import com.intellij.ui.paint.RectanglePainter2D
import com.jetbrains.rd.swing.awtMousePoint
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.IPropertyView
import com.jetbrains.rd.util.reactive.ISource
import com.jetbrains.rd.util.reactive.map
import java.awt.*
import java.awt.event.MouseEvent
import java.awt.event.MouseMotionAdapter
import javax.swing.JComponent
import javax.swing.SwingUtilities
fun IdeGlassPane.mouseMoved(): ISource<MouseEvent> {
return object : ISource<MouseEvent> {
override fun advise(lifetime: Lifetime, handler: (MouseEvent) -> Unit) {
val listener = object : MouseMotionAdapter() {
override fun mouseMoved(e: MouseEvent?) {
if (e != null) {
handler(e)
}
}
}
[email protected](listener, lifetime.createNestedDisposable())
}
}
}
fun IdeGlassPane.childAtMouse(container: Container): ISource<Component?> = [email protected]()
.map { SwingUtilities.convertPoint(it.component, it.x, it.y, container) }
.map { container.getComponentAt(it) }
fun JComponent.childAtMouse(): IPropertyView<Component?> = [email protected]()
.map {
if (it == null) null
else {
[email protected](it)
}
}
fun Graphics2D.fill2DRect(rect: Rectangle, color: Color) {
this.color = color
RectanglePainter2D.FILL.paint(this, rect.x.toDouble(), rect.y.toDouble(), rect.width.toDouble(), rect.height.toDouble())
}
fun Graphics2D.paint2DLine(from: Point, to: Point,
strokeType: LinePainter2D.StrokeType,
strokeWidth: Double, color: Color) {
this.paint2DLine(from.getX(), from.getY(), to.getX(), to.getY(), strokeType, strokeWidth, color)
}
fun Graphics2D.paint2DLine(x1: Double, y1: Double, x2: Double, y2: Double,
strokeType: LinePainter2D.StrokeType,
strokeWidth: Double, color: Color) {
this.color = color
LinePainter2D.paint(this, x1, y1, x2, y2, strokeType,
strokeWidth)
}
| apache-2.0 | daada05540168cbe33059cde5523ef22 | 35.630769 | 140 | 0.699706 | 3.785374 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reified/varargs.kt | 2 | 611 | // WITH_RUNTIME
import kotlin.test.assertEquals
fun <T> foo(vararg a: T) = a.size
inline fun <reified T> bar(block: () -> T): Array<T> {
assertEquals(2, foo(block(), block()))
return arrayOf(block(), block(), block())
}
inline fun <reified T> empty() = arrayOf<T>()
fun box(): String {
var i = 0
val a: Array<String> = bar() { i++; i.toString() }
assertEquals("345", a.joinToString(""))
i = 0
val b: Array<Int> = bar() { i++ }
assertEquals("234", b.map { it.toString() }.joinToString(""))
val c: Array<String> = empty()
assertEquals(0, c.size)
return "OK"
}
| apache-2.0 | 8065e644171e3a24f4c547a60e9d23ea | 20.821429 | 65 | 0.577741 | 3.198953 | false | false | false | false |
JuliusKunze/kotlin-native | shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/ClangArgs.kt | 1 | 5915 | /*
* 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 -> in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.konan.target
import org.jetbrains.kotlin.konan.properties.KonanProperties
import org.jetbrains.kotlin.konan.file.File
class ClangTargetArgs(val target: KonanTarget, konanProperties: KonanProperties) {
val sysRoot = konanProperties.absoluteTargetSysRoot
val targetArg = konanProperties.targetArg
val specificClangArgs: List<String> get() {
val result = when (target) {
KonanTarget.LINUX ->
listOf("--sysroot=$sysRoot",
"-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=64")
KonanTarget.RASPBERRYPI ->
listOf("-target", targetArg!!,
"-mfpu=vfp", "-mfloat-abi=hard",
"-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=32",
"--sysroot=$sysRoot",
// TODO: those two are hacks.
"-I$sysRoot/usr/include/c++/4.8.3",
"-I$sysRoot/usr/include/c++/4.8.3/arm-linux-gnueabihf")
KonanTarget.LINUX_MIPS32 ->
listOf("-target", targetArg!!,
"-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=32",
"--sysroot=$sysRoot",
"-I$sysRoot/usr/include/c++/4.9.4",
"-I$sysRoot/usr/include/c++/4.9.4/mips-unknown-linux-gnu")
KonanTarget.LINUX_MIPSEL32 ->
listOf("-target", targetArg!!,
"-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=32",
"--sysroot=$sysRoot",
"-I$sysRoot/usr/include/c++/4.9.4",
"-I$sysRoot/usr/include/c++/4.9.4/mipsel-unknown-linux-gnu")
KonanTarget.MINGW ->
listOf("-target", targetArg!!, "--sysroot=$sysRoot",
"-DUSE_GCC_UNWIND=1", "-DUSE_PE_COFF_SYMBOLS=1", "-DKONAN_WINDOWS=1", "-Xclang", "-flto-visibility-public-std")
KonanTarget.MACBOOK ->
listOf("--sysroot=$sysRoot", "-mmacosx-version-min=10.11", "-DKONAN_OSX=1",
"-DKONAN_OBJC_INTEROP=1")
KonanTarget.IPHONE ->
listOf("-stdlib=libc++", "-arch", "arm64", "-isysroot", sysRoot, "-miphoneos-version-min=8.0.0",
"-DKONAN_OBJC_INTEROP=1")
KonanTarget.IPHONE_SIM ->
listOf("-stdlib=libc++", "-isysroot", sysRoot, "-miphoneos-version-min=8.0.0",
"-DKONAN_OBJC_INTEROP=1")
KonanTarget.ANDROID_ARM32 ->
listOf("-target", targetArg!!,
"--sysroot=$sysRoot",
"-D__ANDROID__", "-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=32", "-DKONAN_ANDROID",
// HACKS!
"-I$sysRoot/usr/include/c++/4.9.x",
"-I$sysRoot/usr/include/c++/4.9.x/arm-linux-androideabi")
KonanTarget.ANDROID_ARM64 ->
listOf("-target", targetArg!!,
"--sysroot=$sysRoot",
"-D__ANDROID__", "-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=64", "-DKONAN_ANDROID",
// HACKS!
"-I$sysRoot/usr/include/c++/4.9.x",
"-I$sysRoot/usr/include/c++/4.9.x/aarch64-linux-android")
KonanTarget.WASM32 ->
listOf("-target", targetArg!!, "-O1", "-fno-rtti", "-fno-exceptions", "-DKONAN_WASM=1",
"-D_LIBCPP_ABI_VERSION=2", "-D_LIBCPP_NO_EXCEPTIONS=1", "-DKONAN_NO_FFI=1", "-DKONAN_NO_THREADS=1", "-DKONAN_NO_EXCEPTIONS=1",
"-DKONAN_INTERNAL_DLMALLOC=1", "-DKONAN_INTERNAL_SNPRINTF=1", "-DKONAN_INTERNAL_NOW=1",
"-nostdinc", "-Xclang", "-nobuiltininc", "-Xclang", "-nostdsysteminc",
"-Xclang", "-isystem$sysRoot/include/libcxx", "-Xclang", "-isystem$sysRoot/lib/libcxxabi/include",
"-Xclang", "-isystem$sysRoot/include/compat", "-Xclang", "-isystem$sysRoot/include/libc")
}
return result
}
}
class ClangHostArgs(val hostProperties: KonanProperties) {
val targetToolchain get() = hostProperties.absoluteTargetToolchain
val gccToolchain get() = hostProperties.absoluteGccToolchain
val sysRoot get() = hostProperties.absoluteTargetSysRoot
val llvmDir get() = hostProperties.absoluteLlvmHome
val binDir = when(TargetManager.host) {
KonanTarget.LINUX -> "$targetToolchain/bin"
KonanTarget.MINGW -> "$sysRoot/bin"
KonanTarget.MACBOOK -> "$targetToolchain/usr/bin"
else -> throw TargetSupportException("Unexpected host platform")
}
private val extraHostClangArgs =
if (TargetManager.host == KonanTarget.LINUX) {
listOf("--gcc-toolchain=$gccToolchain")
} else {
emptyList()
}
val commonClangArgs = listOf("-B$binDir") + extraHostClangArgs
val hostClangPath = listOf("$llvmDir/bin", binDir)
private val jdkHome = File.jdkHome.absoluteFile.parent
val hostCompilerArgsForJni = listOf("", TargetManager.jniHostPlatformIncludeDir).map { "-I$jdkHome/include/$it" }
}
| apache-2.0 | 2d95668b0bee8538046a6de0386e8540 | 45.210938 | 150 | 0.560609 | 3.85342 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/CallSemanticsActionTest.kt | 3 | 2551 | /*
* 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.test
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.AccessibilityAction
import androidx.compose.ui.semantics.SemanticsPropertyKey
import androidx.compose.ui.semantics.SemanticsPropertyReceiver
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.filters.MediumTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import androidx.test.ext.junit.runners.AndroidJUnit4
@MediumTest
@RunWith(AndroidJUnit4::class)
class CallSemanticsActionTest {
@get:Rule
val rule = createComposeRule()
@Test
fun performSemanticsAction() {
rule.setContent {
val state = remember { mutableStateOf("Nothing") }
BoundaryNode {
setString("SetString") { state.value = it; return@setString true }
contentDescription = state.value
}
}
rule.onNodeWithContentDescription("Nothing")
.assertExists()
.performSemanticsAction(MyActions.SetString) { it("Hello") }
.assertDoesNotExist()
rule.onNodeWithContentDescription("Hello")
.assertExists()
}
object MyActions {
val SetString = SemanticsPropertyKey<AccessibilityAction<(String) -> Boolean>>("SetString")
}
fun SemanticsPropertyReceiver.setString(label: String? = null, action: (String) -> Boolean) {
this[MyActions.SetString] = AccessibilityAction(label, action)
}
@Composable
fun BoundaryNode(props: (SemanticsPropertyReceiver.() -> Unit)) {
Column(Modifier.semantics(properties = props)) {}
}
} | apache-2.0 | 1d123569f02ad805c64947f0d920bc1a | 33.486486 | 99 | 0.727166 | 4.596396 | false | true | false | false |
smmribeiro/intellij-community | platform/testFramework/src/com/intellij/simpleApplicationBootstrapper.kt | 3 | 3204 | // 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
import com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory
import com.intellij.diagnostic.LoadingState
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.ThreadDumper
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginSet
import com.intellij.idea.Main
import com.intellij.idea.callAppInitialized
import com.intellij.idea.initConfigurationStore
import com.intellij.idea.preloadServices
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.util.RecursionManager
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryKeyBean
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl
import com.intellij.testFramework.UITestUtil
import com.intellij.util.SystemProperties
import java.awt.EventQueue
import java.util.concurrent.ExecutionException
import java.util.concurrent.ForkJoinTask
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
fun loadHeadlessAppInUnitTestMode() {
doLoadApp {
EventQueue.invokeAndWait {
// replaces system event queue
IdeEventQueue.getInstance()
}
}
}
internal fun doLoadApp(setupEventQueue: () -> Unit) {
var isHeadless = true
if (System.getProperty("java.awt.headless") == "false") {
isHeadless = false
}
else {
UITestUtil.setHeadlessProperty(true)
}
Main.setHeadlessInTestMode(isHeadless)
PluginManagerCore.isUnitTestMode = true
IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool(true)
PluginManagerCore.scheduleDescriptorLoading()
val loadedModuleFuture = PluginManagerCore.getInitPluginFuture()
setupEventQueue()
val app = ApplicationImpl(true, true, isHeadless, true)
if (SystemProperties.getBooleanProperty("tests.assertOnMissedCache", true)) {
RecursionManager.assertOnMissedCache(app)
}
val pluginSet: PluginSet
try {
// 40 seconds - tests maybe executed on cloud agents where IO speed is a very slow
pluginSet = loadedModuleFuture.get(40, TimeUnit.SECONDS)
app.registerComponents(modules = pluginSet.getEnabledModules(), app = app, precomputedExtensionModel = null, listenerCallbacks = null)
initConfigurationStore(app)
RegistryKeyBean.addKeysFromPlugins()
Registry.markAsLoaded()
val preloadServiceFuture = preloadServices(pluginSet.getEnabledModules(), app, activityPrefix = "")
app.loadComponents()
preloadServiceFuture.get(40, TimeUnit.SECONDS)
ForkJoinTask.invokeAll(callAppInitialized(app))
StartUpMeasurer.setCurrentState(LoadingState.APP_STARTED)
(PersistentFS.getInstance() as PersistentFSImpl).cleanPersistedContents()
}
catch (e: TimeoutException) {
throw RuntimeException("Cannot preload services in 40 seconds: ${ThreadDumper.dumpThreadsToString()}", e)
}
catch (e: ExecutionException) {
throw e.cause ?: e
}
catch (e: InterruptedException) {
throw e.cause ?: e
}
}
| apache-2.0 | 523b8c3b0f68adcb85cf771b465194fe | 35.827586 | 138 | 0.794944 | 4.544681 | false | true | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/extensions/python/PyCallExpressionExt.kt | 13 | 975 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.extensions.python
import com.jetbrains.python.nameResolver.FQNamesProvider
import com.jetbrains.python.nameResolver.NameResolverTools
import com.jetbrains.python.psi.PyAssignmentStatement
import com.jetbrains.python.psi.PyCallExpression
import com.jetbrains.python.psi.PyPossibleClassMember
/**
* Checks if ``foo = SomeExpr()`` where foo is class attribute
*/
val PyCallExpression.isClassAttribute: Boolean
get() =
(parent as? PyAssignmentStatement)?.targets?.filterIsInstance<PyPossibleClassMember>()?.any { it.containingClass != null } == true
/**
* Checks if callee has certain name. Only name is checked, so import aliases aren't supported, but it works pretty fast
*/
fun PyCallExpression.isCalleeName(vararg names: FQNamesProvider): Boolean = NameResolverTools.isCalleeShortCut(this, *names)
| apache-2.0 | e3d35aee5d6818d7823bb41c1068a73c | 45.428571 | 140 | 0.794872 | 4.372197 | false | false | false | false |
firebase/firebase-android-sdk | tools/lint/src/main/kotlin/ProviderAssignmentDetector.kt | 1 | 3797 | // 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.google.firebase.lint.checks
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UBinaryExpression
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UReferenceExpression
import org.jetbrains.uast.getParentOfType
private const val PROVIDER = "com.google.firebase.inject.Provider"
@Suppress("DetectorIsMissingAnnotations")
class ProviderAssignmentDetector : Detector(), SourceCodeScanner {
override fun getApplicableMethodNames() = listOf("get")
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (!isProviderGet(method)) {
return
}
val binaryOperation = node.getParentOfType<UBinaryExpression>(true) ?: return
if (binaryOperation.operatorIdentifier?.name != "=") return
val assignmentTarget = binaryOperation.leftOperand as? UReferenceExpression ?: return
// This would only be true if assigning the result of get(),
// in cases like foo = p.get().someMethod() there would be an intermediate parent
// and we don't want to trigger in such cases.
if (binaryOperation != node.uastParent?.uastParent) {
return
}
if (hasDeferredApiAnnotation(context, binaryOperation)) {
return
}
assignmentTarget.resolve()?.let {
if (it is PsiField) {
context.report(
INVALID_PROVIDER_ASSIGNMENT,
context.getCallLocation(node, includeReceiver = false, includeArguments = true),
"`Provider.get()` assignment to a field detected"
)
}
}
}
private fun isProviderGet(method: PsiMethod): Boolean {
if (!method.parameterList.isEmpty) {
return false
}
(method.parent as? PsiClass)?.let {
return it.qualifiedName == PROVIDER
}
return false
}
companion object {
private val IMPLEMENTATION =
Implementation(ProviderAssignmentDetector::class.java, Scope.JAVA_FILE_SCOPE)
/** Calling methods on the wrong thread */
@JvmField
val INVALID_PROVIDER_ASSIGNMENT =
Issue.create(
id = "ProviderAssignment",
briefDescription = "Invalid use of Provider<T>",
explanation =
"""
Ensures that results of `Provider.get()` are not stored in class fields. Doing \
so may lead to bugs in the context of dynamic feature loading. Namely, optional \
provider dependencies can become available during the execution of the app, so \
dependents must be ready to handle this situation.
""",
category = Category.CORRECTNESS,
priority = 6,
severity = Severity.ERROR,
implementation = IMPLEMENTATION
)
}
}
| apache-2.0 | 3e7bfc986392dfab7aaef43a55388a68 | 35.864078 | 101 | 0.708454 | 4.569194 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/visitor/KotlinMatchingVisitor.kt | 1 | 67170 | // 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.structuralsearch.visitor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.elementType
import com.intellij.structuralsearch.StructuralSearchUtil
import com.intellij.structuralsearch.impl.matcher.CompiledPattern
import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor
import com.intellij.structuralsearch.impl.matcher.handlers.LiteralWithSubstitutionHandler
import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler
import com.intellij.util.containers.reverse
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl
import org.jetbrains.kotlin.fir.builder.toUnaryName
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.calleeName
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.structuralsearch.*
import org.jetbrains.kotlin.kdoc.lexer.KDocTokens
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.kdoc.psi.impl.KDocImpl
import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink
import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.util.OperatorNameConventions
class KotlinMatchingVisitor(private val myMatchingVisitor: GlobalMatchingVisitor) : SSRKtVisitor() {
/** Gets the next element in the query tree and removes unnecessary parentheses. */
private inline fun <reified T> getTreeElementDepar(): T? = when (val element = myMatchingVisitor.element) {
is KtParenthesizedExpression -> {
val deparenthesized = element.deparenthesize()
if (deparenthesized is T) deparenthesized else {
myMatchingVisitor.result = false
null
}
}
else -> getTreeElement<T>()
}
/** Gets the next element in the tree */
private inline fun <reified T> getTreeElement(): T? = when (val element = myMatchingVisitor.element) {
is T -> element
else -> {
myMatchingVisitor.result = false
null
}
}
private fun GlobalMatchingVisitor.matchSequentially(elements: List<PsiElement?>, elements2: List<PsiElement?>) =
matchSequentially(elements.toTypedArray(), elements2.toTypedArray())
private fun GlobalMatchingVisitor.matchInAnyOrder(elements: List<PsiElement?>, elements2: List<PsiElement?>) =
matchInAnyOrder(elements.toTypedArray(), elements2.toTypedArray())
private fun GlobalMatchingVisitor.matchNormalized(
element: KtExpression?,
element2: KtExpression?,
returnExpr: Boolean = false
): Boolean {
val (e1, e2) =
if (element is KtBlockExpression && element2 is KtBlockExpression) element to element2
else normalizeExpressions(element, element2, returnExpr)
val impossible = e1?.let {
val handler = getHandler(it)
e2 !is KtBlockExpression && handler is SubstitutionHandler && handler.minOccurs > 1
} ?: false
return !impossible && match(e1, e2)
}
private fun getHandler(element: PsiElement) = myMatchingVisitor.matchContext.pattern.getHandler(element)
private fun matchTextOrVariable(el1: PsiElement?, el2: PsiElement?): Boolean {
if (el1 == null) return true
if (el2 == null) return el1 == el2
return when (val handler = getHandler(el1)) {
is SubstitutionHandler -> handler.validate(el2, myMatchingVisitor.matchContext)
else -> myMatchingVisitor.matchText(el1, el2)
}
}
override fun visitLeafPsiElement(leafPsiElement: LeafPsiElement) {
val other = getTreeElementDepar<LeafPsiElement>() ?: return
// Match element type
if (!myMatchingVisitor.setResult(leafPsiElement.elementType == other.elementType)) return
when (leafPsiElement.elementType) {
KDocTokens.TEXT -> {
myMatchingVisitor.result = when (val handler = leafPsiElement.getUserData(CompiledPattern.HANDLER_KEY)) {
is LiteralWithSubstitutionHandler -> handler.match(leafPsiElement, other, myMatchingVisitor.matchContext)
else -> matchTextOrVariable(leafPsiElement, other)
}
}
KDocTokens.TAG_NAME, KtTokens.IDENTIFIER -> myMatchingVisitor.result = matchTextOrVariable(leafPsiElement, other)
}
}
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
myMatchingVisitor.result = when (other) {
is KtArrayAccessExpression -> myMatchingVisitor.match(expression.arrayExpression, other.arrayExpression)
&& myMatchingVisitor.matchSons(expression.indicesNode, other.indicesNode)
is KtDotQualifiedExpression -> myMatchingVisitor.match(expression.arrayExpression, other.receiverExpression)
&& other.calleeName == "${OperatorNameConventions.GET}"
&& myMatchingVisitor.matchSequentially(
expression.indexExpressions, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!!
)
else -> false
}
}
/** Matches binary expressions including translated operators. */
override fun visitBinaryExpression(expression: KtBinaryExpression) {
fun KtBinaryExpression.match(other: KtBinaryExpression) = operationToken == other.operationToken
&& myMatchingVisitor.match(left, other.left)
&& myMatchingVisitor.match(right, other.right)
fun KtQualifiedExpression.match(name: Name?, receiver: KtExpression?, callEntry: KtExpression?): Boolean {
val callExpr = callExpression
return callExpr is KtCallExpression && calleeName == "$name"
&& myMatchingVisitor.match(receiver, receiverExpression)
&& myMatchingVisitor.match(callEntry, callExpr.valueArguments.first().getArgumentExpression())
}
fun KtBinaryExpression.matchEq(other: KtBinaryExpression): Boolean {
val otherLeft = other.left?.deparenthesize()
val otherRight = other.right?.deparenthesize()
return otherLeft is KtSafeQualifiedExpression
&& otherLeft.match(OperatorNameConventions.EQUALS, left, right)
&& other.operationToken == KtTokens.ELVIS
&& otherRight is KtBinaryExpression
&& myMatchingVisitor.match(right, otherRight.left)
&& otherRight.operationToken == KtTokens.EQEQEQ
&& myMatchingVisitor.match(KtPsiFactory(other, true).createExpression("null"), otherRight.right)
}
val other = getTreeElementDepar<KtExpression>() ?: return
when (other) {
is KtBinaryExpression -> {
val token = expression.operationToken
if (token in augmentedAssignmentsMap.keys && other.operationToken == KtTokens.EQ) {
// Matching x ?= y with x = x ? y
val right = other.right?.deparenthesize()
val left = other.left?.deparenthesize()
myMatchingVisitor.result = right is KtBinaryExpression
&& augmentedAssignmentsMap[token] == right.operationToken
&& myMatchingVisitor.match(expression.left, left)
&& myMatchingVisitor.match(expression.left, right.left)
&& myMatchingVisitor.match(expression.right, right.right)
return
}
if (token == KtTokens.EQ) {
val right = expression.right?.deparenthesize()
if (right is KtBinaryExpression && right.operationToken == augmentedAssignmentsMap[other.operationToken]) {
// Matching x = x ? y with x ?= y
myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.left)
&& myMatchingVisitor.match(right.left, other.left)
&& myMatchingVisitor.match(right.right, other.right)
return
}
}
if (myMatchingVisitor.setResult(expression.match(other))) return
when (expression.operationToken) { // translated matching
KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ -> { // a.compareTo(b) OP 0
val left = other.left?.deparenthesize()
myMatchingVisitor.result = left is KtDotQualifiedExpression
&& left.match(OperatorNameConventions.COMPARE_TO, expression.left, expression.right)
&& expression.operationToken == other.operationToken
&& myMatchingVisitor.match(other.right, KtPsiFactory(other, true).createExpression("0"))
}
KtTokens.EQEQ -> { // match a?.equals(b) ?: (b === null)
myMatchingVisitor.result = expression.matchEq(other)
}
}
}
is KtDotQualifiedExpression -> { // translated matching
val token = expression.operationToken
val left = expression.left
val right = expression.right
when {
token == KtTokens.IN_KEYWORD -> { // b.contains(a)
val parent = other.parent
val isNotNegated = if (parent is KtPrefixExpression) parent.operationToken != KtTokens.EXCL else true
myMatchingVisitor.result = isNotNegated && other.match(OperatorNameConventions.CONTAINS, right, left)
}
token == KtTokens.NOT_IN -> myMatchingVisitor.result = false // already matches with prefix expression
token == KtTokens.EQ && left is KtArrayAccessExpression -> { // a[x] = expression
val matchedArgs = left.indexExpressions.apply { add(right) }
myMatchingVisitor.result = myMatchingVisitor.match(left.arrayExpression, other.receiverExpression)
&& other.calleeName == "${OperatorNameConventions.SET}"
&& myMatchingVisitor.matchSequentially(
matchedArgs, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!!
)
}
else -> { // a.plus(b) all arithmetic operators
val selector = other.selectorExpression
if (expression.operationToken == KtTokens.EQ && right is KtBinaryExpression) {
// Matching x = x + y with x.plusAssign(y)
val opName = augmentedAssignmentsMap.reverse()[right.operationToken]?.binaryExprOpName()
myMatchingVisitor.result = selector is KtCallExpression
&& myMatchingVisitor.match(left, other.receiverExpression)
&& other.match(opName, right.left, right.right)
} else {
myMatchingVisitor.result = selector is KtCallExpression && other.match(
expression.operationToken.binaryExprOpName(), left, right
)
}
}
}
}
is KtPrefixExpression -> { // translated matching
val baseExpr = other.baseExpression?.deparenthesize()
when (expression.operationToken) {
KtTokens.NOT_IN -> { // !b.contains(a)
myMatchingVisitor.result = other.operationToken == KtTokens.EXCL
&& baseExpr is KtDotQualifiedExpression
&& baseExpr.match(OperatorNameConventions.CONTAINS, expression.right, expression.left)
}
KtTokens.EXCLEQ -> { // !(a?.equals(b) ?: (b === null))
myMatchingVisitor.result = other.operationToken == KtTokens.EXCL
&& baseExpr is KtBinaryExpression
&& expression.matchEq(baseExpr)
}
}
}
else -> myMatchingVisitor.result = false
}
}
override fun visitBlockExpression(expression: KtBlockExpression) {
val other = getTreeElementDepar<KtBlockExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.statements, other.statements)
}
override fun visitUnaryExpression(expression: KtUnaryExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
myMatchingVisitor.result = when (other) {
is KtDotQualifiedExpression -> {
myMatchingVisitor.match(expression.baseExpression, other.receiverExpression)
&& expression.operationToken.toUnaryName().toString() == other.calleeName
}
is KtUnaryExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression)
&& myMatchingVisitor.match(expression.operationReference, other.operationReference)
else -> false
}
}
override fun visitParenthesizedExpression(expression: KtParenthesizedExpression) {
fun KtExpression.countParenthesize(initial: Int = 0): Int {
val parentheses = children.firstOrNull { it is KtParenthesizedExpression } as KtExpression?
return parentheses?.countParenthesize(initial + 1) ?: initial
}
val other = getTreeElement<KtParenthesizedExpression>() ?: return
if (!myMatchingVisitor.setResult(expression.countParenthesize() == other.countParenthesize())) return
myMatchingVisitor.result = myMatchingVisitor.match(expression.deparenthesize(), other.deparenthesize())
}
override fun visitConstantExpression(expression: KtConstantExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
myMatchingVisitor.result = matchTextOrVariable(expression, other)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val other = getTreeElementDepar<PsiElement>() ?: return
val exprHandler = getHandler(expression)
if (other is KtReferenceExpression && exprHandler is SubstitutionHandler) {
try {
val referenced = other.mainReference.resolve()
if (referenced is KtClass || referenced is KtTypeAlias) {
val fqName = referenced.getKotlinFqName()
val predicate = exprHandler.findRegExpPredicate()
if (predicate != null && fqName != null &&
predicate.doMatch(fqName.asString(), myMatchingVisitor.matchContext, other)
) {
myMatchingVisitor.result = true
exprHandler.addResult(other, myMatchingVisitor.matchContext)
return
}
}
} catch (e: Error) {
}
}
// Match Int::class with X.Int::class
val skipReceiver = other.parent is KtDoubleColonExpression
&& other is KtDotQualifiedExpression
&& myMatchingVisitor.match(expression, other.selectorExpression)
myMatchingVisitor.result = skipReceiver || matchTextOrVariable(
expression.getReferencedNameElement(),
if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other
)
val handler = getHandler(expression.getReferencedNameElement())
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(
if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other,
myMatchingVisitor.matchContext
)
}
}
override fun visitContinueExpression(expression: KtContinueExpression) {
val other = getTreeElementDepar<KtContinueExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
}
override fun visitBreakExpression(expression: KtBreakExpression) {
val other = getTreeElementDepar<KtBreakExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
}
override fun visitThisExpression(expression: KtThisExpression) {
val other = getTreeElementDepar<KtThisExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
}
override fun visitSuperExpression(expression: KtSuperExpression) {
val other = getTreeElementDepar<KtSuperExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
&& myMatchingVisitor.match(expression.superTypeQualifier, other.superTypeQualifier)
}
override fun visitReturnExpression(expression: KtReturnExpression) {
val other = getTreeElementDepar<KtReturnExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
&& myMatchingVisitor.match(expression.returnedExpression, other.returnedExpression)
}
override fun visitFunctionType(type: KtFunctionType) {
val other = getTreeElementDepar<KtFunctionType>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(type.receiverTypeReference, other.receiverTypeReference)
&& myMatchingVisitor.match(type.parameterList, other.parameterList)
&& myMatchingVisitor.match(type.returnTypeReference, other.returnTypeReference)
}
override fun visitUserType(type: KtUserType) {
val other = myMatchingVisitor.element
myMatchingVisitor.result = when (other) {
is KtUserType -> {
type.qualifier?.let { typeQualifier -> // if query has fq type
myMatchingVisitor.match(typeQualifier, other.qualifier) // recursively match qualifiers
&& myMatchingVisitor.match(type.referenceExpression, other.referenceExpression)
&& myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList)
} ?: let { // no fq type
myMatchingVisitor.match(type.referenceExpression, other.referenceExpression)
&& myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList)
}
}
is KtTypeElement -> matchTextOrVariable(type.referenceExpression, other)
else -> false
}
}
override fun visitNullableType(nullableType: KtNullableType) {
val other = getTreeElementDepar<KtNullableType>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(nullableType.innerType, other.innerType)
}
override fun visitDynamicType(type: KtDynamicType) {
myMatchingVisitor.result = myMatchingVisitor.element is KtDynamicType
}
private fun matchTypeReferenceWithDeclaration(typeReference: KtTypeReference?, other: KtDeclaration): Boolean {
val type = other.resolveKotlinType()
if (type != null) {
val fqType = DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type)
val factory = KtPsiFactory(other, true)
val analzyableFile = factory.createAnalyzableFile("${other.hashCode()}.kt", "val x: $fqType = TODO()", other)
return myMatchingVisitor.match(typeReference, (analzyableFile.lastChild as KtProperty).typeReference)
}
return false
}
override fun visitTypeReference(typeReference: KtTypeReference) {
val other = getTreeElementDepar<KtTypeReference>() ?: return
val parent = other.parent
val isReceiverTypeReference = when (parent) {
is KtProperty -> parent.receiverTypeReference == other
is KtNamedFunction -> parent.receiverTypeReference == other
else -> false
}
val type = when {
!isReceiverTypeReference && parent is KtProperty -> parent.resolveKotlinType()
isReceiverTypeReference && parent is KtDeclaration && parent.descriptor is FunctionDescriptor ->
(parent.descriptor as FunctionDescriptor).extensionReceiverParameter?.value?.type
isReceiverTypeReference && parent is KtDeclaration && parent.descriptor is PropertyDescriptorImpl ->
(parent.descriptor as PropertyDescriptorImpl).extensionReceiverParameter?.value?.type
else -> null
}
val fqMatch = when {
type != null -> {
val handler = getHandler(typeReference)
type.renderNames().any {
if (handler is SubstitutionHandler)
if (handler.findRegExpPredicate()?.doMatch(it, myMatchingVisitor.matchContext, other) == true) {
handler.addResult(other, myMatchingVisitor.matchContext)
true
} else false
else myMatchingVisitor.matchText(typeReference.text, it)
}
}
else -> false
}
myMatchingVisitor.result = fqMatch || myMatchingVisitor.matchSons(typeReference, other)
}
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
val other = getTreeElementDepar<KtQualifiedExpression>() ?: return
myMatchingVisitor.result = expression.operationSign == other.operationSign
&& myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression)
&& myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression)
}
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
val handler = getHandler(expression.receiverExpression)
if (other is KtDotQualifiedExpression) {
// Regular matching
myMatchingVisitor.result = myMatchingVisitor.matchOptionally(expression.receiverExpression, other.receiverExpression)
&& other.selectorExpression is KtCallExpression == expression.selectorExpression is KtCallExpression
&& myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression)
} else {
val selector = expression.selectorExpression
// Match '_?.'_()
myMatchingVisitor.result = selector is KtCallExpression == other is KtCallExpression
&& (handler is SubstitutionHandler && handler.minOccurs == 0 || other.parent is KtDoubleColonExpression)
&& other.parent !is KtDotQualifiedExpression
&& other.parent !is KtReferenceExpression
&& myMatchingVisitor.match(selector, other)
// Match fq.call() with call()
if (!myMatchingVisitor.result && other is KtCallExpression && other.parent !is KtDotQualifiedExpression && selector is KtCallExpression) {
val expressionCall = expression.text.substringBefore('(')
val otherCall = other.getCallableDescriptor()?.fqNameSafe
myMatchingVisitor.result = otherCall != null
&& myMatchingVisitor.matchText(expressionCall, otherCall.toString().substringBefore(".<"))
&& myMatchingVisitor.match(selector.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(resolveParameters(other),
selector.valueArgumentList, other.valueArgumentList,
selector.lambdaArguments, other.lambdaArguments)
}
}
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
val other = getTreeElementDepar<KtLambdaExpression>() ?: return
val lambdaVP = lambdaExpression.valueParameters
val otherVP = other.valueParameters
myMatchingVisitor.result =
(!lambdaExpression.functionLiteral.hasParameterSpecification()
|| myMatchingVisitor.matchSequentially(lambdaVP, otherVP)
|| lambdaVP.map { p -> getHandler(p).let { if (it is SubstitutionHandler) it.minOccurs else 1 } }.sum() == 1
&& !other.functionLiteral.hasParameterSpecification()
&& (other.functionLiteral.descriptor as AnonymousFunctionDescriptor).valueParameters.size == 1)
&& myMatchingVisitor.match(lambdaExpression.bodyExpression, other.bodyExpression)
}
override fun visitTypeProjection(typeProjection: KtTypeProjection) {
val other = getTreeElementDepar<KtTypeProjection>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(typeProjection.typeReference, other.typeReference)
&& myMatchingVisitor.match(typeProjection.modifierList, other.modifierList)
&& typeProjection.projectionKind == other.projectionKind
}
override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) {
val other = getTreeElementDepar<KtTypeArgumentList>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(typeArgumentList.arguments, other.arguments)
}
override fun visitArgument(argument: KtValueArgument) {
val other = getTreeElementDepar<KtValueArgument>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(argument.getArgumentExpression(), other.getArgumentExpression())
&& (!argument.isNamed() || !other.isNamed() || matchTextOrVariable(
argument.getArgumentName(), other.getArgumentName()
))
}
private fun MutableList<KtValueArgument>.addDefaultArguments(parameters: List<KtParameter?>) {
if (parameters.isEmpty()) return
val params = parameters.toTypedArray()
var i = 0
while (i < size) {
val arg = get(i)
if (arg.isNamed()) {
params[parameters.indexOfFirst { it?.nameAsName == arg.getArgumentName()?.asName }] = null
i++
} else {
val curParam = params[i] ?: throw IllegalStateException(
KotlinBundle.message("error.param.can.t.be.null.at.index.0.in.1", i, params.map { it?.text })
)
params[i] = null
if (curParam.isVarArg) {
val varArgType = arg.getArgumentExpression()?.resolveType()
var curArg: KtValueArgument? = arg
while (varArgType == curArg?.getArgumentExpression()?.resolveType() || curArg?.isSpread == true) {
i++
curArg = getOrNull(i)
}
} else i++
}
}
val psiFactory = KtPsiFactory(myMatchingVisitor.element)
params.filterNotNull().forEach { add(psiFactory.createArgument(it.defaultValue, it.nameAsName, reformat = false)) }
}
private fun matchValueArguments(
parameters: List<KtParameter>,
valueArgList: KtValueArgumentList?,
otherValueArgList: KtValueArgumentList?,
lambdaArgList: List<KtLambdaArgument>,
otherLambdaArgList: List<KtLambdaArgument>
): Boolean {
if (valueArgList != null) {
val handler = getHandler(valueArgList)
val normalizedOtherArgs = otherValueArgList?.arguments?.toMutableList() ?: mutableListOf()
normalizedOtherArgs.addAll(otherLambdaArgList)
normalizedOtherArgs.addDefaultArguments(parameters)
if (normalizedOtherArgs.isEmpty() && handler is SubstitutionHandler && handler.minOccurs == 0) {
return myMatchingVisitor.matchSequentially(lambdaArgList, otherLambdaArgList)
}
val normalizedArgs = valueArgList.arguments.toMutableList()
normalizedArgs.addAll(lambdaArgList)
return matchValueArguments(normalizedArgs, normalizedOtherArgs)
}
return matchValueArguments(lambdaArgList, otherLambdaArgList)
}
private fun matchValueArguments(queryArgs: List<KtValueArgument>, codeArgs: List<KtValueArgument>): Boolean {
var queryIndex = 0
var codeIndex = 0
while (queryIndex < queryArgs.size) {
val queryArg = queryArgs[queryIndex]
val codeArg = codeArgs.getOrElse(codeIndex) { return@matchValueArguments false }
if (getHandler(queryArg) is SubstitutionHandler) {
return myMatchingVisitor.matchSequentially(
queryArgs.subList(queryIndex, queryArgs.lastIndex + 1),
codeArgs.subList(codeIndex, codeArgs.lastIndex + 1)
)
}
// varargs declared in call matching with one-to-one argument passing
if (queryArg.isSpread && !codeArg.isSpread) {
val spreadArgExpr = queryArg.getArgumentExpression()
if (spreadArgExpr is KtCallExpression) {
spreadArgExpr.valueArguments.forEach { spreadedArg ->
if (!myMatchingVisitor.match(spreadedArg, codeArgs[codeIndex++])) return@matchValueArguments false
}
queryIndex++
continue
} // can't match array that is not created in the call itself
myMatchingVisitor.result = false
return myMatchingVisitor.result
}
if (!queryArg.isSpread && codeArg.isSpread) {
val spreadArgExpr = codeArg.getArgumentExpression()
if (spreadArgExpr is KtCallExpression) {
spreadArgExpr.valueArguments.forEach { spreadedArg ->
if (!myMatchingVisitor.match(queryArgs[queryIndex++], spreadedArg)) return@matchValueArguments false
}
codeIndex++
continue
}
return false// can't match array that is not created in the call itself
}
// normal argument matching
if (!myMatchingVisitor.match(queryArg, codeArg)) {
return if (queryArg.isNamed() || codeArg.isNamed()) { // start comparing for out of order arguments
myMatchingVisitor.matchInAnyOrder(
queryArgs.subList(queryIndex, queryArgs.lastIndex + 1),
codeArgs.subList(codeIndex, codeArgs.lastIndex + 1)
)
} else false
}
queryIndex++
codeIndex++
}
if (codeIndex != codeArgs.size) return false
return true
}
private fun resolveParameters(other: KtElement): List<KtParameter> = try {
other.resolveToCall()?.candidateDescriptor?.original?.valueParameters?.map {
it.source.getPsi() as KtParameter
} ?: emptyList()
} catch (e: Exception) {
emptyList()
}
override fun visitCallExpression(expression: KtCallExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
val parameters = resolveParameters(other)
myMatchingVisitor.result = when (other) {
is KtCallExpression -> {
myMatchingVisitor.match(expression.calleeExpression, other.calleeExpression)
&& myMatchingVisitor.match(expression.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(
parameters, expression.valueArgumentList, other.valueArgumentList,
expression.lambdaArguments, other.lambdaArguments
)
}
is KtDotQualifiedExpression -> other.callExpression is KtCallExpression
&& myMatchingVisitor.match(expression.calleeExpression, other.receiverExpression)
&& other.calleeName == "${OperatorNameConventions.INVOKE}"
&& matchValueArguments(
parameters,
expression.valueArgumentList, other.callExpression?.valueArgumentList,
expression.lambdaArguments, other.callExpression?.lambdaArguments ?: emptyList()
)
else -> false
}
}
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
val other = getTreeElementDepar<KtCallableReferenceExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.callableReference, other.callableReference)
&& myMatchingVisitor.matchOptionally(expression.receiverExpression, other.receiverExpression)
}
override fun visitTypeParameter(parameter: KtTypeParameter) {
val other = getTreeElementDepar<KtTypeParameter>() ?: return
myMatchingVisitor.result = matchTextOrVariable(parameter.firstChild, other.firstChild) // match generic identifier
&& myMatchingVisitor.match(parameter.extendsBound, other.extendsBound)
&& parameter.variance == other.variance
parameter.nameIdentifier?.let { nameIdentifier ->
val handler = getHandler(nameIdentifier)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
}
override fun visitParameter(parameter: KtParameter) {
val other = getTreeElementDepar<KtParameter>() ?: return
val decl = other.parent.parent
val typeMatched = when {
decl is KtFunctionType || decl is KtCatchClause || (parameter.isVarArg && other.isVarArg) -> {
myMatchingVisitor.match(parameter.typeReference, other.typeReference)
}
else -> matchTypeReferenceWithDeclaration(parameter.typeReference, other)
}
val otherNameIdentifier = if (getHandler(parameter) is SubstitutionHandler
&& parameter.nameIdentifier != null
&& other.nameIdentifier == null
) other else other.nameIdentifier
myMatchingVisitor.result = typeMatched
&& myMatchingVisitor.match(parameter.defaultValue, other.defaultValue)
&& (parameter.isVarArg == other.isVarArg || getHandler(parameter) is SubstitutionHandler)
&& myMatchingVisitor.match(parameter.valOrVarKeyword, other.valOrVarKeyword)
&& (parameter.nameIdentifier == null || matchTextOrVariable(parameter.nameIdentifier, otherNameIdentifier))
&& myMatchingVisitor.match(parameter.modifierList, other.modifierList)
&& myMatchingVisitor.match(parameter.destructuringDeclaration, other.destructuringDeclaration)
parameter.nameIdentifier?.let { nameIdentifier ->
val handler = getHandler(nameIdentifier)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
}
override fun visitTypeParameterList(list: KtTypeParameterList) {
val other = getTreeElementDepar<KtTypeParameterList>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters)
}
override fun visitParameterList(list: KtParameterList) {
val other = getTreeElementDepar<KtParameterList>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters)
}
override fun visitConstructorDelegationCall(call: KtConstructorDelegationCall) {
val other = getTreeElementDepar<KtConstructorDelegationCall>() ?: return
val parameters = resolveParameters(other)
myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression)
&& myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(
parameters,
call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments
)
}
override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
val other = getTreeElementDepar<KtSecondaryConstructor>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList)
&& myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList)
&& myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList)
&& myMatchingVisitor.match(constructor.getDelegationCallOrNull(), other.getDelegationCallOrNull())
&& myMatchingVisitor.match(constructor.bodyExpression, other.bodyExpression)
}
override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) {
val other = getTreeElementDepar<KtPrimaryConstructor>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList)
&& myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList)
&& myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList)
}
override fun visitAnonymousInitializer(initializer: KtAnonymousInitializer) {
val other = getTreeElementDepar<KtAnonymousInitializer>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(initializer.body, other.body)
}
override fun visitClassBody(classBody: KtClassBody) {
val other = getTreeElementDepar<KtClassBody>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(classBody, other)
}
override fun visitSuperTypeCallEntry(call: KtSuperTypeCallEntry) {
val other = getTreeElementDepar<KtSuperTypeCallEntry>() ?: return
val parameters = resolveParameters(other)
myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression)
&& myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(
parameters,
call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments
)
}
override fun visitSuperTypeEntry(specifier: KtSuperTypeEntry) {
val other = getTreeElementDepar<KtSuperTypeEntry>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(specifier.typeReference, other.typeReference)
}
private fun matchTypeAgainstElement(
type: String,
element: PsiElement,
other: PsiElement
): Boolean {
return when (val predicate = (getHandler(element) as? SubstitutionHandler)?.findRegExpPredicate()) {
null -> element.text == type
// Ignore type parameters if absent from the pattern
|| !element.text.contains('<') && element.text == type.removeTypeParameters()
else -> predicate.doMatch(type, myMatchingVisitor.matchContext, other)
}
}
override fun visitSuperTypeList(list: KtSuperTypeList) {
val other = getTreeElementDepar<KtSuperTypeList>() ?: return
val withinHierarchyEntries = list.entries.filter {
val type = it.typeReference; type is KtTypeReference && getHandler(type).withinHierarchyTextFilterSet
}
(other.parent as? KtClassOrObject)?.let { klass ->
val supertypes = (klass.descriptor as ClassDescriptor).toSimpleType().supertypes()
withinHierarchyEntries.forEach { entry ->
val typeReference = entry.typeReference
if (!matchTextOrVariable(typeReference, klass.nameIdentifier) && typeReference != null && supertypes.none {
it.renderNames().any { type -> matchTypeAgainstElement(type, typeReference, other) }
}) {
myMatchingVisitor.result = false
return@visitSuperTypeList
}
}
}
myMatchingVisitor.result =
myMatchingVisitor.matchInAnyOrder(list.entries.filter { it !in withinHierarchyEntries }, other.entries)
}
override fun visitClass(klass: KtClass) {
val other = getTreeElementDepar<KtClass>() ?: return
val identifier = klass.nameIdentifier
val otherIdentifier = other.nameIdentifier
var matchNameIdentifiers = matchTextOrVariable(identifier, otherIdentifier)
|| identifier != null && otherIdentifier != null && matchTypeAgainstElement(
(other.descriptor as LazyClassDescriptor).defaultType.fqName.toString(), identifier, otherIdentifier
)
// Possible match if "within hierarchy" is set
if (!matchNameIdentifiers && identifier != null && otherIdentifier != null) {
val identifierHandler = getHandler(identifier)
val checkHierarchyDown = identifierHandler.withinHierarchyTextFilterSet
if (checkHierarchyDown) {
// Check hierarchy down (down of pattern element = supertypes of code element)
matchNameIdentifiers = (other.descriptor as ClassDescriptor).toSimpleType().supertypes().any { type ->
type.renderNames().any { renderedType ->
matchTypeAgainstElement(renderedType, identifier, otherIdentifier)
}
}
} else if (identifier.getUserData(KotlinCompilingVisitor.WITHIN_HIERARCHY) == true) {
// Check hierarchy up (up of pattern element = inheritors of code element)
matchNameIdentifiers = HierarchySearchRequest(
other,
GlobalSearchScope.allScope(other.project),
true
).searchInheritors().any { psiClass ->
arrayOf(psiClass.name, psiClass.qualifiedName).filterNotNull().any { renderedType ->
matchTypeAgainstElement(renderedType, identifier, otherIdentifier)
}
}
}
}
myMatchingVisitor.result = myMatchingVisitor.match(klass.getClassOrInterfaceKeyword(), other.getClassOrInterfaceKeyword())
&& myMatchingVisitor.match(klass.modifierList, other.modifierList)
&& matchNameIdentifiers
&& myMatchingVisitor.match(klass.typeParameterList, other.typeParameterList)
&& myMatchingVisitor.match(klass.primaryConstructor, other.primaryConstructor)
&& myMatchingVisitor.matchInAnyOrder(klass.secondaryConstructors, other.secondaryConstructors)
&& myMatchingVisitor.match(klass.getSuperTypeList(), other.getSuperTypeList())
&& myMatchingVisitor.match(klass.body, other.body)
&& myMatchingVisitor.match(klass.docComment, other.docComment)
val handler = getHandler(klass.nameIdentifier!!)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
val other = getTreeElementDepar<KtObjectLiteralExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.objectDeclaration, other.objectDeclaration)
}
override fun visitObjectDeclaration(declaration: KtObjectDeclaration) {
val other = getTreeElementDepar<KtObjectDeclaration>() ?: return
val otherIdentifier =
other.nameIdentifier ?: if (other.isCompanion()) (other.parent.parent as KtClass).nameIdentifier else null
myMatchingVisitor.result = myMatchingVisitor.match(declaration.modifierList, other.modifierList)
&& matchTextOrVariable(declaration.nameIdentifier, otherIdentifier)
&& myMatchingVisitor.match(declaration.getSuperTypeList(), other.getSuperTypeList())
&& myMatchingVisitor.match(declaration.body, other.body)
declaration.nameIdentifier?.let { declNameIdentifier ->
val handler = getHandler(declNameIdentifier)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(otherIdentifier, myMatchingVisitor.matchContext)
}
}
}
private fun normalizeExpressionRet(expression: KtExpression?): KtExpression? = when {
expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement?.let {
if (it is KtReturnExpression) it.returnedExpression else it
}
else -> expression
}
private fun normalizeExpression(expression: KtExpression?): KtExpression? = when {
expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement
else -> expression
}
private fun normalizeExpressions(
patternExpr: KtExpression?,
codeExpr: KtExpression?,
returnExpr: Boolean
): Pair<KtExpression?, KtExpression?> {
val normalizedExpr = if (returnExpr) normalizeExpressionRet(patternExpr) else normalizeExpression(patternExpr)
val normalizedCodeExpr = if (returnExpr) normalizeExpressionRet(codeExpr) else normalizeExpression(codeExpr)
return when {
normalizedExpr is KtBlockExpression || normalizedCodeExpr is KtBlockExpression -> patternExpr to codeExpr
else -> normalizedExpr to normalizedCodeExpr
}
}
override fun visitNamedFunction(function: KtNamedFunction) {
val other = getTreeElementDepar<KtNamedFunction>() ?: return
val (patternBody, codeBody) = normalizeExpressions(function.bodyBlockExpression, other.bodyBlockExpression, true)
val bodyHandler = patternBody?.let(::getHandler)
val bodyMatch = when {
patternBody is KtNameReferenceExpression && codeBody == null -> bodyHandler is SubstitutionHandler
&& bodyHandler.minOccurs <= 1 && bodyHandler.maxOccurs >= 1
&& myMatchingVisitor.match(patternBody, other.bodyExpression)
patternBody is KtNameReferenceExpression -> myMatchingVisitor.match(
function.bodyBlockExpression,
other.bodyBlockExpression
)
patternBody == null && codeBody == null -> myMatchingVisitor.match(function.bodyExpression, other.bodyExpression)
patternBody == null -> function.bodyExpression == null || codeBody !is KtBlockExpression && myMatchingVisitor.match(function.bodyExpression, codeBody)
codeBody == null -> patternBody !is KtBlockExpression && myMatchingVisitor.match(patternBody, other.bodyExpression)
else -> myMatchingVisitor.match(function.bodyBlockExpression, other.bodyBlockExpression)
}
myMatchingVisitor.result = myMatchingVisitor.match(function.modifierList, other.modifierList)
&& matchTextOrVariable(function.nameIdentifier, other.nameIdentifier)
&& myMatchingVisitor.match(function.typeParameterList, other.typeParameterList)
&& matchTypeReferenceWithDeclaration(function.typeReference, other)
&& myMatchingVisitor.match(function.valueParameterList, other.valueParameterList)
&& myMatchingVisitor.match(function.receiverTypeReference, other.receiverTypeReference)
&& bodyMatch
function.nameIdentifier?.let { nameIdentifier ->
val handler = getHandler(nameIdentifier)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
}
override fun visitModifierList(list: KtModifierList) {
val other = getTreeElementDepar<KtModifierList>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(list, other)
}
override fun visitIfExpression(expression: KtIfExpression) {
val other = getTreeElementDepar<KtIfExpression>() ?: return
val elseBranch = normalizeExpression(expression.`else`)
myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
&& myMatchingVisitor.matchNormalized(expression.then, other.then)
&& (elseBranch == null || myMatchingVisitor.matchNormalized(expression.`else`, other.`else`))
}
override fun visitForExpression(expression: KtForExpression) {
val other = getTreeElementDepar<KtForExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.loopParameter, other.loopParameter)
&& myMatchingVisitor.match(expression.loopRange, other.loopRange)
&& myMatchingVisitor.matchNormalized(expression.body, other.body)
}
override fun visitWhileExpression(expression: KtWhileExpression) {
val other = getTreeElementDepar<KtWhileExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
&& myMatchingVisitor.matchNormalized(expression.body, other.body)
}
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
val other = getTreeElementDepar<KtDoWhileExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
&& myMatchingVisitor.matchNormalized(expression.body, other.body)
}
override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) {
val other = getTreeElementDepar<KtWhenConditionInRange>() ?: return
myMatchingVisitor.result = condition.isNegated == other.isNegated
&& myMatchingVisitor.match(condition.rangeExpression, other.rangeExpression)
}
override fun visitWhenConditionIsPattern(condition: KtWhenConditionIsPattern) {
val other = getTreeElementDepar<KtWhenConditionIsPattern>() ?: return
myMatchingVisitor.result = condition.isNegated == other.isNegated
&& myMatchingVisitor.match(condition.typeReference, other.typeReference)
}
override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) {
val other = getTreeElementDepar<PsiElement>() ?: return
val handler = getHandler(condition)
if (handler is SubstitutionHandler) {
myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext)
} else {
myMatchingVisitor.result = other is KtWhenConditionWithExpression
&& myMatchingVisitor.match(condition.expression, other.expression)
}
}
override fun visitWhenEntry(ktWhenEntry: KtWhenEntry) {
val other = getTreeElementDepar<KtWhenEntry>() ?: return
// $x$ -> $y$ should match else branches
val bypassElseTest = ktWhenEntry.firstChild is KtWhenConditionWithExpression
&& ktWhenEntry.firstChild.children.size == 1
&& ktWhenEntry.firstChild.firstChild is KtNameReferenceExpression
myMatchingVisitor.result =
(bypassElseTest && other.isElse || myMatchingVisitor.matchInAnyOrder(ktWhenEntry.conditions, other.conditions))
&& myMatchingVisitor.match(ktWhenEntry.expression, other.expression)
&& (bypassElseTest || ktWhenEntry.isElse == other.isElse)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
val other = getTreeElementDepar<KtWhenExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.subjectExpression, other.subjectExpression)
&& myMatchingVisitor.matchInAnyOrder(expression.entries, other.entries)
}
override fun visitFinallySection(finallySection: KtFinallySection) {
val other = getTreeElementDepar<KtFinallySection>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(finallySection.finalExpression, other.finalExpression)
}
override fun visitCatchSection(catchClause: KtCatchClause) {
val other = getTreeElementDepar<KtCatchClause>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(catchClause.parameterList, other.parameterList)
&& myMatchingVisitor.match(catchClause.catchBody, other.catchBody)
}
override fun visitTryExpression(expression: KtTryExpression) {
val other = getTreeElementDepar<KtTryExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.tryBlock, other.tryBlock)
&& myMatchingVisitor.matchInAnyOrder(expression.catchClauses, other.catchClauses)
&& myMatchingVisitor.match(expression.finallyBlock, other.finallyBlock)
}
override fun visitTypeAlias(typeAlias: KtTypeAlias) {
val other = getTreeElementDepar<KtTypeAlias>() ?: return
myMatchingVisitor.result = matchTextOrVariable(typeAlias.nameIdentifier, other.nameIdentifier)
&& myMatchingVisitor.match(typeAlias.getTypeReference(), other.getTypeReference())
&& myMatchingVisitor.matchInAnyOrder(typeAlias.annotationEntries, other.annotationEntries)
val handler = getHandler(typeAlias.nameIdentifier!!)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
override fun visitConstructorCalleeExpression(constructorCalleeExpression: KtConstructorCalleeExpression) {
val other = getTreeElementDepar<KtConstructorCalleeExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(
constructorCalleeExpression.constructorReferenceExpression, other.constructorReferenceExpression
)
}
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
val other = getTreeElementDepar<KtAnnotationEntry>() ?: return
val parameters = resolveParameters(other)
myMatchingVisitor.result = myMatchingVisitor.match(annotationEntry.calleeExpression, other.calleeExpression)
&& myMatchingVisitor.match(annotationEntry.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(
parameters,
annotationEntry.valueArgumentList, other.valueArgumentList, annotationEntry.lambdaArguments, other.lambdaArguments
)
&& matchTextOrVariable(annotationEntry.useSiteTarget, other.useSiteTarget)
}
override fun visitAnnotatedExpression(expression: KtAnnotatedExpression) {
myMatchingVisitor.result = when (val other = myMatchingVisitor.element) {
is KtAnnotatedExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression)
&& myMatchingVisitor.matchInAnyOrder(expression.annotationEntries, other.annotationEntries)
else -> myMatchingVisitor.match(expression.baseExpression, other) && expression.annotationEntries.all {
val handler = getHandler(it); handler is SubstitutionHandler && handler.minOccurs == 0
}
}
}
override fun visitProperty(property: KtProperty) {
val other = getTreeElementDepar<KtProperty>() ?: return
myMatchingVisitor.result = matchTypeReferenceWithDeclaration(property.typeReference, other)
&& myMatchingVisitor.match(property.modifierList, other.modifierList)
&& matchTextOrVariable(property.nameIdentifier, other.nameIdentifier)
&& myMatchingVisitor.match(property.docComment, other.docComment)
&& myMatchingVisitor.matchOptionally(
property.delegateExpressionOrInitializer,
other.delegateExpressionOrInitializer
)
&& myMatchingVisitor.match(property.getter, other.getter)
&& myMatchingVisitor.match(property.setter, other.setter)
&& myMatchingVisitor.match(property.receiverTypeReference, other.receiverTypeReference)
val handler = getHandler(property.nameIdentifier!!)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
val other = getTreeElementDepar<KtPropertyAccessor>() ?: return
val accessorBody = if (accessor.hasBlockBody()) accessor.bodyBlockExpression else accessor.bodyExpression
val otherBody = if (other.hasBlockBody()) other.bodyBlockExpression else other.bodyExpression
myMatchingVisitor.result = myMatchingVisitor.match(accessor.modifierList, other.modifierList)
&& myMatchingVisitor.matchNormalized(accessorBody, otherBody, true)
}
override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) {
val other = getTreeElementDepar<KtStringTemplateExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.entries, other.entries)
}
override fun visitSimpleNameStringTemplateEntry(entry: KtSimpleNameStringTemplateEntry) {
val other = getTreeElement<KtStringTemplateEntry>() ?: return
val handler = getHandler(entry)
if (handler is SubstitutionHandler) {
myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext)
return
}
myMatchingVisitor.result = when (other) {
is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry ->
myMatchingVisitor.match(entry.expression, other.expression)
else -> false
}
}
override fun visitLiteralStringTemplateEntry(entry: KtLiteralStringTemplateEntry) {
val other = myMatchingVisitor.element
myMatchingVisitor.result = when (val handler = entry.getUserData(CompiledPattern.HANDLER_KEY)) {
is LiteralWithSubstitutionHandler -> handler.match(entry, other, myMatchingVisitor.matchContext)
else -> matchTextOrVariable(entry, other)
}
}
override fun visitBlockStringTemplateEntry(entry: KtBlockStringTemplateEntry) {
val other = getTreeElementDepar<KtBlockStringTemplateEntry>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(entry.expression, other.expression)
}
override fun visitEscapeStringTemplateEntry(entry: KtEscapeStringTemplateEntry) {
val other = getTreeElementDepar<KtEscapeStringTemplateEntry>() ?: return
myMatchingVisitor.result = matchTextOrVariable(entry, other)
}
override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
val other = getTreeElementDepar<KtBinaryExpressionWithTypeRHS>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.operationReference, other.operationReference)
&& myMatchingVisitor.match(expression.left, other.left)
&& myMatchingVisitor.match(expression.right, other.right)
}
override fun visitIsExpression(expression: KtIsExpression) {
val other = getTreeElementDepar<KtIsExpression>() ?: return
myMatchingVisitor.result = expression.isNegated == other.isNegated
&& myMatchingVisitor.match(expression.leftHandSide, other.leftHandSide)
&& myMatchingVisitor.match(expression.typeReference, other.typeReference)
}
override fun visitDestructuringDeclaration(destructuringDeclaration: KtDestructuringDeclaration) {
val other = getTreeElementDepar<KtDestructuringDeclaration>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(destructuringDeclaration.entries, other.entries)
&& myMatchingVisitor.match(destructuringDeclaration.initializer, other.initializer)
&& myMatchingVisitor.match(destructuringDeclaration.docComment, other.docComment)
}
override fun visitDestructuringDeclarationEntry(multiDeclarationEntry: KtDestructuringDeclarationEntry) {
val other = getTreeElementDepar<KtDestructuringDeclarationEntry>() ?: return
myMatchingVisitor.result = matchTypeReferenceWithDeclaration(multiDeclarationEntry.typeReference, other)
&& myMatchingVisitor.match(multiDeclarationEntry.modifierList, other.modifierList)
&& multiDeclarationEntry.isVar == other.isVar
&& matchTextOrVariable(multiDeclarationEntry.nameIdentifier, other.nameIdentifier)
}
override fun visitThrowExpression(expression: KtThrowExpression) {
val other = getTreeElementDepar<KtThrowExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.referenceExpression(), other.referenceExpression())
}
override fun visitClassLiteralExpression(expression: KtClassLiteralExpression) {
val other = getTreeElementDepar<KtClassLiteralExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.firstChild, other.firstChild)
|| myMatchingVisitor.matchText(expression.text, other.resolveType().arguments.first().type.fqName.toString())
}
override fun visitComment(comment: PsiComment) {
val other = getTreeElementDepar<PsiComment>() ?: return
when (val handler = comment.getUserData(CompiledPattern.HANDLER_KEY)) {
is LiteralWithSubstitutionHandler -> {
if (other is KDocImpl) {
myMatchingVisitor.result = handler.match(comment, other, myMatchingVisitor.matchContext)
} else {
val offset = 2 + other.text.substring(2).indexOfFirst { it > ' ' }
myMatchingVisitor.result = handler.match(other, getCommentText(other), offset, myMatchingVisitor.matchContext)
}
}
is SubstitutionHandler -> {
handler.findRegExpPredicate()?.let {
it.setNodeTextGenerator { comment -> getCommentText(comment as PsiComment) }
}
myMatchingVisitor.result = handler.handle(
other,
2,
other.textLength - if (other.tokenType == KtTokens.EOL_COMMENT) 0 else 2,
myMatchingVisitor.matchContext
)
}
else -> myMatchingVisitor.result = myMatchingVisitor.matchText(
StructuralSearchUtil.normalize(getCommentText(comment)),
StructuralSearchUtil.normalize(getCommentText(other))
)
}
}
override fun visitKDoc(kDoc: KDoc) {
val other = getTreeElementDepar<KDoc>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(
kDoc.getChildrenOfType<KDocSection>(),
other.getChildrenOfType<KDocSection>()
)
}
override fun visitKDocSection(section: KDocSection) {
val other = getTreeElementDepar<KDocSection>() ?: return
val important: (PsiElement) -> Boolean = {
it.elementType != KDocTokens.LEADING_ASTERISK
&& !(it.elementType == KDocTokens.TEXT && it.text.trim().isEmpty())
}
myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(
section.allChildren.filter(important).toList(),
other.allChildren.filter(important).toList()
)
}
override fun visitKDocTag(tag: KDocTag) {
val other = getTreeElementDepar<KDocTag>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(tag.getChildrenOfType(), other.getChildrenOfType())
}
override fun visitKDocLink(link: KDocLink) {
val other = getTreeElementDepar<KDocLink>() ?: return
myMatchingVisitor.result = matchTextOrVariable(link, other)
}
companion object {
private val augmentedAssignmentsMap = mapOf(
KtTokens.PLUSEQ to KtTokens.PLUS,
KtTokens.MINUSEQ to KtTokens.MINUS,
KtTokens.MULTEQ to KtTokens.MUL,
KtTokens.DIVEQ to KtTokens.DIV,
KtTokens.PERCEQ to KtTokens.PERC
)
}
} | apache-2.0 | e9f20678ccc3c2006a2daa12917a87ab | 52.995981 | 162 | 0.664538 | 5.737593 | false | false | false | false |
kivensolo/UiUsingListView | module-Home/src/main/java/com/zeke/home/adapter/BannerDelegateAdapter.kt | 1 | 1484 | package com.zeke.home.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.kingz.module.common.adapter.IDelegateAdapter
import com.kingz.module.home.R
import com.zeke.home.entity.TemplatePageData
import com.zeke.kangaroo.adapter.CommonRecyclerAdapter
/**
* author: King.Z <br>
* date: 2020/5/24 13:22 <br>
* description: 单独一个海报的代理Adapter <br>
*/
class BannerDelegateAdapter: IDelegateAdapter<TemplatePageData> {
override fun isForViewType(dataType: TemplatePageData): Boolean {
return dataType.type == "banner"
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.news_one_pic_item, parent, false)
return CommonRecyclerAdapter.ViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, dataType: TemplatePageData) {
if(holder is CommonRecyclerAdapter.ViewHolder){
holder.getView<TextView>(R.id.tv_content)?.text = dataType.name
// GlideApp().with(holder.itemView.getContext()).load(news.imgUrls.get(0)).into(viewHolder.ivPic);
val drawable = holder.itemView.context.resources.getDrawable(R.drawable.cat_m)
holder.getView<ImageView>(R.id.iv_pic).background = drawable
}
}
} | gpl-2.0 | 1cc3ece0341ede008359bbd104b97ce4 | 38.648649 | 110 | 0.74352 | 4.106443 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/klib/KotlinNativeLibrariesFixer.kt | 1 | 3643 | // 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.configuration.klib
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.LibraryData
import com.intellij.openapi.externalSystem.model.project.LibraryDependencyData
import com.intellij.openapi.externalSystem.model.project.LibraryLevel
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.roots.libraries.Library
import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibraryNameUtil.GRADLE_LIBRARY_PREFIX
import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
/**
* Gradle IDE plugin creates [LibraryData] nodes with internal name consisting of two parts:
* - mandatory "Gradle: " prefix
* - and library name
* Then internal name is propagated to IDE [Library] object, and is displayed in IDE as "Gradle: <LIBRARY_NAME>".
* [KotlinNativeLibrariesFixer] removes "Gradle: " prefix from all [LibraryData] items representing KLIBs to make them
* look more friendly.
*
* Also, [KotlinNativeLibrariesFixer] makes sure that all KLIBs from Kotlin/Native distribution are added to IDE project model
* as project-level libraries. This is necessary until the appropriate fix in IDEA will be implemented (for details see IDEA-211451).
*/
internal object KotlinNativeLibrariesFixer {
fun applyTo(ownerNode: DataNode<GradleSourceSetData>, ideProject: DataNode<ProjectData>, resolverCtx: ProjectResolverContext) {
for (libraryDependencyNode in ExternalSystemApiUtil.findAll(ownerNode, ProjectKeys.LIBRARY_DEPENDENCY)) {
val libraryData = libraryDependencyNode.data.target
// Only KLIBs from Kotlin/Native distribution can have such prefix:
if (libraryData.internalName.startsWith("$GRADLE_LIBRARY_PREFIX$KOTLIN_NATIVE_LIBRARY_PREFIX")) {
fixLibraryName(libraryData)
GradleProjectResolverUtil.linkProjectLibrary(resolverCtx, ideProject, libraryData)
fixLibraryDependencyLevel(libraryDependencyNode)
}
}
}
private fun fixLibraryName(libraryData: LibraryData) {
libraryData.internalName = libraryData.internalName.substringAfter(GRADLE_LIBRARY_PREFIX)
}
private fun fixLibraryDependencyLevel(oldDependencyNode: DataNode<LibraryDependencyData>) {
val oldDependency = oldDependencyNode.data
if (oldDependency.level == LibraryLevel.PROJECT) return // nothing to do
val newDependency = LibraryDependencyData(oldDependency.ownerModule, oldDependency.target, LibraryLevel.PROJECT).apply {
scope = oldDependency.scope
order = oldDependency.order
isExported = oldDependency.isExported
}
val parentNode = oldDependencyNode.parent ?: return
val childNodes = oldDependencyNode.children
val newDependencyNode = parentNode.createChild(oldDependencyNode.key, newDependency)
for (child in childNodes) {
newDependencyNode.addChild(child)
}
oldDependencyNode.clear(true)
}
}
| apache-2.0 | 1f8136f32afeb6a975944f33da8f567d | 52.573529 | 158 | 0.771342 | 4.976776 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/base/BaseEntryCommentFragment.kt | 1 | 3732 | package io.github.feelfreelinux.wykopmobilny.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.models.dataclass.EntryComment
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Voter
import io.github.feelfreelinux.wykopmobilny.ui.adapters.EntryCommentAdapter
import io.github.feelfreelinux.wykopmobilny.ui.dialogs.createVotersDialogListener
import io.github.feelfreelinux.wykopmobilny.ui.dialogs.VotersDialogListener
import io.github.feelfreelinux.wykopmobilny.ui.fragments.entrycomments.EntryCommentsFragmentView
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.prepare
import kotlinx.android.synthetic.main.dialog_voters.view.*
import kotlinx.android.synthetic.main.entries_fragment.*
import kotlinx.android.synthetic.main.search_empty_view.*
import javax.inject.Inject
open class BaseEntryCommentFragment : BaseFragment(), EntryCommentsFragmentView, SwipeRefreshLayout.OnRefreshListener {
@Inject lateinit var entryCommentsAdapter: EntryCommentAdapter
lateinit var votersDialogListener: VotersDialogListener
open var loadDataListener: (Boolean) -> Unit = {}
var showSearchEmptyView: Boolean
get() = searchEmptyView.isVisible
set(value) {
searchEmptyView.isVisible = value
if (value) {
entryCommentsAdapter.addData(emptyList(), true)
entryCommentsAdapter.disableLoading()
}
}
override fun openVotersMenu() {
val dialog = com.google.android.material.bottomsheet.BottomSheetDialog(activity!!)
val votersDialogView = layoutInflater.inflate(R.layout.dialog_voters, null)
votersDialogView.votersTextView.isVisible = false
dialog.setContentView(votersDialogView)
votersDialogListener = createVotersDialogListener(dialog, votersDialogView)
dialog.show()
}
override fun showVoters(voters: List<Voter>) = votersDialogListener(voters)
// Inflate view
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
inflater.inflate(R.layout.entries_fragment, container, false)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
entryCommentsAdapter.loadNewDataListener = { loadDataListener(false) }
// Setup views
swipeRefresh.setOnRefreshListener(this)
recyclerView.run {
prepare()
adapter = entryCommentsAdapter
}
loadingView.isVisible = true
}
override fun onRefresh() = loadDataListener(true)
/**
* Removes progressbar from adapter
*/
override fun disableLoading() = entryCommentsAdapter.disableLoading()
/**
* Use this function to add items to EntriesFragment
* @param items List of entries to add
* @param shouldRefresh If true adapter will refresh its data with provided items. False by default
*/
override fun addItems(items: List<EntryComment>, shouldRefresh: Boolean) {
entryCommentsAdapter.addData(items, shouldRefresh)
swipeRefresh?.isRefreshing = false
loadingView?.isVisible = false
// Scroll to top if refreshing list
if (shouldRefresh) {
(recyclerView?.layoutManager as? androidx.recyclerview.widget.LinearLayoutManager)?.scrollToPositionWithOffset(0, 0)
}
}
override fun updateComment(comment: EntryComment) = entryCommentsAdapter.updateComment(comment)
} | mit | aa983eda8799096ae6c65120512c290e | 40.477778 | 128 | 0.748124 | 5.043243 | false | false | false | false |
rustamgaifullin/MP | app/src/main/kotlin/io/rg/mp/ui/spreadsheet/SpreadsheetFragment.kt | 1 | 9746 | package io.rg.mp.ui.spreadsheet
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import androidx.appcompat.app.AlertDialog.Builder
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import com.google.android.material.textfield.TextInputEditText
import dagger.android.support.AndroidSupportInjection
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.rg.mp.R
import io.rg.mp.R.layout
import io.rg.mp.R.string
import io.rg.mp.ui.CreatedSuccessfully
import io.rg.mp.ui.ListSpreadsheet
import io.rg.mp.ui.ReloadViewAuthenticator
import io.rg.mp.ui.RenamedSuccessfully
import io.rg.mp.ui.StartActivity
import io.rg.mp.ui.ToastInfo
import io.rg.mp.ui.ViewModelResult
import io.rg.mp.ui.expense.ExpenseFragment
import io.rg.mp.ui.spreadsheet.SpreadsheetAdapter.Companion.COPY_ACTION
import io.rg.mp.ui.spreadsheet.SpreadsheetAdapter.Companion.RENAME_ACTION
import io.rg.mp.ui.spreadsheet.SpreadsheetViewModel.Companion.DEFAULT_TEMPLATE_ID
import io.rg.mp.ui.spreadsheet.SpreadsheetViewModel.Companion.REQUEST_AUTHORIZATION_FOR_DELETE
import io.rg.mp.ui.spreadsheet.SpreadsheetViewModel.Companion.REQUEST_AUTHORIZATION_LOADING_SPREADSHEETS
import io.rg.mp.ui.spreadsheet.SpreadsheetViewModel.Companion.REQUEST_AUTHORIZATION_NEW_SPREADSHEET
import io.rg.mp.ui.spreadsheet.model.SpreadsheetDataToRestore
import io.rg.mp.ui.spreadsheet.model.SpreadsheetDataToRestore.Companion.emptyPair
import io.rg.mp.utils.setVisibility
import kotlinx.android.synthetic.main.fragment_spreadsheets.spreadsheetsRecyclerView
import kotlinx.android.synthetic.main.fragment_spreadsheets.viewDisableLayout
import me.zhanghai.android.materialprogressbar.MaterialProgressBar
import javax.inject.Inject
class SpreadsheetFragment : Fragment() {
companion object {
private const val SPREADSHEET_DATA_KEY = "io.rg.mp.SPREADSHEET_DATA_KEY"
}
@Inject
lateinit var viewModel: SpreadsheetViewModel
@Inject
lateinit var reloadViewAuthenticator: ReloadViewAuthenticator
private val compositeDisposable = CompositeDisposable()
private val spreadsheetAdapter = SpreadsheetAdapter()
private lateinit var mainProgressBar: MaterialProgressBar
private var menu: Menu? = null
private var spreadsheetData: SpreadsheetDataToRestore? = null
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?): View? {
setHasOptionsMenu(true)
return inflater.inflate(layout.fragment_spreadsheets, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mainProgressBar = requireActivity().findViewById(R.id.mainProgressBar)
registerForContextMenu(spreadsheetsRecyclerView)
spreadsheetsRecyclerView.adapter = spreadsheetAdapter
reloadViewAuthenticator.restoreState(savedInstanceState)
spreadsheetData = savedInstanceState?.getParcelable(SPREADSHEET_DATA_KEY)
}
override fun onStart() {
compositeDisposable.add(
viewModel.viewModelNotifier()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(handleViewModelResult())
)
compositeDisposable.add(
viewModel.isOperationInProgress()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(handleProgressBar())
)
compositeDisposable.add(
spreadsheetAdapter.onClick()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(openExpenseFragment())
)
reloadViewAuthenticator.startReload {
viewModel.reloadData()
}
super.onStart()
}
override fun onStop() {
super.onStop()
compositeDisposable.clear()
viewModel.clear()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putAll(reloadViewAuthenticator.getState())
outState.putParcelable(SPREADSHEET_DATA_KEY, spreadsheetData)
}
override fun onDestroyView() {
spreadsheetsRecyclerView.adapter = null
super.onDestroyView()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
inflater.inflate(R.menu.menu_spreadsheet, menu)
this.menu = menu
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_create_spreadsheet -> createSpreadsheet()
}
return super.onOptionsItemSelected(item)
}
override fun onContextItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
RENAME_ACTION -> renameSpreadsheet()
COPY_ACTION -> copySpreadsheet()
}
return super.onContextItemSelected(item)
}
private fun renameSpreadsheet() {
spreadsheetAdapter.lastClicked()?.let { spreadsheet ->
showDialogWithName(getString(string.rename), spreadsheet.name) { name ->
viewModel.renameSpreadsheet(spreadsheet.id, name)
}
}
}
private fun copySpreadsheet() {
spreadsheetAdapter.lastClicked()?.let {
createSpreadsheet(it.id)
}
}
private fun createSpreadsheet(fromId: String = DEFAULT_TEMPLATE_ID) {
showDialogWithName(getString(string.create), viewModel.createSpreadsheetName()) { name ->
spreadsheetData = SpreadsheetDataToRestore(name, fromId)
createNewSpreadsheet(name, fromId)
}
}
private fun showDialogWithName(positiveButton: String, name: String, positiveAction: (String) -> Unit) {
val builder = Builder(requireActivity())
builder.setTitle(getString(string.enter_name))
val view = View.inflate(requireContext(), layout.dialog_edittext, null)
val editText = view.findViewById<TextInputEditText>(R.id.dialogEditText)
editText.setText(name)
builder.setView(view)
builder.setNegativeButton(android.R.string.cancel) { dialog, _ ->
dialog.dismiss()
}
builder.setPositiveButton(positiveButton) { dialog, _ ->
positiveAction.invoke(editText.text.toString())
dialog.dismiss()
}
builder.create().show()
}
private fun createNewSpreadsheet(name: String, fromId: String) {
viewModel.createNewSpreadsheet(name, fromId)
enableActionComponents(false)
}
private fun enableActionComponents(isEnabled: Boolean) {
menu?.findItem(R.id.action_create_spreadsheet)?.isEnabled = isEnabled
viewDisableLayout.setVisibility(!isEnabled)
}
private fun openExpenseFragment(): (SpreadsheetEvent) -> Unit {
return {
val args = ExpenseFragment.createArgs(it.spreadsheet.id, it.spreadsheet.name)
view?.findNavController()?.navigate(R.id.actionShowExpenseScreen, args)
}
}
private fun handleViewModelResult(): (ViewModelResult) -> Unit {
return {
when (it) {
is ToastInfo -> {
viewModel.deleteFailedSpreadsheets()
Toast.makeText(activity, it.messageId, it.length).show()
}
is StartActivity -> reloadViewAuthenticator.startAuthentication {
startActivityForResult(it.intent, it.requestCode)
}
is ListSpreadsheet -> {
spreadsheetAdapter.setData(it.list)
}
is CreatedSuccessfully -> {
Toast.makeText(activity, "Created successfully", LENGTH_SHORT).show()
viewModel.reloadData()
}
is RenamedSuccessfully -> {
Toast.makeText(activity, "Renamed successfully", LENGTH_SHORT).show()
viewModel.reloadData()
}
}
}
}
private fun handleProgressBar(): (Boolean) -> Unit {
return { isInProgress ->
mainProgressBar.isIndeterminate = isInProgress
mainProgressBar.setVisibility(isInProgress)
if (!isInProgress) {
enableActionComponents(true)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
reloadViewAuthenticator.authenticationFinished()
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_AUTHORIZATION_NEW_SPREADSHEET -> {
val (name, id) = spreadsheetData?.getNameIdPair() ?: emptyPair()
viewModel.deleteFailedSpreadsheets()
viewModel.createNewSpreadsheet(name, id)
}
REQUEST_AUTHORIZATION_LOADING_SPREADSHEETS -> viewModel.reloadData()
REQUEST_AUTHORIZATION_FOR_DELETE -> viewModel.deleteFailedSpreadsheets()
}
}
}
} | mit | 0628babd260938ade3504460fe2b8dc8 | 35.234201 | 108 | 0.67402 | 4.839126 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceWithIgnoreCaseEqualsInspection.kt | 2 | 4053 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceWithIgnoreCaseEqualsInspection : AbstractKotlinInspection() {
companion object {
private val caseConversionFunctionFqNames =
listOf(FqName("kotlin.text.toUpperCase"), FqName("kotlin.text.toLowerCase")).associateBy { it.shortName().asString() }
private fun KtExpression.callInfo(): Pair<KtCallExpression, String>? {
val call = (this as? KtQualifiedExpression)?.callExpression ?: this as? KtCallExpression ?: return null
val calleeText = call.calleeExpression?.text ?: return null
return call to calleeText
}
private fun KtCallExpression.fqName(context: BindingContext): FqName? {
return getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull()
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
binaryExpressionVisitor(fun(binaryExpression: KtBinaryExpression) {
if (binaryExpression.operationToken != KtTokens.EQEQ) return
val (leftCall, leftCalleeText) = binaryExpression.left?.callInfo() ?: return
val (rightCall, rightCalleeText) = binaryExpression.right?.callInfo() ?: return
if (leftCalleeText != rightCalleeText) return
val caseConversionFunctionFqName = caseConversionFunctionFqNames[leftCalleeText] ?: return
val context = binaryExpression.analyze(BodyResolveMode.PARTIAL)
val leftCallFqName = leftCall.fqName(context) ?: return
val rightCallFqName = rightCall.fqName(context) ?: return
if (leftCallFqName != rightCallFqName) return
if (leftCallFqName != caseConversionFunctionFqName) return
holder.registerProblem(
binaryExpression,
KotlinBundle.message("inspection.replace.with.ignore.case.equals.display.name"),
ReplaceFix(),
)
})
private class ReplaceFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.0", "equals(..., ignoreCase = true)")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val binary = descriptor.psiElement as? KtBinaryExpression ?: return
val (leftCall, _) = binary.left?.callInfo() ?: return
val (rightCall, _) = binary.right?.callInfo() ?: return
val psiFactory = KtPsiFactory(binary)
val leftReceiver = leftCall.getQualifiedExpressionForSelector()?.receiverExpression
val rightReceiver = rightCall.getQualifiedExpressionForSelector()?.receiverExpression ?: psiFactory.createThisExpression()
val newExpression = if (leftReceiver != null) {
psiFactory.createExpressionByPattern("$0.equals($1, ignoreCase = true)", leftReceiver, rightReceiver)
} else {
psiFactory.createExpressionByPattern("equals($0, ignoreCase = true)", rightReceiver)
}
binary.replace(newExpression)
}
}
}
| apache-2.0 | 5148b3ed47b0e69141443084626e6afa | 50.303797 | 158 | 0.711078 | 5.291123 | false | false | false | false |
androidx/androidx | buildSrc/private/src/main/kotlin/androidx/build/resources/CheckResourceApiReleaseTask.kt | 3 | 2937 | /*
* 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.build.resources
import androidx.build.checkapi.ApiLocation
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import java.io.File
/**
* Task for verifying changes in the public Android resource surface, e.g. `public.xml`.
*/
@CacheableTask
abstract class CheckResourceApiReleaseTask : DefaultTask() {
/** Reference resource API file (in source control). */
@get:InputFile
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val referenceApiFile: Property<File>
/** Generated resource API file (in build output). */
@get:Internal
abstract val apiLocation: Property<ApiLocation>
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
fun getTaskInput(): File {
return apiLocation.get().resourceFile
}
@TaskAction
fun checkResourceApiRelease() {
val referenceApiFile = referenceApiFile.get()
val apiFile = apiLocation.get().resourceFile
// Read the current API surface, if any, into memory.
val newApiSet = if (apiFile.exists()) {
apiFile.readLines().toSet()
} else {
emptySet()
}
// Read the reference API surface into memory.
val referenceApiSet = referenceApiFile.readLines().toSet()
// POLICY: Ensure that no resources are removed from the last released version.
val removedApiSet = referenceApiSet - newApiSet
if (removedApiSet.isNotEmpty()) {
var removed = ""
for (e in removedApiSet) {
removed += "$e\n"
}
val errorMessage = """Public resources have been removed since the previous revision
Previous definition is ${referenceApiFile.canonicalPath}
Current definition is ${apiFile.canonicalPath}
Public resources are considered part of the library's API surface
and may not be removed within a major version.
Removed resources:
$removed"""
throw GradleException(errorMessage)
}
}
}
| apache-2.0 | 5303813bc15db5de6f41e556cac25ddf | 32 | 96 | 0.709227 | 4.483969 | false | false | false | false |
androidx/androidx | compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/SpringEstimation.kt | 3 | 10427 | /*
* 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.animation.core
import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.sqrt
/**
* Returns the estimated time that the spring will last be at [delta]
* @suppress
*/
/*@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)*/
fun estimateAnimationDurationMillis(
stiffness: Float,
dampingRatio: Float,
initialVelocity: Float,
initialDisplacement: Float,
delta: Float
): Long = estimateAnimationDurationMillis(
stiffness = stiffness.toDouble(),
dampingRatio = dampingRatio.toDouble(),
initialVelocity = initialVelocity.toDouble(),
initialDisplacement = initialDisplacement.toDouble(),
delta = delta.toDouble()
)
/**
* Returns the estimated time that the spring will last be at [delta]
* @suppress
*/
/*@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)*/
fun estimateAnimationDurationMillis(
stiffness: Double,
dampingRatio: Double,
initialVelocity: Double,
initialDisplacement: Double,
delta: Double
): Long {
val dampingCoefficient = 2.0 * dampingRatio * sqrt(stiffness)
val roots = complexQuadraticFormula(1.0, dampingCoefficient, stiffness)
return estimateDurationInternal(
roots,
dampingRatio,
initialVelocity,
initialDisplacement,
delta
)
}
/**
* Returns the estimated time that the spring will last be at [delta]
* @suppress
*/
/*@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)*/
fun estimateAnimationDurationMillis(
springConstant: Double,
dampingCoefficient: Double,
mass: Double,
initialVelocity: Double,
initialDisplacement: Double,
delta: Double
): Long {
val criticalDamping = 2.0 * sqrt(springConstant * mass)
val dampingRatio = dampingCoefficient / criticalDamping
val roots = complexQuadraticFormula(mass, dampingCoefficient, springConstant)
return estimateDurationInternal(
roots = roots,
dampingRatio = dampingRatio,
initialVelocity = initialVelocity,
initialPosition = initialDisplacement,
delta = delta
)
}
/**
* In the under-damped case we simply calculate the envelope of the function.
* The general solution is of the form x(t) = c_1*e^(r*t)*cos(...) + c_2*e^(r*t)sin(...)
* which simplifies to x(t) = c*e^(r*t)*cos(...) where c*e^(r*t) is the envelope of x(t)
*/
private fun estimateUnderDamped(
roots: Pair<ComplexDouble, ComplexDouble>,
p0: Double,
v0: Double,
delta: Double
): Double {
val r = roots.first.real
val c1 = p0
val c2 = (v0 - r * c1) / roots.first.imaginary
val c = sqrt(c1 * c1 + c2 * c2)
return ln(delta / c) / r
}
/**
* In the critically-damped case we apply Newton-Raphson's iterative numerical method of solving
* the equation x(t) = c_1*e^(r*t) + c_2*t*e^(r*t)
*/
private fun estimateCriticallyDamped(
roots: Pair<ComplexDouble, ComplexDouble>,
p0: Double,
v0: Double,
delta: Double
): Double {
val r = roots.first.real
val c1 = p0
val c2 = v0 - r * c1
// Application of Lambert's W function to solve te^t
fun t2Iterate(guess: Double, r: Double): Double {
var t = guess
for (i in 0..5) {
t = (guess - ln(abs(t / r)))
}
return t
}
// For our initial guess, determine the max t of c_1*e^(r*t) = delta and
// c_2*t*e^(r*t) = delta
val t1 = ln(abs(delta / c1)) / r
val t2 = t2Iterate(ln(abs(delta / c2)), r) / r
var tCurr = when {
t1.isNotFinite() -> t2
t2.isNotFinite() -> t1
else -> max(t1, t2)
}
// Calculate the inflection time. This is important if the inflection is in t > 0
val tInflection = -(r * c1 + c2) / (r * c2)
fun xInflection() = c1 * exp(r * tInflection) + c2 * tInflection * exp(r * tInflection)
// For inflection that does not exist in real time, we always solve for x(t)=delta. Note
// the system is manipulated such that p0 is always positive.
val signedDelta = if (tInflection.isNaN() || tInflection <= 0.0) {
-delta
} else if (tInflection > 0.0 && -xInflection() < delta) {
// In this scenario the first crossing with the threshold is to be found. Note that
// the inflection does not exceed delta. As such, we search from the left.
if (c2 < 0 && c1 > 0) {
tCurr = 0.0
}
-delta
} else {
// In this scenario there are three total crossings of the threshold, once from
// above, and then once when the inflection exceeds the threshold and then one last
// one when x(t) finally decays to zero. The point of determining concavity is to
// find the final crossing.
//
// By finding a point between when concavity changes, and when the inflection point is,
// Newton's method will always converge onto the rightmost point (in this case),
// the one that we are interested in.
val tConcavChange = -(2.0 / r) - (c1 / c2)
tCurr = tConcavChange
delta
}
val fn: (Double) -> Double = { t -> (c1 + c2 * t) * exp(r * t) + signedDelta }
val fnPrime: (Double) -> Double = { t -> (c2 * (r * t + 1) + c1 * r) * exp(r * t) }
var tDelta = Double.MAX_VALUE
var iterations = 0
while (tDelta > 0.001 && iterations < 100) {
iterations++
val tLast = tCurr
tCurr = iterateNewtonsMethod(tCurr, fn, fnPrime)
tDelta = abs(tLast - tCurr)
}
return tCurr
}
/**
* In the over-damped case we apply Newton-Raphson's iterative numerical method of solving
* the equation x(t) = c_1*e^(r_1*t) + c_2*e^(r_2*t)
*/
private fun estimateOverDamped(
roots: Pair<ComplexDouble, ComplexDouble>,
p0: Double,
v0: Double,
delta: Double
): Double {
val r1 = roots.first.real
val r2 = roots.second.real
val c2 = (r1 * p0 - v0) / (r1 - r2)
val c1 = p0 - c2
// For our initial guess, determine the max t of c_1*e^(r_1*t) = delta and
// c_2*e^(r_2*t) = delta
val t1 = ln(abs(delta / c1)) / r1
val t2 = ln(abs(delta / c2)) / r2
var tCurr = when {
t1.isNotFinite() -> t2
t2.isNotFinite() -> t1
else -> max(t1, t2)
}
// Calculate the inflection time. This is important if the inflection is in t > 0
val tInflection = ln((c1 * r1) / (-c2 * r2)) / (r2 - r1)
fun xInflection() = c1 * exp(r1 * tInflection) + c2 * exp(r2 * tInflection)
// For inflection that does not exist in real time, we always solve for x(t)=delta. Note
// the system is manipulated such that p0 is always positive.
val signedDelta = if (tInflection.isNaN() || tInflection <= 0.0) {
-delta
} else if (tInflection > 0.0 && -xInflection() < delta) {
// In this scenario the first crossing with the threshold is to be found. Note that
// the inflection does not exceed delta. As such, we search from the left.
if (c2 > 0.0 && c1 < 0.0) {
tCurr = 0.0
}
-delta
} else {
// In this scenario there are three total crossings of the threshold, once from
// above, and then once when the inflection exceeds the threshold and then one last
// one when x(t) finally decays to zero. The point of determining concavity is to
// find the final crossing.
//
// By finding a point between when concavity changes, and when the inflection point is,
// Newton's method will always converge onto the rightmost point (in this case),
// the one that we are interested in.
val tConcavChange = ln(-(c2 * r2 * r2) / (c1 * r1 * r1)) / (r1 - r2)
tCurr = tConcavChange
delta
}
val fn: (Double) -> Double = { t -> c1 * exp(r1 * t) + c2 * exp(r2 * t) + signedDelta }
val fnPrime: (Double) -> Double = { t -> c1 * r1 * exp(r1 * t) + c2 * r2 * exp(r2 * t) }
// For a good initial guess, simply return
if (abs(fn(tCurr)) < 0.0001) {
return tCurr
}
var tDelta = Double.MAX_VALUE
// Cap iterations for safety - Experimentally this method takes <= 5 iterations
var iterations = 0
while (tDelta > 0.001 && iterations < 100) {
iterations++
val tLast = tCurr
tCurr = iterateNewtonsMethod(tCurr, fn, fnPrime)
tDelta = abs(tLast - tCurr)
}
return tCurr
}
// Applies Newton-Raphson's method to solve for the estimated time the spring mass system will
// last be at [delta].
@Suppress("UnnecessaryVariable")
private fun estimateDurationInternal(
roots: Pair<ComplexDouble, ComplexDouble>,
dampingRatio: Double,
initialVelocity: Double,
initialPosition: Double,
delta: Double
): Long {
if (initialPosition == 0.0 && initialVelocity == 0.0) {
return 0L
}
val v0 = if (initialPosition < 0) -initialVelocity else initialVelocity
val p0 = abs(initialPosition)
return (
when {
dampingRatio > 1.0 -> estimateOverDamped(
roots = roots,
v0 = v0,
p0 = p0,
delta = delta
)
dampingRatio < 1.0 -> estimateUnderDamped(
roots = roots,
v0 = v0,
p0 = p0,
delta = delta
)
else -> estimateCriticallyDamped(
roots = roots,
v0 = v0,
p0 = p0,
delta = delta
)
} * 1000.0
).toLong()
}
private inline fun iterateNewtonsMethod(
x: Double,
fn: (Double) -> Double,
fnPrime: (Double) -> Double
): Double {
return x - fn(x) / fnPrime(x)
}
@Suppress("NOTHING_TO_INLINE")
private inline fun Double.isNotFinite() = !this.isFinite()
| apache-2.0 | 6fd4a2d5d9e59eb13d272145965fed04 | 31.892744 | 96 | 0.618203 | 3.635635 | false | false | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/di/DaoModule.kt | 1 | 1215 | package de.droidcon.berlin2018.di
import android.content.Context
import com.hannesdorfmann.sqlbrite.dao.DaoManager
import dagger.Module
import dagger.Provides
import de.droidcon.berlin2018.schedule.database.dao.LocationDao
import de.droidcon.berlin2018.schedule.database.dao.LocationDaoSqlite
import de.droidcon.berlin2018.schedule.database.dao.SessionDao
import de.droidcon.berlin2018.schedule.database.dao.SessionDaoSqlite
import de.droidcon.berlin2018.schedule.database.dao.SpeakerDao
import de.droidcon.berlin2018.schedule.database.dao.SpeakerDaoSqlite
@Module
class DaoModule(context: Context) {
private val sessionDao: SessionDao
private val speakerDao: SpeakerDao
private val locationDao: LocationDao
init {
// DAO's
sessionDao = SessionDaoSqlite()
speakerDao = SpeakerDaoSqlite()
locationDao = LocationDaoSqlite()
DaoManager.with(context.applicationContext)
.add(sessionDao)
.add(speakerDao)
.add(locationDao)
.version(1)
.databaseName("schedule.db")
.build()
}
@Provides
fun provideSessionDao() = sessionDao
@Provides
fun provideSpeakerDao() = speakerDao
@Provides
fun provideLocationDao() = locationDao
}
| apache-2.0 | 17d66a786129062dfb9fa061946c0a00 | 25.413043 | 69 | 0.767078 | 4.077181 | false | false | false | false |
forusoul70/playTorrent | app/src/main/java/playtorrent/com/playtorrent/PieceMessage.kt | 1 | 1774 | package playtorrent.com.playtorrent
import android.util.Log
import java.nio.ByteBuffer
/**
* Piece message
*/
class PieceMessage(val pieceIndex:Int, val offset:Long, val buffer:ByteArray): IBitMessage {
companion object {
private val TAG = "PieceMessage"
private val DEBUG = BuildConfig.DEBUG
private val BASE_MESSAGE_LENGTH = 13
fun parse(message:ByteBuffer, length:Int): PieceMessage? {
if (length <= BASE_MESSAGE_LENGTH) {
if (DEBUG) {
Log.e(TAG, "Invalid piece message length [$length]")
}
return null
}
if (message.remaining() != length) {
if (DEBUG) {
Log.e(TAG, "Expected bytes is $length but remaining is ${message.remaining()}")
}
return null
}
val pieceIndex = message.int
val offset = message.int
val buffer = ByteArray(message.remaining())
message.get(buffer, 0, message.remaining())
if (DEBUG) {
Log.d(TAG, "parsed finished. Payload length is ${buffer.size}")
}
return PieceMessage(pieceIndex, offset.toLong(), buffer)
}
}
override fun getMessage(): ByteArray {
val message = ByteBuffer.allocateDirect(BASE_MESSAGE_LENGTH + buffer.size)
message.putInt(13) // 4 bytes
message.put(IBitMessage.Type.PIECE.value.toByte()) // 1 byte
message.putInt(pieceIndex) // 4 bytes
message.putInt(offset.toInt()) // 4 bytes
message.putInt(buffer.size)
return message.array()
}
override fun getType(): IBitMessage.Type {
return IBitMessage.Type.PIECE
}
}
| apache-2.0 | 7863326a72f9b46a8605fee590f016f2 | 30.678571 | 99 | 0.570462 | 4.52551 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/features/preference/PreferenceActivity.kt | 1 | 4831 | package taiwan.no1.app.ssfm.features.preference
import android.os.Bundle
import com.devrapid.kotlinknifer.SharedPrefs
import com.devrapid.kotlinknifer.recyclerview.WrapContentLinearLayoutManager
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.databinding.ActivityPreferenceBinding
import taiwan.no1.app.ssfm.databinding.ItemPreferenceFirstLayerTitleBinding
import taiwan.no1.app.ssfm.databinding.ItemPreferenceFirstLayerToggleBinding
import taiwan.no1.app.ssfm.databinding.ItemPreferenceSecondLayerTitleBinding
import taiwan.no1.app.ssfm.features.base.AdvancedActivity
import taiwan.no1.app.ssfm.misc.extension.recyclerview.MultipleTypeAdapter
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.adapters.BaseDataBindingAdapter
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.viewholders.BindingHolder
import taiwan.no1.app.ssfm.models.IExpandVisitable
import taiwan.no1.app.ssfm.models.entities.PreferenceEntity
import taiwan.no1.app.ssfm.models.entities.PreferenceOptionEntity
import taiwan.no1.app.ssfm.models.entities.PreferenceToggleEntity
import javax.inject.Inject
/**
* An activity for preference setting.
*
* @author jieyi
* @since 9/8/17
*/
class PreferenceActivity : AdvancedActivity<PreferenceViewModel, ActivityPreferenceBinding>() {
@Inject override lateinit var viewModel: PreferenceViewModel
private var theme by SharedPrefs(false)
private var isAutoPlay by SharedPrefs(false)
private var isAutoDownload by SharedPrefs(false)
private var isDownloadByWifi by SharedPrefs(false)
private var isLockScreenLyrics by SharedPrefs(false)
private var isLastSelectedChannel by SharedPrefs(false)
private val preferenceList: MutableList<IExpandVisitable> = mutableListOf(
PreferenceEntity("Theme", "Dark", R.drawable.ic_theme, childItemList = mutableListOf(
PreferenceOptionEntity("Dark"),
PreferenceOptionEntity("Light"))),
PreferenceToggleEntity("Auto Play", isAutoPlay, R.drawable.ic_music_disk),
PreferenceToggleEntity("Auto Download", isAutoDownload, R.drawable.ic_download),
PreferenceToggleEntity("Download Only Wifi", isDownloadByWifi, R.drawable.ic_wifi),
PreferenceToggleEntity("Lock Screen Lyrics Display", isLockScreenLyrics, R.drawable.ic_queue_music),
PreferenceToggleEntity("Last Selected Channel", isLastSelectedChannel, R.drawable.ic_chart),
PreferenceEntity("About Us", "", R.drawable.ic_info_outline),
PreferenceEntity("Feedback", "", R.drawable.ic_feedback))
//region Fragment lifecycle
override fun onDestroy() {
(binding.adapter as BaseDataBindingAdapter<*, *>).detachAll()
super.onDestroy()
}
//endregion
//region Activity lifecycle
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initial the recycler view.
binding.apply {
layoutManager = WrapContentLinearLayoutManager(this@PreferenceActivity)
adapter = MultipleTypeAdapter(this@PreferenceActivity, preferenceList) { holder, item, _ ->
when (item) {
is PreferenceEntity -> {
(holder as BindingHolder<ItemPreferenceFirstLayerTitleBinding>).binding.avm =
PreferenceItemViewModel(binding.adapter as MultipleTypeAdapter,
preferenceList.indexOf(item), item)
}
is PreferenceOptionEntity -> {
(holder as BindingHolder<ItemPreferenceSecondLayerTitleBinding>).binding.avm =
PreferenceOptionViewModel(item)
}
is PreferenceToggleEntity -> {
(holder as BindingHolder<ItemPreferenceFirstLayerToggleBinding>).binding.avm =
PreferenceToggleViewModel(item).apply {
setBack = { entityName, checked ->
when (entityName) {
"Auto Play" -> isAutoPlay = checked
"Auto Download" -> isAutoDownload = checked
"Download Only Wifi" -> isDownloadByWifi = checked
"Lock Screen Lyrics Display" -> isLockScreenLyrics = checked
"Last Selected Channel" -> isLastSelectedChannel = checked
}
}
}
}
}
}
}
}
//endregion
//region Base activity implement
override fun provideBindingLayoutId() = this to R.layout.activity_preference
//endregion
} | apache-2.0 | 11545aff839e4d5f2a9975361a9f2ea1 | 49.863158 | 108 | 0.657214 | 5.189044 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/java/src/service/completion/GradleCompletionConsumer.kt | 2 | 3760 | // 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.gradle.service.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.PrioritizedLookupElement
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.lang.properties.IProperty
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.ui.JBColor
import com.intellij.util.asSafely
import com.intellij.util.lazyPub
import org.jetbrains.plugins.gradle.codeInspection.GradleForeignDelegateInspection.Companion.getDelegationHierarchy
import org.jetbrains.plugins.gradle.codeInspection.GradleForeignDelegateInspection.Companion.getDelegationSourceCaller
import org.jetbrains.plugins.gradle.codeInspection.GradleForeignDelegateInspection.DelegationHierarchy
import org.jetbrains.plugins.gradle.service.resolve.GradleExtensionsContributor
import org.jetbrains.plugins.groovy.lang.completion.api.GroovyCompletionConsumer
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightField
import kotlin.math.absoluteValue
class GradleCompletionConsumer(position: PsiElement, val delegate: GroovyCompletionConsumer) : GroovyCompletionConsumer by delegate {
private val delegationHierarchy: DelegationHierarchy by lazyPub {
getDelegationHierarchy(position)
}
override fun consume(element: LookupElement) {
val psi = element.psiElement ?: return delegate.consume(element)
val definingClass = getDelegationSourceCaller(delegationHierarchy, psi)
if (definingClass != null && definingClass != delegationHierarchy.list.firstOrNull()?.first && psi is PsiNamedElement) {
val newElement = element.modify { withItemTextForeground(JBColor.GRAY) }
GradleLookupWeigher.setGradleCompletionPriority(newElement, GradleLookupWeigher.DEFAULT_COMPLETION_PRIORITY - 1)
delegate.consume(newElement)
}
else if (psi is GrLightField && psi.originInfo == GradleExtensionsContributor.PROPERTIES_FILE_ORIGINAL_INFO) {
val property = psi.navigationElement.asSafely<IProperty>() ?: return delegate.consume(element)
val value = property.value
val newElement = element.modify { withTailText("=$value").withTypeText(psi.type.presentableText, true) }
delegate.consume(newElement)
}
else {
delegate.consume(element)
}
}
fun LookupElement.modify(modifier: LookupElementBuilder.() -> LookupElementBuilder): LookupElement {
val lookupBuilder = `as`(LookupElementBuilder::class.java) ?: return fallback(modifier)
val modified = lookupBuilder.modifier()
val prioritized = `as`(PrioritizedLookupElement::class.java) ?: return modified
if (prioritized.grouping != 0) {
return PrioritizedLookupElement.withGrouping(modified, prioritized.grouping)
}
else if (prioritized.explicitProximity != 0) {
return PrioritizedLookupElement.withExplicitProximity(modified, prioritized.grouping)
}
else if (prioritized.priority.absoluteValue > 1e-6) {
return PrioritizedLookupElement.withPriority(modified, prioritized.priority)
}
return modified
}
private fun LookupElement.fallback(modifier: LookupElementBuilder.() -> LookupElementBuilder): LookupElement {
val psi = psiElement.asSafely<PsiNamedElement>() ?: return this
return LookupElementBuilder.createWithIcon(psi).modifier()
}
override fun fastElementsProcessed(parameters: CompletionParameters) {
GradleVersionCatalogCompletionContributor().fillCompletionVariants(parameters, delegate.completionResultSet)
super.fastElementsProcessed(parameters)
}
} | apache-2.0 | f50aa7c3cbd05dc9225948f61e160b8d | 51.236111 | 133 | 0.80133 | 4.960422 | false | false | false | false |
YutaKohashi/FakeLineApp | app/src/main/java/jp/yuta/kohashi/fakelineapp/fragments/ListDialogFragment.kt | 1 | 3463 | package jp.yuta.kohashi.fakelineapp.fragments
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
/**
* Author : yutakohashi
* Project name : FakeLineApp
* Date : 10 / 09 / 2017
*/
class ListDialogFragment : DialogFragment() {
// // 選択肢のリスト
private val mTag = ListDialogFragment::class.java.simpleName
private var mActivity: AppCompatActivity? = null
private var mParentFragment: Fragment? = null
private var mItems:Array<String>? = null
companion object {
val KEY_ARRAY_STRING = "key_string"
val KEY_REQUEST_CODE = "request_code"
val KEY_TITLE_STRING = "key_string"
private var mClickAction:((index:Int) -> Unit)? = null
fun create(action: Builder.() -> Unit): ListDialogFragment = Builder(action).build()
}
// override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// val dialog = super.onCreateDialog(savedInstanceState)
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
//
//
// return dialog
// }
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val alert = AlertDialog.Builder(mActivity ?: mParentFragment?.context)
arguments.getString(KEY_TITLE_STRING)?.let { alert.setTitle(it) }
arguments.getStringArray(KEY_ARRAY_STRING)?.let { mItems = it }
alert.setItems(mItems,{ _, index ->
mClickAction?.invoke(index)
})
return alert.create()
}
fun show() {
val fm = mParentFragment!!.fragmentManager
// if (mParentFragment != null) show(mParentFragment!!.childFragmentManager, mTag)
if (mParentFragment != null) show(fm, mTag)
else if (mActivity != null) show(mActivity!!.supportFragmentManager, mTag)
}
fun setOnClickListener(action:(index:Int) -> Unit){
mClickAction = action
}
class Builder private constructor() {
private var requestCode: Int = 1000
private var activity: AppCompatActivity? = null
private var parentFragment: Fragment? = null
private var items: Array<String>? = null
private var title:String? = null
fun activity(action: Builder.() -> AppCompatActivity) {
activity = action()
}
fun requestCode(action: Builder.() -> Int) {
requestCode = action()
}
fun parentFragment(action: Builder.() -> Fragment) {
parentFragment = action()
}
fun items(action: Builder.() -> Array<String>) {
items = action()
}
fun title(action: Builder.() -> String){
title = action()
}
constructor(init: Builder.() -> Unit) : this() {
init()
}
fun build(): ListDialogFragment {
val fragment = ListDialogFragment()
fragment.mActivity = activity
fragment.mParentFragment = parentFragment
val bundle = Bundle()
if (items != null) bundle.putStringArray(ListDialogFragment.KEY_ARRAY_STRING, items)
fragment.arguments = bundle
if (parentFragment != null) fragment.setTargetFragment(parentFragment, requestCode)
else bundle.putInt(KEY_REQUEST_CODE, requestCode)
return fragment
}
}
} | mit | dbd23f7cdb81d955296eccce6e150516 | 30.363636 | 96 | 0.628878 | 4.598667 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/text/DateTimeFormatConfigurable.kt | 4 | 4516 | // 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.ide.ui.text
import com.intellij.ide.IdeBundle
import com.intellij.ide.ui.LafManager
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.options.Configurable.NoScroll
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBTextField
import com.intellij.ui.dsl.builder.*
import com.intellij.util.text.CustomJBDateTimeFormatter
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.text.DateTimeFormatManager
import com.intellij.util.text.JBDateFormat
import java.text.SimpleDateFormat
import javax.swing.JEditorPane
import javax.swing.event.DocumentEvent
/**
* @author Konstantin Bulenkov
*/
class DateTimeFormatConfigurable : BoundSearchableConfigurable(
IdeBundle.message("date.time.format.configurable"),
"ide.date.format"
), NoScroll {
private lateinit var dateFormatField: Cell<JBTextField>
private lateinit var use24HourCheckbox: Cell<JBCheckBox>
private lateinit var datePreviewField: Cell<JEditorPane>
override fun createPanel(): DialogPanel {
val settings = DateTimeFormatManager.getInstance()
return panel {
lateinit var overrideSystemDateFormatting: Cell<JBCheckBox>
row {
overrideSystemDateFormatting = checkBox(IdeBundle.message("date.format.override.system.date.and.time.format"))
.bindSelected(
{ settings.isOverrideSystemDateFormat },
{ settings.isOverrideSystemDateFormat = it })
}
indent {
row(IdeBundle.message("date.format.date.format")) {
dateFormatField = textField()
.bindText({ settings.dateFormatPattern },
{ settings.dateFormatPattern = it })
.columns(16)
.validationOnInput { field ->
validateDatePattern(field.text)?.let { error(it) }
}
.applyToComponent {
document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
updateCommentField()
}
})
}
browserLink(IdeBundle.message("date.format.date.patterns"),
"https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html")
}
row {
use24HourCheckbox = checkBox(IdeBundle.message("date.format.24.hours"))
.bindSelected({ settings.isUse24HourTime },
{ settings.isUse24HourTime = it })
.applyToComponent {
addChangeListener { updateCommentField() }
}
}
row {
datePreviewField = comment("", maxLineLength = MAX_LINE_LENGTH_NO_WRAP)
}
}.enabledIf(overrideSystemDateFormatting.selected)
row {
checkBox(IdeBundle.message("date.format.pretty"))
.bindSelected(
{ settings.isPrettyFormattingAllowed },
{ settings.isPrettyFormattingAllowed = it })
.comment(IdeBundle.message("date.format.relative"))
}.topGap(TopGap.SMALL)
updateCommentField()
onApply {
JBDateFormat.invalidateCustomFormatter()
LafManager.getInstance().updateUI()
}
}
}
private fun validateDatePattern(pattern: String): @NlsContexts.DialogMessage String? {
try {
SimpleDateFormat(pattern)
}
catch (e: IllegalArgumentException) {
return IdeBundle.message("date.format.error.invalid.pattern", e.message)
}
if (pattern.contains("'")) return null // escaped text - assume user knows what they're doing
if (StringUtil.containsAnyChar(pattern, "aHhKkmSs")) {
return IdeBundle.message("date.format.error.contains.time.pattern")
}
return null
}
private fun updateCommentField() {
val text = try {
val formatter = CustomJBDateTimeFormatter(dateFormatField.component.text, use24HourCheckbox.component.isSelected)
formatter.formatDateTime(DateFormatUtil.getSampleDateTime())
}
catch (e: IllegalArgumentException) {
IdeBundle.message("date.format.error.invalid.pattern", e.message)
}
datePreviewField.text(StringUtil.escapeXmlEntities(text))
}
}
| apache-2.0 | 1d5fe846d51150a6a0dc137ba7ff9518 | 35.715447 | 140 | 0.686227 | 4.670114 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis-api-providers-ide-impl/src/org/jetbrains/kotlin/analysis/providers/ide/KotlinIdeAnnotationsResolver.kt | 1 | 6322 | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.providers.ide
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.analysis.providers.KotlinAnnotationsResolver
import org.jetbrains.kotlin.analysis.providers.KotlinAnnotationsResolverFactory
import org.jetbrains.kotlin.idea.stubindex.KotlinAnnotationsIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
internal class KotlinIdeAnnotationsResolverFactory(private val project: Project) : KotlinAnnotationsResolverFactory {
override fun createAnnotationResolver(searchScope: GlobalSearchScope): KotlinAnnotationsResolver {
return KotlinIdeAnnotationsResolver(project, searchScope)
}
}
/**
* IDE-mode implementation for [KotlinAnnotationsResolver].
*
* Uses indices and PSI as a way to "resolve" the annotations, so it might not be 100% accurate.
*
* @param searchScope A scope in which [KotlinIdeAnnotationsResolver] will operate.
*/
private class KotlinIdeAnnotationsResolver(
private val project: Project,
private val searchScope: GlobalSearchScope,
) : KotlinAnnotationsResolver {
override fun declarationsByAnnotation(queriedAnnotation: ClassId): Set<KtAnnotated> {
require(!queriedAnnotation.isLocal && !queriedAnnotation.isNestedClass) {
"Queried annotation must be top-level, but was $queriedAnnotation"
}
val annotationsIndex = KotlinAnnotationsIndex.getInstance()
val annotationEntries = annotationsIndex[queriedAnnotation.shortClassName.asString(), project, searchScope]
return annotationEntries.asSequence()
.filter { it.resolveAnnotationId() == queriedAnnotation }
.mapNotNull { it.annotatedDeclaration }
.filter { it is KtFile || it is KtDeclaration }
.toSet()
}
override fun annotationsOnDeclaration(declaration: KtAnnotated): Set<ClassId> {
val annotationEntries = when (declaration) {
is KtFile -> declaration.annotationEntries
is KtDeclaration -> declaration.annotationEntries
else -> error("Unexpected element of class ${declaration::class}")
}
return annotationEntries.mapNotNull { it.resolveAnnotationId() }.toSet()
}
/**
* Examples of usage:
*
* - `Baz` -> `FqName("Baz")`
* - `Bar.Baz` -> `FqName("Bar.Baz")`
* - `foo.bar.Baz<A, B>` -> `FqName("foo.bar.Baz")`
*/
private fun KtUserType.referencedFqName(): FqName? {
val allTypes = generateSequence(this) { it.qualifier }.toList().asReversed()
val allQualifiers = allTypes.map { it.referencedName ?: return null }
return FqName.fromSegments(allQualifiers)
}
private fun KtAnnotationEntry.resolveAnnotationId(): ClassId? {
return resolveAnnotationFqName()?.let { ClassId.topLevel(it) }
}
private fun KtAnnotationEntry.resolveAnnotationFqName(): FqName? {
val annotationTypeElement = typeReference?.typeElement as? KtUserType
val referencedName = annotationTypeElement?.referencedFqName() ?: return null
// FIXME what happens with aliased imports? They are correctly reported by the annotation index
if (referencedName.isRoot) return null
if (!referencedName.parent().isRoot) {
// we assume here that the annotation is used by its fully-qualified name
return referencedName.takeIf { annotationActuallyExists(it) }
}
val candidates = getCandidatesFromImports(containingKtFile, referencedName.shortName())
return candidates.fromExplicitImports.resolveToSingleName()
?: candidates.fromSamePackage.resolveToSingleName()
?: candidates.fromStarImports.resolveToSingleName()
}
/**
* A set of places where the annotation can be possibly resolved.
*
* @param fromSamePackage A possible candidate from the same package. It is a single name, but it is wrapped into a set for consistency.
* @param fromExplicitImports Candidates from the explicit, fully-qualified imports with matching short name.
* @param fromStarImports Candidates from all star imports in the file; it is possible that the annotation goes from one of them.
*/
private data class ResolveByImportsCandidates(
val fromSamePackage: Set<FqName>,
val fromExplicitImports: Set<FqName>,
val fromStarImports: Set<FqName>,
)
private fun getCandidatesFromImports(
file: KtFile,
targetName: Name,
): ResolveByImportsCandidates {
val starImports = mutableSetOf<FqName>()
val explicitImports = mutableSetOf<FqName>()
for (import in file.importDirectives) {
val importedName = import.importedFqName ?: continue
if (import.isAllUnder) {
starImports += importedName.child(targetName)
} else if (importedName.shortName() == targetName) {
explicitImports += importedName
}
}
val packageImport = file.packageFqName.child(targetName)
return ResolveByImportsCandidates(setOf(packageImport), explicitImports, starImports)
}
private fun Set<FqName>.resolveToSingleName(): FqName? = singleOrNull { annotationActuallyExists(it) }
private fun annotationActuallyExists(matchingImport: FqName): Boolean {
val foundClasses = KotlinFullClassNameIndex.getInstance()[matchingImport.asString(), project, searchScope]
return foundClasses.singleOrNull { it.isAnnotation() && it.isTopLevel() } != null
}
}
/**
* A declaration which is annotated with passed [KtAnnotationEntry].
*/
private val KtAnnotationEntry.annotatedDeclaration: KtAnnotated?
get() {
val modifierListEntry = this.parent as? KtAnnotation ?: this
val modifierList = modifierListEntry.parent as? KtModifierList
return modifierList?.parent as? KtAnnotated
}
| apache-2.0 | 35fdabfbea423b0c2073dd007acd9c61 | 40.592105 | 140 | 0.712591 | 5.009509 | false | false | false | false |
jwren/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyDataclassInspection.kt | 4 | 30632 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jetbrains.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.util.containers.ContainerUtil
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.codeInsight.*
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.ParamHelper
import com.jetbrains.python.psi.impl.PyCallExpressionHelper
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.stubs.PyDataclassFieldStubImpl
import com.jetbrains.python.psi.stubs.PyDataclassFieldStub
import com.jetbrains.python.psi.types.*
import one.util.streamex.StreamEx
class PyDataclassInspection : PyInspection() {
companion object {
private val ORDER_OPERATORS = setOf("__lt__", "__le__", "__gt__", "__ge__")
private val DATACLASSES_HELPERS = setOf("dataclasses.fields", "dataclasses.asdict", "dataclasses.astuple", "dataclasses.replace")
private val ATTRS_HELPERS = setOf("attr.fields",
"attr.fields_dict",
"attr.asdict",
"attr.astuple",
"attr.assoc",
"attr.evolve")
private enum class ClassOrder {
MANUALLY, DC_ORDERED, DC_UNORDERED, UNKNOWN
}
}
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(
holder,PyInspectionVisitor.getContext(session))
private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) {
override fun visitPyTargetExpression(node: PyTargetExpression) {
super.visitPyTargetExpression(node)
checkMutatingFrozenAttribute(node)
}
override fun visitPyDelStatement(node: PyDelStatement) {
super.visitPyDelStatement(node)
node.targets
.asSequence()
.filterIsInstance<PyReferenceExpression>()
.forEach { checkMutatingFrozenAttribute(it) }
}
override fun visitPyClass(node: PyClass) {
super.visitPyClass(node)
val dataclassParameters = parseDataclassParameters(node, myTypeEvalContext)
if (dataclassParameters != null) {
if (dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD) {
processDataclassParameters(node, dataclassParameters)
val postInit = node.findMethodByName(DUNDER_POST_INIT, false, myTypeEvalContext)
val localInitVars = mutableListOf<PyTargetExpression>()
node.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression) {
if (!PyTypingTypeProvider.isClassVar(element, myTypeEvalContext)) {
processDefaultFieldValue(element)
processAsInitVar(element, postInit)?.let { localInitVars.add(it) }
}
processFieldFunctionCall(element)
}
true
}
if (postInit != null) {
processPostInitDefinition(node, postInit, dataclassParameters, localInitVars)
}
}
else if (dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) {
processAttrsParameters(node, dataclassParameters)
node
.findMethodByName(DUNDER_ATTRS_POST_INIT, false, myTypeEvalContext)
?.also { processAttrsPostInitDefinition(it, dataclassParameters) }
processAttrsDefaultThroughDecorator(node)
processAttrsInitializersAndValidators(node)
processAttrIbFunctionCalls(node)
}
processAnnotationsExistence(node, dataclassParameters)
PyNamedTupleInspection.inspectFieldsOrder(
node,
{
val parameters = parseDataclassParameters(it, myTypeEvalContext)
parameters != null && !parameters.kwOnly
},
dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD,
myTypeEvalContext,
this::registerProblem,
{
val stub = it.stub
val fieldStub = if (stub == null) PyDataclassFieldStubImpl.create(it)
else stub.getCustomStub(PyDataclassFieldStub::class.java)
(fieldStub == null || fieldStub.initValue() && !fieldStub.kwOnly()) &&
!(fieldStub == null && it.annotationValue == null) && // skip fields that are not annotated
!PyTypingTypeProvider.isClassVar(it, myTypeEvalContext) // skip classvars
},
{
val fieldStub = PyDataclassFieldStubImpl.create(it)
if (fieldStub != null) {
fieldStub.hasDefault() ||
fieldStub.hasDefaultFactory() ||
dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS &&
node.methods.any { m -> m.decoratorList?.findDecorator("${it.name}.default") != null }
}
else {
val assignedValue = it.findAssignedValue()
assignedValue != null && !resolvesToOmittedDefault(assignedValue, dataclassParameters.type)
}
}
)
}
}
override fun visitPyBinaryExpression(node: PyBinaryExpression) {
super.visitPyBinaryExpression(node)
val leftOperator = node.referencedName
if (leftOperator != null && ORDER_OPERATORS.contains(leftOperator)) {
val leftClass = getInstancePyClass(node.leftExpression) ?: return
val rightClass = getInstancePyClass(node.rightExpression) ?: return
val (leftOrder, leftType) = getDataclassHierarchyOrder(leftClass, leftOperator)
if (leftOrder == ClassOrder.MANUALLY) return
val (rightOrder, _) = getDataclassHierarchyOrder(rightClass, PyNames.leftToRightOperatorName(leftOperator))
if (leftClass == rightClass) {
if (leftOrder == ClassOrder.DC_UNORDERED && rightOrder != ClassOrder.MANUALLY) {
registerProblem(node.psiOperator,
PyPsiBundle.message("INSP.dataclasses.operator.not.supported.between.instances.of.class", leftOperator, leftClass.name),
ProblemHighlightType.GENERIC_ERROR)
}
}
else {
if (leftOrder == ClassOrder.DC_ORDERED ||
leftOrder == ClassOrder.DC_UNORDERED ||
rightOrder == ClassOrder.DC_ORDERED ||
rightOrder == ClassOrder.DC_UNORDERED) {
if (leftOrder == ClassOrder.DC_ORDERED &&
leftType?.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS &&
rightClass.isSubclass(leftClass, myTypeEvalContext)) return // attrs allows to compare ancestor and its subclass
registerProblem(node.psiOperator,
PyPsiBundle.message("INSP.dataclasses.operator.not.supported.between.instances.of.classes", leftOperator, leftClass.name, rightClass.name),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
}
override fun visitPyCallExpression(node: PyCallExpression) {
val callees = node.multiResolveCallee(resolveContext)
val calleeQName = callees.mapNotNullTo(mutableSetOf()) { it.callable?.qualifiedName }.singleOrNull()
if (calleeQName != null) {
val dataclassType = when {
DATACLASSES_HELPERS.contains(calleeQName) -> PyDataclassParameters.PredefinedType.STD
ATTRS_HELPERS.contains(calleeQName) -> PyDataclassParameters.PredefinedType.ATTRS
else -> return
}
val callableType = callees.first()
val mapping = PyCallExpressionHelper.mapArguments(node, callableType, myTypeEvalContext)
val dataclassParameter = callableType.getParameters(myTypeEvalContext)?.firstOrNull()
val dataclassArgument = mapping.mappedParameters.entries.firstOrNull { it.value == dataclassParameter }?.key
if (dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.STD) {
processHelperDataclassArgument(dataclassArgument, calleeQName)
}
else if (dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) {
processHelperAttrsArgument(dataclassArgument, calleeQName)
}
}
}
override fun visitPyReferenceExpression(node: PyReferenceExpression) {
super.visitPyReferenceExpression(node)
if (node.isQualified) {
val cls = getInstancePyClass(node.qualifier) ?: return
val resolved = node.getReference(resolveContext).multiResolve(false)
if (resolved.isNotEmpty() && resolved.asSequence().map { it.element }.all { it is PyTargetExpression && isInitVar(it) }) {
registerProblem(node.lastChild,
PyPsiBundle.message("INSP.dataclasses.object.could.have.no.attribute.because.it.declared.as.init.only", cls.name, node.name),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
}
}
private fun checkMutatingFrozenAttribute(expression: PyQualifiedExpression) {
val cls = getInstancePyClass(expression.qualifier) ?: return
if (StreamEx
.of(cls).append(cls.getAncestorClasses(myTypeEvalContext))
.mapNotNull { parseDataclassParameters(it, myTypeEvalContext) }
.any { it.frozen }) {
registerProblem(expression,
PyPsiBundle.message("INSP.dataclasses.object.attribute.read.only", cls.name, expression.name),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun getDataclassHierarchyOrder(cls: PyClass, operator: String?): Pair<ClassOrder, PyDataclassParameters.Type?> {
var seenUnordered: Pair<ClassOrder, PyDataclassParameters.Type?>? = null
for (current in StreamEx.of(cls).append(cls.getAncestorClasses(myTypeEvalContext))) {
val order = getDataclassOrder(current, operator)
// `order=False` just does not add comparison methods
// but it makes sense when no one in the hierarchy defines any of such methods
if (order.first == ClassOrder.DC_UNORDERED) seenUnordered = order
else if (order.first != ClassOrder.UNKNOWN) return order
}
return if (seenUnordered != null) seenUnordered else ClassOrder.UNKNOWN to null
}
private fun getDataclassOrder(cls: PyClass, operator: String?): Pair<ClassOrder, PyDataclassParameters.Type?> {
val type = cls.getType(myTypeEvalContext)
if (operator != null &&
type != null &&
!type.resolveMember(operator, null, AccessDirection.READ, resolveContext, false).isNullOrEmpty()) {
return ClassOrder.MANUALLY to null
}
val parameters = parseDataclassParameters(cls, myTypeEvalContext) ?: return ClassOrder.UNKNOWN to null
return if (parameters.order) ClassOrder.DC_ORDERED to parameters.type else ClassOrder.DC_UNORDERED to parameters.type
}
private fun getInstancePyClass(element: PyTypedElement?): PyClass? {
val type = element?.let { myTypeEvalContext.getType(it) } as? PyClassType
return if (type != null && !type.isDefinition) type.pyClass else null
}
private fun processDataclassParameters(cls: PyClass, dataclassParameters: PyDataclassParameters) {
if (!dataclassParameters.eq && dataclassParameters.order) {
registerProblem(dataclassParameters.eqArgument, PyPsiBundle.message("INSP.dataclasses.eq.must.be.true.if.order.true"), ProblemHighlightType.GENERIC_ERROR)
}
var initMethodExists = false
var reprMethodExists = false
var eqMethodExists = false
var orderMethodsExist = false
var mutatingMethodsExist = false
var hashMethodExists = false
cls.methods.forEach {
when (it.name) {
PyNames.INIT -> initMethodExists = true
"__repr__" -> reprMethodExists = true
"__eq__" -> eqMethodExists = true
in ORDER_OPERATORS -> orderMethodsExist = true
"__setattr__", "__delattr__" -> mutatingMethodsExist = true
PyNames.HASH -> hashMethodExists = true
}
}
hashMethodExists = hashMethodExists || cls.findClassAttribute(PyNames.HASH, false, myTypeEvalContext) != null
// argument to register problem, argument name and method name
val useless = mutableListOf<Triple<PyExpression?, String, String>>()
if (dataclassParameters.init && initMethodExists) {
useless.add(Triple(dataclassParameters.initArgument, "init", PyNames.INIT))
}
if (dataclassParameters.repr && reprMethodExists) {
useless.add(Triple(dataclassParameters.reprArgument, "repr", "__repr__"))
}
if (dataclassParameters.eq && eqMethodExists) {
useless.add(Triple(dataclassParameters.eqArgument, "eq", "__eq__"))
}
useless.forEach {
registerProblem(it.first,
PyPsiBundle.message("INSP.dataclasses.argument.ignored.if.class.already.defines.method", it.second, it.third),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
if (dataclassParameters.order && orderMethodsExist) {
registerProblem(dataclassParameters.orderArgument,
PyPsiBundle.message("INSP.dataclasses.order.argument.should.be.false.if.class.defines.one.of.order.methods"),
ProblemHighlightType.GENERIC_ERROR)
}
if (dataclassParameters.frozen && mutatingMethodsExist) {
registerProblem(dataclassParameters.frozenArgument,
PyPsiBundle.message("INSP.dataclasses.frozen.attribute.should.be.false.if.class.defines.setattr.or.delattr"),
ProblemHighlightType.GENERIC_ERROR)
}
if (dataclassParameters.unsafeHash && hashMethodExists) {
registerProblem(dataclassParameters.unsafeHashArgument,
PyPsiBundle.message("INSP.dataclasses.unsafe.hash.attribute.should.be.false.if.class.defines.hash"),
ProblemHighlightType.GENERIC_ERROR)
}
var frozenInHierarchy: Boolean? = null
for (current in StreamEx.of(cls).append(cls.getAncestorClasses(myTypeEvalContext))) {
val currentFrozen = parseStdDataclassParameters(current, myTypeEvalContext)?.frozen ?: continue
if (frozenInHierarchy == null) {
frozenInHierarchy = currentFrozen
}
else if (frozenInHierarchy != currentFrozen) {
registerProblem(dataclassParameters.frozenArgument ?: cls.nameIdentifier,
PyPsiBundle.message("INSP.dataclasses.frozen.dataclasses.can.not.inherit.non.frozen.one"),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
private fun processAttrsParameters(cls: PyClass, dataclassParameters: PyDataclassParameters) {
var initMethod: PyFunction? = null
var reprMethod: PyFunction? = null
var strMethod: PyFunction? = null
val cmpMethods = mutableListOf<PyFunction>()
val mutatingMethods = mutableListOf<PyFunction>()
var hashMethod: PsiNameIdentifierOwner? = null
cls.methods.forEach {
when (it.name) {
PyNames.INIT -> initMethod = it
"__repr__" -> reprMethod = it
"__str__" -> strMethod = it
"__eq__",
in ORDER_OPERATORS -> cmpMethods.add(it)
"__setattr__", "__delattr__" -> mutatingMethods.add(it)
PyNames.HASH -> hashMethod = it
}
}
hashMethod = hashMethod ?: cls.findClassAttribute(PyNames.HASH, false, myTypeEvalContext)
// element to register problem and corresponding attr.s parameter
val problems = mutableListOf<Pair<PsiNameIdentifierOwner?, String>>()
if (dataclassParameters.init && initMethod != null) {
problems.add(initMethod to "init")
}
if (dataclassParameters.repr && reprMethod != null) {
problems.add(reprMethod to "repr")
}
if (PyEvaluator.evaluateAsBoolean(PyUtil.peelArgument(dataclassParameters.others["str"]), false) && strMethod != null) {
problems.add(strMethod to "str")
}
if (dataclassParameters.order && cmpMethods.isNotEmpty()) {
cmpMethods.forEach { problems.add(it to "cmp/order") }
}
if (dataclassParameters.frozen && mutatingMethods.isNotEmpty()) {
mutatingMethods.forEach { problems.add(it to "frozen") }
}
if (dataclassParameters.unsafeHash && hashMethod != null) {
problems.add(hashMethod to "hash")
}
problems.forEach {
it.first?.apply {
registerProblem(nameIdentifier,
PyPsiBundle.message("INSP.dataclasses.method.is.ignored.if.class.already.defines.parameter", name, it.second),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
}
if (dataclassParameters.order && dataclassParameters.frozen && hashMethod != null) {
registerProblem(hashMethod?.nameIdentifier,
PyPsiBundle.message("INSP.dataclasses.hash.ignored.if.class.already.defines.cmp.or.order.or.frozen.parameters"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
}
private fun processDefaultFieldValue(field: PyTargetExpression) {
if (field.annotationValue == null) return
val value = field.findAssignedValue()
if (value is PyCallExpression) {
val fieldWithDefaultFactory = value
.multiResolveCallee(resolveContext)
.filter { it.callable?.qualifiedName == "dataclasses.field" }
.any {
PyCallExpressionHelper.mapArguments(value, it, myTypeEvalContext).mappedParameters.values.any { p ->
p.name == "default_factory"
}
}
if (fieldWithDefaultFactory) {
return
}
}
if (PyUtil.isForbiddenMutableDefault(value, myTypeEvalContext)) {
registerProblem(value,
PyPsiBundle.message("INSP.dataclasses.mutable.attribute.default.not.allowed.use.default.factory", value?.text),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun processAttrsDefaultThroughDecorator(cls: PyClass) {
val initializers = mutableMapOf<String, MutableList<PyFunction>>()
cls.methods.forEach { method ->
val decorators = method.decoratorList?.decorators
if (decorators != null) {
decorators
.asSequence()
.mapNotNull { it.qualifiedName }
.filter { it.componentCount == 2 && it.endsWith("default") }
.mapNotNull { it.firstComponent }
.firstOrNull()
?.also { name ->
val attribute = cls.findClassAttribute(name, false, myTypeEvalContext)
if (attribute != null) {
initializers.computeIfAbsent(name, { mutableListOf() }).add(method)
val stub = PyDataclassFieldStubImpl.create(attribute)
if (stub != null && (stub.hasDefault() || stub.hasDefaultFactory())) {
registerProblem(method.nameIdentifier,
PyPsiBundle.message("INSP.dataclasses.attribute.default.is.set.using.attr.ib"),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
}
}
initializers.values.forEach { sameAttrInitializers ->
val first = sameAttrInitializers[0]
sameAttrInitializers
.asSequence()
.drop(1)
.forEach { registerProblem(it.nameIdentifier,
PyPsiBundle.message("INSP.dataclasses.attribute.default.set.using.method", first.name),
ProblemHighlightType.GENERIC_ERROR) }
}
}
private fun processAttrsInitializersAndValidators(cls: PyClass) {
cls.visitMethods(
{ method ->
val decorators = method.decoratorList?.decorators
if (decorators != null) {
decorators
.asSequence()
.mapNotNull { it.qualifiedName }
.filter { it.componentCount == 2 }
.mapNotNull { it.lastComponent }
.forEach {
val expectedParameters = when (it) {
"default" -> 1
"validator" -> 3
else -> return@forEach
}
val actualParameters = method.parameterList
if (actualParameters.parameters.size != expectedParameters) {
val message = PyPsiBundle.message("INSP.dataclasses.method.should.take.only.n.parameter", method.name, expectedParameters)
registerProblem(actualParameters, message, ProblemHighlightType.GENERIC_ERROR)
}
}
}
true
},
false,
myTypeEvalContext
)
}
private fun processAnnotationsExistence(cls: PyClass, dataclassParameters: PyDataclassParameters) {
if (dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD ||
PyEvaluator.evaluateAsBoolean(PyUtil.peelArgument(dataclassParameters.others["auto_attribs"]), false)) {
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression && element.annotation == null && PyDataclassFieldStubImpl.create(element) != null) {
registerProblem(element, PyPsiBundle.message("INSP.dataclasses.attribute.lacks.type.annotation", element.name),
ProblemHighlightType.GENERIC_ERROR)
}
true
}
}
}
private fun processAttrIbFunctionCalls(cls: PyClass) {
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression) {
val call = element.findAssignedValue() as? PyCallExpression
val stub = PyDataclassFieldStubImpl.create(element)
if (call != null && stub != null) {
if (stub.hasDefaultFactory()) {
if (stub.hasDefault()) {
registerProblem(call.argumentList, PyPsiBundle.message("INSP.dataclasses.cannot.specify.both.default.and.factory"),
ProblemHighlightType.GENERIC_ERROR)
}
else {
// at least covers the following case: `attr.ib(default=attr.Factory(...), factory=...)`
val default = call.getKeywordArgument("default")
val factory = call.getKeywordArgument("factory")
if (default != null && factory != null && !resolvesToOmittedDefault(default, PyDataclassParameters.PredefinedType.ATTRS)) {
registerProblem(call.argumentList, PyPsiBundle.message("INSP.dataclasses.cannot.specify.both.default.and.factory"),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
}
}
true
}
}
private fun processAsInitVar(field: PyTargetExpression, postInit: PyFunction?): PyTargetExpression? {
if (isInitVar(field)) {
if (postInit == null) {
registerProblem(field,
PyPsiBundle.message("INSP.dataclasses.attribute.useless.until.post.init.declared", field.name),
ProblemHighlightType.LIKE_UNUSED_SYMBOL)
}
return field
}
return null
}
private fun processFieldFunctionCall(field: PyTargetExpression) {
val fieldStub = PyDataclassFieldStubImpl.create(field) ?: return
val call = field.findAssignedValue() as? PyCallExpression ?: return
if (PyTypingTypeProvider.isClassVar(field, myTypeEvalContext) || isInitVar(field)) {
if (fieldStub.hasDefaultFactory()) {
registerProblem(call.getKeywordArgument("default_factory"),
PyPsiBundle.message("INSP.dataclasses.field.cannot.have.default.factory"),
ProblemHighlightType.GENERIC_ERROR)
}
}
else if (fieldStub.hasDefault() && fieldStub.hasDefaultFactory()) {
registerProblem(call.argumentList, PyPsiBundle.message("INSP.dataclasses.cannot.specify.both.default.and.default.factory"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun processPostInitDefinition(cls: PyClass,
postInit: PyFunction,
dataclassParameters: PyDataclassParameters,
localInitVars: List<PyTargetExpression>) {
if (!dataclassParameters.init) {
registerProblem(postInit.nameIdentifier,
PyPsiBundle.message("INSP.dataclasses.post.init.would.not.be.called.until.init.parameter.set.to.true"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL)
return
}
if (ParamHelper.isSelfArgsKwargsCallable(postInit, myTypeEvalContext)) return
val allInitVars = mutableListOf<PyTargetExpression>()
for (ancestor in cls.getAncestorClasses(myTypeEvalContext).asReversed()) {
if (parseStdDataclassParameters(ancestor, myTypeEvalContext) == null) continue
ancestor.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression && isInitVar(element)) {
allInitVars.add(element)
}
return@processClassLevelDeclarations true
}
}
allInitVars.addAll(localInitVars)
val implicitParameters = postInit.getParameters(myTypeEvalContext)
val parameters = if (implicitParameters.isEmpty()) emptyList<PyCallableParameter>() else ContainerUtil.subList(implicitParameters, 1)
val message = if (allInitVars.size != localInitVars.size) {
PyPsiBundle.message("INSP.dataclasses.post.init.should.take.all.init.only.variables.including.inherited.in.same.order.they.defined")
}
else {
PyPsiBundle.message("INSP.dataclasses.post.init.should.take.all.init.only.variables.in.same.order.they.defined")
}
if (parameters.size != allInitVars.size) {
registerProblem(postInit.parameterList, message, ProblemHighlightType.GENERIC_ERROR)
}
else {
parameters
.asSequence()
.zip(allInitVars.asSequence())
.all { it.first.name == it.second.name }
.also { if (!it) registerProblem(postInit.parameterList, message) }
}
}
private fun processAttrsPostInitDefinition(postInit: PyFunction, dataclassParameters: PyDataclassParameters) {
if (!dataclassParameters.init) {
registerProblem(postInit.nameIdentifier,
PyPsiBundle.message("INSP.dataclasses.attrs.post.init.would.not.be.called.until.init.parameter.set.to.true"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL)
}
if (postInit.getParameters(myTypeEvalContext).size != 1) {
registerProblem(postInit.parameterList,
PyPsiBundle.message("INSP.dataclasses.attrs.post.init.should.not.take.any.parameters.except.self"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun processHelperDataclassArgument(argument: PyExpression?, calleeQName: String) {
if (argument == null) return
val allowDefinition = calleeQName == "dataclasses.fields"
val type = myTypeEvalContext.getType(argument)
val allowSubclass = calleeQName != "dataclasses.asdict"
if (!isExpectedDataclass(type, PyDataclassParameters.PredefinedType.STD, allowDefinition, true, allowSubclass)) {
val message = if (allowDefinition) {
PyPsiBundle.message("INSP.dataclasses.method.should.be.called.on.dataclass.instances.or.types", calleeQName)
}
else {
PyPsiBundle.message("INSP.dataclasses.method.should.be.called.on.dataclass.instances", calleeQName)
}
registerProblem(argument, message)
}
}
private fun processHelperAttrsArgument(argument: PyExpression?, calleeQName: String) {
if (argument == null) return
val instance = calleeQName != "attr.fields" && calleeQName != "attr.fields_dict"
val type = myTypeEvalContext.getType(argument)
if (!isExpectedDataclass(type, PyDataclassParameters.PredefinedType.ATTRS, !instance, instance, true)) {
val message = if (instance) {
PyPsiBundle.message("INSP.dataclasses.method.should.be.called.on.attrs.instances", calleeQName)
}
else {
PyPsiBundle.message("INSP.dataclasses.method.should.be.called.on.attrs.types", calleeQName)
}
registerProblem(argument, message)
}
}
private fun isInitVar(field: PyTargetExpression): Boolean {
return (myTypeEvalContext.getType(field) as? PyClassType)?.classQName == DATACLASSES_INITVAR_TYPE
}
private fun isExpectedDataclass(type: PyType?,
dataclassType: PyDataclassParameters.PredefinedType?,
allowDefinition: Boolean,
allowInstance: Boolean,
allowSubclass: Boolean): Boolean {
if (type is PyStructuralType || PyTypeChecker.isUnknown(type, myTypeEvalContext)) return true
if (type is PyUnionType) return type.members.any {
isExpectedDataclass(it, dataclassType, allowDefinition, allowInstance, allowSubclass)
}
return type is PyClassType &&
(allowDefinition || !type.isDefinition) &&
(allowInstance || type.isDefinition) &&
(
parseDataclassParameters(type.pyClass, myTypeEvalContext)?.type?.asPredefinedType == dataclassType ||
allowSubclass && type.getAncestorTypes(myTypeEvalContext).any {
isExpectedDataclass(it, dataclassType, true, false, false)
}
)
}
}
}
| apache-2.0 | 4f7b49228276e901bf28c502937a90bc | 41.901961 | 167 | 0.643445 | 5.284112 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/actions/persistence/ActionsCollectorImpl.kt | 1 | 14160 | // 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.internal.statistic.collectors.fus.actions.persistence
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.ide.actions.ActionsCollector
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.internal.statistic.eventLog.events.*
import com.intellij.internal.statistic.eventLog.events.FusInputEvent.Companion.from
import com.intellij.internal.statistic.utils.PluginInfo
import com.intellij.internal.statistic.utils.StatisticsUtil.roundDuration
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.FusAwareAction
import com.intellij.openapi.actionSystem.impl.Utils
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.util.TimeoutUtil
import it.unimi.dsi.fastutil.objects.Object2LongMaps
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap
import java.awt.event.InputEvent
import java.lang.ref.WeakReference
import java.util.*
class ActionsCollectorImpl : ActionsCollector() {
private data class ActionUpdateStatsKey(val actionId: String, val language: String)
private val myUpdateStats = Object2LongMaps.synchronize(Object2LongOpenHashMap<ActionUpdateStatsKey>())
override fun record(actionId: String?, event: InputEvent?, context: Class<*>) {
recordCustomActionInvoked(null, actionId, event, context)
}
override fun record(project: Project?, action: AnAction?, event: AnActionEvent?, lang: Language?) {
recordActionInvoked(project, action, event) {
add(EventFields.CurrentFile.with(lang))
}
}
override fun onActionConfiguredByActionId(action: AnAction, actionId: String) {
ourAllowedList.registerDynamicActionId(action, actionId)
}
override fun recordUpdate(action: AnAction, event: AnActionEvent, durationMs: Long) {
if (durationMs <= 5) return
val dataContext = getCachedDataContext(event.dataContext)
val project = CommonDataKeys.PROJECT.getData(dataContext)
ActionsEventLogGroup.ACTION_UPDATED.log(project) {
val info = getPluginInfo(action.javaClass)
val actionId = addActionClass(this, action, info)
var language = getInjectedOrFileLanguage(project, dataContext)
if (language == null) {
language = Language.ANY
}
val statsKey = ActionUpdateStatsKey(actionId, language!!.id)
val reportedData = myUpdateStats.getLong(statsKey)
if (reportedData == 0L || durationMs >= 2 * reportedData) {
myUpdateStats.put(statsKey, durationMs)
add(EventFields.PluginInfo.with(info))
add(EventFields.Language.with(language))
add(EventFields.DurationMs.with(durationMs))
}
else {
skip()
}
}
}
private class Stats(
project: Project?,
/**
* Language from [CommonDataKeys.PSI_FILE]
*/
val fileLanguage: Language?,
/**
* Language from [InjectedDataKeys.EDITOR], [InjectedDataKeys.PSI_FILE] or [CommonDataKeys.PSI_FILE]
*/
var injectedFileLanguage: Language?
) {
/**
* Action start time in milliseconds, used to report "start_time" field
*/
val startMs = System.currentTimeMillis()
/**
* Action start time in nanoseconds, used to report "duration_ms" field
* We can't use ms to measure duration because it depends on local system time and, therefore, can go backwards
*/
val start = System.nanoTime()
var projectRef = WeakReference(project)
val isDumb = if (project != null && !project.isDisposed) DumbService.isDumb(project) else null
}
companion object {
const val DEFAULT_ID = "third.party"
private val ourAllowedList = ActionsBuiltInAllowedlist.getInstance()
private val ourStats: MutableMap<AnActionEvent, Stats> = WeakHashMap()
/** @noinspection unused
*/
@JvmStatic
fun recordCustomActionInvoked(project: Project?, actionId: String?, event: InputEvent?, context: Class<*>) {
val recorded = if (StringUtil.isNotEmpty(actionId) && ourAllowedList.isCustomAllowedAction(actionId!!)) actionId
else DEFAULT_ID
ActionsEventLogGroup.CUSTOM_ACTION_INVOKED.log(project, recorded, FusInputEvent(event, null))
}
@JvmStatic
fun recordActionInvoked(project: Project?,
action: AnAction?,
event: AnActionEvent?,
customDataProvider: MutableList<EventPair<*>>.() -> Unit) {
record(ActionsEventLogGroup.ACTION_FINISHED, project, action, event, customDataProvider)
}
@JvmStatic
fun recordActionGroupExpanded(action: ActionGroup,
context: DataContext,
place: String,
submenu: Boolean,
durationMs: Long,
result: List<AnAction>?) {
val dataContext = getCachedDataContext(context)
val project = CommonDataKeys.PROJECT.getData(dataContext)
ActionsEventLogGroup.ACTION_GROUP_EXPANDED.log(project) {
val info = getPluginInfo(action.javaClass)
val size = result?.count { it !is Separator } ?: -1
val language = getInjectedOrFileLanguage(project, dataContext) ?: Language.ANY
addActionClass(this, action, info)
add(EventFields.PluginInfo.with(info))
add(EventFields.Language.with(language))
add(EventFields.ActionPlace.with(place))
add(ActionsEventLogGroup.IS_SUBMENU.with(submenu))
add(EventFields.DurationMs.with(durationMs))
add(EventFields.Size.with(size))
}
}
@JvmStatic
fun record(eventId: VarargEventId,
project: Project?,
action: AnAction?,
event: AnActionEvent?,
customDataProvider: MutableList<EventPair<*>>.() -> Unit) {
if (action == null) return
eventId.log(project) {
val info = getPluginInfo(action.javaClass)
add(EventFields.PluginInfoFromInstance.with(action))
if (event != null) {
if (action is ToggleAction) {
add(ActionsEventLogGroup.TOGGLE_ACTION.with(Toggleable.isSelected(event.presentation)))
}
addAll(actionEventData(event))
}
if (project != null && !project.isDisposed) {
add(ActionsEventLogGroup.DUMB.with(DumbService.isDumb(project)))
}
customDataProvider()
addActionClass(this, action, info)
}
if (eventId == ActionsEventLogGroup.ACTION_FINISHED) {
FeatureUsageTracker.getInstance().triggerFeatureUsedByAction(getActionId(action))
}
}
@JvmStatic
fun actionEventData(event: AnActionEvent): List<EventPair<*>> {
val data: MutableList<EventPair<*>> = ArrayList()
data.add(EventFields.InputEvent.with(from(event)))
val place = event.place
data.add(EventFields.ActionPlace.with(place))
data.add(ActionsEventLogGroup.CONTEXT_MENU.with(ActionPlaces.isPopupPlace(place)))
return data
}
@JvmStatic
fun addActionClass(data: MutableList<EventPair<*>>,
action: AnAction,
info: PluginInfo): String {
val actionClassName = if (info.isSafeToReport()) action.javaClass.name else DEFAULT_ID
var actionId = getActionId(info, action)
if (action is ActionWithDelegate<*>) {
val delegate = (action as ActionWithDelegate<*>).delegate
val delegateInfo = getPluginInfo(delegate.javaClass)
actionId = if (delegate is AnAction) {
getActionId(delegateInfo, delegate)
}
else {
if (delegateInfo.isSafeToReport()) delegate.javaClass.name else DEFAULT_ID
}
data.add(ActionsEventLogGroup.ACTION_CLASS.with(actionId))
data.add(ActionsEventLogGroup.ACTION_PARENT.with(actionClassName))
}
else {
data.add(ActionsEventLogGroup.ACTION_CLASS.with(actionClassName))
}
data.add(ActionsEventLogGroup.ACTION_ID.with(actionId))
return actionId
}
private fun getActionId(pluginInfo: PluginInfo, action: AnAction): String {
if (!pluginInfo.isSafeToReport()) {
return DEFAULT_ID
}
return getActionId(action)
}
private fun getActionId(action: AnAction): String {
var actionId = ActionManager.getInstance().getId(action)
if (actionId == null && action is ActionIdProvider) {
actionId = (action as ActionIdProvider).id
}
if (actionId != null && !canReportActionId(actionId)) {
return action.javaClass.name
}
if (actionId == null) {
actionId = ourAllowedList.getDynamicActionId(action)
}
return actionId ?: action.javaClass.name
}
@JvmStatic
fun canReportActionId(actionId: String): Boolean {
return ourAllowedList.isAllowedActionId(actionId)
}
/** @noinspection unused
*/
@JvmStatic
fun onActionLoadedFromXml(action: AnAction, actionId: String, plugin: IdeaPluginDescriptor?) {
ourAllowedList.addActionLoadedFromXml(actionId, plugin)
}
fun onActionsLoadedFromKeymapXml(keymap: Keymap, actionIds: Set<String?>) {
ourAllowedList.addActionsLoadedFromKeymapXml(keymap, actionIds)
}
/** @noinspection unused
*/
@JvmStatic
fun onBeforeActionInvoked(action: AnAction, event: AnActionEvent) {
val project = event.project
val context = getCachedDataContext(event.dataContext)
val stats = Stats(project, getFileLanguage(context), getInjectedOrFileLanguage(project, context))
ourStats[event] = stats
}
@JvmStatic
fun onAfterActionInvoked(action: AnAction, event: AnActionEvent, result: AnActionResult) {
val stats = ourStats.remove(event)
val project = stats?.projectRef?.get()
recordActionInvoked(project, action, event) {
val durationMillis = if (stats != null) TimeoutUtil.getDurationMillis(stats.start) else -1
if (stats != null) {
add(EventFields.StartTime.with(stats.startMs))
if (stats.isDumb != null) {
add(ActionsEventLogGroup.DUMB_START.with(stats.isDumb))
}
}
val reportedResult = toReportedResult(result)
add(ActionsEventLogGroup.RESULT.with(reportedResult))
val contextBefore = stats?.fileLanguage
val injectedContextBefore = stats?.injectedFileLanguage
addLanguageContextFields(project, event, contextBefore, injectedContextBefore, this)
if (action is FusAwareAction) {
val additionalUsageData = (action as FusAwareAction).getAdditionalUsageData(event)
add(ActionsEventLogGroup.ADDITIONAL.with(ObjectEventData(additionalUsageData)))
}
add(EventFields.DurationMs.with(roundDuration(durationMillis)))
}
}
private fun toReportedResult(result: AnActionResult): ObjectEventData {
if (result.isPerformed) {
return ObjectEventData(ActionsEventLogGroup.RESULT_TYPE.with("performed"))
}
if (result == AnActionResult.IGNORED) {
return ObjectEventData(ActionsEventLogGroup.RESULT_TYPE.with("ignored"))
}
val error = result.failureCause
return if (error != null) {
ObjectEventData(
ActionsEventLogGroup.RESULT_TYPE.with("failed"),
ActionsEventLogGroup.ERROR.with(error.javaClass)
)
}
else ObjectEventData(ActionsEventLogGroup.RESULT_TYPE.with("unknown"))
}
private fun addLanguageContextFields(project: Project?,
event: AnActionEvent,
contextBefore: Language?,
injectedContextBefore: Language?,
data: MutableList<EventPair<*>>) {
val dataContext = getCachedDataContext(event.dataContext)
val language = getFileLanguage(dataContext)
data.add(EventFields.CurrentFile.with(language ?: contextBefore))
val injectedLanguage = getInjectedOrFileLanguage(project, dataContext)
data.add(EventFields.Language.with(injectedLanguage ?: injectedContextBefore))
}
/**
* Computing fields from data context might be slow and cause freezes.
* To avoid it, we report only those fields which were already computed
* in [AnAction.update] or [AnAction.actionPerformed]
*/
private fun getCachedDataContext(dataContext: DataContext): DataContext {
return DataContext { dataId: String? -> Utils.getRawDataIfCached(dataContext, dataId!!) }
}
/**
* Returns language from [InjectedDataKeys.EDITOR], [InjectedDataKeys.PSI_FILE]
* or [CommonDataKeys.PSI_FILE] if there's no information about injected fragment
*/
private fun getInjectedOrFileLanguage(project: Project?, dataContext: DataContext): Language? {
val injected = getInjectedLanguage(dataContext, project)
return injected ?: getFileLanguage(dataContext)
}
private fun getInjectedLanguage(dataContext: DataContext, project: Project?): Language? {
val file = InjectedDataKeys.PSI_FILE.getData(dataContext)
if (file != null) {
return file.language
}
if (project != null) {
val editor = InjectedDataKeys.EDITOR.getData(dataContext)
if (editor != null && !project.isDisposed) {
val injectedFile = PsiDocumentManager.getInstance(project).getCachedPsiFile(editor.document)
if (injectedFile != null) {
return injectedFile.language
}
}
}
return null
}
/**
* Returns language from [CommonDataKeys.PSI_FILE]
*/
private fun getFileLanguage(dataContext: DataContext): Language? {
return CommonDataKeys.PSI_FILE.getData(dataContext)?.language
}
}
} | apache-2.0 | f6527eee2db23834abffc0649e3360b7 | 39.809798 | 120 | 0.679379 | 4.796748 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/externalCodeProcessing/ExternalUsagesFixer.kt | 6 | 3874 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.externalCodeProcessing
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.j2k.AccessorKind
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
internal class ExternalUsagesFixer(private val usages: List<JKMemberInfoWithUsages>) {
private val conversions = mutableListOf<JKExternalConversion>()
fun fix() {
usages.forEach { it.fix() }
conversions.sort()
conversions.forEach(JKExternalConversion::apply)
}
private fun JKMemberInfoWithUsages.fix() {
when (member) {
is JKFieldDataFromJava -> member.fix(javaUsages, kotlinUsages)
is JKMethodData -> member.fix(javaUsages, kotlinUsages)
}
}
private fun JKFieldDataFromJava.fix(javaUsages: List<PsiElement>, kotlinUsages: List<KtElement>) {
run {
val ktProperty = kotlinElement ?: return@run
when {
javaUsages.isNotEmpty() && ktProperty.isSimpleProperty() ->
ktProperty.addAnnotationIfThereAreNoJvmOnes(JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME)
javaUsages.isNotEmpty() && isStatic && !ktProperty.hasModifier(KtTokens.CONST_KEYWORD) ->
ktProperty.addAnnotationIfThereAreNoJvmOnes(JVM_STATIC_FQ_NAME)
}
}
if (wasRenamed) {
javaUsages.forEach { usage ->
conversions += PropertyRenamedJavaExternalUsageConversion(name, usage)
}
kotlinUsages.forEach { usage ->
conversions += PropertyRenamedKotlinExternalUsageConversion(name, usage)
}
}
}
private fun JKMethodData.fix(javaUsages: List<PsiElement>, kotlinUsages: List<KtElement>) {
usedAsAccessorOfProperty?.let { property ->
val accessorKind =
if (javaElement.name.startsWith("set")) AccessorKind.SETTER
else AccessorKind.GETTER
kotlinUsages.forEach { usage ->
conversions += AccessorToPropertyKotlinExternalConversion(property.name, accessorKind, usage)
}
}
if (javaUsages.isNotEmpty() && isStatic) {
when (val accessorOf = usedAsAccessorOfProperty) {
null -> this
else -> accessorOf
}.kotlinElement?.addAnnotationIfThereAreNoJvmOnes(JVM_STATIC_FQ_NAME)
}
}
private fun KtProperty.isSimpleProperty() =
getter == null
&& setter == null
&& !hasModifier(KtTokens.CONST_KEYWORD)
private fun KtDeclaration.addAnnotationIfThereAreNoJvmOnes(fqName: FqName) {
// we don't want to resolve here and as we are working with fqNames, just by-text comparing is OK
if (annotationEntries.any { entry ->
USED_JVM_ANNOTATIONS.any { jvmAnnotation ->
entry.typeReference?.textMatches(jvmAnnotation.asString()) == true
}
}
) return
addAnnotationEntry(KtPsiFactory(this).createAnnotationEntry("@${fqName.asString()}"))
}
internal data class JKMemberInfoWithUsages(
val member: JKMemberData<*>,
val javaUsages: List<PsiElement>,
val kotlinUsages: List<KtElement>
)
companion object {
private val JVM_STATIC_FQ_NAME = FqName("kotlin.jvm.JvmStatic")
val USED_JVM_ANNOTATIONS = listOf(JVM_STATIC_FQ_NAME, JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME)
}
}
| apache-2.0 | 6110d59645467c0314c283f810d0f634 | 38.530612 | 158 | 0.652814 | 4.747549 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/account/AccountAdapter.kt | 1 | 3825 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.account
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.ViewGroup
import com.daimajia.swipe.SwipeLayout
import com.daimajia.swipe.implments.SwipeItemRecyclerMangerImpl
import com.daimajia.swipe.interfaces.SwipeAdapterInterface
import com.daimajia.swipe.interfaces.SwipeItemMangerInterface
import com.daimajia.swipe.util.Attributes
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.ui.SmoothCheckBox
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.util.QuickAdapter
import kotlinx.android.synthetic.main.account_list_item.view.*
/**
* Created by sinyuk on 2018/1/31.
*
*/
class AccountAdapter(var uniqueId: String) : QuickAdapter<Player, AccountViewHolder>(null), SwipeItemMangerInterface, SwipeAdapterInterface {
private var mItemManger = SwipeItemRecyclerMangerImpl(this)
override fun openItem(position: Int) {
mItemManger.openItem(position)
}
override fun closeItem(position: Int) {
mItemManger.closeItem(position)
}
override fun closeAllExcept(layout: SwipeLayout) {
mItemManger.closeAllExcept(layout)
}
override fun closeAllItems() {
mItemManger.closeAllItems()
}
override fun getOpenItems(): List<Int> {
return mItemManger.openItems
}
override fun getOpenLayouts(): List<SwipeLayout> {
return mItemManger.openLayouts
}
override fun removeShownLayouts(layout: SwipeLayout) {
mItemManger.removeShownLayouts(layout)
}
override fun isOpen(position: Int): Boolean {
return mItemManger.isOpen(position)
}
override fun getMode(): Attributes.Mode {
return mItemManger.mode
}
override fun setMode(mode: Attributes.Mode) {
mItemManger.mode = mode
}
override fun getSwipeLayoutResourceId(position: Int): Int = R.id.swipeLayout
override fun onCreateDefViewHolder(parent: ViewGroup?, viewType: Int) = AccountViewHolder.create(parent!!, uniqueId)
var checked = RecyclerView.NO_POSITION
override fun convert(helper: AccountViewHolder, item: Player) {
helper.addOnClickListener(R.id.deleteButton)
if (item.uniqueId == uniqueId) {
checked = helper.adapterPosition
helper.itemView.swipeLayout.isSwipeEnabled = false
} else {
helper.itemView.swipeLayout.isSwipeEnabled = true
}
helper.itemView.checkbox.setChecked(uniqueId == item.uniqueId, false)
helper.itemView.checkbox.setOnClickListener { v ->
v as SmoothCheckBox
if (!v.isChecked) {
v.setChecked(true, true)
uniqueId = item.uniqueId
helper.itemView.swipeLayout.isSwipeEnabled = false
Log.i("onSwitch", "from $checked to ${helper.adapterPosition}")
if (checked != RecyclerView.NO_POSITION) notifyItemChanged(checked)
checked = helper.adapterPosition
listener?.onSwitch(item.uniqueId)
}
}
helper.bind(item)
}
var listener: AccountListView.OnAccountListListener? = null
} | mit | 2c987d4c256cce1d714be423bfe2ef3e | 31.700855 | 141 | 0.692549 | 4.371429 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/PopupActions.kt | 3 | 12274 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.codeInsight.hints
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager
import com.intellij.codeInsight.hints.HintInfo.MethodInfo
import com.intellij.codeInsight.hints.settings.Diff
import com.intellij.codeInsight.hints.settings.ParameterNameHintsConfigurable
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.injected.editor.EditorWindow
import com.intellij.lang.Language
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.util.PsiTreeUtil
class ShowSettingsWithAddedPattern : AnAction() {
init {
templatePresentation.description = CodeInsightBundle.message("inlay.hints.show.settings.description")
templatePresentation.text = CodeInsightBundle.message("inlay.hints.show.settings", "_")
}
override fun update(e: AnActionEvent) {
val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return
val offset = editor.caretModel.offset
val info = getHintInfoFromProvider(offset, file, editor) ?: return
val text = when (info) {
is HintInfo.OptionInfo -> "Show Hints Settings..."
is HintInfo.MethodInfo -> CodeInsightBundle.message("inlay.hints.show.settings", info.getMethodName())
}
e.presentation.setText(text, false)
}
override fun actionPerformed(e: AnActionEvent) {
val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return
val fileLanguage = file.language.baseLanguage ?: file.language
InlayParameterHintsExtension.forLanguage(fileLanguage) ?: return
val offset = editor.caretModel.offset
val info = getHintInfoFromProvider(offset, file, editor) ?: return
val newPreselectedPattern = when (info) {
is HintInfo.OptionInfo -> null
is HintInfo.MethodInfo -> info.toPattern()
}
val selectedLanguage = (info as? HintInfo.MethodInfo)?.language ?: fileLanguage
val dialog = ParameterNameHintsConfigurable(selectedLanguage, newPreselectedPattern)
dialog.show()
}
}
class BlacklistCurrentMethodIntention : IntentionAction, LowPriorityAction {
companion object {
private val presentableText = CodeInsightBundle.message("inlay.hints.blacklist.method")
private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name")
}
override fun getText(): String = presentableText
override fun getFamilyName(): String = presentableFamilyName
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean {
val language = file.language
val hintsProvider = InlayParameterHintsExtension.forLanguage(language) ?: return false
return hintsProvider.isBlackListSupported
&& hasEditorParameterHintAtOffset(editor, file)
&& isMethodHintAtOffset(editor, file)
}
private fun isMethodHintAtOffset(editor: Editor, file: PsiFile): Boolean {
val offset = editor.caretModel.offset
return getHintInfoFromProvider(offset, file, editor) is MethodInfo
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val info = getHintInfoFromProvider(offset, file, editor) as? MethodInfo ?: return
val language = info.language ?: file.language
ParameterNameHintsSettings.getInstance().addIgnorePattern(language, info.toPattern())
refreshAllOpenEditors()
showHint(project, language, info)
}
private fun showHint(project: Project, language: Language, info: MethodInfo) {
val methodName = info.getMethodName()
val listener = NotificationListener { notification, event ->
when (event.description) {
"settings" -> showSettings(language)
"undo" -> undo(language, info)
}
notification.expire()
}
val notification = Notification("Parameter Name Hints", "Method \"$methodName\" added to blacklist",
"<html><a href='settings'>Show Parameter Hints Settings</a> or <a href='undo'>Undo</a></html>",
NotificationType.INFORMATION, listener)
notification.notify(project)
}
private fun showSettings(language: Language) {
val dialog = ParameterNameHintsConfigurable(language, null)
dialog.show()
}
private fun undo(language: Language, info: MethodInfo) {
val settings = ParameterNameHintsSettings.getInstance()
val diff = settings.getBlackListDiff(language)
val updated = diff.added.toMutableSet().apply {
remove(info.toPattern())
}
settings.setBlackListDiff(language, Diff(updated, diff.removed))
refreshAllOpenEditors()
}
override fun startInWriteAction() = false
}
class DisableCustomHintsOption: IntentionAction, LowPriorityAction {
companion object {
private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name")
}
private var lastOptionName = ""
override fun getText(): String = getIntentionText()
private fun getIntentionText(): String {
if (lastOptionName.startsWith("show", ignoreCase = true)) {
return "Do not ${lastOptionName.toLowerCase()}"
}
return CodeInsightBundle.message("inlay.hints.disable.custom.option", lastOptionName)
}
override fun getFamilyName(): String = presentableFamilyName
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean {
InlayParameterHintsExtension.forLanguage(file.language) ?: return false
if (!hasEditorParameterHintAtOffset(editor, file)) return false
val option = getOptionHintAtOffset(editor, file) ?: return false
lastOptionName = option.optionName
return true
}
private fun getOptionHintAtOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? {
val offset = editor.caretModel.offset
return getHintInfoFromProvider(offset, file, editor) as? HintInfo.OptionInfo
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val option = getOptionHintAtOffset(editor, file) ?: return
option.disable()
refreshAllOpenEditors()
}
override fun startInWriteAction() = false
}
class EnableCustomHintsOption: IntentionAction, HighPriorityAction {
companion object {
private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name")
}
private var lastOptionName = ""
override fun getText(): String {
if (lastOptionName.startsWith("show", ignoreCase = true)) {
return lastOptionName.capitalizeFirstLetter()
}
return CodeInsightBundle.message("inlay.hints.enable.custom.option", lastOptionName)
}
override fun getFamilyName(): String = presentableFamilyName
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean {
if (!EditorSettingsExternalizable.getInstance().isShowParameterNameHints) return false
if (editor !is EditorImpl) return false
InlayParameterHintsExtension.forLanguage(file.language) ?: return false
val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return false
lastOptionName = option.optionName
return true
}
private fun getDisabledOptionInfoAtCaretOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? {
val offset = editor.caretModel.offset
val element = file.findElementAt(offset) ?: return null
val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null
val target = PsiTreeUtil.findFirstParent(element, { provider.hasDisabledOptionHintInfo(it) }) ?: return null
return provider.getHintInfo(target) as? HintInfo.OptionInfo
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return
option.enable()
refreshAllOpenEditors()
}
override fun startInWriteAction() = false
}
private fun InlayParameterHintsProvider.hasDisabledOptionHintInfo(element: PsiElement): Boolean {
val info = getHintInfo(element)
return info is HintInfo.OptionInfo && !info.isOptionEnabled()
}
class ToggleInlineHintsAction : AnAction() {
companion object {
private val disableText = CodeInsightBundle.message("inlay.hints.disable.action.text").capitalize()
private val enableText = CodeInsightBundle.message("inlay.hints.enable.action.text").capitalize()
}
override fun update(e: AnActionEvent) {
if (!InlayParameterHintsExtension.hasAnyExtensions()) {
e.presentation.isEnabledAndVisible = false
return
}
val isHintsShownNow = EditorSettingsExternalizable.getInstance().isShowParameterNameHints
e.presentation.text = if (isHintsShownNow) disableText else enableText
e.presentation.isEnabledAndVisible = true
}
override fun actionPerformed(e: AnActionEvent) {
val settings = EditorSettingsExternalizable.getInstance()
val before = settings.isShowParameterNameHints
settings.isShowParameterNameHints = !before
refreshAllOpenEditors()
}
}
private fun hasEditorParameterHintAtOffset(editor: Editor, file: PsiFile): Boolean {
if (editor is EditorWindow) return false
val offset = editor.caretModel.offset
val element = file.findElementAt(offset)
val startOffset = element?.textRange?.startOffset ?: offset
val endOffset = element?.textRange?.endOffset ?: offset
return editor.inlayModel
.getInlineElementsInRange(startOffset, endOffset)
.find { ParameterHintsPresentationManager.getInstance().isParameterHint(it) } != null
}
private fun refreshAllOpenEditors() {
ParameterHintsPassFactory.forceHintsUpdateOnNextPass();
ProjectManager.getInstance().openProjects.forEach {
val psiManager = PsiManager.getInstance(it)
val daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(it)
val fileEditorManager = FileEditorManager.getInstance(it)
fileEditorManager.selectedFiles.forEach {
psiManager.findFile(it)?.let { daemonCodeAnalyzer.restart(it) }
}
}
}
private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor): HintInfo? {
val element = file.findElementAt(offset) ?: return null
val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null
val isHintOwnedByElement: (PsiElement) -> Boolean = { e -> provider.getHintInfo(e) != null && e.isOwnsInlayInEditor(editor) }
val method = PsiTreeUtil.findFirstParent(element, isHintOwnedByElement) ?: return null
return provider.getHintInfo(method)
}
fun PsiElement.isOwnsInlayInEditor(editor: Editor): Boolean {
if (textRange == null) return false
val start = if (textRange.isEmpty) textRange.startOffset else textRange.startOffset + 1
return !editor.inlayModel.getInlineElementsInRange(start, textRange.endOffset).isEmpty()
}
fun MethodInfo.toPattern() = this.fullyQualifiedName + '(' + this.paramNames.joinToString(",") + ')'
private fun String.capitalize() = StringUtil.capitalizeWords(this, true)
private fun String.capitalizeFirstLetter() = StringUtil.capitalize(this) | apache-2.0 | 2f7c117a4a9f0c1d03cc9159f9fff539 | 36.31003 | 140 | 0.758107 | 4.975274 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickTest.kt | 3 | 3019 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.cherrypick
import com.intellij.vcs.log.impl.HashImpl
import git4idea.test.*
abstract class GitCherryPickTest : GitSingleRepoTest() {
protected fun `check dirty tree conflicting with commit`() {
val file = file("c.txt")
file.create("initial\n").addCommit("initial")
branch("feature")
val commit = file.append("master\n").addCommit("fix #1").hash()
checkout("feature")
file.append("local\n")
cherryPick(commit)
assertErrorNotification("Cherry-pick Failed", """
${shortHash(commit)} fix #1
Your local changes would be overwritten by cherry-pick.
Commit your changes or stash them to proceed.""")
}
protected fun `check untracked file conflicting with commit`() {
branch("feature")
val file = file("untracked.txt")
val commit = file.create("master\n").addCommit("fix #1").hash()
checkout("feature")
file.create("untracked\n")
cherryPick(commit)
assertErrorNotification("Untracked Files Prevent Cherry-pick", """
Move or commit them before cherry-pick""")
}
protected fun `check conflict with cherry-picked commit should show merge dialog`() {
val initial = tac("c.txt", "base\n")
val commit = repo.appendAndCommit("c.txt", "master")
repo.checkoutNew("feature", initial)
repo.appendAndCommit("c.txt", "feature")
`do nothing on merge`()
cherryPick(commit)
`assert merge dialog was shown`()
}
protected fun `check resolve conflicts and commit`() {
val commit = repo.prepareConflict()
`mark as resolved on merge`()
vcsHelper.onCommit { msg ->
git("commit -am '$msg'")
true
}
cherryPick(commit)
`assert commit dialog was shown`()
assertLastMessage("""
on_master
(cherry picked from commit ${shortHash(commit)})""".trimIndent())
repo.assertCommitted {
modified("c.txt")
}
assertSuccessfulNotification("Cherry-pick successful",
"${shortHash(commit)} on_master")
changeListManager.assertOnlyDefaultChangelist()
}
protected fun cherryPick(hashes: List<String>) {
updateChangeListManager()
val details = readDetails(hashes)
GitCherryPicker(project, git).cherryPick(details)
}
protected fun cherryPick(vararg hashes: String) {
cherryPick(hashes.asList())
}
protected fun shortHash(hash: String) = HashImpl.build(hash).toShortString()
}
| apache-2.0 | 171b62cb91d4cba940bcf040654991dc | 29.494949 | 87 | 0.683339 | 4.319027 | false | false | false | false |
Heapy/komodo | komodo-http/src/main/kotlin/io/heapy/komodo/http/HttpClient.kt | 1 | 3338 | package io.heapy.komodo.http
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.concurrent.FutureCallback
import org.apache.http.impl.nio.client.HttpAsyncClients
import org.apache.http.nio.client.HttpAsyncClient
/**
* Coroutines adapter for [HttpAsyncClient.execute].
*/
suspend fun HttpAsyncClient.execute(request: HttpUriRequest): HttpResponse {
return suspendCancellableCoroutine { cont: CancellableContinuation<HttpResponse> ->
val callback = object : FutureCallback<HttpResponse> {
override fun completed(result: HttpResponse) {
println("completed ${request.uri}")
cont.resumeWith(Result.success(result))
}
override fun cancelled() {
println("cancelled ${request.uri}")
if (cont.isCancelled) {
println("coroutine cancelled ${request.uri}")
return
}
cont.resumeWith(Result.failure(FutureCallbackCanceledException(request)))
}
override fun failed(ex: Exception) {
println("Failed ${request.uri}")
cont.resumeWith(Result.failure(ex))
}
}
val future = this.execute(request, callback)
GlobalScope.launch {
println("cancel launch ${request.uri}")
future.cancel(false)
}
cont.invokeOnCancellation {
println("cancel future ${request.uri}")
future.cancel(false)
}
Unit
}
}
@InternalCoroutinesApi
suspend fun main(args: Array<String>) {
val asyncClient = HttpAsyncClients.custom()
.setMaxConnPerRoute(1000)
.setMaxConnTotal(1000)
.build()
try {
asyncClient.start()
withTimeoutOrNull(90) {
val list = mutableListOf<Job>()
(1..10).forEach {
list += launch {
println(">> Making request")
println(asyncClient.execute(HttpGet("https://heapy.io/?q=$it")).body().length)
println(">> Request done")
}
}
list.forEach { it.join() }
list.forEach {
if (it.isCancelled) {
println(it.getCancellationException().message)
}
}
}
} finally {
println(">> Finally")
println(">> Close")
asyncClient.close()
println(">> Closed")
}
}
class FutureCallbackCanceledException(
private val request: HttpUriRequest
) : CancellationException() {
override val message: String
get() = "${request.method} request to ${request.uri} is cancelled."
}
/**
* Helper method for reading response body.
*/
fun HttpResponse.body(): String {
return entity.content.bufferedReader(Charsets.UTF_8).use { it.readText() }
}
| lgpl-3.0 | ad6415add91a23c88adf4620a51d30dd | 28.803571 | 98 | 0.615638 | 4.959881 | false | false | false | false |
Softmotions/ncms | ncms-engine/ncms-engine-core/src/main/java/com/softmotions/ncms/mtt/http/MttRequestParametersAction.kt | 1 | 1497 | package com.softmotions.ncms.mtt.http
import com.google.inject.Singleton
import com.softmotions.commons.cont.KVOptions
import org.slf4j.LoggerFactory
import javax.annotation.concurrent.ThreadSafe
import javax.servlet.http.HttpServletResponse
/**
* Set request parameters action handler
*
* @author Adamansky Anton ([email protected])
*/
@Singleton
@ThreadSafe
class MttRequestParametersAction : MttActionHandler {
private val log = LoggerFactory.getLogger(javaClass)
override val type: String = "parameters"
override fun execute(ctx: MttActionHandlerContext,
rmc: MttRequestModificationContext,
resp: HttpServletResponse): Boolean {
val overwrite = ctx.spec.path("overwrite").asBoolean()
if (!ctx.containsKey("pmap")) {
synchronized(this) {
if (ctx.containsKey("pmap")) return@synchronized
// {"overwrite":true,"params":"foo=bar"}
ctx["pmap"] = KVOptions(ctx.spec.path("params").asText(""))
}
}
@Suppress("UNCHECKED_CAST")
(ctx["pmap"] as Map<String, String>).forEach {
val opv = rmc.req.getParameter(it.key)
if (overwrite || opv == null) {
if (log.isDebugEnabled) {
log.debug("Setup request parameter ${it.key}=${it.value}")
}
rmc.params.put(it.key, it.value)
}
}
return false
}
} | apache-2.0 | 86b7d751095fa8a12e60c3527642ae00 | 31.565217 | 78 | 0.605878 | 4.495495 | false | false | false | false |
fgsguedes/adventofcode | 2015/src/main/kotlin/day5/naughty_words.kt | 1 | 791 | package day5
import fromMultipleLineInput
import kotlin.text.Regex
fun String.isNice(): Boolean {
val bannedWords = arrayOf(
Regex.fromLiteral("ab"),
Regex.fromLiteral("cd"),
Regex.fromLiteral("pq"),
Regex.fromLiteral("xy")
)
val threeVowelsRegex = Regex("[aeiou]")
val atLeastThreeVowels = threeVowelsRegex.findAll(this).count() >= 3
val twiceInARow = Regex("(\\w)\\1").findAll(this).count() > 0
val containsBannedWords = bannedWords.any { it.findAll(this).count() > 0 }
return atLeastThreeVowels && twiceInARow && !containsBannedWords
}
fun main(args: Array<String>) {
val naughtyWords = fromMultipleLineInput(2015, 5, "naughty_words_input.txt") { fileContent ->
fileContent.filter(String::isNice).count()
}
println(naughtyWords)
}
| gpl-2.0 | 8ede9fd2dc84ca1a79cff1c6f1b3c0f5 | 24.516129 | 95 | 0.696587 | 3.365957 | false | false | false | false |
amigocloud/amigoSurvey | Android/AmigoSurvey/app/src/main/java/com/amigocloud/amigosurvey/toothpick/provider/HttpClientProvider.kt | 1 | 2109 | package com.amigocloud.amigosurvey.toothpick.provider
import android.net.ConnectivityManager
import android.util.Log
import com.amigocloud.amigosurvey.BuildConfig
import com.amigocloud.amigosurvey.repository.AmigoAuthenticator
import com.amigocloud.amigosurvey.repository.CacheInterceptor
import com.amigocloud.amigosurvey.repository.OfflineCacheInterceptor
import com.amigocloud.amigosurvey.toothpick.CacheDir
import com.facebook.stetho.okhttp3.StethoInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import toothpick.ProvidesSingletonInScope
import java.io.File
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
@ProvidesSingletonInScope
class HttpClientProvider @Inject constructor(private val authenticator: AmigoAuthenticator,
@CacheDir val cacheDir: File,
private val connectivityManager: ConnectivityManager) : Provider<OkHttpClient> {
val TAG = "HttpClientProvider"
val cacheInterceptor = CacheInterceptor(connectivityManager)
val offlineCacheInterceptor = OfflineCacheInterceptor(connectivityManager)
val logging = HttpLoggingInterceptor()
override fun get(): OkHttpClient = OkHttpClient.Builder()
.authenticator(authenticator)
.addInterceptor(authenticator)
.addInterceptor(offlineCacheInterceptor)
.addNetworkInterceptor(cacheInterceptor)
.cache(provideCache())
.apply { if (BuildConfig.DEBUG) addNetworkInterceptor(StethoInterceptor()) }
// .addInterceptor(logging)
.build()
private fun provideCache(): Cache? {
logging.level = HttpLoggingInterceptor.Level.BASIC
var cache: Cache? = null
try {
cache = Cache( File(cacheDir.absoluteFile, "http-cache"),
(1000 * 1024 * 1024).toLong()) // 1000 MB
} catch (e: Exception) {
Log.e(TAG, "Could not create Cache!")
}
return cache
}
}
| gpl-3.0 | 881fe20f36d8ba9ba3108177b52a2990 | 34.745763 | 125 | 0.710289 | 5.057554 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.