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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mklimek/tab-bar-view | library/src/main/kotlin/com.mklimek.library/TabBarController.kt | 1 | 2914 | package com.mklimek.library
import android.content.Context
import android.graphics.Color
import android.graphics.LightingColorFilter
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.widget.TextView
class TabBarController(context: Context, val tabs: List<Tab>, val tabBarView: TabBarView) {
var tintSelectedColor = 0
var tintSelectedEnabled = false
var currentItem = 0
set(value) {
field = value
tabs.filter { tabs.indexOf(it) != value }.forEach {
val child = tabBarView.getChildAt(tabs.indexOf(it))
child.background = it.background
if(tintSelectedEnabled){
val tv = child as TextView
tv.setTextColor(Color.BLACK)
it.iconId?.colorFilter = null
}
}
val selectedTab = tabs.first { tabs.indexOf(it) == value }
val selectedChild = tabBarView.getChildAt(tabs.indexOf(selectedTab))
selectedChild.background = selectedTab.backgroundSelected
if(tintSelectedEnabled){
val tv = selectedChild as TextView
tv.setTextColor(tintSelectedColor)
selectedTab.iconId?.colorFilter = LightingColorFilter(Color.BLACK, tintSelectedColor)
}
listener?.pageHasBeenChanged(value)
}
private var listener: TabBarListener? = null
init{
val inflater = LayoutInflater.from(context)
for(tab in tabs){
val textView = inflater.inflate(R.layout.bottom_tab_bar_item, tabBarView, false) as TextView
textView.text = tab.title
textView.setTextColor(Color.WHITE)
textView.background = tab.background
textView.setCompoundDrawablesWithIntrinsicBounds(null, tab.iconId, null, null)
textView.setOnClickListener { currentItem = tabs.indexOf(tab) }
tabBarView.addView(textView)
}
}
fun getTabsAsTextViews(): List<TextView>{
var children = mutableListOf<TextView>()
tabs.forEach {
children.add(tabBarView.getChildAt(tabs.indexOf(it)) as TextView)
}
return children
}
fun setListener(listener: TabBarListener){
this.listener = listener
}
object TabBuilder{
private var tabs = mutableListOf<Tab>()
fun addTab(title: String, iconId: Drawable?, backgroundId: Drawable?, backgroundSelectedId: Drawable?): TabBuilder{
tabs.add(Tab(title, iconId, backgroundId, backgroundSelectedId))
return this
}
fun build(): List<Tab>{
val result = tabs.toList()
tabs.clear()
return result
}
}
class Tab(val title: String, val iconId: Drawable?, val background: Drawable?, val backgroundSelected: Drawable?){
}
}
| apache-2.0 | 0bfeab965d50930460c92cec074f74cd | 32.883721 | 123 | 0.625944 | 4.856667 | false | false | false | false |
teobaranga/T-Tasks | t-tasks/src/main/java/com/teo/ttasks/TasksAdapter.kt | 1 | 7382 | package com.teo.ttasks
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.teo.ttasks.data.model.Task
import com.teo.ttasks.ui.views.TaskDateView
import com.teo.ttasks.util.DateUtils
import org.threeten.bp.ZonedDateTime
const val VIEW_TYPE_TOP = 0
const val VIEW_TYPE_MIDDLE = 1
const val VIEW_TYPE_BOTTOM = 2
class TasksAdapter(
var activeTasks: List<Task> = emptyList(),
var completedTasks: List<Task> = emptyList()
) : RecyclerView.Adapter<TasksAdapter.ViewHolder>() {
companion object {
private val currentYear by lazy { ZonedDateTime.now().year }
}
interface TaskClickListener {
fun onTaskClicked(task: Task)
}
enum class DateType(val accessFunction: Task.() -> ZonedDateTime?) {
COMPLETED({ completedDate }),
DUE({ dueDate });
}
abstract class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
abstract fun bind(position: Int)
}
inner class TopViewHolder(itemView: View) : ViewHolder(itemView) {
val title: TextView = itemView.findViewById(R.id.section_title)
val completed: String = itemView.context.getString(R.string.task_section_completed)
val active: String = itemView.context.getString(R.string.task_section_active)
override fun bind(position: Int) {
if (activeTasks.isEmpty() || position != 0) {
title.text = completed
title.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_done_24dp, 0, 0, 0)
} else {
title.text = active
title.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_whatshot_24dp, 0, 0, 0)
}
}
}
inner class MiddleViewHolder(itemView: View) : ViewHolder(itemView), View.OnClickListener {
private val dayView: TaskDateView = itemView.findViewById(R.id.task_date)
private val monthView: TextView = itemView.findViewById(R.id.month)
private val title: TextView = itemView.findViewById(R.id.task_title)
private val description: TextView = itemView.findViewById(R.id.task_description)
private val reminder: TextView = itemView.findViewById(R.id.reminder)
private val taskBodyLayout: View = itemView.findViewById(R.id.layout_task_body)
private lateinit var task: Task
init {
taskBodyLayout.setOnClickListener(this)
}
override fun bind(position: Int) {
val (task, prevTask, dateType) = when {
position == 0 -> throw IllegalArgumentException("Not supposed to be 0 and MIDDLE")
position <= activeTasks.size -> Triple(
activeTasks[position - 1],
activeTasks.getOrNull(position - 2),
DateType.DUE
)
else -> Triple(
completedTasks[position - activeTasks.size - 3],
completedTasks.getOrNull(position - activeTasks.size - 4),
DateType.COMPLETED
)
}
this.task = task
val getSortDate: Task.() -> ZonedDateTime? = dateType.accessFunction
val taskSortDate = task.getSortDate()
val prevTaskSortDate = prevTask?.getSortDate()
with(dayView) {
val showDay = prevTaskSortDate?.dayOfMonth != taskSortDate?.dayOfMonth
if (showDay) {
date = taskSortDate
visibility = View.VISIBLE
} else {
date = null
visibility = View.GONE
}
}
with(monthView) {
val showMonth = prevTaskSortDate?.month != taskSortDate?.month
if (showMonth && taskSortDate != null) {
text = when (currentYear) {
taskSortDate.year -> taskSortDate.format(DateUtils.formatterMonth)
else -> taskSortDate.format(DateUtils.formatterMonthYear)
}
visibility = View.VISIBLE
} else {
visibility = View.GONE
}
}
title.text = task.title
if (task.notes.isNullOrBlank()) {
description.visibility = View.GONE
} else {
description.text = task.notes
description.visibility = View.VISIBLE
}
if (task.reminderDate == null) {
reminder.visibility = View.GONE
} else {
reminder.text = task.reminderDate!!.format(DateUtils.formatterTime)
reminder.visibility = View.VISIBLE
}
}
override fun onClick(v: View?) {
val adapterPosition = adapterPosition
taskClickListener?.let {
if (adapterPosition != RecyclerView.NO_POSITION) {
it.onTaskClicked(task)
}
}
}
}
inner class BottomViewHolder(itemView: View) : ViewHolder(itemView) {
override fun bind(position: Int) {
// Nothing to do
}
}
var taskClickListener: TaskClickListener? = null
override fun getItemViewType(position: Int): Int {
if (activeTasks.isEmpty() && completedTasks.isEmpty()) {
return VIEW_TYPE_MIDDLE
}
if (position == 0) {
return VIEW_TYPE_TOP
}
if (position == itemCount - 1) {
return VIEW_TYPE_BOTTOM
}
if (activeTasks.isEmpty() || completedTasks.isEmpty()) {
return VIEW_TYPE_MIDDLE
}
if (position == activeTasks.size + 1) {
return VIEW_TYPE_BOTTOM
}
if (position == activeTasks.size + 2) {
return VIEW_TYPE_TOP
}
return VIEW_TYPE_MIDDLE
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
with(recyclerView.recycledViewPool) {
setMaxRecycledViews(VIEW_TYPE_TOP, 2)
setMaxRecycledViews(VIEW_TYPE_MIDDLE, 15)
setMaxRecycledViews(VIEW_TYPE_BOTTOM, 2)
}
}
override fun getItemCount(): Int {
return (if (activeTasks.isEmpty()) 0 else activeTasks.size + 2) +
(if (completedTasks.isEmpty()) 0 else completedTasks.size + 2)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return when (viewType) {
VIEW_TYPE_TOP ->
TopViewHolder(layoutInflater.inflate(R.layout.task_section_top, parent, false))
VIEW_TYPE_MIDDLE ->
MiddleViewHolder(layoutInflater.inflate(R.layout.task_section_middle, parent, false))
VIEW_TYPE_BOTTOM ->
BottomViewHolder(layoutInflater.inflate(R.layout.task_section_bottom, parent, false))
else -> throw IllegalArgumentException("Unsupported viewType: $viewType")
}
}
}
| apache-2.0 | 4708f5cddee2f8a93ce4647f02d922f5 | 34.152381 | 107 | 0.588729 | 4.901726 | false | false | false | false |
JetBrains-Research/big | src/main/kotlin/org/jetbrains/bio/RomBuffer.kt | 2 | 6148 | package org.jetbrains.bio
import com.google.common.primitives.Bytes
import org.iq80.snappy.Snappy
import org.jetbrains.bio.big.RTreeIndex
import java.io.Closeable
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.zip.Inflater
/** A read-only buffer. */
abstract class RomBuffer : Closeable {
abstract var position: Long
abstract val order: ByteOrder
abstract val maxLength: Long
open var limit: Long = -1
set(value) {
check(value <= maxLength) {
"Limit $value is greater than buffer length $maxLength"
}
field = if (value == -1L) maxLength else value
}
init {
@Suppress("LeakingThis")
require(maxLength >= 0) {
"Buffer length is $maxLength, maybe associated stream failed to open."
}
}
/**
* Returns a new buffer sharing the data with its parent.
*
* @position:
* @see ByteBuffer.duplicate for details.
*/
abstract fun duplicate(position: Long, limit: Long): RomBuffer
fun checkHeader(leMagic: Int) {
val magic = readInt()
check(magic == leMagic) {
val bigMagic = java.lang.Integer.reverseBytes(leMagic)
"Unexpected header magic: Actual $magic doesn't match expected LE=$leMagic (BE=$bigMagic)"
}
}
abstract fun readInts(size: Int): IntArray
abstract fun readFloats(size: Int): FloatArray
abstract fun readBytes(size: Int): ByteArray
abstract fun readByte(): Byte
fun readUnsignedByte() = java.lang.Byte.toUnsignedInt(readByte())
abstract fun readShort(): Short
fun readUnsignedShort() = java.lang.Short.toUnsignedInt(readShort())
abstract fun readInt(): Int
abstract fun readLong(): Long
abstract fun readFloat(): Float
abstract fun readDouble(): Double
abstract fun readCString(): String
protected fun doReadCString(): String {
val sb = StringBuilder()
do {
val ch = readByte()
if (ch == 0.toByte()) {
break
}
sb.append(ch.toChar())
} while (true)
return sb.toString()
}
// Real buffer often is limited by current block size, so compare with 'limit', not eof or real input size
fun hasRemaining() = position < limit
protected fun checkLimit() {
check(position <= limit) { "Buffer overflow: pos $position > limit $limit, max length: $maxLength" }
}
/**
* Executes a `block` on a fixed-size possibly compressed input.
*
* This of this method as a way to get buffered input locally.
* See for example [RTreeIndex.findOverlappingBlocks].
*/
internal fun <T> with(offset: Long, size: Long,
compression: CompressionType = CompressionType.NO_COMPRESSION,
uncompressBufSize: Int,
block: RomBuffer.() -> T): T = decompress(
offset, size, compression, uncompressBufSize
).use(block)
internal fun decompress(offset: Long, size: Long,
compression: CompressionType = CompressionType.NO_COMPRESSION,
uncompressBufSize: Int): RomBuffer {
return if (compression.absent) {
duplicate(offset, offset + size)
} else {
val compressedBuf = duplicate(offset, limit).use {
with(it) {
readBytes(com.google.common.primitives.Ints.checkedCast(size))
}
}
var uncompressedSize: Int
var uncompressedBuf: ByteArray
when (compression) {
CompressionType.DEFLATE -> {
uncompressedSize = 0
uncompressedBuf = ByteArray(when (uncompressBufSize) {
0 -> 2 * size.toInt() // e.g in TDF
else -> uncompressBufSize
})
val inflater = inf
inflater.reset()
inflater.setInput(compressedBuf)
val sizeInt = size.toInt()
var remaining = sizeInt
val maxUncompressedChunk = if (uncompressBufSize == 0) sizeInt else uncompressBufSize
while (remaining > 0) {
uncompressedBuf = Bytes.ensureCapacity(
uncompressedBuf,
uncompressedSize + maxUncompressedChunk,
maxUncompressedChunk / 2 // 1.5x
)
// start next chunk if smth remains
if (inflater.finished()) {
inflater.reset()
inflater.setInput(compressedBuf, sizeInt - remaining, remaining)
}
val actual = inflater.inflate(uncompressedBuf, uncompressedSize, maxUncompressedChunk)
remaining = inflater.remaining
uncompressedSize += actual
}
// Not obligatory, but let's left thread local variable in clean state
inflater.reset()
}
CompressionType.SNAPPY -> {
uncompressedSize = Snappy.getUncompressedLength(compressedBuf, 0)
uncompressedBuf = ByteArray(uncompressedSize)
Snappy.uncompress(compressedBuf, 0, compressedBuf.size,
uncompressedBuf, 0)
}
CompressionType.NO_COMPRESSION -> {
throw IllegalStateException("Unexpected compression: $compression")
}
}
val input = ByteBuffer.wrap(uncompressedBuf, 0, uncompressedSize)
BBRomBuffer(input.order(order))
}
}
companion object {
// This is important to keep lazy, otherwise the GC will be trashed
// by a zillion of pending finalizers.
private val inf by ThreadLocal.withInitial { Inflater() }
}
}
| mit | f05f528606b82f37ef9d81b18105fd09 | 34.333333 | 110 | 0.555953 | 5.304573 | false | false | false | false |
sebastiansokolowski/AuctionHunter---Allegro | server/src/main/kotlin/com/sebastiansokolowski/auctionhunter/entity/BlacklistUser.kt | 1 | 317 | package com.sebastiansokolowski.auctionhunter.entity
import javax.persistence.*
@Entity
@Table(name = "blacklist_user")
data class BlacklistUser(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0,
var username: String = "",
var regex: Boolean = false
) | apache-2.0 | 281133a4fa01fdd50ab12b35ed474e24 | 23.461538 | 59 | 0.671924 | 4.116883 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/ComposableAvatarView.kt | 1 | 1195 | package com.habitrpg.android.habitica.ui.views
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.viewinterop.AndroidView
import com.habitrpg.common.habitica.views.AvatarView
import com.habitrpg.shared.habitica.models.Avatar
object AvatarCircleShape : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline =
CircleShape.createOutline(size, 20f, 20f, 20f, 20f, layoutDirection)
}
@Composable
fun ComposableAvatarView(
avatar: Avatar?,
modifier: Modifier = Modifier
) {
AndroidView(
modifier = modifier, // Occupy the max size in the Compose UI tree
factory = { context ->
AvatarView(context)
},
update = { view ->
if (avatar != null) {
view.setAvatar(avatar)
}
}
)
} | gpl-3.0 | 1706c1676bf0e9b47bde18fdbdf981b5 | 28.9 | 76 | 0.705439 | 4.345455 | false | false | false | false |
robfletcher/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartStageHandlerTest.kt | 1 | 36972 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spinnaker.assertj.assertSoftly
import com.netflix.spinnaker.orca.DefaultStageResolver
import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.events.StageStarted
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionNotFoundException
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.CompleteStage
import com.netflix.spinnaker.orca.q.DummyTask
import com.netflix.spinnaker.orca.q.InvalidExecutionId
import com.netflix.spinnaker.orca.q.InvalidStageId
import com.netflix.spinnaker.orca.q.SkipStage
import com.netflix.spinnaker.orca.q.StageDefinitionBuildersProvider
import com.netflix.spinnaker.orca.q.StartStage
import com.netflix.spinnaker.orca.q.StartTask
import com.netflix.spinnaker.orca.q.buildBeforeStages
import com.netflix.spinnaker.orca.q.buildTasks
import com.netflix.spinnaker.orca.q.failPlanningStage
import com.netflix.spinnaker.orca.q.get
import com.netflix.spinnaker.orca.q.multiTaskStage
import com.netflix.spinnaker.orca.q.rollingPushStage
import com.netflix.spinnaker.orca.q.singleTaskStage
import com.netflix.spinnaker.orca.q.stageWithParallelBranches
import com.netflix.spinnaker.orca.q.stageWithSyntheticAfter
import com.netflix.spinnaker.orca.q.stageWithSyntheticAfterAndNoTasks
import com.netflix.spinnaker.orca.q.stageWithSyntheticBefore
import com.netflix.spinnaker.orca.q.webhookStage
import com.netflix.spinnaker.orca.q.zeroTaskStage
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.spek.and
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.anyOrNull
import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.doThrow
import com.nhaarman.mockito_kotlin.isA
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import java.time.Duration
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
object StartStageHandlerTest : SubjectSpek<StartStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val stageNavigator: StageNavigator = mock()
val publisher: ApplicationEventPublisher = mock()
val exceptionHandler: ExceptionHandler = mock()
val objectMapper = ObjectMapper()
val clock = fixedClock()
val registry = NoopRegistry()
val retryDelay = Duration.ofSeconds(5)
subject(GROUP) {
StartStageHandler(
queue,
repository,
stageNavigator,
DefaultStageDefinitionBuilderFactory(
DefaultStageResolver(
StageDefinitionBuildersProvider(
listOf(
singleTaskStage,
multiTaskStage,
stageWithSyntheticBefore,
stageWithSyntheticAfter,
stageWithParallelBranches,
rollingPushStage,
zeroTaskStage,
stageWithSyntheticAfterAndNoTasks,
webhookStage,
failPlanningStage
)
)
)
),
ContextParameterProcessor(),
publisher,
listOf(exceptionHandler),
objectMapper,
clock,
registry,
retryDelayMs = retryDelay.toMillis()
)
}
fun resetMocks() = reset(queue, repository, publisher, exceptionHandler)
describe("starting a stage") {
given("there is a single initial task") {
val pipeline = pipeline {
application = "foo"
stage {
type = singleTaskStage.type
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("updates the stage status") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.status).isEqualTo(RUNNING)
assertThat(it.startTime).isEqualTo(clock.millis())
}
)
}
it("attaches tasks to the stage") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.tasks.size).isEqualTo(1)
it.tasks.first().apply {
assertThat(id).isEqualTo("1")
assertThat(name).isEqualTo("dummy")
assertThat(implementingClass).isEqualTo(DummyTask::class.java.name)
assertThat(isStageStart).isEqualTo(true)
assertThat(isStageEnd).isEqualTo(true)
}
}
)
}
it("starts the first task") {
verify(queue).push(StartTask(message, "1"))
}
it("publishes an event") {
verify(publisher).publishEvent(
check<StageStarted> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
}
)
}
}
given("the stage has no tasks") {
and("no after stages") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = zeroTaskStage.type
}
}
val message = StartStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("updates the stage status") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.status).isEqualTo(RUNNING)
assertThat(it.startTime).isEqualTo(clock.millis())
}
)
}
it("immediately completes the stage") {
verify(queue).push(CompleteStage(message))
verifyNoMoreInteractions(queue)
}
it("publishes an event") {
verify(publisher).publishEvent(
check<StageStarted> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
}
)
}
}
and("at least one after stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticAfterAndNoTasks.type
}
}
val message = StartStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("updates the stage status") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.status).isEqualTo(RUNNING)
assertThat(it.startTime).isEqualTo(clock.millis())
}
)
}
it("completes the stage") {
verify(queue).push(CompleteStage(message))
verifyNoMoreInteractions(queue)
}
it("publishes an event") {
verify(publisher).publishEvent(
check<StageStarted> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
}
)
}
}
}
given("the stage has several linear tasks") {
val pipeline = pipeline {
application = "foo"
stage {
type = multiTaskStage.type
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
on("receiving a message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("attaches tasks to the stage") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.tasks.size).isEqualTo(3)
it.tasks[0].apply {
assertThat(id).isEqualTo("1")
assertThat(name).isEqualTo("dummy1")
assertThat(implementingClass).isEqualTo(DummyTask::class.java.name)
assertThat(isStageStart).isEqualTo(true)
assertThat(isStageEnd).isEqualTo(false)
}
it.tasks[1].apply {
assertThat(id).isEqualTo("2")
assertThat(name).isEqualTo("dummy2")
assertThat(implementingClass).isEqualTo(DummyTask::class.java.name)
assertThat(isStageStart).isEqualTo(false)
assertThat(isStageEnd).isEqualTo(false)
}
it.tasks[2].apply {
assertThat(id).isEqualTo("3")
assertThat(name).isEqualTo("dummy3")
assertThat(implementingClass).isEqualTo(DummyTask::class.java.name)
assertThat(isStageStart).isEqualTo(false)
assertThat(isStageEnd).isEqualTo(true)
}
}
)
}
it("starts the first task") {
verify(queue).push(
StartTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
"1"
)
)
}
}
given("the stage has synthetic stages") {
context("before the main stage") {
val pipeline = pipeline {
application = "foo"
stage {
type = stageWithSyntheticBefore.type
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
on("receiving a message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("attaches the synthetic stage to the pipeline") {
verify(repository, times(2)).addStage(
check {
assertThat(it.parentStageId).isEqualTo(message.stageId)
assertThat(it.syntheticStageOwner).isEqualTo(STAGE_BEFORE)
}
)
}
it("raises an event to indicate the synthetic stage is starting") {
verify(queue).push(
StartStage(
message.executionType,
message.executionId,
"foo",
pipeline.stages.first().id
)
)
}
}
context("after the main stage") {
val pipeline = pipeline {
application = "foo"
stage {
type = stageWithSyntheticAfter.type
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("defers planning the after stages") {
verify(repository, never()).addStage(any())
}
it("raises an event to indicate the first task is starting") {
verify(queue).push(
StartTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
"1"
)
)
}
}
}
given("the stage has other upstream stages") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = singleTaskStage.type
}
stage {
refId = "2"
type = singleTaskStage.type
}
stage {
refId = "3"
requisiteStageRefIds = setOf("1", "2")
type = singleTaskStage.type
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("3").id)
and("at least one is incomplete") {
beforeGroup {
pipeline.stageByRef("1").status = SUCCEEDED
pipeline.stageByRef("2").status = RUNNING
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("doesn't build its tasks") {
assertThat(pipeline.stageByRef("3").tasks).isEmpty()
}
it("waits for the other upstream stage to complete") {
verify(queue, never()).push(isA<StartTask>())
}
it("does not publish an event") {
verifyZeroInteractions(publisher)
}
it("re-queues the message with a delay") {
verify(queue).push(message, retryDelay)
}
}
and("they are all complete") {
beforeGroup {
pipeline.stageByRef("1").status = SUCCEEDED
pipeline.stageByRef("2").status = SUCCEEDED
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("starts its first task") {
verify(queue).push(isA<StartTask>())
}
it("publishes an event") {
verify(publisher).publishEvent(isA<StageStarted>())
}
}
and("one of them failed") {
beforeGroup {
pipeline.stageByRef("1").status = SUCCEEDED
pipeline.stageByRef("2").status = TERMINAL
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("publishes no events") {
verifyZeroInteractions(publisher)
}
it("completes the execution") {
verify(queue).push(CompleteExecution(message))
verifyNoMoreInteractions(queue)
}
}
and("completion of another has already started this stage") {
beforeGroup {
pipeline.stageByRef("1").status = SUCCEEDED
pipeline.stageByRef("2").status = SUCCEEDED
pipeline.stageByRef("3").status = RUNNING
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("does not queue any messages") {
verifyZeroInteractions(queue)
}
it("does not publish any events") {
verifyZeroInteractions(publisher)
}
}
}
given("the stage has an execution window") {
and("synthetic before stages") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBefore.type
context["restrictExecutionDuringTimeWindow"] = true
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("injects a 'wait for execution window' stage before any other synthetic stages") {
argumentCaptor<StageExecution>().apply {
verify(repository, times(3)).addStage(capture())
assertSoftly {
assertThat(firstValue.type).isEqualTo(RestrictExecutionDuringTimeWindow.TYPE)
assertThat(firstValue.parentStageId).isEqualTo(message.stageId)
assertThat(firstValue.syntheticStageOwner).isEqualTo(STAGE_BEFORE)
assertThat(secondValue.requisiteStageRefIds).isEqualTo(setOf(firstValue.refId))
}
}
}
it("starts the 'wait for execution window' stage") {
verify(queue).push(
check<StartStage> {
assertThat(it.stageId).isEqualTo(pipeline.stages.find { it.type == RestrictExecutionDuringTimeWindow.TYPE }!!.id)
}
)
verifyNoMoreInteractions(queue)
}
}
and("parallel stages") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithParallelBranches.type
context["restrictExecutionDuringTimeWindow"] = true
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("injects a 'wait for execution window' stage before any other synthetic stages") {
argumentCaptor<StageExecution>().apply {
verify(repository, times(4)).addStage(capture())
assertSoftly {
assertThat(firstValue.type)
.isEqualTo(RestrictExecutionDuringTimeWindow.TYPE)
assertThat(firstValue.parentStageId).isEqualTo(message.stageId)
assertThat(firstValue.syntheticStageOwner).isEqualTo(STAGE_BEFORE)
allValues[1..3].forEach {
assertThat(it.requisiteStageRefIds)
.isEqualTo(setOf(firstValue.refId))
}
assertThat(allValues[1..3].map { it.type })
.allMatch { it == singleTaskStage.type }
}
}
}
it("starts the 'wait for execution window' stage") {
verify(queue).push(
check<StartStage> {
assertThat(it.stageId).isEqualTo(pipeline.stages.find { it.type == RestrictExecutionDuringTimeWindow.TYPE }!!.id)
}
)
verifyNoMoreInteractions(queue)
}
}
}
given("the stage has a stage type alias") {
val pipeline = pipeline {
application = "foo"
stage {
type = "bar"
context["alias"] = webhookStage.type
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("starts the stage") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.type).isEqualTo("bar")
assertThat(it.status).isEqualTo(RUNNING)
assertThat(it.startTime).isEqualTo(clock.millis())
}
)
}
it("attaches a task to the stage") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.tasks.size).isEqualTo(1)
it.tasks.first().apply {
assertThat(id).isEqualTo("1")
assertThat(name).isEqualTo("createWebhook")
assertThat(implementingClass).isEqualTo(DummyTask::class.java.name)
assertThat(isStageStart).isEqualTo(true)
assertThat(isStageEnd).isEqualTo(true)
}
}
)
}
}
given("the stage has a start time after ttl") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "bar"
type = singleTaskStage.type
startTimeExpiry = clock.instant().minusSeconds(30).toEpochMilli()
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("cancels the stage") {
verify(queue).push(
SkipStage(
pipeline.stageByRef("bar")
)
)
}
}
given("an exception is thrown planning the stage") {
val pipeline = pipeline {
application = "covfefe"
stage {
refId = "1"
type = failPlanningStage.type
}
}
val message = StartStage(pipeline.stageByRef("1"))
and("it is not recoverable") {
val exceptionDetails = ExceptionHandler.Response(
RuntimeException::class.qualifiedName,
"o noes",
ExceptionHandler.responseDetails("o noes"),
false
)
and("the pipeline should fail") {
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("completes the stage") {
verify(queue).push(isA<CompleteStage>())
}
it("attaches the exception to the stage context") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.context["exception"]).isEqualTo(exceptionDetails)
}
)
}
}
and("only the branch should fail") {
beforeGroup {
pipeline.stageByRef("1").apply {
context["failPipeline"] = false
context["continuePipeline"] = false
context["beforeStagePlanningFailed"] = null
}
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("completes the stage") {
verify(queue).push(isA<CompleteStage>())
}
it("attaches the exception to the stage context") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.context["exception"]).isEqualTo(exceptionDetails)
}
)
}
it("attaches flag to the stage context to indicate that before stage planning failed") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.context["beforeStagePlanningFailed"]).isEqualTo(true)
}
)
}
}
and("the branch should be allowed to continue") {
beforeGroup {
pipeline.stageByRef("1").apply {
context["failPipeline"] = false
context["continuePipeline"] = true
context["beforeStagePlanningFailed"] = null
}
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("completes the stage") {
verify(queue).push(isA<CompleteStage>())
}
it("attaches the exception to the stage context") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.context["exception"]).isEqualTo(exceptionDetails)
}
)
}
it("attaches flag to the stage context to indicate that before stage planning failed") {
verify(repository, times(2)).storeStage(
check {
assertThat(it.context["beforeStagePlanningFailed"]).isEqualTo(true)
}
)
}
}
}
and("it is recoverable") {
val exceptionDetails = ExceptionHandler.Response(
RuntimeException::class.qualifiedName,
"o noes",
ExceptionHandler.responseDetails("o noes"),
true
)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("re-runs the task") {
verify(queue).push(message, retryDelay)
}
}
}
}
describe("running a branching stage") {
context("when the stage starts") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "parallel"
type = stageWithParallelBranches.type
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("builds tasks for the main branch") {
val stage = pipeline.stageById(message.stageId)
assertThat(stage.tasks.map(TaskExecution::getName)).isEqualTo(listOf("post-branch"))
}
it("builds synthetic stages for each parallel branch") {
assertThat(pipeline.stages.size).isEqualTo(4)
assertThat(pipeline.stages.map { it.type })
.isEqualTo(listOf(singleTaskStage.type, singleTaskStage.type, singleTaskStage.type, stageWithParallelBranches.type))
}
it("builds stages that will run in parallel") {
assertThat(pipeline.stages.flatMap { it.requisiteStageRefIds })
.isEmpty()
// TODO: contexts, etc.
}
it("renames each parallel branch") {
val stage = pipeline.stageByRef("1")
assertThat(pipeline.stages.filter { it.parentStageId == stage.id }.map { it.name }).isEqualTo(listOf("run in us-east-1", "run in us-west-2", "run in eu-west-1"))
}
it("runs the parallel stages") {
verify(queue, times(3)).push(
check<StartStage> {
assertThat(pipeline.stageById(it.stageId).parentStageId).isEqualTo(message.stageId)
}
)
}
}
context("when one branch starts") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "parallel"
type = stageWithParallelBranches.type
stageWithParallelBranches.buildBeforeStages(this)
stageWithParallelBranches.buildTasks(this)
}
}
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stages[0].id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("builds tasks for the branch") {
val stage = pipeline.stageById(message.stageId)
assertThat(stage.tasks).isNotEmpty
assertThat(stage.tasks.map(TaskExecution::getName)).isEqualTo(listOf("dummy"))
}
it("does not build more synthetic stages") {
val stage = pipeline.stageById(message.stageId)
assertThat(pipeline.stages.mapNotNull(StageExecution::getParentStageId))
.doesNotContain(stage.id)
}
}
}
describe("running a rolling push stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = rollingPushStage.type
}
}
context("when the stage starts") {
val message = StartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("builds tasks for the main branch") {
pipeline.stageById(message.stageId).let { stage ->
assertThat(stage.tasks.size).isEqualTo(5)
assertThat(stage.tasks[0].isLoopStart).isEqualTo(false)
assertThat(stage.tasks[1].isLoopStart).isEqualTo(true)
assertThat(stage.tasks[2].isLoopStart).isEqualTo(false)
assertThat(stage.tasks[3].isLoopStart).isEqualTo(false)
assertThat(stage.tasks[4].isLoopStart).isEqualTo(false)
assertThat(stage.tasks[0].isLoopEnd).isEqualTo(false)
assertThat(stage.tasks[1].isLoopEnd).isEqualTo(false)
assertThat(stage.tasks[2].isLoopEnd).isEqualTo(false)
assertThat(stage.tasks[3].isLoopEnd).isEqualTo(true)
assertThat(stage.tasks[4].isLoopEnd).isEqualTo(false)
}
}
it("runs the parallel stages") {
verify(queue).push(
check<StartTask> {
assertThat(it.taskId).isEqualTo("1")
}
)
}
}
}
describe("running an optional stage") {
given("the stage should be run") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBefore.type
context["stageEnabled"] = mapOf(
"type" to "expression",
"expression" to "true"
)
}
}
val message = StartStage(pipeline.stages.first())
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("proceeds with the first synthetic stage as normal") {
verify(queue).push(any<StartStage>())
}
}
given("the stage should be skipped") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBefore.type
context["stageEnabled"] = mapOf(
"type" to "expression",
"expression" to "false"
)
}
}
val message = StartStage(pipeline.stages.first())
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("skips the stage") {
verify(queue).push(isA<SkipStage>())
}
it("doesn't build any tasks") {
assertThat(pipeline.stageById(message.stageId).tasks).isEmpty()
}
it("doesn't build any synthetic stages") {
assertThat(pipeline.stages.filter { it.parentStageId == message.stageId })
.isEmpty()
}
}
given("the stage's optionality is a nested condition") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "Preceding"
status = FAILED_CONTINUE
}
stage {
refId = "2"
type = stageWithSyntheticBefore.type
context["stageEnabled"] = mapOf(
"type" to "expression",
"expression" to "execution.stages.?[name == 'Preceding'][0]['status'].toString() != \"SUCCEEDED\""
)
}
}
val message = StartStage(pipeline.stageByRef("2"))
and("the stage should be run") {
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("proceeds with the first synthetic stage as normal") {
verify(queue).push(any<StartStage>())
}
}
and("the stage should be skipped") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "Preceding"
status = SUCCEEDED
}
stage {
refId = "2"
type = stageWithSyntheticBefore.type
context["stageEnabled"] = mapOf(
"type" to "expression",
"expression" to "execution.stages.?[name == 'Preceding'][0]['status'].toString() != \"SUCCEEDED\""
)
}
}
val message = StartStage(pipeline.stageByRef("2"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("skips the stage") {
verify(queue).push(isA<SkipStage>())
}
}
}
}
describe("invalid commands") {
val message = StartStage(PIPELINE, "1", "foo", "1")
given("no such execution") {
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doThrow ExecutionNotFoundException("No Pipeline found for ${message.executionId}")
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("emits an error event") {
verify(queue).push(isA<InvalidExecutionId>())
}
}
given("no such stage") {
val pipeline = pipeline {
id = message.executionId
application = "foo"
}
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("emits an error event") {
verify(queue).push(isA<InvalidStageId>())
}
}
}
})
| apache-2.0 | a47d2aef5e9b97c833893c2803877ed1 | 30.121212 | 169 | 0.600563 | 4.946749 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/UndyingBow.kt | 1 | 1816 | package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.DefaultBow
import nl.sugcube.dirtyarrows.util.itemInOffHand
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.entity.PlayerDeathEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
/**
* Acts as a totem of undying - saves you from death when held.
*
* @author SugarCaney
*/
open class UndyingBow(plugin: DirtyArrows) : BowAbility(
plugin = plugin,
type = DefaultBow.UNDYING,
canShootInProtectedRegions = true,
removeArrow = false,
description = "Saves you from death when held."
) {
@EventHandler
fun saveFromDeath(event: PlayerDeathEvent) {
val player = event.entity
val bow = player.bowItem() ?: return
// Temporarily give a totem of undying.
val cachedOffHand = player.itemInOffHand
val originalDamageCause = player.lastDamageCause
with(player) {
health = 0.5
inventory.setItemInOffHand(ItemStack(Material.TOTEM_OF_UNDYING, 1))
fireTicks = 0
damage(999999.9)
lastDamageCause = originalDamageCause
event.deathMessage = null
addPotionEffect(PotionEffect(PotionEffectType.FIRE_RESISTANCE, 200, 0))
addPotionEffect(PotionEffect(PotionEffectType.WATER_BREATHING, 200, 0))
}
// Completely use up the bow. If it's in the offhand, removeItem doesnt work for some reason.
if (cachedOffHand != bow) {
player.inventory.setItemInOffHand(cachedOffHand)
player.inventory.removeItem(bow)
}
}
} | gpl-3.0 | c82bd37264483f4f1c6b0be8f2f36625 | 33.283019 | 101 | 0.69163 | 4.223256 | false | false | false | false |
googlesamples/android-media-controller | mediacontroller/src/main/java/com/example/android/mediacontroller/tv/TvLauncherFragment.kt | 1 | 4230 | /*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.mediacontroller.tv
import android.annotation.TargetApi
import android.os.Build
import android.os.Bundle
import androidx.leanback.app.BrowseSupportFragment
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.DiffCallback
import androidx.leanback.widget.HeaderItem
import androidx.leanback.widget.ListRow
import androidx.leanback.widget.ListRowPresenter
import androidx.leanback.widget.OnItemViewClickedListener
import androidx.leanback.widget.Presenter
import com.example.android.mediacontroller.MediaAppDetails
import com.example.android.mediacontroller.R
import com.example.android.mediacontroller.tasks.FindMediaAppsTask
import com.example.android.mediacontroller.tasks.FindMediaBrowserAppsTask
/**
* Displays a list of media apps that currently implement MediaBrowserService.
*/
class TvLauncherFragment : BrowseSupportFragment() {
private val browserAppsUpdated = object : FindMediaAppsTask.AppListUpdatedCallback {
override fun onAppListUpdated(mediaAppEntries: List<MediaAppDetails>) {
listBrowserApps(mediaAppEntries)
}
}
private val mediaAppsRowAdapter = ArrayObjectAdapter(ListRowPresenter())
private val mediaAppClickedListener = OnItemViewClickedListener { _, item, _, _ ->
if (item is MediaAppDetails) {
activity?.let {
startActivity(TvTestingActivity.buildIntent(it, item))
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupUIElements()
adapter = mediaAppsRowAdapter
onItemViewClickedListener = mediaAppClickedListener
}
override fun onStart() {
super.onStart()
FindMediaBrowserAppsTask(requireContext(), browserAppsUpdated).execute()
}
@TargetApi(Build.VERSION_CODES.M)
private fun setupUIElements() {
badgeDrawable = activity?.resources?.getDrawable(R.drawable.tv_banner, null)
headersState = HEADERS_DISABLED
}
private inline fun <reified T> Collection<T>.toArrayObjectAdapter(
presenter: Presenter
): ArrayObjectAdapter {
val adapter = ArrayObjectAdapter(presenter)
this.forEach { item -> adapter.add(item) }
return adapter
}
private fun listBrowserApps(apps: List<MediaAppDetails>) {
val listRowAdapter = apps.toArrayObjectAdapter(MediaAppCardPresenter())
val headerItem = HeaderItem(BROWSER_HEADER_ID, BROWSER_HEADER_NAME)
val diffCallback = object : DiffCallback<ListRow>() {
override fun areItemsTheSame(oldItem: ListRow, newItem: ListRow): Boolean {
return oldItem.headerItem.id == newItem.headerItem.id
}
override fun areContentsTheSame(oldItem: ListRow, newItem: ListRow): Boolean {
val oldAdapter = oldItem.adapter
val newAdapter = newItem.adapter
val sameSize = oldAdapter.size() == newAdapter.size()
if (!sameSize) {
return false
}
return (0 until oldAdapter.size()).none {
oldAdapter[it] as MediaAppDetails != newAdapter[it] as MediaAppDetails
}
}
}
mediaAppsRowAdapter.setItems(
mutableListOf(ListRow(headerItem, listRowAdapter)),
diffCallback
)
}
companion object {
private const val BROWSER_HEADER_ID = 1L
private const val BROWSER_HEADER_NAME = "MediaBrowserService Implementations"
}
}
| apache-2.0 | 5c756268def0978d2880bd0cb8fd9c4b | 36.767857 | 90 | 0.696217 | 4.901506 | false | false | false | false |
notsyncing/lightfur | lightfur-integration-vertx-entity/src/test/kotlin/io/github/notsyncing/lightfur/integration/vertx/entity/tests/EntityDataMapperTest.kt | 1 | 3668 | package io.github.notsyncing.lightfur.integration.vertx.entity.tests
import io.github.notsyncing.lightfur.entity.EntityModel
import io.github.notsyncing.lightfur.integration.vertx.entity.VertxEntityDataMapper
import io.github.notsyncing.lightfur.tests.DataMapperTest
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.ext.sql.ResultSet
import org.junit.Assert
import org.junit.Test
import java.math.BigDecimal
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
class EntityDataMapperTest : DataMapperTest(VertxEntityDataMapper::class.java) {
class TestObject : EntityModel(table = "") {
var id: Int by field(column = "id")
var name: String? by field(column = "username")
var date: LocalDateTime? by field(column = "date")
var type: TestEnum? by field(column = "type")
var list: IntArray? by field(column = "list")
var list2: IntArray? by field(column = "list2")
var complex: TestInnerObject? by field(column = "complex")
var complexArray: Array<TestInnerObject>? by field(column = "complex2")
var longNumber: BigDecimal? by field(column = "long_number")
}
class TestLongObject : EntityModel(table = "") {
var id: Long by field(column = "id")
var list: LongArray? by field(column = "list")
}
@Test
override fun testMap() {
val r = ResultSet()
r.columnNames = Arrays.asList("id", "username", "date", "type", "list", "list2", "complex", "complex2", "long_number")
val arr = JsonArray()
arr.add(1)
arr.add("test")
arr.add("2015-04-03T11:35:29.384")
arr.add(TestEnum.TypeB.ordinal)
arr.add("{1,2,3}")
arr.add(JsonArray("[4,5,6]"))
arr.add(JsonObject("{\"a\":7,\"b\":8}"))
arr.add("[{\"a\":9,\"b\":0},{\"a\":1,\"b\":2}]")
arr.add("92375947293472934923794729345345345433.2345345345")
r.results = Arrays.asList(arr)
val o = dataMapper.map(TestObject::class.java, r)
Assert.assertNotNull(o)
Assert.assertEquals(1, o.id.toLong())
Assert.assertEquals("test", o.name)
val t = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
Assert.assertEquals("2015-04-03T11:35:29.384", t.format(o.date))
Assert.assertEquals(TestEnum.TypeB, o.type)
Assert.assertArrayEquals(intArrayOf(1, 2, 3), o.list)
Assert.assertArrayEquals(intArrayOf(4, 5, 6), o.list2)
Assert.assertNotNull(o.complex)
Assert.assertEquals(7, o.complex?.a)
Assert.assertEquals(8, o.complex?.b)
Assert.assertNotNull(o.complexArray)
Assert.assertEquals(2, o.complexArray?.size)
Assert.assertNotNull(o.complexArray!![0])
Assert.assertEquals(9, o.complexArray!![0].a)
Assert.assertEquals(0, o.complexArray!![0].b)
Assert.assertNotNull(o.complexArray!![1])
Assert.assertEquals(1, o.complexArray!![1].a)
Assert.assertEquals(2, o.complexArray!![1].b)
Assert.assertTrue(BigDecimal("92375947293472934923794729345345345433.2345345345") == o.longNumber)
}
@Test
override fun testMapLong() {
val r = ResultSet()
r.columnNames = Arrays.asList("id", "list")
val arr = JsonArray()
arr.add(19839L)
arr.add("{78998,325345,3678346}")
r.results = Arrays.asList(arr)
val o = dataMapper.map(TestLongObject::class.java, r)
Assert.assertNotNull(o)
Assert.assertEquals(19839L, o.id)
Assert.assertArrayEquals(longArrayOf(78998L, 325345L, 3678346L), o.list)
}
} | gpl-3.0 | b918cf893827b399d3e05c391b3d5b3c | 34.621359 | 126 | 0.6494 | 3.575049 | false | true | false | false |
Maccimo/intellij-community | platform/platform-impl/src/com/intellij/idea/IdeStarter.kt | 2 | 10506 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.idea
import com.intellij.diagnostic.LoadingState
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.StartUpMeasurer.startActivity
import com.intellij.diagnostic.runActivity
import com.intellij.diagnostic.runChild
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.*
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginManagerMain
import com.intellij.internal.inspector.UiInspectorAction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationStarter
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.wm.impl.SystemDock
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.ui.AppUIUtil
import com.intellij.ui.mac.touchbar.TouchbarSupport
import com.intellij.util.io.URLUtil.SCHEME_SEPARATOR
import com.intellij.util.ui.accessibility.ScreenReader
import java.awt.EventQueue
import java.beans.PropertyChangeListener
import java.nio.file.Path
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ForkJoinPool
import javax.swing.JOptionPane
open class IdeStarter : ApplicationStarter {
companion object {
private var filesToLoad: List<Path> = Collections.emptyList()
private var uriToOpen: String? = null
@JvmStatic fun openFilesOnLoading(value: List<Path>) {
filesToLoad = value
}
@JvmStatic fun openUriOnLoading(value: String) {
uriToOpen = value
}
}
override fun isHeadless() = false
override fun getCommandName(): String? = null
final override fun getRequiredModality() = ApplicationStarter.NOT_IN_EDT
override fun main(args: List<String>) {
val app = ApplicationManagerEx.getApplicationEx()
assert(!app.isDispatchThread)
if (app.isLightEditMode && !app.isHeadlessEnvironment) {
// In a light mode UI is shown very quickly, tab layout requires ActionManager, but it is forbidden to init ActionManager in EDT,
// so, preload
ForkJoinPool.commonPool().execute {
ActionManager.getInstance()
}
}
val lifecyclePublisher = app.messageBus.syncPublisher(AppLifecycleListener.TOPIC)
openProjectIfNeeded(args, app, lifecyclePublisher).thenRun {
reportPluginErrors()
if (!app.isHeadlessEnvironment) {
postOpenUiTasks(app)
}
StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, LoadingState.APP_STARTED)
lifecyclePublisher.appStarted()
if (!app.isHeadlessEnvironment && PluginManagerCore.isRunningFromSources()) {
AppUIUtil.updateWindowIcon(JOptionPane.getRootFrame())
}
}
}
@OptIn(IntellijInternalApi::class)
protected open fun openProjectIfNeeded(args: List<String>, app: ApplicationEx, lifecyclePublisher: AppLifecycleListener): CompletableFuture<*> {
val frameInitActivity = startActivity("frame initialization")
frameInitActivity.runChild("app frame created callback") {
lifecyclePublisher.appFrameCreated(args)
}
// must be after `AppLifecycleListener#appFrameCreated`, because some listeners can mutate the state of `RecentProjectsManager`
if (app.isHeadlessEnvironment) {
frameInitActivity.end()
LifecycleUsageTriggerCollector.onIdeStart()
return CompletableFuture.completedFuture(null)
}
if (ApplicationManager.getApplication().isInternal) {
UiInspectorAction.initGlobalInspector()
}
ForkJoinPool.commonPool().execute {
LifecycleUsageTriggerCollector.onIdeStart()
}
if (uriToOpen != null || args.isNotEmpty() && args[0].contains(SCHEME_SEPARATOR)) {
frameInitActivity.end()
processUriParameter(uriToOpen ?: args[0], lifecyclePublisher)
return CompletableFuture.completedFuture(null)
}
else {
val recentProjectManager = RecentProjectsManager.getInstance()
val willReopenRecentProjectOnStart = recentProjectManager.willReopenProjectOnStart()
val willOpenProject = willReopenRecentProjectOnStart || !args.isEmpty() || !filesToLoad.isEmpty()
val needToOpenProject = willOpenProject || showWelcomeFrame(lifecyclePublisher)
frameInitActivity.end()
if (!needToOpenProject) {
return CompletableFuture.completedFuture(null)
}
val project = when {
filesToLoad.isNotEmpty() -> ProjectUtil.tryOpenFiles(null, filesToLoad, "MacMenu")
args.isNotEmpty() -> loadProjectFromExternalCommandLine(args)
else -> null
}
return when {
project != null -> {
CompletableFuture.completedFuture(null)
}
willReopenRecentProjectOnStart -> {
recentProjectManager.reopenLastProjectsOnStart().thenAccept { isOpened ->
if (!isOpened) {
WelcomeFrame.showIfNoProjectOpened(lifecyclePublisher)
}
}
}
else -> {
CompletableFuture.completedFuture(null).thenRun {
WelcomeFrame.showIfNoProjectOpened(lifecyclePublisher)
}
}
}
}
}
private fun showWelcomeFrame(lifecyclePublisher: AppLifecycleListener): Boolean {
val showWelcomeFrameTask = WelcomeFrame.prepareToShow()
if (showWelcomeFrameTask == null) {
return true
}
ApplicationManager.getApplication().invokeLater {
showWelcomeFrameTask.run()
lifecyclePublisher.welcomeScreenDisplayed()
}
return false
}
private fun processUriParameter(uri: String, lifecyclePublisher: AppLifecycleListener) {
ApplicationManager.getApplication().invokeLater {
CommandLineProcessor.processProtocolCommand(uri)
.thenAccept {
if (it.exitCode == ProtocolHandler.PLEASE_QUIT) {
ApplicationManager.getApplication().invokeLater {
ApplicationManagerEx.getApplicationEx().exit(false, true)
}
}
else if (it.exitCode != ProtocolHandler.PLEASE_NO_UI) {
WelcomeFrame.showIfNoProjectOpened(lifecyclePublisher)
}
}
}
}
internal class StandaloneLightEditStarter : IdeStarter() {
override fun openProjectIfNeeded(args: List<String>,
app: ApplicationEx,
lifecyclePublisher: AppLifecycleListener): CompletableFuture<*> {
val project = when {
filesToLoad.isNotEmpty() -> ProjectUtil.tryOpenFiles(null, filesToLoad, "MacMenu")
args.isNotEmpty() -> loadProjectFromExternalCommandLine(args)
else -> null
}
if (project != null) {
return CompletableFuture.completedFuture(null)
}
val recentProjectManager = RecentProjectsManager.getInstance()
return (if (recentProjectManager.willReopenProjectOnStart()) recentProjectManager.reopenLastProjectsOnStart()
else CompletableFuture.completedFuture(true))
.thenAccept { isOpened ->
if (!isOpened) {
ApplicationManager.getApplication().invokeLater {
LightEditService.getInstance().showEditorWindow()
}
}
}
}
}
}
private fun loadProjectFromExternalCommandLine(commandLineArgs: List<String>): Project? {
val currentDirectory = System.getenv(SocketLock.LAUNCHER_INITIAL_DIRECTORY_ENV_VAR)
@Suppress("SSBasedInspection")
Logger.getInstance("#com.intellij.idea.ApplicationLoader").info("ApplicationLoader.loadProject (cwd=${currentDirectory})")
val result = CommandLineProcessor.processExternalCommandLine(commandLineArgs, currentDirectory)
if (result.hasError) {
ApplicationManager.getApplication().invokeAndWait {
result.showErrorIfFailed()
ApplicationManager.getApplication().exit(true, true, false)
}
}
return result.project
}
private fun postOpenUiTasks(app: Application) {
if (SystemInfoRt.isMac) {
ForkJoinPool.commonPool().execute {
runActivity("mac touchbar on app init") {
TouchbarSupport.onApplicationLoaded()
}
}
}
else if (SystemInfoRt.isXWindow && SystemInfo.isJetBrainsJvm) {
ForkJoinPool.commonPool().execute {
runActivity("input method disabling on Linux") {
disableInputMethodsIfPossible()
}
}
}
invokeLaterWithAnyModality("system dock menu") {
SystemDock.updateMenu()
}
invokeLaterWithAnyModality("ScreenReader") {
val generalSettings = GeneralSettings.getInstance()
generalSettings.addPropertyChangeListener(GeneralSettings.PROP_SUPPORT_SCREEN_READERS, app, PropertyChangeListener { e ->
ScreenReader.setActive(e.newValue as Boolean)
})
ScreenReader.setActive(generalSettings.isSupportScreenReaders)
}
}
private fun invokeLaterWithAnyModality(name: String, task: () -> Unit) {
EventQueue.invokeLater {
runActivity(name, task = task)
}
}
private fun reportPluginErrors() {
val pluginErrors = PluginManagerCore.getAndClearPluginLoadingErrors()
if (pluginErrors.isEmpty()) {
return
}
ApplicationManager.getApplication().invokeLater({
val title = IdeBundle.message("title.plugin.error")
val content = HtmlBuilder().appendWithSeparators(HtmlChunk.p(), pluginErrors).toString()
NotificationGroupManager.getInstance().getNotificationGroup("Plugin Error").createNotification(title, content, NotificationType.ERROR)
.setListener { notification, event ->
notification.expire()
PluginManagerMain.onEvent(event.description)
}
.notify(null)
}, ModalityState.NON_MODAL)
}
| apache-2.0 | f8f39570380efc1f371c2cd8ccf842ab | 36.3879 | 146 | 0.733771 | 5.005241 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/type/Type.kt | 1 | 2303 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.type
/**
* Representation of a type within Arcs.
*
* TODO: variableMap is implemented as a `MutableMap<Any, Any>`, but this has awful code-smell.
* Febreeze, please.
*/
interface Type {
val tag: Tag
/** Checks whether or not this [Type] is at least as specific as the given [other] [Type]. */
fun isAtLeastAsSpecificAs(other: Type): Boolean {
if (tag != other.tag) return false
// Throw if they are the same tag but the implementation class hasn't overridden this
// method.
throw UnsupportedOperationException("$this does not support same-type specificity checking")
}
/** Produces a string-representation of this [Type], configurable with [options]. */
fun toStringWithOptions(options: ToStringOptions): String = "${this.tag}"
/** Options used with [Type.toStringWithOptions]. */
data class ToStringOptions(
val hideFields: Boolean = false,
val pretty: Boolean = false
)
/** Defines a [Type] for data capable of being a container for data of another [Type]. */
interface TypeContainer<T : Type> : Type {
/** The [Type] of data contained by this [Type]. Think: kotlin's `typeParameter`. */
val containedType: T
}
companion object {
/**
* Returns the deepest unique types contained by the given pair.
*
* Recursively traverses [type1] and [type2]'s [containedType]s until their [tag]s are equal
* and neither has a [containedType].
*/
tailrec fun unwrapPair(pair: Pair<Type, Type>): Pair<Type, Type> {
val (type1, type2) = pair
// Base case: tags are not equal.
if (type1.tag != type2.tag) return pair
// Base case: If they're not both containers of other types, we're done.
if (type1 !is TypeContainer<*> || type2 !is TypeContainer<*>) return pair
val contained1 = type1.containedType
val contained2 = type2.containedType
// "We need to go deeper." - Dom Cobb
return unwrapPair(contained1 to contained2)
}
}
}
| bsd-3-clause | daa5d6d97a6b6667da05b992f78b4df5 | 32.376812 | 96 | 0.677377 | 3.977547 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/util/lexer/regex/RegexStringIterator.kt | 1 | 3829 | package com.bajdcc.util.lexer.regex
import com.bajdcc.util.Position
import com.bajdcc.util.lexer.error.RegexException
import com.bajdcc.util.lexer.error.RegexException.RegexError
import com.bajdcc.util.lexer.token.MetaType
import java.util.*
/**
* 字符串迭代器,提供字节流解析功能
*
* @author bajdcc
*/
open class RegexStringIterator() : IRegexStringIterator, Cloneable {
override fun regexDescription() = context
/**
* 存储字符串
*/
open var context: String = ""
/**
* 用于恢复的位置堆栈
*/
var stackIndex = Stack<Int>()
/**
* 位置
*/
protected var position = Position()
/**
* 用于恢复行列数的堆栈
*/
var stackPosition = Stack<Position>()
/**
* 当前的分析信息
*/
protected var data = RegexStringIteratorData()
/**
* 记录每行起始的位置
*/
protected var arrLinesNo = mutableListOf<Int>()
/**
* 字符解析组件
*/
protected var utility = RegexStringUtility(this)
init {
arrLinesNo.add(-1)
}
constructor(context: String) : this() {
this.context = context
}
@Throws(RegexException::class)
override fun err(error: RegexError) {
throw RegexException(error, position)
}
override fun next() {
if (available()) {
advance()
}
translate()
position.column = position.column + 1
if (data.current == MetaType.NEW_LINE.char) {
val prev = arrLinesNo[arrLinesNo.size - 1]
if (prev < data.index)
arrLinesNo.add(data.index)
position.column = 0
position.line = position.line + 1
}
}
override fun scan() {
throw NotImplementedError()
}
override fun position(): Position {
return position
}
override fun translate() {
if (!available()) {
data.current = '\u0000'
data.meta = MetaType.END
return
}
data.current = current()
transform()
}
/**
* 分析字符类型
*/
protected open fun transform() {
data.meta = MetaType.CHARACTER
}
override fun available(): Boolean {
return data.index >= 0 && data.index < context.length
}
override fun advance() {
data.index++
}
override fun current(): Char {
return context[data.index]
}
override fun meta(): MetaType {
return data.meta
}
override fun index(): Int {
return data.index
}
@Throws(RegexException::class)
override fun expect(meta: MetaType, error: RegexError) {
if (data.meta === meta) {
next()
} else {
err(error)
}
}
override fun snapshot() {
stackIndex.push(data.index)
stackPosition.push(Position(position.column, position.line))
}
override fun cover() {
stackIndex[stackIndex.size - 1] = data.index
stackPosition[stackPosition.size - 1] = Position(position)
}
override fun restore() {
data.index = stackIndex.pop()
position = Position(stackPosition.pop())
}
override fun discard() {
stackIndex.pop()
stackPosition.pop()
}
override fun utility(): RegexStringUtility {
return utility
}
override fun copy(): IRegexStringIterator {
throw NotImplementedError()
}
override fun clone(): Any {
val o = super.clone() as RegexStringIterator
o.position = o.position.clone() as Position
o.data = o.data.clone()
o.utility = RegexStringUtility(o)
return o
}
override fun ex(): IRegexStringIteratorEx {
throw NotImplementedError()
}
} | mit | 60861fcad76e18c794413333a00765a7 | 20.206897 | 68 | 0.569531 | 4.245109 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/OP/syntax/precedence/PrecedenceTable.kt | 1 | 14103 | package com.bajdcc.OP.syntax.precedence
import com.bajdcc.LL1.syntax.prediction.PredictionInstruction
import com.bajdcc.LL1.syntax.token.PredictType
import com.bajdcc.OP.grammar.error.GrammarException
import com.bajdcc.OP.grammar.error.GrammarException.GrammarError
import com.bajdcc.OP.grammar.handler.IPatternHandler
import com.bajdcc.OP.syntax.exp.RuleExp
import com.bajdcc.OP.syntax.exp.TokenExp
import com.bajdcc.OP.syntax.handler.SyntaxException
import com.bajdcc.OP.syntax.handler.SyntaxException.SyntaxError
import com.bajdcc.OP.syntax.solver.FirstVTSolver
import com.bajdcc.OP.syntax.solver.LastVTSolver
import com.bajdcc.OP.syntax.solver.OPTableSolver
import com.bajdcc.OP.syntax.token.PrecedenceType
import com.bajdcc.util.lexer.regex.IRegexStringIterator
import com.bajdcc.util.lexer.token.Token
import com.bajdcc.util.lexer.token.TokenType
import java.util.*
/**
* 【算法优先分析】算法优先关系表
*
* @author bajdcc
*/
class PrecedenceTable(
protected var arrNonTerminals: MutableList<RuleExp>,
protected var arrTerminals: MutableList<TokenExp>,
private val mapPattern: MutableMap<String, IPatternHandler>,
private val iter: IRegexStringIterator) : OPTableSolver() {
/**
* 非终结符映射
*/
protected var mapNonTerminals = mutableMapOf<RuleExp, Int>()
/**
* 终结符映射
*/
protected var mapTerminals = mutableMapOf<TokenExp, Int>()
/**
* 算符优先分析表
*/
private var table: Array<Array<PrecedenceType>>? = null
/**
* 得到当前终结符ID
*
* @return 终结符ID
*/
private val tokenId: Int
get() {
val token = iter.ex().token()
if (token.type === TokenType.EOF) {
return -2
}
for (exp in arrTerminals) {
if (exp.kType === token.type && (exp.`object` == null || exp.`object` == token.obj)) {
return exp.id
}
}
return -1
}
/**
* 获得矩阵描述
*
* @return 矩阵描述
*/
val matrixString: String
get() {
val sb = StringBuilder()
val size = arrTerminals.size
sb.append("#### 算符优先关系矩阵 ####")
sb.append(System.lineSeparator())
sb.append("\t")
for (i in 0 until size) {
sb.append(i).append("\t")
}
sb.append(System.lineSeparator())
for (i in 0 until size) {
sb.append(i).append("\t")
for (j in 0 until size) {
sb.append(table!![i][j].desc).append("\t")
}
sb.append(System.lineSeparator())
}
return sb.toString()
}
init {
initialize()
}
/**
* 抛出异常
*
* @param error 错误类型
* @throws GrammarException 语法错误
*/
@Throws(GrammarException::class)
private fun err(error: GrammarError) {
throw GrammarException(error, iter.position(), iter.ex().token())
}
/**
* 抛出异常
*
* @param error 错误类型
* @throws SyntaxException 词法错误
*/
@Throws(SyntaxException::class)
private fun err(error: SyntaxError) {
throw SyntaxException(error, iter.position(), iter.ex().token())
}
/**
* 添加归约模式
*
* @param pattern 模式串(由0和1组成,0=Vn,1=Vt)
* @param handler 处理器
* @throws SyntaxException 词法错误
*/
@Throws(SyntaxException::class)
fun addPatternHandler(pattern: String, handler: IPatternHandler) {
if (mapPattern.put(pattern, handler) != null) {
err(SyntaxError.REDECLARATION)
}
}
/**
* 初始化
*/
private fun initialize() {
initMap()
initTable()
buildFirstVTAndLastVt()
buildTable()
}
/**
* 初始化符号映射表
*/
private fun initMap() {
for (i in arrNonTerminals.indices) {
mapNonTerminals[arrNonTerminals[i]] = i
}
for (i in arrTerminals.indices) {
mapTerminals[arrTerminals[i]] = i
}
}
/**
* 初始化算符优先关系表
*/
private fun initTable() {
val size = arrTerminals.size
table = Array(size) { Array(size) { PrecedenceType.NULL } }
}
/**
* 构造FirstVT和LastVT
*/
private fun buildFirstVTAndLastVt() {
/* 迭代求值 */
var update: Boolean
do {
update = false
for (exp in arrNonTerminals) {
for (item in exp.rule.arrRules) {
val firstVT = FirstVTSolver(exp)
val lastVT = LastVTSolver(exp)
item.expression.visit(firstVT)
item.expression.visitReverse(lastVT)
update = update or firstVT.isUpdated
update = update or lastVT.isUpdated
}
}
} while (update)
/* 将哈希表按ID排序并保存 */
for (exp in arrNonTerminals) {
exp.rule.arrFirstVT = sortTerminal(exp.rule.setFirstVT).toMutableList()
exp.rule.arrLastVT = sortTerminal(exp.rule.setLastVT).toMutableList()
}
}
/**
* 建立算符优先表
*/
private fun buildTable() {
for (exp in arrNonTerminals) {
for (item in exp.rule.arrRules) {
item.expression.visit(this)
}
}
}
override fun setCell(x: Int, y: Int, type: PrecedenceType) {
if (table!![x][y] == PrecedenceType.NULL) {
table!![x][y] = type
} else if (table!![x][y] != type) {
System.err.println(String.format("项目冲突:[%s] -> [%s],'%s' -> '%s'",
arrTerminals[x], arrTerminals[y],
table!![x][y].desc, type.desc))
}
}
/**
* 给指定终结符集合按ID排序
*
* @param colletion 要排序的集合
* @return 排序后的结果
*/
private fun sortTerminal(colletion: Collection<TokenExp>): List<TokenExp> {
val list = colletion.toList()
return list.sortedBy { it.id }
}
private fun println() {
if (debug)
println()
}
private fun println(str: String) {
if (debug)
println(str)
}
/**
* 进行分析
*
* @return 计算后的值
* @throws GrammarException 语法错误
*/
@Throws(GrammarException::class)
fun run(): Any? {
/* 指令堆栈 */
val spi = Stack<PredictionInstruction>()
/* 数据堆栈 */
val sobj = Stack<FixedData>()
/* 结束符号进栈 */
spi.push(PredictionInstruction(PredictType.EPSILON, -1))
sobj.push(FixedData())
/* 执行步骤顺序 */
var index = 0
/* 输入字符索引 */
var input = tokenId// #为-2
/* 栈顶的终结符索引 */
var top = -1
/* 栈顶的终结符位置 */
var topIndex = -1
while (!(spi.size == 2 && input == -2)) {// 栈层为2且输入为#,退出
index++
println("步骤[$index]")
println("\t----------------")
if (input == -1) {// 没有找到,非法字符
err(GrammarError.UNDECLARED)
}
if (input == -2 && spi.size == 1) {// 栈为#,输入为#,报错
err(GrammarError.NULL)
}
val token = iter.ex().token()
println("\t输入:[$token]")
if (top != -1 && input != -2
&& table!![top][input] == PrecedenceType.NULL) {
err(GrammarError.MISS_PRECEDENCE)
}
if (top == -1 || input != -2 && table!![top][input] != PrecedenceType.GT) {
/* 栈顶为#,或者top<=input,则直接移进 */
println("\t移进:[$token]")
/* 1.指令进栈 */
spi.push(PredictionInstruction(PredictType.TERMINAL, input))
/* 2.数据进栈 */
sobj.push(FixedData(token))
/* 3.保存单词 */
iter.ex().saveToken()
/* 4.取下一个单词 */
iter.scan()
/* 5.刷新当前输入字符索引 */
input = tokenId
} else {
/* 不是移进就是归约 */
/* 1.从栈顶向下寻找第一个出现LT的终结符 */
var head: Int
var comp_top = top
var comp_top_index = topIndex
head = topIndex - 1
while (head >= 0) {
if (spi[head].type == PredictType.EPSILON) {
// 找到底部#
comp_top_index = head + 1
break
}
if (spi[head].type == PredictType.TERMINAL) {
if (table!![spi[head].inst][comp_top] == PrecedenceType.LT) {
// 找到第一个优先级LT的
comp_top_index = head + 1
break
} else if (table!![spi[head].inst][comp_top] == PrecedenceType.EQ) {
// 素短语内部优先级相同
comp_top = spi[head].inst
comp_top_index = head
}
}
head--
}
// head原来为最左素短语的头,从head+1到栈顶为可归约子串
val primePhraseCount = spi.size - comp_top_index
/* 2.保存最左素短语 */
val primeInstList = mutableListOf<PredictionInstruction>()
val primeDataList = mutableListOf<FixedData>()
for (i in 0 until primePhraseCount) {
primeInstList.add(0, spi.pop())
primeDataList.add(0, sobj.pop())
}
println("\t----==== 最左素短语模式 ====----")
val pattern = getPattern(primeInstList)
println("\t" + pattern + ": "
+ pattern.replace("0", "[op]").replace("1", "[tok]"))
println("\t----==== 最左素短语 ====----")
for (i in 0 until primePhraseCount) {
println("\t" + primeDataList[i])
}
/* 3.新建指令集和数据集(用于用户级回调) */
val tempTokenList = mutableListOf<Token>()
val tempObjectList = mutableListOf<Any>()
for (i in 0 until primePhraseCount) {
val pt = primeInstList[i].type
if (pt == PredictType.TERMINAL) {
tempTokenList.add(primeDataList[i].token!!)
} else if (pt == PredictType.NONTERMINAL) {
tempObjectList.add(primeDataList[i].obj!!)
}
}
/* 4.寻找定义过的有效的模式,进行归约 */
val handler = mapPattern[pattern]
if (handler == null) {
System.err.println("缺少处理模式:" + pattern + ": "
+ pattern.replace("0", "[op]").replace("1", "[tok]"))
err(GrammarError.MISS_HANDLER)
}
println("\t----==== 处理模式名称 ====----")
println("\t" + handler!!.patternName)
/* 5.归约处理 */
val result = handler.handle(tempTokenList, tempObjectList)
println("\t----==== 处理结果 ====----")
println("\t" + result)
/* 将结果压栈 */
/* 6.指令进栈(非终结符进栈) */
spi.push(PredictionInstruction(PredictType.NONTERMINAL, -1))
/* 7.数据进栈(结果进栈) */
sobj.push(FixedData(result))
}
println("\t----==== 指令堆栈 ====----")
for (i in spi.indices.reversed()) {
val pi = spi[i]
when (pi.type) {
PredictType.NONTERMINAL -> println("\t$i: [数据]")
PredictType.TERMINAL -> println("\t" + i + ": ["
+ arrTerminals[pi.inst].toString() + "]")
PredictType.EPSILON -> println("\t" + i + ": ["
+ TokenType.EOF.desc + "]")
}
}
println("\t----==== 数据堆栈 ====----")
for (i in sobj.indices.reversed()) {
println("\t" + i + ": [" + sobj[i] + "]")
}
println()
/* 更新栈顶终结符索引 */
if (spi.peek().type == PredictType.TERMINAL) {
top = spi.peek().inst
topIndex = spi.size - 1
} else {// 若栈顶为非终结符,则第二顶必为终结符
top = spi.elementAt(spi.size - 2).inst
topIndex = spi.size - 2
}
}
println()
return if (sobj.peek().obj == null) sobj.peek().token!!.obj else sobj.peek().obj
}
override fun toString(): String {
return matrixString
}
companion object {
private val debug = false
/**
* 获取素短语模式
*
* @param spi 素短语
* @return 模式字符串
*/
private fun getPattern(spi: Collection<PredictionInstruction>): String {
val sb = StringBuilder()
for (pi in spi) {
sb.append(if (pi.type == PredictType.TERMINAL) "1" else "0")
}
return sb.toString()
}
}
}
| mit | 818cce05255ca830345c6a19f268a44d | 31.017199 | 102 | 0.475712 | 4.007073 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/test/kotlin/com/acornui/recycle/IndexedRecycleListTest.kt | 1 | 4833 | /*
* Copyright 2019 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.recycle
import com.acornui.assertionsEnabled
import com.acornui.test.assertUnorderedListEquals
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class IndexedRecycleListTest {
@BeforeTest
fun setUp() {
assertionsEnabled = true
TestObj.changedCount = 0
TestObj.constructionCount = 0
}
/**
* Test that the second obtain / flip set recycles based on index.
*/
@Test
fun smartObtain() {
val c = IndexedPool(ClearableObjectPool { TestObj() })
for (i in 5..9) {
c.obtain(i).value = i
}
c.flip()
assertChangedCount(5)
assertConstructionCount(5)
// Second set, the exact same values:
for (i in 5..9) {
c.obtain(i).value = i
}
c.flip()
assertChangedCount(0)
assertConstructionCount(0)
// Third set, shifted 2:
for (i in 7..11) {
c.obtain(i).value = i
}
c.flip()
assertChangedCount(2)
assertConstructionCount(0)
// Reversed
for (i in 11 downTo 7) {
c.obtain(i).value = i
}
c.flip()
assertChangedCount(0)
assertConstructionCount(0)
// Split forward
for (i in 8..11) {
c.obtain(i).value = i
}
assertChangedCount(0)
for (i in 7 downTo 5) {
c.obtain(i).value = i
}
assertChangedCount(2)
assertConstructionCount(2)
c.flip()
// Split reversed
for (i in 8 downTo 11) {
c.obtain(i).value = i
}
assertChangedCount(0)
for (i in 7 downTo 5) {
c.obtain(i).value = i
}
assertChangedCount(0)
assertConstructionCount(0)
c.flip()
}
/**
* Test that obtaining forwards, but a negative offset or obtaining reversed, but a positive offset is optimal.
*/
@Test
fun smartObtainOppositeDirection() {
val c = IndexedPool(ClearableObjectPool { TestObj() })
for (i in 5..9) {
c.obtain(i).value = i
}
c.flip()
assertChangedCount(5)
assertConstructionCount(5)
// Step down one
for (i in 4..8) {
c.obtain(i).value = i
}
c.flip()
assertChangedCount(1)
assertConstructionCount(0)
// Step up one
for (i in 9 downTo 5) {
c.obtain(i).value = i
}
c.flip()
assertChangedCount(1)
assertConstructionCount(0)
}
@Test
fun testNonSequential1() {
val c = IndexedPool(ClearableObjectPool { TestObj() })
c.obtain(9).value = 9
c.obtain(11).value = 11
c.flip()
assertUnorderedListEquals(listOf(9, 11), c.getUnused())
c.obtain(11)
assertUnorderedListEquals(listOf(9), c.getUnused())
c.obtain(9)
assertUnorderedListEquals(listOf(), c.getUnused())
assertEquals(Int.MAX_VALUE, c.obtain(12).value)
}
@Test
fun testNonSequential2() {
val c = IndexedPool(ClearableObjectPool { TestObj() })
c.obtain(9)
c.obtain(7)
}
@Test
fun forEach() {
val c = IndexedPool(ClearableObjectPool { TestObj() })
for (i in 5..9) {
c.obtain(i).value = i
}
c.flip()
assertUnorderedListEquals(listOf(5, 6, 7, 8, 9), c.getUnused())
c.obtain(6)
assertUnorderedListEquals(listOf(5, 7, 8, 9), c.getUnused())
c.obtain(7)
assertUnorderedListEquals(listOf(5, 8, 9), c.getUnused())
c.obtain(5)
assertUnorderedListEquals(listOf(8, 9), c.getUnused())
c.clear()
assertUnorderedListEquals(listOf(), c.getUnused())
}
@Test
fun getObtainedSerial() {
val c = IndexedPool(ClearableObjectPool { TestObj() })
for (i in 5..9) {
c.obtain(i).value = i
}
for (i in 5..9) {
assertEquals(i, c.getObtainedByIndex(i).value)
}
assertFails { c.getObtainedByIndex(4) }
assertFails { c.getObtainedByIndex(10) }
}
private fun IndexedPool<TestObj>.getUnused(): List<Int> {
val list = ArrayList<Int>()
forEachUnused { _, it ->
list.add(it.value)
}
return list
}
private fun assertChangedCount(i: Int) {
assertEquals(i, TestObj.changedCount)
TestObj.changedCount = 0
}
private fun assertConstructionCount(i: Int) {
assertEquals(i, TestObj.constructionCount)
TestObj.constructionCount = 0
}
}
private class TestObj : Clearable {
init {
constructionCount++
}
private var _value: Int = Int.MAX_VALUE
var value: Int
get() = _value
set(value) {
if (_value == value) return
_value = value
changedCount++
}
override fun clear() {
_value = Int.MAX_VALUE
}
companion object {
var changedCount = 0
var constructionCount = 0
}
}
| apache-2.0 | a4a6fad175df7322db19edcfd85e85f8 | 20.672646 | 112 | 0.678047 | 3 | false | true | false | false |
ingokegel/intellij-community | platform/execution-impl/src/com/intellij/execution/impl/RunManagerImpl.kt | 1 | 52551 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment")
package com.intellij.execution.impl
import com.intellij.configurationStore.*
import com.intellij.execution.*
import com.intellij.execution.configurations.*
import com.intellij.execution.runToolbar.RunToolbarSlotManager
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.runners.ProgramRunner
import com.intellij.ide.plugins.DynamicPluginListener
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.ProjectExtensionPointName
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.UnknownFeaturesCollector
import com.intellij.openapi.util.ClearableLazyValue
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.isDirectoryBased
import com.intellij.util.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.containers.filterSmart
import com.intellij.util.containers.mapSmart
import com.intellij.util.containers.nullize
import com.intellij.util.containers.toMutableSmartList
import com.intellij.util.text.UniqueNameGenerator
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.SourceRootEntity
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.Callable
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.ReentrantReadWriteLock
import javax.swing.Icon
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.concurrent.read
import kotlin.concurrent.write
private const val SELECTED_ATTR = "selected"
internal const val METHOD = "method"
private const val OPTION = "option"
private const val RECENT = "recent_temporary"
private val RUN_CONFIGURATION_TEMPLATE_PROVIDER_EP = ProjectExtensionPointName<RunConfigurationTemplateProvider>("com.intellij.runConfigurationTemplateProvider")
interface RunConfigurationTemplateProvider {
fun getRunConfigurationTemplate(factory: ConfigurationFactory, runManager: RunManagerImpl): RunnerAndConfigurationSettingsImpl?
}
@State(name = "RunManager", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE, useSaveThreshold = ThreeState.NO))])
open class RunManagerImpl @JvmOverloads constructor(val project: Project, sharedStreamProvider: StreamProvider? = null) : RunManagerEx(), PersistentStateComponent<Element>, Disposable {
companion object {
const val CONFIGURATION = "configuration"
const val NAME_ATTR = "name"
internal val LOG = logger<RunManagerImpl>()
@JvmStatic
fun getInstanceImpl(project: Project) = getInstance(project) as RunManagerImpl
fun canRunConfiguration(environment: ExecutionEnvironment): Boolean {
return environment.runnerAndConfigurationSettings?.let { canRunConfiguration(it, environment.executor) } ?: false
}
@JvmStatic
fun canRunConfiguration(configuration: RunnerAndConfigurationSettings, executor: Executor): Boolean {
try {
ApplicationManager.getApplication().assertIsNonDispatchThread()
configuration.checkSettings(executor)
}
catch (ignored: IndexNotReadyException) {
return false
}
catch (ignored: RuntimeConfigurationError) {
return false
}
catch (ignored: RuntimeConfigurationException) {
}
return true
}
}
private val lock = ReentrantReadWriteLock()
private val idToType = object {
private var cachedValue: Map<String, ConfigurationType>? = null
val value: Map<String, ConfigurationType>
get() {
var result = cachedValue
if (result == null) {
result = compute()
cachedValue = result
}
return result
}
fun drop() {
cachedValue = null
}
fun resolve(value: Map<String, ConfigurationType>) {
cachedValue = value
}
private fun compute(): Map<String, ConfigurationType> {
return buildConfigurationTypeMap(ConfigurationType.CONFIGURATION_TYPE_EP.extensionList)
}
}
@Suppress("LeakingThis")
private val listManager = RunConfigurationListManagerHelper(this)
private val templateIdToConfiguration = HashMap<String, RunnerAndConfigurationSettingsImpl>()
// template configurations are not included here
private val idToSettings: LinkedHashMap<String, RunnerAndConfigurationSettings>
get() = listManager.idToSettings
// When readExternal not all configuration may be loaded, so we need to remember the selected configuration
// so that when it is eventually loaded, we can mark is as a selected.
// See also notYetAppliedInitialSelectedConfigurationId, which helps when the initially selected RC is stored in some arbitrary *.run.xml file in project
protected open var selectedConfigurationId: String? = null
// RCs stored in arbitrary *.run.xml files are loaded a bit later than RCs from workspace and from .idea/runConfigurations.
// This var helps if initially selected RC is a one from such file.
// Empty string means that there's no information about initially selected RC in workspace.xml => IDE should select any.
private var notYetAppliedInitialSelectedConfigurationId: String? = null
private var selectedRCSetupScheduled: Boolean = false
private val iconCache = TimedIconCache()
private val recentlyUsedTemporaries = ArrayList<RunnerAndConfigurationSettings>()
// templates should be first because to migrate old before run list to effective, we need to get template before run task
private val workspaceSchemeManagerProvider = SchemeManagerIprProvider("configuration", Comparator { n1, n2 ->
val w1 = getNameWeight(n1)
val w2 = getNameWeight(n2)
if (w1 == w2) {
n1.compareTo(n2)
}
else {
w1 - w2
}
})
internal val schemeManagerIprProvider = if (project.isDirectoryBased || sharedStreamProvider != null) null else SchemeManagerIprProvider("configuration")
@Suppress("LeakingThis")
private val templateDifferenceHelper = TemplateDifferenceHelper(this)
@Suppress("LeakingThis")
private val workspaceSchemeManager = SchemeManagerFactory.getInstance(project).create("workspace",
RunConfigurationSchemeManager(this, templateDifferenceHelper,
isShared = false,
isWrapSchemeIntoComponentElement = false),
streamProvider = workspaceSchemeManagerProvider,
isAutoSave = false)
@Suppress("LeakingThis")
private val projectSchemeManager = SchemeManagerFactory.getInstance(project).create("runConfigurations",
RunConfigurationSchemeManager(this, templateDifferenceHelper,
isShared = true,
isWrapSchemeIntoComponentElement = schemeManagerIprProvider == null),
schemeNameToFileName = OLD_NAME_CONVERTER,
streamProvider = sharedStreamProvider ?: schemeManagerIprProvider)
internal val dotIdeaRunConfigurationsPath: String
get() = FileUtil.toSystemIndependentName(projectSchemeManager.rootDirectory.path)
private val rcInArbitraryFileManager = RCInArbitraryFileManager(project)
private val isFirstLoadState = AtomicBoolean(true)
private val stringIdToBeforeRunProvider = object : ClearableLazyValue<ConcurrentMap<String, BeforeRunTaskProvider<*>>>() {
override fun compute(): ConcurrentMap<String, BeforeRunTaskProvider<*>> {
val result = ConcurrentHashMap<String, BeforeRunTaskProvider<*>>()
for (provider in BeforeRunTaskProvider.EP_NAME.getExtensions(project)) {
result.put(provider.id.toString(), provider)
}
return result
}
}
internal val eventPublisher: RunManagerListener
get() = project.messageBus.syncPublisher(RunManagerListener.TOPIC)
init {
val messageBusConnection = project.messageBus.connect()
WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(messageBusConnection, object : WorkspaceModelChangeListener {
override fun changed(event: VersionedStorageChange) {
if (event.getChanges(ContentRootEntity::class.java).isNotEmpty() || event.getChanges(SourceRootEntity::class.java).isNotEmpty()) {
clearSelectedConfigurationIcon()
deleteRunConfigsFromArbitraryFilesNotWithinProjectContent()
}
}
})
messageBusConnection.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener {
override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) {
iconCache.clear()
}
override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) {
iconCache.clear()
// must be on unload and not before, since load must not be able to use unloaded plugin classes
reloadSchemes()
}
})
BeforeRunTaskProvider.EP_NAME.getPoint(project).addChangeListener(stringIdToBeforeRunProvider::drop, project)
}
override fun shouldSetRunConfigurationFromContext(): Boolean {
return Registry.`is`("select.run.configuration.from.context") && !isRunWidgetActive()
}
override fun isRunWidgetActive(): Boolean {
return RunToolbarSlotManager.getInstance(project).active
}
private fun clearSelectedConfigurationIcon() {
selectedConfiguration?.let {
iconCache.remove(it.uniqueID)
}
}
@TestOnly
fun initializeConfigurationTypes(factories: List<ConfigurationType>) {
idToType.resolve(buildConfigurationTypeMap(factories))
}
private fun buildConfigurationTypeMap(factories: List<ConfigurationType>): Map<String, ConfigurationType> {
val types = factories.toMutableList()
types.add(UnknownConfigurationType.getInstance())
val map = HashMap<String, ConfigurationType>()
for (type in types) {
map.put(type.id, type)
}
return map
}
override fun createConfiguration(name: String, factory: ConfigurationFactory): RunnerAndConfigurationSettings {
val template = getConfigurationTemplate(factory)
return createConfiguration(factory.createConfiguration(name, template.configuration), template)
}
override fun createConfiguration(runConfiguration: RunConfiguration, factory: ConfigurationFactory): RunnerAndConfigurationSettings {
return createConfiguration(runConfiguration, getConfigurationTemplate(factory))
}
private fun createConfiguration(configuration: RunConfiguration, template: RunnerAndConfigurationSettingsImpl): RunnerAndConfigurationSettings {
val settings = RunnerAndConfigurationSettingsImpl(this, configuration)
settings.importRunnerAndConfigurationSettings(template)
configuration.beforeRunTasks = template.configuration.beforeRunTasks
return settings
}
override fun dispose() {
lock.write {
iconCache.clear()
templateIdToConfiguration.clear()
}
}
open val config by lazy { RunManagerConfig(PropertiesComponent.getInstance(project)) }
/**
* Template configuration is not included
*/
override fun getConfigurationsList(type: ConfigurationType): List<RunConfiguration> {
var result: MutableList<RunConfiguration>? = null
for (settings in allSettings) {
val configuration = settings.configuration
if (type.id == configuration.type.id) {
if (result == null) {
result = SmartList()
}
result.add(configuration)
}
}
return result ?: emptyList()
}
override val allConfigurationsList: List<RunConfiguration>
get() = allSettings.mapSmart { it.configuration }
fun getSettings(configuration: RunConfiguration) = allSettings.firstOrNull { it.configuration === configuration } as? RunnerAndConfigurationSettingsImpl
override fun getConfigurationSettingsList(type: ConfigurationType) = allSettings.filterSmart { it.type === type }
fun getConfigurationsGroupedByTypeAndFolder(isIncludeUnknown: Boolean): Map<ConfigurationType, Map<String?, List<RunnerAndConfigurationSettings>>> {
val result = LinkedHashMap<ConfigurationType, MutableMap<String?, MutableList<RunnerAndConfigurationSettings>>>()
// use allSettings to return sorted result
for (setting in allSettings) {
val type = setting.type
if (!isIncludeUnknown && type === UnknownConfigurationType.getInstance()) {
continue
}
val folderToConfigurations = result.getOrPut(type) { LinkedHashMap() }
folderToConfigurations.getOrPut(setting.folderName) { SmartList() }.add(setting)
}
return result
}
override fun getConfigurationTemplate(factory: ConfigurationFactory): RunnerAndConfigurationSettingsImpl {
if (!project.isDefault) {
for (provider in RUN_CONFIGURATION_TEMPLATE_PROVIDER_EP.getExtensions(project)) {
provider.getRunConfigurationTemplate(factory, this)?.let {
return it
}
}
}
val key = getFactoryKey(factory)
return lock.read { templateIdToConfiguration.get(key) } ?: lock.write {
templateIdToConfiguration.getOrPut(key) {
val template = createTemplateSettings(factory)
workspaceSchemeManager.addScheme(template)
template
}
}
}
internal fun createTemplateSettings(factory: ConfigurationFactory): RunnerAndConfigurationSettingsImpl {
val configuration = factory.createTemplateConfiguration(project, this)
configuration.isAllowRunningInParallel = factory.singletonPolicy.isAllowRunningInParallel
val template = RunnerAndConfigurationSettingsImpl(this, configuration, isTemplate = true)
if (configuration is UnknownRunConfiguration) {
configuration.isDoNotStore = true
}
configuration.beforeRunTasks = getHardcodedBeforeRunTasks(configuration, factory)
return template
}
private fun deleteRunConfigsFromArbitraryFilesNotWithinProjectContent() {
ReadAction
.nonBlocking(Callable {
lock.read { rcInArbitraryFileManager.findRunConfigsThatAreNotWithinProjectContent() }
})
.coalesceBy(this)
.expireWith(project)
.finishOnUiThread(ModalityState.defaultModalityState()) {
// don't delete file just because it has become excluded
removeConfigurations(it, deleteFileIfStoredInArbitraryFile = false)
}
.submit(AppExecutorUtil.getAppExecutorService())
}
// Paths in <code>deletedFilePaths</code> and <code>updatedFilePaths</code> may be not related to the project, use ProjectIndex.isInContent() when needed
internal fun updateRunConfigsFromArbitraryFiles(deletedFilePaths: Collection<String>, updatedFilePaths: Collection<String>) {
val oldSelectedId = selectedConfigurationId
val deletedRunConfigs = lock.read { rcInArbitraryFileManager.getRunConfigsFromFiles(deletedFilePaths) }
// file is already deleted - no need to delete it once again
removeConfigurations(deletedRunConfigs, deleteFileIfStoredInArbitraryFile = false)
for (filePath in updatedFilePaths) {
val deletedAndAddedRunConfigs = lock.read { rcInArbitraryFileManager.loadChangedRunConfigsFromFile(this, filePath) }
for (runConfig in deletedAndAddedRunConfigs.addedRunConfigs) {
addConfiguration(runConfig)
if (runConfig.isTemplate) continue
if (!StartupManager.getInstance(project).postStartupActivityPassed()) {
// Empty string means that there's no information about initially selected RC in workspace.xml => IDE should select any.
if (!selectedRCSetupScheduled && (notYetAppliedInitialSelectedConfigurationId == runConfig.uniqueID ||
notYetAppliedInitialSelectedConfigurationId == "" && runConfig.type.isManaged)) {
selectedRCSetupScheduled = true
// Project is being loaded. Finally we can set the right RC as 'selected' in the RC combo box.
// Need to set selectedConfiguration in EDT to avoid deadlock with ExecutionTargetManagerImpl or similar implementations of runConfigurationSelected()
StartupManager.getInstance(project).runAfterOpened {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, project.disposed, Runnable {
// Empty string means that there's no information about initially selected RC in workspace.xml
// => IDE should select any if still none selected (CLion could have set the selected RC itself).
if (selectedConfiguration == null || notYetAppliedInitialSelectedConfigurationId != "") {
selectedConfiguration = runConfig
}
notYetAppliedInitialSelectedConfigurationId = null
})
}
}
}
else if (selectedConfigurationId == null && runConfig.uniqueID == oldSelectedId) {
// don't loose currently selected RC in case of any external changes in the file
selectedConfigurationId = oldSelectedId
}
}
// some VFS event caused RC to disappear (probably manual editing) - but the file itself shouldn't be deleted
removeConfigurations(deletedAndAddedRunConfigs.deletedRunConfigs, deleteFileIfStoredInArbitraryFile = false)
}
}
override fun addConfiguration(settings: RunnerAndConfigurationSettings) {
doAddConfiguration(settings as RunnerAndConfigurationSettingsImpl, isCheckRecentsLimit = true)
}
private fun doAddConfiguration(settings: RunnerAndConfigurationSettingsImpl, isCheckRecentsLimit: Boolean) {
if (settings.isTemplate) {
addOrUpdateTemplateConfiguration(settings)
return
}
val newId = settings.uniqueID
var existingId: String?
lock.write {
// https://youtrack.jetbrains.com/issue/IDEA-112821
// we should check by instance, not by id (todo is it still relevant?)
existingId = if (idToSettings.get(newId) === settings) newId else findExistingConfigurationId(settings)
existingId?.let {
if (newId != it) {
idToSettings.remove(it)
if (selectedConfigurationId == it) {
selectedConfigurationId = newId
}
listManager.updateConfigurationId(it, newId)
}
}
idToSettings.put(newId, settings)
listManager.requestSort()
if (existingId == null) {
refreshUsagesList(settings)
}
ensureSettingsAreTrackedByCorrectManager(settings, existingId != null)
}
if (existingId == null) {
if (isCheckRecentsLimit && settings.isTemporary) {
checkRecentsLimit()
}
eventPublisher.runConfigurationAdded(settings)
}
else {
eventPublisher.runConfigurationChanged(settings, existingId)
}
}
private fun addOrUpdateTemplateConfiguration(settings: RunnerAndConfigurationSettingsImpl) {
val factory = settings.factory
// do not register unknown RC type templates (it is saved in any case in the scheme manager, so, not lost on save)
if (factory == UnknownConfigurationType.getInstance()) return
lock.write {
val key = getFactoryKey(factory)
val existing = templateIdToConfiguration.put(key, settings)
ensureSettingsAreTrackedByCorrectManager(settings, existing != null)
}
}
private fun ensureSettingsAreTrackedByCorrectManager(settings: RunnerAndConfigurationSettingsImpl,
ensureSettingsAreRemovedFromOtherManagers: Boolean) {
if (ensureSettingsAreRemovedFromOtherManagers) {
// storage could change, need to remove from old storages
when {
settings.isStoredInDotIdeaFolder -> {
rcInArbitraryFileManager.removeRunConfiguration(settings)
workspaceSchemeManager.removeScheme(settings)
}
settings.isStoredInArbitraryFileInProject -> {
// path could change: need to remove and add again
rcInArbitraryFileManager.removeRunConfiguration(settings, removeRunConfigOnlyIfFileNameChanged = true)
projectSchemeManager.removeScheme(settings)
workspaceSchemeManager.removeScheme(settings)
}
else -> {
rcInArbitraryFileManager.removeRunConfiguration(settings)
projectSchemeManager.removeScheme(settings)
}
}
}
// storage could change, need to make sure the RC is added to the corresponding scheme manager (no harm if it's already there)
when {
settings.isStoredInDotIdeaFolder -> projectSchemeManager.addScheme(settings)
settings.isStoredInArbitraryFileInProject -> rcInArbitraryFileManager.addRunConfiguration(settings)
else -> workspaceSchemeManager.addScheme(settings)
}
}
override fun refreshUsagesList(profile: RunProfile) {
if (profile !is RunConfiguration) {
return
}
getSettings(profile)?.let {
refreshUsagesList(it)
}
}
private fun refreshUsagesList(settings: RunnerAndConfigurationSettings) {
if (settings.isTemporary) {
lock.write {
recentlyUsedTemporaries.remove(settings)
recentlyUsedTemporaries.add(0, settings)
trimUsagesListToLimit()
}
}
}
// call only under write lock
private fun trimUsagesListToLimit() {
while (recentlyUsedTemporaries.size > config.recentsLimit) {
recentlyUsedTemporaries.removeAt(recentlyUsedTemporaries.size - 1)
}
}
fun checkRecentsLimit() {
var removed: MutableList<RunnerAndConfigurationSettings>? = null
lock.write {
trimUsagesListToLimit()
var excess = idToSettings.values.count { it.isTemporary } - config.recentsLimit
if (excess <= 0) {
return
}
for (settings in idToSettings.values) {
if (settings.isTemporary && !recentlyUsedTemporaries.contains(settings)) {
if (removed == null) {
removed = SmartList()
}
removed!!.add(settings)
if (--excess <= 0) {
break
}
}
}
}
removed?.let { removeConfigurations(it) }
}
@JvmOverloads
fun setOrder(comparator: Comparator<RunnerAndConfigurationSettings>, isApplyAdditionalSortByTypeAndGroup: Boolean = true) {
lock.write {
listManager.setOrder(comparator, isApplyAdditionalSortByTypeAndGroup)
}
}
override var selectedConfiguration: RunnerAndConfigurationSettings?
get() {
return lock.read {
selectedConfigurationId?.let { idToSettings.get(it) }
}
}
set(value) {
fun isTheSame() = value?.uniqueID == selectedConfigurationId
lock.read {
if (isTheSame()) {
return
}
}
lock.write {
if (isTheSame()) {
return
}
val id = value?.uniqueID
if (id != null && !idToSettings.containsKey(id)) {
LOG.error("$id must be added before selecting")
}
selectedConfigurationId = id
}
eventPublisher.runConfigurationSelected(value)
}
internal fun isFileContainsRunConfiguration(file: VirtualFile): Boolean {
val runConfigs = lock.read { rcInArbitraryFileManager.getRunConfigsFromFiles(listOf(file.path)) }
return runConfigs.isNotEmpty()
}
internal fun selectConfigurationStoredInFile(file: VirtualFile) {
val runConfigs = lock.read { rcInArbitraryFileManager.getRunConfigsFromFiles(listOf(file.path)) }
runConfigs.find { idToSettings.containsKey(it.uniqueID) }?.let { selectedConfiguration = it }
}
fun requestSort() {
lock.write {
listManager.requestSort()
}
}
override val allSettings: List<RunnerAndConfigurationSettings>
get() {
listManager.immutableSortedSettingsList?.let {
return it
}
lock.write {
return listManager.buildImmutableSortedSettingsList()
}
}
override fun getState(): Element {
if (!isFirstLoadState.get()) {
lock.read {
val list = idToSettings.values.toList()
list.forEachManaged {
listManager.checkIfDependenciesAreStable(it.configuration, list)
}
}
}
val element = Element("state")
workspaceSchemeManager.save()
lock.read {
rcInArbitraryFileManager.saveRunConfigs()
workspaceSchemeManagerProvider.writeState(element)
if (idToSettings.size > 1) {
selectedConfiguration?.let {
element.setAttribute(SELECTED_ATTR, it.uniqueID)
}
listManager.writeOrder(element)
}
val recentList = SmartList<String>()
recentlyUsedTemporaries.forEachManaged {
recentList.add(it.uniqueID)
}
if (!recentList.isEmpty()) {
val recent = Element(RECENT)
element.addContent(recent)
val listElement = Element("list")
recent.addContent(listElement)
for (id in recentList) {
listElement.addContent(Element("item").setAttribute("itemvalue", id))
}
}
}
return element
}
fun writeContext(element: Element) {
for (setting in allSettings) {
if (setting.isTemporary) {
element.addContent((setting as RunnerAndConfigurationSettingsImpl).writeScheme())
}
}
selectedConfiguration?.let {
element.setAttribute(SELECTED_ATTR, it.uniqueID)
}
}
fun writeConfigurations(parentNode: Element, settings: Collection<RunnerAndConfigurationSettings>) {
settings.forEach { parentNode.addContent((it as RunnerAndConfigurationSettingsImpl).writeScheme()) }
}
fun writeBeforeRunTasks(configuration: RunConfiguration): Element {
val tasks = configuration.beforeRunTasks
val methodElement = Element(METHOD)
methodElement.setAttribute("v", "2")
for (task in tasks) {
val child = Element(OPTION)
child.setAttribute(NAME_ATTR, task.providerId.toString())
if (task is PersistentStateComponent<*>) {
if (!task.isEnabled) {
child.setAttribute("enabled", "false")
}
serializeStateInto(task, child)
}
else {
@Suppress("DEPRECATION")
task.writeExternal(child)
}
methodElement.addContent(child)
}
return methodElement
}
/**
* used by MPS. Do not use if not approved.
*/
fun reloadSchemes() {
var arbitraryFilePaths: Collection<String>
lock.write {
// not really required, but hot swap friendly - 1) factory is used a key, 2) developer can change some defaults.
templateDifferenceHelper.clearCache()
templateIdToConfiguration.clear()
listManager.idToSettings.clear()
arbitraryFilePaths = rcInArbitraryFileManager.clearAllAndReturnFilePaths()
recentlyUsedTemporaries.clear()
stringIdToBeforeRunProvider.drop()
}
workspaceSchemeManager.reload()
projectSchemeManager.reload()
reloadRunConfigsFromArbitraryFiles(arbitraryFilePaths)
}
private fun reloadRunConfigsFromArbitraryFiles(filePaths: Collection<String>) {
for (filePath in filePaths) {
updateRunConfigsFromArbitraryFiles(emptyList(), filePaths)
}
}
protected open fun addExtensionPointListeners() {
if (ProjectManagerImpl.isLight(project)) {
return
}
ConfigurationType.CONFIGURATION_TYPE_EP.addExtensionPointListener(object : ExtensionPointListener<ConfigurationType> {
override fun extensionAdded(extension: ConfigurationType, pluginDescriptor: PluginDescriptor) {
idToType.drop()
project.stateStore.reloadState(RunManagerImpl::class.java)
}
override fun extensionRemoved(extension: ConfigurationType, pluginDescriptor: PluginDescriptor) {
idToType.drop()
for (settings in idToSettings.values) {
settings as RunnerAndConfigurationSettingsImpl
if (settings.type == extension) {
val configuration = UnknownConfigurationType.getInstance().createTemplateConfiguration(project)
configuration.name = settings.configuration.name
settings.setConfiguration(configuration)
}
}
lock.write {
templateIdToConfiguration.values.removeIf(java.util.function.Predicate { it.type == extension })
}
}
}, this)
ProgramRunner.PROGRAM_RUNNER_EP.addExtensionPointListener(object : ExtensionPointListener<ProgramRunner<*>> {
override fun extensionRemoved(extension: ProgramRunner<*>, pluginDescriptor: PluginDescriptor) {
for (runnerAndConfigurationSettings in allSettings) {
val settingsImpl = runnerAndConfigurationSettings as RunnerAndConfigurationSettingsImpl
settingsImpl.handleRunnerRemoved(extension)
}
}
}, this)
}
override fun noStateLoaded() {
val first = isFirstLoadState.getAndSet(false)
loadSharedRunConfigurations()
runConfigurationFirstLoaded()
eventPublisher.stateLoaded(this, first)
if (first) {
addExtensionPointListeners()
}
}
override fun loadState(parentNode: Element) {
config.migrateToAdvancedSettings()
val oldSelectedConfigurationId: String?
val isFirstLoadState = isFirstLoadState.compareAndSet(true, false)
if (isFirstLoadState) {
oldSelectedConfigurationId = null
}
else {
oldSelectedConfigurationId = selectedConfigurationId
clear(false)
}
val nameGenerator = UniqueNameGenerator()
workspaceSchemeManagerProvider.load(parentNode) { element ->
var schemeKey: String? = element.getAttributeValue("name")
if (schemeKey == "<template>" || schemeKey == null) {
// scheme name must be unique
element.getAttributeValue("type")?.let {
if (schemeKey == null) {
schemeKey = "<template>"
}
schemeKey += ", type: ${it}"
}
}
else if (schemeKey != null) {
val typeId = element.getAttributeValue("type")
if (typeId == null) {
LOG.warn("typeId is null for '${schemeKey}'")
}
schemeKey = "${typeId ?: "unknown"}-${schemeKey}"
}
// in case if broken configuration, do not fail, just generate name
if (schemeKey == null) {
schemeKey = nameGenerator.generateUniqueName("Unnamed")
}
else {
schemeKey = "${schemeKey!!}, factoryName: ${element.getAttributeValue("factoryName", "")}"
nameGenerator.addExistingName(schemeKey!!)
}
schemeKey!!
}
workspaceSchemeManager.reload()
lock.write {
recentlyUsedTemporaries.clear()
val recentListElement = parentNode.getChild(RECENT)?.getChild("list")
if (recentListElement != null) {
for (id in recentListElement.getChildren("item").mapNotNull { it.getAttributeValue("itemvalue") }) {
idToSettings.get(id)?.let {
recentlyUsedTemporaries.add(it)
}
}
}
selectedConfigurationId = parentNode.getAttributeValue(SELECTED_ATTR)
}
if (isFirstLoadState) {
loadSharedRunConfigurations()
}
// apply order after loading shared RC
lock.write {
listManager.readCustomOrder(parentNode)
}
runConfigurationFirstLoaded()
fireBeforeRunTasksUpdated()
if (!isFirstLoadState && oldSelectedConfigurationId != null && oldSelectedConfigurationId != selectedConfigurationId) {
eventPublisher.runConfigurationSelected(selectedConfiguration)
}
eventPublisher.stateLoaded(this, isFirstLoadState)
if (isFirstLoadState) {
addExtensionPointListeners()
}
}
private fun loadSharedRunConfigurations() {
if (schemeManagerIprProvider == null) {
projectSchemeManager.loadSchemes()
}
else {
project.service<IprRunManagerImpl>().lastLoadedState.getAndSet(null)?.let { data ->
schemeManagerIprProvider.load(data)
projectSchemeManager.reload()
}
}
}
private fun runConfigurationFirstLoaded() {
if (project.isDefault) {
return
}
if (selectedConfiguration == null) {
// Empty string means that there's no information about initially selected RC in workspace.xml => IDE should select any.
notYetAppliedInitialSelectedConfigurationId = selectedConfigurationId ?: ""
selectAnyConfiguration()
}
}
private fun selectAnyConfiguration() {
selectedConfiguration = allSettings.firstOrNull { it.type.isManaged }
}
fun readContext(parentNode: Element) {
var selectedConfigurationId = parentNode.getAttributeValue(SELECTED_ATTR)
for (element in parentNode.children) {
val config = loadConfiguration(element, false)
if (selectedConfigurationId == null && element.getAttributeBooleanValue(SELECTED_ATTR)) {
selectedConfigurationId = config.uniqueID
}
}
this.selectedConfigurationId = selectedConfigurationId
eventPublisher.runConfigurationSelected(selectedConfiguration)
}
override fun hasSettings(settings: RunnerAndConfigurationSettings) = lock.read { idToSettings.get(settings.uniqueID) == settings }
private fun findExistingConfigurationId(settings: RunnerAndConfigurationSettings): String? {
for ((key, value) in idToSettings) {
if (value === settings) {
return key
}
}
return null
}
// used by MPS, don't delete
fun clearAll() {
clear(true)
idToType.drop()
}
private fun clear(allConfigurations: Boolean) {
val removedConfigurations = lock.write {
listManager.immutableSortedSettingsList = null
val configurations = if (allConfigurations) {
val configurations = idToSettings.values.toList()
idToSettings.clear()
selectedConfigurationId = null
configurations
}
else {
val configurations = SmartList<RunnerAndConfigurationSettings>()
val iterator = idToSettings.values.iterator()
for (configuration in iterator) {
if (configuration.isTemporary || !configuration.isShared) {
iterator.remove()
configurations.add(configuration)
}
}
selectedConfigurationId?.let {
if (idToSettings.containsKey(it)) {
selectedConfigurationId = null
}
}
configurations
}
templateIdToConfiguration.clear()
recentlyUsedTemporaries.clear()
configurations
}
iconCache.clear()
val eventPublisher = eventPublisher
removedConfigurations.forEach { eventPublisher.runConfigurationRemoved(it) }
}
fun loadConfiguration(element: Element, isStoredInDotIdeaFolder: Boolean): RunnerAndConfigurationSettings {
val settings = RunnerAndConfigurationSettingsImpl(this)
LOG.runAndLogException {
settings.readExternal(element, isStoredInDotIdeaFolder)
}
addConfiguration(element, settings)
return settings
}
internal fun addConfiguration(element: Element, settings: RunnerAndConfigurationSettingsImpl, isCheckRecentsLimit: Boolean = true) {
doAddConfiguration(settings, isCheckRecentsLimit)
if (element.getAttributeBooleanValue(SELECTED_ATTR) && !settings.isTemplate) {
// to support old style
selectedConfiguration = settings
}
}
fun readBeforeRunTasks(element: Element?, settings: RunnerAndConfigurationSettings, configuration: RunConfiguration) {
var result: MutableList<BeforeRunTask<*>>? = null
if (element != null) {
for (methodElement in element.getChildren(OPTION)) {
val key = methodElement.getAttributeValue(NAME_ATTR) ?: continue
val provider = stringIdToBeforeRunProvider.value.getOrPut(key) {
UnknownBeforeRunTaskProvider(key)
}
val beforeRunTask = provider.createTask(configuration) ?: continue
if (beforeRunTask is PersistentStateComponent<*>) {
// for PersistentStateComponent we don't write default value for enabled, so, set it to true explicitly
beforeRunTask.isEnabled = true
deserializeAndLoadState(beforeRunTask, methodElement)
}
else {
@Suppress("DEPRECATION")
beforeRunTask.readExternal(methodElement)
}
if (result == null) {
result = SmartList()
}
result.add(beforeRunTask)
}
}
if (element?.getAttributeValue("v") == null) {
if (settings.isTemplate) {
if (result.isNullOrEmpty()) {
configuration.beforeRunTasks = getHardcodedBeforeRunTasks(configuration, configuration.factory!!)
return
}
}
else {
configuration.beforeRunTasks = getEffectiveBeforeRunTaskList(result ?: emptyList(), getConfigurationTemplate(configuration.factory!!).configuration.beforeRunTasks,
ownIsOnlyEnabled = true, isDisableTemplateTasks = false)
return
}
}
configuration.beforeRunTasks = result ?: emptyList()
}
@JvmOverloads
fun getFactory(
typeId: String?,
factoryId: String?,
checkUnknown: Boolean = false,
): ConfigurationFactory {
return idToType.value[typeId]?.let { getFactory(it, factoryId) }
?: UnknownConfigurationType.getInstance().also {
if (checkUnknown && typeId != null) {
UnknownFeaturesCollector.getInstance(project).registerUnknownFeature(
CONFIGURATION_TYPE_FEATURE_ID,
ExecutionBundle.message("plugins.advertiser.feature.run.configuration"),
typeId,
null
)
}
}
}
fun getFactory(type: ConfigurationType, factoryId: String?): ConfigurationFactory? {
return when (type) {
is UnknownConfigurationType -> type.configurationFactories.firstOrNull()
is SimpleConfigurationType -> type
else -> type.configurationFactories.firstOrNull { factoryId == null || it.id == factoryId }
}
}
override fun setTemporaryConfiguration(tempConfiguration: RunnerAndConfigurationSettings?) {
if (tempConfiguration == null) {
return
}
tempConfiguration.isTemporary = true
addConfiguration(tempConfiguration)
if (shouldSetRunConfigurationFromContext()) {
selectedConfiguration = tempConfiguration
}
}
override val tempConfigurationsList: List<RunnerAndConfigurationSettings>
get() = allSettings.filterSmart { it.isTemporary }
override fun makeStable(settings: RunnerAndConfigurationSettings) {
settings.isTemporary = false
doMakeStable(settings)
fireRunConfigurationChanged(settings)
}
private fun doMakeStable(settings: RunnerAndConfigurationSettings) {
lock.write {
recentlyUsedTemporaries.remove(settings)
listManager.afterMakeStable()
}
}
override fun <T : BeforeRunTask<*>> getBeforeRunTasks(taskProviderId: Key<T>): List<T> {
val tasks = SmartList<T>()
val checkedTemplates = SmartList<RunnerAndConfigurationSettings>()
lock.read {
for (settings in allSettings) {
val configuration = settings.configuration
for (task in getBeforeRunTasks(configuration)) {
if (task.isEnabled && task.providerId === taskProviderId) {
@Suppress("UNCHECKED_CAST")
tasks.add(task as T)
}
else {
val template = getConfigurationTemplate(configuration.factory!!)
if (!checkedTemplates.contains(template)) {
checkedTemplates.add(template)
for (templateTask in getBeforeRunTasks(template.configuration)) {
if (templateTask.isEnabled && templateTask.providerId === taskProviderId) {
@Suppress("UNCHECKED_CAST")
tasks.add(templateTask as T)
}
}
}
}
}
}
}
return tasks
}
override fun getConfigurationIcon(settings: RunnerAndConfigurationSettings, withLiveIndicator: Boolean): Icon {
val uniqueId = settings.uniqueID
if (selectedConfiguration?.uniqueID == uniqueId) {
iconCache.checkValidity(uniqueId)
}
var icon = iconCache.get(uniqueId, settings, project)
if (withLiveIndicator) {
val runningDescriptors = ExecutionManagerImpl.getInstance(project).getRunningDescriptors(Condition { it === settings })
when {
runningDescriptors.size == 1 -> icon = ExecutionUtil.getLiveIndicator(icon)
runningDescriptors.size > 1 -> icon = IconUtil.addText(icon, runningDescriptors.size.toString())
}
}
return icon
}
fun isInvalidInCache(configuration: RunConfiguration): Boolean {
findSettings(configuration)?.let {
return iconCache.isInvalid(it.uniqueID)
}
return false
}
fun getConfigurationById(id: String): RunnerAndConfigurationSettings? = lock.read { idToSettings.get(id) }
override fun findConfigurationByName(name: String?): RunnerAndConfigurationSettings? {
if (name == null) {
return null
}
return allSettings.firstOrNull { it.name == name }
}
override fun findSettings(configuration: RunConfiguration): RunnerAndConfigurationSettings? {
val id = RunnerAndConfigurationSettingsImpl.getUniqueIdFor(configuration)
lock.read {
return idToSettings.get(id)
}
}
override fun isTemplate(configuration: RunConfiguration): Boolean {
lock.read {
return templateIdToConfiguration.values.any { it.configuration === configuration }
}
}
override fun <T : BeforeRunTask<*>> getBeforeRunTasks(settings: RunConfiguration, taskProviderId: Key<T>): List<T> {
if (settings is WrappingRunConfiguration<*>) {
return getBeforeRunTasks(settings.peer, taskProviderId)
}
var result: MutableList<T>? = null
for (task in getBeforeRunTasks(settings)) {
if (task.providerId === taskProviderId) {
if (result == null) {
result = SmartList()
}
@Suppress("UNCHECKED_CAST")
result.add(task as T)
}
}
return result ?: emptyList()
}
override fun getBeforeRunTasks(configuration: RunConfiguration) = doGetBeforeRunTasks(configuration)
fun shareConfiguration(settings: RunnerAndConfigurationSettings, value: Boolean) {
if (settings.isShared == value) {
return
}
if (value && settings.isTemporary) {
doMakeStable(settings)
}
if (value) {
settings.storeInDotIdeaFolder()
}
else {
settings.storeInLocalWorkspace()
}
fireRunConfigurationChanged(settings)
}
override fun setBeforeRunTasks(configuration: RunConfiguration, tasks: List<BeforeRunTask<*>>) {
if (!configuration.type.isManaged) {
return
}
configuration.beforeRunTasks = tasks
fireBeforeRunTasksUpdated()
}
fun fireBeginUpdate() {
eventPublisher.beginUpdate()
}
fun fireEndUpdate() {
eventPublisher.endUpdate()
}
fun fireRunConfigurationChanged(settings: RunnerAndConfigurationSettings) {
eventPublisher.runConfigurationChanged(settings, null)
}
@Suppress("OverridingDeprecatedMember")
override fun addRunManagerListener(listener: RunManagerListener) {
project.messageBus.connect().subscribe(RunManagerListener.TOPIC, listener)
}
fun fireBeforeRunTasksUpdated() {
eventPublisher.beforeRunTasksChanged()
}
override fun removeConfiguration(settings: RunnerAndConfigurationSettings?) {
if (settings != null) {
removeConfigurations(listOf(settings))
}
}
fun removeConfigurations(toRemove: Collection<RunnerAndConfigurationSettings>) = removeConfigurations(toRemove,
deleteFileIfStoredInArbitraryFile = true)
internal fun removeConfigurations(_toRemove: Collection<RunnerAndConfigurationSettings>,
deleteFileIfStoredInArbitraryFile: Boolean = true,
onSchemeManagerDeleteEvent: Boolean = false) {
if (_toRemove.isEmpty()) {
return
}
val changedSettings = SmartList<RunnerAndConfigurationSettings>()
val removed = SmartList<RunnerAndConfigurationSettings>()
var selectedConfigurationWasRemoved = false
lock.write {
val runConfigsToRemove = removeTemplatesAndReturnRemaining(_toRemove, deleteFileIfStoredInArbitraryFile, onSchemeManagerDeleteEvent)
val runConfigsToRemoveButNotYetRemoved = runConfigsToRemove.toMutableList()
listManager.immutableSortedSettingsList = null
val iterator = idToSettings.values.iterator()
for (settings in iterator) {
if (runConfigsToRemove.contains(settings)) {
if (selectedConfigurationId == settings.uniqueID) {
selectedConfigurationWasRemoved = true
}
runConfigsToRemoveButNotYetRemoved.remove(settings)
iterator.remove()
removeSettingsFromCorrespondingManager(settings as RunnerAndConfigurationSettingsImpl, deleteFileIfStoredInArbitraryFile)
recentlyUsedTemporaries.remove(settings)
removed.add(settings)
iconCache.remove(settings.uniqueID)
}
else {
var isChanged = false
val otherConfiguration = settings.configuration
val newList = otherConfiguration.beforeRunTasks.nullize()?.toMutableSmartList() ?: continue
val beforeRunTaskIterator = newList.iterator()
for (task in beforeRunTaskIterator) {
if (task is RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask &&
runConfigsToRemove.firstOrNull { task.isMySettings(it) } != null) {
beforeRunTaskIterator.remove()
isChanged = true
changedSettings.add(settings)
}
}
if (isChanged) {
otherConfiguration.beforeRunTasks = newList
}
}
}
for (settings in runConfigsToRemoveButNotYetRemoved) {
// At this point runConfigsToRemoveButNotYetRemoved contains entries that haven't been there in idToSettings map at all.
// This may happen, for example, if some Run Configuration appears twice or more in a *.run.xml file (e.g. as a merge result).
removeSettingsFromCorrespondingManager(settings as RunnerAndConfigurationSettingsImpl, deleteFileIfStoredInArbitraryFile)
}
}
if (selectedConfigurationWasRemoved) {
selectAnyConfiguration()
}
removed.forEach { eventPublisher.runConfigurationRemoved(it) }
changedSettings.forEach { eventPublisher.runConfigurationChanged(it, null) }
}
private fun removeTemplatesAndReturnRemaining(toRemove: Collection<RunnerAndConfigurationSettings>,
deleteFileIfStoredInArbitraryFile: Boolean,
onSchemeManagerDeleteEvent: Boolean): Collection<RunnerAndConfigurationSettings> {
val result = mutableListOf<RunnerAndConfigurationSettings>()
for (settings in toRemove) {
if (settings.isTemplate) {
templateIdToConfiguration.remove(getFactoryKey(settings.factory))
if (!onSchemeManagerDeleteEvent) {
removeSettingsFromCorrespondingManager(settings as RunnerAndConfigurationSettingsImpl, deleteFileIfStoredInArbitraryFile)
}
}
else {
result.add(settings)
}
}
return result
}
private fun removeSettingsFromCorrespondingManager(settings: RunnerAndConfigurationSettingsImpl,
deleteFileIfStoredInArbitraryFile: Boolean) {
when {
settings.isStoredInDotIdeaFolder -> projectSchemeManager.removeScheme(settings)
settings.isStoredInArbitraryFileInProject -> {
rcInArbitraryFileManager.removeRunConfiguration(settings,
removeRunConfigOnlyIfFileNameChanged = false,
deleteContainingFile = deleteFileIfStoredInArbitraryFile)
}
else -> workspaceSchemeManager.removeScheme(settings)
}
}
@TestOnly
fun getTemplateIdToConfiguration(): Map<String, RunnerAndConfigurationSettingsImpl> {
if (!ApplicationManager.getApplication().isUnitTestMode) {
throw IllegalStateException("test only")
}
return templateIdToConfiguration
}
fun copyTemplatesToProjectFromTemplate(project: Project) {
if (workspaceSchemeManager.isEmpty) {
return
}
val otherRunManager = getInstanceImpl(project)
workspaceSchemeManagerProvider.copyIfNotExists(otherRunManager.workspaceSchemeManagerProvider)
otherRunManager.lock.write {
otherRunManager.templateIdToConfiguration.clear()
}
otherRunManager.workspaceSchemeManager.reload()
}
}
const val PROJECT_RUN_MANAGER_COMPONENT_NAME = "ProjectRunConfigurationManager"
@State(name = PROJECT_RUN_MANAGER_COMPONENT_NAME, useLoadedStateAsExisting = false /* ProjectRunConfigurationManager is used only for IPR, avoid relatively cost call getState */)
internal class IprRunManagerImpl(private val project: Project) : PersistentStateComponent<Element> {
val lastLoadedState = AtomicReference<Element>()
override fun getState(): Element? {
val iprProvider = RunManagerImpl.getInstanceImpl(project).schemeManagerIprProvider ?: return null
val result = Element("state")
iprProvider.writeState(result)
return result
}
override fun loadState(state: Element) {
lastLoadedState.set(state)
}
}
private fun getNameWeight(n1: String) = if (n1.startsWith("<template> of ") || n1.startsWith("_template__ ")) 0 else 1
internal fun doGetBeforeRunTasks(configuration: RunConfiguration): List<BeforeRunTask<*>> {
return when (configuration) {
is WrappingRunConfiguration<*> -> doGetBeforeRunTasks(configuration.peer)
else -> configuration.beforeRunTasks
}
}
internal fun RunConfiguration.cloneBeforeRunTasks() {
beforeRunTasks = doGetBeforeRunTasks(this).mapSmart { it.clone() }
}
fun callNewConfigurationCreated(factory: ConfigurationFactory, configuration: RunConfiguration) {
@Suppress("UNCHECKED_CAST", "DEPRECATION")
(factory as? com.intellij.execution.configuration.ConfigurationFactoryEx<RunConfiguration>)?.onNewConfigurationCreated(configuration)
(configuration as? ConfigurationCreationListener)?.onNewConfigurationCreated()
}
private fun getFactoryKey(factory: ConfigurationFactory): String {
return when (factory.type) {
is SimpleConfigurationType -> factory.type.id
else -> "${factory.type.id}.${factory.id}"
}
}
| apache-2.0 | c3c2d05f7a89e56968ceaa7d4db4d633 | 36.456165 | 185 | 0.697399 | 5.541016 | false | true | false | false |
hzsweers/CatchUp | app/src/main/kotlin/io/sweers/catchup/ui/base/CatchUpItemViewHolder.kt | 1 | 8126 | /*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.ui.base
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.text.format.DateUtils
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import androidx.annotation.ColorInt
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.text.PrecomputedTextCompat
import androidx.core.view.isVisible
import androidx.core.widget.TextViewCompat
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import io.sweers.catchup.R
import io.sweers.catchup.databinding.ListItemGeneralBinding
import io.sweers.catchup.service.api.BindableCatchUpItemViewHolder
import io.sweers.catchup.service.api.CatchUpItem
import io.sweers.catchup.service.api.Mark
import io.sweers.catchup.service.api.TemporaryScopeHolder
import io.sweers.catchup.service.api.temporaryScope
import io.sweers.catchup.util.hide
import io.sweers.catchup.util.kotlin.format
import io.sweers.catchup.util.primaryLocale
import io.sweers.catchup.util.show
import io.sweers.catchup.util.showIf
import kotlinx.datetime.Instant
class CatchUpItemViewHolder(
itemView: View
) : ViewHolder(itemView), BindableCatchUpItemViewHolder, TemporaryScopeHolder by temporaryScope() {
private val binding = ListItemGeneralBinding.bind(itemView)
internal val container = binding.container
internal val tagsContainer = binding.tagsContainer
internal val title = binding.title
internal val description = binding.description
internal val score = binding.score
internal val scoreDivider = binding.scoreDivider
internal val timestamp = binding.timestamp
internal val author = binding.author
internal val authorDivider = binding.authorDivider
internal val source = binding.source
internal val mark = binding.mark
internal val tag = binding.tag
internal val tagDivider = binding.tagDivider
private val markBackground: Drawable = mark.background
private val constraintSet: ConstraintSet = ConstraintSet()
override fun itemView(): View = itemView
override fun tint(@ColorInt color: Int) {
score.setTextColor(color)
tag.setTextColor(color)
scoreDivider.setTextColor(color)
tintMark(color)
}
private fun tintMark(@ColorInt color: Int) {
if (mark.background == null) {
mark.background = markBackground.mutate()
}
DrawableCompat.setTintList(mark.compoundDrawables[1], ColorStateList.valueOf(color))
}
fun setLongClickHandler(longClickHandler: OnLongClickListener?) {
container.setOnLongClickListener(longClickHandler)
}
override fun bind(
item: CatchUpItem,
itemClickHandler: OnClickListener?,
markClickHandler: OnClickListener?,
longClickHandler: OnLongClickListener?
) {
title(item.title.trim())
description(item.description?.trim())
score(item.score)
timestamp(item.timestamp)
author(item.author?.trim())
source(item.source?.trim())
tag(item.tag?.trim())
container.setOnClickListener(itemClickHandler)
setLongClickHandler(longClickHandler)
item.mark?.let { sourceMark ->
mark(sourceMark)
if (markClickHandler != null) {
mark.isClickable = true
mark.isFocusable = true
mark.setOnClickListener(markClickHandler)
} else {
mark.background = null
mark.isClickable = false
mark.isFocusable = false
}
} ?: run { hideMark() }
}
fun title(titleText: CharSequence?) {
title.setTextFuture(
PrecomputedTextCompat.getTextFuture(
titleText ?: "",
TextViewCompat.getTextMetricsParams(title),
null
)
)
}
fun description(titleText: CharSequence?) {
if (titleText != null) {
description.isVisible = true
description.setTextFuture(
PrecomputedTextCompat.getTextFuture(
titleText,
TextViewCompat.getTextMetricsParams(description),
null
)
)
} else {
description.isVisible = false
}
}
fun score(scoreValue: Pair<String, Int>?) {
score.text = scoreValue?.let {
"${scoreValue.first} ${scoreValue.second.toLong().format()}"
}
updateDividerVisibility()
}
fun tag(text: String?) {
tag.text = text?.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(tag.context.primaryLocale) else it.toString()
}
updateDividerVisibility()
}
private fun updateDividerVisibility() {
val numVisible = arrayOf(score, tag, timestamp)
.asSequence()
.map { (it to it.text.isBlank()) }
.onEach { (view, isBlank) ->
if (isBlank) {
view.hide()
} else {
view.show()
}
}
.count { (_, isBlank) -> !isBlank }
tagsContainer showIf (numVisible > 0)
when (numVisible) {
0, 1 -> {
scoreDivider.hide()
tagDivider.hide()
}
2 -> {
when {
timestamp.isVisible -> {
tagDivider.show()
scoreDivider.hide()
}
score.isVisible -> {
scoreDivider.show()
tagDivider.hide()
}
else -> {
tagDivider.show()
scoreDivider.hide()
}
}
}
3 -> {
scoreDivider.show()
tagDivider.show()
}
}
}
fun timestamp(instant: Instant?) = timestamp(instant?.toEpochMilliseconds())
private fun timestamp(date: Long?) {
timestamp.text = date?.let {
DateUtils.getRelativeTimeSpanString(
it,
System.currentTimeMillis(),
0L,
DateUtils.FORMAT_ABBREV_ALL
)
}
updateDividerVisibility()
}
fun author(authorText: CharSequence?) {
author.text = authorText
updateAttributionVisibility()
}
fun source(sourceText: CharSequence?) {
source.text = sourceText
updateAttributionVisibility()
}
private fun updateAttributionVisibility() {
val sourceBlank = source.text.isBlank()
val authorBlank = author.text.isBlank()
with(authorDivider) {
if (sourceBlank || authorBlank) {
hide()
} else {
show()
}
}
if (sourceBlank) {
source.hide()
} else {
source.show()
}
if (authorBlank) {
author.hide()
} else {
author.show()
}
constraintSet.apply {
clone(container)
// Set the vertical bias on the timestamp view since it is the head of the vertical chain.
setVerticalBias(R.id.timestamp, getVerticalBias(sourceBlank, authorBlank))
applyTo(container)
}
}
@SuppressLint("SetTextI18n")
fun mark(sourceMark: Mark) {
mark.show()
sourceMark.text?.let { text ->
val finalText = if (sourceMark.formatTextAsCount) {
text.toLong().format()
} else text
mark.text = "${sourceMark.textPrefix.orEmpty()}$finalText"
}
sourceMark.icon?.let { color ->
mark.setCompoundDrawablesWithIntrinsicBounds(
null,
AppCompatResources.getDrawable(mark.context, color),
null,
null
)
tintMark(sourceMark.iconTintColor ?: score.currentTextColor)
}
}
fun hideMark() = mark.hide()
private fun getVerticalBias(
sourceBlank: Boolean,
authorBlank: Boolean
) = if (sourceBlank && authorBlank) {
0.5f // Center
} else if (sourceBlank) {
0f // Top
} else {
0.5f // Center
}
}
| apache-2.0 | 534153f6acfe6bab0514181c9de18783 | 27.313589 | 99 | 0.678317 | 4.368817 | false | false | false | false |
jcornaz/kable | src/main/kotlin/com/github/jcornaz/kable/impl/BiKeyMap.kt | 2 | 2771 | /**
* Copyright 2017 Jonathan Cornaz
*
* This file is part of Kable.
*
* Kable is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kable 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kable. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.jcornaz.kable.impl
import com.github.jcornaz.kable.Table.Entry
import com.github.jcornaz.kable.util.entry
import com.github.jcornaz.kable.util.toTableEntry
/**
* Implementation of a [com.github.jcornaz.kable.Table] backed with [Map] where keys are row-column pairs
*/
class BiKeyMap<R, C, V>(entries: Iterable<Entry<R, C, V>> = emptyList()) : AbstractTable<R, C, V>() {
/** Map of the values by row-column pairs */
val map: Map<Pair<R, C>, V> = entries.associate { (row, column, value) -> (row to column) to value }
/** Map of maps by rows, then by columns */
val rowsMap: Map<R, Map<C, V>> by lazy {
map.asSequence().groupBy { it.key.first }.mapValues { entry ->
entry.value.associate {
it.key.second to it.value
}
}
}
/** Map of maps by columns, then by rows */
val columnsMap: Map<C, Map<R, V>> by lazy {
map.asSequence().groupBy { it.key.second }.mapValues { entry ->
entry.value.associate {
it.key.first to it.value
}
}
}
override val size by lazy { map.size }
override val rows by lazy { rowsMap.keys }
override val columns by lazy { columnsMap.keys }
override val values by lazy { map.values }
override val entries by lazy { map.asSequence().map { entry(it.key.first, it.key.second, it.value) }.toSet() }
override fun isEmpty(): Boolean = map.isEmpty()
override fun contains(row: R, column: C) = (row to column) in map
override fun containsValue(value: V) = map.containsValue(value)
override fun getRow(row: R) = rowsMap[row] ?: emptyMap()
override fun getColumn(column: C) = columnsMap[column] ?: emptyMap()
override fun get(row: R, column: C) = map[row to column]
override fun iterator() = object : Iterator<Entry<R, C, V>> {
val i = map.iterator()
override fun hasNext() = i.hasNext()
override fun next() = i.next().toTableEntry()
}
override fun toString() = map.toString()
} | lgpl-3.0 | d8b806590324ded8b92bc60d4880ad8b | 34.538462 | 114 | 0.653194 | 3.689747 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/CodeConverter.kt | 4 | 8962 | // 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 org.jetbrains.kotlin.j2k.ast.*
class CodeConverter(
val converter: Converter,
private val expressionConverter: ExpressionConverter,
private val statementConverter: StatementConverter,
val methodReturnType: PsiType?
) {
val typeConverter: TypeConverter = converter.typeConverter
val settings: ConverterSettings = converter.settings
fun withSpecialExpressionConverter(specialConverter: SpecialExpressionConverter): CodeConverter
= CodeConverter(converter, expressionConverter.withSpecialConverter(specialConverter), statementConverter, methodReturnType)
fun withSpecialStatementConverter(specialConverter: SpecialStatementConverter): CodeConverter
= CodeConverter(converter, expressionConverter, statementConverter.withSpecialConverter(specialConverter), methodReturnType)
fun withMethodReturnType(methodReturnType: PsiType?): CodeConverter
= CodeConverter(converter, expressionConverter, statementConverter, methodReturnType)
fun withConverter(converter: Converter): CodeConverter
= CodeConverter(converter, expressionConverter, statementConverter, methodReturnType)
fun convertBlock(block: PsiCodeBlock?, notEmpty: Boolean = true, statementFilter: (PsiStatement) -> Boolean = { true }): Block {
if (block == null) return Block.Empty
val lBrace = LBrace().assignPrototype(block.lBrace)
val rBrace = RBrace().assignPrototype(block.rBrace)
return Block(block.statements.filter(statementFilter).map { convertStatement(it) }, lBrace, rBrace, notEmpty).assignPrototype(block)
}
fun convertStatement(statement: PsiStatement?): Statement {
if (statement == null) return Statement.Empty
return statementConverter.convertStatement(statement, this).assignPrototype(statement)
}
fun convertExpressionsInList(expressions: List<PsiExpression>): List<Expression>
= expressions.map { convertExpression(it).assignPrototype(it, CommentsAndSpacesInheritance.LINE_BREAKS) }
fun convertArgumentList(list: PsiExpressionList): ArgumentList {
return ArgumentList(
convertExpressionsInList(list.expressions.asList()),
LPar.withPrototype(list.lPar()),
RPar.withPrototype(list.rPar())
).assignPrototype(list)
}
fun convertExpression(expression: PsiExpression?, shouldParenthesize: Boolean = false): Expression {
if (expression == null) return Expression.Empty
val converted = expressionConverter.convertExpression(expression, this).assignPrototype(expression)
if (shouldParenthesize) {
return ParenthesizedExpression(converted).assignNoPrototype()
}
return converted
}
fun convertLocalVariable(variable: PsiLocalVariable): LocalVariable {
val isVal = canChangeType(variable)
val type = typeConverter.convertVariableType(variable)
val explicitType = type.takeIf { settings.specifyLocalVariableTypeByDefault || converter.shouldDeclareVariableType(variable, type, isVal) }
return LocalVariable(variable.declarationIdentifier(),
converter.convertAnnotations(variable),
converter.convertModifiers(variable, isMethodInOpenClass = false, isInObject = false),
explicitType,
convertExpression(variable.initializer, variable.type),
isVal).assignPrototype(variable)
}
fun canChangeType(variable: PsiLocalVariable) : Boolean {
return variable.hasModifierProperty(PsiModifier.FINAL) ||
variable.initializer == null/* we do not know actually and prefer val until we have better analysis*/ ||
!variable.hasWriteAccesses(converter.referenceSearcher, variable.getContainingMethod())
}
fun convertExpression(expression: PsiExpression?, expectedType: PsiType?, expectedNullability: Nullability? = null): Expression {
if (expression == null) return Identifier.Empty
var convertedExpression = convertExpression(expression)
if (convertedExpression.isNullable && expectedNullability != null && expectedNullability == Nullability.NotNull) {
convertedExpression = BangBangExpression.surroundIfNullable(convertedExpression)
}
if (expectedType == null || expectedType == PsiType.VOID) return convertedExpression
val actualType = expression.type ?: return convertedExpression
if ((actualType is PsiPrimitiveType && actualType != PsiType.NULL) || actualType is PsiClassType && expectedType is PsiPrimitiveType) {
convertedExpression = BangBangExpression.surroundIfNullable(convertedExpression)
}
if (actualType.needTypeConversion(expectedType)) {
val expectedTypeStr = expectedType.canonicalText
if (expression is PsiLiteralExpression) {
if (actualType.canonicalText == "char" && expression.parent !is PsiExpressionList) {
expression.getTypeConversionMethod(expectedType)?.also {
convertedExpression = MethodCallExpression.buildNonNull(convertedExpression, it)
}
}
else if (expectedTypeStr == "float" || expectedTypeStr == "double") {
var text = convertedExpression.canonicalCode()
if (text.last() in setOf('f', 'L')) {
text = text.substring(0, text.length - 1)
}
if (expectedTypeStr == "float") {
text += "f"
}
if (expectedTypeStr == "double") {
if (!text.contains(".") && !text.contains("e", true)) {
text += ".0"
}
}
convertedExpression = LiteralExpression(text)
}
else if (expectedTypeStr == "long") {
if (expression.parent is PsiBinaryExpression) {
convertedExpression = LiteralExpression("${convertedExpression.canonicalCode()}L")
}
}
else if (expectedTypeStr == "char") {
convertedExpression = MethodCallExpression.buildNonNull(convertedExpression, "toChar")
}
}
else if (expression is PsiPrefixExpression && expression.isLiteralWithSign()) {
val operandConverted = convertExpression(expression.operand, expectedType)
convertedExpression = PrefixExpression(Operator(expression.operationSign.tokenType).assignPrototype(expression.operationSign), operandConverted)
}
else {
val conversion = PRIMITIVE_TYPE_CONVERSIONS[expectedTypeStr]
if (conversion != null) {
convertedExpression = MethodCallExpression.buildNonNull(convertedExpression, conversion)
}
}
}
return convertedExpression.assignPrototype(expression)
}
fun convertedExpressionType(expression: PsiExpression, expectedType: PsiType): Type {
with(converter.codeConverterForType) {
val convertedExpression = convertExpression(expression)
val actualType = expression.type ?: return ErrorType()
var resultType = typeConverter.convertType(actualType, if (convertedExpression.isNullable) Nullability.Nullable else Nullability.NotNull)
if (actualType is PsiPrimitiveType && resultType.isNullable ||
expectedType is PsiPrimitiveType && actualType is PsiClassType) {
resultType = resultType.toNotNullType()
}
if (actualType.needTypeConversion(expectedType)) {
val expectedTypeStr = expectedType.canonicalText
val willConvert = if (convertedExpression is LiteralExpression
|| expression is PsiPrefixExpression && expression.isLiteralWithSign())
expectedTypeStr == "float" || expectedTypeStr == "double"
else
PRIMITIVE_TYPE_CONVERSIONS[expectedTypeStr] != null
if (willConvert) {
resultType = typeConverter.convertType(expectedType, Nullability.NotNull)
}
}
return resultType
}
}
private fun PsiPrefixExpression.isLiteralWithSign()
= operand is PsiLiteralExpression && operationTokenType in setOf(JavaTokenType.PLUS, JavaTokenType.MINUS)
}
| apache-2.0 | af552ab204fc8e86ed15bc8fa02bd527 | 49.067039 | 160 | 0.65231 | 5.950863 | false | false | false | false |
ftomassetti/kolasu | core/src/main/kotlin/com/strumenta/kolasu/codegen/PrinterOutput.kt | 1 | 3770 | package com.strumenta.kolasu.codegen
import com.strumenta.kolasu.model.Node
import com.strumenta.kolasu.model.Position
import com.strumenta.kolasu.model.START_POINT
import com.strumenta.kolasu.model.TextFileDestination
import kotlin.reflect.KClass
/**
* Know how to print a single node type.
*/
fun interface NodePrinter {
fun print(output: PrinterOutput, ast: Node)
}
/**
* This provides a mechanism to generate code tracking indentation, handling lists, and providing other facilities.
* This is used in the implementation of NodePrinter and in ASTCodeGenerator.
*/
class PrinterOutput(private val nodePrinters: Map<KClass<*>, NodePrinter>) {
private val sb = StringBuilder()
private var currentPoint = START_POINT
private var indentationLevel = 0
private var onNewLine = true
private var indentationBlock = " "
private var newLineStr = "\n"
fun text() = sb.toString()
fun println() {
println("")
}
fun println(text: String = "") {
print(text)
sb.append(newLineStr)
currentPoint += newLineStr
onNewLine = true
}
fun printFlag(flag: Boolean, text: String) {
if (flag) {
print(text)
}
}
fun print(text: String) {
var text = text
val needPrintln = text.endsWith("\n")
if (needPrintln) {
text = text.removeSuffix("\n")
}
considerIndentation()
require(text.lines().size < 2) { "Given text span multiple lines: $text" }
sb.append(text)
currentPoint += text
if (needPrintln) {
println()
}
}
fun print(text: Char) {
this.print(text.toString())
}
fun print(value: Int) {
this.print(value.toString())
}
private fun considerIndentation() {
if (onNewLine) {
onNewLine = false
(1..(indentationLevel)).forEach {
print(indentationBlock)
}
}
}
fun print(text: String?, prefix: String = "", postfix: String = "") {
if (text == null) {
return
}
print(prefix)
print(text)
print(postfix)
}
fun print(ast: Node?, prefix: String? = null, postfix: String? = null) {
if (ast == null) {
return
}
prefix?.let { print(it) }
val printer = nodePrinters[ast::class] ?: throw java.lang.IllegalArgumentException("Unable to print $ast")
associate(ast) {
printer.print(this, ast)
}
postfix?.let { print(it) }
}
fun println(ast: Node?, prefix: String = "", postfix: String = "") {
print(ast, prefix, postfix + "\n")
}
fun indent() {
indentationLevel++
}
fun dedent() {
indentationLevel--
}
fun associate(ast: Node, generation: PrinterOutput.() -> Unit) {
val startPoint = currentPoint
generation()
val endPoint = currentPoint
val nodePositionInGeneratedCode = Position(startPoint, endPoint)
ast.destination = TextFileDestination(nodePositionInGeneratedCode)
}
fun <T : Node> printList(elements: List<T>, separator: String = ", ") {
var i = 0
while (i < elements.size) {
if (i != 0) {
print(separator)
}
print(elements[i])
i += 1
}
}
fun <T : Node> printList(
prefix: String,
elements: List<T>,
postfix: String,
printEvenIfEmpty: Boolean = false,
separator: String = ", "
) {
if (elements.isNotEmpty() || printEvenIfEmpty) {
print(prefix)
printList(elements, separator)
print(postfix)
}
}
}
| apache-2.0 | 9f497b0c16de9f4b3e6a3c8674a28430 | 25.549296 | 115 | 0.567109 | 4.279228 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/utils/FirstSettings.kt | 1 | 744 | package lt.markmerkk.utils
import org.slf4j.LoggerFactory
import java.util.*
/**
* Created by mariusmerkevicius on 11/24/15.
* First time launch settings
*/
class FirstSettings : BaseSettings() {
var isFirst = true
private set
override fun propertyPath(): String {
return PROPERTIES_FILE
}
override fun onLoad(properties: Properties) {
val firstProperty = properties.getProperty("first", "true")
isFirst = "false" != firstProperty
}
override fun onSave(properties: Properties) {
properties.put("first", "false")
}
companion object {
var logger = LoggerFactory.getLogger(FirstSettings::class.java)
val PROPERTIES_FILE = "first.properties"
}
}
| apache-2.0 | 8a3bb36fcdfc03ceb68676acb5f9eeb9 | 22.25 | 71 | 0.66129 | 4.376471 | false | false | false | false |
google/accompanist | systemuicontroller/src/main/java/com/google/accompanist/systemuicontroller/SystemUiController.kt | 1 | 11541 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.systemuicontroller
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.os.Build
import android.view.View
import android.view.Window
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.window.DialogWindowProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
/**
* A class which provides easy-to-use utilities for updating the System UI bar
* colors within Jetpack Compose.
*
* @sample com.google.accompanist.sample.systemuicontroller.SystemUiControllerSample
*/
@Stable
interface SystemUiController {
/**
* Control for the behavior of the system bars. This value should be one of the
* [WindowInsetsControllerCompat] behavior constants:
* [WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH],
* [WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE] and
* [WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE].
*/
var systemBarsBehavior: Int
/**
* Property which holds the status bar visibility. If set to true, show the status bar,
* otherwise hide the status bar.
*/
var isStatusBarVisible: Boolean
/**
* Property which holds the navigation bar visibility. If set to true, show the navigation bar,
* otherwise hide the navigation bar.
*/
var isNavigationBarVisible: Boolean
/**
* Property which holds the status & navigation bar visibility. If set to true, show both bars,
* otherwise hide both bars.
*/
var isSystemBarsVisible: Boolean
get() = isNavigationBarVisible && isStatusBarVisible
set(value) {
isStatusBarVisible = value
isNavigationBarVisible = value
}
/**
* Set the status bar color.
*
* @param color The **desired** [Color] to set. This may require modification if running on an
* API level that only supports white status bar icons.
* @param darkIcons Whether dark status bar icons would be preferable.
* @param transformColorForLightContent A lambda which will be invoked to transform [color] if
* dark icons were requested but are not available. Defaults to applying a black scrim.
*
* @see statusBarDarkContentEnabled
*/
fun setStatusBarColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
transformColorForLightContent: (Color) -> Color = BlackScrimmed
)
/**
* Set the navigation bar color.
*
* @param color The **desired** [Color] to set. This may require modification if running on an
* API level that only supports white navigation bar icons. Additionally this will be ignored
* and [Color.Transparent] will be used on API 29+ where gesture navigation is preferred or the
* system UI automatically applies background protection in other navigation modes.
* @param darkIcons Whether dark navigation bar icons would be preferable.
* @param navigationBarContrastEnforced Whether the system should ensure that the navigation
* bar has enough contrast when a fully transparent background is requested. Only supported on
* API 29+.
* @param transformColorForLightContent A lambda which will be invoked to transform [color] if
* dark icons were requested but are not available. Defaults to applying a black scrim.
*
* @see navigationBarDarkContentEnabled
* @see navigationBarContrastEnforced
*/
fun setNavigationBarColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
navigationBarContrastEnforced: Boolean = true,
transformColorForLightContent: (Color) -> Color = BlackScrimmed
)
/**
* Set the status and navigation bars to [color].
*
* @see setStatusBarColor
* @see setNavigationBarColor
*/
fun setSystemBarsColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
isNavigationBarContrastEnforced: Boolean = true,
transformColorForLightContent: (Color) -> Color = BlackScrimmed
) {
setStatusBarColor(color, darkIcons, transformColorForLightContent)
setNavigationBarColor(
color,
darkIcons,
isNavigationBarContrastEnforced,
transformColorForLightContent
)
}
/**
* Property which holds whether the status bar icons + content are 'dark' or not.
*/
var statusBarDarkContentEnabled: Boolean
/**
* Property which holds whether the navigation bar icons + content are 'dark' or not.
*/
var navigationBarDarkContentEnabled: Boolean
/**
* Property which holds whether the status & navigation bar icons + content are 'dark' or not.
*/
var systemBarsDarkContentEnabled: Boolean
get() = statusBarDarkContentEnabled && navigationBarDarkContentEnabled
set(value) {
statusBarDarkContentEnabled = value
navigationBarDarkContentEnabled = value
}
/**
* Property which holds whether the system is ensuring that the navigation bar has enough
* contrast when a fully transparent background is requested. Only has an affect when running
* on Android API 29+ devices.
*/
var isNavigationBarContrastEnforced: Boolean
}
/**
* Remembers a [SystemUiController] for the given [window].
*
* If no [window] is provided, an attempt to find the correct [Window] is made.
*
* First, if the [LocalView]'s parent is a [DialogWindowProvider], then that dialog's [Window] will
* be used.
*
* Second, we attempt to find [Window] for the [Activity] containing the [LocalView].
*
* If none of these are found (such as may happen in a preview), then the functionality of the
* returned [SystemUiController] will be degraded, but won't throw an exception.
*/
@Composable
fun rememberSystemUiController(
window: Window? = findWindow(),
): SystemUiController {
val view = LocalView.current
return remember(view, window) { AndroidSystemUiController(view, window) }
}
@Composable
private fun findWindow(): Window? =
(LocalView.current.parent as? DialogWindowProvider)?.window
?: LocalView.current.context.findWindow()
private tailrec fun Context.findWindow(): Window? =
when (this) {
is Activity -> window
is ContextWrapper -> baseContext.findWindow()
else -> null
}
/**
* A helper class for setting the navigation and status bar colors for a [View], gracefully
* degrading behavior based upon API level.
*
* Typically you would use [rememberSystemUiController] to remember an instance of this.
*/
internal class AndroidSystemUiController(
private val view: View,
private val window: Window?
) : SystemUiController {
private val windowInsetsController = window?.let {
WindowCompat.getInsetsController(it, view)
}
override fun setStatusBarColor(
color: Color,
darkIcons: Boolean,
transformColorForLightContent: (Color) -> Color
) {
statusBarDarkContentEnabled = darkIcons
window?.statusBarColor = when {
darkIcons && windowInsetsController?.isAppearanceLightStatusBars != true -> {
// If we're set to use dark icons, but our windowInsetsController call didn't
// succeed (usually due to API level), we instead transform the color to maintain
// contrast
transformColorForLightContent(color)
}
else -> color
}.toArgb()
}
override fun setNavigationBarColor(
color: Color,
darkIcons: Boolean,
navigationBarContrastEnforced: Boolean,
transformColorForLightContent: (Color) -> Color
) {
navigationBarDarkContentEnabled = darkIcons
isNavigationBarContrastEnforced = navigationBarContrastEnforced
window?.navigationBarColor = when {
darkIcons && windowInsetsController?.isAppearanceLightNavigationBars != true -> {
// If we're set to use dark icons, but our windowInsetsController call didn't
// succeed (usually due to API level), we instead transform the color to maintain
// contrast
transformColorForLightContent(color)
}
else -> color
}.toArgb()
}
override var systemBarsBehavior: Int
get() = windowInsetsController?.systemBarsBehavior ?: 0
set(value) {
windowInsetsController?.systemBarsBehavior = value
}
override var isStatusBarVisible: Boolean
get() {
return ViewCompat.getRootWindowInsets(view)
?.isVisible(WindowInsetsCompat.Type.statusBars()) == true
}
set(value) {
if (value) {
windowInsetsController?.show(WindowInsetsCompat.Type.statusBars())
} else {
windowInsetsController?.hide(WindowInsetsCompat.Type.statusBars())
}
}
override var isNavigationBarVisible: Boolean
get() {
return ViewCompat.getRootWindowInsets(view)
?.isVisible(WindowInsetsCompat.Type.navigationBars()) == true
}
set(value) {
if (value) {
windowInsetsController?.show(WindowInsetsCompat.Type.navigationBars())
} else {
windowInsetsController?.hide(WindowInsetsCompat.Type.navigationBars())
}
}
override var statusBarDarkContentEnabled: Boolean
get() = windowInsetsController?.isAppearanceLightStatusBars == true
set(value) {
windowInsetsController?.isAppearanceLightStatusBars = value
}
override var navigationBarDarkContentEnabled: Boolean
get() = windowInsetsController?.isAppearanceLightNavigationBars == true
set(value) {
windowInsetsController?.isAppearanceLightNavigationBars = value
}
override var isNavigationBarContrastEnforced: Boolean
get() = Build.VERSION.SDK_INT >= 29 && window?.isNavigationBarContrastEnforced == true
set(value) {
if (Build.VERSION.SDK_INT >= 29) {
window?.isNavigationBarContrastEnforced = value
}
}
}
private val BlackScrim = Color(0f, 0f, 0f, 0.3f) // 30% opaque black
private val BlackScrimmed: (Color) -> Color = { original ->
BlackScrim.compositeOver(original)
}
| apache-2.0 | abfd3cea60805d531c83648adb1dd19b | 36.109325 | 99 | 0.68391 | 4.996104 | false | false | false | false |
cfieber/orca | orca-keel/src/main/kotlin/com/netflix/spinnaker/orca/keel/task/DeleteIntentTask.kt | 1 | 1990 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.keel.task
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.KeelService
import com.netflix.spinnaker.orca.RetryableTask
import com.netflix.spinnaker.orca.TaskResult
import com.netflix.spinnaker.orca.pipeline.model.Stage
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit
@Component
class DeleteIntentTask
@Autowired constructor(
private val keelService: KeelService
) : RetryableTask {
private val log = LoggerFactory.getLogger(javaClass)
override fun execute(stage: Stage) : TaskResult {
if (!stage.context.containsKey("intentId")) {
throw IllegalArgumentException("Missing required task parameter (intentId)")
}
val intentId = stage.context["intentId"].toString()
val status = stage.context["status"]?.toString()
val response = keelService.deleteIntents(intentId, status)
val outputs = mapOf("intent.id" to intentId)
return TaskResult(
if (response.status == HttpStatus.NO_CONTENT.value()) ExecutionStatus.SUCCEEDED else ExecutionStatus.TERMINAL,
outputs
)
}
override fun getBackoffPeriod() = TimeUnit.SECONDS.toMillis(15)
override fun getTimeout() = TimeUnit.MINUTES.toMillis(1)
}
| apache-2.0 | ea940e78b0ee2a952b5cfac06f5d42e7 | 32.728814 | 116 | 0.766834 | 4.234043 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinModuleType.kt | 1 | 814 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import javax.swing.Icon
object MixinModuleType : AbstractModuleType<MixinModule>("org.spongepowered", "mixin") {
const val ID = "MIXIN_MODULE_TYPE"
override val platformType = PlatformType.MIXIN
override val icon: Icon? = null
override val id = ID
override val ignoredAnnotations = emptyList<String>()
override val listenerAnnotations = emptyList<String>()
override val hasIcon = false
override fun generateModule(facet: MinecraftFacet) = MixinModule(facet)
}
| mit | b7812d385646e13d87075d6b70998be2 | 26.133333 | 88 | 0.751843 | 4.284211 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantReturnLabelInspection.kt | 1 | 1479 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.quickfix.RemoveReturnLabelFix
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.returnExpressionVisitor
class RedundantReturnLabelInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = returnExpressionVisitor(
fun(returnExpression) {
val label = returnExpression.getTargetLabel() ?: return
val function = returnExpression.getParentOfType<KtNamedFunction>(true, KtLambdaExpression::class.java) ?: return
if (function.name == null) return
val labelName = label.getReferencedName()
holder.registerProblem(
label,
KotlinBundle.message("redundant.0", labelName),
IntentionWrapper(RemoveReturnLabelFix(returnExpression, labelName)),
)
},
)
}
| apache-2.0 | fb2215f0fec0c6b3ff33a3ff2f84bba1 | 48.3 | 124 | 0.761325 | 5.33935 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/MarkdownTokenTypes.kt | 1 | 4228 | package org.intellij.markdown
public open class MarkdownTokenTypes {
companion object {
@JvmField
public val TEXT: IElementType = MarkdownElementType("TEXT", true)
@JvmField
public val CODE_LINE: IElementType = MarkdownElementType("CODE_LINE", true)
@JvmField
public val BLOCK_QUOTE: IElementType = MarkdownElementType("BLOCK_QUOTE", true)
@JvmField
public val HTML_BLOCK_CONTENT: IElementType = MarkdownElementType("HTML_BLOCK_CONTENT", true)
@JvmField
public val SINGLE_QUOTE: IElementType = MarkdownElementType("'", true)
@JvmField
public val DOUBLE_QUOTE: IElementType = MarkdownElementType("\"", true)
@JvmField
public val LPAREN: IElementType = MarkdownElementType("(", true)
@JvmField
public val RPAREN: IElementType = MarkdownElementType(")", true)
@JvmField
public val LBRACKET: IElementType = MarkdownElementType("[", true)
@JvmField
public val RBRACKET: IElementType = MarkdownElementType("]", true)
@JvmField
public val LT: IElementType = MarkdownElementType("<", true)
@JvmField
public val GT: IElementType = MarkdownElementType(">", true)
@JvmField
public val COLON: IElementType = MarkdownElementType(":", true)
@JvmField
public val EXCLAMATION_MARK: IElementType = MarkdownElementType("!", true)
@JvmField
public val HARD_LINE_BREAK: IElementType = MarkdownElementType("BR", true)
@JvmField
public val EOL: IElementType = MarkdownElementType("EOL", true)
@JvmField
public val LINK_ID: IElementType = MarkdownElementType("LINK_ID", true)
@JvmField
public val ATX_HEADER: IElementType = MarkdownElementType("ATX_HEADER", true)
@JvmField
public val ATX_CONTENT: IElementType = MarkdownElementType("ATX_CONTENT", true)
@JvmField
public val SETEXT_1: IElementType = MarkdownElementType("SETEXT_1", true)
@JvmField
public val SETEXT_2: IElementType = MarkdownElementType("SETEXT_2", true)
@JvmField
public val SETEXT_CONTENT: IElementType = MarkdownElementType("SETEXT_CONTENT", true)
@JvmField
public val EMPH: IElementType = MarkdownElementType("EMPH", true)
@JvmField
public val BACKTICK: IElementType = MarkdownElementType("BACKTICK", true)
@JvmField
public val ESCAPED_BACKTICKS: IElementType = MarkdownElementType("ESCAPED_BACKTICKS", true)
@JvmField
public val LIST_BULLET: IElementType = MarkdownElementType("LIST_BULLET", true)
@JvmField
public val URL: IElementType = MarkdownElementType("URL", true)
@JvmField
public val HORIZONTAL_RULE: IElementType = MarkdownElementType("HORIZONTAL_RULE", true)
@JvmField
public val LIST_NUMBER: IElementType = MarkdownElementType("LIST_NUMBER", true)
@JvmField
public val FENCE_LANG: IElementType = MarkdownElementType("FENCE_LANG", true)
@JvmField
public val CODE_FENCE_START: IElementType = MarkdownElementType("CODE_FENCE_START", true)
@JvmField
public val CODE_FENCE_CONTENT: IElementType = MarkdownElementType("CODE_FENCE_CONTENT", true)
@JvmField
public val CODE_FENCE_END: IElementType = MarkdownElementType("CODE_FENCE_END", true)
@JvmField
public val LINK_TITLE: IElementType = MarkdownElementType("LINK_TITLE", true)
@JvmField
public val AUTOLINK: IElementType = MarkdownElementType("AUTOLINK", true)
@JvmField
public val EMAIL_AUTOLINK: IElementType = MarkdownElementType("EMAIL_AUTOLINK", true)
@JvmField
public val HTML_TAG: IElementType = MarkdownElementType("HTML_TAG", true)
@JvmField
public val BAD_CHARACTER: IElementType = MarkdownElementType("BAD_CHARACTER", true)
@JvmField
public val WHITE_SPACE: IElementType = object : MarkdownElementType("WHITE_SPACE", true) {
override fun toString(): String {
return "WHITE_SPACE";
}
}
}
}
| apache-2.0 | aaabbeb42099e42ae98eeb80d7943f10 | 32.291339 | 101 | 0.656102 | 5.063473 | false | false | false | false |
paplorinc/intellij-community | java/java-analysis-api/src/com/intellij/lang/jvm/actions/JvmElementActionsFactory.kt | 2 | 2187 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.jvm.actions
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmMethod
import com.intellij.lang.jvm.JvmModifiersOwner
/**
* Extension Point provides language-abstracted code modifications for JVM-based languages.
*
* Each method should return list of code modifications which could be empty.
* If method returns empty list this means that operation on given elements is not supported or not yet implemented for a language.
*
* Every new added method should return empty list by default and then be overridden in implementations for each language if it is possible.
*/
abstract class JvmElementActionsFactory {
open fun createChangeModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> =
createChangeModifierActions(target, MemberRequest.Modifier(request.modifier, request.shouldBePresent()))
@Deprecated(message = "use createChangeModifierActions(JvmModifiersOwner, ChangeModifierRequest)")
open fun createChangeModifierActions(target: JvmModifiersOwner, request: MemberRequest.Modifier): List<IntentionAction> = emptyList()
open fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> = emptyList()
@Deprecated(message = "use createAddMethodActions with proper request")
open fun createAddPropertyActions(targetClass: JvmClass, request: MemberRequest.Property): List<IntentionAction> = emptyList()
open fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> = emptyList()
open fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> = emptyList()
open fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> = emptyList()
open fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> = emptyList()
}
| apache-2.0 | 42f7476256d165545b57b7ff597a8815 | 56.552632 | 140 | 0.815272 | 5.074246 | false | false | false | false |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/project/convertModuleGroupsToQualifiedNames.kt | 4 | 9212 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.project
import com.intellij.CommonBundle
import com.intellij.application.runInAllowSaveMode
import com.intellij.codeInsight.intention.IntentionManager
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionProfileWrapper
import com.intellij.codeInspection.ex.InspectionToolWrapper
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper
import com.intellij.lang.StdLanguages
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LineExtensionInfo
import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModulePointerManager
import com.intellij.openapi.module.impl.ModulePointerManagerImpl
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.*
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import java.awt.Color
import java.awt.Font
import java.util.function.Function
import java.util.function.Supplier
import javax.swing.Action
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JPanel
class ConvertModuleGroupsToQualifiedNamesDialog(val project: Project) : DialogWrapper(project) {
private val editorArea: EditorTextField
private val document: Document
get() = editorArea.document
private lateinit var modules: List<Module>
private val recordPreviousNamesCheckBox: JCheckBox
private var modified = false
init {
title = ProjectBundle.message("convert.module.groups.dialog.title")
isModal = false
setOKButtonText(ProjectBundle.message("convert.module.groups.button.text"))
editorArea = EditorTextFieldProvider.getInstance().getEditorField(StdLanguages.TEXT, project, listOf(EditorCustomization {
it.settings.apply {
isLineNumbersShown = false
isLineMarkerAreaShown = false
isFoldingOutlineShown = false
isRightMarginShown = false
additionalLinesCount = 0
additionalColumnsCount = 0
isAdditionalPageAtBottom = false
isShowIntentionBulb = false
}
(it as? EditorImpl)?.registerLineExtensionPainter(this::generateLineExtension)
setupHighlighting(it)
}, MonospaceEditorCustomization.getInstance()))
document.addDocumentListener(object: DocumentListener {
override fun documentChanged(event: DocumentEvent) {
modified = true
}
}, disposable)
recordPreviousNamesCheckBox = JCheckBox(ProjectBundle.message("convert.module.groups.record.previous.names.text"), true)
importRenamingScheme(emptyMap())
init()
}
private fun setupHighlighting(editor: Editor) {
editor.putUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY, false)
val inspections = Supplier<List<InspectionToolWrapper<*, *>>> {
listOf(LocalInspectionToolWrapper(ModuleNamesListInspection()))
}
val file = PsiDocumentManager.getInstance(project).getPsiFile(document)
file?.putUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY, Function {
val profile = InspectionProfileImpl("Module names", inspections, null)
for (spellCheckingToolName in SpellCheckingEditorCustomizationProvider.getInstance().spellCheckingToolNames) {
profile.getToolsOrNull(spellCheckingToolName, project)?.isEnabled = false
}
InspectionProfileWrapper(profile)
})
}
override fun createCenterPanel(): JPanel {
val text = XmlStringUtil.wrapInHtml(ProjectBundle.message("convert.module.groups.description.text"))
val recordPreviousNames = com.intellij.util.ui.UI.PanelFactory.panel(recordPreviousNamesCheckBox)
.withTooltip(ProjectBundle.message("convert.module.groups.record.previous.names.tooltip",
ApplicationNamesInfo.getInstance().fullProductName)).createPanel()
return JBUI.Panels.simplePanel(0, UIUtil.DEFAULT_VGAP)
.addToCenter(editorArea)
.addToTop(JBLabel(text))
.addToBottom(recordPreviousNames)
}
override fun getPreferredFocusedComponent(): JComponent = editorArea.focusTarget
private fun generateLineExtension(line: Int): Collection<LineExtensionInfo> {
val lineText = document.charsSequence.subSequence(document.getLineStartOffset(line), document.getLineEndOffset(line)).toString()
if (line !in modules.indices || modules[line].name == lineText) return emptyList()
val name = LineExtensionInfo(" <- ${modules[line].name}", JBColor.GRAY, null, null, Font.PLAIN)
val groupPath = ModuleManager.getInstance(project).getModuleGroupPath(modules[line])
if (groupPath == null) {
return listOf(name)
}
val group = LineExtensionInfo(groupPath.joinToString(separator = "/", prefix = " (", postfix = ")"), Color.GRAY, null, null, Font.PLAIN)
return listOf(name, group)
}
fun importRenamingScheme(renamingScheme: Map<String, String>) {
val moduleManager = ModuleManager.getInstance(project)
fun getDefaultName(module: Module) = (moduleManager.getModuleGroupPath(module)?.let { it.joinToString(".") + "." } ?: "") + module.name
val names = moduleManager.modules.associateBy({ it }, { renamingScheme.getOrElse(it.name, { getDefaultName(it) }) })
modules = moduleManager.modules.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { names[it]!! }))
runWriteAction {
document.setText(modules.joinToString("\n") { names[it]!! })
}
modified = false
}
fun getRenamingScheme(): Map<String, String> {
val lines = document.charsSequence.split('\n')
return modules.withIndex().filter { lines[it.index] != it.value.name }.associateByTo(LinkedHashMap(), { it.value.name }, {
if (it.index in lines.indices) lines[it.index] else it.value.name
})
}
override fun doCancelAction() {
if (modified) {
val answer = Messages.showYesNoCancelDialog(project,
ProjectBundle.message("convert.module.groups.do.you.want.to.save.scheme"),
ProjectBundle.message("convert.module.groups.dialog.title"), null)
when (answer) {
Messages.CANCEL -> return
Messages.YES -> {
if (!saveModuleRenamingScheme(this)) {
return
}
}
}
}
super.doCancelAction()
}
override fun doOKAction() {
ModuleNamesListInspection.checkModuleNames(document.charsSequence.lines(), project) { line, message ->
Messages.showErrorDialog(project,
ProjectBundle.message("convert.module.groups.error.at.text", line + 1, StringUtil.decapitalize(message)),
CommonBundle.getErrorTitle())
return
}
val renamingScheme = getRenamingScheme()
if (renamingScheme.isNotEmpty()) {
val model = ModuleManager.getInstance(project).modifiableModel
val byName = modules.associateBy { it.name }
for (entry in renamingScheme) {
model.renameModule(byName[entry.key]!!, entry.value)
}
modules.forEach {
model.setModuleGroupPath(it, null)
}
runInAllowSaveMode(isSaveAllowed = false) {
runWriteAction {
model.commit()
}
if (recordPreviousNamesCheckBox.isSelected) {
(ModulePointerManager.getInstance(project) as ModulePointerManagerImpl).setRenamingScheme(renamingScheme)
}
}
project.save()
}
super.doOKAction()
}
override fun createActions(): Array<Action> {
return arrayOf(okAction, SaveModuleRenamingSchemeAction(this, { modified = false }),
LoadModuleRenamingSchemeAction(this), cancelAction)
}
}
class ConvertModuleGroupsToQualifiedNamesAction : DumbAwareAction(ProjectBundle.message("convert.module.groups.action.text"),
ProjectBundle.message("convert.module.groups.action.description"), null) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
ConvertModuleGroupsToQualifiedNamesDialog(project).show()
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = e.project != null && ModuleManager.getInstance(e.project!!).hasModuleGroups()
}
}
| apache-2.0 | 6c4fdcccaf9525a4a8290fc004bb81ac | 42.658768 | 140 | 0.731763 | 4.731382 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildEntityImpl.kt | 1 | 8820 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildEntityImpl(val dataSource: ChildEntityData) : ChildEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentEntity::class.java, ChildEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val childData: String
get() = dataSource.childData
override val parentEntity: ParentEntity
get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildEntityData?) : ModifiableWorkspaceEntityBase<ChildEntity>(), ChildEntity.Builder {
constructor() : this(ChildEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isChildDataInitialized()) {
error("Field ChildEntity#childData should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field ChildEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field ChildEntity#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildEntity
this.entitySource = dataSource.entitySource
this.childData = dataSource.childData
if (parents != null) {
this.parentEntity = parents.filterIsInstance<ParentEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var childData: String
get() = getEntityData().childData
set(value) {
checkModificationAllowed()
getEntityData().childData = value
changedProperty.add("childData")
}
override var parentEntity: ParentEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as ParentEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): ChildEntityData = result ?: super.getEntityData() as ChildEntityData
override fun getEntityClass(): Class<ChildEntity> = ChildEntity::class.java
}
}
class ChildEntityData : WorkspaceEntityData<ChildEntity>() {
lateinit var childData: String
fun isChildDataInitialized(): Boolean = ::childData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildEntity> {
val modifiable = ChildEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildEntity {
return getCached(snapshot) {
val entity = ChildEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildEntity(childData, entitySource) {
this.parentEntity = parents.filterIsInstance<ParentEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ParentEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildEntityData
if (this.entitySource != other.entitySource) return false
if (this.childData != other.childData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildEntityData
if (this.childData != other.childData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | be56ae9e7d41c38c8adc0fb0126a599c | 34.421687 | 149 | 0.696032 | 5.374771 | false | false | false | false |
Masterzach32/SwagBot | src/main/kotlin/commands/Premium.kt | 1 | 1416 | package xyz.swagbot.commands
import io.facet.chatcommands.*
import io.facet.common.*
import io.facet.common.dsl.*
import xyz.swagbot.*
import xyz.swagbot.util.*
object Premium : ChatCommand(
name = "${EnvVars.BOT_NAME} Premium",
aliases = setOf("premium"),
category = "music",
description = "Learn more about ${EnvVars.BOT_NAME} premium, as well as see premium status in this server."
) {
private val template = baseTemplate.and {
title = "${EnvVars.BOT_NAME} Premium"
description = ""
field {
name = "Volume Control"
value = "Enables you to change the music volume for everyone listening."
}
field {
name = "Custom Playlists"
value = "Import playlists from YouTube, Spotify, and more; They're automatically saved and can be " +
"queued up on demand."
}
field {
name = "Autoplay"
value = "${EnvVars.BOT_NAME} can automatically queue similar music to what you've been listening to " +
"once the queue is empty, so you dont need to worry about adding more songs!"
}
field {
name = "Audio Effects"
value = "Base boost, adjust EQ, and more."
}
}
override fun DSLCommandNode<ChatCommandSource>.register() {
runs {
message.reply(template)
}
}
}
| gpl-2.0 | 2d4c50ba75affd7bfdcd01a84657edb4 | 27.897959 | 115 | 0.588983 | 4.466877 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/schedule/ScheduleTimeHeadersDecoration.kt | 4 | 7959 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.schedule
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.Typeface
import android.text.Layout.Alignment.ALIGN_CENTER
import android.text.SpannableStringBuilder
import android.text.StaticLayout
import android.text.TextPaint
import android.text.style.AbsoluteSizeSpan
import android.text.style.StyleSpan
import android.view.View
import androidx.core.content.res.ResourcesCompat
import androidx.core.content.res.getColorOrThrow
import androidx.core.content.res.getDimensionPixelSizeOrThrow
import androidx.core.content.res.getResourceIdOrThrow
import androidx.core.graphics.withTranslation
import androidx.core.text.inSpans
import androidx.core.view.isEmpty
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.RecyclerView.State
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.model.Session
import com.google.samples.apps.iosched.util.isRtl
import com.google.samples.apps.iosched.util.newStaticLayout
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
import timber.log.Timber
/**
* A [RecyclerView.ItemDecoration] which draws sticky headers for a given list of sessions.
*/
class ScheduleTimeHeadersDecoration(
context: Context,
sessions: List<Session>,
zoneId: ZoneId
) : ItemDecoration() {
private val paint: TextPaint
private val width: Int
private val padding: Int
private val timeTextSize: Int
private val meridiemTextSize: Int
private val timeFormatter = DateTimeFormatter.ofPattern("h:mm")
private val meridiemFormatter = DateTimeFormatter.ofPattern("a")
private val timeTextSizeSpan: AbsoluteSizeSpan
private val meridiemTextSizeSpan: AbsoluteSizeSpan
private val boldSpan = StyleSpan(Typeface.BOLD)
init {
val attrs = context.obtainStyledAttributes(
R.style.Widget_IOSched_TimeHeaders,
R.styleable.TimeHeader
)
paint = TextPaint(ANTI_ALIAS_FLAG).apply {
color = attrs.getColorOrThrow(R.styleable.TimeHeader_android_textColor)
try {
typeface = ResourcesCompat.getFont(
context,
attrs.getResourceIdOrThrow(R.styleable.TimeHeader_android_fontFamily)
)
} catch (_: Exception) {
// ignore
}
}
width = attrs.getDimensionPixelSizeOrThrow(R.styleable.TimeHeader_android_width)
padding = attrs.getDimensionPixelSize(R.styleable.TimeHeader_android_padding, 0)
timeTextSize = attrs.getDimensionPixelSizeOrThrow(R.styleable.TimeHeader_timeTextSize)
meridiemTextSize =
attrs.getDimensionPixelSizeOrThrow(R.styleable.TimeHeader_meridiemTextSize)
attrs.recycle()
timeTextSizeSpan = AbsoluteSizeSpan(timeTextSize)
meridiemTextSizeSpan = AbsoluteSizeSpan(meridiemTextSize)
}
// Get the sessions index:start time and create header layouts for each
private val timeSlots: Map<Int, StaticLayout> =
indexSessionHeaders(sessions, zoneId).map {
it.first to createHeader(it.second)
}.toMap()
/**
* Loop over each child and draw any corresponding headers i.e. items who's position is a key in
* [timeSlots]. We also look back to see if there are any headers _before_ the first header we
* found i.e. which needs to be sticky.
*/
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: State) {
if (timeSlots.isEmpty() || parent.isEmpty()) return
val isRtl = parent.isRtl()
if (isRtl) {
c.save()
c.translate((parent.width - width).toFloat(), 0f)
}
val parentPadding = parent.paddingTop
var earliestPosition = Int.MAX_VALUE
var previousHeaderPosition = -1
var previousHasHeader = false
var earliestChild: View? = null
for (i in parent.childCount - 1 downTo 0) {
val child = parent.getChildAt(i)
if (child == null) {
// This should not be null, but observed null at times.
// Guard against it to avoid crash and log the state.
Timber.w(
"""View is null. Index: $i, childCount: ${parent.childCount},
|RecyclerView.State: $state""".trimMargin()
)
continue
}
if (child.y > parent.height || (child.y + child.height) < 0) {
// Can't see this child
continue
}
val position = parent.getChildAdapterPosition(child)
if (position < 0) {
continue
}
if (position < earliestPosition) {
earliestPosition = position
earliestChild = child
}
val header = timeSlots[position]
if (header != null) {
drawHeader(c, child, parentPadding, header, child.alpha, previousHasHeader)
previousHeaderPosition = position
previousHasHeader = true
} else {
previousHasHeader = false
}
}
if (earliestChild != null && earliestPosition != previousHeaderPosition) {
// This child needs a sicky header
findHeaderBeforePosition(earliestPosition)?.let { stickyHeader ->
previousHasHeader = previousHeaderPosition - earliestPosition == 1
drawHeader(c, earliestChild, parentPadding, stickyHeader, 1f, previousHasHeader)
}
}
if (isRtl) {
c.restore()
}
}
private fun findHeaderBeforePosition(position: Int): StaticLayout? {
for (headerPos in timeSlots.keys.reversed()) {
if (headerPos < position) {
return timeSlots[headerPos]
}
}
return null
}
private fun drawHeader(
canvas: Canvas,
child: View,
parentPadding: Int,
header: StaticLayout,
headerAlpha: Float,
previousHasHeader: Boolean
) {
val childTop = child.y.toInt()
val childBottom = childTop + child.height
var top = (childTop + padding).coerceAtLeast(parentPadding)
if (previousHasHeader) {
top = top.coerceAtMost(childBottom - header.height - padding)
}
paint.alpha = (headerAlpha * 255).toInt()
canvas.withTranslation(y = top.toFloat()) {
header.draw(canvas)
}
}
/**
* Create a header layout for the given [startTime].
*/
private fun createHeader(startTime: ZonedDateTime): StaticLayout {
val text = SpannableStringBuilder().apply {
inSpans(timeTextSizeSpan) {
append(timeFormatter.format(startTime))
}
append(System.lineSeparator())
inSpans(meridiemTextSizeSpan, boldSpan) {
append(meridiemFormatter.format(startTime).toUpperCase())
}
}
return newStaticLayout(text, paint, width, ALIGN_CENTER, 1f, 0f, false)
}
}
| apache-2.0 | 88867388505446044c2d3dc5e195e563 | 35.847222 | 100 | 0.648951 | 4.690041 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/soundsystem/BeadsMusic.kt | 2 | 1920 | package io.github.chrislo27.rhre3.soundsystem
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.utils.Disposable
import net.beadsproject.beads.ugens.SamplePlayer
class BeadsMusic(val audio: BeadsAudio) : Disposable {
val player: GainedSamplePlayer = GainedSamplePlayer(
SamplePlayer(BeadsSoundSystem.audioContext, audio.sample).apply {
killOnEnd = false
pause(true)
}) {}.apply {
addToContext()
}
private val startOfSound: Float = run {
val sample = audio.sample
val array = FloatArray(sample.numChannels) { 0f }
for (i in 0 until sample.numFrames) {
sample.getFrame(i.toInt(), array)
if (array.any { !MathUtils.isEqual(it, 0f, 0.0005f) }) {
return@run sample.samplesToMs(i.toDouble()).toFloat() / 1000f
}
}
-1f
}
fun getStartOfSound(): Float {
return startOfSound
}
fun play() {
player.addToContext()
player.player.start()
}
fun stop() {
player.player.pause(true)
player.player.reset()
}
fun pause() {
player.player.pause(true)
}
fun getPosition(): Float {
return player.player.position.toFloat() / 1000
}
fun setPosition(seconds: Float) {
player.player.position = seconds.toDouble() * 1000
}
fun getVolume(): Float {
return player.gain.gain
}
fun setVolume(vol: Float) {
player.gain.gain = vol.coerceAtLeast(0f)
}
fun getPitch(): Float {
return player.pitch.value
}
fun setPitch(pitch: Float) {
player.pitch.value = pitch
}
override fun dispose() {
// player.player.pause(true)
// player.player.kill()
}
fun isPlaying(): Boolean {
return !player.player.isPaused
}
fun update(delta: Float) {
}
} | gpl-3.0 | 30fe670e71a7dcb295b63f135830e313 | 22.426829 | 77 | 0.585938 | 4 | false | false | false | false |
ursjoss/sipamato | public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/paper/browse/PublicPaperDetailPage.kt | 1 | 7904 | package ch.difty.scipamato.publ.web.paper.browse
import ch.difty.scipamato.common.web.LABEL_RESOURCE_TAG
import ch.difty.scipamato.common.web.LABEL_TAG
import ch.difty.scipamato.common.web.TITLE_RESOURCE_TAG
import ch.difty.scipamato.publ.entity.PublicPaper
import ch.difty.scipamato.publ.persistence.api.PublicPaperService
import ch.difty.scipamato.publ.web.PublicPageParameters
import ch.difty.scipamato.publ.web.common.BasePage
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapButton
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapExternalLink
import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons
import de.agilecoders.wicket.core.markup.html.bootstrap.image.GlyphIconType
import org.apache.wicket.AttributeModifier
import org.apache.wicket.PageReference
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.model.IModel
import org.apache.wicket.model.Model
import org.apache.wicket.model.PropertyModel
import org.apache.wicket.model.StringResourceModel
import org.apache.wicket.request.mapper.parameter.PageParameters
import org.apache.wicket.spring.injection.annot.SpringBean
import org.wicketstuff.annotation.mount.MountPath
import kotlin.reflect.KProperty1
@Suppress("SameParameterValue")
@MountPath("/paper/number/\${number}")
class PublicPaperDetailPage : BasePage<PublicPaper> {
@SpringBean
private lateinit var publicPaperService: PublicPaperService
private val callingPageRef: PageReference?
private val showBackButton: Boolean
/**
* Loads the page with the record specified by the 'id' passed in via
* PageParameters. If the parameter 'no' contains a valid business key number
* instead, the page will be loaded by number.
*
* @JvmOverloads required for using the path via mount path
*/
@JvmOverloads
constructor(
parameters: PageParameters,
callingPageRef: PageReference? = null,
showBackButton: Boolean = true,
) : super(parameters) {
this.callingPageRef = callingPageRef
this.showBackButton = showBackButton
parameters.tryLoadingRecordFromNumber()
}
internal constructor(
paperModel: IModel<PublicPaper>?,
callingPageRef: PageReference?,
showBackButton: Boolean = true,
) : super(paperModel) {
this.callingPageRef = callingPageRef
this.showBackButton = showBackButton
}
private fun PageParameters.tryLoadingRecordFromNumber() {
val number = this[PublicPageParameters.NUMBER.parameterName].toLong(0L)
if (number > 0)
publicPaperService.findByNumber(number)?.let { model = Model.of(it) }
if (model == null || modelObject == null)
warn("Page parameter ${PublicPageParameters.NUMBER.parameterName} was missing or invalid. No paper loaded.")
}
override fun onInitialize() {
super.onInitialize()
queue(Form<Void>("form"))
queue(newNavigationButton("previous", GlyphIconType.stepbackward, paperIdManager::hasPrevious) {
paperIdManager.previous()
paperIdManager.itemWithFocus
})
queue(newNavigationButton("next", GlyphIconType.stepforward, paperIdManager::hasNext) {
paperIdManager.next()
paperIdManager.itemWithFocus
})
queue(newBackButton("back"))
queue(newPubmedLink("pubmed"))
queueTopic(newLabel("caption", model))
PublicPaper::title.asQueuedTopic(label = null)
queueTopic(newLabel("reference"),
PublicPaper::authors.asReadOnlyField(),
PublicPaper::title.asReadOnlyField(id = "title2"),
PublicPaper::location.asReadOnlyField()
)
PublicPaper::goals.asQueuedTopic()
PublicPaper::population.asQueuedTopic()
PublicPaper::methods.asQueuedTopic()
PublicPaper::result.asQueuedTopic()
PublicPaper::comment.asQueuedTopic()
}
private fun <V> KProperty1<PublicPaper, V>.asQueuedTopic(label: String? = name) {
queueTopic(label?.let { newLabel(it) }, asReadOnlyField())
}
private fun newNavigationButton(
id: String,
icon: GlyphIconType,
getEnabled: () -> Boolean,
getId: () -> Long?,
) = object : BootstrapButton(id, Model.of(""), Buttons.Type.Default) {
override fun onSubmit() {
getId()?.let {
pageParameters[PublicPageParameters.NUMBER.parameterName] = it
setResponsePage(PublicPaperDetailPage(pageParameters, callingPageRef))
}
}
override fun onConfigure() {
super.onConfigure()
isEnabled = getEnabled()
}
}.apply<BootstrapButton> {
defaultFormProcessing = false
setIconType(icon)
add(AttributeModifier(AM_TITLE, id.toTitleResourceModel(BUTTON_RESOURCE_PREFIX)))
setType(Buttons.Type.Primary)
}
private fun newBackButton(id: String) = object : BootstrapButton(
id,
StringResourceModel("$BUTTON_RESOURCE_PREFIX$id$LABEL_RESOURCE_TAG"),
Buttons.Type.Default,
) {
override fun onSubmit() {
callingPageRef?.let { pr ->
setResponsePage(pr.page)
} ?: setResponsePage(PublicPage::class.java)
}
}.apply {
isVisible = showBackButton
defaultFormProcessing = false
add(AttributeModifier(AM_TITLE, id.toTitleResourceModel(BUTTON_RESOURCE_PREFIX)))
}
private fun newPubmedLink(id: String): BootstrapExternalLink = if (modelObject != null) {
val pmId = modelObject.pmId
newExternalLink(id, href = "${properties.pubmedBaseUrl}$pmId") { pmId != null }.apply {
setTarget(BootstrapExternalLink.Target.blank)
setLabel(id.toLabelResourceModel(LINK_RESOURCE_PREFIX))
add(AttributeModifier(AM_TITLE, id.toTitleResourceModel(LINK_RESOURCE_PREFIX)))
}
} else newExternalLink(id)
private fun newExternalLink(id: String, href: String = "", getVisibility: () -> Boolean = { false }) =
object : BootstrapExternalLink(id, Model.of(href), Buttons.Type.Default) {
override fun onConfigure() {
super.onConfigure()
isVisible = getVisibility()
}
}
private fun queueTopic(label: Label?, vararg fields: Label) {
fun Label.setVisibleAndQueue(visible: Boolean) {
isVisible = visible
[email protected](this)
}
val show = fields.isEmpty() || fields.mapNotNull { it.defaultModelObject }.isNotEmpty()
for (f in fields) f.setVisibleAndQueue(show)
label?.setVisibleAndQueue(show)
}
private fun newLabel(idPart: String, parameterModel: IModel<*>? = null) = Label(
"$idPart$LABEL_TAG",
StringResourceModel("$idPart$LABEL_RESOURCE_TAG", this@PublicPaperDetailPage, parameterModel).string +
if (parameterModel == null) ":" else "",
)
private fun <V> KProperty1<PublicPaper, V>.asReadOnlyField(id: String = name) =
Label(id, PropertyModel<Any>([email protected], name))
private fun String.toLabelResourceModel(prefix: String) = newStringResourceModel(this, prefix, LABEL_RESOURCE_TAG)
private fun String.toTitleResourceModel(prefix: String) = newStringResourceModel(this, prefix, TITLE_RESOURCE_TAG)
private fun newStringResourceModel(id: String, prefix: String, tag: String) = StringResourceModel(
"$prefix$id$tag", this@PublicPaperDetailPage, null
)
companion object {
private const val serialVersionUID = 1L
private const val LINK_RESOURCE_PREFIX = "link."
private const val BUTTON_RESOURCE_PREFIX = "button."
private const val AM_TITLE = "title"
}
}
| gpl-3.0 | f8cd7b29613ddc35d5571c26faafaaf1 | 39.326531 | 120 | 0.684464 | 4.496018 | false | false | false | false |
DeflatedPickle/Quiver | textviewer/src/main/kotlin/com/deflatedpickle/quiver/textviewer/util/ThemeSerializer.kt | 1 | 1000 | package com.deflatedpickle.quiver.textviewer.util
import com.deflatedpickle.quiver.textviewer.api.Theme
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
@ExperimentalSerializationApi
@Serializer(forClass = Theme::class)
object ThemeSerializer : KSerializer<Theme> {
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor(
serialName = "Theme",
kind = PrimitiveKind.STRING
)
override fun serialize(encoder: Encoder, value: Theme) =
encoder.encodeString(value.id)
override fun deserialize(decoder: Decoder): Theme =
Theme(decoder.decodeString())
} | mit | 514f919b9ceb6a6dc9a5cc6b707e4df4 | 36.074074 | 66 | 0.796 | 5.405405 | false | false | false | false |
75py/TextCounter | app/src/main/java/com/nagopy/android/textcounter/MainActivity.kt | 1 | 5286 | /*
* Copyright 2018 75py
*
* 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.nagopy.android.textcounter
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.app.ShareCompat
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.github.salomonbrys.kodein.android.KodeinAppCompatActivity
import com.github.salomonbrys.kodein.instance
import com.nagopy.android.textcounter.counter.TextCounters
import com.nagopy.android.textcounter.databinding.ActivityMainBinding
import timber.log.Timber
class MainActivity : KodeinAppCompatActivity()
, Ads.RewardAdsExplanationDialogFragment.Listener
, TextCounters.TextCounterLanguageSelectDialogFragment.Listener {
lateinit var binding: ActivityMainBinding
val textCounters: TextCounters by instance()
val ads: Ads by instance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
updateTitle()
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.textCounter = textCounters
ads.onCreate(this, binding.ad)
}
override fun onStart() {
super.onStart()
textCounters.onStart()
}
override fun onResume() {
super.onResume()
ads.onResume()
}
override fun onPause() {
ads.onPause()
super.onPause()
}
override fun onStop() {
textCounters.onStop()
super.onStop()
}
override fun onDestroy() {
super.onDestroy()
ads.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
Timber.d("onCreateOptionsMenu")
menuInflater.inflate(R.menu.activity_main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
Timber.d("onPrepareOptionsMenu() ads.shouldDisplayBannerAds()=%s", ads.shouldDisplayBannerAds())
menu?.findItem(R.id.menu_reward)?.isVisible = ads.shouldDisplayBannerAds()
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
Timber.d("onOptionsItemSelected item?.itemId=%d", item?.itemId)
when (item?.itemId) {
R.id.menu_license -> {
startActivity(Intent(this, LicenseActivity::class.java))
}
R.id.menu_share_text -> {
ShareCompat.IntentBuilder.from(this)
.setSubject(getString(R.string.share_text_subject))
.setText(binding.editText.text.toString())
.setType("text/plain")
.startChooser()
}
R.id.menu_share_result -> {
val resultStr = listOf(
binding.resultChars
, binding.resultWords
, binding.resultSentences
, binding.resultParagraphs
, binding.resultWhitespaces
).filter { it.visibility == View.VISIBLE }
.joinToString(separator = "\n") { it.text }
ShareCompat.IntentBuilder.from(this)
.setSubject(getString(R.string.share_result_subject))
.setText(resultStr)
.setType("text/plain")
.startChooser()
}
R.id.menu_reward -> {
if (ads.shouldDisplayBannerAds()) {
Ads.RewardAdsExplanationDialogFragment
.newInstance()
.show(supportFragmentManager, "RewardAdsExplanationDialogFragment")
}
}
R.id.menu_choose_count_lang -> {
TextCounters.TextCounterLanguageSelectDialogFragment
.newInstance()
.show(supportFragmentManager, "TextCounterLanguageSelectDialogFragment")
}
}
return super.onOptionsItemSelected(item)
}
override fun onRewardAdsStartClicked() {
Timber.d("onRewardAdsStartClicked")
ads.showRewardAds()
}
override fun onTextCounterLanguageChanged() {
Timber.d("onTextCounterLanguageChanged")
invalidateOptionsMenu()
supportInvalidateOptionsMenu()
textCounters.counter = textCounters.getCurrentTextCounter()
textCounters.update()
updateTitle()
}
fun updateTitle() {
title = getString(R.string.app_name_with_count_lang,
resources.getStringArray(R.array.count_lang)[textCounters.getCurrentLangIndex()]
)
}
}
| apache-2.0 | 6d2d31c27e518b18dc975ffdc502d9a8 | 34.24 | 104 | 0.624669 | 5.019943 | false | false | false | false |
ollide/intellij-java2smali | src/main/kotlin/org/ollide/java2smali/GenerateAction.kt | 1 | 1549 | package org.ollide.java2smali
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
class GenerateAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
LOG.debug("Action performed.")
val vFile = getVirtualFileFromEvent(e) ?: return
val project = e.project!!
val module = ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(vFile)!!
DexCompiler(vFile, project, module).run()
}
override fun update(e: AnActionEvent) {
var enabled = false
getVirtualFileFromEvent(e)?.let {
e.project?.let { project ->
val m = ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(it)
val extension = it.fileType.defaultExtension
enabled = (JAVA == extension || KOTLIN == extension) && m != null
}
}
e.presentation.isEnabled = enabled
}
private fun getVirtualFileFromEvent(e: AnActionEvent): VirtualFile? {
val psiFile = e.getData(LangDataKeys.PSI_FILE) ?: return null
return psiFile.virtualFile
}
companion object {
private val LOG = Logger.getInstance(GenerateAction::class.java)
private const val JAVA = "java"
private const val KOTLIN = "kt"
}
}
| mit | bb3c2da176027146f10097744b7ce42b | 31.957447 | 96 | 0.679793 | 4.825545 | false | false | false | false |
stefanosiano/PowerfulImageView | powerfulimageview_rs/src/main/java/com/stefanosiano/powerful_libraries/imageview/progress/drawers/HorizontalIndeterminateProgressDrawer.kt | 2 | 5489 | package com.stefanosiano.powerful_libraries.imageview.progress.drawers
import android.animation.Animator
import android.animation.ValueAnimator
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.view.animation.AccelerateDecelerateInterpolator
import com.stefanosiano.powerful_libraries.imageview.progress.ProgressOptions
/** Default animation duration. */
private const val DEFAULT_ANIMATION_DURATION: Long = 1000
/** ProgressDrawer that shows an indeterminate animated bar as progress indicator. */
internal class HorizontalIndeterminateProgressDrawer : ProgressDrawer {
/** Left bound used to draw the rectangle. */
private var mLeft: Float = 0f
/** Right bound used to draw the rectangle. */
private var mRight: Float = 0f
/** Paint used to draw the rectangle. */
private var mProgressPaint: Paint = Paint()
/** Animator that transforms the x coordinates used to draw the progress. */
private var mProgressAnimator: ValueAnimator = ValueAnimator.ofFloat(0f, 1f)
/** Start x coordinate of the rectangle. */
private var mStartX: Float = 0f
/** End x coordinate of the rectangle. */
private var mEndX: Float = 0f
/** Whether the progress is shrinking or expanding. Used to adjust behaviour during animation. */
private var isShrinking: Boolean = false
/** Whether to reverse the progress. */
private var mIsProgressReversed: Boolean = false
/** Custom animation duration. If it's less then 0, default duration is used. */
private var mProgressAnimationDuration: Long = -1
/** Listener to handle things from the drawer. */
private var listener: ProgressDrawerManager.ProgressDrawerListener? = null
init {
mProgressAnimator.duration =
if (mProgressAnimationDuration < 0) DEFAULT_ANIMATION_DURATION else mProgressAnimationDuration
mProgressAnimator.interpolator = AccelerateDecelerateInterpolator()
mProgressAnimator.repeatCount = ValueAnimator.INFINITE
mProgressAnimator.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {}
override fun onAnimationEnd(animation: Animator) {}
override fun onAnimationCancel(animation: Animator) {}
override fun onAnimationRepeat(animation: Animator) { isShrinking = !isShrinking }
})
// Using animation.getAnimatedFraction() because animation.getAnimatedValue() leaks memory
mProgressAnimator.addUpdateListener { setProgressValues(mLeft + (mRight - mLeft) * it.animatedFraction) }
}
override fun setProgressPercent(progressPercent: Float) {}
override fun setAnimationEnabled(enabled: Boolean) {}
override fun setup(progressOptions: ProgressOptions) {
mProgressPaint.color = progressOptions.indeterminateColor
mProgressPaint.style = Paint.Style.FILL_AND_STROKE
mLeft = progressOptions.rect.left
mRight = progressOptions.rect.right
setProgressValues(if (isShrinking) mStartX else mEndX)
mIsProgressReversed = progressOptions.isProgressReversed
val optionAnimationDuration = progressOptions.animationDuration.toLong()
mProgressAnimationDuration =
if (optionAnimationDuration < 0) DEFAULT_ANIMATION_DURATION else optionAnimationDuration
if (mProgressAnimator.duration != mProgressAnimationDuration) {
mProgressAnimator.duration = mProgressAnimationDuration
if (mProgressAnimator.isRunning) {
mProgressAnimator.cancel()
mProgressAnimator.start()
}
}
}
/** Set the x coordinate of the rectangle that will be drawn.
* [currentX] is used when progress is shrinking (as start) or expanding (as end).
*/
private fun setProgressValues(currentX: Float) {
if (isShrinking) {
this.mStartX = currentX
this.mEndX = mRight
} else {
this.mStartX = mLeft
this.mEndX = currentX
}
listener?.onRequestInvalidate()
}
override fun startIndeterminateAnimation() {
this.mProgressAnimator.cancel()
this.isShrinking = false
setProgressValues(mLeft)
mProgressAnimator.start()
}
override fun draw(canvas: Canvas, progressBounds: RectF) {
if (!mIsProgressReversed) {
canvas.drawRect(mStartX, progressBounds.top, mEndX, progressBounds.bottom, mProgressPaint)
} else {
canvas.drawRect(
progressBounds.right - mEndX,
progressBounds.top,
progressBounds.right + progressBounds.left - mStartX,
progressBounds.bottom,
mProgressPaint
)
}
}
override fun stopIndeterminateAnimation() {
mProgressAnimator.cancel()
}
override fun setAnimationDuration(millis: Long) {
mProgressAnimationDuration = if (millis < 0) DEFAULT_ANIMATION_DURATION else millis
if (mProgressAnimator.duration != mProgressAnimationDuration) {
mProgressAnimator.duration = mProgressAnimationDuration
if (mProgressAnimator.isRunning) {
mProgressAnimator.cancel()
mProgressAnimator.start()
}
}
}
override fun setListener(listener: ProgressDrawerManager.ProgressDrawerListener) { this.listener = listener }
}
| mit | 699c2f6684f91085217a2d1d3ebc262c | 37.65493 | 113 | 0.690107 | 5.149156 | false | false | false | false |
leafclick/intellij-community | python/src/com/jetbrains/python/statistics/PyPackageUsagesCollector.kt | 1 | 2898 | // 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.python.statistics
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomWhiteListRule
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.reference.SoftReference
import com.jetbrains.extensions.getSdk
import com.jetbrains.python.packaging.PyPIPackageCache
import com.jetbrains.python.packaging.PyPackageManager
import java.lang.ref.WeakReference
/**
* Reports usages of packages and versions
*/
class PyPackageVersionUsagesCollector : ProjectUsagesCollector() {
override fun getMetrics(project: Project) = getPackages(project)
override fun requiresReadAccess(): Boolean = true
override fun getGroupId() = "python.packages"
override fun getVersion() = 2
}
private fun getPackages(project: Project): Set<MetricEvent> {
val result = HashSet<MetricEvent>()
for (module in project.modules) {
val sdk = module.getSdk() ?: continue
val usageData = FeatureUsageData().addPythonSpecificInfo(sdk)
PyPackageManager.getInstance(sdk).getRequirements(module)?.apply {
val packageNames = getPyPiPackagesCache()
filter { it.name.toLowerCase() in packageNames }.forEach { req ->
ProgressManager.checkCanceled()
val version = req.versionSpecs.firstOrNull()?.version?.trim() ?: "unknown"
result.add(MetricEvent("python_package_installed",
usageData.copy() // Not to calculate interpreter on each call
.addData("package", req.name)
.addData("package_version", version)))
}
}
}
return result
}
private fun getPyPiPackagesCache() = PyPIPackageCache.getInstance().packageNames.map(String::toLowerCase).toSet()
class PyPackageUsagesWhiteListRule : CustomWhiteListRule() {
private var packagesRef: WeakReference<Set<String>>? = null
@Synchronized
private fun getPackages(): Set<String> {
SoftReference.dereference(packagesRef)?.let { return it }
val pyPiPackages = getPyPiPackagesCache()
packagesRef = WeakReference(pyPiPackages)
return pyPiPackages
}
override fun acceptRuleId(ruleId: String?) = "python_packages" == ruleId
override fun doValidate(data: String, context: EventContext) =
if (data.toLowerCase() in getPackages()) ValidationResultType.ACCEPTED else ValidationResultType.REJECTED
} | apache-2.0 | 224d0f169f78be595467f5759709591c | 41.632353 | 140 | 0.755003 | 4.61465 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/enum/kt7257_namedLocalFun.kt | 3 | 265 | enum class X {
B {
val value2 = "K"
val value3: String
init {
fun foo() = value2
value3 = "O" + foo()
}
override val value = value3
};
abstract val value: String
}
fun box() = X.B.value | apache-2.0 | 228a273ed77ce05909b1ee09fdeed6fa | 14.647059 | 35 | 0.449057 | 3.732394 | false | false | false | false |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/algorithms/KMaxConsecutiveOnes.kt | 1 | 585 | package me.consuegra.algorithms
/**
* Given a binary array, find the maximum number of consecutive 1s in this array.
* <p>
* Example
* <p>
* Input: [1,1,0,1,1,1]
* Output: 3
*/
class KMaxConsecutiveOnes {
fun findMaxConsecutiveOnes(input: IntArray) : Int {
var maxOnes = 0
var ones = 0
input.forEach { num ->
if (num == 1) {
ones++
if (ones > maxOnes) {
maxOnes++
}
} else {
ones = 0
}
}
return maxOnes
}
}
| mit | 26e0f7c516b6cfdeca813308c5620059 | 19.172414 | 81 | 0.459829 | 3.848684 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/finally/finallyAndFinally.kt | 5 | 648 | class MyString {
var s = ""
operator fun plus(x : String) : MyString {
s += x
return this
}
override fun toString(): String {
return s
}
}
fun test1() : MyString {
var r = MyString()
try {
r + "Try1"
try {
r + "Try2"
if (true)
return r
} finally {
r + "Finally2"
if (true) {
return r
}
}
return r
} finally {
r + "Finally1"
}
}
fun box(): String {
return if (test1().toString() == "Try1Try2Finally2Finally1") "OK" else "fail: ${test1()}"
} | apache-2.0 | 644fe387b44877f7927f6021977d986c | 15.641026 | 91 | 0.419753 | 3.767442 | false | true | false | false |
blokadaorg/blokada | android5/app/src/main/java/utils/AndroidUtils.kt | 1 | 3411 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui.utils
import android.app.PendingIntent
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import android.util.TypedValue
import android.widget.Toast
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import model.SystemTunnelRevoked
import model.Uri
import org.blokada.R
import service.ContextService
import utils.Logger
object AndroidUtils {
private val context = ContextService
fun copyToClipboard(text: String) {
val ctx = context.requireContext()
val clipboard = ContextCompat.getSystemService(ctx, ClipboardManager::class.java)
val clip = ClipData.newPlainText("name", text)
clipboard?.setPrimaryClip(clip)
Toast.makeText(ctx, ctx.getString(R.string.universal_status_copied_to_clipboard), Toast.LENGTH_SHORT).show()
}
}
fun Context.getPendingIntentForService(intent: Intent, flags: Int): PendingIntent {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.getService(this, 0, intent, flags or PendingIntent.FLAG_IMMUTABLE)
} else {
PendingIntent.getService(this, 0, intent, flags)
}
}
fun Context.getPendingIntentForActivity(intent: Intent, flags: Int): PendingIntent {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.getActivity(this, 0, intent, flags or PendingIntent.FLAG_IMMUTABLE)
} else {
PendingIntent.getActivity(this, 0, intent, flags)
}
}
fun Context.getPendingIntentForBroadcast(intent: Intent, flags: Int): PendingIntent {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.getBroadcast(this, 0, intent, flags or PendingIntent.FLAG_IMMUTABLE)
} else {
PendingIntent.getBroadcast(this, 0, intent, flags)
}
}
fun String.cause(ex: Throwable): String {
return when (ex) {
is SystemTunnelRevoked -> "$this: ${ex.localizedMessage}"
else -> {
val stacktrace = Log.getStackTraceString(ex)
return "$this: ${ex.localizedMessage}\n$stacktrace"
}
}
}
@ColorInt
fun Context.getColorFromAttr(
@AttrRes attrColor: Int,
typedValue: TypedValue = TypedValue(),
resolveRefs: Boolean = true
): Int {
theme.resolveAttribute(attrColor, typedValue, resolveRefs)
return typedValue.data
}
fun Fragment.getColor(colorResId: Int): Int {
return ContextCompat.getColor(requireContext(), colorResId)
}
fun now() = System.currentTimeMillis()
fun openInBrowser(url: Uri) {
try {
val ctx = ContextService.requireContext()
val intent = Intent(Intent.ACTION_VIEW)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.data = android.net.Uri.parse(url)
ctx.startActivity(intent)
} catch (ex: Exception) {
Logger.w("Browser", "Could not open url in browser: $url".cause(ex))
}
} | mpl-2.0 | d8d0a4a083c0a493c025cbe48bd978e5 | 30.583333 | 116 | 0.71349 | 4.074074 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/primitiveTypes/equalsHashCodeToString.kt | 5 | 793 | fun box(): String {
val b: Byte = 42
val c: Char = 'z'
val s: Short = 239
val i: Int = -1
val j: Long = -42L
val f: Float = 3.14f
val d: Double = -2.72
val z: Boolean = true
b.equals(b)
b == b
b.hashCode()
b.toString()
"$b"
c.equals(c)
c == c
c.hashCode()
c.toString()
"$c"
s.equals(s)
s == s
s.hashCode()
s.toString()
"$s"
i.equals(i)
i == i
i.hashCode()
i.toString()
"$i"
j.equals(j)
j == j
j.hashCode()
j.toString()
"$j"
f.equals(f)
f == f
f.hashCode()
f.toString()
"$f"
d.equals(d)
d == d
d.hashCode()
d.toString()
"$d"
z.equals(z)
z == z
z.hashCode()
z.toString()
"$z"
return "OK"
}
| apache-2.0 | adf663a0ed2295f15575c9b3e47ac9b3 | 12.216667 | 25 | 0.432535 | 2.832143 | false | false | false | false |
smmribeiro/intellij-community | xml/impl/src/com/intellij/ide/browsers/WebBrowserXmlServiceImpl.kt | 6 | 1749 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.browsers
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.lang.Language
import com.intellij.lang.html.HTMLLanguage
import com.intellij.lang.xhtml.XHTMLLanguage
import com.intellij.lang.xml.XMLLanguage
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.xml.util.HtmlUtil
class WebBrowserXmlServiceImpl : WebBrowserXmlService() {
override fun isHtmlFile(element: PsiElement): Boolean {
return HtmlUtil.isHtmlFile(element)
}
override fun isHtmlFile(file: VirtualFile): Boolean {
return HtmlUtil.isHtmlFile(file)
}
override fun isHtmlOrXmlFile(psiFile: PsiFile): Boolean {
if (!isHtmlFile(psiFile.virtualFile) && !FileTypeRegistry.getInstance().isFileOfType(psiFile.virtualFile, XmlFileType.INSTANCE)) {
return false
}
val baseLanguage: Language = psiFile.viewProvider.baseLanguage
if (isHtmlOrXmlLanguage(baseLanguage)) {
return true
}
return if (psiFile.fileType is LanguageFileType) {
isHtmlOrXmlLanguage((psiFile.fileType as LanguageFileType).language)
}
else false
}
override fun isXmlLanguage(language: Language): Boolean {
return language == XMLLanguage.INSTANCE
}
override fun isHtmlOrXmlLanguage(language: Language): Boolean {
return language.isKindOf(HTMLLanguage.INSTANCE)
|| language === XHTMLLanguage.INSTANCE
|| language === XMLLanguage.INSTANCE
}
} | apache-2.0 | 5a2edf25ce41f4bd3beda0ccfc79187c | 34.714286 | 140 | 0.767296 | 4.473146 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionProvider.kt | 1 | 7775 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.SourcePositionProvider
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.impl.DebuggerContextUtil
import com.intellij.debugger.impl.PositionUtil
import com.intellij.debugger.ui.tree.FieldDescriptor
import com.intellij.debugger.ui.tree.LocalVariableDescriptor
import com.intellij.debugger.ui.tree.NodeDescriptor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.ClassNotPreparedException
import com.sun.jdi.ClassType
import com.sun.jdi.ReferenceType
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContextUtils
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.synthetic.JavaSyntheticPropertiesScope.Companion.possibleGetMethodNames
class KotlinSourcePositionProvider : SourcePositionProvider() {
override fun computeSourcePosition(
descriptor: NodeDescriptor,
project: Project,
context: DebuggerContextImpl,
nearest: Boolean
): SourcePosition? {
if (context.frameProxy == null || DumbService.isDumb(project)) return null
return when(descriptor) {
is FieldDescriptor -> computeSourcePosition(descriptor, context, nearest)
is GetterDescriptor -> computeSourcePosition(descriptor, context, nearest)
is LocalVariableDescriptor -> computeSourcePosition(descriptor, context, nearest)
else -> null
}
}
private fun computeSourcePosition(
descriptor: LocalVariableDescriptor,
context: DebuggerContextImpl,
nearest: Boolean
): SourcePosition? {
val place = PositionUtil.getContextElement(context) ?: return null
if (place.containingFile !is KtFile) return null
val contextElement = getContextElement(place) ?: return null
val codeFragment = KtPsiFactory(context.project).createExpressionCodeFragment(descriptor.name, contextElement)
val expression = codeFragment.getContentElement()
if (expression is KtSimpleNameExpression) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val declarationDescriptor = BindingContextUtils.extractVariableDescriptorFromReference(bindingContext, expression)
val sourceElement = declarationDescriptor?.source
if (sourceElement is KotlinSourceElement) {
val element = sourceElement.getPsi() ?: return null
if (nearest) {
return DebuggerContextUtil.findNearest(context, element, element.containingFile)
}
return SourcePosition.createFromOffset(element.containingFile, element.textOffset)
}
}
return null
}
private fun computeSourcePositionForDeclaration(
name: String,
declaringType: ReferenceType,
context: DebuggerContextImpl,
nearest: Boolean
) = computeSourcePositionForDeclaration(declaringType, context, nearest) {
it.name == name
}
private fun computeSourcePositionForPropertyDeclaration(
name: String,
declaringType: ReferenceType,
context: DebuggerContextImpl,
nearest: Boolean
) = computeSourcePositionForDeclaration(declaringType, context, nearest) {
it.name == name || it.name in name.getPropertyDeclarationNameVariations()
}
private fun String.getPropertyDeclarationNameVariations(): List<String> {
val name = Name.guessByFirstCharacter(this)
return possibleGetMethodNames(name).map(Name::asString)
}
private fun computeSourcePositionForDeclaration(
declaringType: ReferenceType,
context: DebuggerContextImpl,
nearest: Boolean,
declarationSelector: (KtDeclaration) -> Boolean
): SourcePosition? {
val myClass = findClassByType(context.project, declaringType, context)?.navigationElement as? KtClassOrObject ?: return null
val declaration = myClass.declarations.firstOrNull(declarationSelector) ?: return null
if (nearest) {
return DebuggerContextUtil.findNearest(context, declaration, myClass.containingFile)
}
return SourcePosition.createFromOffset(declaration.containingFile, declaration.textOffset)
}
private fun computeSourcePosition(
descriptor: FieldDescriptor,
context: DebuggerContextImpl,
nearest: Boolean
): SourcePosition? {
val fieldName = descriptor.field.name()
if (fieldName == AsmUtil.CAPTURED_THIS_FIELD
|| fieldName == AsmUtil.CAPTURED_RECEIVER_FIELD
|| fieldName.startsWith(AsmUtil.LABELED_THIS_FIELD)
) {
return null
}
return computeSourcePositionForDeclaration(fieldName, descriptor.field.declaringType(), context, nearest)
}
private fun computeSourcePosition(
descriptor: GetterDescriptor,
context: DebuggerContextImpl,
nearest: Boolean
): SourcePosition? {
val name = descriptor.name
val type = descriptor.getter.declaringType()
computeSourcePositionForPropertyDeclaration(name, type, context, nearest)?.let { return it }
if (type is ClassType) {
val interfaces = type.safeAllInterfaces().distinct()
for (intf in interfaces) {
computeSourcePositionForPropertyDeclaration(name, intf, context, nearest)?.let { return it }
}
}
return null
}
private fun findClassByType(project: Project, type: ReferenceType, context: DebuggerContextImpl): PsiElement? {
val session = context.debuggerSession
val scope = session?.searchScope ?: GlobalSearchScope.allScope(project)
val className = JvmClassName.byInternalName(type.name()).fqNameForClassNameWithoutDollars.asString()
val myClass = JavaPsiFacade.getInstance(project).findClass(className, scope)
if (myClass != null) return myClass
val position = getLastSourcePosition(type, context)
if (position != null) {
val element = position.elementAt
if (element != null) {
return element.getStrictParentOfType<KtClassOrObject>()
}
}
return null
}
private fun getLastSourcePosition(type: ReferenceType, context: DebuggerContextImpl): SourcePosition? {
val debugProcess = context.debugProcess
if (debugProcess != null) {
try {
val locations = type.safeAllLineLocations()
if (locations.isNotEmpty()) {
val lastLocation = locations[locations.size - 1]
return debugProcess.positionManager.getSourcePosition(lastLocation)
}
} catch (ignored: AbsentInformationException) {
} catch (ignored: ClassNotPreparedException) {
}
}
return null
}
}
| apache-2.0 | 2307a190d36b6f46319418a67fe71be7 | 41.027027 | 158 | 0.705338 | 5.406815 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/typeAliases/withTypeArgument.kt | 9 | 211 | // "Replace with 'B<String>'" "true"
// WITH_STDLIB
@Deprecated(message = "renamed", replaceWith = ReplaceWith("B<E>"))
typealias A<E> = List<E>
typealias B<E> = List<E>
val x: <caret>A<String> = emptyList()
| apache-2.0 | f3f0a0283f57b6c3f59bf7976b783989 | 22.444444 | 67 | 0.649289 | 2.813333 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinPathsProvider.kt | 1 | 4605 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.compiler.configuration
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.jarRepository.RemoteRepositoriesConfiguration
import com.intellij.jarRepository.RemoteRepositoryDescription
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.util.io.Decompressor
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties
import org.jetbrains.kotlin.utils.KotlinPaths
import org.jetbrains.kotlin.utils.KotlinPathsFromHomeDir
import java.io.File
object KotlinPathsProvider {
const val KOTLIN_MAVEN_GROUP_ID = "org.jetbrains.kotlin"
const val KOTLIN_DIST_ARTIFACT_ID = "kotlin-dist-for-ide"
fun getKotlinPaths(version: String): KotlinPaths =
KotlinPathsFromHomeDir(File(PathManager.getSystemPath(), KOTLIN_DIST_ARTIFACT_ID).resolve(version))
fun getKotlinPaths(project: Project) =
getKotlinPaths(KotlinJpsPluginSettings.getInstance(project).settings.version)
fun lazyDownloadAndUnpackKotlincDist(
project: Project,
version: String,
indicator: ProgressIndicator,
beforeDownload: () -> Unit,
onError: (String) -> Unit,
): File? {
val destination = getKotlinPaths(version).homePath
val unpackedDistTimestamp = destination.lastModified()
val packedDistTimestamp = getExpectedMavenArtifactJarPath(KOTLIN_DIST_ARTIFACT_ID, version).lastModified()
if (unpackedDistTimestamp != 0L && packedDistTimestamp != 0L && unpackedDistTimestamp >= packedDistTimestamp) {
return destination
}
destination.deleteRecursively()
val jar = lazyDownloadMavenArtifact(project, KOTLIN_DIST_ARTIFACT_ID, version, indicator, beforeDownload, onError)
if (jar == null) return null
Decompressor.Zip(jar).extract(destination)
check(destination.isDirectory)
return destination
}
fun lazyDownloadMavenArtifact(
project: Project,
artifactId: String,
version: String,
indicator: ProgressIndicator,
beforeDownload: () -> Unit,
onError: (String) -> Unit,
): File? {
getExpectedMavenArtifactJarPath(artifactId, version).takeIf { it.exists() }?.let {
return it
}
val prop = RepositoryLibraryProperties(
KOTLIN_MAVEN_GROUP_ID,
artifactId,
version,
/* includeTransitiveDependencies = */false,
emptyList()
)
val repos = RemoteRepositoriesConfiguration.getInstance(project).repositories +
listOf( // TODO remove once KTI-724 is fixed
RemoteRepositoryDescription(
"kotlin.ide.plugin.dependencies",
"Kotlin IDE Plugin Dependencies",
"https://cache-redirector.jetbrains.com/maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-ide-plugin-dependencies"
)
)
beforeDownload()
val downloadedCompiler = JarRepositoryManager.loadDependenciesSync(
project,
prop,
/* loadSources = */ false,
/* loadJavadoc = */ false,
/* copyTo = */ null,
repos,
indicator
)
if (downloadedCompiler.isEmpty()) {
with(prop) {
onError("Failed to download maven artifact ($groupId:$artifactId${getVersion()}). " +
"Searched the artifact in following repos:\n" +
repos.joinToString("\n") { it.url })
}
return null
}
return downloadedCompiler.singleOrNull().let { it ?: error("Expected to download only single artifact") }.file
.toVirtualFileUrl(VirtualFileUrlManager.getInstance(project)).presentableUrl.let { File(it) }
}
fun getExpectedMavenArtifactJarPath(artifactId: String, version: String) =
JarRepositoryManager.getLocalRepositoryPath()
.resolve(KOTLIN_MAVEN_GROUP_ID.replace(".", "/"))
.resolve(artifactId)
.resolve(version)
.resolve("$artifactId-$version.jar")
}
| apache-2.0 | 72de8a5f5397efc3552aa3b96f6bc4f2 | 41.638889 | 137 | 0.662758 | 5.128062 | false | false | false | false |
google/intellij-community | java/compiler/impl/src/com/intellij/packaging/impl/artifacts/workspacemodel/EntityToElement.kt | 5 | 11591 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.packaging.impl.artifacts.workspacemodel
import com.intellij.configurationStore.deserializeInto
import com.intellij.openapi.module.ModulePointerManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.packaging.artifacts.ArtifactPointerManager
import com.intellij.packaging.elements.CompositePackagingElement
import com.intellij.packaging.elements.PackagingElement
import com.intellij.packaging.elements.PackagingElementFactory
import com.intellij.packaging.impl.artifacts.UnknownPackagingElementTypeException
import com.intellij.packaging.impl.elements.*
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.util.JpsPathUtil
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
private val rwLock: ReadWriteLock = if (
Registry.`is`("ide.new.project.model.artifacts.sync.initialization")
) ReentrantReadWriteLock()
else EmptyReadWriteLock()
/**
* We use VersionedEntityStorage here instead of the builder/snapshot because we need an actual data of the storage for double check
*/
internal fun CompositePackagingElementEntity.toCompositeElement(
project: Project,
storage: VersionedEntityStorage,
addToMapping: Boolean = true,
): CompositePackagingElement<*> {
rwLock.readLock().lock()
var existing = try {
testCheck(1)
storage.base.elements.getDataByEntity(this)
}
catch (e: Exception) {
rwLock.readLock().unlock()
throw e
}
if (existing == null) {
rwLock.readLock().unlock()
rwLock.writeLock().lock()
try {
testCheck(2)
// Double check
existing = storage.base.elements.getDataByEntity(this)
if (existing == null) {
val element = when (this) {
is DirectoryPackagingElementEntity -> {
val element = DirectoryPackagingElement(this.directoryName)
this.children.pushTo(element, project, storage)
element
}
is ArchivePackagingElementEntity -> {
val element = ArchivePackagingElement(this.fileName)
this.children.pushTo(element, project, storage)
element
}
is ArtifactRootElementEntity -> {
val element = ArtifactRootElementImpl()
this.children.pushTo(element, project, storage)
element
}
is CustomPackagingElementEntity -> {
val unpacked = unpackCustomElement(storage, project)
if (unpacked !is CompositePackagingElement<*>) {
error("Expected composite packaging element")
}
unpacked
}
else -> unknownElement()
}
if (addToMapping) {
val storageBase = storage.base
if (storageBase is MutableEntityStorage) {
val mutableMapping = storageBase.mutableElements
mutableMapping.addMapping(this, element)
}
else {
WorkspaceModel.getInstance(project).updateProjectModelSilent {
val mutableMapping = it.mutableElements
mutableMapping.addMapping(this, element)
}
}
}
existing = element
}
// Lock downgrade
rwLock.readLock().lock()
}
finally {
rwLock.writeLock().unlock()
}
}
rwLock.readLock().unlock()
return existing as CompositePackagingElement<*>
}
fun PackagingElementEntity.toElement(project: Project, storage: VersionedEntityStorage): PackagingElement<*> {
rwLock.readLock().lock()
var existing = try {
testCheck(3)
storage.base.elements.getDataByEntity(this)
}
catch (e: Exception) {
rwLock.readLock().unlock()
throw e
}
if (existing == null) {
rwLock.readLock().unlock()
rwLock.writeLock().lock()
try {
testCheck(4)
// Double check
existing = storage.base.elements.getDataByEntity(this)
if (existing == null) {
val element = when (this) {
is ModuleOutputPackagingElementEntity -> {
val module = this.module
if (module != null) {
val modulePointer = ModulePointerManager.getInstance(project).create(module.name)
ProductionModuleOutputPackagingElement(project, modulePointer)
}
else {
ProductionModuleOutputPackagingElement(project)
}
}
is ModuleTestOutputPackagingElementEntity -> {
val module = this.module
if (module != null) {
val modulePointer = ModulePointerManager.getInstance(project).create(module.name)
TestModuleOutputPackagingElement(project, modulePointer)
}
else {
TestModuleOutputPackagingElement(project)
}
}
is ModuleSourcePackagingElementEntity -> {
val module = this.module
if (module != null) {
val modulePointer = ModulePointerManager.getInstance(project).create(module.name)
ProductionModuleSourcePackagingElement(project, modulePointer)
}
else {
ProductionModuleSourcePackagingElement(project)
}
}
is ArtifactOutputPackagingElementEntity -> {
val artifact = this.artifact
if (artifact != null) {
val artifactPointer = ArtifactPointerManager.getInstance(project).createPointer(artifact.name)
ArtifactPackagingElement(project, artifactPointer)
}
else {
ArtifactPackagingElement(project)
}
}
is ExtractedDirectoryPackagingElementEntity -> {
val pathInArchive = this.pathInArchive
val archive = this.filePath
ExtractedDirectoryPackagingElement(JpsPathUtil.urlToPath(archive.url), pathInArchive)
}
is FileCopyPackagingElementEntity -> {
val file = this.filePath
val renamedOutputFileName = this.renamedOutputFileName
if (renamedOutputFileName != null) {
FileCopyPackagingElement(JpsPathUtil.urlToPath(file.url), renamedOutputFileName)
}
else {
FileCopyPackagingElement(JpsPathUtil.urlToPath(file.url))
}
}
is DirectoryCopyPackagingElementEntity -> {
val directory = this.filePath
DirectoryCopyPackagingElement(JpsPathUtil.urlToPath(directory.url))
}
is ArchivePackagingElementEntity -> this.toCompositeElement(project, storage, false)
is DirectoryPackagingElementEntity -> this.toCompositeElement(project, storage, false)
is ArtifactRootElementEntity -> this.toCompositeElement(project, storage, false)
is LibraryFilesPackagingElementEntity -> {
val mapping = storage.base.getExternalMapping<PackagingElement<*>>("intellij.artifacts.packaging.elements")
val data = mapping.getDataByEntity(this)
if (data != null) {
return data
}
val library = this.library
if (library != null) {
val tableId = library.tableId
val moduleName = if (tableId is LibraryTableId.ModuleLibraryTableId) tableId.moduleId.name else null
LibraryPackagingElement(tableId.level, library.name, moduleName)
}
else {
LibraryPackagingElement()
}
}
is CustomPackagingElementEntity -> unpackCustomElement(storage, project)
else -> unknownElement()
}
val storageBase = storage.base
if (storageBase is MutableEntityStorage) {
val mutableMapping = storageBase.mutableElements
mutableMapping.addIfAbsent(this, element)
}
else {
WorkspaceModel.getInstance(project).updateProjectModelSilent {
val mutableMapping = it.mutableElements
mutableMapping.addIfAbsent(this, element)
}
}
existing = element
}
// Lock downgrade
rwLock.readLock().lock()
}
finally {
rwLock.writeLock().unlock()
}
}
rwLock.readLock().unlock()
return existing as PackagingElement<*>
}
private fun CustomPackagingElementEntity.unpackCustomElement(storage: VersionedEntityStorage,
project: Project): PackagingElement<*> {
val mapping = storage.base.getExternalMapping<PackagingElement<*>>("intellij.artifacts.packaging.elements")
val data = mapping.getDataByEntity(this)
if (data != null) {
return data
}
// TODO: 09.04.2021 It should be invalid artifact instead of error
val elementType = PackagingElementFactory.getInstance().findElementType(this.typeId)
?: throw UnknownPackagingElementTypeException(this.typeId)
@Suppress("UNCHECKED_CAST")
val packagingElement = elementType.createEmpty(project) as PackagingElement<Any>
val state = packagingElement.state
if (state != null) {
val element = JDOMUtil.load(this.propertiesXmlTag)
element.deserializeInto(state)
packagingElement.loadState(state)
}
if (packagingElement is CompositePackagingElement<*>) {
this.children.pushTo(packagingElement, project, storage)
}
return packagingElement
}
private fun PackagingElementEntity.unknownElement(): Nothing {
error("Unknown packaging element entity: $this")
}
private fun List<PackagingElementEntity>.pushTo(element: CompositePackagingElement<*>,
project: Project,
storage: VersionedEntityStorage) {
val children = this.map { it.toElement(project, storage) }.toList()
children.reversed().forEach { element.addFirstChild(it) }
}
private class EmptyReadWriteLock : ReadWriteLock {
override fun readLock(): Lock = EmptyLock
override fun writeLock(): Lock = EmptyLock
}
private object EmptyLock : Lock {
override fun lock() {
// Nothing
}
override fun lockInterruptibly() {
// Nothing
}
override fun tryLock(): Boolean {
throw UnsupportedOperationException()
}
override fun tryLock(time: Long, unit: TimeUnit): Boolean {
throw UnsupportedOperationException()
}
override fun unlock() {
// Nothing
}
override fun newCondition(): Condition {
throw UnsupportedOperationException()
}
}
// Instruments for testing code with unexpected exceptions
// I assume that tests with bad approach is better than no tests at all
@TestOnly
object ArtifactsTestingState {
var testLevel: Int = 0
var exceptionsThrows: MutableList<Int> = ArrayList()
fun reset() {
testLevel = 0
exceptionsThrows = ArrayList()
}
}
@Suppress("TestOnlyProblems")
private fun testCheck(level: Int) {
if (level == ArtifactsTestingState.testLevel) {
ArtifactsTestingState.exceptionsThrows += level
error("Exception on level: $level")
}
}
| apache-2.0 | 90ad2136efcc77a48ec85413244a7ed0 | 34.555215 | 140 | 0.663618 | 5.275831 | false | true | false | false |
romannurik/muzei | wearable/src/main/java/com/google/android/apps/muzei/complications/ArtworkComplicationWorker.kt | 2 | 3306 | /*
* Copyright 2018 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.complications
import android.content.ComponentName
import android.content.Context
import android.os.Build
import android.support.wearable.complications.ProviderUpdateRequester
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.preference.PreferenceManager
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.google.android.apps.muzei.api.MuzeiContract
import net.nurik.roman.muzei.BuildConfig
import java.util.TreeSet
/**
* Worker which listens for artwork change events and updates the Artwork Complication
*/
@RequiresApi(Build.VERSION_CODES.N)
class ArtworkComplicationWorker(
context: Context,
workerParams: WorkerParameters
) : Worker(context, workerParams) {
companion object {
private const val TAG = "ArtworkComplication"
internal fun scheduleComplicationUpdate(context: Context) {
val workManager = WorkManager.getInstance(context)
workManager.enqueueUniqueWork(TAG, ExistingWorkPolicy.REPLACE,
OneTimeWorkRequestBuilder<ArtworkComplicationWorker>()
.setConstraints(Constraints.Builder()
.addContentUriTrigger(MuzeiContract.Artwork.CONTENT_URI, true)
.build())
.build())
if (BuildConfig.DEBUG) {
Log.d(TAG, "Work scheduled")
}
}
internal fun cancelComplicationUpdate(context: Context) {
val workManager = WorkManager.getInstance(context)
workManager.cancelUniqueWork(TAG)
if (BuildConfig.DEBUG) {
Log.d(TAG, "Work cancelled")
}
}
}
override fun doWork(): Result {
val providerUpdateRequester = ProviderUpdateRequester(applicationContext,
ComponentName(applicationContext, ArtworkComplicationProviderService::class.java))
val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val complicationSet = preferences.getStringSet(
ArtworkComplicationProviderService.KEY_COMPLICATION_IDS, TreeSet())
if (complicationSet?.isNotEmpty() == true) {
providerUpdateRequester.requestUpdate(*complicationSet.map { Integer.parseInt(it) }.toIntArray())
}
// Reschedule the job to listen for the next change
scheduleComplicationUpdate(applicationContext)
return Result.success()
}
}
| apache-2.0 | 263c044d6c7603542217442713002d8a | 38.831325 | 109 | 0.701754 | 5.173709 | false | false | false | false |
siosio/intellij-community | platform/remote-servers/target-integration-tests/testSrc/com/intellij/tests/targets/java/JavaTargetTestBase.kt | 1 | 26052 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.tests.targets.java
import com.intellij.execution.PsiLocation
import com.intellij.execution.ShortenCommandLine
import com.intellij.execution.application.ApplicationConfiguration
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.junit.JUnitConfiguration
import com.intellij.execution.process.ProcessOutputType
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionEnvironmentBuilder
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.testFramework.PlatformTestUtil
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
/**
* Create a subclass to briefly test a compatibility of some Run Target with Java run configurations.
*/
abstract class JavaTargetTestBase(executionMode: ExecutionMode) : CommonJavaTargetTestBase(executionMode) {
/** One test checks that the being launched on the target, a test application can read the file at this path. */
abstract val targetFilePath: String
/** Expected contents of [targetFilePath]. */
abstract val targetFileContent: String
override fun getTestAppPath(): String = "${PlatformTestUtil.getCommunityPath()}/platform/remote-servers/target-integration-tests/targetApp"
override fun setUpModule() {
super.setUpModule()
val contentRoot = LocalFileSystem.getInstance().findFileByPath(testAppPath)
initializeSampleModule(module, contentRoot!!)
}
@Test
fun `test can read file at target`(): Unit = runBlocking {
if (executionMode != ExecutionMode.RUN) return@runBlocking
doTestCanReadFileAtTarget(ShortenCommandLine.NONE)
}
@Test
fun `test can read file at target with manifest shortener`(): Unit = runBlocking {
if (executionMode != ExecutionMode.RUN) return@runBlocking
doTestCanReadFileAtTarget(ShortenCommandLine.MANIFEST)
}
@Test
fun `test can read file at target with args file shortener`(): Unit = runBlocking {
if (executionMode != ExecutionMode.RUN) return@runBlocking
doTestCanReadFileAtTarget(ShortenCommandLine.ARGS_FILE)
}
private suspend fun doTestCanReadFileAtTarget(shortenCommandLine: ShortenCommandLine) {
val cwd = tempDir.createDir()
val executor = DefaultRunExecutor.getRunExecutorInstance()
val executionEnvironment: ExecutionEnvironment = withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
ExecutionEnvironmentBuilder(project, executor)
.runProfile(
ApplicationConfiguration("CatRunConfiguration", project).also { conf ->
conf.setModule(module)
conf.workingDirectory = cwd.toString()
conf.mainClassName = "Cat"
conf.programParameters = targetFilePath
conf.defaultTargetName = targetName
conf.shortenCommandLine = shortenCommandLine
}
)
.build()
}
val textDeferred = processOutputReader { _, outputType -> outputType == ProcessOutputType.STDOUT }
withDeletingExcessiveEditors {
withTimeout(30_000) {
CompletableDeferred<RunContentDescriptor>()
.also { deferred ->
executionEnvironment.setCallback { deferred.complete(it) }
withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
executionEnvironment.runner.execute(executionEnvironment)
}
}
.await()
}
}
val text = withTimeout(30_000) { textDeferred.await() }
assertThat(text).isEqualTo(targetFileContent)
}
@Test
fun `test java application`(): Unit = runBlocking {
val cwd = tempDir.createDir()
val executionEnvironment: ExecutionEnvironment = withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
ExecutionEnvironmentBuilder(project, getExecutor()).runProfile(
ApplicationConfiguration("CatRunConfiguration", project).also { conf ->
conf.setModule(module)
conf.workingDirectory = cwd.toString()
conf.mainClassName = "Cat"
conf.programParameters = targetFilePath
conf.defaultTargetName = targetName
}
)
.build()
}
if (executionMode == ExecutionMode.DEBUG) {
createBreakpoints(runReadAction {
getTestClass("Cat").containingFile
})
}
val textDeferred = processOutputReader filter@{ event, outputType ->
val text = event.text ?: return@filter false
when (outputType) {
ProcessOutputType.STDOUT ->
// For some reason this string appears in stdout. Don't know whether it should appear or not.
!text.startsWith("Listening for transport ")
ProcessOutputType.SYSTEM -> text.startsWith("Debugger")
else -> false
}
}
withDeletingExcessiveEditors {
withTimeout(30_000) {
CompletableDeferred<RunContentDescriptor>()
.also { deferred ->
executionEnvironment.setCallback { deferred.complete(it) }
withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
executionEnvironment.runner.execute(executionEnvironment)
}
}
.await()
}
}
val text = withTimeout(30_000) { textDeferred.await() }
val expectedText = when (executionMode) {
ExecutionMode.DEBUG -> "Debugger: $targetFileContent\n$targetFileContent"
else -> targetFileContent
}
assertThat(text).isEqualTo(expectedText)
}
private suspend inline fun withDeletingExcessiveEditors(handler: () -> Unit) {
val editorFactory = EditorFactory.getInstance()
val editorsBefore = editorFactory.allEditors.filterTo(hashSetOf()) { it.project === project }
try {
handler()
}
finally {
withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
for (editor in editorFactory.allEditors) {
if (editor.project === project && editor !in editorsBefore) {
editorFactory.releaseEditor(editor)
}
}
}
}
}
@Test
fun `test junit tests - run all`() {
val runConfiguration = createJUnitConfiguration(JUnitConfiguration.TEST_PACKAGE)
doTestJUnitRunConfiguration(runConfiguration = runConfiguration,
expectedTestsResultExported = "<testrun name=\"JUnit tests Run Configuration\">\n" +
" <count name=\"total\" value=\"2\" />\n" +
" <count name=\"failed\" value=\"1\" />\n" +
" <count name=\"passed\" value=\"1\" />\n" +
" <root name=\"<default package>\" location=\"java:suite://<default package>\" />\n" +
" <suite locationUrl=\"java:suite://AlsoTest\" name=\"AlsoTest\" status=\"failed\">\n" +
" <test locationUrl=\"java:test://AlsoTest/testShouldFail\" name=\"testShouldFail()\" metainfo=\"\" status=\"failed\">\n" +
" <diff actual=\"5\" expected=\"4\" />\n" +
" <output type=\"stdout\">Debugger: testShouldFail() reached</output>\n" +
" <output type=\"stderr\">org.opentest4j.AssertionFailedError: \n" +
"\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:54)\n" +
"\tat org.junit.jupiter.api.AssertEquals.failNotEqual(AssertEquals.java:195)\n" +
"\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:152)\n" +
"\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:147)\n" +
"\tat org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:326)\n" +
"\tat AlsoTest.testShouldFail(AlsoTest.java:12)\n" +
"\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
"\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(</output>\n" +
" </test>\n" +
" </suite>\n" +
" <suite locationUrl=\"java:suite://SomeTest\" name=\"SomeTest\" status=\"passed\">\n" +
" <test locationUrl=\"java:test://SomeTest/testSomething\" name=\"testSomething()\" metainfo=\"\" status=\"passed\">\n" +
" <output type=\"stdout\">Debugger: testSomething() reached</output>\n" +
" </test>\n" +
" </suite>\n" +
"</testrun>")
}
@Test
fun `test junit tests - run single test`() {
val alsoTestClass = getTestClass("AlsoTest")
val runConfiguration = createJUnitConfiguration(JUnitConfiguration.TEST_CLASS).also { conf ->
conf.persistentData.setMainClass(alsoTestClass)
}
@Suppress("SpellCheckingInspection", "GrazieInspection")
doTestJUnitRunConfiguration(runConfiguration = runConfiguration,
expectedTestsResultExported = "<testrun name=\"JUnit tests Run Configuration\">\n" +
" <count name=\"total\" value=\"1\" />\n" +
" <count name=\"failed\" value=\"1\" />\n" +
" <suite locationUrl=\"java:suite://AlsoTest\" name=\"AlsoTest\" status=\"failed\">\n" +
" <test locationUrl=\"java:test://AlsoTest/testShouldFail\" name=\"testShouldFail()\" metainfo=\"\" status=\"failed\">\n" +
" <diff actual=\"5\" expected=\"4\" />\n" +
" <output type=\"stdout\">Debugger: testShouldFail() reached</output>\n" +
" <output type=\"stderr\">org.opentest4j.AssertionFailedError: \n" +
"\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:54)\n" +
"\tat org.junit.jupiter.api.AssertEquals.failNotEqual(AssertEquals.java:195)\n" +
"\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:152)\n" +
"\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:147)\n" +
"\tat org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:326)\n" +
"\tat AlsoTest.testShouldFail(AlsoTest.java:12)\n" +
"\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
"\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(</output>\n" +
" </test>\n" +
" </suite>\n" +
"</testrun>")
}
@Test
fun `test junit tests - run tests in directory`() {
val runConfiguration = createJUnitConfiguration(JUnitConfiguration.TEST_DIRECTORY).also { conf ->
conf.persistentData.dirName = "$testAppPath/tests"
}
@Suppress("SpellCheckingInspection", "GrazieInspection")
doTestJUnitRunConfiguration(runConfiguration = runConfiguration,
expectedTestsResultExported = "<testrun name=\"JUnit tests Run Configuration\">\n" +
" <count name=\"total\" value=\"2\" />\n" +
" <count name=\"failed\" value=\"1\" />\n" +
" <count name=\"passed\" value=\"1\" />\n" +
" <root name=\"<default package>\" location=\"java:suite://<default package>\" />\n" +
" <suite locationUrl=\"java:suite://AlsoTest\" name=\"AlsoTest\" status=\"failed\">\n" +
" <test locationUrl=\"java:test://AlsoTest/testShouldFail\" name=\"testShouldFail()\" metainfo=\"\" status=\"failed\">\n" +
" <diff actual=\"5\" expected=\"4\" />\n" +
" <output type=\"stdout\">Debugger: testShouldFail() reached</output>\n" +
" <output type=\"stderr\">org.opentest4j.AssertionFailedError: \n" +
"\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:54)\n" +
"\tat org.junit.jupiter.api.AssertEquals.failNotEqual(AssertEquals.java:195)\n" +
"\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:152)\n" +
"\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:147)\n" +
"\tat org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:326)\n" +
"\tat AlsoTest.testShouldFail(AlsoTest.java:12)\n" +
"\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
"\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(</output>\n" +
" </test>\n" +
" </suite>\n" +
" <suite locationUrl=\"java:suite://SomeTest\" name=\"SomeTest\" status=\"passed\">\n" +
" <test locationUrl=\"java:test://SomeTest/testSomething\" name=\"testSomething()\" metainfo=\"\" status=\"passed\">\n" +
" <output type=\"stdout\">Debugger: testSomething() reached</output>\n" +
" </test>\n" +
" </suite>\n" +
"</testrun>")
}
@Test
fun `test junit tests - run tests by pattern`() {
val runConfiguration = createJUnitConfiguration(JUnitConfiguration.TEST_PATTERN).also { conf ->
conf.persistentData.setPatterns(LinkedHashSet(listOf("^So.*")))
}
@Suppress("SpellCheckingInspection", "GrazieInspection")
doTestJUnitRunConfiguration(runConfiguration = runConfiguration,
expectedTestsResultExported = "<testrun name=\"JUnit tests Run Configuration\">\n" +
" <count name=\"total\" value=\"1\" />\n" +
" <count name=\"passed\" value=\"1\" />\n" +
" <root name=\"<default package>\" location=\"java:suite://<default package>\" />\n" +
" <suite locationUrl=\"java:suite://SomeTest\" name=\"SomeTest\" status=\"passed\">\n" +
" <test locationUrl=\"java:test://SomeTest/testSomething\" name=\"testSomething()\" metainfo=\"\" status=\"passed\">\n" +
" <output type=\"stdout\">Debugger: testSomething() reached</output>\n" +
" </test>\n" +
" </suite>\n" +
"</testrun>")
}
@Test
fun `test junit tests - run test method by pattern`() {
val runConfiguration = createJUnitConfiguration(JUnitConfiguration.TEST_PATTERN).also { conf ->
conf.persistentData.setPatterns(LinkedHashSet(listOf("SomeTest,testSomething")))
}
doTestJUnitRunConfiguration(runConfiguration = runConfiguration,
expectedTestsResultExported = "<testrun name=\"JUnit tests Run Configuration\">\n" +
" <count name=\"total\" value=\"1\" />\n" +
" <count name=\"passed\" value=\"1\" />\n" +
" <root name=\"<default package>\" location=\"java:suite://<default package>\" />\n" +
" <suite locationUrl=\"java:suite://SomeTest\" name=\"SomeTest\" status=\"passed\">\n" +
" <test locationUrl=\"java:test://SomeTest/testSomething\" name=\"testSomething()\" metainfo=\"\" status=\"passed\">\n" +
" <output type=\"stdout\">Debugger: testSomething() reached</output>\n" +
" </test>\n" +
" </suite>\n" +
"</testrun>")
}
private fun createJUnitConfiguration(testObject: String) = JUnitConfiguration("JUnit tests Run Configuration", project).also { conf ->
conf.setModule(module)
conf.defaultTargetName = targetName
conf.persistentData.TEST_OBJECT = testObject
}
@Test
fun `test junit tests - run test method`() {
val runConfiguration = createJUnitConfiguration(JUnitConfiguration.TEST_METHOD).also { conf ->
conf.persistentData.setTestMethod(PsiLocation.fromPsiElement(getTestClass("AlsoTest").findMethodsByName("testShouldFail", false)[0]))
}
@Suppress("SpellCheckingInspection", "GrazieInspection")
doTestJUnitRunConfiguration(runConfiguration = runConfiguration,
expectedTestsResultExported = "<testrun name=\"JUnit tests Run Configuration\">\n" +
" <count name=\"total\" value=\"1\" />\n" +
" <count name=\"failed\" value=\"1\" />\n" +
" <suite locationUrl=\"java:suite://AlsoTest\" name=\"AlsoTest\" status=\"failed\">\n" +
" <test locationUrl=\"java:test://AlsoTest/testShouldFail\" name=\"testShouldFail()\" metainfo=\"\" status=\"failed\">\n" +
" <diff actual=\"5\" expected=\"4\" />\n" +
" <output type=\"stdout\">Debugger: testShouldFail() reached</output>\n" +
" <output type=\"stderr\">org.opentest4j.AssertionFailedError: \n" +
"\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:54)\n" +
"\tat org.junit.jupiter.api.AssertEquals.failNotEqual(AssertEquals.java:195)\n" +
"\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:152)\n" +
"\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:147)\n" +
"\tat org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:326)\n" +
"\tat AlsoTest.testShouldFail(AlsoTest.java:12)\n" +
"\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
"\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(</output>\n" +
" </test>\n" +
" </suite>\n" +
"</testrun>")
}
@Test
fun `test junit tests - run tagged tests`() {
val runConfiguration = createJUnitConfiguration(JUnitConfiguration.TEST_TAGS).also { conf ->
conf.persistentData.tags = "selected"
}
@Suppress("SpellCheckingInspection", "GrazieInspection")
doTestJUnitRunConfiguration(runConfiguration = runConfiguration,
expectedTestsResultExported = "<testrun name=\"JUnit tests Run Configuration\">\n" +
" <count name=\"total\" value=\"1\" />\n" +
" <count name=\"passed\" value=\"1\" />\n" +
" <root name=\"<default package>\" location=\"java:suite://<default package>\" />\n" +
" <suite locationUrl=\"java:suite://SomeTest\" name=\"SomeTest\" status=\"passed\">\n" +
" <test locationUrl=\"java:test://SomeTest/testSomething\" name=\"testSomething()\" metainfo=\"\" status=\"passed\">\n" +
" <output type=\"stdout\">Debugger: testSomething() reached</output>\n" +
" </test>\n" +
" </suite>\n" +
"</testrun>")
}
@Test
fun `test junit tests - run tests by uniqueId`() {
val runConfiguration = createJUnitConfiguration(JUnitConfiguration.TEST_UNIQUE_ID).also { conf ->
conf.persistentData.setUniqueIds("[engine:junit-jupiter]/[class:SomeTest]")
}
@Suppress("SpellCheckingInspection", "GrazieInspection")
doTestJUnitRunConfiguration(runConfiguration = runConfiguration,
expectedTestsResultExported = "<testrun name=\"JUnit tests Run Configuration\">\n" +
" <count name=\"total\" value=\"1\" />\n" +
" <count name=\"passed\" value=\"1\" />\n" +
" <root name=\"<default package>\" location=\"java:suite://<default package>\" />\n" +
" <suite locationUrl=\"java:suite://SomeTest\" name=\"SomeTest\" status=\"passed\">\n" +
" <test locationUrl=\"java:test://SomeTest/testSomething\" name=\"testSomething()\" metainfo=\"\" status=\"passed\">\n" +
" <output type=\"stdout\">Debugger: testSomething() reached</output>\n" +
" </test>\n" +
" </suite>\n" +
"</testrun>")
}
}
| apache-2.0 | f3475962a4aa0efedc91cc797b684c0e | 67.557895 | 188 | 0.487563 | 5.740855 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/DebuggerConnection.kt | 1 | 4019 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine
import com.intellij.debugger.DebuggerInvocationUtil
import com.intellij.debugger.engine.JavaDebugProcess
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.configurations.RunConfigurationBase
import com.intellij.execution.ui.RunnerLayoutUi
import com.intellij.execution.ui.layout.PlaceInGrid
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.content.Content
import com.intellij.util.messages.MessageBusConnection
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.XDebuggerManager
import com.intellij.xdebugger.XDebuggerManagerListener
import com.intellij.xdebugger.impl.XDebugSessionImpl
import org.jetbrains.kotlin.idea.debugger.coroutine.util.CreateContentParamsProvider
import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger
import org.jetbrains.kotlin.idea.debugger.coroutine.view.XCoroutineView
class DebuggerConnection(
val project: Project,
val configuration: RunConfigurationBase<*>?,
val params: JavaParameters?,
modifyArgs: Boolean = true,
val alwaysShowPanel: Boolean = false
) : XDebuggerManagerListener, Disposable {
companion object {
private val log by logger
}
private var connection: MessageBusConnection? = null
private val coroutineAgentAttached: Boolean
init {
if (params is JavaParameters && modifyArgs) {
// gradle related logic in KotlinGradleCoroutineDebugProjectResolver
coroutineAgentAttached = CoroutineAgentConnector.attachCoroutineAgent(project, params)
} else {
coroutineAgentAttached = false
log.debug("Coroutine debugger disabled.")
}
connection = project.messageBus.connect()
connection?.subscribe(XDebuggerManager.TOPIC, this)
}
override fun processStarted(debugProcess: XDebugProcess) {
DebuggerInvocationUtil.swingInvokeLater(project) {
if (debugProcess is JavaDebugProcess) {
if (!Disposer.isDisposed(this) && coroutinesPanelShouldBeShown()) {
registerXCoroutinesPanel(debugProcess.session)?.let {
Disposer.register(this, it)
}
}
}
}
}
override fun processStopped(debugProcess: XDebugProcess) {
ApplicationManager.getApplication().invokeLater {
Disposer.dispose(this)
}
}
private fun registerXCoroutinesPanel(session: XDebugSession): Disposable? {
val ui = session.ui ?: return null
val xCoroutineThreadView = XCoroutineView(project, session as XDebugSessionImpl)
val framesContent: Content = createContent(ui, xCoroutineThreadView)
framesContent.isCloseable = false
ui.addContent(framesContent, 0, PlaceInGrid.right, false)
session.addSessionListener(xCoroutineThreadView.debugSessionListener(session))
session.rebuildViews()
return xCoroutineThreadView
}
private fun coroutinesPanelShouldBeShown() = alwaysShowPanel || configuration is ExternalSystemRunConfiguration || coroutineAgentAttached
private fun createContent(ui: RunnerLayoutUi, createContentParamProvider: CreateContentParamsProvider): Content {
val param = createContentParamProvider.createContentParams()
return ui.createContent(param.id, param.component, param.displayName, param.icon, param.parentComponent)
}
override fun dispose() {
connection?.disconnect()
connection = null
}
}
| apache-2.0 | 791202be183d4650a50f557cdf053d72 | 41.755319 | 158 | 0.747201 | 5.126276 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/MultiplatformModelImportingContext.kt | 1 | 5997 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.gradle
import org.gradle.api.Project
internal interface MultiplatformModelImportingContext: KotlinSourceSetContainer {
val project: Project
val targets: Collection<KotlinTarget>
val compilations: Collection<KotlinCompilation>
/**
* All source sets in a project, including those that are created but not included into any compilations
* (so-called "orphan" source sets). Use [isOrphanSourceSet] to get only compiled source sets
*/
val sourceSets: Collection<KotlinSourceSetImpl> get() = sourceSetsByName.values
override val sourceSetsByName: Map<String, KotlinSourceSetImpl>
/**
* Platforms, which are actually used in this project (i.e. platforms, for which targets has been created)
*/
val projectPlatforms: Collection<KotlinPlatform>
fun sourceSetByName(name: String): KotlinSourceSet?
fun compilationsBySourceSet(sourceSet: KotlinSourceSet): Collection<KotlinCompilation>?
/**
* "Orphan" is a source set which is not actually compiled by the compiler, i.e. the one
* which doesn't belong to any [KotlinCompilation].
*
* Orphan source sets might appear if one creates a source-set manually and doesn't link
* it anywhere (essentially this is a misconfiguration)
*/
fun isOrphanSourceSet(sourceSet: KotlinSourceSet): Boolean = compilationsBySourceSet(sourceSet) == null
/**
* "Declared" source-set is a source-set which is included into compilation directly, rather
* through closure over dependsOn-relation.
*
* See also KDoc for [KotlinCompilation.declaredSourceSets]
*/
fun isDeclaredSourceSet(sourceSet: KotlinSourceSet): Boolean
}
internal fun MultiplatformModelImportingContext.getProperty(property: GradleImportProperties): Boolean = project.getProperty(property)
internal fun Project.getProperty(property: GradleImportProperties): Boolean {
val explicitValueIfAny = try {
(findProperty(property.id) as? String)?.toBoolean()
} catch (e: Exception) {
logger.error("Error while trying to read property $property from project $project", e)
null
}
return explicitValueIfAny ?: property.defaultValue
}
internal enum class GradleImportProperties(val id: String, val defaultValue: Boolean) {
IS_HMPP_ENABLED("kotlin.mpp.enableGranularSourceSetsMetadata", false),
COERCE_ROOT_SOURCE_SETS_TO_COMMON("kotlin.mpp.coerceRootSourceSetsToCommon", true),
ENABLE_NATIVE_DEPENDENCY_PROPAGATION("kotlin.native.enableDependencyPropagation", true),
BUILD_METADATA_DEPENDENCIES("build_metadata_dependencies_for_actualised_source_sets", true),
IMPORT_ORPHAN_SOURCE_SETS("import_orphan_source_sets", true),
INCLUDE_ANDROID_DEPENDENCIES("kotlin.include.android.dependencies", false)
;
}
internal class MultiplatformModelImportingContextImpl(override val project: Project) : MultiplatformModelImportingContext {
/** see [initializeSourceSets] */
override lateinit var sourceSetsByName: Map<String, KotlinSourceSetImpl>
private set
/** see [initializeCompilations] */
override lateinit var compilations: Collection<KotlinCompilation>
private set
private lateinit var sourceSetToParticipatedCompilations: Map<KotlinSourceSet, Set<KotlinCompilation>>
private lateinit var allDeclaredSourceSets: Set<KotlinSourceSet>
/** see [initializeTargets] */
override lateinit var targets: Collection<KotlinTarget>
private set
override lateinit var projectPlatforms: Collection<KotlinPlatform>
private set
internal fun initializeSourceSets(sourceSetsByNames: Map<String, KotlinSourceSetImpl>) {
require(!this::sourceSetsByName.isInitialized) {
"Attempt to re-initialize source sets for $this. Previous value: ${this.sourceSetsByName}"
}
this.sourceSetsByName = sourceSetsByNames
}
@OptIn(ExperimentalGradleToolingApi::class)
internal fun initializeCompilations(compilations: Collection<KotlinCompilation>) {
require(!this::compilations.isInitialized) { "Attempt to re-initialize compilations for $this. Previous value: ${this.compilations}" }
this.compilations = compilations
val sourceSetToCompilations = LinkedHashMap<KotlinSourceSet, MutableSet<KotlinCompilation>>()
for (target in targets) {
for (compilation in target.compilations) {
for (sourceSet in compilation.allSourceSets) {
sourceSetToCompilations.getOrPut(sourceSet) { LinkedHashSet() } += compilation
resolveAllDependsOnSourceSets(sourceSet).forEach {
sourceSetToCompilations.getOrPut(it) { LinkedHashSet() } += compilation
}
}
}
}
this.sourceSetToParticipatedCompilations = sourceSetToCompilations
this.allDeclaredSourceSets = compilations.flatMapTo(mutableSetOf()) { it.declaredSourceSets }
}
internal fun initializeTargets(targets: Collection<KotlinTarget>) {
require(!this::targets.isInitialized) { "Attempt to re-initialize targets for $this. Previous value: ${this.targets}" }
this.targets = targets
this.projectPlatforms = targets.map { it.platform }
}
// overload for small optimization
override fun isOrphanSourceSet(sourceSet: KotlinSourceSet): Boolean = sourceSet !in sourceSetToParticipatedCompilations.keys
override fun isDeclaredSourceSet(sourceSet: KotlinSourceSet): Boolean = sourceSet in allDeclaredSourceSets
override fun compilationsBySourceSet(sourceSet: KotlinSourceSet): Collection<KotlinCompilation>? =
sourceSetToParticipatedCompilations[sourceSet]
override fun sourceSetByName(name: String): KotlinSourceSet? = sourceSetsByName[name]
}
| apache-2.0 | b900889eb6ddace530b88b79e66af9c2 | 43.095588 | 158 | 0.733367 | 5.178756 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/util/StatsOutput.kt | 1 | 4229 | // 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.perf.util
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import org.jetbrains.kotlin.idea.perf.Stats
import org.jetbrains.kotlin.idea.testFramework.suggestOsNeutralFileName
import org.jetbrains.kotlin.test.KotlinRoot
import java.io.BufferedWriter
import java.io.File
internal fun List<Benchmark>.writeCSV(name: String) {
val header = listOf("benchmark", "name", "measurement", "value", "buildId", "timestamp")
fun Benchmark.append(output: BufferedWriter, warmUpValues: Boolean = false) {
fun values(n: String, value: Long?): String? = value?.let {
listOf(
benchmark,
this.name,
n,
value,
buildId?.toString() ?: "",
buildTimestamp
).joinToString()
}
val s = if (warmUpValues) {
val warmUpValue = metrics.firstOrNull { it.metricName == "_value" }?.let { metric ->
metric.rawMetrics?.firstOrNull { it.warmUp == true && it.index == 0 }?.metricValue
}
values(Stats.WARM_UP + " #0", warmUpValue)
} else {
values(Stats.GEOM_MEAN, metricValue)
}
s?.let(output::appendLine)
}
val statsFile = statsFile(name, "csv")
statsFile.bufferedWriter().use { output ->
output.appendLine(header.joinToString())
for (warmUpValue in arrayOf(true, false)) {
filterNot { it.name == Stats.GEOM_MEAN }.forEach { it.append(output, warmUpValues = warmUpValue) }
}
output.flush()
}
}
internal fun Metric.writeTeamCityStats(name: String, rawMeasurementName: String = "rawMetrics", rawMetrics: Boolean = false) {
fun Metric.append(prefix: String, depth: Int) {
val s = if (this.metricName.isEmpty()) {
prefix
} else {
if (depth == 0 && this.metricName != Stats.GEOM_MEAN) "$prefix: ${this.metricName}" else "$prefix ${this.metricName}"
}.trim()
if (s != prefix) {
metricValue?.let {
TeamCity.statValue(s, it)
}
}
metrics?.let { list ->
for (childIndex in list.withIndex()) {
if (!rawMetrics && childIndex.index > 0) break
childIndex.value.append(s, depth + 1)
}
}
}
append(name, 0)
}
internal val kotlinJsonMapper = jacksonObjectMapper()
.registerKotlinModule()
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.INDENT_OUTPUT, true)
internal fun Benchmark.statsFile() = statsFile(id(), "json")
internal fun Benchmark.writeJson() {
val json = kotlinJsonMapper.writeValueAsString(this)
val statsFile = statsFile()
logMessage { "write $statsFile" }
statsFile.bufferedWriter().use { output ->
output.appendLine(json)
output.flush()
}
}
internal fun File.loadBenchmark(): Benchmark = kotlinJsonMapper.readValue(this, object : TypeReference<Benchmark>() {})
internal fun Benchmark.loadJson() {
val statsFile = statsFile()
if (statsFile.exists()) {
val value = kotlinJsonMapper.readValue(statsFile, object : TypeReference<Benchmark>() {})
metrics = value.metrics
}
}
private fun statsFile(name: String, extension: String) =
pathToResource("stats${statFilePrefix(name)}.$extension").absoluteFile
internal fun pathToResource(resource: String) = File(KotlinRoot.REPO, "out/$resource").canonicalFile
internal fun statFilePrefix(name: String) = if (name.isNotEmpty()) "-${plainname(name)}" else ""
internal fun plainname(name: String) = suggestOsNeutralFileName(name)
| apache-2.0 | 786d1f436cc92e7a8cf5cebb8073ae32 | 37.099099 | 158 | 0.656893 | 4.276036 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/donate/card/CreditCardValidationState.kt | 1 | 580 | package org.thoughtcrime.securesms.components.settings.app.subscription.donate.card
data class CreditCardValidationState(
val type: CreditCardType,
val numberValidity: CreditCardNumberValidator.Validity,
val expirationValidity: CreditCardExpirationValidator.Validity,
val codeValidity: CreditCardCodeValidator.Validity
) {
val isValid: Boolean =
numberValidity == CreditCardNumberValidator.Validity.FULLY_VALID &&
expirationValidity == CreditCardExpirationValidator.Validity.FULLY_VALID &&
codeValidity == CreditCardCodeValidator.Validity.FULLY_VALID
}
| gpl-3.0 | 1a980739c5eff69499a5ebe669b217ec | 43.615385 | 83 | 0.818966 | 4.915254 | false | false | false | false |
androidx/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/UiDemos.kt | 3 | 11933 | /*
* 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.demos
import androidx.compose.foundation.demos.text.SoftwareKeyboardControllerDemo
import androidx.compose.integration.demos.common.ActivityDemo
import androidx.compose.integration.demos.common.ComposableDemo
import androidx.compose.integration.demos.common.DemoCategory
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.demos.autofill.ExplicitAutofillTypesDemo
import androidx.compose.ui.demos.focus.AdjacentScrollablesFocusDemo
import androidx.compose.ui.demos.focus.CancelFocusDemo
import androidx.compose.ui.demos.focus.CaptureFocusDemo
import androidx.compose.ui.demos.focus.ClickableInLazyColumnDemo
import androidx.compose.ui.demos.focus.ConditionalFocusabilityDemo
import androidx.compose.ui.demos.focus.CustomFocusOrderDemo
import androidx.compose.ui.demos.focus.ExplicitEnterExitWithCustomFocusEnterExitDemo
import androidx.compose.ui.demos.focus.FocusInDialogDemo
import androidx.compose.ui.demos.focus.FocusInPopupDemo
import androidx.compose.ui.demos.focus.FocusManagerMoveFocusDemo
import androidx.compose.ui.demos.focus.FocusableDemo
import androidx.compose.ui.demos.focus.OneDimensionalFocusSearchDemo
import androidx.compose.ui.demos.focus.ReuseFocusRequesterDemo
import androidx.compose.ui.demos.focus.ScrollableLazyRowFocusDemo
import androidx.compose.ui.demos.focus.ScrollableRowFocusDemo
import androidx.compose.ui.demos.focus.LazyListChildFocusDemos
import androidx.compose.ui.demos.focus.NestedLazyListFocusSearchDemo
import androidx.compose.ui.demos.focus.TwoDimensionalFocusSearchDemo
import androidx.compose.ui.demos.gestures.ButtonMetaStateDemo
import androidx.compose.ui.demos.gestures.DetectTapGesturesDemo
import androidx.compose.ui.demos.gestures.DetectTapPressureGesturesDemo
import androidx.compose.ui.demos.gestures.DoubleTapGestureFilterDemo
import androidx.compose.ui.demos.gestures.DoubleTapInTapDemo
import androidx.compose.ui.demos.gestures.DragAndScaleGestureFilterDemo
import androidx.compose.ui.demos.gestures.DragGestureFilterDemo
import androidx.compose.ui.demos.gestures.DragSlopExceededGestureFilterDemo
import androidx.compose.ui.demos.gestures.EventTypesDemo
import androidx.compose.ui.demos.gestures.HorizontalScrollersInVerticalScrollersDemo
import androidx.compose.ui.demos.gestures.LongPressDragGestureFilterDemo
import androidx.compose.ui.demos.gestures.LongPressGestureDetectorDemo
import androidx.compose.ui.demos.gestures.NestedLongPressDemo
import androidx.compose.ui.demos.gestures.NestedPressingDemo
import androidx.compose.ui.demos.gestures.NestedScrollDispatchDemo
import androidx.compose.ui.demos.gestures.NestedScrollingDemo
import androidx.compose.ui.demos.gestures.PointerInputDuringSubComp
import androidx.compose.ui.demos.gestures.PopupDragDemo
import androidx.compose.ui.demos.gestures.PressIndicatorGestureFilterDemo
import androidx.compose.ui.demos.gestures.RawDragGestureFilterDemo
import androidx.compose.ui.demos.gestures.ScaleGestureFilterDemo
import androidx.compose.ui.demos.gestures.ScrollGestureFilterDemo
import androidx.compose.ui.demos.gestures.VerticalScrollerInDrawerDemo
import androidx.compose.ui.demos.input.TouchModeDemo
import androidx.compose.ui.demos.keyinput.InterceptEnterToSendMessageDemo
import androidx.compose.ui.demos.keyinput.KeyInputDemo
import androidx.compose.ui.demos.modifier.CommunicatingModifierDemo
import androidx.compose.ui.demos.recyclerview.RecyclerViewDemos
import androidx.compose.ui.demos.viewinterop.AndroidInComposeDemos
import androidx.compose.ui.demos.viewinterop.BottomSheetFragmentNestedScrollInteropDemo
import androidx.compose.ui.demos.viewinterop.ComplexTouchInterop
import androidx.compose.ui.demos.viewinterop.ComposeInAndroidCoordinatorLayout
import androidx.compose.ui.demos.viewinterop.ComposeInAndroidDemos
import androidx.compose.ui.demos.viewinterop.ComposeViewComposeNestedInterop
import androidx.compose.ui.demos.viewinterop.EditTextInteropDemo
import androidx.compose.ui.demos.viewinterop.FocusTransferDemo
import androidx.compose.ui.demos.viewinterop.NestedScrollInteropComposeParentWithAndroidChild
import androidx.compose.ui.demos.viewinterop.ResizeComposeViewDemo
import androidx.compose.ui.demos.viewinterop.ViewComposeViewNestedScrollInteropDemo
import androidx.compose.ui.demos.viewinterop.ViewInteropDemo
import androidx.compose.ui.samples.NestedScrollConnectionSample
private val GestureDemos = DemoCategory(
"Gestures",
listOf(
DemoCategory(
"Common Gestures",
listOf(
ComposableDemo("Press Indication") { PressIndicatorGestureFilterDemo() },
ComposableDemo("Tap") { DetectTapGesturesDemo() },
ComposableDemo("Pressure Tap") { DetectTapPressureGesturesDemo() },
ComposableDemo("Double Tap") { DoubleTapGestureFilterDemo() },
ComposableDemo("Long Press") { LongPressGestureDetectorDemo() },
ComposableDemo("Scroll") { ScrollGestureFilterDemo() },
ComposableDemo("Drag") { DragGestureFilterDemo() },
ComposableDemo("Long Press Drag") { LongPressDragGestureFilterDemo() },
ComposableDemo("Scale") { ScaleGestureFilterDemo() },
ComposableDemo("Button/Meta State") { ButtonMetaStateDemo() },
ComposableDemo("Event Types") { EventTypesDemo() },
)
),
DemoCategory(
"Building Block Gestures",
listOf(
ComposableDemo("Drag Slop Exceeded") { DragSlopExceededGestureFilterDemo() },
ComposableDemo("Raw Drag") { RawDragGestureFilterDemo() }
)
),
DemoCategory(
"Combinations / Case Studies",
listOf(
ComposableDemo("Nested Pressing") { NestedPressingDemo() },
ComposableDemo("Horizontal Scrollers In Vertical Scroller") {
HorizontalScrollersInVerticalScrollersDemo()
},
ComposableDemo("Vertical Scroller in Nav Drawer") {
VerticalScrollerInDrawerDemo()
},
ComposableDemo("Nested Scrolling") { NestedScrollingDemo() },
ComposableDemo("Drag and Scale") { DragAndScaleGestureFilterDemo() },
ComposableDemo("Popup Drag") { PopupDragDemo() },
ComposableDemo("Double Tap in Tap") { DoubleTapInTapDemo() },
ComposableDemo("Nested Long Press") { NestedLongPressDemo() },
ComposableDemo("Pointer Input During Sub Comp") { PointerInputDuringSubComp() }
)
),
DemoCategory(
"New nested scroll",
listOf(
ComposableDemo("Nested scroll connection") { NestedScrollConnectionSample() },
ComposableDemo("Nested scroll dispatch") { NestedScrollDispatchDemo() }
)
)
)
)
private val FocusDemos = DemoCategory(
"Focus",
listOf(
ComposableDemo("Focusable Siblings") { FocusableDemo() },
ComposableDemo("Focus Within Dialog") { FocusInDialogDemo() },
ComposableDemo("Focus Within Popup") { FocusInPopupDemo() },
ComposableDemo("Reuse Focus Requester") { ReuseFocusRequesterDemo() },
ComposableDemo("1D Focus Search") { OneDimensionalFocusSearchDemo() },
ComposableDemo("2D Focus Search") { TwoDimensionalFocusSearchDemo() },
ComposableDemo("Custom Focus Order") { CustomFocusOrderDemo() },
ComposableDemo("Explicit Enter/Exit Focus Group") {
ExplicitEnterExitWithCustomFocusEnterExitDemo()
},
ComposableDemo("Cancel Focus Move") { CancelFocusDemo() },
ComposableDemo("FocusManager.moveFocus()") { FocusManagerMoveFocusDemo() },
ComposableDemo("Capture/Free Focus") { CaptureFocusDemo() },
ComposableDemo("Focus In Scrollable Row") { ScrollableRowFocusDemo() },
ComposableDemo("Focus in Lazy Row") { ScrollableLazyRowFocusDemo() },
ComposableDemo("LazyList Child Focusability") { LazyListChildFocusDemos() },
ComposableDemo("Focus In Adjacent Scrollable Rows") { AdjacentScrollablesFocusDemo() },
ComposableDemo("Clickable in LazyColumn") { ClickableInLazyColumnDemo() },
ComposableDemo("Nested LazyLists") { NestedLazyListFocusSearchDemo() },
ComposableDemo("Conditional Focusability") { ConditionalFocusabilityDemo() }
)
)
private val KeyInputDemos = DemoCategory(
"KeyInput",
listOf(
ComposableDemo("onKeyEvent") { KeyInputDemo() },
ComposableDemo("onPreviewKeyEvent") { InterceptEnterToSendMessageDemo() },
)
)
private val GraphicsDemos = DemoCategory(
"Graphics",
listOf(
ComposableDemo("VectorGraphicsDemo") { VectorGraphicsDemo() },
ComposableDemo("DeclarativeGraphicsDemo") { DeclarativeGraphicsDemo() },
ActivityDemo(
"Painter Resources Demo",
PainterResourcesDemoActivity::class
)
)
)
@OptIn(ExperimentalComposeUiApi::class)
private val NestedScrollInteropDemos = DemoCategory(
"Nested Scroll Interop",
listOf(
ActivityDemo(
"(Collaborating) View -> Compose",
ComposeInAndroidCoordinatorLayout::class
),
ActivityDemo(
"(Collaborating) View -> Compose -> View",
ViewComposeViewNestedScrollInteropDemo::class
),
ActivityDemo(
"Material Bottom Sheet Interop",
BottomSheetFragmentNestedScrollInteropDemo::class
),
ComposableDemo("Compose -> View") {
NestedScrollInteropComposeParentWithAndroidChild()
},
ComposableDemo("Compose -> (Collaborating) View -> Compose Interop") {
ComposeViewComposeNestedInterop()
}
)
)
private val ViewInteropDemos = DemoCategory(
"View Interop",
listOf(
ComposableDemo("Views interoperability") { ViewInteropDemo() },
ComposeInAndroidDemos,
AndroidInComposeDemos,
ComplexTouchInterop,
ComposableDemo("TextField Interop") { EditTextInteropDemo() },
ComposableDemo("Focus Transfer") { FocusTransferDemo() },
NestedScrollInteropDemos,
ComposableDemo("Resize ComposeView") { ResizeComposeViewDemo() },
)
)
private val ModifierDemos = DemoCategory(
"Modifiers",
listOf(
ComposableDemo("Inter-Modifier Communication") { CommunicatingModifierDemo() }
)
)
private val AccessibilityDemos = DemoCategory(
"Accessibility",
listOf(
ComposableDemo("Overlaid Nodes") { OverlaidNodeLayoutDemo() }
)
)
val CoreDemos = DemoCategory(
"Framework",
listOf(
ModifierDemos,
ComposableDemo("Explicit autofill types") { ExplicitAutofillTypesDemo() },
FocusDemos,
KeyInputDemos,
ComposableDemo("TouchMode") { TouchModeDemo() },
ComposableDemo("Multiple collects measure") { MultipleCollectTest() },
ComposableDemo("Dialog") { DialogDemo() },
ComposableDemo("Popup") { PopupDemo() },
GraphicsDemos,
GestureDemos,
ViewInteropDemos,
ComposableDemo("Software Keyboard Controller") { SoftwareKeyboardControllerDemo() },
RecyclerViewDemos,
AccessibilityDemos
)
)
| apache-2.0 | 4020396265f77b464268b53f0dea5ac6 | 45.613281 | 95 | 0.732004 | 4.924887 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/ConvertToBlockBodyIntention.kt | 1 | 5412 | // 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.k2.codeinsight.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.types.KtClassErrorType
import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferences
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.KotlinApplicableIntentionWithContext
import org.jetbrains.kotlin.idea.codeinsight.utils.adjustLineIndent
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
internal class ConvertToBlockBodyIntention :
KotlinApplicableIntentionWithContext<KtDeclarationWithBody, ConvertToBlockBodyIntention.Context>(KtDeclarationWithBody::class) {
class Context(
val returnTypeIsUnit: Boolean,
val returnTypeIsNothing: Boolean,
val returnTypeString: String,
val returnTypeClassId: ClassId?,
val bodyTypeIsUnit: Boolean,
val bodyTypeIsNothing: Boolean,
val reformat: Boolean,
)
override fun getFamilyName(): String = KotlinBundle.message("convert.to.block.body")
override fun getActionName(element: KtDeclarationWithBody, context: Context): String = familyName
override fun isApplicableByPsi(element: KtDeclarationWithBody): Boolean =
(element is KtNamedFunction || element is KtPropertyAccessor) && !element.hasBlockBody() && element.hasBody()
context(KtAnalysisSession)
override fun prepareContext(element: KtDeclarationWithBody): Context? {
if (element is KtNamedFunction) {
val returnType = element.getReturnKtType()
if (!element.hasDeclaredReturnType() && returnType is KtClassErrorType) return null
}
return createContextForDeclaration(element, reformat = true)
}
override fun apply(element: KtDeclarationWithBody, context: Context, project: Project, editor: Editor?) {
val body = element.bodyExpression ?: return
val newBody = when (element) {
is KtNamedFunction -> {
if (!element.hasDeclaredReturnType() && !context.returnTypeIsUnit) {
element.setType(context.returnTypeString, context.returnTypeClassId)
}
generateBody(body, context, returnsValue = !context.returnTypeIsUnit && !context.returnTypeIsNothing)
}
is KtPropertyAccessor -> {
val parent = element.parent
if (parent is KtProperty && parent.typeReference == null) {
parent.setType(context.returnTypeString, context.returnTypeClassId)
}
generateBody(body, context, element.isGetter)
}
else -> throw RuntimeException("Unknown declaration type: $element")
}
element.equalsToken?.delete()
val replaced = body.replace(newBody)
if (context.reformat) element.containingKtFile.adjustLineIndent(replaced.startOffset, replaced.endOffset)
}
override fun skipProcessingFurtherElementsAfter(element: PsiElement) =
element is KtDeclaration || super.skipProcessingFurtherElementsAfter(element)
}
private fun KtAnalysisSession.createContextForDeclaration(
declaration: KtDeclarationWithBody,
reformat: Boolean
): ConvertToBlockBodyIntention.Context? {
val body = declaration.bodyExpression ?: return null
val returnType = declaration.getReturnKtType().approximateToSuperPublicDenotableOrSelf()
val bodyType = body.getKtType() ?: return null
return ConvertToBlockBodyIntention.Context(
returnType.isUnit,
returnType.isNothing,
returnType.render(),
returnType.expandedClassSymbol?.classIdIfNonLocal,
bodyType.isUnit,
bodyType.isNothing,
reformat,
)
}
private fun generateBody(body: KtExpression, context: ConvertToBlockBodyIntention.Context, returnsValue: Boolean): KtExpression {
val factory = KtPsiFactory(body)
if (context.bodyTypeIsUnit && body is KtNameReferenceExpression) return factory.createEmptyBody()
val needReturn = returnsValue && (!context.bodyTypeIsUnit && !context.bodyTypeIsNothing)
return if (needReturn) {
val annotatedExpr = body as? KtAnnotatedExpression
val returnedExpr = annotatedExpr?.baseExpression ?: body
val block = factory.createSingleStatementBlock(factory.createExpressionByPattern("return $0", returnedExpr))
val statement = block.firstStatement
annotatedExpr?.annotationEntries?.forEach {
block.addBefore(it, statement)
block.addBefore(factory.createNewLine(), statement)
}
block
} else {
factory.createSingleStatementBlock(body)
}
}
private fun KtCallableDeclaration.setType(typeString: String, classId: ClassId?) {
val addedTypeReference = setTypeReference(KtPsiFactory(project).createType(typeString))
if (classId != null && addedTypeReference != null) {
shortenReferences(addedTypeReference)
}
}
| apache-2.0 | b9b491def64c50c32dc1a0ef315a7298 | 43.727273 | 158 | 0.724871 | 5.259475 | false | false | false | false |
siosio/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyDataclassInspection.kt | 1 | 30336 | /*
* 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.intellij.util.containers.isNullOrEmpty
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.resolve.PyResolveContext
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, session)
private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) {
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) {
super.visitPyCallExpression(node)
val resolveContext = PyResolveContext.defaultContext(myTypeEvalContext)
val callableType = node.multiResolveCallee(resolveContext).singleOrNull()
val callee = callableType?.callable
val calleeQName = callee?.qualifiedName
if (callableType != null && callee != null) {
val dataclassType = when {
DATACLASSES_HELPERS.contains(calleeQName) -> PyDataclassParameters.PredefinedType.STD
ATTRS_HELPERS.contains(calleeQName) -> PyDataclassParameters.PredefinedType.ATTRS
else -> return
}
val mapping = PyCallExpressionHelper.mapArguments(node, callableType, myTypeEvalContext)
val dataclassParameter = callee.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 (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 | 50c9851cf5905c360421468303d01144 | 42.152205 | 167 | 0.645669 | 5.295165 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/KotlinExtractSuperclassHandler.kt | 1 | 1734 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.extractClass
import com.intellij.java.refactoring.JavaRefactoringBundle
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringBundle
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.ui.KotlinExtractSuperclassDialog
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
object KotlinExtractSuperclassHandler : KotlinExtractSuperHandlerBase(false) {
val REFACTORING_NAME = KotlinBundle.message("text.extract.superclass")
override fun getErrorMessage(klass: KtClassOrObject): String? {
val superMessage = super.getErrorMessage(klass)
if (superMessage != null) return superMessage
if (klass is KtClass) {
if (klass.isInterface()) return RefactoringBundle.message("superclass.cannot.be.extracted.from.an.interface")
if (klass.isEnum()) return JavaRefactoringBundle.message("superclass.cannot.be.extracted.from.an.enum")
if (klass.isAnnotation()) return KotlinBundle.message("error.text.superclass.cannot.be.extracted.from.an.annotation.class")
}
return null
}
override fun createDialog(klass: KtClassOrObject, targetParent: PsiElement) =
KotlinExtractSuperclassDialog(
originalClass = klass,
targetParent = targetParent,
conflictChecker = { checkConflicts(klass, it) },
refactoring = { ExtractSuperRefactoring(it).performRefactoring() }
)
} | apache-2.0 | 1aecdb73fd461b74b2374a571fbf3d91 | 50.029412 | 158 | 0.750865 | 4.790055 | false | false | false | false |
JetBrains/kotlin-native | build-tools/src/main/kotlin/org/jetbrains/kotlin/bitcode/CompileToBitcode.kt | 1 | 6514 | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.bitcode
import org.gradle.api.DefaultTask
import org.gradle.api.file.FileCollection
import org.gradle.api.tasks.*
import org.jetbrains.kotlin.ExecClang
import org.jetbrains.kotlin.konan.target.Family
import org.jetbrains.kotlin.konan.target.HostManager
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.konan.target.SanitizerKind
import java.io.File
import javax.inject.Inject
open class CompileToBitcode @Inject constructor(
val srcRoot: File,
val folderName: String,
val target: String,
val outputGroup: String,
) : DefaultTask() {
enum class Language {
C, CPP
}
// Compiler args are part of compilerFlags so we don't register them as an input.
val compilerArgs = mutableListOf<String>()
@Input
val linkerArgs = mutableListOf<String>()
var excludeFiles: List<String> = listOf(
"**/*Test.cpp",
"**/*TestSupport.cpp",
"**/*Test.mm",
"**/*TestSupport.mm",
)
var includeFiles: List<String> = listOf(
"**/*.cpp",
"**/*.mm"
)
// Source files and headers are registered as inputs by the `inputFiles` and `headers` properties.
var srcDirs: FileCollection = project.files(srcRoot.resolve("cpp"))
var headersDirs: FileCollection = project.files(srcRoot.resolve("headers"))
@Input
var language = Language.CPP
@Input @Optional
var sanitizer: SanitizerKind? = null
private val targetDir: File
get() {
val sanitizerSuffix = when (sanitizer) {
null -> ""
SanitizerKind.ADDRESS -> "-asan"
SanitizerKind.THREAD -> "-tsan"
}
return project.buildDir.resolve("bitcode/$outputGroup/$target$sanitizerSuffix")
}
@get:Input
val objDir
get() = File(targetDir, folderName)
private val KonanTarget.isMINGW
get() = this.family == Family.MINGW
val executable
get() = when (language) {
Language.C -> "clang"
Language.CPP -> "clang++"
}
@get:Input
val compilerFlags: List<String>
get() {
val commonFlags = listOf("-c", "-emit-llvm") + headersDirs.map { "-I$it" }
val sanitizerFlags = when (sanitizer) {
null -> listOf()
SanitizerKind.ADDRESS -> listOf("-fsanitize=address")
SanitizerKind.THREAD -> listOf("-fsanitize=thread")
}
val languageFlags = when (language) {
Language.C ->
// Used flags provided by original build of allocator C code.
listOf("-std=gnu11", "-O3", "-Wall", "-Wextra", "-Werror")
Language.CPP ->
listOfNotNull("-std=c++17", "-Werror", "-O2",
"-Wall", "-Wextra",
"-Wno-unused-parameter", // False positives with polymorphic functions.
"-fPIC".takeIf { !HostManager().targetByName(target).isMINGW })
}
return commonFlags + sanitizerFlags + languageFlags + compilerArgs
}
@get:SkipWhenEmpty
@get:InputFiles
val inputFiles: Iterable<File>
get() {
return srcDirs.flatMap { srcDir ->
project.fileTree(srcDir) {
it.include(includeFiles)
it.exclude(excludeFiles)
}.files
}
}
private fun outputFileForInputFile(file: File, extension: String) = objDir.resolve("${file.nameWithoutExtension}.${extension}")
private fun bitcodeFileForInputFile(file: File) = outputFileForInputFile(file, "bc")
@get:InputFiles
protected val headers: Iterable<File>
get() {
// Not using clang's -M* flags because there's a problem with our current include system:
// We allow includes relative to the current directory and also pass -I for each imported module
// Given file tree:
// a:
// header.hpp
// b:
// impl.cpp
// Assume module b adds a to its include path.
// If b/impl.cpp has #include "header.hpp", it'll be included from a/header.hpp. If we add another file
// header.hpp into b/, the next compilation of b/impl.cpp will include b/header.hpp. -M flags, however,
// won't generate a dependency on b/header.hpp, so incremental compilation will be broken.
// TODO: Apart from dependency generation this also makes it awkward to have two files with
// the same name (e.g. Utils.h) in directories a/ and b/: For the b/impl.cpp to include a/header.hpp
// it needs to have #include "../a/header.hpp"
val dirs = mutableSetOf<File>()
// First add dirs with sources, as clang by default adds directory with the source to the include path.
inputFiles.forEach {
dirs.add(it.parentFile)
}
// Now add manually given header dirs.
dirs.addAll(headersDirs.files)
return dirs.flatMap { dir ->
project.fileTree(dir) {
val includePatterns = when (language) {
Language.C -> arrayOf("**/.h")
Language.CPP -> arrayOf("**/*.h", "**/*.hpp")
}
it.include(*includePatterns)
}.files
}
}
@get:OutputFile
val outFile: File
get() = File(targetDir, "${folderName}.bc")
@TaskAction
fun compile() {
objDir.mkdirs()
val plugin = project.convention.getPlugin(ExecClang::class.java)
plugin.execKonanClang(target) {
it.workingDir = objDir
it.executable = executable
it.args = compilerFlags + inputFiles.map { it.absolutePath }
}
project.exec {
val llvmDir = project.findProperty("llvmDir")
it.executable = "$llvmDir/bin/llvm-link"
it.args = listOf("-o", outFile.absolutePath) + linkerArgs +
inputFiles.map {
bitcodeFileForInputFile(it).absolutePath
}
}
}
}
| apache-2.0 | f6b09eabaa922d0cb18b6a0532852801 | 36.222857 | 131 | 0.57031 | 4.561625 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/AnalyzeDisposer.kt | 2 | 25047 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diagnostic.hprof.analysis
import com.intellij.diagnostic.hprof.classstore.ClassDefinition
import com.intellij.diagnostic.hprof.navigator.ObjectNavigator
import com.intellij.diagnostic.hprof.util.HeapReportUtils.toPaddedShortStringAsSize
import com.intellij.diagnostic.hprof.util.HeapReportUtils.toShortStringAsCount
import com.intellij.diagnostic.hprof.util.HeapReportUtils.toShortStringAsSize
import com.intellij.diagnostic.hprof.util.TreeNode
import com.intellij.diagnostic.hprof.util.TreeVisualizer
import com.intellij.diagnostic.hprof.util.TruncatingPrintBuffer
import com.intellij.util.ExceptionUtil
import it.unimi.dsi.fastutil.longs.*
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import java.util.*
import java.util.function.LongConsumer
class AnalyzeDisposer(private val analysisContext: AnalysisContext) {
private var prepareException: Exception? = null
data class Grouping(val childClass: ClassDefinition,
val parentClass: ClassDefinition?,
val rootClass: ClassDefinition)
class InstanceStats {
private val parentIds = LongArrayList()
private val rootIds = LongOpenHashSet()
fun parentCount() = LongOpenHashSet(parentIds).size
fun rootCount() = rootIds.size
fun objectCount() = parentIds.size
fun registerObject(parentId: Long, rootId: Long) {
parentIds.add(parentId)
rootIds.add(rootId)
}
}
data class DisposedDominatorReportEntry(val classDefinition: ClassDefinition, val count: Long, val size: Long)
companion object {
val TOP_REPORTED_CLASSES = setOf(
"com.intellij.openapi.project.impl.ProjectImpl"
)
}
fun prepareDisposerChildren() {
prepareException = null
val result = analysisContext.disposerParentToChildren
result.clear()
if (!analysisContext.classStore.containsClass("com.intellij.openapi.util.Disposer")) {
return
}
try {
val nav = analysisContext.navigator
nav.goToStaticField("com.intellij.openapi.util.Disposer", "ourTree")
analysisContext.disposerTreeObjectId = nav.id.toInt()
if (nav.getClass().refInstanceFields.any { it.name == "myObject2NodeMap" }) {
goToArrayOfDisposableObjectNodes(nav)
collectDisposerParentToChildren(nav, result)
}
else {
collectDisposerParentToChildrenNew(nav, result)
}
result.values.forEach(LongArrayList::trim)
}
catch (ex: Exception) {
prepareException = ex
}
}
private fun collectDisposerParentToChildren(nav: ObjectNavigator, result: Long2ObjectOpenHashMap<LongArrayList>) {
nav.getReferencesCopy().forEach {
if (it == 0L) return@forEach
nav.goTo(it)
verifyClassIsObjectNode(nav.getClass())
val objectNodeParentId = nav.getInstanceFieldObjectId(null, "myParent")
val childId = nav.getInstanceFieldObjectId(null, "myObject")
nav.goTo(objectNodeParentId)
val parentId = if (nav.isNull()) {
0L
}
else {
nav.getInstanceFieldObjectId(null, "myObject")
}
val childrenList = result.getOrPut(parentId) { LongArrayList() }
childrenList.add(childId)
}
}
private fun goToArrayOfDisposableObjectNodes(nav: ObjectNavigator) {
nav.goToStaticField("com.intellij.openapi.util.Disposer", "ourTree")
analysisContext.disposerTreeObjectId = nav.id.toInt()
verifyClassIsObjectTree(nav.getClass())
if (nav.isNull()) {
throw ObjectNavigator.NavigationException("Disposer.ourTree == null")
}
nav.goToInstanceField(null, "myObject2NodeMap")
if (nav.getClass().name == "gnu.trove.THashMap") {
nav.goToInstanceField("gnu.trove.THashMap", "_values")
}
else {
nav.goToInstanceField("it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap", "value")
}
if (nav.isNull()) {
throw ObjectNavigator.NavigationException("Collection of children is null")
}
if (!nav.getClass().isArray()) {
throw ObjectNavigator.NavigationException("Invalid type of map values collection: ${nav.getClass().name}")
}
}
private fun collectDisposerParentToChildrenNew(nav: ObjectNavigator, result: Long2ObjectOpenHashMap<LongArrayList>) {
nav.goToStaticField("com.intellij.openapi.util.Disposer", "ourTree")
analysisContext.disposerTreeObjectId = nav.id.toInt()
nav.goToInstanceField("com.intellij.openapi.util.ObjectTree", "myRootNode")
val rootObjectNodeIds = getObjectNodeChildrenIds(nav)
for (i in 0 until rootObjectNodeIds.size) {
val rootObjectNodeId = rootObjectNodeIds.getLong(i)
nav.goTo(rootObjectNodeId)
if (nav.isNull()) continue
val rootObjectId = nav.getInstanceFieldObjectId("com.intellij.openapi.util.ObjectNode", "myObject")
nav.goTo(rootObjectNodeId)
visitObjectTreeRecursively(nav, rootObjectNodeId, 0L, result/*, null, rootObjectId, rootObjectClass,
tooDeepObjectClasses, maxTreeDepth, 0, groupingToObjectStats*/)
}
}
private fun visitObjectTreeRecursively(nav: ObjectNavigator,
currentNodeId: Long,
parentObjectId: Long,
result: Long2ObjectOpenHashMap<LongArrayList>) {
nav.goTo(currentNodeId)
if (nav.isNull()) return
val currentObjectId = nav.getInstanceFieldObjectId("com.intellij.openapi.util.ObjectNode", "myObject")
result.getOrPut(parentObjectId) { LongArrayList() }.add(currentObjectId)
val childrenNodeIds = getObjectNodeChildrenIds(nav)
for (i in 0 until childrenNodeIds.size) {
val childNodeId = childrenNodeIds.getLong(i)
visitObjectTreeRecursively(nav, childNodeId, currentObjectId, result)
}
}
private fun getObjectNodeChildrenIds(nav: ObjectNavigator): LongList {
nav.goToInstanceField("com.intellij.openapi.util.ObjectNode", "myChildren")
return when (nav.getClass().name) {
Collections.emptyList<Any>().javaClass.name, "com.intellij.openapi.util.ObjectNode\$1" -> {
// no children
LongList.of()
}
"com.intellij.openapi.util.ObjectNode\$ListNodeChildren" -> {
nav.goToInstanceField("com.intellij.openapi.util.ObjectNode\$ListNodeChildren", "myChildren")
getSmartListChildren(nav)
}
"com.intellij.openapi.util.ObjectNode\$MapNodeChildren" -> {
nav.goToInstanceField("com.intellij.openapi.util.ObjectNode\$MapNodeChildren", "myChildren")
getMapNodeChildren(nav)
}
else -> {
getSmartListChildren(nav)
}
}
}
private fun getSmartListChildren(nav: ObjectNavigator): LongList {
nav.goToInstanceField("com.intellij.util.SmartList", "myElem")
if (nav.isNull()) return LongList.of()
if (nav.getClass().isArray()) {
return nav.getReferencesCopy()
}
else {
// myElem is ObjectNode
return LongList.of(nav.id)
}
}
private fun getMapNodeChildren(nav: ObjectNavigator): LongList {
nav.goToInstanceField("it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap", "value")
return nav.getReferencesCopy()
}
private fun verifyClassIsObjectNode(clazzObjectTree: ClassDefinition) {
if (clazzObjectTree.undecoratedName != "com.intellij.openapi.util.objectTree.ObjectNode" &&
clazzObjectTree.undecoratedName != "com.intellij.openapi.util.ObjectNode") {
throw ObjectNavigator.NavigationException("Wrong type, expected ObjectNode: ${clazzObjectTree.name}")
}
}
private fun verifyClassIsObjectTree(clazzObjectTree: ClassDefinition) {
if (clazzObjectTree.undecoratedName != "com.intellij.openapi.util.objectTree.ObjectTree" &&
clazzObjectTree.undecoratedName != "com.intellij.openapi.util.ObjectTree") {
throw ObjectNavigator.NavigationException("Wrong type, expected ObjectTree: ${clazzObjectTree.name}")
}
}
private class DisposerNode(val className: String) : TreeNode {
var count = 0
var subtreeSize = 0
var filteredSubtreeSize = 0
val children = HashMap<String, DisposerNode>()
fun equals(other: DisposerNode): Boolean = className == other.className
override fun equals(other: Any?): Boolean = other != null && other is DisposerNode && equals(other)
override fun hashCode() = className.hashCode()
override fun description(): String = "[$subtreeSize] $count $className"
override fun children(): Collection<TreeNode> = children.values.sortedByDescending { it.subtreeSize }
fun addInstance() {
count++
}
fun getChildForClassName(name: String): DisposerNode = children.getOrPut(name, { DisposerNode(name) })
}
private enum class SubTreeUpdaterOperation { PROCESS_CHILDREN, UPDATE_SIZE }
fun prepareDisposerTreeSummarySection(
disposerParentToChildren: Long2ObjectOpenHashMap<LongArrayList>,
options: AnalysisConfig.DisposerTreeSummaryOptions
): String = buildString {
TruncatingPrintBuffer(options.headLimit, 0, this::appendLine).use { buffer ->
if (!analysisContext.classStore.containsClass("com.intellij.openapi.util.Disposer")) {
return@buildString
}
prepareException?.let {
buffer.println(ExceptionUtil.getThrowableText(it))
return@buildString
}
val nav = analysisContext.navigator
try {
val rootNode = buildDisposerTree(analysisContext.disposerParentToChildren, nav)
// Update subtree size
data class SubtreeSizeUpdateStackObject(val node: DisposerNode, val operation: SubTreeUpdaterOperation)
val nodeStack = Stack<SubtreeSizeUpdateStackObject>()
nodeStack.push(SubtreeSizeUpdateStackObject(rootNode, SubTreeUpdaterOperation.PROCESS_CHILDREN))
while (!nodeStack.isEmpty()) {
val (currentNode, operation) = nodeStack.pop()
if (operation == SubTreeUpdaterOperation.PROCESS_CHILDREN) {
currentNode.subtreeSize = currentNode.count
currentNode.filteredSubtreeSize = currentNode.count
nodeStack.push(SubtreeSizeUpdateStackObject(currentNode, SubTreeUpdaterOperation.UPDATE_SIZE))
currentNode.children.values.forEach {
nodeStack.push(SubtreeSizeUpdateStackObject(it, SubTreeUpdaterOperation.PROCESS_CHILDREN))
}
}
else {
assert(operation == SubTreeUpdaterOperation.UPDATE_SIZE)
currentNode.children.values.forEach { currentNode.subtreeSize += it.subtreeSize }
currentNode.children.entries.removeIf { it.value.filteredSubtreeSize < options.nodeCutoff }
currentNode.children.values.forEach { currentNode.filteredSubtreeSize += it.subtreeSize }
}
}
val visualizer = TreeVisualizer()
buffer.println("Cutoff: ${options.nodeCutoff}")
buffer.println("Count of disposable objects: ${rootNode.subtreeSize}")
buffer.println()
rootNode.children().forEach {
visualizer.visualizeTree(it, buffer, analysisContext.config.disposerOptions.disposerTreeSummaryOptions)
buffer.println()
}
}
catch (ex: Exception) {
buffer.println(ExceptionUtil.getThrowableText(ex))
}
}
}
/**
* Build a map: object -> list of its disposable children
* Collect top-level objects (i.e. have no parent)
*/
private fun buildDisposerTree(disposerParentToChildren: Long2ObjectOpenHashMap<LongArrayList>,
nav: ObjectNavigator): DisposerNode {
val rootNode = DisposerNode("<root>")
data class StackObject(val node: DisposerNode, val childrenIds: LongCollection)
val stack = Stack<StackObject>()
stack.push(StackObject(rootNode, disposerParentToChildren[0L]))
while (!stack.empty()) {
val (currentNode, childrenIds) = stack.pop()
val nodeToChildren = HashMap<DisposerNode, LongArrayList>()
childrenIds.forEach(LongConsumer {
val childClassName = nav.getClassForObjectId(it).name
val childNode = currentNode.getChildForClassName(childClassName)
childNode.addInstance()
disposerParentToChildren[it]?.let {
nodeToChildren.getOrPut(childNode) { LongArrayList() }.addAll(it)
}
})
nodeToChildren.forEach { (node, children) -> stack.push(StackObject(node, children)) }
}
return rootNode
}
fun prepareDisposerTreeSection(): String = buildString {
if (!analysisContext.classStore.containsClass("com.intellij.openapi.util.Disposer")) {
return@buildString
}
prepareException?.let {
appendLine(ExceptionUtil.getThrowableText(it))
return@buildString
}
val nav = analysisContext.navigator
try {
val groupingToObjectStats = HashMap<Grouping, InstanceStats>()
val tooDeepObjectClasses = HashSet<ClassDefinition>()
val parentMap = Long2LongOpenHashMap()
analysisContext.disposerParentToChildren.forEach { parentId, childrenId ->
childrenId.forEach { childId -> parentMap.put(childId, parentId) }
}
val maxTreeDepth = 200
analysisContext.disposerParentToChildren.forEach { parentId, childrenId ->
childrenId.forEach { childId ->
val parentClass =
if (parentId == 0L)
null
else {
nav.goTo(parentId)
nav.getClass()
}
nav.goTo(childId)
val objectClass = nav.getClass()
val rootClass: ClassDefinition
val rootId: Long
if (parentId == 0L) {
rootClass = objectClass
rootId = childId
}
else {
var rootObjectId: Long = parentId
var iterationCount = 0
while (parentMap[rootObjectId] != 0L) {
rootObjectId = parentMap[rootObjectId]
iterationCount++
if (iterationCount == maxTreeDepth) break
}
if (iterationCount >= maxTreeDepth) {
tooDeepObjectClasses.add(objectClass)
rootId = parentId
rootClass = parentClass!!
}
else {
nav.goTo(rootObjectId)
rootId = rootObjectId
rootClass = nav.getClass()
}
}
groupingToObjectStats
.getOrPut(Grouping(objectClass, parentClass, rootClass)) { InstanceStats() }
.registerObject(parentId, rootId)
}
}
TruncatingPrintBuffer(400, 0, this::appendLine).use { buffer ->
groupingToObjectStats
.entries
.sortedByDescending { it.value.objectCount() }
.groupBy { it.key.rootClass }
.forEach { (rootClass, entries) ->
buffer.println("Root: ${rootClass.name}")
TruncatingPrintBuffer(100, 0, buffer::println).use { buffer ->
entries.forEach { (mapping, groupedObjects) ->
printDisposerTreeReportLine(buffer, mapping, groupedObjects)
}
}
buffer.println()
}
}
if (tooDeepObjectClasses.size > 0) {
appendLine("Skipped analysis of objects too deep in disposer tree:")
tooDeepObjectClasses.forEach {
appendLine(" * ${nav.classStore.getShortPrettyNameForClass(it)}")
}
}
} catch (ex : Exception) {
appendLine(ExceptionUtil.getThrowableText(ex))
}
}
private fun printDisposerTreeReportLine(buffer: TruncatingPrintBuffer,
mapping: Grouping,
groupedObjects: InstanceStats) {
val (sourceClass, parentClass, rootClass) = mapping
val nav = analysisContext.navigator
val objectCount = groupedObjects.objectCount()
val parentCount = groupedObjects.parentCount()
// Ignore 1-1 mappings
if (parentClass != null && objectCount == parentCount)
return
val parentString: String
if (parentClass == null) {
parentString = "(no parent)"
}
else {
val parentClassName = nav.classStore.getShortPrettyNameForClass(parentClass)
val rootCount = groupedObjects.rootCount()
if (rootClass != parentClass || rootCount != parentCount) {
parentString = "<-- $parentCount $parentClassName [...] $rootCount"
}
else
parentString = "<-- $parentCount"
}
val sourceClassName = nav.classStore.getShortPrettyNameForClass(sourceClass)
buffer.println(" ${String.format("%6d", objectCount)} $sourceClassName $parentString")
}
fun computeDisposedObjectsIDs() {
val disposedObjectsIDs = analysisContext.disposedObjectsIDs
disposedObjectsIDs.clear()
if (prepareException != null) {
return
}
try {
val nav = analysisContext.navigator
val parentList = analysisContext.parentList
if (!nav.classStore.containsClass("com.intellij.openapi.util.Disposer")) {
return
}
nav.goToStaticField("com.intellij.openapi.util.Disposer", "ourTree")
if (nav.isNull()) {
throw ObjectNavigator.NavigationException("ourTree is null")
}
verifyClassIsObjectTree(nav.getClass())
nav.goToInstanceField(null, "myDisposedObjects")
nav.goToInstanceField("com.intellij.util.containers.WeakHashMap", "myMap")
nav.goToInstanceField("com.intellij.util.containers.RefHashMap\$MyMap", "key")
val weakKeyClass = nav.classStore.getClassIfExists("com.intellij.util.containers.WeakHashMap\$WeakKey")
nav.getReferencesCopy().forEach {
if (it == 0L) {
return@forEach
}
nav.goTo(it, ObjectNavigator.ReferenceResolution.ALL_REFERENCES)
if (nav.getClass() != weakKeyClass) {
return@forEach
}
nav.goToInstanceField("com.intellij.util.containers.WeakHashMap\$WeakKey", "referent")
if (nav.id == 0L) return@forEach
val leakId = nav.id.toInt()
if (parentList.get(leakId) == 0) {
// If there is no parent, then the object does not have a strong-reference path to GC root
return@forEach
}
disposedObjectsIDs.add(leakId)
}
}
catch (navEx: ObjectNavigator.NavigationException) {
prepareException = navEx
}
}
fun prepareDisposedObjectsSection(): String = buildString {
val leakedInstancesByClass = HashMap<ClassDefinition, LongList>()
val countByClass = Object2IntOpenHashMap<ClassDefinition>()
var totalCount = 0
val nav = analysisContext.navigator
val disposedObjectsIDs = analysisContext.disposedObjectsIDs
val disposerOptions = analysisContext.config.disposerOptions
disposedObjectsIDs.forEach {
nav.goTo(it.toLong(), ObjectNavigator.ReferenceResolution.ALL_REFERENCES)
val leakClass = nav.getClass()
val leakId = nav.id
leakedInstancesByClass.computeIfAbsent(leakClass) { LongArrayList() }.add(leakId)
countByClass.put(leakClass, countByClass.getInt(leakClass) + 1)
totalCount++
}
// Convert TObjectIntHashMap to list of entries
data class TObjectIntMapEntry<T>(val key: T, val value: Int)
val entries = mutableListOf<TObjectIntMapEntry<ClassDefinition>>()
countByClass.object2IntEntrySet().fastForEach {
entries.add(TObjectIntMapEntry(it.key, it.intValue))
}
if (disposerOptions.includeDisposedObjectsSummary) {
// Print counts of disposed-but-strong-referenced objects
TruncatingPrintBuffer(100, 0, this::appendLine).use { buffer ->
buffer.println("Count of disposed-but-strong-referenced objects: $totalCount")
entries
.sortedByDescending { it.value }
.partition { TOP_REPORTED_CLASSES.contains(it.key.name) }
.let { it.first + it.second }
.forEach { entry ->
buffer.println(" ${entry.value} ${entry.key.prettyName}")
}
}
appendLine()
}
val disposedTree = GCRootPathsTree(analysisContext, AnalysisConfig.TreeDisplayOptions.all(), null)
for (disposedObjectsID in disposedObjectsIDs) {
disposedTree.registerObject(disposedObjectsID)
}
val disposedDominatorNodesByClass = disposedTree.getDisposedDominatorNodes()
var allDominatorsCount = 0L
var allDominatorsSubgraphSize = 0L
val disposedDominatorClassSizeList = mutableListOf<DisposedDominatorReportEntry>()
disposedDominatorNodesByClass.forEach { (classDefinition, nodeList) ->
var dominatorClassSubgraphSize = 0L
var dominatorClassInstanceCount = 0L
nodeList.forEach {
dominatorClassInstanceCount += it.instances.size
dominatorClassSubgraphSize += it.totalSizeInDwords.toLong() * 4
}
allDominatorsCount += dominatorClassInstanceCount
allDominatorsSubgraphSize += dominatorClassSubgraphSize
disposedDominatorClassSizeList.add(
DisposedDominatorReportEntry(classDefinition, dominatorClassInstanceCount, dominatorClassSubgraphSize))
}
if (disposerOptions.includeDisposedObjectsSummary) {
TruncatingPrintBuffer(30, 0, this::appendLine).use { buffer ->
buffer.println("Disposed-but-strong-referenced dominator object count: $allDominatorsCount")
buffer.println(
"Disposed-but-strong-referenced dominator sub-graph size: ${toShortStringAsSize(allDominatorsSubgraphSize)}")
disposedDominatorClassSizeList
.sortedByDescending { it.size }
.forEach { entry ->
buffer.println(
" ${toPaddedShortStringAsSize(entry.size)} - ${toShortStringAsCount(entry.count)} ${entry.classDefinition.name}")
}
}
appendLine()
}
if (disposerOptions.includeDisposedObjectsDetails) {
val instancesListInOrder = getInstancesListInPriorityOrder(
leakedInstancesByClass,
disposedDominatorClassSizeList
)
TruncatingPrintBuffer(700, 0, this::appendLine).use { buffer ->
instancesListInOrder
.forEach { instances ->
nav.goTo(instances.getLong(0))
buffer.println(
"Disposed but still strong-referenced objects: ${instances.size} ${nav.getClass().prettyName}, most common paths from GC-roots:")
val gcRootPathsTree = GCRootPathsTree(analysisContext, disposerOptions.disposedObjectsDetailsTreeDisplayOptions, nav.getClass())
instances.forEach { leakId ->
gcRootPathsTree.registerObject(leakId.toInt())
}
gcRootPathsTree.printTree().lineSequence().forEach(buffer::println)
}
}
}
}
private fun getInstancesListInPriorityOrder(
classToLeakedIdsList: HashMap<ClassDefinition, LongList>,
disposedDominatorReportEntries: List<DisposedDominatorReportEntry>): List<LongList> {
val result = mutableListOf<LongList>()
// Make a mutable copy. When a class instances are added to the result list, remove the class entry from the copy.
val classToLeakedIdsListCopy = HashMap(classToLeakedIdsList)
// First, all top classes
TOP_REPORTED_CLASSES.forEach { topClassName ->
classToLeakedIdsListCopy
.filterKeys { it.name == topClassName }
.forEach { (classDefinition, list) ->
result.add(list)
classToLeakedIdsListCopy.remove(classDefinition)
}
}
// Alternate between class with most instances leaked and class with most bytes leaked
// Prepare instance count class list by priority
val classOrderByInstanceCount = ArrayDeque(
classToLeakedIdsListCopy
.entries
.sortedByDescending { it.value.size }
.map { it.key }
)
// Prepare dominator bytes count class list by priority
val classOrderByByteCount = ArrayDeque(
disposedDominatorReportEntries
.sortedByDescending { it.size }
.map { it.classDefinition }
)
// zip, but ignore duplicates
var nextByInstanceCount = true
while (!classOrderByInstanceCount.isEmpty() ||
!classOrderByByteCount.isEmpty()) {
val nextCollection = if (nextByInstanceCount) classOrderByInstanceCount else classOrderByByteCount
if (!nextCollection.isEmpty()) {
val nextClass = nextCollection.removeFirst()
val list = classToLeakedIdsListCopy.remove(nextClass) ?: continue
result.add(list)
}
nextByInstanceCount = !nextByInstanceCount
}
return result
}
} | apache-2.0 | 3482668c313e75462d75463a8608705a | 36.951515 | 143 | 0.681838 | 4.5 | false | false | false | false |
BenWoodworth/FastCraft | fastcraft-bukkit/bukkit-1.13/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/gui/FcGuiButton_Bukkit_1_13.kt | 1 | 2223 | package net.benwoodworth.fastcraft.bukkit.gui
import net.benwoodworth.fastcraft.bukkit.util.updateMeta
import net.benwoodworth.fastcraft.platform.gui.FcGuiButton
import net.benwoodworth.fastcraft.platform.text.FcText
import net.benwoodworth.fastcraft.platform.text.FcTextConverter
import net.benwoodworth.fastcraft.platform.world.FcItem
import net.benwoodworth.fastcraft.platform.world.FcItemStack
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.meta.Damageable
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
open class FcGuiButton_Bukkit_1_13(
inventory: Inventory,
slotIndex: Int,
locale: Locale,
fcTextFactory: FcText.Factory,
fcTextConverter: FcTextConverter,
fcItemOperations: FcItem.Operations,
fcItemStackOperations: FcItemStack.Operations,
) : FcGuiButton_Bukkit_1_8(
inventory = inventory,
slotIndex = slotIndex,
locale = locale,
fcTextFactory = fcTextFactory,
fcTextConverter = fcTextConverter,
fcItemOperations = fcItemOperations,
fcItemStackOperations = fcItemStackOperations,
) {
override fun updateDamage() {
if (!isProgressSet) return
val maxDurability = itemStack.type.maxDurability.toInt()
itemStack.updateMeta {
if (this is Damageable) {
damage = calculateDurability(_progress, maxDurability)
}
}
}
@Singleton
class Factory @Inject constructor(
private val fcTextFactory: FcText.Factory,
private val fcTextConverter: FcTextConverter,
private val fcItemOperations: FcItem.Operations,
private val fcItemStackOperations: FcItemStack.Operations,
) : FcGuiButton_Bukkit.Factory {
override fun create(inventory: Inventory, slotIndex: Int, locale: Locale): FcGuiButton {
return FcGuiButton_Bukkit_1_13(
inventory = inventory,
slotIndex = slotIndex,
locale = locale,
fcTextFactory = fcTextFactory,
fcTextConverter = fcTextConverter,
fcItemOperations = fcItemOperations,
fcItemStackOperations = fcItemStackOperations,
)
}
}
}
| gpl-3.0 | eea7f534649e5ef5752b313d05c9165a | 34.285714 | 96 | 0.702654 | 5.075342 | false | false | false | false |
TimePath/java-vfs | src/main/kotlin/com/timepath/vfs/MockFile.kt | 1 | 267 | package com.timepath.vfs
public class MockFile(override val name: String, contents: String? = null) : SimpleVFile() {
private val bytes = contents?.toByteArray()
override val isDirectory = bytes == null
override fun openStream() = bytes?.inputStream
}
| artistic-2.0 | 3e356c70e6d1ce2afad492103be0a634 | 28.666667 | 92 | 0.719101 | 4.377049 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/test/kotlin/org/maxur/mserv/core/EitherSpec.kt | 1 | 2132 | package org.maxur.mserv.core
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
@RunWith(JUnitPlatform::class)
class EitherSpec : Spek({
describe("Build either") {
context("as right") {
val right: Either<String, String> = right("R")
it("should create new instance") {
assertThat(right).isNotNull()
}
it("should fold right value") {
val result = right.fold(
{ throw AssertionError("it's left but must be right") },
{ r -> r + "1" }
)
assertThat(result).isEqualTo("R1")
}
it("should map right value by mapRight") {
val result = right.mapRight { r -> right(r + "1") }
assertThat(result).isEqualTo(right("R1"))
}
it("should do nothing by mapLeft") {
val result = right.mapLeft { r -> left(r + "1") }
assertThat(result).isEqualTo(right)
}
}
context("as left") {
val left: Either<String, String> = left("L")
it("should create new instance") {
assertThat(left).isNotNull()
}
it("should fold right value") {
val result = left.fold(
{ l -> l + "1" },
{ throw AssertionError("it's right but must be left") }
)
assertThat(result).isEqualTo("L1")
}
it("should do nothing by mapRight") {
val result = left.mapRight { r -> right(r + "1") }
assertThat(result).isEqualTo(left)
}
it("should map left value by mapLeft") {
val result = left.mapLeft { r -> r + "1" }
assertThat(result).isEqualTo(left("L1"))
}
}
}
})
| apache-2.0 | 4e94016c18b758071a018d4439edc521 | 32.84127 | 76 | 0.505629 | 4.404959 | false | false | false | false |
byoutline/SecretSauce | SecretSauce/src/main/java/com/byoutline/secretsauce/SecretSauceSettings.kt | 1 | 3312 | package com.byoutline.secretsauce
import androidx.lifecycle.ViewModelProvider
import android.content.Context
import androidx.annotation.IdRes
/**
* Initializes some variables globally for SecretSauce.
* As an alternative you usually can pass those values as method optional
* parameter.
*
* @author Sebastian Kacprzak <nait at naitbit.com>
*/
object SecretSauceSettings {
var DEBUG: Boolean = false
private var containerViewId: Int? = null
internal fun getContainerViewId(): Int = checkNotNull(containerViewId)
{ "Attempt to use method that requires `containerViewId` without setting it first" }
private var brViewModelId: Int? = null
internal fun getBrViewModelId(): Int = checkNotNull(brViewModelId)
{ "Attempt to use method that requires `brViewModelId` without setting it first" }
var logPrefix = "SecretS"
var viewModelFactoryProvider: (ctx: Context) -> ViewModelProvider.Factory = {
throw IllegalStateException("You must init viewModelFactoryProvider")
}
var useFragmentViewModelProvider: Boolean = true
/**
* @param debug - If true enables debug toasts, and low priority logs in [com.byoutline.secretsauce.utils.LogUtils]
* @param containerViewId - Default value for [com.byoutline.secretsauce.activities.showFragment]
* @param bindingViewModelId - Default value for DataBinding methods that set ViewModel
* @param viewModelFactoryProvider - Required for using getViewModel and related extension function
* @param setFastJodaTimeZoneProvider - If true System property will be set so Joda time uses [com.byoutline.secretsauce.utils.JdkBasedTimeZoneProvider]
* which is faster on Android. If there is no Joda dependency in classpath this will do nothing.
* @param useFragmentViewModelProvider - Default lifecycle for ViewModels [com.byoutline.secretsauce.lifecycle.getVMWithAutoLifecycle]
*/
fun set(
debug: Boolean = DEBUG,
@IdRes containerViewId: Int = this.containerViewId ?: ID_NOT_SET,
bindingViewModelId: Int = brViewModelId ?: ID_NOT_SET,
viewModelFactoryProvider: (ctx: Context) -> ViewModelProvider.Factory = this.viewModelFactoryProvider,
setFastJodaTimeZoneProvider: Boolean = true,
useFragmentViewModelProvider: Boolean = this.useFragmentViewModelProvider
) {
require(bindingViewModelId > 0 || bindingViewModelId == ID_NOT_SET) { "containerViewId cannot be negative, given: $containerViewId" }
if (containerViewId != ID_NOT_SET) this.containerViewId = containerViewId
if (bindingViewModelId != ID_NOT_SET) brViewModelId = bindingViewModelId
DEBUG = debug
this.viewModelFactoryProvider = viewModelFactoryProvider
this.useFragmentViewModelProvider = useFragmentViewModelProvider
if (setFastJodaTimeZoneProvider) {
setFastJodaTimeZoneProvider()
}
}
private fun setFastJodaTimeZoneProvider() {
try {
Class.forName("org.joda.time.DateTimeZone")
System.setProperty(
"org.joda.time.DateTimeZone.Provider",
"com.byoutline.secretsauce.utils.JdkBasedTimeZoneProvider"
)
} catch (ignored: ClassNotFoundException) {
}
}
}
private const val ID_NOT_SET = -877726
| apache-2.0 | 1f50d42a115d895f3778d6569364a7cc | 45.647887 | 156 | 0.724638 | 4.806967 | false | false | false | false |
aspanu/KibarDataApi | src/main/kotlin/id/kibar/api/data/Main.kt | 1 | 2025 | package id.kibar.api.data
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import id.kibar.api.data.entity.User
import id.kibar.api.data.service.RegistrationService
import io.javalin.Javalin
import javax.xml.ws.http.HTTPException
fun main(args: Array<String>) {
val regService = RegistrationService()
val app = Javalin.create().port(7070).start()
with(app) {
get("/user/emailIdentification/:email") { ctx ->
ctx.json(regService.getUserIdForEmail(ctx.param("email")!!))
}
post("/user/checkIn") { ctx ->
regService.checkIn(ctx.queryParam("userId")!!.toInt(), ctx.queryParam("activityId")!!.toInt())
ctx.status(204)
}
post("/user/activity/register") { ctx ->
regService.registerUserForActivity(
ctx.queryParam("userId")!!.toInt(),
ctx.queryParam("activityId")!!.toInt()
)
ctx.status(204)
}
post("/activity/create") { ctx ->
val activityId = regService.createActivity(
ctx.formParam("name")!!,
ctx.formParam("description")!!,
ctx.formParam("activityDate")!!
)
ctx.status(200).json("activityId: $activityId")
}
post("/user/signIn") { ctx ->
val sub = ctx.formParam("sub") ?: throw HTTPException(400)
val email = ctx.formParam("email") ?: throw HTTPException(400)
val name = ctx.formParam("name") ?: ""
val newUser = regService.signInUserIsNew(name = name, email = email, sub = sub)
ctx.status(201).json(newUser)
}
post("/user/update") { ctx ->
val mapper = ObjectMapper().registerKotlinModule()
val user = mapper.readValue(ctx.body(), User::class.java)
regService.save(user)
ctx.status(200).json("Updated user: ${user.id} successfully")
}
}
}
| gpl-3.0 | 207cb9830a578b96edac5b50e7e47bf2 | 32.196721 | 106 | 0.58321 | 4.272152 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/download/src/main/java/jp/hazuki/yuzubrowser/download/core/utils/DownloadInternalUtils.kt | 1 | 9542 | /*
* Copyright (C) 2017-2021 Hazuki
*
* 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 jp.hazuki.yuzubrowser.download.core.utils
import android.content.ContentResolver
import android.content.Context
import android.media.MediaScannerConnection
import android.net.Uri
import android.text.format.Formatter
import android.util.Base64
import androidx.documentfile.provider.DocumentFile
import jp.hazuki.yuzubrowser.core.utility.storage.toDocumentFile
import jp.hazuki.yuzubrowser.core.utility.utils.FileUtils
import jp.hazuki.yuzubrowser.core.utility.utils.createUniqueFileName
import jp.hazuki.yuzubrowser.core.utility.utils.getExtensionFromMimeType
import jp.hazuki.yuzubrowser.core.utility.utils.getMimeTypeFromExtension
import jp.hazuki.yuzubrowser.download.TMP_FILE_SUFFIX
import jp.hazuki.yuzubrowser.download.core.data.DownloadFileInfo
import java.io.IOException
import java.net.URLDecoder
import java.util.*
internal fun ContentResolver.saveBase64Image(imageData: Base64Image, file: DocumentFile): Boolean {
if (imageData.isValid) {
try {
val image = Base64.decode(imageData.getData(), Base64.DEFAULT)
openOutputStream(file.uri)?.use { outputStream ->
outputStream.write(image)
outputStream.flush()
return true
}
} catch (e: IllegalArgumentException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
return false
}
internal fun decodeBase64Image(url: String): Base64Image {
return Base64Image(url)
}
internal class Base64Image(url: String) {
val data: Array<String> = url.split(',').dropLastWhile { it.isEmpty() }.toTypedArray()
val isValid: Boolean
get() = data.size >= 2
val header: String
get() = data[0]
val mimeType: String
get() = data[0].split(':')[1].split(';').first()
fun getData(): String {
return data[1]
}
}
internal fun guessDownloadFileName(root: DocumentFile, url: String, contentDisposition: String?, mimetype: String?, defaultExt: String?): String {
var guessType = mimetype
if (url.startsWith("data:")) {
val data = url.split(',').dropLastWhile { it.isEmpty() }.toTypedArray()
if (data.size > 1) {
guessType = data[0].split(';').dropLastWhile { it.isEmpty() }.toTypedArray()[0].substring(5)
}
}
if ("application/octet-stream" == guessType) {
guessType = null
}
var filename = guessFileName(url, contentDisposition, guessType)
if (filename.isEmpty()) {
filename = "index.html"
}
var extension = defaultExt
if (filename.endsWith(".bin") && mimetype != null && defaultExt == null) {
when (mimetype) {
"multipart/related", "message/rfc822", "application/x-mimearchive" -> extension = ".mhtml"
"application/javascript", "application/x-javascript", "text/javascript" -> extension = ".js"
}
}
if (filename.endsWith(".bin") && extension != null) {
var decodedUrl: String? = Uri.decode(url)
if (decodedUrl != null) {
val queryIndex = decodedUrl.indexOf('?')
// If there is a query string strip it, same as desktop browsers
if (queryIndex > 0) {
decodedUrl = decodedUrl.substring(0, queryIndex)
}
if (!decodedUrl.endsWith("/")) {
val index = decodedUrl.lastIndexOf('/') + 1
if (index > 0) {
filename = decodedUrl.substring(index)
if (filename.indexOf('.') < 0) {
filename += defaultExt
}
}
}
}
}
return createUniqueFileName(root, filename, TMP_FILE_SUFFIX)
}
private fun guessFileName(url: String, contentDisposition: String?, mimeType: String?): String {
var fileName = if (contentDisposition != null) guessFileNameFromContentDisposition(contentDisposition) else null
if (fileName != null) return fileName
if (url.startsWith("data:")) {
fileName = System.currentTimeMillis().toString()
} else {
// If all the other http-related approaches failed, use the plain uri
var decodedUrl: String? = Uri.decode(url)
if (decodedUrl != null) {
val queryIndex = decodedUrl.indexOf('?')
// If there is a query string strip it, same as desktop browsers
if (queryIndex > 0) {
decodedUrl = decodedUrl.substring(0, queryIndex)
}
if (!decodedUrl.endsWith("/")) {
val index = decodedUrl.lastIndexOf('/') + 1
if (index > 0) {
fileName = FileUtils.replaceProhibitionWord(decodedUrl.substring(index))
}
}
}
}
// Finally, if couldn't get filename from URI, get a generic filename
if (fileName == null) {
fileName = "downloadfile"
}
val dotIndex = fileName.indexOf('.')
var extension: String? = null
if (dotIndex < 0) {
if (mimeType != null) {
extension = getExtensionFromMimeType(mimeType)
if (extension != null) {
extension = ".$extension"
}
}
if (extension == null) {
extension = if (mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("text/")) {
if (mimeType.equals("text/html", ignoreCase = true)) {
".html"
} else {
".txt"
}
} else {
".bin"
}
}
} else {
if (mimeType != null) {
// Compare the last segment of the extension against the mime type.
// If there's a mismatch, discard the entire extension.
val lastDotIndex = fileName.lastIndexOf('.')
val typeFromExt = getMimeTypeFromExtension(fileName.substring(lastDotIndex + 1))
if (!typeFromExt.equals(mimeType, ignoreCase = true)) {
extension = getExtensionFromMimeType(mimeType)
if (extension != null) {
extension = ".$extension"
}
}
}
if (extension == null) {
extension = fileName.substring(dotIndex)
}
fileName = fileName.substring(0, dotIndex)
}
if (extension == ".htm") {
extension = ".html"
}
if (fileName.length + extension.length > 127) {
val size = 127 - extension.length
fileName = if (size > 0) {
fileName.substring(0, 127 - extension.length)
} else {
""
}
}
return fileName + extension
}
private const val NAME_UTF_8 = "filename\\*=UTF-8''(\\S+)"
private const val NAME_NORMAL = "filename=\"(.*)\""
private const val NAME_NO_QUOT = "filename=(\\S+)"
internal fun guessFileNameFromContentDisposition(contentDisposition: String): String? {
val utf8 = NAME_UTF_8.toRegex().find(contentDisposition)
if (utf8 != null) {
/** RFC 6266 */
return URLDecoder.decode(utf8.groupValues[1], "UTF-8")
}
val normal = NAME_NORMAL.toRegex().find(contentDisposition)
if (normal != null) {
return FileUtils.replaceProhibitionWord(
try {
URLDecoder.decode(normal.groupValues[1], "UTF-8")
} catch (e: IllegalArgumentException) {
normal.groupValues[1]
}
)
}
val noQuot = NAME_NO_QUOT.toRegex().find(contentDisposition)
if (noQuot != null) {
return FileUtils.replaceProhibitionWord(
try {
URLDecoder.decode(noQuot.groupValues[1], "UTF-8")
} catch (e: IllegalArgumentException) {
noQuot.groupValues[1]
}
)
}
return null
}
internal fun DownloadFileInfo.getNotificationString(context: Context): String {
return if (size > 0) {
"${currentSize * 100 / size}% (${Formatter.formatFileSize(context, currentSize)}" +
" / ${Formatter.formatFileSize(context, size)}" +
" ${Formatter.formatFileSize(context, transferSpeed)}/s)"
} else {
Formatter.formatFileSize(context, currentSize) +
" ${Formatter.formatFileSize(context, transferSpeed)}/s"
}
}
internal fun DownloadFileInfo.getFile(context: Context): DocumentFile? {
return if (state == DownloadFileInfo.STATE_DOWNLOADED) {
val file = root.toDocumentFile(context)
when {
file.isFile -> file
file.isDirectory -> file.findFile(name)
else -> null
}
} else {
null
}
}
internal fun DownloadFileInfo.checkFlag(flag: Int): Boolean = (state and flag) == flag
internal fun Context.registerMediaScanner(vararg path: String) {
MediaScannerConnection.scanFile(applicationContext, path, null, null)
}
| apache-2.0 | f255de6d8d0055a23da7fb191ee4ed05 | 33.447653 | 146 | 0.598721 | 4.488241 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/util/AppPermissions.kt | 1 | 3657 | package com.orgzly.android.util
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.ui.CommonActivity
import com.orgzly.android.ui.showSnackbar
import com.orgzly.android.ui.util.ActivityUtils
object AppPermissions {
private val TAG = AppPermissions::class.java.name
@JvmStatic
fun isGrantedOrRequest(activity: CommonActivity, requestCode: Usage): Boolean {
val permission = permissionForRequest(requestCode)
val rationale = rationaleForRequest(requestCode)
val grantedOrRequested = if (!isGranted(activity, requestCode)) {
/* Should we show an explanation? */
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
activity.showSnackbar(rationale, R.string.settings) {
ActivityUtils.openAppInfoSettings(activity)
}
} else {
/* No explanation needed -- request the permission. */
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, requestCode, permission, "Requesting...")
ActivityCompat.requestPermissions(activity, arrayOf(permission), requestCode.ordinal)
}
false
} else {
true
}
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, requestCode, permission, grantedOrRequested)
return grantedOrRequested
}
@JvmStatic
fun isGranted(context: Context, requestCode: Usage): Boolean {
val permission = permissionForRequest(requestCode)
// WRITE_EXTERNAL_STORAGE is unused in API 30 and later
if (permission == Manifest.permission.WRITE_EXTERNAL_STORAGE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (BuildConfig.LOG_DEBUG)
LogUtils.d(TAG, requestCode, permission, "API " + Build.VERSION.SDK_INT + ", returning true")
return true
}
val isGranted = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, requestCode, permission, isGranted)
return isGranted
}
/** Map request code to permission. */
private fun permissionForRequest(requestCode: Usage): String {
return when (requestCode) {
Usage.LOCAL_REPO -> Manifest.permission.WRITE_EXTERNAL_STORAGE
Usage.BOOK_EXPORT -> Manifest.permission.WRITE_EXTERNAL_STORAGE
Usage.SYNC_START -> Manifest.permission.WRITE_EXTERNAL_STORAGE
Usage.SAVED_SEARCHES_EXPORT_IMPORT -> Manifest.permission.WRITE_EXTERNAL_STORAGE
Usage.EXTERNAL_FILES_ACCESS -> Manifest.permission.READ_EXTERNAL_STORAGE
}
}
/** Map request code to explanation. */
private fun rationaleForRequest(requestCode: Usage): Int {
return when (requestCode) {
Usage.LOCAL_REPO -> R.string.permissions_rationale_for_local_repo
Usage.BOOK_EXPORT -> R.string.permissions_rationale_for_book_export
Usage.SYNC_START -> R.string.permissions_rationale_for_sync_start
Usage.SAVED_SEARCHES_EXPORT_IMPORT -> R.string.storage_permissions_missing
Usage.EXTERNAL_FILES_ACCESS -> R.string.permissions_rationale_for_external_files_access
}
}
enum class Usage {
LOCAL_REPO,
BOOK_EXPORT,
SYNC_START,
SAVED_SEARCHES_EXPORT_IMPORT,
EXTERNAL_FILES_ACCESS
}
}
| gpl-3.0 | 2da0d71e8f7e5578b4b85593ab720b2a | 37.494737 | 121 | 0.67405 | 4.755527 | false | true | false | false |
solokot/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/ExcludeFolderDialog.kt | 1 | 2826 | package com.simplemobiletools.gallery.pro.dialogs
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.getBasePath
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import kotlinx.android.synthetic.main.dialog_exclude_folder.view.*
class ExcludeFolderDialog(val activity: BaseSimpleActivity, val selectedPaths: List<String>, val callback: () -> Unit) {
val alternativePaths = getAlternativePathsList()
var radioGroup: RadioGroup? = null
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_exclude_folder, null).apply {
exclude_folder_parent.beVisibleIf(alternativePaths.size > 1)
radioGroup = exclude_folder_radio_group
exclude_folder_radio_group.beVisibleIf(alternativePaths.size > 1)
}
alternativePaths.forEachIndexed { index, value ->
val radioButton = (activity.layoutInflater.inflate(R.layout.radio_button, null) as RadioButton).apply {
text = alternativePaths[index]
isChecked = index == 0
id = index
}
radioGroup!!.addView(radioButton, RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
val path = if (alternativePaths.isEmpty()) selectedPaths[0] else alternativePaths[radioGroup!!.checkedRadioButtonId]
activity.config.addExcludedFolder(path)
callback()
}
private fun getAlternativePathsList(): List<String> {
val pathsList = ArrayList<String>()
if (selectedPaths.size > 1)
return pathsList
val path = selectedPaths[0]
var basePath = path.getBasePath(activity)
val relativePath = path.substring(basePath.length)
val parts = relativePath.split("/").filter(String::isNotEmpty)
if (parts.isEmpty())
return pathsList
pathsList.add(basePath)
if (basePath == "/")
basePath = ""
for (part in parts) {
basePath += "/$part"
pathsList.add(basePath)
}
return pathsList.reversed()
}
}
| gpl-3.0 | ffd58dec744171d00ce07d0becabb2e9 | 37.712329 | 144 | 0.673744 | 4.897747 | false | false | false | false |
hannesa2/TouchImageView | touchview/src/main/java/com/ortiz/touchview/TouchImageView.kt | 1 | 53414 | package com.ortiz.touchview
import android.annotation.TargetApi
import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.PointF
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Bundle
import android.os.Parcelable
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.GestureDetector.OnDoubleTapListener
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.LinearInterpolator
import android.widget.OverScroller
import androidx.appcompat.widget.AppCompatImageView
@Suppress("unused")
open class TouchImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : AppCompatImageView(context, attrs, defStyle) {
/**
* Get the current zoom. This is the zoom relative to the initial
* scale, not the original resource.
*
* @return current zoom multiplier.
*/
// Scale of image ranges from minScale to maxScale, where minScale == 1
// when the image is stretched to fit view.
var currentZoom = 0f
private set
// Matrix applied to image. MSCALE_X and MSCALE_Y should always be equal.
// MTRANS_X and MTRANS_Y are the other values used. prevMatrix is the matrix saved prior to the screen rotating.
private var touchMatrix: Matrix? = null
private var prevMatrix: Matrix? = null
var isZoomEnabled = false
private var isRotateImageToFitScreen = false
enum class FixedPixel {
CENTER, TOP_LEFT, BOTTOM_RIGHT
}
var orientationChangeFixedPixel: FixedPixel? = FixedPixel.CENTER
var viewSizeChangeFixedPixel: FixedPixel? = FixedPixel.CENTER
private var orientationJustChanged = false
private enum class State {
NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM
}
private var state: State? = null
private var userSpecifiedMinScale = 0f
private var minScale = 0f
private var maxScaleIsSetByMultiplier = false
private var maxScaleMultiplier = 0f
private var maxScale = 0f
private var superMinScale = 0f
private var superMaxScale = 0f
private var floatMatrix: FloatArray? = null
/**
* Get zoom multiplier for double tap
*
* @return double tap zoom multiplier.
*/
/**
* Set custom zoom multiplier for double tap.
* By default maxScale will be used as value for double tap zoom multiplier.
*
*/
var doubleTapScale = 0f
private var fling: Fling? = null
private var orientation = 0
private var touchScaleType: ScaleType? = null
private var imageRenderedAtLeastOnce = false
private var onDrawReady = false
private var delayedZoomVariables: ZoomVariables? = null
// Size of view and previous view size (ie before rotation)
private var viewWidth = 0
private var viewHeight = 0
private var prevViewWidth = 0
private var prevViewHeight = 0
// Size of image when it is stretched to fit view. Before and After rotation.
private var matchViewWidth = 0f
private var matchViewHeight = 0f
private var prevMatchViewWidth = 0f
private var prevMatchViewHeight = 0f
private var mScaleDetector: ScaleGestureDetector? = null
private var mGestureDetector: GestureDetector? = null
private var doubleTapListener: OnDoubleTapListener? = null
private var userTouchListener: OnTouchListener? = null
private var touchImageViewListener: OnTouchImageViewListener? = null
init {
super.setClickable(true)
orientation = resources.configuration.orientation
mScaleDetector = ScaleGestureDetector(context, ScaleListener())
mGestureDetector = GestureDetector(context, GestureListener())
touchMatrix = Matrix()
prevMatrix = Matrix()
floatMatrix = FloatArray(9)
currentZoom = 1f
if (touchScaleType == null) {
touchScaleType = ScaleType.FIT_CENTER
}
minScale = 1f
maxScale = 3f
superMinScale = SUPER_MIN_MULTIPLIER * minScale
superMaxScale = SUPER_MAX_MULTIPLIER * maxScale
imageMatrix = touchMatrix
scaleType = ScaleType.MATRIX
setState(State.NONE)
onDrawReady = false
super.setOnTouchListener(PrivateOnTouchListener())
val attributes = context.theme.obtainStyledAttributes(attrs, R.styleable.TouchImageView, defStyle, 0)
try {
if (!isInEditMode) {
isZoomEnabled = attributes.getBoolean(R.styleable.TouchImageView_zoom_enabled, true)
}
} finally {
// release the TypedArray so that it can be reused.
attributes.recycle()
}
}
fun setRotateImageToFitScreen(rotateImageToFitScreen: Boolean) {
isRotateImageToFitScreen = rotateImageToFitScreen
}
override fun setOnTouchListener(onTouchListener: OnTouchListener) {
userTouchListener = onTouchListener
}
fun setOnTouchImageViewListener(onTouchImageViewListener: OnTouchImageViewListener) {
touchImageViewListener = onTouchImageViewListener
}
fun setOnDoubleTapListener(onDoubleTapListener: OnDoubleTapListener) {
doubleTapListener = onDoubleTapListener
}
override fun setImageResource(resId: Int) {
imageRenderedAtLeastOnce = false
super.setImageResource(resId)
savePreviousImageValues()
fitImageToView()
}
override fun setImageBitmap(bm: Bitmap) {
imageRenderedAtLeastOnce = false
super.setImageBitmap(bm)
savePreviousImageValues()
fitImageToView()
}
override fun setImageDrawable(drawable: Drawable?) {
imageRenderedAtLeastOnce = false
super.setImageDrawable(drawable)
savePreviousImageValues()
fitImageToView()
}
override fun setImageURI(uri: Uri?) {
imageRenderedAtLeastOnce = false
super.setImageURI(uri)
savePreviousImageValues()
fitImageToView()
}
override fun setScaleType(type: ScaleType) {
if (type == ScaleType.MATRIX) {
super.setScaleType(ScaleType.MATRIX)
} else {
touchScaleType = type
if (onDrawReady) {
//
// If the image is already rendered, scaleType has been called programmatically
// and the TouchImageView should be updated with the new scaleType.
//
setZoom(this)
}
}
}
override fun getScaleType(): ScaleType {
return touchScaleType!!
}
/**
* Returns false if image is in initial, unzoomed state. False, otherwise.
*
* @return true if image is zoomed
*/
val isZoomed: Boolean
get() = currentZoom != 1f
/**
* Return a Rect representing the zoomed image.
*
* @return rect representing zoomed image
*/
val zoomedRect: RectF
get() {
if (touchScaleType == ScaleType.FIT_XY) {
throw UnsupportedOperationException("getZoomedRect() not supported with FIT_XY")
}
val topLeft = transformCoordTouchToBitmap(0f, 0f, true)
val bottomRight = transformCoordTouchToBitmap(viewWidth.toFloat(), viewHeight.toFloat(), true)
val w = getDrawableWidth(drawable).toFloat()
val h = getDrawableHeight(drawable).toFloat()
return RectF(topLeft.x / w, topLeft.y / h, bottomRight.x / w, bottomRight.y / h)
}
/**
* Save the current matrix and view dimensions
* in the prevMatrix and prevView variables.
*/
fun savePreviousImageValues() {
if (touchMatrix != null && viewHeight != 0 && viewWidth != 0) {
touchMatrix!!.getValues(floatMatrix)
prevMatrix!!.setValues(floatMatrix)
prevMatchViewHeight = matchViewHeight
prevMatchViewWidth = matchViewWidth
prevViewHeight = viewHeight
prevViewWidth = viewWidth
}
}
public override fun onSaveInstanceState(): Parcelable? {
val bundle = Bundle()
bundle.putParcelable("instanceState", super.onSaveInstanceState())
bundle.putInt("orientation", orientation)
bundle.putFloat("saveScale", currentZoom)
bundle.putFloat("matchViewHeight", matchViewHeight)
bundle.putFloat("matchViewWidth", matchViewWidth)
bundle.putInt("viewWidth", viewWidth)
bundle.putInt("viewHeight", viewHeight)
touchMatrix!!.getValues(floatMatrix)
bundle.putFloatArray("matrix", floatMatrix)
bundle.putBoolean("imageRendered", imageRenderedAtLeastOnce)
bundle.putSerializable("viewSizeChangeFixedPixel", viewSizeChangeFixedPixel)
bundle.putSerializable("orientationChangeFixedPixel", orientationChangeFixedPixel)
return bundle
}
public override fun onRestoreInstanceState(state: Parcelable) {
if (state is Bundle) {
val bundle = state
currentZoom = bundle.getFloat("saveScale")
floatMatrix = bundle.getFloatArray("matrix")
prevMatrix!!.setValues(floatMatrix)
prevMatchViewHeight = bundle.getFloat("matchViewHeight")
prevMatchViewWidth = bundle.getFloat("matchViewWidth")
prevViewHeight = bundle.getInt("viewHeight")
prevViewWidth = bundle.getInt("viewWidth")
imageRenderedAtLeastOnce = bundle.getBoolean("imageRendered")
viewSizeChangeFixedPixel = bundle.getSerializable("viewSizeChangeFixedPixel") as FixedPixel?
orientationChangeFixedPixel = bundle.getSerializable("orientationChangeFixedPixel") as FixedPixel?
val oldOrientation = bundle.getInt("orientation")
if (orientation != oldOrientation) {
orientationJustChanged = true
}
super.onRestoreInstanceState(bundle.getParcelable("instanceState"))
return
}
super.onRestoreInstanceState(state)
}
override fun onDraw(canvas: Canvas) {
onDrawReady = true
imageRenderedAtLeastOnce = true
if (delayedZoomVariables != null) {
setZoom(delayedZoomVariables!!.scale, delayedZoomVariables!!.focusX, delayedZoomVariables!!.focusY, delayedZoomVariables!!.scaleType)
delayedZoomVariables = null
}
super.onDraw(canvas)
}
public override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
val newOrientation = resources.configuration.orientation
if (newOrientation != orientation) {
orientationJustChanged = true
orientation = newOrientation
}
savePreviousImageValues()
}
/**
* Get the max zoom multiplier.
*
* @return max zoom multiplier.
*/
/**
* Set the max zoom multiplier to a constant. Default value: 3.
*
*/
var maxZoom: Float
get() = maxScale
set(max) {
maxScale = max
superMaxScale = SUPER_MAX_MULTIPLIER * maxScale
maxScaleIsSetByMultiplier = false
}
/**
* Set the max zoom multiplier as a multiple of minZoom, whatever minZoom may change to. By
* default, this is not done, and maxZoom has a fixed value of 3.
*
* @param max max zoom multiplier, as a multiple of minZoom
*/
fun setMaxZoomRatio(max: Float) {
maxScaleMultiplier = max
maxScale = minScale * maxScaleMultiplier
superMaxScale = SUPER_MAX_MULTIPLIER * maxScale
maxScaleIsSetByMultiplier = true
}
/**
* Get the min zoom multiplier.
*
* @return min zoom multiplier.
*/// CENTER_CROP
/**
* Set the min zoom multiplier. Default value: 1.
*
*/
var minZoom: Float
get() = minScale
set(min) {
userSpecifiedMinScale = min
if (min == AUTOMATIC_MIN_ZOOM) {
if (touchScaleType == ScaleType.CENTER || touchScaleType == ScaleType.CENTER_CROP) {
val drawable = drawable
val drawableWidth = getDrawableWidth(drawable)
val drawableHeight = getDrawableHeight(drawable)
if (drawable != null && drawableWidth > 0 && drawableHeight > 0) {
val widthRatio = viewWidth.toFloat() / drawableWidth
val heightRatio = viewHeight.toFloat() / drawableHeight
minScale = if (touchScaleType == ScaleType.CENTER) {
Math.min(widthRatio, heightRatio)
} else { // CENTER_CROP
Math.min(widthRatio, heightRatio) / Math.max(widthRatio, heightRatio)
}
}
} else {
minScale = 1.0f
}
} else {
minScale = userSpecifiedMinScale
}
if (maxScaleIsSetByMultiplier) {
setMaxZoomRatio(maxScaleMultiplier)
}
superMinScale = SUPER_MIN_MULTIPLIER * minScale
}
/**
* Reset zoom and translation to initial state.
*/
fun resetZoom() {
currentZoom = 1f
fitImageToView()
}
fun resetZoomAnimated() {
setZoomAnimated(1f, 0.5f, 0.5f)
}
/**
* Set zoom to the specified scale. Image will be centered by default.
*/
fun setZoom(scale: Float) {
setZoom(scale, 0.5f, 0.5f)
}
/**
* Set zoom to the specified scale. Image will be centered around the point
* (focusX, focusY). These floats range from 0 to 1 and denote the focus point
* as a fraction from the left and top of the view. For example, the top left
* corner of the image would be (0, 0). And the bottom right corner would be (1, 1).
*/
fun setZoom(scale: Float, focusX: Float, focusY: Float) {
setZoom(scale, focusX, focusY, touchScaleType)
}
/**
* Set zoom to the specified scale. Image will be centered around the point
* (focusX, focusY). These floats range from 0 to 1 and denote the focus point
* as a fraction from the left and top of the view. For example, the top left
* corner of the image would be (0, 0). And the bottom right corner would be (1, 1).
*/
fun setZoom(scale: Float, focusX: Float, focusY: Float, scaleType: ScaleType?) {
//
// setZoom can be called before the image is on the screen, but at this point,
// image and view sizes have not yet been calculated in onMeasure. Thus, we should
// delay calling setZoom until the view has been measured.
//
if (!onDrawReady) {
delayedZoomVariables = ZoomVariables(scale, focusX, focusY, scaleType)
return
}
if (userSpecifiedMinScale == AUTOMATIC_MIN_ZOOM) {
minZoom = AUTOMATIC_MIN_ZOOM
if (currentZoom < minScale) {
currentZoom = minScale
}
}
if (scaleType != touchScaleType) {
setScaleType(scaleType!!)
}
resetZoom()
scaleImage(scale.toDouble(), viewWidth / 2.toFloat(), viewHeight / 2.toFloat(), true)
touchMatrix!!.getValues(floatMatrix)
floatMatrix!![Matrix.MTRANS_X] = -(focusX * imageWidth - viewWidth * 0.5f)
floatMatrix!![Matrix.MTRANS_Y] = -(focusY * imageHeight - viewHeight * 0.5f)
touchMatrix!!.setValues(floatMatrix)
fixTrans()
savePreviousImageValues()
imageMatrix = touchMatrix
}
/**
* Set zoom parameters equal to another TouchImageView. Including scale, position,
* and ScaleType.
*/
fun setZoom(img: TouchImageView) {
val center = img.scrollPosition
setZoom(img.currentZoom, center.x, center.y, img.scaleType)
}
/**
* Return the point at the center of the zoomed image. The PointF coordinates range
* in value between 0 and 1 and the focus point is denoted as a fraction from the left
* and top of the view. For example, the top left corner of the image would be (0, 0).
* And the bottom right corner would be (1, 1).
*
* @return PointF representing the scroll position of the zoomed image.
*/
val scrollPosition: PointF
get() {
val drawable = drawable ?: return PointF(.5f, .5f)
val drawableWidth = getDrawableWidth(drawable)
val drawableHeight = getDrawableHeight(drawable)
val point = transformCoordTouchToBitmap(viewWidth / 2.toFloat(), viewHeight / 2.toFloat(), true)
point.x /= drawableWidth.toFloat()
point.y /= drawableHeight.toFloat()
return point
}
private fun orientationMismatch(drawable: Drawable?): Boolean {
return viewWidth > viewHeight != drawable!!.intrinsicWidth > drawable.intrinsicHeight
}
private fun getDrawableWidth(drawable: Drawable?): Int {
return if (orientationMismatch(drawable) && isRotateImageToFitScreen) {
drawable!!.intrinsicHeight
} else drawable!!.intrinsicWidth
}
private fun getDrawableHeight(drawable: Drawable?): Int {
return if (orientationMismatch(drawable) && isRotateImageToFitScreen) {
drawable!!.intrinsicWidth
} else drawable!!.intrinsicHeight
}
/**
* Set the focus point of the zoomed image. The focus points are denoted as a fraction from the
* left and top of the view. The focus points can range in value between 0 and 1.
*/
fun setScrollPosition(focusX: Float, focusY: Float) {
setZoom(currentZoom, focusX, focusY)
}
/**
* Performs boundary checking and fixes the image matrix if it
* is out of bounds.
*/
private fun fixTrans() {
touchMatrix!!.getValues(floatMatrix)
val transX = floatMatrix!![Matrix.MTRANS_X]
val transY = floatMatrix!![Matrix.MTRANS_Y]
var offset = 0f
if (isRotateImageToFitScreen && orientationMismatch(drawable)) {
offset = imageWidth
}
val fixTransX = getFixTrans(transX, viewWidth.toFloat(), imageWidth, offset)
val fixTransY = getFixTrans(transY, viewHeight.toFloat(), imageHeight, 0f)
touchMatrix!!.postTranslate(fixTransX, fixTransY)
}
/**
* When transitioning from zooming from focus to zoom from center (or vice versa)
* the image can become unaligned within the view. This is apparent when zooming
* quickly. When the content size is less than the view size, the content will often
* be centered incorrectly within the view. fixScaleTrans first calls fixTrans() and
* then makes sure the image is centered correctly within the view.
*/
private fun fixScaleTrans() {
fixTrans()
touchMatrix!!.getValues(floatMatrix)
if (imageWidth < viewWidth) {
var xOffset = (viewWidth - imageWidth) / 2
if (isRotateImageToFitScreen && orientationMismatch(drawable)) {
xOffset += imageWidth
}
floatMatrix!![Matrix.MTRANS_X] = xOffset
}
if (imageHeight < viewHeight) {
floatMatrix!![Matrix.MTRANS_Y] = (viewHeight - imageHeight) / 2
}
touchMatrix!!.setValues(floatMatrix)
}
private fun getFixTrans(trans: Float, viewSize: Float, contentSize: Float, offset: Float): Float {
val minTrans: Float
val maxTrans: Float
if (contentSize <= viewSize) {
minTrans = offset
maxTrans = offset + viewSize - contentSize
} else {
minTrans = offset + viewSize - contentSize
maxTrans = offset
}
if (trans < minTrans) return -trans + minTrans
return if (trans > maxTrans) -trans + maxTrans else 0f
}
private fun getFixDragTrans(delta: Float, viewSize: Float, contentSize: Float): Float {
return if (contentSize <= viewSize) {
0f
} else
delta
}
private val imageWidth: Float
get() = matchViewWidth * currentZoom
private val imageHeight: Float
get() = matchViewHeight * currentZoom
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val drawable = drawable
if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) {
setMeasuredDimension(0, 0)
return
}
val drawableWidth = getDrawableWidth(drawable)
val drawableHeight = getDrawableHeight(drawable)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
val totalViewWidth = setViewSize(widthMode, widthSize, drawableWidth)
val totalViewHeight = setViewSize(heightMode, heightSize, drawableHeight)
if (!orientationJustChanged) {
savePreviousImageValues()
}
// Image view width, height must consider padding
val width = totalViewWidth - paddingLeft - paddingRight
val height = totalViewHeight - paddingTop - paddingBottom
// Set view dimensions
setMeasuredDimension(width, height)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
//
// Fit content within view.
//
// onMeasure may be called multiple times for each layout change, including orientation
// changes. For example, if the TouchImageView is inside a ConstraintLayout, onMeasure may
// be called with:
// widthMeasureSpec == "AT_MOST 2556" and then immediately with
// widthMeasureSpec == "EXACTLY 1404", then back and forth multiple times in quick
// succession, as the ConstraintLayout tries to solve its constraints.
//
// onSizeChanged is called once after the final onMeasure is called. So we make all changes
// to class members, such as fitting the image into the new shape of the TouchImageView,
// here, after the final size has been determined. This helps us avoid both
// repeated computations, and making irreversible changes (e.g. making the View temporarily too
// big or too small, thus making the current zoom fall outside of an automatically-changing
// minZoom and maxZoom).
//
viewWidth = w
viewHeight = h
fitImageToView()
}
/**
* This function can be called:
* 1. When the TouchImageView is first loaded (onMeasure).
* 2. When a new image is loaded (setImageResource|Bitmap|Drawable|URI).
* 3. On rotation (onSaveInstanceState, then onRestoreInstanceState, then onMeasure).
* 4. When the view is resized (onMeasure).
* 5. When the zoom is reset (resetZoom).
*
*
* In cases 2, 3 and 4, we try to maintain the zoom state and position as directed by
* orientationChangeFixedPixel or viewSizeChangeFixedPixel (if there is an existing zoom state
* and position, which there might not be in case 2).
*
*
* If the normalizedScale is equal to 1, then the image is made to fit the View. Otherwise, we
* maintain zoom level and attempt to roughly put the same part of the image in the View as was
* there before, paying attention to orientationChangeFixedPixel or viewSizeChangeFixedPixel.
*/
private fun fitImageToView() {
val fixedPixel = if (orientationJustChanged) orientationChangeFixedPixel else viewSizeChangeFixedPixel
orientationJustChanged = false
val drawable = drawable
if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) {
return
}
if (touchMatrix == null || prevMatrix == null) {
return
}
if (userSpecifiedMinScale == AUTOMATIC_MIN_ZOOM) {
minZoom = AUTOMATIC_MIN_ZOOM
if (currentZoom < minScale) {
currentZoom = minScale
}
}
val drawableWidth = getDrawableWidth(drawable)
val drawableHeight = getDrawableHeight(drawable)
//
// Scale image for view
//
var scaleX = viewWidth.toFloat() / drawableWidth
var scaleY = viewHeight.toFloat() / drawableHeight
when (touchScaleType) {
ScaleType.CENTER -> {
scaleY = 1f
scaleX = scaleY
}
ScaleType.CENTER_CROP -> {
scaleY = Math.max(scaleX, scaleY)
scaleX = scaleY
}
ScaleType.CENTER_INSIDE -> {
run {
scaleY = Math.min(1f, Math.min(scaleX, scaleY))
scaleX = scaleY
}
run {
scaleY = Math.min(scaleX, scaleY)
scaleX = scaleY
}
}
ScaleType.FIT_CENTER, ScaleType.FIT_START, ScaleType.FIT_END -> {
scaleY = Math.min(scaleX, scaleY)
scaleX = scaleY
}
ScaleType.FIT_XY -> {
}
else -> {
}
}
// Put the image's center in the right place.
val redundantXSpace = viewWidth - scaleX * drawableWidth
val redundantYSpace = viewHeight - scaleY * drawableHeight
matchViewWidth = viewWidth - redundantXSpace
matchViewHeight = viewHeight - redundantYSpace
if (!isZoomed && !imageRenderedAtLeastOnce) {
// Stretch and center image to fit view
if (isRotateImageToFitScreen && orientationMismatch(drawable)) {
touchMatrix!!.setRotate(90f)
touchMatrix!!.postTranslate(drawableWidth.toFloat(), 0f)
touchMatrix!!.postScale(scaleX, scaleY)
} else {
touchMatrix!!.setScale(scaleX, scaleY)
}
when (touchScaleType) {
ScaleType.FIT_START -> touchMatrix!!.postTranslate(0f, 0f)
ScaleType.FIT_END -> touchMatrix!!.postTranslate(redundantXSpace, redundantYSpace)
else -> touchMatrix!!.postTranslate(redundantXSpace / 2, redundantYSpace / 2)
}
currentZoom = 1f
} else {
// These values should never be 0 or we will set viewWidth and viewHeight
// to NaN in newTranslationAfterChange. To avoid this, call savePreviousImageValues
// to set them equal to the current values.
if (prevMatchViewWidth == 0f || prevMatchViewHeight == 0f) {
savePreviousImageValues()
}
// Use the previous matrix as our starting point for the new matrix.
prevMatrix!!.getValues(floatMatrix)
// Rescale Matrix if appropriate
floatMatrix!![Matrix.MSCALE_X] = matchViewWidth / drawableWidth * currentZoom
floatMatrix!![Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * currentZoom
// TransX and TransY from previous matrix
val transX = floatMatrix!![Matrix.MTRANS_X]
val transY = floatMatrix!![Matrix.MTRANS_Y]
// X position
val prevActualWidth = prevMatchViewWidth * currentZoom
val actualWidth = imageWidth
floatMatrix!![Matrix.MTRANS_X] = newTranslationAfterChange(transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth, fixedPixel)
// Y position
val prevActualHeight = prevMatchViewHeight * currentZoom
val actualHeight = imageHeight
floatMatrix!![Matrix.MTRANS_Y] = newTranslationAfterChange(transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight, fixedPixel)
// Set the matrix to the adjusted scale and translation values.
touchMatrix!!.setValues(floatMatrix)
}
fixTrans()
imageMatrix = touchMatrix
}
/**
* Set view dimensions based on layout params
*/
private fun setViewSize(mode: Int, size: Int, drawableWidth: Int): Int {
val viewSize: Int
viewSize = when (mode) {
MeasureSpec.EXACTLY -> size
MeasureSpec.AT_MOST -> Math.min(drawableWidth, size)
MeasureSpec.UNSPECIFIED -> drawableWidth
else -> size
}
return viewSize
}
/**
* After any change described in the comments for fitImageToView, the matrix needs to be
* translated. This function translates the image so that the fixed pixel in the image
* stays in the same place in the View.
*
* @param trans the value of trans in that axis before the rotation
* @param prevImageSize the width/height of the image before the rotation
* @param imageSize width/height of the image after rotation
* @param prevViewSize width/height of view before rotation
* @param viewSize width/height of view after rotation
* @param drawableSize width/height of drawable
* @param sizeChangeFixedPixel how we should choose the fixed pixel
*/
private fun newTranslationAfterChange(trans: Float, prevImageSize: Float, imageSize: Float, prevViewSize: Int, viewSize: Int, drawableSize: Int, sizeChangeFixedPixel: FixedPixel?): Float {
return if (imageSize < viewSize) {
//
// The width/height of image is less than the view's width/height. Center it.
//
(viewSize - drawableSize * floatMatrix!![Matrix.MSCALE_X]) * 0.5f
} else if (trans > 0) {
//
// The image is larger than the view, but was not before the view changed. Center it.
//
-((imageSize - viewSize) * 0.5f)
} else {
//
// Where is the pixel in the View that we are keeping stable, as a fraction of the
// width/height of the View?
//
var fixedPixelPositionInView = 0.5f // CENTER
if (sizeChangeFixedPixel == FixedPixel.BOTTOM_RIGHT) {
fixedPixelPositionInView = 1.0f
} else if (sizeChangeFixedPixel == FixedPixel.TOP_LEFT) {
fixedPixelPositionInView = 0.0f
}
//
// Where is the pixel in the Image that we are keeping stable, as a fraction of the
// width/height of the Image?
//
val fixedPixelPositionInImage = (-trans + fixedPixelPositionInView * prevViewSize) / prevImageSize
//
// Here's what the new translation should be so that, after whatever change triggered
// this function to be called, the pixel at fixedPixelPositionInView of the View is
// still the pixel at fixedPixelPositionInImage of the image.
//
-(fixedPixelPositionInImage * imageSize - viewSize * fixedPixelPositionInView)
}
}
private fun setState(state: State) {
this.state = state
}
@Deprecated("")
fun canScrollHorizontallyFroyo(direction: Int): Boolean {
return canScrollHorizontally(direction)
}
override fun canScrollHorizontally(direction: Int): Boolean {
touchMatrix!!.getValues(floatMatrix)
val x = floatMatrix!![Matrix.MTRANS_X]
return if (imageWidth < viewWidth) {
false
} else if (x >= -1 && direction < 0) {
false
} else Math.abs(x) + viewWidth + 1 < imageWidth || direction <= 0
}
override fun canScrollVertically(direction: Int): Boolean {
touchMatrix!!.getValues(floatMatrix)
val y = floatMatrix!![Matrix.MTRANS_Y]
return if (imageHeight < viewHeight) {
false
} else if (y >= -1 && direction < 0) {
false
} else Math.abs(y) + viewHeight + 1 < imageHeight || direction <= 0
}
/**
* Gesture Listener detects a single click or long click and passes that on
* to the view's listener.
*/
private inner class GestureListener : SimpleOnGestureListener() {
override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
// Pass on to the OnDoubleTapListener if it is present, otherwise let the View handle the click.
return doubleTapListener?.onSingleTapConfirmed(e) ?: performClick()
}
override fun onLongPress(e: MotionEvent?) {
performLongClick()
}
override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
// If a previous fling is still active, it should be cancelled so that two flings
// are not run simultaneously.
fling?.cancelFling()
fling = Fling(velocityX.toInt(), velocityY.toInt())
.also { compatPostOnAnimation(it) }
return super.onFling(e1, e2, velocityX, velocityY)
}
override fun onDoubleTap(e: MotionEvent?): Boolean {
var consumed = false
if (e != null && isZoomEnabled) {
doubleTapListener?.let {
consumed = it.onDoubleTap(e)
}
if (state == State.NONE) {
val maxZoomScale = if (doubleTapScale == 0f) maxScale else doubleTapScale
val targetZoom = if (currentZoom == minScale) maxZoomScale else minScale
val doubleTap = DoubleTapZoom(targetZoom, e.x, e.y, false)
compatPostOnAnimation(doubleTap)
consumed = true
}
}
return consumed
}
override fun onDoubleTapEvent(e: MotionEvent?): Boolean {
return doubleTapListener?.onDoubleTapEvent(e) ?: false
}
}
interface OnTouchImageViewListener {
fun onMove()
}
/**
* Responsible for all touch events. Handles the heavy lifting of drag and also sends
* touch events to Scale Detector and Gesture Detector.
*/
private inner class PrivateOnTouchListener : OnTouchListener {
// Remember last point position for dragging
private val last = PointF()
override fun onTouch(v: View, event: MotionEvent): Boolean {
if (drawable == null) {
setState(State.NONE)
return false
}
if (isZoomEnabled) {
mScaleDetector!!.onTouchEvent(event)
}
mGestureDetector!!.onTouchEvent(event)
val curr = PointF(event.x, event.y)
if (state == State.NONE || state == State.DRAG || state == State.FLING) {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
last.set(curr)
if (fling != null) fling!!.cancelFling()
setState(State.DRAG)
}
MotionEvent.ACTION_MOVE -> if (state == State.DRAG) {
val deltaX = curr.x - last.x
val deltaY = curr.y - last.y
val fixTransX = getFixDragTrans(deltaX, viewWidth.toFloat(), imageWidth)
val fixTransY = getFixDragTrans(deltaY, viewHeight.toFloat(), imageHeight)
touchMatrix!!.postTranslate(fixTransX, fixTransY)
fixTrans()
last[curr.x] = curr.y
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> setState(State.NONE)
}
}
imageMatrix = touchMatrix
//
// User-defined OnTouchListener
//
if (userTouchListener != null) {
userTouchListener!!.onTouch(v, event)
}
//
// OnTouchImageViewListener is set: TouchImageView dragged by user.
//
if (touchImageViewListener != null) {
touchImageViewListener!!.onMove()
}
//
// indicate event was handled
//
return true
}
}
/**
* ScaleListener detects user two finger scaling and scales image.
*/
private inner class ScaleListener : SimpleOnScaleGestureListener() {
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
setState(State.ZOOM)
return true
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
scaleImage(detector.scaleFactor.toDouble(), detector.focusX, detector.focusY, true)
//
// OnTouchImageViewListener is set: TouchImageView pinch zoomed by user.
//
if (touchImageViewListener != null) {
touchImageViewListener!!.onMove()
}
return true
}
override fun onScaleEnd(detector: ScaleGestureDetector) {
super.onScaleEnd(detector)
setState(State.NONE)
var animateToZoomBoundary = false
var targetZoom: Float = currentZoom
if (currentZoom > maxScale) {
targetZoom = maxScale
animateToZoomBoundary = true
} else if (currentZoom < minScale) {
targetZoom = minScale
animateToZoomBoundary = true
}
if (animateToZoomBoundary) {
val doubleTap = DoubleTapZoom(targetZoom, (viewWidth / 2).toFloat(), (viewHeight / 2).toFloat(), true)
compatPostOnAnimation(doubleTap)
}
}
}
private fun scaleImage(deltaScale: Double, focusX: Float, focusY: Float, stretchImageToSuper: Boolean) {
var deltaScaleLocal = deltaScale
val lowerScale: Float
val upperScale: Float
if (stretchImageToSuper) {
lowerScale = superMinScale
upperScale = superMaxScale
} else {
lowerScale = minScale
upperScale = maxScale
}
val origScale = currentZoom
currentZoom *= deltaScaleLocal.toFloat()
if (currentZoom > upperScale) {
currentZoom = upperScale
deltaScaleLocal = upperScale / origScale.toDouble()
} else if (currentZoom < lowerScale) {
currentZoom = lowerScale
deltaScaleLocal = lowerScale / origScale.toDouble()
}
touchMatrix!!.postScale(deltaScaleLocal.toFloat(), deltaScaleLocal.toFloat(), focusX, focusY)
fixScaleTrans()
}
/**
* DoubleTapZoom calls a series of runnables which apply
* an animated zoom in/out graphic to the image.
*/
private inner class DoubleTapZoom internal constructor(targetZoom: Float, focusX: Float, focusY: Float, stretchImageToSuper: Boolean) : Runnable {
private val startTime: Long
private val startZoom: Float
private val targetZoom: Float
private val bitmapX: Float
private val bitmapY: Float
private val stretchImageToSuper: Boolean
private val interpolator = AccelerateDecelerateInterpolator()
private val startTouch: PointF
private val endTouch: PointF
override fun run() {
if (drawable == null) {
setState(State.NONE)
return
}
val t = interpolate()
val deltaScale = calculateDeltaScale(t)
scaleImage(deltaScale, bitmapX, bitmapY, stretchImageToSuper)
translateImageToCenterTouchPosition(t)
fixScaleTrans()
imageMatrix = touchMatrix
// double tap runnable updates listener with every frame.
if (touchImageViewListener != null) {
touchImageViewListener!!.onMove()
}
if (t < 1f) {
// We haven't finished zooming
compatPostOnAnimation(this)
} else {
// Finished zooming
setState(State.NONE)
}
}
/**
* Interpolate between where the image should start and end in order to translate
* the image so that the point that is touched is what ends up centered at the end
* of the zoom.
*/
private fun translateImageToCenterTouchPosition(t: Float) {
val targetX = startTouch.x + t * (endTouch.x - startTouch.x)
val targetY = startTouch.y + t * (endTouch.y - startTouch.y)
val curr = transformCoordBitmapToTouch(bitmapX, bitmapY)
touchMatrix!!.postTranslate(targetX - curr.x, targetY - curr.y)
}
/**
* Use interpolator to get t
*/
private fun interpolate(): Float {
val currTime = System.currentTimeMillis()
var elapsed = (currTime - startTime) / DEFAULT_ZOOM_TIME.toFloat()
elapsed = Math.min(1f, elapsed)
return interpolator.getInterpolation(elapsed)
}
/**
* Interpolate the current targeted zoom and get the delta
* from the current zoom.
*/
private fun calculateDeltaScale(t: Float): Double {
val zoom = startZoom + t * (targetZoom - startZoom).toDouble()
return zoom / currentZoom
}
init {
setState(State.ANIMATE_ZOOM)
startTime = System.currentTimeMillis()
startZoom = currentZoom
this.targetZoom = targetZoom
this.stretchImageToSuper = stretchImageToSuper
val bitmapPoint = transformCoordTouchToBitmap(focusX, focusY, false)
bitmapX = bitmapPoint.x
bitmapY = bitmapPoint.y
// Used for translating image during scaling
startTouch = transformCoordBitmapToTouch(bitmapX, bitmapY)
endTouch = PointF((viewWidth / 2).toFloat(), (viewHeight / 2).toFloat())
}
}
/**
* This function will transform the coordinates in the touch event to the coordinate
* system of the drawable that the imageview contain
*
* @param x x-coordinate of touch event
* @param y y-coordinate of touch event
* @param clipToBitmap Touch event may occur within view, but outside image content. True, to clip return value
* to the bounds of the bitmap size.
* @return Coordinates of the point touched, in the coordinate system of the original drawable.
*/
protected fun transformCoordTouchToBitmap(x: Float, y: Float, clipToBitmap: Boolean): PointF {
touchMatrix!!.getValues(floatMatrix)
val origW = drawable.intrinsicWidth.toFloat()
val origH = drawable.intrinsicHeight.toFloat()
val transX = floatMatrix!![Matrix.MTRANS_X]
val transY = floatMatrix!![Matrix.MTRANS_Y]
var finalX = (x - transX) * origW / imageWidth
var finalY = (y - transY) * origH / imageHeight
if (clipToBitmap) {
finalX = Math.min(Math.max(finalX, 0f), origW)
finalY = Math.min(Math.max(finalY, 0f), origH)
}
return PointF(finalX, finalY)
}
/**
* Inverse of transformCoordTouchToBitmap. This function will transform the coordinates in the
* drawable's coordinate system to the view's coordinate system.
*
* @param bx x-coordinate in original bitmap coordinate system
* @param by y-coordinate in original bitmap coordinate system
* @return Coordinates of the point in the view's coordinate system.
*/
protected fun transformCoordBitmapToTouch(bx: Float, by: Float): PointF {
touchMatrix!!.getValues(floatMatrix)
val origW = drawable.intrinsicWidth.toFloat()
val origH = drawable.intrinsicHeight.toFloat()
val px = bx / origW
val py = by / origH
val finalX = floatMatrix!![Matrix.MTRANS_X] + imageWidth * px
val finalY = floatMatrix!![Matrix.MTRANS_Y] + imageHeight * py
return PointF(finalX, finalY)
}
/**
* Fling launches sequential runnables which apply
* the fling graphic to the image. The values for the translation
* are interpolated by the Scroller.
*/
private inner class Fling internal constructor(velocityX: Int, velocityY: Int) : Runnable {
var scroller: CompatScroller?
var currX: Int
var currY: Int
fun cancelFling() {
if (scroller != null) {
setState(State.NONE)
scroller!!.forceFinished(true)
}
}
override fun run() {
// OnTouchImageViewListener is set: TouchImageView listener has been flung by user.
// Listener runnable updated with each frame of fling animation.
if (touchImageViewListener != null) {
touchImageViewListener!!.onMove()
}
if (scroller!!.isFinished) {
scroller = null
return
}
if (scroller!!.computeScrollOffset()) {
val newX = scroller!!.currX
val newY = scroller!!.currY
val transX = newX - currX
val transY = newY - currY
currX = newX
currY = newY
touchMatrix!!.postTranslate(transX.toFloat(), transY.toFloat())
fixTrans()
imageMatrix = touchMatrix
compatPostOnAnimation(this)
}
}
init {
setState(State.FLING)
scroller = CompatScroller(context)
touchMatrix!!.getValues(floatMatrix)
var startX = floatMatrix!![Matrix.MTRANS_X].toInt()
val startY = floatMatrix!![Matrix.MTRANS_Y].toInt()
val minX: Int
val maxX: Int
val minY: Int
val maxY: Int
if (isRotateImageToFitScreen && orientationMismatch(drawable)) {
startX -= imageWidth.toInt()
}
if (imageWidth > viewWidth) {
minX = viewWidth - imageWidth.toInt()
maxX = 0
} else {
maxX = startX
minX = maxX
}
if (imageHeight > viewHeight) {
minY = viewHeight - imageHeight.toInt()
maxY = 0
} else {
maxY = startY
minY = maxY
}
scroller!!.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY)
currX = startX
currY = startY
}
}
@TargetApi(VERSION_CODES.GINGERBREAD)
private inner class CompatScroller internal constructor(context: Context?) {
var overScroller: OverScroller
fun fling(startX: Int, startY: Int, velocityX: Int, velocityY: Int, minX: Int, maxX: Int, minY: Int, maxY: Int) {
overScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY)
}
fun forceFinished(finished: Boolean) {
overScroller.forceFinished(finished)
}
val isFinished: Boolean
get() = overScroller.isFinished
fun computeScrollOffset(): Boolean {
overScroller.computeScrollOffset()
return overScroller.computeScrollOffset()
}
val currX: Int
get() = overScroller.currX
val currY: Int
get() = overScroller.currY
init {
overScroller = OverScroller(context)
}
}
@TargetApi(VERSION_CODES.JELLY_BEAN)
private fun compatPostOnAnimation(runnable: Runnable) {
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
postOnAnimation(runnable)
} else {
postDelayed(runnable, 1000 / 60.toLong())
}
}
private inner class ZoomVariables internal constructor(var scale: Float, var focusX: Float, var focusY: Float, var scaleType: ScaleType?)
interface OnZoomFinishedListener {
fun onZoomFinished()
}
/**
* Set zoom to the specified scale with a linearly interpolated animation. Image will be
* centered around the point (focusX, focusY). These floats range from 0 to 1 and denote the
* focus point as a fraction from the left and top of the view. For example, the top left
* corner of the image would be (0, 0). And the bottom right corner would be (1, 1).
*/
fun setZoomAnimated(scale: Float, focusX: Float, focusY: Float) {
setZoomAnimated(scale, focusX, focusY, DEFAULT_ZOOM_TIME)
}
fun setZoomAnimated(scale: Float, focusX: Float, focusY: Float, zoomTimeMs: Int) {
val animation = AnimatedZoom(scale, PointF(focusX, focusY), zoomTimeMs)
compatPostOnAnimation(animation)
}
/**
* Set zoom to the specified scale with a linearly interpolated animation. Image will be
* centered around the point (focusX, focusY). These floats range from 0 to 1 and denote the
* focus point as a fraction from the left and top of the view. For example, the top left
* corner of the image would be (0, 0). And the bottom right corner would be (1, 1).
*
* @param listener the listener, which will be notified, once the animation ended
*/
fun setZoomAnimated(scale: Float, focusX: Float, focusY: Float, zoomTimeMs: Int, listener: OnZoomFinishedListener?) {
val animation = AnimatedZoom(scale, PointF(focusX, focusY), zoomTimeMs)
animation.setListener(listener)
compatPostOnAnimation(animation)
}
fun setZoomAnimated(scale: Float, focusX: Float, focusY: Float, listener: OnZoomFinishedListener?) {
val animation = AnimatedZoom(scale, PointF(focusX, focusY), DEFAULT_ZOOM_TIME)
animation.setListener(listener)
compatPostOnAnimation(animation)
}
/**
* AnimatedZoom calls a series of runnables which apply
* an animated zoom to the specified target focus at the specified zoom level.
*/
private inner class AnimatedZoom internal constructor(targetZoom: Float, focus: PointF, zoomTimeMillis: Int) : Runnable {
private val zoomTimeMillis: Int
private val startTime: Long
private val startZoom: Float
private val targetZoom: Float
private val startFocus: PointF
private val targetFocus: PointF
private val interpolator = LinearInterpolator()
private var listener: OnZoomFinishedListener? = null
override fun run() {
val t = interpolate()
// Calculate the next focus and zoom based on the progress of the interpolation
val nextZoom = startZoom + (targetZoom - startZoom) * t
val nextX = startFocus.x + (targetFocus.x - startFocus.x) * t
val nextY = startFocus.y + (targetFocus.y - startFocus.y) * t
setZoom(nextZoom, nextX, nextY)
if (t < 1f) {
// We haven't finished zooming
compatPostOnAnimation(this)
} else {
// Finished zooming
setState(State.NONE)
if (listener != null) listener!!.onZoomFinished()
}
}
/**
* Use interpolator to get t
*
* @return progress of the interpolation
*/
private fun interpolate(): Float {
var elapsed = (System.currentTimeMillis() - startTime) / zoomTimeMillis.toFloat()
elapsed = Math.min(1f, elapsed)
return interpolator.getInterpolation(elapsed)
}
fun setListener(listener: OnZoomFinishedListener?) {
this.listener = listener
}
init {
setState(State.ANIMATE_ZOOM)
startTime = System.currentTimeMillis()
startZoom = currentZoom
this.targetZoom = targetZoom
this.zoomTimeMillis = zoomTimeMillis
// Used for translating image during zooming
startFocus = scrollPosition
targetFocus = focus
}
}
companion object {
private const val DEBUG = "DEBUG"
// SuperMin and SuperMax multipliers. Determine how much the image can be
// zoomed below or above the zoom boundaries, before animating back to the
// min/max zoom boundary.
private const val SUPER_MIN_MULTIPLIER = .75f
private const val SUPER_MAX_MULTIPLIER = 1.25f
private const val DEFAULT_ZOOM_TIME = 500
/**
* If setMinZoom(AUTOMATIC_MIN_ZOOM), then we'll set the min scale to include the whole image.
*/
const val AUTOMATIC_MIN_ZOOM = -1.0f
}
}
| mit | a4ae0eeccf317244e9a09ec63e5d3e30 | 38.361828 | 192 | 0.61291 | 4.906669 | false | false | false | false |
drmaas/ratpack-kotlin | ratpack-kotlin-dsl/src/main/kotlin/ratpack/kotlin/handling/Ratpack.kt | 1 | 461 | package ratpack.kotlin.handling
import ratpack.server.RatpackServer
/*
* Kotlin DSL top-level function.
*/
inline fun serverOf(crossinline cb: KServerSpec.(KServerSpec) -> Unit) = RatpackServer.of { val s = KServerSpec(it); s.cb(s) }
inline fun serverStart(crossinline cb: KServerSpec.(KServerSpec) -> Unit) = RatpackServer.start { val s = KServerSpec(it); s.cb(s) }
inline fun ratpack(crossinline cb: KServerSpec.(KServerSpec) -> Unit) = serverStart(cb)
| apache-2.0 | 714a1c66db5308479d1ed4d0fdb8e09e | 37.416667 | 132 | 0.744035 | 3.546154 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/adapters/SmartListAdapter.kt | 1 | 4431 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Hadrien De Sousa <[email protected]>
* Author: Adrien Béraud <[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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.adapters
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import cx.ring.databinding.ItemSmartlistBinding
import cx.ring.databinding.ItemSmartlistHeaderBinding
import cx.ring.viewholders.SmartListViewHolder
import cx.ring.viewholders.SmartListViewHolder.SmartListListeners
import io.reactivex.rxjava3.disposables.CompositeDisposable
import net.jami.model.Conversation
import net.jami.services.ConversationFacade
class SmartListAdapter(
conversations: ConversationFacade.ConversationList?,
private val listener: SmartListListeners,
private val conversationFacade: ConversationFacade,
private val disposable: CompositeDisposable
) : RecyclerView.Adapter<SmartListViewHolder>() {
private var conversations = setItems(conversations ?: ConversationFacade.ConversationList())
private var recyclerView: RecyclerView? = null
private var itemCount: Int = 0
private var searchHeaderIndex: Int = -1
private var convHeaderIndex: Int = -1
fun setItems(list: ConversationFacade.ConversationList): ConversationFacade.ConversationList {
itemCount = list.getCombinedSize()
if (list.publicDirectory.isNotEmpty()) {
searchHeaderIndex = 0
convHeaderIndex = if (list.conversations.isEmpty()) -1 else list.publicDirectory.size + 1
} else {
searchHeaderIndex = -1
convHeaderIndex = -1
}
return list
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SmartListViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return if (viewType == 0) SmartListViewHolder(ItemSmartlistBinding.inflate(layoutInflater, parent, false), disposable)
else SmartListViewHolder(ItemSmartlistHeaderBinding.inflate(layoutInflater, parent, false), disposable)
}
override fun getItemViewType(position: Int): Int {
return when(position) {
searchHeaderIndex, convHeaderIndex -> 1
else -> 0
}
}
override fun onViewRecycled(holder: SmartListViewHolder) {
super.onViewRecycled(holder)
holder.unbind()
}
override fun onBindViewHolder(holder: SmartListViewHolder, position: Int) {
conversations[position]?.let { conversation ->
return holder.bind(conversationFacade, listener, conversation)
}
conversations.getHeader(position).let { title ->
return holder.bindHeader(title)
}
}
override fun getItemCount(): Int = itemCount
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
this.recyclerView = recyclerView
}
fun update(viewModels: List<Conversation>) {
update(ConversationFacade.ConversationList(viewModels))
}
fun update(viewModels: ConversationFacade.ConversationList) {
val old: ConversationFacade.ConversationList = conversations
conversations = setItems(viewModels)
if (!viewModels.isEmpty()) {
val recyclerViewState = recyclerView?.layoutManager?.onSaveInstanceState()
DiffUtil.calculateDiff(SmartListDiffUtil(old, viewModels))
.dispatchUpdatesTo(this)
recyclerView?.layoutManager?.onRestoreInstanceState(recyclerViewState)
} else {
notifyDataSetChanged()
}
}
} | gpl-3.0 | 0658998d5e32fd64f24a0f2a0546494f | 39.281818 | 126 | 0.724153 | 4.955257 | false | false | false | false |
ibinti/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/RemoteTestCase.kt | 11 | 5142 | /*
* 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 com.intellij.testGuiFramework.remote
import com.intellij.testGuiFramework.launcher.GuiTestLocalLauncher
import com.intellij.testGuiFramework.launcher.ide.Ide
import com.intellij.testGuiFramework.remote.server.JUnitServerHolder
import com.intellij.testGuiFramework.remote.server.ServerHandler
import com.intellij.testGuiFramework.remote.transport.*
import java.util.concurrent.TimeUnit
/**
* @author Sergey Karashevich
*/
abstract class RemoteTestCase {
fun startIde(ide: Ide,
host: String = "localhost",
port: Int,
path: String = "undefined",
body: IdeTestFixture.() -> Unit) {
with(IdeTestFixture(ide, host, port, path)) {
start()
body()
}
}
fun installPlugin(ide: com.intellij.testGuiFramework.launcher.ide.Ide) {
TODO("add body here")
}
fun startAndClose(ide: com.intellij.testGuiFramework.launcher.ide.Ide,
host: String = "localhost",
port: Int,
path: String = "undefined",
body: com.intellij.testGuiFramework.remote.IdeTestFixture.() -> Unit) {
with(IdeTestFixture(ide, host, port, path)) {
start()
body()
close()
}
}
}
class IdeTestFixture(val ide: Ide,
val host: String,
val port: Int,
val path: String = "undefined") {
fun start() {
val server = JUnitServerHolder.getServer() // ensure that server has been started
val serverPort = server.getPort()
if (path == "undefined") {
if (!server.isConnected()) {
GuiTestLocalLauncher.runIdeLocally(ide, serverPort)
} else {
TODO("idea is already started")
}
}
else {
//ensure that TestGuiFramework has been copied
//copy test classes or add additional classpath as an argument
GuiTestLocalLauncher.runIdeByPath(path, ide, serverPort)
}
}
fun close() {
JUnitServerHolder.getServer().sendAndWaitAnswer(TransportMessage(MessageType.CLOSE_IDE), 300L, TimeUnit.SECONDS)
}
fun runTest(testClassAndMethod: String,
timeout: Long = 0,
timeUnit: java.util.concurrent.TimeUnit = java.util.concurrent.TimeUnit.SECONDS) {
val (testClassName, testMethodName) = testClassAndMethod.split("#")
val declaringClass = Class.forName(testClassName)
val myCountDownLatch = java.util.concurrent.CountDownLatch(1)
val myServerHandler = createServerHandlerForTest(testClassAndMethod, myCountDownLatch)
with(JUnitServerHolder.getServer()) {
addHandler(myServerHandler)
setFailHandler({ throwable -> myCountDownLatch.countDown(); throw throwable })
send(runTestMessage(declaringClass, testMethodName)) // send container with test to IDE with started JUnitClient to run test
if (timeout == 0L)
myCountDownLatch.await()
else
myCountDownLatch.await(timeout, timeUnit)
removeHandler(myServerHandler)
}
}
private fun runTestMessage(declaringClass: Class<*>, methodName: String): TransportMessage
= TransportMessage(MessageType.RUN_TEST, JUnitTestContainer(declaringClass, methodName))
private fun createServerHandlerForTest(testName: String, conditionToFinish: java.util.concurrent.CountDownLatch): ServerHandler {
return object : ServerHandler() {
override fun acceptObject(message: TransportMessage) = message.content is JUnitInfo
override fun handleObject(message: TransportMessage) {
val jUnitInfo = message.content as JUnitInfo
when (jUnitInfo.type) {
Type.STARTED -> println("Test '$testName' started")
Type.ASSUMPTION_FAILURE -> {
println("Test '$testName' assumption error"); conditionToFinish.countDown()
}
Type.IGNORED -> {
println("Test '$testName' ignored"); conditionToFinish.countDown()
}
Type.FAILURE -> {
println("Test '$testName' failed");
// (jUnitInfo.obj as Array<StackTraceElement>)
// .forEach { System.err.println(it) }
val t = jUnitInfo.obj as Throwable
System.err.println(t)
t.printStackTrace(System.err)
conditionToFinish.countDown()
}
Type.FINISHED -> {
println("Test '$testName' finished"); conditionToFinish.countDown()
}
else -> throw UnsupportedOperationException("Unable to recognize received from JUnitClient")
}
}
}
}
} | apache-2.0 | 64254ab48e698c0e8ce255e7c6fb8653 | 34.468966 | 131 | 0.663555 | 4.704483 | false | true | false | false |
collave/workbench-android-common | library/src/main/kotlin/com/collave/workbench/common/android/component/state/StatefulRequest.kt | 1 | 1279 | package com.collave.workbench.common.android.component.state
import io.reactivex.Single
/**
* Created by Andrew on 4/20/2017.
*/
abstract class StatefulRequest<T> {
enum class State {
Idle, InProgress, RequestError, Successful;
val isIdle: Boolean get() = this == Idle
val isInProgress: Boolean get() = this == InProgress
val isRequestError: Boolean get() = this == RequestError
val isSuccessful: Boolean get() = this == Successful
}
val lastErrorVariable = NullableVariable<Throwable>()
var lastError by lastErrorVariable
private set
val stateVariable = Variable(State.Idle)
var state by stateVariable
private set
val onStateUpdated get() = stateVariable.onValueUpdated
val onErrorReceived get() = lastErrorVariable.onValueUpdated
abstract fun createRequest(vararg args: Any?): Single<T>
abstract fun handleResult(result: T)
fun execute(vararg args: Any?) {
if (state == State.InProgress) return
state = State.InProgress
createRequest(*args).subscribe({ result ->
handleResult(result)
state = State.Successful
}) { error ->
lastError = error
state = State.RequestError
}
}
} | gpl-3.0 | 68f3cf4b316f460f98dbcbbbe4a24b87 | 27.444444 | 64 | 0.652072 | 4.667883 | false | false | false | false |
wiryls/HomeworkCollectionOfMYLS | 2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/fragment/DormApplFragment.kt | 1 | 11181 | package com.myls.odes.fragment
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.ViewGroup
import com.myls.odes.R
import com.myls.odes.activity.MainActivity
import com.myls.odes.application.AnApplication
import com.myls.odes.data.UserList
import org.greenrobot.eventbus.EventBus
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.support.design.widget.Snackbar
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.widget.Toast
import com.myls.odes.data.RoomInfo
import com.myls.odes.request.QueryApply
import com.myls.odes.request.QueryRoom
import com.myls.odes.request.ResponseCode
import com.myls.odes.service.PullJsonService
import com.myls.odes.utility.Storage
import kotlinx.android.synthetic.main.fragment_dorm_appl.*
import kotlinx.android.synthetic.main.item_friend.view.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import android.view.animation.AnimationUtils
class DormApplFragment : Fragment()
{
private var holder: Holder? = null
private lateinit var saver: Storage
private lateinit var userl: UserList
private lateinit var roomi: RoomInfo
private lateinit var user: UserList.User
override fun onCreateView
(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)
= inflater.inflate(R.layout.fragment_dorm_appl, container, false)!!
override fun onActivityCreated(savedInstanceState: Bundle?)
= super.onActivityCreated(savedInstanceState).also {
(activity.application as AnApplication).let {
saver = it.saver
userl = it.userlist
roomi = it.roominfo
user = userl.list.firstOrNull()
?: return@let post(MainActivity.InvalidDataEvent("UserList is empty"))
}
with(stid_view) {
text = user.info.stid
setOnClickListener { onCopyText(getString(R.string.desc_stid), user.info.stid) }
}
with(code_view) {
text = user.info.code
setOnClickListener { onCopyText(getString(R.string.desc_code), user.info.code) }
}
with(dorm_layout) {
setOnClickListener {
onPrepareDorm()
holder?.onReceiveFragmentAttribute(FragmentAttribute.DORM_DORM)
}
}
with(friends_layout) {
setOnClickListener{
holder?.onReceiveFragmentAttribute(FragmentAttribute.DORM_FRIS)
}
with(friends_value_layout) {
layoutManager = LinearLayoutManager([email protected])
adapter = FriendsRecyclerAdapter(user.dorm.fris)
}
}
onUpdateDormLayout()
onUpdateFriendsLayout()
}
private fun onCopyText(label: String, text: String) {
with(context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager) {
primaryClip = ClipData.newPlainText(label, text)
// [How to Copy Text to Clip Board in Android?]
// (https://stackoverflow.com/a/19253868)
// [What exactly is “label” parameter in ClipData in Android?]
// (https://stackoverflow.com/a/33207959)
}
Toast
.makeText(context, "$text ${getString(R.string.desc_copied)}", Toast.LENGTH_SHORT)
.show()
}
private fun onUpdateFloatingActionButton() {
holder?.fab?.run {
if (dorm_empty_layout.visibility == View.VISIBLE) {
hide()
} else {
show()
}
}
}
private fun onPrepareDorm() {
with(activity) {
val param = if (user.info.gender.contentEquals(getString(R.string.desc_female))) 2 else 1
Intent(Intent.ACTION_SYNC, null, this, PullJsonService::class.java).apply {
putExtra(PullJsonService.Contract.REQUEST.name, QueryRoom.Request(param))
startService(this)
}
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onApplyResultEvent(event: QueryApply.Response) {
holder?.isSending = false
val done = event.errcode == ResponseCode.SUCCESS.CODE
if (done) {
holder?.onReceiveFragmentAttribute(FragmentAttribute.DORMITORY)
activity.onBackPressed()
} else {
holder?.snb?.show()
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onUpdateDormLayout(event: RoomUpdatedEvent) {
if (event.done)
onUpdateDormLayout()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onUpdateDormLayout(event: UserDormUpdatedEvent = UserDormUpdatedEvent(user.dorm)) {
(if (roomi.info.containsKey(event.dorm.pick)) event.dorm.pick else "").let {
dorm_value_layout.visibility = if (it.isEmpty()) View.GONE else View.VISIBLE
dorm_empty_layout.visibility = if (it.isEmpty()) View.VISIBLE else View.GONE
dorm_value.text = getString(R.string.desc_fmt_building).format(it)
onUpdateFloatingActionButton()
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onUpdateFriendsLayout(event: UserDormUpdatedEvent = UserDormUpdatedEvent(user.dorm)) {
event.dorm.fris.let {
friends_empty_layout.visibility = if (it.isEmpty()) View.VISIBLE else View.GONE
friends_value_layout.visibility = if (it.isEmpty()) View.GONE else View.VISIBLE
friends_value_layout.adapter.notifyDataSetChanged()
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onServiceErrorEvent(event: PullJsonService.ErrorEvent) {
when(event.request) {
is QueryRoom.Request -> post(RoomUpdatedEvent(false, roomi))
is QueryApply.Request -> {
holder?.snb?.show()
holder?.isSending = false
}
else -> {}
}
Log.e(TAG, "Unexpected Error: ${event.code.name} - ${event.request} - ${event.message}")
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onRoomUpdatedEvent(event: QueryRoom.Response) {
val done = event.errcode == ResponseCode.SUCCESS.CODE
if (done) {
event.data.filter{
it.value.toIntOrNull() != null
}.map {
it.key to it.value.toInt()
}.toMap(roomi.info)
saver.put(roomi)
} else {
Log.d(TAG, "Unexpected Response: ${event.errcode} - ${event.data.getOrDefault("errmsg", "?")}")
}
EVENT_BUS.post(RoomUpdatedEvent(done, roomi))
}
override fun onAttach(context: Context) {
super.onAttach(context)
holder = Holder(context)
}
override fun onStart() {
super.onStart()
EVENT_BUS.register(this)
}
override fun onResume() {
super.onResume()
holder?.onResume()
onPrepareDorm()
holder?.fab?.run {
setOnClickListener {
if (holder?.isSending == true)
return@setOnClickListener
else
holder?.isSending = true
with(activity) {
val request = QueryApply.Request(
user.info.stid,
user.dorm.fris.map { it.stid to it.code }.toMap(),
user.dorm.pick,
3)
Intent(Intent.ACTION_SYNC, null, this, PullJsonService::class.java).apply {
putExtra(PullJsonService.Contract.REQUEST.name, request)
startService(this)
}
}
}
}
}
override fun onPause() {
holder?.onPause()
super.onPause()
holder?.fab?.run {
setOnClickListener(null)
}
}
override fun onStop() {
EVENT_BUS.unregister(this)
super.onStop()
}
override fun onDetach() {
holder = null
super.onDetach()
}
private class FriendsRecyclerAdapter(private val items: List<UserList.Dorm.Friend>)
: RecyclerView.Adapter<FriendsRecyclerAdapter.ViewHolder>()
{
override fun getItemCount() = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
= ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_friend, parent, false)!!)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
with(holder) { items[position].let {
stid.text = it.stid
code.text = it.code
}}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val stid = view.item_desc!!
val code = view.item_value!!
}
}
private class Holder(context: Context) {
private val interaction =
context as? FragmentInteraction
?: throw RuntimeException("$context must implement ${FragmentInteraction::class.java.simpleName}")
private val frameLayout = interaction.requireFrameLayout()
private var isSendingFlag = false
val snb = Snackbar.make(frameLayout, R.string.desc_no_server, Snackbar.LENGTH_SHORT)
val fab = interaction.requireFloatingActionButton()
fun onReceiveFragmentAttribute(attr: FragmentAttribute)
= interaction.onReceiveFragmentAttribute(attr)
fun onResume() {
with(fab) {
setImageResource(ICON_SEND)
show()
}
}
fun onPause() {
with(fab) {
hide()
setImageDrawable(null)
isClickable = false
}
}
var isSending: Boolean
get() = fab.isShown && isSendingFlag
set(status) {
if (!fab.isShown || status == isSendingFlag)
return
else
isSendingFlag = status
with(fab) {
setImageResource(if (status) ICON_WAIT else ICON_SEND)
if (status) {
AnimationUtils.loadAnimation(context, R.anim.rotate).let {
startAnimation(it)
}
} else {
clearAnimation()
}
}
}
companion object {
val ICON_SEND = R.drawable.ic_navigate_next_white
val ICON_WAIT = R.drawable.ic_refresh_white_24dp
}
}
data class RoomUpdatedEvent(val done: Boolean, val room: RoomInfo)
data class UserDormUpdatedEvent(val dorm: UserList.Dorm)
companion object {
private val TAG = DormApplFragment::class.java.canonicalName!!
private val EVENT_BUS = EventBus.getDefault()
private fun <T> post(data: T) = EVENT_BUS.post(data)
fun create() = DormApplFragment()
}
}
| mit | 48941e2db9473a672b0911a97a84822a | 32.166172 | 110 | 0.600877 | 4.53612 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/resolver/ResolverCoordinatorTest.kt | 3 | 3709 | package org.gradle.kotlin.dsl.resolver
import org.gradle.kotlin.dsl.fixtures.assertInstanceOf
import org.junit.Test
class ResolverCoordinatorTest {
@Test
fun `given an environment with a 'getScriptSectionTokens' entry, when no buildscript change, it will not try to retrieve the model`() {
val environment =
environmentWithGetScriptSectionTokensReturning(
"buildscript" to sequenceOf(""),
"plugins" to sequenceOf("")
)
val action1 = resolverActionFor(environment, null)
org.gradle.kotlin.dsl.fixtures.withInstanceOf<ResolverAction.RequestNew>(action1) {
val action2 = resolverActionFor(environment, scriptDependencies())
assertInstanceOf<ResolverAction.ReturnPrevious>(action2)
}
}
@Test
fun `given an environment with a 'getScriptSectionTokens' entry, when buildscript changes, it will try to retrieve the model again`() {
val env1 = environmentWithGetScriptSectionTokensReturning("buildscript" to sequenceOf("foo"))
val env2 = environmentWithGetScriptSectionTokensReturning("buildscript" to sequenceOf("bar"))
val action1 = resolverActionFor(env1, null)
org.gradle.kotlin.dsl.fixtures.withInstanceOf<ResolverAction.RequestNew>(action1) {
val action2 = resolverActionFor(env2, scriptDependencies())
assertInstanceOf<ResolverAction.RequestNew>(action2)
}
}
@Test
fun `given an environment with a 'getScriptSectionTokens' entry, when plugins block changes, it will try to retrieve the model again`() {
val env1 = environmentWithGetScriptSectionTokensReturning("plugins" to sequenceOf("foo"))
val env2 = environmentWithGetScriptSectionTokensReturning("plugins" to sequenceOf("bar"))
val action1 = resolverActionFor(env1, null)
org.gradle.kotlin.dsl.fixtures.withInstanceOf<ResolverAction.RequestNew>(action1) {
val action2 = resolverActionFor(env2, scriptDependencies())
assertInstanceOf<ResolverAction.RequestNew>(action2)
}
}
@Test
fun `given an environment lacking a 'getScriptSectionTokens' entry, it will always try to retrieve the model`() {
val environment = emptyMap<String, Any?>()
val action1 = resolverActionFor(environment, null)
org.gradle.kotlin.dsl.fixtures.withInstanceOf<ResolverAction.RequestNew>(action1) {
val action2 = resolverActionFor(environment, scriptDependencies())
assertInstanceOf<ResolverAction.RequestNew>(action2)
}
}
private
fun resolverActionFor(environment: Map<String, Any?>, previousDependencies: kotlin.script.dependencies.KotlinScriptExternalDependencies?) =
ResolverCoordinator.selectNextActionFor(EmptyScriptContents, environment, previousDependencies)
private
fun ResolverAction.RequestNew.scriptDependencies() =
KotlinBuildScriptDependencies(emptyList(), emptyList(), emptyList(), null, classPathBlocksHash)
private
fun environmentWithGetScriptSectionTokensReturning(vararg sections: Pair<String, Sequence<String>>) =
environmentWithGetScriptSectionTokens { _, section -> sections.find { it.first == section }?.second ?: emptySequence() }
private
fun environmentWithGetScriptSectionTokens(function: (CharSequence, String) -> Sequence<String>) =
mapOf<String, Any?>("getScriptSectionTokens" to function)
}
private
object EmptyScriptContents : kotlin.script.dependencies.ScriptContents {
override val file: java.io.File? = null
override val text: CharSequence? = ""
override val annotations: Iterable<Annotation> = emptyList()
}
| apache-2.0 | 218d45437ec577d739e1d34648fec901 | 42.127907 | 143 | 0.719871 | 4.761232 | false | true | false | false |
jayrave/falkon | falkon-sql-builder-common/src/main/kotlin/com/jayrave/falkon/sqlBuilders/common/SimpleQuerySqlBuilder.kt | 1 | 4094 | package com.jayrave.falkon.sqlBuilders.common
import com.jayrave.falkon.sqlBuilders.lib.JoinInfo
import com.jayrave.falkon.sqlBuilders.lib.OrderInfo
import com.jayrave.falkon.sqlBuilders.lib.SelectColumnInfo
import com.jayrave.falkon.sqlBuilders.lib.WhereSection
object SimpleQuerySqlBuilder {
/**
* Builds a `SELECT ...` statement with the passed in info. Conditions for `WHERE`
* clause are added in the iteration order of [whereSections]
*/
fun build(
tableName: String, distinct: Boolean, columns: Iterable<SelectColumnInfo>?,
joinInfos: Iterable<JoinInfo>?, whereSections: Iterable<WhereSection>?,
groupBy: Iterable<String>?, orderBy: Iterable<OrderInfo>?, limit: Long?,
offset: Long?): String {
val querySql = StringBuilder(120)
querySql.append("SELECT")
querySql.addDistinctIfRequired(distinct)
querySql.addColumnsToBeSelected(columns)
querySql.append(" FROM")
// JOIN clause takes care of including the table name. If there is no JOIN clause,
// the table name has to be included exclusively
if (!querySql.addJoinsIfPossible(joinInfos, tableName)) {
querySql.append(" $tableName")
}
querySql.addWhereIfPossible(whereSections, ARG_PLACEHOLDER)
querySql.addGroupIfPossible(groupBy)
querySql.addOrderByIfPossible(orderBy)
querySql.addLimitIfPossible(limit)
querySql.addOffsetIfPossible(offset)
return querySql.toString()
}
private fun StringBuilder.addDistinctIfRequired(distinct: Boolean) {
if (distinct) {
append(" DISTINCT")
}
}
private fun StringBuilder.addColumnsToBeSelected(columns: Iterable<SelectColumnInfo>?) {
append(' ') // Add separator
val columnSelection = columns.joinToStringIfHasItems {
val alias = it.alias
when (alias) {
null -> it.columnName
else -> "${it.columnName} AS $alias"
}
}
when (isValidPart(columnSelection)) {
true -> append(columnSelection) // Add comma separated column names
else -> append("*") // No columns were exclusively requested. Get back all
}
}
/**
* @return `true` if JOIN clause was added; `false` otherwise
*/
private fun StringBuilder.addJoinsIfPossible(
joinInfos: Iterable<JoinInfo>?, firstTableNameForFirstJoin: String)
: Boolean {
val joinSql = joinInfos?.buildJoinClause(firstTableNameForFirstJoin)
return when {
!isValidPart(joinSql) -> false
else -> {
append(" $joinSql")
true
}
}
}
private fun StringBuilder.addWhereIfPossible(
whereSections: Iterable<WhereSection>?, argPlaceholder: String) {
val whereSql = whereSections?.buildWhereClause(argPlaceholder)
if (isValidPart(whereSql)) {
append(" $whereSql")
}
}
private fun StringBuilder.addGroupIfPossible(groupBy: Iterable<String>?) {
val groupBySql = groupBy.joinToStringIfHasItems(prefix = " GROUP BY ") { it }
if (isValidPart(groupBySql)) {
append(groupBySql)
}
}
private fun StringBuilder.addOrderByIfPossible(orderBy: Iterable<OrderInfo>?) {
val orderBySql = orderBy.joinToStringIfHasItems(prefix = " ORDER BY ") {
val order = if (it.ascending) "ASC" else "DESC"
"${it.columnName} $order"
}
if (isValidPart(orderBySql)) {
append(orderBySql)
}
}
private fun StringBuilder.addLimitIfPossible(limit: Long?) {
if (limit != null) {
append(" LIMIT $limit")
}
}
private fun StringBuilder.addOffsetIfPossible(offset: Long?) {
if (offset != null) {
append(" OFFSET $offset")
}
}
private fun isValidPart(sqlString: String?): Boolean {
return !sqlString.isNullOrBlank()
}
} | apache-2.0 | d027fdc87624c6658ff2945a162f7725 | 30.022727 | 92 | 0.621153 | 4.700344 | false | false | false | false |
Kotlin/anko | anko/library/generated/sdk23-listeners/src/main/java/Listeners.kt | 4 | 20213 | @file:JvmName("Sdk23ListenersListenersKt")
package org.jetbrains.anko.sdk23.listeners
inline fun android.view.View.onLayoutChange(noinline l: (v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit) {
addOnLayoutChangeListener(l)
}
fun android.view.View.onAttachStateChangeListener(init: __View_OnAttachStateChangeListener.() -> Unit) {
val listener = __View_OnAttachStateChangeListener()
listener.init()
addOnAttachStateChangeListener(listener)
}
class __View_OnAttachStateChangeListener : android.view.View.OnAttachStateChangeListener {
private var _onViewAttachedToWindow: ((android.view.View) -> Unit)? = null
override fun onViewAttachedToWindow(v: android.view.View) {
_onViewAttachedToWindow?.invoke(v)
}
fun onViewAttachedToWindow(listener: (android.view.View) -> Unit) {
_onViewAttachedToWindow = listener
}
private var _onViewDetachedFromWindow: ((android.view.View) -> Unit)? = null
override fun onViewDetachedFromWindow(v: android.view.View) {
_onViewDetachedFromWindow?.invoke(v)
}
fun onViewDetachedFromWindow(listener: (android.view.View) -> Unit) {
_onViewDetachedFromWindow = listener
}
}
fun android.widget.TextView.textChangedListener(init: __TextWatcher.() -> Unit) {
val listener = __TextWatcher()
listener.init()
addTextChangedListener(listener)
}
class __TextWatcher : android.text.TextWatcher {
private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
_beforeTextChanged?.invoke(s, start, count, after)
}
fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_beforeTextChanged = listener
}
private var _onTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
_onTextChanged?.invoke(s, start, before, count)
}
fun onTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_onTextChanged = listener
}
private var _afterTextChanged: ((android.text.Editable?) -> Unit)? = null
override fun afterTextChanged(s: android.text.Editable?) {
_afterTextChanged?.invoke(s)
}
fun afterTextChanged(listener: (android.text.Editable?) -> Unit) {
_afterTextChanged = listener
}
}
fun android.gesture.GestureOverlayView.onGestureListener(init: __GestureOverlayView_OnGestureListener.() -> Unit) {
val listener = __GestureOverlayView_OnGestureListener()
listener.init()
addOnGestureListener(listener)
}
class __GestureOverlayView_OnGestureListener : android.gesture.GestureOverlayView.OnGestureListener {
private var _onGestureStarted: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureStarted?.invoke(overlay, event)
}
fun onGestureStarted(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureStarted = listener
}
private var _onGesture: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGesture?.invoke(overlay, event)
}
fun onGesture(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGesture = listener
}
private var _onGestureEnded: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureEnded?.invoke(overlay, event)
}
fun onGestureEnded(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureEnded = listener
}
private var _onGestureCancelled: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureCancelled?.invoke(overlay, event)
}
fun onGestureCancelled(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureCancelled = listener
}
}
inline fun android.gesture.GestureOverlayView.onGesturePerformed(noinline l: (overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit) {
addOnGesturePerformedListener(l)
}
fun android.gesture.GestureOverlayView.onGesturingListener(init: __GestureOverlayView_OnGesturingListener.() -> Unit) {
val listener = __GestureOverlayView_OnGesturingListener()
listener.init()
addOnGesturingListener(listener)
}
class __GestureOverlayView_OnGesturingListener : android.gesture.GestureOverlayView.OnGesturingListener {
private var _onGesturingStarted: ((android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) {
_onGesturingStarted?.invoke(overlay)
}
fun onGesturingStarted(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingStarted = listener
}
private var _onGesturingEnded: ((android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) {
_onGesturingEnded?.invoke(overlay)
}
fun onGesturingEnded(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingEnded = listener
}
}
inline fun android.media.tv.TvView.onUnhandledInputEvent(noinline l: (event: android.view.InputEvent?) -> Boolean) {
setOnUnhandledInputEventListener(l)
}
inline fun android.view.View.onApplyWindowInsets(noinline l: (v: android.view.View?, insets: android.view.WindowInsets?) -> android.view.WindowInsets?) {
setOnApplyWindowInsetsListener(l)
}
inline fun android.view.View.onClick(noinline l: (v: android.view.View?) -> Unit) {
setOnClickListener(l)
}
inline fun android.view.View.onContextClick(noinline l: (v: android.view.View?) -> Boolean) {
setOnContextClickListener(l)
}
inline fun android.view.View.onCreateContextMenu(noinline l: (menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit) {
setOnCreateContextMenuListener(l)
}
inline fun android.view.View.onDrag(noinline l: (v: android.view.View, event: android.view.DragEvent) -> Boolean) {
setOnDragListener(l)
}
inline fun android.view.View.onFocusChange(noinline l: (v: android.view.View, hasFocus: Boolean) -> Unit) {
setOnFocusChangeListener(l)
}
inline fun android.view.View.onGenericMotion(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnGenericMotionListener(l)
}
inline fun android.view.View.onHover(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnHoverListener(l)
}
inline fun android.view.View.onKey(noinline l: (v: android.view.View, keyCode: Int, event: android.view.KeyEvent?) -> Boolean) {
setOnKeyListener(l)
}
inline fun android.view.View.onLongClick(noinline l: (v: android.view.View?) -> Boolean) {
setOnLongClickListener(l)
}
inline fun android.view.View.onScrollChange(noinline l: (v: android.view.View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit) {
setOnScrollChangeListener(l)
}
inline fun android.view.View.onSystemUiVisibilityChange(noinline l: (visibility: Int) -> Unit) {
setOnSystemUiVisibilityChangeListener(l)
}
inline fun android.view.View.onTouch(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnTouchListener(l)
}
fun android.view.ViewGroup.onHierarchyChangeListener(init: __ViewGroup_OnHierarchyChangeListener.() -> Unit) {
val listener = __ViewGroup_OnHierarchyChangeListener()
listener.init()
setOnHierarchyChangeListener(listener)
}
class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener {
private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) {
_onChildViewAdded?.invoke(parent, child)
}
fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewAdded = listener
}
private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) {
_onChildViewRemoved?.invoke(parent, child)
}
fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewRemoved = listener
}
}
inline fun android.view.ViewStub.onInflate(noinline l: (stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit) {
setOnInflateListener(l)
}
fun android.widget.AbsListView.onScrollListener(init: __AbsListView_OnScrollListener.() -> Unit) {
val listener = __AbsListView_OnScrollListener()
listener.init()
setOnScrollListener(listener)
}
class __AbsListView_OnScrollListener : android.widget.AbsListView.OnScrollListener {
private var _onScrollStateChanged: ((android.widget.AbsListView?, Int) -> Unit)? = null
override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) {
_onScrollStateChanged?.invoke(view, scrollState)
}
fun onScrollStateChanged(listener: (android.widget.AbsListView?, Int) -> Unit) {
_onScrollStateChanged = listener
}
private var _onScroll: ((android.widget.AbsListView?, Int, Int, Int) -> Unit)? = null
override fun onScroll(view: android.widget.AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
_onScroll?.invoke(view, firstVisibleItem, visibleItemCount, totalItemCount)
}
fun onScroll(listener: (android.widget.AbsListView?, Int, Int, Int) -> Unit) {
_onScroll = listener
}
}
inline fun android.widget.ActionMenuView.onMenuItemClick(noinline l: (item: android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
inline fun android.widget.AdapterView<out android.widget.Adapter>.onItemClick(noinline l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) {
setOnItemClickListener(l)
}
inline fun android.widget.AdapterView<out android.widget.Adapter>.onItemLongClick(noinline l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Boolean) {
setOnItemLongClickListener(l)
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemSelectedListener(init: __AdapterView_OnItemSelectedListener.() -> Unit) {
val listener = __AdapterView_OnItemSelectedListener()
listener.init()
setOnItemSelectedListener(listener)
}
class __AdapterView_OnItemSelectedListener : android.widget.AdapterView.OnItemSelectedListener {
private var _onItemSelected: ((android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) {
_onItemSelected?.invoke(p0, p1, p2, p3)
}
fun onItemSelected(listener: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
_onItemSelected = listener
}
private var _onNothingSelected: ((android.widget.AdapterView<*>?) -> Unit)? = null
override fun onNothingSelected(p0: android.widget.AdapterView<*>?) {
_onNothingSelected?.invoke(p0)
}
fun onNothingSelected(listener: (android.widget.AdapterView<*>?) -> Unit) {
_onNothingSelected = listener
}
}
inline fun android.widget.AutoCompleteTextView.onDismiss(noinline l: () -> Unit) {
setOnDismissListener(l)
}
inline fun android.widget.CalendarView.onDateChange(noinline l: (view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit) {
setOnDateChangeListener(l)
}
inline fun android.widget.Chronometer.onChronometerTick(noinline l: (chronometer: android.widget.Chronometer?) -> Unit) {
setOnChronometerTickListener(l)
}
inline fun android.widget.CompoundButton.onCheckedChange(noinline l: (buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit) {
setOnCheckedChangeListener(l)
}
inline fun android.widget.ExpandableListView.onChildClick(noinline l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Boolean) {
setOnChildClickListener(l)
}
inline fun android.widget.ExpandableListView.onGroupClick(noinline l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Boolean) {
setOnGroupClickListener(l)
}
inline fun android.widget.ExpandableListView.onGroupCollapse(noinline l: (groupPosition: Int) -> Unit) {
setOnGroupCollapseListener(l)
}
inline fun android.widget.ExpandableListView.onGroupExpand(noinline l: (groupPosition: Int) -> Unit) {
setOnGroupExpandListener(l)
}
inline fun android.widget.NumberPicker.onScroll(noinline l: (view: android.widget.NumberPicker?, scrollState: Int) -> Unit) {
setOnScrollListener(l)
}
inline fun android.widget.NumberPicker.onValueChanged(noinline l: (picker: android.widget.NumberPicker?, oldVal: Int, newVal: Int) -> Unit) {
setOnValueChangedListener(l)
}
inline fun android.widget.RadioGroup.onCheckedChange(noinline l: (group: android.widget.RadioGroup?, checkedId: Int) -> Unit) {
setOnCheckedChangeListener(l)
}
inline fun android.widget.RatingBar.onRatingBarChange(noinline l: (ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit) {
setOnRatingBarChangeListener(l)
}
inline fun android.widget.SearchView.onClose(noinline l: () -> Boolean) {
setOnCloseListener(l)
}
inline fun android.widget.SearchView.onQueryTextFocusChange(noinline l: (v: android.view.View, hasFocus: Boolean) -> Unit) {
setOnQueryTextFocusChangeListener(l)
}
fun android.widget.SearchView.onQueryTextListener(init: __SearchView_OnQueryTextListener.() -> Unit) {
val listener = __SearchView_OnQueryTextListener()
listener.init()
setOnQueryTextListener(listener)
}
class __SearchView_OnQueryTextListener : android.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: ((String?) -> Boolean)? = null
override fun onQueryTextSubmit(query: String?) = _onQueryTextSubmit?.invoke(query) ?: false
fun onQueryTextSubmit(listener: (String?) -> Boolean) {
_onQueryTextSubmit = listener
}
private var _onQueryTextChange: ((String?) -> Boolean)? = null
override fun onQueryTextChange(newText: String?) = _onQueryTextChange?.invoke(newText) ?: false
fun onQueryTextChange(listener: (String?) -> Boolean) {
_onQueryTextChange = listener
}
}
inline fun android.widget.SearchView.onSearchClick(noinline l: (v: android.view.View?) -> Unit) {
setOnSearchClickListener(l)
}
fun android.widget.SearchView.onSuggestionListener(init: __SearchView_OnSuggestionListener.() -> Unit) {
val listener = __SearchView_OnSuggestionListener()
listener.init()
setOnSuggestionListener(listener)
}
class __SearchView_OnSuggestionListener : android.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: ((Int) -> Boolean)? = null
override fun onSuggestionSelect(position: Int) = _onSuggestionSelect?.invoke(position) ?: false
fun onSuggestionSelect(listener: (Int) -> Boolean) {
_onSuggestionSelect = listener
}
private var _onSuggestionClick: ((Int) -> Boolean)? = null
override fun onSuggestionClick(position: Int) = _onSuggestionClick?.invoke(position) ?: false
fun onSuggestionClick(listener: (Int) -> Boolean) {
_onSuggestionClick = listener
}
}
fun android.widget.SeekBar.onSeekBarChangeListener(init: __SeekBar_OnSeekBarChangeListener.() -> Unit) {
val listener = __SeekBar_OnSeekBarChangeListener()
listener.init()
setOnSeekBarChangeListener(listener)
}
class __SeekBar_OnSeekBarChangeListener : android.widget.SeekBar.OnSeekBarChangeListener {
private var _onProgressChanged: ((android.widget.SeekBar?, Int, Boolean) -> Unit)? = null
override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) {
_onProgressChanged?.invoke(seekBar, progress, fromUser)
}
fun onProgressChanged(listener: (android.widget.SeekBar?, Int, Boolean) -> Unit) {
_onProgressChanged = listener
}
private var _onStartTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {
_onStartTrackingTouch?.invoke(seekBar)
}
fun onStartTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStartTrackingTouch = listener
}
private var _onStopTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {
_onStopTrackingTouch?.invoke(seekBar)
}
fun onStopTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStopTrackingTouch = listener
}
}
inline fun android.widget.SlidingDrawer.onDrawerClose(noinline l: () -> Unit) {
setOnDrawerCloseListener(l)
}
inline fun android.widget.SlidingDrawer.onDrawerOpen(noinline l: () -> Unit) {
setOnDrawerOpenListener(l)
}
fun android.widget.SlidingDrawer.onDrawerScrollListener(init: __SlidingDrawer_OnDrawerScrollListener.() -> Unit) {
val listener = __SlidingDrawer_OnDrawerScrollListener()
listener.init()
setOnDrawerScrollListener(listener)
}
class __SlidingDrawer_OnDrawerScrollListener : android.widget.SlidingDrawer.OnDrawerScrollListener {
private var _onScrollStarted: (() -> Unit)? = null
override fun onScrollStarted() {
_onScrollStarted?.invoke()
}
fun onScrollStarted(listener: () -> Unit) {
_onScrollStarted = listener
}
private var _onScrollEnded: (() -> Unit)? = null
override fun onScrollEnded() {
_onScrollEnded?.invoke()
}
fun onScrollEnded(listener: () -> Unit) {
_onScrollEnded = listener
}
}
inline fun android.widget.TabHost.onTabChanged(noinline l: (tabId: String?) -> Unit) {
setOnTabChangedListener(l)
}
inline fun android.widget.TextView.onEditorAction(noinline l: (v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Boolean) {
setOnEditorActionListener(l)
}
inline fun android.widget.TimePicker.onTimeChanged(noinline l: (view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit) {
setOnTimeChangedListener(l)
}
inline fun android.widget.Toolbar.onMenuItemClick(noinline l: (item: android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
inline fun android.widget.VideoView.onCompletion(noinline l: (mp: android.media.MediaPlayer?) -> Unit) {
setOnCompletionListener(l)
}
inline fun android.widget.VideoView.onError(noinline l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) {
setOnErrorListener(l)
}
inline fun android.widget.VideoView.onInfo(noinline l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) {
setOnInfoListener(l)
}
inline fun android.widget.VideoView.onPrepared(noinline l: (mp: android.media.MediaPlayer?) -> Unit) {
setOnPreparedListener(l)
}
inline fun android.widget.ZoomControls.onZoomInClick(noinline l: (v: android.view.View?) -> Unit) {
setOnZoomInClickListener(l)
}
inline fun android.widget.ZoomControls.onZoomOutClick(noinline l: (v: android.view.View?) -> Unit) {
setOnZoomOutClickListener(l)
}
| apache-2.0 | 3eeedd790cba1b994ab2cfa9c5ca69ff | 35.48556 | 201 | 0.727057 | 4.372269 | false | false | false | false |
SourceUtils/hl2-utils | src/main/kotlin/com/timepath/hl2/CVarTest.kt | 1 | 17551 | package com.timepath.hl2
import com.timepath.hl2.cvar.CVar
import com.timepath.hl2.cvar.CVarList
import com.timepath.plaf.x.filechooser.NativeFileChooser
import com.timepath.swing.StatusBar
import java.awt.Color
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.io.IOException
import java.io.RandomAccessFile
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
import java.util.regex.Pattern
import java.util.regex.PatternSyntaxException
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.table.DefaultTableModel
import javax.swing.table.TableModel
import javax.swing.table.TableRowSorter
import kotlin.platform.platformStatic
/**
* @author TimePath
*/
SuppressWarnings("serial")
class CVarTest
/**
* Creates new form CVarTest
*/
private constructor() : JFrame() {
private val sorter: TableRowSorter<TableModel>
private var caseSensitiveCheckBox: JCheckBox? = null
private var jLabel1: JLabel? = null
private var jLabel5: JLabel? = null
private var jTable1: JTable? = null
private var jTextField1: JTextField? = null
private var notCheckBox: JCheckBox? = null
private var regexCheckBox: JCheckBox? = null
init {
initComponents()
sorter = TableRowSorter(jTable1!!.getModel())
val comparator = object : Comparator<String> {
override fun compare(o1: String, o2: String): Int {
return (o1.replaceFirstLiteral("+", "")
.replaceFirstLiteral("-", "")
.toLowerCase()).compareTo(o2.replaceFirstLiteral("+", "")
.replaceFirstLiteral("-", "")
.toLowerCase())
}
}
sorter.setComparator(0, comparator)
val sortKeys = LinkedList<RowSorter.SortKey>()
sortKeys.add(RowSorter.SortKey(0, SortOrder.ASCENDING))
sorter.setSortKeys(sortKeys)
jTable1!!.setRowSorter(sorter)
jTextField1!!.getDocument().addDocumentListener(object : DocumentListener {
override fun insertUpdate(e: DocumentEvent) {
filter()
}
override fun removeUpdate(e: DocumentEvent) {
filter()
}
override fun changedUpdate(e: DocumentEvent) {
filter()
}
})
}
private fun filter() {
jLabel1!!.setText(Integer.toString(sorter.getModelRowCount()))
try {
var str = jTextField1!!.getText()
if (str.isEmpty()) {
sorter.setRowFilter(null)
} else {
if (!regexCheckBox!!.isSelected()) {
str = Pattern.quote(str)
}
if (!caseSensitiveCheckBox!!.isSelected()) {
str = "(?i)$str"
}
var rf = RowFilter.regexFilter<TableModel, Any>(str, 0, 1, 2, 3, 4, 5, 6)
if (notCheckBox!!.isSelected()) {
rf = RowFilter.notFilter<TableModel, Any>(rf)
}
sorter.setRowFilter(rf)
}
jLabel5!!.setText(Integer.toString(sorter.getViewRowCount()))
jTextField1!!.setForeground(Color.BLACK)
} catch (e: PatternSyntaxException) {
jTextField1!!.setForeground(Color.RED)
}
}
private fun initComponents() {
val jScrollPane1 = JScrollPane()
jTable1 = JTable()
val statusBar1 = StatusBar()
val jLabel2 = JLabel()
jLabel1 = JLabel()
val jSeparator1 = JToolBar.Separator()
val jLabel4 = JLabel()
jLabel5 = JLabel()
val jPanel1 = JPanel()
jTextField1 = JTextField()
val jLabel3 = JLabel()
regexCheckBox = JCheckBox()
caseSensitiveCheckBox = JCheckBox()
notCheckBox = JCheckBox()
val jMenuBar1 = JMenuBar()
val jMenu1 = JMenu()
val jMenuItem1 = JMenuItem()
val jMenuItem4 = JMenuItem()
val jMenuItem6 = JMenuItem()
val jMenuItem5 = JMenuItem()
val jMenuItem7 = JMenuItem()
val jMenu2 = JMenu()
val jMenuItem2 = JMenuItem()
val jMenuItem3 = JMenuItem()
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
setTitle("CVar listing")
jTable1!!.setModel(DefaultTableModel(arrayOf<Array<Any>>(), arrayOf("Name", "Value", "Default", "Min", "Max", "Tags", "Description")))
jScrollPane1.setViewportView(jTable1)
statusBar1.setRollover(true)
jLabel2.setText(" Total convars/concommands: ")
statusBar1.add(jLabel2)
jLabel1!!.setText("0")
statusBar1.add(jLabel1!!)
statusBar1.add(jSeparator1)
jLabel4.setText("Showing: ")
statusBar1.add(jLabel4)
jLabel5!!.setText("0")
statusBar1.add(jLabel5!!)
jLabel3.setText("Find:")
regexCheckBox!!.setMnemonic('R')
regexCheckBox!!.setText("Regular Expression")
regexCheckBox!!.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
regexCheckBoxActionPerformed()
}
})
caseSensitiveCheckBox!!.setMnemonic('M')
caseSensitiveCheckBox!!.setText("Match Case")
caseSensitiveCheckBox!!.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
caseSensitiveCheckBoxActionPerformed()
}
})
notCheckBox!!.setMnemonic('M')
notCheckBox!!.setText("Not")
notCheckBox!!.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
notCheckBoxActionPerformed()
}
})
val jPanel1Layout = GroupLayout(jPanel1)
jPanel1.setLayout(jPanel1Layout)
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1!!)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(notCheckBox!!)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(caseSensitiveCheckBox!!)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(regexCheckBox!!)))
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1!!, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(regexCheckBox!!)
.addComponent(caseSensitiveCheckBox!!)
.addComponent(notCheckBox!!))
.addGap(0, 0, 0)))
jMenu1.setText("File")
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK))
jMenuItem1.setText("Open")
jMenuItem1.addActionListener {
jMenuItem1ActionPerformed()
}
jMenu1.add(jMenuItem1)
jMenuItem4.setText("Get cvarlist")
jMenuItem4.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
jMenuItem4ActionPerformed()
}
})
jMenu1.add(jMenuItem4)
jMenuItem6.setText("Get differences")
jMenuItem6.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
jMenuItem6ActionPerformed()
}
})
jMenu1.add(jMenuItem6)
jMenuItem5.setText("Reset cvars")
jMenuItem5.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
jMenuItem5ActionPerformed()
}
})
jMenu1.add(jMenuItem5)
jMenuItem7.setText("Clear")
jMenuItem7.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
jMenuItem7ActionPerformed()
}
})
jMenu1.add(jMenuItem7)
jMenuBar1.add(jMenu1)
jMenu2.setText("Edit")
jMenuItem2.setText("Copy names")
jMenuItem2.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
jMenuItem2ActionPerformed()
}
})
jMenu2.add(jMenuItem2)
jMenuItem3.setText("Copy markdown")
jMenuItem3.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
jMenuItem3ActionPerformed()
}
})
jMenu2.add(jMenuItem3)
jMenuBar1.add(jMenu2)
setJMenuBar(jMenuBar1)
val layout = GroupLayout(getContentPane())
getContentPane().setLayout(layout)
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(statusBar1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt()).addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 908, java.lang.Short.MAX_VALUE.toInt()).addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt()))
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addGap(0, 0, 0).addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 201, java.lang.Short.MAX_VALUE.toInt()).addGap(0, 0, 0).addComponent(statusBar1, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)))
pack()
}
private fun analyze(scanner: Scanner): Map<String, CVar> {
return CVarList.analyzeList(scanner, HashMap<String, CVar>())
}
private fun jMenuItem1ActionPerformed() {
try {
val f = NativeFileChooser().setTitle("Select cvarlist").choose()
if (f != null) {
val worker = object : SwingWorker<Void, Array<Any?>>() {
override fun doInBackground(): Void? {
val rf = RandomAccessFile(f[0].getPath(), "r")
val scanner = Scanner(rf.getChannel())
val map = analyze(scanner)
for (entry in map.entrySet()) {
val v = entry.getValue()
publish(arrayOf(v.name, v.value, v.defaultValue, v.minimum, v.maximum, Arrays.toString(v.tags.toTypedArray()), v.desc))
}
return null
}
override fun process(chunks: List<Array<Any?>>?) {
for (row in chunks!!) {
(jTable1!!.getModel() as DefaultTableModel).addRow(row)
}
filter()
}
}
worker.execute()
}
} catch (ex: IOException) {
Logger.getLogger(javaClass<CVarTest>().getName()).log(Level.SEVERE, null, ex)
}
}
private fun regexCheckBoxActionPerformed() {
filter()
}
private fun caseSensitiveCheckBoxActionPerformed() {
filter()
}
private fun jMenuItem2ActionPerformed() {
val sb = StringBuilder()
for (i in 0..jTable1!!.getModel().getRowCount() - 1) {
val row = jTable1!!.convertRowIndexToModel(i)
sb.append(jTable1!!.getModel().getValueAt(row, 0)).append('\n')
}
val selection = StringSelection(sb.toString())
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection)
}
private fun jMenuItem3ActionPerformed() {
val m = jTable1!!.getModel()
val sb = StringBuilder()
val tab = "|"
val col: Int
val rows = m.getRowCount()
val cols = m.getColumnCount()
for (i in 0..cols - 1) {
col = jTable1!!.convertColumnIndexToModel(i)
sb.append(tab).append(m.getColumnName(col))
}
val line = "\n"
sb.append(tab).append(line)
for (i in 0..cols - 1) {
sb.append(tab).append("--")
}
sb.append(tab).append(line)
for (i in 0..rows - 1) {
val row = jTable1!!.convertRowIndexToModel(i)
for (j in 0..cols - 1) {
col = jTable1!!.convertColumnIndexToModel(j)
var obj: Any? = m.getValueAt(row, col)
if (col == 0) {
obj = "[$obj](/r/tf2scripthelp/wiki/$obj#todo \"TODO\")"
}
sb.append(tab)
if (obj != null) {
if (obj is Array<Any>) {
sb.append(obj[0])
for (k in 1..obj.size() - 1) {
sb.append(", ").append(obj[k])
}
} else {
sb.append(obj)
}
}
}
sb.append(tab).append(line)
}
val selection = StringSelection(sb.toString())
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection)
}
private fun jMenuItem4ActionPerformed() {
clear()
var ret: String? = null
val limit = 5
run {
var i = 0
while (true) {
val temp = ExternalConsole.exec("cvarlist; echo --end of cvarlist--", "--end of cvarlist--")
if (temp == ret) {
break
}
if (i == limit) {
LOG.warning("Aborting inconsistency fixer")
break
}
ret = temp
i++
}
}
val selection = StringSelection(ret)
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection)
val map = analyze(Scanner(ret!!))
for (entry in map.entrySet()) {
val v = entry.getValue()
val chunks = arrayOf(v.name, v.value, v.defaultValue, v.minimum, v.maximum, Arrays.toString(v.tags.toTypedArray()), v.desc)
(jTable1!!.getModel() as DefaultTableModel).addRow(chunks)
}
filter()
}
private fun notCheckBoxActionPerformed() {
filter()
}
private fun jMenuItem5ActionPerformed() {
val sb = StringBuilder()
sb.append("sv_cheats 1\n")
ExternalConsole.exec("sv_cheats 1", null)
val m = jTable1!!.getModel()
val rows = m.getRowCount()
for (i in 0..rows - 1) {
val row = jTable1!!.convertRowIndexToModel(i)
val name = m.getValueAt(row, jTable1!!.convertColumnIndexToModel(0))
if ("sv_cheats" == name.toString()) {
continue
}
val `val` = m.getValueAt(row, jTable1!!.convertColumnIndexToModel(2))
if (`val` != null) {
val strVal = "\"$`val`"
sb.append(name).append(' ').append(strVal).append('\n')
ExternalConsole.exec("${name.toString()} $strVal", null)
}
}
sb.append("sv_cheats 0\n")
ExternalConsole.exec("sv_cheats 0", null)
val selection = StringSelection(sb.toString())
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection)
}
private fun jMenuItem6ActionPerformed() {
clear()
val ret = ExternalConsole.exec("differences; echo --end of differences--", "--end of differences--")
val map = analyze(Scanner(ret))
for (entry in map.entrySet()) {
val `var` = entry.getValue()
val chunks = arrayOf(`var`.name, `var`.value, `var`.defaultValue, `var`.minimum, `var`.maximum, Arrays.toString(`var`.tags.toTypedArray()), `var`.desc)
(jTable1!!.getModel() as DefaultTableModel).addRow(chunks)
}
filter()
}
private fun jMenuItem7ActionPerformed() {
clear()
}
private fun clear() {
val dm = jTable1!!.getModel() as DefaultTableModel
val rowCount = dm.getRowCount()
for (i in 0..rowCount - 1) {
dm.removeRow(0)
}
filter()
}
companion object {
private val LOG = Logger.getLogger(javaClass<CVarTest>().getName())
public platformStatic fun main(args: Array<String>) {
SwingUtilities.invokeLater {
CVarTest().setVisible(true)
}
}
}
}
| artistic-2.0 | 26cc7132d4b364963ef8be2164746eab | 38.708145 | 445 | 0.574326 | 4.633316 | false | false | false | false |
VladRassokhin/intellij-hcl | src/java/org/intellij/plugins/hcl/UpdateComponent.kt | 1 | 5649 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hcl
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.components.ApplicationComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.EditorFactoryAdapter
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.FocusChangeListener
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.updateSettings.impl.UpdateChecker
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.io.HttpRequests
import org.intellij.plugins.hcl.terraform.config.TerraformFileType
import org.intellij.plugins.hil.HILFileType
import org.jdom.JDOMException
import java.io.IOException
import java.net.URLEncoder
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit
/**
* Based on org.rust.ide.update.UpdateComponent
*/
@Suppress("DEPRECATION")
class UpdateComponent : ApplicationComponent.Adapter(), Disposable {
init {
Disposer.register(ApplicationManager.getApplication(), this)
val pluginId = PluginManager.getPluginByClassName(this.javaClass.name)
val descriptor = PluginManager.getPlugin(pluginId)
ourCurrentPluginVersion = descriptor?.version
}
override fun initComponent() {
val application = ApplicationManager.getApplication()
if (!application.isUnitTestMode) {
EditorFactory.getInstance().addEditorFactoryListener(EditorListener(this), this)
}
}
override fun dispose() {
}
private class EditorListener(val parentDisposable: Disposable) : EditorFactoryAdapter() {
override fun editorCreated(event: EditorFactoryEvent) {
val document = event.editor.document
val file = FileDocumentManager.getInstance().getFile(document)
if (file != null && file.fileType in FILE_TYPES) {
updateOnPooledThread()
(event.editor as? EditorEx)?.addFocusListener(object : FocusChangeListener {
override fun focusGained(editor: Editor) {
updateOnPooledThread()
}
override fun focusLost(editor: Editor) {}
}, parentDisposable)
}
}
}
companion object {
private val lock: Any = Any()
private val PLUGIN_ID: String = "org.intellij.plugins.hcl"
private val LAST_UPDATE: String = "$PLUGIN_ID.LAST_UPDATE"
private val LAST_VERSION: String = "$PLUGIN_ID.LAST_VERSION"
private val FILE_TYPES: Set<FileType> = setOf(HCLFileType, TerraformFileType, HILFileType)
private val LOG = Logger.getInstance(UpdateComponent::class.java)
private var ourCurrentPluginVersion: String? = null
fun updateOnPooledThread() = ApplicationManager.getApplication().executeOnPooledThread { update() }
fun update() {
val properties = PropertiesComponent.getInstance()
synchronized(lock) {
val lastPluginVersion = properties.getValue(LAST_VERSION)
val lastUpdate = properties.getOrInitLong(LAST_UPDATE, 0L)
val shouldUpdate = lastUpdate == 0L
|| System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)
|| lastPluginVersion == null
|| lastPluginVersion != ourCurrentPluginVersion
if (shouldUpdate) {
properties.setValue(LAST_UPDATE, System.currentTimeMillis().toString())
properties.setValue(LAST_VERSION, ourCurrentPluginVersion)
} else {
return
}
}
val url = updateUrl
try {
HttpRequests.request(url).connect {
try {
JDOMUtil.load(it.reader)
} catch (e: JDOMException) {
LOG.warn(e)
}
LOG.info("updated: $url")
}
} catch (ignored: UnknownHostException) {
// No internet connections, no need to log anything
} catch (e: IOException) {
LOG.warn(e)
}
}
private val updateUrl: String get() {
val applicationInfo = ApplicationInfoEx.getInstanceEx()
val buildNumber = applicationInfo.build.asString()
val plugin = PluginManager.getPlugin(PluginId.getId(PLUGIN_ID))!!
val pluginId = plugin.pluginId.idString
val os = URLEncoder.encode("${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION}", Charsets.UTF_8.name())
val uid = UpdateChecker.getInstallationUID(PropertiesComponent.getInstance())
val baseUrl = "https://plugins.jetbrains.com/plugins/list"
return "$baseUrl?pluginId=$pluginId&build=$buildNumber&pluginVersion=${plugin.version}&os=$os&uuid=$uid"
}
}
} | apache-2.0 | 03640aec4ea5b1ca74cdf0b0078d3220 | 37.435374 | 110 | 0.7265 | 4.61897 | false | false | false | false |
jiaweizhang/pokur | src/test/kotlin/ProbabilityVerifyTests.kt | 1 | 4248 | import io.kotlintest.specs.StringSpec
import pokur.calculate.HandProcessor
import pokur.generate.CardGenerator
/**
* Created by jiaweizhang on 6/19/2017.
*/
class ProbabilityVerifyTests : StringSpec() {
val runs = 1000000
init {
val cg = CardGenerator()
val hp = HandProcessor()
"Probs 5" {
var sfCount = 0
var qCount = 0
var fhCount = 0
var fCount = 0
var sCount = 0
var tCount = 0
var tpCount = 0
var pCount = 0
var hCount = 0
for (i in 1..runs) {
val fiveCards = cg.generateCardsBySet(5)
val handValue = hp.findHandValue5(fiveCards)
when (handValue shr 20) {
9 -> sfCount++
8 -> qCount++
7 -> fhCount++
6 -> fCount++
5 -> sCount++
4 -> tCount++
3 -> tpCount++
2 -> pCount++
1 -> hCount++
}
}
println("SF: ${sfCount * 100.0 / runs}")
println("Q : ${qCount * 100.0 / runs}")
println("FH: ${fhCount * 100.0 / runs}")
println("F : ${fCount * 100.0 / runs}")
println("S : ${sCount * 100.0 / runs}")
println("T : ${tCount * 100.0 / runs}")
println("TP: ${tpCount * 100.0 / runs}")
println("P : ${pCount * 100.0 / runs}")
println("H : ${hCount * 100.0 / runs}")
println()
}
"Probs 6" {
var sfCount = 0
var qCount = 0
var fhCount = 0
var fCount = 0
var sCount = 0
var tCount = 0
var tpCount = 0
var pCount = 0
var hCount = 0
for (i in 1..runs) {
val sixCards = cg.generateCardsBySet(6)
val handValue = hp.findHandValue6Using5(sixCards)
when (handValue shr 20) {
9 -> sfCount++
8 -> qCount++
7 -> fhCount++
6 -> fCount++
5 -> sCount++
4 -> tCount++
3 -> tpCount++
2 -> pCount++
1 -> hCount++
}
}
println("SF: ${sfCount * 100.0 / runs}")
println("Q : ${qCount * 100.0 / runs}")
println("FH: ${fhCount * 100.0 / runs}")
println("F : ${fCount * 100.0 / runs}")
println("S : ${sCount * 100.0 / runs}")
println("T : ${tCount * 100.0 / runs}")
println("TP: ${tpCount * 100.0 / runs}")
println("P : ${pCount * 100.0 / runs}")
println("H : ${hCount * 100.0 / runs}")
println()
}
"Probs 7" {
var sfCount = 0
var qCount = 0
var fhCount = 0
var fCount = 0
var sCount = 0
var tCount = 0
var tpCount = 0
var pCount = 0
var hCount = 0
for (i in 1..runs) {
val sevenCards = cg.generateCardsBySet(7)
val handValue = hp.findHandValue7Complex(sevenCards)
when (handValue shr 20) {
9 -> sfCount++
8 -> qCount++
7 -> fhCount++
6 -> fCount++
5 -> sCount++
4 -> tCount++
3 -> tpCount++
2 -> pCount++
1 -> hCount++
}
}
println("SF: ${sfCount * 100.0 / runs}")
println("Q : ${qCount * 100.0 / runs}")
println("FH: ${fhCount * 100.0 / runs}")
println("F : ${fCount * 100.0 / runs}")
println("S : ${sCount * 100.0 / runs}")
println("T : ${tCount * 100.0 / runs}")
println("TP: ${tpCount * 100.0 / runs}")
println("P : ${pCount * 100.0 / runs}")
println("H : ${hCount * 100.0 / runs}")
println()
}
}
} | gpl-3.0 | f86f2a93ad6d970fd244ed9fe8a35c7c | 30.474074 | 68 | 0.389831 | 4.286579 | false | false | false | false |
mua-uniandes/weekly-problems | codeforces/43/A/43A.kt | 1 | 527 | package codeforces
import java.io.BufferedReader
import java.io.InputStreamReader
fun main() {
val In = BufferedReader(InputStreamReader(System.`in`))
val lines = In.readLine().toInt()
var s = ""
var s2 = ""
var a = 0
var b = 0
for(i in 1..lines) {
val team = In.readLine()
if(s.equals("") or s.equals(team) ) {
s = team
a++
} else {
s2 = team
b++
}
}
if (a > b)
print(s)
else
print(s2)
} | gpl-3.0 | 7080e18a38d3c055e2ed449b542d12ac | 18.555556 | 59 | 0.481973 | 3.585034 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/features/multiblock_parts/Blocks.kt | 2 | 3596 | package com.cout970.magneticraft.features.multiblock_parts
import com.cout970.magneticraft.misc.CreativeTabMg
import com.cout970.magneticraft.misc.RegisterBlocks
import com.cout970.magneticraft.systems.blocks.BlockBase
import com.cout970.magneticraft.systems.blocks.BlockBuilder
import com.cout970.magneticraft.systems.blocks.IBlockMaker
import com.cout970.magneticraft.systems.blocks.IStatesEnum
import com.cout970.magneticraft.systems.itemblocks.itemBlockListOf
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.block.properties.IProperty
import net.minecraft.block.properties.PropertyEnum
import net.minecraft.block.state.IBlockState
import net.minecraft.item.ItemBlock
import net.minecraft.util.EnumFacing
import net.minecraft.util.IStringSerializable
/**
* Created by cout970 on 2017/06/13.
*/
@RegisterBlocks
object Blocks : IBlockMaker {
val PROPERTY_PART_TYPE: PropertyEnum<PartType> =
PropertyEnum.create("part_type", PartType::class.java)
val PROPERTY_COLUMN_AXIS: PropertyEnum<ColumnOrientation> =
PropertyEnum.create("column_axis", ColumnOrientation::class.java)
lateinit var parts: BlockBase private set
lateinit var column: BlockBase private set
lateinit var pumpjackDrill: BlockBase private set
override fun initBlocks(): List<Pair<Block, ItemBlock>> {
val builder = BlockBuilder().apply {
material = Material.IRON
creativeTab = CreativeTabMg
}
parts = builder.withName("multiblock_parts").copy {
states = PartType.values().toList()
}.build()
column = builder.withName("multiblock_column").copy {
states = ColumnOrientation.values().toList()
alwaysDropDefault = true
onBlockPlaced = { it.defaultValue.withProperty(PROPERTY_COLUMN_AXIS, it.facing.axis.toColumnAxis()) }
}.build()
pumpjackDrill = builder.withName("pumpjack_drill").copy {
onDrop = { emptyList() }
}.build()
return itemBlockListOf(parts, column, pumpjackDrill)
}
enum class PartType(override val stateName: String,
override val isVisible: Boolean) : IStatesEnum, IStringSerializable {
BASE("base", true),
ELECTRIC("electric", true),
GRATE("grate", true),
STRIPED("striped", true),
COPPER_COIL("copper_coil", true),
CORRUGATED_IRON("corrugated_iron", true);
override fun getName() = name.toLowerCase()
override val properties: List<IProperty<*>> get() = listOf(PROPERTY_PART_TYPE)
override fun getBlockState(block: Block): IBlockState {
return block.defaultState.withProperty(PROPERTY_PART_TYPE, this)
}
}
enum class ColumnOrientation(override val stateName: String,
override val isVisible: Boolean) : IStatesEnum, IStringSerializable {
AXIS_Y("axis_y", true),
AXIS_X("axis_x", false),
AXIS_Z("axis_z", false);
override fun getName() = name.toLowerCase()
override val properties: List<IProperty<*>> get() = listOf(PROPERTY_COLUMN_AXIS)
override fun getBlockState(block: Block): IBlockState {
return block.defaultState.withProperty(PROPERTY_COLUMN_AXIS, this)
}
}
}
fun EnumFacing.Axis.toColumnAxis(): Blocks.ColumnOrientation = when (this) {
EnumFacing.Axis.X -> Blocks.ColumnOrientation.AXIS_X
EnumFacing.Axis.Y -> Blocks.ColumnOrientation.AXIS_Y
EnumFacing.Axis.Z -> Blocks.ColumnOrientation.AXIS_Z
}
| gpl-2.0 | 61b183eada0b14d821b42de16844571c | 36.458333 | 113 | 0.694383 | 4.265718 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/packaging/src/main/kotlin/org/gradle/gradlebuild/packaging/ApiMetadataPlugin.kt | 1 | 2034 | /*
* Copyright 2018 the original author or 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.gradle.gradlebuild.packaging
import accessors.sourceSets
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.tasks.WriteProperties
import org.gradle.kotlin.dsl.*
/**
* Generates Gradle API metadata resources.
*
* Include and exclude patterns for the Gradle API.
* Parameter names for the Gradle API.
*/
open class ApiMetadataPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
val extension = extensions.create("apiMetadata", ApiMetadataExtension::class, project)
val apiDeclaration by tasks.registering(WriteProperties::class) {
property("includes", extension.includes.get().joinToString(":"))
property("excludes", extension.excludes.get().joinToString(":"))
outputFile = generatedPropertiesFileFor(apiDeclarationFilename).get().asFile
}
sourceSets {
"main" {
output.dir(generatedDirFor(apiDeclarationFilename), "builtBy" to apiDeclaration)
}
}
}
private
fun Project.generatedDirFor(name: String) =
layout.buildDirectory.dir("generated-api-metadata/$name")
private
fun Project.generatedPropertiesFileFor(name: String) =
layout.buildDirectory.file("generated-api-metadata/$name/$name.properties")
private
val apiDeclarationFilename = "gradle-api-declaration"
}
| apache-2.0 | 38c74232c02201f5ab3523eba5196ef3 | 31.285714 | 96 | 0.708948 | 4.450766 | false | false | false | false |
EZTEQ/rbtv-firetv | app/src/main/java/de/markhaehnel/rbtv/rocketbeanstv/ui/startup/StartupFragment.kt | 1 | 2205 | package de.markhaehnel.rbtv.rocketbeanstv.ui.startup
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import androidx.databinding.DataBindingComponent
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment
import de.markhaehnel.rbtv.rocketbeanstv.R
import de.markhaehnel.rbtv.rocketbeanstv.binding.FragmentDataBindingComponent
import de.markhaehnel.rbtv.rocketbeanstv.databinding.FragmentStartupBinding
import de.markhaehnel.rbtv.rocketbeanstv.di.Injectable
import de.markhaehnel.rbtv.rocketbeanstv.util.autoCleared
import kotlinx.android.synthetic.main.fragment_startup.*
import javax.inject.Inject
class StartupFragment : Fragment(), Injectable {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
// mutable for testing
var binding by autoCleared<FragmentStartupBinding>()
private var dataBindingComponent: DataBindingComponent = FragmentDataBindingComponent(this)
private lateinit var startupViewModel: StartupViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? {
val dataBinding = DataBindingUtil.inflate<FragmentStartupBinding>(
inflater,
R.layout.fragment_startup,
container,
false,
dataBindingComponent
)
binding = dataBinding
return dataBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
startupViewModel = ViewModelProvider(this, viewModelFactory).get(StartupViewModel::class.java)
binding.lifecycleOwner = viewLifecycleOwner
}
override fun onStart() {
super.onStart()
imageLogo.startAnimation(AnimationUtils.loadAnimation(context, R.anim.infinite_rotate_zoom_in_out_anim))
}
override fun onResume() {
super.onResume()
NavHostFragment.findNavController(this).navigate(StartupFragmentDirections.actionStartupFragmentToPlayerFragment())
}
}
| mit | 32105360896c621e4354531fc9c0dbd9 | 37.684211 | 123 | 0.775964 | 5.127907 | false | false | false | false |
ProgramLeague/EmailEverything | src/main/kotlin/ray/eldath/ew/mail/Share.kt | 1 | 2764 | package ray.eldath.ew.mail
import org.simplejavamail.email.Recipient
import ray.eldath.ew.tool.EmailFromDecoder
import ray.eldath.ew.util.ReceivedEmail
import ray.eldath.ew.util.ReceivedEmailSet
import java.io.Closeable
import java.time.ZoneId
import java.util.*
import javax.mail.*
import kotlin.collections.ArrayList
class Share(protocol: String, server: String, port: Int,
private val username: String, private val password: String, ssl: Boolean) : Closeable {
companion object {
private const val DEBUG = false
}
private val prop = Properties()
private lateinit var store: Store
private lateinit var folder: Folder
private lateinit var messages: Array<Message>
init {
prop["mail.store.protocol"] = protocol
prop["mail.$protocol.host"] = server
prop["mail.$protocol.port"] = port
if (ssl) {
// Security.addProvider(com.sun.net.ssl.internal.ssl.Provider())
prop["mail.$protocol.socketFactory.class"] = "javax.net.ssl.SSLSocketFactory"
prop["mail.$protocol.socketFactory.fallback"] = false
prop["mail.$protocol.socketFactory.port"] = port
prop["mail.$protocol.auth"] = true
}
}
fun receive(): ReceivedEmailSet {
val session = Session.getDefaultInstance(prop)
session.debug = DEBUG
store = session.store
store.connect(username, password)
folder = store.getFolder("INBOX") // 收件箱
folder.open(Folder.READ_WRITE)
// 获取总邮件数
val all = folder.messageCount
// 得到收件箱文件夹信息,获取邮件列表
val unread = folder.unreadMessageCount
messages = folder.messages
return ReceivedEmailSet(all, unread, parseMessage(messages))
}
fun delete(mail: ReceivedEmail) = messages[mail.id].setFlag(Flags.Flag.DELETED, true)
private fun parseMessage(messages: Array<Message>): List<ReceivedEmail> {
val result: ArrayList<ReceivedEmail> = ArrayList()
for (index in messages.indices) {
val it = messages[index]
val itFrom: Array<Address> = it.from
val from = ArrayList<Recipient>()
for (thisFrom in itFrom) {
val string = thisFrom.toString().trim().replace(" ", "")
val nameT = string.substringBefore('<')
val name = EmailFromDecoder.decode(nameT)
val addressT = string.removePrefix(nameT)
val address = addressT.substring(1, addressT.length - 1)
// =?utf-8?Q?=E5=9B=BE=E7=81=B5=E7=94=B5=E5=AD=90=E4=B9=A6?= <[email protected]>
// Twitter <[email protected]>
from.add(Recipient(name, address, Message.RecipientType.TO))
}
result.add(ReceivedEmail(index, it.subject, from, it.size,
it.sentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
it.flags.contains(Flags.Flag.SEEN), it.content.toString()))
}
return result
}
override fun close() {
folder.close(true)
store.close()
}
} | gpl-3.0 | 6cc6f91829f7016ac168d813ae35f506 | 30.917647 | 99 | 0.719395 | 3.26747 | false | false | false | false |
google/horologist | media-ui/src/test/java/com/google/android/horologist/media/ui/FigmaVolumeScreenTest.kt | 1 | 2187 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistComposeToolsApi::class, ExperimentalHorologistPaparazziApi::class)
package com.google.android.horologist.media.ui
import androidx.compose.runtime.Composable
import com.google.android.horologist.audio.AudioOutput
import com.google.android.horologist.audio.VolumeState
import com.google.android.horologist.audio.ui.VolumeScreen
import com.google.android.horologist.audio.ui.components.toAudioOutputUi
import com.google.android.horologist.compose.tools.ExperimentalHorologistComposeToolsApi
import com.google.android.horologist.compose.tools.RoundPreview
import com.google.android.horologist.media.ui.uamp.UampTheme
import com.google.android.horologist.paparazzi.ExperimentalHorologistPaparazziApi
import com.google.android.horologist.paparazzi.WearPaparazzi
import org.junit.Rule
import org.junit.Test
class FigmaVolumeScreenTest {
@get:Rule
val paparazzi = WearPaparazzi(
maxPercentDifference = 5.0
)
@Test
fun volumePlayerScreen() {
paparazzi.snapshot {
UampRoundPreview {
VolumeScreen(
volume = { VolumeState(5, 10) },
audioOutputUi = AudioOutput.BluetoothHeadset("1", "Device").toAudioOutputUi(),
increaseVolume = { },
decreaseVolume = { },
onAudioOutputClick = { }
)
}
}
}
}
@Composable
fun UampRoundPreview(content: @Composable () -> Unit) {
RoundPreview {
UampTheme {
content()
}
}
}
| apache-2.0 | 06e70592d50f5d913b671775a018082f | 33.171875 | 100 | 0.706904 | 4.382766 | false | false | false | false |
googlemaps/android-samples | ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/polyline/PolylineDemoActivity.kt | 1 | 8721 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.kotlindemos.polyline
import android.graphics.Color
import android.os.Bundle
import android.widget.RadioGroup
import android.widget.RadioGroup.OnCheckedChangeListener
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.example.kotlindemos.R
import com.google.android.libraries.maps.CameraUpdateFactory
import com.google.android.libraries.maps.GoogleMap
import com.google.android.libraries.maps.GoogleMap.OnPolylineClickListener
import com.google.android.libraries.maps.OnMapReadyCallback
import com.google.android.libraries.maps.SupportMapFragment
import com.google.android.libraries.maps.model.Dash
import com.google.android.libraries.maps.model.Dot
import com.google.android.libraries.maps.model.Gap
import com.google.android.libraries.maps.model.LatLng
import com.google.android.libraries.maps.model.Polyline
import com.google.android.libraries.maps.model.PolylineOptions
import java.util.ArrayList
import java.util.Arrays
/**
* This shows how to apply multiple colors on a polyline.
*/
class PolylineDemoActivity : AppCompatActivity(), OnMapReadyCallback, OnPageChangeListener, OnCheckedChangeListener, OnPolylineClickListener {
private var australiaPolyline: Polyline? = null
private var melbournePolyline: Polyline? = null
private var sydneyPolyline: Polyline? = null
private var worldPolyline: Polyline? = null
private var selectedPolyline: Polyline? = null
private lateinit var pagerAdapter: PolylineControlFragmentPagerAdapter
private val spanResetPolylines = mutableSetOf<Polyline>()
private lateinit var polylineRadio: RadioGroup
private lateinit var pager: ViewPager // TODO use ViewPager2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.multicolor_polyline_demo)
pagerAdapter = PolylineControlFragmentPagerAdapter(
supportFragmentManager,
/* isLiteMode= */false
)
pager = findViewById(R.id.pager)
pager.adapter = pagerAdapter
// onPageSelected(0) isn't invoked once views are ready, so post a Runnable to
// refreshControlPanel() for the first time instead...
pager.post { refreshControlPanel() }
polylineRadio = findViewById(R.id.polyline_radio)
val mapFragment: SupportMapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onMapReady(map: GoogleMap) {
// For accessibility mode. Ideally this string would be localised.
map.setContentDescription("Google Map with polylines.")
// Non-loop polyline that goes past Australian cities. Added before sydneyPolyline and would
// normally be underneath, but increase Z-Index so that this line is on top.
australiaPolyline = map.addPolyline(
PolylineOptions()
.add(PERTH, ADELAIDE, SYDNEY, MELBOURNE)
.pattern(Arrays.asList(Dot(), Gap(20.0f)))
.color(Color.MAGENTA)
.zIndex(1F))
// Geodesic polyline that goes around the world.
worldPolyline = map.addPolyline(
PolylineOptions()
.add(LONDON, AUCKLAND, LOS_ANGELES, NEW_YORK, LONDON)
.width(5F)
.color(Color.BLUE)
.geodesic(true)
.clickable(true))
// Loop polyline centered at Sydney.
val radius = 4
sydneyPolyline = map.addPolyline(
PolylineOptions()
.add(LatLng(SYDNEY.latitude + radius, SYDNEY.longitude + radius))
.add(LatLng(SYDNEY.latitude + radius, SYDNEY.longitude - radius))
.add(LatLng(SYDNEY.latitude - radius, SYDNEY.longitude - radius))
.add(LatLng(SYDNEY.latitude - radius, SYDNEY.longitude))
.add(LatLng(SYDNEY.latitude - radius, SYDNEY.longitude + radius))
.add(LatLng(SYDNEY.latitude + radius, SYDNEY.longitude + radius))
.pattern(listOf(Dash(45.0f), Gap(10.0f)))
.color(Color.RED)
.width(5F)
.clickable(true))
// Create Melbourne polyline to show layering of polylines with same Z-Index. This is added
// second so it will be layered on top of the Sydney polyline (both have Z-Index == 0).
melbournePolyline = map.addPolyline(
PolylineOptions()
.add(LatLng(MELBOURNE.latitude + radius, MELBOURNE.longitude + radius))
.add(LatLng(MELBOURNE.latitude + radius, MELBOURNE.longitude - radius))
.add(LatLng(MELBOURNE.latitude - radius, MELBOURNE.longitude - radius))
.add(LatLng(MELBOURNE.latitude - radius, MELBOURNE.longitude))
.add(LatLng(MELBOURNE.latitude - radius, MELBOURNE.longitude + radius))
.add(LatLng(MELBOURNE.latitude + radius, MELBOURNE.longitude + radius))
.color(Color.GREEN)
.width(5F)
.clickable(true))
map.moveCamera(CameraUpdateFactory.newLatLng(SYDNEY))
selectedPolyline = australiaPolyline
polylineRadio.check(R.id.polyline_radio_australia)
pager.addOnPageChangeListener(this)
polylineRadio.setOnCheckedChangeListener(this)
map.setOnPolylineClickListener(this)
}
override fun onPolylineClick(polyline: Polyline) {
// Flip the values of the r, g and b components of the polyline's color.
val strokeColor: Int = polyline.color xor 0x00ffffff
polyline.color = strokeColor
polyline.setSpans(ArrayList())
spanResetPolylines.add(polyline)
refreshControlPanel()
}
override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
when (checkedId) {
R.id.polyline_radio_australia -> {
selectedPolyline = australiaPolyline
}
R.id.polyline_radio_sydney -> {
selectedPolyline = sydneyPolyline
}
R.id.polyline_radio_melbourne -> {
selectedPolyline = melbournePolyline
}
R.id.polyline_radio_world -> {
selectedPolyline = worldPolyline
}
}
refreshControlPanel()
}
override fun onPageSelected(position: Int) {
refreshControlPanel()
}
private fun refreshControlPanel() {
val fragment: PolylineControlFragment? = pagerAdapter.getFragmentAtPosition(pager.getCurrentItem())
if (fragment != null) {
if (fragment is PolylineSpansControlFragment
&& spanResetPolylines.contains(selectedPolyline)) {
val spansControlFragment: PolylineSpansControlFragment = fragment as PolylineSpansControlFragment
spansControlFragment.resetSpanState(selectedPolyline)
spanResetPolylines.remove(selectedPolyline)
}
fragment.polyline = selectedPolyline
}
}
override fun onPageScrollStateChanged(state: Int) {
// Don't do anything here.
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
// Don't do anything here.
}
override fun onPointerCaptureChanged(hasCapture: Boolean) {
}
companion object {
val TAG: String = PolylineDemoActivity::class.java.getSimpleName()
private val MELBOURNE: LatLng = LatLng(-37.81319, 144.96298)
private val SYDNEY: LatLng = LatLng(-33.87365, 151.20689)
private val ADELAIDE: LatLng = LatLng(-34.92873, 138.59995)
private val PERTH: LatLng = LatLng(-31.95285, 115.85734)
private val LONDON: LatLng = LatLng(51.471547, -0.460052)
private val LOS_ANGELES: LatLng = LatLng(33.936524, -118.377686)
private val NEW_YORK: LatLng = LatLng(40.641051, -73.777485)
private val AUCKLAND: LatLng = LatLng(-37.006254, 174.783018)
}
} | apache-2.0 | 1964a72ee6748b9b0678661aa7032c3c | 43.274112 | 142 | 0.67584 | 4.580357 | false | false | false | false |
mrebollob/LoteriadeNavidad | androidApp/src/main/java/com/mrebollob/loteria/android/presentation/home/ui/CountdownSectionView.kt | 1 | 2369 | package com.mrebollob.loteria.android.presentation.home.ui
import android.content.res.Configuration
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mrebollob.loteria.android.R
import com.mrebollob.loteria.android.presentation.platform.extension.getStringDate
import com.mrebollob.loteria.android.presentation.platform.ui.theme.Grey4
import com.mrebollob.loteria.android.presentation.platform.ui.theme.LotteryTheme
import java.util.Date
@Composable
fun CountdownSectionView(
modifier: Modifier = Modifier,
today: Date,
daysToLotteryDraw: Int
) {
val resources = LocalContext.current.resources
Column(
modifier = modifier
) {
Text(
color = Grey4,
text = today.getStringDate(),
style = MaterialTheme.typography.body2
)
Text(
text = when {
daysToLotteryDraw == 0 -> stringResource(R.string.lottery_countdown_today)
daysToLotteryDraw < 0 -> stringResource(R.string.lottery_countdown_end)
else -> resources.getQuantityString(
R.plurals.lottery_countdown_days,
daysToLotteryDraw,
daysToLotteryDraw
)
},
style = MaterialTheme.typography.h5,
color = MaterialTheme.colors.onBackground
)
}
}
@Preview("Countdown section")
@Preview("Countdown section (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewCountdownSectionView() {
LotteryTheme {
Surface(
modifier = Modifier.fillMaxSize()
) {
Column(
modifier = Modifier.padding(16.dp)
) {
CountdownSectionView(
today = Date(),
daysToLotteryDraw = 10
)
}
}
}
}
| apache-2.0 | fa8b75c2d58fd2edbd2ad2b02d4d0940 | 31.452055 | 90 | 0.663993 | 4.700397 | false | false | false | false |
angryziber/picasa-gallery | src/views/albumPart.kt | 1 | 719 | package views
import photos.Album
import photos.AlbumPart
import web.RequestProps
// language=HTML
fun albumPart(albumPart: AlbumPart, album: Album, req: RequestProps) = """
<div class="load-time hidden">${albumPart.photos.size} loaded at ${albumPart.loadedAt}</div>
${albumPart.photos.each {"""
<a id="$id" class="photo" href="${album.url}/$id" data-url="${baseUrl?.url}"
${timestamp / """data-time="$dateTime""""}
${geo / """data-coords="${geo?.lat}:${geo?.lon}""""}
${exif / """data-exif="$exif""""}>
<img ${req.bot / """src="$thumbUrl""""} ${description / """alt="$description""""}>
</a>
"""}}
<script>
viewer.addPhotos()
thumbsView.loadMore('${+albumPart.nextPageToken}')
</script>
"""
| gpl-3.0 | 4d9db5683254a1e96623268087c41106 | 28.958333 | 92 | 0.62726 | 3.313364 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/binary/KSAnnotationDescriptorImpl.kt | 1 | 15613 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.symbol.impl.binary
import com.google.devtools.ksp.ExceptionMessage
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.getClassDeclarationByName
import com.google.devtools.ksp.processing.impl.ResolverImpl
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.impl.findPsi
import com.google.devtools.ksp.symbol.impl.java.KSAnnotationJavaImpl
import com.google.devtools.ksp.symbol.impl.kotlin.KSErrorType
import com.google.devtools.ksp.symbol.impl.kotlin.KSNameImpl
import com.google.devtools.ksp.symbol.impl.kotlin.KSValueArgumentLiteImpl
import com.google.devtools.ksp.symbol.impl.kotlin.getKSTypeCached
import com.google.devtools.ksp.symbol.impl.synthetic.KSTypeReferenceSyntheticImpl
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiAnnotationMethod
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.NotFoundClasses
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.load.java.components.JavaAnnotationDescriptor
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaAnnotationDescriptor
import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.*
import org.jetbrains.kotlin.load.java.structure.impl.VirtualFileBoundJavaClass
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryClassSignatureParser
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryJavaAnnotationVisitor
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryJavaMethod
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.ClassifierResolutionContext
import org.jetbrains.kotlin.load.kotlin.VirtualFileKotlinClass
import org.jetbrains.kotlin.load.kotlin.getContainingKotlinJvmBinaryClass
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue
import org.jetbrains.kotlin.resolve.constants.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes.API_VERSION
class KSAnnotationDescriptorImpl private constructor(
val descriptor: AnnotationDescriptor,
override val parent: KSNode?
) : KSAnnotation {
companion object : KSObjectCache<Pair<AnnotationDescriptor, KSNode?>, KSAnnotationDescriptorImpl>() {
fun getCached(descriptor: AnnotationDescriptor, parent: KSNode?) = cache.getOrPut(Pair(descriptor, parent)) {
KSAnnotationDescriptorImpl(descriptor, parent)
}
}
override val origin =
when (descriptor) {
is JavaAnnotationDescriptor, is LazyJavaAnnotationDescriptor -> Origin.JAVA_LIB
else -> Origin.KOTLIN_LIB
}
override val location: Location = NonExistLocation
override val annotationType: KSTypeReference by lazy {
KSTypeReferenceDescriptorImpl.getCached(descriptor.type, origin, this)
}
override val arguments: List<KSValueArgument> by lazy {
descriptor.createKSValueArguments(this)
}
override val defaultArguments: List<KSValueArgument> by lazy {
descriptor.getDefaultArguments(this)
}
override val shortName: KSName by lazy {
KSNameImpl.getCached(descriptor.fqName!!.shortName().asString())
}
override val useSiteTarget: AnnotationUseSiteTarget? = null
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitAnnotation(this, data)
}
override fun toString(): String {
return "@${shortName.asString()}"
}
}
private fun ClassId.findKSClassDeclaration(): KSClassDeclaration? {
val ksName = KSNameImpl.getCached(this.asSingleFqName().asString().replace("$", "."))
return ResolverImpl.instance!!.getClassDeclarationByName(ksName)
}
private fun ClassId.findKSType(): KSType? = findKSClassDeclaration()?.asStarProjectedType()
private fun <T> ConstantValue<T>.toValue(parent: KSNode): Any? = when (this) {
is AnnotationValue -> KSAnnotationDescriptorImpl.getCached(value, parent)
is ArrayValue -> value.map { it.toValue(parent) }
is EnumValue -> value.first.findKSClassDeclaration()?.declarations?.find {
it is KSClassDeclaration && it.classKind == ClassKind.ENUM_ENTRY &&
it.simpleName.asString() == value.second.asString()
}?.let { (it as KSClassDeclaration).asStarProjectedType() }
is KClassValue -> when (val classValue = value) {
is KClassValue.Value.NormalClass -> if (classValue.arrayDimensions > 0) {
classValue.value.classId.findKSType()?.let { componentType ->
var resultingType = componentType
for (i in 1..classValue.arrayDimensions) {
resultingType = ResolverImpl.instance!!.builtIns.arrayType.replace(
listOf(
ResolverImpl.instance!!.getTypeArgument(
KSTypeReferenceSyntheticImpl.getCached(resultingType, null), Variance.INVARIANT
)
)
)
}
resultingType
}
} else classValue.classId.findKSType()
is KClassValue.Value.LocalClass -> getKSTypeCached(classValue.type)
}
is ErrorValue, is NullValue -> null
else -> value
}
fun AnnotationDescriptor.createKSValueArguments(ownerAnnotation: KSAnnotation): List<KSValueArgument> {
val presentValueArguments = allValueArguments.map { (name, constantValue) ->
KSValueArgumentLiteImpl.getCached(
KSNameImpl.getCached(name.asString()),
constantValue.toValue(ownerAnnotation),
ownerAnnotation
)
}
val presentValueArgumentNames = presentValueArguments.map { it.name.asString() }
val argumentsFromDefault = this.type.getDefaultConstructorArguments(presentValueArgumentNames, ownerAnnotation)
return presentValueArguments.plus(argumentsFromDefault)
}
internal fun AnnotationDescriptor.getDefaultArguments(ownerAnnotation: KSAnnotation): List<KSValueArgument> {
return this.type.getDefaultConstructorArguments(emptyList(), ownerAnnotation)
}
internal fun TypeConstructor.toDeclarationDescriptor(): ClassDescriptor? {
if (this.declarationDescriptor !is NotFoundClasses.MockClassDescriptor) {
return this.declarationDescriptor as? ClassDescriptor
}
val fqName = (this.declarationDescriptor as? ClassDescriptor)?.fqNameSafe ?: return null
val shortNames = fqName.shortName().asString().split("$")
var parent = ResolverImpl.instance!!
.getClassDeclarationByName("${fqName.parent().asString()}.${shortNames.first()}")
for (i in 1 until shortNames.size) {
if (parent == null) {
return null
}
parent = parent.declarations
.filterIsInstance<KSClassDeclaration>()
.singleOrNull { it.simpleName.asString() == shortNames[i] }
}
return parent?.let { ResolverImpl.instance!!.resolveClassDeclaration(it) }
}
internal fun KotlinType.getDefaultConstructorArguments(
excludeNames: List<String>,
ownerAnnotation: KSAnnotation
): List<KSValueArgument> {
return this.constructor.toDeclarationDescriptor()?.constructors?.single()
?.getAbsentDefaultArguments(excludeNames, ownerAnnotation) ?: emptyList()
}
fun ClassConstructorDescriptor.getAbsentDefaultArguments(
excludeNames: List<String>,
ownerAnnotation: KSAnnotation
): List<KSValueArgument> {
return this.valueParameters
.filterNot { param -> excludeNames.contains(param.name.asString()) || !param.hasDefaultValue() }
.map { param ->
KSValueArgumentLiteImpl.getCached(
KSNameImpl.getCached(param.name.asString()),
param.getDefaultValue(ownerAnnotation),
ownerAnnotation,
Origin.SYNTHETIC
)
}
}
fun ValueParameterDescriptor.getDefaultValue(ownerAnnotation: KSAnnotation): Any? {
// Copied from kotlin compiler
// TODO: expose in upstream
fun convertTypeToKClassValue(javaType: JavaType): KClassValue? {
var type = javaType
var arrayDimensions = 0
while (type is JavaArrayType) {
type = type.componentType
arrayDimensions++
}
return when (type) {
is JavaPrimitiveType -> {
val primitiveType = type.type
// void.class is not representable in Kotlin, we approximate it by Unit::class
?: return KClassValue(ClassId.topLevel(StandardNames.FqNames.unit.toSafe()), 0)
if (arrayDimensions > 0) {
KClassValue(ClassId.topLevel(primitiveType.arrayTypeFqName), arrayDimensions - 1)
} else {
KClassValue(ClassId.topLevel(primitiveType.typeFqName), arrayDimensions)
}
}
is JavaClassifierType -> {
val fqName = FqName(type.classifierQualifiedName)
// TODO: support nested classes somehow
val classId = JavaToKotlinClassMap.mapJavaToKotlin(fqName) ?: ClassId.topLevel(fqName)
KClassValue(classId, arrayDimensions)
}
else -> null
}
}
// Copied from kotlin compiler
// TODO: expose in upstream
fun JavaAnnotationArgument.convert(expectedType: KotlinType): ConstantValue<*>? {
return when (this) {
is JavaLiteralAnnotationArgument -> value?.let {
when (value) {
// Note: `value` expression may be of class that does not match field type in some cases
// tested for Int, left other checks just in case
is Byte, is Short, is Int, is Long -> {
ConstantValueFactory.createIntegerConstantValue((value as Number).toLong(), expectedType, false)
}
else -> {
ConstantValueFactory.createConstantValue(value)
}
}
}
is JavaEnumValueAnnotationArgument -> {
enumClassId?.let { enumClassId ->
entryName?.let { entryName ->
EnumValue(enumClassId, entryName)
}
}
}
is JavaArrayAnnotationArgument -> {
val elementType = expectedType.builtIns.getArrayElementType(expectedType)
ConstantValueFactory.createArrayValue(
getElements().mapNotNull { it.convert(elementType) },
expectedType
)
}
is JavaAnnotationAsAnnotationArgument -> {
AnnotationValue(
LazyJavaAnnotationDescriptor(ResolverImpl.instance!!.lazyJavaResolverContext, this.getAnnotation())
)
}
is JavaClassObjectAnnotationArgument -> {
convertTypeToKClassValue(getReferencedType())
}
else -> null
}
}
val psi = this.findPsi()
return when (psi) {
null -> {
val file = if (this.source is JavaSourceElement) {
(
((this.source as JavaSourceElement).javaElement as? BinaryJavaMethod)
?.containingClass as? VirtualFileBoundJavaClass
)?.virtualFile?.contentsToByteArray()
} else {
(this.containingDeclaration.getContainingKotlinJvmBinaryClass() as? VirtualFileKotlinClass)
?.file?.contentsToByteArray()
}
if (file == null) {
null
} else {
var defaultValue: JavaAnnotationArgument? = null
ClassReader(file).accept(
object : ClassVisitor(API_VERSION) {
override fun visitMethod(
access: Int,
name: String?,
desc: String?,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor {
return if (name == [email protected]()) {
object : MethodVisitor(API_VERSION) {
override fun visitAnnotationDefault(): AnnotationVisitor =
BinaryJavaAnnotationVisitor(
ClassifierResolutionContext { null },
BinaryClassSignatureParser()
) {
defaultValue = it
}
}
} else {
object : MethodVisitor(API_VERSION) {}
}
}
},
ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES
)
if (!this.type.isError) {
defaultValue?.convert(this.type)?.toValue(ownerAnnotation)
} else {
KSErrorType
}
}
}
is KtParameter -> if (!this.type.isError) {
ResolverImpl.instance!!.evaluateConstant(psi.defaultValue, this.type)?.toValue(ownerAnnotation)
} else {
KSErrorType
}
is PsiAnnotationMethod -> {
when (psi.defaultValue) {
is PsiAnnotation -> KSAnnotationJavaImpl.getCached(psi.defaultValue as PsiAnnotation)
else -> JavaPsiFacade.getInstance(psi.project).constantEvaluationHelper
.computeConstantExpression((psi).defaultValue)
}
}
else -> throw IllegalStateException("Unexpected psi ${psi.javaClass}, $ExceptionMessage")
}
}
| apache-2.0 | 77da880c21d237a9ff325f3b3c2df97b | 43.994236 | 120 | 0.647986 | 5.283587 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/services/NotificationService.kt | 1 | 4961 | /*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.services
import android.app.job.JobParameters
import androidx.core.app.NotificationManagerCompat
import ca.allanwang.kau.utils.string
import com.pitchedapps.frost.BuildConfig
import com.pitchedapps.frost.R
import com.pitchedapps.frost.db.CookieDao
import com.pitchedapps.frost.db.CookieEntity
import com.pitchedapps.frost.db.NotificationDao
import com.pitchedapps.frost.db.selectAll
import com.pitchedapps.frost.prefs.Prefs
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.frostEvent
import com.pitchedapps.frost.widgets.NotificationWidget
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
/**
* Created by Allan Wang on 2017-06-14.
*
* Service to manage notifications Will periodically check through all accounts in the db and send
* notifications when appropriate
*
* All fetching is done through parsers
*/
@AndroidEntryPoint
class NotificationService : BaseJobService() {
@Inject lateinit var prefs: Prefs
@Inject lateinit var notifDao: NotificationDao
@Inject lateinit var cookieDao: CookieDao
override fun onStopJob(params: JobParameters?): Boolean {
super.onStopJob(params)
prepareFinish(true)
return false
}
private var preparedFinish = false
private fun prepareFinish(abrupt: Boolean) {
if (preparedFinish) return
preparedFinish = true
val time = System.currentTimeMillis() - startTime
L.i {
"Notification service has ${if (abrupt) "finished abruptly" else "finished"} in $time ms"
}
frostEvent(
"NotificationTime",
"Type" to (if (abrupt) "Service force stop" else "Service"),
"IM Included" to prefs.notificationsInstantMessages,
"Duration" to time
)
}
override fun onStartJob(params: JobParameters?): Boolean {
super.onStartJob(params)
L.i { "Fetching notifications" }
launch {
try {
sendNotifications(params)
} finally {
if (!isActive) prepareFinish(false)
jobFinished(params, false)
}
}
return true
}
private suspend fun sendNotifications(params: JobParameters?): Unit =
withContext(Dispatchers.Default) {
val currentId = prefs.userId
val cookies = cookieDao.selectAll()
yield()
val jobId = params?.extras?.getInt(NOTIFICATION_PARAM_ID, -1) ?: -1
var notifCount = 0
for (cookie in cookies) {
yield()
val current = cookie.id == currentId
if (prefs.notificationsGeneral && (current || prefs.notificationAllAccounts))
notifCount += fetch(jobId, NotificationType.GENERAL, cookie)
if (prefs.notificationsInstantMessages && (current || prefs.notificationsImAllAccounts))
notifCount += fetch(jobId, NotificationType.MESSAGE, cookie)
}
L.i { "Sent $notifCount notifications" }
if (notifCount == 0 && jobId == NOTIFICATION_JOB_NOW)
generalNotification(665, R.string.no_new_notifications, BuildConfig.DEBUG)
if (notifCount > 0) {
NotificationWidget.forceUpdate(this@NotificationService)
}
}
/**
* Implemented fetch to also notify when an error occurs Also normalized the output to return the
* number of notifications received
*/
private suspend fun fetch(jobId: Int, type: NotificationType, cookie: CookieEntity): Int {
val count = type.fetch(this, cookie, prefs, notifDao)
if (count < 0) {
if (jobId == NOTIFICATION_JOB_NOW)
generalNotification(666, R.string.error_notification, BuildConfig.DEBUG)
return 0
}
return count
}
private fun logNotif(text: String): NotificationContent? {
L.eThrow("NotificationService: $text")
return null
}
private fun generalNotification(id: Int, textRes: Int, withDefaults: Boolean) {
val notifBuilder =
frostNotification(NOTIF_CHANNEL_GENERAL)
.setFrostAlert(this, withDefaults, prefs.notificationRingtone, prefs)
.setContentTitle(string(R.string.frost_name))
.setContentText(string(textRes))
NotificationManagerCompat.from(this).notify(id, notifBuilder.build())
}
}
| gpl-3.0 | a8aba88b7e8ba3259820922bbe05a57a | 33.213793 | 99 | 0.72183 | 4.313913 | false | false | false | false |
jpmoreto/play-with-robots | android/app/src/main/java/jpm/android/ui/MainActivity.kt | 1 | 11349 | package jpm.android.ui
import android.content.Context
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.*
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import jpm.android.App
import jpm.messages.ChangeGraphVisibility
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), OnItemSelectedListener {
private class SectionsPagerAdapter(fm: FragmentManager, private val context: Context) : FragmentPagerAdapter(fm) {
private val fragments = arrayOf(ChartFragment(), LogsFragment(), ControlFragment(), ConfigureFragment(), MapFragment(), RobotFragment())
override fun getItem(position: Int): Fragment = fragments[position]
override fun getPageTitle(position: Int): CharSequence = fragments[position].getName(context)
override fun getCount(): Int = fragments.size // number of tabs.
}
private var sensors: Map<String,Pair<Int,Int>>? = null
private var optionsMenu: Menu? = null
private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
private fun initSensors() {
sensors = mapOf(
getString(jpm.android.R.string.sel_chart_accelerometer_x) to Pair(0, jpm.android.R.id.sel_chart_accelerometer_x),
getString(jpm.android.R.string.sel_chart_accelerometer_y) to Pair(1, jpm.android.R.id.sel_chart_accelerometer_y),
getString(jpm.android.R.string.sel_chart_accelerometer_z) to Pair(2, jpm.android.R.id.sel_chart_accelerometer_z),
getString(jpm.android.R.string.sel_chart_gyroscope_x) to Pair(3, jpm.android.R.id.sel_chart_gyroscope_x),
getString(jpm.android.R.string.sel_chart_gyroscope_y) to Pair(4, jpm.android.R.id.sel_chart_gyroscope_y),
getString(jpm.android.R.string.sel_chart_gyroscope_z) to Pair(5, jpm.android.R.id.sel_chart_gyroscope_z),
getString(jpm.android.R.string.sel_chart_compass_x) to Pair(6, jpm.android.R.id.sel_chart_compass_x),
getString(jpm.android.R.string.sel_chart_compass_y) to Pair(7, jpm.android.R.id.sel_chart_compass_y),
getString(jpm.android.R.string.sel_chart_compass_z) to Pair(8, jpm.android.R.id.sel_chart_compass_z),
getString(jpm.android.R.string.sel_chart_motor_front_left) to Pair(9, jpm.android.R.id.sel_chart_motor_front_left),
getString(jpm.android.R.string.sel_chart_motor_front_right) to Pair(10, jpm.android.R.id.sel_chart_motor_front_right),
getString(jpm.android.R.string.sel_chart_motor_back_left) to Pair(11, jpm.android.R.id.sel_chart_motor_back_left),
getString(jpm.android.R.string.sel_chart_motor_back_right) to Pair(12, jpm.android.R.id.sel_chart_motor_back_right)
)
}
override fun onCreate(savedInstanceState: Bundle?) {
//requestWindowFeature(Window.FEATURE_NO_TITLE)
super.onCreate(savedInstanceState)
App.readConfiguration(getPreferences(Context.MODE_PRIVATE))
setUiVisibility()
setContentView(jpm.android.R.layout.activity_main)
initSensors()
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager, this)
this.container.offscreenPageLimit = mSectionsPagerAdapter!!.count
this.container.adapter = mSectionsPagerAdapter
// disable lateral scrolling
this.container.setOnTouchListener { _, _ -> true }
setSupportActionBar(this.toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
spinner.adapter = ArrayAdapter<CharSequence>(
toolbar.context,
android.R.layout.simple_list_item_1,
Array(mSectionsPagerAdapter!!.count, { i -> mSectionsPagerAdapter!!.getPageTitle(i)}))
spinner.onItemSelectedListener = this
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
App.init()
App.getBroker() // init Bluetooth connection
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
setUiVisibility()
}
}
private fun setUiVisibility() {
window.decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_FULLSCREEN or
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
}
override fun onDestroy() {
super.onDestroy()
App.writeConfiguration(getPreferences(Context.MODE_PRIVATE))
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
optionsMenu = menu
menuInflater.inflate(jpm.android.R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
fun activateGraph(index: Int, activate: Boolean): Boolean {
Log.i("MainActivity","activateGraph($index,$activate)")
App.getBroker().send(ChangeGraphVisibility(System.currentTimeMillis(),index,activate))
return true
}
fun activateGraph(index: Int): Boolean {
item.isChecked = !item.isChecked
return activateGraph(index,item.isChecked)
}
fun activateGraph(title: String, menu: SubMenu?, activate: Boolean) {
sensors!!.forEach { e ->
val menuItem = menu!!.findItem(e.value.second)
Log.i("MainActivity","activateGraph($title,${menu.size()},$activate,${e.value.second}) menuItem = $menuItem")
if(menuItem != null) {
menuItem.isChecked = activate
activateGraph(sensors!![menuItem.title.toString()]!!.first,activate)
}
}
}
when (item.itemId) {
jpm.android.R.id.action_settings -> {
Snackbar.make(findViewById(jpm.android.R.id.toolbar), "Menu item ${item.title} called", Snackbar.LENGTH_LONG).setAction("Action", null).show()
return true
}
jpm.android.R.id.action_quit -> {
Snackbar.make(findViewById(jpm.android.R.id.toolbar), "Menu item ${item.title} called", Snackbar.LENGTH_LONG).setAction("Action", null).show()
this.finishAffinity()
return true
}
jpm.android.R.id.action_stop -> {
Snackbar.make(findViewById(jpm.android.R.id.toolbar), "Menu item ${item.title} called", Snackbar.LENGTH_LONG).setAction("Action", null).show()
return true
}
jpm.android.R.id.action_select_all -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(2).title.toString(),group.getItem(2).subMenu,true)
activateGraph(group.getItem(3).title.toString(),group.getItem(3).subMenu,true)
activateGraph(group.getItem(4).title.toString(),group.getItem(4).subMenu,true)
activateGraph(group.getItem(5).title.toString(),group.getItem(5).subMenu,true)
return true
}
jpm.android.R.id.action_unselect_all -> {
Log.i("MainActivity","action_unselect_all(${optionsMenu!!.getItem(2).title})")
val group = optionsMenu!!.getItem(2).subMenu
Log.i("MainActivity","action_unselect_all getItem(2) = ${group!!.getItem(2).title}")
activateGraph(group.getItem(2).title.toString(),group.getItem(2).subMenu,false)
activateGraph(group.getItem(3).title.toString(),group.getItem(3).subMenu,false)
activateGraph(group.getItem(4).title.toString(),group.getItem(4).subMenu,false)
activateGraph(group.getItem(5).title.toString(),group.getItem(5).subMenu,false)
return true
}
jpm.android.R.id.action_select_all_motor_graph -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(2).title.toString(),group.getItem(2).subMenu,true)
return true
}
jpm.android.R.id.action_unselect_all_motor_graph -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(2).title.toString(),group.getItem(2).subMenu,false)
return true
}
jpm.android.R.id.action_select_all_accelerometer_graph -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(3).title.toString(),group.getItem(3).subMenu,true)
return true
}
jpm.android.R.id.action_unselect_all_accelerometer_graph -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(3).title.toString(),group.getItem(3).subMenu,false)
return true
}
jpm.android.R.id.action_select_all_gyroscope_graph -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(4).title.toString(),group.getItem(4).subMenu,true)
return true
}
jpm.android.R.id.action_unselect_all_gyroscope_graph -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(4).title.toString(),group.getItem(4).subMenu,false)
return true
}
jpm.android.R.id.action_select_all_compass_graph -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(5).title.toString(),group.getItem(5).subMenu,true)
return true
}
jpm.android.R.id.action_unselect_all_compass_graph -> {
val group = optionsMenu!!.getItem(2).subMenu
activateGraph(group!!.getItem(5).title.toString(),group.getItem(5).subMenu,false)
return true
}
else -> {
if(sensors!!.containsKey(item.title.toString())) {
return activateGraph(sensors!![item.title.toString()]!!.first)
}
Log.i("MainActivity","onOptionsItemSelected(${item.title},${item.isChecked})")
return super.onOptionsItemSelected(item)
}
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) =
this.container.setCurrentItem(position,false)
}
| mit | 16111e86a33a23e24b5ac08466805eec | 48.776316 | 158 | 0.617147 | 4.281026 | false | false | false | false |
VisualDig/visualdig-kotlin | dig/src/main/io/visualdig/actions/ExecutedQuery.kt | 1 | 2312 | package io.visualdig.actions
import io.visualdig.element.DigElementQuery
import io.visualdig.element.DigSpacialQuery
import io.visualdig.element.DigTextQuery
import io.visualdig.exceptions.DigFatalException
data class ExecutedQuery (val queryType: String,
val textQuery: DigTextQuery?,
val spacialQuery: DigSpacialQuery?) {
fun queryDescription() : String {
when(queryType) {
DigTextQuery.queryType() -> {
if(textQuery != null) {
val text = textQuery.text
return "'$text' element"
}
throw DigFatalException("For \"$queryType\" the object expected textQuery field was null")
}
DigSpacialQuery.queryType() -> {
if(spacialQuery != null) {
val elementType = spacialQuery.elementType.description
return "spacially found $elementType"
}
throw DigFatalException("For \"$queryType\" the object expected spacialSearch field was null")
}
else -> {
throw DigFatalException("Unable to resolve action type \"$queryType\" while generating query description")
}
}
}
companion object {
fun createExecutedQuery(query : DigElementQuery) : ExecutedQuery {
val actionType = query.action().action.actionType
when(actionType) {
FindTextAction.actionType() -> {
val textQuery = query as DigTextQuery
return ExecutedQuery(queryType = DigTextQuery.queryType(),
textQuery = textQuery,
spacialQuery = null)
}
SpacialSearchAction.actionType() -> {
val spacialQuery = query as DigSpacialQuery
return ExecutedQuery(queryType = DigSpacialQuery.queryType(),
textQuery = null,
spacialQuery = spacialQuery)
}
else -> {
throw DigFatalException("Unable to resolve action type \"$actionType\" while creating executed query")
}
}
}
}
}
| mit | 4127b5c1872ccf613142c4f6110c6824 | 38.862069 | 122 | 0.541522 | 5.598063 | false | false | false | false |
alashow/music-android | modules/data/src/main/java/tm/alashow/data/Interactor.kt | 1 | 3417 | /*
* Copyright (C) 2018, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.data
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withTimeout
import tm.alashow.domain.models.InvokeError
import tm.alashow.domain.models.InvokeStarted
import tm.alashow.domain.models.InvokeStatus
import tm.alashow.domain.models.InvokeSuccess
abstract class Interactor<in P> {
operator fun invoke(params: P, timeoutMs: Long = defaultTimeoutMs): Flow<InvokeStatus> {
return flow {
withTimeout(timeoutMs) {
emit(InvokeStarted)
doWork(params)
emit(InvokeSuccess)
}
}.catch { t ->
emit(InvokeError(t))
}
}
suspend fun executeSync(params: P) = doWork(params)
protected abstract suspend fun doWork(params: P)
companion object {
private val defaultTimeoutMs = TimeUnit.MINUTES.toMillis(5)
}
}
abstract class ResultInteractor<in P, R> {
operator fun invoke(params: P): Flow<R> = flow {
emit(doWork(params))
}
suspend fun executeSync(params: P): R = doWork(params)
protected abstract suspend fun doWork(params: P): R
}
abstract class PagingInteractor<P : PagingInteractor.Parameters<T>, T : Any> : SubjectInteractor<P, PagingData<T>>() {
interface Parameters<T : Any> {
val pagingConfig: PagingConfig
}
companion object {
val DEFAULT_PAGING_CONFIG = PagingConfig(
pageSize = 100,
initialLoadSize = 100,
prefetchDistance = 5,
enablePlaceholders = true
)
}
}
abstract class SuspendingWorkInteractor<P : Any, T> : SubjectInteractor<P, T>() {
override fun createObservable(params: P): Flow<T> = flow {
emit(doWork(params))
}
abstract suspend fun doWork(params: P): T
}
abstract class SubjectInteractor<P : Any, T> {
// Ideally this would be buffer = 0, since we use flatMapLatest below, BUT invoke is not
// suspending. This means that we can't suspend while flatMapLatest cancels any
// existing flows. The buffer of 1 means that we can use tryEmit() and buffer the value
// instead, resulting in mostly the same result.
private val paramState = MutableSharedFlow<P>(
replay = 1,
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
operator fun invoke(params: P) {
paramState.tryEmit(params)
}
protected abstract fun createObservable(params: P): Flow<T>
val flow: Flow<T> = paramState
.distinctUntilChanged()
.flatMapLatest { createObservable(it) }
.distinctUntilChanged()
private val errorState = MutableSharedFlow<Throwable>(
replay = 1,
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
protected fun onError(error: Throwable) {
errorState.tryEmit(error)
}
fun errors(): Flow<Throwable> = errorState.asSharedFlow()
}
| apache-2.0 | 10299f8d3eb536878a9c244204b0ced9 | 29.508929 | 118 | 0.685982 | 4.437662 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/impl/BlockQuoteMarkerBlock.kt | 1 | 1824 | package org.intellij.markdown.parser.markerblocks.impl
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.lexer.Compat.assert
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.constraints.applyToNextLineAndAddModifiers
import org.intellij.markdown.parser.constraints.extendsPrev
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl
class BlockQuoteMarkerBlock(myConstraints: MarkdownConstraints, marker: ProductionHolder.Marker) : MarkerBlockImpl(myConstraints, marker) {
override fun allowsSubBlocks(): Boolean = true
override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = pos.offsetInCurrentLine == -1
override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int {
return pos.nextLineOffset ?: -1
}
override fun getDefaultAction(): MarkerBlock.ClosingAction {
return MarkerBlock.ClosingAction.DONE
}
override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult {
assert(pos.offsetInCurrentLine == -1)
val nextLineConstraints = constraints.applyToNextLineAndAddModifiers(pos)
// That means nextLineConstraints are "shorter" so our blockquote char is absent
if (!nextLineConstraints.extendsPrev(constraints)) {
return MarkerBlock.ProcessingResult.DEFAULT
}
return MarkerBlock.ProcessingResult.PASS
}
override fun getDefaultNodeType(): IElementType {
return MarkdownElementTypes.BLOCK_QUOTE
}
}
| apache-2.0 | 43325407b4dece3dab32b531c5faf93b | 42.428571 | 139 | 0.791667 | 5.271676 | false | false | false | false |
rock3r/detekt | buildSrc/src/main/kotlin/UpdateVersionInFileTask.kt | 1 | 1334 | import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.property
import java.io.File
open class UpdateVersionInFileTask : DefaultTask(), Runnable {
private val fileProp: RegularFileProperty = project.objects.fileProperty()
@get:InputFile
var fileToUpdate: File
get() = fileProp.get().asFile
set(value) {
fileProp.set(value)
}
private val containingProp: Property<String> = project.objects.property()
@get:Input
var linePartToFind: String
get() = containingProp.get()
set(value) {
containingProp.set(value)
}
@Input
var lineTransformation: ((String) -> String)? = null
@TaskAction
override fun run() {
val transformation = lineTransformation
checkNotNull(transformation) { "lineTransformation property is not set." }
val newContent = fileToUpdate.readLines()
.joinToString(LN) { if (it.contains(linePartToFind)) transformation(it) else it }
fileToUpdate.writeText("$newContent$LN")
}
companion object {
val LN: String = System.lineSeparator()
}
}
| apache-2.0 | 071558419e58ebda5767b773a1d43036 | 29.318182 | 93 | 0.682159 | 4.275641 | false | false | false | false |
cfig/Nexus_boot_image_editor | bbootimg/src/main/kotlin/avb/Avb.kt | 1 | 14747 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfig
import avb.AVBInfo
import avb.alg.Algorithms
import avb.blob.AuthBlob
import avb.blob.AuxBlob
import avb.blob.Footer
import avb.blob.Header
import avb.desc.*
import cfig.helper.Helper
import cfig.helper.Helper.Companion.paddingWith
import cfig.helper.KeyHelper
import cfig.helper.KeyHelper2
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.commons.codec.binary.Hex
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
class Avb {
private val MAX_VBMETA_SIZE = 64 * 1024
private val MAX_FOOTER_SIZE = 4096
//migrated from: avbtool::Avb::addHashFooter
fun addHashFooter(
image_file: String, //file to be hashed and signed
partition_size: Long, //aligned by Avb::BLOCK_SIZE
partition_name: String,
newAvbInfo: AVBInfo
) {
log.info("addHashFooter($image_file) ...")
imageSizeCheck(partition_size, image_file)
//truncate AVB footer if there is. Then addHashFooter() is idempotent
trimFooter(image_file)
val newImageSize = File(image_file).length()
//VBmeta blob: update hash descriptor
newAvbInfo.apply {
val itr = this.auxBlob!!.hashDescriptors.iterator()
var hd = HashDescriptor()
while (itr.hasNext()) {//remove previous hd entry
val itrValue = itr.next()
if (itrValue.partition_name == partition_name) {
itr.remove()
hd = itrValue
}
}
//HashDescriptor
hd.update(image_file)
log.info("updated hash descriptor:" + Hex.encodeHexString(hd.encode()))
this.auxBlob!!.hashDescriptors.add(hd)
}
// image + padding
val imgPaddingNeeded = Helper.round_to_multiple(newImageSize, BLOCK_SIZE) - newImageSize
// + vbmeta + padding
val vbmetaBlob = newAvbInfo.encode()
val vbmetaOffset = newImageSize + imgPaddingNeeded
val vbmetaBlobWithPadding = newAvbInfo.encodePadded()
// + DONT_CARE chunk
val vbmetaEndOffset = vbmetaOffset + vbmetaBlobWithPadding.size
val dontCareChunkSize = partition_size - vbmetaEndOffset - 1 * BLOCK_SIZE
// + AvbFooter + padding
newAvbInfo.footer!!.apply {
originalImageSize = newImageSize
vbMetaOffset = vbmetaOffset
vbMetaSize = vbmetaBlob.size.toLong()
}
log.info(newAvbInfo.footer.toString())
val footerBlobWithPadding = newAvbInfo.footer!!.encode().paddingWith(BLOCK_SIZE.toUInt(), true)
FileOutputStream(image_file, true).use { fos ->
log.info("1/4 Padding image with $imgPaddingNeeded bytes ...")
fos.write(ByteArray(imgPaddingNeeded.toInt()))
log.info("2/4 Appending vbmeta (${vbmetaBlobWithPadding.size} bytes)...")
fos.write(vbmetaBlobWithPadding)
log.info("3/4 Appending DONT CARE CHUNK ($dontCareChunkSize bytes) ...")
fos.write(ByteArray(dontCareChunkSize.toInt()))
log.info("4/4 Appending AVB footer (${footerBlobWithPadding.size} bytes)...")
fos.write(footerBlobWithPadding)
}
assert(partition_size == File(image_file).length()) { "generated file size mismatch" }
log.info("addHashFooter($image_file) done.")
}
private fun trimFooter(image_file: String) {
var footer: Footer? = null
FileInputStream(image_file).use {
it.skip(File(image_file).length() - 64)
try {
footer = Footer(it)
log.info("original image $image_file has AVB footer")
} catch (e: IllegalArgumentException) {
log.info("original image $image_file doesn't have AVB footer")
}
}
footer?.let {
FileOutputStream(File(image_file), true).channel.use { fc ->
log.info(
"original image $image_file has AVB footer, " +
"truncate it to original SIZE: ${it.originalImageSize}"
)
fc.truncate(it.originalImageSize)
}
}
}
private fun imageSizeCheck(partition_size: Long, image_file: String) {
//image size sanity check
val maxMetadataSize = MAX_VBMETA_SIZE + MAX_FOOTER_SIZE
if (partition_size < maxMetadataSize) {
throw IllegalArgumentException(
"Parition SIZE of $partition_size is too small. " +
"Needs to be at least $maxMetadataSize"
)
}
val maxImageSize = partition_size - maxMetadataSize
log.info("max_image_size: $maxImageSize")
//TODO: typical block size = 4096L, from avbtool::Avb::ImageHandler::block_size
//since boot.img is not in sparse format, we are safe to hardcode it to 4096L for now
if (partition_size % BLOCK_SIZE != 0L) {
throw IllegalArgumentException(
"Partition SIZE of $partition_size is not " +
"a multiple of the image block SIZE 4096"
)
}
val originalFileSize = File(image_file).length()
if (originalFileSize > maxImageSize) {
throw IllegalArgumentException(
"Image size of $originalFileSize exceeds maximum image size " +
"of $maxImageSize in order to fit in a partition size of $partition_size."
)
}
}
fun verify(ai: AVBInfo, image_file: String, parent: String = ""): Array<Any> {
val ret: Array<Any> = arrayOf(true, "")
val localParent = if (parent.isEmpty()) image_file else parent
//header
val rawHeaderBlob = ByteArray(Header.SIZE).apply {
FileInputStream(image_file).use { fis ->
ai.footer?.let {
fis.skip(it.vbMetaOffset)
}
fis.read(this)
}
}
// aux
val rawAuxBlob = ByteArray(ai.header!!.auxiliary_data_block_size.toInt()).apply {
FileInputStream(image_file).use { fis ->
val vbOffset = if (ai.footer == null) 0 else ai.footer!!.vbMetaOffset
fis.skip(vbOffset + Header.SIZE + ai.header!!.authentication_data_block_size)
fis.read(this)
}
}
//integrity check
val declaredAlg = Algorithms.get(ai.header!!.algorithm_type)
if (declaredAlg!!.public_key_num_bytes > 0) {
if (AuxBlob.encodePubKey(declaredAlg).contentEquals(ai.auxBlob!!.pubkey!!.pubkey)) {
log.info("VERIFY($localParent): signed with dev key: " + declaredAlg.defaultKey)
} else {
log.info("VERIFY($localParent): signed with release key")
}
val calcHash = Helper.join(declaredAlg.padding, AuthBlob.calcHash(rawHeaderBlob, rawAuxBlob, declaredAlg.name))
val readHash = Helper.join(declaredAlg.padding, Helper.fromHexString(ai.authBlob!!.hash!!))
if (calcHash.contentEquals(readHash)) {
log.info("VERIFY($localParent->AuthBlob): verify hash... PASS")
val readPubKey = KeyHelper.decodeRSAkey(ai.auxBlob!!.pubkey!!.pubkey)
val hashFromSig = KeyHelper2.rawRsa(readPubKey, Helper.fromHexString(ai.authBlob!!.signature!!))
if (hashFromSig.contentEquals(readHash)) {
log.info("VERIFY($localParent->AuthBlob): verify signature... PASS")
} else {
ret[0] = false
ret[1] = ret[1] as String + " verify signature fail;"
log.warn("read=" + Helper.toHexString(readHash) + ", calc=" + Helper.toHexString(calcHash))
log.warn("VERIFY($localParent->AuthBlob): verify signature... FAIL")
}
} else {
ret[0] = false
ret[1] = ret[1] as String + " verify hash fail"
log.warn("read=" + ai.authBlob!!.hash!! + ", calc=" + Helper.toHexString(calcHash))
log.warn("VERIFY($localParent->AuthBlob): verify hash... FAIL")
}
} else {
log.warn("VERIFY($localParent->AuthBlob): algorithm=[${declaredAlg.name}], no signature, skip")
}
val morePath = System.getenv("more")
val morePrefix = if (!morePath.isNullOrBlank()) "$morePath/" else ""
ai.auxBlob!!.chainPartitionDescriptors.forEach {
val vRet = it.verify(listOf(morePrefix + it.partition_name + ".img", it.partition_name + ".img"),
image_file + "->Chain[${it.partition_name}]")
if (vRet[0] as Boolean) {
log.info("VERIFY($localParent->Chain[${it.partition_name}]): " + "PASS")
} else {
ret[0] = false
ret[1] = ret[1] as String + "; " + vRet[1] as String
log.info("VERIFY($localParent->Chain[${it.partition_name}]): " + vRet[1] as String + "... FAIL")
}
}
ai.auxBlob!!.hashDescriptors.forEach {
val vRet = it.verify(listOf(morePrefix + it.partition_name + ".img", it.partition_name + ".img"),
image_file + "->HashDescriptor[${it.partition_name}]")
if (vRet[0] as Boolean) {
log.info("VERIFY($localParent->HashDescriptor[${it.partition_name}]): ${it.hash_algorithm} " + "PASS")
} else {
ret[0] = false
ret[1] = ret[1] as String + "; " + vRet[1] as String
log.info("VERIFY($localParent->HashDescriptor[${it.partition_name}]): ${it.hash_algorithm} " + vRet[1] as String + "... FAIL")
}
}
ai.auxBlob!!.hashTreeDescriptors.forEach {
val vRet = it.verify(listOf(morePrefix + it.partition_name + ".img", it.partition_name + ".img"),
image_file + "->HashTreeDescriptor[${it.partition_name}]")
if (vRet[0] as Boolean) {
log.info("VERIFY($localParent->HashTreeDescriptor[${it.partition_name}]): ${it.hash_algorithm} " + "PASS")
} else {
ret[0] = false
ret[1] = ret[1] as String + "; " + vRet[1] as String
log.info("VERIFY($localParent->HashTreeDescriptor[${it.partition_name}]): ${it.hash_algorithm} " + vRet[1] as String + "... FAIL")
}
}
return ret
}
companion object {
private val log = LoggerFactory.getLogger(Avb::class.java)
const val BLOCK_SIZE = 4096
const val AVB_VERSION_MAJOR = 1
const val AVB_VERSION_MINOR = 1
const val AVB_VERSION_SUB = 0
fun getJsonFileName(image_file: String): String {
val jsonFile = File(image_file).name.removeSuffix(".img") + ".avb.json"
return Helper.prop("workDir") + jsonFile
}
fun hasAvbFooter(fileName: String): Boolean {
val expectedBf = "AVBf".toByteArray()
FileInputStream(fileName).use { fis ->
fis.skip(File(fileName).length() - 64)
val bf = ByteArray(4)
fis.read(bf)
return bf.contentEquals(expectedBf)
}
}
fun verifyAVBIntegrity(fileName: String, avbtool: String): Boolean {
val cmdline = "python $avbtool verify_image --image $fileName"
log.info(cmdline)
try {
DefaultExecutor().execute(CommandLine.parse(cmdline))
} catch (e: Exception) {
log.error("$fileName failed integrity check by \"$cmdline\"")
return false
}
return true
}
fun updateVbmeta(fileName: String) {
if (File("vbmeta.img").exists()) {
log.info("Updating vbmeta.img side by side ...")
val partitionName =
ObjectMapper().readValue(File(getJsonFileName(fileName)), AVBInfo::class.java).let {
it.auxBlob!!.hashDescriptors.get(0).partition_name
}
//read hashDescriptor from image
val newHashDesc = AVBInfo.parseFrom("$fileName.signed")
assert(newHashDesc.auxBlob!!.hashDescriptors.size == 1)
var seq = -1 //means not found
//main vbmeta
ObjectMapper().readValue(File(getJsonFileName("vbmeta.img")), AVBInfo::class.java).apply {
val itr = this.auxBlob!!.hashDescriptors.iterator()
while (itr.hasNext()) {
val itrValue = itr.next()
if (itrValue.partition_name == partitionName) {
log.info("Found $partitionName in vbmeta, update it")
seq = itrValue.sequence
itr.remove()
break
}
}
if (-1 == seq) {
log.warn("main vbmeta doesn't have $partitionName hashDescriptor, won't update vbmeta.img")
} else {
//add hashDescriptor back to main vbmeta
val hd = newHashDesc.auxBlob!!.hashDescriptors.get(0).apply { this.sequence = seq }
this.auxBlob!!.hashDescriptors.add(hd)
log.info("Writing padded vbmeta to file: vbmeta.img.signed")
Files.write(Paths.get("vbmeta.img.signed"), encodePadded(), StandardOpenOption.CREATE)
log.info("Updating vbmeta.img side by side (partition=$partitionName, seq=$seq) done")
}
}
} else {
log.debug("no companion vbmeta.img")
}
}
}
}
| apache-2.0 | 8b739261cc6d17faae254a3c8f467902 | 43.418675 | 146 | 0.569065 | 4.370777 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/model/plans/PlanOffersMapper.kt | 2 | 2351 | package org.wordpress.android.fluxc.model.plans
import dagger.Reusable
import org.wordpress.android.fluxc.model.plans.PlanOffersModel.Feature
import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOffer
import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOfferFeature
import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOfferId
import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOfferWithDetails
import javax.inject.Inject
@Reusable
class PlanOffersMapper @Inject constructor() {
fun toDatabaseModel(
internalPlanId: Int,
domainModel: PlanOffersModel
): PlanOfferWithDetails = with(domainModel) {
return PlanOfferWithDetails(
planOffer = PlanOffer(
internalPlanId = internalPlanId,
name = this.name,
shortName = this.shortName,
tagline = this.tagline,
description = this.description,
icon = this.iconUrl
),
planIds = this.planIds?.map {
PlanOfferId(
productId = it,
internalPlanId = internalPlanId
)
} ?: emptyList(),
planFeatures = this.features?.map {
PlanOfferFeature(
internalPlanId = internalPlanId,
stringId = it.id,
name = it.name,
description = it.description
)
} ?: emptyList()
)
}
fun toDomainModel(
databaseModel: PlanOfferWithDetails
): PlanOffersModel = with(databaseModel) {
return PlanOffersModel(
planIds = this.planIds.map {
it.productId
},
features = this.planFeatures.map {
Feature(id = it.stringId, name = it.name, description = it.description)
},
name = this.planOffer.name,
shortName = this.planOffer.shortName,
tagline = this.planOffer.tagline,
description = this.planOffer.description,
iconUrl = this.planOffer.icon
)
}
}
| gpl-2.0 | a93f4d65daf40171f830d7db669e4247 | 38.183333 | 91 | 0.545725 | 5.189845 | false | false | false | false |
raatiniemi/worker | core/src/test/java/me/raatiniemi/worker/domain/repository/PageRequestTest.kt | 1 | 1518 | /*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.domain.repository
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class PageRequestTest {
@Test
fun withOffsetAndMaxResults() {
val pageRequest = PageRequest.withOffsetAndMaxResults(offset = 1, maxResults = 2)
assertEquals(1, pageRequest.offset)
assertEquals(2, pageRequest.maxResults)
}
@Test
fun withOffset() {
val pageRequest = PageRequest.withOffset(offset = 1)
assertEquals(1, pageRequest.offset)
assertEquals(PageRequest.MAX_RESULTS, pageRequest.maxResults)
}
@Test
fun withMaxResults() {
val pageRequest = PageRequest.withMaxResults(100)
assertEquals(0, pageRequest.offset)
assertEquals(100, pageRequest.maxResults)
}
}
| gpl-2.0 | c39d28562ef77ec473ad724de98d1cc0 | 29.979592 | 89 | 0.722003 | 4.228412 | false | true | false | false |
cfig/Android_boot_image_editor | bbootimg/src/main/kotlin/ota/BrilloProp.kt | 1 | 2091 | // Copyright 2022 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cc.cfig.droid.ota
import cfig.helper.ZipHelper.Companion.getEntryOffset
import org.apache.commons.compress.archivers.zip.ZipFile
import org.slf4j.LoggerFactory
import java.io.File
// tuple(name, offset, size) of an zip entry
class BrilloProp(
var name: String,
var offset: Long,
var size: Long
) {
constructor(zf: ZipFile, entryName: String) : this("", 0, 0) {
val entry = zf.getEntry(entryName)
name = File(entryName).name
offset = entry.getEntryOffset()
size = entry.size
log.debug("extra size = " + entry.localFileDataExtra.size)
log.debug("file name len = " + entry.name.length)
}
companion object {
private val log = LoggerFactory.getLogger(BrilloProp::class.java)
}
override fun toString(): String {
return if (offset == 0L && size == 0L) {
name + " ".repeat(15)
} else {
"$name:$offset:$size"
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BrilloProp
if (name != other.name) return false
if (offset != other.offset) return false
if (size != other.size) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + offset.hashCode()
result = 31 * result + size.hashCode()
return result
}
}
| apache-2.0 | c97845389fe9f20a35037e8b33c9239f | 31.169231 | 75 | 0.644668 | 4.03668 | false | false | false | false |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/actions/people/SyncPersonShowCredits.kt | 1 | 6611 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.actions.people
import android.content.ContentProviderOperation
import android.content.Context
import net.simonvt.cathode.actions.CallAction
import net.simonvt.cathode.actions.people.SyncPersonShowCredits.Params
import net.simonvt.cathode.api.entity.Credit
import net.simonvt.cathode.api.entity.Credits
import net.simonvt.cathode.api.enumeration.Department
import net.simonvt.cathode.api.enumeration.Extended
import net.simonvt.cathode.api.service.PeopleService
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.ShowCastColumns
import net.simonvt.cathode.provider.DatabaseContract.ShowCrewColumns
import net.simonvt.cathode.provider.DatabaseSchematic.Tables
import net.simonvt.cathode.provider.ProviderSchematic.ShowCast
import net.simonvt.cathode.provider.ProviderSchematic.ShowCrew
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.helper.PersonDatabaseHelper
import net.simonvt.cathode.provider.helper.ShowDatabaseHelper
import net.simonvt.cathode.provider.query
import retrofit2.Call
import java.util.ArrayList
import javax.inject.Inject
class SyncPersonShowCredits @Inject constructor(
private val context: Context,
private val showHelper: ShowDatabaseHelper,
private val personHelper: PersonDatabaseHelper,
private val peopleService: PeopleService
) : CallAction<Params, Credits>() {
override fun key(params: Params): String = "SyncPersonShowCredits&traktId=${params.traktId}"
override fun getCall(params: Params): Call<Credits> =
peopleService.shows(params.traktId, Extended.FULL)
override suspend fun handleResponse(params: Params, response: Credits) {
val ops = arrayListOf<ContentProviderOperation>()
val personId = personHelper.getId(params.traktId)
val oldCastCursor = context.contentResolver.query(
ShowCast.withPerson(personId),
arrayOf(Tables.SHOW_CAST + "." + ShowCastColumns.ID, ShowCastColumns.SHOW_ID)
)
val oldCast = mutableListOf<Long>()
val showToCastIdMap = mutableMapOf<Long, Long>()
while (oldCastCursor.moveToNext()) {
val id = oldCastCursor.getLong(ShowCastColumns.ID)
val showId = oldCastCursor.getLong(ShowCastColumns.SHOW_ID)
oldCast.add(showId)
showToCastIdMap[showId] = id
}
oldCastCursor.close()
val cast = response.cast
if (cast != null) {
for (credit in cast) {
val showId = showHelper.partialUpdate(credit.show!!)
if (oldCast.remove(showId)) {
val castId = showToCastIdMap[showId]!!
val op = ContentProviderOperation.newUpdate(ShowCast.withId(castId))
.withValue(ShowCastColumns.SHOW_ID, showId)
.withValue(ShowCastColumns.PERSON_ID, personId)
.withValue(ShowCastColumns.CHARACTER, credit.character)
.build()
ops.add(op)
} else {
val op = ContentProviderOperation.newInsert(ShowCast.SHOW_CAST)
.withValue(ShowCastColumns.SHOW_ID, showId)
.withValue(ShowCastColumns.PERSON_ID, personId)
.withValue(ShowCastColumns.CHARACTER, credit.character)
.build()
ops.add(op)
}
}
}
for (showId in oldCast) {
val castId = showToCastIdMap[showId]!!
val op = ContentProviderOperation.newDelete(ShowCast.withId(castId)).build()
ops.add(op)
}
val crew = response.crew
if (crew != null) {
insertCrew(ops, personId, Department.PRODUCTION, crew.production)
insertCrew(ops, personId, Department.ART, crew.art)
insertCrew(ops, personId, Department.CREW, crew.crew)
insertCrew(ops, personId, Department.COSTUME_AND_MAKEUP, crew.costume_and_make_up)
insertCrew(ops, personId, Department.DIRECTING, crew.directing)
insertCrew(ops, personId, Department.WRITING, crew.writing)
insertCrew(ops, personId, Department.SOUND, crew.sound)
insertCrew(ops, personId, Department.CAMERA, crew.camera)
}
context.contentResolver.batch(ops)
}
private fun insertCrew(
ops: ArrayList<ContentProviderOperation>,
personId: Long,
department: Department,
crew: List<Credit>?
) {
val oldCrewCursor = context.contentResolver.query(
ShowCrew.withPerson(personId),
arrayOf(Tables.SHOW_CREW + "." + ShowCrewColumns.ID, ShowCrewColumns.SHOW_ID),
ShowCrewColumns.CATEGORY + "=?",
arrayOf(department.toString())
)
val oldCrew = mutableListOf<Long>()
val showToCrewIdMap = mutableMapOf<Long, Long>()
while (oldCrewCursor.moveToNext()) {
val id = oldCrewCursor.getLong(ShowCrewColumns.ID)
val showId = oldCrewCursor.getLong(ShowCrewColumns.SHOW_ID)
oldCrew.add(showId)
showToCrewIdMap[showId] = id
}
oldCrewCursor.close()
if (crew != null) {
for (credit in crew) {
val showId = showHelper.partialUpdate(credit.show!!)
if (oldCrew.remove(showId)) {
val crewId = showToCrewIdMap[showId]!!
val op = ContentProviderOperation.newUpdate(ShowCrew.withId(crewId))
.withValue(ShowCrewColumns.SHOW_ID, showId)
.withValue(ShowCrewColumns.PERSON_ID, personId)
.withValue(ShowCrewColumns.CATEGORY, department.toString())
.withValue(ShowCrewColumns.JOB, credit.job)
.build()
ops.add(op)
} else {
val op = ContentProviderOperation.newInsert(ShowCrew.SHOW_CREW)
.withValue(ShowCrewColumns.SHOW_ID, showId)
.withValue(ShowCrewColumns.PERSON_ID, personId)
.withValue(ShowCrewColumns.CATEGORY, department.toString())
.withValue(ShowCrewColumns.JOB, credit.job)
.build()
ops.add(op)
}
}
}
for (showId in oldCrew) {
val crewId = showToCrewIdMap[showId]!!
val op = ContentProviderOperation.newDelete(ShowCrew.withId(crewId)).build()
ops.add(op)
}
}
data class Params(val traktId: Long)
}
| apache-2.0 | 137ef49126fef6fb33a7f70ca0d3422c | 37.436047 | 94 | 0.709272 | 4.116438 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.