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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DarkToast/AxonSpring | src/main/kotlin/de/tarent/axon/query/Game.kt | 1 | 1208 | package de.tarent.axon.query
import java.util.*
import javax.persistence.CascadeType
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.OneToMany
@Entity
data class Game (
@Id
val gameUuid: UUID,
val version: Long,
@OneToMany(cascade = arrayOf(CascadeType.ALL), orphanRemoval = true)
val movesFromX: List<Movement>,
@OneToMany(cascade = arrayOf(CascadeType.ALL), orphanRemoval = true)
val movesFromO: List<Movement>,
val lastMoveFrom: Char,
val finished: Boolean
) {
// Just for JPA
@Suppress("unused")
private constructor() : this(UUID.randomUUID(), 0L, emptyList<Movement>(), emptyList<Movement>(), 'X', false)
override fun toString(): String {
val state = arrayOf(
arrayOf('-', '-', '-'),
arrayOf('-', '-', '-'),
arrayOf('-', '-', '-')
)
movesFromX.forEach({ move ->
state[move.row][move.column] = 'X'
})
movesFromO.forEach({ move ->
state[move.row][move.column] = 'O'
})
return state.fold("") { acc, elem ->
acc + " " + elem.joinToString(" | ") + "\n"
}.trimEnd()
}
} | apache-2.0 | ed92d75b3532a75ed1df5a2f75ca9d78 | 23.673469 | 113 | 0.578642 | 4.108844 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt | 1 | 7936 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.plugins.logging
import io.ktor.client.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.observer.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.util.*
import io.ktor.utils.io.*
import io.ktor.utils.io.charsets.*
import kotlinx.coroutines.*
private val ClientCallLogger = AttributeKey<HttpClientCallLogger>("CallLogger")
private val DisableLogging = AttributeKey<Unit>("DisableLogging")
/**
* A client's plugin that provides the capability to log HTTP calls.
*
* You can learn more from [Logging](https://ktor.io/docs/client-logging.html).
*/
public class Logging private constructor(
public val logger: Logger,
public var level: LogLevel,
public var filters: List<(HttpRequestBuilder) -> Boolean> = emptyList()
) {
/**
* A configuration for the [Logging] plugin.
*/
@KtorDsl
public class Config {
/**
* filters
*/
internal var filters = mutableListOf<(HttpRequestBuilder) -> Boolean>()
private var _logger: Logger? = null
/**
* Specifies a [Logger] instance.
*/
public var logger: Logger
get() = _logger ?: Logger.DEFAULT
set(value) {
_logger = value
}
/**
* Specifies the log the logging level.
*/
public var level: LogLevel = LogLevel.HEADERS
/**
* Allows you to filter log messages for calls matching a [predicate].
*/
public fun filter(predicate: (HttpRequestBuilder) -> Boolean) {
filters.add(predicate)
}
}
private fun setupRequestLogging(client: HttpClient) {
client.sendPipeline.intercept(HttpSendPipeline.Monitoring) {
if (!shouldBeLogged(context)) {
context.attributes.put(DisableLogging, Unit)
return@intercept
}
val response = try {
logRequest(context)
} catch (_: Throwable) {
null
}
try {
proceedWith(response ?: subject)
} catch (cause: Throwable) {
logRequestException(context, cause)
throw cause
} finally {
}
}
}
private suspend fun logRequest(request: HttpRequestBuilder): OutgoingContent? {
val content = request.body as OutgoingContent
val logger = HttpClientCallLogger(logger)
request.attributes.put(ClientCallLogger, logger)
val message = buildString {
if (level.info) {
appendLine("REQUEST: ${Url(request.url)}")
appendLine("METHOD: ${request.method}")
}
if (level.headers) {
appendLine("COMMON HEADERS")
logHeaders(request.headers.entries())
appendLine("CONTENT HEADERS")
content.contentLength?.let { logHeader(HttpHeaders.ContentLength, it.toString()) }
content.contentType?.let { logHeader(HttpHeaders.ContentType, it.toString()) }
logHeaders(content.headers.entries())
}
}
if (message.isNotEmpty()) {
logger.logRequest(message)
}
if (message.isEmpty() || !level.body) {
logger.closeRequestLog()
return null
}
return logRequestBody(content, logger)
}
@OptIn(DelicateCoroutinesApi::class)
private suspend fun logRequestBody(
content: OutgoingContent,
logger: HttpClientCallLogger
): OutgoingContent {
val requestLog = StringBuilder()
requestLog.appendLine("BODY Content-Type: ${content.contentType}")
val charset = content.contentType?.charset() ?: Charsets.UTF_8
val channel = ByteChannel()
GlobalScope.launch(Dispatchers.Unconfined) {
val text = channel.tryReadText(charset) ?: "[request body omitted]"
requestLog.appendLine("BODY START")
requestLog.appendLine(text)
requestLog.append("BODY END")
}.invokeOnCompletion {
logger.logRequest(requestLog.toString())
logger.closeRequestLog()
}
return content.observe(channel)
}
private fun logRequestException(context: HttpRequestBuilder, cause: Throwable) {
if (level.info) {
logger.log("REQUEST ${Url(context.url)} failed with exception: $cause")
}
}
@OptIn(InternalAPI::class)
private fun setupResponseLogging(client: HttpClient) {
client.receivePipeline.intercept(HttpReceivePipeline.State) { response ->
if (level == LogLevel.NONE || response.call.attributes.contains(DisableLogging)) return@intercept
val logger = response.call.attributes[ClientCallLogger]
val header = StringBuilder()
var failed = false
try {
logResponseHeader(header, response.call.response, level)
proceedWith(subject)
} catch (cause: Throwable) {
logResponseException(header, response.call.request, cause)
failed = true
throw cause
} finally {
logger.logResponseHeader(header.toString())
if (failed || !level.body) logger.closeResponseLog()
}
}
client.responsePipeline.intercept(HttpResponsePipeline.Receive) {
if (level == LogLevel.NONE || context.attributes.contains(DisableLogging)) {
return@intercept
}
try {
proceed()
} catch (cause: Throwable) {
val log = StringBuilder()
val logger = context.attributes[ClientCallLogger]
logResponseException(log, context.request, cause)
logger.logResponseException(log.toString())
logger.closeResponseLog()
throw cause
}
}
if (!level.body) return
val observer: ResponseHandler = observer@{
if (level == LogLevel.NONE || it.call.attributes.contains(DisableLogging)) {
return@observer
}
val logger = it.call.attributes[ClientCallLogger]
val log = StringBuilder()
try {
logResponseBody(log, it.contentType(), it.content)
} catch (_: Throwable) {
} finally {
logger.logResponseBody(log.toString().trim())
logger.closeResponseLog()
}
}
ResponseObserver.install(ResponseObserver(observer), client)
}
private fun logResponseException(log: StringBuilder, request: HttpRequest, cause: Throwable) {
if (!level.info) return
log.append("RESPONSE ${request.url} failed with exception: $cause")
}
public companion object : HttpClientPlugin<Config, Logging> {
override val key: AttributeKey<Logging> = AttributeKey("ClientLogging")
override fun prepare(block: Config.() -> Unit): Logging {
val config = Config().apply(block)
return Logging(config.logger, config.level, config.filters)
}
override fun install(plugin: Logging, scope: HttpClient) {
plugin.setupRequestLogging(scope)
plugin.setupResponseLogging(scope)
}
}
private fun shouldBeLogged(request: HttpRequestBuilder): Boolean = filters.isEmpty() || filters.any { it(request) }
}
/**
* Configures and installs [Logging] in [HttpClient].
*/
public fun HttpClientConfig<*>.Logging(block: Logging.Config.() -> Unit = {}) {
install(Logging, block)
}
| apache-2.0 | 07ba173d0dc6049ff5bc21a7e142387e | 32.066667 | 119 | 0.592742 | 4.907854 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/base/activity/BaseThemedActivity.kt | 2 | 2592 | package eu.kanade.tachiyomi.ui.base.activity
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.PreferenceValues
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.util.system.prepareTabletUiContext
import uy.kohesive.injekt.injectLazy
abstract class BaseThemedActivity : AppCompatActivity() {
val preferences: PreferencesHelper by injectLazy()
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(newBase.prepareTabletUiContext())
}
override fun onCreate(savedInstanceState: Bundle?) {
applyAppTheme(preferences)
super.onCreate(savedInstanceState)
}
companion object {
fun AppCompatActivity.applyAppTheme(preferences: PreferencesHelper) {
getThemeResIds(preferences.appTheme().get(), preferences.themeDarkAmoled().get())
.forEach { setTheme(it) }
}
fun getThemeResIds(appTheme: PreferenceValues.AppTheme, isAmoled: Boolean): List<Int> {
val resIds = mutableListOf<Int>()
when (appTheme) {
PreferenceValues.AppTheme.MONET -> {
resIds += R.style.Theme_Tachiyomi_Monet
}
PreferenceValues.AppTheme.GREEN_APPLE -> {
resIds += R.style.Theme_Tachiyomi_GreenApple
}
PreferenceValues.AppTheme.MIDNIGHT_DUSK -> {
resIds += R.style.Theme_Tachiyomi_MidnightDusk
}
PreferenceValues.AppTheme.STRAWBERRY_DAIQUIRI -> {
resIds += R.style.Theme_Tachiyomi_StrawberryDaiquiri
}
PreferenceValues.AppTheme.TAKO -> {
resIds += R.style.Theme_Tachiyomi_Tako
}
PreferenceValues.AppTheme.TEALTURQUOISE -> {
resIds += R.style.Theme_Tachiyomi_TealTurquoise
}
PreferenceValues.AppTheme.YINYANG -> {
resIds += R.style.Theme_Tachiyomi_YinYang
}
PreferenceValues.AppTheme.YOTSUBA -> {
resIds += R.style.Theme_Tachiyomi_Yotsuba
}
else -> {
resIds += R.style.Theme_Tachiyomi
}
}
if (isAmoled) {
resIds += R.style.ThemeOverlay_Tachiyomi_Amoled
}
return resIds
}
}
}
| apache-2.0 | 0205d49b63a69a7e6bd4cf2ac49c7f29 | 36.028571 | 95 | 0.593364 | 4.721311 | false | false | false | false |
ayatk/biblio | app/src/main/kotlin/com/ayatk/biblio/ui/home/library/LibraryViewModel.kt | 1 | 2088 | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.ui.home.library
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.ayatk.biblio.domain.usecase.LibraryUseCase
import com.ayatk.biblio.model.Library
import com.ayatk.biblio.model.Novel
import com.ayatk.biblio.ui.util.toResult
import com.ayatk.biblio.util.Result
import com.ayatk.biblio.util.ext.toLiveData
import com.ayatk.biblio.util.rx.SchedulerProvider
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.subscribeBy
import timber.log.Timber
import javax.inject.Inject
class LibraryViewModel @Inject constructor(
private val useCase: LibraryUseCase,
private val schedulerProvider: SchedulerProvider
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
val libraries: LiveData<Result<List<Library>>> by lazy {
useCase.libraries
.toResult(schedulerProvider)
.toLiveData()
}
var refreshing = MutableLiveData<Boolean>()
override fun onCleared() {
compositeDisposable.clear()
}
fun onSwipeRefresh() {
useCase.update()
.observeOn(schedulerProvider.ui())
.subscribeBy(
onComplete = { refreshing.postValue(false) },
onError = Timber::e
)
.addTo(compositeDisposable)
}
fun delete(novel: Novel) =
useCase.delete(novel)
.observeOn(schedulerProvider.ui())
.subscribe()
.addTo(compositeDisposable)
}
| apache-2.0 | 1251e0ab6d376bbfee0745810958334c | 29.26087 | 75 | 0.75 | 4.322981 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/persistence/local/room/relations/TaskEntityAndRelations.kt | 1 | 1475 | /*
* Copyright 2019 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.android.ground.persistence.local.room.relations
import androidx.room.Embedded
import androidx.room.Relation
import com.google.android.ground.persistence.local.room.entity.MultipleChoiceEntity
import com.google.android.ground.persistence.local.room.entity.OptionEntity
import com.google.android.ground.persistence.local.room.entity.TaskEntity
/**
* Represents relationship between TaskEntity, MultipleChoiceEntity, and OptionEntity.
*
* Querying any of the below data classes automatically loads the task annotated as @Relation.
*/
data class TaskEntityAndRelations(
@Embedded val taskEntity: TaskEntity,
@Relation(parentColumn = "id", entityColumn = "task_id")
val multipleChoiceEntities: List<MultipleChoiceEntity>,
@Relation(parentColumn = "id", entityColumn = "task_id", entity = OptionEntity::class)
val optionEntities: List<OptionEntity>
)
| apache-2.0 | ba414c5efe346c1727b5dd325cf2f332 | 41.142857 | 94 | 0.779661 | 4.15493 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/LeftEntityImpl.kt | 2 | 10639 | 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.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class LeftEntityImpl: LeftEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeBaseEntity::class.java, BaseEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeBaseEntity::class.java, BaseEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
CHILDREN_CONNECTION_ID,
)
}
override val parentEntity: CompositeBaseEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
override val children: List<BaseEntity>
get() = snapshot.extractOneToAbstractManyChildren<BaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: LeftEntityData?): ModifiableWorkspaceEntityBase<LeftEntity>(), LeftEntity.Builder {
constructor(): this(LeftEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity LeftEntity 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
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field CompositeBaseEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field CompositeBaseEntity#children should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field CompositeBaseEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentEntity: CompositeBaseEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositeBaseEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositeBaseEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// 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.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// 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 var children: List<BaseEntity>
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyChildren<BaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<BaseEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<BaseEntity> ?: emptyList()
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence())
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): LeftEntityData = result ?: super.getEntityData() as LeftEntityData
override fun getEntityClass(): Class<LeftEntity> = LeftEntity::class.java
}
}
class LeftEntityData : WorkspaceEntityData<LeftEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LeftEntity> {
val modifiable = LeftEntityImpl.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): LeftEntity {
val entity = LeftEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return LeftEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LeftEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LeftEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
} | apache-2.0 | 81ab7412c3aced0d6eea7d6d1035952e | 43.518828 | 214 | 0.60861 | 5.970258 | false | false | false | false |
openium/auvergne-webcams-droid | app/src/main/java/fr/openium/auvergnewebcams/model/entity/Webcam.kt | 1 | 1600 | package fr.openium.auvergnewebcams.model.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Created by Openium on 19/02/2019.
*/
@Entity
class Webcam {
@PrimaryKey
var uid: Long = 0
var sectionUid: Long? = null
var order: Int = 0
var title: String? = null
var imageLD: String? = null
var imageHD: String? = null
var viewsurfLD: String? = null
var viewsurfHD: String? = null
var type: String? = null
var tags: List<String>? = listOf()
var mediaViewSurfLD: String? = null
var mediaViewSurfHD: String? = null
var lastUpdate: Long? = null
var isFavoris: Boolean = false
var hidden: Boolean? = false
fun populateId(uid: Long) {
sectionUid = uid
}
fun getUrlForWebcam(canBeHD: Boolean, canBeVideo: Boolean): String =
if (type == WebcamType.VIEWSURF.nameType) {
val format = if (canBeVideo) "%s/%s.mp4" else "%s/%s.jpg"
// Load LD/HD video
if (canBeHD && !mediaViewSurfHD.isNullOrEmpty() && !viewsurfHD.isNullOrEmpty()) {
String.format(format, viewsurfHD, mediaViewSurfHD)
} else String.format(format, viewsurfLD, mediaViewSurfLD)
} else {
// Load LD/HD image
if (canBeHD && !imageHD.isNullOrBlank()) imageHD ?: "" else imageLD ?: ""
}
fun getLastUpdateDate(): Long? =
if (lastUpdate != null && lastUpdate != 0L) {
lastUpdate
} else null
enum class WebcamType(val nameType: String) {
IMAGE("image"),
VIEWSURF("viewsurf")
}
} | mit | a28ef1310fa9a30659ee251d58d3fae6 | 28.648148 | 93 | 0.606875 | 3.669725 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/table/HighlightWord.kt | 1 | 8647 | package jp.juggler.subwaytooter.table
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import jp.juggler.subwaytooter.App1
import jp.juggler.subwaytooter.global.appDatabase
import jp.juggler.util.*
import java.util.concurrent.atomic.AtomicReference
class HighlightWord {
companion object : TableCompanion {
private val log = LogCategory("HighlightWord")
const val SOUND_TYPE_NONE = 0
const val SOUND_TYPE_DEFAULT = 1
const val SOUND_TYPE_CUSTOM = 2
override val table = "highlight_word"
const val COL_ID = BaseColumns._ID
const val COL_NAME = "name"
private const val COL_TIME_SAVE = "time_save"
private const val COL_COLOR_BG = "color_bg"
private const val COL_COLOR_FG = "color_fg"
private const val COL_SOUND_TYPE = "sound_type"
private const val COL_SOUND_URI = "sound_uri"
private const val COL_SPEECH = "speech"
private const val selection_name = "$COL_NAME=?"
private const val selection_speech = "$COL_SPEECH<>0"
private const val selection_id = "$COL_ID=?"
private val columns_name = arrayOf(COL_NAME)
override fun onDBCreate(db: SQLiteDatabase) {
log.d("onDBCreate!")
db.execSQL(
"""create table if not exists $table
($COL_ID INTEGER PRIMARY KEY
,$COL_NAME text not null
,$COL_TIME_SAVE integer not null
,$COL_COLOR_BG integer not null default 0
,$COL_COLOR_FG integer not null default 0
,$COL_SOUND_TYPE integer not null default 1
,$COL_SOUND_URI text default null
,$COL_SPEECH integer default 0
)"""
)
db.execSQL(
"create unique index if not exists ${table}_name on $table(name)"
)
}
override fun onDBUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 21 && newVersion >= 21) {
onDBCreate(db)
}
if (oldVersion < 43 && newVersion >= 43) {
try {
db.execSQL("alter table $table add column $COL_SPEECH integer default 0")
} catch (ex: Throwable) {
log.trace(ex)
}
}
}
fun load(name: String): HighlightWord? {
try {
appDatabase.query(table, null, selection_name, arrayOf(name), null, null, null)
.use { cursor ->
if (cursor.moveToNext()) {
return HighlightWord(cursor)
}
}
} catch (ex: Throwable) {
log.trace(ex)
}
return null
}
fun load(id: Long): HighlightWord? {
try {
appDatabase.query(
table,
null,
selection_id,
arrayOf(id.toString()),
null,
null,
null
)
.use { cursor ->
if (cursor.moveToNext()) {
return HighlightWord(cursor)
}
}
} catch (ex: Throwable) {
log.trace(ex)
}
return null
}
fun createCursor(): Cursor {
return appDatabase.query(table, null, null, null, null, null, "$COL_NAME asc")
}
val nameSet: WordTrieTree?
get() {
val dst = WordTrieTree()
try {
appDatabase.query(table, columns_name, null, null, null, null, null)
.use { cursor ->
val idx_name = cursor.getColumnIndex(COL_NAME)
while (cursor.moveToNext()) {
val s = cursor.getString(idx_name)
dst.add(s)
}
}
} catch (ex: Throwable) {
log.trace(ex)
}
return if (dst.isEmpty) null else dst
}
private val hasTextToSpeechHighlightWordCache = AtomicReference<Boolean>(null)
fun hasTextToSpeechHighlightWord(): Boolean {
synchronized(this) {
var cached = hasTextToSpeechHighlightWordCache.get()
if (cached == null) {
cached = false
try {
appDatabase.query(
table,
columns_name,
selection_speech,
null,
null,
null,
null
)
.use { cursor ->
while (cursor.moveToNext()) {
cached = true
}
}
} catch (ex: Throwable) {
log.trace(ex)
}
hasTextToSpeechHighlightWordCache.set(cached)
}
return cached
}
}
}
var id = -1L
var name: String
var color_bg = 0
var color_fg = 0
var sound_type = 0
var sound_uri: String? = null
var speech = 0
fun encodeJson(): JsonObject {
val dst = JsonObject()
dst[COL_ID] = id
dst[COL_NAME] = name
dst[COL_COLOR_BG] = color_bg
dst[COL_COLOR_FG] = color_fg
dst[COL_SOUND_TYPE] = sound_type
dst[COL_SPEECH] = speech
sound_uri?.let { dst[COL_SOUND_URI] = it }
return dst
}
constructor(src: JsonObject) {
this.id = src.long(COL_ID) ?: -1L
this.name = src.stringOrThrow(COL_NAME)
this.color_bg = src.optInt(COL_COLOR_BG)
this.color_fg = src.optInt(COL_COLOR_FG)
this.sound_type = src.optInt(COL_SOUND_TYPE)
this.sound_uri = src.string(COL_SOUND_URI)
this.speech = src.optInt(COL_SPEECH)
}
constructor(name: String) {
this.name = name
this.sound_type = SOUND_TYPE_DEFAULT
this.color_fg = -0x10000
}
constructor(cursor: Cursor) {
this.id = cursor.getLong(COL_ID)
this.name = cursor.getString(COL_NAME)
this.color_bg = cursor.getInt(COL_COLOR_BG)
this.color_fg = cursor.getInt(COL_COLOR_FG)
this.sound_type = cursor.getInt(COL_SOUND_TYPE)
this.sound_uri = cursor.getStringOrNull(COL_SOUND_URI)
this.speech = cursor.getInt(COL_SPEECH)
}
fun save(context: Context) {
if (name.isEmpty()) error("HighlightWord.save(): name is empty")
try {
val cv = ContentValues()
cv.put(COL_NAME, name)
cv.put(COL_TIME_SAVE, System.currentTimeMillis())
cv.put(COL_COLOR_BG, color_bg)
cv.put(COL_COLOR_FG, color_fg)
cv.put(COL_SOUND_TYPE, sound_type)
val sound_uri = this.sound_uri
if (sound_uri?.isEmpty() != false) {
cv.putNull(COL_SOUND_URI)
} else {
cv.put(COL_SOUND_URI, sound_uri)
}
cv.put(COL_SPEECH, speech)
if (id == -1L) {
id = appDatabase.replace(table, null, cv)
} else {
appDatabase.update(table, cv, selection_id, arrayOf(id.toString()))
}
} catch (ex: Throwable) {
log.e(ex, "save failed.")
}
synchronized(Companion) {
hasTextToSpeechHighlightWordCache.set(null)
}
App1.getAppState(context).enableSpeech()
}
fun delete(context: Context) {
try {
appDatabase.delete(table, selection_id, arrayOf(id.toString()))
} catch (ex: Throwable) {
log.e(ex, "delete failed.")
}
synchronized(Companion) {
hasTextToSpeechHighlightWordCache.set(null)
}
App1.getAppState(context).enableSpeech()
}
}
| apache-2.0 | ea4f104ddfa7b3eb8d4af3839f5a413e | 31.909804 | 95 | 0.477044 | 4.641439 | false | false | false | false |
ediTLJ/novelty | app/src/main/java/ro/edi/novelty/ui/FeedsActivity.kt | 1 | 3808 | /*
* Copyright 2019 Eduard Scarlat
*
* 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 ro.edi.novelty.ui
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback
import ro.edi.novelty.R
import ro.edi.novelty.databinding.ActivityFeedsBinding
import ro.edi.novelty.ui.adapter.FeedsAdapter
import ro.edi.novelty.ui.viewmodel.FeedsViewModel
import timber.log.Timber.Forest.i as logi
class FeedsActivity : AppCompatActivity() {
private val feedsModel: FeedsViewModel by lazy(LazyThreadSafetyMode.NONE) {
ViewModelProvider(
viewModelStore,
defaultViewModelProviderFactory
)[FeedsViewModel::class.java]
}
override fun onCreate(savedInstanceState: Bundle?) {
// attach a callback used to capture the shared elements from this activity
// to be used by the container transform transition
setExitSharedElementCallback(MaterialContainerTransformSharedElementCallback())
// keep system bars (status bar, navigation bar) persistent throughout the transition
window.sharedElementsUseOverlay = false
super.onCreate(savedInstanceState)
val binding: ActivityFeedsBinding =
DataBindingUtil.setContentView(this, R.layout.activity_feeds)
binding.lifecycleOwner = this
binding.model = feedsModel
initView(binding)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_feeds, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_add -> {
val iAdd = Intent(this, FeedInfoActivity::class.java)
iAdd.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(iAdd)
}
}
return super.onOptionsItemSelected(item)
}
private fun initView(binding: ActivityFeedsBinding) {
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.feeds.apply {
setHasFixedSize(true)
adapter = FeedsAdapter(this@FeedsActivity, feedsModel).apply {
setHasStableIds(true)
itemTouchHelper.attachToRecyclerView(binding.feeds)
}
}
feedsModel.feeds.observe(this) { feeds ->
logi("feeds changed: %d feeds", feeds.size)
if (feeds.isEmpty()) {
binding.empty.visibility = View.VISIBLE
binding.feeds.visibility = View.GONE
} else {
binding.empty.visibility = View.GONE
binding.feeds.visibility = View.VISIBLE
(binding.feeds.adapter as FeedsAdapter).submitList(feeds)
}
}
}
} | apache-2.0 | 8d4004472ad41ba87219a21e27d533b1 | 33.943396 | 102 | 0.670168 | 4.850955 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/cognito/src/main/kotlin/com/kotlin/cognito/CreateUserPool.kt | 1 | 1816 | // snippet-sourcedescription:[CreateUserPool.kt demonstrates how to create a user pool for Amazon Cognito.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Cognito]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.cognito
// snippet-start:[cognito.kotlin.create_user_pool.import]
import aws.sdk.kotlin.services.cognitoidentityprovider.CognitoIdentityProviderClient
import aws.sdk.kotlin.services.cognitoidentityprovider.model.CreateUserPoolRequest
import kotlin.system.exitProcess
// snippet-end:[cognito.kotlin.create_user_pool.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage: <userPoolName>
Where:
userPoolName - The ID given to your user pool.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val userPoolName = args[0]
val userPoolId = createPool(userPoolName)
print("The new user pool Id is $userPoolId")
}
// snippet-start:[cognito.kotlin.create_user_pool.main]
suspend fun createPool(userPoolName: String): String? {
val request = CreateUserPoolRequest {
this.poolName = userPoolName
}
CognitoIdentityProviderClient { region = "us-east-1" }.use { cognitoClient ->
val createUserPoolResponse = cognitoClient.createUserPool(request)
return createUserPoolResponse.userPool?.id
}
}
// snippet-end:[cognito.kotlin.create_user_pool.main]
| apache-2.0 | ea5dd881f5a218c15268d6e45681a9ec | 29.859649 | 107 | 0.703194 | 3.815126 | false | false | false | false |
sachil/Essence | app/src/main/java/xyz/sachil/essence/repository/callback/DataBoundaryCallback.kt | 1 | 1841 | package xyz.sachil.essence.repository.callback
import androidx.lifecycle.MutableLiveData
import androidx.paging.PagedList
import kotlinx.coroutines.launch
import xyz.sachil.essence.model.net.bean.TypeData
import xyz.sachil.essence.model.net.response.TypeDataResponse
import xyz.sachil.essence.repository.wrap.DataRequest
import xyz.sachil.essence.util.*
class DataBoundaryCallback(
val request: DataRequest,
val localTotalCount: suspend (DataRequest) -> Int,
val loadFromNet: suspend (DataRequest, Int) -> TypeDataResponse,
val handleTypeData: suspend (List<TypeData>) -> Unit
) : PagedList.BoundaryCallback<TypeData>() {
companion object {
private const val TAG = "DataBoundaryCallback"
}
val loadState = MutableLiveData<LoadState>()
//当初次加载时,如果从room返回的pagedList中没有数据时,会被调用
override fun onZeroItemsLoaded() {
loadState.postValue(Refreshing)
loadItemsFromNet()
}
//当从room返回的pagedList最后一个数据被加载时,会被调用
override fun onItemAtEndLoaded(itemAtEnd: TypeData) {
loadState.postValue(Loading)
loadItemsFromNet()
}
private fun loadItemsFromNet() = request.coroutineScope.launch(request.coroutineContext) {
try {
val totalCount = localTotalCount(request)
val response = loadFromNet(request, totalCount)
if (response.totalCounts == totalCount) {
loadState.postValue(NoMoreData)
} else {
if (response.data.isNotEmpty()) {
handleTypeData(response.data)
}
loadState.postValue(Success)
}
} catch (exception: Exception) {
loadState.postValue(Failed)
throw exception
}
}
} | apache-2.0 | 5598e65bceadb100eb7bd66e476971c1 | 31.481481 | 94 | 0.673702 | 4.62533 | false | false | false | false |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.kt | 1 | 62222 | // 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.execution.impl
import com.intellij.execution.*
import com.intellij.execution.configuration.ConfigurationFactoryEx
import com.intellij.execution.configurations.*
import com.intellij.execution.impl.RunConfigurable.Companion.collectNodesRecursively
import com.intellij.execution.impl.RunConfigurableNodeKind.*
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.options.SettingsEditorConfigurable
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.LabeledComponent.create
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.Trinity
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance
import com.intellij.ui.*
import com.intellij.ui.RowsDnDSupport.RefinedDropSupport.Position.*
import com.intellij.ui.mac.TouchbarDataKeys
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.ArrayUtilRt
import com.intellij.util.IconUtil
import com.intellij.util.PlatformIcons
import com.intellij.util.containers.TreeTraversal
import com.intellij.util.ui.EditableModel
import com.intellij.util.ui.GridBag
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import gnu.trove.THashMap
import gnu.trove.THashSet
import gnu.trove.TObjectIntHashMap
import net.miginfocom.swing.MigLayout
import java.awt.BorderLayout
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.event.KeyEvent
import java.util.*
import java.util.function.ToIntFunction
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.tree.*
private const val TEMPLATE_GROUP_NODE_NAME = "Templates"
internal val TEMPLATES_NODE_USER_OBJECT = object : Any() {
override fun toString() = TEMPLATE_GROUP_NODE_NAME
}
private const val INITIAL_VALUE_KEY = "initialValue"
private val LOG = logger<RunConfigurable>()
internal fun getUserObjectName(userObject: Any): String {
return when {
userObject is ConfigurationType -> userObject.displayName
userObject === TEMPLATES_NODE_USER_OBJECT -> TEMPLATE_GROUP_NODE_NAME
userObject is ConfigurationFactory -> userObject.name
//Folder objects are strings
else -> if (userObject is SingleConfigurationConfigurable<*>) userObject.nameText else (userObject as? RunnerAndConfigurationSettingsImpl)?.name ?: userObject.toString()
}
}
fun createRunConfigurationConfigurable(project: Project): RunConfigurable {
return when {
project.isDefault -> RunConfigurable(project)
else -> ProjectRunConfigurationConfigurable(project)
}
}
open class RunConfigurable @JvmOverloads constructor(protected val project: Project, var runDialog: RunDialogBase? = null) : Configurable, Disposable {
@Volatile private var isDisposed: Boolean = false
val root = DefaultMutableTreeNode("Root")
val treeModel = MyTreeModel(root)
val tree = Tree(treeModel)
private val rightPanel = JPanel(BorderLayout())
private val splitter = JBSplitter("RunConfigurable.dividerProportion", 0.3f)
private var wholePanel: JPanel? = null
private var selectedConfigurable: Configurable? = null
private val recentsLimit = JTextField("5", 2)
private val confirmation = JCheckBox(ExecutionBundle.message("rerun.confirmation.checkbox"), true)
private val confirmationDeletionFromPopup = JCheckBox(ExecutionBundle.message("popup.deletion.confirmation"), true)
private val additionalSettings = ArrayList<Pair<UnnamedConfigurable, JComponent>>()
private val storedComponents = THashMap<ConfigurationFactory, Configurable>()
protected var toolbarDecorator: ToolbarDecorator? = null
private var isFolderCreating = false
protected val toolbarAddAction = MyToolbarAddAction()
private val runDashboardTypesPanel = RunDashboardTypesPanel(project)
private var isModified = false
companion object {
fun collectNodesRecursively(parentNode: DefaultMutableTreeNode, nodes: MutableList<DefaultMutableTreeNode>, vararg allowed: RunConfigurableNodeKind) {
for (i in 0 until parentNode.childCount) {
val child = parentNode.getChildAt(i) as DefaultMutableTreeNode
if (ArrayUtilRt.find(allowed, getKind(child)) != -1) {
nodes.add(child)
}
collectNodesRecursively(child, nodes, *allowed)
}
}
fun getKind(node: DefaultMutableTreeNode?): RunConfigurableNodeKind {
if (node == null) {
return UNKNOWN
}
val userObject = node.userObject
return when (userObject) {
is SingleConfigurationConfigurable<*>, is RunnerAndConfigurationSettings -> {
val settings = getSettings(node) ?: return UNKNOWN
if (settings.isTemporary) TEMPORARY_CONFIGURATION else CONFIGURATION
}
is String -> FOLDER
else -> if (userObject is ConfigurationType) CONFIGURATION_TYPE else UNKNOWN
}
}
}
override fun getDisplayName() = ExecutionBundle.message("run.configurable.display.name")
protected fun initTree() {
tree.isRootVisible = false
tree.showsRootHandles = true
UIUtil.setLineStyleAngled(tree)
TreeUtil.installActions(tree)
TreeSpeedSearch(tree) { o ->
val node = o.lastPathComponent as DefaultMutableTreeNode
val userObject = node.userObject
when (userObject) {
is RunnerAndConfigurationSettingsImpl -> return@TreeSpeedSearch userObject.name
is SingleConfigurationConfigurable<*> -> return@TreeSpeedSearch userObject.nameText
else -> if (userObject is ConfigurationType) {
return@TreeSpeedSearch userObject.displayName
}
else if (userObject is String) {
return@TreeSpeedSearch userObject
}
}
o.toString()
}
tree.cellRenderer = RunConfigurableTreeRenderer(runManager)
addRunConfigurationsToModel(root)
// add templates
val templates = DefaultMutableTreeNode(TEMPLATES_NODE_USER_OBJECT)
for (type in ConfigurationType.CONFIGURATION_TYPE_EP.extensionList) {
val configurationFactories = type.configurationFactories
val typeNode = DefaultMutableTreeNode(type)
templates.add(typeNode)
if (configurationFactories.size != 1) {
for (factory in configurationFactories) {
typeNode.add(DefaultMutableTreeNode(factory))
}
}
}
if (templates.childCount > 0) {
root.add(templates)
if (project.isDefault) {
SwingUtilities.invokeLater {
expandTemplatesNode(templates)
}
}
}
tree.addTreeSelectionListener {
val selectionPath = tree.selectionPath
if (selectionPath != null) {
val node = selectionPath.lastPathComponent as DefaultMutableTreeNode
val userObject = getSafeUserObject(node)
if (userObject is SingleConfigurationConfigurable<*>) {
@Suppress("UNCHECKED_CAST")
updateRightPanel(userObject as SingleConfigurationConfigurable<RunConfiguration>)
}
else if (userObject is String) {
showFolderField(node, userObject)
}
else if (userObject is ConfigurationFactory) {
showTemplateConfigurable(userObject)
}
else if (userObject === TEMPLATES_NODE_USER_OBJECT) {
drawPressAddButtonMessage(null)
}
else if (userObject is ConfigurationType) {
val parent = node.parent as DefaultMutableTreeNode
if (parent.isRoot && !project.isDefault) {
drawPressAddButtonMessage(userObject)
}
else {
val factories = userObject.configurationFactories
if (factories.size == 1) {
showTemplateConfigurable(factories[0])
}
else {
drawPressAddButtonMessage(userObject)
}
}
}
}
updateDialog()
}
tree.registerKeyboardAction({ clickDefaultButton() }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED)
sortTopLevelBranches()
(tree.model as DefaultTreeModel).reload()
}
protected open fun addRunConfigurationsToModel(model: DefaultMutableTreeNode) {
}
fun selectConfigurableOnShow(option: Boolean): RunConfigurable {
if (!option) {
return this
}
SwingUtilities.invokeLater {
if (isDisposed) {
return@invokeLater
}
tree.requestFocusInWindow()
val settings = runManager.selectedConfiguration
if (settings != null) {
if (selectConfiguration(settings.configuration)) {
return@invokeLater
}
}
else {
selectedConfigurable = null
}
drawPressAddButtonMessage(null)
}
return this
}
private fun selectConfiguration(configuration: RunConfiguration): Boolean {
val enumeration = root.breadthFirstEnumeration()
while (enumeration.hasMoreElements()) {
val node = enumeration.nextElement() as DefaultMutableTreeNode
var userObject = node.userObject
if (userObject is SettingsEditorConfigurable<*>) {
userObject = userObject.settings
}
if (userObject is RunnerAndConfigurationSettingsImpl) {
val otherConfiguration = (userObject as RunnerAndConfigurationSettings).configuration
if (otherConfiguration.factory?.type?.id == configuration.factory?.type?.id && otherConfiguration.name == configuration.name) {
TreeUtil.selectInTree(node, true, tree)
return true
}
}
}
return false
}
private fun showTemplateConfigurable(factory: ConfigurationFactory) {
var configurable: Configurable? = storedComponents[factory]
if (configurable == null) {
configurable = TemplateConfigurable(runManager.getConfigurationTemplate(factory))
storedComponents.put(factory, configurable)
configurable.reset()
}
updateRightPanel(configurable)
}
private fun showFolderField(node: DefaultMutableTreeNode, folderName: String) {
rightPanel.removeAll()
val p = JPanel(MigLayout("ins ${toolbarDecorator!!.actionsPanel.height} 5 0 0, flowx"))
val textField = JTextField(folderName)
textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
node.userObject = textField.text
treeModel.reload(node)
}
})
textField.addActionListener { getGlobalInstance().doWhenFocusSettlesDown { getGlobalInstance().requestFocus(tree, true) } }
p.add(JLabel("Folder name:"), "gapright 5")
p.add(textField, "pushx, growx, wrap")
p.add(JLabel(ExecutionBundle.message("run.configuration.rename.folder.disclaimer")), "gaptop 5, spanx 2")
rightPanel.add(p)
rightPanel.revalidate()
rightPanel.repaint()
if (isFolderCreating) {
textField.selectAll()
getGlobalInstance().doWhenFocusSettlesDown { getGlobalInstance().requestFocus(textField, true) }
}
}
private fun getSafeUserObject(node: DefaultMutableTreeNode): Any {
val userObject = node.userObject
if (userObject is RunnerAndConfigurationSettingsImpl) {
val configurationConfigurable = SingleConfigurationConfigurable.editSettings<RunConfiguration>(userObject as RunnerAndConfigurationSettings, null)
installUpdateListeners(configurationConfigurable)
node.userObject = configurationConfigurable
return configurationConfigurable
}
return userObject
}
fun updateRightPanel(configurable: Configurable) {
rightPanel.removeAll()
selectedConfigurable = configurable
val configurableComponent = configurable.createComponent()
rightPanel.add(BorderLayout.CENTER, configurableComponent)
if (configurable is SingleConfigurationConfigurable<*>) {
rightPanel.add(configurable.validationComponent, BorderLayout.SOUTH)
ApplicationManager.getApplication().invokeLater { configurable.updateWarning() }
if (configurableComponent != null) {
val dataProvider = DataManager.getDataProvider(configurableComponent)
if (dataProvider != null) {
DataManager.registerDataProvider(rightPanel, dataProvider)
}
}
}
setupDialogBounds()
}
private fun sortTopLevelBranches() {
val expandedPaths = TreeUtil.collectExpandedPaths(tree)
TreeUtil.sortRecursively(root) { o1, o2 ->
val userObject1 = o1.userObject
val userObject2 = o2.userObject
when {
userObject1 is ConfigurationType && userObject2 is ConfigurationType -> (userObject1).displayName.compareTo(userObject2.displayName, true)
userObject1 === TEMPLATES_NODE_USER_OBJECT && userObject2 is ConfigurationType -> 1
userObject2 === TEMPLATES_NODE_USER_OBJECT && userObject1 is ConfigurationType -> - 1
else -> 0
}
}
TreeUtil.restoreExpandedPaths(tree, expandedPaths)
}
private fun update() {
updateDialog()
val selectionPath = tree.selectionPath
if (selectionPath != null) {
val node = selectionPath.lastPathComponent as DefaultMutableTreeNode
treeModel.reload(node)
}
}
private fun installUpdateListeners(info: SingleConfigurationConfigurable<RunConfiguration>) {
var changed = false
info.editor.addSettingsEditorListener { editor ->
update()
val configuration = info.configuration
if (configuration is LocatableConfiguration) {
if (configuration.isGeneratedName && !changed) {
try {
val snapshot = editor.snapshot.configuration as LocatableConfiguration
val generatedName = snapshot.suggestedName()
if (generatedName != null && generatedName.isNotEmpty()) {
info.nameText = generatedName
changed = false
}
}
catch (ignore: ConfigurationException) {
}
}
}
setupDialogBounds()
}
info.addNameListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
changed = true
update()
}
})
info.addSharedListener {
changed = true
update()
}
}
private fun drawPressAddButtonMessage(configurationType: ConfigurationType?) {
val panel = JPanel(BorderLayout())
createTipPanelAboutAddingNewRunConfiguration(configurationType)?.let {
panel.add(it, BorderLayout.CENTER)
}
if (configurationType == null) {
val settingsPanel = JPanel(GridBagLayout())
val grid = GridBag().setDefaultAnchor(GridBagConstraints.NORTHWEST)
for (each in additionalSettings) {
settingsPanel.add(each.second, grid.nextLine().next())
}
settingsPanel.add(createSettingsPanel(), grid.nextLine().next())
val settingsWrapper = JPanel(BorderLayout())
settingsWrapper.add(settingsPanel, BorderLayout.WEST)
settingsWrapper.add(Box.createGlue(), BorderLayout.CENTER)
val wrapper = JPanel(BorderLayout())
wrapper.add(runDashboardTypesPanel, BorderLayout.CENTER)
runDashboardTypesPanel.addChangeListener(this::defaultsSettingsChanged)
runDashboardTypesPanel.border = JBUI.Borders.empty(0, 0, 20, 0)
wrapper.add(settingsWrapper, BorderLayout.SOUTH)
panel.add(wrapper, BorderLayout.SOUTH)
}
rightPanel.removeAll()
rightPanel.add(ScrollPaneFactory.createScrollPane(panel, true), BorderLayout.CENTER)
rightPanel.revalidate()
rightPanel.repaint()
}
protected open fun createTipPanelAboutAddingNewRunConfiguration(configurationType: ConfigurationType?): JComponent? = null
protected open fun createLeftPanel(): JComponent {
initTree()
val panel = ScrollPaneFactory.createScrollPane(tree)
panel.border = IdeBorderFactory.createBorder(SideBorder.ALL)
return panel
}
private fun defaultsSettingsChanged() {
isModified = recentsLimit.text != recentsLimit.getClientProperty(INITIAL_VALUE_KEY) ||
confirmation.isSelected != confirmation.getClientProperty(INITIAL_VALUE_KEY) ||
confirmationDeletionFromPopup.isSelected != confirmationDeletionFromPopup.getClientProperty(INITIAL_VALUE_KEY) ||
runDashboardTypesPanel.isModified()
}
private fun createSettingsPanel(): JPanel {
val bottomPanel = JPanel(GridBagLayout())
val g = GridBag().setDefaultAnchor(GridBagConstraints.WEST)
bottomPanel.add(confirmation, g.nextLine().coverLine())
bottomPanel.add(confirmationDeletionFromPopup, g.nextLine().coverLine())
bottomPanel.add(create(recentsLimit, ExecutionBundle.message("temporary.configurations.limit"), BorderLayout.WEST),
g.nextLine().insets(JBUI.insets(10, 0, 0, 0)))
recentsLimit.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
defaultsSettingsChanged()
}
})
confirmation.addChangeListener {
defaultsSettingsChanged()
}
confirmationDeletionFromPopup.addChangeListener {
defaultsSettingsChanged()
}
return bottomPanel
}
private val selectedConfigurationType: ConfigurationType?
get() {
val configurationTypeNode = selectedConfigurationTypeNode
return if (configurationTypeNode != null) configurationTypeNode.userObject as ConfigurationType else null
}
override fun createComponent(): JComponent? {
for (each in RunConfigurationsSettings.EXTENSION_POINT.getExtensions(project)) {
val configurable = each.createConfigurable()
additionalSettings.add(Pair.create(configurable, configurable.createComponent()))
}
val touchbarActions = DefaultActionGroup(toolbarAddAction)
TouchbarDataKeys.putActionDescriptor(touchbarActions).setShowText(true).isCombineWithDlgButtons = true
wholePanel = JPanel(BorderLayout())
DataManager.registerDataProvider(wholePanel!!) { dataId ->
when (dataId) {
RunConfigurationSelector.KEY.name -> RunConfigurationSelector { configuration -> selectConfiguration(configuration) }
TouchbarDataKeys.ACTIONS_KEY.name -> touchbarActions
CommonDataKeys.PROJECT.name -> project
else -> null
}
}
splitter.firstComponent = createLeftPanel()
splitter.setHonorComponentsMinimumSize(true)
splitter.secondComponent = rightPanel
wholePanel!!.add(splitter, BorderLayout.CENTER)
updateDialog()
val d = wholePanel!!.preferredSize
d.width = Math.max(d.width, 800)
d.height = Math.max(d.height, 600)
wholePanel!!.preferredSize = d
return wholePanel
}
override fun reset() {
val manager = runManager
val config = manager.config
recentsLimit.text = Integer.toString(config.recentsLimit)
recentsLimit.putClientProperty(INITIAL_VALUE_KEY, recentsLimit.text)
confirmation.isSelected = config.isRestartRequiresConfirmation
confirmation.putClientProperty(INITIAL_VALUE_KEY, confirmation.isSelected)
confirmationDeletionFromPopup.isSelected = config.isDeletionFromPopupRequiresConfirmation
confirmationDeletionFromPopup.putClientProperty(INITIAL_VALUE_KEY, confirmationDeletionFromPopup.isSelected)
runDashboardTypesPanel.reset()
for (each in additionalSettings) {
each.first.reset()
}
isModified = false
}
@Throws(ConfigurationException::class)
override fun apply() {
val manager = runManager
manager.fireBeginUpdate()
try {
val settingsToOrder = TObjectIntHashMap<RunnerAndConfigurationSettings>()
var order = 0
val toDeleteSettings = THashSet(manager.allSettings)
val selectedSettings = selectedSettings
for (i in 0 until root.childCount) {
val node = root.getChildAt(i) as DefaultMutableTreeNode
val userObject = node.userObject
if (userObject is ConfigurationType) {
for (bean in applyByType(node, userObject, selectedSettings)) {
settingsToOrder.put(bean.settings, order++)
toDeleteSettings.remove(bean.settings)
}
}
}
manager.removeConfigurations(toDeleteSettings)
val recentLimit = Math.max(RunManagerConfig.MIN_RECENT_LIMIT, StringUtil.parseInt(recentsLimit.text, 0))
if (manager.config.recentsLimit != recentLimit) {
manager.config.recentsLimit = recentLimit
manager.checkRecentsLimit()
}
recentsLimit.text = recentLimit.toString()
recentsLimit.putClientProperty(INITIAL_VALUE_KEY, recentsLimit.text)
manager.config.isRestartRequiresConfirmation = confirmation.isSelected
confirmation.putClientProperty(INITIAL_VALUE_KEY, confirmation.isSelected)
manager.config.isDeletionFromPopupRequiresConfirmation = confirmationDeletionFromPopup.isSelected
confirmationDeletionFromPopup.putClientProperty(INITIAL_VALUE_KEY, confirmationDeletionFromPopup.isSelected)
runDashboardTypesPanel.apply()
for (configurable in storedComponents.values) {
if (configurable.isModified) {
configurable.apply()
}
}
additionalSettings.forEach { it.first.apply() }
manager.setOrder(Comparator.comparingInt(ToIntFunction { settingsToOrder.get(it) }), isApplyAdditionalSortByTypeAndGroup = false)
}
finally {
manager.fireEndUpdate()
}
updateActiveConfigurationFromSelected()
isModified = false
tree.repaint()
}
fun updateActiveConfigurationFromSelected() {
val selectedConfigurable = selectedConfigurable
if (selectedConfigurable is SingleConfigurationConfigurable<*>) {
runManager.selectedConfiguration = selectedConfigurable.settings
}
}
@Throws(ConfigurationException::class)
private fun applyByType(typeNode: DefaultMutableTreeNode,
type: ConfigurationType,
selectedSettings: RunnerAndConfigurationSettings?): List<RunConfigurationBean> {
var indexToMove = -1
val configurationBeans = ArrayList<RunConfigurationBean>()
val names = THashSet<String>()
val configurationNodes = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION)
for (node in configurationNodes) {
val userObject = node.userObject
var configurationBean: RunConfigurationBean? = null
var settings: RunnerAndConfigurationSettings? = null
if (userObject is SingleConfigurationConfigurable<*>) {
settings = userObject.settings
applyConfiguration(typeNode, userObject)
configurationBean = RunConfigurationBean(userObject)
}
else if (userObject is RunnerAndConfigurationSettingsImpl) {
settings = userObject
configurationBean = RunConfigurationBean(settings)
}
if (configurationBean != null) {
val configurable = configurationBean.configurable
val nameText = if (configurable != null) configurable.nameText else configurationBean.settings.name
if (!names.add(nameText)) {
TreeUtil.selectNode(tree, node)
throw ConfigurationException(type.displayName + " with name \'" + nameText + "\' already exists")
}
configurationBeans.add(configurationBean)
if (settings === selectedSettings) {
indexToMove = configurationBeans.size - 1
}
}
}
val folderNodes = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(typeNode, folderNodes, FOLDER)
names.clear()
for (node in folderNodes) {
val folderName = node.userObject as String
if (folderName.isEmpty()) {
TreeUtil.selectNode(tree, node)
throw ConfigurationException("Folder name shouldn't be empty")
}
if (!names.add(folderName)) {
TreeUtil.selectNode(tree, node)
throw ConfigurationException("Folders name \'$folderName\' is duplicated")
}
}
// try to apply all
for (bean in configurationBeans) {
applyConfiguration(typeNode, bean.configurable)
}
// just saved as 'stable' configuration shouldn't stay between temporary ones (here we order model to save)
var shift = 0
if (selectedSettings != null && selectedSettings.type === type) {
shift = adjustOrder()
}
if (shift != 0 && indexToMove != -1) {
configurationBeans.add(indexToMove - shift, configurationBeans.removeAt(indexToMove))
}
return configurationBeans
}
private fun getConfigurationTypeNode(type: ConfigurationType): DefaultMutableTreeNode? {
for (i in 0 until root.childCount) {
val node = root.getChildAt(i) as DefaultMutableTreeNode
if (node.userObject === type) {
return node
}
}
return null
}
@Throws(ConfigurationException::class)
private fun applyConfiguration(typeNode: DefaultMutableTreeNode, configurable: SingleConfigurationConfigurable<*>?) {
try {
if (configurable != null && configurable.isModified) {
configurable.apply()
}
}
catch (e: ConfigurationException) {
for (i in 0 until typeNode.childCount) {
val node = typeNode.getChildAt(i) as DefaultMutableTreeNode
if (configurable == node.userObject) {
TreeUtil.selectNode(tree, node)
break
}
}
throw e
}
}
override fun isModified(): Boolean {
if (isModified) {
return true
}
val runManager = runManager
val allSettings = runManager.allSettings
var currentSettingCount = 0
for (i in 0 until root.childCount) {
val typeNode = root.getChildAt(i) as DefaultMutableTreeNode
val configurationType = typeNode.userObject as? ConfigurationType ?: continue
val configurationNodes = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION)
val allTypeSettings = allSettings.filter { it.type == configurationType }
if (allTypeSettings.size != configurationNodes.size) {
return true
}
var currentTypeSettingsCount = 0
for (configurationNode in configurationNodes) {
val userObject = configurationNode.userObject
val settings: RunnerAndConfigurationSettings
if (userObject is SingleConfigurationConfigurable<*>) {
if (userObject.isModified) {
return true
}
settings = userObject.settings
}
else if (userObject is RunnerAndConfigurationSettings) {
settings = userObject
}
else {
continue
}
currentSettingCount++
val index = currentTypeSettingsCount++
// we compare by instance, equals is not implemented and in any case object modification is checked by other logic
// we compare by index among current types settings because indexes among all configurations may differ
// since temporary configurations are stored in the end
if (allTypeSettings.size <= index || allTypeSettings.get(index) !== settings) {
return true
}
}
}
return allSettings.size != currentSettingCount || storedComponents.values.any { it.isModified } || additionalSettings.any { it.first.isModified }
}
override fun disposeUIResources() {
Disposer.dispose(this)
}
override fun dispose() {
isDisposed = true
storedComponents.values.forEach { it.disposeUIResources() }
storedComponents.clear()
additionalSettings.forEach { it.first.disposeUIResources() }
TreeUtil.treeNodeTraverser(root)
.traverse(TreeTraversal.PRE_ORDER_DFS)
.processEach { node ->
((node as? DefaultMutableTreeNode)?.userObject as? SingleConfigurationConfigurable<*>)?.disposeUIResources()
true
}
rightPanel.removeAll()
splitter.dispose()
}
private fun updateDialog() {
val runDialog = runDialog
val executor = runDialog?.executor ?: return
val buffer = StringBuilder()
buffer.append(executor.id)
val configuration = selectedConfiguration
if (configuration != null) {
buffer.append(" - ")
buffer.append(configuration.nameText)
}
runDialog.setOKActionEnabled(canRunConfiguration(configuration, executor))
runDialog.setTitle(buffer.toString())
}
private fun setupDialogBounds() {
SwingUtilities.invokeLater { UIUtil.setupEnclosingDialogBounds(wholePanel!!) }
}
private val selectedConfiguration: SingleConfigurationConfigurable<RunConfiguration>?
get() {
val selectionPath = tree.selectionPath
if (selectionPath != null) {
val treeNode = selectionPath.lastPathComponent as DefaultMutableTreeNode
val userObject = treeNode.userObject
if (userObject is SingleConfigurationConfigurable<*>) {
@Suppress("UNCHECKED_CAST")
return userObject as SingleConfigurationConfigurable<RunConfiguration>
}
}
return null
}
open val runManager: RunManagerImpl
get() = RunManagerImpl.getInstanceImpl(project)
override fun getHelpTopic(): String? {
return selectedConfigurationType?.helpTopic ?: "reference.dialogs.rundebug"
}
private fun clickDefaultButton() {
runDialog?.clickDefaultButton()
}
private val selectedConfigurationTypeNode: DefaultMutableTreeNode?
get() {
val selectionPath = tree.selectionPath
var node: DefaultMutableTreeNode? = if (selectionPath != null) selectionPath.lastPathComponent as DefaultMutableTreeNode else null
while (node != null) {
val userObject = node.userObject
if (userObject is ConfigurationType) {
return node
}
node = node.parent as? DefaultMutableTreeNode
}
return null
}
private fun getNode(row: Int) = tree.getPathForRow(row).lastPathComponent as DefaultMutableTreeNode
fun getAvailableDropPosition(direction: Int): Trinity<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>? {
val rows = tree.selectionRows
if (rows == null || rows.size != 1) {
return null
}
val oldIndex = rows[0]
var newIndex = oldIndex + direction
if (!getKind(tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode).supportsDnD()) {
return null
}
while (newIndex > 0 && newIndex < tree.rowCount) {
val targetPath = tree.getPathForRow(newIndex)
val allowInto = getKind(targetPath.lastPathComponent as DefaultMutableTreeNode) == FOLDER && !tree.isExpanded(targetPath)
val position = when {
allowInto && treeModel.isDropInto(tree, oldIndex, newIndex) -> INTO
direction > 0 -> BELOW
else -> ABOVE
}
val oldNode = getNode(oldIndex)
val newNode = getNode(newIndex)
if (oldNode.parent !== newNode.parent && getKind(newNode) != FOLDER) {
var copy = position
if (position == BELOW) {
copy = ABOVE
}
else if (position == ABOVE) {
copy = BELOW
}
if (treeModel.canDrop(oldIndex, newIndex, copy)) {
return Trinity.create(oldIndex, newIndex, copy)
}
}
if (treeModel.canDrop(oldIndex, newIndex, position)) {
return Trinity.create(oldIndex, newIndex, position)
}
when {
position == BELOW && newIndex < tree.rowCount - 1 && treeModel.canDrop(oldIndex, newIndex + 1, ABOVE) -> return Trinity.create(oldIndex, newIndex + 1, ABOVE)
position == ABOVE && newIndex > 1 && treeModel.canDrop(oldIndex, newIndex - 1, BELOW) -> return Trinity.create(oldIndex, newIndex - 1, BELOW)
position == BELOW && treeModel.canDrop(oldIndex, newIndex, ABOVE) -> return Trinity.create(oldIndex, newIndex, ABOVE)
position == ABOVE && treeModel.canDrop(oldIndex, newIndex, BELOW) -> return Trinity.create(oldIndex, newIndex, BELOW)
else -> newIndex += direction
}
}
return null
}
private fun createNewConfiguration(settings: RunnerAndConfigurationSettings,
node: DefaultMutableTreeNode?,
selectedNode: DefaultMutableTreeNode?): SingleConfigurationConfigurable<RunConfiguration> {
val configurationConfigurable = SingleConfigurationConfigurable.editSettings<RunConfiguration>(settings, null)
installUpdateListeners(configurationConfigurable)
val nodeToAdd = DefaultMutableTreeNode(configurationConfigurable)
treeModel.insertNodeInto(nodeToAdd, node!!, if (selectedNode != null) node.getIndex(selectedNode) + 1 else node.childCount)
TreeUtil.selectNode(tree, nodeToAdd)
return configurationConfigurable
}
fun createNewConfiguration(factory: ConfigurationFactory): SingleConfigurationConfigurable<RunConfiguration> {
var typeNode = getConfigurationTypeNode(factory.type)
if (typeNode == null) {
typeNode = DefaultMutableTreeNode(factory.type)
root.add(typeNode)
sortTopLevelBranches()
(tree.model as DefaultTreeModel).reload()
}
val selectedNode = tree.selectionPath?.lastPathComponent as? DefaultMutableTreeNode
var node = typeNode
if (selectedNode != null && typeNode.isNodeDescendant(selectedNode)) {
node = selectedNode
if (getKind(node).isConfiguration) {
node = node.parent as DefaultMutableTreeNode
}
}
val settings = runManager.createConfiguration("", factory)
val configuration = settings.configuration
configuration.name = createUniqueName(typeNode, suggestName(configuration), CONFIGURATION, TEMPORARY_CONFIGURATION)
(configuration as? LocatableConfigurationBase<*>)?.setNameChangedByUser(false)
callNewConfigurationCreated(factory, configuration)
return createNewConfiguration(settings, node, selectedNode)
}
private fun suggestName(configuration: RunConfiguration): String? {
if (configuration is LocatableConfiguration) {
val name = configuration.suggestedName()
if (name != null && name.isNotEmpty()) {
return name
}
}
return null
}
protected inner class MyToolbarAddAction : AnAction(ExecutionBundle.message("add.new.run.configuration.action2.name"),
ExecutionBundle.message("add.new.run.configuration.action2.name"),
IconUtil.getAddIcon()), AnActionButtonRunnable {
init {
registerCustomShortcutSet(CommonShortcuts.INSERT, tree)
}
override fun actionPerformed(e: AnActionEvent) {
showAddPopup(true)
}
override fun run(button: AnActionButton) {
showAddPopup(true)
}
private fun showAddPopup(showApplicableTypesOnly: Boolean) {
val allTypes = ConfigurationType.CONFIGURATION_TYPE_EP.extensionList
val configurationTypes: MutableList<ConfigurationType?> = getTypesToShow(showApplicableTypesOnly, allTypes).toMutableList()
configurationTypes.sortWith(kotlin.Comparator { type1, type2 -> compareTypesForUi(type1!!, type2!!) })
val hiddenCount = allTypes.size - configurationTypes.size
if (hiddenCount > 0) {
configurationTypes.add(null)
}
val popup = NewRunConfigurationPopup.createAddPopup(configurationTypes,
ExecutionBundle.message("show.irrelevant.configurations.action.name",
hiddenCount),
{ factory -> createNewConfiguration(factory) }, selectedConfigurationType,
{ showAddPopup(false) }, true)
//new TreeSpeedSearch(myTree);
popup.showUnderneathOf(toolbarDecorator!!.actionsPanel)
}
private fun getTypesToShow(showApplicableTypesOnly: Boolean, allTypes: List<ConfigurationType>): List<ConfigurationType> {
if (showApplicableTypesOnly) {
val applicableTypes = allTypes.filter { configurationType -> configurationType.configurationFactories.any { it.isApplicable(project) } }
if (applicableTypes.size < (allTypes.size - 3)) {
return applicableTypes
}
}
return allTypes
}
}
protected inner class MyRemoveAction : AnAction(ExecutionBundle.message("remove.run.configuration.action.name"),
ExecutionBundle.message("remove.run.configuration.action.name"),
IconUtil.getRemoveIcon()), AnActionButtonRunnable, AnActionButtonUpdater {
init {
registerCustomShortcutSet(CommonShortcuts.getDelete(), tree)
}
override fun actionPerformed(e: AnActionEvent) {
doRemove()
}
override fun run(button: AnActionButton) {
doRemove()
}
private fun doRemove() {
val selections = tree.selectionPaths
tree.clearSelection()
var nodeIndexToSelect = -1
var parentToSelect: DefaultMutableTreeNode? = null
val changedParents = HashSet<DefaultMutableTreeNode>()
var wasRootChanged = false
for (each in selections!!) {
val node = each.lastPathComponent as DefaultMutableTreeNode
val parent = node.parent as DefaultMutableTreeNode
val kind = getKind(node)
if (!kind.isConfiguration && kind != FOLDER)
continue
if (node.userObject is SingleConfigurationConfigurable<*>) {
(node.userObject as SingleConfigurationConfigurable<*>).disposeUIResources()
}
nodeIndexToSelect = parent.getIndex(node)
parentToSelect = parent
treeModel.removeNodeFromParent(node)
changedParents.add(parent)
if (kind == FOLDER) {
val children = ArrayList<DefaultMutableTreeNode>()
for (i in 0 until node.childCount) {
val child = node.getChildAt(i) as DefaultMutableTreeNode
val userObject = getSafeUserObject(child)
if (userObject is SingleConfigurationConfigurable<*>) {
userObject.folderName = null
}
children.add(0, child)
}
var confIndex = 0
for (i in 0 until parent.childCount) {
if (getKind(parent.getChildAt(i) as DefaultMutableTreeNode).isConfiguration) {
confIndex = i
break
}
}
for (child in children) {
if (getKind(child) == CONFIGURATION)
treeModel.insertNodeInto(child, parent, confIndex)
}
confIndex = parent.childCount
for (i in 0 until parent.childCount) {
if (getKind(parent.getChildAt(i) as DefaultMutableTreeNode) == TEMPORARY_CONFIGURATION) {
confIndex = i
break
}
}
for (child in children) {
if (getKind(child) == TEMPORARY_CONFIGURATION) {
treeModel.insertNodeInto(child, parent, confIndex)
}
}
}
if (parent.childCount == 0 && parent.userObject is ConfigurationType) {
changedParents.remove(parent)
wasRootChanged = true
nodeIndexToSelect = root.getIndex(parent)
nodeIndexToSelect = Math.max(0, nodeIndexToSelect - 1)
parentToSelect = root
parent.removeFromParent()
}
}
if (wasRootChanged) {
(tree.model as DefaultTreeModel).reload()
}
else {
for (each in changedParents) {
treeModel.reload(each)
tree.expandPath(TreePath(each))
}
}
selectedConfigurable = null
if (root.childCount == 0) {
drawPressAddButtonMessage(null)
}
else {
if (parentToSelect!!.childCount > 0) {
val nodeToSelect = if (nodeIndexToSelect < parentToSelect.childCount) {
parentToSelect.getChildAt(nodeIndexToSelect)
}
else {
parentToSelect.getChildAt(nodeIndexToSelect - 1)
}
TreeUtil.selectInTree(nodeToSelect as DefaultMutableTreeNode, true, tree)
}
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = isEnabled(e)
}
override fun isEnabled(e: AnActionEvent): Boolean {
var enabled = false
val selections = tree.selectionPaths
if (selections != null) {
for (each in selections) {
val kind = getKind(each.lastPathComponent as DefaultMutableTreeNode)
if (kind.isConfiguration || kind == FOLDER) {
enabled = true
break
}
}
}
return enabled
}
}
protected inner class MyCopyAction : AnAction(ExecutionBundle.message("copy.configuration.action.name"),
ExecutionBundle.message("copy.configuration.action.name"), PlatformIcons.COPY_ICON) {
init {
val action = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_DUPLICATE)
registerCustomShortcutSet(action.shortcutSet, tree)
}
override fun actionPerformed(e: AnActionEvent) {
val configuration = selectedConfiguration!!
try {
val typeNode = selectedConfigurationTypeNode!!
val settings = configuration.createSnapshot(true)
val copyName = createUniqueName(typeNode, configuration.nameText, CONFIGURATION, TEMPORARY_CONFIGURATION)
settings.name = copyName
val factory = settings.factory
@Suppress("UNCHECKED_CAST", "DEPRECATION")
(factory as? ConfigurationFactoryEx<RunConfiguration>)?.onConfigurationCopied(settings.configuration)
(settings.configuration as? ConfigurationCreationListener)?.onConfigurationCopied()
val parentNode = selectedNode?.parent
val node = (if ((parentNode as? DefaultMutableTreeNode)?.userObject is String) parentNode else typeNode) as DefaultMutableTreeNode
val configurable = createNewConfiguration(settings, node, selectedNode)
IdeFocusManager.getInstance(project).requestFocus(configurable.nameTextField, true)
configurable.nameTextField.selectionStart = 0
configurable.nameTextField.selectionEnd = copyName.length
}
catch (e: ConfigurationException) {
Messages.showErrorDialog(toolbarDecorator!!.actionsPanel, e.message, e.title)
}
}
override fun update(e: AnActionEvent) {
val configuration = selectedConfiguration
e.presentation.isEnabled = configuration != null && configuration.configuration.type.isManaged
}
}
protected inner class MySaveAction : AnAction(ExecutionBundle.message("action.name.save.configuration"), null,
AllIcons.Actions.Menu_saveall) {
override fun actionPerformed(e: AnActionEvent) {
val configurationConfigurable = selectedConfiguration
LOG.assertTrue(configurationConfigurable != null)
val originalConfiguration = configurationConfigurable!!.settings
if (originalConfiguration.isTemporary) {
//todo Don't make 'stable' real configurations here but keep the set 'they want to be stable' until global 'Apply' action
runManager.makeStable(originalConfiguration)
adjustOrder()
}
tree.repaint()
}
override fun update(e: AnActionEvent) {
val configuration = selectedConfiguration
e.presentation.isEnabledAndVisible = when (configuration) {
null -> false
else -> configuration.settings.isTemporary
}
}
}
/**
* Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order nodes in JTree only)
* @return shift (positive) for move configuration "up" to other stable configurations. Zero means "there is nothing to change"
*/
private fun adjustOrder(): Int {
val selectionPath = tree.selectionPath ?: return 0
val treeNode = selectionPath.lastPathComponent as DefaultMutableTreeNode
val selectedSettings = getSettings(treeNode)
if (selectedSettings == null || selectedSettings.isTemporary) {
return 0
}
val parent = treeNode.parent as MutableTreeNode
val initialPosition = parent.getIndex(treeNode)
var position = initialPosition
var node: DefaultMutableTreeNode? = treeNode.previousSibling
while (node != null) {
val settings = getSettings(node)
if (settings != null && settings.isTemporary) {
position--
}
else {
break
}
node = node.previousSibling
}
for (i in 0 until initialPosition - position) {
TreeUtil.moveSelectedRow(tree, -1)
}
return initialPosition - position
}
protected inner class MyMoveAction(text: String, description: String?, icon: Icon, private val direction: Int) :
AnAction(text, description, icon), AnActionButtonRunnable, AnActionButtonUpdater {
override fun actionPerformed(e: AnActionEvent) {
doMove()
}
private fun doMove() {
getAvailableDropPosition(direction)?.let {
treeModel.drop(it.first, it.second, it.third)
}
}
override fun run(button: AnActionButton) {
doMove()
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = isEnabled(e)
}
override fun isEnabled(e: AnActionEvent) = getAvailableDropPosition(direction) != null
}
protected inner class MyEditTemplatesAction : AnAction(ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
ExecutionBundle.message("run.configuration.edit.default.configuration.settings.description"),
AllIcons.General.Settings) {
override fun actionPerformed(e: AnActionEvent) {
var templates = TreeUtil.findNodeWithObject(TEMPLATES_NODE_USER_OBJECT, tree.model, root) ?: return
selectedConfigurationType?.let {
templates = TreeUtil.findNodeWithObject(it, tree.model, templates) ?: return
}
expandTemplatesNode(templates as DefaultMutableTreeNode? ?: return)
}
override fun update(e: AnActionEvent) {
var isEnabled = TreeUtil.findNodeWithObject(TEMPLATES_NODE_USER_OBJECT, tree.model, root) != null
val path = tree.selectionPath
if (path != null) {
var o = path.lastPathComponent
if (o is DefaultMutableTreeNode && o.userObject == TEMPLATES_NODE_USER_OBJECT) {
isEnabled = false
}
o = path.parentPath.lastPathComponent
if (o is DefaultMutableTreeNode && o.userObject == TEMPLATES_NODE_USER_OBJECT) {
isEnabled = false
}
}
e.presentation.isEnabled = isEnabled
}
}
private fun expandTemplatesNode(templatesNode: DefaultMutableTreeNode) {
val path = TreeUtil.getPath(root, templatesNode)
tree.expandPath(path)
TreeUtil.selectInTree(templatesNode, true, tree)
tree.scrollPathToVisible(path)
}
protected inner class MyCreateFolderAction : AnAction(ExecutionBundle.message("run.configuration.create.folder.text"),
ExecutionBundle.message("run.configuration.create.folder.description"),
AllIcons.Actions.NewFolder) {
override fun actionPerformed(e: AnActionEvent) {
val type = selectedConfigurationType ?: return
val selectedNodes = selectedNodes
val typeNode = getConfigurationTypeNode(type) ?: return
val folderName = createUniqueName(typeNode, "New Folder", FOLDER)
val folders = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(getConfigurationTypeNode(type)!!, folders, FOLDER)
val folderNode = DefaultMutableTreeNode(folderName)
treeModel.insertNodeInto(folderNode, typeNode, folders.size)
isFolderCreating = true
try {
for (node in selectedNodes) {
val folderRow = tree.getRowForPath(TreePath(folderNode.path))
val rowForPath = tree.getRowForPath(TreePath(node.path))
if (getKind(node).isConfiguration && treeModel.canDrop(rowForPath, folderRow, INTO)) {
treeModel.drop(rowForPath, folderRow, INTO)
}
}
tree.selectionPath = TreePath(folderNode.path)
}
finally {
isFolderCreating = false
}
}
override fun update(e: AnActionEvent) {
var isEnabled = false
var toMove = false
val selectedNodes = selectedNodes
var selectedType: ConfigurationType? = null
for (node in selectedNodes) {
val type = getType(node)
if (selectedType == null) {
selectedType = type
}
else {
if (type != selectedType) {
isEnabled = false
break
}
}
val kind = getKind(node)
if (kind.isConfiguration || kind == CONFIGURATION_TYPE && node.parent === root || kind == FOLDER) {
isEnabled = true
}
if (kind.isConfiguration) {
toMove = true
}
}
e.presentation.text = ExecutionBundle.message("run.configuration.create.folder.description${if (toMove) ".move" else ""}")
e.presentation.isEnabled = isEnabled
}
}
protected inner class MySortFolderAction : AnAction(ExecutionBundle.message("run.configuration.sort.folder.text"),
ExecutionBundle.message("run.configuration.sort.folder.description"),
AllIcons.ObjectBrowser.Sorted), Comparator<DefaultMutableTreeNode> {
override fun compare(node1: DefaultMutableTreeNode, node2: DefaultMutableTreeNode): Int {
val kind1 = getKind(node1)
val kind2 = getKind(node2)
if (kind1 == FOLDER) {
return if (kind2 == FOLDER) node1.parent.getIndex(node1) - node2.parent.getIndex(node2) else -1
}
if (kind2 == FOLDER) {
return 1
}
val name1 = getUserObjectName(node1.userObject)
val name2 = getUserObjectName(node2.userObject)
return when (kind1) {
TEMPORARY_CONFIGURATION -> if (kind2 == TEMPORARY_CONFIGURATION) name1.compareTo(name2) else 1
else -> if (kind2 == TEMPORARY_CONFIGURATION) -1 else name1.compareTo(name2)
}
}
override fun actionPerformed(e: AnActionEvent) {
val selectedNodes = selectedNodes
val foldersToSort = ArrayList<DefaultMutableTreeNode>()
for (node in selectedNodes) {
val kind = getKind(node)
if (kind == CONFIGURATION_TYPE || kind == FOLDER) {
foldersToSort.add(node)
}
}
for (folderNode in foldersToSort) {
val children = ArrayList<DefaultMutableTreeNode>()
for (i in 0 until folderNode.childCount) {
children.add(folderNode.getChildAt(i) as DefaultMutableTreeNode)
}
children.sortWith(this)
for (child in children) {
folderNode.add(child)
}
treeModel.nodeStructureChanged(folderNode)
}
}
override fun update(e: AnActionEvent) {
val selectedNodes = selectedNodes
for (node in selectedNodes) {
val kind = getKind(node)
if (kind == CONFIGURATION_TYPE || kind == FOLDER) {
e.presentation.isEnabled = true
return
}
}
e.presentation.isEnabled = false
}
}
private val selectedNodes: Array<DefaultMutableTreeNode>
get() = tree.getSelectedNodes(DefaultMutableTreeNode::class.java, null)
private val selectedNode: DefaultMutableTreeNode?
get() = tree.getSelectedNodes(DefaultMutableTreeNode::class.java, null).firstOrNull()
private val selectedSettings: RunnerAndConfigurationSettings?
get() {
val selectionPath = tree.selectionPath ?: return null
return getSettings(selectionPath.lastPathComponent as DefaultMutableTreeNode)
}
inner class MyTreeModel(root: TreeNode) : DefaultTreeModel(root), EditableModel, RowsDnDSupport.RefinedDropSupport {
override fun addRow() {}
override fun removeRow(index: Int) {}
override fun exchangeRows(oldIndex: Int, newIndex: Int) {
//Do nothing, use drop() instead
}
//Legacy, use canDrop() instead
override fun canExchangeRows(oldIndex: Int, newIndex: Int) = false
override fun canDrop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position): Boolean {
if (tree.rowCount <= oldIndex || tree.rowCount <= newIndex || oldIndex < 0 || newIndex < 0) {
return false
}
val oldNode = tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode
val newNode = tree.getPathForRow(newIndex).lastPathComponent as DefaultMutableTreeNode
val oldParent = oldNode.parent as DefaultMutableTreeNode
val newParent = newNode.parent as DefaultMutableTreeNode
val oldKind = getKind(oldNode)
val newKind = getKind(newNode)
val oldType = getType(oldNode)
val newType = getType(newNode)
if (oldParent === newParent) {
if (oldNode.previousSibling === newNode && position == BELOW) {
return false
}
if (oldNode.nextSibling === newNode && position == ABOVE) {
return false
}
}
when {
oldType == null -> return false
oldType !== newType -> {
val typeNode = getConfigurationTypeNode(oldType)
if (getKind(oldParent) == FOLDER && typeNode != null && typeNode.nextSibling === newNode && position == ABOVE) {
return true
}
return getKind(oldParent) == CONFIGURATION_TYPE &&
oldKind == FOLDER &&
typeNode != null &&
typeNode.nextSibling === newNode &&
position == ABOVE &&
oldParent.lastChild !== oldNode &&
getKind(oldParent.lastChild as DefaultMutableTreeNode) == FOLDER
}
newParent === oldNode || oldParent === newNode -> return false
oldKind == FOLDER && newKind != FOLDER -> return newKind.isConfiguration &&
position == ABOVE &&
getKind(newParent) == CONFIGURATION_TYPE &&
newIndex > 1 &&
getKind(tree.getPathForRow(newIndex - 1).parentPath.lastPathComponent as DefaultMutableTreeNode) == FOLDER
!oldKind.supportsDnD() || !newKind.supportsDnD() -> return false
oldKind.isConfiguration && newKind == FOLDER && position == ABOVE -> return false
oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == ABOVE -> return false
oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == BELOW -> return false
oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == ABOVE -> return newNode.previousSibling == null ||
getKind(newNode.previousSibling) == CONFIGURATION ||
getKind(newNode.previousSibling) == FOLDER
oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == BELOW -> return newNode.nextSibling == null || getKind(newNode.nextSibling) == TEMPORARY_CONFIGURATION
oldParent === newParent -> //Same parent
if (oldKind.isConfiguration && newKind.isConfiguration) {
return oldKind == newKind//both are temporary or saved
}
else if (oldKind == FOLDER) {
return !tree.isExpanded(newIndex) || position == ABOVE
}
}
return true
}
override fun isDropInto(component: JComponent, oldIndex: Int, newIndex: Int): Boolean {
val oldNode = (tree.getPathForRow(oldIndex) ?: return false).lastPathComponent as DefaultMutableTreeNode
val newNode = (tree.getPathForRow(newIndex) ?: return false).lastPathComponent as DefaultMutableTreeNode
return getKind(oldNode).isConfiguration && getKind(newNode) == FOLDER
}
override fun drop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position) {
val oldNode = tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode
val newNode = tree.getPathForRow(newIndex).lastPathComponent as DefaultMutableTreeNode
var newParent = newNode.parent as DefaultMutableTreeNode
val oldKind = getKind(oldNode)
val wasExpanded = tree.isExpanded(TreePath(oldNode.path))
// drop in folder
if (isDropInto(tree, oldIndex, newIndex)) {
removeNodeFromParent(oldNode)
var index = newNode.childCount
if (oldKind.isConfiguration) {
var middleIndex = newNode.childCount
for (i in 0 until newNode.childCount) {
if (getKind(newNode.getChildAt(i) as DefaultMutableTreeNode) == TEMPORARY_CONFIGURATION) {
//index of first temporary configuration in target folder
middleIndex = i
break
}
}
if (position != INTO) {
if (oldIndex < newIndex) {
index = if (oldKind == CONFIGURATION) 0 else middleIndex
}
else {
index = if (oldKind == CONFIGURATION) middleIndex else newNode.childCount
}
}
else {
index = if (oldKind == TEMPORARY_CONFIGURATION) newNode.childCount else middleIndex
}
}
insertNodeInto(oldNode, newNode, index)
tree.expandPath(TreePath(newNode.path))
}
else {
val type = getType(oldNode)!!
removeNodeFromParent(oldNode)
var index: Int
if (type !== getType(newParent)) {
newParent = getConfigurationTypeNode(type)!!
index = newParent.childCount
}
else {
index = newParent.getIndex(newNode)
if (position == BELOW) {
index++
}
}
insertNodeInto(oldNode, newParent, index)
}
val treePath = TreePath(oldNode.path)
tree.selectionPath = treePath
if (wasExpanded) {
tree.expandPath(treePath)
}
}
override fun insertNodeInto(newChild: MutableTreeNode, parent: MutableTreeNode, index: Int) {
super.insertNodeInto(newChild, parent, index)
if (!getKind(newChild as DefaultMutableTreeNode).isConfiguration) {
return
}
val userObject = getSafeUserObject(newChild)
val newFolderName = if (getKind(parent as DefaultMutableTreeNode) == FOLDER) parent.userObject as String else null
if (userObject is SingleConfigurationConfigurable<*>) {
userObject.folderName = newFolderName
}
}
override fun reload(node: TreeNode?) {
super.reload(node)
val userObject = (node as DefaultMutableTreeNode).userObject
if (userObject is String) {
for (i in 0 until node.childCount) {
val safeUserObject = getSafeUserObject(node.getChildAt(i) as DefaultMutableTreeNode)
if (safeUserObject is SingleConfigurationConfigurable<*>) {
safeUserObject.folderName = userObject
}
}
}
}
private fun getType(treeNode: DefaultMutableTreeNode?): ConfigurationType? {
val userObject = treeNode?.userObject ?: return null
return when (userObject) {
is SingleConfigurationConfigurable<*> -> userObject.configuration.type
is RunnerAndConfigurationSettings -> userObject.type
is ConfigurationType -> userObject
else -> if (treeNode.parent is DefaultMutableTreeNode) getType(treeNode.parent as DefaultMutableTreeNode) else null
}
}
}
}
private fun canRunConfiguration(configuration: SingleConfigurationConfigurable<RunConfiguration>?, executor: Executor): Boolean {
return try {
configuration != null && RunManagerImpl.canRunConfiguration(configuration.createSnapshot(false), executor)
}
catch (e: ConfigurationException) {
false
}
}
private fun createUniqueName(typeNode: DefaultMutableTreeNode, baseName: String?, vararg kinds: RunConfigurableNodeKind): String {
val str = baseName ?: ExecutionBundle.message("run.configuration.unnamed.name.prefix")
val configurationNodes = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(typeNode, configurationNodes, *kinds)
val currentNames = ArrayList<String>()
for (node in configurationNodes) {
val userObject = node.userObject
when (userObject) {
is SingleConfigurationConfigurable<*> -> currentNames.add(userObject.nameText)
is RunnerAndConfigurationSettingsImpl -> currentNames.add((userObject as RunnerAndConfigurationSettings).name)
is String -> currentNames.add(userObject)
}
}
return RunManager.suggestUniqueName(str, currentNames)
}
private fun getType(_node: DefaultMutableTreeNode?): ConfigurationType? {
var node = _node
while (node != null) {
(node.userObject as? ConfigurationType)?.let {
return it
}
node = node.parent as? DefaultMutableTreeNode
}
return null
}
private fun getSettings(treeNode: DefaultMutableTreeNode?): RunnerAndConfigurationSettings? {
if (treeNode == null) {
return null
}
val settings: RunnerAndConfigurationSettings? = null
return when {
treeNode.userObject is SingleConfigurationConfigurable<*> -> (treeNode.userObject as SingleConfigurationConfigurable<*>).settings
treeNode.userObject is RunnerAndConfigurationSettings -> treeNode.userObject as RunnerAndConfigurationSettings
else -> settings
}
}
| apache-2.0 | 66afcb7cc3d2db935ef438ffdfd044f3 | 38.281566 | 188 | 0.678168 | 5.472471 | false | true | false | false |
auricgoldfinger/Memento-Namedays | memento/src/main/java/com/alexstyl/gsc/Sound.kt | 4 | 1227 | package com.alexstyl.gsc
/**
* This class holds all different sounds a single symbol can be associated with.</br>
* <p>H can be associated with the sound X and the sound I</p>
*/
data class Sound(private val soundSymbols: List<Char>) {
fun soundsLike(other: Sound): Boolean {
soundSymbols.forEach { thisSymbol ->
other.soundSymbols.forEach { otherSymbol ->
if (thisSymbol == otherSymbol) {
return true
}
}
}
return false
}
operator fun plus(other: Sound): Sound = Sound(this.soundSymbols + other.soundSymbols)
companion object {
/**
* Combines a series of different sounds into one.
*/
fun flatten(sounds: Iterable<Sound>): Sound {
val fold = sounds.fold<Sound, List<Char>>(emptyList(), { list, name ->
list + name.soundSymbols
})
return Sound(fold)
}
}
}
fun sound(char: Char) = Sound(listOf(char))
fun sound(chars: String): Sound {
val sounds = chars.split(',')
return sound(CharArray(sounds.size, { sounds[it].single() }))
}
fun sound(soundSymbols: CharArray) = Sound(soundSymbols.toList())
| mit | ff4a7533a58d28ee4adb35ee49873bdf | 27.534884 | 90 | 0.586797 | 4.245675 | false | false | false | false |
deso88/TinyGit | src/main/kotlin/hamburg/remme/tinygit/gui/builder/Nodes.kt | 1 | 1033 | package hamburg.remme.tinygit.gui.builder
import javafx.beans.value.ObservableBooleanValue
import javafx.scene.Node
import javafx.scene.control.Tooltip
import javafx.util.Duration
fun <T : Node> T.addClass(vararg styleClass: String): T {
this.styleClass += styleClass
return this
}
fun <T : Node> T.flipX(): T {
scaleX = -1.0
return this
}
fun <T : Node> T.flipY(): T {
scaleY = -1.0
return this
}
fun <T : Node> T.flipXY() = flipX().flipY()
fun <T : Node> T.visibleWhen(observable: ObservableBooleanValue): T {
visibleProperty().bind(observable)
return this
}
fun <T : Node> T.managedWhen(observable: ObservableBooleanValue): T {
managedProperty().bind(observable)
return this
}
fun <T : Node> T.disabledWhen(observable: ObservableBooleanValue): T {
disableProperty().bind(observable)
return this
}
fun <T : Node> T.tooltip(text: String): T {
val tooltip = Tooltip(text)
tooltip.showDelay = Duration.millis(250.0)
Tooltip.install(this, tooltip)
return this
}
| bsd-3-clause | 0a8c18ede1aad0a6681be93ca0664ff4 | 21.955556 | 70 | 0.692159 | 3.466443 | false | false | false | false |
jmfayard/skripts | kotlin/tornado/OkApp.kt | 1 | 1214 | package tornado
import javafx.scene.layout.GridPane
import tornadofx.App
import tornadofx.Stylesheet
import tornadofx.View
import tornadofx.box
import tornadofx.cssclass
import tornadofx.label
import tornadofx.px
import tornadofx.row
import tornadofx.vbox
class OkApp : App(DemoTableView::class, OkStyles::class)
class OkStyles : Stylesheet() {
companion object {
val list by cssclass()
}
init {
select(list) {
padding = box(15.px)
vgap = 7.px
hgap = 10.px
}
}
}
class DemoTableView : View() {
override val root = GridPane()
val mapTableContent = mapOf(Pair("item 1", 5), Pair("item 2", 10), Pair("item 3", 6))
init {
with(root) {
row {
vbox {
label("Tableview from a map")
// tableview(FXCollections.observableArrayList<Map.Entry<String, Int>>(mapTableContent.entries)) {
// column("Item", Map.Entry<String, Int>::key)
// column("Count", Map.Entry<String, Int>::value)
// resizeColumnsToFitContent()
// }
}
}
}
}
}
| apache-2.0 | 9f29e6aeb1fed87d8935b768bbc9cb9a | 23.77551 | 117 | 0.553542 | 4.244755 | false | false | false | false |
google/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/XmlReader.kt | 3 | 37067 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("XmlReader")
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.ide.plugins
import com.intellij.openapi.components.ComponentConfig
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.ExtensionPointDescriptor
import com.intellij.openapi.extensions.LoadingOrder
import com.intellij.openapi.extensions.PluginId
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.messages.ListenerDescriptor
import com.intellij.util.xml.dom.NoOpXmlInterner
import com.intellij.util.xml.dom.XmlInterner
import com.intellij.util.xml.dom.createNonCoalescingXmlStreamReader
import com.intellij.util.xml.dom.readXmlAsModel
import org.codehaus.stax2.XMLStreamReader2
import org.codehaus.stax2.typed.TypedXMLStreamException
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.io.InputStream
import java.text.ParseException
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
import javax.xml.stream.XMLStreamConstants
import javax.xml.stream.XMLStreamException
import javax.xml.stream.XMLStreamReader
import javax.xml.stream.events.XMLEvent
@ApiStatus.Internal const val PACKAGE_ATTRIBUTE = "package"
@ApiStatus.Internal const val IMPLEMENTATION_DETAIL_ATTRIBUTE = "implementation-detail"
@ApiStatus.Experimental const val ON_DEMAND_ATTRIBUTE = "on-demand"
private const val defaultXPointerValue = "xpointer(/idea-plugin/*)"
/**
* Do not use [java.io.BufferedInputStream] - buffer is used internally already.
*/
fun readModuleDescriptor(input: InputStream,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?,
locationSource: String?): RawPluginDescriptor {
return readModuleDescriptor(reader = createNonCoalescingXmlStreamReader(input, locationSource),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto)
}
fun readModuleDescriptor(input: ByteArray,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?,
locationSource: String?): RawPluginDescriptor {
return readModuleDescriptor(reader = createNonCoalescingXmlStreamReader(input, locationSource),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto)
}
internal fun readModuleDescriptor(reader: XMLStreamReader2,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?): RawPluginDescriptor {
try {
if (reader.eventType != XMLStreamConstants.START_DOCUMENT) {
throw XMLStreamException("State ${XMLStreamConstants.START_DOCUMENT} is expected, " +
"but current state is ${getEventTypeString(reader.eventType)}", reader.location)
}
val descriptor = readInto ?: RawPluginDescriptor()
@Suppress("ControlFlowWithEmptyBody")
while (reader.next() != XMLStreamConstants.START_ELEMENT) {
}
if (!reader.isStartElement) {
return descriptor
}
readRootAttributes(reader, descriptor)
reader.consumeChildElements { localName ->
readRootElementChild(reader = reader,
descriptor = descriptor,
readContext = readContext,
localName = localName,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase)
assert(reader.isEndElement)
}
return descriptor
}
finally {
reader.closeCompletely()
}
}
@TestOnly
fun readModuleDescriptorForTest(input: ByteArray): RawPluginDescriptor {
return readModuleDescriptor(
input = input,
readContext = object : ReadModuleContext {
override val interner = NoOpXmlInterner
override val isMissingIncludeIgnored
get() = false
},
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
dataLoader = object : DataLoader {
override val pool: ZipFilePool? = null
override fun load(path: String) = throw UnsupportedOperationException()
override fun toString() = ""
},
includeBase = null,
readInto = null,
locationSource = null,
)
}
private fun readRootAttributes(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
PACKAGE_ATTRIBUTE -> descriptor.`package` = getNullifiedAttributeValue(reader, i)
"url" -> descriptor.url = getNullifiedAttributeValue(reader, i)
"use-idea-classloader" -> descriptor.isUseIdeaClassLoader = reader.getAttributeAsBoolean(i)
"allow-bundled-update" -> descriptor.isBundledUpdateAllowed = reader.getAttributeAsBoolean(i)
IMPLEMENTATION_DETAIL_ATTRIBUTE -> descriptor.implementationDetail = reader.getAttributeAsBoolean(i)
ON_DEMAND_ATTRIBUTE -> descriptor.onDemand = reader.getAttributeAsBoolean(i)
"require-restart" -> descriptor.isRestartRequired = reader.getAttributeAsBoolean(i)
"version" -> {
// internalVersionString - why it is not used, but just checked?
getNullifiedAttributeValue(reader, i)?.let {
try {
it.toInt()
}
catch (e: NumberFormatException) {
LOG.error("Cannot parse version: $it'", e)
}
}
}
}
}
}
/**
* Keep in sync with KotlinPluginUtil.KNOWN_KOTLIN_PLUGIN_IDS
*/
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog", "SSBasedInspection")
private val KNOWN_KOTLIN_PLUGIN_IDS = HashSet(Arrays.asList(
"org.jetbrains.kotlin",
"com.intellij.appcode.kmm",
"org.jetbrains.kotlin.native.appcode"
))
private fun readRootElementChild(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
localName: String,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?) {
when (localName) {
"id" -> {
if (descriptor.id == null) {
descriptor.id = getNullifiedContent(reader)
}
else if (!KNOWN_KOTLIN_PLUGIN_IDS.contains(descriptor.id) && descriptor.id != "com.intellij") {
// no warn and no redefinition for kotlin - compiler.xml is a known issue
LOG.warn("id redefinition (${reader.locationInfo.location})")
descriptor.id = getNullifiedContent(reader)
}
else {
reader.skipElement()
}
}
"name" -> descriptor.name = getNullifiedContent(reader)
"category" -> descriptor.category = getNullifiedContent(reader)
"version" -> {
// kotlin includes compiler.xml that due to some reasons duplicates version
if (descriptor.version == null || !KNOWN_KOTLIN_PLUGIN_IDS.contains(descriptor.id)) {
descriptor.version = getNullifiedContent(reader)
}
else {
reader.skipElement()
}
}
"description" -> descriptor.description = getNullifiedContent(reader)
"change-notes" -> descriptor.changeNotes = getNullifiedContent(reader)
"resource-bundle" -> descriptor.resourceBundleBaseName = getNullifiedContent(reader)
"product-descriptor" -> readProduct(reader, descriptor)
"module" -> {
findAttributeValue(reader, "value")?.let { moduleName ->
var modules = descriptor.modules
if (modules == null) {
descriptor.modules = Collections.singletonList(PluginId.getId(moduleName))
}
else {
if (modules.size == 1) {
val singleton = modules
modules = ArrayList(4)
modules.addAll(singleton)
descriptor.modules = modules
}
modules.add(PluginId.getId(moduleName))
}
}
reader.skipElement()
}
"idea-version" -> {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"since-build" -> descriptor.sinceBuild = getNullifiedAttributeValue(reader, i)
"until-build" -> descriptor.untilBuild = getNullifiedAttributeValue(reader, i)
}
}
reader.skipElement()
}
"vendor" -> {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"email" -> descriptor.vendorEmail = getNullifiedAttributeValue(reader, i)
"url" -> descriptor.vendorUrl = getNullifiedAttributeValue(reader, i)
}
}
descriptor.vendor = getNullifiedContent(reader)
}
"incompatible-with" -> {
getNullifiedContent(reader)?.let {
var list = descriptor.incompatibilities
if (list == null) {
list = ArrayList()
descriptor.incompatibilities = list
}
list.add(PluginId.getId(it))
}
}
"application-components" -> readComponents(reader, descriptor.appContainerDescriptor)
"project-components" -> readComponents(reader, descriptor.projectContainerDescriptor)
"module-components" -> readComponents(reader, descriptor.moduleContainerDescriptor)
"applicationListeners" -> readListeners(reader, descriptor.appContainerDescriptor)
"projectListeners" -> readListeners(reader, descriptor.projectContainerDescriptor)
"extensions" -> readExtensions(reader, descriptor, readContext.interner)
"extensionPoints" -> readExtensionPoints(reader = reader,
descriptor = descriptor,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase)
"content" -> readContent(reader = reader,
descriptor = descriptor,
readContext = readContext)
"dependencies" -> readDependencies(reader = reader, descriptor = descriptor, readContext = readContext)
"depends" -> readOldDepends(reader, descriptor)
"actions" -> readActions(descriptor, reader, readContext)
"include" -> readInclude(reader = reader,
readInto = descriptor,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
allowedPointer = defaultXPointerValue)
"helpset" -> {
// deprecated and not used element
reader.skipElement()
}
"locale" -> {
// not used in descriptor
reader.skipElement()
}
else -> {
LOG.error("Unknown element: $localName")
reader.skipElement()
}
}
if (!reader.isEndElement) {
throw XMLStreamException("Unexpected state (" +
"expected=END_ELEMENT, " +
"actual=${getEventTypeString(reader.eventType)}, " +
"lastProcessedElement=$localName" +
")", reader.location)
}
}
private fun readActions(descriptor: RawPluginDescriptor, reader: XMLStreamReader2, readContext: ReadModuleContext) {
var actionElements = descriptor.actions
if (actionElements == null) {
actionElements = ArrayList()
descriptor.actions = actionElements
}
val resourceBundle = findAttributeValue(reader, "resource-bundle")
reader.consumeChildElements { elementName ->
if (checkXInclude(elementName, reader)) {
return@consumeChildElements
}
actionElements.add(RawPluginDescriptor.ActionDescriptor(
name = elementName,
element = readXmlAsModel(reader = reader, rootName = elementName, interner = readContext.interner),
resourceBundle = resourceBundle,
))
}
}
private fun readOldDepends(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
var isOptional = false
var configFile: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"optional" -> isOptional = reader.getAttributeAsBoolean(i)
"config-file" -> configFile = reader.getAttributeValue(i)
}
}
val dependencyIdString = getNullifiedContent(reader) ?: return
var depends = descriptor.depends
if (depends == null) {
depends = ArrayList()
descriptor.depends = depends
}
depends.add(PluginDependency(pluginId = PluginId.getId(dependencyIdString), configFile = configFile, isOptional = isOptional))
}
private fun readExtensions(reader: XMLStreamReader2, descriptor: RawPluginDescriptor, interner: XmlInterner) {
val ns = findAttributeValue(reader, "defaultExtensionNs")
reader.consumeChildElements { elementName ->
if (checkXInclude(elementName, reader)) {
return@consumeChildElements
}
var implementation: String? = null
var os: ExtensionDescriptor.Os? = null
var qualifiedExtensionPointName: String? = null
var order = LoadingOrder.ANY
var orderId: String? = null
var hasExtraAttributes = false
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"implementation" -> implementation = reader.getAttributeValue(i)
"implementationClass" -> {
// deprecated attribute
implementation = reader.getAttributeValue(i)
}
"os" -> os = readOs(reader.getAttributeValue(i))
"id" -> orderId = getNullifiedAttributeValue(reader, i)
"order" -> order = readOrder(reader.getAttributeValue(i))
"point" -> qualifiedExtensionPointName = getNullifiedAttributeValue(reader, i)
else -> hasExtraAttributes = true
}
}
if (qualifiedExtensionPointName == null) {
qualifiedExtensionPointName = interner.name("${ns ?: reader.namespaceURI}.${elementName}")
}
val containerDescriptor: ContainerDescriptor
when (qualifiedExtensionPointName) {
"com.intellij.applicationService" -> containerDescriptor = descriptor.appContainerDescriptor
"com.intellij.projectService" -> containerDescriptor = descriptor.projectContainerDescriptor
"com.intellij.moduleService" -> containerDescriptor = descriptor.moduleContainerDescriptor
else -> {
// bean EP can use id / implementation attributes for own bean class
// - that's why we have to create XmlElement even if all attributes are common
val element = if (qualifiedExtensionPointName == "com.intellij.postStartupActivity") {
reader.skipElement()
null
}
else {
readXmlAsModel(reader = reader, rootName = null, interner = interner).takeIf {
!it.children.isEmpty() || !it.attributes.keys.isEmpty()
}
}
var map = descriptor.epNameToExtensions
if (map == null) {
map = HashMap()
descriptor.epNameToExtensions = map
}
val extensionDescriptor = ExtensionDescriptor(implementation, os, orderId, order, element, hasExtraAttributes)
val list = map.get(qualifiedExtensionPointName)
if (list == null) {
map.put(qualifiedExtensionPointName, Collections.singletonList(extensionDescriptor))
}
else if (list.size == 1) {
val l = ArrayList<ExtensionDescriptor>(4)
l.add(list.get(0))
l.add(extensionDescriptor)
map.put(qualifiedExtensionPointName, l)
}
else {
list.add(extensionDescriptor)
}
assert(reader.isEndElement)
return@consumeChildElements
}
}
containerDescriptor.addService(readServiceDescriptor(reader, os))
reader.skipElement()
}
}
private fun readOrder(orderAttr: String?): LoadingOrder {
return when (orderAttr) {
null -> LoadingOrder.ANY
LoadingOrder.FIRST_STR -> LoadingOrder.FIRST
LoadingOrder.LAST_STR -> LoadingOrder.LAST
else -> LoadingOrder(orderAttr)
}
}
private fun checkXInclude(elementName: String, reader: XMLStreamReader2): Boolean {
if (elementName == "include" && reader.namespaceURI == "http://www.w3.org/2001/XInclude") {
LOG.error("`include` is supported only on a root level (${reader.location})")
reader.skipElement()
return true
}
return false
}
@Suppress("DuplicatedCode")
private fun readExtensionPoints(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?) {
reader.consumeChildElements { elementName ->
if (elementName != "extensionPoint") {
if (elementName == "include" && reader.namespaceURI == "http://www.w3.org/2001/XInclude") {
val partial = RawPluginDescriptor()
readInclude(reader = reader,
readInto = partial,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
allowedPointer = "xpointer(/idea-plugin/extensionPoints/*)")
LOG.warn("`include` is supported only on a root level (${reader.location})")
applyPartialContainer(partial, descriptor) { it.appContainerDescriptor }
applyPartialContainer(partial, descriptor) { it.projectContainerDescriptor }
applyPartialContainer(partial, descriptor) { it.moduleContainerDescriptor }
}
else {
LOG.error("Unknown element: $elementName (${reader.location})")
reader.skipElement()
}
return@consumeChildElements
}
var area: String? = null
var qualifiedName: String? = null
var name: String? = null
var beanClass: String? = null
var `interface`: String? = null
var isDynamic = false
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"area" -> area = getNullifiedAttributeValue(reader, i)
"qualifiedName" -> qualifiedName = reader.getAttributeValue(i)
"name" -> name = getNullifiedAttributeValue(reader, i)
"beanClass" -> beanClass = getNullifiedAttributeValue(reader, i)
"interface" -> `interface` = getNullifiedAttributeValue(reader, i)
"dynamic" -> isDynamic = reader.getAttributeAsBoolean(i)
}
}
if (beanClass == null && `interface` == null) {
throw RuntimeException("Neither beanClass nor interface attribute is specified for extension point at ${reader.location}")
}
if (beanClass != null && `interface` != null) {
throw RuntimeException("Both beanClass and interface attributes are specified for extension point at ${reader.location}")
}
reader.skipElement()
val containerDescriptor = when (area) {
null -> descriptor.appContainerDescriptor
"IDEA_PROJECT" -> descriptor.projectContainerDescriptor
"IDEA_MODULE" -> descriptor.moduleContainerDescriptor
else -> {
LOG.error("Unknown area: $area")
return@consumeChildElements
}
}
var result = containerDescriptor.extensionPoints
if (result == null) {
result = ArrayList()
containerDescriptor.extensionPoints = result
}
result.add(ExtensionPointDescriptor(
name = qualifiedName ?: name ?: throw RuntimeException("`name` attribute not specified for extension point at ${reader.location}"),
isNameQualified = qualifiedName != null,
className = `interface` ?: beanClass!!,
isBean = `interface` == null,
isDynamic = isDynamic
))
}
}
private inline fun applyPartialContainer(from: RawPluginDescriptor,
to: RawPluginDescriptor,
crossinline extractor: (RawPluginDescriptor) -> ContainerDescriptor) {
extractor(from).extensionPoints?.let {
val toContainer = extractor(to)
if (toContainer.extensionPoints == null) {
toContainer.extensionPoints = it
}
else {
toContainer.extensionPoints!!.addAll(it)
}
}
}
@Suppress("DuplicatedCode")
private fun readServiceDescriptor(reader: XMLStreamReader2, os: ExtensionDescriptor.Os?): ServiceDescriptor {
var serviceInterface: String? = null
var serviceImplementation: String? = null
var testServiceImplementation: String? = null
var headlessImplementation: String? = null
var configurationSchemaKey: String? = null
var overrides = false
var preload = ServiceDescriptor.PreloadMode.FALSE
var client: ServiceDescriptor.ClientKind? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"serviceInterface" -> serviceInterface = getNullifiedAttributeValue(reader, i)
"serviceImplementation" -> serviceImplementation = getNullifiedAttributeValue(reader, i)
"testServiceImplementation" -> testServiceImplementation = getNullifiedAttributeValue(reader, i)
"headlessImplementation" -> headlessImplementation = getNullifiedAttributeValue(reader, i)
"configurationSchemaKey" -> configurationSchemaKey = reader.getAttributeValue(i)
"overrides" -> overrides = reader.getAttributeAsBoolean(i)
"preload" -> {
when (reader.getAttributeValue(i)) {
"true" -> preload = ServiceDescriptor.PreloadMode.TRUE
"await" -> preload = ServiceDescriptor.PreloadMode.AWAIT
"notHeadless" -> preload = ServiceDescriptor.PreloadMode.NOT_HEADLESS
"notLightEdit" -> preload = ServiceDescriptor.PreloadMode.NOT_LIGHT_EDIT
else -> LOG.error("Unknown preload mode value ${reader.getAttributeValue(i)} at ${reader.location}")
}
}
"client" -> {
when (reader.getAttributeValue(i)) {
"all" -> client = ServiceDescriptor.ClientKind.ALL
"local" -> client = ServiceDescriptor.ClientKind.LOCAL
"guest" -> client = ServiceDescriptor.ClientKind.GUEST
else -> LOG.error("Unknown client value: ${reader.getAttributeValue(i)} at ${reader.location}")
}
}
}
}
return ServiceDescriptor(serviceInterface, serviceImplementation, testServiceImplementation, headlessImplementation,
overrides, configurationSchemaKey, preload, client, os)
}
private fun readProduct(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"code" -> descriptor.productCode = getNullifiedAttributeValue(reader, i)
"release-date" -> descriptor.releaseDate = parseReleaseDate(reader.getAttributeValue(i))
"release-version" -> {
try {
descriptor.releaseVersion = reader.getAttributeAsInt(i)
}
catch (e: TypedXMLStreamException) {
descriptor.releaseVersion = 0
}
}
"optional" -> descriptor.isLicenseOptional = reader.getAttributeAsBoolean(i)
}
}
reader.skipElement()
}
private fun readComponents(reader: XMLStreamReader2, containerDescriptor: ContainerDescriptor) {
val result = containerDescriptor.getComponentListToAdd()
reader.consumeChildElements("component") {
var isApplicableForDefaultProject = false
var interfaceClass: String? = null
var implementationClass: String? = null
var headlessImplementationClass: String? = null
var os: ExtensionDescriptor.Os? = null
var overrides = false
var options: MutableMap<String, String?>? = null
reader.consumeChildElements { elementName ->
when (elementName) {
"skipForDefaultProject" -> {
val value = reader.elementText
if (!value.isEmpty() && value.equals("false", ignoreCase = true)) {
isApplicableForDefaultProject = true
}
}
"loadForDefaultProject" -> {
val value = reader.elementText
isApplicableForDefaultProject = value.isEmpty() || value.equals("true", ignoreCase = true)
}
"interface-class" -> interfaceClass = getNullifiedContent(reader)
// empty value must be supported
"implementation-class" -> implementationClass = getNullifiedContent(reader)
// empty value must be supported
"headless-implementation-class" -> headlessImplementationClass = reader.elementText
"option" -> {
var name: String? = null
var value: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = getNullifiedAttributeValue(reader, i)
"value" -> value = getNullifiedAttributeValue(reader, i)
}
}
reader.skipElement()
if (name != null && value != null) {
when {
name == "os" -> os = readOs(value)
name == "overrides" -> overrides = value.toBoolean()
options == null -> {
options = Collections.singletonMap(name, value)
}
else -> {
if (options!!.size == 1) {
options = HashMap(options)
}
options!!.put(name, value)
}
}
}
}
else -> reader.skipElement()
}
assert(reader.isEndElement)
}
assert(reader.isEndElement)
result.add(ComponentConfig(interfaceClass, implementationClass, headlessImplementationClass, isApplicableForDefaultProject,
os, overrides, options))
}
}
private fun readContent(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
readContext: ReadModuleContext) {
var items = descriptor.contentModules
if (items == null) {
items = ArrayList()
descriptor.contentModules = items
}
reader.consumeChildElements { elementName ->
when (elementName) {
"module" -> {
var name: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (name.isNullOrEmpty()) {
throw RuntimeException("Name is not specified at ${reader.location}")
}
var configFile: String? = null
val index = name.lastIndexOf('/')
if (index != -1) {
configFile = "${name.substring(0, index)}.${name.substring(index + 1)}.xml"
}
items.add(PluginContentDescriptor.ModuleItem(name = name, configFile = configFile))
}
else -> throw RuntimeException("Unknown content item type: $elementName")
}
reader.skipElement()
}
assert(reader.isEndElement)
}
private fun readDependencies(reader: XMLStreamReader2, descriptor: RawPluginDescriptor, readContext: ReadModuleContext) {
var modules: MutableList<ModuleDependenciesDescriptor.ModuleReference>? = null
var plugins: MutableList<ModuleDependenciesDescriptor.PluginReference>? = null
reader.consumeChildElements { elementName ->
when (elementName) {
"module" -> {
var name: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (modules == null) {
modules = ArrayList()
}
modules!!.add(ModuleDependenciesDescriptor.ModuleReference(name!!))
}
"plugin" -> {
var id: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"id" -> id = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (plugins == null) {
plugins = ArrayList()
}
plugins!!.add(ModuleDependenciesDescriptor.PluginReference(PluginId.getId(id!!)))
}
else -> throw RuntimeException("Unknown content item type: $elementName")
}
reader.skipElement()
}
descriptor.dependencies = ModuleDependenciesDescriptor(modules ?: Collections.emptyList(), plugins ?: Collections.emptyList())
assert(reader.isEndElement)
}
private fun findAttributeValue(reader: XMLStreamReader2, name: String): String? {
for (i in 0 until reader.attributeCount) {
if (reader.getAttributeLocalName(i) == name) {
return getNullifiedAttributeValue(reader, i)
}
}
return null
}
private fun getNullifiedContent(reader: XMLStreamReader2): String? = reader.elementText.takeIf { !it.isEmpty() }
private fun getNullifiedAttributeValue(reader: XMLStreamReader2, i: Int) = reader.getAttributeValue(i).takeIf { !it.isEmpty() }
interface ReadModuleContext {
val interner: XmlInterner
val isMissingIncludeIgnored: Boolean
get() = false
}
private fun readInclude(reader: XMLStreamReader2,
readInto: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
allowedPointer: String) {
var path: String? = null
var pointer: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"href" -> path = getNullifiedAttributeValue(reader, i)
"xpointer" -> pointer = reader.getAttributeValue(i)?.takeIf { !it.isEmpty() && it != allowedPointer }
"includeIf" -> {
checkConditionalIncludeIsSupported("includeIf", readInto)
val value = reader.getAttributeValue(i)?.let { System.getProperty(it) }
if (value != "true") {
reader.skipElement()
return
}
}
"includeUnless" -> {
checkConditionalIncludeIsSupported("includeUnless", readInto)
val value = reader.getAttributeValue(i)?.let { System.getProperty(it) }
if (value == "true") {
reader.skipElement()
return
}
}
else -> throw RuntimeException("Unknown attribute ${reader.getAttributeLocalName(i)} (${reader.location})")
}
}
if (pointer != null) {
throw RuntimeException("Attribute `xpointer` is not supported anymore (xpointer=$pointer, location=${reader.location})")
}
if (path == null) {
throw RuntimeException("Missing `href` attribute (${reader.location})")
}
var isOptional = false
reader.consumeChildElements("fallback") {
isOptional = true
reader.skipElement()
}
var readError: IOException? = null
val read = try {
pathResolver.loadXIncludeReference(dataLoader = dataLoader,
base = includeBase,
relativePath = path,
readContext = readContext,
readInto = readInto)
}
catch (e: IOException) {
readError = e
false
}
if (read || isOptional) {
return
}
if (readContext.isMissingIncludeIgnored) {
LOG.info("$path include ignored (dataLoader=$dataLoader)", readError)
return
}
else {
throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader)", readError)
}
}
private fun checkConditionalIncludeIsSupported(attribute: String, pluginDescriptor: RawPluginDescriptor) {
if (pluginDescriptor.id !in KNOWN_KOTLIN_PLUGIN_IDS) {
throw IllegalArgumentException("$attribute of 'include' is not supported")
}
}
private var dateTimeFormatter: DateTimeFormatter? = null
private val LOG: Logger
get() = PluginManagerCore.getLogger()
private fun parseReleaseDate(dateString: String): LocalDate? {
if (dateString.isEmpty() || dateString == "__DATE__") {
return null
}
var formatter = dateTimeFormatter
if (formatter == null) {
formatter = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.US)
dateTimeFormatter = formatter
}
try {
return LocalDate.parse(dateString, formatter)
}
catch (e: ParseException) {
LOG.error("Cannot parse release date", e)
}
return null
}
private fun readListeners(reader: XMLStreamReader2, containerDescriptor: ContainerDescriptor) {
var result = containerDescriptor.listeners
if (result == null) {
result = ArrayList()
containerDescriptor.listeners = result
}
reader.consumeChildElements("listener") {
var os: ExtensionDescriptor.Os? = null
var listenerClassName: String? = null
var topicClassName: String? = null
var activeInTestMode = true
var activeInHeadlessMode = true
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"os" -> os = readOs(reader.getAttributeValue(i))
"class" -> listenerClassName = getNullifiedAttributeValue(reader, i)
"topic" -> topicClassName = getNullifiedAttributeValue(reader, i)
"activeInTestMode" -> activeInTestMode = reader.getAttributeAsBoolean(i)
"activeInHeadlessMode" -> activeInHeadlessMode = reader.getAttributeAsBoolean(i)
}
}
if (listenerClassName == null || topicClassName == null) {
LOG.error("Listener descriptor is not correct as ${reader.location}")
}
else {
result.add(ListenerDescriptor(os, listenerClassName, topicClassName, activeInTestMode, activeInHeadlessMode))
}
reader.skipElement()
}
assert(reader.isEndElement)
}
private fun readOs(value: String): ExtensionDescriptor.Os {
return when (value) {
"mac" -> ExtensionDescriptor.Os.mac
"linux" -> ExtensionDescriptor.Os.linux
"windows" -> ExtensionDescriptor.Os.windows
"unix" -> ExtensionDescriptor.Os.unix
"freebsd" -> ExtensionDescriptor.Os.freebsd
else -> throw IllegalArgumentException("Unknown OS: $value")
}
}
private inline fun XMLStreamReader.consumeChildElements(crossinline consumer: (name: String) -> Unit) {
// cursor must be at the start of parent element
assert(isStartElement)
var depth = 1
while (true) {
when (next()) {
XMLStreamConstants.START_ELEMENT -> {
depth++
consumer(localName)
assert(isEndElement)
depth--
}
XMLStreamConstants.END_ELEMENT -> {
if (depth != 1) {
throw IllegalStateException("Expected depth: 1")
}
return
}
XMLStreamConstants.CDATA,
XMLStreamConstants.SPACE,
XMLStreamConstants.CHARACTERS,
XMLStreamConstants.ENTITY_REFERENCE,
XMLStreamConstants.COMMENT,
XMLStreamConstants.PROCESSING_INSTRUCTION -> {
// ignore
}
else -> throw XMLStreamException("Unexpected state: ${getEventTypeString(eventType)}", location)
}
}
}
private inline fun XMLStreamReader2.consumeChildElements(name: String, crossinline consumer: () -> Unit) {
consumeChildElements {
if (name == it) {
consumer()
assert(isEndElement)
}
else {
skipElement()
}
}
}
private fun getEventTypeString(eventType: Int): String {
return when (eventType) {
XMLEvent.START_ELEMENT -> "START_ELEMENT"
XMLEvent.END_ELEMENT -> "END_ELEMENT"
XMLEvent.PROCESSING_INSTRUCTION -> "PROCESSING_INSTRUCTION"
XMLEvent.CHARACTERS -> "CHARACTERS"
XMLEvent.COMMENT -> "COMMENT"
XMLEvent.START_DOCUMENT -> "START_DOCUMENT"
XMLEvent.END_DOCUMENT -> "END_DOCUMENT"
XMLEvent.ENTITY_REFERENCE -> "ENTITY_REFERENCE"
XMLEvent.ATTRIBUTE -> "ATTRIBUTE"
XMLEvent.DTD -> "DTD"
XMLEvent.CDATA -> "CDATA"
XMLEvent.SPACE -> "SPACE"
else -> "UNKNOWN_EVENT_TYPE, $eventType"
}
} | apache-2.0 | 4b55f4faf97ae4340bac602c680b2983 | 36.670732 | 137 | 0.64378 | 4.925847 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ucache/ScriptSdksBuilder.kt | 2 | 4867 | // 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.core.script.ucache
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.core.script.configuration.utils.ScriptClassRootsStorage
import org.jetbrains.kotlin.idea.core.script.scriptingWarnLog
import org.jetbrains.kotlin.idea.util.application.runReadAction
import java.nio.file.Path
class ScriptSdksBuilder(
val project: Project,
internal val sdks: MutableMap<SdkId, Sdk?> = mutableMapOf(),
private val remove: Sdk? = null
) {
private val defaultSdk by lazy { getScriptDefaultSdk() }
fun build(): ScriptSdks {
val nonIndexedSdks = sdks.values.filterNotNullTo(mutableSetOf())
val nonIndexedClassRoots = mutableSetOf<VirtualFile>()
val nonIndexedSourceRoots = mutableSetOf<VirtualFile>()
runReadAction {
for (module in ModuleManager.getInstance(project).modules.filter { !it.isDisposed }) {
ProgressManager.checkCanceled()
if (nonIndexedSdks.isEmpty()) break
nonIndexedSdks.remove(ModuleRootManager.getInstance(module).sdk)
}
nonIndexedSdks.forEach { sdk ->
nonIndexedClassRoots += sdk.rootProvider.getFiles(OrderRootType.CLASSES)
nonIndexedSourceRoots += sdk.rootProvider.getFiles(OrderRootType.SOURCES)
}
}
return ScriptSdks(sdks, nonIndexedClassRoots, nonIndexedSourceRoots)
}
@Deprecated("Don't use, used only from DefaultScriptingSupport for saving to storage")
fun addAll(other: ScriptSdksBuilder) {
sdks.putAll(other.sdks)
}
fun addAll(other: ScriptSdks) {
sdks.putAll(other.sdks)
}
// add sdk by home path with checking for removed sdk
fun addSdk(sdkId: SdkId): Sdk? {
val canonicalPath = sdkId.homeDirectory ?: return addDefaultSdk()
return addSdk(Path.of(canonicalPath))
}
fun addSdk(javaHome: Path?): Sdk? {
if (javaHome == null) return addDefaultSdk()
return sdks.getOrPut(SdkId(javaHome)) {
getScriptSdkByJavaHome(javaHome) ?: defaultSdk
}
}
private fun getScriptSdkByJavaHome(javaHome: Path): Sdk? {
// workaround for mismatched gradle wrapper and plugin version
val javaHomeVF = try {
VfsUtil.findFile(javaHome, true)
} catch (e: Throwable) {
null
} ?: return null
return runReadAction { ProjectJdkTable.getInstance() }.allJdks
.find { it.homeDirectory == javaHomeVF }
?.takeIf { it.canBeUsedForScript() }
}
fun addDefaultSdk(): Sdk? =
sdks.getOrPut(SdkId.default) { defaultSdk }
fun addSdkByName(sdkName: String) {
val sdk = runReadAction { ProjectJdkTable.getInstance() }.allJdks
.find { it.name == sdkName }
?.takeIf { it.canBeUsedForScript() }
?: defaultSdk
?: return
val homePath = sdk.homePath ?: return
sdks[SdkId(homePath)] = sdk
}
private fun getScriptDefaultSdk(): Sdk? {
val projectSdk = ProjectRootManager.getInstance(project).projectSdk?.takeIf { it.canBeUsedForScript() }
if (projectSdk != null) return projectSdk
val allJdks = runReadAction { ProjectJdkTable.getInstance() }.allJdks
val anyJavaSdk = allJdks.find { it.canBeUsedForScript() }
if (anyJavaSdk != null) {
return anyJavaSdk
}
scriptingWarnLog(
"Default Script SDK is null: " +
"projectSdk = ${ProjectRootManager.getInstance(project).projectSdk}, " +
"all sdks = ${allJdks.joinToString("\n")}"
)
return null
}
private fun Sdk.canBeUsedForScript() = this != remove && sdkType is JavaSdkType
fun toStorage(storage: ScriptClassRootsStorage) {
storage.sdks = sdks.values.mapNotNullTo(mutableSetOf()) { it?.name }
storage.defaultSdkUsed = sdks.containsKey(SdkId.default)
}
fun fromStorage(storage: ScriptClassRootsStorage) {
storage.sdks.forEach {
addSdkByName(it)
}
if (storage.defaultSdkUsed) {
addDefaultSdk()
}
}
}
| apache-2.0 | 8ff09e0e0e5c12b500305fea49e2d26c | 35.320896 | 158 | 0.668584 | 4.818812 | false | false | false | false |
google/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/MavenArtifactsProperties.kt | 1 | 2091 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.util.JpsPathUtil
import java.nio.file.Path
/**
* Specifies how Maven artifacts for IDE modules should be generated.
* Public artifacts are generated under {@link BuildPaths#artifactDir}/maven-artifacts directory.
* Proprietary artifacts are generated under {@link BuildPaths#artifactDir}/proprietary-maven-artifacts directory.
* @see ProductProperties#mavenArtifacts
* @see org.jetbrains.intellij.build.impl.MavenArtifactsBuilder#generateMavenArtifacts
*/
class MavenArtifactsProperties {
/**
* If {@code true} Maven artifacts are generated for all modules included into the IDE distribution.
*/
var forIdeModules = false
/**
* Names of additional modules for which Maven artifacts should be generated.
*/
var additionalModules: PersistentList<String> = persistentListOf()
/**
* Names of modules for which Maven artifacts should be generated, that will create all its module-dependencies in a single jar.
*
* Initially, it's introduced for having `util-base` artifact which will include `util-rt` in it to avoid JPMS package-split.
*/
var squashedModules: PersistentList<String> = persistentListOf()
/**
* Names of proprietary modules for which Maven artifacts should be generated.
*
* <p>
* Note: Intended only for private Maven repository publication.
* </p>
*/
var proprietaryModules: PersistentList<String> = persistentListOf()
/**
* A predicate which returns {@code true} for modules which sources should be published as Maven artifacts.
*/
var publishSourcesFilter: (JpsModule, BuildContext) -> Boolean = { module, context ->
module.contentRootsList.urls.all { Path.of(JpsPathUtil.urlToPath(it)).startsWith(context.paths.communityHomeDir.communityRoot) }
}
}
| apache-2.0 | fbfa0ed8e295debafede587910a5a7e1 | 40.82 | 132 | 0.761836 | 4.545652 | false | false | false | false |
mikepenz/Storyblok-Android-SDK | library/src/main/java/com/mikepenz/storyblok/model/Link.kt | 1 | 1394 | package com.mikepenz.storyblok.model
import org.json.JSONObject
import java.util.*
/**
* Created by mikepenz on 14/04/2017.
*/
class Link(story: JSONObject) : Entity(story) {
var isFolder: Boolean = false
private set
var parentId: Long = 0
private set
var isPublished: Boolean = false
private set
var position: Int = 0
private set
init {
if (story.has("is_folder")) {
this.isFolder = story.optBoolean("is_folder")
}
if (story.has("parent_id")) {
this.parentId = story.optLong("parent_id")
}
if (story.has("published")) {
this.isPublished = story.optBoolean("published")
}
if (story.has("position")) {
this.position = story.optInt("position")
}
}
companion object {
fun parseLinks(result: JSONObject?): Map<String, Link>? {
if (result != null && result.has("links")) {
val jsonObject = result.optJSONObject("links")
val links = HashMap<String, Link>(jsonObject.length())
val i = jsonObject.keys()
while (i.hasNext()) {
val key = i.next()
links[key] = Link(jsonObject.optJSONObject(key))
}
return links
}
return null
}
}
}
| apache-2.0 | 47e94c56ff4030a350f648dbb5ec409b | 25.807692 | 70 | 0.521521 | 4.383648 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/KotlinScriptExternalLibrariesNodesProvider.kt | 1 | 2947 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.core.script
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.projectView.impl.nodes.ExternalLibrariesWorkspaceModelNodesProvider
import com.intellij.ide.projectView.impl.nodes.SyntheticLibraryElementNode
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.SyntheticLibrary
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.workspaceModel.ide.impl.virtualFile
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.core.script.ucache.*
import java.nio.file.Path
import javax.swing.Icon
class KotlinScriptExternalLibrariesNodesProvider: ExternalLibrariesWorkspaceModelNodesProvider<KotlinScriptEntity> {
override fun getWorkspaceClass(): Class<KotlinScriptEntity> = KotlinScriptEntity::class.java
override fun createNode(entity: KotlinScriptEntity, project: Project, settings: ViewSettings?): AbstractTreeNode<*>? {
if (!scriptsAsEntities) return null
val dependencies = entity.listDependencies()
val scriptFile = VirtualFileManager.getInstance().findFileByNioPath(Path.of(entity.path))
?: error("Cannot find file: ${entity.path}")
val library = KotlinScriptDependenciesLibrary("Script: ${scriptFile.relativeName(project)}",
dependencies.compiled, dependencies.sources)
return SyntheticLibraryElementNode(project, library, library, settings)
}
}
private data class KotlinScriptDependenciesLibrary(val name: String, val classes: Collection<VirtualFile>, val sources: Collection<VirtualFile>) :
SyntheticLibrary(), ItemPresentation {
override fun getBinaryRoots(): Collection<VirtualFile> = classes
override fun getSourceRoots(): Collection<VirtualFile> = sources
override fun getPresentableText(): String = name
override fun getIcon(unused: Boolean): Icon = KotlinIcons.SCRIPT
}
private fun KotlinScriptEntity.listDependencies(): ScriptDependencies {
fun List<KotlinScriptLibraryRoot>.files() = asSequence()
.mapNotNull { it.url.virtualFile }
.filter { it.isValid }
.toList()
val (compiledRoots, sourceRoots) = dependencies.asSequence()
.flatMap { it.roots }
.partition { it.type == KotlinScriptLibraryRootTypeId.COMPILED }
return ScriptDependencies(Pair(compiledRoots.files(), sourceRoots.files()))
}
@JvmInline
private value class ScriptDependencies(private val compiledAndSources: Pair<List<VirtualFile>, List<VirtualFile>>) {
val compiled
get() = compiledAndSources.first
val sources
get() = compiledAndSources.second
} | apache-2.0 | 9457249f6a5308c243252be95d9e5a86 | 41.724638 | 146 | 0.76247 | 4.903494 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_info/ui/adapter/delegates/CourseInfoSkillsAdapterDelegate.kt | 1 | 2179 | package org.stepik.android.view.course_info.ui.adapter.delegates
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import by.kirich1409.viewbindingdelegate.viewBinding
import org.stepic.droid.R
import org.stepic.droid.databinding.ItemSkillCourseInfoBinding
import org.stepic.droid.databinding.ViewCourseInfoSkillsBinding
import org.stepik.android.view.course_info.model.CourseInfoItem
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
import ru.nobird.android.ui.adapterdelegates.dsl.adapterDelegate
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
class CourseInfoSkillsAdapterDelegate : AdapterDelegate<CourseInfoItem, DelegateViewHolder<CourseInfoItem>>() {
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseInfoItem> =
ViewHolder(createView(parent, R.layout.view_course_info_skills))
override fun isForViewType(position: Int, data: CourseInfoItem): Boolean =
data is CourseInfoItem.Skills
inner class ViewHolder(root: View) : DelegateViewHolder<CourseInfoItem>(root) {
private val viewBinding: ViewCourseInfoSkillsBinding by viewBinding { ViewCourseInfoSkillsBinding.bind(root) }
private val skillsAdapter: DefaultDelegateAdapter<String> = DefaultDelegateAdapter()
init {
skillsAdapter += adapterDelegate(
layoutResId = R.layout.item_skill_course_info
) {
val viewBinding: ItemSkillCourseInfoBinding = ItemSkillCourseInfoBinding.bind(itemView)
onBind { data ->
viewBinding.skillText.text = data
}
}
with(viewBinding.skillsRecycler) {
adapter = skillsAdapter
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
isNestedScrollingEnabled = false
}
}
override fun onBind(data: CourseInfoItem) {
data as CourseInfoItem.Skills
skillsAdapter.items = data.acquiredSkills
}
}
} | apache-2.0 | 7e9f90e9cbd1026ec707f1a91d55ab0f | 43.489796 | 118 | 0.729234 | 5.288835 | false | false | false | false |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/clients/beehive/json/BeehiveJSONParser.kt | 1 | 7669 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.clients.beehive.json
import android.util.Log
import com.neatorobotics.sdk.android.models.*
import com.neatorobotics.sdk.android.utils.DateUtils
import org.json.JSONException
import org.json.JSONObject
import java.util.ArrayList
import java.util.Calendar
object BeehiveJSONParser {
private val TAG = "BeehiveJSONParser"
fun parseRobot(json: JSONObject): Robot {
return Robot().apply { loadFromJSON(json) }
}
fun parseRobotList(json: JSONObject?): List<Robot> {
val robots = ArrayList<Robot>()
if (json?.has("value") != null) {
try {
val arr = json.getJSONArray("value")
for (i in 0 until arr.length()) {
val robot = Robot().apply { loadFromJSON(arr.getJSONObject(i)) }
if (!robot.linkedAt.isNullOrEmpty()) {
robots.add(robot)
}
}
} catch (e: JSONException) {
Log.d(TAG, e.message)
}
}
return robots
}
fun parseRobotMaps(json: JSONObject): List<CleaningMap> {
val maps = mutableListOf<CleaningMap>()
try {
val arr = json.getJSONArray("maps")
for (i in 0 until arr.length()) {
//Only VERSION 1 Map now
if (arr.getJSONObject(i).optInt("version", 0) == 1) {
val item = CleaningMap()
item.url = arr.getJSONObject(i).optString("url", "")
item.id = arr.getJSONObject(i).optString("id", "")
item.startAt = arr.getJSONObject(i).optString("start_at", "")
item.endAt = arr.getJSONObject(i).optString("end_at", "")
item.error = arr.getJSONObject(i).optString("error", "")
item.isDocked = arr.getJSONObject(i).optBoolean("is_docked", false)
item.isDelocalized = arr.getJSONObject(i).optBoolean("delocalized", false)
item.isValidAsPersistentMap = arr.getJSONObject(i).optBoolean("valid_as_persistent_map", false)
item.area = arr.getJSONObject(i).optDouble("cleaned_area", 0.0)
item.status = arr.getJSONObject(i).optString("status", CleaningMap.INVALID)
item.chargingTimeSeconds = arr.getJSONObject(i).optDouble("time_in_suspended_cleaning", 0.0)
item.timeInError = arr.getJSONObject(i).optDouble("time_in_error", 0.0)
item.timeInPause = arr.getJSONObject(i).optDouble("time_in_pause", 0.0)
//compute the expiration date
val urlValidForSeconds = arr.getJSONObject(i).optInt("url_valid_for_seconds", 300)
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, urlValidForSeconds)
item.urlExpiresAt = calendar.time
//discard map/stats before EPOCH TIME
val start = DateUtils.getDate("yyyy-MM-dd'T'HH:mm:ss'Z'", item.startAt!!)
if (DateUtils.isAfterEpochTime(start!!)) {
maps.add(item)
}
}
}
} catch (e: JSONException) {
Log.d(TAG, e.message)
}
return maps.toList()
}
fun parseRobotMap(json: JSONObject): CleaningMap {
val map = CleaningMap()
//Only VERSION 1 Map now
if (json.optInt("version", 0) == 1) {
map.url = json.optString("url", "")
map.id = json.optString("id", "")
map.startAt = json.optString("start_at", "")
map.endAt = json.optString("end_at", "")
map.error = json.optString("error", "")
map.isDocked = json.optBoolean("is_docked", false)
map.isDelocalized = json.optBoolean("delocalized", false)
map.area = json.optDouble("cleaned_area", 0.0)
map.status = json.optString("status", CleaningMap.INVALID)
map.chargingTimeSeconds = json.optDouble("time_in_suspended_cleaning", 0.0)
map.timeInError = json.optDouble("time_in_error", 0.0)
map.timeInPause = json.optDouble("time_in_pause", 0.0)
//compute the expiration date
val urlValidForSeconds = json.optInt("url_valid_for_seconds", 300)
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, urlValidForSeconds)
map.urlExpiresAt = calendar.time
}
return map
}
fun parseRobotPersistentMaps(json: JSONObject?): List<PersistentMap> {
val maps = ArrayList<PersistentMap>()
if (json != null) {
try {
val list = json.getJSONArray("value")
for (i in 0 until list.length()) {
val mapJson = list.getJSONObject(i)
val map = PersistentMap()
var name = mapJson.optString("name")
if (name.isNullOrEmpty()) name = "My Home"
map.name = name
map.id = mapJson.optString("id")
map.url = mapJson.optString("url")
map.rawMapUrl = mapJson.optString("raw_floor_map_url")
//compute the expiration date
val urlValidForSeconds = mapJson.optInt("url_valid_for_seconds", 300)
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, urlValidForSeconds)
map.expireAt = calendar.time
maps.add(map)
}
} catch (e: JSONException) {
Log.e(TAG, "Exception", e)
}
}
return maps
}
fun parseRobotExplorationMaps(json: JSONObject): List<PersistentMap> {
val maps = ArrayList<PersistentMap>()
try {
val list = json.getJSONArray("exploration_maps")
for (i in 0 until list.length()) {
val mapJson = list.getJSONObject(i)
val map = PersistentMap()
map.name = mapJson.optString("name")
map.id = mapJson.optString("id")
map.url = mapJson.optString("url")
//compute the expiration date
val urlValidForSeconds = mapJson.optInt("url_valid_for_seconds", 300)
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, urlValidForSeconds)
map.expireAt = calendar.time
maps.add(map)
}
} catch (e: JSONException) {
Log.e(TAG, "Exception", e)
}
return maps
}
fun parseUser(json: JSONObject?): UserInfo {
val user = UserInfo()
if(json == null) return user
if (json.has("newsletter")) {
user.newsletter = json.getBoolean("newsletter")
}
if (json.has("id")) {
user.id = json.getString("id")
}
if (json.has("email")) {
user.email = json.getString("email")
}
if (json.has("country_code")) {
user.countryCode = json.getString("country_code")
}
if (json.has("locale")) {
user.locale = json.getString("locale")
}
if (json.has("first_name")) {
user.first_name = json.getString("first_name")
}
if (json.has("last_name")) {
user.last_name = json.getString("last_name")
}
return user
}
}
| mit | f3ae56bcdbb9667c626f4881c95e4ac8 | 38.942708 | 115 | 0.535924 | 4.382286 | false | false | false | false |
Kiskae/DiscordKt | implementation/src/main/kotlin/net/serverpeon/discord/internal/data/model/MessageNode.kt | 1 | 7293 | package net.serverpeon.discord.internal.data.model
import net.serverpeon.discord.internal.jsonmodels.MessageModel
import net.serverpeon.discord.internal.rest.WrappedId
import net.serverpeon.discord.internal.rest.retro.Channels
import net.serverpeon.discord.internal.toFuture
import net.serverpeon.discord.message.Message
import net.serverpeon.discord.model.DiscordId
import net.serverpeon.discord.model.PermissionSet
import net.serverpeon.discord.model.PostedMessage
import net.serverpeon.discord.model.User
import java.time.ZonedDateTime
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicBoolean
class MessageNode(val root: DiscordNode,
override val postedAt: ZonedDateTime,
override val textToSpeech: Boolean,
override val lastEdited: ZonedDateTime?,
override val rawContent: String,
override val id: DiscordId<PostedMessage>,
override val author: User,
override val channel: ChannelNode<*>) : PostedMessage {
override val content: Message by lazy { parse(rawContent, root) }
override fun edit(): PostedMessage.Edit {
if (author.id != root.self.id) {
channel.checkPermission(PermissionSet.Permission.MANAGE_MESSAGES)
}
return Transaction(content)
}
override fun delete(): CompletableFuture<Void> {
return root.api.Channels.deleteMessage(
WrappedId(channel.id), WrappedId(id)
).toFuture()
}
override fun toString(): String {
return "Message(postedAt=$postedAt, tts=$textToSpeech, lastEdited=${lastEdited ?: postedAt}, rawContent='$rawContent', id=$id, author=$author, channel=$channel)"
}
inner class Transaction(override var content: Message) : PostedMessage.Edit {
private var completed = AtomicBoolean(false)
override fun commit(): CompletableFuture<PostedMessage> {
if (completed.getAndSet(true)) {
throw IllegalStateException("Don't call complete() twice")
} else {
return root.api.Channels.editMessage(WrappedId(channel.id), WrappedId(id), Channels.EditMessageRequest(
content = content.encodedContent,
mentions = content.mentions.map { it.id }.toList().toBlocking().first()
)).toFuture().thenApply { Builder.message(it, root) }
}
}
}
companion object {
fun create(model: MessageModel, root: DiscordNode) = Builder.message(model, root)
private fun parse(content: String, root: DiscordNode): Message {
val len = content.length
var i = 0
val builder = Message.Builder()
while (i < len) {
val specialEsc = content.indexOf('<', i)
val codeBlockEsc = content.indexOf("```", i)
if (isBefore(specialEsc, listOf(codeBlockEsc))) {
// Opening <, check next character
if (specialEsc + 1 < len) {
i = when (content[specialEsc + 1]) {
'#' -> {
parseTag(i, specialEsc, content, builder) { str, b ->
// cut off @
val channel = root.channelMap[DiscordId(str.substring(1))]
if (channel is ChannelNode.Public) {
b.append(channel)
} else {
b.append(str)
}
}
}
'@' -> {
parseTag(i, specialEsc, content, builder) { str, b ->
val user = root.userCache.retrieve(DiscordId(str.substring(1)))
if (user != null) {
b.append(user)
} else {
b.append(str)
}
}
}
else -> {
builder.append(content.substring(i..specialEsc))
specialEsc + 1
}
}
} else {
// Append final part of the string
builder.append(content.substring(i))
i = len
}
} else if (isBefore(codeBlockEsc, listOf(specialEsc))) {
if (codeBlockEsc + 3 < len) {
val closingChars = content.indexOf("```", codeBlockEsc + 4)
if (closingChars != -1) {
val code = content.substring((codeBlockEsc + 3)..(closingChars - 1))
val parts = code.split('\n', limit = 2)
if (parts.size == 2) {
builder.appendCodeBlock(parts[1], parts[0])
} else {
builder.appendCodeBlock(parts[0], "unknown")
}
i = closingChars + 3
} else {
//Just append all the text until after the ```
builder.append(content.substring(i..(codeBlockEsc + 2)))
i = codeBlockEsc + 3
}
} else {
//Just append all the text until after the ```
builder.append(content.substring(i..(codeBlockEsc + 2)))
i = codeBlockEsc + 3
}
} else {
// No tags left, just append the test of the string
builder.append(content.substring(i))
i = len
}
}
return builder.build()
}
private fun parseTag(previousIndex: Int, locationOfBracket: Int, source: String, builder: Message.Builder,
handler: (String, Message.Builder) -> Unit): Int {
//First append everything before the location bracket
builder.append(source.substring(previousIndex..(locationOfBracket - 1)))
val closingBracket = source.indexOf('>', locationOfBracket + 1)
return if (closingBracket != -1) {
handler(source.substring((locationOfBracket + 1)..(closingBracket - 1)), builder)
closingBracket + 1
} else {
// Abort, just retroactively append the <
builder.append("<")
locationOfBracket + 1
}
}
private fun isBefore(index: Int, otherIndexes: List<Int>): Boolean {
return if (index != -1) {
otherIndexes.all { it == -1 || index < it }
} else {
false
}
}
}
} | mit | ac3684f925ab270a7fdbe522074b66a2 | 45.164557 | 169 | 0.482243 | 5.537585 | false | false | false | false |
allotria/intellij-community | plugins/dependency-updater/src/com/intellij/buildsystem/model/BuildScriptEntryMetadata.kt | 10 | 1006 | package com.intellij.buildsystem.model
data class BuildScriptEntryMetadata constructor(
val startLine: Int,
val startColumn: Int,
val endLine: Int,
val endColumn: Int,
val rawText: String
) {
val linesCount: Int = endLine - startLine + 1
init {
require(startLine >= 1) { "The startLine value is 1-based, and must be [1, +inf), but was $startLine" }
require(startColumn >= 1) { "The startColumn value is 1-based, and must be [1, +inf), but was $startColumn" }
require(endLine >= 1) { "The endLine value is 1-based, and must be [1, +inf), but was $endLine" }
require(endColumn >= 1) { "The endColumn value is 1-based, and must be [1, +inf), but was $endColumn" }
require(endLine >= startLine) { "The endLine value must be equal or greater to the startLine value" }
if (linesCount == 1) {
require(endColumn >= startColumn) { "The endColumn value must be equal or greater to the startColumn value" }
}
}
}
| apache-2.0 | 03b07aed82a2d4b7385e2a3fc9de8b3d | 40.916667 | 121 | 0.642147 | 3.992063 | false | false | false | false |
DeflatedPickle/Quiver | imageviewer/src/main/kotlin/com/deflatedpickle/imageviewer/ImageViewerPlugin.kt | 1 | 1568 | /* Copyright (c) 2020-2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.imageviewer
import com.deflatedpickle.haruhi.api.Registry
import com.deflatedpickle.haruhi.api.plugin.Plugin
import com.deflatedpickle.haruhi.api.plugin.PluginType
import com.deflatedpickle.haruhi.event.EventProgramFinishSetup
import com.deflatedpickle.haruhi.util.RegistryUtil
import com.deflatedpickle.quiver.filepanel.api.Viewer
@Suppress("unused")
@Plugin(
value = "$[name]",
author = "$[author]",
version = "$[version]",
description = """
<br>
A viewer for PNG files
""",
type = PluginType.OTHER,
dependencies = [
"deflatedpickle@file_panel#>=1.0.0"
]
)
// TODO: Support image animation interpolation
object ImageViewerPlugin {
private val extensionSet = setOf(
"png",
"jpg", "jpeg"
)
init {
EventProgramFinishSetup.addListener {
@Suppress("UNCHECKED_CAST")
val registry = RegistryUtil.get("viewer") as Registry<String, MutableList<Viewer<Any>>>?
if (registry != null) {
for (i in this.extensionSet) {
if (registry.get(i) == null) {
@Suppress("UNCHECKED_CAST")
registry.register(i, mutableListOf(ImageViewer as Viewer<Any>))
} else {
@Suppress("UNCHECKED_CAST")
registry.get(i)!!.add(ImageViewer as Viewer<Any>)
}
}
}
}
}
}
| mit | 7ecd58cf44747af58cd077a7d1a80e12 | 29.745098 | 100 | 0.588648 | 4.48 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/database/TransferItemDao.kt | 1 | 2162 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.database
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import org.monora.uprotocol.client.android.database.model.UTransferItem
import org.monora.uprotocol.core.protocol.Direction
import org.monora.uprotocol.core.transfer.TransferItem
import org.monora.uprotocol.core.transfer.TransferItem.State.Constants.PENDING
@Dao
interface TransferItemDao {
@Delete
suspend fun delete(transferItem: UTransferItem)
@Query("SELECT * FROM transferItem WHERE groupId = :groupId ORDER BY name")
fun getAll(groupId: Long): LiveData<List<UTransferItem>>
@Query("SELECT * FROM transferItem WHERE groupId = :groupId AND state == '$PENDING' ORDER BY name LIMIT 1")
suspend fun getReceivable(groupId: Long): UTransferItem?
@Query("SELECT * FROM transferItem WHERE groupId = :groupId AND id = :id AND direction = :direction LIMIT 1")
suspend fun get(groupId: Long, id: Long, direction: Direction): UTransferItem?
@Query("SELECT * FROM transferItem WHERE location = :location AND direction = :direction")
suspend fun get(location: String, direction: Direction): UTransferItem?
@Insert
suspend fun insert(list: List<UTransferItem>)
@Update
suspend fun update(transferItem: UTransferItem)
}
| gpl-2.0 | 2e2ab80d8a3d26d0d96268d58cb6034d | 39.018519 | 113 | 0.760759 | 4.356855 | false | false | false | false |
leafclick/intellij-community | java/java-tests/testSrc/com/intellij/projectView/ModulesInProjectViewTest.kt | 1 | 5437 | // 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.projectView
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.ui.Queryable
import com.intellij.testFramework.PsiTestUtil
import com.intellij.util.io.directoryContent
import com.intellij.util.io.generateInVirtualTempDir
class ModulesInProjectViewTest : BaseProjectViewTestCase() {
init {
myPrintInfo = Queryable.PrintInfo()
}
override fun setUp() {
super.setUp()
myStructure.isShowLibraryContents = false
}
fun `test unloaded modules`() {
val root = directoryContent {
dir("loaded") {
dir("unloaded-inner") {
dir("subdir") { }
file("y.txt")
}
}
dir("unloaded") {
dir("loaded-inner") {
dir("subdir") { }
file("z.txt")
}
}
}.generateInVirtualTempDir()
PsiTestUtil.addContentRoot(createModule("loaded"), root.findChild("loaded")!!)
PsiTestUtil.addContentRoot(createModule("unloaded-inner"), root.findFileByRelativePath("loaded/unloaded-inner")!!)
PsiTestUtil.addContentRoot(createModule("unloaded"), root.findChild("unloaded")!!)
PsiTestUtil.addContentRoot(createModule("loaded-inner"), root.findFileByRelativePath("unloaded/loaded-inner")!!)
val expected = """
|Project
| loaded
| unloaded-inner
| subdir
| y.txt
| loaded-inner.iml
| loaded.iml
| test unloaded modules.iml
| unloaded
| loaded-inner
| subdir
| z.txt
| unloaded-inner.iml
| unloaded.iml
|
""".trimMargin()
assertStructureEqual(expected)
ModuleManager.getInstance(myProject).setUnloadedModules(listOf("unloaded", "unloaded-inner"))
assertStructureEqual(expected)
}
fun `test unloaded module with qualified name`() {
val root = directoryContent {
dir("unloaded") {
dir("subdir") {}
file("y.txt")
}
dir("unloaded2") {
dir("subdir") {}
}
}.generateInVirtualTempDir()
PsiTestUtil.addContentRoot(createModule("foo.bar.unloaded"), root.findChild("unloaded")!!)
PsiTestUtil.addContentRoot(createModule("unloaded2"), root.findChild("unloaded2")!!)
val expected = """
|Project
| Group: foo.bar
| unloaded
| subdir
| y.txt
| foo.bar.unloaded.iml
| test unloaded module with qualified name.iml
| unloaded2
| subdir
| unloaded2.iml
|
""".trimMargin()
assertStructureEqual(expected)
ModuleManager.getInstance(myProject).setUnloadedModules(listOf("unloaded"))
assertStructureEqual(expected)
}
fun `test do not show parent groups for single module`() {
val root = directoryContent {
dir("module") {
dir("subdir") {}
}
}.generateInVirtualTempDir()
PsiTestUtil.addContentRoot(createModule("foo.bar.module"), root.findChild("module")!!)
assertStructureEqual("""
|Project
| foo.bar.module.iml
| module
| subdir
| test do not show parent groups for single module.iml
|
""".trimMargin())
}
fun `test flatten modules option`() {
val root = directoryContent {
dir("module1") {}
dir("module2") {}
}.generateInVirtualTempDir()
PsiTestUtil.addContentRoot(createModule("foo.bar.module1"), root.findChild("module1")!!)
PsiTestUtil.addContentRoot(createModule("foo.bar.module2"), root.findChild("module2")!!)
myStructure.isFlattenModules = true
assertStructureEqual("""
|Project
| foo.bar.module1.iml
| foo.bar.module2.iml
| module1
| module2
| test flatten modules option.iml
|
""".trimMargin())
}
fun `test do not show groups duplicating module names`() {
val root = directoryContent {
dir("foo") {}
dir("foo.bar") {}
}.generateInVirtualTempDir()
PsiTestUtil.addContentRoot(createModule("xxx.foo"), root.findChild("foo")!!)
PsiTestUtil.addContentRoot(createModule("xxx.foo.bar"), root.findChild("foo.bar")!!)
assertStructureEqual("""
|Project
| Group: xxx
| foo
| foo.bar
| test do not show groups duplicating module names.iml
| xxx.foo.bar.iml
| xxx.foo.iml
|
""".trimMargin())
}
fun `test modules with common parent group`() {
val root = directoryContent {
dir("module1") {
dir("subdir") {}
}
dir("module2") {
dir("subdir") {}
}
}.generateInVirtualTempDir()
PsiTestUtil.addContentRoot(createModule("foo.bar.module1"), root.findChild("module1")!!)
PsiTestUtil.addContentRoot(createModule("foo.baz.module2"), root.findChild("module2")!!)
assertStructureEqual("""
|Project
| Group: foo
| Group: bar
| module1
| subdir
| Group: baz
| module2
| subdir
| foo.bar.module1.iml
| foo.baz.module2.iml
| test modules with common parent group.iml
|
""".trimMargin())
}
override fun getTestPath() = null
} | apache-2.0 | 91feba7074226829e3cdddfeb202712e | 29.723164 | 140 | 0.594445 | 4.658955 | false | true | false | false |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/collections/Sets.kt | 2 | 7380 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
internal object EmptySet : Set<Nothing> {
override fun equals(other: Any?): Boolean = other is Set<*> && other.isEmpty()
override fun hashCode(): Int = 0
override fun toString(): String = "[]"
override val size: Int get() = 0
override fun isEmpty(): Boolean = true
override fun contains(element: Nothing): Boolean = false
override fun containsAll(elements: Collection<Nothing>): Boolean = elements.isEmpty()
override fun iterator(): Iterator<Nothing> = EmptyIterator
private fun readResolve(): Any = EmptySet
}
/** Returns an empty read-only set. The returned set is serializable (JVM). */
public fun <T> emptySet(): Set<T> = EmptySet
/**
* Returns a new read-only set with the given elements.
* Elements of the set are iterated in the order they were specified.
*/
public fun <T> setOf(vararg elements: T): Set<T> = if (elements.size > 0) elements.toSet() else emptySet()
/** Returns an empty read-only set. */
@kotlin.internal.InlineOnly
public inline fun <T> setOf(): Set<T> = emptySet()
/**
* Returns a new [MutableSet] with the given elements.
* Elements of the set are iterated in the order they were specified.
*/
public fun <T> mutableSetOf(vararg elements: T): MutableSet<T> = elements.toCollection(HashSet<T>(mapCapacity(elements.size)))
/** Returns a new [HashSet] with the given elements. */
public fun <T> hashSetOf(vararg elements: T): HashSet<T> = elements.toCollection(HashSet<T>(mapCapacity(elements.size)))
/**
* Returns a new [LinkedHashSet] with the given elements.
* Elements of the set are iterated in the order they were specified.
*/
public fun <T> linkedSetOf(vararg elements: T): LinkedHashSet<T> = elements.toCollection(LinkedHashSet(mapCapacity(elements.size)))
/** Returns this Set if it's not `null` and the empty set otherwise. */
@kotlin.internal.InlineOnly
public inline fun <T> Set<T>?.orEmpty(): Set<T> = this ?: emptySet()
// TODO: Add SingletonSet class
/**
* Returns an immutable set containing only the specified object [element].
*/
public fun <T> setOf(element: T): Set<T> = hashSetOf(element)
/**
* Returns a new [SortedSet] with the given elements.
*/
// public fun <T> sortedSetOf(vararg elements: T): TreeSet<T> = elements.toCollection(TreeSet<T>())
/**
* Returns a new [SortedSet] with the given [comparator] and elements.
*/
//public fun <T> sortedSetOf(comparator: Comparator<in T>, vararg elements: T): TreeSet<T> = elements.toCollection(TreeSet<T>(comparator))
internal fun <T> Set<T>.optimizeReadOnlySet() = when (size) {
0 -> emptySet()
1 -> setOf(iterator().next())
else -> this
}
/**
* Returns a set containing all elements of the original set except the given [element].
*
* The returned set preserves the element iteration order of the original set.
*/
public operator fun <T> Set<T>.minus(element: T): Set<T> {
val result = LinkedHashSet<T>(mapCapacity(size))
var removed = false
return this.filterTo(result) { if (!removed && it == element) { removed = true; false } else true }
}
/**
* Returns a set containing all elements of the original set except the elements contained in the given [elements] array.
*
* The returned set preserves the element iteration order of the original set.
*/
public operator fun <T> Set<T>.minus(elements: Array<out T>): Set<T> {
val result = LinkedHashSet<T>(this)
result.removeAll(elements)
return result
}
/**
* Returns a set containing all elements of the original set except the elements contained in the given [elements] collection.
*
* The returned set preserves the element iteration order of the original set.
*/
public operator fun <T> Set<T>.minus(elements: Iterable<T>): Set<T> {
val other = elements.convertToSetForSetOperationWith(this)
if (other.isEmpty())
return this.toSet()
if (other is Set)
return this.filterNotTo(LinkedHashSet<T>()) { it in other }
val result = LinkedHashSet<T>(this)
result.removeAll(other)
return result
}
/**
* Returns a set containing all elements of the original set except the elements contained in the given [elements] sequence.
*
* The returned set preserves the element iteration order of the original set.
*/
public operator fun <T> Set<T>.minus(elements: Sequence<T>): Set<T> {
val result = LinkedHashSet<T>(this)
result.removeAll(elements)
return result
}
/**
* Returns a set containing all elements of the original set except the given [element].
*
* The returned set preserves the element iteration order of the original set.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Set<T>.minusElement(element: T): Set<T> {
return minus(element)
}
/**
* Returns a set containing all elements of the original set and then the given [element] if it isn't already in this set.
*
* The returned set preserves the element iteration order of the original set.
*/
public operator fun <T> Set<T>.plus(element: T): Set<T> {
val result = LinkedHashSet<T>(mapCapacity(size + 1))
result.addAll(this)
result.add(element)
return result
}
/**
* Returns a set containing all elements of the original set and the given [elements] array,
* which aren't already in this set.
*
* The returned set preserves the element iteration order of the original set.
*/
public operator fun <T> Set<T>.plus(elements: Array<out T>): Set<T> {
val result = LinkedHashSet<T>(mapCapacity(this.size + elements.size))
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a set containing all elements of the original set and the given [elements] collection,
* which aren't already in this set.
* The returned set preserves the element iteration order of the original set.
*/
public operator fun <T> Set<T>.plus(elements: Iterable<T>): Set<T> {
val result = LinkedHashSet<T>(mapCapacity(elements.collectionSizeOrNull()?.let { this.size + it } ?: this.size * 2))
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a set containing all elements of the original set and the given [elements] sequence,
* which aren't already in this set.
*
* The returned set preserves the element iteration order of the original set.
*/
public operator fun <T> Set<T>.plus(elements: Sequence<T>): Set<T> {
val result = LinkedHashSet<T>(mapCapacity(this.size * 2))
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a set containing all elements of the original set and then the given [element] if it isn't already in this set.
*
* The returned set preserves the element iteration order of the original set.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Set<T>.plusElement(element: T): Set<T> {
return plus(element)
}
| apache-2.0 | 4b052c34f3dbb69adb1254a4354cbab7 | 34.311005 | 138 | 0.710027 | 3.904762 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/functions/invoke/kt3821invokeOnThis.kt | 5 | 213 | //KT-3821 Invoke convention doesn't work for `this`
class A() {
operator fun invoke() = 42
fun foo() = this() // Expecting a function type, but found A
}
fun box() = if (A().foo() == 42) "OK" else "fail" | apache-2.0 | c7e7f1c96ac3c7821ff22cf5e24c64cd | 25.75 | 64 | 0.605634 | 3.179104 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/closures/capturedVarsOptimization/capturedVarsOfSize2.kt | 3 | 442 | // WITH_RUNTIME
fun box(): String {
var xl = 0L // Long, size 2
var xi = 0 // Int, size 1
var xd = 0.0 // Double, size 2
run {
xl++
xd += 1.0
xi++
}
run {
run {
xl++
xd += 1.0
xi++
}
}
if (xi != 2) return "fail: xi=$xi"
if (xl != 2L) return "fail: xl=$xl"
if (xd != 2.0) return "fail: xd=$xd"
return "OK"
} | apache-2.0 | 440874770daf832c69fb6a358cc7d866 | 16.038462 | 40 | 0.368778 | 2.966443 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/compiler-plugins/kapt/src/org/jetbrains/kotlin/idea/compilerPlugin/kapt/gradleJava/KaptGradleProjectImportHandler.kt | 5 | 2393 | // 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.compilerPlugin.kapt.gradleJava
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.idea.gradleJava.configuration.GradleProjectImportHandler
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import java.io.File
import java.util.*
class KaptGradleProjectImportHandler : GradleProjectImportHandler {
override fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode<GradleSourceSetData>) {
modifyCompilerArgumentsForPlugin(facet)
}
override fun importByModule(facet: KotlinFacet, moduleNode: DataNode<ModuleData>) {
modifyCompilerArgumentsForPlugin(facet)
}
private fun modifyCompilerArgumentsForPlugin(facet: KotlinFacet) {
val facetSettings = facet.configuration.settings
// Can't reuse const in Kapt3CommandLineProcessor, we don't have Kapt in the IDEA plugin
val compilerPluginId = "org.jetbrains.kotlin.kapt3"
val compilerArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl()
val newPluginOptions = (compilerArguments.pluginOptions ?: emptyArray()).filter { !it.startsWith("plugin:$compilerPluginId:") }
val newPluginClasspath = (compilerArguments.pluginClasspaths ?: emptyArray()).filter { !isKaptCompilerPluginPath(it) }
fun List<String>.toArrayIfNotEmpty() = takeIf { it.isNotEmpty() }?.toTypedArray()
compilerArguments.pluginOptions = newPluginOptions.toArrayIfNotEmpty()
compilerArguments.pluginClasspaths = newPluginClasspath.toArrayIfNotEmpty()
facetSettings.compilerArguments = compilerArguments
}
private fun isKaptCompilerPluginPath(path: String): Boolean {
val lastIndexOfFile = path.lastIndexOfAny(charArrayOf('/', File.separatorChar)).takeIf { it >= 0 } ?: return false
val fileName = path.drop(lastIndexOfFile + 1).toLowerCase(Locale.US)
return fileName.matches("kotlin\\-annotation\\-processing(\\-gradle)?\\-[0-9].*\\.jar".toRegex())
}
}
| apache-2.0 | f12bbb3ca8bc2e3b6d40599901d038ca | 51.021739 | 158 | 0.76682 | 5.059197 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/browsers/BrowserLauncherImpl.kt | 4 | 3175 | // 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.IdeBundle
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.showOkNoDialog
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.Urls
import org.jetbrains.ide.BuiltInServerManager
open class BrowserLauncherImpl : BrowserLauncherAppless() {
override fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? {
var effectiveBrowser = browser
if (browser == null) {
// https://youtrack.jetbrains.com/issue/WEB-26547
val browserManager = WebBrowserManager.getInstance()
if (browserManager.getDefaultBrowserPolicy() == DefaultBrowserPolicy.FIRST) {
effectiveBrowser = browserManager.firstActiveBrowser
}
}
return effectiveBrowser
}
override fun signUrl(url: String): String {
@Suppress("NAME_SHADOWING")
var url = url
@Suppress("NAME_SHADOWING")
val serverManager = BuiltInServerManager.getInstance()
val parsedUrl = Urls.parse(url, false)
if (parsedUrl != null && serverManager.isOnBuiltInWebServer(parsedUrl)) {
if (Registry.`is`("ide.built.in.web.server.activatable", false)) {
PropertiesComponent.getInstance().setValue("ide.built.in.web.server.active", true)
}
url = serverManager.addAuthToken(parsedUrl).toExternalForm()
}
return url
}
override fun openWithExplicitBrowser(url: String, browserPath: String?, project: Project?) {
val browserManager = WebBrowserManager.getInstance()
if (browserManager.getDefaultBrowserPolicy() == DefaultBrowserPolicy.FIRST) {
browserManager.firstActiveBrowser?.let {
browse(url, it, project)
return
}
}
else if (SystemInfo.isMac && "open" == browserPath) {
browserManager.firstActiveBrowser?.let {
browseUsingPath(url, null, it, project)
return
}
}
super.openWithExplicitBrowser(url, browserPath, project)
}
override fun showError(@NlsContexts.DialogMessage error: String?, browser: WebBrowser?, project: Project?, @NlsContexts.DialogTitle title: String?, fix: (() -> Unit)?) {
AppUIExecutor.onUiThread().expireWith(project ?: Disposable {}).submit {
if (showOkNoDialog(title ?: IdeBundle.message("browser.error"), error ?: IdeBundle.message("unknown.error"), project,
okText = IdeBundle.message("button.fix"),
noText = Messages.getOkButton())) {
val browserSettings = BrowserSettings()
if (ShowSettingsUtil.getInstance().editConfigurable(project, browserSettings, browser?.let { Runnable { browserSettings.selectBrowser(it) } })) {
fix?.invoke()
}
}
}
}
} | apache-2.0 | 4d974b6a0a149c57d068370ee34d5fec | 40.246753 | 171 | 0.71622 | 4.471831 | false | false | false | false |
smmribeiro/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellSelectionModelProvider.kt | 4 | 1095 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.lang.LanguageExtension
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.Key
interface NotebookCellSelectionModelProvider {
fun create(editor: Editor): NotebookCellSelectionModel
companion object : LanguageExtension<NotebookCellSelectionModelProvider>(ID)
}
val Editor.cellSelectionModel: NotebookCellSelectionModel?
get() = key.get(this) ?: install(this)
val Editor.hasCellSelectionModelSupport: Boolean
get() = key.get(this) != null || getProvider(this) != null
private val key = Key.create<NotebookCellSelectionModel>(NotebookCellSelectionModel::class.java.name)
private const val ID: String = "org.jetbrains.plugins.notebooks.notebookCellSelectionModelProvider"
private fun install(editor: Editor): NotebookCellSelectionModel? {
val model = getProvider(editor)?.create(editor)
key.set(editor, model)
return model
}
private fun getProvider(editor: Editor): NotebookCellSelectionModelProvider? =
getLanguage(editor)?.let(NotebookCellSelectionModelProvider::forLanguage) | apache-2.0 | f29249640e1c1fabbad1c6240aa808f9 | 35.533333 | 101 | 0.814612 | 4.36255 | false | false | false | false |
Flank/flank | test_runner/src/main/kotlin/ftl/reports/outcome/Util.kt | 1 | 1038 | package ftl.reports.outcome
import com.google.api.client.json.GenericJson
import com.google.api.services.toolresults.model.Environment
import com.google.api.services.toolresults.model.Step
import ftl.environment.orUnknown
import ftl.util.mutableMapProperty
internal fun Step.axisValue() = dimensionValue.axisValue()
internal fun Environment.axisValue() = dimensionValue.axisValue()
private fun List<GenericJson>?.axisValue() = this
?.toDimensionMap()
?.getValues(dimensionKeys)
?.joinToString("-")
.orUnknown()
private fun List<GenericJson>.toDimensionMap(): Map<String?, String?> = associate { it.key to it.value }
private fun Map<String?, String?>.getValues(keys: Iterable<String>) = keys.mapNotNull { key -> get(key) }
private val GenericJson.key: String? by mutableMapProperty { null }
private val GenericJson.value: String? by mutableMapProperty { null }
private val dimensionKeys = DimensionValue.values().map(DimensionValue::name)
private enum class DimensionValue { Model, Version, Locale, Orientation }
| apache-2.0 | a3ccb3a879f799aa40a3b60ae26c24c9 | 34.793103 | 105 | 0.773603 | 3.88764 | false | false | false | false |
vanniktech/lint-rules | lint-rules-android-lint/src/test/java/com/vanniktech/lintrules/android/LayoutFileNameMatchesClassDetectorTest.kt | 1 | 7061 | @file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final.
package com.vanniktech.lintrules.android
import com.android.tools.lint.checks.infrastructure.TestFiles.java
import com.android.tools.lint.checks.infrastructure.TestFiles.kt
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import org.junit.Test
class LayoutFileNameMatchesClassDetectorTest {
private val r = java(
"""
package foo;
public final class R {
public static final class layout {
public static final int activity_bar = 1;
public static final int activity_foo = 2;
public static final int activity_game_times = 3;
public static final int unit_test_activity_foo = 3;
public static final int foo2bar_activity_rider = 4;
public static final int foo2bar_activity = 5;
}
}
""",
).indented()
private val activity = java(
"""
package foo;
public abstract class Activity {
public void setContentView(int viewId) { }
}
""",
).indented()
@Test fun nonRUsage() {
lint()
.files(
r, activity,
java(
"""
package foo;
class FooActivity extends Activity {
void foo(int id) {
setContentView(id);
}
}
""",
).indented(),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expectClean()
}
@Test fun fooActivityUsesActivityFoo() {
lint()
.files(
r, activity,
java(
"""
package foo;
class FooActivity extends Activity {
void foo() {
setContentView(R.layout.activity_foo);
}
}
""",
).indented(),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expectClean()
}
@Test fun foo2BarRiderActivityUsesActivitySomethingWithResourcePrefix() {
lint()
.files(
r, activity,
kt(
"""
package foo
class Foo2BarRiderActivity : Activity() {
fun foo() {
setContentView(R.layout.foo2bar_activity_rider)
}
}
""",
).indented(),
resourcePrefix("foo2bar_"),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expectClean()
}
@Test fun foo2BarActivityUsesActivityWithResourcePrefix() {
lint()
.files(
r, activity,
kt(
"""
package foo
class Foo2BarActivity : Activity() {
fun foo() {
setContentView(R.layout.foo2bar_activity)
}
}
""",
).indented(),
resourcePrefix("foo2bar_"),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expectClean()
}
@Test fun fooActivityUsesActivityFooWithResourcePrefix() {
lint()
.files(
r, activity,
java(
"""
package foo;
class FooActivity extends Activity {
void foo() {
setContentView(R.layout.unit_test_activity_foo);
}
}
""",
).indented(),
resourcePrefix("unit_test_"),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expectClean()
}
@Test fun gameTimesActivityUsesActivityGameTimes() {
lint()
.files(
r, activity,
kt(
"""
package foo
class GameTimesActivity : Activity() {
fun foo() {
setContentView(R.layout.activity_game_times)
}
}
""",
).indented(),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expectClean()
}
@Test fun fooActivityUsesActivityBarWithResourcePrefix() {
lint()
.files(
r, activity,
java(
"""
package foo;
class FooActivity extends Activity {
void foo() {
setContentView(R.layout.activity_bar);
}
}
""",
).indented(),
resourcePrefix("unit_test_"),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expect(
"""
|src/main/java/foo/FooActivity.java:5: Warning: Parameter should be named R.layout.unit_test_activity_foo [LayoutFileNameMatchesClass]
| setContentView(R.layout.activity_bar);
| ~~~~~~~~~~~~~~~~~~~~~
|0 errors, 1 warnings
""".trimMargin(),
)
.expectFixDiffs(
"""
|Fix for src/main/java/foo/FooActivity.java line 4: Replace with unit_test_activity_foo:
|@@ -5 +5
|- setContentView(R.layout.activity_bar);
|+ setContentView(R.layout.unit_test_activity_foo);
""".trimMargin(),
)
}
@Test fun gameTimesActivityUsesActivityBar() {
lint()
.files(
r, activity,
java(
"""
package foo;
class GameTimesActivity extends Activity {
void foo() {
setContentView(R.layout.activity_bar);
}
}
""",
).indented(),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expect(
"""
|src/foo/GameTimesActivity.java:5: Warning: Parameter should be named R.layout.activity_game_times [LayoutFileNameMatchesClass]
| setContentView(R.layout.activity_bar);
| ~~~~~~~~~~~~~~~~~~~~~
|0 errors, 1 warnings
""".trimMargin(),
)
.expectFixDiffs(
"""
|Fix for src/foo/GameTimesActivity.java line 4: Replace with activity_game_times:
|@@ -5 +5
|- setContentView(R.layout.activity_bar);
|+ setContentView(R.layout.activity_game_times);
""".trimMargin(),
)
}
@Test fun themesActivityUsesActivityBarInKotlin() {
lint()
.files(
r, activity,
kt(
"""
package foo
class ThemesActivity : Activity() {
fun foo() {
setContentView(R.layout.activity_bar)
}
}
""",
).indented(),
)
.issues(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS)
.run()
.expect(
"""
|src/foo/ThemesActivity.kt:5: Warning: Parameter should be named R.layout.activity_themes [LayoutFileNameMatchesClass]
| setContentView(R.layout.activity_bar)
| ~~~~~~~~~~~~~~~~~~~~~
|0 errors, 1 warnings
""".trimMargin(),
)
.expectFixDiffs(
"""
|Fix for src/foo/ThemesActivity.kt line 4: Replace with activity_themes:
|@@ -5 +5
|- setContentView(R.layout.activity_bar)
|+ setContentView(R.layout.activity_themes)
""".trimMargin(),
)
}
}
| apache-2.0 | 2c2d9fdc9bea5ebfb27bb3e805873be6 | 24.676364 | 146 | 0.512392 | 4.48033 | false | true | false | false |
firebase/firebase-android-sdk | tools/lint/src/main/kotlin/Annotations.kt | 1 | 2812 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.lint.checks
import com.android.tools.lint.detector.api.JavaContext
import com.intellij.lang.jvm.JvmModifier
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UAnonymousClass
import org.jetbrains.uast.UElement
import org.jetbrains.uast.ULambdaExpression
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.getParentOfType
internal const val ANNOTATION = "com.google.firebase.annotations.DeferredApi"
fun hasDeferredApiAnnotation(context: JavaContext, methodCall: UElement): Boolean {
lambdaMethod(methodCall)?.let {
return hasDeferredApiAnnotation(context, it)
}
val method =
methodCall.getParentOfType<UElement>(
UMethod::class.java,
true,
UAnonymousClass::class.java,
ULambdaExpression::class.java
) as? PsiMethod
return hasDeferredApiAnnotation(context, method)
}
fun hasDeferredApiAnnotation(context: JavaContext, calledMethod: PsiMethod?): Boolean {
var method = calledMethod ?: return false
while (true) {
for (annotation in method.modifierList.annotations) {
annotation.qualifiedName?.let {
if (it == ANNOTATION) {
return@hasDeferredApiAnnotation true
}
}
}
method = context.evaluator.getSuperMethod(method) ?: break
}
var cls = method.containingClass ?: return false
while (true) {
val modifierList = cls.modifierList
if (modifierList != null) {
for (annotation in modifierList.annotations) {
annotation.qualifiedName?.let {
if (it == ANNOTATION) {
return@hasDeferredApiAnnotation true
}
}
}
}
cls = cls.superClass ?: break
}
return false
}
fun lambdaMethod(element: UElement): PsiMethod? {
val lambda =
element.getParentOfType<ULambdaExpression>(
ULambdaExpression::class.java,
true,
UMethod::class.java,
UAnonymousClass::class.java
)
?: return null
val type = lambda.functionalInterfaceType
if (type is PsiClassType) {
val resolved = type.resolve()
if (resolved != null) {
return resolved.allMethods.firstOrNull { it.hasModifier(JvmModifier.ABSTRACT) }
}
}
return null
}
| apache-2.0 | b737cbcd9dee09cfd6092275c467cdf1 | 28.914894 | 87 | 0.713371 | 4.407524 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm-debugger/eval4j/src/org/jetbrains/eval4j/interpreter.kt | 7 | 15338 | // 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.eval4j
import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Opcodes.*
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException
import org.jetbrains.org.objectweb.asm.tree.analysis.Interpreter
class UnsupportedByteCodeException(message: String) : RuntimeException(message)
interface Eval {
fun loadClass(classType: Type): Value
fun loadString(str: String): Value
fun newInstance(classType: Type): Value
fun isInstanceOf(value: Value, targetType: Type): Boolean
fun newArray(arrayType: Type, size: Int): Value
fun newMultiDimensionalArray(arrayType: Type, dimensionSizes: List<Int>): Value
fun getArrayLength(array: Value): Value
fun getArrayElement(array: Value, index: Value): Value
fun setArrayElement(array: Value, index: Value, newValue: Value)
fun getStaticField(fieldDesc: FieldDescription): Value
fun setStaticField(fieldDesc: FieldDescription, newValue: Value)
fun invokeStaticMethod(methodDesc: MethodDescription, arguments: List<Value>): Value
fun getField(instance: Value, fieldDesc: FieldDescription): Value
fun setField(instance: Value, fieldDesc: FieldDescription, newValue: Value)
fun invokeMethod(instance: Value, methodDesc: MethodDescription, arguments: List<Value>, invokeSpecial: Boolean = false): Value
}
class SingleInstructionInterpreter(private val eval: Eval) : Interpreter<Value>(API_VERSION) {
override fun newValue(type: Type?): Value? {
if (type == null) {
return NOT_A_VALUE
}
return makeNotInitializedValue(type)
}
override fun newOperation(insn: AbstractInsnNode): Value {
return when (insn.opcode) {
ACONST_NULL -> {
return NULL_VALUE
}
ICONST_M1 -> int(-1)
ICONST_0 -> int(0)
ICONST_1 -> int(1)
ICONST_2 -> int(2)
ICONST_3 -> int(3)
ICONST_4 -> int(4)
ICONST_5 -> int(5)
LCONST_0 -> long(0)
LCONST_1 -> long(1)
FCONST_0 -> float(0.0f)
FCONST_1 -> float(1.0f)
FCONST_2 -> float(2.0f)
DCONST_0 -> double(0.0)
DCONST_1 -> double(1.0)
BIPUSH, SIPUSH -> int((insn as IntInsnNode).operand)
LDC -> {
when (val cst = (insn as LdcInsnNode).cst) {
is Int -> int(cst)
is Float -> float(cst)
is Long -> long(cst)
is Double -> double(cst)
is String -> eval.loadString(cst)
is Type -> {
when (cst.sort) {
Type.OBJECT, Type.ARRAY -> eval.loadClass(cst)
Type.METHOD -> throw UnsupportedByteCodeException("Method handles are not supported")
else -> throw UnsupportedByteCodeException("Illegal LDC constant $cst")
}
}
is Handle -> throw UnsupportedByteCodeException("Method handles are not supported")
else -> throw UnsupportedByteCodeException("Illegal LDC constant $cst")
}
}
JSR -> LabelValue((insn as JumpInsnNode).label)
GETSTATIC -> eval.getStaticField(FieldDescription(insn as FieldInsnNode))
NEW -> eval.newInstance(Type.getObjectType((insn as TypeInsnNode).desc))
else -> throw UnsupportedByteCodeException("$insn")
}
}
override fun copyOperation(insn: AbstractInsnNode, value: Value): Value {
return value
}
override fun unaryOperation(insn: AbstractInsnNode, value: Value): Value? {
return when (insn.opcode) {
INEG -> int(-value.int)
IINC -> int(value.int + (insn as IincInsnNode).incr)
L2I -> int(value.long.toInt())
F2I -> int(value.float.toInt())
D2I -> int(value.double.toInt())
I2B -> byte(value.int.toByte())
I2C -> char(value.int.toChar())
I2S -> short(value.int.toShort())
FNEG -> float(-value.float)
I2F -> float(value.int.toFloat())
L2F -> float(value.long.toFloat())
D2F -> float(value.double.toFloat())
LNEG -> long(-value.long)
I2L -> long(value.int.toLong())
F2L -> long(value.float.toLong())
D2L -> long(value.double.toLong())
DNEG -> double(-value.double)
I2D -> double(value.int.toDouble())
L2D -> double(value.long.toDouble())
F2D -> double(value.float.toDouble())
IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IFNULL, IFNONNULL -> {
// Handled by interpreter loop, see checkUnaryCondition()
null
}
// TODO: switch
TABLESWITCH,
LOOKUPSWITCH -> throw UnsupportedByteCodeException("Switch is not supported yet")
PUTSTATIC -> {
eval.setStaticField(FieldDescription(insn as FieldInsnNode), value)
null
}
GETFIELD -> eval.getField(value, FieldDescription(insn as FieldInsnNode))
NEWARRAY -> {
val typeStr = when ((insn as IntInsnNode).operand) {
T_BOOLEAN -> "[Z"
T_CHAR -> "[C"
T_BYTE -> "[B"
T_SHORT -> "[S"
T_INT -> "[I"
T_FLOAT -> "[F"
T_DOUBLE -> "[D"
T_LONG -> "[J"
else -> throw AnalyzerException(insn, "Invalid array type")
}
eval.newArray(Type.getType(typeStr), value.int)
}
ANEWARRAY -> {
val desc = (insn as TypeInsnNode).desc
eval.newArray(Type.getType("[" + Type.getObjectType(desc)), value.int)
}
ARRAYLENGTH -> eval.getArrayLength(value)
ATHROW -> {
// Handled by interpreter loop
null
}
CHECKCAST -> {
val targetType = Type.getObjectType((insn as TypeInsnNode).desc)
when {
value == NULL_VALUE -> NULL_VALUE
eval.isInstanceOf(value, targetType) -> ObjectValue(value.obj(), targetType)
else -> throwInterpretingException(
ClassCastException(
"${value.asmType.className} cannot be cast to ${targetType.className}"
)
)
}
}
INSTANCEOF -> {
val targetType = Type.getObjectType((insn as TypeInsnNode).desc)
boolean(eval.isInstanceOf(value, targetType))
}
// TODO: maybe just do nothing?
MONITORENTER, MONITOREXIT -> throw UnsupportedByteCodeException("Monitor instructions are not supported")
else -> throw UnsupportedByteCodeException("$insn")
}
}
fun checkUnaryCondition(value: Value, opcode: Int): Boolean {
return when (opcode) {
IFEQ -> value.int == 0
IFNE -> value.int != 0
IFLT -> value.int < 0
IFGT -> value.int > 0
IFLE -> value.int <= 0
IFGE -> value.int >= 0
IFNULL -> value.obj() == null
IFNONNULL -> value.obj() != null
else -> throw UnsupportedByteCodeException("Unknown opcode: $opcode")
}
}
private fun divisionByZero(): Nothing = throwInterpretingException(ArithmeticException("Division by zero"))
override fun binaryOperation(insn: AbstractInsnNode, value1: Value, value2: Value): Value? {
return when (insn.opcode) {
IALOAD, BALOAD, CALOAD, SALOAD,
FALOAD, LALOAD, DALOAD,
AALOAD -> eval.getArrayElement(value1, value2)
IADD -> int(value1.int + value2.int)
ISUB -> int(value1.int - value2.int)
IMUL -> int(value1.int * value2.int)
IDIV -> {
val divider = value2.int
if (divider == 0) {
divisionByZero()
}
int(value1.int / divider)
}
IREM -> {
val divider = value2.int
if (divider == 0) {
divisionByZero()
}
int(value1.int % divider)
}
ISHL -> int(value1.int shl value2.int)
ISHR -> int(value1.int shr value2.int)
IUSHR -> int(value1.int ushr value2.int)
IAND -> int(value1.int and value2.int)
IOR -> int(value1.int or value2.int)
IXOR -> int(value1.int xor value2.int)
LADD -> long(value1.long + value2.long)
LSUB -> long(value1.long - value2.long)
LMUL -> long(value1.long * value2.long)
LDIV -> {
val divider = value2.long
if (divider == 0L) {
divisionByZero()
}
long(value1.long / divider)
}
LREM -> {
val divider = value2.long
if (divider == 0L) {
divisionByZero()
}
long(value1.long % divider)
}
LSHL -> long(value1.long shl value2.int)
LSHR -> long(value1.long shr value2.int)
LUSHR -> long(value1.long ushr value2.int)
LAND -> long(value1.long and value2.long)
LOR -> long(value1.long or value2.long)
LXOR -> long(value1.long xor value2.long)
FADD -> float(value1.float + value2.float)
FSUB -> float(value1.float - value2.float)
FMUL -> float(value1.float * value2.float)
FDIV -> {
val divider = value2.float
if (divider == 0f) {
divisionByZero()
}
float(value1.float / divider)
}
FREM -> {
val divider = value2.float
if (divider == 0f) {
divisionByZero()
}
float(value1.float % divider)
}
DADD -> double(value1.double + value2.double)
DSUB -> double(value1.double - value2.double)
DMUL -> double(value1.double * value2.double)
DDIV -> {
val divider = value2.double
if (divider == 0.0) {
divisionByZero()
}
double(value1.double / divider)
}
DREM -> {
val divider = value2.double
if (divider == 0.0) {
divisionByZero()
}
double(value1.double % divider)
}
LCMP -> {
val l1 = value1.long
val l2 = value2.long
int(
when {
l1 > l2 -> 1
l1 == l2 -> 0
else -> -1
}
)
}
FCMPL,
FCMPG -> {
val l1 = value1.float
val l2 = value2.float
int(
when {
l1 > l2 -> 1
l1 == l2 -> 0
l1 < l2 -> -1
// one of them is NaN
else -> if (insn.opcode == FCMPG) 1 else -1
}
)
}
DCMPL,
DCMPG -> {
val l1 = value1.double
val l2 = value2.double
int(
when {
l1 > l2 -> 1
l1 == l2 -> 0
l1 < l2 -> -1
// one of them is NaN
else -> if (insn.opcode == DCMPG) 1 else -1
}
)
}
IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE -> {
// Handled by interpreter loop, see checkBinaryCondition()
null
}
PUTFIELD -> {
eval.setField(value1, FieldDescription(insn as FieldInsnNode), value2)
null
}
else -> throw UnsupportedByteCodeException("$insn")
}
}
fun checkBinaryCondition(value1: Value, value2: Value, opcode: Int): Boolean {
return when (opcode) {
IF_ICMPEQ -> value1.int == value2.int
IF_ICMPNE -> value1.int != value2.int
IF_ICMPLT -> value1.int < value2.int
IF_ICMPGT -> value1.int > value2.int
IF_ICMPLE -> value1.int <= value2.int
IF_ICMPGE -> value1.int >= value2.int
IF_ACMPEQ -> value1.obj() == value2.obj()
IF_ACMPNE -> value1.obj() != value2.obj()
else -> throw UnsupportedByteCodeException("Unknown opcode: $opcode")
}
}
override fun ternaryOperation(insn: AbstractInsnNode, value1: Value, value2: Value, value3: Value): Value? {
return when (insn.opcode) {
IASTORE, LASTORE, FASTORE, DASTORE, AASTORE, BASTORE, CASTORE, SASTORE -> {
eval.setArrayElement(value1, value2, value3)
null
}
else -> throw UnsupportedByteCodeException("$insn")
}
}
override fun naryOperation(insn: AbstractInsnNode, values: List<Value>): Value {
return when (insn.opcode) {
MULTIANEWARRAY -> {
val node = insn as MultiANewArrayInsnNode
eval.newMultiDimensionalArray(Type.getType(node.desc), values.map(Value::int))
}
INVOKEVIRTUAL, INVOKESPECIAL, INVOKEINTERFACE -> {
eval.invokeMethod(
values[0],
MethodDescription(insn as MethodInsnNode),
values.subList(1, values.size),
insn.opcode == INVOKESPECIAL
)
}
INVOKESTATIC -> eval.invokeStaticMethod(MethodDescription(insn as MethodInsnNode), values)
INVOKEDYNAMIC -> throw UnsupportedByteCodeException("INVOKEDYNAMIC is not supported")
else -> throw UnsupportedByteCodeException("$insn")
}
}
override fun returnOperation(insn: AbstractInsnNode, value: Value, expected: Value) {
when (insn.opcode) {
IRETURN, LRETURN, FRETURN, DRETURN, ARETURN -> {
// Handled by interpreter loop
}
else -> throw UnsupportedByteCodeException("$insn")
}
}
override fun merge(v: Value, w: Value): Value {
// We always remember the NEW value
return w
}
}
| apache-2.0 | 508d8669c5a97b0d33fa89a904aa1f33 | 35.606205 | 131 | 0.50326 | 4.492677 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceConstant/KotlinIntroduceConstantHandler.kt | 1 | 8154 | // 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.introduceConstant
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.NameUtil
import com.intellij.refactoring.RefactoringActionHandler
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.util.ElementKind
import org.jetbrains.kotlin.idea.refactoring.getExtractionContainers
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.*
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceProperty.KotlinInplacePropertyIntroducer
import org.jetbrains.kotlin.idea.refactoring.introduce.selectElementsWithTargetSibling
import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHint
import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHintByKey
import org.jetbrains.kotlin.idea.refactoring.introduce.validateExpressionElements
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.plainContent
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinIntroduceConstantHandler(
val helper: ExtractionEngineHelper = InteractiveExtractionHelper
) : RefactoringActionHandler {
object InteractiveExtractionHelper : ExtractionEngineHelper(INTRODUCE_CONSTANT) {
private fun getExtractionTarget(descriptor: ExtractableCodeDescriptor) =
propertyTargets.firstOrNull { it.isAvailable(descriptor) }
override fun validate(descriptor: ExtractableCodeDescriptor) =
descriptor.validate(getExtractionTarget(descriptor) ?: ExtractionTarget.FUNCTION)
override fun configureAndRun(
project: Project,
editor: Editor,
descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts,
onFinish: (ExtractionResult) -> Unit
) {
val descriptor = descriptorWithConflicts.descriptor
val target = getExtractionTarget(descriptor)
if (target != null) {
val options = ExtractionGeneratorOptions(target = target, delayInitialOccurrenceReplacement = true, isConst = true)
doRefactor(ExtractionGeneratorConfiguration(descriptor, options), onFinish)
} else {
showErrorHint(
project,
editor,
KotlinBundle.message("error.text.can.t.introduce.constant.for.this.expression"),
INTRODUCE_CONSTANT
)
}
}
}
fun doInvoke(project: Project, editor: Editor, file: KtFile, elements: List<PsiElement>, target: PsiElement) {
val adjustedElements = (elements.singleOrNull() as? KtBlockExpression)?.statements ?: elements
when {
adjustedElements.isEmpty() -> {
showErrorHintByKey(
project, editor, "cannot.refactor.no.expression",
INTRODUCE_CONSTANT
)
}
else -> {
val options = ExtractionOptions(extractAsProperty = true)
val extractionData = ExtractionData(file, adjustedElements.toRange(), target, null, options)
ExtractionEngine(helper).run(editor, extractionData) {
val property = it.declaration as KtProperty
val descriptor = it.config.descriptor
editor.caretModel.moveToOffset(property.textOffset)
editor.selectionModel.removeSelection()
if (editor.settings.isVariableInplaceRenameEnabled && !isUnitTestMode()) {
with(PsiDocumentManager.getInstance(project)) {
commitDocument(editor.document)
doPostponedOperationsAndUnblockDocument(editor.document)
}
val introducer = KotlinInplacePropertyIntroducer(
property = property,
editor = editor,
project = project,
title = INTRODUCE_CONSTANT,
doNotChangeVar = false,
exprType = descriptor.returnType,
extractionResult = it,
availableTargets = listOf(ExtractionTarget.PROPERTY_WITH_GETTER)
)
introducer.performInplaceRefactoring(LinkedHashSet(getNameSuggestions(property) + descriptor.suggestedNames))
} else {
processDuplicatesSilently(it.duplicateReplacers, project)
}
}
}
}
}
private fun getNameSuggestions(property: KtProperty): List<String> {
val initializerValue = property.initializer.safeAs<KtStringTemplateExpression>()?.plainContent
val identifierValue = property.identifyingElement?.text
return listOfNotNull(initializerValue, identifierValue).map { NameUtil.capitalizeAndUnderscore(it) }
}
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
if (file !is KtFile) return
selectElements(editor, file) { elements, targets -> doInvoke(project, editor, file, elements, targets) }
}
fun selectElements(
editor: Editor,
file: KtFile,
continuation: (elements: List<PsiElement>, targets: PsiElement) -> Unit
) {
selectElementsWithTargetSibling(
INTRODUCE_CONSTANT,
editor,
file,
KotlinBundle.message("title.select.target.code.block"),
listOf(ElementKind.EXPRESSION),
::validateElements,
{ _, sibling ->
sibling.getExtractionContainers(strict = true, includeAll = true)
.filter { (it is KtFile && !it.isScript()) }
},
continuation
)
}
private fun validateElements(elements: List<PsiElement>): String? {
val errorMessage = validateExpressionElements(elements)
return when {
errorMessage != null -> errorMessage
elements.any {
// unchecked cast always succeeds because only expressions are selected in selectElements
(it as KtExpression).isNotConst()
} -> KotlinBundle.message(
"error.text.can.t.introduce.constant.for.this.expression.because.not.constant"
)
else -> null
}
}
private fun KtExpression.isNotConst(): Boolean {
when (this) {
// Handle these two expressions separately because in case of selecting part of a string
// a temp file will be created in which the analysis fails
is KtConstantExpression -> return false
is KtStringTemplateExpression -> return this.hasInterpolation()
else -> {
val constInfo = ConstantExpressionEvaluator.getConstant(this, analyze(BodyResolveMode.PARTIAL))
return constInfo == null || constInfo.usesNonConstValAsConstant
}
}
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) {
throw AssertionError("$INTRODUCE_CONSTANT can only be invoked from editor")
}
}
val INTRODUCE_CONSTANT: String
@Nls
get() = KotlinBundle.message("introduce.constant")
| apache-2.0 | f0a158dedffd16e1aa63d55c57571045 | 45.862069 | 158 | 0.654893 | 5.539402 | false | false | false | false |
nsk-mironov/sento | sento-compiler/src/main/kotlin/io/mironov/sento/compiler/annotations/Metadata.kt | 1 | 529 | package io.mironov.sento.compiler.annotations
@AnnotationDelegate("kotlin.Metadata")
interface Metadata {
companion object {
const val KIND_CLASS = 1
const val KIND_FILE = 2
const val KIND_SYNTHETIC_CLASS = 3
const val KIND_MULTIFILE_CLASS_FACADE = 4
const val KIND_MULTIFILE_CLASS_PART = 5
}
fun k(): Int
fun d1(): Array<String>
fun d2(): Array<String>
}
val Metadata.data: Array<String>
get() = d1()
val Metadata.strings: Array<String>
get() = d2()
val Metadata.kind: Int
get() = k()
| apache-2.0 | d837043d602229704284827d372a49ef | 18.592593 | 45 | 0.672968 | 3.369427 | false | false | false | false |
JetBrains/xodus | environment/src/main/kotlin/jetbrains/exodus/io/FileDataReader.kt | 1 | 4508 | /**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.io
import jetbrains.exodus.ExodusException
import jetbrains.exodus.core.dataStructures.LongArrayList
import jetbrains.exodus.log.Log
import jetbrains.exodus.log.LogUtil
import mu.KLogging
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
class FileDataReader(val dir: File) : DataReader, KLogging() {
companion object : KLogging()
private var useNio = false
private var log: Log? = null
internal var usedWithWatcher = false
override fun getBlocks(): Iterable<Block> {
val files = LogUtil.listFileAddresses(dir)
files.sort()
return toBlocks(files)
}
override fun getBlocks(fromAddress: Long): Iterable<Block> {
val files = LogUtil.listFileAddresses(fromAddress, dir)
files.sort()
return toBlocks(files)
}
override fun close() {
try {
SharedOpenFilesCache.getInstance().removeDirectory(dir)
if (useNio) {
SharedMappedFilesCache.getInstance().removeDirectory(dir)
}
} catch (e: IOException) {
throw ExodusException("Can't close all files", e)
}
}
fun setLog(log: Log) {
this.log = log
}
override fun getLocation(): String {
return dir.path
}
internal fun useNio(freePhysicalMemoryThreshold: Long) {
useNio = true
SharedMappedFilesCache.createInstance(freePhysicalMemoryThreshold)
}
private fun toBlocks(files: LongArrayList) =
files.toArray().asSequence().map { address -> FileBlock(address, this) }.asIterable()
class FileBlock(private val address: Long, private val reader: FileDataReader) :
File(reader.dir, LogUtil.getLogFilename(address)), Block {
override fun getAddress() = address
override fun read(output: ByteArray, position: Long, offset: Int, count: Int): Int {
try {
val log = reader.log
val immutable = log?.isImmutableFile(address) ?: !canWrite()
val filesCache = SharedOpenFilesCache.getInstance()
val file = if (immutable && !reader.usedWithWatcher) filesCache.getCachedFile(this) else filesCache.openFile(this)
file.use { f ->
if (reader.useNio &&
/* only read-only (immutable) files can be mapped */ immutable) {
try {
SharedMappedFilesCache.getInstance().getFileBuffer(f).use { mappedBuffer ->
val buffer = mappedBuffer.buffer
buffer.position(position.toInt())
buffer.get(output, offset, count)
return count
}
} catch (t: Throwable) {
// if we failed to read mapped file, then try ordinary RandomAccessFile.read()
if (logger.isWarnEnabled) {
logger.warn("Failed to transfer bytes from memory mapped file", t)
}
}
}
f.seek(position)
return readFully(f, output, offset, count)
}
} catch (e: IOException) {
throw ExodusException("Can't read file $absolutePath", e)
}
}
private fun readFully(file: RandomAccessFile, output: ByteArray, offset: Int, size: Int): Int {
var read = 0
while (read < size) {
val r = file.read(output, offset + read, size - read)
if (r == -1) {
break
}
read += r
}
return read
}
override fun refresh() = this
}
}
| apache-2.0 | e78da8314c9b54bf336e7067d07926fc | 33.676923 | 130 | 0.572981 | 4.857759 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinDefinitionsSearcher.kt | 1 | 7564 | // 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.search.ideaExtensions
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.search.searches.DefinitionsScopedSearch
import com.intellij.util.Processor
import com.intellij.util.QueryExecutor
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.toFakeLightClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.actualsForExpected
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isExpectDeclaration
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachImplementation
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingMethod
import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import java.util.concurrent.Callable
class KotlinDefinitionsSearcher : QueryExecutor<PsiElement, DefinitionsScopedSearch.SearchParameters> {
override fun execute(queryParameters: DefinitionsScopedSearch.SearchParameters, consumer: Processor<in PsiElement>): Boolean {
val processor = skipDelegatedMethodsConsumer(consumer)
val element = queryParameters.element
val scope = queryParameters.scope
return when (element) {
is KtClass -> {
val isExpectEnum = runReadAction { element.isEnum() && element.isExpectDeclaration() }
if (isExpectEnum) {
processActualDeclarations(element, processor)
} else {
processClassImplementations(element, processor) && processActualDeclarations(element, processor)
}
}
is KtObjectDeclaration -> {
processActualDeclarations(element, processor)
}
is KtLightClass -> {
val useScope = runReadAction { element.useScope }
if (useScope is LocalSearchScope)
processLightClassLocalImplementations(element, useScope, processor)
else
true
}
is KtNamedFunction, is KtSecondaryConstructor -> {
processFunctionImplementations(element as KtFunction, scope, processor) && processActualDeclarations(element, processor)
}
is KtProperty -> {
processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor)
}
is KtParameter -> {
if (isFieldParameter(element)) {
processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor)
} else {
true
}
}
else -> true
}
}
companion object {
private fun skipDelegatedMethodsConsumer(baseConsumer: Processor<in PsiElement>): Processor<PsiElement> = Processor { element ->
if (isDelegated(element)) {
return@Processor true
}
baseConsumer.process(element)
}
private fun isDelegated(element: PsiElement): Boolean = element is KtLightMethod && element.isDelegated
private fun isFieldParameter(parameter: KtParameter): Boolean = runReadAction {
KtPsiUtil.getClassIfParameterIsProperty(parameter) != null
}
private fun processClassImplementations(klass: KtClass, consumer: Processor<PsiElement>): Boolean {
val psiClass = runReadAction { klass.toLightClass() ?: klass.toFakeLightClass() }
val searchScope = runReadAction { psiClass.useScope }
if (searchScope is LocalSearchScope) {
return processLightClassLocalImplementations(psiClass, searchScope, consumer)
}
return runReadAction { ContainerUtil.process(ClassInheritorsSearch.search(psiClass, true), consumer) }
}
private fun processLightClassLocalImplementations(
psiClass: KtLightClass,
searchScope: LocalSearchScope,
consumer: Processor<PsiElement>
): Boolean {
// workaround for IDEA optimization that uses Java PSI traversal to locate inheritors in local search scope
val virtualFiles = runReadAction {
searchScope.scope.mapTo(HashSet()) { it.containingFile.virtualFile }
}
val globalScope = GlobalSearchScope.filesScope(psiClass.project, virtualFiles)
return ContainerUtil.process(ClassInheritorsSearch.search(psiClass, globalScope, true)) { candidate ->
val candidateOrigin = candidate.unwrapped ?: candidate
val inScope = runReadAction { candidateOrigin in searchScope }
if (inScope) {
consumer.process(candidate)
} else {
true
}
}
}
private fun processFunctionImplementations(
function: KtFunction,
scope: SearchScope,
consumer: Processor<PsiElement>,
): Boolean =
ReadAction.nonBlocking(Callable {
function.toPossiblyFakeLightMethods().firstOrNull()?.forEachImplementation(scope, consumer::process) ?: true
}).executeSynchronously()
private fun processPropertyImplementations(
declaration: KtNamedDeclaration,
scope: SearchScope,
consumer: Processor<PsiElement>
): Boolean = runReadAction {
processPropertyImplementationsMethods(declaration.toPossiblyFakeLightMethods(), scope, consumer)
}
private fun processActualDeclarations(declaration: KtDeclaration, consumer: Processor<PsiElement>): Boolean = runReadAction {
if (!declaration.isExpectDeclaration()) true
else declaration.actualsForExpected().all(consumer::process)
}
fun processPropertyImplementationsMethods(
accessors: Iterable<PsiMethod>,
scope: SearchScope,
consumer: Processor<PsiElement>
): Boolean = accessors.all { method ->
method.forEachOverridingMethod(scope) { implementation ->
if (isDelegated(implementation)) return@forEachOverridingMethod true
val elementToProcess = runReadAction {
when (val mirrorElement = (implementation as? KtLightMethod)?.kotlinOrigin) {
is KtProperty, is KtParameter -> mirrorElement
is KtPropertyAccessor -> if (mirrorElement.parent is KtProperty) mirrorElement.parent else implementation
else -> implementation
}
}
consumer.process(elementToProcess)
}
}
}
}
| apache-2.0 | d2f73325d5d84856f7654775d6e4f4a2 | 43.494118 | 136 | 0.66605 | 5.960599 | false | false | false | false |
sheungon/SotwtmSupportLib | lib-sotwtm-support/src/main/kotlin/com/sotwtm/support/dialog/StringOrStringRes.kt | 1 | 1265 | package com.sotwtm.support.dialog
import android.content.Context
import androidx.databinding.ObservableField
import androidx.annotation.StringRes
import com.sotwtm.util.Log
class StringOrStringRes(private val context: Context) : ObservableField<String?>() {
constructor(
context: Context,
@StringRes msgRes: Int
) : this(context) {
this.msgRes = msgRes
}
constructor(
context: Context,
msg: String
) : this(context) {
set(msg)
}
var msgRes: Int? = null
@Synchronized
set(value) {
field = value
if (value != null) {
set(null)
}
}
@Synchronized
override fun get(): String? = msgRes?.let {
try {
context.getString(it)
} catch (th: Throwable) {
Log.e("Error on get resources $it", th)
null
}
} ?: super.get()
?: ""
@Synchronized
override fun set(value: String?) {
if (value != null) {
msgRes = null
}
super.set(value)
}
@Synchronized
fun sync(value: StringOrStringRes) {
msgRes = value.msgRes
if (msgRes == null) {
set(value.get())
}
}
} | apache-2.0 | 50781dc1307c8c6357486e6ba363b0b6 | 20.457627 | 84 | 0.531225 | 4.332192 | false | false | false | false |
androidx/androidx | compose/ui/ui-util/src/commonMain/kotlin/androidx/compose/ui/util/ListUtils.kt | 3 | 6992 | /*
* 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.util
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
/**
* Iterates through a [List] using the index and calls [action] for each item.
* This does not allocate an iterator like [Iterable.forEach].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {
contract { callsInPlace(action) }
for (index in indices) {
val item = get(index)
action(item)
}
}
/**
* Iterates through a [List] using the index and calls [action] for each item.
* This does not allocate an iterator like [Iterable.forEachIndexed].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T> List<T>.fastForEachIndexed(action: (Int, T) -> Unit) {
contract { callsInPlace(action) }
for (index in indices) {
val item = get(index)
action(index, item)
}
}
/**
* Returns `true` if all elements match the given [predicate].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T> List<T>.fastAll(predicate: (T) -> Boolean): Boolean {
contract { callsInPlace(predicate) }
fastForEach { if (!predicate(it)) return false }
return true
}
/**
* Returns `true` if at least one element matches the given [predicate].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T> List<T>.fastAny(predicate: (T) -> Boolean): Boolean {
contract { callsInPlace(predicate) }
fastForEach { if (predicate(it)) return true }
return false
}
/**
* Returns the first value that [predicate] returns `true` for or `null` if nothing matches.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T> List<T>.fastFirstOrNull(predicate: (T) -> Boolean): T? {
contract { callsInPlace(predicate) }
fastForEach { if (predicate(it)) return it }
return null
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the
* list.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T> List<T>.fastSumBy(selector: (T) -> Int): Int {
contract { callsInPlace(selector) }
var sum = 0
fastForEach { element ->
sum += selector(element)
}
return sum
}
/**
* Returns a list containing the results of applying the given [transform] function
* to each element in the original collection.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T, R> List<T>.fastMap(transform: (T) -> R): List<R> {
contract { callsInPlace(transform) }
val target = ArrayList<R>(size)
fastForEach {
target += transform(it)
}
return target
}
// TODO: should be fastMaxByOrNull to match stdlib
/**
* Returns the first element yielding the largest value of the given function or `null` if there
* are no elements.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T, R : Comparable<R>> List<T>.fastMaxBy(selector: (T) -> R): T? {
contract { callsInPlace(selector) }
if (isEmpty()) return null
var maxElem = get(0)
var maxValue = selector(maxElem)
for (i in 1..lastIndex) {
val e = get(i)
val v = selector(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Applies the given [transform] function to each element of the original collection
* and appends the results to the given [destination].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T, R, C : MutableCollection<in R>> List<T>.fastMapTo(
destination: C,
transform: (T) -> R
): C {
contract { callsInPlace(transform) }
fastForEach { item ->
destination.add(transform(item))
}
return destination
}
| apache-2.0 | a14ea9566d0acf8128cacebf9b2e338a | 36.390374 | 96 | 0.708238 | 4.088889 | false | false | false | false |
androidx/androidx | compose/foundation/foundation-layout/src/androidAndroidTest/kotlin/androidx/compose/foundation/layout/BoxWithConstraintsTest.kt | 3 | 36202 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("Deprecation")
package androidx.compose.foundation.layout
import android.graphics.Bitmap
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.View
import android.view.ViewTreeObserver
import androidx.annotation.RequiresApi
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasurePolicy
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.node.Ref
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import androidx.test.rule.ActivityTestRule
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
@MediumTest
@RunWith(AndroidJUnit4::class)
class BoxWithConstraintsTest : LayoutTest() {
var drawLatch = CountDownLatch(1)
@Test
fun withConstraintsTest() {
val size = 20
val countDownLatch = CountDownLatch(1)
val topConstraints = Ref<Constraints>()
val paddedConstraints = Ref<Constraints>()
val firstChildConstraints = Ref<Constraints>()
val secondChildConstraints = Ref<Constraints>()
show {
BoxWithConstraints {
topConstraints.value = constraints
Padding(size = size) {
val drawModifier = Modifier.drawBehind {
countDownLatch.countDown()
}
BoxWithConstraints(drawModifier) {
paddedConstraints.value = constraints
Layout(
measurePolicy = { _, childConstraints ->
firstChildConstraints.value = childConstraints
layout(size, size) { }
},
content = { }
)
Layout(
measurePolicy = { _, chilConstraints ->
secondChildConstraints.value = chilConstraints
layout(size, size) { }
},
content = { }
)
}
}
}
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
val expectedPaddedConstraints = Constraints(
0,
topConstraints.value!!.maxWidth - size * 2,
0,
topConstraints.value!!.maxHeight - size * 2
)
assertEquals(expectedPaddedConstraints, paddedConstraints.value)
assertEquals(paddedConstraints.value, firstChildConstraints.value)
assertEquals(paddedConstraints.value, secondChildConstraints.value)
}
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun withConstraints_layoutListener() {
val green = Color.Green
val white = Color.White
val model = SquareModel(size = 20, outerColor = green, innerColor = white)
show {
BoxWithConstraints {
val outerModifier = Modifier.drawBehind {
drawRect(model.outerColor)
}
Layout(
content = {
val innerModifier = Modifier.drawBehind {
drawLatch.countDown()
drawRect(model.innerColor)
}
Layout(
content = {},
modifier = innerModifier
) { measurables, constraints2 ->
layout(model.size, model.size) {}
}
},
modifier = outerModifier
) { measurables, constraints3 ->
val placeable = measurables[0].measure(
Constraints.fixed(
model.size,
model.size
)
)
layout(model.size * 3, model.size * 3) {
placeable.place(model.size, model.size)
}
}
}
}
takeScreenShot(60).apply {
assertRect(color = white, size = 20)
assertRect(color = green, holeSize = 20)
}
drawLatch = CountDownLatch(1)
activityTestRule.runOnUiThread {
model.size = 10
}
takeScreenShot(30).apply {
assertRect(color = white, size = 10)
assertRect(color = green, holeSize = 10)
}
}
/**
* WithConstraints will cause a requestLayout during layout in some circumstances.
* The test here is the minimal example from a bug.
*/
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun requestLayoutDuringLayout() {
val offset = mutableStateOf(0)
show {
Scroller(
modifier = Modifier.countdownLatchBackground(Color.Yellow),
onScrollPositionChanged = { position, _ ->
offset.value = position
},
offset = offset
) {
// Need to pass some param here to a separate function or else it works fine
TestLayout(5)
}
}
takeScreenShot(30).apply {
assertRect(color = Color.Red, size = 10)
assertRect(color = Color.Yellow, holeSize = 10)
}
}
@Test
fun subcomposionInsideWithConstraintsDoesntAffectModelReadsObserving() {
val model = mutableStateOf(0)
var latch = CountDownLatch(1)
show {
BoxWithConstraints {
// this block is called as a subcomposition from LayoutNode.measure()
// VectorPainter introduces additional subcomposition which is closing the
// current frame and opens a new one. our model reads during measure()
// wasn't possible to survide Frames swicth previously so the model read
// within the child Layout wasn't recorded
val background = Modifier.paint(
rememberVectorPainter(
name = "testPainter",
defaultWidth = 10.dp,
defaultHeight = 10.dp,
autoMirror = false
) { _, _ ->
/* intentionally empty */
}
)
Layout(modifier = background, content = {}) { _, _ ->
// read the model
model.value
latch.countDown()
layout(10, 10) {}
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
latch = CountDownLatch(1)
activityTestRule.runOnUiThread { model.value++ }
assertTrue(latch.await(1, TimeUnit.SECONDS))
}
@Test
fun withConstraintCallbackIsNotExecutedWithInnerRecompositions() {
val model = mutableStateOf(0)
var latch = CountDownLatch(1)
var recompositionsCount1 = 0
var recompositionsCount2 = 0
show {
BoxWithConstraints {
recompositionsCount1++
Container(100, 100) {
model.value // model read
recompositionsCount2++
latch.countDown()
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
latch = CountDownLatch(1)
activityTestRule.runOnUiThread { model.value++ }
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertEquals(1, recompositionsCount1)
assertEquals(2, recompositionsCount2)
}
@Test
fun updateConstraintsRecomposingWithConstraints() {
val model = mutableStateOf(50)
var latch = CountDownLatch(1)
var actualConstraints: Constraints? = null
show {
ChangingConstraintsLayout(model) {
BoxWithConstraints {
actualConstraints = constraints
assertEquals(1, latch.count)
latch.countDown()
Container(width = 100, height = 100) {}
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertEquals(Constraints.fixed(50, 50), actualConstraints)
latch = CountDownLatch(1)
activityTestRule.runOnUiThread { model.value = 100 }
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertEquals(Constraints.fixed(100, 100), actualConstraints)
}
@Test
fun withConstsraintsBehavesAsWrap() {
val size = mutableStateOf(50)
var withConstLatch = CountDownLatch(1)
var childLatch = CountDownLatch(1)
var withConstSize: IntSize? = null
var childSize: IntSize? = null
show {
Container(width = 200, height = 200) {
BoxWithConstraints(
modifier = Modifier.onGloballyPositioned {
// OnPositioned can be fired multiple times with the same value
// for example when requestLayout() was triggered on ComposeView.
// if we called twice, let's make sure we got the correct values.
assertTrue(withConstSize == null || withConstSize == it.size)
withConstSize = it.size
withConstLatch.countDown()
}
) {
Container(
width = size.value, height = size.value,
modifier = Modifier.onGloballyPositioned {
// OnPositioned can be fired multiple times with the same value
// for example when requestLayout() was triggered on ComposeView.
// if we called twice, let's make sure we got the correct values.
assertTrue(childSize == null || childSize == it.size)
childSize = it.size
childLatch.countDown()
}
) {
}
}
}
}
assertTrue(withConstLatch.await(1, TimeUnit.SECONDS))
assertTrue(childLatch.await(1, TimeUnit.SECONDS))
var expectedSize = IntSize(50, 50)
assertEquals(expectedSize, withConstSize)
assertEquals(expectedSize, childSize)
withConstSize = null
childSize = null
withConstLatch = CountDownLatch(1)
childLatch = CountDownLatch(1)
activityTestRule.runOnUiThread { size.value = 100 }
assertTrue(withConstLatch.await(1, TimeUnit.SECONDS))
assertTrue(childLatch.await(1, TimeUnit.SECONDS))
expectedSize = IntSize(100, 100)
assertEquals(expectedSize, withConstSize)
assertEquals(expectedSize, childSize)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun withConstraintsIsNotSwallowingInnerRemeasureRequest() {
val model = mutableStateOf(100)
show {
Container(100, 100, Modifier.background(Color.Red)) {
ChangingConstraintsLayout(model) {
BoxWithConstraints {
val receivedConstraints = constraints
Container(100, 100, infiniteConstraints) {
Container(100, 100) {
Layout(
{},
Modifier.countdownLatchBackground(Color.Yellow)
) { _, _ ->
// the same as the value inside ValueModel
val size = receivedConstraints.maxWidth
layout(size, size) {}
}
}
}
}
}
}
}
takeScreenShot(100).apply {
assertRect(color = Color.Yellow)
}
drawLatch = CountDownLatch(1)
activityTestRule.runOnUiThread {
model.value = 50
}
takeScreenShot(100).apply {
assertRect(color = Color.Red, holeSize = 50)
assertRect(color = Color.Yellow, size = 50)
}
}
@Test
fun updateModelInMeasuringAndReadItInCompositionWorksInsideWithConstraints() {
val latch = CountDownLatch(1)
show {
Container(width = 100, height = 100) {
BoxWithConstraints {
// this replicates the popular pattern we currently use
// where we save some data calculated in the measuring block
// and then use it in the next composition frame
var model by remember { mutableStateOf(false) }
Layout({
if (model) {
latch.countDown()
}
}) { _, _ ->
if (!model) {
model = true
}
layout(100, 100) {}
}
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun removeLayoutNodeFromWithConstraintsDuringOnMeasure() {
val model = mutableStateOf(100)
drawLatch = CountDownLatch(2)
show {
Container(
100, 100,
modifier = Modifier.countdownLatchBackground(Color.Red)
) {
// this component changes the constraints which triggers subcomposition
// within onMeasure block
ChangingConstraintsLayout(model) {
BoxWithConstraints {
if (constraints.maxWidth == 100) {
// we will stop emitting this layouts after constraints change
// Additional Container is needed so the Layout will be
// marked as not affecting parent size which means the Layout
// will be added into relayoutNodes List separately
Container(100, 100) {
Layout(
content = {},
modifier = Modifier.countdownLatchBackground(Color.Yellow)
) { _, _ ->
layout(model.value, model.value) {}
}
}
}
}
Container(100, 100, Modifier) {}
}
}
}
takeScreenShot(100).apply {
assertRect(color = Color.Yellow)
}
drawLatch = CountDownLatch(1)
activityTestRule.runOnUiThread {
model.value = 50
}
takeScreenShot(100).apply {
assertRect(color = Color.Red)
}
}
@Test
fun withConstraintsSiblingWhichIsChangingTheModelInsideMeasureBlock() {
// WithConstraints used to call FrameManager.nextFrame() after composition
// so this code was causing an issue as the model value change is triggering
// remeasuring while our parent is measuring right now and this child was
// already measured
val drawlatch = CountDownLatch(1)
show {
val state = remember { mutableStateOf(false) }
var lastLayoutValue: Boolean = false
val drawModifier = Modifier.drawBehind {
// this verifies the layout was remeasured before being drawn
assertTrue(lastLayoutValue)
drawlatch.countDown()
}
Layout(content = {}, modifier = drawModifier) { _, _ ->
lastLayoutValue = state.value
// this registers the value read
if (!state.value) {
// change the value right inside the measure block
// it will cause one more remeasure pass as we also read this value
state.value = true
}
layout(100, 100) {}
}
BoxWithConstraints {}
}
assertTrue(drawlatch.await(1, TimeUnit.SECONDS))
}
@Test
fun allTheStepsCalledExactlyOnce() {
val outerComposeLatch = CountDownLatch(1)
val outerMeasureLatch = CountDownLatch(1)
val outerLayoutLatch = CountDownLatch(1)
val innerComposeLatch = CountDownLatch(1)
val innerMeasureLatch = CountDownLatch(1)
val innerLayoutLatch = CountDownLatch(1)
show {
assertEquals(1, outerComposeLatch.count)
outerComposeLatch.countDown()
val content = @Composable {
Layout(
content = {
BoxWithConstraints {
assertEquals(1, innerComposeLatch.count)
innerComposeLatch.countDown()
Layout(content = {}) { _, _ ->
assertEquals(1, innerMeasureLatch.count)
innerMeasureLatch.countDown()
layout(100, 100) {
assertEquals(1, innerLayoutLatch.count)
innerLayoutLatch.countDown()
}
}
}
}
) { measurables, constraints ->
assertEquals(1, outerMeasureLatch.count)
outerMeasureLatch.countDown()
layout(100, 100) {
assertEquals(1, outerLayoutLatch.count)
outerLayoutLatch.countDown()
measurables.forEach { it.measure(constraints).place(0, 0) }
}
}
}
Layout(content) { measurables, _ ->
layout(100, 100) {
// we fix the constraints used by children so if the constraints given
// by the android view will change it would not affect the test
val constraints = Constraints(maxWidth = 100, maxHeight = 100)
measurables.first().measure(constraints).place(0, 0)
}
}
}
assertTrue(outerComposeLatch.await(1, TimeUnit.SECONDS))
assertTrue(outerMeasureLatch.await(1, TimeUnit.SECONDS))
assertTrue(outerLayoutLatch.await(1, TimeUnit.SECONDS))
assertTrue(innerComposeLatch.await(1, TimeUnit.SECONDS))
assertTrue(innerMeasureLatch.await(1, TimeUnit.SECONDS))
assertTrue(innerLayoutLatch.await(1, TimeUnit.SECONDS))
}
@Test
fun triggerRootRemeasureWhileRootIsLayouting() {
show {
val state = remember { mutableStateOf(0) }
ContainerChildrenAffectsParentSize(100, 100) {
BoxWithConstraints {
Layout(
content = {},
modifier = Modifier.countdownLatchBackground(Color.Transparent)
) { _, _ ->
// read and write once inside measureBlock
if (state.value == 0) {
state.value = 1
}
layout(100, 100) {}
}
}
Container(100, 100) {
BoxWithConstraints {}
}
}
}
assertTrue(drawLatch.await(1, TimeUnit.SECONDS))
// before the fix this was failing our internal assertions in AndroidOwner
// so nothing else to assert, apart from not crashing
}
@Test
fun withConstraintsChildIsMeasuredEvenWithDefaultConstraints() {
val compositionLatch = CountDownLatch(1)
val childMeasureLatch = CountDownLatch(1)
val zeroConstraints = Constraints.fixed(0, 0)
show {
Layout(
measurePolicy = { measurables, _ ->
layout(0, 0) {
// there was a bug when the child of WithConstraints wasn't marking
// needsRemeasure and it was only measured because the constraints
// have been changed. to verify needRemeasure is true we measure the
// children with the default zero constraints so it will be equals to the
// initial constraints
measurables.first().measure(zeroConstraints).place(0, 0)
}
},
content = {
BoxWithConstraints {
compositionLatch.countDown()
Layout(content = {}) { _, _ ->
childMeasureLatch.countDown()
layout(0, 0) {}
}
}
}
)
}
assertTrue(compositionLatch.await(1, TimeUnit.SECONDS))
assertTrue(childMeasureLatch.await(1, TimeUnit.SECONDS))
}
@Test
fun onDisposeInsideWithConstraintsCalled() {
var emit by mutableStateOf(true)
val composedLatch = CountDownLatch(1)
val disposedLatch = CountDownLatch(1)
show {
if (emit) {
BoxWithConstraints {
composedLatch.countDown()
DisposableEffect(Unit) {
onDispose {
disposedLatch.countDown()
}
}
}
}
}
assertTrue(composedLatch.await(1, TimeUnit.SECONDS))
activityTestRule.runOnUiThread {
emit = false
}
assertTrue(disposedLatch.await(1, TimeUnit.SECONDS))
}
@Test
fun dpOverloadsHaveCorrectValues() {
val latch = CountDownLatch(1)
show {
val minWidthConstraint = 5.dp
val maxWidthConstraint = 7.dp
val minHeightConstraint = 9.dp
val maxHeightConstraint = 12.dp
Layout(
content = @Composable {
BoxWithConstraints {
with(LocalDensity.current) {
assertEquals(minWidthConstraint.roundToPx(), minWidth.roundToPx())
assertEquals(maxWidthConstraint.roundToPx(), maxWidth.roundToPx())
assertEquals(minHeightConstraint.roundToPx(), minHeight.roundToPx())
assertEquals(maxHeightConstraint.roundToPx(), maxHeight.roundToPx())
}
latch.countDown()
}
}
) { m, _ ->
layout(0, 0) {
m.first().measure(
Constraints(
minWidth = minWidthConstraint.roundToPx(),
maxWidth = maxWidthConstraint.roundToPx(),
minHeight = minHeightConstraint.roundToPx(),
maxHeight = maxHeightConstraint.roundToPx()
)
).place(IntOffset.Zero)
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
}
@Test
fun preservesInfinity() {
val latch = CountDownLatch(1)
show {
BoxWithConstraints(Modifier.wrapContentSize(unbounded = true)) {
assertEquals(Dp.Infinity, maxWidth)
assertEquals(Dp.Infinity, maxHeight)
latch.countDown()
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
}
// waitAndScreenShot() requires API level 26
@RequiresApi(Build.VERSION_CODES.O)
private fun takeScreenShot(size: Int): Bitmap {
assertTrue(drawLatch.await(1, TimeUnit.SECONDS))
val bitmap = activityTestRule.waitAndScreenShot()
assertEquals(size, bitmap.width)
assertEquals(size, bitmap.height)
return bitmap
}
@Suppress("DEPRECATION")
@RequiresApi(Build.VERSION_CODES.O)
fun ActivityTestRule<*>.waitAndScreenShot(
forceInvalidate: Boolean = true
): Bitmap = waitAndScreenShot(findComposeView(), forceInvalidate)
@Suppress("DEPRECATION")
@RequiresApi(Build.VERSION_CODES.O)
fun ActivityTestRule<*>.waitAndScreenShot(
view: View,
forceInvalidate: Boolean = true
): Bitmap {
val flushListener = DrawCounterListener(view)
val offset = intArrayOf(0, 0)
var handler: Handler? = null
runOnUiThread {
view.getLocationInWindow(offset)
if (forceInvalidate) {
view.viewTreeObserver.addOnPreDrawListener(flushListener)
view.invalidate()
}
handler = Handler(Looper.getMainLooper())
}
if (forceInvalidate) {
assertTrue("Drawing latch timed out", flushListener.latch.await(1, TimeUnit.SECONDS))
}
val width = view.width
val height = view.height
val dest =
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val srcRect = android.graphics.Rect(0, 0, width, height)
srcRect.offset(offset[0], offset[1])
val latch = CountDownLatch(1)
var copyResult = 0
val onCopyFinished = object : PixelCopy.OnPixelCopyFinishedListener {
override fun onPixelCopyFinished(result: Int) {
copyResult = result
latch.countDown()
}
}
PixelCopy.request(activity.window, srcRect, dest, onCopyFinished, handler!!)
assertTrue("Pixel copy latch timed out", latch.await(1, TimeUnit.SECONDS))
assertEquals(PixelCopy.SUCCESS, copyResult)
return dest
}
private fun Modifier.countdownLatchBackground(color: Color): Modifier = drawBehind {
drawRect(color)
drawLatch.countDown()
}
}
@Composable
private fun TestLayout(@Suppress("UNUSED_PARAMETER") someInput: Int) {
Layout(
content = {
BoxWithConstraints {
NeedsOtherMeasurementComposable(10)
}
}
) { measurables, constraints ->
val withConstraintsPlaceable = measurables[0].measure(constraints)
layout(30, 30) {
withConstraintsPlaceable.place(10, 10)
}
}
}
@Composable
private fun NeedsOtherMeasurementComposable(foo: Int) {
Layout(
content = {},
modifier = Modifier.background(Color.Red)
) { _, _ ->
layout(foo, foo) { }
}
}
@Composable
fun Container(
width: Int,
height: Int,
modifier: Modifier = Modifier,
content: @Composable () ->
Unit
) {
Layout(
content = content,
modifier = modifier,
measurePolicy = remember(width, height) {
MeasurePolicy { measurables, _ ->
val constraint = Constraints(maxWidth = width, maxHeight = height)
layout(width, height) {
measurables.forEach {
val placeable = it.measure(constraint)
placeable.place(
(width - placeable.width) / 2,
(height - placeable.height) / 2
)
}
}
}
}
)
}
@Composable
fun ContainerChildrenAffectsParentSize(
width: Int,
height: Int,
content: @Composable () -> Unit
) {
Layout(
content = content,
measurePolicy = remember(width, height) {
MeasurePolicy { measurables, _ ->
val constraint = Constraints(maxWidth = width, maxHeight = height)
val placeables = measurables.map { it.measure(constraint) }
layout(width, height) {
placeables.forEach {
it.place((width - width) / 2, (height - height) / 2)
}
}
}
}
)
}
@Composable
private fun ChangingConstraintsLayout(size: State<Int>, content: @Composable () -> Unit) {
Layout(content) { measurables, _ ->
layout(100, 100) {
val constraints = Constraints.fixed(size.value, size.value)
measurables.first().measure(constraints).place(0, 0)
}
}
}
fun Modifier.background(color: Color): Modifier = drawBehind {
drawRect(color)
}
val infiniteConstraints = object : LayoutModifier {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(Constraints())
return layout(constraints.maxWidth, constraints.maxHeight) {
placeable.place(0, 0)
}
}
}
@Composable
internal fun Padding(
size: Int,
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Layout(
modifier = modifier,
measurePolicy = { measurables, constraints ->
val totalDiff = size * 2
val targetMinWidth = constraints.minWidth - totalDiff
val targetMaxWidth = if (constraints.hasBoundedWidth) {
constraints.maxWidth - totalDiff
} else {
Constraints.Infinity
}
val targetMinHeight = constraints.minHeight - totalDiff
val targetMaxHeight = if (constraints.hasBoundedHeight) {
constraints.maxHeight - totalDiff
} else {
Constraints.Infinity
}
val newConstraints = Constraints(
minWidth = targetMinWidth.coerceAtLeast(0),
maxWidth = targetMaxWidth.coerceAtLeast(0),
minHeight = targetMinHeight.coerceAtLeast(0),
maxHeight = targetMaxHeight.coerceAtLeast(0)
)
val placeables = measurables.map { m ->
m.measure(newConstraints)
}
var maxWidth = size
var maxHeight = size
placeables.forEach { child ->
maxHeight = max(child.height + totalDiff, maxHeight)
maxWidth = max(child.width + totalDiff, maxWidth)
}
layout(maxWidth, maxHeight) {
placeables.forEach { child ->
child.placeRelative(size, size)
}
}
},
content = content
)
}
fun Bitmap.assertRect(
color: Color,
holeSize: Int = 0,
size: Int = width,
centerX: Int = width / 2,
centerY: Int = height / 2
) {
assertTrue(centerX + size / 2 <= width)
assertTrue(centerX - size / 2 >= 0)
assertTrue(centerY + size / 2 <= height)
assertTrue(centerY - size / 2 >= 0)
val halfHoleSize = holeSize / 2
for (x in centerX - size / 2 until centerX + size / 2) {
for (y in centerY - size / 2 until centerY + size / 2) {
if (abs(x - centerX) > halfHoleSize &&
abs(y - centerY) > halfHoleSize
) {
val currentColor = Color(getPixel(x, y))
assertColorsEqual(color, currentColor)
}
}
}
}
@Composable
fun Scroller(
modifier: Modifier = Modifier,
onScrollPositionChanged: (position: Int, maxPosition: Int) -> Unit,
offset: State<Int>,
content: @Composable () -> Unit
) {
val maxPosition = remember { mutableStateOf(Constraints.Infinity) }
ScrollerLayout(
modifier = modifier,
maxPosition = maxPosition.value,
onMaxPositionChanged = {
maxPosition.value = 0
onScrollPositionChanged(offset.value, 0)
},
content = content
)
}
@Composable
private fun ScrollerLayout(
modifier: Modifier = Modifier,
@Suppress("UNUSED_PARAMETER") maxPosition: Int,
onMaxPositionChanged: () -> Unit,
content: @Composable () -> Unit
) {
Layout(modifier = modifier, content = content) { measurables, constraints ->
val childConstraints = constraints.copy(
maxHeight = constraints.maxHeight,
maxWidth = Constraints.Infinity
)
val childMeasurable = measurables.first()
val placeable = childMeasurable.measure(childConstraints)
val width = min(placeable.width, constraints.maxWidth)
layout(width, placeable.height) {
onMaxPositionChanged()
placeable.placeRelative(0, 0)
}
}
}
class DrawCounterListener(private val view: View) :
ViewTreeObserver.OnPreDrawListener {
val latch = CountDownLatch(5)
override fun onPreDraw(): Boolean {
latch.countDown()
if (latch.count > 0) {
view.postInvalidate()
} else {
view.viewTreeObserver.removeOnPreDrawListener(this)
}
return true
}
}
fun assertColorsEqual(
expected: Color,
color: Color,
error: () -> String = { "$expected and $color are not similar!" }
) {
val errorString = error()
assertEquals(errorString, expected.red, color.red, 0.01f)
assertEquals(errorString, expected.green, color.green, 0.01f)
assertEquals(errorString, expected.blue, color.blue, 0.01f)
assertEquals(errorString, expected.alpha, color.alpha, 0.01f)
}
@Stable
class SquareModel(
size: Int = 10,
outerColor: Color = Color(0xFF000080),
innerColor: Color = Color(0xFFFFFFFF)
) {
var size: Int by mutableStateOf(size)
var outerColor: Color by mutableStateOf(outerColor)
var innerColor: Color by mutableStateOf(innerColor)
} | apache-2.0 | d4b783ee90d3e1110f563b88f052d5fe | 35.166833 | 97 | 0.541904 | 5.394427 | false | false | false | false |
androidx/androidx | navigation/navigation-safe-args-generator/src/main/kotlin/androidx/navigation/safe/args/generator/kotlin/KotlinTypes.kt | 3 | 10951 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.safe.args.generator.kotlin
import androidx.navigation.safe.args.generator.BoolArrayType
import androidx.navigation.safe.args.generator.BoolType
import androidx.navigation.safe.args.generator.BooleanValue
import androidx.navigation.safe.args.generator.EnumValue
import androidx.navigation.safe.args.generator.FloatArrayType
import androidx.navigation.safe.args.generator.FloatType
import androidx.navigation.safe.args.generator.FloatValue
import androidx.navigation.safe.args.generator.IntArrayType
import androidx.navigation.safe.args.generator.IntType
import androidx.navigation.safe.args.generator.IntValue
import androidx.navigation.safe.args.generator.LongArrayType
import androidx.navigation.safe.args.generator.LongType
import androidx.navigation.safe.args.generator.LongValue
import androidx.navigation.safe.args.generator.NavType
import androidx.navigation.safe.args.generator.NullValue
import androidx.navigation.safe.args.generator.ObjectArrayType
import androidx.navigation.safe.args.generator.ObjectType
import androidx.navigation.safe.args.generator.ReferenceArrayType
import androidx.navigation.safe.args.generator.ReferenceType
import androidx.navigation.safe.args.generator.ReferenceValue
import androidx.navigation.safe.args.generator.StringArrayType
import androidx.navigation.safe.args.generator.StringType
import androidx.navigation.safe.args.generator.StringValue
import androidx.navigation.safe.args.generator.WritableValue
import androidx.navigation.safe.args.generator.ext.toClassNameParts
import androidx.navigation.safe.args.generator.models.Argument
import androidx.navigation.safe.args.generator.models.ResReference
import com.squareup.kotlinpoet.ARRAY
import com.squareup.kotlinpoet.BOOLEAN
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FLOAT
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.INT
import com.squareup.kotlinpoet.LONG
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.asTypeName
import java.lang.UnsupportedOperationException
internal val NAV_DIRECTION_CLASSNAME: ClassName = ClassName("androidx.navigation", "NavDirections")
internal val ACTION_ONLY_NAV_DIRECTION_CLASSNAME: ClassName =
ClassName("androidx.navigation", "ActionOnlyNavDirections")
internal val NAV_ARGS_CLASSNAME: ClassName = ClassName("androidx.navigation", "NavArgs")
internal val BUNDLE_CLASSNAME: ClassName = ClassName("android.os", "Bundle")
internal val SAVED_STATE_HANDLE_CLASSNAME: ClassName =
ClassName("androidx.lifecycle", "SavedStateHandle")
internal val PARCELABLE_CLASSNAME = ClassName("android.os", "Parcelable")
internal val SERIALIZABLE_CLASSNAME = ClassName("java.io", "Serializable")
internal fun NavType.addBundleGetStatement(
builder: FunSpec.Builder,
arg: Argument,
lValue: String,
bundle: String
): FunSpec.Builder = when (this) {
is ObjectType -> builder.apply {
beginControlFlow(
"if (%T::class.java.isAssignableFrom(%T::class.java) " +
"|| %T::class.java.isAssignableFrom(%T::class.java))",
PARCELABLE_CLASSNAME, arg.type.typeName(),
SERIALIZABLE_CLASSNAME, arg.type.typeName()
)
addStatement(
"%L = %L.%L(%S)·as·%T",
lValue, bundle, "get", arg.name, arg.type.typeName().copy(nullable = true)
)
nextControlFlow("else")
addStatement(
"throw·%T(%T::class.java.name + %S)",
UnsupportedOperationException::class.asTypeName(),
arg.type.typeName(),
" must implement Parcelable or Serializable or must be an Enum."
)
endControlFlow()
}
is ObjectArrayType -> builder.apply {
val baseType = (arg.type.typeName() as ParameterizedTypeName).typeArguments.first()
addStatement(
"%L = %L.%L(%S)?.map { it as %T }?.toTypedArray()",
lValue, bundle, bundleGetMethod(), arg.name, baseType
)
}
else -> builder.addStatement(
"%L = %L.%L(%S)",
lValue,
bundle,
bundleGetMethod(),
arg.name
)
}
internal fun NavType.addBundlePutStatement(
builder: FunSpec.Builder,
arg: Argument,
bundle: String,
argValue: String
): FunSpec.Builder = when (this) {
is ObjectType -> builder.apply {
beginControlFlow(
"if (%T::class.java.isAssignableFrom(%T::class.java))",
PARCELABLE_CLASSNAME, arg.type.typeName()
)
addStatement(
"%L.%L(%S, %L as %T)",
bundle, "putParcelable", arg.name, argValue,
PARCELABLE_CLASSNAME.copy(nullable = arg.isNullable)
)
nextControlFlow(
"else if (%T::class.java.isAssignableFrom(%T::class.java))",
SERIALIZABLE_CLASSNAME, arg.type.typeName()
)
addStatement(
"%L.%L(%S, %L as %T)",
bundle, "putSerializable", arg.name, argValue,
SERIALIZABLE_CLASSNAME.copy(nullable = arg.isNullable)
)
if (!arg.isOptional()) {
nextControlFlow("else")
addStatement(
"throw·%T(%T::class.java.name + %S)",
UnsupportedOperationException::class.asTypeName(),
arg.type.typeName(),
" must implement Parcelable or Serializable or must be an Enum."
)
}
endControlFlow()
}
else -> builder.addStatement(
"%L.%L(%S, %L)",
bundle,
bundlePutMethod(),
arg.name,
argValue
)
}
internal fun NavType.addSavedStateGetStatement(
builder: FunSpec.Builder,
arg: Argument,
lValue: String,
savedStateHandle: String
): FunSpec.Builder = when (this) {
is ObjectType -> builder.apply {
beginControlFlow(
"if (%T::class.java.isAssignableFrom(%T::class.java) " +
"|| %T::class.java.isAssignableFrom(%T::class.java))",
PARCELABLE_CLASSNAME, arg.type.typeName(),
SERIALIZABLE_CLASSNAME, arg.type.typeName()
)
addStatement(
"%L = %L.get<%T>(%S)",
lValue, savedStateHandle, arg.type.typeName().copy(nullable = true), arg.name
)
nextControlFlow("else")
addStatement(
"throw·%T(%T::class.java.name + %S)",
UnsupportedOperationException::class.asTypeName(),
arg.type.typeName(),
" must implement Parcelable or Serializable or must be an Enum."
)
endControlFlow()
}
is ObjectArrayType -> builder.apply {
val baseType = (arg.type.typeName() as ParameterizedTypeName).typeArguments.first()
addStatement(
"%L = %L.get<Array<%T>>(%S)?.map { it as %T }?.toTypedArray()",
lValue, savedStateHandle, PARCELABLE_CLASSNAME, arg.name, baseType
)
}
else -> builder.addStatement(
"%L = %L[%S]",
lValue,
savedStateHandle,
arg.name
)
}
internal fun NavType.addSavedStateSetStatement(
builder: FunSpec.Builder,
arg: Argument,
savedStateHandle: String,
argValue: String
): FunSpec.Builder = when (this) {
is ObjectType -> builder.apply {
beginControlFlow(
"if (%T::class.java.isAssignableFrom(%T::class.java))",
PARCELABLE_CLASSNAME, arg.type.typeName()
)
addStatement(
"%L.set(%S, %L as %T)",
savedStateHandle, arg.name, argValue,
PARCELABLE_CLASSNAME.copy(nullable = arg.isNullable)
)
nextControlFlow(
"else if (%T::class.java.isAssignableFrom(%T::class.java))",
SERIALIZABLE_CLASSNAME, arg.type.typeName()
)
addStatement(
"%L.set(%S, %L as %T)",
savedStateHandle, arg.name, argValue,
SERIALIZABLE_CLASSNAME.copy(nullable = arg.isNullable)
)
if (!arg.isOptional()) {
nextControlFlow("else")
addStatement(
"throw·%T(%T::class.java.name + %S)",
UnsupportedOperationException::class.asTypeName(),
arg.type.typeName(),
" must implement Parcelable or Serializable or must be an Enum."
)
}
endControlFlow()
}
else -> builder.addStatement(
"%L.set(%S, %L)",
savedStateHandle,
arg.name,
argValue
)
}
internal fun NavType.typeName(): TypeName = when (this) {
IntType -> INT
IntArrayType -> IntArray::class.asTypeName()
LongType -> LONG
LongArrayType -> LongArray::class.asTypeName()
FloatType -> FLOAT
FloatArrayType -> FloatArray::class.asTypeName()
StringType -> String::class.asTypeName()
StringArrayType -> ARRAY.parameterizedBy(String::class.asTypeName())
BoolType -> BOOLEAN
BoolArrayType -> BooleanArray::class.asTypeName()
ReferenceType -> INT
ReferenceArrayType -> IntArray::class.asTypeName()
is ObjectType ->
canonicalName.toClassNameParts().let { (packageName, simpleName, innerNames) ->
ClassName(packageName, simpleName, *innerNames)
}
is ObjectArrayType -> ARRAY.parameterizedBy(
canonicalName.toClassNameParts().let { (packageName, simpleName, innerNames) ->
ClassName(packageName, simpleName, *innerNames)
}
)
else -> throw IllegalStateException("Unknown type: $this")
}
internal fun WritableValue.write(): CodeBlock {
return when (this) {
is ReferenceValue -> resReference.accessor()
is StringValue -> CodeBlock.of("%S", value)
is IntValue -> CodeBlock.of(value)
is LongValue -> CodeBlock.of(value)
is FloatValue -> CodeBlock.of("${value}F")
is BooleanValue -> CodeBlock.of(value)
is NullValue -> CodeBlock.of("null")
is EnumValue -> CodeBlock.of("%T.%N", type.typeName(), value)
else -> throw IllegalStateException("Unknown value: $this")
}
}
internal fun ResReference?.accessor() = this?.let {
CodeBlock.of("%T.%N", ClassName(packageName, "R", resType), javaIdentifier)
} ?: CodeBlock.of("0") | apache-2.0 | 7372d1589941bcddb52b081fa7a50f0d | 37.542254 | 99 | 0.661855 | 4.429381 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/processor/CustomConverterProcessor.kt | 3 | 8907 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.processor
import androidx.room.BuiltInTypeConverters
import androidx.room.ProvidedTypeConverter
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import androidx.room.compiler.processing.XElement
import androidx.room.compiler.processing.XMethodElement
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.XTypeElement
import androidx.room.compiler.processing.isVoid
import androidx.room.processor.ProcessorErrors.INNER_CLASS_TYPE_CONVERTER_MUST_BE_STATIC
import androidx.room.processor.ProcessorErrors.TYPE_CONVERTER_BAD_RETURN_TYPE
import androidx.room.processor.ProcessorErrors.TYPE_CONVERTER_EMPTY_CLASS
import androidx.room.processor.ProcessorErrors.TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR
import androidx.room.processor.ProcessorErrors.TYPE_CONVERTER_MUST_BE_PUBLIC
import androidx.room.processor.ProcessorErrors.TYPE_CONVERTER_MUST_RECEIVE_1_PARAM
import androidx.room.processor.ProcessorErrors.TYPE_CONVERTER_UNBOUND_GENERIC
import androidx.room.solver.types.CustomTypeConverterWrapper
import androidx.room.vo.BuiltInConverterFlags
import androidx.room.vo.CustomTypeConverter
/**
* Processes classes that are referenced in TypeConverters annotations.
*/
class CustomConverterProcessor(val context: Context, val element: XTypeElement) {
companion object {
private fun XType.isInvalidReturnType() =
isError() || isVoid() || isNone()
fun findConverters(context: Context, element: XElement): ProcessResult {
if (!element.hasAnnotation(TypeConverters::class)) {
return ProcessResult.EMPTY
}
if (!element.validate()) {
context.reportMissingTypeReference(element.toString())
return ProcessResult.EMPTY
}
val annotation = element.requireAnnotation(TypeConverters::class)
val classes = annotation.getAsTypeList("value").mapTo(LinkedHashSet()) { it }
val converters = classes.flatMap {
val typeElement = it.typeElement
if (typeElement == null) {
context.logger.e(
element,
ProcessorErrors.typeConverterMustBeDeclared(
it.asTypeName().toString(context.codeLanguage)
)
)
emptyList()
} else {
CustomConverterProcessor(context, typeElement).process()
}
}
reportDuplicates(context, converters)
val builtInStates =
annotation.getAsAnnotationBox<BuiltInTypeConverters>("builtInTypeConverters").let {
BuiltInConverterFlags(
enums = it.value.enums,
uuid = it.value.uuid,
byteBuffer = it.value.byteBuffer
)
}
return ProcessResult(
classes = classes,
converters = converters.map(::CustomTypeConverterWrapper),
builtInConverterFlags = builtInStates
)
}
private fun reportDuplicates(context: Context, converters: List<CustomTypeConverter>) {
converters
.groupBy { it.from.asTypeName() to it.to.asTypeName() }
.filterValues { it.size > 1 }
.values.forEach { possiblyDuplicateConverters ->
possiblyDuplicateConverters.forEach { converter ->
val duplicates = possiblyDuplicateConverters.filter { duplicate ->
duplicate !== converter &&
duplicate.from.isSameType(converter.from) &&
duplicate.to.isSameType(converter.to)
}
if (duplicates.isNotEmpty()) {
context.logger.e(
converter.method,
ProcessorErrors.duplicateTypeConverters(duplicates)
)
}
}
}
}
}
fun process(): List<CustomTypeConverter> {
if (!element.validate()) {
context.reportMissingTypeReference(element.qualifiedName)
}
val methods = element.getAllMethods()
val converterMethods = methods.filter {
it.hasAnnotation(TypeConverter::class)
}.toList()
val isProvidedConverter = element.hasAnnotation(ProvidedTypeConverter::class)
context.checker.check(converterMethods.isNotEmpty(), element, TYPE_CONVERTER_EMPTY_CLASS)
val allStatic = converterMethods.all { it.isStatic() }
val constructors = element.getConstructors()
val isKotlinObjectDeclaration = element.isKotlinObject()
if (!isProvidedConverter) {
context.checker.check(
element.enclosingTypeElement == null || element.isStatic(),
element,
INNER_CLASS_TYPE_CONVERTER_MUST_BE_STATIC
)
context.checker.check(
isKotlinObjectDeclaration || allStatic || constructors.isEmpty() ||
constructors.any {
it.parameters.isEmpty()
},
element, TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR
)
}
return converterMethods.mapNotNull {
processMethod(
container = element,
isContainerKotlinObject = isKotlinObjectDeclaration,
methodElement = it,
isProvidedConverter = isProvidedConverter
)
}
}
private fun processMethod(
container: XTypeElement,
methodElement: XMethodElement,
isContainerKotlinObject: Boolean,
isProvidedConverter: Boolean
): CustomTypeConverter? {
val asMember = methodElement.asMemberOf(container.type)
val returnType = asMember.returnType
val invalidReturnType = returnType.isInvalidReturnType()
context.checker.check(
methodElement.isPublic(), methodElement, TYPE_CONVERTER_MUST_BE_PUBLIC
)
if (invalidReturnType) {
context.logger.e(methodElement, TYPE_CONVERTER_BAD_RETURN_TYPE)
return null
}
context.checker.notUnbound(
returnType, methodElement,
TYPE_CONVERTER_UNBOUND_GENERIC
)
val params = methodElement.parameters
if (params.size != 1) {
context.logger.e(methodElement, TYPE_CONVERTER_MUST_RECEIVE_1_PARAM)
return null
}
val param = params.map {
it.asMemberOf(container.type)
}.first()
context.checker.notUnbound(param, params[0], TYPE_CONVERTER_UNBOUND_GENERIC)
return CustomTypeConverter(
enclosingClass = container,
isEnclosingClassKotlinObject = isContainerKotlinObject,
method = methodElement,
from = param,
to = returnType,
isProvidedConverter = isProvidedConverter
)
}
/**
* Order of classes is important hence they are a LinkedHashSet not a set.
*/
data class ProcessResult(
val classes: LinkedHashSet<XType>,
val converters: List<CustomTypeConverterWrapper>,
val builtInConverterFlags: BuiltInConverterFlags
) {
companion object {
val EMPTY = ProcessResult(
classes = LinkedHashSet(),
converters = emptyList(),
builtInConverterFlags = BuiltInConverterFlags.DEFAULT
)
}
operator fun plus(other: ProcessResult): ProcessResult {
val newClasses = LinkedHashSet<XType>()
newClasses.addAll(classes)
newClasses.addAll(other.classes)
return ProcessResult(
classes = newClasses,
converters = converters + other.converters,
builtInConverterFlags = other.builtInConverterFlags.withNext(
builtInConverterFlags
)
)
}
}
}
| apache-2.0 | 974e94a452c7cf1e78c8a5bdbdda6be8 | 40.621495 | 99 | 0.610307 | 5.528864 | false | false | false | false |
GunoH/intellij-community | java/compiler/impl/src/com/intellij/packaging/impl/artifacts/workspacemodel/BridgeUtils.kt | 2 | 6212 | // 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.serialize
import com.intellij.openapi.compiler.JavaCompilerBundle
import com.intellij.openapi.module.ProjectLoadingErrorsNotifier
import com.intellij.openapi.project.Project
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.UnknownFeature
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.UnknownFeaturesCollector
import com.intellij.openapi.util.JDOMUtil
import com.intellij.packaging.artifacts.ArtifactProperties
import com.intellij.packaging.artifacts.ArtifactPropertiesProvider
import com.intellij.packaging.artifacts.ArtifactType
import com.intellij.packaging.elements.CompositePackagingElement
import com.intellij.packaging.elements.PackagingElement
import com.intellij.packaging.elements.PackagingElementFactory
import com.intellij.packaging.elements.PackagingElementType
import com.intellij.packaging.impl.artifacts.ArtifactLoadingErrorDescription
import com.intellij.packaging.impl.artifacts.workspacemodel.ArtifactManagerBridge.Companion.mutableArtifactsMap
import com.intellij.packaging.impl.elements.*
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.*
import org.jetbrains.annotations.Nls
internal fun addBridgesToDiff(newBridges: List<ArtifactBridge>, builder: MutableEntityStorage) {
for (newBridge in newBridges) {
val artifactEntity = builder.resolve(newBridge.artifactId) ?: continue
builder.mutableArtifactsMap.addMapping(artifactEntity, newBridge)
}
}
internal fun createArtifactBridge(it: ArtifactEntity, entityStorage: VersionedEntityStorage, project: Project): ArtifactBridge {
if (ArtifactType.findById(it.artifactType) == null) {
return createInvalidArtifact(it, entityStorage, project, JavaCompilerBundle.message("unknown.artifact.type.0", it.artifactType))
}
fun findMissingArtifactType(element: PackagingElementEntity): String? {
if (element is CustomPackagingElementEntity) {
if (PackagingElementFactory.getInstance().findElementType(element.typeId) == null) {
return element.typeId
}
}
if (element is CompositePackagingElementEntity) {
element.children.forEach { child ->
val artifactType = findMissingArtifactType(child)
if (artifactType != null) return artifactType
}
}
return null
}
val missingArtifactType = findMissingArtifactType(it.rootElement!!)
if (missingArtifactType != null) {
return createInvalidArtifact(it, entityStorage, project, JavaCompilerBundle.message("unknown.element.0", missingArtifactType))
}
val unknownProperty = it.customProperties.firstOrNull { ArtifactPropertiesProvider.findById(it.providerType) == null }
if (unknownProperty != null) {
return createInvalidArtifact(it, entityStorage, project,
JavaCompilerBundle.message("unknown.artifact.properties.0", unknownProperty))
}
return ArtifactBridge(it.symbolicId, entityStorage, project, null, null)
}
private fun createInvalidArtifact(it: ArtifactEntity,
entityStorage: VersionedEntityStorage,
project: Project,
@Nls message: String): InvalidArtifactBridge {
val invalidArtifactBridge = InvalidArtifactBridge(it.symbolicId, entityStorage, project, null, message)
val errorDescription = ArtifactLoadingErrorDescription(project, invalidArtifactBridge)
ProjectLoadingErrorsNotifier.getInstance(project).registerError(errorDescription)
UnknownFeaturesCollector.getInstance(project)
.registerUnknownFeature(UnknownFeature(
errorDescription.errorType.featureType,
JavaCompilerBundle.message("plugins.advertiser.feature.artifact"),
it.artifactType,
))
return invalidArtifactBridge
}
fun PackagingElement<*>.forThisAndFullTree(action: (PackagingElement<*>) -> Unit) {
action(this)
if (this is CompositePackagingElement<*>) {
this.children.forEach {
if (it is CompositePackagingElement<*>) {
it.forThisAndFullTree(action)
}
else {
action(it)
}
}
}
}
fun EntityStorage.get(id: ArtifactId): ArtifactEntity = this.resolve(id) ?: error("Cannot find artifact by id: ${id.name}")
internal fun PackagingElementEntity.sameTypeWith(type: PackagingElementType<out PackagingElement<*>>): Boolean {
return when (this) {
is ModuleOutputPackagingElementEntity -> type == ProductionModuleOutputElementType.ELEMENT_TYPE
is ModuleTestOutputPackagingElementEntity -> type == TestModuleOutputElementType.ELEMENT_TYPE
is ModuleSourcePackagingElementEntity -> type == ProductionModuleSourceElementType.ELEMENT_TYPE
is ArtifactOutputPackagingElementEntity -> type == PackagingElementFactoryImpl.ARCHIVE_ELEMENT_TYPE
is ExtractedDirectoryPackagingElementEntity -> type == PackagingElementFactoryImpl.EXTRACTED_DIRECTORY_ELEMENT_TYPE
is FileCopyPackagingElementEntity -> type == PackagingElementFactoryImpl.FILE_COPY_ELEMENT_TYPE
is DirectoryCopyPackagingElementEntity -> type == PackagingElementFactoryImpl.DIRECTORY_COPY_ELEMENT_TYPE
is DirectoryPackagingElementEntity -> type == PackagingElementFactoryImpl.DIRECTORY_ELEMENT_TYPE
is ArchivePackagingElementEntity -> type == PackagingElementFactoryImpl.ARCHIVE_ELEMENT_TYPE
is ArtifactRootElementEntity -> type == PackagingElementFactoryImpl.ARTIFACT_ROOT_ELEMENT_TYPE
is LibraryFilesPackagingElementEntity -> type == LibraryElementType.LIBRARY_ELEMENT_TYPE
is CustomPackagingElementEntity -> this.typeId == type.id
else -> error("Unexpected branch. $this")
}
}
internal fun ArtifactProperties<*>.propertiesTag(): String? {
val state = state
return if (state != null) {
val element = serialize(state) ?: return null
element.name = "options"
JDOMUtil.write(element)
}
else null
}
| apache-2.0 | 4c3d0b2fee7e647c865f5a4719d36bb0 | 47.155039 | 140 | 0.78123 | 5.142384 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/content/impl/MessageViewImpl.kt | 8 | 1736 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.content.impl
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.UIBundle
import com.intellij.ui.content.ContentManager
import com.intellij.ui.content.MessageView
internal class MessageViewImpl(project: Project) : MessageView {
private var toolWindow: ToolWindow? = null
private val postponedRunnables = ArrayList<Runnable>()
init {
StartupManager.getInstance(project).runAfterOpened {
// in a unit test mode this code maybe executed in EDT, so, don't use here invokeLater
// also, MessageView service maybe called directly from EDT
AppUIExecutor.onUiThread().expireWith(project).execute {
toolWindow = ToolWindowManager.getInstance(project).registerToolWindow(ToolWindowId.MESSAGES_WINDOW) {
icon = AllIcons.Toolwindows.ToolWindowMessages
stripeTitle = UIBundle.messagePointer("tool.window.name.messages")
}
for (postponedRunnable in postponedRunnables) {
postponedRunnable.run()
}
postponedRunnables.clear()
}
}
}
override fun getContentManager(): ContentManager {
return toolWindow!!.contentManager
}
override fun runWhenInitialized(runnable: Runnable) {
if (toolWindow == null) {
postponedRunnables.add(runnable)
}
else {
runnable.run()
}
}
} | apache-2.0 | 683ca2c73c835f0ad31de3e16d60c23f | 35.1875 | 120 | 0.744816 | 4.629333 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromUsageFix.kt | 1 | 12744 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.ide.util.DirectoryChooserUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.psi.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.quickfix.IntentionActionPriority
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.*
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind.*
import org.jetbrains.kotlin.idea.refactoring.SeparateFileWrapper
import org.jetbrains.kotlin.idea.refactoring.canRefactor
import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary
import org.jetbrains.kotlin.idea.refactoring.getOrCreateKotlinFile
import org.jetbrains.kotlin.idea.refactoring.ui.CreateKotlinClassDialog
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.SmartList
import java.util.*
import com.intellij.codeInsight.daemon.impl.quickfix.ClassKind as IdeaClassKind
enum class ClassKind(@NonNls val keyword: String, @Nls val description: String) {
PLAIN_CLASS("class", KotlinBundle.message("text.class")),
ENUM_CLASS("enum class", KotlinBundle.message("text.enum")),
ENUM_ENTRY("", KotlinBundle.message("text.enum.constant")),
ANNOTATION_CLASS("annotation class", KotlinBundle.message("text.annotation")),
INTERFACE("interface", KotlinBundle.message("text.interface")),
OBJECT("object", KotlinBundle.message("text.object")),
DEFAULT("", "") // Used as a placeholder and must be replaced with one of the kinds above
}
fun ClassKind.toIdeaClassKind() = IdeaClassKind { [email protected]() }
val ClassKind.actionPriority: IntentionActionPriority
get() = if (this == ANNOTATION_CLASS) IntentionActionPriority.LOW else IntentionActionPriority.NORMAL
data class ClassInfo(
val kind: ClassKind = DEFAULT,
val name: String,
private val targetParents: List<PsiElement>,
val expectedTypeInfo: TypeInfo,
val inner: Boolean = false,
val open: Boolean = false,
val typeArguments: List<TypeInfo> = Collections.emptyList(),
val parameterInfos: List<ParameterInfo> = Collections.emptyList(),
val primaryConstructorVisibility: DescriptorVisibility? = null
) {
val applicableParents by lazy {
targetParents.filter {
if (kind == OBJECT && it is KtClass && (it.isInner() || it.isLocal)) return@filter false
true
}
}
}
open class CreateClassFromUsageFix<E : KtElement> protected constructor(
element: E,
private val classInfo: ClassInfo
) : CreateFromUsageFixBase<E>(element) {
override fun getText() = KotlinBundle.message("create.0.1", classInfo.kind.description, classInfo.name)
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
with(classInfo) {
if (kind == DEFAULT) return false
if (applicableParents.isEmpty()) return false
applicableParents.forEach {
if (it is PsiClass) {
if (kind == OBJECT || kind == ENUM_ENTRY) return false
if (it.isInterface && inner) return false
}
}
}
return true
}
override fun startInWriteAction() = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (editor == null) return
val applicableParents = SmartList<PsiElement>().also { parents ->
classInfo.applicableParents.filterNotTo(parents) { element ->
element is KtClassOrObject && element.superTypeListEntries.any {
when (it) {
is KtDelegatedSuperTypeEntry, is KtSuperTypeEntry -> it.typeAsUserType == this.element
is KtSuperTypeCallEntry -> it == this.element
else -> false
}
}
}
if (classInfo.kind != ENUM_ENTRY && parents.find { it is PsiPackage } == null) {
parents += SeparateFileWrapper(PsiManager.getInstance(project))
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
val targetParent = applicableParents.firstOrNull { element ->
if (element is PsiPackage) false else element.allChildren.any { it is PsiComment && it.text == "// TARGET_PARENT:" }
} ?: classInfo.applicableParents.last()
return doInvoke(targetParent, editor, file)
}
chooseContainerElementIfNecessary(
applicableParents.reversed(),
editor,
KotlinBundle.message("choose.class.container"),
true,
) {
doInvoke(it, editor, file)
}
}
private fun createFileByPackage(
psiPackage: PsiPackage,
editor: Editor,
originalFile: KtFile
): KtFile? {
val directories = psiPackage.directories.filter { it.canRefactor() }
assert(directories.isNotEmpty()) { "Package '${psiPackage.qualifiedName}' must be refactorable" }
val currentModule = ModuleUtilCore.findModuleForPsiElement(originalFile)
val preferredDirectory =
directories.firstOrNull { ModuleUtilCore.findModuleForPsiElement(it) == currentModule }
?: directories.firstOrNull()
val targetDirectory = if (directories.size > 1 && !ApplicationManager.getApplication().isUnitTestMode) {
DirectoryChooserUtil.chooseDirectory(directories.toTypedArray(), preferredDirectory, originalFile.project, HashMap())
} else {
preferredDirectory
} ?: return null
val fileName = "${classInfo.name}.${KotlinFileType.INSTANCE.defaultExtension}"
val targetFile = getOrCreateKotlinFile(fileName, targetDirectory)
if (targetFile == null) {
val filePath = "${targetDirectory.virtualFile.path}/$fileName"
CodeInsightUtils.showErrorHint(
targetDirectory.project,
editor,
KotlinBundle.message("file.0.already.exists.but.does.not.correspond.to.kotlin.file", filePath),
KotlinBundle.message("create.file"),
null
)
}
return targetFile
}
private fun doInvoke(selectedParent: PsiElement, editor: Editor, file: KtFile, startCommand: Boolean = true) {
val className = classInfo.name
if (selectedParent is SeparateFileWrapper) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return doInvoke(file, editor, file)
}
val ideaClassKind = classInfo.kind.toIdeaClassKind()
val defaultPackageFqName = file.packageFqName
val dialog = object : CreateKotlinClassDialog(
file.project,
KotlinBundle.message("create.0", ideaClassKind.description.capitalize()),
className,
defaultPackageFqName.asString(),
ideaClassKind,
false,
file.module
) {
override fun reportBaseInSourceSelectionInTest() = true
}
dialog.show()
if (dialog.exitCode != DialogWrapper.OK_EXIT_CODE) return
val targetDirectory = dialog.targetDirectory ?: return
val fileName = "$className.${KotlinFileType.EXTENSION}"
val packageFqName = targetDirectory.getFqNameWithImplicitPrefix()
file.project.executeWriteCommand(text) {
val targetFile = getOrCreateKotlinFile(fileName, targetDirectory, (packageFqName ?: defaultPackageFqName).asString())
if (targetFile != null) {
doInvoke(targetFile, editor, file, false)
}
}
return
}
val element = element ?: return
runWriteAction<Unit> {
with(classInfo) {
val targetParent =
when (selectedParent) {
is KtElement, is PsiClass -> selectedParent
is PsiPackage -> createFileByPackage(selectedParent, editor, file)
else -> throw KotlinExceptionWithAttachments("Unexpected element: ${selectedParent::class.java}")
.withAttachment("selectedParent", selectedParent.text)
} ?: return@runWriteAction
val constructorInfo = ClassWithPrimaryConstructorInfo(
classInfo,
// Need for #KT-22137
if (expectedTypeInfo.isUnit) TypeInfo.Empty else expectedTypeInfo,
primaryConstructorVisibility = classInfo.primaryConstructorVisibility
)
val builder = CallableBuilderConfiguration(
Collections.singletonList(constructorInfo),
element,
file,
editor,
false,
kind == PLAIN_CLASS || kind == INTERFACE
).createBuilder()
builder.placement = CallablePlacement.NoReceiver(targetParent)
fun buildClass() {
builder.build {
if (targetParent !is KtFile || targetParent == file) return@build
val targetPackageFqName = targetParent.packageFqName
if (targetPackageFqName == file.packageFqName) return@build
val reference = (element.getQualifiedElementSelector() as? KtSimpleNameExpression)?.mainReference ?: return@build
reference.bindToFqName(
targetPackageFqName.child(Name.identifier(className)),
KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING
)
}
}
if (startCommand) {
file.project.executeCommand(text, command = ::buildClass)
} else {
buildClass()
}
}
}
}
private class LowPriorityCreateClassFromUsageFix<E : KtElement>(
element: E,
classInfo: ClassInfo
) : CreateClassFromUsageFix<E>(element, classInfo), LowPriorityAction
private class HighPriorityCreateClassFromUsageFix<E : KtElement>(
element: E,
classInfo: ClassInfo
) : CreateClassFromUsageFix<E>(element, classInfo), HighPriorityAction
companion object {
fun <E : KtElement> create(element: E, classInfo: ClassInfo): CreateClassFromUsageFix<E> {
return when (classInfo.kind.actionPriority) {
IntentionActionPriority.NORMAL -> CreateClassFromUsageFix(element, classInfo)
IntentionActionPriority.LOW -> LowPriorityCreateClassFromUsageFix(element, classInfo)
IntentionActionPriority.HIGH -> HighPriorityCreateClassFromUsageFix(element, classInfo)
}
}
}
}
private val TypeInfo.isUnit: Boolean
get() = ((this as? TypeInfo.DelegatingTypeInfo)?.delegate as? TypeInfo.ByType)?.theType?.isUnit() == true
| apache-2.0 | 3fac3ba02af8e6b51e8c4f7ce082feb3 | 44.352313 | 158 | 0.655524 | 5.53125 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/NewNavigator.kt | 1 | 8573 | package io.github.feelfreelinux.wykopmobilny.ui.modules
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ShareCompat
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link
import io.github.feelfreelinux.wykopmobilny.ui.modules.addlink.AddlinkActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.embedview.EmbedViewActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.embedview.YoutubeActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.BaseInputActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.AddEntryActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.comment.EditEntryCommentActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.edit.EditEntryActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.link.edit.LinkCommentEditActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.links.downvoters.DownvotersActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.links.linkdetails.LinkDetailsActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.links.related.RelatedActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.links.upvoters.UpvotersActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen.LoginScreenActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.mainnavigation.MainNavigationActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.entry.EntryActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.NotificationsListActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.photoview.PhotoViewActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversation.ConversationActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.profile.ProfileActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.settings.SettingsActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.tag.TagActivity
import io.github.feelfreelinux.wykopmobilny.utils.openBrowser
import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferences
import io.github.feelfreelinux.wykopmobilny.utils.wykopLog
import java.lang.Exception
interface NewNavigatorApi {
fun openMainActivity(targetFragment: String? = null)
fun openEntryDetailsActivity(entryId: Int, isRevealed: Boolean)
fun openTagActivity(tag: String)
fun openConversationListActivity(user: String)
fun openPhotoViewActivity(url: String)
fun openSettingsActivity()
fun openLoginScreen(requestCode: Int)
fun openAddEntryActivity(receiver: String? = null, extraBody: String? = null)
fun openEditEntryActivity(body: String, entryId: Int)
fun openEditLinkCommentActivity(commentId: Int, body: String, linkId: Int)
fun openEditEntryCommentActivity(body: String, entryId: Int, commentId: Int)
fun openBrowser(url: String)
fun openReportScreen(violationUrl: String)
fun openLinkDetailsActivity(link: Link)
fun openLinkDetailsActivity(linkId: Int, commentId: Int = -1)
fun openLinkUpvotersActivity(linkId: Int)
fun openLinkDownvotersActivity(linkId: Int)
fun openLinkRelatedActivity(linkId: Int)
fun openProfileActivity(username: String)
fun openNotificationsListActivity(preselectIndex: Int = NotificationsListActivity.PRESELECT_NOTIFICATIONS)
fun openEmbedActivity(url: String)
fun openYoutubeActivity(url: String)
fun openAddLinkActivity()
fun shareUrl(url: String)
}
class NewNavigator(val context: Activity) : NewNavigatorApi {
companion object {
const val STARTED_FROM_NOTIFICATIONS_CODE = 228
}
private val settingsPreferencesApi = SettingsPreferences(context)
override fun openMainActivity(targetFragment: String?) {
context.startActivity(MainNavigationActivity.getIntent(context, targetFragment)
.apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) })
}
override fun openEntryDetailsActivity(entryId: Int, isRevealed: Boolean) =
context.startActivity(EntryActivity.createIntent(context, entryId, null, isRevealed))
override fun openTagActivity(tag: String) =
context.startActivity(TagActivity.createIntent(context, tag))
override fun openConversationListActivity(user: String) =
context.startActivity(ConversationActivity.createIntent(context, user))
override fun openPhotoViewActivity(url: String) =
context.startActivity(PhotoViewActivity.createIntent(context, url))
override fun openSettingsActivity() =
context.startActivity(SettingsActivity.createIntent(context))
override fun openLoginScreen(requestCode: Int) =
context.startActivityForResult(LoginScreenActivity.createIntent(context), requestCode)
override fun openAddEntryActivity(receiver: String?, extraBody: String?) =
context.startActivity(AddEntryActivity.createIntent(context, receiver, extraBody))
override fun openEditEntryActivity(body: String, entryId: Int) =
context.startActivityForResult(EditEntryActivity.createIntent(context, body, entryId), BaseInputActivity.EDIT_ENTRY)
override fun openEditLinkCommentActivity(commentId: Int, body: String, linkId: Int) =
context.startActivityForResult(LinkCommentEditActivity.createIntent(context, commentId, body, linkId), BaseInputActivity.EDIT_LINK_COMMENT)
override fun openEditEntryCommentActivity(body: String, entryId: Int, commentId: Int) =
context.startActivityForResult(EditEntryCommentActivity.createIntent(context, body, entryId, commentId), BaseInputActivity.EDIT_ENTRY_COMMENT)
override fun openBrowser(url: String) {
if (settingsPreferencesApi.useBuiltInBrowser) {
context.openBrowser(url)
} else {
val i = Intent(Intent.ACTION_VIEW)
i.data = Uri.parse(url)
context.startActivity(i)
}
}
override fun openReportScreen(violationUrl: String) =
context.openBrowser(violationUrl)
override fun openLinkDetailsActivity(link: Link) =
context.startActivity(LinkDetailsActivity.createIntent(context, link))
override fun openLinkUpvotersActivity(linkId: Int) =
context.startActivity(UpvotersActivity.createIntent(linkId, context))
override fun openLinkDetailsActivity(linkId: Int, commentId: Int) =
context.startActivity(LinkDetailsActivity.createIntent(context, linkId, commentId))
override fun openLinkDownvotersActivity(linkId: Int) =
context.startActivity(DownvotersActivity.createIntent(linkId, context))
override fun openLinkRelatedActivity(linkId: Int) =
context.startActivity(RelatedActivity.createIntent(linkId, context))
override fun openProfileActivity(username: String) =
context.startActivity(ProfileActivity.createIntent(context, username))
override fun openNotificationsListActivity(preselectIndex: Int) =
context.startActivityForResult(NotificationsListActivity.createIntent(context, preselectIndex), STARTED_FROM_NOTIFICATIONS_CODE)
override fun openEmbedActivity(url: String) =
context.startActivity(EmbedViewActivity.createIntent(context, url))
override fun openYoutubeActivity(url: String) =
startAndReportOnError({ YoutubeActivity.createIntent(context, url) }, "YouTube")
override fun openAddLinkActivity() =
context.startActivity(AddlinkActivity.createIntent(context))
override fun shareUrl(url: String) {
ShareCompat.IntentBuilder
.from(context)
.setType("text/plain")
.setChooserTitle(R.string.share)
.setText(url)
.startChooser()
}
private fun startAndReportOnError(intentCreator: () -> Intent, actionName: String) {
try {
val intent = intentCreator()
context.startActivity(intent)
} catch (ex: Exception) {
wykopLog(Log::e, "Failed to create and start '$actionName' activity", ex)
val message = context.getString(R.string.error_cannot_open_activity).format(actionName)
AlertDialog.Builder(context)
.setTitle(R.string.error_occured)
.setMessage(message)
.setPositiveButton(R.string.close, null)
.create().show()
}
}
}
| mit | 6cdcf61284b73f2a5f7ed88da7a9a5bc | 48.270115 | 150 | 0.772425 | 4.715622 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/ui/ScratchFileOptionsFile.kt | 4 | 1233 | // 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.scratch.ui
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.core.util.AbstractFileAttributePropertyService
import org.jetbrains.kotlin.idea.scratch.ScratchFileOptions
@Service
internal class ScratchFileOptionsFile: AbstractFileAttributePropertyService<ScratchFileOptions>(
name = "kotlin-scratch-file-options",
version = 1,
read = { ScratchFileOptions(readBoolean(), readBoolean(), readBoolean()) },
write = {
writeBoolean(it.isRepl)
writeBoolean(it.isMakeBeforeRun)
writeBoolean(it.isInteractiveMode)
}
) {
companion object {
operator fun get(project: Project, file: VirtualFile) = project.service<ScratchFileOptionsFile>()[file]
operator fun set(project: Project, file: VirtualFile, newValue: ScratchFileOptions?) {
project.service<ScratchFileOptionsFile>()[file] = newValue
}
}
} | apache-2.0 | 52a76631e114981ad75dde7c80fbb2f2 | 40.133333 | 158 | 0.755069 | 4.419355 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt | 10 | 1212 | // 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.jetbrains.python.sdk.flavors
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
class MayaSdkFlavor private constructor() : CPythonSdkFlavor() {
override fun isValidSdkHome(path: String): Boolean {
val file = File(path)
return file.isFile && isValidSdkPath(file) || isMayaFolder(file)
}
override fun isValidSdkPath(file: File): Boolean {
val name = FileUtil.getNameWithoutExtension(file).toLowerCase()
return name.startsWith("mayapy")
}
override fun getSdkPath(path: VirtualFile): VirtualFile? {
if (isMayaFolder(File(path.path))) {
return path.findFileByRelativePath("Contents/bin/mayapy")
}
return path
}
companion object {
val INSTANCE: MayaSdkFlavor = MayaSdkFlavor()
private fun isMayaFolder(file: File): Boolean {
return file.isDirectory && file.name == "Maya.app"
}
}
}
class MayaFlavorProvider: PythonFlavorProvider {
override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE
}
| apache-2.0 | 7170736acf6a3a821e93931a23b7c1ac | 29.3 | 140 | 0.736799 | 4.208333 | false | false | false | false |
craftsmenlabs/gareth-jvm | gareth-execution-ri/src/test/kotlin/org/craftsmenlabs/gareth/execution/integration/ExperimentLifecycleIntegrationTest.kt | 1 | 3635 | package org.craftsmenlabs.gareth.execution.integration
import org.assertj.core.api.Assertions.assertThat
import org.craftsmenlabs.gareth.execution.GarethExecutionApplication
import org.craftsmenlabs.gareth.execution.definitions.SaleOfFruit
import org.craftsmenlabs.gareth.execution.dto.ExperimentRunEnvironmentBuilder
import org.craftsmenlabs.gareth.validator.model.*
import org.craftsmenlabs.gareth.validator.rest.BasicAuthenticationRestClient
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest(classes = arrayOf(GarethExecutionApplication::class, SaleOfFruit::class), webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@TestPropertySource(properties = arrayOf("server.port=8101"))
@ActiveProfiles("test")
class ExperimentLifecycleIntegrationTest {
val path = "http://localhost:8101/gareth/validator/v1/"
val restClient = BasicAuthenticationRestClient("user", "secret")
private val fullGluelineSet = ValidatedGluelines(
baseline = "sale of fruit",
assume = "sale of fruit has risen by 81 per cent",
time = "next Easter",
success = "send email to John",
failure = "send email to Bob")
private val noFinalizationGluelineSet = ValidatedGluelines(
baseline = "sale of fruit",
assume = "sale of fruit has risen by 81 per cent",
time = "next Easter")
private val failingBaselineGluelineSet = ValidatedGluelines(
baseline = "get snake oil",
assume = "sale of fruit has risen by 81 per cent",
time = "2 days")
@Test
fun testBaseline() {
assertThat(doPut("${path}baseline", createRequest(fullGluelineSet)).status).isEqualTo(ExecutionStatus.RUNNING)
}
@Test
fun testSuccessfulAssume() {
assertThat(doPut("${path}assume", createRequest(fullGluelineSet)).status).isEqualTo(ExecutionStatus.SUCCESS)
assertThat(doPut("${path}assume", createRequest(noFinalizationGluelineSet)).status).isEqualTo(ExecutionStatus.SUCCESS)
}
@Test
fun testFailedBaseline() {
val request = createRequest(failingBaselineGluelineSet)
assertThat(doPut("${path}baseline", request).status).isEqualTo(ExecutionStatus.ERROR)
}
@Test
fun testFailedAssume() {
val request = createRequest(fullGluelineSet)
val failedAssume = request.copy(glueLines = request.glueLines.copy(assume = "sale of fruit has risen by 79 per cent"))
assertThat(doPut("${path}assume", failedAssume).status).isEqualTo(ExecutionStatus.FAILURE)
}
@Test
fun testDuration() {
val response = restClient.putAsEntity(createRequest(fullGluelineSet), Duration::class.java, "${path}time")
assertThat(response.body.amount).isEqualTo(14400L)
}
fun createRequest(gluelines: ValidatedGluelines): ExecutionRequest {
return ExecutionRequest(ExperimentRunEnvironmentBuilder.createEmpty(), gluelines)
}
fun doPut(path: String, dto: ExecutionRequest): ExecutionResult {
val response = restClient.putAsEntity(dto, ExecutionResult::class.java, path)
assertThat(response.statusCode.is2xxSuccessful).isTrue()
println(response.body)
return response.body
}
}
| gpl-2.0 | c185ad1e37a760c1cdf1d2e9b7b867d8 | 40.781609 | 150 | 0.735901 | 4.509926 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/klib/KlibMetadataDeserializerForDecompiler.kt | 2 | 3541 | // 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.klib
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataVersion
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.NotFoundClasses
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DeserializerForDecompilerBase
import org.jetbrains.kotlin.idea.decompiler.textBuilder.LoggingErrorReporter
import org.jetbrains.kotlin.idea.decompiler.textBuilder.ResolveEverythingToKotlinAnyLocalClassifierResolver
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.library.metadata.KlibMetadataClassDataFinder
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.NameResolver
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.sam.SamConversionResolverImpl
import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol
import org.jetbrains.kotlin.serialization.deserialization.*
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope
class KlibMetadataDeserializerForDecompiler(
packageFqName: FqName,
private val proto: ProtoBuf.PackageFragment,
private val nameResolver: NameResolver,
serializerProtocol: SerializerExtensionProtocol,
flexibleTypeDeserializer: FlexibleTypeDeserializer
) : DeserializerForDecompilerBase(packageFqName) {
override val builtIns: KotlinBuiltIns get() = DefaultBuiltIns.Instance
override val deserializationComponents: DeserializationComponents
init {
val notFoundClasses = NotFoundClasses(storageManager, moduleDescriptor)
deserializationComponents = DeserializationComponents(
storageManager, moduleDescriptor, DeserializationConfiguration.Default,
KlibMetadataClassDataFinder(proto, nameResolver),
AnnotationAndConstantLoaderImpl(moduleDescriptor, notFoundClasses, serializerProtocol), packageFragmentProvider,
ResolveEverythingToKotlinAnyLocalClassifierResolver(builtIns), LoggingErrorReporter(LOG),
LookupTracker.DO_NOTHING, flexibleTypeDeserializer, emptyList(), notFoundClasses, ContractDeserializer.DEFAULT,
extensionRegistryLite = serializerProtocol.extensionRegistry,
samConversionResolver = SamConversionResolverImpl(storageManager, samWithReceiverResolvers = emptyList())
)
}
override fun resolveDeclarationsInFacade(facadeFqName: FqName): List<DeclarationDescriptor> {
assert(facadeFqName == directoryPackageFqName) {
"Was called for $facadeFqName; only members of $directoryPackageFqName package are expected."
}
val membersScope = DeserializedPackageMemberScope(
createDummyPackageFragment(facadeFqName),
proto.`package`,
nameResolver,
KlibMetadataVersion.INSTANCE,
containerSource = null,
components = deserializationComponents
) { emptyList() }
return membersScope.getContributedDescriptors().toList()
}
companion object {
private val LOG = Logger.getInstance(KlibMetadataDeserializerForDecompiler::class.java)
}
}
| apache-2.0 | 3e5e6a7c4830c4ef23281fc82572e595 | 50.318841 | 158 | 0.797515 | 5.6656 | false | false | false | false |
AMARJITVS/NoteDirector | app/src/main/kotlin/com/amar/notesapp/activities/ViewPagerActivity.kt | 1 | 27196 | package com.amar.NoteDirector.activities
import android.animation.Animator
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.drawable.ColorDrawable
import android.hardware.SensorManager
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.MediaStore
import android.support.v4.view.ViewPager
import android.util.DisplayMetrics
import android.util.Log
import android.view.*
import android.view.animation.DecelerateInterpolator
import com.simplemobiletools.commons.dialogs.ConfirmationDialog
import com.simplemobiletools.commons.dialogs.PropertiesDialog
import com.simplemobiletools.commons.dialogs.RenameItemDialog
import com.simplemobiletools.commons.extensions.*
import com.amar.NoteDirector.activities.MediaActivity.Companion.mMedia
import com.amar.NoteDirector.adapters.MyPagerAdapter
import com.amar.NoteDirector.asynctasks.GetMediaAsynctask
import com.amar.NoteDirector.dialogs.SaveAsDialog
import com.amar.NoteDirector.dialogs.SlideshowDialog
import com.amar.NoteDirector.extensions.*
import com.amar.NoteDirector.fragments.PhotoFragment
import com.amar.NoteDirector.fragments.VideoFragment
import com.amar.NoteDirector.fragments.ViewPagerFragment
import com.amar.NoteDirector.helpers.*
import com.amar.NoteDirector.models.Medium
import kotlinx.android.synthetic.main.activity_medium.*
import java.io.File
import java.io.OutputStream
import java.util.*
class ViewPagerActivity : SimpleActivity(), ViewPager.OnPageChangeListener, ViewPagerFragment.FragmentListener {
lateinit var mOrientationEventListener: OrientationEventListener
private var mPath = ""
private var mDirectory = ""
private var mIsFullScreen = false
private var mPos = -1
private var mShowAll = false
private var mIsSlideshowActive = false
private var mRotationDegrees = 0f
private var mLastHandledOrientation = 0
private var mPrevHashcode = 0
private var mSlideshowHandler = Handler()
private var mSlideshowInterval = SLIDESHOW_DEFAULT_INTERVAL
private var mSlideshowMoveBackwards = false
private var mSlideshowMedia = mutableListOf<Medium>()
private var mAreSlideShowMediaVisible = false
companion object {
var screenWidth = 0
var screenHeight = 0
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.amar.NoteDirector.R.layout.activity_medium)
if (!hasWriteStoragePermission()) {
finish()
return
}
measureScreen()
val uri = intent.data
if (uri != null) {
var cursor: Cursor? = null
try {
val proj = arrayOf(MediaStore.Images.Media.DATA)
cursor = contentResolver.query(uri, proj, null, null, null)
if (cursor?.moveToFirst() == true) {
mPath = cursor.getStringValue(MediaStore.Images.Media.DATA)
}
} finally {
cursor?.close()
}
} else {
try {
mPath = intent.getStringExtra(MEDIUM)
mShowAll = config.showAll
} catch (e: Exception) {
showErrorToast(e)
finish()
return
}
}
if (mPath.isEmpty()) {
toast(com.amar.NoteDirector.R.string.unknown_error_occurred)
finish()
return
}
if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) {
if (isShowHiddenFlagNeeded()) {
if (!config.isPasswordProtectionOn) {
config.temporarilyShowHidden = true
}
}
config.isThirdPartyIntent = true
}
showSystemUI()
mDirectory = File(mPath).parent
title = mPath.getFilenameFromPath()
view_pager.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
view_pager.viewTreeObserver.removeOnGlobalLayoutListener(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed)
return
if (mMedia.isNotEmpty()) {
gotMedia(mMedia)
}
}
})
reloadViewPager()
scanPath(mPath) {}
setupOrientationEventListener()
if (config.darkBackground)
view_pager.background = ColorDrawable(Color.BLACK)
if (config.hideSystemUI)
fragmentClicked()
window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
mIsFullScreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
view_pager.adapter?.let {
(it as MyPagerAdapter).toggleFullscreen(mIsFullScreen)
checkSystemUI()
}
}
}
override fun onDestroy() {
super.onDestroy()
if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) {
config.temporarilyShowHidden = false
}
if (config.isThirdPartyIntent) {
mMedia.clear()
config.isThirdPartyIntent = false
}
}
private fun setupOrientationEventListener() {
mOrientationEventListener = object : OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
override fun onOrientationChanged(orientation: Int) {
val currOrient = when (orientation) {
in 45..134 -> ORIENT_LANDSCAPE_RIGHT
in 225..314 -> ORIENT_LANDSCAPE_LEFT
else -> ORIENT_PORTRAIT
}
if (mLastHandledOrientation != currOrient) {
mLastHandledOrientation = currOrient
requestedOrientation = when (currOrient) {
ORIENT_LANDSCAPE_LEFT -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
ORIENT_LANDSCAPE_RIGHT -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
else -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
}
}
}
override fun onResume() {
super.onResume()
if (!hasWriteStoragePermission()) {
finish()
}
supportActionBar?.setBackgroundDrawable(resources.getDrawable(com.amar.NoteDirector.R.drawable.actionbar_gradient_background))
if (config.maxBrightness) {
val attributes = window.attributes
attributes.screenBrightness = 1f
window.attributes = attributes
}
if (config.screenRotation == ROTATE_BY_DEVICE_ROTATION && mOrientationEventListener.canDetectOrientation()) {
mOrientationEventListener.enable()
} else if (config.screenRotation == ROTATE_BY_SYSTEM_SETTING) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
invalidateOptionsMenu()
}
override fun onPause() {
super.onPause()
mOrientationEventListener.disable()
stopSlideshow()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(com.amar.NoteDirector.R.menu.menu_viewpager, menu)
val currentMedium = getCurrentMedium() ?: return true
menu.apply {
findItem(com.amar.NoteDirector.R.id.menu_share_1).isVisible = !config.replaceShare
findItem(com.amar.NoteDirector.R.id.menu_share_2).isVisible = config.replaceShare
findItem(com.amar.NoteDirector.R.id.menu_set_as).isVisible = currentMedium.isImage()
findItem(com.amar.NoteDirector.R.id.menu_edit).isVisible = currentMedium.isImage()
findItem(com.amar.NoteDirector.R.id.menu_rotate).isVisible = currentMedium.isImage()
findItem(com.amar.NoteDirector.R.id.menu_save_as).isVisible = mRotationDegrees != 0f
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (getCurrentMedium() == null)
return true
when (item.itemId) {
com.amar.NoteDirector.R.id.menu_set_as -> trySetAs(getCurrentFile())
com.amar.NoteDirector.R.id.slideshow -> initSlideshow()
com.amar.NoteDirector.R.id.menu_copy_to -> copyMoveTo(true)
com.amar.NoteDirector.R.id.menu_move_to -> copyMoveTo(false)
com.amar.NoteDirector.R.id.menu_open_with -> openWith(getCurrentFile())
com.amar.NoteDirector.R.id.menu_share_1 -> shareMedium(getCurrentMedium()!!)
com.amar.NoteDirector.R.id.menu_share_2 -> shareMedium(getCurrentMedium()!!)
com.amar.NoteDirector.R.id.menu_delete -> askConfirmDelete()
com.amar.NoteDirector.R.id.menu_rename -> renameFile()
com.amar.NoteDirector.R.id.menu_properties -> showProperties()
com.amar.NoteDirector.R.id.show_on_map -> showOnMap()
com.amar.NoteDirector.R.id.menu_rotate -> rotateImage()
com.amar.NoteDirector.R.id.menu_save_as -> saveImageAs()
com.amar.NoteDirector.R.id.settings -> launchSettings()
else -> return super.onOptionsItemSelected(item)
}
return true
}
private fun updatePagerItems(media: MutableList<Medium>) {
val pagerAdapter = MyPagerAdapter(this, supportFragmentManager, media)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 || !isDestroyed) {
view_pager.apply {
adapter = pagerAdapter
adapter!!.notifyDataSetChanged()
currentItem = mPos
addOnPageChangeListener(this@ViewPagerActivity)
}
}
}
private fun initSlideshow() {
SlideshowDialog(this) {
startSlideshow()
}
}
private fun startSlideshow() {
if (getMediaForSlideshow()) {
view_pager.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
view_pager.viewTreeObserver.removeOnGlobalLayoutListener(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed)
return
hideSystemUI()
mSlideshowInterval = config.slideshowInterval
mSlideshowMoveBackwards = config.slideshowMoveBackwards
mIsSlideshowActive = true
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
scheduleSwipe()
}
})
}
}
private fun animatePagerTransition(forward: Boolean) {
val oldPosition = view_pager.currentItem
val animator = ValueAnimator.ofInt(0, view_pager.width)
animator.addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationEnd(animation: Animator?) {
view_pager.endFakeDrag()
if (view_pager.currentItem == oldPosition) {
slideshowEnded(forward)
}
}
override fun onAnimationCancel(animation: Animator?) {
view_pager.endFakeDrag()
}
override fun onAnimationStart(animation: Animator?) {
}
})
animator.interpolator = DecelerateInterpolator()
animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
var oldDragPosition = 0
override fun onAnimationUpdate(animation: ValueAnimator) {
val dragPosition = animation.animatedValue as Int
val dragOffset = dragPosition - oldDragPosition
oldDragPosition = dragPosition
view_pager.fakeDragBy(dragOffset * (if (forward) 1f else -1f))
}
})
animator.duration = SLIDESHOW_SCROLL_DURATION
view_pager.beginFakeDrag()
animator.start()
}
private fun slideshowEnded(forward: Boolean) {
if (config.loopSlideshow) {
if (forward) {
view_pager.setCurrentItem(0, false)
} else {
view_pager.setCurrentItem(view_pager.adapter!!.count - 1, false)
}
} else {
stopSlideshow()
toast(com.amar.NoteDirector.R.string.slideshow_ended)
}
}
private fun stopSlideshow() {
if (mIsSlideshowActive) {
showSystemUI()
mIsSlideshowActive = false
mSlideshowHandler.removeCallbacksAndMessages(null)
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
private fun scheduleSwipe() {
mSlideshowHandler.removeCallbacksAndMessages(null)
if (mIsSlideshowActive) {
if (getCurrentMedium()!!.isImage() || getCurrentMedium()!!.isGif()) {
mSlideshowHandler.postDelayed({
if (mIsSlideshowActive && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && !isDestroyed) {
swipeToNextMedium()
}
}, mSlideshowInterval * 1000L)
} else {
(getCurrentFragment() as? VideoFragment)!!.playVideo()
}
}
}
private fun swipeToNextMedium() {
animatePagerTransition(!mSlideshowMoveBackwards)
}
private fun getMediaForSlideshow(): Boolean {
mSlideshowMedia = mMedia.toMutableList()
if (!config.slideshowIncludePhotos) {
mSlideshowMedia = mSlideshowMedia.filter { !it.isImage() } as MutableList
}
if (!config.slideshowIncludeVideos) {
mSlideshowMedia = mSlideshowMedia.filter { it.isImage() || it.isGif() } as MutableList
}
if (!config.slideshowIncludeGIFs) {
mSlideshowMedia = mSlideshowMedia.filter { !it.isGif() } as MutableList
}
if (config.slideshowRandomOrder) {
Collections.shuffle(mSlideshowMedia)
mPos = 0
} else {
mPath = getCurrentPath()
mPos = getPositionInList(mSlideshowMedia)
}
return if (mSlideshowMedia.isEmpty()) {
toast(com.amar.NoteDirector.R.string.no_media_for_slideshow)
false
} else {
updatePagerItems(mSlideshowMedia)
mAreSlideShowMediaVisible = true
true
}
}
private fun copyMoveTo(isCopyOperation: Boolean) {
val files = ArrayList<File>(1).apply { add(getCurrentFile()) }
tryCopyMoveFilesTo(files, isCopyOperation) {
config.tempFolderPath = ""
if (!isCopyOperation) {
reloadViewPager()
}
}
}
private fun toggleFileVisibility(hide: Boolean) {
toggleFileVisibility(getCurrentFile(), hide) {
val newFileName = it.absolutePath.getFilenameFromPath()
title = newFileName
getCurrentMedium()!!.apply {
name = newFileName
path = it.absolutePath
getCurrentMedia()[mPos] = this
}
invalidateOptionsMenu()
}
}
private fun rotateImage() {
val currentMedium = getCurrentMedium() ?: return
if (currentMedium.isJpg() && !isPathOnSD(currentMedium.path)) {
rotateByExif()
} else {
rotateByDegrees()
}
}
private fun rotateByExif() {
val exif = ExifInterface(getCurrentPath())
val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
val newOrientation = getNewOrientation(orientation)
exif.setAttribute(ExifInterface.TAG_ORIENTATION, newOrientation)
exif.saveAttributes()
File(getCurrentPath()).setLastModified(System.currentTimeMillis())
(getCurrentFragment() as? PhotoFragment)?.refreshBitmap()
}
private fun getNewOrientation(rotation: Int): String {
return when (rotation) {
ExifInterface.ORIENTATION_ROTATE_90 -> ExifInterface.ORIENTATION_ROTATE_180
ExifInterface.ORIENTATION_ROTATE_180 -> ExifInterface.ORIENTATION_ROTATE_270
ExifInterface.ORIENTATION_ROTATE_270 -> ExifInterface.ORIENTATION_NORMAL
else -> ExifInterface.ORIENTATION_ROTATE_90
}.toString()
}
private fun rotateByDegrees() {
mRotationDegrees = (mRotationDegrees + 90) % 360
getCurrentFragment()?.let {
(it as? PhotoFragment)?.rotateImageViewBy(mRotationDegrees)
}
supportInvalidateOptionsMenu()
}
private fun saveImageAs() {
val currPath = getCurrentPath()
SaveAsDialog(this, currPath) {
Thread({
toast(com.amar.NoteDirector.R.string.saving)
val selectedFile = File(it)
val tmpFile = File(selectedFile.parent, "tmp_${it.getFilenameFromPath()}")
try {
val bitmap = BitmapFactory.decodeFile(currPath)
getFileOutputStream(tmpFile) {
if (it == null) {
toast(com.amar.NoteDirector.R.string.unknown_error_occurred)
deleteFile(tmpFile) {}
return@getFileOutputStream
}
saveFile(tmpFile, bitmap, it)
if (needsStupidWritePermissions(selectedFile.absolutePath)) {
deleteFile(selectedFile) {}
}
renameFile(tmpFile, selectedFile) {
deleteFile(tmpFile) {}
}
}
} catch (e: OutOfMemoryError) {
toast(com.amar.NoteDirector.R.string.out_of_memory_error)
deleteFile(tmpFile) {}
} catch (e: Exception) {
toast(com.amar.NoteDirector.R.string.unknown_error_occurred)
deleteFile(tmpFile) {}
}
}).start()
}
}
private fun saveFile(file: File, bitmap: Bitmap, out: OutputStream) {
val matrix = Matrix()
matrix.postRotate(mRotationDegrees)
val bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
bmp.compress(file.getCompressionFormat(), 90, out)
out.flush()
out.close()
toast(com.amar.NoteDirector.R.string.file_saved)
}
private fun isShowHiddenFlagNeeded(): Boolean {
val file = File(mPath)
if (file.isHidden)
return true
var parent = file.parentFile ?: return false
while (true) {
if (parent.isHidden || parent.listFiles()?.contains(File(NOMEDIA)) == true) {
return true
}
if (parent.absolutePath == "/") {
break
}
parent = parent.parentFile ?: return false
}
return false
}
private fun getCurrentFragment() = (view_pager.adapter as MyPagerAdapter).getCurrentFragment(view_pager.currentItem)
private fun showProperties() {
if (getCurrentMedium() != null)
PropertiesDialog(this, getCurrentPath(), false)
}
private fun showOnMap() {
val exif = ExifInterface(getCurrentPath())
val lat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE)
val lat_ref = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF)
val lon = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)
val lon_ref = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF)
if (lat == null || lat_ref == null || lon == null || lon_ref == null) {
toast(com.amar.NoteDirector.R.string.unknown_location)
} else {
val geoLat = if (lat_ref == "N") {
convertToDegree(lat)
} else {
0 - convertToDegree(lat)
}
val geoLon = if (lon_ref == "E") {
convertToDegree(lon)
} else {
0 - convertToDegree(lon)
}
val uriBegin = "geo:$geoLat,$geoLon"
val query = "$geoLat, $geoLon"
val encodedQuery = Uri.encode(query)
val uriString = "$uriBegin?q=$encodedQuery&z=16"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uriString))
val packageManager = packageManager
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
toast(com.amar.NoteDirector.R.string.no_map_application)
}
}
}
private fun convertToDegree(stringDMS: String): Float {
val dms = stringDMS.split(",".toRegex(), 3).toTypedArray()
val stringD = dms[0].split("/".toRegex(), 2).toTypedArray()
val d0 = stringD[0].toDouble()
val d1 = stringD[1].toDouble()
val floatD = d0 / d1
val stringM = dms[1].split("/".toRegex(), 2).toTypedArray()
val m0 = stringM[0].toDouble()
val m1 = stringM[1].toDouble()
val floatM = m0 / m1
val stringS = dms[2].split("/".toRegex(), 2).toTypedArray()
val s0 = stringS[0].toDouble()
val s1 = stringS[1].toDouble()
val floatS = s0 / s1
return (floatD + floatM / 60 + floatS / 3600).toFloat()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (requestCode == REQUEST_EDIT_IMAGE) {
if (resultCode == Activity.RESULT_OK && resultData != null) {
mPos = -1
reloadViewPager()
}
} else if (requestCode == REQUEST_SET_AS) {
if (resultCode == Activity.RESULT_OK) {
toast(com.amar.NoteDirector.R.string.wallpaper_set_successfully)
}
}
super.onActivityResult(requestCode, resultCode, resultData)
}
private fun askConfirmDelete() {
ConfirmationDialog(this) {
deleteFileBg(File(getCurrentMedia()[mPos].path)) {
reloadViewPager()
}
}
}
private fun isDirEmpty(media: ArrayList<Medium>): Boolean {
return if (media.isEmpty()) {
deleteDirectoryIfEmpty()
finish()
true
} else
false
}
private fun renameFile() {
RenameItemDialog(this, getCurrentPath()) {
getCurrentMedia()[mPos].path = it
updateActionbarTitle()
}
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
measureScreen()
}
private fun measureScreen() {
val metrics = DisplayMetrics()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
windowManager.defaultDisplay.getRealMetrics(metrics)
screenWidth = metrics.widthPixels
screenHeight = metrics.heightPixels
} else {
windowManager.defaultDisplay.getMetrics(metrics)
screenWidth = metrics.widthPixels
screenHeight = metrics.heightPixels
}
}
private fun reloadViewPager() {
GetMediaAsynctask(applicationContext, mDirectory, false, false, mShowAll) {
gotMedia(it)
}.execute()
}
private fun gotMedia(media: ArrayList<Medium>) {
if (isDirEmpty(media) || media.hashCode() == mPrevHashcode) {
return
}
mPrevHashcode = media.hashCode()
mMedia = media
mPos = if (mPos == -1) {
getPositionInList(media)
} else {
Math.min(mPos, mMedia.size - 1)
}
updateActionbarTitle()
updatePagerItems(mMedia.toMutableList())
invalidateOptionsMenu()
checkOrientation()
}
private fun getPositionInList(items: MutableList<Medium>): Int {
mPos = 0
for ((i, medium) in items.withIndex()) {
if (medium.path == mPath) {
return i
}
}
return mPos
}
private fun deleteDirectoryIfEmpty() {
val file = File(mDirectory)
if (config.deleteEmptyFolders && !file.isDownloadsFolder() && file.isDirectory && file.listFiles()?.isEmpty() == true) {
deleteFile(file, true) {}
}
scanPath(mDirectory) {}
}
private fun checkOrientation() {
if (config.screenRotation == ROTATE_BY_ASPECT_RATIO) {
val res = getCurrentFile().getResolution()
if (res.x > res.y) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} else if (res.x < res.y) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
}
override fun fragmentClicked() {
mIsFullScreen = !mIsFullScreen
checkSystemUI()
}
override fun videoEnded(): Boolean {
if (mIsSlideshowActive)
swipeToNextMedium()
return mIsSlideshowActive
}
private fun checkSystemUI() {
if (mIsFullScreen) {
hideSystemUI()
} else {
stopSlideshow()
showSystemUI()
}
}
private fun updateActionbarTitle() {
runOnUiThread {
if (mPos < getCurrentMedia().size) {
title = getCurrentMedia()[mPos].path.getFilenameFromPath()
}
}
}
private fun getCurrentMedium(): Medium? {
return if (getCurrentMedia().isEmpty() || mPos == -1)
null
else
getCurrentMedia()[Math.min(mPos, getCurrentMedia().size - 1)]
}
private fun getCurrentMedia() = if (mAreSlideShowMediaVisible) mSlideshowMedia else mMedia
private fun getCurrentPath() = getCurrentMedium()!!.path
private fun getCurrentFile() = File(getCurrentPath())
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
if (view_pager.offscreenPageLimit == 1) {
view_pager.offscreenPageLimit = 2
}
mPos = position
updateActionbarTitle()
mRotationDegrees = 0f
supportInvalidateOptionsMenu()
scheduleSwipe()
}
override fun onPageScrollStateChanged(state: Int) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
checkOrientation()
}
}
}
| apache-2.0 | 35e475b1c5cb199ff940ba302843cd6f | 34.182406 | 134 | 0.598397 | 4.960963 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/v2/http/categories/CategoriesController.kt | 1 | 4212 | package xyz.nulldev.ts.api.v2.http.categories
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import xyz.nulldev.ts.api.v2.http.BaseController
import xyz.nulldev.ts.api.v2.http.Response
import xyz.nulldev.ts.api.v2.http.jvcompat.*
import xyz.nulldev.ts.api.v2.java.model.categories.CategoryCollection
import xyz.nulldev.ts.ext.kInstanceLazy
object CategoriesController : BaseController() {
private val db: DatabaseHelper by kInstanceLazy()
//TODO Swap to Javalin attribute passing
fun prepareCategoriesAttributes(ctx: Context) {
val categoriesParam = ctx.param(CATEGORIES_PARAM)
ctx.attribute(CATEGORIES_ATTR, if(categoriesParam != null)
api.categories.get(*categoriesParam.split(",").map {
it.trim().toInt()
}.toIntArray())
else
api.categories.getAll()
)
}
private val CATEGORIES_PARAM = ":categories"
private val CATEGORIES_ATTR = "categories"
fun getName(ctx: Context) {
prepareCategoriesAttributes(ctx)
getApiField(ctx,
CATEGORIES_ATTR,
CategoryCollection::id,
CategoryCollection::name,
CategoryName::class)
}
fun setName(ctx: Context) {
prepareCategoriesAttributes(ctx)
setApiField(ctx,
CATEGORIES_ATTR,
CategoryCollection::id,
CategoryCollection::name,
CategoryName::id,
CategoryName::name)
}
fun getOrder(ctx: Context) {
prepareCategoriesAttributes(ctx)
getApiField(ctx,
CATEGORIES_ATTR,
CategoryCollection::id,
CategoryCollection::order,
CategoryOrder::class)
}
fun setOrder(ctx: Context) {
prepareCategoriesAttributes(ctx)
setApiField(ctx,
CATEGORIES_ATTR,
CategoryCollection::id,
CategoryCollection::order,
CategoryOrder::id,
CategoryOrder::order)
}
fun getFlags(ctx: Context) {
prepareCategoriesAttributes(ctx)
getApiField(ctx,
CATEGORIES_ATTR,
CategoryCollection::id,
CategoryCollection::flags,
CategoryFlags::class)
}
fun setFlags(ctx: Context) {
prepareCategoriesAttributes(ctx)
setApiField(ctx,
CATEGORIES_ATTR,
CategoryCollection::id,
CategoryCollection::flags,
CategoryFlags::id,
CategoryFlags::flags)
}
fun getCategory(ctx: Context) {
prepareCategoriesAttributes(ctx)
ctx.json(Response.Success(ctx.attribute<CategoryCollection>(CATEGORIES_ATTR).map {
SerializableCategoryModel(it)
}))
}
fun addCategory(ctx: Context) {
val template = ctx.bodyAsClass<CategoryTemplate>()
val res = SerializableCategoryModel(api.categories.add(template.name,
template.order,
template.flags ?: 0))
ctx.json(Response.Success(res))
}
fun deleteCategory(ctx: Context) {
prepareCategoriesAttributes(ctx)
ctx.attribute<CategoryCollection>(CATEGORIES_ATTR).delete()
ctx.json(Response.Success())
}
fun getManga(ctx: Context) {
prepareCategoriesAttributes(ctx)
val attr = ctx.attribute<CategoryCollection>(CATEGORIES_ATTR)
ctx.json(Response.Success(attr.manga.mapIndexed { index, data ->
CategoryManga(attr.id[index], data?.map { it.id!! })
}))
}
fun setManga(ctx: Context) {
prepareCategoriesAttributes(ctx)
val attr = ctx.attribute<CategoryCollection>(CATEGORIES_ATTR)
val new = ctx.bodyAsClass<Array<CategoryManga>>().toList()
attr.manga = attr.id.map { item ->
new.find { it.id == item }?.let {
it.manga?.map { mangaId ->
db.getManga(mangaId).executeAsBlocking()
?: error("Manga $mangaId does not exist!")
}
}
}
ctx.json(Response.Success())
}
}
| apache-2.0 | f3af7c21b624841101a6431a533a8288 | 27.849315 | 90 | 0.59188 | 4.685206 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/EditCustomSettingsAction.kt | 2 | 6182 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.ide.actions
import com.intellij.CommonBundle
import com.intellij.diagnostic.VMOptions
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessExtension
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.DefaultProjectFactory
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.ui.EditorTextField
import com.intellij.util.LineSeparator
import java.io.File
import java.io.IOException
import javax.swing.JFrame
import javax.swing.ScrollPaneConstants
abstract class EditCustomSettingsAction : DumbAwareAction() {
protected abstract fun file(): File?
protected abstract fun template(): String
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = (e.project != null || WelcomeFrame.getInstance() != null) && file() != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
val frame = WelcomeFrame.getInstance() as JFrame?
val file = file() ?: return
if (project != null) {
if (!file.exists()) {
val confirmation = IdeBundle.message("edit.custom.settings.confirm", FileUtil.getLocationRelativeToUserHome(file.path))
val title = e.presentation.text!!
val ok = IdeBundle.message("button.create")
val cancel = IdeBundle.message("button.cancel")
val result = Messages.showOkCancelDialog(project, confirmation, title, ok, cancel, Messages.getQuestionIcon())
if (result == Messages.CANCEL) return
try {
FileUtil.writeToFile(file, template())
}
catch (ex: IOException) {
Logger.getInstance(javaClass).warn(file.path, ex)
val message = IdeBundle.message("edit.custom.settings.failed", file, ex.message)
Messages.showErrorDialog(project, message, CommonBundle.message("title.error"))
return
}
}
val vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)
if (vFile != null) {
vFile.refresh(false, false)
OpenFileDescriptor(project, vFile, vFile.length.toInt()).navigate(true)
}
}
else if (frame != null) {
val text = if (file.exists()) StringUtil.convertLineSeparators(FileUtil.loadFile(file)) else template()
object : DialogWrapper(frame, true) {
private val editor: EditorTextField
init {
title = FileUtil.getLocationRelativeToUserHome(file.path)
setOKButtonText(IdeBundle.message("button.save"))
val document = EditorFactory.getInstance().createDocument(text)
val defaultProject = DefaultProjectFactory.getInstance().defaultProject
val fileType = FileTypeManager.getInstance().getFileTypeByFileName(file.name)
editor = object : EditorTextField(document, defaultProject, fileType, false, false) {
override fun createEditor(): EditorEx {
val editor = super.createEditor()
editor.scrollPane.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
editor.scrollPane.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
return editor
}
}
init()
}
override fun createCenterPanel() = editor
override fun getPreferredFocusedComponent() = editor
override fun getDimensionServiceKey() = "ide.config.custom.settings"
override fun doOKAction() {
val toSave = StringUtil.convertLineSeparators(editor.text, LineSeparator.getSystemLineSeparator().separatorString)
try {
FileUtil.writeToFile(file, toSave)
close(OK_EXIT_CODE)
}
catch (ex: IOException) {
Logger.getInstance(javaClass).warn(file.path, ex)
val message = IdeBundle.message("edit.custom.settings.failed", file, ex.message)
Messages.showErrorDialog(this.window, message, CommonBundle.message("title.error"))
}
}
}.show()
}
}
}
class EditCustomPropertiesAction : EditCustomSettingsAction() {
private companion object {
val file = lazy {
val dir = PathManager.getCustomOptionsDirectory()
return@lazy if (dir != null) File(dir, PathManager.PROPERTIES_FILE_NAME) else null
}
}
override fun file(): File? = EditCustomPropertiesAction.file.value
override fun template(): String = "# custom ${ApplicationNamesInfo.getInstance().fullProductName} properties\n\n"
class AccessExtension : NonProjectFileWritingAccessExtension {
override fun isWritable(file: VirtualFile): Boolean = FileUtil.pathsEqual(file.path, EditCustomPropertiesAction.file.value?.path)
}
}
class EditCustomVmOptionsAction : EditCustomSettingsAction() {
private companion object {
val file = lazy { VMOptions.getWriteFile() }
}
override fun file(): File? = EditCustomVmOptionsAction.file.value
override fun template(): String = "# custom ${ApplicationNamesInfo.getInstance().fullProductName} VM options\n\n${VMOptions.read() ?: ""}"
fun isEnabled() = file() != null
class AccessExtension : NonProjectFileWritingAccessExtension {
override fun isWritable(file: VirtualFile): Boolean = FileUtil.pathsEqual(file.path, EditCustomVmOptionsAction.file.value?.path)
}
} | apache-2.0 | a7b95b15a98f97853714841a1c647b64 | 40.777027 | 140 | 0.721611 | 4.78483 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/v3/operations/categories/CategoryOperations.kt | 1 | 6344 | package xyz.nulldev.ts.api.v3.operations.categories
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.MangaCategory
import io.vertx.core.Vertx
import io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory
import org.eclipse.jetty.http.HttpStatus
import xyz.nulldev.ts.api.v3.OperationGroup
import xyz.nulldev.ts.api.v3.models.categories.*
import xyz.nulldev.ts.api.v3.models.exceptions.WErrorTypes
import xyz.nulldev.ts.api.v3.models.exceptions.WErrorTypes.*
import xyz.nulldev.ts.api.v3.op
import xyz.nulldev.ts.api.v3.opWithParams
import xyz.nulldev.ts.api.v3.util.await
import xyz.nulldev.ts.ext.kInstanceLazy
private const val CATEGORY_ID_PARAM = "categoryId"
class CategoryOperations(private val vertx: Vertx) : OperationGroup {
private val db: DatabaseHelper by kInstanceLazy()
override fun register(routerFactory: OpenAPI3RouterFactory) {
routerFactory.op(::getCategories.name, ::getCategories)
routerFactory.op(::createCategory.name, ::createCategory)
routerFactory.op(::editCategories.name, ::editCategories)
routerFactory.opWithParams(::getCategory.name, CATEGORY_ID_PARAM, ::getCategory)
routerFactory.opWithParams(::editCategory.name, CATEGORY_ID_PARAM, ::editCategory)
routerFactory.opWithParams(::deleteCategory.name, CATEGORY_ID_PARAM, ::deleteCategory)
routerFactory.opWithParams(::editCategoryManga.name, CATEGORY_ID_PARAM, ::editCategoryManga)
}
suspend fun getCategories(): List<WCategory> {
return db.getCategories().await().map {
it.asWeb()
}
}
suspend fun editCategories(requests: List<WBatchMutateCategoryRequest>): List<WCategory> {
val dbCategories = db.getCategories().await()
val resultingCategories = requests.map { request ->
(dbCategories.find { it.id == request.id }
?: abort(HttpStatus.NOT_FOUND_404, request.id.toString())).apply {
request.name?.let { name = it }
request.order?.let { order = it }
}
}
validateCategoryList(dbCategories)
db.insertCategories(resultingCategories).await()
return resultingCategories.map { it.asWeb() }
}
suspend fun createCategory(request: WMutateCategoryRequest): WCategory {
val existingCategories = db.getCategories().await()
validateMutationRequest(existingCategories, -1, request)
val categoryName = request.name ?: run {
var currentCategoryIndex = 1
var newCategoryName: String
do {
newCategoryName = "Category ${currentCategoryIndex++}"
} while (existingCategories.any { it.name.equals(newCategoryName, true) })
newCategoryName
}
val newCategory = Category.create(categoryName).apply {
order = request.order ?: ((existingCategories.maxBy { it.order }?.order ?: 0) + 1)
}
newCategory.id = db.insertCategory(newCategory).await().insertedId()!!.toInt()
return newCategory.asWeb()
}
suspend fun getCategory(categoryId: Int): WCategory {
return db.getCategory(categoryId).await()?.asWeb() ?: notFound()
}
suspend fun editCategory(categoryId: Int, request: WMutateCategoryRequest): WCategory {
val existingCategories = db.getCategories().await()
validateMutationRequest(existingCategories, categoryId, request)
val category = db.getCategory(categoryId).await()?.apply {
request.name?.let { name = it }
request.order?.let { order = it }
} ?: notFound()
db.insertCategory(category).await()
return category.asWeb()
}
suspend fun deleteCategory(categoryId: Int) {
db.deleteCategory(db.getCategory(categoryId).await() ?: notFound()).await()
}
suspend fun editCategoryManga(categoryId: Int, request: WMutateCategoryMangaRequest): Array<Long> {
val category = db.getCategory(categoryId).await() ?: notFound(WErrorTypes.NO_CATEGORY)
if (request.add.any { it in request.remove }) badRequest()
val allMangas = db.getMangas().await().sortedBy { it.id }
val mangaToAdd = allMangas.filter { it.id in request.add }
val mangaToRemove = allMangas.filter { it.id in request.remove }
if (mangaToAdd.size != request.add.size || mangaToRemove.size != request.remove.size) notFound(NO_MANGA)
val mangaCategories = db.getMangaCategoriesForCategory(category).await()
mangaToRemove.forEach { m ->
val mangaCategory = mangaCategories.find { it.manga_id == m.id }
if (mangaCategory != null) {
db.deleteMangaCategory(mangaCategory).await()
}
}
db.insertMangasCategories(mangaToAdd.filter { m ->
mangaCategories.none { it.manga_id == m.id }
}.map { MangaCategory.create(it, category) }).await()
return (mangaCategories.map { it.manga_id } - request.remove + request.add).toSet().toTypedArray()
}
private fun validateMutationRequest(categoryList: List<Category>, curId: Int, request: WMutateCategoryRequestBase) {
val categoryListExcludingCurrent = categoryList.filter { it.id != curId }
if (categoryListExcludingCurrent.any { it.name.equals(request.name, true) })
abort(409, NAME_CONFLICT)
if (request.order != null && categoryListExcludingCurrent.any { it.order == request.order })
abort(409, ORDER_CONFLICT)
}
private fun validateCategoryList(categoryList: List<Category>) {
val seenCategories = mutableSetOf<String>()
val seenOrders = mutableSetOf<Int>()
categoryList.forEach {
val lowerName = it.nameLower
if (lowerName in seenCategories) abort(HttpStatus.CONFLICT_409, NAME_CONFLICT)
if (it.order in seenOrders) abort(HttpStatus.CONFLICT_409, ORDER_CONFLICT)
seenCategories += lowerName
seenOrders += it.order
}
}
suspend fun Category.asWeb() = WCategory(
id!!,
db.getMangaCategoriesForCategory(this).await().map {
it.manga_id
},
name,
order
)
} | apache-2.0 | 32de0155f6fb0e3800edbf5b3c6d489e | 41.583893 | 120 | 0.665826 | 4.333333 | false | false | false | false |
WYKCode/WYK-Android | app/src/main/java/college/wyk/app/ui/timetable/TimetableDayFragment.kt | 1 | 2212 | package college.wyk.app.ui.timetable
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import college.wyk.app.R
import college.wyk.app.commons.adapter.ViewType
import college.wyk.app.model.timetable.Timetable
import college.wyk.app.ui.feed.sns.adapter.DelegatedAdapter
import kotlinx.android.synthetic.main.fragment_timetable.*
class TimetableDayFragment : Fragment() {
private var weekday: Int = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_timetable, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
weekday = arguments.getInt("weekday")
Log.i("WYK", "Now on day ${weekday + 1}")
// set up recycler view
recycler_view.setHasFixedSize(true)
val layoutManager = LinearLayoutManager(activity)
layoutManager.orientation = LinearLayoutManager.VERTICAL
recycler_view.layoutManager = layoutManager
if (recycler_view.adapter == null) {
recycler_view.adapter = TimetableDayAdapter(weekday)
}
// update from current timetable
updateFromCurrentTimetable()
}
fun updateFromCurrentTimetable() {
Timetable.current?.let {
Log.i("WYK", "Updated day ${weekday + 1}")
(recycler_view.adapter as TimetableDayAdapter).updateFromTimetable(it)
}
}
}
class TimetableDayAdapter(val weekday: Int) : DelegatedAdapter() {
init {
delegateAdapters.put(ViewType.timetable_item.ordinal, TimetableEntryDelegateAdapter())
items.add(loadingItem())
notifyDataSetChanged()
}
fun updateFromTimetable(timetable: Timetable) {
items.clear()
for ((key, value) in timetable.entries[weekday].entries) {
items.add(TimetableEntryItem(value.first(), period = key))
}
notifyDataSetChanged()
}
} | mit | 3bf3b0430e2078bc93c2173b7fb50c2e | 31.072464 | 116 | 0.701627 | 4.560825 | false | false | false | false |
sg26565/hott-transmitter-config | HoTT-TTS/src/main/kotlin/de/treichels/hott/tts/PreferencesView.kt | 1 | 1565 | package de.treichels.hott.tts
import de.treichels.hott.tts.polly.PollyTTSProvider
import de.treichels.hott.tts.voicerss.VoiceRSSTTSProvider
import tornadofx.*
class PreferencesView : View() {
private val prefsImage = resources.imageview("prefs.png")
override val root = vbox {
spacing = 5.0
paddingAll = 5.0
prefWidth = 250.0
prefHeight = 245.0
titledpane("VoiceRSS") {
isCollapsible = false
vbox {
label("API Key")
textfield {
text = VoiceRSSTTSProvider.apiKey
setOnKeyReleased {
if (text != null) VoiceRSSTTSProvider.apiKey = text
}
}
}
}
titledpane("Amazon Web Services") {
isCollapsible = false
vbox {
label("Access Key ID")
textfield {
text = PollyTTSProvider.accessKey
setOnKeyReleased {
if (text != null) PollyTTSProvider.accessKey = text
}
}
label("Secret Key")
textfield {
text = PollyTTSProvider.secretKey
setOnKeyReleased {
if (text != null) PollyTTSProvider.secretKey = text
}
}
}
}
}
init {
icon = prefsImage
title = messages["title"]
primaryStage.sizeToScene()
}
}
| lgpl-3.0 | b97588151cbb144a9616905f78bbe5a5 | 25.525424 | 75 | 0.473482 | 5.251678 | false | false | false | false |
gallonyin/clockoff | app/src/main/java/org/caworks/clockoff/fragment/MineFragment.kt | 1 | 1912 | package org.caworks.clockoff.Base
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import org.caworks.clockoff.R
import org.caworks.clockoff.activity.TaskDetailActivity
import org.caworks.clockoff.adapter.MineAdapter
import org.caworks.clockoff.entity.greendao.ClockOffBean
import org.caworks.clockoff.entity.greendao.DBManager
import org.caworks.library.base.BaseFragment
import org.caworks.library.util.GLog
import java.util.*
/**
* Created by Gallon on 2017/6/1
*/
class MineFragment : BaseFragment() {
lateinit var rv_mine: RecyclerView
val list = ArrayList<ClockOffBean>()
override fun getLayoutResId(): Int {
return R.layout.fragment_mine
}
override fun initView(viewRoot: View) {
viewRoot.findViewById(R.id.bt_insert).setOnClickListener { newTask() }
rv_mine = viewRoot.findViewById(R.id.rv_mine) as RecyclerView
rv_mine.layoutManager = LinearLayoutManager(mContext)
rv_mine.adapter = MineAdapter(mContext, list, R.layout.item_mine_habit)
}
override fun onResume() {
super.onResume()
query()
}
/**
* 新建任务
*/
fun newTask() {
GLog.e()
val clockOffBeanList = ArrayList<ClockOffBean>()
// val clockOffBean = ClockOffBean(null, "测试名称2", "测试描述", "", "开始时间", "提醒时间", "记录时间", 1, 1)
// clockOffBeanList.add(clockOffBean)
// DBManager.getInstance(mContext).insertclockOffBeanList(clockOffBeanList, true)
TaskDetailActivity.enterActivity(mContext, null)
}
/**
* 查询 更新集合
*/
fun query() {
val queryClockOffBeanList = DBManager.getInstance(mContext).queryclockOffBeanList()
list.clear()
list.addAll(queryClockOffBeanList)
rv_mine.adapter.notifyDataSetChanged()
}
} | apache-2.0 | fbc59d217d2812d69c037cbd2e09743e | 29.377049 | 98 | 0.696004 | 3.617188 | false | false | false | false |
intrigus/jtransc | jtransc-core/src/com/jtransc/backend/asm1/AsmToAstMethodBody1.kt | 1 | 27499 | package com.jtransc.backend.asm1
import com.jtransc.ast.*
import com.jtransc.ast.optimize.optimize
import com.jtransc.backend.JvmOpcode
import com.jtransc.backend.ast
import com.jtransc.ds.cast
import com.jtransc.ds.hasFlag
import com.jtransc.error.deprecated
import com.jtransc.error.invalidOp
import com.jtransc.error.noImpl
import com.jtransc.org.objectweb.asm.Handle
import com.jtransc.org.objectweb.asm.Opcodes
import com.jtransc.org.objectweb.asm.Type
import com.jtransc.org.objectweb.asm.tree.*
import java.util.*
//const val DEBUG = true
const val DEBUG = false
// classNode.sourceDebug ?: "${classNode.name}.java"
fun AsmToAstMethodBody1(clazz: AstType.REF, method: MethodNode, types: AstTypes, source: String = "unknown.java"): AstBody {
val methodType = types.demangleMethod(method.desc)
val methodInstructions = method.instructions
val methodRef = AstMethodRef(clazz.name, method.name, methodType)
//val DEBUG = method.name == "paramOrderSimple"
if (DEBUG) {
println("--------------------------------------------------------------------")
println("::::::::::::: ${clazz.name}.${method.name}:${method.desc}")
println("--------------------------------------------------------------------")
}
val tryCatchBlocks = method.tryCatchBlocks.cast<TryCatchBlockNode>()
val referencedLabels = hashSetOf<LabelNode>()
for (i in method.instructions) {
when (i) {
is JumpInsnNode -> referencedLabels += i.label
is LookupSwitchInsnNode -> {
referencedLabels.add(i.dflt)
referencedLabels.addAll(i.labels.cast<LabelNode>())
}
is TableSwitchInsnNode -> {
referencedLabels.add(i.dflt)
referencedLabels.addAll(i.labels.cast<LabelNode>())
}
}
}
for (i in tryCatchBlocks) {
referencedLabels += i.handler
referencedLabels += i.start
referencedLabels += i.end
}
val basicBlocks = BasicBlocks(clazz, method, DEBUG, source, types)
val locals = basicBlocks.locals
val labels = basicBlocks.labels
labels.referencedLabelsAsm = referencedLabels
for (b in tryCatchBlocks) {
labels.ref(labels.label(b.start))
labels.ref(labels.label(b.end))
labels.ref(labels.label(b.handler))
labels.referencedHandlers += b.start
labels.referencedHandlers += b.end
labels.referencedHandlers += b.handler
}
val prefix = createFunctionPrefix(clazz, method, locals, types)
basicBlocks.queue(method.instructions.first, prefix.output)
for (b in tryCatchBlocks) {
val catchStack = Stack<AstExpr>()
catchStack.push(AstExpr.CAUGHT_EXCEPTION(types.REF_INT3(b.type) ?: AstType.THROWABLE))
basicBlocks.queue(b.handler, BasicBlock.Frame(catchStack, prefix.output.locals))
}
var hasDynamicInvoke = false
val body2 = method.instructions.toArray().toList().flatMap {
//println(basicBlocks.getBasicBlockForLabel(it))
val bb = basicBlocks.getBasicBlockForLabel(it)
if (bb != null && bb.hasInvokeDynamic) hasDynamicInvoke = true
bb?.stms ?: listOf()
}
val optimizedStms = optimize(prefix.stms + body2, labels.referencedLabels).stm()
val out = AstBody(
types,
optimizedStms,
types.demangleMethod(method.desc),
//locals.locals.values.toList(),
tryCatchBlocks.map {
AstTrap(
start = labels.label(it.start),
end = labels.label(it.end),
handler = labels.label(it.handler),
exception = types.REF_INT3(it.type) ?: AstType.THROWABLE
)
},
AstBodyFlags(types = types, strictfp = method.access.hasFlag(Opcodes.ACC_STRICT), hasDynamicInvoke = hasDynamicInvoke),
methodRef = methodRef
).optimize()
return out
}
fun optimize(stms: List<AstStm>, referencedLabels: HashSet<AstLabel>): List<AstStm> {
return stms.filter {
when (it) {
is AstStm.STM_LABEL -> it.label in referencedLabels
is AstStm.NOP -> false
else -> true
}
}
}
data class FunctionPrefix(val output: BasicBlock.Frame, val stms: List<AstStm>)
class BasicBlocks(
private val clazz: AstType.REF,
private val method: MethodNode,
private val DEBUG: Boolean,
private val source: String,
private val types: AstTypes
) {
val locals = Locals()
val labels = Labels()
private val blocks = hashMapOf<AbstractInsnNode, BasicBlock>()
fun queue(entry: AbstractInsnNode, input: BasicBlock.Frame) {
if (entry in blocks) return
val bb = BasicBlockBuilder(clazz, method, locals, labels, DEBUG, source, types).call(entry, input)
blocks[bb.entry] = bb
for (item in bb.outgoingAll) queue(item, bb.output)
}
fun getBasicBlockForLabel(label: AbstractInsnNode): BasicBlock? {
return blocks[label]
}
}
fun createFunctionPrefix(clazz: AstType.REF, method: MethodNode, locals: Locals, types: AstTypes): FunctionPrefix {
//val localsOutput = arrayListOf<AstExpr.LocalExpr>()
val localsOutput = hashMapOf<Locals.ID, AstLocal>()
val isStatic = method.access.hasFlag(Opcodes.ACC_STATIC)
val methodType = types.demangleMethod(method.desc)
val stms = ArrayList<AstStm>()
var idx = 0
for (arg in (if (!isStatic) listOf(AstExpr.THIS(clazz.name)) else listOf()) + methodType.args.map { AstExpr.PARAM(it) }) {
//setLocalAtIndex(idx, AstExpr.PARAM(arg))
val local = locals.local(fixType(arg.type), idx)
stms.add(local.setTo(arg))
val info = localPair(idx, arg.type, "l")
localsOutput[info] = local
idx++
if (arg.type.isLongOrDouble()) {
localsOutput[info] = local
idx++
}
}
return FunctionPrefix(BasicBlock.Frame(Stack(), localsOutput), stms)
}
data class BasicBlock(
val input: Frame,
val output: Frame,
val entry: AbstractInsnNode,
val stms: List<AstStm>,
val next: AbstractInsnNode?,
val hasInvokeDynamic: Boolean,
val outgoing: List<AbstractInsnNode>
) {
val outgoingAll = (if (next != null) listOf(next) else listOf()) + outgoing
data class Frame(
val stack: Stack<AstExpr>,
val locals: Map<Locals.ID, AstLocal>
)
}
class Labels {
val labels = hashMapOf<AbstractInsnNode, AstLabel>()
val referencedLabels = hashSetOf<AstLabel>()
val referencedHandlers = hashSetOf<LabelNode>()
lateinit var referencedLabelsAsm: HashSet<LabelNode>
var labelId = 0
fun label(label: AbstractInsnNode): AstLabel {
if (label !in labels) {
labels[label] = AstLabel("label_$labelId")
labelId++
}
return labels[label]!!
}
fun ref(label: AbstractInsnNode): AstLabel {
return ref(label(label))
}
fun ref(label: AstLabel): AstLabel {
referencedLabels += label
return label
}
}
fun localPair(index: Int, type: AstType, prefix: String) = Locals.ID(index, fixType(type), prefix)
class Locals {
data class ID(val index: Int, val type: AstType, val prefix: String)
var tempLocalId = 0
val locals = hashMapOf<ID, AstLocal>() // @TODO: remove this
private fun _local(type: AstType, index: Int, prefix: String): AstLocal {
val info = localPair(index, type, prefix)
val type2 = fixType(type)
if (info !in locals) locals[info] = AstLocal(index, "$prefix${nameType(type2)}$index", type2)
return locals[info]!!
}
fun local(type: AstType, index: Int): AstLocal = _local(type, index, "l")
fun temp(type: AstType): AstLocal = _local(type, tempLocalId++, "t")
fun frame(type: AstType, index: Int): AstLocal = _local(type, index, "f")
}
fun fixType(type: AstType): AstType {
return if (type is AstType.Primitive) {
when (type) {
AstType.INT, AstType.FLOAT, AstType.DOUBLE, AstType.LONG -> type
else -> AstType.INT
}
} else {
AstType.OBJECT
}
}
fun nameType(type: AstType): String = (type as? AstType.Primitive)?.chstring ?: "A"
// http://stackoverflow.com/questions/4324321/java-local-variables-how-do-i-get-a-variable-name-or-type-using-its-index
private class BasicBlockBuilder(
val clazz: AstType.REF,
val method: MethodNode,
val locals: Locals,
val labels: Labels,
val DEBUG: Boolean,
val source: String,
val types: AstTypes
) {
companion object {
val PTYPES = listOf(AstType.INT, AstType.LONG, AstType.FLOAT, AstType.DOUBLE, AstType.OBJECT, AstType.BYTE, AstType.CHAR, AstType.SHORT)
val CTYPES = listOf(AstBinop.EQ, AstBinop.NE, AstBinop.LT, AstBinop.GE, AstBinop.GT, AstBinop.LE, AstBinop.EQ, AstBinop.NE)
}
//val list = method.instructions
val methodType = types.demangleMethod(method.desc)
var hasInvokeDynamic = false
val stms = ArrayList<AstStm>()
val stack = Stack<AstExpr>()
var lastLine = -1
//fun fix(field: AstFieldRef): AstFieldRef = locateRightClass.locateRightField(field)
//fun fix(method: AstMethodRef): AstMethodRef = locateRightClass.locateRightMethod(method)
fun fix(field: AstFieldRef): AstFieldRef = field
fun fix(method: AstMethodRef): AstMethodRef = method
fun stmAdd(s: AstStm) {
// Adding statements must dump stack (and restore later) so we preserve calling order!
// Unless it is just a LValue
//if (stack.size == 1 && stack.peek() is AstExpr.LocalExpr) {
//if (false) {
// stms.add(s)
//} else {
if (DEBUG) println("Preserve because stm: $s")
val stack = preserveStack()
stms.add(s)
restoreStack(stack)
//}
}
fun stackPush(e: AstExpr) = run { stack.push(e) }
fun stackPush(e: AstLocal) = run { stack.push(AstExprUtils.localRef(e)) }
fun stackPushListLocal(e: List<AstLocal>) = run { for (i in e) stackPush(i) }
fun stackPop(): AstExpr {
if (stack.isEmpty()) {
println("stackPop() : stack is empty! : ${this.clazz.name}::${this.method.name}")
}
return stack.pop()
}
fun stackPeek(): AstExpr {
if (stack.isEmpty()) {
println("stackPeek() : stack is empty! : ${this.clazz.name}::${this.method.name}")
}
return stack.peek()
}
fun stmSet(local: AstLocal, value: AstExpr): Boolean {
//if (value is AstExpr.REF && value.expr is AstExpr.LOCAL && (value.expr as AstExpr.LOCAL).local == local) return false
if (value is AstExpr.LOCAL && value.local == local) return false
stmAdd(local.setTo(value))
return true
}
//fun stmSet2(local: AstExpr.LocalExpr, value: AstExpr): Boolean {
// if (local != value) {
// stms.add(AstStm.SET(local, fastcast(value, local.type)))
// return true
// } else {
// return false
// }
//}
fun handleField(i: FieldInsnNode) {
//val isStatic = (i.opcode == Opcodes.GETSTATIC) || (i.opcode == Opcodes.PUTSTATIC)
val ref = fix(AstFieldRef(types.REF_INT2(i.owner).fqname.fqname, i.name, types.demangle(i.desc)))
when (i.opcode) {
Opcodes.GETSTATIC -> {
stackPush(AstExpr.FIELD_STATIC_ACCESS(ref).castTo(ref.type))
}
Opcodes.GETFIELD -> {
val obj = stackPop().castTo(ref.containingTypeRef)
stackPush(AstExpr.FIELD_INSTANCE_ACCESS(ref, obj).castTo(ref.type))
}
Opcodes.PUTSTATIC -> {
stmAdd(AstStm.SET_FIELD_STATIC(ref, stackPop().castTo(ref.type)))
}
Opcodes.PUTFIELD -> {
val param = stackPop()
val obj = stackPop().castTo(ref.containingTypeRef)
stmAdd(AstStm.SET_FIELD_INSTANCE(ref, obj, param.castTo(ref.type)))
}
else -> invalidOp
}
}
// peephole optimizations
fun optimize(e: AstExpr.BINOP): AstExpr {
return e
}
fun pushBinop(type: AstType, op: AstBinop) {
val r = stackPop()
val l = stackPop()
//val type2 = when (type) {
// AstType.LONG -> AstType.LONG
// else -> AstType.INT
//}
stackPush(optimize(AstExprUtils.BINOP(type, l, op, r)))
}
fun arrayLoad(type: AstType): Unit {
val index = stackPop()
val array = stackPop()
stackPush(AstExpr.ARRAY_ACCESS(array.castTo(AstType.ARRAY(type)), index.castTo(AstType.INT)))
}
fun arrayStore(elementType: AstType): Unit {
val expr = stackPop()
val index = stackPop()
val array = stackPop()
val arrayTyped = array.castTo(AstType.ARRAY(elementType))
stmAdd(AstStm.SET_ARRAY(arrayTyped, index.castTo(AstType.INT), expr.castTo(elementType)))
}
private var stackPopToLocalsItemsCount = 0
fun stackPopToLocalsFixOrder() {
if (stackPopToLocalsItemsCount == 0) return
val last = stms.takeLast(stackPopToLocalsItemsCount)
for (n in 0 until stackPopToLocalsItemsCount) stms.removeAt(stms.size - 1)
stms.addAll(last.reversed())
//stms.addAll(last)
//if (DEBUG) println("stackPopToLocalsFixOrder")
stackPopToLocalsItemsCount = 0
}
fun stackPopDouble(): List<AstLocal> {
return if (stackPeek().type.isLongOrDouble()) stackPopToLocalsCount(1) else stackPopToLocalsCount(2)
}
fun stackPopToLocalsCount(count: Int): List<AstLocal> {
val pairs = (0 until count).map {
val v = stackPop()
val local = locals.temp(v.type)
Pair(local, v)
}
stackPopToLocalsItemsCount += pairs.count { stmSet(it.first, it.second) }
return pairs.map { it.first }.reversed()
}
@Suppress("RemoveRedundantCallsOfConversionMethods")
fun handleInsn(i: InsnNode): Unit {
val op = i.opcode
when (i.opcode) {
Opcodes.NOP -> {
//stmAdd(AstStm.NOP)
Unit
}
Opcodes.ACONST_NULL -> stackPush(null.lit)
in Opcodes.ICONST_M1..Opcodes.ICONST_5 -> stackPush((op - Opcodes.ICONST_0).toInt().lit)
in Opcodes.LCONST_0..Opcodes.LCONST_1 -> stackPush((op - Opcodes.LCONST_0).toLong().lit)
in Opcodes.FCONST_0..Opcodes.FCONST_2 -> stackPush((op - Opcodes.FCONST_0).toFloat().lit)
in Opcodes.DCONST_0..Opcodes.DCONST_1 -> stackPush((op - Opcodes.DCONST_0).toDouble().lit)
in Opcodes.IALOAD..Opcodes.SALOAD -> arrayLoad(PTYPES[op - Opcodes.IALOAD])
in Opcodes.IASTORE..Opcodes.SASTORE -> arrayStore(PTYPES[op - Opcodes.IASTORE])
Opcodes.POP -> {
// We store it, so we don't lose all the calculated stuff!
stackPopToLocalsCount(1)
stackPopToLocalsFixOrder()
}
Opcodes.POP2 -> {
stackPopDouble()
stackPopToLocalsFixOrder()
}
Opcodes.DUP -> {
val value = stackPop()
val local = locals.temp(value.type)
stmSet(local, value)
stackPush(local)
stackPush(local)
}
Opcodes.DUP_X1 -> {
//untestedWarn2("DUP_X1")
val chunk1 = stackPopToLocalsCount(1)
val chunk2 = stackPopToLocalsCount(1)
stackPopToLocalsFixOrder()
stackPushListLocal(chunk1)
stackPushListLocal(chunk2)
stackPushListLocal(chunk1)
}
Opcodes.DUP_X2 -> {
val chunk1 = stackPopToLocalsCount(1)
val chunk2 = stackPopDouble()
stackPopToLocalsFixOrder()
stackPushListLocal(chunk1)
stackPushListLocal(chunk2)
stackPushListLocal(chunk1)
}
Opcodes.DUP2 -> {
val chunk1 = stackPopDouble()
stackPopToLocalsFixOrder()
stackPushListLocal(chunk1)
stackPushListLocal(chunk1)
}
Opcodes.DUP2_X1 -> {
//untestedWarn2("DUP2_X1")
val chunk1 = stackPopDouble()
val chunk2 = stackPopToLocalsCount(1)
stackPopToLocalsFixOrder()
stackPushListLocal(chunk1)
stackPushListLocal(chunk2)
stackPushListLocal(chunk1)
}
Opcodes.DUP2_X2 -> {
//untestedWarn2("DUP2_X2")
val chunk1 = stackPopDouble()
val chunk2 = stackPopDouble()
stackPopToLocalsFixOrder()
stackPushListLocal(chunk1)
stackPushListLocal(chunk2)
stackPushListLocal(chunk1)
}
Opcodes.SWAP -> {
val v1 = stackPop()
val v2 = stackPop()
stackPopToLocalsFixOrder()
stackPush(v1)
stackPush(v2)
}
in Opcodes.INEG..Opcodes.DNEG -> stackPush(AstExpr.UNOP(AstUnop.NEG, stackPop()))
in Opcodes.IADD..Opcodes.DADD -> pushBinop(PTYPES[op - Opcodes.IADD], AstBinop.ADD)
in Opcodes.ISUB..Opcodes.DSUB -> pushBinop(PTYPES[op - Opcodes.ISUB], AstBinop.SUB)
in Opcodes.IMUL..Opcodes.DMUL -> pushBinop(PTYPES[op - Opcodes.IMUL], AstBinop.MUL)
in Opcodes.IDIV..Opcodes.DDIV -> pushBinop(PTYPES[op - Opcodes.IDIV], AstBinop.DIV)
in Opcodes.IREM..Opcodes.DREM -> pushBinop(PTYPES[op - Opcodes.IREM], AstBinop.REM)
in Opcodes.ISHL..Opcodes.LSHL -> pushBinop(PTYPES[op - Opcodes.ISHL], AstBinop.SHL)
in Opcodes.ISHR..Opcodes.LSHR -> pushBinop(PTYPES[op - Opcodes.ISHR], AstBinop.SHR)
in Opcodes.IUSHR..Opcodes.LUSHR -> pushBinop(PTYPES[op - Opcodes.IUSHR], AstBinop.USHR)
in Opcodes.IAND..Opcodes.LAND -> pushBinop(PTYPES[op - Opcodes.IAND], AstBinop.AND)
in Opcodes.IOR..Opcodes.LOR -> pushBinop(PTYPES[op - Opcodes.IOR], AstBinop.OR)
in Opcodes.IXOR..Opcodes.LXOR -> pushBinop(PTYPES[op - Opcodes.IXOR], AstBinop.XOR)
Opcodes.I2L, Opcodes.F2L, Opcodes.D2L -> stackPush(stackPop().castTo(AstType.LONG))
Opcodes.I2F, Opcodes.L2F, Opcodes.D2F -> stackPush(stackPop().castTo(AstType.FLOAT))
Opcodes.I2D, Opcodes.L2D, Opcodes.F2D -> stackPush(stackPop().castTo(AstType.DOUBLE))
Opcodes.L2I, Opcodes.F2I, Opcodes.D2I -> stackPush(stackPop().castTo(AstType.INT))
Opcodes.I2B -> stackPush(stackPop().castTo(AstType.BYTE))
Opcodes.I2C -> stackPush(stackPop().castTo(AstType.CHAR))
Opcodes.I2S -> stackPush(stackPop().castTo(AstType.SHORT))
Opcodes.LCMP -> pushBinop(AstType.INT, AstBinop.LCMP)
Opcodes.FCMPL -> pushBinop(AstType.FLOAT, AstBinop.CMPL)
Opcodes.FCMPG -> pushBinop(AstType.FLOAT, AstBinop.CMPG)
Opcodes.DCMPL -> pushBinop(AstType.DOUBLE, AstBinop.CMPL)
Opcodes.DCMPG -> pushBinop(AstType.DOUBLE, AstBinop.CMPG)
Opcodes.ARRAYLENGTH -> stackPush(AstExpr.ARRAY_LENGTH(stackPop()))
Opcodes.MONITORENTER -> stmAdd(AstStm.MONITOR_ENTER(stackPop()))
Opcodes.MONITOREXIT -> stmAdd(AstStm.MONITOR_EXIT(stackPop()))
else -> invalidOp("$op")
}
}
fun handleMultiArray(i: MultiANewArrayInsnNode) {
when (i.opcode) {
Opcodes.MULTIANEWARRAY -> {
stackPush(AstExpr.NEW_ARRAY(types.REF_INT(i.desc).asArray(), (0 until i.dims).map { stackPop() }.reversed()))
}
else -> invalidOp("$i")
}
}
fun handleType(i: TypeInsnNode) {
val type = types.REF_INT(i.desc)
when (i.opcode) {
Opcodes.NEW -> stackPush(AstExpr.NEW(type as AstType.REF).castTo(AstType.OBJECT))
Opcodes.ANEWARRAY -> stackPush(AstExpr.NEW_ARRAY(AstType.ARRAY(type), listOf(stackPop())))
Opcodes.CHECKCAST -> stackPush(stackPop().checkedCastTo(type))
Opcodes.INSTANCEOF -> stackPush(AstExpr.INSTANCE_OF(stackPop(), type as AstType.Reference))
else -> invalidOp("$i")
}
}
fun handleVar(i: VarInsnNode) {
val op = i.opcode
val index = i.`var`
fun load(type: AstType) {
stackPush(AstExprUtils.localRef(locals.local(type, index)))
}
fun store(type: AstType) {
stmSet(locals.local(type, index), stackPop())
}
when (op) {
in Opcodes.ILOAD..Opcodes.ALOAD -> load(PTYPES[op - Opcodes.ILOAD])
in Opcodes.ISTORE..Opcodes.ASTORE -> store(PTYPES[op - Opcodes.ISTORE])
Opcodes.RET -> deprecated
else -> invalidOp
}
}
fun addJump(cond: AstExpr?, label: AstLabel) {
if (DEBUG) println("Preserve because jump")
restoreStack(preserveStack())
labels.ref(label)
if (cond != null) {
stms.add(AstStm.IF_GOTO(label, cond))
} else {
stms.add(AstStm.GOTO(label))
}
}
fun handleLdc(i: LdcInsnNode) {
val cst = i.cst
when (cst) {
is Int, is Float, is Long, is Double, is String -> stackPush(cst.lit)
is Type -> stackPush(types.REF_INT(cst.internalName).lit)
else -> invalidOp
}
}
fun handleInt(i: IntInsnNode) {
when (i.opcode) {
Opcodes.BIPUSH -> stackPush(i.operand.toByte().lit)
Opcodes.SIPUSH -> stackPush(i.operand.toShort().lit)
Opcodes.NEWARRAY -> {
val type = when (i.operand) {
Opcodes.T_BOOLEAN -> AstType.BOOL
Opcodes.T_CHAR -> AstType.CHAR
Opcodes.T_FLOAT -> AstType.FLOAT
Opcodes.T_DOUBLE -> AstType.DOUBLE
Opcodes.T_BYTE -> AstType.BYTE
Opcodes.T_SHORT -> AstType.SHORT
Opcodes.T_INT -> AstType.INT
Opcodes.T_LONG -> AstType.LONG
else -> invalidOp
}
stackPush(AstExpr.NEW_ARRAY(types.ARRAY(type, 1), listOf(stackPop())))
}
else -> invalidOp
}
}
fun handleMethod(i: MethodInsnNode) {
val type = types.REF_INT(i.owner)
val clazz = (type as? AstType.REF) ?: AstType.OBJECT
val methodRef = fix(AstMethodRef(clazz.fqname.fqname, i.name, types.demangleMethod(i.desc)))
val isSpecial = i.opcode == Opcodes.INVOKESPECIAL
val args = methodRef.type.args.reversed().map { stackPop().castTo(it.type) }.reversed()
val obj = if (i.opcode != Opcodes.INVOKESTATIC) stackPop() else null
if (obj != null) {
val cobj = obj.castTo(methodRef.containingClassType)
stackPush(AstExpr.CALL_INSTANCE(cobj, methodRef, args, isSpecial))
} else {
stackPush(AstExpr.CALL_STATIC(clazz, methodRef, args, isSpecial))
}
if (methodRef.type.retVoid) {
//preserveStack()
stmAdd(AstStm.STM_EXPR(stackPop()))
}
}
fun handleInvokeDynamic(i: InvokeDynamicInsnNode) {
hasInvokeDynamic = true
val dynamicResult = AstExprUtils.INVOKE_DYNAMIC(
AstMethodWithoutClassRef(i.name, types.demangleMethod(i.desc)),
i.bsm.ast(types),
i.bsmArgs.map {
when (it) {
is Type -> when (it.sort) {
Type.METHOD -> types.demangleMethod(it.descriptor).lit
else -> noImpl("${it.sort} : $it")
}
is Handle -> {
val kind = AstMethodHandle.Kind.fromId(it.tag)
val type = types.demangleMethod(it.desc)
AstMethodHandle(type, AstMethodRef(FqName.fromInternal(it.owner), it.name, type), kind).lit
}
else -> it.lit
}
}
)
if (dynamicResult is AstExpr.INVOKE_DYNAMIC_METHOD) {
// dynamicResult.startArgs = stackPopToLocalsCount(dynamicResult.extraArgCount).map { AstExpr.LOCAL(it) }.reversed()
dynamicResult.startArgs = (0 until dynamicResult.extraArgCount).map { stackPop() }.reversed()
}
stackPush(dynamicResult)
}
fun handleIinc(i: IincInsnNode) {
val local = locals.local(AstType.INT, i.`var`)
stmSet(local, AstExprUtils.localRef(local) + i.incr.lit)
}
fun handleLineNumber(i: LineNumberNode) {
lastLine = i.line
stmAdd(AstStm.LINE(source, i.line))
}
fun preserveStackLocal(index: Int, type: AstType): AstLocal {
return locals.frame(type, index)
}
fun dumpExprs() {
while (stack.isNotEmpty()) stmAdd(AstStm.STM_EXPR(stackPop()))
}
@Suppress("UNCHECKED_CAST")
fun preserveStack(): List<AstLocal> {
if (stack.isEmpty()) return Collections.EMPTY_LIST as List<AstLocal>
val items = arrayListOf<AstLocal>()
val preservedStack = (0 until stack.size).map { stackPop() }
if (DEBUG) println("[[")
for ((index2, value) in preservedStack.withIndex().reversed()) {
//val index = index2
val index = preservedStack.size - index2 - 1
val local = preserveStackLocal(index, value.type)
if (DEBUG) println("PRESERVE: $local : $index, ${value.type}")
stmSet(local, value)
items.add(local)
}
items.reverse()
if (DEBUG) println("]]")
return items
}
fun restoreStack(stackToRestore: List<AstLocal>) {
if (stackToRestore.size >= 2) {
//println("stackToRestore.size:" + stackToRestore.size)
}
for (i in stackToRestore.reversed()) {
if (DEBUG) println("RESTORE: $i")
// @TODO: avoid reversed by inserting in the right order!
this.stack.push(AstExprUtils.localRef(i))
}
}
@Suppress("UNCHECKED_CAST")
fun call(entry: AbstractInsnNode, input: BasicBlock.Frame): BasicBlock {
var i: AbstractInsnNode? = entry
var next: AbstractInsnNode? = null
val outgoing = arrayListOf<AbstractInsnNode>()
// RESTORE INPUTS
if (DEBUG && input.stack.size >= 2) println("---------")
if (i is LabelNode) {
stms.add(AstStm.STM_LABEL(labels.label(i)))
i = i.next
}
this.stack.clear()
for (i2 in input.stack.clone() as Stack<AstExpr>) {
this.stack += i2
}
for ((key, value) in HashMap(input.locals)) locals.locals[key] = value
if (DEBUG) {
println("**** BASIC_BLOCK ${clazz.name}.${method.name}:${method.desc} :: BASIC_BLOCK: $entry, $input")
}
loop@ while (i != null) {
if (DEBUG) println(JvmOpcode.disasm(i))
val op = i.opcode
when (i) {
is FieldInsnNode -> handleField(i)
is InsnNode -> {
when (op) {
in Opcodes.IRETURN..Opcodes.ARETURN -> {
val ret = stackPop()
dumpExprs()
stmAdd(AstStm.RETURN(ret.castTo(this.methodType.ret)))
next = null
break@loop
}
Opcodes.RETURN -> {
dumpExprs()
stmAdd(AstStm.RETURN_VOID())
next = null
break@loop
}
Opcodes.ATHROW -> {
val ret = stackPop()
dumpExprs()
stmAdd(AstStm.THROW(ret))
next = null
break@loop
}
else -> handleInsn(i)
}
}
is JumpInsnNode -> {
when (op) {
in Opcodes.IFEQ..Opcodes.IFLE -> {
addJump(AstExprUtils.BINOP(AstType.BOOL, stackPop(), CTYPES[op - Opcodes.IFEQ], 0.lit), labels.label(i.label))
//addJump(null, labels.label(i.next))
}
in Opcodes.IFNULL..Opcodes.IFNONNULL -> {
addJump(AstExprUtils.BINOP(AstType.BOOL, stackPop(), CTYPES[op - Opcodes.IFNULL], null.lit), labels.label(i.label))
}
in Opcodes.IF_ICMPEQ..Opcodes.IF_ACMPNE -> {
val r = stackPop()
val l = stackPop()
addJump(AstExprUtils.BINOP(AstType.BOOL, l, CTYPES[op - Opcodes.IF_ICMPEQ], r), labels.label(i.label))
}
Opcodes.GOTO -> addJump(null, labels.label(i.label))
Opcodes.JSR -> deprecated
else -> invalidOp
}
if (op == Opcodes.GOTO) {
next = i.label
break@loop
} else {
next = i.next
outgoing.add(i.label)
break@loop
}
}
is LookupSwitchInsnNode -> {
val labels2 = i.labels.cast<LabelNode>()
stmAdd(AstStm.SWITCH_GOTO(
stackPop(),
labels.ref(labels.label(i.dflt)),
i.keys.cast<Int>().zip(labels2.map { labels.ref(labels.label(it)) }).groupByLabel()
))
next = i.dflt
outgoing.addAll(labels2)
break@loop
}
is TableSwitchInsnNode -> {
val labels2 = i.labels.cast<LabelNode>()
stmAdd(AstStm.SWITCH_GOTO(
stackPop(),
labels.ref(labels.label(i.dflt)),
(i.min..i.max).zip(labels2.map { labels.ref(labels.label(it)) }).groupByLabel()
))
next = i.dflt
outgoing.addAll(labels2)
break@loop
}
is LabelNode -> {
if (i in labels.referencedLabelsAsm) {
if (DEBUG) println("Preserve because label")
restoreStack(preserveStack())
next = i
break@loop
}
}
is FrameNode -> Unit
is LdcInsnNode -> handleLdc(i)
is IntInsnNode -> handleInt(i)
is MethodInsnNode -> handleMethod(i)
is TypeInsnNode -> handleType(i)
is VarInsnNode -> handleVar(i)
is InvokeDynamicInsnNode -> handleInvokeDynamic(i)
is IincInsnNode -> handleIinc(i)
is LineNumberNode -> handleLineNumber(i)
is MultiANewArrayInsnNode -> handleMultiArray(i)
else -> invalidOp("$i")
}
i = i.next
}
return BasicBlock(
input = input,
hasInvokeDynamic = hasInvokeDynamic,
output = BasicBlock.Frame(
stack.clone() as Stack<AstExpr>,
locals.locals.clone() as Map<Locals.ID, AstLocal>
),
entry = entry,
stms = stms,
next = next,
outgoing = outgoing
)
}
}
fun AbstractInsnNode.disasm() = JvmOpcode.disasm(this)
fun JvmOpcode.Companion.disasm(i: AbstractInsnNode): String {
val op = BY_ID[i.opcode]
return when (i) {
is FieldInsnNode -> "$op ${i.owner}.${i.name} :: ${i.desc}"
is InsnNode -> "$op"
is TypeInsnNode -> "$op ${i.desc}"
is VarInsnNode -> "$op ${i.`var`}"
is JumpInsnNode -> "$op ${i.label.label}"
is LdcInsnNode -> "$op (${i.cst}) : ${i.cst.javaClass}"
is IntInsnNode -> "$op ${i.operand}"
is MethodInsnNode -> "$op ${i.owner}.${i.name} :: ${i.desc} :: ${i.itf}"
is LookupSwitchInsnNode -> "$op ${i.dflt.label} ${i.keys} ${i.labels.cast<LabelNode>().map { it.label }}"
is TableSwitchInsnNode -> "$op ${i.dflt.label} ${i.min}..${i.max} ${i.labels.cast<LabelNode>().map { it.label }}"
is InvokeDynamicInsnNode -> "$op ${i.name} ${i.desc} ${i.bsm} ${i.bsmArgs}"
is LabelNode -> ":${i.label}"
is IincInsnNode -> "$op ${i.`var`} += ${i.incr}"
is LineNumberNode -> "LINE_${i.line}"
is FrameNode -> "FRAME: ${i.local} : ${i.stack} : ${i.type}"
is MultiANewArrayInsnNode -> "$op : ${i.desc} : ${i.dims}"
else -> invalidOp("$i")
}
//BY_ID[i.opcode]?.toString() ?: "$i"
}
| apache-2.0 | ce4bb36e854f0453d5dbd8e5d735efaf | 30.754042 | 138 | 0.678388 | 3.070113 | false | false | false | false |
intrigus/jtransc | jtransc-utils/src/com/jtransc/text/reader.kt | 2 | 4569 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.text
import com.jtransc.error.InvalidOperationException
import com.jtransc.error.invalidOp
import java.io.Reader
class StrReader(val str: String, var offset: Int = 0) {
val length: Int get() = str.length
val eof: Boolean get() = offset >= length
val hasMore: Boolean get() = !eof
fun readch(): Char = this.str[offset++]
fun read(): Int = if (!eof) readch().toInt() else -1
fun peek(count: Int): String {
if (offset >= length) return ""
return this.str.substring(offset, Math.min(length, offset + count))
}
fun peekch(): Char = if (hasMore) this.str[offset] else 0.toChar()
fun read(count: Int): String {
val out = this.peek(count)
this.offset += count
return out
}
fun skipSpaces(): StrReader {
while (this.hasMore && this.peek(1).isNullOrBlank()) this.read()
return this
}
fun expect(expected: String): String {
val result = this.read(expected.length)
if (result != expected) throw InvalidOperationException("Expecting '$expected' but found '$result' in '$str'")
return result
}
fun matchEReg(v: Regex): String? {
val result = v.find(this.str.substring(this.offset)) ?: return null
val m = result.groups[0]!!.value
this.offset += m.length;
return m;
}
override fun toString() = "StrReader('$str')"
fun <T> readList(min: Int, readElement: (s: StrReader) -> T?): List<T> {
val out = arrayListOf<T>()
while (this.hasMore) {
out.add(readElement(this) ?: break)
}
if (out.size < min) invalidOp("Expected a list of at least $min elements and had ${out.size}")
return out
}
fun clone() = StrReader(str, offset)
}
fun Reader.readUntil(expectedCh: Set<Char>, including: Boolean = false, readDelimiter: Boolean = true): String {
var out = ""
while (this.hasMore) {
val ch = this.peekch()
if (ch in expectedCh) {
if (including) out += ch
if (readDelimiter) this.readch()
break
}
out += ch
this.readch()
}
return out
}
fun Reader.readUntil(vararg expectedCh: Char, including: Boolean = false, readDelimiter: Boolean = true): String = this.readUntil(expectedCh.toSet(), including)
fun Reader.read(count: Int): String {
val out = CharArray(count)
this.read(out)
return String(out)
}
fun Reader.peek(count: Int): String {
val out = CharArray(count)
this.mark(count)
this.read(out)
this.reset()
return String(out)
}
fun Reader.peekch(): Char {
this.mark(1)
val result = this.readch()
this.reset()
return result
}
fun Reader.expect(expected: String): String {
val result = this.read(expected.length)
if (result != expected) throw InvalidOperationException()
return result
}
val Reader.hasMore: Boolean get() = !this.eof
val Reader.eof: Boolean get() {
this.mark(1)
val result = this.read()
this.reset()
return result < 0
}
fun Reader.readch(): Char {
val value = this.read()
if (value < 0) throw RuntimeException("End of stream")
return value.toChar()
}
fun <T : Reader> T.skipSpaces(): T {
while (this.peek(1).isNullOrBlank()) {
this.read()
}
return this
}
fun StrReader.readUntil(expectedCh: Set<Char>, including: Boolean = false, readDelimiter: Boolean = true): String {
var out = ""
while (this.hasMore) {
val ch = this.peekch()
if (ch in expectedCh) {
if (including) out += ch
if (readDelimiter) this.readch()
break
}
out += ch
this.readch()
}
return out
}
fun StrReader.readUntil(vararg expectedCh: Char, including: Boolean = false, readDelimiter: Boolean = true): String = this.readUntil(expectedCh.toSet(), including)
inline fun StrReader.createRange(action: () -> Unit): String? {
val start = this.offset
action()
val end = this.offset
return if (start < end) this.str.substring(start, end) else null
}
inline fun StrReader.readWhile(cond: (Char) -> Boolean): String? {
return this.createRange {
while (this.hasMore) {
if (!cond(this.peekch())) break
this.readch()
}
}
}
inline fun StrReader.readUntil(cond: (Char) -> Boolean): String? {
return readWhile { !cond(it) }
} | apache-2.0 | 6c7b8373dd773fab3c3169876c9d9892 | 25.416185 | 163 | 0.688991 | 3.16632 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/writedownkey/WriteDownKeyController.kt | 1 | 3859 | /**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 10/10/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.writedownkey
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.core.os.bundleOf
import com.breadwallet.R
import com.breadwallet.databinding.ControllerWriteDownBinding
import com.breadwallet.tools.util.BRConstants
import com.breadwallet.ui.BaseMobiusController
import com.breadwallet.ui.auth.AuthenticationController
import com.breadwallet.ui.flowbind.clicks
import com.breadwallet.ui.navigation.OnCompleteAction
import com.breadwallet.ui.writedownkey.WriteDownKey.E
import com.breadwallet.ui.writedownkey.WriteDownKey.F
import com.breadwallet.ui.writedownkey.WriteDownKey.M
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import org.kodein.di.direct
import org.kodein.di.erased.instance
class WriteDownKeyController(args: Bundle? = null) :
BaseMobiusController<M, E, F>(args),
AuthenticationController.Listener {
companion object {
private const val EXTRA_ON_COMPLETE = "on-complete"
private const val EXTRA_REQUEST_AUTH = "request-brd-auth"
}
constructor(
doneAction: OnCompleteAction,
requestAuth: Boolean
) : this(
bundleOf(
EXTRA_ON_COMPLETE to doneAction.name,
EXTRA_REQUEST_AUTH to requestAuth
)
)
init {
registerForActivityResult(BRConstants.SHOW_PHRASE_REQUEST_CODE)
}
private val onComplete = OnCompleteAction.valueOf(arg(EXTRA_ON_COMPLETE))
private val requestAuth = arg<Boolean>(EXTRA_REQUEST_AUTH)
override val layoutId: Int = R.layout.controller_write_down
override val defaultModel = M.createDefault(onComplete, requestAuth)
override val update = WriteDownKeyUpdate
override val flowEffectHandler
get() = createWriteDownKeyHandler(direct.instance())
private val binding by viewBinding(ControllerWriteDownBinding::inflate)
override fun bindView(modelFlow: Flow<M>): Flow<E> = with(binding) {
merge(
faqButton.clicks().map { E.OnFaqClicked },
closeButton.clicks().map { E.OnCloseClicked },
buttonWriteDown.clicks().map { E.OnWriteDownClicked }
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == BRConstants.SHOW_PHRASE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
eventConsumer.accept(E.OnUserAuthenticated)
}
}
override fun onAuthenticationSuccess() {
eventConsumer.accept(E.OnUserAuthenticated)
}
}
| mit | bf380adc7272278a878190bff0c2ae85 | 37.979798 | 102 | 0.741643 | 4.35062 | false | false | false | false |
android/uamp | app/src/main/java/com/example/android/uamp/viewmodels/MainActivityViewModel.kt | 4 | 7247 | /*
* 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.uamp.viewmodels
import android.support.v4.media.MediaBrowserCompat
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.android.uamp.MainActivity
import com.example.android.uamp.MediaItemData
import com.example.android.uamp.common.MusicServiceConnection
import com.example.android.uamp.fragments.NowPlayingFragment
import com.example.android.uamp.media.extensions.id
import com.example.android.uamp.media.extensions.isPlayEnabled
import com.example.android.uamp.media.extensions.isPlaying
import com.example.android.uamp.media.extensions.isPrepared
import com.example.android.uamp.utils.Event
/**
* Small [ViewModel] that watches a [MusicServiceConnection] to become connected
* and provides the root/initial media ID of the underlying [MediaBrowserCompat].
*/
class MainActivityViewModel(
private val musicServiceConnection: MusicServiceConnection
) : ViewModel() {
val rootMediaId: LiveData<String> =
Transformations.map(musicServiceConnection.isConnected) { isConnected ->
if (isConnected) {
musicServiceConnection.rootMediaId
} else {
null
}
}
/**
* [navigateToMediaItem] acts as an "event", rather than state. [Observer]s
* are notified of the change as usual with [LiveData], but only one [Observer]
* will actually read the data. For more information, check the [Event] class.
*/
val navigateToMediaItem: LiveData<Event<String>> get() = _navigateToMediaItem
private val _navigateToMediaItem = MutableLiveData<Event<String>>()
/**
* This [LiveData] object is used to notify the MainActivity that the main
* content fragment needs to be swapped. Information about the new fragment
* is conveniently wrapped by the [Event] class.
*/
val navigateToFragment: LiveData<Event<FragmentNavigationRequest>> get() = _navigateToFragment
private val _navigateToFragment = MutableLiveData<Event<FragmentNavigationRequest>>()
/**
* This method takes a [MediaItemData] and routes it depending on whether it's
* browsable (i.e.: it's the parent media item of a set of other media items,
* such as an album), or not.
*
* If the item is browsable, handle it by sending an event to the Activity to
* browse to it, otherwise play it.
*/
fun mediaItemClicked(clickedItem: MediaItemData) {
if (clickedItem.browsable) {
browseToItem(clickedItem)
} else {
playMedia(clickedItem, pauseAllowed = false)
showFragment(NowPlayingFragment.newInstance())
}
}
/**
* Convenience method used to swap the fragment shown in the main activity
*
* @param fragment the fragment to show
* @param backStack if true, add this transaction to the back stack
* @param tag the name to use for this fragment in the stack
*/
fun showFragment(fragment: Fragment, backStack: Boolean = true, tag: String? = null) {
_navigateToFragment.value = Event(FragmentNavigationRequest(fragment, backStack, tag))
}
/**
* This posts a browse [Event] that will be handled by the
* observer in [MainActivity].
*/
private fun browseToItem(mediaItem: MediaItemData) {
_navigateToMediaItem.value = Event(mediaItem.mediaId)
}
/**
* This method takes a [MediaItemData] and does one of the following:
* - If the item is *not* the active item, then play it directly.
* - If the item *is* the active item, check whether "pause" is a permitted command. If it is,
* then pause playback, otherwise send "play" to resume playback.
*/
fun playMedia(mediaItem: MediaItemData, pauseAllowed: Boolean = true) {
val nowPlaying = musicServiceConnection.nowPlaying.value
val transportControls = musicServiceConnection.transportControls
val isPrepared = musicServiceConnection.playbackState.value?.isPrepared ?: false
if (isPrepared && mediaItem.mediaId == nowPlaying?.id) {
musicServiceConnection.playbackState.value?.let { playbackState ->
when {
playbackState.isPlaying ->
if (pauseAllowed) transportControls.pause() else Unit
playbackState.isPlayEnabled -> transportControls.play()
else -> {
Log.w(
TAG, "Playable item clicked but neither play nor pause are enabled!" +
" (mediaId=${mediaItem.mediaId})"
)
}
}
}
} else {
transportControls.playFromMediaId(mediaItem.mediaId, null)
}
}
fun playMediaId(mediaId: String) {
val nowPlaying = musicServiceConnection.nowPlaying.value
val transportControls = musicServiceConnection.transportControls
val isPrepared = musicServiceConnection.playbackState.value?.isPrepared ?: false
if (isPrepared && mediaId == nowPlaying?.id) {
musicServiceConnection.playbackState.value?.let { playbackState ->
when {
playbackState.isPlaying -> transportControls.pause()
playbackState.isPlayEnabled -> transportControls.play()
else -> {
Log.w(
TAG, "Playable item clicked but neither play nor pause are enabled!" +
" (mediaId=$mediaId)"
)
}
}
}
} else {
transportControls.playFromMediaId(mediaId, null)
}
}
class Factory(
private val musicServiceConnection: MusicServiceConnection
) : ViewModelProvider.NewInstanceFactory() {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return MainActivityViewModel(musicServiceConnection) as T
}
}
}
/**
* Helper class used to pass fragment navigation requests between MainActivity
* and its corresponding ViewModel.
*/
data class FragmentNavigationRequest(
val fragment: Fragment,
val backStack: Boolean = false,
val tag: String? = null
)
private const val TAG = "MainActivitytVM"
| apache-2.0 | 5460886750f3b1dc8c52a7cb471f0fda | 38.601093 | 98 | 0.663171 | 4.970508 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/progress/BasePaintDrawable.kt | 1 | 1499 | /*
* Copyright (C) 2017-2019 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.
*/
/*
* Copyright (c) 2016 Zhang Hai <[email protected]>
* All Rights Reserved.
*/
package jp.hazuki.yuzubrowser.ui.widget.progress
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
internal abstract class BasePaintDrawable : BaseDrawable() {
private var mPaint: Paint? = null
override fun onDraw(canvas: Canvas, width: Int, height: Int) {
val paint = mPaint ?: Paint().also {
mPaint = it
it.isAntiAlias = true
it.color = Color.BLACK
onPreparePaint(it)
}
paint.alpha = mAlpha
paint.colorFilter = colorFilterForDrawing
onDraw(canvas, width, height, paint)
}
protected abstract fun onPreparePaint(paint: Paint)
protected abstract fun onDraw(canvas: Canvas, width: Int, height: Int,
paint: Paint)
}
| apache-2.0 | 956188ab010fa4838b15a213dc33075c | 29.591837 | 75 | 0.677785 | 4.210674 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/command/money/MoneyWalletCommand.kt | 1 | 7382 | /*
* Copyright 2016 Ross Binden
*
* 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.rpkit.economy.bukkit.command.money
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.economy.bukkit.RPKEconomyBukkit
import com.rpkit.economy.bukkit.currency.RPKCurrency
import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider
import com.rpkit.economy.bukkit.economy.RPKEconomyProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.conversations.*
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
/**
* Money wallet command.
* Opens the player's active character's wallet with a physical currency representation.
*/
class MoneyWalletCommand(private val plugin: RPKEconomyBukkit): CommandExecutor {
private val conversationFactory = ConversationFactory(plugin)
.withModality(true)
.withFirstPrompt(CurrencyPrompt())
.withEscapeSequence("cancel")
.thatExcludesNonPlayersWithMessage(plugin.messages["not-from-console"])
.addConversationAbandonedListener { event ->
if (!event.gracefulExit()) {
val conversable = event.context.forWhom
if (conversable is Player) {
conversable.sendMessage(plugin.messages["operation-cancelled"])
}
}
}
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender.hasPermission("rpkit.economy.command.money.wallet")) {
if (sender is Player) {
val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class)
if (args.isNotEmpty()) {
val currency = currencyProvider.getCurrency(args[0])
if (currency != null) {
showWallet(sender, currency)
} else {
sender.sendMessage(plugin.messages["money-wallet-currency-invalid-currency"])
}
} else {
val currency = currencyProvider.defaultCurrency
if (currency != null) {
showWallet(sender, currency)
} else {
conversationFactory.buildConversation(sender).begin()
}
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-money-wallet"])
}
return true
}
private fun showWallet(bukkitPlayer: Player, currency: RPKCurrency) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val economyProvider = plugin.core.serviceManager.getServiceProvider(RPKEconomyProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
val wallet = plugin.server.createInventory(null, 27, "Wallet [" + currency.name + "]")
val coin = ItemStack(currency.material)
val meta = coin.itemMeta ?: plugin.server.itemFactory.getItemMeta(coin.type) ?: return
meta.setDisplayName(currency.nameSingular)
coin.itemMeta = meta
val coinStack = ItemStack(currency.material, 64)
val stackMeta = coinStack.itemMeta ?: plugin.server.itemFactory.getItemMeta(coinStack.type) ?: return
stackMeta.setDisplayName(currency.nameSingular)
coinStack.itemMeta = stackMeta
val remainder = (economyProvider.getBalance(character, currency) % 64)
var i = 0
while (i < economyProvider.getBalance(character, currency)) {
val leftover = wallet.addItem(coinStack)
if (!leftover.isEmpty()) {
bukkitPlayer.world.dropItem(bukkitPlayer.location, leftover.values.iterator().next())
}
i += 64
}
if (remainder != 0) {
val remove = ItemStack(coin)
remove.amount = 64 - remainder
wallet.removeItem(remove)
}
bukkitPlayer.openInventory(wallet)
} else {
bukkitPlayer.sendMessage(plugin.messages["no-character"])
}
} else {
bukkitPlayer.sendMessage(plugin.messages["no-minecraft-profile"])
}
}
private inner class CurrencyPrompt: ValidatingPrompt() {
override fun isInputValid(context: ConversationContext, input: String): Boolean {
return plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class).getCurrency(input) != null
}
override fun acceptValidatedInput(context: ConversationContext, input: String): Prompt {
context.setSessionData("currency", plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class).getCurrency(input))
return CurrencySetPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["money-subtract-currency-prompt"] + "\n" +
plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class).currencies
.joinToString("\n") { currency ->
plugin.messages["money-subtract-currency-prompt-list-item", mapOf(
Pair("currency", currency.name)
)]
}
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String {
return plugin.messages["money-subtract-currency-invalid-currency"]
}
}
private inner class CurrencySetPrompt: MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt? {
showWallet(context.forWhom as Player, context.getSessionData("currency") as RPKCurrency)
return END_OF_CONVERSATION
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["money-subtract-currency-valid"]
}
}
} | apache-2.0 | 44e670315bb813195d5e707109c47e5c | 45.727848 | 140 | 0.629098 | 5.349275 | false | false | false | false |
Adven27/Exam | exam-core/src/main/java/io/github/adven27/concordion/extensions/exam/core/handlebars/HandlebarsSupport.kt | 1 | 3435 | package io.github.adven27.concordion.extensions.exam.core.handlebars
import com.github.jknack.handlebars.Context
import com.github.jknack.handlebars.EscapingStrategy.NOOP
import com.github.jknack.handlebars.Formatter
import com.github.jknack.handlebars.Handlebars
import com.github.jknack.handlebars.Helper
import com.github.jknack.handlebars.Options
import io.github.adven27.concordion.extensions.exam.core.handlebars.date.DateHelpers
import io.github.adven27.concordion.extensions.exam.core.handlebars.matchers.MatcherHelpers
import io.github.adven27.concordion.extensions.exam.core.handlebars.misc.MiscHelpers
import org.concordion.api.Evaluator
val HELPER_RESULTS: MutableList<Any?> = mutableListOf()
val HANDLEBARS: Handlebars = Handlebars()
.with { value: Any?, next: Formatter.Chain ->
(if (value is Result<*>) value.getOrThrow() else value).let {
HELPER_RESULTS.add(it)
next.format(it.toString())
}
}
.with(NOOP)
.prettyPrint(false)
.registerHelpers(MiscHelpers::class.java)
.registerHelpers(DateHelpers::class.java)
.registerHelpers(MatcherHelpers::class.java)
.registerHelperMissing(HelperMissing())
class MissingHelperException(options: Options) : IllegalArgumentException(
"Variable or helper '${options.fn.text()}' not found"
)
class HelperMissing : Helper<Any?> {
override fun apply(context: Any?, options: Options) = throw MissingHelperException(options)
companion object {
fun helpersDesc(): Map<Package, Map<String, Helper<*>>> =
HANDLEBARS.helpers().groupBy { it.value.javaClass.`package` }.map { e ->
e.key to e.value
.filterNot { it.key == "helperMissing" }
.sortedBy { it.key }
.associate { it.key to it.value }
}.toMap()
}
}
private fun Handlebars.resolve(eval: Any?, placeholder: String): Any? = compileInline(placeholder).let { template ->
HELPER_RESULTS.clear()
template.apply(Context.newBuilder(eval).resolver(EvaluatorValueResolver.INSTANCE).build()).let {
if (HELPER_RESULTS.size == 1 && placeholder.singleHelper()) HELPER_RESULTS.single() else it
}
}
fun Handlebars.resolveObj(eval: Evaluator, placeholder: String?): Any? = placeholder?.trim()?.let {
resolve(
eval,
if (placeholder.insideApostrophes()) placeholder.substring(1, placeholder.lastIndex) else placeholder
)
}
private fun String.insideApostrophes() = startsWith("'") && endsWith("'")
private fun String.singleHelper() = startsWith("{{") && endsWith("}}")
interface ExamHelper : Helper<Any?> {
val example: String
val context: Map<String, Any?>
val expected: Any?
val options: Map<String, String>
fun describe() =
"$example will produce: ${expectedStr()} ${if (context.isEmpty()) "" else "(given context has variables: $context)"}"
private fun expectedStr() = when (expected) {
is String -> "\"$expected\""
null -> null
else -> "object of ${expected?.javaClass} = \"$expected\""
}
class InvocationFailed(name: String, context: Any?, options: Options, throwable: Throwable) :
RuntimeException(
"Invocation of {{$name}} (context: $context, options: ${options.fn.text()}) failed: ${throwable.message}",
throwable
)
}
fun Options.evaluator(): Evaluator = (this.context.model() as Evaluator)
| mit | af5eced3a9b1928ac48dea941d14d8fd | 38.482759 | 125 | 0.682096 | 4.084423 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/toolbar/main/TabBar.kt | 1 | 5280 | /*
* Copyright (C) 2017-2019 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.legacy.toolbar.main
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import jp.hazuki.yuzubrowser.core.utility.extensions.convertDpToPx
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.manager.ActionController
import jp.hazuki.yuzubrowser.legacy.action.manager.ActionIconManager
import jp.hazuki.yuzubrowser.legacy.action.manager.SoftButtonActionArrayManager
import jp.hazuki.yuzubrowser.legacy.databinding.ToolbarTabBinding
import jp.hazuki.yuzubrowser.legacy.tab.manager.MainTabData
import jp.hazuki.yuzubrowser.legacy.toolbar.ButtonToolbarController
import jp.hazuki.yuzubrowser.legacy.utils.view.tab.FullTabLayout
import jp.hazuki.yuzubrowser.legacy.utils.view.tab.ScrollableTabLayout
import jp.hazuki.yuzubrowser.legacy.utils.view.tab.TabLayout
import jp.hazuki.yuzubrowser.ui.settings.AppPrefs
import jp.hazuki.yuzubrowser.ui.theme.ThemeData
class TabBar(context: Context, controller: ActionController, iconManager: ActionIconManager, request_callback: RequestCallback) : ToolbarBase(context, AppPrefs.toolbar_tab, request_callback) {
private val binding = ToolbarTabBinding.inflate(LayoutInflater.from(context), this, true)
private val tabSizeX = context.convertDpToPx(AppPrefs.tab_size_x.get())
private val tabSizeY = context.convertDpToPx(AppPrefs.toolbar_tab.size.get())
private val tabFontSize = AppPrefs.tab_font_size.get()
private val mTabLayout: TabLayout
private val mLeftButtonController = ButtonToolbarController(binding.leftLinearLayout, controller, iconManager, tabSizeY)
private val mRightButtonController = ButtonToolbarController(binding.rightLinearLayout, controller, iconManager, tabSizeY)
init {
mTabLayout = when (AppPrefs.tab_type.get()) {
TAB_TYPE_SCROLLABLE -> {
ScrollableTabLayout(context).also {
binding.tabLayoutBase.addView(it)
}
}
TAB_TYPE_FULL -> {
FullTabLayout(context).also {
binding.tabLayoutBase.addView(it)
}
}
else -> throw IllegalArgumentException()
}
addButtons()
}
override fun notifyChangeWebState(data: MainTabData?) {
super.notifyChangeWebState(data)
mLeftButtonController.notifyChangeState()
mRightButtonController.notifyChangeState()
}
override fun resetToolBar() {
mLeftButtonController.resetIcon()
mRightButtonController.resetIcon()
}
override fun applyTheme(themeData: ThemeData?) {
super.applyTheme(themeData)
applyTheme(mLeftButtonController)
applyTheme(mRightButtonController)
mTabLayout.applyTheme(themeData)
}
private fun addButtons() {
val manager = SoftButtonActionArrayManager.getInstance(context)
mLeftButtonController.addButtons(manager.btn_tab_left.list)
mRightButtonController.addButtons(manager.btn_tab_right.list)
onThemeChanged(ThemeData.getInstance())// TODO
}
fun addNewTabView(): View {
val view = LayoutInflater.from(context).inflate(R.layout.tab_item, null, true)
view.findViewById<TextView>(R.id.textView).textSize = tabFontSize.toFloat()
val params = LinearLayout.LayoutParams(tabSizeX, tabSizeY)
mTabLayout.addTabView(view, params)
return view
}
override fun onPreferenceReset() {
super.onPreferenceReset()
addButtons()
mTabLayout.onPreferenceReset()
mTabLayout.setSense(AppPrefs.tab_action_sensitivity.get())
}
fun removeTab(no: Int) {
mTabLayout.removeTabAt(no)
}
fun addTab(id: Int, view: View) {
val params = LinearLayout.LayoutParams(tabSizeX, tabSizeY)
mTabLayout.addTabView(id, view, params)
}
fun setOnTabClickListener(l: TabLayout.OnTabClickListener) {
mTabLayout.setOnTabClickListener(l)
}
fun changeCurrentTab(to: Int) {
mTabLayout.setCurrentTab(to)
}
fun fullScrollRight() {
mTabLayout.fullScrollRight()
}
fun fullScrollLeft() {
mTabLayout.fullScrollLeft()
}
fun scrollToPosition(position: Int) {
mTabLayout.scrollToPosition(position)
}
fun swapTab(a: Int, b: Int) {
mTabLayout.swapTab(a, b)
}
fun moveTab(from: Int, to: Int, new_curernt: Int) {
mTabLayout.moveTab(from, to, new_curernt)
}
companion object {
const val TAB_TYPE_SCROLLABLE = 0
const val TAB_TYPE_FULL = 1
}
}
| apache-2.0 | b4499487e329741a74e6491a7291936d | 34.675676 | 192 | 0.711553 | 4.254633 | false | false | false | false |
Magneticraft-Team/ModelLoader | src/main/kotlin/com/cout970/modelloader/gltf/GltfFormatHandler.kt | 1 | 8683 | @file:Suppress("DEPRECATION")
package com.cout970.modelloader.gltf
import com.cout970.modelloader.*
import com.cout970.modelloader.animation.*
import com.cout970.modelloader.api.EmptyRenderCache
import com.cout970.modelloader.api.ModelCache
import com.cout970.modelloader.api.TRSTransformation
import com.cout970.modelloader.api.Utilities
import com.cout970.modelloader.mutable.MutableModel
import com.cout970.modelloader.mutable.MutableModelNode
import net.minecraft.client.renderer.model.BakedQuad
import net.minecraft.client.renderer.model.IUnbakedModel
import net.minecraft.client.renderer.model.ItemCameraTransforms
import net.minecraft.client.renderer.model.ModelRotation
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.client.renderer.vertex.VertexFormat
import net.minecraft.resources.IResourceManager
import net.minecraft.util.ResourceLocation
import net.minecraftforge.client.model.ModelLoader
import java.io.InputStream
import java.util.function.Function
import javax.vecmath.*
object GltfFormatHandler : IFormatHandler {
override fun loadModel(resourceManager: IResourceManager, modelLocation: ResourceLocation): IUnbakedModel {
val fileStream = resourceManager.getResource(modelLocation).inputStream
val file = GltfDefinition.parse(fileStream)
fun retrieveFile(path: String): InputStream {
val basePath = modelLocation.path.substringBeforeLast('/', "")
val loc = ResourceLocation(modelLocation.namespace, if (basePath.isEmpty()) path else "$basePath/$path")
return resourceManager.getResource(loc).inputStream
}
val tree = GltfTree.parse(file, modelLocation, ::retrieveFile)
return UnbakedGltfModel(tree)
}
}
internal class GltfAnimator(
val tree: GltfTree.DefinitionTree,
val getSprite: Function<ResourceLocation, TextureAtlasSprite>? = ModelLoader.defaultTextureGetter()
) {
val nodeMap = mutableMapOf<Int, GltfTree.Node>()
fun animate(animation: GltfTree.Animation) = AnimationBuilder().apply {
val scene = tree.scenes[tree.scene]
scene.nodes.forEach {
createNode(it.index) { newNode(it) }
}
animation.channels.forEach { channel ->
when (channel.path) {
GltfChannelPath.translation -> {
addTranslationChannel(channel.node, channel.times.zip(channel.values).map {
AnimationKeyframe(it.first, it.second as Vector3d)
})
}
GltfChannelPath.rotation -> {
addRotationChannel(channel.node, channel.times.zip(channel.values).map {
AnimationKeyframe(it.first, it.second as Vector4d)
})
}
GltfChannelPath.scale -> {
val base = nodeMap[channel.node]?.transform?.scale ?: Vector3d(1.0, 1.0, 1.0)
addScaleChannel(channel.node, channel.times.zip(channel.values).map {
AnimationKeyframe(it.first, (it.second as Vector3d) / base)
})
}
GltfChannelPath.weights -> error("Unsupported")
}
}
}.debugBuild()
fun AnimationNodeBuilder.newNode(node: GltfTree.Node) {
nodeMap[node.index] = node
withTransform(node.transform)
node.children.forEach {
createChildren(it.index) { newNode(it) }
}
val mesh = node.mesh ?: return
withVertices(mesh.primitives.mapNotNull {
val group = it.toVertexGroup(TRSTransformation.IDENTITY, null) ?: return@mapNotNull null
group.copy(texture = locationToFile(it.material))
})
}
fun locationToFile(res: ResourceLocation): ResourceLocation {
return ResourceLocation(res.namespace, "textures/${res.path}.png")
}
}
internal class GltfBaker(
val format: VertexFormat,
val bakedTextureGetter: Function<ResourceLocation, TextureAtlasSprite>,
val rotation: ModelRotation
) {
fun bake(model: UnbakedGltfModel): BakedGltfModel {
val nodeQuads = mutableListOf<BakedQuad>()
val scene = model.tree.scenes[model.tree.scene]
val offset = Vector3d(0.5, 0.5, 0.5)
val trs = TRSTransformation(-offset) + rotation.matrixVec.toTRS() + TRSTransformation(offset)
scene.nodes.forEach { node ->
recursiveBakeNodes(node, trs, nodeQuads)
}
val particleLocation = model.tree.textures.firstOrNull() ?: ModelLoaderMod.defaultParticleTexture
val particle = bakedTextureGetter.apply(particleLocation)
return BakedGltfModel(nodeQuads, particle, ItemCameraTransforms.DEFAULT)
}
fun bakeMutableModel(model: UnbakedGltfModel): MutableModel {
val scene = model.tree.scenes[model.tree.scene]
val offset = Vector3d(0.5, 0.5, 0.5)
val trs = TRSTransformation(-offset) + rotation.matrixVec.toTRS() + TRSTransformation(offset)
val children = mutableMapOf<String, MutableModelNode>()
scene.nodes.forEachIndexed { index, node ->
val name = node.name ?: index.toString()
children[name] = recursiveBakeMutableNodes(node)
}
return MutableModel(MutableModelNode(EmptyRenderCache, children, transform = trs.toMutable(), useTransform = true))
}
fun recursiveBakeMutableNodes(node: GltfTree.Node): MutableModelNode {
val children = mutableMapOf<String, MutableModelNode>()
val content = node.mesh?.let { mesh ->
val baked = bakeMesh(mesh, TRSTransformation())
ModelCache { Utilities.renderQuadsSlow(baked) }
} ?: EmptyRenderCache
node.children.forEachIndexed { index, child ->
val name = child.name ?: index.toString()
children[name] = recursiveBakeMutableNodes(child)
}
return MutableModelNode(
content = content,
children = children,
transform = node.transform.toMutable(),
useTransform = true
)
}
fun recursiveBakeNodes(node: GltfTree.Node, transform: TRSTransformation, list: MutableList<BakedQuad>) {
val globalTransform = node.transform + transform
node.children.forEach {
recursiveBakeNodes(it, globalTransform, list)
}
val mesh = node.mesh ?: return
list += bakeMesh(mesh, globalTransform)
}
@Suppress("UNCHECKED_CAST")
fun bakeMesh(mesh: GltfTree.Mesh, globalTransform: TRSTransformation): List<BakedQuad> {
val quads = mutableListOf<BakedQuad>()
mesh.primitives.forEach { prim ->
val sprite = bakedTextureGetter.apply(prim.material)
val group = prim.toVertexGroup(globalTransform, null) ?: return@forEach
quads += VertexUtilities.bakedVertices(format, sprite, group.vertex)
}
return quads
}
}
private fun GltfTree.Primitive.toVertexGroup(globalTransform: TRSTransformation, sprite: TextureAtlasSprite?): VertexGroup? {
if (mode != GltfMode.TRIANGLES && mode != GltfMode.QUADS) {
ModelLoaderMod.logger.warn("Found primitive with unsupported mode: ${mode}, ignoring")
return null
}
val posBuffer = attributes[GltfAttribute.POSITION]
val texBuffer = attributes[GltfAttribute.TEXCOORD_0]
if (posBuffer == null) {
ModelLoaderMod.logger.warn("Found primitive without vertex, ignoring")
return null
}
if (posBuffer.type != GltfType.VEC3) {
ModelLoaderMod.logger.warn("Found primitive with in valid vertex pos type: ${posBuffer.type}, ignoring")
return null
}
if (texBuffer != null && texBuffer.type != GltfType.VEC2) {
ModelLoaderMod.logger.warn("Found primitive with in valid vertex uv type: ${texBuffer.type}, ignoring")
return null
}
@Suppress("UNCHECKED_CAST")
val indexList = indices?.data as? List<Int>
@Suppress("UNCHECKED_CAST")
val pos = posBuffer.data as List<Vector3d>
@Suppress("UNCHECKED_CAST")
val tex = texBuffer?.data as? List<Vector2d> ?: emptyList()
val matrix = globalTransform.matrixVec.apply { transpose() }
val newPos = pos.map { vec ->
Point3f(vec.x.toFloat(), vec.y.toFloat(), vec.z.toFloat())
.also { matrix.transform(it) }
.run { Vector3d(x.toDouble(), y.toDouble(), z.toDouble()) }
}
val vertex = mutableListOf<Vertex>()
VertexUtilities.collect(
CompactModelData(indexList, newPos, tex, newPos.size, mode != GltfMode.QUADS), sprite, vertex
)
return VertexGroup(material, vertex)
} | gpl-2.0 | 7e54c1be524f0401f2215f18de92da73 | 36.270386 | 125 | 0.66659 | 4.387569 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/ui/NewPasswordInputDialog.kt | 1 | 11364 | package io.oversec.one.crypto.ui
import android.content.*
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.IBinder
import android.os.RemoteException
import android.support.design.widget.TextInputLayout
import android.support.v4.content.ContextCompat
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.*
import com.afollestad.materialdialogs.MaterialDialog
import io.oversec.one.crypto.IZxcvbnService
import io.oversec.one.crypto.R
import io.oversec.one.crypto.ui.util.EditTextPasswordWithVisibilityToggle
import uk.co.biddell.diceware.dictionaries.DiceWare
import java.io.IOException
object NewPasswordInputDialog {
private const val ENTROPY_MEDIUM = 45
private const val ENTROPY_HIGH_SHARE = 75
private const val ENTROPY_HIGH_PBKDF = 75
private const val ENTROPY_HIGH_DEVICE = 60
private const val DICEWARE_WORDS_KEYSTORE = 4
private const val DICEWARE_WORDS_SHARE = 5
private const val DICEWARE_WORDS_PBKDF = 6
enum class MODE {
SHARE, KEYSTORE, PBKDF
}
fun show(ctx: Context, mode: MODE, callback: NewPasswordInputDialogCallback) {
val serviceIntent = Intent()
.setComponent(
ComponentName(
ctx,
"io.oversec.one.crypto.ZxcvbnService"
)
) //do NOT reference by CLASS
ctx.startService(serviceIntent)
val mZxcvbnService = arrayOfNulls<IZxcvbnService>(1)
val mConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
mZxcvbnService[0] = IZxcvbnService.Stub.asInterface(service)
}
override fun onServiceDisconnected(name: ComponentName) {
mZxcvbnService[0] = null
}
}
ctx.bindService(serviceIntent, mConnection, Context.BIND_ALLOW_OOM_MANAGEMENT)
val dialog = MaterialDialog.Builder(ctx)
.customView(R.layout.new_password_input_dialog, false)
.positiveText(getPositiveText(mode))
.neutralText(R.string.common_cancel)
.autoDismiss(false)
.dismissListener {
try {
mZxcvbnService[0]?.exit()
} catch (e: RemoteException) {
e.printStackTrace()
}
ctx.unbindService(mConnection)
}
.cancelListener { dialog ->
callback.neutralAction()
//TODO: clear passwords on cancel?
dialog.dismiss()
}
.onPositive { dialog, which ->
val view = dialog.customView
if (handlePositive(view!!, callback, mode, mZxcvbnService[0])) {
dialog.dismiss()
}
}
.onNeutral { dialog, which ->
val view = dialog.customView
val etPw1 = view!!.findViewById<View>(R.id.new_password_password) as EditText
val etPw2 = view.findViewById<View>(R.id.new_password_password_again) as EditText
etPw1.setText("") //TODO better way?
etPw2.setText("") //TODO better way?
callback.neutralAction()
dialog.dismiss()
}.build()
dialog.window!!.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
)
dialog.window!!.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
val view = dialog.customView
val etPw1 =
view!!.findViewById<View>(R.id.new_password_password) as EditTextPasswordWithVisibilityToggle
val etPw2 =
view.findViewById<View>(R.id.new_password_password_again) as EditTextPasswordWithVisibilityToggle
etPw2.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
if (handlePositive(view, callback, mode, mZxcvbnService[0])) {
dialog.dismiss()
return@OnEditorActionListener true
}
}
false
})
val wrapPw1 = view.findViewById<View>(R.id.new_password_password_wrapper) as TextInputLayout
val tvText = view.findViewById<View>(R.id.new_password_text) as TextView
tvText.setText(getBody(mode))
val tvTitle = view.findViewById<View>(R.id.new_password_title) as TextView
tvTitle.setText(getTitle(mode))
val cbWeak = view.findViewById<View>(R.id.cb_accept_weak_password) as CheckBox
cbWeak.visibility = View.GONE
val btSuggest = view.findViewById<View>(R.id.new_password_generate) as Button
btSuggest.setOnClickListener {
// cbShowPassphrase.setChecked(true);
try {
val dw = DiceWare(ctx).getDiceWords(
getDicewareExtraSecurity(mode)!!,
getDicewareNumWords(mode)
)
etPw1.setText(dw.toString())
etPw1.setPasswordVisible(true)
etPw2.setPasswordVisible(true)
} catch (e: IOException) {
e.printStackTrace()
}
}
val sbStrength = view.findViewById<View>(R.id.create_key_seekbar) as SeekBar
etPw1.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
val entropy = calcPasswordEntropy(s, wrapPw1, mZxcvbnService[0])
updateSeekBar(view, sbStrength, entropy, mode)
}
override fun afterTextChanged(s: Editable) {
}
})
updateSeekBar(view, sbStrength, 0, mode)
dialog.show()
}
private fun getBody(mode: MODE): Int {
return when (mode) {
NewPasswordInputDialog.MODE.KEYSTORE -> R.string.new_password_keystore_text
NewPasswordInputDialog.MODE.PBKDF -> R.string.new_password_pbkdf_text
NewPasswordInputDialog.MODE.SHARE -> R.string.new_password_share_text
}
}
private fun getTitle(mode: MODE): Int {
return when (mode) {
NewPasswordInputDialog.MODE.KEYSTORE -> R.string.new_password_keystore_title
NewPasswordInputDialog.MODE.PBKDF -> R.string.new_password_pbkdf_title
NewPasswordInputDialog.MODE.SHARE -> R.string.new_password_share_title
}
}
private fun getDicewareExtraSecurity(mode: MODE): DiceWare.Type? {
return when (mode) {
NewPasswordInputDialog.MODE.KEYSTORE -> DiceWare.Type.PASSPHRASE
NewPasswordInputDialog.MODE.PBKDF -> DiceWare.Type.PASSPHRASE_EXTRA_SECURITY
NewPasswordInputDialog.MODE.SHARE -> DiceWare.Type.PASSPHRASE_EXTRA_SECURITY
}
}
private fun getDicewareNumWords(mode: MODE): Int {
return when (mode) {
NewPasswordInputDialog.MODE.KEYSTORE -> DICEWARE_WORDS_KEYSTORE
NewPasswordInputDialog.MODE.PBKDF -> DICEWARE_WORDS_PBKDF
NewPasswordInputDialog.MODE.SHARE -> DICEWARE_WORDS_SHARE
}
}
private fun getPositiveText(mode: MODE): Int {
return when (mode) {
NewPasswordInputDialog.MODE.KEYSTORE -> R.string.action_save
NewPasswordInputDialog.MODE.PBKDF -> R.string.action_generate
NewPasswordInputDialog.MODE.SHARE -> R.string.action_share
}
}
private fun getEntropyHighLevel(mode: MODE): Int {
return when (mode) {
NewPasswordInputDialog.MODE.KEYSTORE -> ENTROPY_HIGH_DEVICE
NewPasswordInputDialog.MODE.PBKDF -> ENTROPY_HIGH_PBKDF
NewPasswordInputDialog.MODE.SHARE -> ENTROPY_HIGH_SHARE
}
}
private fun getEntropyMinimum(mode: MODE): Int {
return when (mode) {
NewPasswordInputDialog.MODE.KEYSTORE -> ENTROPY_MEDIUM //facilitate usage fur "dumb" users
NewPasswordInputDialog.MODE.PBKDF -> ENTROPY_MEDIUM //facilitate usage fur "dumb" users
NewPasswordInputDialog.MODE.SHARE -> ENTROPY_HIGH_SHARE
}
}
private fun updateSeekBar(view: View?, sbStrength: SeekBar, entropy: Int, mode: MODE) {
sbStrength.max = 100
sbStrength.progress = Math.max(10, entropy)
var color = R.color.password_strength_low
if (entropy >= ENTROPY_MEDIUM) {
color = R.color.password_strength_medium
}
if (entropy >= getEntropyHighLevel(mode)) {
color = R.color.password_strength_high
val cbWeak = view!!.findViewById<View>(R.id.cb_accept_weak_password) as CheckBox
cbWeak.visibility = View.GONE
}
sbStrength.progressDrawable.colorFilter = PorterDuffColorFilter(
ContextCompat.getColor(sbStrength.context, color),
PorterDuff.Mode.MULTIPLY
)
}
private fun calcPasswordEntropy(
s: CharSequence,
wrapper: TextInputLayout,
zxcvbn: IZxcvbnService?
): Int {
zxcvbn?: return 0 //service not bound?
return try {
val r = zxcvbn.calcEntropy(s.toString())
wrapper.error = r.warning
r.entropy
} catch (ex: RemoteException) {
ex.printStackTrace()
0
}
}
private fun handlePositive(
view: View,
callback: NewPasswordInputDialogCallback,
mode: MODE,
zxcvbn: IZxcvbnService?
): Boolean {
val etPw1 = view.findViewById<View>(R.id.new_password_password) as EditText
val etPw2 = view.findViewById<View>(R.id.new_password_password_again) as EditText
val wrapPw1 = view.findViewById<View>(R.id.new_password_password_wrapper) as TextInputLayout
val wrapPw2 =
view.findViewById<View>(R.id.new_password_password_again_wrapper) as TextInputLayout
val cbWeak = view.findViewById<View>(R.id.cb_accept_weak_password) as CheckBox
val editablePw1 = etPw1.text
val editablePw2 = etPw2.text
if (editablePw1.toString() != editablePw2.toString()) {
wrapPw1.error = view.context.getString(R.string.error_passwords_dont_match)
return false
}
val entropy = calcPasswordEntropy(etPw1.text, wrapPw1, zxcvbn)
if (entropy < getEntropyMinimum(mode) && !cbWeak.isChecked) {
wrapPw1.error = view.context.getString(R.string.error_password_length)
cbWeak.visibility = View.VISIBLE
cbWeak.requestFocus()
cbWeak.parent.requestChildFocus(cbWeak, cbWeak)
return false
}
val pl = editablePw1.length
val aPassPhrase = CharArray(pl)
editablePw1.getChars(0, pl, aPassPhrase, 0)
etPw1.setText("") //TODO better way?
etPw2.setText("") //TODO better way?
callback.positiveAction(aPassPhrase)
return true
}
}
| gpl-3.0 | fc2ecfa025c6efdfa4190c0afb69f78a | 35.306709 | 109 | 0.622756 | 4.340718 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/api/ucp/UcpHistoryEndpoint.kt | 2 | 733 | package me.proxer.library.api.ucp
import me.proxer.library.ProxerCall
import me.proxer.library.api.PagingLimitEndpoint
import me.proxer.library.entity.ucp.UcpHistoryEntry
/**
* Endpoint for requesting the history of the current user.
*
* @author Ruben Gees
*/
class UcpHistoryEndpoint internal constructor(
private val internalApi: InternalApi
) : PagingLimitEndpoint<List<UcpHistoryEntry>> {
private var page: Int? = null
private var limit: Int? = null
override fun page(page: Int?) = this.apply { this.page = page }
override fun limit(limit: Int?) = this.apply { this.limit = limit }
override fun build(): ProxerCall<List<UcpHistoryEntry>> {
return internalApi.history(page, limit)
}
}
| gpl-3.0 | ecc65ed3e072a322f57ce0bd87879daf | 28.32 | 71 | 0.725784 | 4.005464 | false | false | false | false |
viniciussoares/esl-pod-client | app/src/main/java/br/com/wakim/eslpodclient/data/interactor/DownloadedPodcastItemInteractor.kt | 2 | 1588 | package br.com.wakim.eslpodclient.data.interactor
import br.com.wakim.eslpodclient.Application
import br.com.wakim.eslpodclient.data.model.PodcastItem
import br.com.wakim.eslpodclient.data.model.PodcastList
import br.com.wakim.eslpodclient.util.extensions.onSuccessIfSubscribed
import rx.Single
import java.util.*
class DownloadedPodcastItemInteractor(private val podcastDbInteractor: PodcastDbInteractor, app: Application): PodcastInteractor(podcastDbInteractor, app) {
companion object {
const val ITEMS_PER_PAGE = 20
}
fun getDownloaded(page: Int, limit: Int): Single<List<PodcastItem>> =
Single.create<List<PodcastItem>> { subscriber ->
subscriber.onSuccessIfSubscribed(podcastDbInteractor.getDownloaded(page, limit))
}
override fun getCachedPodcasts(nextPageToken: String?): Single<PodcastList> = getPodcasts(nextPageToken)
override fun getPodcasts(nextPageToken: String?): Single<PodcastList> =
getDownloaded(nextPageToken?.toInt() ?: 0, ITEMS_PER_PAGE)
.map { list ->
val currentPageToken = nextPageToken?.toInt()
val podcastList = PodcastList(currentPageToken.toString(), ((currentPageToken ?: 0) + 1).toString())
podcastList.list = list as? ArrayList<PodcastItem> ?: ArrayList(list)
if (podcastList.list.size < ITEMS_PER_PAGE) {
podcastList.nextPageToken = null
}
podcastList
}
} | apache-2.0 | dd10f01d369eb4b5752c633e1f474386 | 43.138889 | 156 | 0.654282 | 5.009464 | false | false | false | false |
gradle/gradle | .teamcity/src/main/kotlin/promotion/PublishNightlySnapshotFromQuickFeedbackStepUpload.kt | 2 | 1764 | /*
* Copyright 2019 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 promotion
import common.VersionedSettingsBranch
import vcsroots.gradlePromotionBranches
class PublishNightlySnapshotFromQuickFeedbackStepUpload(branch: VersionedSettingsBranch) : BasePublishGradleDistribution(
promotedBranch = branch.branchName,
prepTask = branch.prepNightlyTaskName(),
triggerName = "QuickFeedback",
vcsRootId = gradlePromotionBranches
) {
init {
id("Promotion_SnapshotFromQuickFeedbackStepUpload")
name = "Nightly Snapshot (from QuickFeedback) - Upload"
description = "Builds and uploads the latest successful changes on '${branch.branchName}' from Quick Feedback as a new distribution"
steps {
buildStep(
this@PublishNightlySnapshotFromQuickFeedbackStepUpload.extraParameters,
this@PublishNightlySnapshotFromQuickFeedbackStepUpload.gitUserName,
this@PublishNightlySnapshotFromQuickFeedbackStepUpload.gitUserEmail,
this@PublishNightlySnapshotFromQuickFeedbackStepUpload.triggerName,
branch.prepNightlyTaskName(),
"uploadAll"
)
}
}
}
| apache-2.0 | da80c5a44ae5eddd4276fb92cda8eca7 | 39.090909 | 140 | 0.72619 | 5.011364 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-permissions-lib-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/vault/RPKPermissionsVaultPermissions.kt | 1 | 7550 | /*
* Copyright 2022 Ren Binden
*
* 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.rpkit.permissions.bukkit.vault
import com.rpkit.core.service.Services
import com.rpkit.permissions.bukkit.RPKPermissionsLibBukkit
import com.rpkit.permissions.bukkit.group.*
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftUsername
import net.milkbowl.vault.permission.Permission
class RPKPermissionsVaultPermissions(plugin: RPKPermissionsLibBukkit) : Permission() {
init {
this.plugin = plugin
}
override fun getName(): String {
return "rpk-permissions"
}
override fun isEnabled(): Boolean {
return true
}
override fun hasSuperPermsCompat(): Boolean {
return true
}
@Deprecated("Deprecated in Java")
override fun playerHas(worldName: String, playerName: String, permission: String): Boolean {
if (plugin.server.isPrimaryThread) {
plugin.logger.warning("Vault is being used from the main thread! This may cause lag! (playerHas)")
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return false
val minecraftProfile = minecraftProfileService.getMinecraftProfile(RPKMinecraftUsername(playerName)).join() ?: return false
val profile = minecraftProfile.profile as? RPKProfile ?: return false
return profile.hasPermission(permission).join()
}
@Deprecated("Deprecated in Java")
override fun playerAdd(worldName: String, playerName: String, permission: String): Boolean {
return false
}
@Deprecated("Deprecated in Java")
override fun playerRemove(worldName: String, playerName: String, permission: String): Boolean {
return false
}
override fun groupHas(worldName: String, groupName: String, permission: String): Boolean {
if (plugin.server.isPrimaryThread) {
plugin.logger.warning("Vault is being used from the main thread! This may cause lag! (groupHas)")
}
val groupService = Services[RPKGroupService::class.java] ?: return false
val group = groupService.getGroup(RPKGroupName(groupName)) ?: return false
return group.hasPermission(permission)
}
override fun groupAdd(worldName: String, groupName: String, permission: String): Boolean {
return false
}
override fun groupRemove(worldName: String, groupName: String, permission: String): Boolean {
return false
}
@Deprecated("Deprecated in Java")
override fun playerInGroup(worldName: String, playerName: String, groupName: String): Boolean {
if (plugin.server.isPrimaryThread) {
plugin.logger.warning("Vault is being used from the main thread! This may cause lag! (playerInGroup)")
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return false
val groupService = Services[RPKGroupService::class.java] ?: return false
val minecraftProfile = minecraftProfileService.getMinecraftProfile(RPKMinecraftUsername(playerName)).join() ?: return false
val profile = minecraftProfile.profile as? RPKProfile ?: return false
val group = groupService.getGroup(RPKGroupName(groupName)) ?: return false
return profile.groups.join().map(RPKGroup::name).contains(group.name)
}
@Deprecated("Deprecated in Java")
override fun playerAddGroup(worldName: String, playerName: String, groupName: String): Boolean {
if (plugin.server.isPrimaryThread) {
plugin.logger.warning("Vault is being used from the main thread! This may cause lag! (playerAddGroup)")
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return false
val groupService = Services[RPKGroupService::class.java] ?: return false
val minecraftProfile = minecraftProfileService.getMinecraftProfile(RPKMinecraftUsername(playerName)).join() ?: return false
val profile = minecraftProfile.profile as? RPKProfile ?: return false
val group = groupService.getGroup(RPKGroupName(groupName)) ?: return false
profile.addGroup(group)
return true
}
@Deprecated("Deprecated in Java")
override fun playerRemoveGroup(worldName: String, playerName: String, groupName: String): Boolean {
if (plugin.server.isPrimaryThread) {
plugin.logger.warning("Vault is being used from the main thread! This may cause lag! (playerRemoveGroup)")
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return false
val groupService = Services[RPKGroupService::class.java] ?: return false
val minecraftProfile = minecraftProfileService.getMinecraftProfile(RPKMinecraftUsername(playerName)).join() ?: return false
val profile = minecraftProfile.profile as? RPKProfile ?: return false
val group = groupService.getGroup(RPKGroupName(groupName)) ?: return false
profile.removeGroup(group)
return true
}
@Deprecated("Deprecated in Java")
override fun getPlayerGroups(worldName: String, playerName: String): Array<String> {
if (plugin.server.isPrimaryThread) {
plugin.logger.warning("Vault is being used from the main thread! This may cause lag! (getPlayerGroups)")
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return emptyArray()
val minecraftProfile = minecraftProfileService.getMinecraftProfile(RPKMinecraftUsername(playerName)).join() ?: return emptyArray()
val profile = minecraftProfile.profile as? RPKProfile ?: return emptyArray()
return profile.groups.join().map { group -> group.name.value }.toTypedArray()
}
@Deprecated("Deprecated in Java")
override fun getPrimaryGroup(worldName: String, playerName: String): String? {
if (plugin.server.isPrimaryThread) {
plugin.logger.warning("Vault is being used from the main thread! This may cause lag! (getPrimaryGroup)")
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return null
val minecraftProfile = minecraftProfileService.getMinecraftProfile(RPKMinecraftUsername(playerName)).join() ?: return null
val profile = minecraftProfile.profile as? RPKProfile ?: return null
return profile.groups.join()[0].name.value
}
override fun getGroups(): Array<String> {
if (plugin.server.isPrimaryThread) {
plugin.logger.warning("Vault is being used from the main thread! This may cause lag! (getGroups)")
}
val groupService = Services[RPKGroupService::class.java] ?: return emptyArray()
return groupService.groups.map { group -> group.name.value }.toTypedArray()
}
override fun hasGroupSupport(): Boolean {
return true
}
} | apache-2.0 | 41ddda130cfbd125a2b12fb8ab85a689 | 46.791139 | 138 | 0.712848 | 4.957321 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/ui/widget/SearchFragment.kt | 1 | 9862 | package tech.summerly.quiet.ui.widget
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v7.app.AppCompatDialogFragment
import android.support.v7.util.DiffUtil
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.view.inputmethod.InputMethodManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_search.view.*
import kotlinx.android.synthetic.main.item_search_suggest.view.*
import me.drakeet.multitype.MultiTypeAdapter
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.support.v4.ctx
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.uiThread
import tech.summerly.quiet.R
import tech.summerly.quiet.module.common.bean.MusicType
import tech.summerly.quiet.data.search.SearchHistoryApi
import tech.summerly.quiet.extensions.lib.KItemViewBinder
import tech.summerly.quiet.extensions.log
import tech.summerly.quiet.extensions.multiTypeAdapter
import tech.summerly.quiet.extensions.subscribeK
import tech.summerly.quiet.ui.activity.SearchResultActivity
import tech.summerly.quiet.ui.animation.CircularRevealAnim
/**
* Created by Summerly on 2017/10/4.
* Desc:
*/
class SearchFragment : AppCompatDialogFragment(), TextWatcher, CircularRevealAnim.AnimListener, ViewTreeObserver.OnPreDrawListener, DialogInterface.OnKeyListener {
companion object {
fun newInstance(): SearchFragment {
return SearchFragment()
}
}
private lateinit var circularRevealAnimation: CircularRevealAnim
private val data: ArrayList<Suggest> = ArrayList(20)//预计最多有20条推荐及最近搜索
private val histories = ArrayList<Suggest>()
private val suggests = ArrayList<Suggest>()
override fun onActivityCreated(savedInstanceState: Bundle?) {
//让它全屏
dialog.window.requestFeature(Window.FEATURE_NO_TITLE)
super.onActivityCreated(savedInstanceState)
dialog.window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
// dialog.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
dialog.window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
dialog.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
dialog.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
dialog.window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_search, container, false)
circularRevealAnimation = CircularRevealAnim()
circularRevealAnimation.setAnimListener(this)
view.viewTreeObserver.addOnPreDrawListener(this)
view.buttonBack.setOnClickListener {
dismiss()
}
view.buttonSearch.setOnClickListener {
search()
}
view.outSide.setOnClickListener {
dismiss()
}
view.editSearch.addTextChangedListener(this)
view.listSuggest.adapter = MultiTypeAdapter(data).also {
it.register(Suggest::class.java, SuggestViewBinder())
}
dialog.setOnKeyListener(this)
return view
}
override fun onStart() {
super.onStart()
dialog.window.setWindowAnimations(0)
showHistory()
}
/**
* 显示最新的十条历史纪录
*/
private fun showHistory() {
doAsync {
histories.clear()
histories.addAll(SearchHistoryApi.latestTenSearchHistory()
.map {
Suggest(Suggest.TYPE_HISTORY, it)
})
uiThread {
//显示搜索记录...
suggests.clear()
displaySuggest()
}
}
}
private fun displaySuggest() {
val list = view?.listSuggest ?: return
DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val old = data[oldItemPosition]
val new = if (newItemPosition >= 0 && newItemPosition < histories.size) {
histories[newItemPosition]
} else {
suggests[newItemPosition - histories.size]
}
return new.text == old.text && new.type == old.type
}
override fun getOldListSize(): Int {
return data.size
}
override fun getNewListSize(): Int {
return histories.size + suggests.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val old = data[oldItemPosition]
val new = if (newItemPosition >= 0 && newItemPosition < histories.size) {
histories[newItemPosition]//历史纪录显示在最上面
} else {
suggests[newItemPosition - histories.size]
}
return old.text == new.text
}
}, true).dispatchUpdatesTo(list.multiTypeAdapter)
data.clear()
data.addAll(histories)//历史纪录显示在最上面
data.addAll(suggests)
}
override fun onHideAnimationEnd() {
super.dismiss()//当隐藏动画结束时,dismiss dialog
}
override fun onShowAnimationEnd() {
if (isVisible) {
val editSearch = view?.editSearch ?: return
ctx.getSystemService(InputMethodManager::class.java).showSoftInput(editSearch, InputMethodManager.SHOW_IMPLICIT)
}
}
override fun onPreDraw(): Boolean {
view?.let {
it.viewTreeObserver.removeOnPreDrawListener(this)
circularRevealAnimation.show(it.buttonSearch, view)
}
return false
}
override fun dismiss() {
//回退动画
view?.buttonSearch?.let {
circularRevealAnimation.hide(it, view)
ctx.getSystemService(InputMethodManager::class.java)
.hideSoftInputFromWindow(view?.editSearch?.windowToken, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
//super.dismiss()将在onHideAnimationEnd中被调用
}
override fun onKey(dialog: DialogInterface, keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
dismiss()
return true
} else if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
search()
}
return false
}
private fun search() {
val editSearch = view?.editSearch ?: return
val text = editSearch.text.trim().toString()
if (text.isEmpty()) {
editSearch.error = "can not be empty!"
return
}
SearchHistoryApi.add(text)
with(SearchResultActivity) {
startActivity<SearchResultActivity>(ARG_KEYWORD to text, ARG_SOURCE to MusicType.NETEASE.name)
}
dismiss()
}
override fun afterTextChanged(s: Editable) {
val text = s.toString().trim()
if (text.isEmpty()) {
showHistory()//当编辑框为空时,只显示历史纪录
return
}
log(text)
//根据文字获取匹配的历史搜索
Observable
.create<List<Suggest>> {
SearchHistoryApi.suggestHistory(text)
.map {
Suggest(Suggest.TYPE_HISTORY, it)
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeK {
onNext {
histories.addAll(it)
displaySuggest()
}
}
//获取推荐的搜索 TODO
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//don't care
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//don't care
view?.editSearch?.error = null
}
private inner class SuggestViewBinder : KItemViewBinder<Suggest>() {
override fun onBindViewHolder(holder: KViewHolder, item: Suggest) {
if (item.type == Suggest.TYPE_SUGGEST) {
holder.itemView.suggestIndicator.setImageResource(R.drawable.ic_search_black_24dp)
} else if (item.type == Suggest.TYPE_HISTORY) {
holder.itemView.suggestIndicator.setImageResource(R.drawable.ic_history_black_24dp)
}
holder.itemView.textSuggest.text = item.text
holder.itemView.setOnClickListener {
//开始搜索
view?.editSearch?.setText(item.text)
search()
}
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): KViewHolder {
return KViewHolder(inflater.inflate(R.layout.item_search_suggest, parent, false))
}
}
private class Suggest(val type: Int = TYPE_SUGGEST, val text: String) {
companion object {
val TYPE_SUGGEST = 1
val TYPE_HISTORY = 2
}
override fun toString(): String {
return "Suggest(type=$type, text='$text')"
}
}
} | gpl-2.0 | 408d0cde1994ff317cce0801c8db9eb5 | 34.714815 | 163 | 0.627152 | 4.801793 | false | false | false | false |
Catherine22/WebServices | WebServices/app/src/main/java/com/catherine/webservices/kotlin_sample/KotlinEntrance.kt | 1 | 808 | package com.catherine.webservices.kotlin_sample
import com.catherine.webservices.toolkits.CLog
import java.util.*
/**
* Created by Catherine on 2017/7/31.
*/
object KotlinEntrance {
val TAG = "KotlinEntrance"
fun printHello() {
CLog.v(TAG, "你好啊!")
}
fun printGenerics() {
var composite = ArrayList<Any>()
composite.add("我是String")
composite.add(false)
composite.add(12)
composite.map(::println)
}
}
class KotlinDynamicEntrance {
fun printParameters(a: Int, b: String) {
CLog.v(KotlinEntrance.TAG, "a:$a, b:$b")
}
@JvmOverloads
fun printOptionalParameters(a: Int = 0, b: String = "default", c: Int = 0, d: String = "default") {
CLog.v(KotlinEntrance.TAG, "a:$a, b:$b, c:$c, d:$d")
}
} | apache-2.0 | 43d7033b26715b1048d89d545e0e733d | 21.771429 | 103 | 0.609296 | 3.209677 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/toggle/services/QSPrivateDNSTileService.kt | 1 | 2642 | package com.itachi1706.cheesecakeutilities.modules.toggle.services
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import androidx.annotation.RequiresApi
import com.itachi1706.cheesecakeutilities.R
import com.itachi1706.cheesecakeutilities.modules.toggle.ToggleHelper
import com.itachi1706.cheesecakeutilities.modules.toggle.ToggleHelper.PRIVATE_DNS_SETTING
import com.itachi1706.helperlib.helpers.LogHelper
import com.itachi1706.helperlib.helpers.PrefHelper
@RequiresApi(Build.VERSION_CODES.N)
class QSPrivateDNSTileService : TileService() {
private lateinit var appContext: Context
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
appContext = baseContext
return super.onStartCommand(intent, flags, startId)
}
override fun onStartListening() {
super.onStartListening()
if (!ToggleHelper.checkWriteSecurePermission(this)) { noGo(); return }
updateTileState(if (checkSettingEnabled()) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE)
}
override fun onClick() {
super.onClick()
if (!ToggleHelper.checkWriteSecurePermission(this)) { noGo(); return }
if (isLocked) { LogHelper.w(TAG, "Not executing. Secure Lockscreen"); return }
if (checkSettingEnabled()) {
// Turn off
Settings.Global.putString(contentResolver, PRIVATE_DNS_SETTING, "off")
LogHelper.i(TAG, "Disabled Private DNS")
updateTileState(Tile.STATE_INACTIVE)
} else {
// Turn on
Settings.Global.putString(contentResolver, PRIVATE_DNS_SETTING, getActivateString())
LogHelper.i(TAG, "Enabled Private DNS")
updateTileState(Tile.STATE_ACTIVE)
}
}
private fun checkSettingEnabled(): Boolean { return Settings.Global.getString(contentResolver, PRIVATE_DNS_SETTING) == getActivateString() }
private fun getActivateString(): String {
val sp = PrefHelper.getDefaultSharedPreferences(this)
val pos = sp.getInt(PRIVATE_DNS_SETTING, 0)
return resources.getStringArray(R.array.private_dns_entries_option)[pos]
}
private fun updateTileState(newState: Int) { qsTile.apply { state = newState; updateTile() } }
private fun noGo() {
updateTileState(Tile.STATE_UNAVAILABLE)
LogHelper.w(TAG, "Unavailable. WRITE_SECURE_SETTINGS permission has not been granted")
}
companion object { private const val TAG = "QSPrivDNSTile" }
}
| mit | 73cd53ad21dc6fc2e2f715306de38102 | 39.030303 | 144 | 0.719531 | 4.462838 | false | false | false | false |
CPRTeam/CCIP-Android | app/src/main/java/app/opass/ccip/ui/fastpass/MyTicketFragment.kt | 1 | 3168 | package app.opass.ccip.ui.fastpass
import android.content.Intent
import android.content.res.Resources
import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import app.opass.ccip.R
import app.opass.ccip.ui.auth.AuthActivity
import app.opass.ccip.util.PreferenceUtil
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import kotlinx.android.synthetic.main.fragment_my_ticket.*
import kotlinx.android.synthetic.main.include_login.*
class MyTicketFragment : Fragment() {
companion object {
private const val WHITE = -0x1
private const val BLACK = -0x1000000
fun encodeAsBitmap(
contents: String?,
format: BarcodeFormat,
desiredWidth: Int,
desiredHeight: Int
): Bitmap {
val writer = MultiFormatWriter()
var result: BitMatrix? = null
try {
result = writer.encode(contents, format, desiredWidth, desiredHeight, null)
} catch (e: WriterException) {
e.printStackTrace()
}
val width = result!!.width
val height = result.height
val pixels = IntArray(width * height)
for (y in 0 until height) {
val offset = y * width
for (x in 0 until width) {
pixels[offset + x] = if (result.get(x, y)) BLACK else WHITE
}
}
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
return bitmap
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_my_ticket, container, false)
}
private fun updateView() {
val activity = requireActivity()
if (PreferenceUtil.getToken(activity) != null) {
val widthPixels = Resources.getSystem().displayMetrics.widthPixels / 4
val bm = encodeAsBitmap(PreferenceUtil.getToken(activity), BarcodeFormat.QR_CODE, widthPixels, widthPixels)
qrcodeImage.setImageBitmap(bm)
qrcodeImage.isGone = false
ticket_notice.isGone = false
login_view.isGone = true
} else {
qrcodeImage.isGone = true
ticket_notice.isGone = true
login_view.isGone = false
login_button.setOnClickListener {
activity.startActivity(Intent(activity, AuthActivity::class.java))
}
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
updateView()
}
override fun onResume() {
super.onResume()
updateView()
}
}
| gpl-3.0 | cd8a73cd102596bc7880efa1ba72fb9c | 32 | 119 | 0.636679 | 4.735426 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/syncadapter/ContactsSyncManager.kt | 1 | 12934 | /*
* Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.syncadapter
import android.accounts.Account
import android.content.*
import android.os.Bundle
import android.provider.ContactsContract
import at.bitfire.ical4android.CalendarStorageException
import at.bitfire.vcard4android.BatchOperation
import at.bitfire.vcard4android.Contact
import at.bitfire.vcard4android.ContactsStorageException
import com.etesync.journalmanager.Exceptions
import com.etesync.journalmanager.JournalEntryManager
import com.etesync.journalmanager.model.SyncEntry
import com.etebase.client.Item
import com.etesync.syncadapter.AccountSettings
import com.etesync.syncadapter.Constants
import com.etesync.syncadapter.HttpClient
import com.etesync.syncadapter.R
import com.etesync.syncadapter.log.Logger
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.resource.LocalAddress
import com.etesync.syncadapter.resource.LocalAddressBook
import com.etesync.syncadapter.resource.LocalContact
import com.etesync.syncadapter.resource.LocalGroup
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import org.apache.commons.collections4.SetUtils
import java.io.FileNotFoundException
import java.io.IOException
import java.io.StringReader
import java.util.logging.Level
/**
*
* Synchronization manager for CardDAV collections; handles contacts and groups.
*/
class ContactsSyncManager @Throws(Exceptions.IntegrityException::class, Exceptions.GenericCryptoException::class, ContactsStorageException::class)
constructor(context: Context, account: Account, settings: AccountSettings, extras: Bundle, authority: String, private val provider: ContentProviderClient, result: SyncResult, localAddressBook: LocalAddressBook, private val remote: HttpUrl) : SyncManager<LocalAddress>(context, account, settings, extras, authority, result, localAddressBook.url, CollectionInfo.Type.ADDRESS_BOOK, localAddressBook.mainAccount.name) {
private val resourceDownloader: ResourceDownloader
protected override val syncErrorTitle: String
get() = context.getString(R.string.sync_error_contacts, account.name)
protected override val syncSuccessfullyTitle: String
get() = context.getString(R.string.sync_successfully_contacts, account.name)
init {
localCollection = localAddressBook
resourceDownloader = ResourceDownloader(context)
}
override fun notificationId(): Int {
return Constants.NOTIFICATION_CONTACTS_SYNC
}
@Throws(ContactsStorageException::class, CalendarStorageException::class)
override fun prepare(): Boolean {
if (!super.prepare())
return false
val localAddressBook = localAddressBook()
if (LocalContact.HASH_HACK) {
// workaround for Android 7 which sets DIRTY flag when only meta-data is changed
val reallyDirty = localAddressBook.verifyDirty()
val deleted = localAddressBook.findDeleted().size
if (extras.containsKey(ContentResolver.SYNC_EXTRAS_UPLOAD) && reallyDirty == 0 && deleted == 0) {
Logger.log.info("This sync was called to up-sync dirty/deleted contacts, but no contacts have been changed")
return false
}
}
if (isLegacy) {
journal = JournalEntryManager(httpClient.okHttpClient, remote, localAddressBook.url)
}
return true
}
@Throws(CalendarStorageException::class, ContactsStorageException::class)
override fun prepareDirty() {
super.prepareDirty()
val addressBook = localAddressBook()
/* groups as separate VCards: there are group contacts and individual contacts */
// mark groups with changed members as dirty
val batch = BatchOperation(addressBook.provider!!)
for (contact in addressBook.findDirtyContacts()) {
try {
Logger.log.fine("Looking for changed group memberships of contact " + contact.fileName)
val cachedGroups = contact.getCachedGroupMemberships()
val currentGroups = contact.getGroupMemberships()
for (groupID in SetUtils.disjunction(cachedGroups, currentGroups)) {
Logger.log.fine("Marking group as dirty: " + groupID!!)
batch.enqueue(BatchOperation.CpoBuilder.newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(ContactsContract.Groups.CONTENT_URI, groupID)))
.withValue(ContactsContract.Groups.DIRTY, 1)
)
}
} catch (ignored: FileNotFoundException) {
}
}
batch.commit()
}
@Throws(CalendarStorageException::class, ContactsStorageException::class)
override fun postProcess() {
super.postProcess()
/* VCard4 group handling: there are group contacts and individual contacts */
Logger.log.info("Assigning memberships of downloaded contact groups")
LocalGroup.applyPendingMemberships(localAddressBook())
}
// helpers
private fun localAddressBook(): LocalAddressBook {
return localCollection as LocalAddressBook
}
override fun processItem(item: Item) {
val local = localCollection!!.findByFilename(item.uid)
if (!item.isDeleted) {
val inputReader = StringReader(String(item.content))
val contacts = Contact.fromReader(inputReader, resourceDownloader)
if (contacts.size == 0) {
Logger.log.warning("Received VCard without data, ignoring")
return
} else if (contacts.size > 1) {
Logger.log.warning("Received multiple VCALs, using first one")
}
val contact = contacts[0]
processContact(item, contact, local)
} else {
if (local != null) {
Logger.log.info("Removing local record which has been deleted on the server")
local.delete()
} else {
Logger.log.warning("Tried deleting a non-existent record: " + item.uid)
}
}
}
@Throws(IOException::class, ContactsStorageException::class, CalendarStorageException::class)
override fun processSyncEntryImpl(cEntry: SyncEntry) {
val inputReader = StringReader(cEntry.content)
val contacts = Contact.fromReader(inputReader, resourceDownloader)
if (contacts.size == 0) {
Logger.log.warning("Received VCard without data, ignoring")
return
} else if (contacts.size > 1)
Logger.log.warning("Received multiple VCards, using first one")
val contact = contacts[0]
val local = localCollection!!.findByUid(contact.uid!!)
if (cEntry.isAction(SyncEntry.Actions.ADD) || cEntry.isAction(SyncEntry.Actions.CHANGE)) {
legacyProcessContact(contact, local)
} else {
if (local != null) {
Logger.log.info("Removing local record which has been deleted on the server")
local.delete()
} else {
Logger.log.warning("Tried deleting a non-existent record: " + contact.uid)
}
}
}
private fun processContact(item: Item, newData: Contact, _local: LocalAddress?): LocalAddress {
var local = _local
val uuid = newData.uid
// update local contact, if it exists
if (local != null) {
Logger.log.log(Level.INFO, "Updating $uuid in local address book")
if (local is LocalGroup && newData.group) {
// update group
val group: LocalGroup = local
group.eTag = item.etag
group.update(newData)
syncResult.stats.numUpdates++
} else if (local is LocalContact && !newData.group) {
// update contact
val contact: LocalContact = local
contact.eTag = item.etag
contact.update(newData)
syncResult.stats.numUpdates++
} else {
// group has become an individual contact or vice versa
try {
local.delete()
local = null
} catch (e: CalendarStorageException) {
// CalendarStorageException is not used by LocalGroup and LocalContact
}
}
}
if (local == null) {
if (newData.group) {
Logger.log.log(Level.INFO, "Creating local group", item.uid)
val group = LocalGroup(localAddressBook(), newData, item.uid, item.etag)
group.add()
local = group
} else {
Logger.log.log(Level.INFO, "Creating local contact", item.uid)
val contact = LocalContact(localAddressBook(), newData, item.uid, item.etag)
contact.add()
local = contact
}
syncResult.stats.numInserts++
}
if (LocalContact.HASH_HACK && local is LocalContact)
// workaround for Android 7 which sets DIRTY flag when only meta-data is changed
local.updateHashCode(null)
return local
}
@Throws(IOException::class, ContactsStorageException::class)
private fun legacyProcessContact(newData: Contact, _local: LocalAddress?): LocalAddress {
var local = _local
val uuid = newData.uid
// update local contact, if it exists
if (local != null) {
Logger.log.log(Level.INFO, "Updating $uuid in local address book")
if (local is LocalGroup && newData.group) {
// update group
val group: LocalGroup = local
group.eTag = uuid
group.update(newData)
syncResult.stats.numUpdates++
} else if (local is LocalContact && !newData.group) {
// update contact
val contact: LocalContact = local
contact.eTag = uuid
contact.update(newData)
syncResult.stats.numUpdates++
} else {
// group has become an individual contact or vice versa
try {
local.delete()
local = null
} catch (e: CalendarStorageException) {
// CalendarStorageException is not used by LocalGroup and LocalContact
}
}
}
if (local == null) {
if (newData.group) {
Logger.log.log(Level.INFO, "Creating local group", newData.uid)
val group = LocalGroup(localAddressBook(), newData, uuid, uuid)
group.add()
local = group
} else {
Logger.log.log(Level.INFO, "Creating local contact", newData.uid)
val contact = LocalContact(localAddressBook(), newData, uuid, uuid)
contact.add()
local = contact
}
syncResult.stats.numInserts++
}
if (LocalContact.HASH_HACK && local is LocalContact)
// workaround for Android 7 which sets DIRTY flag when only meta-data is changed
local.updateHashCode(null)
return local
}
// downloader helper class
class ResourceDownloader(internal var context: Context) : Contact.Downloader {
override fun download(url: String, accepts: String): ByteArray? {
val httpUrl = url.toHttpUrlOrNull()
if (httpUrl == null) {
Logger.log.log(Level.SEVERE, "Invalid external resource URL", url)
return null
}
val host = httpUrl.host
if (host == null) {
Logger.log.log(Level.SEVERE, "External resource URL doesn't specify a host name", url)
return null
}
val resourceClient = HttpClient.Builder(context).setForeground(false).build().okHttpClient
try {
val response = resourceClient.newCall(Request.Builder()
.get()
.url(httpUrl)
.build()).execute()
val body = response.body
if (body != null) {
return body.bytes()
}
} catch (e: IOException) {
Logger.log.log(Level.SEVERE, "Couldn't download external resource", e)
}
return null
}
}
}
| gpl-3.0 | de79e31a48ec33c163bc6c48a401aa47 | 37.485119 | 415 | 0.618436 | 5.045259 | false | false | false | false |
reid112/Reidit | app/src/main/java/ca/rjreid/reidit/ui/main/InfiniteScrollListener.kt | 1 | 1175 | package ca.rjreid.reidit.ui.main
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
class InfiniteScrollListener(private val layoutManager: LinearLayoutManager,
private val onEndListReached: () -> Unit)
: RecyclerView.OnScrollListener() {
private var previousTotal = 0
private var loading = true
private var visibleThreshold = 2
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dy > 0) {
val visibleItemCount = recyclerView.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
if (loading) {
if (totalItemCount > previousTotal) {
loading = false
previousTotal = totalItemCount
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
onEndListReached()
loading = true
}
}
}
} | apache-2.0 | d62f5bc947673145b5e8a49b316ab804 | 32.6 | 107 | 0.611915 | 5.649038 | false | false | false | false |
pixis/TraktTV | app/src/main/java/com/pixis/traktTV/views/AdvancedRecyclerView.kt | 2 | 2970 | package com.pixis.traktTV.views
import android.content.Context
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import com.pixis.traktTV.R
open class AdvancedRecyclerView : LinearLayout {
private lateinit var recyclerView: RecyclerView
private lateinit var emptyView: View
private lateinit var swipeRefreshLayout: SwipeRefreshLayout
private var isDataView = true
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
init()
}
internal fun init() {
if (isInEditMode) {
return
}
val v = LayoutInflater.from(context).inflate(R.layout.advanced_recyclerview, this, false)
recyclerView = v.findViewById(R.id.advanced_recyclerview_recyclerView) as RecyclerView
emptyView = v.findViewById(R.id.advanced_recyclerview_emptyView)
swipeRefreshLayout = v.findViewById(R.id.advanced_recyclerview_refreshContainer) as SwipeRefreshLayout
//Init recyclerview
val layoutManager = LinearLayoutManager(context)
recyclerView.layoutManager = layoutManager
addView(v)
}
fun setAdapter(adapter: RecyclerView.Adapter<*>) {
recyclerView.adapter = adapter
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
super.onChanged()
if (adapter.itemCount == 0) {
showEmptyView()
} else {
showDataView()
}
}
})
}
fun setOnRefreshListener(onRefreshListener: SwipeRefreshLayout.OnRefreshListener) {
swipeRefreshLayout.setOnRefreshListener(onRefreshListener)
}
private fun showEmptyView() {
if (isDataView) {
emptyView.visibility = View.VISIBLE
recyclerView.visibility = View.GONE
isDataView = false
}
}
private fun showDataView() {
if (!isDataView) {
emptyView.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
isDataView = true
}
}
fun setRefreshing(refreshing : Boolean) {
swipeRefreshLayout.isRefreshing = refreshing
}
}
| apache-2.0 | 4b5a751210b64102661971aea2182152 | 29.9375 | 144 | 0.670034 | 5.12069 | false | false | false | false |
alondero/nestlin | src/main/kotlin/com/github/alondero/nestlin/ppu/Ppu.kt | 1 | 9040 | package com.github.alondero.nestlin.ppu
import com.github.alondero.nestlin.*
import com.github.alondero.nestlin.ui.FrameListener
import java.util.*
const val RESOLUTION_WIDTH = 256
const val RESOLUTION_HEIGHT = 224
const val NTSC_SCANLINES = 262
const val IDLE_SCANLINE = 0
const val PRE_RENDER_SCANLINE = 261
const val POST_RENDER_SCANLINE = 240
class Ppu(var memory: Memory) {
private var cycle = 0
private var scanline = 0
// 2 16-Bit registers containing bitmap data for two tiles
// Every 8 cycles, the bitmap data for the next tile is loaded into the upper 8 bits of this shift register.
// Meanwhile, the pixel to render is fetched from one of the lower 8 bits.
var youngTile = 0xFFFF.toSignedShort()
var nextTile = 0xFFFF.toSignedShort()
// 2 8-bit shift registers - These contain the palette attributes for the lower 8 pixels of the 16-bit shift register.
// Every 8 cycles, the latch is loaded with the palette attribute for the next tile.
val paletteRegisters = 0
// These registers are fed by a latch which contains the palette attribute for the next tile.
val paletteLatch = 0
private var listener: FrameListener? = null
private var vBlank = false
private var frame = Frame()
private val rand = Random()
private var lastNametableByte: Byte = 0
private var lastAttributeTableByte: Byte = 0
fun tick() {
// println("Rendering ($cycle, $scanline)")
if (cycle == 341) {
endLine()
return
}
if (rendering()) {
// Fetch tile data
when (cycle) {// Idle
in 1..256 -> fetchData()
in 257..320 -> fetchSpriteTile()
in 321..336 -> fetchData() // Ready for next scanline
}
checkAndSetVerticalAndHorizontalData()
}
if (cycle in 241..260) {
vBlank = true // Should be set at the second 'tick'?
memory.ppuAddressedMemory.nmiOccurred = true
}
if (scanline == PRE_RENDER_SCANLINE && cycle == 1) {memory.ppuAddressedMemory.status.clearFlags()}
if (cycle % 8 == 0) {
// Bitmap data for the next tile is loaded into the upper 8 bits
val bitmap = 0xFF.toSignedByte()
}
// Every cycle a bit is fetched from the 4 backgroundNametables shift registers in order to create a pixel on screen
// with(spriteNametables) {
// decrementCounters()
// getActiveSprites().forEach {
// // If the counter is zero, the sprite becomes "active", and the respective pair of shift registers for the sprite is shifted once every cycle.
// // This output accompanies the data in the sprite's latch, to form a pixel.
// it.shiftRegisters()
// // The current pixel for each "active" sprite is checked (from highest to lowest priority), and the first non-transparent pixel moves on to a multiplexer,
// // where it joins the BG pixel
// }
// }
cycle++
}
private fun rendering() = with (memory.ppuAddressedMemory.mask) { showBackground() && showSprites() }
private fun checkAndSetVerticalAndHorizontalData() {
when (cycle) {
256 -> memory.ppuAddressedMemory.vRamAddress.incrementVerticalPosition()
257 -> with(memory.ppuAddressedMemory) {
vRamAddress.coarseXScroll = tempVRamAddress.coarseXScroll
vRamAddress.horizontalNameTable = tempVRamAddress.horizontalNameTable
}
}
if (scanline == PRE_RENDER_SCANLINE && cycle in 280..304) {
with (memory.ppuAddressedMemory) {
vRamAddress.coarseYScroll = tempVRamAddress.coarseYScroll
vRamAddress.fineYScroll = tempVRamAddress.fineYScroll
vRamAddress.verticalNameTable = tempVRamAddress.verticalNameTable
}
}
}
private fun endLine() {
when (scanline) {
NTSC_SCANLINES - 1 -> endFrame()
else -> scanline++
}
cycle = 0
}
private fun endFrame() {
listener?.frameUpdated(frame)
// What to do here?
scanline = 0
vBlank = false
}
private fun fetchSpriteTile() {
// The tile data for the spriteNametables on the next scanline are fetched here. Again, each memory access takes 2 PPU cycles to complete, and 4 are performed for each of the 8 spriteNametables:
//
// Garbage nametable byte
// Garbage nametable byte
// Tile bitmap low
// Tile bitmap high (+8 bytes from tile bitmap low)
// The garbage fetches occur so that the same circuitry that performs the BG tile fetches could be reused for the sprite tile fetches.
//
// If there are less than 8 spriteNametables on the next scanline, then dummy fetches to tile $FF occur for the left-over spriteNametables, because of the dummy sprite data in the secondary OAM (see sprite evaluation). This data is then discarded, and the spriteNametables are loaded with a transparent bitmap instead.
//
// In addition to this, the X positions and attributes for each sprite are loaded from the secondary OAM into their respective counters/latches. This happens during the second garbage nametable fetch, with the attribute byte loaded during the first tick and the X coordinate during the second.
}
private fun fetchData() {
when (cycle % 8) {
0 -> with (memory.ppuAddressedMemory){
vRamAddress.incrementHorizontalPosition()
lastNametableByte = ppuInternalMemory[controller.baseNametableAddr() or (address.toUnsignedInt() and 0x0FFF)]
}
2 -> with(memory.ppuAddressedMemory){
/**
* v := ppu.v
address := 0x23C0 | (v & 0x0C00) | ((v >> 4) & 0x38) | ((v >> 2) & 0x07)
shift := ((v >> 4) & 4) | (v & 2)
ppu.attributeTableByte = ((ppu.Read(address) >> shift) & 3) << 2
*/
// Don't understand this logic... had to inspect other source code to work out what to do...
val address = controller.baseNametableAddr() or (vRamAddress.coarseXScroll and 0b11100) or (vRamAddress.coarseYScroll and 0b11100)
lastAttributeTableByte = ppuInternalMemory[controller.baseNametableAddr() + 0x3C0]
}
4 -> with(memory.ppuAddressedMemory) {
// Fetch Low Tile Byte
}
6 -> with(memory.ppuAddressedMemory) {
// Fetch High Tile Byte
}
}
// The data for each tile is fetched during this phase. Each memory access takes 2 PPU cycles to complete, and 4 must be performed per tile:
// Nametable byte
// Attribute table byte
// Tile bitmap low
// Tile bitmap high (+8 bytes from tile bitmap low)
// The data fetched from these accesses is placed into internal latches, and then fed to the appropriate shift registers when it's time to do so (every 8 cycles). Because the PPU can only fetch an attribute byte every 8 cycles, each sequential string of 8 pixels is forced to have the same palette attribute.
//
// Sprite zero hits act as if the image starts at cycle 2 (which is the same cycle that the shifters shift for the first time), so the sprite zero flag will be raised at this point at the earliest. Actual pixel output is delayed further due to internal render pipelining, and the first pixel is output during cycle 4.
//
// The shifters are reloaded during ticks 9, 17, 25, ..., 257.
//
// Note: At the beginning of each scanline, the data for the first two tiles is already loaded into the shift registers (and ready to be rendered), so the first tile that gets fetched is Tile 3.
//
// While all of this is going on, sprite evaluation for the next scanline is taking place as a seperate process, independent to what's happening here.
if (scanline < RESOLUTION_HEIGHT && cycle - 1 < RESOLUTION_WIDTH) {
frame[scanline, cycle - 1] = rand.nextInt(0xFFFFFF)
}
}
fun addFrameListener(listener: FrameListener) {
this.listener = listener
}
}
class ObjectAttributeMemory {
private val memory = ByteArray(0x100)
}
class Sprites {
// Holds 8 sprites for the current scanline
private val sprites = Array(size = 8, init = { Sprite() })
fun decrementCounters() = sprites.forEach { it.counter.dec() }
fun getActiveSprites() = sprites.filter(Sprite::isActive)
}
data class Sprite(
val objectAttributeMemory: Byte = 0,
var bitmapDataA: Byte = 0,
var bitmapDataB: Byte = 0,
val latch: Byte = 0,
val counter: Int = 0
) {
fun isActive() = counter <= 0
fun shiftRegisters() {
bitmapDataA = bitmapDataA.shiftRight()
bitmapDataB = bitmapDataB.shiftRight()
}
}
| gpl-3.0 | 4d26fbbcd62956b59d395a02a1e2361b | 40.658986 | 325 | 0.637721 | 4.306813 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/LawnchairApp.kt | 1 | 9126 | /*
* Copyright 2021, Lawnchair
*
* 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 app.lawnchair
import android.app.Activity
import android.app.Application
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import app.lawnchair.backup.LawnchairBackup
import app.lawnchair.preferences.PreferenceManager
import app.lawnchair.ui.AlertBottomSheetContent
import app.lawnchair.ui.preferences.openAppInfo
import app.lawnchair.util.restartLauncher
import app.lawnchair.views.ComposeBottomSheet
import com.android.launcher3.BuildConfig
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.Launcher
import com.android.launcher3.R
import com.android.quickstep.RecentsActivity
import com.android.systemui.shared.system.QuickStepContract
import java.io.File
class LawnchairApp : Application() {
val activityHandler = ActivityHandler()
private val compatible = Build.VERSION.SDK_INT in BuildConfig.QUICKSTEP_MIN_SDK..BuildConfig.QUICKSTEP_MAX_SDK
private val isRecentsComponent by lazy { checkRecentsComponent() }
private val recentsEnabled get() = compatible && isRecentsComponent
internal var accessibilityService: LawnchairAccessibilityService? = null
val vibrateOnIconAnimation by lazy { getSystemUiBoolean("config_vibrateOnIconAnimation", false) }
override fun onCreate() {
super.onCreate()
instance = this
QuickStepContract.sRecentsDisabled = !recentsEnabled
}
fun onLauncherAppStateCreated() {
registerActivityLifecycleCallbacks(activityHandler)
}
fun restart(recreateLauncher: Boolean = true) {
if (recreateLauncher) {
activityHandler.finishAll()
} else {
restartLauncher(this)
}
}
fun renameRestoredDb(dbName: String) {
val restoredDbFile = getDatabasePath(LawnchairBackup.RESTORED_DB_FILE_NAME)
if (!restoredDbFile.exists()) return
val dbFile = getDatabasePath(dbName)
restoredDbFile.renameTo(dbFile)
}
fun migrateDbName(dbName: String) {
val dbFile = getDatabasePath(dbName)
if (dbFile.exists()) return
val prefs = PreferenceManager.INSTANCE.get(this)
val dbJournalFile = getJournalFile(dbFile)
val oldDbSlot = prefs.sp.getString("pref_currentDbSlot", "a")
val oldDbName = if (oldDbSlot == "a") "launcher.db" else "launcher.db_b"
val oldDbFile = getDatabasePath(oldDbName)
val oldDbJournalFile = getJournalFile(oldDbFile)
if (oldDbFile.exists()) {
oldDbFile.copyTo(dbFile)
oldDbJournalFile.copyTo(dbJournalFile)
oldDbFile.delete()
oldDbJournalFile.delete()
}
}
fun cleanUpDatabases() {
val idp = InvariantDeviceProfile.INSTANCE.get(this)
val dbName = idp.dbFile
val dbFile = getDatabasePath(dbName)
dbFile?.parentFile?.listFiles()?.forEach { file ->
val name = file.name
if (name.startsWith("launcher") && !name.startsWith(dbName)) {
file.delete()
}
}
}
private fun getJournalFile(file: File): File =
File(file.parentFile, "${file.name}-journal")
private fun getSystemUiBoolean(resName: String, fallback: Boolean): Boolean {
val systemUiPackage = "com.android.systemui"
val res = packageManager.getResourcesForApplication(systemUiPackage)
val resId = res.getIdentifier(resName, "bool", systemUiPackage)
if (resId == 0) {
return fallback
}
return res.getBoolean(resId)
}
class ActivityHandler : ActivityLifecycleCallbacks {
val activities = HashSet<Activity>()
var foregroundActivity: Activity? = null
fun finishAll() {
HashSet(activities).forEach { it.finish() }
}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {
foregroundActivity = activity
}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityDestroyed(activity: Activity) {
if (activity == foregroundActivity) foregroundActivity = null
activities.remove(activity)
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
activities.add(activity)
}
}
private fun checkRecentsComponent(): Boolean {
val resId = resources.getIdentifier("config_recentsComponentName", "string", "android")
if (resId == 0) {
Log.d(TAG, "config_recentsComponentName not found, disabling recents")
return false
}
val recentsComponent = ComponentName.unflattenFromString(resources.getString(resId))
if (recentsComponent == null) {
Log.d(TAG, "config_recentsComponentName is empty, disabling recents")
return false
}
val isRecentsComponent = recentsComponent.packageName == packageName
&& recentsComponent.className == RecentsActivity::class.java.name
if (!isRecentsComponent) {
Log.d(TAG, "config_recentsComponentName ($recentsComponent) is not Lawnchair, disabling recents")
return false
}
return true
}
fun isAccessibilityServiceBound(): Boolean = accessibilityService != null
fun performGlobalAction(action: Int): Boolean {
return if (accessibilityService != null) {
accessibilityService!!.performGlobalAction(action)
} else {
startActivity(
Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
false
}
}
companion object {
private const val TAG = "LawnchairApp"
@JvmStatic
var instance: LawnchairApp? = null
private set
@JvmStatic
val isRecentsEnabled: Boolean
get() = instance?.recentsEnabled == true
fun Launcher.showQuickstepWarningIfNecessary() {
val launcher = this
if (!lawnchairApp.isRecentsComponent || isRecentsEnabled) return
ComposeBottomSheet.show(this) {
AlertBottomSheetContent(
title = { Text(text = stringResource(id = R.string.quickstep_incompatible)) },
text = {
val description = stringResource(
id = R.string.quickstep_incompatible_description,
stringResource(id = R.string.derived_app_name),
Build.VERSION.RELEASE
)
Text(text = description)
},
buttons = {
OutlinedButton(
onClick = {
openAppInfo(launcher)
close(true)
}
) {
Text(text = stringResource(id = R.string.app_info_drop_target_label))
}
Spacer(modifier = Modifier.requiredWidth(8.dp))
Button(
onClick = { close(true) }
) {
Text(text = stringResource(id = android.R.string.ok))
}
}
)
}
}
fun getUriForFile(context: Context, file: File): Uri {
return FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.fileprovider", file)
}
}
}
val Context.lawnchairApp get() = applicationContext as LawnchairApp
val Context.foregroundActivity get() = lawnchairApp.activityHandler.foregroundActivity
| gpl-3.0 | b4aca00be4f037913f65556a972dfc5e | 35.798387 | 114 | 0.640368 | 4.957089 | false | false | false | false |
xfournet/intellij-community | platform/usageView/src/com/intellij/usages/UsageViewSettings.kt | 1 | 3726 | // 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.usages
import com.intellij.openapi.components.*
import com.intellij.util.PathUtil
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Transient
/**
* Passed params will be used as default values, so, do not use constructor if instance will be used as a state (unless you want to change defaults)
*/
@State(name = "UsageViewSettings", storages = [(Storage("usageView.xml")), (Storage(value = "other.xml", deprecated = true))])
open class UsageViewSettings(
isGroupByFileStructure: Boolean = true,
isGroupByModule: Boolean = true,
isGroupByPackage: Boolean = true,
isGroupByUsageType: Boolean = true,
isGroupByScope: Boolean = false
) : BaseState(), PersistentStateComponent<UsageViewSettings> {
companion object {
@JvmStatic
val instance: UsageViewSettings
get() = ServiceManager.getService(UsageViewSettings::class.java)
}
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByModule")
var GROUP_BY_MODULE = isGroupByModule
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByUsageType")
var GROUP_BY_USAGE_TYPE = isGroupByUsageType
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByFileStructure")
var GROUP_BY_FILE_STRUCTURE = isGroupByFileStructure
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByScope")
var GROUP_BY_SCOPE = isGroupByScope
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByPackage")
var GROUP_BY_PACKAGE = isGroupByPackage
@Suppress("MemberVisibilityCanPrivate")
@get:OptionTag("EXPORT_FILE_NAME")
internal var EXPORT_FILE_NAME by property("report.txt")
@get:OptionTag("IS_EXPANDED")
var isExpanded by property(false)
@get:OptionTag("IS_AUTOSCROLL_TO_SOURCE")
var isAutoScrollToSource by property(false)
@get:OptionTag("IS_FILTER_DUPLICATED_LINE")
var isFilterDuplicatedLine by property(true)
@get:OptionTag("IS_SHOW_METHODS")
var isShowModules by property(false)
@get:OptionTag("IS_PREVIEW_USAGES")
var isPreviewUsages by property(false)
@get:OptionTag("IS_REPLACE_PREVIEW_USAGES")
var isReplacePreviewUsages by property(true)
@get:OptionTag("IS_SORT_MEMBERS_ALPHABETICALLY")
var isSortAlphabetically by property(false)
@get:OptionTag("PREVIEW_USAGES_SPLITTER_PROPORTIONS")
var previewUsagesSplitterProportion by property(0.5f)
@get:OptionTag("GROUP_BY_USAGE_TYPE")
var isGroupByUsageType by property(isGroupByUsageType)
@get:OptionTag("GROUP_BY_MODULE")
var isGroupByModule by property(isGroupByModule)
@get:OptionTag("FLATTEN_MODULES")
var isFlattenModules by property(true)
@get:OptionTag("GROUP_BY_PACKAGE")
var isGroupByPackage by property(isGroupByPackage)
@get:OptionTag("GROUP_BY_FILE_STRUCTURE")
var isGroupByFileStructure by property(isGroupByFileStructure)
@get:OptionTag("GROUP_BY_SCOPE")
var isGroupByScope: Boolean by property(isGroupByScope)
var exportFileName: String?
@Transient
get() = PathUtil.toSystemDependentName(EXPORT_FILE_NAME)
set(value) {
EXPORT_FILE_NAME = PathUtil.toSystemIndependentName(value)
}
override fun getState() = this
@Suppress("DEPRECATION")
override fun loadState(state: UsageViewSettings) {
copyFrom(state)
GROUP_BY_MODULE = isGroupByModule
GROUP_BY_USAGE_TYPE = isGroupByUsageType
GROUP_BY_FILE_STRUCTURE = isGroupByFileStructure
GROUP_BY_SCOPE = isGroupByScope
GROUP_BY_PACKAGE = isGroupByPackage
}
}
| apache-2.0 | 1226200c305d3b6eca21d987df0d4059 | 30.05 | 148 | 0.753355 | 4.248575 | false | false | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/renderers/pageId.kt | 1 | 1083 | package org.jetbrains.dokka.base.renderers
import org.jetbrains.dokka.base.renderers.html.NavigationNode
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.DisplaySourceSet
import org.jetbrains.dokka.pages.ContentPage
internal val ContentPage.pageId: String
get() = pageId(dri.first(), sourceSets())
internal val NavigationNode.pageId: String
get() = pageId(dri, sourceSets)
@JvmName("shortenSourceSetsToUrl")
internal fun Set<DisplaySourceSet>.shortenToUrl() =
sortedBy { it.sourceSetIDs.merged.let { it.scopeId + it.sourceSetName } }.joinToString().hashCode()
internal fun DRI.shortenToUrl() = toString()
@JvmName("shortenDrisToUrl")
internal fun Set<DRI>.shortenToUrl() = sortedBy { it.toString() }.joinToString().hashCode()
/**
* Page Id is required to have a sourceSet in order to distinguish between different pages that has same DRI but different sourceSet
* like main functions that are not expect/actual
*/
private fun pageId(dri: DRI, sourceSets: Set<DisplaySourceSet>): String = "${dri.shortenToUrl()}/${sourceSets.shortenToUrl()}" | apache-2.0 | 002608682cebe4898bfd95449a80518b | 39.148148 | 132 | 0.77193 | 4.117871 | false | false | false | false |
mustafa01ali/Dev-Tiles | app/src/main/kotlin/xyz/mustafaali/devqstiles/util/AnimationScaler.kt | 1 | 2257 | package xyz.mustafaali.devqstiles.util
import android.content.ContentResolver
import android.content.Context
import android.provider.Settings
import android.support.annotation.DrawableRes
import android.widget.Toast
import timber.log.Timber
import xyz.mustafaali.devqstiles.R
/**
* A utility class for working with system Window Animation Scale, Transition Animation Scale, and Animator Duration Scale.
*/
object AnimationScaler {
@DrawableRes
fun getIcon(scale: Float): Int {
when {
scale <= 0f -> return R.drawable.ic_animation_off
else -> return R.drawable.ic_animation_on
}
}
fun toggleAnimationScale(context: Context): Boolean {
val animationScale = if (getAnimationScale(context.contentResolver) == 1.0f) 0.0f else 1.0f
return try {
Settings.Global.putFloat(
context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, animationScale)
Settings.Global.putFloat(
context.contentResolver, Settings.Global.WINDOW_ANIMATION_SCALE, animationScale)
Settings.Global.putFloat(
context.contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE, animationScale)
true
} catch (se: SecurityException) {
val message = context.getString(R.string.permission_required_toast)
Toast.makeText(context.applicationContext, message, Toast.LENGTH_LONG).show()
Timber.e(se, message)
false
}
}
fun getAnimationScale(contentResolver: ContentResolver?): Float {
var scale = 1f
try {
scale = maxOf(
Settings.Global.getFloat(contentResolver,
Settings.Global.ANIMATOR_DURATION_SCALE),
Settings.Global.getFloat(contentResolver,
Settings.Global.WINDOW_ANIMATION_SCALE),
Settings.Global.getFloat(contentResolver,
Settings.Global.TRANSITION_ANIMATION_SCALE))
} catch (e: Settings.SettingNotFoundException) {
Timber.e(e, "Could not read Animation Scale setting")
}
return if (scale >= 1) 1.0f else 0.0f
}
}
| apache-2.0 | 0df4de74dbe91fb36c65bc11aa41c819 | 37.913793 | 123 | 0.638901 | 4.78178 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_bps/src/main/java/no/nordicsemi/android/bps/view/BPSScreen.kt | 1 | 4317 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.bps.view
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import no.nordicsemi.android.bps.R
import no.nordicsemi.android.bps.viewmodel.BPSViewModel
import no.nordicsemi.android.service.*
import no.nordicsemi.android.ui.view.BackIconAppBar
import no.nordicsemi.android.ui.view.LoggerIconAppBar
import no.nordicsemi.android.utils.exhaustive
import no.nordicsemi.ui.scanner.ui.DeviceConnectingView
import no.nordicsemi.ui.scanner.ui.DeviceDisconnectedView
import no.nordicsemi.ui.scanner.ui.NoDeviceView
import no.nordicsemi.ui.scanner.ui.Reason
@Composable
fun BPSScreen() {
val viewModel: BPSViewModel = hiltViewModel()
val state = viewModel.state.collectAsState().value
Column {
val navigateUp = { viewModel.onEvent(DisconnectEvent) }
AppBar(state = state, navigateUp = navigateUp, viewModel = viewModel)
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
when (state) {
NoDeviceState -> NoDeviceView()
is WorkingState -> when (state.result) {
is IdleResult,
is ConnectingResult -> DeviceConnectingView { viewModel.onEvent(DisconnectEvent) }
is ConnectedResult -> DeviceConnectingView { viewModel.onEvent(DisconnectEvent) }
is DisconnectedResult -> DeviceDisconnectedView(Reason.USER, navigateUp)
is LinkLossResult -> DeviceDisconnectedView(Reason.LINK_LOSS, navigateUp)
is MissingServiceResult -> DeviceDisconnectedView(Reason.MISSING_SERVICE, navigateUp)
is UnknownErrorResult -> DeviceDisconnectedView(Reason.UNKNOWN, navigateUp)
is SuccessResult -> BPSContentView(state.result.data) { viewModel.onEvent(it) }
}
}.exhaustive
}
}
}
@Composable
private fun AppBar(state: BPSViewState, navigateUp: () -> Unit, viewModel: BPSViewModel) {
val toolbarName = (state as? WorkingState)?.let {
(it.result as? DeviceHolder)?.deviceName()
}
if (toolbarName == null) {
BackIconAppBar(stringResource(id = R.string.bps_title), navigateUp)
} else {
LoggerIconAppBar(toolbarName, {
viewModel.onEvent(DisconnectEvent)
}, { viewModel.onEvent(DisconnectEvent) }) {
viewModel.onEvent(OpenLoggerEvent)
}
}
}
| bsd-3-clause | 1eca30f43e0e7cf442b8f31ee60d571d | 43.96875 | 105 | 0.731063 | 4.692391 | false | false | false | false |
ybonjour/test-store | backend/src/test/kotlin/ch/yvu/teststore/common/PagedResultFetcherTest.kt | 1 | 6225 | package ch.yvu.teststore.common
import ch.yvu.teststore.integration.run.runInstance
import ch.yvu.teststore.run.Run
import com.datastax.driver.core.ExecutionInfo
import com.datastax.driver.core.PagingState
import com.datastax.driver.core.ResultSet
import com.datastax.driver.core.Session
import com.datastax.driver.core.SimpleStatement
import com.datastax.driver.core.Statement
import com.datastax.driver.mapping.Mapper
import com.datastax.driver.mapping.Result
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations.initMocks
import org.mockito.hamcrest.MockitoHamcrest.argThat
import java.util.Date
import java.util.UUID.randomUUID
// This test would ideally be an integration test using the cassandra database directly
// In order to test it we have to mock objects that are not under our control. This is an anti pattern
// Since setting up a database integration test is too costly right now, I decided this is better than no tests.
class PagedResultFetcherTest {
companion object {
val testSuite = randomUUID()
val run = runInstance()
val query = SimpleQuery("SELECT * FROM run WHERE testSuite=?", testSuite)
val pagingState = PagingState.fromString("00270010001b000800000156e1d573f11004f3aed39d784b4cb666646f4c5add50f07ffffffdf07ffffffd14f77afb69f7d2b915966de34665f10c0004")
}
@Mock
lateinit var session: Session
@Mock
lateinit var mapper: Mapper<Run>
@Mock
lateinit var resultSet: ResultSet
@Mock
lateinit var result: Result<Run>
lateinit var fetcher: PagedResultFetcher<Run>
@Before
fun setUp() {
initMocks(this)
`when`(session.execute(any(Statement::class.java))).thenReturn(resultSet)
`when`(mapper.map(resultSet)).thenReturn(result)
fetcher = PagedResultFetcher(session, mapper)
}
@Test
fun executesQuery() {
givenAResultWithNRows(n = 0)
fetcher.fetch(query)
verify(session).execute(argThat(statementWithQuery(query)))
}
@Test
fun returnsResult() {
givenAResultWithNRows(n = 1)
`when`(result.isExhausted).thenReturn(false).thenReturn(true)
val page = fetcher.fetch(query)
assertEquals(listOf(run), page.results)
}
@Test
fun usesCorrectFetchSize() {
givenAResultWithNRows(n = 0)
fetcher.fetch(query)
verify(session).execute(argThat(statementWithFetchSize(PagedResultFetcher.defaultFetchSize)))
}
@Test
fun overrideDefaultPageSizeIfPageSizeIsPrvoided() {
val fetchSize = 2
givenAResultWithNRows(n = 0)
fetcher.fetch(query, fetchSize = fetchSize)
verify(session).execute(argThat(statementWithFetchSize(fetchSize)))
}
@Test
fun onlyConsumesAsManyRowsAsFetched() {
givenAResultWithNRows(n = 2)
`when`(resultSet.availableWithoutFetching).thenReturn(1)
fetcher.fetch(query)
verify(result, times(1)).one()
}
@Test
fun returnsPagingStateInPage() {
givenAResultWithNRows(n = 1)
givenResultPagingState(pagingState)
val page = fetcher.fetch(query)
assertEquals(pagingState.toString(), page.nextPage)
}
@Test
fun setsProvidedPagingState() {
givenAResultWithNRows(n = 1)
val statement = mock(Statement::class.java)
val query = mock(Query::class.java)
`when`(query.createStatement()).thenReturn(statement)
fetcher.fetch(query, pagingState.toString())
verify(statement).setPagingState(argThat(pagingState(pagingState.toString())))
}
private fun givenResultPagingState(pagingState: PagingState) {
val executionInfo = mock(ExecutionInfo::class.java)
`when`(executionInfo.pagingState).thenReturn(pagingState)
`when`(resultSet.executionInfo).thenReturn(executionInfo)
}
private fun givenAResultWithNRows(n: Int) {
var count = 0;
`when`(result.one()).thenAnswer {
if (count < n) {
count += 1
run
} else null
}
`when`(resultSet.availableWithoutFetching).thenReturn(n)
}
private fun pagingState(pagingState: String) = object : TypeSafeMatcher<PagingState>() {
override fun describeTo(description: Description?) {
if (description == null) return
description.appendValue(pagingState)
}
override fun matchesSafely(item: PagingState?): Boolean {
if (item == null) return false
return item.toString() == pagingState
}
}
private fun statementWithFetchSize(fetchSize: Int) = object : TypeSafeMatcher<SimpleStatement>() {
override fun matchesSafely(item: SimpleStatement?): Boolean {
if (item == null) return false
return item.fetchSize == fetchSize
}
override fun describeTo(description: Description?) {
if (description == null) return
description.appendText("Statement with fetchSize ").appendValue(fetchSize)
}
}
private fun statementWithQuery(query: SimpleQuery) = object : TypeSafeMatcher<SimpleStatement>() {
override fun describeTo(description: Description?) {
if (description == null) return
description
.appendText("Statement with query '").appendValue(query.queryString)
.appendText("' and values ").appendValue(query.values);
}
override fun matchesSafely(statement: SimpleStatement?): Boolean {
if (statement == null) return false
var i = 0
for (value in query.values) {
if (!statement.getObject(i).equals(value)) {
return false
}
i += 1
}
return query.queryString == statement.queryString
}
}
} | mit | 0eb987d5d64b824c0c559cc891832d8e | 29.077295 | 174 | 0.671647 | 4.377637 | false | true | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_rscs/src/main/java/no/nordicsemi/android/rscs/view/SensorsReadingView.kt | 1 | 3009 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.rscs.view
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import no.nordicsemi.android.theme.ScreenSection
import no.nordicsemi.android.rscs.R
import no.nordicsemi.android.rscs.data.RSCSData
import no.nordicsemi.android.ui.view.KeyValueField
import no.nordicsemi.android.ui.view.SectionTitle
@Composable
internal fun SensorsReadingView(state: RSCSData) {
ScreenSection {
SectionTitle(resId = R.drawable.ic_records, title = "Records")
Spacer(modifier = Modifier.height(16.dp))
KeyValueField(stringResource(id = R.string.rscs_activity), state.displayActivity())
Spacer(modifier = Modifier.height(4.dp))
KeyValueField(stringResource(id = R.string.rscs_pace), state.displayPace())
Spacer(modifier = Modifier.height(4.dp))
KeyValueField(stringResource(id = R.string.rscs_cadence), state.displayCadence())
Spacer(modifier = Modifier.height(4.dp))
state.displayNumberOfSteps()?.let {
KeyValueField(stringResource(id = R.string.rscs_number_of_steps), it)
}
}
}
@Preview
@Composable
private fun Preview() {
SensorsReadingView(RSCSData())
}
| bsd-3-clause | edf3ad3b743451be4d8eb46510de07af | 41.985714 | 91 | 0.763377 | 4.17337 | false | false | false | false |
daemontus/glucose | core/src/main/java/com/glucose/app/presenter/LifecycleHost.kt | 2 | 9049 | package com.glucose.app.presenter
import android.support.annotation.AnyThread
import android.support.annotation.MainThread
import com.glucose.app.presenter.Lifecycle.State.*
import rx.Observable
import rx.Observer
import rx.Subscriber
import rx.Subscription
object Lifecycle {
/**
* Possible events that can occur during a lifecycle.
*/
enum class Event {
ATTACH, START, RESUME, PAUSE, STOP, DETACH, DESTROY
}
/**
* Possible states an object can be in within a lifecycle.
* Each state hierarchy is inclusive with respect to states that are smaller
* (except for [DESTROYED]), meaning that a component that
* is [STARTED] is also [ATTACHED] and [ALIVE].
*
* Possible state transitions are as follows:
* . -> ALIVE
* ALIVE -> ATTACHED
* ALIVE -> DESTROYED
* ATTACHED -> STARTED
* ATTACHED -> ALIVE
* STARTED -> RESUMED
* STARTED -> ATTACHED
* RESUMED -> STARTED
*/
enum class State {
DESTROYED, ALIVE, ATTACHED, STARTED, RESUMED;
/**
* Return the event that will end this state.
*/
fun closingEvent(): Event {
return when (this) {
ALIVE -> Event.DESTROY
ATTACHED -> Event.DETACH
STARTED -> Event.STOP
RESUMED -> Event.PAUSE
DESTROYED -> throw LifecycleException("$this does not have a closing event.")
}
}
/**
* Return the event that started this state.
*/
fun openingEvent(): Event {
return when (this) {
ALIVE -> throw LifecycleException("$this does not have an opening event.")
ATTACHED -> Event.ATTACH
STARTED -> Event.START
RESUMED -> Event.RESUME
DESTROYED -> Event.DESTROY
}
}
}
}
/**
* [LifecycleHost] provides access to the lifecycle information of a component.
*
* That means it provides:
* - current state the component is in
* - asynchronous notifications in the form of an observable
* - synchronous notifications in the form of callbacks
*/
interface LifecycleHost {
/**
* Current state of the component.
*/
val state: Lifecycle.State
/**
* Notifications about lifecycle events.
* Note that there is no guarantee about delay between the lifecycle event and
* the event delivery (especially when using schedulers) and that
* the events aren't cached. So upon subscribing, you will always receive only
* the upcoming events.
*
* Hence one can't assume that after receiving a START notification,
* the host is actually started - it may have been stopped already.
* But at some point in the past, it was indeed started.
*/
val lifecycleEvents: Observable<Lifecycle.Event>
/**
* Add a callback that will be executed during lifecycle change.
*
* Note that the component can't change state again until all callbacks
* are finished. So if you add a START callback, it will be executed
* before the component can be stopped, providing a synchronous
* notification.
*/
@MainThread
fun addEventCallback(event: Lifecycle.Event, callback: () -> Unit)
/**
* Remove a previously added callback. Returns true if the callback
* was found and false if there was no such pending callback.
*/
@MainThread
fun removeEventCallback(event: Lifecycle.Event, callback: () -> Unit): Boolean
fun <T> Observable<T>.takeUntil(event: Lifecycle.Event): Observable<T>
= this.takeUntil(this@LifecycleHost, event)
fun <T> Observable<T>.takeWhileIn(state: Lifecycle.State): Observable<T>
= this.takeWhileIn(this@LifecycleHost, state)
fun Subscription.until(event: Lifecycle.Event) : Subscription
= this.until(this@LifecycleHost, event)
fun <T> Observable<T>.whileIn(state: Lifecycle.State) : BoundSubscription<T>
= this.whileIn(this@LifecycleHost, state)
}
/**
* Returns an [Observable] which will stop emitting items as soon as given [LifecycleHost]
* emits specified [Lifecycle.Event].
*
* Note that the termination will be achieved by emitting an onCompleted event
* and depends on asynchronous notifications (therefore there can be some delay).
*
* If you need synchronous behavior, use [until].
* If you want take hosts state into account, see [takeWhileIn].
*
* Scheduler: No particular info.
*
* @see LifecycleHost
* @see until
* @see takeWhileIn
*/
@AnyThread
fun <T> Observable<T>.takeUntil(host: LifecycleHost, event: Lifecycle.Event): Observable<T> {
return this.takeUntil(host.lifecycleEvents.filter { it == event })
}
/**
* Return an [Observable] which will emit items while given [LifecycleHost] is
* in given (or higher) [Lifecycle.State]. If (at the time of subscription) the host is
* in a lower state, no items will be emitted.
*
* Note that the termination will be achieved by emitting an onCompleted event
* and depends on asynchronous notifications (therefore there can be some delay).
*
* If you need synchronous behavior, use [whileIn].
* If you don't need to check hosts state, use [takeUntil]
*
* Scheduler: The returned observable will operate on the main thread.
*
* @see LifecycleHost
* @see takeUntil
* @see whileIn
*/
@AnyThread
fun <T> Observable<T>.takeWhileIn(host: LifecycleHost, state: Lifecycle.State): Observable<T> {
//If state is DESTROYED, closing event will kick in and kill this fast
val event = state.closingEvent()
return Observable.defer {
if (host.state >= state) {
this.takeUntil(host, event)
} else {
Observable.empty()
}
}
}
/**
* Adds a callback to the [LifecycleHost] that will ensure that as soon as it
* changes state due to specified [Lifecycle.Event], this subscription will be
* unsubscribed.
*
* If all you need is asynchronous behavior, use [takeUntil].
* If you want to take hosts state into account, us [whileIn].
*
* @see LifecycleHost
* @see takeUntil
* @see whileIn
*/
@MainThread
fun Subscription.until(
host: LifecycleHost, event: Lifecycle.Event
): Subscription {
host.addEventCallback(event) {
if (!this.isUnsubscribed) this.unsubscribe()
}
return this
}
/**
* Returns a [BoundSubscription] that ensures that this observable is subscribed to
* only while given [LifecycleHost] is in a specified (or higher) [Lifecycle.State].
* If the host is not in the specified state, the subscription won't be created.
* If it is, it will be created and a callback will be added to ensure that the
* subscription will be unsubscribed as soon as the host leaves the state.
*
* If all you need is asynchronous behavior, use [takeWhileIn].
* If you don't need to take hosts state into account, use [until].
*
* @see LifecycleHost
* @see takeWhileIn
* @see until
*/
@MainThread
fun <T> Observable<T>.whileIn(host: LifecycleHost, state: Lifecycle.State): BoundSubscription<T>
= BoundSubscription(this, state, host)
/**
* A helper class for implementing lifecycle-bound subscriptions.
* [BoundSubscription] mimics the subscription API of an [Observable],
* but asserts that during subscription, the [LifecycleHost] connected
* to this [BoundSubscription] is in the desired state and that the
* subscription will be unsubscribed when the [LifecycleHost] leaves this state.
*/
class BoundSubscription<out T>(
private val observable: Observable<T>,
private val state: Lifecycle.State,
private val host: LifecycleHost
) {
fun subscribe(): Subscription?
= checkState { observable.subscribe() }
fun subscribe(onNext: (T) -> Unit): Subscription?
= checkState { observable.subscribe(onNext) }
fun subscribe(onNext: (T) -> Unit, onError: (Throwable) -> Unit): Subscription?
= checkState { observable.subscribe(onNext, onError) }
fun subscribe(onNext: (T) -> Unit, onError: (Throwable) -> Unit, onCompleted: () -> Unit)
= checkState { observable.subscribe(onNext, onError, onCompleted) }
fun subscribe(observer: Observer<in T>): Subscription?
= checkState { observable.subscribe(observer) }
fun subscribe(subscriber: Subscriber<in T>): Subscription?
= checkState { observable.subscribe(subscriber) }
private inline fun checkState(andDo: () -> Subscription): Subscription? {
return if (host.state >= state) andDo().until(host, state.closingEvent()) else null
}
}
//some simple helper functions regarding state
val LifecycleHost.isAlive: Boolean
get() = this.state >= ALIVE
val LifecycleHost.isAttached: Boolean
get() = this.state >= ATTACHED
val LifecycleHost.isStarted: Boolean
get() = this.state >= STARTED
val LifecycleHost.isResumed: Boolean
get() = this.state >= RESUMED
val LifecycleHost.isDestroyed: Boolean
get() = this.state <= DESTROYED
| mit | 34d8c04dda661e401572df16f62d1fe7 | 33.538168 | 96 | 0.671455 | 4.346302 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/users/Auth0Utils.kt | 1 | 2276 | package com.openlattice.users
import com.auth0.client.mgmt.ManagementAPI
import com.auth0.client.mgmt.filter.UserFilter
import com.auth0.exception.Auth0Exception
import com.auth0.json.mgmt.users.User
import com.auth0.json.mgmt.users.UsersPage
import com.auth0.jwt.algorithms.Algorithm
import com.geekbeast.auth0.*
import com.openlattice.authentication.Auth0AuthenticationConfiguration
import java.security.InvalidAlgorithmParameterException
import java.time.Instant
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
private const val SEARCH_ENGINE_VERSION = "v3"
private const val MAX_PAGE_SIZE = 100
val AUTH0_USER_FIELDS = listOf(
APP_METADATA,
EMAIL,
FAMILY_NAME,
GIVEN_NAME,
IDENTITIES,
NAME,
NICKNAME,
USER_ID
)
@Throws(Auth0Exception::class)
fun getUpdatedUsersPage(
managementApi: ManagementAPI, lastSync: Instant, currentSync: Instant, page: Int, pageSize: Int
): UsersPage {
require(pageSize <= MAX_PAGE_SIZE)
{ "Requested page size of $pageSize exceeds max page size of $MAX_PAGE_SIZE." }
return managementApi.users().list(
UserFilter()
.withSearchEngine(SEARCH_ENGINE_VERSION)
.withQuery("$UPDATED_AT={$lastSync TO $currentSync]")
.withFields(AUTH0_USER_FIELDS.joinToString(","), true)
.withPage(page, pageSize)
).execute()
}
@Throws(Auth0Exception::class)
fun getUser(managementApi: ManagementAPI, principalId: String): User {
return managementApi.users().get(
principalId,
UserFilter()
.withSearchEngine(SEARCH_ENGINE_VERSION)
.withFields("$USER_ID,$EMAIL,$NICKNAME,$APP_METADATA,$IDENTITIES", true)
.withPage(0, MAX_PAGE_SIZE)
).execute()
}
internal fun parseAlgorithm(aac: Auth0AuthenticationConfiguration): Algorithm {
val algorithm: (String) -> Algorithm = when (aac.signingAlgorithm) {
"HS256" -> Algorithm::HMAC256
"HS384" -> Algorithm::HMAC384
"HS512" -> Algorithm::HMAC512
else -> throw InvalidAlgorithmParameterException("Algorithm ${aac.signingAlgorithm} not recognized.")
}
return algorithm(aac.secret)
}
| gpl-3.0 | 8ebfdd727ba8216f3608a95661f31bcf | 32.970149 | 109 | 0.675747 | 4.007042 | false | false | false | false |
http4k/http4k | src/docs/guide/reference/chaos/example_chaos.kt | 1 | 1706 | package guide.reference.chaos
import org.http4k.chaos.ChaosBehaviours.ReturnStatus
import org.http4k.chaos.ChaosEngine
import org.http4k.chaos.ChaosStages.Wait
import org.http4k.chaos.ChaosTriggers.PercentageBased
import org.http4k.chaos.appliedWhen
import org.http4k.chaos.then
import org.http4k.chaos.until
import org.http4k.client.OkHttp
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.INTERNAL_SERVER_ERROR
import org.http4k.core.Status.Companion.OK
import org.http4k.core.then
import org.http4k.server.SunHttp
import org.http4k.server.asServer
val client = OkHttp()
fun main() {
// chaos is split into "stages", which can be triggered by specific request or time-based criteria
val doNothingStage = Wait.until { tx: Request -> tx.method == POST }
val errorStage = ReturnStatus(INTERNAL_SERVER_ERROR).appliedWhen(PercentageBased(50))
// chain the stages together with then() and create the Chaos Engine (activated)
val engine = ChaosEngine(doNothingStage.then(errorStage)).enable()
val svc: HttpHandler = { Response(OK).body("A normal response") }
engine.then(svc).asServer(SunHttp(9000)).start().use {
repeat(10) { performA(GET) }
// this triggers the change in behaviour
performA(POST)
repeat(10) { performA(GET) }
// disable the chaos
engine.disable()
repeat(10) { performA(GET) }
}
}
fun performA(method: Method) =
println(method.name + " got a " + client(Request(method, "http://localhost:9000")).status)
| apache-2.0 | 410cec59ba9bc60e5bf09a6bf0183fa2 | 32.45098 | 102 | 0.740328 | 3.40519 | false | false | false | false |
orbit/orbit | src/orbit-proto/src/main/kotlin/orbit/shared/proto/MessageConverters.kt | 1 | 5587 | /*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.shared.proto
import orbit.shared.mesh.NodeId
import orbit.shared.net.InvocationReason
import orbit.shared.net.Message
import orbit.shared.net.MessageContent
import orbit.shared.net.MessageTarget
import orbit.shared.router.Route
fun Messages.MessageProto.toMessage(): Message =
Message(
messageId = messageId,
source = source?.toNodeId(),
target = target?.toMessageTarget(),
content = content.toMessageContent(),
attempts = attempts
)
fun Message.toMessageProto(): Messages.MessageProto =
Messages.MessageProto.newBuilder().let {
if (messageId != null) it.setMessageId(messageId!!) else it
}.let {
if (source != null) it.setSource(source!!.toNodeIdProto()) else it
}.let {
if (target != null) it.setTarget(target!!.toMessageTargetProto()) else it
}.setAttempts(attempts)
.setContent(content.toMessageContentProto()).build()
fun Messages.MessageTargetProto.toMessageTarget(): MessageTarget? =
when (this.targetCase.number) {
Messages.MessageTargetProto.UNICASTTARGET_FIELD_NUMBER -> {
MessageTarget.Unicast(unicastTarget.target.toNodeId())
}
Messages.MessageTargetProto.ROUTEDUNICASTTARGET_FIELD_NUMBER -> {
MessageTarget.RoutedUnicast(Route(routedUnicastTarget.targetList.map { it.toNodeId() }))
}
else -> null
}
fun MessageTarget.toMessageTargetProto() = Messages.MessageTargetProto.newBuilder().let {
when (this) {
is MessageTarget.Unicast -> it.setUnicastTarget(
Messages.MessageTargetProto.Unicast.newBuilder().setTarget(targetNode.toNodeIdProto())
)
is MessageTarget.RoutedUnicast -> it.setRoutedUnicastTarget(
Messages.MessageTargetProto.RoutedUnicast.newBuilder()
.addAllTarget(route.path.map(NodeId::toNodeIdProto))
)
}
}.build()
fun Messages.MessageContentProto.toMessageContent(): MessageContent =
when {
hasInvocationRequest() -> {
MessageContent.InvocationRequest(
method = invocationRequest.method,
arguments = invocationRequest.arguments,
destination = invocationRequest.reference.toAddressableReference(),
reason = InvocationReason.fromInt(invocationRequest.reasonValue)
)
}
hasInvocationResponse() -> {
MessageContent.InvocationResponse(
data = invocationResponse.value
)
}
hasError() -> {
MessageContent.Error(
description = error.description
)
}
hasInvocationResponseError() -> {
MessageContent.InvocationResponseError(
description = invocationResponseError.description,
platform = invocationResponseError.platform
)
}
hasInfoRequest() -> {
MessageContent.ConnectionInfoRequest
}
hasInfoResponse() -> {
MessageContent.ConnectionInfoResponse(
nodeId = infoResponse.nodeId.toNodeId()
)
}
else -> throw Throwable("Unknown message type")
}
fun MessageContent.toMessageContentProto(): Messages.MessageContentProto =
Messages.MessageContentProto.newBuilder()
.let { builder ->
when (this) {
is MessageContent.InvocationRequest -> {
builder.setInvocationRequest(
Messages.InvocationRequestProto.newBuilder()
.setReference(destination.toAddressableReferenceProto())
.setMethod(method)
.setArguments(arguments)
.setReason(Messages.InvocationReasonProto.forNumber(reason.value))
.build()
)
}
is MessageContent.InvocationResponse -> {
builder.setInvocationResponse(
Messages.InvocationResponseProto.newBuilder()
.setValue(data)
.build()
)
}
is MessageContent.InvocationResponseError -> {
builder.setInvocationResponseError(
Messages.InvocationResponseErrorProto.newBuilder()
.setDescription(description)
.setPlatform(platform)
.build()
)
}
is MessageContent.Error -> {
builder.setError(
Messages.ErrorProto.newBuilder()
.setDescription(description)
.build()
)
}
is MessageContent.ConnectionInfoRequest -> {
builder.setInfoRequest(
Messages.ConnectionInfoRequestProto.newBuilder()
)
}
is MessageContent.ConnectionInfoResponse -> {
builder.setInfoResponse(
Messages.ConnectionInfoResponseProto.newBuilder()
.setNodeId(nodeId.toNodeIdProto())
)
}
}
}.build()
| bsd-3-clause | e66ee3ea6495b13a617ad76540d40b5d | 34.585987 | 100 | 0.567926 | 5.609438 | false | false | false | false |
Gark/DiffUtils | app/src/main/java/gark/diffutils/MainActivity.kt | 1 | 1365 | package gark.diffutils
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val mPresenter = Presenter()
private var mAdapter: PeronAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mAdapter = PeronAdapter(mPresenter.getOriginalList())
recycler_view.layoutManager = GridLayoutManager(this, 3)
recycler_view.adapter = mAdapter
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.sort_by_name -> mAdapter?.swapData(mPresenter.getSortedByName())
R.id.sort_by_age -> mAdapter?.swapData(mPresenter.getSortedByAge())
R.id.older_than_18 -> mAdapter?.swapData(mPresenter.getOlderThan18())
R.id.younger_than_18 -> mAdapter?.swapData(mPresenter.getYoungerThan18())
}
return true
}
}
| apache-2.0 | d0b7df8208ed2277a73091451da1b373 | 33.125 | 85 | 0.70989 | 4.333333 | false | false | false | false |
Vavassor/Tusky | app/src/main/java/com/keylesspalace/tusky/AccountListActivity.kt | 1 | 3606 | /* Copyright 2017 Andrew Dawson
*
* This file is a part of Tusky.
*
* 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.
*
* Tusky 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 Tusky; if not,
* see <http://www.gnu.org/licenses>. */
package com.keylesspalace.tusky
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.MenuItem
import com.keylesspalace.tusky.fragment.AccountListFragment
import javax.inject.Inject
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.toolbar_basic.*
class AccountListActivity : BaseActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
enum class Type {
FOLLOWS,
FOLLOWERS,
BLOCKS,
MUTES,
FOLLOW_REQUESTS,
REBLOGGED,
FAVOURITED
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_account_list)
val type = intent.getSerializableExtra(EXTRA_TYPE) as Type
val id: String? = intent.getStringExtra(EXTRA_ID)
setSupportActionBar(toolbar)
supportActionBar?.apply {
when (type) {
AccountListActivity.Type.BLOCKS -> setTitle(R.string.title_blocks)
AccountListActivity.Type.MUTES -> setTitle(R.string.title_mutes)
AccountListActivity.Type.FOLLOW_REQUESTS -> setTitle(R.string.title_follow_requests)
AccountListActivity.Type.FOLLOWERS -> setTitle(R.string.title_followers)
AccountListActivity.Type.FOLLOWS -> setTitle(R.string.title_follows)
AccountListActivity.Type.REBLOGGED -> setTitle(R.string.title_reblogged_by)
AccountListActivity.Type.FAVOURITED -> setTitle(R.string.title_favourited_by)
}
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, AccountListFragment.newInstance(type, id))
.commit()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun supportFragmentInjector(): AndroidInjector<Fragment>? {
return dispatchingAndroidInjector
}
companion object {
private const val EXTRA_TYPE = "type"
private const val EXTRA_ID = "id"
@JvmStatic
fun newIntent(context: Context, type: Type, id: String? = null): Intent {
return Intent(context, AccountListActivity::class.java).apply {
putExtra(EXTRA_TYPE, type)
putExtra(EXTRA_ID, id)
}
}
}
}
| gpl-3.0 | 6bded8a5b1b11e6a32801fae82fd98dc | 34.352941 | 100 | 0.675541 | 4.906122 | false | false | false | false |
keidrun/qstackoverflow | src/main/kotlin/com/keidrun/qstackoverflow/app/App.kt | 1 | 8774 | /**
* Copyright 2017 Keid
*/
package com.keidrun.qstackoverflow.app
import com.github.kevinsawicki.http.HttpRequest
import com.keidrun.qstackoverflow.lib.*
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import org.apache.commons.cli.*
import kotlin.system.exitProcess
/**
* Stack Overflow Search CLI.
*
* @author Keid
*/
fun main(args: Array<String>) {
try {
val options: Options = buildOptions()
val cmd: CommandLine = DefaultParser().parse(options, args)
val formatter: HelpFormatter = HelpFormatter()
if ((cmd.args.isEmpty() && cmd.options.isEmpty()) || (cmd.options.size == 1 && cmd.hasOption("h"))) {
formatter.printHelp("sos [title] [option...]", options);
exitProcess(0)
}
val varboseFlag: Boolean = cmd.hasOption("v")
if (varboseFlag) showArgs(cmd)
val inTitle: String = if (cmd.args.isNotEmpty()) cmd.args[0]
else throw IllegalArgumentException("Title is required")
val params: SOParams = buildParams(inTitle, cmd)
val query: Query<SOParams, String> = SOQuery(params)
if (varboseFlag) {
println("url:")
print(" ")
println("${query.url}")
println()
println("results:")
}
val res: String = query.search(params)
if (cmd.hasOption("r")) {
println(res)
} else {
val moshi = Moshi.Builder().build()
val adapter: JsonAdapter<SOItems> = moshi.adapter(SOItems::class.java)
val itemsObj: SOItems = adapter.fromJson(res) as SOItems
if (cmd.hasOption("c")) {
for (item in itemsObj.items) {
println("\"${item.question_id}\",\"${item.title}\",\"${item.link}\"")
}
} else {
for (item in itemsObj.items) {
println("[${item.question_id}][${item.title}][${item.link}]")
}
println("Total: ${itemsObj.items.size} questions.")
}
}
exitProcess(0)
} catch (e: IllegalArgumentException) {
println(e.message)
exitProcess(1)
} catch (e: ParseException) {
print("Unknown arguments: ")
for (arg in args) print("$arg ")
println()
exitProcess(1)
} catch (e: MissingOptionException) {
print("Unknown arguments: ")
for (arg in args) print("$arg ")
println()
exitProcess(1)
} catch (e: HttpRequest.HttpRequestException) {
println("Internet disconnected:")
println("Error Discription -> $e")
exitProcess(1)
} catch (e: Exception) {
println("An unexpected error occurred:")
println("Error Discription -> $e")
exitProcess(1)
}
}
fun buildOptions(): Options {
var options: Options = Options()
options.addOption(Option.builder("p")
.hasArg(true)
.required(false)
.argName("page")
.desc("set a \"page\" parameter")
.longOpt("page")
.build())
options.addOption(Option.builder("z")
.hasArg(true)
.required(false)
.argName("pagesize")
.desc("set a \"pagesize\" parameter")
.longOpt("pagesize")
.build())
options.addOption(Option.builder("f")
.hasArg(true)
.required(false)
.argName("fromdate")
.desc("set a \"fromdate\" parameter, a format must be \"${SOSerector.Format.DATE}\"")
.longOpt("fromdate")
.build())
options.addOption(Option.builder("t")
.hasArg(true)
.required(false)
.argName("todate")
.desc("set a \"todate\" parameter, a format must be \"${SOSerector.Format.DATE}\"")
.longOpt("todate")
.build())
options.addOption(Option.builder("o")
.hasArg(true)
.required(false)
.argName("order")
.desc("set a \"order\" parameter, \"desc\"(default) or \"asc\"")
.longOpt("order")
.build())
options.addOption(Option.builder("min")
.hasArg(true)
.required(false)
.argName("mindate")
.desc("set a \"min\" date parameter, a format must be \"${SOSerector.Format.DATE}\"")
.longOpt("mindate")
.build())
options.addOption(Option.builder("max")
.hasArg(true)
.required(false)
.argName("maxdate")
.desc("set a \"max\" date parameter, a format must be \"${SOSerector.Format.DATE}\"")
.longOpt("maxdate")
.build())
options.addOption(Option.builder("s")
.hasArg(true)
.required(false)
.argName("sort")
.desc("set a \"sort\" parameter, \"activity\"(default) or \"votes\" or \"creation\" or \"relevance\"")
.longOpt("sort")
.build())
options.addOption(Option.builder("g")
.hasArg(true)
.required(false)
.argName("tagged")
.desc("set a \"tagged\" parameter.")
.longOpt("tagged")
.build())
options.addOption(Option.builder("n")
.hasArg(true)
.required(false)
.argName("notagged")
.desc("set a \"notagged\" parameter")
.longOpt("notagged")
.build())
options.addOption(Option.builder("l")
.hasArg(true)
.required(false)
.argName("lang")
.desc("access the language's site, \"en\"(default) or \"ja\"")
.longOpt("lang")
.build())
options.addOption(Option.builder("v")
.required(false)
.desc("show verbose")
.longOpt("verbose")
.build())
options.addOption(Option.builder("h")
.required(false)
.desc("show help")
.longOpt("help")
.build())
options.addOption(Option.builder("r")
.required(false)
.desc("show raw json")
.longOpt("raw")
.build())
options.addOption(Option.builder("c")
.required(false)
.desc("show csv format")
.longOpt("csv")
.build())
return options
}
fun buildParams(inTitle: String, cmd: CommandLine): SOParams {
val params: SOParams =
if (cmd.hasOption("g")) SOParams(inTitle, cmd.getOptionValue("g")) else SOParams(inTitle, "")
if (cmd.hasOption("p")) params.page = cmd.getOptionValue("p").toInt()
if (cmd.hasOption("z")) params.pageSize = cmd.getOptionValue("z").toInt()
if (cmd.hasOption("f")) params.fromDate = params.parseDate(cmd.getOptionValue("f"))
if (cmd.hasOption("t")) params.toDate = params.parseDate(cmd.getOptionValue("t"))
if (cmd.hasOption("o")) params.order = SOSerector.Order.DESC.serectorOf(cmd.getOptionValue("o"))
if (cmd.hasOption("min")) params.minDate = params.parseDate(cmd.getOptionValue("min"))
if (cmd.hasOption("max")) params.maxDate = params.parseDate(cmd.getOptionValue("max"))
if (cmd.hasOption("s")) params.sort = SOSerector.Sort.ACTIVITY.serectorOf(cmd.getOptionValue("s"))
if (cmd.hasOption("n")) params.noTagged = cmd.getOptionValue("n")
if (cmd.hasOption("l")) params.site = SOSerector.Site.ENGLISH.serectorOf(cmd.getOptionValue("l"))
return params
}
fun showArgs(cmd: CommandLine) {
println("arguments: ")
if (cmd.args.isNotEmpty()) println(" title: \"${cmd.args[0]}\"") else println(" title:\"\"")
if (cmd.hasOption("p")) println(" page: \"${cmd.getOptionValue("p")}\"")
if (cmd.hasOption("z")) println(" pagesize: \"${cmd.getOptionValue("s")}\"")
if (cmd.hasOption("f")) println(" fromdate: \"${cmd.getOptionValue("f")}\"")
if (cmd.hasOption("t")) println(" todate: \"${cmd.getOptionValue("t")}\"")
if (cmd.hasOption("o")) println(" order: \"${cmd.getOptionValue("o")}\"")
if (cmd.hasOption("min")) println(" mindate: \"${cmd.getOptionValue("min")}\"")
if (cmd.hasOption("max")) println(" maxdate: \"${cmd.getOptionValue("max")}\"")
if (cmd.hasOption("s")) println(" sort: \"${cmd.getOptionValue("s")}\"")
if (cmd.hasOption("g")) println(" tagged: \"${cmd.getOptionValue("g")}\"")
if (cmd.hasOption("n")) println(" notagged: \"${cmd.getOptionValue("n")}\"")
if (cmd.hasOption("l")) println(" lang: \"${cmd.getOptionValue("l")}\"")
// flag
if (cmd.hasOption("v")) println(" verbose: yes")
if (cmd.hasOption("r")) println(" raw: yes")
else if (cmd.hasOption("c")) println(" csv: yes")
println()
} | mit | 7e0ddae4a102c362284ab1632cae2357 | 35.869748 | 114 | 0.549578 | 3.979138 | false | false | false | false |
simonlebras/Radio-France | app/src/main/kotlin/fr/simonlebras/radiofrance/ui/browser/list/RadioListPresenter.kt | 1 | 3393 | package fr.simonlebras.radiofrance.ui.browser.list
import android.support.v4.media.session.PlaybackStateCompat
import fr.simonlebras.radiofrance.di.scopes.FragmentScope
import fr.simonlebras.radiofrance.models.Radio
import fr.simonlebras.radiofrance.ui.base.BasePresenter
import fr.simonlebras.radiofrance.ui.base.BaseView
import fr.simonlebras.radiofrance.ui.browser.manager.RadioManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import javax.inject.Inject
@FragmentScope
class RadioListPresenter @Inject constructor(private val radioManager: RadioManager) : BasePresenter<RadioListPresenter.View>() {
private var refreshSubject = PublishSubject.create<Boolean>()
private var searchSubject = BehaviorSubject.create<String>()
fun connect() {
compositeDisposable.add(radioManager.connection
.subscribe {
view?.onConnected()
})
}
fun subscribeToRefreshAndSearchEvents() {
compositeDisposable.add(Observable
.combineLatest(refreshSubject, searchSubject.startWith(""), BiFunction { _: Boolean, search: String -> search })
.switchMap {
val query = it
radioManager.radios
.onErrorResumeNext(Observable.just(emptyList()))
.flatMap {
Observable.fromIterable(it)
.filter {
it.name.toLowerCase().contains(query.toLowerCase())
}
.toList()
.map {
Pair(query, it)
}
.toObservable()
}
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
val query = it.first
val radios = it.second
if (radios.isEmpty()) {
if (query.isNullOrBlank()) {
view?.showRefreshError()
} else {
view?.showSearchError()
}
return@subscribe
}
view?.showRadios(radios)
})
}
fun subscribeToPlaybackUpdates() {
compositeDisposable.add(radioManager.playbackUpdates
.subscribe {
if (it is PlaybackStateCompat) {
view?.onPlaybackStateChanged(it)
}
}
)
}
fun refresh() {
refreshSubject.onNext(true)
}
fun searchRadios(query: String) {
searchSubject.onNext(query)
}
fun play(id: String) {
radioManager.play(id)
}
interface View : BaseView {
fun onConnected()
fun showRadios(radios: List<Radio>)
fun showRefreshError()
fun showSearchError()
fun onPlaybackStateChanged(playbackState: PlaybackStateCompat)
}
}
| mit | 7c15897b9e22a20c595a0744bd5fb06c | 33.272727 | 129 | 0.530504 | 5.741117 | false | false | false | false |
kunny/RxFirebase | firebase-database/src/test/kotlin/com/androidhuman/rxfirebase2/database/RxFirebaseDatabaseTest.kt | 1 | 47525 | package com.androidhuman.rxfirebase2.database
import com.androidhuman.rxfirebase2.database.model.DataValue
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseException
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.GenericTypeIndicator
import com.google.firebase.database.MutableData
import com.google.firebase.database.Query
import com.google.firebase.database.Transaction
import com.google.firebase.database.ValueEventListener
import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import io.reactivex.BackpressureStrategy
import io.reactivex.observers.TestObserver
import io.reactivex.subscribers.TestSubscriber
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
@Suppress("NOTHING_TO_INLINE")
class RxFirebaseDatabaseTest {
@Mock
private lateinit var databaseReference: DatabaseReference
@Mock
lateinit var query: Query
private val childEventListener = argumentCaptor<ChildEventListener>()
private val valueEventListener = argumentCaptor<ValueEventListener>()
private val transactionHandler = argumentCaptor<Transaction.Handler>()
private val completionListener = argumentCaptor<DatabaseReference.CompletionListener>()
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
}
// Bindings for DatabaseReference
@Test
fun dataReferenceFlowableChildEventsAdded() {
val snapshot = mock<DataSnapshot>()
with(TestSubscriber.create<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildAdded(snapshot, "foo")
childEventListener.lastValue.onChildAdded(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildAddEvent.create(snapshot, "foo"),
ChildAddEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildAdded(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun dataReferenceObservableChildEventsAdded() {
val snapshot = mock<DataSnapshot>()
with(TestObserver.create<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildAdded(snapshot, "foo")
childEventListener.lastValue.onChildAdded(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildAddEvent.create(snapshot, "foo"),
ChildAddEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildAdded(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun dataReferenceFlowableChildEventsChanged() {
val snapshot = mock<DataSnapshot>()
with(TestSubscriber<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildChanged(snapshot, "foo")
childEventListener.lastValue.onChildChanged(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildChangeEvent.create(snapshot, "foo"),
ChildChangeEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildChanged(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun dataReferenceObservableChildEventsChanged() {
val snapshot = mock<DataSnapshot>()
with(TestObserver<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildChanged(snapshot, "foo")
childEventListener.lastValue.onChildChanged(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildChangeEvent.create(snapshot, "foo"),
ChildChangeEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildChanged(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun dataReferenceFlowableChildEventsRemoved() {
val snapshot = mock<DataSnapshot>()
with(TestSubscriber<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildRemoved(snapshot)
childEventListener.lastValue.onChildRemoved(snapshot)
assertNotComplete()
assertNoErrors()
assertValues(
ChildRemoveEvent.create(snapshot),
ChildRemoveEvent.create(snapshot))
dispose()
// simulate the callback
childEventListener.lastValue.onChildRemoved(snapshot)
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun dataReferenceObservableChildEventsRemoved() {
val snapshot = mock<DataSnapshot>()
with(TestObserver<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildRemoved(snapshot)
childEventListener.lastValue.onChildRemoved(snapshot)
assertNotComplete()
assertNoErrors()
assertValues(
ChildRemoveEvent.create(snapshot),
ChildRemoveEvent.create(snapshot))
dispose()
// simulate the callback
childEventListener.lastValue.onChildRemoved(snapshot)
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun dataReferenceFlowableChildEventsMoved() {
val snapshot = mock<DataSnapshot>()
with(TestSubscriber<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildMoved(snapshot, "foo")
childEventListener.lastValue.onChildMoved(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildMoveEvent.create(snapshot, "foo"),
ChildMoveEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildMoved(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun dataReferenceObservableChildEventsMoved() {
val snapshot = mock<DataSnapshot>()
with(TestObserver<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildMoved(snapshot, "foo")
childEventListener.lastValue.onChildMoved(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildMoveEvent.create(snapshot, "foo"),
ChildMoveEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildMoved(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun dataReferenceFlowableChildEventsCancelled() {
val error = databaseError()
with(TestSubscriber<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun dataReferenceObservableChildEventsCancelled() {
val error = databaseError()
with(TestObserver<ChildEvent>()) {
RxFirebaseDatabase.childEvents(databaseReference)
.subscribe(this)
// verify addChildEventListener() has called
databaseReference.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun dataReferenceData() {
val snapshot = dataSnapshot("foo")
with(TestObserver.create<DataSnapshot>()) {
RxFirebaseDatabase.data(databaseReference)
.subscribe(this)
// verify addListenerForSingleValueEvent() has called
databaseReference.verifyAddListenerForSingleValueEvent()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertValue { "foo" == it.value }
dispose()
}
}
@Test
fun dataReferenceDataCancelled() {
val error = databaseError()
with(TestObserver.create<DataSnapshot>()) {
RxFirebaseDatabase.data(databaseReference)
.subscribe(this)
// verify addValueForSingleValueEvent() has called
databaseReference.verifyAddListenerForSingleValueEvent()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun dataReferenceFlowableDataChanges() {
val snapshot1 = dataSnapshot("foo")
val snapshot2 = dataSnapshot("bar")
with(TestSubscriber.create<DataSnapshot>()) {
RxFirebaseDatabase.dataChanges(databaseReference, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addValueEventListener() has called
databaseReference.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot1)
valueEventListener.lastValue.onDataChange(snapshot2)
assertNoErrors()
assertNotComplete()
assertValueAt(0) { "foo" == it.value }
assertValueAt(1) { "bar" == it.value }
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot1)
// assert no more values
assertValueCount(2)
}
}
@Test
fun dataReferenceObservableDataChanges() {
val snapshot1 = dataSnapshot("foo")
val snapshot2 = dataSnapshot("bar")
with(TestObserver.create<DataSnapshot>()) {
RxFirebaseDatabase.dataChanges(databaseReference)
.subscribe(this)
// verify addValueEventListener() has called
databaseReference.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot1)
valueEventListener.lastValue.onDataChange(snapshot2)
assertNoErrors()
assertNotComplete()
assertValueAt(0) { "foo" == it.value }
assertValueAt(1) { "bar" == it.value }
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot1)
// assert no more values
assertValueCount(2)
}
}
@Test
fun dataReferenceFlowableDataChangesCancelled() {
val error = databaseError()
with(TestSubscriber.create<DataSnapshot>()) {
RxFirebaseDatabase.dataChanges(databaseReference, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addValueEventListener() has called
databaseReference.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
// assert no more values
assertThat(errorCount())
.isEqualTo(1)
}
}
@Test
fun dataReferenceObservableDataChangesCancelled() {
val error = databaseError()
with(TestObserver.create<DataSnapshot>()) {
RxFirebaseDatabase.dataChanges(databaseReference)
.subscribe(this)
// verify addValueEventListener() has called
databaseReference.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
// assert no more values
assertThat(errorCount())
.isEqualTo(1)
}
}
@Test
fun dataReferenceFlowableDataChangesOfClazz() {
val snapshot = dataSnapshotOfClazz("foo")
with(TestSubscriber.create<DataValue<String>>()) {
RxFirebaseDatabase.dataChangesOf(databaseReference,
String::class.java, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addValueEventListener() has called
databaseReference.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertNoErrors()
assertNotComplete()
assertValueAt(0) { "foo" == it.value() }
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
// assert no more values
assertValueCount(1)
}
}
@Test
fun dataReferenceObservableDataChangesOfClazz() {
val snapshot = dataSnapshotOfClazz("foo")
with(TestObserver.create<DataValue<String>>()) {
RxFirebaseDatabase.dataChangesOf(databaseReference, String::class.java)
.subscribe(this)
// verify addValueEventListener() has called
databaseReference.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertNoErrors()
assertNotComplete()
assertValueAt(0) { "foo" == it.value() }
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
// assert no more values
assertValueCount(1)
}
}
@Test
fun dataReferenceFlowableDataChangesOfTypeIndicator() {
val ti = mock<GenericTypeIndicator<List<String>>>()
val snapshot = dataSnapshotOfTypeIndicator(listOf("foo", "bar"), ti)
with(TestSubscriber.create<DataValue<List<String>>>()) {
RxFirebaseDatabase.dataChangesOf(databaseReference, ti, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addValueEventListener() has called
databaseReference.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertNoErrors()
assertNotComplete()
assertThat(values()[0].value())
.containsExactly("foo", "bar")
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
// assert no more values
assertValueCount(1)
}
}
@Test
fun dataReferenceObservableDataChangesOfTypeIndicator() {
val ti = mock<GenericTypeIndicator<List<String>>>()
val snapshot = dataSnapshotOfTypeIndicator(listOf("foo", "bar"), ti)
with(TestObserver.create<DataValue<List<String>>>()) {
RxFirebaseDatabase.dataChangesOf(databaseReference, ti)
.subscribe(this)
// verify addValueEventListener() has called
databaseReference.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertNoErrors()
assertNotComplete()
assertThat(values()[0].value())
.containsExactly("foo", "bar")
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
// assert no more values
assertValueCount(1)
}
}
@Test
fun dataReferenceDataOfClazz() {
val snapshot = dataSnapshotOfClazz("foo")
with(TestObserver.create<String>()) {
RxFirebaseDatabase.dataOf(databaseReference, String::class.java)
.subscribe(this)
// verify addListenerForSingleValueEvent() has called
databaseReference.verifyAddListenerForSingleValueEvent()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertValue { "foo" == it }
dispose()
}
}
@Test
fun dataReferenceDataOfGenericTypeIndicator() {
val ti = mock<GenericTypeIndicator<List<String>>>()
val snapshot = dataSnapshotOfTypeIndicator(listOf("foo", "bar"), ti)
with(TestObserver.create<List<String>>()) {
RxFirebaseDatabase.dataOf(databaseReference, ti)
.subscribe(this)
// verify addListenerForSingleValueEvent() has called
databaseReference.verifyAddListenerForSingleValueEvent()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertValueCount(1)
assertThat(values()[0])
.containsExactly("foo", "bar")
dispose()
}
}
@Test
fun dataReferenceRemoveValue() {
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.removeValue(databaseReference)
.subscribe(this)
// verify removeValue() has called
verify(databaseReference, times(1))
.removeValue(completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(null, databaseReference)
assertNoErrors()
assertComplete()
dispose()
}
}
@Test
fun dataReferenceRemoveValueNotSuccessful() {
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.removeValue(databaseReference)
.subscribe(this)
// verify removeValue() has called
verify(databaseReference, times(1))
.removeValue(completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(databaseError(), databaseReference)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun dataReferenceSetPriority() {
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.setPriority(databaseReference, 1)
.subscribe(this)
// verify setPriority() has called
verify(databaseReference, times(1))
.setPriority(eq(1), completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(null, databaseReference)
assertNoErrors()
assertComplete()
dispose()
}
}
@Test
fun dataReferenceSetPriorityNotSuccessful() {
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.setPriority(databaseReference, 1)
.subscribe(this)
// verify setPriority() has called
verify(databaseReference, times(1))
.setPriority(eq(1), completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(databaseError(), databaseReference)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun dataReferenceSetValue() {
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.setValue(databaseReference, 100)
.subscribe(this)
// verify setValue() has called
verify(databaseReference, times(1))
.setValue(eq(100), completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(null, databaseReference)
assertNoErrors()
assertComplete()
dispose()
}
}
@Test
fun dataReferenceSetValueNotSuccessful() {
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.setValue(databaseReference, 100)
.subscribe(this)
// verify setValue() has called
verify(databaseReference, times(1))
.setValue(eq(100), completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(databaseError(), databaseReference)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun dataReferenceSetValueWithPriority() {
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.setValue(databaseReference, 100, 1)
.subscribe(this)
// verify setValue() has called
verify(databaseReference, times(1))
.setValue(eq(100), eq(1), completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(null, databaseReference)
assertNoErrors()
assertComplete()
dispose()
}
}
@Test
fun dataReferenceSetValueWithPriorityNotSuccessful() {
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.setValue(databaseReference, 100, 1)
.subscribe(this)
// verify setValue() has called
verify(databaseReference, times(1))
.setValue(eq(100), eq(1), completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(databaseError(), databaseReference)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun dataReferenceUpdateChildren() {
val update = mock<Map<String, Any>>()
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.updateChildren(databaseReference, update)
.subscribe(this)
// verify updateChildren() has called
verify(databaseReference, times(1))
.updateChildren(eq(update), completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(null, databaseReference)
assertNoErrors()
assertComplete()
dispose()
}
}
@Test
fun dataReferenceUpdateChildrenNotSuccessful() {
val update = mock<Map<String, Any>>()
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.updateChildren(databaseReference, update)
.subscribe(this)
// verify updateChildren() has called
verify(databaseReference, times(1))
.updateChildren(eq(update), completionListener.capture())
// simulate the callback
completionListener.lastValue.onComplete(databaseError(), databaseReference)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun dataReferenceRunTransaction() {
val snapshot = dataSnapshot("foo")
val task = mock<io.reactivex.functions.Function<MutableData, Transaction.Result>>()
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.runTransaction(databaseReference, task)
.subscribe(this)
// verify runTransaction() has called
verify(databaseReference, times(1))
.runTransaction(transactionHandler.capture(), eq(true))
// simulate the callback
transactionHandler.lastValue.doTransaction(mock())
transactionHandler.lastValue.onComplete(null, true, snapshot)
assertNoErrors()
assertComplete()
dispose()
}
}
@Test
fun dataReferenceRunTransactionNotSuccessful() {
val snapshot = dataSnapshot("foo")
val task = mock<io.reactivex.functions.Function<MutableData, Transaction.Result>>()
with(TestObserver.create<Any>()) {
RxFirebaseDatabase.runTransaction(databaseReference, task)
.subscribe(this)
// verify runTransaction() has called
verify(databaseReference, times(1))
.runTransaction(transactionHandler.capture(), eq(true))
// simulate the callback
transactionHandler.lastValue.onComplete(databaseError(), true, snapshot)
assertError(DatabaseException::class.java)
dispose()
}
}
// Bindings for Query
@Test
fun queryFlowableChildEventsAdded() {
val snapshot = mock<DataSnapshot>()
with(TestSubscriber.create<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildAdded(snapshot, "foo")
childEventListener.lastValue.onChildAdded(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildAddEvent.create(snapshot, "foo"),
ChildAddEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildAdded(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun queryObservableChildEventsAdded() {
val snapshot = mock<DataSnapshot>()
with(TestObserver.create<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildAdded(snapshot, "foo")
childEventListener.lastValue.onChildAdded(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildAddEvent.create(snapshot, "foo"),
ChildAddEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildAdded(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun queryFlowableChildEventsChanged() {
val snapshot = mock<DataSnapshot>()
with(TestSubscriber<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildChanged(snapshot, "foo")
childEventListener.lastValue.onChildChanged(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildChangeEvent.create(snapshot, "foo"),
ChildChangeEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildChanged(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun queryObservableChildEventsChanged() {
val snapshot = mock<DataSnapshot>()
with(TestObserver<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildChanged(snapshot, "foo")
childEventListener.lastValue.onChildChanged(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildChangeEvent.create(snapshot, "foo"),
ChildChangeEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildChanged(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun queryFlowableChildEventsRemoved() {
val snapshot = mock<DataSnapshot>()
with(TestSubscriber<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildRemoved(snapshot)
childEventListener.lastValue.onChildRemoved(snapshot)
assertNotComplete()
assertNoErrors()
assertValues(
ChildRemoveEvent.create(snapshot),
ChildRemoveEvent.create(snapshot))
dispose()
// simulate the callback
childEventListener.lastValue.onChildRemoved(snapshot)
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun queryObservableChildEventsRemoved() {
val snapshot = mock<DataSnapshot>()
with(TestObserver<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildRemoved(snapshot)
childEventListener.lastValue.onChildRemoved(snapshot)
assertNotComplete()
assertNoErrors()
assertValues(
ChildRemoveEvent.create(snapshot),
ChildRemoveEvent.create(snapshot))
dispose()
// simulate the callback
childEventListener.lastValue.onChildRemoved(snapshot)
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun queryFlowableChildEventsMoved() {
val snapshot = mock<DataSnapshot>()
with(TestSubscriber<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildMoved(snapshot, "foo")
childEventListener.lastValue.onChildMoved(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildMoveEvent.create(snapshot, "foo"),
ChildMoveEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildMoved(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun queryObservableChildEventsMoved() {
val snapshot = mock<DataSnapshot>()
with(TestObserver<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onChildMoved(snapshot, "foo")
childEventListener.lastValue.onChildMoved(snapshot, "bar")
assertNotComplete()
assertNoErrors()
assertValues(
ChildMoveEvent.create(snapshot, "foo"),
ChildMoveEvent.create(snapshot, "bar"))
dispose()
// simulate the callback
childEventListener.lastValue.onChildMoved(snapshot, "baz")
// assert no more values are emitted
assertValueCount(2)
}
}
@Test
fun queryFlowableChildEventsCancelled() {
val error = databaseError()
with(TestSubscriber<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun queryObservableChildEventsCancelled() {
val error = databaseError()
with(TestObserver<ChildEvent>()) {
RxFirebaseDatabase.childEvents(query)
.subscribe(this)
// verify addChildEventListener() has called
query.verifyAddChildEventListenerCalled()
// simulate the callback
childEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun queryData() {
val snapshot = mock<DataSnapshot>().apply {
whenever(value)
.thenReturn("foo")
}
with(TestObserver.create<DataSnapshot>()) {
RxFirebaseDatabase.data(query)
.subscribe(this)
// verify addListenerForSingleValueEvent() has called
query.verifyAddListenerForSingleValueEvent()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertValue { "foo" == it.value }
dispose()
}
}
@Test
fun queryDataCancelled() {
val error = databaseError()
with(TestObserver.create<DataSnapshot>()) {
RxFirebaseDatabase.data(query)
.subscribe(this)
// verify addListenerForSingleValueEvent() has called
query.verifyAddListenerForSingleValueEvent()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
}
}
@Test
fun queryFlowableDataChanges() {
val snapshot1 = dataSnapshot("foo")
val snapshot2 = dataSnapshot("bar")
with(TestSubscriber.create<DataSnapshot>()) {
RxFirebaseDatabase.dataChanges(query, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addValueEventListener() has called
query.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot1)
valueEventListener.lastValue.onDataChange(snapshot2)
assertNoErrors()
assertNotComplete()
assertValueAt(0) { "foo" == it.value }
assertValueAt(1) { "bar" == it.value }
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot1)
// assert no more values
assertValueCount(2)
}
}
@Test
fun queryObservableDataChanges() {
val snapshot1 = dataSnapshot("foo")
val snapshot2 = dataSnapshot("bar")
with(TestObserver.create<DataSnapshot>()) {
RxFirebaseDatabase.dataChanges(query)
.subscribe(this)
// verify addValueEventListener() has called
query.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot1)
valueEventListener.lastValue.onDataChange(snapshot2)
assertNoErrors()
assertNotComplete()
assertValueAt(0) { "foo" == it.value }
assertValueAt(1) { "bar" == it.value }
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot1)
// assert no more values
assertValueCount(2)
}
}
@Test
fun queryFlowableDataChangesCancelled() {
val error = databaseError()
with(TestSubscriber.create<DataSnapshot>()) {
RxFirebaseDatabase.dataChanges(query, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addValueEventListener() has called
query.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
// assert no more values
assertThat(errorCount())
.isEqualTo(1)
}
}
@Test
fun queryObservableDataChangesCancelled() {
val error = databaseError()
with(TestObserver.create<DataSnapshot>()) {
RxFirebaseDatabase.dataChanges(query)
.subscribe(this)
// verify addValueEventListener() has called
query.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
assertError(DatabaseException::class.java)
dispose()
// simulate the callback
valueEventListener.lastValue.onCancelled(error)
// assert no more values
assertThat(errorCount())
.isEqualTo(1)
}
}
@Test
fun queryFlowableDataChangesOfClazz() {
val snapshot = dataSnapshotOfClazz("foo")
with(TestSubscriber.create<DataValue<String>>()) {
RxFirebaseDatabase.dataChangesOf(query,
String::class.java, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addValueEventListener() has called
query.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertNoErrors()
assertNotComplete()
assertValueAt(0) { "foo" == it.value() }
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
// assert no more values
assertValueCount(1)
}
}
@Test
fun queryObservableDataChangesOfClazz() {
val snapshot = dataSnapshotOfClazz("foo")
with(TestObserver.create<DataValue<String>>()) {
RxFirebaseDatabase.dataChangesOf(query, String::class.java)
.subscribe(this)
// verify addValueEventListener() has called
query.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertNoErrors()
assertNotComplete()
assertValueAt(0) { "foo" == it.value() }
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
// assert no more values
assertValueCount(1)
}
}
@Test
fun queryFlowableDataChangesOfTypeIndicator() {
val ti = mock<GenericTypeIndicator<List<String>>>()
val snapshot = dataSnapshotOfTypeIndicator(listOf("foo", "bar"), ti)
with(TestSubscriber.create<DataValue<List<String>>>()) {
RxFirebaseDatabase.dataChangesOf(query, ti, BackpressureStrategy.BUFFER)
.subscribe(this)
// verify addValueEventListener() has called
query.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertNoErrors()
assertNotComplete()
assertThat(values()[0].value())
.containsExactly("foo", "bar")
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
// assert no more values
assertValueCount(1)
}
}
@Test
fun queryObservableDataChangesOfTypeIndicator() {
val ti = mock<GenericTypeIndicator<List<String>>>()
val snapshot = dataSnapshotOfTypeIndicator(listOf("foo", "bar"), ti)
with(TestObserver.create<DataValue<List<String>>>()) {
RxFirebaseDatabase.dataChangesOf(query, ti)
.subscribe(this)
// verify addValueEventListener() has called
query.verifyAddValueEventListenerCalled()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertNoErrors()
assertNotComplete()
assertThat(values()[0].value())
.containsExactly("foo", "bar")
dispose()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
// assert no more values
assertValueCount(1)
}
}
@Test
fun queryDataOfClazz() {
val snapshot = dataSnapshotOfClazz("foo")
with(TestObserver.create<String>()) {
RxFirebaseDatabase.dataOf(query, String::class.java)
.subscribe(this)
// verify addListenerForSingleValueEvent() has called
query.verifyAddListenerForSingleValueEvent()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertValue { "foo" == it }
dispose()
}
}
@Test
fun queryDataOfGenericTypeIndicator() {
val ti = mock<GenericTypeIndicator<List<String>>>()
val snapshot = dataSnapshotOfTypeIndicator(listOf("foo", "bar"), ti)
with(TestObserver.create<List<String>>()) {
RxFirebaseDatabase.dataOf(query, ti)
.subscribe(this)
// verify addListenerForSingleValueEvent() has called
query.verifyAddListenerForSingleValueEvent()
// simulate the callback
valueEventListener.lastValue.onDataChange(snapshot)
assertValueCount(1)
assertThat(values()[0])
.containsExactly("foo", "bar")
dispose()
}
}
private inline fun DatabaseReference.verifyAddChildEventListenerCalled() {
verify(this, times(1))
.addChildEventListener(childEventListener.capture())
}
private inline fun DatabaseReference.verifyAddListenerForSingleValueEvent() {
verify(this, times(1))
.addListenerForSingleValueEvent(valueEventListener.capture())
}
private inline fun DatabaseReference.verifyAddValueEventListenerCalled() {
verify(this, times(1))
.addValueEventListener(valueEventListener.capture())
}
private inline fun Query.verifyAddChildEventListenerCalled() {
verify(this, times(1))
.addChildEventListener(childEventListener.capture())
}
private inline fun Query.verifyAddListenerForSingleValueEvent() {
verify(this, times(1))
.addListenerForSingleValueEvent(valueEventListener.capture())
}
private inline fun Query.verifyAddValueEventListenerCalled() {
verify(this, times(1))
.addValueEventListener(valueEventListener.capture())
}
} | apache-2.0 | ce14983d2be93ecbe2b948008bdf2ad9 | 29.761165 | 96 | 0.604945 | 5.853553 | false | true | false | false |
Kotlin/kotlinx.serialization | formats/json/commonMain/src/kotlinx/serialization/json/JsonContentPolymorphicSerializer.kt | 1 | 5235 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.modules.*
import kotlin.reflect.*
/**
* Base class for custom serializers that allows selecting polymorphic serializer
* without a dedicated class discriminator, on a content basis.
*
* Usually, polymorphic serialization (represented by [PolymorphicSerializer] and [SealedClassSerializer])
* requires a dedicated `"type"` property in the JSON to
* determine actual serializer that is used to deserialize Kotlin class.
*
* However, sometimes (e.g. when interacting with external API) type property is not present in the input
* and it is expected to guess the actual type by the shape of JSON, for example by the presence of specific key.
* [JsonContentPolymorphicSerializer] provides a skeleton implementation for such strategy. Please note that
* since JSON content is represented by [JsonElement] class and could be read only with [JsonDecoder] decoder,
* this class works only with [Json] format.
*
* Deserialization happens in two stages: first, a value from the input JSON is read
* to as a [JsonElement]. Second, [selectDeserializer] function is called to determine which serializer should be used.
* The returned serializer is used to deserialize [JsonElement] back to Kotlin object.
*
* It is possible to serialize values this serializer. In that case, class discriminator property won't
* be added to JSON stream, i.e., deserializing a class from the string and serializing it back yields the original string.
* However, to determine a serializer, a standard polymorphic mechanism represented by [SerializersModule] is used.
* For convenience, [serialize] method can lookup default serializer, but it is recommended to follow
* standard procedure with [registering][SerializersModuleBuilder.polymorphic].
*
* Usage example:
* ```
* interface Payment {
* val amount: String
* }
*
* @Serializable
* data class SuccessfulPayment(override val amount: String, val date: String) : Payment
*
* @Serializable
* data class RefundedPayment(override val amount: String, val date: String, val reason: String) : Payment
*
* object PaymentSerializer : JsonContentPolymorphicSerializer<Payment>(Payment::class) {
* override fun selectDeserializer(content: JsonElement) = when {
* "reason" in content.jsonObject -> RefundedPayment.serializer()
* else -> SuccessfulPayment.serializer()
* }
* }
*
* // Now both statements will yield different subclasses of Payment:
*
* Json.parse(PaymentSerializer, """{"amount":"1.0","date":"03.02.2020"}""")
* Json.parse(PaymentSerializer, """{"amount":"2.0","date":"03.02.2020","reason":"complaint"}""")
* ```
*
* @param T A root class for all classes that could be possibly encountered during serialization and deserialization.
* @param baseClass A class token for [T].
*/
@OptIn(ExperimentalSerializationApi::class)
public abstract class JsonContentPolymorphicSerializer<T : Any>(private val baseClass: KClass<T>) : KSerializer<T> {
/**
* A descriptor for this set of content-based serializers.
* By default, it uses the name composed of [baseClass] simple name,
* kind is set to [PolymorphicKind.SEALED] and contains 0 elements.
*
* However, this descriptor can be overridden to achieve better representation of custom transformed JSON shape
* for schema generating/introspection purposes.
*/
override val descriptor: SerialDescriptor =
buildSerialDescriptor("JsonContentPolymorphicSerializer<${baseClass.simpleName}>", PolymorphicKind.SEALED)
final override fun serialize(encoder: Encoder, value: T) {
val actualSerializer =
encoder.serializersModule.getPolymorphic(baseClass, value)
?: value::class.serializerOrNull()
?: throwSubtypeNotRegistered(value::class, baseClass)
@Suppress("UNCHECKED_CAST")
(actualSerializer as KSerializer<T>).serialize(encoder, value)
}
final override fun deserialize(decoder: Decoder): T {
val input = decoder.asJsonDecoder()
val tree = input.decodeJsonElement()
@Suppress("UNCHECKED_CAST")
val actualSerializer = selectDeserializer(tree) as KSerializer<T>
return input.json.decodeFromJsonElement(actualSerializer, tree)
}
/**
* Determines a particular strategy for deserialization by looking on a parsed JSON [element].
*/
protected abstract fun selectDeserializer(element: JsonElement): DeserializationStrategy<out T>
private fun throwSubtypeNotRegistered(subClass: KClass<*>, baseClass: KClass<*>): Nothing {
val subClassName = subClass.simpleName ?: "$subClass"
val scope = "in the scope of '${baseClass.simpleName}'"
throw SerializationException(
"Class '${subClassName}' is not registered for polymorphic serialization $scope.\n" +
"Mark the base class as 'sealed' or register the serializer explicitly.")
}
}
| apache-2.0 | 67ec32fa1b1bfa7683b9f706519fb44d | 47.027523 | 123 | 0.72531 | 4.780822 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.