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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
msebire/intellij-community | platform/platform-impl/src/com/intellij/configurationStore/storageUtil.kt | 1 | 6283 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathMacros
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.UnknownMacroNotification
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectMacrosUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.createDirectories
import com.intellij.util.io.inputStream
import com.intellij.util.io.systemIndependentPath
import gnu.trove.THashSet
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Path
import java.util.*
const val NOTIFICATION_GROUP_ID = "Load Error"
@TestOnly
var DEBUG_LOG: String? = null
fun doNotify(macros: MutableSet<String>, project: Project, substitutorToStore: Map<TrackingPathMacroSubstitutor, IComponentStore>) {
val productName = ApplicationNamesInfo.getInstance().productName
val content = "<p><i>${macros.joinToString(", ")}</i> ${if (macros.size == 1) "is" else "are"} undefined. <a href=\"define\">Fix it</a></p>" +
"<br>Path variables are used to substitute absolute paths in " + productName + " project files " +
"and allow project file sharing in version control systems.<br>" +
"Some of the files describing the current project settings contain unknown path variables " +
"and " + productName + " cannot restore those paths."
UnknownMacroNotification(NOTIFICATION_GROUP_ID, "Load error: undefined path variables", content, NotificationType.ERROR,
{ _, _ -> checkUnknownMacros(project, true, macros, substitutorToStore) }, macros)
.notify(project)
}
fun checkUnknownMacros(project: Project, notify: Boolean) {
// use linked set/map to get stable results
val unknownMacros = LinkedHashSet<String>()
val substitutorToStore = LinkedHashMap<TrackingPathMacroSubstitutor, IComponentStore>()
collect(project, unknownMacros, substitutorToStore)
for (module in ModuleManager.getInstance(project).modules) {
collect(module, unknownMacros, substitutorToStore)
}
if (unknownMacros.isEmpty()) {
return
}
if (notify) {
doNotify(unknownMacros, project, substitutorToStore)
return
}
checkUnknownMacros(project, false, unknownMacros, substitutorToStore)
}
private fun checkUnknownMacros(project: Project,
showDialog: Boolean,
unknownMacros: MutableSet<String>,
substitutorToStore: Map<TrackingPathMacroSubstitutor, IComponentStore>) {
if (unknownMacros.isEmpty() || (showDialog && !ProjectMacrosUtil.checkMacros(project, THashSet(unknownMacros)))) {
return
}
val pathMacros = PathMacros.getInstance()
unknownMacros.removeAll { pathMacros.getValue(it).isNullOrBlank() && !pathMacros.isIgnoredMacroName(it) }
if (unknownMacros.isEmpty()) {
return
}
val notificationManager = NotificationsManager.getNotificationsManager()
for ((substitutor, store) in substitutorToStore) {
val components = substitutor.getComponents(unknownMacros)
if (store.isReloadPossible(components)) {
substitutor.invalidateUnknownMacros(unknownMacros)
for (notification in notificationManager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) {
if (unknownMacros.containsAll(notification.macros)) {
notification.expire()
}
}
store.reloadStates(components, project.messageBus)
}
else if (Messages.showYesNoDialog(project, "Component could not be reloaded. Reload project?", "Configuration Changed",
Messages.getQuestionIcon()) == Messages.YES) {
ProjectManagerEx.getInstanceEx().reloadProject(project)
}
}
}
private fun collect(componentManager: ComponentManager,
unknownMacros: MutableSet<String>,
substitutorToStore: MutableMap<TrackingPathMacroSubstitutor, IComponentStore>) {
val store = componentManager.stateStore
val substitutor = store.storageManager.macroSubstitutor as? TrackingPathMacroSubstitutor ?: return
val macros = substitutor.getUnknownMacros(null)
if (macros.isEmpty()) {
return
}
unknownMacros.addAll(macros)
substitutorToStore.put(substitutor, store)
}
fun getOrCreateVirtualFile(file: Path, requestor: Any?): VirtualFile {
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(file.systemIndependentPath)
if (virtualFile != null) {
return virtualFile
}
val parentFile = file.parent
parentFile.createDirectories()
// need refresh if the directory has just been created
val parentVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(parentFile.systemIndependentPath)
?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile))
if (ApplicationManager.getApplication().isWriteAccessAllowed) {
return parentVirtualFile.createChildData(requestor, file.fileName.toString())
}
else {
return runUndoTransparentWriteAction { parentVirtualFile.createChildData(requestor, file.fileName.toString()) }
}
}
@Throws(IOException::class)
fun readProjectNameFile(nameFile: Path): String? {
return nameFile.inputStream().reader().useLines { line -> line.firstOrNull { !it.isEmpty() }?.trim() }
} | apache-2.0 | e6ffd7a5550f26be6ca7f0ded5e22a31 | 42.944056 | 144 | 0.752029 | 4.920125 | false | false | false | false |
Aidanvii7/Toolbox | arch-viewmodel-factory/src/main/java/com/aidanvii/toolbox/arch/viewmodel/ViewModelFactory.kt | 1 | 2620 | package com.aidanvii.toolbox.arch.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.aidanvii.toolbox.unchecked
/**
* Implementation of [ViewModelProvider.Factory] that takes care of the slightly awkward generic method [ViewModelProvider.Factory.create]
*
* It removes the need for the client to manually handle the given ViewModel [Class] in an if else clause or switch statement, or perform type casting when returning.
*
* Example:
*
* Suppose you have a [ViewModel] with a non-default constructor, where the [TypedFactory] for [MyViewModel] is declared inside such as:
* ```
* class MyViewModel(val someData: String) : ViewModel() {
* class Factory() : ViewModelFactory.TypedFactory<MyViewModel> {
* override fun create() = MyViewModel("hello world")
* }
* }
* ```
* To create a [ViewModelFactory] with this [TypedFactory]:
* ```
* val factory = ViewModelFactory.Builder()
* .addTypedFactory(MyViewModel.Factory())
* .build()
* ```
*/
class ViewModelFactory private constructor(
private val classFactoryMap: Map<Class<out ViewModel>, TypedFactory<*>>
) : ViewModelProvider.Factory {
interface TypedFactory<out T : ViewModel> {
fun create(): T
}
class Builder() {
val typedFactories = mutableMapOf<Class<out ViewModel>, TypedFactory<*>>()
fun build() = ViewModelFactory(typedFactories.toMap())
}
@Suppress(unchecked)
override fun <T : ViewModel> create(viewModelClass: Class<T>): T =
classFactoryMap[viewModelClass]?.create() as? T ?: throwNoFactoryInstalled(viewModelClass)
private fun throwNoFactoryInstalled(viewModelClass: Class<*>): Nothing =
throw UnsupportedOperationException("No view-model factory installed for class: $viewModelClass")
}
inline fun <reified T : ViewModel> ViewModelFactory.Builder.addTypedFactory(factory: ViewModelFactory.TypedFactory<T>) = this.apply {
typedFactories[T::class.java] = factory
}
fun FragmentActivity.viewModelProvider(factory: ViewModelProvider.Factory? = null): ViewModelProvider =
if (factory != null) ViewModelProviders.of(this, factory) else ViewModelProviders.of(this)
fun Fragment.viewModelProvider(factory: ViewModelProvider.Factory? = null): ViewModelProvider =
if (factory != null) ViewModelProviders.of(this, factory) else ViewModelProviders.of(this)
inline fun <reified T : ViewModel> ViewModelProvider.get() = get(T::class.java) | apache-2.0 | ffc45fe4116916d440072d10564141c9 | 39.953125 | 166 | 0.738931 | 4.501718 | false | false | false | false |
Gu3pardo/PasswordSafe-AndroidClient | mobile/src/main/java/guepardoapps/passwordsafe/models/accountgroups/AccountGroup.kt | 1 | 1192 | package guepardoapps.passwordsafe.models.accountgroups
import guepardoapps.passwordsafe.annotations.CsvEntry
import guepardoapps.passwordsafe.enums.ModelState
internal class AccountGroup {
@CsvEntry(0, "Id")
lateinit var id: String
@CsvEntry(1, "Title")
lateinit var title: String
@CsvEntry(2, "Description")
lateinit var description: String
@CsvEntry(3, "UserId")
var userId: String? = null
@CsvEntry(4, "ModelState")
var modelState: ModelState = ModelState.Null
fun isSameAs(accountGroup: AccountGroup): Boolean {
return this.id == accountGroup.id
&& this.title == accountGroup.title
&& this.description == accountGroup.description
}
companion object {
fun clone(accountGroup: AccountGroup): AccountGroup {
return AccountGroup()
.apply {
id = accountGroup.id
title = accountGroup.title
description = accountGroup.description
userId = accountGroup.userId
modelState = accountGroup.modelState
}
}
}
} | mit | 1bc17a28b8acf687625dddb0ec276b68 | 28.825 | 63 | 0.599832 | 5.029536 | false | false | false | false |
debop/debop4k | debop4k-data-orm/src/main/java/debop4k/data/orm/hibernate/Criteriax.kt | 1 | 18461 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
@file:JvmName("Criteriax")
package debop4k.data.orm.hibernate
import debop4k.core.collections.fastListOf
import debop4k.core.loggerOf
import org.hibernate.Criteria
import org.hibernate.criterion.*
import org.hibernate.criterion.MatchMode.ANYWHERE
import org.hibernate.criterion.Restrictions.*
import org.springframework.data.domain.Sort
import org.springframework.data.domain.Sort.Direction.ASC
import java.util.*
private val log = loggerOf("Criteriax")
fun Sort.toOrders(): List<Order> {
val orders = fastListOf<Order>()
this.forEach {
when (it) {
ASC -> orders.add(Order.asc(it.property))
else -> orders.add(Order.desc(it.property))
}
}
return orders
}
fun String.eq(value: Any): Criterion = eq(this, value)
fun String.eqOrIsNull(value: Any): Criterion = eqOrIsNull(this, value)
fun String.ne(value: Any): Criterion = ne(this, value)
fun String.neOrIsNotNull(value: Any): Criterion = neOrIsNotNull(this, value)
fun Criterion.not(): Criterion = not(this)
fun String.gt(value: Any): Criterion = gt(this, value)
fun String.ge(value: Any): Criterion = ge(this, value)
fun String.geProperty(otherPropertyName: String): Criterion = geProperty(this, otherPropertyName)
fun String.gtProperty(otherPropertyName: String): Criterion = gtProperty(this, otherPropertyName)
@JvmOverloads
fun String.greater(value: Any, includeValue: Boolean = true): Criterion
= if (includeValue) this.ge(value) else this.gt(value)
@JvmOverloads
fun String.greaterProperty(otherPropertyName: String, includeValue: Boolean = true): Criterion
= if (includeValue) this.geProperty(otherPropertyName) else this.gtProperty(otherPropertyName)
fun String.lt(value: Any): Criterion = lt(this, value)
fun String.le(value: Any): Criterion = le(this, value)
fun String.leProperty(otherPropertyName: String): Criterion = leProperty(this, otherPropertyName)
fun String.ltProperty(otherPropertyName: String): Criterion = ltProperty(this, otherPropertyName)
@JvmOverloads
fun String.less(value: Any, includeValue: Boolean = true): Criterion
= if (includeValue) this.le(value) else this.lt(value)
@JvmOverloads
fun String.lessProperty(otherPropertyName: String, includeValue: Boolean = true): Criterion
= if (includeValue) this.leProperty(otherPropertyName) else this.ltProperty(otherPropertyName)
fun String.like(value: String, matchMode: MatchMode = ANYWHERE): Criterion = like(this, value, matchMode)
fun String.ilike(value: String, matchMode: MatchMode = ANYWHERE): Criterion = ilike(this, value, matchMode)
fun String.`in`(values: Collection<*>): Criterion = Restrictions.`in`(this, values)
fun String.`in`(vararg values: Any?): Criterion = Restrictions.`in`(this, *values)
/**
* ์์ฑ ๊ฐ์ด lo, hi ์ฌ์ด์ ๊ฐ์ธ์ง๋ฅผ ๊ฒ์ฌํ๋ ์ง์์ด
*
* @param lo ํํ ๊ฐ
* @param hi ์ํ ๊ฐ
* @param loInclude include lo value ?
* @param hiInclude include hi value ?
* @return the is between criterion
*/
@JvmOverloads
fun String.between(lo: Any?, hi: Any?, loInclude: Boolean = true, hiInclude: Boolean = true): Criterion {
if (lo == null && hi == null)
throw IllegalArgumentException("lo and hi is null both")
if (lo != null && hi != null && loInclude && hiInclude)
return between(this, lo, hi)
val conj = conjunction()
lo?.let { conj.add(this.greater(it, loInclude)) }
hi?.let { conj.add(this.less(it, hiInclude)) }
return conj
}
/**
* ์ง์ ํ ๊ฐ์ด ๋ ์์ฑ ๊ฐ ์ฌ์ด์ ์กด์ฌํ๋์ง ์ฌ๋ถ
*
* @param loPropertyName the lo property name
* @param hiPropertyName the hi property name
* @param loInclude include lo value ?
* @param hiInclude include hi value ?
* @return the is in range criterion
*/
@JvmOverloads
fun Any.inRange(loPropertyName: String,
hiPropertyName: String,
loInclude: Boolean = true,
hiInclude: Boolean = true): Criterion {
val loCriterion = loPropertyName.greater(this, loInclude)
val hiCriterion = hiPropertyName.less(this, hiInclude)
return conjunction()
.add(disjunction()
.add(isNull(loPropertyName))
.add(loCriterion))
.add(disjunction().add(isNull(hiPropertyName))
.add(hiCriterion))
}
/**
* ์ง์ ํ ๋ฒ์ ๊ฐ์ด ๋ ์์ฑ ๊ฐ ๊ตฌ๊ฐ๊ณผ ๊ฒน์น๋์ง๋ฅผ ์์๋ณด๊ธฐ ์ํ ์ง์์ด
*
* @param loProperty the lo property name
* @param hiProperty the hi property name
* @param lo the lo value
* @param hi the hi value
* @param loInclude include lo value ?
* @param hiInclude include hi value ?
* @return the is overlap criterion
*/
@JvmOverloads
fun overlap(loProperty: String,
hiProperty: String,
lo: Any?,
hi: Any?,
loInclude: Boolean = true,
hiInclude: Boolean = true): Criterion {
if (lo == null && hi == null)
throw IllegalArgumentException("์ํํ ๊ฐ ๋ชจ๋ null ์
๋๋ค.")
if (lo != null && hi != null)
return disjunction()
.add(lo.inRange(loProperty, hiProperty, loInclude, hiInclude))
.add(hi.inRange(loProperty, hiProperty, loInclude, hiInclude))
.add(loProperty.between(lo, hi, loInclude, hiInclude))
.add(hiProperty.between(lo, hi, loInclude, hiInclude))
lo?.let {
return disjunction()
.add(it.inRange(loProperty, hiProperty, loInclude, hiInclude))
.add(loProperty.less(it, loInclude))
.add(hiProperty.greater(it, loInclude))
}
hi?.let {
return disjunction()
.add(it.inRange(loProperty, hiProperty, loInclude, hiInclude))
.add(loProperty.less(it, hiInclude))
.add(hiProperty.greater(it, hiInclude))
}
?: throw IllegalArgumentException("์ํํ ๊ฐ ๋ชจ๋ null ์
๋๋ค.")
}
fun String.eqIncludeNull(value: Any?): Criterion
= if (value == null) isNull(this) else eqOrIsNull(this, value)
@JvmOverloads
fun String.insensitiveLikeIncludeNull(value: String?,
matchMode: MatchMode = MatchMode.ANYWHERE): Criterion {
if (value.isNullOrBlank())
return isEmpty(this)
return disjunction()
.add(ilike(this, value, matchMode))
.add(isEmpty(this))
}
//
//
// Criteria
//
//
fun Criteria.addEq(propertyName: String, value: Any): Criteria = this.add(propertyName.eq(value))
fun Criteria.addEqOrIsNull(propertyName: String, value: Any): Criteria = this.add(propertyName.eqOrIsNull(value))
fun Criteria.addNe(propertyName: String, value: Any): Criteria = this.add(propertyName.ne(value))
fun Criteria.addNeOrIsNotNull(propertyName: String, value: Any): Criteria = this.add(propertyName.neOrIsNotNull(value))
fun Criteria.addGe(propertyName: String, value: Any): Criteria = this.add(propertyName.ge(value))
fun Criteria.addGt(propertyName: String, value: Any): Criteria = this.add(propertyName.gt(value))
@JvmOverloads
fun Criteria.addGreater(propertyName: String, value: Any, includeValue: Boolean = true): Criteria
= this.add(propertyName.greater(value, includeValue))
fun Criteria.addGeProperty(propertyName: String, otherPropertyName: String): Criteria
= this.add(propertyName.geProperty(otherPropertyName))
fun Criteria.addGtProperty(propertyName: String, otherPropertyName: String): Criteria
= this.add(propertyName.gtProperty(otherPropertyName))
@JvmOverloads
fun Criteria.addGreaterProperty(propertyName: String, otherPropertyName: String, includeValue: Boolean = true): Criteria
= add(propertyName.greaterProperty(otherPropertyName, includeValue))
fun Criteria.addLe(propertyName: String, value: Any): Criteria
= this.add(propertyName.le(value))
fun Criteria.addLt(propertyName: String, value: Any): Criteria
= this.add(propertyName.lt(value))
@JvmOverloads
fun Criteria.addLess(propertyName: String, value: Any, includeValue: Boolean = true): Criteria
= add(propertyName.less(value, includeValue))
fun Criteria.addLeProperty(propertyName: String, otherPropertyName: String): Criteria
= this.add(propertyName.leProperty(otherPropertyName))
fun Criteria.addLtProperty(propertyName: String, otherPropertyName: String): Criteria
= this.add(propertyName.ltProperty(otherPropertyName))
@JvmOverloads
fun Criteria.addLessProperty(propertyName: String, otherPropertyName: String, includeValue: Boolean = true): Criteria
= add(propertyName.lessProperty(otherPropertyName, includeValue))
fun Criteria.addAllEq(propertyValues: Map<String, Any?>): Criteria = add(allEq(propertyValues))
fun Criteria.addIsEmpty(propertyName: String): Criteria = add(isEmpty(propertyName))
fun Criteria.addIsNull(propertyName: String): Criteria = add(isNull(propertyName))
fun Criteria.addIsNotEmpty(propertyName: String): Criteria = add(isNotEmpty(propertyName))
fun Criteria.addIsNotNull(propertyName: String): Criteria = add(isNotNull(propertyName))
@JvmOverloads
fun Criteria.addLike(propertyName: String, value: String, matchMode: MatchMode = ANYWHERE): Criteria
= add(propertyName.like(value, matchMode))
@JvmOverloads
fun Criteria.addIlike(propertyName: String, value: String, matchMode: MatchMode = ANYWHERE): Criteria
= add(propertyName.ilike(value, matchMode))
fun Criteria.addIn(propertyName: String, values: Collection<*>): Criteria = add(propertyName.`in`(values))
fun Criteria.addIn(propertyName: String, vararg values: Any?): Criteria = add(propertyName.`in`(*values))
@JvmOverloads
fun Criteria.addBetween(propertyName: String,
lo: Any?,
hi: Any?,
loInclude: Boolean = true,
hiInclude: Boolean = true): Criteria
= add(propertyName.between(lo, hi, loInclude, hiInclude))
@JvmOverloads
fun Criteria.addInRange(loPropertyName: String,
hiPropertyName: String,
value: Any,
loInclude: Boolean = true,
hiInclude: Boolean = true): Criteria
= add(value.inRange(loPropertyName, hiPropertyName, loInclude, hiInclude))
@JvmOverloads
fun Criteria.addOverlap(loPropertyName: String,
hiPropertyName: String,
lo: Any?,
hi: Any?,
loInclude: Boolean = true,
hiInclude: Boolean = true): Criteria
= add(overlap(loPropertyName, hiPropertyName, lo, hi, loInclude, hiInclude))
fun Criteria.addElapsed(propertyName: String, moment: Date): Criteria = add(propertyName.lt(moment))
fun Criteria.addElapsedOrEquals(propertyName: String, moment: Date): Criteria = add(propertyName.le(moment))
fun Criteria.addFutures(propertyName: String, moment: Date): Criteria = add(propertyName.gt(moment))
fun Criteria.addFuturesOrEquals(propertyName: String, moment: Date): Criteria = add(propertyName.ge(moment))
/**
* ์์ฑ ๊ฐ์ด null์ธ ๊ฒฝ์ฐ๋ false๋ก ๊ฐ์ฃผํ๊ณ , value์ ๊ฐ์ ๊ฐ์ ๊ฐ์ง๋ ์ง์์ด๋ฅผ ์ถ๊ฐํฉ๋๋ค.
* @param propertyName ์์ฑ๋ช
* @param value ์ง์ ํ ๊ฐ
* @return Criteria instance.
*/
fun Criteria.addNullAsFalse(propertyName: String, value: Boolean?): Criteria {
if (value == null || value == true)
return addEq(propertyName, true)
return addEqOrIsNull(propertyName, false)
}
/**
* ์์ฑ ๊ฐ์ด null์ธ ๊ฒฝ์ฐ๋ true๋ก ๊ฐ์ฃผํ๊ณ , value์ ๊ฐ์ ๊ฐ์ ๊ฐ์ง๋ ์ง์์ด๋ฅผ ์ถ๊ฐํฉ๋๋ค.
* @param propertyName ์์ฑ๋ช
* @param value ์ง์ ํ ๊ฐ
* @return Criteria instance.
*/
fun Criteria.addNullAsTrue(propertyName: String, value: Boolean?): Criteria {
if (value == null || value == true)
return addEq(propertyName, true)
return addEqOrIsNull(propertyName, true)
}
fun Criteria.addNot(expr: Criterion): Criteria = add(expr.not())
//
//
// DetachedCriteria
//
//
fun DetachedCriteria.addEq(propertyName: String, value: Any): DetachedCriteria = this.add(propertyName.eq(value))
fun DetachedCriteria.addEqOrIsNull(propertyName: String, value: Any): DetachedCriteria = this.add(propertyName.eqOrIsNull(value))
fun DetachedCriteria.addNe(propertyName: String, value: Any): DetachedCriteria = this.add(propertyName.ne(value))
fun DetachedCriteria.addNeOrIsNotNull(propertyName: String, value: Any): DetachedCriteria = this.add(propertyName.neOrIsNotNull(value))
fun DetachedCriteria.addGe(propertyName: String, value: Any): DetachedCriteria = this.add(propertyName.ge(value))
fun DetachedCriteria.addGt(propertyName: String, value: Any): DetachedCriteria = this.add(propertyName.gt(value))
@JvmOverloads
fun DetachedCriteria.addGreater(propertyName: String, value: Any, includeValue: Boolean = true): DetachedCriteria
= this.add(propertyName.greater(value, includeValue))
fun DetachedCriteria.addGeProperty(propertyName: String, otherPropertyName: String): DetachedCriteria
= this.add(propertyName.geProperty(otherPropertyName))
fun DetachedCriteria.addGtProperty(propertyName: String, otherPropertyName: String): DetachedCriteria
= this.add(propertyName.gtProperty(otherPropertyName))
@JvmOverloads
fun DetachedCriteria.addGreaterProperty(propertyName: String, otherPropertyName: String, includeValue: Boolean = true): DetachedCriteria
= add(propertyName.greaterProperty(otherPropertyName, includeValue))
fun DetachedCriteria.addLe(propertyName: String, value: Any): DetachedCriteria
= this.add(propertyName.le(value))
fun DetachedCriteria.addLt(propertyName: String, value: Any): DetachedCriteria
= this.add(propertyName.lt(value))
@JvmOverloads
fun DetachedCriteria.addLess(propertyName: String, value: Any, includeValue: Boolean = true): DetachedCriteria
= add(propertyName.less(value, includeValue))
fun DetachedCriteria.addLeProperty(propertyName: String, otherPropertyName: String): DetachedCriteria
= this.add(propertyName.leProperty(otherPropertyName))
fun DetachedCriteria.addLtProperty(propertyName: String, otherPropertyName: String): DetachedCriteria
= this.add(propertyName.ltProperty(otherPropertyName))
@JvmOverloads
fun DetachedCriteria.addLessProperty(propertyName: String, otherPropertyName: String, includeValue: Boolean = true): DetachedCriteria
= add(propertyName.lessProperty(otherPropertyName, includeValue))
fun DetachedCriteria.addAllEq(propertyValues: Map<String, Any?>): DetachedCriteria = add(allEq(propertyValues))
fun DetachedCriteria.addIsEmpty(propertyName: String): DetachedCriteria = add(isEmpty(propertyName))
fun DetachedCriteria.addIsNull(propertyName: String): DetachedCriteria = add(isNull(propertyName))
fun DetachedCriteria.addIsNotEmpty(propertyName: String): DetachedCriteria = add(isNotEmpty(propertyName))
fun DetachedCriteria.addIsNotNull(propertyName: String): DetachedCriteria = add(isNotNull(propertyName))
@JvmOverloads
fun DetachedCriteria.addLike(propertyName: String, value: String, matchMode: MatchMode = ANYWHERE): DetachedCriteria
= add(propertyName.like(value, matchMode))
@JvmOverloads
fun DetachedCriteria.addIlike(propertyName: String, value: String, matchMode: MatchMode = ANYWHERE): DetachedCriteria
= add(propertyName.ilike(value, matchMode))
fun DetachedCriteria.addIn(propertyName: String, values: Collection<*>): DetachedCriteria = add(propertyName.`in`(values))
fun DetachedCriteria.addIn(propertyName: String, vararg values: Any?): DetachedCriteria = add(propertyName.`in`(*values))
@JvmOverloads
fun DetachedCriteria.addBetween(propertyName: String,
lo: Any?,
hi: Any?,
loInclude: Boolean = true,
hiInclude: Boolean = true): DetachedCriteria
= add(propertyName.between(lo, hi, loInclude, hiInclude))
@JvmOverloads
fun DetachedCriteria.addInRange(loPropertyName: String,
hiPropertyName: String,
value: Any,
loInclude: Boolean = true,
hiInclude: Boolean = true): DetachedCriteria
= add(value.inRange(loPropertyName, hiPropertyName, loInclude, hiInclude))
@JvmOverloads
fun DetachedCriteria.addOverlap(loPropertyName: String,
hiPropertyName: String,
lo: Any?,
hi: Any?,
loInclude: Boolean = true,
hiInclude: Boolean = true): DetachedCriteria
= add(overlap(loPropertyName, hiPropertyName, lo, hi, loInclude, hiInclude))
fun DetachedCriteria.addElapsed(propertyName: String, moment: Date) = add(propertyName.lt(moment))
fun DetachedCriteria.addElapsedOrEquals(propertyName: String, moment: Date) = add(propertyName.le(moment))
fun DetachedCriteria.addFutures(propertyName: String, moment: Date) = add(propertyName.gt(moment))
fun DetachedCriteria.addFuturesOrEquals(propertyName: String, moment: Date) = add(propertyName.ge(moment))
/**
* ์์ฑ ๊ฐ์ด null์ธ ๊ฒฝ์ฐ๋ false๋ก ๊ฐ์ฃผํ๊ณ , value์ ๊ฐ์ ๊ฐ์ ๊ฐ์ง๋ ์ง์์ด๋ฅผ ์ถ๊ฐํฉ๋๋ค.
* @param propertyName ์์ฑ๋ช
* @param value ์ง์ ํ ๊ฐ
* @return DetachedCriteria instance.
*/
fun DetachedCriteria.addNullAsFalse(propertyName: String, value: Boolean?): DetachedCriteria {
if (value == null || value == true)
return addEq(propertyName, true)
return addEqOrIsNull(propertyName, false)
}
/**
* ์์ฑ ๊ฐ์ด null์ธ ๊ฒฝ์ฐ๋ true๋ก ๊ฐ์ฃผํ๊ณ , value์ ๊ฐ์ ๊ฐ์ ๊ฐ์ง๋ ์ง์์ด๋ฅผ ์ถ๊ฐํฉ๋๋ค.
* @param propertyName ์์ฑ๋ช
* @param value ์ง์ ํ ๊ฐ
* @return DetachedCriteria instance.
*/
fun DetachedCriteria.addNullAsTrue(propertyName: String, value: Boolean?): DetachedCriteria {
if (value == null || value == true)
return addEq(propertyName, true)
return addEqOrIsNull(propertyName, true)
}
fun DetachedCriteria.addNot(expr: Criterion): DetachedCriteria = add(expr.not())
| apache-2.0 | 6a439c1d1bdb7be602bb7d0726d7eb70 | 39.786848 | 136 | 0.719964 | 3.965388 | false | false | false | false |
ntlv/BasicLauncher2 | app/src/main/java/se/ntlv/basiclauncher/packagehandling/PackageManagerObserver.kt | 1 | 1416 | package se.ntlv.basiclauncher.packagehandling
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import se.ntlv.basiclauncher.tag
class PackageManagerObserver : BroadcastReceiver() {
val TAG = tag()
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("PackageManagerObserver", "Received intent $intent")
val isReplacing = intent != null && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)
if (isReplacing || context == null) {
return
}
val packageName = intent!!.dataString
val strippedPackageName = packageName.substringAfter(':')
if (strippedPackageName == packageName) {
Log.e(TAG, "Unable to parse package name of $packageName")
return
}
val action = intent.action
when (action) {
Intent.ACTION_PACKAGE_ADDED ->
AppChangeLoggerService.logPackageInstall(context, strippedPackageName)
Intent.ACTION_PACKAGE_REMOVED ->
AppChangeLoggerService.logPackageRemove(context, strippedPackageName)
Intent.ACTION_PACKAGE_CHANGED ->
AppChangeLoggerService.logPackageChanged(context, strippedPackageName)
else ->
Log.d("PackageManagerObserver", "Undefined action $action")
}
}
}
| mit | 69958025677fddd9100afa3810e5d5e4 | 36.263158 | 97 | 0.660311 | 5.075269 | false | false | false | false |
tasks/tasks | app/src/googleplay/java/org/tasks/play/PlayServices.kt | 1 | 1410 | package org.tasks.play
import android.app.Activity
import android.content.Context
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability.getInstance
import com.google.android.play.core.ktx.launchReview
import com.google.android.play.core.ktx.requestReview
import com.google.android.play.core.review.ReviewManagerFactory
import com.todoroo.andlib.utility.DateUtilities.now
import dagger.hilt.android.qualifiers.ApplicationContext
import org.tasks.R
import org.tasks.analytics.Firebase
import org.tasks.preferences.Preferences
import javax.inject.Inject
class PlayServices @Inject constructor(
@ApplicationContext private val context: Context,
private val preferences: Preferences,
private val firebase: Firebase,
) {
fun isAvailable() =
getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
suspend fun requestReview(activity: Activity) {
if (firebase.reviewCooldown) {
return
}
try {
with(ReviewManagerFactory.create(context)) {
val request = requestReview()
launchReview(activity, request)
preferences.lastReviewRequest = now()
firebase.logEvent(R.string.event_request_review)
}
} catch (e: Exception) {
firebase.reportException(e)
}
}
} | gpl-3.0 | 5d4c3cff5fc127c98b38ff22812e7b23 | 34.275 | 88 | 0.720567 | 4.607843 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/fields/DoubleSliderField.kt | 1 | 2534 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.parameters.fields
import javafx.geometry.Orientation
import javafx.scene.Node
import javafx.scene.control.Label
import javafx.scene.control.Slider
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import uk.co.nickthecoder.paratask.parameters.DoubleParameter
class DoubleSliderField(val doubleParameter: DoubleParameter, val sliderInfo: DoubleParameter.SliderInfo)
: ParameterField(doubleParameter) {
var slider: Slider? = null
override fun createControl(): Node {
val slider = Slider(
doubleParameter.minValue,
doubleParameter.maxValue,
doubleParameter.value ?: doubleParameter.minValue)
slider.blockIncrement = sliderInfo.blockIncrement.toDouble()
slider.majorTickUnit = sliderInfo.majorTickUnit.toDouble()
slider.minorTickCount = sliderInfo.minorTickCount
slider.orientation = if (sliderInfo.horizontal) Orientation.HORIZONTAL else Orientation.VERTICAL
slider.isSnapToTicks = sliderInfo.snapToTicks
slider.isShowTickMarks = true
slider.valueProperty().addListener { _, _, newValue ->
doubleParameter.value = newValue.toDouble()
}
this.slider = slider
if (sliderInfo.showValue) {
val valueLabel = Label()
valueLabel.textProperty().bindBidirectional(doubleParameter.valueProperty, doubleParameter.converter)
if (sliderInfo.horizontal) {
val box = HBox()
box.styleClass.add("box-group")
box.children.addAll(slider, valueLabel)
return box
} else {
val box = VBox()
box.children.addAll(slider, valueLabel)
return box
}
} else {
return slider
}
}
}
| gpl-3.0 | 989d3107dad3879b2416ec2360809d8f | 34.194444 | 113 | 0.68824 | 4.745318 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/metrics/NotificationsMetrics.kt | 1 | 1529 | package net.nemerosa.ontrack.extension.notifications.metrics
/**
* Names of the metrics for the notifications.
*/
object NotificationsMetrics {
/**
* Prefix for all metric names
*/
private const val prefix = "ontrack_extension_notifications"
const val event_listening_received = "${prefix}_event_listening_received"
const val event_listening_queued = "${prefix}_event_listening_queued"
const val event_listening_dequeued = "${prefix}_event_listening_dequeued"
const val event_listening_dequeued_error = "${prefix}_event_listening_dequeued_error"
const val event_listening = "${prefix}_event_listening"
const val event_dispatching_queued = "${prefix}_event_dispatching_queued"
const val event_dispatching_dequeued = "${prefix}_event_dispatching_dequeued"
const val event_dispatching_result = "${prefix}_event_dispatching_result"
const val event_processing_started = "${prefix}_event_processing_started"
const val event_processing_channel_started = "${prefix}_event_processing_channel_started"
const val event_processing_channel_unknown = "${prefix}_event_processing_channel_unknown"
const val event_processing_channel_invalid = "${prefix}_event_processing_channel_invalid"
const val event_processing_channel_publishing = "${prefix}_event_processing_channel_publishing"
const val event_processing_channel_result = "${prefix}_event_processing_channel_result"
const val event_processing_channel_error = "${prefix}_event_processing_channel_error"
} | mit | 50cffaa5b10dfc3293bb399e3b9688fe | 48.354839 | 99 | 0.743623 | 4.189041 | false | false | false | false |
nemerosa/ontrack | ontrack-repository-impl/src/main/java/net/nemerosa/ontrack/repository/EntityDataStoreJdbcRepository.kt | 1 | 20779 | package net.nemerosa.ontrack.repository
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.json.JsonUtils
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.Signature
import net.nemerosa.ontrack.repository.support.AbstractJdbcRepository
import net.nemerosa.ontrack.repository.support.store.*
import org.apache.commons.lang3.StringUtils
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.stereotype.Repository
import java.sql.ResultSet
import java.sql.SQLException
import java.time.LocalDateTime
import java.util.*
import java.util.function.Consumer
import java.util.stream.Collectors
import javax.sql.DataSource
@Repository
class EntityDataStoreJdbcRepository(
dataSource: DataSource,
) : AbstractJdbcRepository(dataSource), EntityDataStore {
override fun add(
entity: ProjectEntity,
category: String,
name: String,
signature: Signature,
groupName: String?,
data: JsonNode,
): EntityDataStoreRecord {
val id = dbCreate(String.format(
"INSERT INTO ENTITY_DATA_STORE(%s, CATEGORY, NAME, GROUPID, JSON, CREATION, CREATOR) VALUES (:entityId, :category, :name, :groupId, :json, :creation, :creator)",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
.addValue("name", name)
.addValue("groupId", groupName)
.addValue("json", writeJson(data))
.addValue("creation", dateTimeForDB(signature.time))
.addValue("creator", signature.user.name)
)
// Audit
audit(EntityDataStoreRecordAuditType.CREATED, id, signature)
// OK
return EntityDataStoreRecord(
id,
entity,
category,
name,
groupName,
signature,
data
)
}
override fun replaceOrAdd(
entity: ProjectEntity,
category: String,
name: String,
signature: Signature,
groupName: String?,
data: JsonNode,
): EntityDataStoreRecord { // Gets the last ID by category and name
val id = getFirstItem(String.format(
"SELECT ID FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category " +
"AND NAME = :name " +
"ORDER BY ID DESC " +
"LIMIT 1",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
.addValue("name", name),
Int::class.java
)
// Existing record
return if (id != null) {
namedParameterJdbcTemplate!!.update(
"UPDATE ENTITY_DATA_STORE SET " +
"CREATION = :creation, " +
"CREATOR = :creator, " +
"JSON = :json, " +
"GROUPID = :groupId " +
"WHERE ID = :id",
params("id", id)
.addValue("groupId", groupName)
.addValue("json", writeJson(data))
.addValue("creation", dateTimeForDB(signature.time))
.addValue("creator", signature.user.name)
)
audit(EntityDataStoreRecordAuditType.UPDATED, id, signature)
EntityDataStoreRecord(
id,
entity,
category,
name,
groupName,
signature,
data
)
} else {
add(entity, category, name, signature, groupName, data)
}
}
override fun getRecordAudit(id: Int): List<EntityDataStoreRecordAudit> {
return namedParameterJdbcTemplate!!.query(
"SELECT * FROM ENTITY_DATA_STORE_AUDIT " +
"WHERE RECORD_ID = :recordId " +
"ORDER BY ID DESC",
params("recordId", id)
) { rs: ResultSet, _: Int ->
EntityDataStoreRecordAudit(
EntityDataStoreRecordAuditType.valueOf(rs.getString("AUDIT_TYPE")),
readSignature(rs, "TIMESTAMP", "CREATOR")
)
}
}
override fun deleteByName(entity: ProjectEntity, category: String, name: String) {
namedParameterJdbcTemplate!!.update(String.format(
"DELETE FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category " +
"AND NAME = :name",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
.addValue("name", name)
)
}
override fun deleteByGroup(entity: ProjectEntity, category: String, groupName: String) {
namedParameterJdbcTemplate!!.update(String.format(
"DELETE FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category " +
"AND GROUPID = :groupId",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
.addValue("groupId", groupName)
)
}
override fun deleteByCategoryBefore(category: String, beforeTime: LocalDateTime) {
namedParameterJdbcTemplate!!.update(
"DELETE FROM ENTITY_DATA_STORE " +
"WHERE CATEGORY = :category " +
"AND CREATION <= :beforeTime",
params("category", category)
.addValue("beforeTime", dateTimeForDB(beforeTime))
)
}
override fun findLastByCategoryAndName(
entity: ProjectEntity,
category: String,
name: String,
beforeTime: LocalDateTime?,
): Optional<EntityDataStoreRecord> { // SQL & parameters
var sql = String.format(
"SELECT * FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId AND CATEGORY = :category AND NAME = :name ",
entity.projectEntityType.name
)
var params = params("entityId", entity.id())
.addValue("category", category)
.addValue("name", name)
// Time criteria
if (beforeTime != null) {
sql += "AND CREATION <= :beforeTime "
params = params.addValue("beforeTime", dateTimeForDB(beforeTime))
}
// Ordering
sql += "ORDER BY CREATION DESC, ID DESC LIMIT 1"
// Performs the query
return getOptional(
sql,
params
) { rs: ResultSet, _: Int -> toEntityDataStoreRecord(entity, rs) }
}
override fun findLastByCategoryAndGroupAndName(
entity: ProjectEntity,
category: String,
groupName: String,
name: String,
): Optional<EntityDataStoreRecord> {
return getLastByName(
namedParameterJdbcTemplate!!.query(String.format(
"SELECT * FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category " +
"AND GROUPID = :groupId " +
"AND NAME = :name",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
.addValue("groupId", groupName)
.addValue("name", name)
) { rs: ResultSet, _: Int -> toEntityDataStoreRecord(entity, rs) }
).stream().findFirst()
}
override fun findLastRecordsByNameInCategory(entity: ProjectEntity, category: String): List<EntityDataStoreRecord> {
return getLastByName(
namedParameterJdbcTemplate!!.query(String.format(
"SELECT * FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category " +
"ORDER BY CREATION DESC, ID DESC",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
) { rs: ResultSet, _: Int -> toEntityDataStoreRecord(entity, rs) }
)
}
private fun getLastByName(entries: List<EntityDataStoreRecord>): List<EntityDataStoreRecord> {
return entries.stream()
.collect(Collectors.groupingBy { obj: EntityDataStoreRecord -> obj.name }) // Gets each list separately
.values.stream() // Sorts each list from the newest to the oldest
.map { list: List<EntityDataStoreRecord?> ->
list.stream()
.sorted(Comparator.naturalOrder())
.findFirst()
} // Gets only the non empty lists
.filter { obj: Optional<EntityDataStoreRecord?> -> obj.isPresent }
.map { obj: Optional<EntityDataStoreRecord?> -> obj.get() }
.sorted(Comparator.naturalOrder())
.collect(Collectors.toList())
}
@Throws(SQLException::class)
private fun toEntityDataStoreRecord(entity: ProjectEntity?, rs: ResultSet): EntityDataStoreRecord {
return EntityDataStoreRecord(
rs.getInt("ID"),
entity,
rs.getString("CATEGORY"),
rs.getString("NAME"),
rs.getString("GROUPID"),
readSignature(rs),
readJson(rs, "JSON")
)
}
override fun addObject(
entity: ProjectEntity,
category: String,
name: String,
signature: Signature,
groupName: String?,
data: Any,
): EntityDataStoreRecord {
return add(
entity,
category,
name,
signature,
groupName,
JsonUtils.format(data)
)
}
override fun replaceOrAddObject(
entity: ProjectEntity,
category: String,
name: String,
signature: Signature,
groupName: String?,
data: Any,
): EntityDataStoreRecord {
return replaceOrAdd(
entity,
category,
name,
signature,
groupName,
JsonUtils.format(data)
)
}
override fun getById(entity: ProjectEntity, id: Int): Optional<EntityDataStoreRecord> {
return getOptional(String.format(
"SELECT * FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND ID = :id",
entity.projectEntityType.name
),
params("id", id).addValue("entityId", entity.id())
) { rs: ResultSet, _: Int -> toEntityDataStoreRecord(entity, rs) }
}
override fun getByCategoryAndName(
entity: ProjectEntity,
category: String,
name: String,
offset: Int,
page: Int,
): List<EntityDataStoreRecord> {
return namedParameterJdbcTemplate!!.query(String.format(
"SELECT * FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category " +
"AND NAME = :name " +
"ORDER BY CREATION DESC, ID DESC " +
"LIMIT :page OFFSET :offset",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
.addValue("name", name)
.addValue("offset", offset)
.addValue("page", page)
) { rs: ResultSet, _: Int -> toEntityDataStoreRecord(entity, rs) }
}
override fun getByCategory(
entity: ProjectEntity,
category: String,
offset: Int,
page: Int,
): List<EntityDataStoreRecord> {
return namedParameterJdbcTemplate!!.query(String.format(
"SELECT * FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category " +
"ORDER BY CREATION DESC, ID DESC " +
"LIMIT :page OFFSET :offset",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
.addValue("offset", offset)
.addValue("page", page)
) { rs: ResultSet, _: Int -> toEntityDataStoreRecord(entity, rs) }
}
override fun getCountByCategoryAndName(entity: ProjectEntity, category: String, name: String): Int {
return namedParameterJdbcTemplate!!.queryForObject(String.format(
"SELECT COUNT(*) FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category " +
"AND NAME = :name ",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category)
.addValue("name", name),
Int::class.java
) ?: 0
}
override fun getCountByCategory(entity: ProjectEntity, category: String): Int {
return namedParameterJdbcTemplate!!.queryForObject(String.format(
"SELECT COUNT(*) FROM ENTITY_DATA_STORE " +
"WHERE %s = :entityId " +
"AND CATEGORY = :category ",
entity.projectEntityType.name
),
params("entityId", entity.id())
.addValue("category", category),
Int::class.java
) ?: 0
}
override fun deleteAll() {
jdbcTemplate!!.update(
"DELETE FROM ENTITY_DATA_STORE"
)
}
override fun getByFilter(entityDataStoreFilter: EntityDataStoreFilter): List<EntityDataStoreRecord> {
// Checks the entity
requireNotNull(entityDataStoreFilter.entity) { "The filter `entity` parameter is required." }
// SQL criterias
val context = StringBuilder()
val critera = StringBuilder()
val params = MapSqlParameterSource()
buildCriteria(entityDataStoreFilter, context, critera, params)
// Runs the query
return namedParameterJdbcTemplate!!.query(
"""
SELECT *
FROM ENTITY_DATA_STORE
$context
WHERE 1 = 1
$critera
ORDER BY CREATION DESC, ID DESC
LIMIT :page OFFSET :offset""",
params
.addValue("offset", entityDataStoreFilter.offset)
.addValue("page", entityDataStoreFilter.count)
) { rs: ResultSet, _: Int -> toEntityDataStoreRecord(entityDataStoreFilter.entity, rs) }
}
override fun forEachByFilter(
entityDataStoreFilter: EntityDataStoreFilter,
consumer: Consumer<EntityDataStoreRecord>,
) {
// Checks the entity
requireNotNull(entityDataStoreFilter.entity) { "The filter `entity` parameter is required." }
// SQL criterias
val context = StringBuilder()
val critera = StringBuilder()
val params = MapSqlParameterSource()
buildCriteria(entityDataStoreFilter, context, critera, params)
// Runs the query
namedParameterJdbcTemplate!!.query(
"""
SELECT *
FROM ENTITY_DATA_STORE
$context
WHERE 1 = 1
$critera
ORDER BY CREATION DESC, ID DESC
LIMIT :page OFFSET :offset""",
params
.addValue("offset", entityDataStoreFilter.offset)
.addValue("page", entityDataStoreFilter.count)
) { rs: ResultSet, _: Int ->
val record = toEntityDataStoreRecord(entityDataStoreFilter.entity, rs)
consumer.accept(record)
}
}
override fun getCountByFilter(entityDataStoreFilter: EntityDataStoreFilter): Int {
// SQL criterias
val context = StringBuilder()
val critera = StringBuilder()
val params = MapSqlParameterSource()
buildCriteria(entityDataStoreFilter, context, critera, params)
// Runs the query
return namedParameterJdbcTemplate!!.queryForObject(String.format(
"SELECT COUNT(*) FROM ENTITY_DATA_STORE " +
"$context " +
"WHERE 1 = 1 " +
" %s " +
"LIMIT :page OFFSET :offset",
critera
),
params
.addValue("offset", entityDataStoreFilter.offset)
.addValue("page", entityDataStoreFilter.count),
Int::class.java
) ?: 0
}
override fun deleteByFilter(entityDataStoreFilter: EntityDataStoreFilter): Int { // SQL criterias
val context = StringBuilder()
val critera = StringBuilder()
val params = MapSqlParameterSource()
buildCriteria(entityDataStoreFilter, context, critera, params)
// Runs the query
return namedParameterJdbcTemplate!!.update(
"DELETE FROM ENTITY_DATA_STORE $context WHERE 1 = 1 $critera",
params
)
}
override fun deleteRangeByFilter(entityDataStoreFilter: EntityDataStoreFilter): Int { // SQL criterias
val critera = StringBuilder()
val context = StringBuilder()
val params = MapSqlParameterSource()
buildCriteria(entityDataStoreFilter, context, critera, params)
// Runs the query
return namedParameterJdbcTemplate!!.update("""
DELETE FROM ENTITY_DATA_STORE
WHERE ctid IN (
SELECT ctid
FROM ENTITY_DATA_STORE
$context
WHERE 1 = 1
$critera
ORDER BY ID DESC
LIMIT :page OFFSET :offset
)
""",
params
.addValue("offset", entityDataStoreFilter.offset)
.addValue("page", entityDataStoreFilter.count)
)
}
private fun buildCriteria(
filter: EntityDataStoreFilter,
context: StringBuilder,
criteria: StringBuilder,
params: MapSqlParameterSource,
) { // Entity
if (filter.entity != null) {
criteria.append(String.format(" AND %s = :entityId", filter.entity!!.projectEntityType.name))
params.addValue("entityId", filter.entity!!.id())
}
// Category
if (StringUtils.isNotBlank(filter.category)) {
criteria.append(" AND CATEGORY = :category")
params.addValue("category", filter.category)
}
// Name
if (StringUtils.isNotBlank(filter.name)) {
criteria.append(" AND NAME = :name")
params.addValue("name", filter.name)
}
// Group
if (StringUtils.isNotBlank(filter.group)) {
criteria.append(" AND GROUPID = :group")
params.addValue("group", filter.group)
}
// Before time
if (filter.beforeTime != null) {
criteria.append(" AND CREATION <= :beforeTime")
params.addValue("beforeTime", dateTimeForDB(filter.beforeTime))
}
// Creator
val creator = filter.creator
if (!creator.isNullOrBlank()) {
criteria.append(" AND CREATOR = :creator")
params.addValue("creator", creator)
}
// JSON context
if (!filter.jsonContext.isNullOrBlank()) {
context.append(filter.jsonContext)
}
// JSON filter
if (!filter.jsonFilter.isNullOrBlank()) {
criteria.append(" AND ${filter.jsonFilter}")
filter.jsonFilterCriterias?.onEach { (name, value) ->
params.addValue(name, value)
}
}
}
private fun audit(type: EntityDataStoreRecordAuditType, recordId: Int, signature: Signature) {
namedParameterJdbcTemplate!!.update(
"INSERT INTO ENTITY_DATA_STORE_AUDIT(RECORD_ID, AUDIT_TYPE, TIMESTAMP, CREATOR) " +
"VALUES (:recordId, :auditType, :timestamp, :user)",
params("recordId", recordId)
.addValue("auditType", type.name)
.addValue("timestamp", dateTimeForDB(signature.time))
.addValue("user", signature.user.name)
)
}
} | mit | 530cb8d9c9494b7612de28bf5d83a7ce | 36.509025 | 173 | 0.545166 | 5.09664 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/test/java/net/mm2d/upnp/internal/impl/ControlPointTest.kt | 1 | 52184 | /*
* Copyright (c) 2019 ๅคงๅ่ฏไป (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.impl
import com.google.common.truth.Truth.assertThat
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.spyk
import io.mockk.unmockkObject
import io.mockk.verify
import net.mm2d.upnp.Adapter.discoveryListener
import net.mm2d.upnp.Adapter.eventListener
import net.mm2d.upnp.Adapter.iconFilter
import net.mm2d.upnp.Adapter.multicastEventListener
import net.mm2d.upnp.Adapter.notifyEventListener
import net.mm2d.upnp.Adapter.taskExecutor
import net.mm2d.upnp.ControlPoint.DiscoveryListener
import net.mm2d.upnp.ControlPoint.EventListener
import net.mm2d.upnp.ControlPoint.NotifyEventListener
import net.mm2d.upnp.ControlPointFactory
import net.mm2d.upnp.Device
import net.mm2d.upnp.HttpClient
import net.mm2d.upnp.Protocol
import net.mm2d.upnp.Service
import net.mm2d.upnp.SsdpMessage
import net.mm2d.upnp.StateVariable
import net.mm2d.upnp.internal.manager.DeviceHolder
import net.mm2d.upnp.internal.manager.SubscribeManagerImpl
import net.mm2d.upnp.internal.message.SsdpRequest
import net.mm2d.upnp.internal.message.SsdpResponse
import net.mm2d.upnp.internal.parser.DeviceParser
import net.mm2d.upnp.internal.server.DEFAULT_SSDP_MESSAGE_FILTER
import net.mm2d.upnp.internal.server.MulticastEventReceiverList
import net.mm2d.upnp.internal.server.SsdpNotifyServer
import net.mm2d.upnp.internal.server.SsdpNotifyServerList
import net.mm2d.upnp.internal.server.SsdpSearchServer
import net.mm2d.upnp.internal.server.SsdpSearchServerList
import net.mm2d.upnp.internal.thread.TaskExecutors
import net.mm2d.upnp.util.NetworkUtils
import net.mm2d.upnp.util.TestUtils
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.experimental.runners.Enclosed
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.IOException
import java.net.InetAddress
import java.net.URL
@Suppress("TestFunctionName", "NonAsciiCharacters", "ClassName")
@RunWith(Enclosed::class)
class ControlPointTest {
@RunWith(JUnit4::class)
class mockๆชไฝฟ็จ {
@Test(expected = IllegalStateException::class)
fun constructor_ใคใณใฟใผใใงใผใน็ฉบใงๆๅฎ() {
ControlPointImpl(
Protocol.DEFAULT, emptyList(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = mockk(relaxed = true)
)
}
@Test(timeout = 10000L)
fun initialize_terminate() {
val cp = ControlPointFactory.create()
cp.initialize()
cp.terminate()
}
@Test(timeout = 10000L)
fun initialize_initialize_terminate() {
val cp = ControlPointFactory.create()
cp.initialize()
cp.initialize()
cp.terminate()
}
@Test(timeout = 10000L)
fun initialize_terminate_intercept() {
val thread = Thread {
val cp = ControlPointFactory.create()
cp.initialize()
cp.terminate()
}
thread.start()
Thread.sleep(200)
thread.interrupt()
thread.join()
}
@Test(timeout = 10000L)
fun terminate() {
val cp = ControlPointFactory.create()
cp.terminate()
}
@Test(timeout = 10000L)
fun start_stop() {
val cp = ControlPointFactory.create()
cp.initialize()
cp.start()
cp.stop()
cp.terminate()
}
@Test(timeout = 10000L)
fun start_stop2() {
val cp = ControlPointFactory.create()
cp.initialize()
cp.start()
cp.stop()
cp.stop()
cp.terminate()
}
@Test(timeout = 10000L)
fun start_stop_with_multicast_eventing() {
val multicastEventReceiverList: MulticastEventReceiverList = mockk(relaxed = true)
val factory: DiFactory = mockk(relaxed = true)
every { factory.createMulticastEventReceiverList(any(), any(), any()) } returns multicastEventReceiverList
val cp = ControlPointImpl(
Protocol.DEFAULT, Protocol.DEFAULT.getAvailableInterfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = true,
factory = factory
)
cp.start()
verify(exactly = 1) { multicastEventReceiverList.start() }
cp.stop()
verify(exactly = 1) { multicastEventReceiverList.stop() }
}
@Test(timeout = 10000L)
fun start_stop_illegal() {
val cp = ControlPointFactory.create()
cp.start()
cp.start()
cp.terminate()
cp.terminate()
}
@Test(expected = IllegalStateException::class)
fun search_not_started() {
val cp = ControlPointFactory.create()
cp.search()
}
@Test
fun search() {
val list: SsdpSearchServerList = mockk(relaxed = true)
val factory: DiFactory = mockk(relaxed = true)
every { factory.createSsdpSearchServerList(any(), any(), any()) } returns list
val cp = ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = factory
)
cp.initialize()
cp.start()
cp.search()
verify(exactly = 1) { list.search(null) }
cp.stop()
cp.terminate()
}
@Test
fun needToUpdateSsdpMessage_DUAL_STACK() {
val cp = ControlPointFactory.create(
protocol = Protocol.DUAL_STACK,
interfaces = NetworkUtils.getAvailableInterfaces()
) as ControlPointImpl
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("fe80::1:1:1:1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("169.254.1.1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("192.168.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("169.254.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("192.168.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("fe80::1:1:1:1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("169.254.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("192.168.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("fe80::1:1:1:1")
)
).isFalse()
}
@Test
fun needToUpdateSsdpMessage_IP_V4_ONLY() {
val cp = ControlPointFactory.create(
protocol = Protocol.IP_V4_ONLY,
interfaces = NetworkUtils.getAvailableInterfaces()
) as ControlPointImpl
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("fe80::1:1:1:1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("169.254.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("192.168.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("169.254.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("192.168.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("fe80::1:1:1:1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("169.254.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("192.168.1.1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("fe80::1:1:1:1")
)
).isFalse()
}
@Test
fun needToUpdateSsdpMessage_IP_V6_ONLY() {
val cp = ControlPointFactory.create(
protocol = Protocol.IP_V6_ONLY,
interfaces = NetworkUtils.getAvailableInterfaces()
) as ControlPointImpl
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("fe80::1:1:1:1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("169.254.1.1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("fe80::1:1:1:1"),
makeAddressMock("192.168.1.1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("169.254.1.1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("192.168.1.1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("169.254.1.1"),
makeAddressMock("fe80::1:1:1:1")
)
).isTrue()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("169.254.1.1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("192.168.1.1")
)
).isFalse()
assertThat(
cp.needToUpdateSsdpMessage(
makeAddressMock("192.168.1.1"),
makeAddressMock("fe80::1:1:1:1")
)
).isTrue()
}
private fun makeAddressMock(address: String): SsdpMessage {
val message: SsdpMessage = mockk(relaxed = true)
val inetAddress = InetAddress.getByName(address)
every { message.localAddress } returns inetAddress
return message
}
@Test
fun setIconFilter_nullใๆๅฎใใฆใๅ้กใชใ() {
val cp = ControlPointFactory.create()
cp.setIconFilter(null)
}
}
@RunWith(JUnit4::class)
class ใใใใฏใผใฏๆชไฝฟ็จ {
private lateinit var cp: ControlPointImpl
private val ssdpSearchServerList: SsdpSearchServerList = mockk(relaxed = true)
private val ssdpNotifyServerList: SsdpNotifyServerList = mockk(relaxed = true)
private val taskExecutors: TaskExecutors = mockk(relaxed = true)
private val diFactory = spyk(DiFactory())
private val subscribeManager = spyk(SubscribeManagerImpl(taskExecutors, mockk(relaxed = true), diFactory))
@Before
fun setUp() {
val factory = spyk(DiFactory())
every { factory.createSsdpSearchServerList(any(), any(), any()) } returns ssdpSearchServerList
every { factory.createSsdpNotifyServerList(any(), any(), any()) } returns ssdpNotifyServerList
every { factory.createSubscribeManager(any(), any(), any()) } returns subscribeManager
cp = spyk(
ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = factory
)
)
}
@Test
fun discoverDevice_onDiscoverใ้็ฅใใใ() {
val l: DiscoveryListener = mockk(relaxed = true)
cp.addDiscoveryListener(l)
val uuid = "uuid"
val device: Device = mockk(relaxed = true)
every { device.udn } returns uuid
cp.discoverDevice(device)
Thread.sleep(100)
assertThat(cp.getDevice(uuid)).isEqualTo(device)
assertThat(cp.deviceList).contains(device)
assertThat(cp.deviceListSize).isEqualTo(1)
verify(exactly = 1) { l.onDiscover(device) }
}
@Test
fun clearDeviceList_Deviceใใฏใชใขใใใ() {
val l: DiscoveryListener = mockk(relaxed = true)
cp.addDiscoveryListener(l)
val uuid = "uuid"
val device: Device = mockk(relaxed = true)
every { device.udn } returns uuid
cp.discoverDevice(device)
Thread.sleep(100)
assertThat(cp.getDevice(uuid)).isEqualTo(device)
assertThat(cp.deviceList).contains(device)
assertThat(cp.deviceListSize).isEqualTo(1)
verify(exactly = 1) { l.onDiscover(device) }
cp.clearDeviceList()
Thread.sleep(100)
assertThat(cp.getDevice(uuid)).isNull()
assertThat(cp.deviceList).doesNotContain(device)
assertThat(cp.deviceListSize).isEqualTo(0)
verify(exactly = 1) { l.onDiscover(device) }
}
@Test
fun lostDevice_onLostใ้็ฅใใใ() {
val l: DiscoveryListener = mockk(relaxed = true)
cp.addDiscoveryListener(l)
val uuid = "uuid"
val device: Device = mockk(relaxed = true)
val service: Service = mockk(relaxed = true)
every { device.udn } returns uuid
every { device.serviceList } returns listOf(service)
cp.discoverDevice(device)
Thread.sleep(100)
cp.lostDevice(device)
Thread.sleep(100)
assertThat(cp.getDevice(uuid)).isNull()
assertThat(cp.deviceListSize).isEqualTo(0)
verify(exactly = 1) { l.onLost(device) }
verify(exactly = 1) { subscribeManager.unregister(service) }
}
@Test
fun stop_lostDeviceใ้็ฅใใใ() {
val uuid = "uuid"
val device: Device = mockk(relaxed = true)
val service: Service = mockk(relaxed = true)
every { device.udn } returns uuid
every { device.expireTime } returns System.currentTimeMillis() + 1000L
every { device.serviceList } returns listOf(service)
cp.start()
cp.discoverDevice(device)
Thread.sleep(100)
cp.stop()
Thread.sleep(100)
assertThat(cp.getDevice(uuid)).isNull()
assertThat(cp.deviceListSize).isEqualTo(0)
verify(exactly = 1) { cp.lostDevice(device) }
verify(exactly = 1) { subscribeManager.unregister(service) }
}
@Test
fun removeDiscoveryListener_ๅ้คใงใใ() {
val l: DiscoveryListener = mockk(relaxed = true)
cp.addDiscoveryListener(l)
cp.removeDiscoveryListener(l)
val uuid = "uuid"
val device: Device = mockk(relaxed = true)
every { device.udn } returns uuid
cp.discoverDevice(device)
Thread.sleep(100)
verify(inverse = true) { l.onDiscover(device) }
}
@Test
fun addDiscoveryListener_ๅค้็ป้ฒ้ฒๆญข() {
val l: DiscoveryListener = mockk(relaxed = true)
cp.addDiscoveryListener(l)
cp.addDiscoveryListener(l)
cp.removeDiscoveryListener(l)
val uuid = "uuid"
val device: Device = mockk(relaxed = true)
every { device.udn } returns uuid
cp.discoverDevice(device)
Thread.sleep(100)
verify(inverse = true) { l.onDiscover(device) }
}
@Test
fun addDiscoveryListener_by_adapter() {
val discover: (Device) -> Unit = mockk(relaxed = true)
val lost: (Device) -> Unit = mockk(relaxed = true)
cp.addDiscoveryListener(discoveryListener(discover, lost))
val uuid = "uuid"
val device: Device = mockk(relaxed = true)
every { device.udn } returns uuid
cp.discoverDevice(device)
Thread.sleep(100)
verify(exactly = 1) { discover(device) }
cp.lostDevice(device)
Thread.sleep(100)
verify(exactly = 1) { lost(device) }
}
@Test
fun registerSubscribeService_ใซใใ็ป้ฒ() {
val sid = "sid"
val service: Service = mockk(relaxed = true)
every { service.subscriptionId } returns sid
subscribeManager.register(service, 1000L, true)
assertThat(subscribeManager.getSubscribeService(sid)).isEqualTo(service)
}
@Test
fun unregisterSubscribeService_ใซใใๅ้ค() {
val sid = "sid"
val service: Service = mockk(relaxed = true)
every { service.subscriptionId } returns sid
subscribeManager.register(service, 1000L, true)
subscribeManager.unregister(service)
assertThat(subscribeManager.getSubscribeService(sid)).isNull()
}
}
@RunWith(JUnit4::class)
class DeviceDiscovery {
private lateinit var cp: ControlPointImpl
private lateinit var loadingDeviceMap: MutableMap<String, DeviceImpl.Builder>
private lateinit var deviceHolder: DeviceHolder
private lateinit var taskExecutors: TaskExecutors
@Before
fun setUp() {
loadingDeviceMap = spyk(HashMap())
val factory = spyk(DiFactory())
taskExecutors = spyk(TaskExecutors())
every { factory.createTaskExecutors() } returns taskExecutors
every { factory.createLoadingDeviceMap() } returns loadingDeviceMap
every { factory.createDeviceHolder(any(), any()) } answers {
spyk(
DeviceHolder(
arg(0),
arg(1)
)
).also { deviceHolder = it }
}
cp = spyk(
ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = factory
)
)
}
@Test
fun onReceiveSsdp_่ชญใฟ่พผใฟๆธใฟใใใคในใซใชใbyebyeๅไฟก() {
val data = TestUtils.getResourceAsByteArray("ssdp-notify-byebye0.bin")
val addr = InetAddress.getByName("192.0.2.3")
val message = SsdpRequest.create(addr, data, data.size)
cp.onReceiveSsdpMessage(message)
verify(exactly = 1) { loadingDeviceMap.remove(any()) }
}
@Test
fun onReceiveSsdp_่ชญใฟ่พผใฟๆธใฟใใใคในใฎbyebyeๅไฟก() {
val data = TestUtils.getResourceAsByteArray("ssdp-notify-byebye0.bin")
val addr = InetAddress.getByName("192.0.2.3")
val message = SsdpRequest.create(addr, data, data.size)
val device: Device = mockk(relaxed = true)
val udn = "uuid:01234567-89ab-cdef-0123-456789abcdef"
every { device.udn } returns udn
cp.discoverDevice(device)
assertThat(deviceHolder[udn]).isEqualTo(device)
cp.onReceiveSsdpMessage(message)
assertThat(deviceHolder[udn]).isNull()
}
@Test
fun onReceiveSsdp_aliveๅไฟกๅพๅคฑๆ() {
val data = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin")
val addr = InetAddress.getByName("192.0.2.3")
val message = SsdpRequest.create(addr, data, data.size)
val udn = "uuid:01234567-89ab-cdef-0123-456789abcdef"
val client: HttpClient = mockk(relaxed = true)
every { client.downloadString(any()) } answers {
Thread.sleep(500L)
throw IOException()
}
mockkObject(HttpClient.Companion)
every { HttpClient.create(any()) } returns client
cp.onReceiveSsdpMessage(message)
assertThat(loadingDeviceMap).containsKey(udn)
Thread.sleep(1000L) // Exception็บ็ใๅพ
ใค
assertThat(loadingDeviceMap).doesNotContainKey(udn)
assertThat(deviceHolder.size).isEqualTo(0)
unmockkObject(HttpClient.Companion)
}
@Test
fun onReceiveSsdp_aliveๅไฟกๅพๆๅ() {
val httpClient: HttpClient = mockk(relaxed = true)
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/device.xml"))
} returns TestUtils.getResourceAsString("device.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/cds.xml"))
} returns TestUtils.getResourceAsString("cds.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/cms.xml"))
} returns TestUtils.getResourceAsString("cms.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/mmupnp.xml"))
} returns TestUtils.getResourceAsString("mmupnp.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/icon/icon120.jpg"))
} returns TestUtils.getResourceAsString("icon/icon120.jpg")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/icon/icon48.jpg"))
} returns TestUtils.getResourceAsString("icon/icon48.jpg")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/icon/icon120.png"))
} returns TestUtils.getResourceAsString("icon/icon120.png")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/icon/icon48.png"))
} returns TestUtils.getResourceAsString("icon/icon48.png")
val data = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin")
val address = InetAddress.getByName("192.0.2.3")
val message = SsdpRequest.create(address, data, data.size)
val udn = "uuid:01234567-89ab-cdef-0123-456789abcdef"
mockkObject(HttpClient.Companion)
every { HttpClient.create(any()) } returns httpClient
val iconFilter = spyk(iconFilter { listOf(it[0]) })
cp.setIconFilter(iconFilter)
cp.onReceiveSsdpMessage(message)
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
val device = cp.getDevice(udn)
verify(exactly = 1) { iconFilter.invoke(any()) }
assertThat(device!!.iconList).hasSize(4)
assertThat(device.iconList[0].binary).isNotNull()
assertThat(device.iconList[1].binary).isNull()
assertThat(device.iconList[2].binary).isNull()
assertThat(device.iconList[3].binary).isNull()
unmockkObject(HttpClient.Companion)
}
@Test
fun onReceiveSsdp_่ชญใฟ่พผใฟๆธใฟใใใคในใฎaliveๅไฟก() {
val data = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin")
val addr = InetAddress.getByName("192.0.2.3")
val message = SsdpRequest.create(addr, data, data.size)
val device: Device = mockk(relaxed = true)
every { device.ssdpMessage } returns message
val udn = "uuid:01234567-89ab-cdef-0123-456789abcdef"
every { device.udn } returns udn
cp.discoverDevice(device)
cp.onReceiveSsdpMessage(message)
}
@Test
fun onReceiveSsdp_ใญใผใไธญใใใคในใฎaliveๅไฟก() {
val data1 = TestUtils.getResourceAsByteArray("ssdp-notify-alive1.bin")
val addr = InetAddress.getByName("192.0.2.3")
val message1 = SsdpRequest.create(addr, data1, data1.size)
val deviceBuilder = spyk(DeviceImpl.Builder(cp, message1))
loadingDeviceMap[deviceBuilder.getUuid()] = deviceBuilder
val data2 = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin")
val message2 = SsdpRequest.create(addr, data2, data2.size)
cp.onReceiveSsdpMessage(message2)
verify(exactly = 1) { deviceBuilder.updateSsdpMessage(message2) }
}
@Test
fun tryAddDevice() {
val uuid = "uuid"
every { taskExecutors.io(any<() -> Unit>()) } returns true
cp.tryAddDevice(uuid, "http://10.0.0.1/")
verify(exactly = 1) { cp.loadDevice(uuid, any()) }
}
@Test
fun tryAddDevice_already_added() {
val uuid = "uuid"
every { taskExecutors.io(any<() -> Unit>()) } returns true
cp.tryAddDevice(uuid, "http://10.0.0.1/")
cp.tryAddDevice(uuid, "http://10.0.0.1/")
verify(exactly = 1) { cp.loadDevice(uuid, any()) }
}
@Test
fun tryAddDevice_already_added_fail_first() {
val uuid = "uuid"
every { taskExecutors.io(any<() -> Unit>()) } returns false
cp.tryAddDevice(uuid, "http://10.0.0.1/")
cp.tryAddDevice(uuid, "http://10.0.0.1/")
verify(exactly = 2) { cp.loadDevice(uuid, any()) }
}
@Test
fun tryAddDevice_already_loaded() {
val location = "http://10.0.0.1/"
val device: Device = mockk()
every { device.location } returns location
every { cp.deviceList } returns listOf(device)
val uuid = "uuid"
every { taskExecutors.io(any<() -> Unit>()) } returns true
cp.tryAddDevice(uuid, location)
verify(inverse = true) { cp.loadDevice(uuid, any()) }
}
}
@RunWith(JUnit4::class)
class PinnedDevice {
private lateinit var cp: ControlPointImpl
private lateinit var httpClient: HttpClient
@Before
fun setUp() {
cp = spyk(
ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = DiFactory(Protocol.DEFAULT)
)
)
httpClient = mockk(relaxed = true)
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/device.xml"))
} returns TestUtils.getResourceAsString("device.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/cds.xml"))
} returns TestUtils.getResourceAsString("cds.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/cms.xml"))
} returns TestUtils.getResourceAsString("cms.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/mmupnp.xml"))
} returns TestUtils.getResourceAsString("mmupnp.xml")
mockkObject(HttpClient.Companion)
every { HttpClient.create(any()) } returns httpClient
every { httpClient.localAddress } returns InetAddress.getByName("192.0.2.3")
}
@After
fun teardown() {
unmockkObject(HttpClient.Companion)
}
@Test
fun tryAddPinnedDevice() {
cp.tryAddPinnedDevice("http://192.0.2.2:12345/device.xml")
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
assertThat(cp.deviceListSize).isEqualTo(1)
val device = cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdef")
assertThat(device!!.isPinned).isTrue()
}
@Test
fun tryAddPinnedDevice2ๅ็ฎ() {
cp.tryAddPinnedDevice("http://192.0.2.2:12345/device.xml")
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
assertThat(cp.deviceListSize).isEqualTo(1)
val device = cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdef")
assertThat(device!!.isPinned).isTrue()
cp.tryAddPinnedDevice("http://192.0.2.2:12345/device.xml")
}
@Test
fun tryAddPinnedDevice_ใใงใซ็บ่ฆๆธใฟ() {
val data = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin")
val address = InetAddress.getByName("192.0.2.3")
val message = SsdpRequest.create(address, data, data.size)
cp.onReceiveSsdpMessage(message)
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
cp.tryAddPinnedDevice("http://192.0.2.2:12345/device.xml")
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
assertThat(cp.deviceListSize).isEqualTo(1)
val device = cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdef")
assertThat(device!!.isPinned).isTrue()
}
@Test
fun tryAddPinnedDeviceใฎๅพใซ็บ่ฆ() {
val data = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin")
val address = InetAddress.getByName("192.0.2.3")
val message = SsdpRequest.create(address, data, data.size)
cp.onReceiveSsdpMessage(message)
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
val device = cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdef")
assertThat(device!!.isPinned).isFalse()
cp.tryAddPinnedDevice("http://192.0.2.2:12345/device.xml")
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
assertThat(cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdef")!!.isPinned).isTrue()
cp.discoverDevice(device)
assertThat(cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdef")!!.isPinned).isTrue()
}
@Test
fun tryAddPinnedDevice_Exceptionใ็บ็ใใฆใใฏใฉใใทใฅใใชใ() {
every { httpClient.downloadString(any()) } throws IOException()
cp.tryAddPinnedDevice("http://192.0.2.2:12345/device.xml")
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
}
@Test
fun removePinnedDevice() {
cp.tryAddPinnedDevice("http://192.0.2.2:12345/device.xml")
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
assertThat(cp.deviceListSize).isEqualTo(1)
cp.removePinnedDevice("http://192.0.2.2:12345/device.xml")
assertThat(cp.deviceListSize).isEqualTo(0)
}
@Test
fun removePinnedDevice_before_load() {
cp.tryAddPinnedDevice("http://192.0.2.2:12345/device.xml")
assertThat(cp.deviceListSize).isEqualTo(0)
cp.removePinnedDevice("http://192.0.2.2:12345/device.xml")
Thread.sleep(1000) // ่ชญใฟ่พผใฟใๅพ
ใค
assertThat(cp.deviceListSize).isEqualTo(0)
}
}
@RunWith(JUnit4::class)
class ใคใใณใไผๆฌใในใ {
private lateinit var cp: ControlPointImpl
private lateinit var subscribeManager: SubscribeManagerImpl
private val loadingDeviceMap = spyk(HashMap<String, DeviceImpl.Builder>())
private lateinit var deviceHolder: DeviceHolder
private val ssdpSearchServerList: SsdpSearchServerList = mockk(relaxed = true)
private val ssdpNotifyServerList: SsdpNotifyServerList = mockk(relaxed = true)
private lateinit var responseListener: (SsdpMessage) -> Unit
private lateinit var notifyListener: (SsdpMessage) -> Unit
@Before
fun setUp() {
val factory = spyk(DiFactory())
every { factory.createLoadingDeviceMap() } returns loadingDeviceMap
every { factory.createDeviceHolder(any(), any()) } answers {
spyk(
DeviceHolder(
arg(0),
arg(1)
)
).also { deviceHolder = it }
}
every { factory.createSsdpSearchServerList(any(), any(), any()) } answers {
responseListener = arg(2)
ssdpSearchServerList
}
every { factory.createSsdpNotifyServerList(any(), any(), any()) } answers {
notifyListener = arg(2)
ssdpNotifyServerList
}
every { factory.createSubscribeManager(any(), any(), any()) } answers {
spyk(SubscribeManagerImpl(arg(1), arg(2), factory)).also { subscribeManager = it }
}
cp = ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = factory
)
}
@Test
fun stopๆใซunsubscribeใจlostใ็บ็ใใใใจ() {
cp.start()
val device: Device = mockk(relaxed = true)
every { device.udn } returns "udn"
cp.discoverDevice(device)
val service: Service = mockk(relaxed = true)
every { service.subscriptionId } returns "SubscriptionId"
subscribeManager.register(service, 1000L, false)
cp.stop()
cp.terminate()
Thread.sleep(100)
coVerify(exactly = 1) { service.unsubscribe() }
verify(exactly = 1) { deviceHolder.remove(device) }
}
@Test
fun onReceiveSsdp_ResponseListenerใใไผๆฌ() {
val data = TestUtils.getResourceAsByteArray("ssdp-search-response0.bin")
val message = spyk(SsdpResponse.create(mockk(relaxed = true), data, data.size))
responseListener.invoke(message)
Thread.sleep(100)
verify { message.uuid }
}
@Test
fun onReceiveSsdp_NotifyListenerใใไผๆฌ() {
val data = TestUtils.getResourceAsByteArray("ssdp-notify-byebye0.bin")
val message = spyk(SsdpRequest.create(mockk(relaxed = true), data, data.size))
notifyListener.invoke(message)
Thread.sleep(100)
verify { message.uuid }
}
}
@RunWith(JUnit4::class)
class EventReceiverใซ่ตทๅ ใใใในใ {
private lateinit var cp: ControlPointImpl
private lateinit var subscribeManager: SubscribeManagerImpl
@Before
fun setUp() {
val factory = spyk(DiFactory())
every { factory.createSsdpSearchServerList(any(), any(), any()) } returns mockk(relaxed = true)
every { factory.createSsdpNotifyServerList(any(), any(), any()) } returns mockk(relaxed = true)
every { factory.createSubscribeManager(any(), any(), any()) } answers {
spyk(SubscribeManagerImpl(arg(1), arg(2), factory)).also { subscribeManager = it }
}
cp = spyk(
ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = factory
)
)
}
@Test
fun notifyEvent_ใคใใณใใใชในใใผใซ้็ฅใใใใใจ() {
val sid = "sid"
val service: Service = mockk(relaxed = true)
every { service.subscriptionId } returns sid
val variableName = "variable"
val variable: StateVariable = mockk(relaxed = true)
every { variable.isSendEvents } returns true
every { variable.name } returns variableName
every { service.findStateVariable(variableName) } returns variable
subscribeManager.register(service, 1000L, false)
val eventListener: EventListener = mockk(relaxed = true)
cp.addEventListener(eventListener)
val notifyEventListener: NotifyEventListener = mockk(relaxed = true)
cp.addNotifyEventListener(notifyEventListener)
val value = "value"
subscribeManager.onEventReceived(sid, 0, listOf(variableName to value))
Thread.sleep(2000)
verify(exactly = 1) { notifyEventListener.onNotifyEvent(service, 0, variableName, value) }
verify(exactly = 1) { eventListener.onEvent(service, 0, listOf(variableName to value)) }
}
@Test
fun notifyEvent_ๅ้คใใใชในใใผใซ้็ฅใใใชใใใจ() {
val sid = "sid"
val service: Service = mockk(relaxed = true)
every { service.subscriptionId } returns sid
val variableName = "variable"
val variable: StateVariable = mockk(relaxed = true)
every { variable.isSendEvents } returns true
every { variable.name } returns variableName
every { service.findStateVariable(variableName) } returns variable
subscribeManager.register(service, 1000L, false)
val eventListener: EventListener = mockk(relaxed = true)
cp.addEventListener(eventListener)
cp.removeEventListener(eventListener)
val notifyEventListener: NotifyEventListener = mockk(relaxed = true)
cp.addNotifyEventListener(notifyEventListener)
cp.removeNotifyEventListener(notifyEventListener)
val value = "value"
subscribeManager.onEventReceived(sid, 0, listOf(variableName to value))
Thread.sleep(100)
verify(inverse = true) { notifyEventListener.onNotifyEvent(service, 0, variableName, value) }
verify(inverse = true) { eventListener.onEvent(service, 0, listOf(variableName to value)) }
}
@Test
fun notifyEvent_ๅฏพๅฟใใๅคๆฐใฎใชใใคใใณใใ็ก่ฆใใใใใจ() {
val sid = "sid"
val service: Service = mockk(relaxed = true)
every { service.subscriptionId } returns sid
val variableName = "variable"
val variable: StateVariable = mockk(relaxed = true)
every { variable.isSendEvents } returns true
every { variable.name } returns variableName
every { service.findStateVariable(variableName) } returns variable
subscribeManager.register(service, 1000L, false)
val eventListener: EventListener = mockk(relaxed = true)
cp.addEventListener(eventListener)
val notifyEventListener: NotifyEventListener = mockk(relaxed = true)
cp.addNotifyEventListener(notifyEventListener)
val value = "value"
subscribeManager.onEventReceived(sid, 0, listOf(variableName + 1 to value))
Thread.sleep(100)
verify(inverse = true) { notifyEventListener.onNotifyEvent(service, 0, variableName, value) }
verify(exactly = 1) { eventListener.onEvent(service, 0, listOf(variableName + 1 to value)) }
}
@Test
fun notifyEvent_ๅฏพๅฟใใใตใผใในใใชใ() {
val sid = "sid"
val variableName = "variable"
val value = "value"
assertThat(subscribeManager.onEventReceived(sid, 0, listOf(variableName + 1 to value))).isFalse()
}
@Test
fun notifyEvent_by_adapter() {
val sid = "sid"
val service: Service = mockk(relaxed = true)
every { service.subscriptionId } returns sid
val variableName = "variable"
val variable: StateVariable = mockk(relaxed = true)
every { variable.isSendEvents } returns true
every { variable.name } returns variableName
every { service.findStateVariable(variableName) } returns variable
subscribeManager.register(service, 1000L, false)
val onEvent: (service: Service, seq: Long, properties: List<Pair<String, String>>) -> Unit =
mockk(relaxed = true)
cp.addEventListener(eventListener(onEvent))
val notifyEvent: (service: Service, seq: Long, variable: String, value: String) -> Unit =
mockk(relaxed = true)
cp.addNotifyEventListener(notifyEventListener(notifyEvent))
val value = "value"
subscribeManager.onEventReceived(sid, 0, listOf(variableName to value))
Thread.sleep(2000)
verify(exactly = 1) { notifyEvent(service, 0, variableName, value) }
verify(exactly = 1) { onEvent(service, 0, listOf(variableName to value)) }
}
}
@RunWith(JUnit4::class)
class SsdpMessageFilterใฎใในใ {
private lateinit var cp: ControlPointImpl
private lateinit var ssdpMessage: SsdpMessage
private val receiverList: MutableList<SsdpNotifyServer> = mutableListOf()
private val serverList: MutableList<SsdpSearchServer> = mutableListOf()
@Before
fun setUp() {
mockkObject(SsdpNotifyServerList.Companion)
mockkObject(SsdpSearchServerList.Companion)
every { SsdpNotifyServerList.newServer(any(), any(), any(), any()) } answers {
mockk<SsdpNotifyServer>(relaxed = true).also { receiverList += it }
}
every { SsdpSearchServerList.newServer(any(), any(), any(), any()) } answers {
mockk<SsdpSearchServer>(relaxed = true).also { serverList += it }
}
cp = spyk(
ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = DiFactory(Protocol.DEFAULT)
)
)
val data = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin")
val addr = InetAddress.getByName("192.0.2.3")
ssdpMessage = SsdpRequest.create(addr, data, data.size)
}
@After
fun teardown() {
unmockkObject(SsdpNotifyServerList.Companion)
unmockkObject(SsdpSearchServerList.Companion)
}
@Test
fun filterใๅ
จserverใซ่จญๅฎใใใ() {
val filter: (SsdpMessage) -> Boolean = mockk()
cp.setSsdpMessageFilter(filter)
receiverList.forEach {
verify { it.setFilter(filter) }
}
serverList.forEach {
verify { it.setFilter(filter) }
}
}
@Test
fun filterใซnullใๆๅฎใใใจๅ
จserverใซ่จญๅฎใใใ() {
cp.setSsdpMessageFilter(null)
receiverList.forEach {
verify { it.setFilter(DEFAULT_SSDP_MESSAGE_FILTER) }
}
serverList.forEach {
verify { it.setFilter(DEFAULT_SSDP_MESSAGE_FILTER) }
}
}
}
@RunWith(JUnit4::class)
class MulticastEventingใฎใในใ {
private lateinit var cp: ControlPointImpl
@Before
fun setUp() {
cp = spyk(
ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = DiFactory(Protocol.DEFAULT, taskExecutor { it.run().let { true } })
)
)
}
@Test
fun `onReceiveMulticastEvent listenerใซ้็ฅใใใ`() {
val uuid = "uuid"
val svcid = "svcid"
val device: Device = mockk(relaxed = true)
every { device.udn } returns uuid
val service: Service = mockk(relaxed = true)
every { device.findServiceById(svcid) } returns service
cp.discoverDevice(device)
val listener = spyk(multicastEventListener { _, _, _, _ -> })
cp.addMulticastEventListener(listener)
val lvl = "upnp:/info"
val seq = 0L
val properties = listOf<Pair<String, String>>()
cp.onReceiveMulticastEvent(uuid, svcid, lvl, seq, properties)
verify(exactly = 1) { listener.onEvent(service, lvl, seq, properties) }
}
@Test
fun `onReceiveMulticastEvent removeใใlistenerใซใฏ้็ฅใใใชใ`() {
val uuid = "uuid"
val svcid = "svcid"
val device: Device = mockk(relaxed = true)
every { device.udn } returns uuid
val service: Service = mockk(relaxed = true)
every { device.findServiceById(svcid) } returns service
cp.discoverDevice(device)
val listener = spyk(multicastEventListener { _, _, _, _ -> })
cp.addMulticastEventListener(listener)
cp.removeMulticastEventListener(listener)
val lvl = "upnp:/info"
val seq = 0L
val properties = listOf<Pair<String, String>>()
cp.onReceiveMulticastEvent(uuid, svcid, lvl, seq, properties)
verify(inverse = true) { listener.onEvent(any(), any(), any(), any()) }
}
@Test
fun `onReceiveMulticastEvent uuidใsvcidใ้ใฃใฆใใใจไฝใ่ตทใใใชใ`() {
val uuid = "uuid"
val svcid = "svcid"
val device: Device = mockk(relaxed = true)
every { device.udn } returns uuid
val service: Service = mockk(relaxed = true)
every { device.findServiceById(any()) } returns null
every { device.findServiceById(svcid) } returns service
cp.discoverDevice(device)
val listener = spyk(multicastEventListener { _, _, _, _ -> })
cp.addMulticastEventListener(listener)
val lvl = "upnp:/info"
val seq = 0L
val properties = listOf<Pair<String, String>>()
cp.onReceiveMulticastEvent("hoge", svcid, lvl, seq, properties)
verify(inverse = true) { listener.onEvent(any(), any(), any(), any()) }
cp.onReceiveMulticastEvent(uuid, "hoge", lvl, seq, properties)
verify(inverse = true) { listener.onEvent(any(), any(), any(), any()) }
}
}
@RunWith(JUnit4::class)
class EmbeddedDevice {
@Test
fun embeddedDeviceใใจใซuuidใ็ฐใชใๅ ดๅใฉใฎuuidใงใๅใๅบใใ() {
val cp: ControlPointImpl = spyk(
ControlPointImpl(
Protocol.DEFAULT,
NetworkUtils.getAvailableInet4Interfaces(),
notifySegmentCheckEnabled = false,
subscriptionEnabled = true,
multicastEventingEnabled = false,
factory = DiFactory(Protocol.DEFAULT)
)
)
val httpClient: HttpClient = mockk(relaxed = true)
val data = TestUtils.getResourceAsByteArray("ssdp-notify-alive0.bin")
val ssdpMessage: SsdpMessage = SsdpRequest.create(mockk(relaxed = true), data, data.size)
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/device.xml"))
} returns TestUtils.getResourceAsString("device-with-embedded-device.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/cds.xml"))
} returns TestUtils.getResourceAsString("cds.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/cms.xml"))
} returns TestUtils.getResourceAsString("cms.xml")
every {
httpClient.downloadString(URL("http://192.0.2.2:12345/mmupnp.xml"))
} returns TestUtils.getResourceAsString("mmupnp.xml")
mockkObject(HttpClient.Companion)
every { HttpClient.create(any()) } returns httpClient
every { httpClient.localAddress } returns InetAddress.getByName("192.0.2.3")
val builder = DeviceImpl.Builder(cp, ssdpMessage)
DeviceParser.loadDescription(httpClient, builder)
val device = builder.build()
cp.discoverDevice(device)
assertThat(cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdee")).isEqualTo(device)
assertThat(cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcded")).isEqualTo(device)
assertThat(cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdef")).isEqualTo(device)
cp.lostDevice(device)
assertThat(cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdee")).isNull()
assertThat(cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcded")).isNull()
assertThat(cp.getDevice("uuid:01234567-89ab-cdef-0123-456789abcdef")).isNull()
unmockkObject(HttpClient.Companion)
}
}
}
| mit | 5743fd27cd819a680d9c7e7196b86603 | 38.360429 | 118 | 0.567237 | 4.522115 | false | true | false | false |
ohmae/mmupnp | mmupnp/src/main/java/net/mm2d/upnp/internal/thread/DefaultTaskExecutor.kt | 1 | 1555 | /*
* Copyright (c) 2019 ๅคงๅ่ฏไป (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.thread
import net.mm2d.upnp.Property
import net.mm2d.upnp.TaskExecutor
import net.mm2d.upnp.log.Logger
import java.util.concurrent.ExecutorService
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
internal class DefaultTaskExecutor(
executor: ExecutorService,
private val awaitTermination: Boolean = false
) : TaskExecutor {
private val executorReference = AtomicReference(executor)
override fun execute(task: Runnable): Boolean {
val executor = executorReference.get() ?: return false
try {
executor.execute(task)
} catch (ignored: RejectedExecutionException) {
return false
}
return true
}
override fun terminate() {
val executor = executorReference.getAndSet(null) ?: return
if (!awaitTermination) {
executor.shutdownNow()
return
}
try {
executor.shutdown()
if (!executor.awaitTermination(AWAIT_TIMEOUT, TimeUnit.MILLISECONDS)) {
executor.shutdownNow()
}
} catch (e: InterruptedException) {
executor.shutdownNow()
Logger.w(e)
}
}
companion object {
private val AWAIT_TIMEOUT = Property.DEFAULT_TIMEOUT.toLong()
}
}
| mit | 7c57961e06febc978795a30a2aef98e4 | 27.648148 | 83 | 0.656109 | 4.687879 | false | false | false | false |
KyuBlade/kotlin-discord-bot | src/main/kotlin/com/omega/discord/bot/command/impl/moderation/BanCommand.kt | 1 | 1982 | package com.omega.discord.bot.command.impl.moderation
import com.omega.discord.bot.command.Command
import com.omega.discord.bot.ext.StringUtils
import com.omega.discord.bot.permission.Permission
import com.omega.discord.bot.util.MessageSender
import sx.blah.discord.handle.obj.IChannel
import sx.blah.discord.handle.obj.IMessage
import sx.blah.discord.handle.obj.IUser
import sx.blah.discord.util.MissingPermissionsException
import sx.blah.discord.util.RequestBuffer
class BanCommand : Command {
override val name: String = "ban"
override val aliases: Array<String>? = null
override val usage: String = "**ban <userMention>** - Ban the mentioned user from the server"
override val allowPrivate: Boolean = false
override val permission: Permission? = Permission.COMMAND_SKIP_FORCE
override val ownerOnly: Boolean = false
override fun execute(author: IUser, channel: IChannel, message: IMessage, args: List<String>) {
if (args.isNotEmpty()) {
val userMentionStr = args.first()
val user: IUser? = StringUtils.parseUserMention(userMentionStr)
if (user != null) {
val reason: String? = if (args.size > 1) args.drop(1).joinToString(" ") else null
RequestBuffer.request {
try {
channel.guild.banUser(user, reason)
MessageSender.sendMessage(channel,
"**Banned user ${user.mention()}**" +
if (reason != null) "\n**Reason:** $reason" else ""
)
} catch (e: MissingPermissionsException) {
MessageSender.sendMessage(channel, e.errorMessage)
}
}
} else {
MessageSender.sendMessage(channel, "User $userMentionStr not found")
}
} else {
missingArgs(author, message)
}
}
} | gpl-3.0 | 3d0d71c3c2ce1de811c0253fec01347a | 39.469388 | 99 | 0.605954 | 4.587963 | false | false | false | false |
is00hcw/anko | dsl/testData/compile/AndroidLayoutParamsTest.kt | 4 | 2463 | package com.example.android_test
import android.app.Activity
import android.os.Bundle
import org.jetbrains.anko.*
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.AbsoluteLayout
import android.widget.FrameLayout
import android.widget.GridLayout
import android.view.Gravity
public open class MyActivity() : Activity() {
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
UI {
linearLayout {
editText {
lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
gravity = Gravity.RIGHT
weight = 1.3591409142295225f
}
}
}
relativeLayout {
editText {
lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE)
addRule(RelativeLayout.CENTER_IN_PARENT)
}
}
}
absoluteLayout {
editText {
lparams(-2, -2, 12, 23) {
height = 9
x = 100
y = 200
}
}
}
frameLayout {
editText {
lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
gravity = Gravity.RIGHT
}
}
}
gridLayout {
editText {
lparams() {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
gravity = Gravity.RIGHT
}
}
}
}
}
} | apache-2.0 | 1e7f65abb89f98609795448fbb52adaf | 30.189873 | 86 | 0.381242 | 6.785124 | false | false | false | false |
samtstern/quickstart-android | auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MultiFactorUnenrollActivity.kt | 1 | 2687 | package com.google.firebase.quickstart.auth.kotlin
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.PhoneMultiFactorInfo
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.databinding.ActivityMultiFactorSignInBinding
import com.google.firebase.quickstart.auth.java.BaseActivity
class MultiFactorUnenrollActivity : BaseActivity() {
private lateinit var binding: ActivityMultiFactorSignInBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMultiFactorSignInBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.smsCode.visibility = View.GONE
binding.finishMfaSignIn.visibility = View.GONE
// Users are currently limited to having 5 second factors
val phoneFactorButtonList = listOf(
binding.phoneFactor1, binding.phoneFactor2, binding.phoneFactor3,
binding.phoneFactor4, binding.phoneFactor5)
for (button in phoneFactorButtonList) {
button.visibility = View.GONE
}
val multiFactorInfoList = FirebaseAuth.getInstance().currentUser!!.multiFactor.enrolledFactors
for (i in multiFactorInfoList.indices) {
val phoneMultiFactorInfo = multiFactorInfoList[i] as PhoneMultiFactorInfo
val button = phoneFactorButtonList[i]
button.visibility = View.VISIBLE
button.text = phoneMultiFactorInfo.phoneNumber
button.isClickable = true
button.setOnClickListener(generateFactorOnClickListener(phoneMultiFactorInfo))
}
}
private fun generateFactorOnClickListener(phoneMultiFactorInfo: PhoneMultiFactorInfo): View.OnClickListener {
return View.OnClickListener {
Firebase.auth
.currentUser!!
.multiFactor
.unenroll(phoneMultiFactorInfo)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this@MultiFactorUnenrollActivity,
"Successfully unenrolled!", Toast.LENGTH_SHORT).show()
finish()
} else {
Toast.makeText(this@MultiFactorUnenrollActivity,
"Unable to unenroll second factor. " + task.exception, Toast.LENGTH_SHORT).show()
}
}
}
}
}
| apache-2.0 | 0242af196b45742da982d2d34a79c1e8 | 42.33871 | 117 | 0.653889 | 5.167308 | false | false | false | false |
AngrySoundTech/CouponCodes3 | core/src/main/kotlin/tech/feldman/couponcodes/core/commands/runnables/AddCommand.kt | 2 | 7597 | /**
* The MIT License
* Copyright (c) 2015 Nicholas Feldman (AngrySoundTech)
* <p/>
* 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:
* <p/>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p/>
* 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 tech.feldman.couponcodes.core.commands.runnables
import tech.feldman.couponcodes.api.command.CommandSender
import tech.feldman.couponcodes.api.exceptions.UnknownMaterialException
import tech.feldman.couponcodes.core.coupon.*
import tech.feldman.couponcodes.core.database.SimpleDatabaseHandler
import tech.feldman.couponcodes.core.util.LocaleHandler
import tech.feldman.couponcodes.core.util.RandomName
import java.util.*
class AddCommand(private val sender: CommandSender, private val args: Array<String>) : Runnable {
override fun run() {
if (args.size < 2) {
helpAdd(sender)
return
}
when(args[1].toLowerCase()) {
"item" -> {
if (args.size >= 4) {
var name = args[2]
if (name.equals("random", ignoreCase = true))
name = RandomName.generateName()
if (args.size >= 5) {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddItem"))
return
}
val itemHash: Map<String, Int>
try {
itemHash = SimpleDatabaseHandler.itemStringToHash(args[3])
} catch (e: UnknownMaterialException) {
sender.sendMessage(LocaleHandler.getString("Command.Add.InvalidName", e.itemName))
return
}
val ic = SimpleItemCoupon(name, 1, -1, HashMap(), itemHash)
if (ic.addToDatabase()) {
sender.sendMessage(LocaleHandler.getString("Command.Add.Added", name))
} else {
sender.sendMessage(LocaleHandler.getString("Command.Add.AlreadyExists"))
}
} else {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddItem"))
}
}
"econ" -> {
if (args.size >= 4) {
var name = args[2]
val money = Integer.parseInt(args[3])
if (name.equals("random", ignoreCase = true))
name = RandomName.generateName()
if (args.size >= 5) {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddEcon"))
return
}
val ec = SimpleEconomyCoupon(name, 1, -1, HashMap(), money)
if (ec.addToDatabase()) {
sender.sendMessage(LocaleHandler.getString("Command.Add.Added", name))
} else {
sender.sendMessage(LocaleHandler.getString("Command.Add.AlreadyExists"))
}
} else {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddEcon"))
}
}
"rank" -> {
if (args.size >= 4) {
var name = args[2]
val group = args[3]
if (name.equals("random", ignoreCase = true))
name = RandomName.generateName()
if (args.size >= 5) {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddRank"))
return
}
val rc = SimpleRankCoupon(name, 1, -1, HashMap(), group)
if (rc.addToDatabase()) {
sender.sendMessage(LocaleHandler.getString("Command.Add.Added", name))
} else {
sender.sendMessage(LocaleHandler.getString("Command.Add.AlreadyExists"))
}
} else {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddRank"))
}
}
"xp" -> {
if (args.size >= 4) {
var name = args[2]
val xp = Integer.parseInt(args[3])
if (name.equals("random", ignoreCase = true))
name = RandomName.generateName()
if (args.size >= 5) {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddXp"))
return
}
val xc = SimpleXpCoupon(name, 1, -1, HashMap(), xp)
if (xc.addToDatabase()) {
sender.sendMessage(LocaleHandler.getString("Command.Add.Added", name))
} else {
sender.sendMessage(LocaleHandler.getString("Command.Add.AlreadyExists"))
}
} else {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddXp"))
}
}
"cmd" -> {
if (args.size >= 4) {
var name = args[2]
val sb = StringBuilder()
for (i in 3..args.size - 1) {
sb.append(args[i]).append(" ")
}
val cmd = sb.toString()
if (name.equals("random", ignoreCase = true))
name = RandomName.generateName()
val cc = SimpleCommandCoupon(name, 1, -1, HashMap(), cmd)
if (cc.addToDatabase()) {
sender.sendMessage(LocaleHandler.getString("Command.Add.Added", name))
} else {
sender.sendMessage(LocaleHandler.getString("Command.Add.AlreadyExists"))
}
} else {
sender.sendMessage(LocaleHandler.getString("Command.Help.AddCmd"))
}
}
else -> helpAdd(sender)
}
}
private fun helpAdd(sender: CommandSender) {
sender.sendMessage(LocaleHandler.getString("Command.Help.Header"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddItem"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddEcon"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddRank"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddXp"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddCmd"))
}
}
| mit | 1ca473ad72abfdc740a893a55c07d53c | 42.164773 | 106 | 0.530078 | 4.942746 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/htl/highlighting/HtlTemplateHighlighter.kt | 1 | 1771 | package co.nums.intellij.aem.htl.highlighting
import co.nums.intellij.aem.htl.HtlLanguage
import co.nums.intellij.aem.htl.psi.HtlTypes
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.editor.ex.util.LayerDescriptor
import com.intellij.openapi.editor.ex.util.LayeredLexerEditorHighlighter
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings
class HtlTemplateHighlighter(project: Project?, virtualFile: VirtualFile?, colors: EditorColorsScheme)
: LayeredLexerEditorHighlighter(HtlSyntaxHighlighter, colors) {
init {
registerOuterLanguageHighlighter(project, virtualFile)
}
private fun registerOuterLanguageHighlighter(project: Project?, virtualFile: VirtualFile?) {
val outerLanguageHighlighter = getOuterSyntaxHighlighter(project, virtualFile)
registerLayer(HtlTypes.OUTER_TEXT, LayerDescriptor(outerLanguageHighlighter, ""))
}
private fun getOuterSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter? {
var fileType: FileType = StdFileTypes.PLAIN_TEXT
if (project != null && virtualFile != null) {
val language = TemplateDataLanguageMappings.getInstance(project).getMapping(virtualFile)
fileType = language?.associatedFileType ?: HtlLanguage.getTemplateLanguageFileType()
}
return SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, virtualFile)
}
}
| gpl-3.0 | 1f943674819c094af4fc8d5ef957ca9e | 46.864865 | 109 | 0.79729 | 4.960784 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/icons/HtlIcons.kt | 1 | 814 | package co.nums.intellij.aem.icons
import com.intellij.openapi.util.IconLoader
object HtlIcons {
val HTL_FILE = IconLoader.getIcon("/icons/htl/htl-file.svg")
val HTL_BLOCK = IconLoader.getIcon("/icons/htl/htl-block.svg")
val HTL_EXPRESSION_OPTION = IconLoader.getIcon("/icons/htl/htl-expression-option.svg")
val HTL_DISPLAY_CONTEXT = IconLoader.getIcon("/icons/htl/htl-display-context.svg")
val HTL_GLOBAL_OBJECT = IconLoader.getIcon("/icons/htl/htl-global-object.svg")
val HTL_PREDEFINED_PROPERTY = IconLoader.getIcon("/icons/htl/htl-predefined-property.svg")
val HTL_USE_OBJECT = IconLoader.getIcon("/icons/htl/htl-use-object.svg")
val HTL_TEMPLATE = IconLoader.getIcon("/icons/htl/htl-template.svg")
val HTL_VARIABLE = IconLoader.getIcon("/icons/htl/htl-variable.svg")
}
| gpl-3.0 | e35c303037547a6d57bf68590a908e83 | 46.882353 | 94 | 0.739558 | 3.508621 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/service/LengthyOperationsService.kt | 1 | 19680 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.service
import android.accounts.AccountManager
import android.app.Notification
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.support.annotation.UiThread
import android.support.annotation.WorkerThread
import android.support.v4.app.NotificationCompat
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import de.vanita5.microblog.library.MicroBlogException
import nl.komponents.kovenant.task
import nl.komponents.kovenant.ui.successUi
import org.mariotaku.abstask.library.AbstractTask
import org.mariotaku.abstask.library.ManualTaskStarter
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.getNullableTypedArrayExtra
import org.mariotaku.ktextension.toLongOr
import de.vanita5.microblog.library.twitter.TwitterUpload
import de.vanita5.microblog.library.twitter.model.MediaUploadResponse
import de.vanita5.microblog.library.twitter.model.MediaUploadResponse.ProcessingInfo
import org.mariotaku.restfu.http.ContentType
import org.mariotaku.restfu.http.mime.Body
import org.mariotaku.restfu.http.mime.SimpleBody
import org.mariotaku.sqliteqb.library.Expression
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.constant.refreshAfterTweetKey
import de.vanita5.twittnuker.extension.getErrorMessage
import de.vanita5.twittnuker.extension.model.notificationBuilder
import de.vanita5.twittnuker.extension.queryOne
import de.vanita5.twittnuker.extension.withAppendedPath
import de.vanita5.twittnuker.model.*
import de.vanita5.twittnuker.model.draft.SendDirectMessageActionExtras
import de.vanita5.twittnuker.model.draft.StatusObjectActionExtras
import de.vanita5.twittnuker.model.notification.NotificationChannelSpec
import de.vanita5.twittnuker.model.schedule.ScheduleInfo
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.model.util.ParcelableStatusUpdateUtils
import de.vanita5.twittnuker.provider.TwidereDataStore.Drafts
import de.vanita5.twittnuker.task.CreateFavoriteTask
import de.vanita5.twittnuker.task.RetweetStatusTask
import de.vanita5.twittnuker.task.twitter.UpdateStatusTask
import de.vanita5.twittnuker.task.twitter.message.SendMessageTask
import de.vanita5.twittnuker.util.deleteDrafts
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* Intent service for lengthy operations like update status/send DM.
*/
class LengthyOperationsService : BaseIntentService("lengthy_operations") {
private val handler: Handler by lazy { Handler(Looper.getMainLooper()) }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return Service.START_STICKY
}
override fun onHandleIntent(intent: Intent?) {
if (intent == null) return
val action = intent.action ?: return
when (action) {
INTENT_ACTION_UPDATE_STATUS -> {
handleUpdateStatusIntent(intent)
}
INTENT_ACTION_SEND_DIRECT_MESSAGE -> {
handleSendDirectMessageIntent(intent)
}
INTENT_ACTION_DISCARD_DRAFT -> {
handleDiscardDraftIntent(intent)
}
INTENT_ACTION_SEND_DRAFT -> {
handleSendDraftIntent(intent)
}
}
}
private fun showToast(e: Exception, longMessage: Boolean) {
handler.post {
Toast.makeText(this, e.getErrorMessage(this), if (longMessage) Toast.LENGTH_LONG else Toast.LENGTH_SHORT).show()
}
}
private fun showToast(message: Int, longMessage: Boolean) {
handler.post { Toast.makeText(this, message, if (longMessage) Toast.LENGTH_LONG else Toast.LENGTH_SHORT).show() }
}
private fun handleSendDraftIntent(intent: Intent) {
val uri = intent.data ?: return
notificationManager.cancel(uri.toString(), NOTIFICATION_ID_DRAFTS)
val draftId = uri.lastPathSegment.toLongOr(-1L)
if (draftId == -1L) return
val where = Expression.equals(Drafts._ID, draftId)
val draft: Draft = contentResolver.queryOne(Drafts.CONTENT_URI, Drafts.COLUMNS, where.sql,
null, null, cls = Draft::class.java) ?: return
contentResolver.delete(Drafts.CONTENT_URI, where.sql, null)
if (TextUtils.isEmpty(draft.action_type)) {
draft.action_type = Draft.Action.UPDATE_STATUS
}
when (draft.action_type) {
Draft.Action.UPDATE_STATUS_COMPAT_1, Draft.Action.UPDATE_STATUS_COMPAT_2,
Draft.Action.UPDATE_STATUS, Draft.Action.REPLY, Draft.Action.QUOTE -> {
updateStatuses(arrayOf(ParcelableStatusUpdateUtils.fromDraftItem(this, draft)))
}
Draft.Action.SEND_DIRECT_MESSAGE_COMPAT, Draft.Action.SEND_DIRECT_MESSAGE -> {
val extras = draft.action_extras as? SendDirectMessageActionExtras ?: return
val message = ParcelableNewMessage().apply {
this.account = draft.account_keys?.firstOrNull()?.let { key ->
val am = AccountManager.get(this@LengthyOperationsService)
return@let AccountUtils.getAccountDetails(am, key, true)
}
this.text = draft.text
this.media = draft.media
this.recipient_ids = extras.recipientIds
this.conversation_id = extras.conversationId
}
sendMessage(message)
}
Draft.Action.FAVORITE -> {
performStatusAction(draft) { accountKey, status ->
CreateFavoriteTask(this, accountKey, status)
}
}
Draft.Action.RETWEET -> {
performStatusAction(draft) { accountKey, status ->
RetweetStatusTask(this, accountKey, status)
}
}
}
}
private fun handleDiscardDraftIntent(intent: Intent) {
val data = intent.data ?: return
task {
if (deleteDrafts(longArrayOf(data.lastPathSegment.toLongOr(-1L))) < 1) {
throw IOException()
}
return@task data
}.successUi { uri ->
notificationManager.cancel(uri.toString(), NOTIFICATION_ID_DRAFTS)
}
}
private fun handleSendDirectMessageIntent(intent: Intent) {
val message = intent.getParcelableExtra<ParcelableNewMessage>(EXTRA_MESSAGE) ?: return
sendMessage(message)
}
private fun sendMessage(message: ParcelableNewMessage) {
val title = getString(R.string.sending_direct_message)
val builder = NotificationChannelSpec.backgroundProgresses.notificationBuilder(this)
builder.setSmallIcon(R.drawable.ic_stat_send)
builder.setProgress(100, 0, true)
builder.setTicker(title)
builder.setContentTitle(title)
builder.setContentText(message.text)
builder.setCategory(NotificationCompat.CATEGORY_PROGRESS)
builder.setOngoing(true)
val notification = builder.build()
startForeground(NOTIFICATION_ID_SEND_DIRECT_MESSAGE, notification)
val task = SendMessageTask(this)
task.params = message
invokeBeforeExecute(task)
val result = ManualTaskStarter.invokeExecute(task)
invokeAfterExecute(task, result)
if (result.hasData()) {
showToast(R.string.message_direct_message_sent, false)
} else {
UpdateStatusTask.saveDraft(this, Draft.Action.SEND_DIRECT_MESSAGE) {
account_keys = arrayOf(message.account.key)
text = message.text
media = message.media
action_extras = SendDirectMessageActionExtras().apply {
recipientIds = message.recipient_ids
conversationId = message.conversation_id
}
}
val exception = result.exception
if (exception != null) {
showToast(exception, true)
}
}
stopForeground(false)
notificationManager.cancel(NOTIFICATION_ID_SEND_DIRECT_MESSAGE)
}
private fun handleUpdateStatusIntent(intent: Intent) {
val status = intent.getParcelableExtra<ParcelableStatusUpdate>(EXTRA_STATUS)
val statusParcelables = intent.getNullableTypedArrayExtra<ParcelableStatusUpdate>(EXTRA_STATUSES)
val scheduleInfo = intent.getParcelableExtra<ScheduleInfo>(EXTRA_SCHEDULE_INFO)
val statuses: Array<ParcelableStatusUpdate>
if (statusParcelables != null) {
statuses = statusParcelables
} else if (status != null) {
statuses = arrayOf(status)
} else
return
@Draft.Action
val actionType = intent.getStringExtra(EXTRA_ACTION)
statuses.forEach { it.draft_action = actionType }
updateStatuses(statuses, scheduleInfo)
}
private fun updateStatuses(statuses: Array<ParcelableStatusUpdate>, scheduleInfo: ScheduleInfo? = null) {
val context = this
val builder = NotificationChannelSpec.backgroundProgresses.notificationBuilder(context)
startForeground(NOTIFICATION_ID_UPDATE_STATUS, updateUpdateStatusNotification(context,
builder, 0, null))
for (item in statuses) {
val task = UpdateStatusTask(context, object : UpdateStatusTask.StateCallback {
@WorkerThread
override fun onStartUploadingMedia() {
startForeground(NOTIFICATION_ID_UPDATE_STATUS, updateUpdateStatusNotification(context,
builder, 0, item))
}
@WorkerThread
override fun onUploadingProgressChanged(index: Int, current: Long, total: Long) {
val progress = (current * 100 / total).toInt()
startForeground(NOTIFICATION_ID_UPDATE_STATUS, updateUpdateStatusNotification(context,
builder, progress, item))
}
@WorkerThread
override fun onShorteningStatus() {
startForeground(NOTIFICATION_ID_UPDATE_STATUS, updateUpdateStatusNotification(context,
builder, 0, item))
}
@WorkerThread
override fun onUpdatingStatus() {
startForeground(NOTIFICATION_ID_UPDATE_STATUS, updateUpdateStatusNotification(context,
builder, 0, item))
}
@UiThread
override fun afterExecute(result: UpdateStatusTask.UpdateStatusResult) {
var failed = false
val exception = result.exception
val exceptions = result.exceptions
if (exception != null) {
val cause = exception.cause
if (cause is MicroBlogException) {
Toast.makeText(context, cause.errors?.firstOrNull()?.message ?: cause.message,
Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, exception.message, Toast.LENGTH_SHORT).show()
}
failed = true
Log.w(LOGTAG, exception)
} else for (e in exceptions) {
if (e != null) {
// Show error
val errorMessage = e.getErrorMessage(context)
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
failed = true
break
}
}
if (!failed) {
if (scheduleInfo != null) {
Toast.makeText(context, R.string.message_toast_status_scheduled,
Toast.LENGTH_SHORT).show()
} else if (item.repost_status_id != null ||
item.draft_action == Draft.Action.QUOTE) {
Toast.makeText(context, R.string.message_toast_status_retweeted,
Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, R.string.message_toast_status_updated,
Toast.LENGTH_SHORT).show()
}
}
}
override fun beforeExecute() {
}
})
task.callback = this
task.params = Pair(item, scheduleInfo)
invokeBeforeExecute(task)
val result = ManualTaskStarter.invokeExecute(task)
invokeAfterExecute(task, result)
if (!result.succeed) {
contentResolver.insert(Drafts.CONTENT_URI_NOTIFICATIONS.withAppendedPath(result.draftId.toString()), null)
}
}
if (preferences[refreshAfterTweetKey]) {
handler.post { twitterWrapper.refreshAll() }
}
stopForeground(false)
notificationManager.cancel(NOTIFICATION_ID_UPDATE_STATUS)
}
@Throws(IOException::class, MicroBlogException::class)
private fun uploadMedia(upload: TwitterUpload, body: Body): MediaUploadResponse {
val mediaType = body.contentType().contentType
val length = body.length()
val stream = body.stream()
var response = upload.initUploadMedia(mediaType, length, null, null)
val segments = if (length == 0L) 0 else (length / BULK_SIZE + 1).toInt()
for (segmentIndex in 0 until segments) {
val currentBulkSize = Math.min(BULK_SIZE, length - segmentIndex * BULK_SIZE).toInt()
val bulk = SimpleBody(ContentType.OCTET_STREAM, null, currentBulkSize.toLong(),
stream)
upload.appendUploadMedia(response.id, segmentIndex, bulk)
}
response = upload.finalizeUploadMedia(response.id)
run {
var info: ProcessingInfo? = response.processingInfo
while (info != null && shouldWaitForProcess(info)) {
val checkAfterSecs = info.checkAfterSecs
if (checkAfterSecs <= 0) {
break
}
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(checkAfterSecs))
} catch (e: InterruptedException) {
break
}
response = upload.getUploadMediaStatus(response.id)
info = response.processingInfo
}
}
val info = response.processingInfo
if (info != null && ProcessingInfo.State.FAILED == info.state) {
val exception = MicroBlogException()
val errorInfo = info.error
if (errorInfo != null) {
exception.errors = arrayOf(errorInfo)
}
throw exception
}
return response
}
private fun shouldWaitForProcess(info: ProcessingInfo): Boolean {
when (info.state) {
ProcessingInfo.State.PENDING, ProcessingInfo.State.IN_PROGRESS -> return true
else -> return false
}
}
private fun <T> performStatusAction(draft: Draft, action: (accountKey: UserKey, status: ParcelableStatus) -> AbstractTask<*, T, *>): Boolean {
val accountKey = draft.account_keys?.firstOrNull() ?: return false
val status = (draft.action_extras as? StatusObjectActionExtras)?.status ?: return false
val task = action(accountKey, status)
invokeBeforeExecute(task)
val result = ManualTaskStarter.invokeExecute(task)
invokeAfterExecute(task, result)
return true
}
private fun invokeBeforeExecute(task: AbstractTask<*, *, *>) {
handler.post { ManualTaskStarter.invokeBeforeExecute(task) }
}
private fun <T> invokeAfterExecute(task: AbstractTask<*, T, *>, result: T) {
handler.post { ManualTaskStarter.invokeAfterExecute(task, result) }
}
companion object {
private val BULK_SIZE = (128 * 1024).toLong() // 128KiB
private fun updateSendDirectMessageNotification(context: Context,
builder: NotificationCompat.Builder,
progress: Int, message: String?): Notification {
builder.setContentTitle(context.getString(R.string.sending_direct_message))
if (message != null) {
builder.setContentText(message)
}
builder.setSmallIcon(R.drawable.ic_stat_send)
builder.setProgress(100, progress, progress >= 100 || progress <= 0)
builder.setOngoing(true)
return builder.build()
}
private fun updateUpdateStatusNotification(context: Context,
builder: NotificationCompat.Builder,
progress: Int,
status: ParcelableStatusUpdate?): Notification {
builder.setContentTitle(context.getString(R.string.updating_status_notification))
if (status != null) {
builder.setContentText(status.text)
}
builder.setSmallIcon(R.drawable.ic_stat_send)
builder.setProgress(100, progress, progress >= 100 || progress <= 0)
builder.setOngoing(true)
return builder.build()
}
fun updateStatusesAsync(context: Context, @Draft.Action action: String,
vararg statuses: ParcelableStatusUpdate, scheduleInfo: ScheduleInfo? = null) {
val intent = Intent(context, LengthyOperationsService::class.java)
intent.action = INTENT_ACTION_UPDATE_STATUS
intent.putExtra(EXTRA_STATUSES, statuses)
intent.putExtra(EXTRA_SCHEDULE_INFO, scheduleInfo)
intent.putExtra(EXTRA_ACTION, action)
context.startService(intent)
}
fun sendMessageAsync(context: Context, message: ParcelableNewMessage) {
val intent = Intent(context, LengthyOperationsService::class.java)
intent.action = INTENT_ACTION_SEND_DIRECT_MESSAGE
intent.putExtra(EXTRA_MESSAGE, message)
context.startService(intent)
}
}
} | gpl-3.0 | 0f07303d7a871d482a65bf9bbe6c4ea7 | 43.127803 | 146 | 0.618089 | 4.982278 | false | false | false | false |
Xenoage/Zong | core/src/com/xenoage/zong/core/instrument/PitchedInstrument.kt | 1 | 824 | package com.xenoage.zong.core.instrument
import com.xenoage.zong.core.music.Pitch
/**
* Pitched instrument, like piano or trumpet.
*/
class PitchedInstrument(
id: String
) : Instrument(id) {
/** The MIDI program used for playback */
var midiProgram = 0
set(midiProgram) {
field = if (midiProgram in 0..128) midiProgram else
throw IllegalArgumentException("MIDI program must be between 0 and 127")
}
/** The transposition information */
var transpose: Transpose = Transpose.noTranspose
/** The bottommost playable note (in notation) */
var bottomPitch: Pitch? = null
/** The topmost playable note (in notation) */
var topPitch: Pitch? = null
/**
* The number of notes that can be played at the same time on
* this instrument, or 0 if there is no limit.
*/
var polyphonic: Int = 0
}
| agpl-3.0 | 688c25b803f23af8248be86950cf64aa | 23.235294 | 76 | 0.700243 | 3.419087 | false | false | false | false |
hannesa2/owncloud-android | owncloudApp/src/main/java/com/owncloud/android/presentation/adapters/sharing/ShareUserListAdapter.kt | 2 | 3782 | /*
* ownCloud Android client application
*
* @author masensio
* @author Christian Schabesberger
* @author David Gonzรกlez Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.presentation.adapters.sharing
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import com.owncloud.android.R
import com.owncloud.android.domain.sharing.shares.model.OCShare
import com.owncloud.android.domain.sharing.shares.model.ShareType
import com.owncloud.android.utils.PreferenceUtils
/**
* Adapter to show a user/group in Share With List
*/
class ShareUserListAdapter(
private val mContext: Context, resource: Int,
private var shares: List<OCShare>,
private val listener: ShareUserAdapterListener
) : ArrayAdapter<OCShare>(mContext, resource) {
init {
shares = shares.sortedBy { it.sharedWithDisplayName }
}
override fun getCount(): Int = shares.size
override fun getItem(position: Int): OCShare? = shares[position]
override fun getItemId(position: Int): Long = 0
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflator = mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflator.inflate(R.layout.share_user_item, parent, false)
// Allow or disallow touches with other visible windows
view.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(mContext)
if (shares.size > position) {
val share = shares[position]
val userName = view.findViewById<TextView>(R.id.userOrGroupName)
val iconView = view.findViewById<ImageView>(R.id.icon)
var name = share.sharedWithDisplayName
name = if (share.sharedWithAdditionalInfo!!.isEmpty())
name
else
name + " (" + share.sharedWithAdditionalInfo + ")"
var icon = context.resources.getDrawable(R.drawable.ic_user, null)
iconView.tag = R.drawable.ic_user
if (share.shareType == ShareType.GROUP) {
name = context.getString(R.string.share_group_clarification, name)
icon = context.resources.getDrawable(R.drawable.ic_group, null)
iconView.tag = R.drawable.ic_group
}
userName.text = name
iconView.setImageDrawable(icon)
/// bind listener to edit privileges
val editShareButton = view.findViewById<ImageView>(R.id.editShareButton)
editShareButton.setOnClickListener { listener.editShare(shares[position]) }
/// bind listener to unshare
val unshareButton = view.findViewById<ImageView>(R.id.unshareButton)
unshareButton.setOnClickListener { listener.unshareButtonPressed(shares[position]) }
}
return view
}
interface ShareUserAdapterListener {
fun unshareButtonPressed(share: OCShare)
fun editShare(share: OCShare)
}
}
| gpl-2.0 | c6f616fc9b94a0d0935d94dcfa705f78 | 37.191919 | 111 | 0.697699 | 4.506555 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/concurrency/Task.kt | 1 | 5120 | package au.com.codeka.warworlds.client.concurrency
import au.com.codeka.warworlds.client.concurrency.RunnableTask.*
import kotlin.collections.ArrayList
/**
* Wrapper for a "task", which allows chaining of following tasks (via [.then]) and handling
* of errors (via [.error]).
*
* @param <P> the type of the input parameter to this task. Can be Void if you want nothing.
* @param <R> the type of the return value from the task. Can be Void if you want nothing.
*/
open class Task<P, R> internal constructor(private val taskRunner: TaskRunner) {
private var thenTasks: MutableList<Task<R, *>>? = null
private var errorTasks: MutableList<Task<Exception?, Void?>>? = null
private val lock = Any()
private var finished = false
private var result: R? = null
private var error: Exception? = null
open fun run(param: P?) {}
protected fun onComplete(result: R?) {
synchronized(lock) {
finished = true
this.result = result
val remaining = thenTasks ?: return
thenTasks = null
for (task in remaining) {
taskRunner.runTask(task, result)
}
}
}
protected fun onError(error: Exception?) {
synchronized(lock) {
finished = true
this.error = error
if (errorTasks != null) {
for (task in errorTasks!!) {
taskRunner.runTask(task, null)
}
errorTasks = null
}
}
}
/**
* Queues up the given [Task] to run after this task. It will be handed this task's result
* as it's parameter.
* @param task The task to queue after this task completes.
* @return The new task (so you can chain .then().then().then() calls to get tasks to run one
* after the other.
*/
fun <TR> then(task: Task<R, TR>): Task<R, TR> {
synchronized(lock) {
if (finished) {
if (error == null) {
taskRunner.runTask(task, result)
}
return task
}
val remaining = thenTasks ?: ArrayList()
remaining.add(task)
thenTasks = remaining
}
return task
}
/**
* Queues the given runnable to run after this task. If this task returns a result, obviously the
* runnable will not know what it was.
*
* @param runnable The runnable to run after this task completes.
* @param thread The [Threads] on which to run the runnable.
* @return The new task (so you can chain .then().then().then() calls to get tasks to run one
* after the other.
*/
fun then(runnable: Runnable?, thread: Threads): Task<R, Void> {
return then(RunnableTask(taskRunner, runnable, thread))
}
/**
* Queues the given runnable to run after this task. If this task returns a result, obviously the
* runnable will not know what it was.
*
* @param runnable The runnable to run after this task completes.
* @param thread The [Threads] on which to run the runnable.
* @return The new task (so you can chain .then().then().then() calls to get tasks to run one
* after the other.
*/
fun then(runnable: RunnableP<R>?, thread: Threads): Task<R, Void> {
return then(RunnableTask(taskRunner, runnable, thread))
}
/**
* Queues the given runnable to run after this task. If this task returns a result, obviously the
* runnable will not know what it was.
*
* @param runnable The runnable to run after this task completes.
* @param thread The [Threads] on which to run the runnable.
* @return The new task (so you can chain .then().then().then() calls to get tasks to run one
* after the other.
*/
fun <RR> then(runnable: RunnableR<RR>?, thread: Threads): Task<R, RR> {
return then(RunnableTask(taskRunner, runnable, thread))
}
/**
* Queues the given runnable to run after this task. If this task returns a result, obviously the
* runnable will not know what it was.
*
* @param runnable The runnable to run after this task completes.
* @param thread The [Threads] on which to run the runnable.
* @return The new task (so you can chain .then().then().then() calls to get tasks to run one
* after the other.
*/
fun <RR> then(runnable: RunnablePR<R, RR>?, thread: Threads): Task<R, RR> {
return then(RunnableTask(taskRunner, runnable, thread))
}
/**
* Queue a task to run in case there's an exception running the current task.
*
* @param task The task to run if there's an error.
* @return The current task, so you can queue up calls like task.error().then() to handle both
* the error case and the 'next' case.
*/
fun error(task: Task<Exception?, Void?>): Task<P, R> {
synchronized(lock) {
if (finished) {
if (error != null) {
taskRunner.runTask(task, error)
}
return this
}
if (errorTasks == null) {
errorTasks = ArrayList()
}
errorTasks!!.add(task)
}
return this
}
fun error(runnable: Runnable?, thread: Threads): Task<P, R> {
return error(RunnableTask(taskRunner, runnable, thread))
}
fun error(runnable: RunnableP<Exception?>?, thread: Threads): Task<P, R> {
return error(RunnableTask(taskRunner, runnable, thread))
}
} | mit | 74499c96b577b2c8554e90335a52472c | 32.253247 | 99 | 0.648438 | 3.959783 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/types/ty/TyFunction.kt | 3 | 1418 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.TypeVisitor
import org.rust.lang.core.types.mergeFlags
data class TyFunction(
val paramTypes: List<Ty>,
val retType: Ty,
override val aliasedBy: BoundElement<RsTypeAlias>? = null
) : Ty(mergeFlags(paramTypes) or retType.flags) {
override fun superFoldWith(folder: TypeFolder): Ty =
TyFunction(paramTypes.map { it.foldWith(folder) }, retType.foldWith(folder), aliasedBy?.foldWith(folder))
override fun superVisitWith(visitor: TypeVisitor): Boolean =
paramTypes.any { it.visitWith(visitor) } || retType.visitWith(visitor)
override fun withAlias(aliasedBy: BoundElement<RsTypeAlias>): Ty = copy(aliasedBy = aliasedBy)
override fun isEquivalentToInner(other: Ty): Boolean {
if (this === other) return true
if (other !is TyFunction) return false
if (paramTypes.size != other.paramTypes.size) return false
for (i in paramTypes.indices) {
if (!paramTypes[i].isEquivalentTo(other.paramTypes[i])) return false
}
if (!retType.isEquivalentTo(other.retType)) return false
return true
}
}
| mit | aa5ac3b8a2bd6c34f53a66995c78b76c | 34.45 | 113 | 0.710155 | 4.051429 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/inspections/borrowck/RsBorrowCheckerFixesTest.kt | 4 | 3160 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.borrowck
import org.rust.ProjectDescriptor
import org.rust.WithStdlibRustProjectDescriptor
import org.rust.ide.inspections.RsBorrowCheckerInspection
import org.rust.ide.inspections.RsInspectionsTestBase
class RsBorrowCheckerFixesTest : RsInspectionsTestBase(RsBorrowCheckerInspection::class) {
fun `test derive copy on struct`() = checkFixByText("Derive Copy trait", """
struct S;
fn main() {
let x = S;
let y = x;
<error descr="Use of moved value">x<caret></error>;
}
""", """
#[derive(Clone, Copy)]
struct S;
fn main() {
let x = S;
let y = x;
x;
}
""", checkWarn = false)
fun `test derive copy on struct with attr`() = checkFixByText("Derive Copy trait", """
#[derive(PartialOrd, /* come comment */ PartialEq)]
struct S;
fn main() {
let x = S;
let y = x;
<error descr="Use of moved value">x<caret></error>;
}
""", """
#[derive(PartialOrd, /* come comment */ PartialEq, Clone, Copy)]
struct S;
fn main() {
let x = S;
let y = x;
x;
}
""", checkWarn = false)
fun `test derive copy on enum`() = checkFixByText("Derive Copy trait", """
enum E { One }
fn main() {
let x = E::One;
let y = x;
<error descr="Use of moved value">x<caret></error>;
}
""", """
#[derive(Clone, Copy)]
enum E { One }
fn main() {
let x = E::One;
let y = x;
x;
}
""", checkWarn = false)
fun `test derive copy is unavailable on non-copyable enum`() = checkFixIsUnavailable("Derive Copy trait", """
struct S;
enum E { One, Two(S) }
fn main() {
let x = E::One;
let y = x;
<error descr="Use of moved value">x<caret></error>;
}
""", checkWarn = false)
fun `test derive copy is unavailable on non-copyable struct`() = checkFixIsUnavailable("Derive Copy trait", """
struct T;
struct S { data: T }
fn main() {
let x = S { data: T };
x.data;
<error descr="Use of moved value">x.data</error><caret>;
}
""", checkWarn = false)
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
fun `test derive copy on struct with impl clone`() = checkFixByText("Derive Copy trait", """
struct S;
impl Clone for S { fn clone(&self) -> S { unimplemented!() } }
fn main() {
let x = S;
let y = x;
<error descr="Use of moved value">x<caret></error>;
}
""", """
#[derive(Copy)]
struct S;
impl Clone for S { fn clone(&self) -> S { unimplemented!() } }
fn main() {
let x = S;
let y = x;
x;
}
""", checkWarn = false)
}
| mit | bdfced25d167fec5626c5d2052b66cf1 | 26.241379 | 115 | 0.504747 | 4.224599 | false | true | false | false |
applivery/applivery-android-sdk | applvsdklib/src/main/java/com/applivery/applvsdklib/ui/views/login/LoginView.kt | 1 | 1923 | /*
* Copyright (c) 2019 Applivery
*
* 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.applivery.applvsdklib.ui.views.login
import android.app.Activity
import android.app.AlertDialog
import com.applivery.applvsdklib.R
import com.applivery.applvsdklib.domain.model.UserData
import com.applivery.applvsdklib.tools.injection.Injection
class LoginView(private val activity: Activity, private val onSuccess: () -> Unit = {}) {
val presenter: LoginPresenter = Injection.provideLoginPresenter()
init {
presenter.view = this
}
fun showLoginDialog() {
if (activity.fragmentManager.findFragmentByTag(TAG) != null) {
return
}
val loginDialog = LoginDialog()
loginDialog.listener = { username, password ->
presenter.makeLogin(UserData(username = username, password = password))
}
loginDialog.show(activity.fragmentManager, TAG)
}
fun showLoginSuccess() {
onSuccess()
}
fun showLoginError() {
val alertDialog = AlertDialog.Builder(activity).create()
alertDialog.setTitle(activity.getString(R.string.appliveryLoginFailDielogTitle))
alertDialog.setMessage(activity.getString(R.string.appliveryLoginFailDielogText))
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK") { dialog, _ ->
showLoginDialog()
dialog.dismiss()
}
alertDialog.show()
}
companion object {
private const val TAG = "LoginView"
}
}
| apache-2.0 | 3790b86502732680b055a6247bf8ce97 | 29.046875 | 89 | 0.731669 | 4.282851 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/graphql/mutation/src/test/kotlin/org/tsdes/advanced/graphql/mutation/MutationGraphQLApplicationTest.kt | 1 | 6526 | package org.tsdes.advanced.graphql.mutation
import io.restassured.RestAssured
import io.restassured.RestAssured.given
import io.restassured.http.ContentType
import org.hamcrest.Matchers.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.test.context.junit.jupiter.SpringExtension
@ExtendWith(SpringExtension::class)
@SpringBootTest(classes = [MutationGraphQLApplication::class],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MutationGraphQLApplicationTest {
@LocalServerPort
protected var port = 0
@Autowired
private lateinit var repository: UserRepository
@BeforeEach
fun clean() {
// RestAssured configs shared by all the tests
RestAssured.baseURI = "http://localhost"
RestAssured.port = port
RestAssured.basePath = "/graphql"
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails()
repository.clear()
}
@Test
fun testEmpty() {
given().accept(ContentType.JSON)
.queryParam("query", "{all{id}}")
.get()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.all.size()", equalTo(0))
}
@Test
fun testNotFound(){
given().accept(ContentType.JSON)
.queryParam("query", """
{findById(id:"-1"){id, name, surname, age}}"
""".trimIndent())
.get()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.findById", equalTo(null))
}
@Test
fun testCreateUser() {
val name = "Foo"
val id = given().accept(ContentType.JSON)
.contentType(ContentType.JSON)
.body("""
{ "query" : "mutation{create(name:\"$name\", surname:\"Bar\", age: 18)}" }
""".trimIndent())
.post()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.create", notNullValue())
.extract().body().path<String>("data.create")
given().accept(ContentType.JSON)
.queryParam("query", "{all{id}}")
.get()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.all.size()", equalTo(1))
given().accept(ContentType.JSON)
.queryParam("query", """
{findById(id:"$id"){id, name, surname, age}}"
""".trimIndent())
.get()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.findById.name", equalTo(name))
}
@Test
fun wrongMethodForMutation() {
val query = """
mutation{create(name:\"Foo\", surname:\"Bar\", age: 18)}
""".trimIndent()
given().accept(ContentType.JSON)
.contentType(ContentType.JSON)
.queryParam("query", query)
.body("""
{ "query" : "$query" }
""".trimIndent())
.post()
.then()
.statusCode(200)
//works fine
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
given().accept(ContentType.JSON)
.queryParam("query", query.replace('\\',' '))
.get()
.then()
.statusCode(200)
//fails
.body("data", equalTo(null))
.body("$", hasKey("errors"))
}
@Test
fun testUpdate(){
val name = "Foo"
val changedName = "Changed"
val id = given().accept(ContentType.JSON)
.contentType(ContentType.JSON)
.body("""
{ "query" : "mutation{create(name:\"$name\", surname:\"Bar\", age: 18)}" }
""".trimIndent())
.post()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.create", notNullValue())
.extract().body().path<String>("data.create")
given().accept(ContentType.JSON)
.contentType(ContentType.JSON)
.body("""
{ "query" :
"mutation{update(user:{id:\"$id\",name:\"$changedName\",surname:\"Bar\",age: 18})}"
}
""".trimIndent())
.post()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.update", equalTo(true))
given().accept(ContentType.JSON)
.queryParam("query", """
{findById(id:"$id"){id, name, surname, age}}"
""".trimIndent())
.get()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.findById.name", equalTo(changedName))
}
@Test
fun testUpdateNonExistent(){
given().accept(ContentType.JSON)
.contentType(ContentType.JSON)
.body("""
{ "query" :
"mutation{update(user:{id:\"-1\",name:\"Foo\",surname:\"Bar\",age: 18})}"
}
""".trimIndent())
.post()
.then()
.statusCode(200)
.body("$", hasKey("data"))
.body("$", not(hasKey("errors")))
.body("data.update", equalTo(false))
}
} | lgpl-3.0 | 9f555bf0dc2f1891603460ffbee8fa07 | 30.531401 | 108 | 0.463377 | 5.004601 | false | true | false | false |
androidx/androidx | window/window-samples/src/main/java/androidx/window/sample/demos/WindowDemosActivity.kt | 3 | 3402 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.sample.demos
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.window.sample.DisplayFeaturesConfigChangeActivity
import androidx.window.sample.DisplayFeaturesNoConfigChangeActivity
import androidx.window.sample.ImeActivity
import androidx.window.sample.PresentationActivity
import androidx.window.sample.R
import androidx.window.sample.R.string.display_features_config_change
import androidx.window.sample.R.string.display_features_no_config_change
import androidx.window.sample.R.string.show_all_display_features_config_change_description
import androidx.window.sample.R.string.show_all_display_features_no_config_change_description
import androidx.window.sample.SplitLayoutActivity
import androidx.window.sample.WindowMetricsActivity
/**
* Main activity that launches WindowManager demos.
*/
class WindowDemosActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_window_demos)
val demoItems = listOf(
DemoItem(
buttonTitle = getString(display_features_config_change),
description = getString(show_all_display_features_config_change_description),
clazz = DisplayFeaturesConfigChangeActivity::class.java
),
DemoItem(
buttonTitle = getString(display_features_no_config_change),
description = getString(show_all_display_features_no_config_change_description),
clazz = DisplayFeaturesNoConfigChangeActivity::class.java
),
DemoItem(
buttonTitle = getString(R.string.window_metrics),
description = getString(R.string.window_metrics_description),
clazz = WindowMetricsActivity::class.java
),
DemoItem(
buttonTitle = getString(R.string.split_layout),
description = getString(R.string.split_layout_demo_description),
clazz = SplitLayoutActivity::class.java
),
DemoItem(
buttonTitle = getString(R.string.presentation),
description = getString(R.string.presentation_demo_description),
clazz = PresentationActivity::class.java
),
DemoItem(
buttonTitle = getString(R.string.ime),
description = getString(R.string.ime_demo_description),
clazz = ImeActivity::class.java
)
)
val recyclerView = findViewById<RecyclerView>(R.id.demo_recycler_view)
recyclerView.adapter = DemoAdapter(demoItems)
}
} | apache-2.0 | 7123258e1a988f2d14413b2787621946 | 42.628205 | 96 | 0.695767 | 4.692414 | false | true | false | false |
holisticon/ranked | backend/views/player/src/main/kotlin/PlayerView.kt | 1 | 2829 | @file:Suppress("UNUSED")
package de.holisticon.ranked.view.player
import de.holisticon.ranked.model.Player
import de.holisticon.ranked.model.UserName
import de.holisticon.ranked.model.event.PlayerCreated
import de.holisticon.ranked.model.event.TeamCreated
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import mu.KLogging
import org.axonframework.config.ProcessingGroup
import org.axonframework.eventhandling.EventHandler
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@ProcessingGroup(PlayerViewService.NAME)
@RestController
@Api(tags = ["Players", "Teams"])
@RequestMapping(value = ["/view"])
class PlayerViewService {
companion object : KLogging() {
const val NAME = "Player"
}
val players: MutableSet<Player> = mutableSetOf()
val teams: MutableSet<TeamFull> = mutableSetOf()
// candidates of teams (missing user, denoted by the username, if both a re missing, the event is stored twice)
val candidates: MutableMap<UserName, TeamCreated> = mutableMapOf()
@ApiOperation(value = "Lists all players")
@GetMapping("/player")
fun findAllPlayers() = players.sortedBy { it.userName.value }
@ApiOperation(value = "Lists all teams")
@GetMapping("/teams")
fun findAllTeams() = teams.sortedBy { it.name }
@ApiOperation(value = "Get player by userName")
@GetMapping("/player/{userName}")
fun findPlayer(@PathVariable("userName") userName: String) = players.find { userName == it.userName.value }
@EventHandler
fun on(e: PlayerCreated) {
players.add(
Player(
userName = e.userName,
displayName = e.displayName,
imageUrl = e.imageUrl,
eloRanking = e.initialElo
))
// try to add team, if it was a candidate
val candidate = candidates[e.userName]
if (candidate != null) {
addTeam(candidate)
}
}
@EventHandler
fun on (e: TeamCreated) {
// store the candidate
candidates[e.team.player1] = e
candidates[e.team.player2] = e
// try to add team
addTeam(e)
}
fun addTeam(e: TeamCreated) {
val player1 = players.find { e.team.player1 == it.userName }
val player2 = players.find { e.team.player2 == it.userName }
if (player1 != null && player2 != null) {
teams.add(TeamFull(
name = e.name,
id = e.id,
imageUrl = e.imageUrl,
player1 = player1,
player2 = player2
))
// remove
candidates.remove(e.team.player1)
candidates.remove(e.team.player2)
}
}
}
data class TeamFull(
val name: String,
val id: String,
val imageUrl: String,
val player1 : Player,
val player2 : Player
)
| bsd-3-clause | 219124c3ab9d223a974fd990611ac9e7 | 26.466019 | 113 | 0.69848 | 3.896694 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui-test/src/org/jetbrains/kotlin/ui/tests/editors/navigation/library/NavigationTestLibrary.kt | 1 | 4929 | package org.jetbrains.kotlin.ui.tests.editors.navigation.library
import org.jetbrains.kotlin.testframework.utils.TestJavaProject
import org.jetbrains.kotlin.core.compiler.KotlinCompiler
import org.eclipse.core.runtime.Path
import java.io.File
import org.eclipse.jdt.core.IPackageFragmentRoot
import org.eclipse.core.resources.IFolder
import java.io.InputStream
import org.eclipse.core.runtime.CoreException
import java.util.jar.JarOutputStream
import java.io.FileOutputStream
import java.util.jar.Manifest
import java.util.jar.JarEntry
import java.io.FileInputStream
import java.io.BufferedInputStream
import kotlin.io.use
import org.eclipse.jdt.internal.compiler.util.Util.isClassFileName
import org.eclipse.core.resources.IResource
import java.util.zip.ZipOutputStream
import java.util.zip.ZipEntry
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import org.jetbrains.kotlin.core.launch.KotlinCLICompiler
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import java.io.Reader
import org.jetbrains.kotlin.core.compiler.KotlinCompiler.KotlinCompilerResult
import org.jetbrains.kotlin.core.launch.CompilerOutputData
import java.util.ArrayList
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.core.launch.CompilerOutputParser
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import java.io.BufferedReader
import java.io.StringReader
import org.jetbrains.kotlin.core.utils.ProjectUtils
import org.junit.Assert
import org.jetbrains.kotlin.cli.common.ExitCode
public data class TestLibraryData(val libPath: String, val srcPath: String)
public fun getTestLibrary() =
NavigationTestLibrary().let {
TestLibraryData(it.libraryPath, it.sourceArchivePath)
}
public fun TestLibraryData.clean() {
File(libPath).delete()
File(srcPath).delete()
}
private class NavigationTestLibrary {
private val srcFolderName = "src"
private val targetFolderName = "target"
public val commonArtifactName: String = "kotlin-navigation-test-lib"
private val testDataRootFolder = File("testData/navigation/lib/")
private val srcPath = File(testDataRootFolder, srcFolderName)
private val libraryFile: File
private val sourceArchiveFile: File
public val libraryPath: String
get() {
return libraryFile.getAbsolutePath()
}
public val sourceArchivePath: String
get() {
return sourceArchiveFile.getAbsolutePath()
}
init {
val targetFolder = File(testDataRootFolder, targetFolderName)
if (!targetFolder.exists()) {
targetFolder.mkdir()
}
libraryFile = File(targetFolder, "${commonArtifactName}.jar")
if (!libraryFile.exists()) {
runCompiler(libraryFile)
}
sourceArchiveFile = File(targetFolder, "${commonArtifactName}-sources.zip")
if (!sourceArchiveFile.exists()) {
createSourceArchive(sourceArchiveFile, srcPath)
}
}
public fun clean() {
libraryFile.delete()
sourceArchiveFile.delete();
}
private fun createSourceArchive(targetFile: File, contentsDir: File) {
val stream = ZipOutputStream(FileOutputStream(targetFile))
stream.use {
writeEntriesToJarRecursively(stream, contentsDir, "")
}
}
private fun writeEntriesToJarRecursively(stream: ZipOutputStream, contentDir: File, pathPrefix: String) {
contentDir.listFiles().forEach {
val entryName = pathPrefix + it.getName() + if (it.isDirectory()) "/" else ""
when {
it.isDirectory() -> {
stream.putNextEntry(ZipEntry(entryName))
stream.closeEntry()
writeEntriesToJarRecursively(stream, it, entryName)
}
it.isFile() -> {
stream.putNextEntry(ZipEntry(entryName))
val inStream = BufferedInputStream(FileInputStream(it));
inStream.use {
it.copyTo(stream)
}
stream.closeEntry()
}
}
}
}
private fun runCompiler(targetFile: File) {
val targetPath: String = Path(targetFile.getAbsolutePath()).toOSString()
val outputStream = ByteArrayOutputStream();
val out = PrintStream(outputStream);
val exitCode = KotlinCLICompiler.doMain(K2JVMCompiler(), out,
arrayOf("-d", targetPath, "-kotlin-home", ProjectUtils.KT_HOME, srcPath.getAbsolutePath()))
Assert.assertTrue(
"Could not compile test library, exitCode = $exitCode\n ${outputStream.toString()}",
exitCode == ExitCode.OK)
}
}
| apache-2.0 | 6e00e179ff17a94b97eb7e6f5a09e84c | 35.783582 | 109 | 0.683506 | 4.818182 | false | true | false | false |
codebutler/odyssey | retrograde-app-tv/src/main/java/com/codebutler/retrograde/app/feature/settings/AboutFragment.kt | 1 | 1798 | package com.codebutler.retrograde.app.feature.settings
import android.app.Fragment
import android.content.Intent
import android.os.Bundle
import androidx.preference.PreferenceFragment
import androidx.leanback.preference.LeanbackPreferenceFragment
import androidx.leanback.preference.LeanbackSettingsFragment
import androidx.preference.Preference
import androidx.preference.PreferenceScreen
import com.codebutler.retrograde.BuildConfig
import com.codebutler.retrograde.R
class AboutFragment : LeanbackSettingsFragment() {
override fun onPreferenceStartInitialScreen() {
startPreferenceFragment(AboutPrefFragment())
}
override fun onPreferenceStartScreen(caller: PreferenceFragment, pref: PreferenceScreen): Boolean = false
override fun onPreferenceStartFragment(caller: PreferenceFragment, pref: Preference): Boolean {
val fragment = Class.forName(pref.fragment).newInstance() as Fragment
startPreferenceFragment(fragment)
return true
}
class AboutPrefFragment : LeanbackPreferenceFragment() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.about)
val versionPref = findPreference(getString(R.string.pref_key_version))
versionPref.summary = "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})"
}
override fun onPreferenceTreeClick(preference: Preference): Boolean =
when (preference.key) {
getString(R.string.pref_key_licenses) -> {
startActivity(Intent(activity, LicensesActivity::class.java))
true
}
else -> super.onPreferenceTreeClick(preference)
}
}
}
| gpl-3.0 | 56a21a09a3c0e052abf416e483117f71 | 38.955556 | 109 | 0.713571 | 5.481707 | false | true | false | false |
52inc/android-52Kit | library-arch/src/main/java/com/ftinc/kit/arch/util/Kotterknife.kt | 1 | 5932 | /*
* Copyright (c) 2019 52inc.
*
* 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("unused")
package com.ftinc.kit.arch.util
import android.app.Activity
import android.app.Dialog
import android.app.DialogFragment
import android.app.Fragment
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import androidx.fragment.app.DialogFragment as SupportDialogFragment
import androidx.fragment.app.Fragment as SupportFragment
fun <V : View> View.bindView(id: Int)
: ReadOnlyProperty<View, V> = required(id, viewFinder)
fun <V : View> Activity.bindView(id: Int)
: ReadOnlyProperty<Activity, V> = required(id, viewFinder)
fun <V : View> Dialog.bindView(id: Int)
: ReadOnlyProperty<Dialog, V> = required(id, viewFinder)
fun <V : View> SupportDialogFragment.bindView(id: Int)
: ReadOnlyProperty<SupportDialogFragment, V> = required(id, viewFinder)
fun <V : View> SupportFragment.bindView(id: Int)
: ReadOnlyProperty<SupportFragment, V> = required(id, viewFinder)
fun <V : View> ViewHolder.bindView(id: Int)
: ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder)
fun <V : View> View.bindOptionalView(id: Int)
: ReadOnlyProperty<View, V?> = optional(id, viewFinder)
fun <V : View> Activity.bindOptionalView(id: Int)
: ReadOnlyProperty<Activity, V?> = optional(id, viewFinder)
fun <V : View> Dialog.bindOptionalView(id: Int)
: ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder)
fun <V : View> SupportDialogFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportDialogFragment, V?> = optional(id, viewFinder)
fun <V : View> SupportFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportFragment, V?> = optional(id, viewFinder)
fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder)
fun <V : View> View.bindViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = required(ids, viewFinder)
fun <V : View> Activity.bindViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder)
fun <V : View> Dialog.bindViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder)
fun <V : View> SupportDialogFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportDialogFragment, List<V>> = required(ids, viewFinder)
fun <V : View> SupportFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = required(ids, viewFinder)
fun <V : View> ViewHolder.bindViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder)
fun <V : View> View.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder)
fun <V : View> Activity.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder)
fun <V : View> Dialog.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder)
fun <V : View> SupportDialogFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportDialogFragment, List<V>> = optional(ids, viewFinder)
fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, viewFinder)
fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder)
private val View.viewFinder: View.(Int) -> View?
get() = { findViewById(it) }
private val Activity.viewFinder: Activity.(Int) -> View?
get() = { findViewById(it) }
private val Dialog.viewFinder: Dialog.(Int) -> View?
get() = { findViewById(it) }
private val SupportDialogFragment.viewFinder: SupportDialogFragment.(Int) -> View?
get() = { dialog?.findViewById(it) }
private val SupportFragment.viewFinder: SupportFragment.(Int) -> View?
get() = { view!!.findViewById(it) }
private val ViewHolder.viewFinder: ViewHolder.(Int) -> View?
get() = { itemView.findViewById(it) }
private fun viewNotFound(id: Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?) = Lazy { t: T, desc ->
t.finder(id) as V? ?: viewNotFound(id, desc)
}
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?) = Lazy { t: T, _ -> t.finder(id) as V? }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(ids: IntArray, finder: T.(Int) -> View?) = Lazy { t: T, desc ->
ids.map {
t.finder(it) as V? ?: viewNotFound(it, desc)
}
}
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(ids: IntArray, finder: T.(Int) -> View?) = Lazy { t: T, _ -> ids.map { t.finder(it) as V? }.filterNotNull() }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
}
| apache-2.0 | 6f048f64fcbb7f855fb4371bd78ee8a3 | 38.026316 | 144 | 0.709036 | 3.778344 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/util/Extensions.kt | 1 | 3334 | package org.wordpress.aztec.util
import android.content.ClipData
import android.content.Context
import android.text.Editable
import android.text.Spannable
import android.text.Spanned
import android.view.View
import android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK
import android.widget.Button
import android.widget.ToggleButton
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.view.ContextThemeWrapper
import androidx.core.view.AccessibilityDelegateCompat
import androidx.core.view.ViewCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
import org.wordpress.aztec.AztecParser
import org.wordpress.aztec.R
fun Editable.getLast(kind: Class<*>): Any? {
val spans = this.getSpans(0, this.length, kind)
if (spans.isEmpty()) {
return null
} else {
return (spans.size downTo 1)
.firstOrNull { this.getSpanFlags(spans[it - 1]) == Spannable.SPAN_MARK_MARK }
?.let { spans[it - 1] }
}
}
inline fun <reified T> Editable.getLast(): T? {
val spans = this.getSpans(0, this.length, T::class.java)
if (spans.isEmpty()) {
return null
} else {
return (spans.size downTo 1)
.firstOrNull { this.getSpanFlags(spans[it - 1]) == Spannable.SPAN_MARK_MARK }
?.let { spans[it - 1] }
}
}
fun ClipData.Item.coerceToStyledText(context: Context, parser: AztecParser): CharSequence {
val text = text ?: ""
if (text is Spanned) {
return text
}
val html = htmlText ?: ""
return parser.fromHtml(html, context)
}
fun ClipData.Item.coerceToHtmlText(parser: AztecParser): String {
// If the item has an explicit HTML value, simply return that.
val htmlText = htmlText
if (htmlText != null) {
return htmlText
}
// If this Item has a plain text value, return it as HTML.
val text = text ?: ""
if (text is Spanned) {
return parser.toHtml(text)
}
return text.toString()
}
/**
* Some of the toggle button controls that exist on the Aztec formatting toolbar act as buttons but are
* announced as switches so this function converts the accessibility properties to that of a button.
*/
fun ToggleButton.convertToButtonAccessibilityProperties() {
ViewCompat.setAccessibilityDelegate(this, object : AccessibilityDelegateCompat() {
override fun onInitializeAccessibilityNodeInfo(host: View?, info: AccessibilityNodeInfoCompat?) {
super.onInitializeAccessibilityNodeInfo(host, info)
info?.className = Button::class.java.name
info?.isCheckable = false
info?.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat(ACTION_CLICK, context.getString(R.string.accessibility_action_click_label)))
}
})
}
/**
* Method sets a customisable background drawable to all the toolbar buttons.
* The AztecToolbarStyle can be overridden in the main app module to customise the color of the toolbar buttons.
*/
fun ToggleButton.setBackgroundDrawableRes(@DrawableRes backgroundDrawableRes: Int) {
val wrapper = ContextThemeWrapper(context, R.style.AztecToolbarStyle)
val drawable = AppCompatResources.getDrawable(wrapper, backgroundDrawableRes)
this.background = drawable
}
| mpl-2.0 | c83047e66ae13fba85816714f8085f27 | 34.468085 | 158 | 0.717457 | 4.363874 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/view/delegate/ServerListActivityDelegate.kt | 1 | 3792 | /*
* Copyright (c) 2017 ๅคงๅ่ฏไป (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.view.delegate
import android.app.ActivityOptions
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.CallSuper
import androidx.core.view.doOnLayout
import androidx.databinding.DataBindingUtil
import net.mm2d.dmsexplorer.R
import net.mm2d.dmsexplorer.Repository
import net.mm2d.dmsexplorer.databinding.ServerListActivityBinding
import net.mm2d.dmsexplorer.log.EventLogger
import net.mm2d.dmsexplorer.settings.Settings
import net.mm2d.dmsexplorer.view.ContentListActivity
import net.mm2d.dmsexplorer.view.base.BaseActivity
import net.mm2d.dmsexplorer.viewmodel.ServerListActivityModel
import net.mm2d.dmsexplorer.viewmodel.ServerListActivityModel.ServerSelectListener
/**
* @author [ๅคงๅ่ฏไป (OHMAE Ryosuke)](mailto:[email protected])
*/
abstract class ServerListActivityDelegate internal constructor(
protected val activity: BaseActivity,
val binding: ServerListActivityBinding
) : ServerSelectListener {
protected abstract val isTwoPane: Boolean
@CallSuper
open fun onCreate(savedInstanceState: Bundle?) {
val binding = binding
val activity = activity
binding.toolbar.popupTheme = Settings.get().themeParams.popupThemeId
binding.model = ServerListActivityModel(activity, Repository.get(), this, isTwoPane)
activity.setSupportActionBar(binding.toolbar)
activity.supportActionBar?.setTitle(R.string.title_device_select)
if (savedInstanceState != null) {
restoreScroll(savedInstanceState)
}
}
open fun prepareSaveInstanceState() {}
@CallSuper
open fun onSaveInstanceState(outState: Bundle) {
saveScroll(outState)
}
open fun onStart() {}
private fun restoreScroll(savedInstanceState: Bundle) {
val position = savedInstanceState.getInt(KEY_SCROLL_POSITION, 0)
val offset = savedInstanceState.getInt(KEY_SCROLL_OFFSET, 0)
if (position == 0 && offset == 0) {
return
}
val recyclerView = binding.recyclerView
recyclerView.doOnLayout {
recyclerView.scrollToPosition(position)
recyclerView.post { recyclerView.scrollBy(0, offset) }
}
}
private fun saveScroll(outState: Bundle) {
val recyclerView = binding.recyclerView
if (recyclerView.childCount == 0) {
return
}
val view = recyclerView.getChildAt(0)
outState.putInt(KEY_SCROLL_POSITION, recyclerView.getChildAdapterPosition(view))
outState.putInt(KEY_SCROLL_OFFSET, -view.top)
}
companion object {
private const val KEY_SCROLL_POSITION = "KEY_SCROLL_POSITION"
private const val KEY_SCROLL_OFFSET = "KEY_SCROLL_OFFSET"
fun create(activity: BaseActivity): ServerListActivityDelegate {
val binding = DataBindingUtil.setContentView<ServerListActivityBinding>(
activity,
R.layout.server_list_activity
)
return if (binding.serverDetailContainer == null) {
ServerListActivityDelegateOnePane(activity, binding)
} else ServerListActivityDelegateTwoPane(activity, binding)
}
fun startCdsListActivity(
context: Context,
v: View
) {
val intent = ContentListActivity.makeIntent(context)
val option = ActivityOptions
.makeScaleUpAnimation(v, 0, 0, v.width, v.height)
.toBundle()
context.startActivity(intent, option)
EventLogger.sendSelectServer()
}
}
}
| mit | f1ef5a737fdff080aec694a00172ec0c | 33.962963 | 92 | 0.691737 | 4.708229 | false | false | false | false |
0x1bad1d3a/Kaku | app/src/main/java/ca/fuwafuwa/kaku/LangUtils.kt | 1 | 4597 | package ca.fuwafuwa.kaku
class LangUtils {
companion object {
private val KanaHalf: IntArray = intArrayOf(
0x3092, 0x3041, 0x3043, 0x3045, 0x3047, 0x3049, 0x3083, 0x3085,
0x3087, 0x3063, 0x30FC, 0x3042, 0x3044, 0x3046, 0x3048, 0x304A,
0x304B, 0x304D, 0x304F, 0x3051, 0x3053, 0x3055, 0x3057, 0x3059,
0x305B, 0x305D, 0x305F, 0x3061, 0x3064, 0x3066, 0x3068, 0x306A,
0x306B, 0x306C, 0x306D, 0x306E, 0x306F, 0x3072, 0x3075, 0x3078,
0x307B, 0x307E, 0x307F, 0x3080, 0x3081, 0x3082, 0x3084, 0x3086,
0x3088, 0x3089, 0x308A, 0x308B, 0x308C, 0x308D, 0x308F, 0x3093
)
private val KanaVoiced: IntArray = intArrayOf(
0x30F4, 0xFF74, 0xFF75, 0x304C, 0x304E, 0x3050, 0x3052, 0x3054,
0x3056, 0x3058, 0x305A, 0x305C, 0x305E, 0x3060, 0x3062, 0x3065,
0x3067, 0x3069, 0xFF85, 0xFF86, 0xFF87, 0xFF88, 0xFF89, 0x3070,
0x3073, 0x3076, 0x3079, 0x307C
)
private val KanaSemiVoiced: IntArray = intArrayOf(
0x3071, 0x3074, 0x3077, 0x307A, 0x307D
)
fun IsHiragana(char: Char) : Boolean
{
return Character.UnicodeBlock.of(char) == Character.UnicodeBlock.HIRAGANA
}
fun IsKatakana(char: Char) : Boolean
{
return Character.UnicodeBlock.of(char) == Character.UnicodeBlock.KATAKANA
}
fun IsKanji(char: Char) : Boolean
{
val block = Character.UnicodeBlock.of(char)
return block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS ||
block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A ||
block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B ||
block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C ||
block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D
}
fun IsJapaneseChar(char: Char) : Boolean
{
return IsHiragana(char) || IsKatakana(char) || IsKanji(char)
}
fun ConvertKanatanaToHiragana(text: String): String
{
var result: StringBuilder = StringBuilder()
var ordPrev: Int = 0;
for (i in text){
var ordCurr: Int = i.toInt()
// Full-width katakana to hiragana
if ((ordCurr >= 0x30A1) && (ordCurr <= 0x30F3))
{
ordCurr -= 0x60
}
// Half-width katakana to hiragana
else if ((ordCurr >= 0xFF66) && (ordCurr <= 0xFF9D))
{
ordCurr = KanaHalf[ordCurr - 0xFF66]
}
// Voiced (used in half-width katakana) to hiragana
else if (ordCurr == 0xFF9E)
{
if (ordPrev >= 0xFF73 && ordPrev <= 0xFF8E)
{
result.setLength(result.length - 1)
ordCurr = KanaVoiced[ordPrev - 0xFF73]
}
}
// Semi-voiced (used in half-width katakana) to hiragana
else if (ordCurr == 0xFF9F)
{
if (ordPrev >= 0xFF8A && ordPrev <= 0xFF8E)
{
result.setLength(result.length - 1)
ordCurr = KanaSemiVoiced[ordPrev - 0xFF8A]
}
}
// Ignore Japanese ~
else if (ordCurr == 0xFF5E)
{
ordPrev = 0
continue
}
result.append(ordCurr.toChar())
ordPrev = ordCurr
}
return result.toString()
}
fun ConvertIntToCircledNum(num: Int): String
{
var circledNum: String = "($num)"
if (num == 0)
{
circledNum = "โช"
} else if ((num >= 1) && (num <= 20))
{
circledNum = (('โ ' - 1) + num).toString()
}
// Note: Numbers over 20 may depend on font
else if ((num >= 21) && (num <= 35))
{
circledNum = (('ใ' - 21) + num).toString()
}
else if ((num >= 36) && (num <= 50))
{
circledNum = (('ใฑ' - 36) + num).toString()
}
return circledNum
}
}
} | bsd-3-clause | 699a7ca4c2aa30453a9d3a9c526ed791 | 34.859375 | 88 | 0.482458 | 3.538165 | false | false | false | false |
midhunhk/random-contact | app/src/main/java/com/ae/apps/randomcontact/contacts/RandomContactApiGatewayImpl.kt | 1 | 5506 | package com.ae.apps.randomcontact.contacts
import android.content.Context
import com.ae.apps.lib.api.contacts.ContactsApiGateway
import com.ae.apps.lib.api.contacts.types.ContactInfoFilterOptions
import com.ae.apps.lib.api.contacts.types.ContactInfoOptions
import com.ae.apps.lib.api.contacts.types.ContactsApiGatewayFactory
import com.ae.apps.lib.api.contacts.types.ContactsDataConsumer
import com.ae.apps.lib.common.models.ContactInfo
import com.ae.apps.randomcontact.preferences.AppPreferences
import com.ae.apps.randomcontact.room.repositories.ContactGroupRepository
import com.ae.apps.randomcontact.utils.CONTACT_ID_SEPARATOR
import com.ae.apps.randomcontact.utils.DEFAULT_CONTACT_GROUP
import java.util.*
class RandomContactApiGatewayImpl(
private val contactGroupRepository: ContactGroupRepository,
private val contactsApi: ContactsApiGateway,
private val appPreferences: AppPreferences
) : ContactsApiGateway, ContactsDataConsumer {
private var index: Int = 0
private var dataConsumer: ContactsDataConsumer? = null
private var isContactsRead = false
companion object {
@Volatile
private var INSTANCE: ContactsApiGateway? = null
fun getInstance(
context: Context,
contactsGroupRepo: ContactGroupRepository,
contactsApiFactory: ContactsApiGatewayFactory,
appPreferences: AppPreferences
): ContactsApiGateway =
INSTANCE ?: synchronized(this) {
val contactsApi = contactsApiFactory.getContactsApiGateway(context)
INSTANCE ?: RandomContactApiGatewayImpl(
contactsGroupRepo,
contactsApi,
appPreferences
).also { INSTANCE = it }
}
}
override fun initialize(options: ContactInfoFilterOptions?) {
initialize(ContactInfoFilterOptions.of(true))
}
override fun initializeAsync(
options: ContactInfoFilterOptions?,
consumer: ContactsDataConsumer?
) {
// Store the consumer and invoke the onContactsRead on it after our own initialization
dataConsumer = consumer
if (isContactsRead) {
dataConsumer?.onContactsRead()
} else {
contactsApi.initializeAsync(options, this)
}
}
override fun onContactsRead() {
// In order to avoid repetition of contacts, we simply start from a random point in the list of contacts
// Hopefully the user has a very large number of contacts with phone numbers and may not notice :)
// This would be based on the order the contacts were added to the contacts database which should
// be random unless it was imported in a sorted order (the chances of which are less)
val totalContactCount = readContactsCount
// Handle conditions when there are no contacts. This can happen when
// 1. The user has no contacts yet
// 2. Access to Contacts permission denied in Marshmallow and up
if (totalContactCount > 0) {
index = Random().nextInt(totalContactCount.toInt())
}
dataConsumer?.onContactsRead()
isContactsRead = true
}
override fun getAllContacts(): List<ContactInfo> = contactsApi.allContacts
override fun getReadContactsCount(): Long = contactsApi.readContactsCount
override fun getRandomContact(): ContactInfo? {
if (allContacts.isEmpty()) {
return null
}
// If there are no custom contact groups, default to all contacts
// The database is the source of truth, override the values in appPreference
val customContactGroups = contactGroupRepository.getContactGroupCount()
val selectedGroup = if(customContactGroups > 0){
appPreferences.selectedContactGroup()
} else {
// Update the Selected Contact Group so that it correctly selects the
// All Contacts option in Manage Contact Groups Fragment
appPreferences.setSelectedContactGroup(DEFAULT_CONTACT_GROUP)
DEFAULT_CONTACT_GROUP
}
val randomContactId: String
if (DEFAULT_CONTACT_GROUP == selectedGroup) {
index = ((index + 1) % readContactsCount.toInt())
randomContactId = allContacts[index].id
} else {
val contactGroup = contactGroupRepository.findContactGroupById(selectedGroup)
val subList: List<String> = contactGroup.selectedContacts.split(CONTACT_ID_SEPARATOR)
randomContactId = subList[Random().nextInt(subList.size)]
}
val options = ContactInfoOptions.Builder()
.includePhoneDetails(true)
.includeContactPicture(true)
.defaultContactPicture(com.ae.apps.lib.R.drawable.profile_icon_3)
.filterDuplicatePhoneNumbers(true)
.build()
return getContactInfo(randomContactId, options)
}
override fun getContactInfo(contactId: String): ContactInfo = contactsApi.getContactInfo(contactId)
override fun getContactInfo(contactId: String?, options: ContactInfoOptions?): ContactInfo =
contactsApi.getContactInfo(
contactId,
options
)
override fun getContactIdFromRawContact(contactId: String?): String =
contactsApi.getContactIdFromRawContact(contactId)
override fun getContactIdFromAddress(address: String?): String = contactsApi.getContactIdFromAddress(address)
} | apache-2.0 | 2936263fda557ed0241de80abbae4cfe | 39.19708 | 113 | 0.690156 | 4.955896 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/classes/classObjectAsStaticInitializer.kt | 1 | 265 | var global = 0;
class C {
companion object {
init {
global = 1;
}
}
}
fun box(): String {
if (global != 0) {
return "fail1: global = $global"
}
val c = C()
if (global == 1) return "OK" else return "fail2: global = $global"
}
| apache-2.0 | e0ddd77df999b57108a5dca4edb8cc15 | 12.947368 | 68 | 0.509434 | 3.045977 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/cache/attempt/dao/AttemptDaoImpl.kt | 2 | 4116 | package org.stepik.android.cache.attempt.dao
import android.content.ContentValues
import android.database.Cursor
import com.google.gson.Gson
import org.stepic.droid.storage.dao.DaoBase
import org.stepic.droid.storage.operations.DatabaseOperations
import org.stepic.droid.util.getDate
import org.stepic.droid.util.getLong
import org.stepic.droid.util.getString
import org.stepic.droid.util.toObject
import org.stepik.android.cache.attempt.structure.DbStructureAttempt
import org.stepik.android.model.attempts.Attempt
import org.stepik.android.model.attempts.DatasetWrapper
import javax.inject.Inject
class AttemptDaoImpl
@Inject
constructor(
private val gson: Gson,
databaseOperations: DatabaseOperations
) : DaoBase<Attempt>(databaseOperations) {
override fun getDbName(): String =
DbStructureAttempt.TABLE_NAME
override fun getDefaultPrimaryColumn(): String =
DbStructureAttempt.Columns.ID
override fun getDefaultPrimaryValue(persistentObject: Attempt): String =
persistentObject.id.toString()
override fun parsePersistentObject(cursor: Cursor): Attempt =
Attempt(
id = cursor.getLong(DbStructureAttempt.Columns.ID),
step = cursor.getLong(DbStructureAttempt.Columns.STEP),
user = cursor.getLong(DbStructureAttempt.Columns.USER),
_dataset = DatasetWrapper(cursor.getString(DbStructureAttempt.Columns.DATASET)?.toObject(gson)),
datasetUrl = cursor.getString(DbStructureAttempt.Columns.DATASET_URL),
status = cursor.getString(DbStructureAttempt.Columns.STATUS),
time = cursor.getDate(DbStructureAttempt.Columns.TIME),
timeLeft = cursor.getString(DbStructureAttempt.Columns.TIME_LEFT)
)
override fun getContentValues(persistentObject: Attempt): ContentValues =
ContentValues().apply {
put(DbStructureAttempt.Columns.ID, persistentObject.id)
put(DbStructureAttempt.Columns.STEP, persistentObject.step)
put(DbStructureAttempt.Columns.USER, persistentObject.user)
put(DbStructureAttempt.Columns.DATASET, persistentObject.dataset?.let(gson::toJson))
put(DbStructureAttempt.Columns.DATASET_URL, persistentObject.datasetUrl)
put(DbStructureAttempt.Columns.STATUS, persistentObject.status)
put(DbStructureAttempt.Columns.TIME, persistentObject.time?.time ?: -1)
put(DbStructureAttempt.Columns.TIME_LEFT, persistentObject.timeLeft)
}
override fun insertOrReplaceAll(persistentObjects: List<Attempt>) {
persistentObjects.forEach(::insertOrReplace)
}
override fun insertOrReplace(persistentObject: Attempt) {
executeSql("""
INSERT OR REPLACE INTO ${DbStructureAttempt.TABLE_NAME} (
${DbStructureAttempt.Columns.ID},
${DbStructureAttempt.Columns.STEP},
${DbStructureAttempt.Columns.USER},
${DbStructureAttempt.Columns.DATASET},
${DbStructureAttempt.Columns.DATASET_URL},
${DbStructureAttempt.Columns.STATUS},
${DbStructureAttempt.Columns.TIME},
${DbStructureAttempt.Columns.TIME_LEFT}
)
SELECT ?, ?, ?, ?, ?, ?, ?, ?
WHERE NOT EXISTS (
SELECT * FROM ${DbStructureAttempt.TABLE_NAME}
WHERE ${DbStructureAttempt.Columns.ID} > ?
AND ${DbStructureAttempt.Columns.STEP} = ?
AND ${DbStructureAttempt.Columns.USER} = ?
)
""".trimIndent(),
arrayOf(
persistentObject.id,
persistentObject.step,
persistentObject.user,
persistentObject.dataset?.let(gson::toJson),
persistentObject.datasetUrl,
persistentObject.status,
persistentObject.time?.time ?: -1,
persistentObject.timeLeft,
persistentObject.id,
persistentObject.step,
persistentObject.user
)
)
}
} | apache-2.0 | 70ade968f4cbc082bc1b86e134bfe2f5 | 41.885417 | 108 | 0.664966 | 5.031785 | false | false | false | false |
funkyg/funkytunes | app/src/main/kotlin/com/github/funkyg/funkytunes/view/BottomControlView.kt | 1 | 3213 | package com.github.funkyg.funkytunes.view
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.*
import com.github.funkyg.funkytunes.R
import com.github.funkyg.funkytunes.Song
import com.github.funkyg.funkytunes.Util
import com.github.funkyg.funkytunes.activities.PlayingQueueActivity
import com.github.funkyg.funkytunes.service.MusicService
import com.github.funkyg.funkytunes.service.PlaybackInterface
class BottomControlView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : RelativeLayout(context, attrs, defStyleAttr), PlaybackInterface {
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
private lateinit var musicService: MusicService
private val logo: ImageView by lazy { findViewById(R.id.logo) as ImageView }
private val textHolder: View by lazy { findViewById(R.id.text_holder) }
private val progressBar: ProgressBar by lazy { findViewById(R.id.progress_bar) as ProgressBar }
private val title: TextView by lazy { findViewById(R.id.title) as TextView }
private val artist: TextView by lazy { findViewById(R.id.artist) as TextView }
private val playPause: ImageButton by lazy { findViewById(R.id.play_pause) as ImageButton }
fun setMusicService(musicService: MusicService) {
this.musicService = musicService
musicService.addPlaybackInterface(this)
val listener = View.OnClickListener{
val intent = Intent(context, PlayingQueueActivity::class.java)
context.startActivity(intent)
}
logo.setOnClickListener(listener)
textHolder.setOnClickListener(listener)
musicService.getCurrentSong()?.let { s -> onPlaySong(s, -1) }
if (musicService.isPlaying())
onResumed()
else
onPaused()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
musicService.removePlaybackInterface(this)
}
override fun onPlaySong(song: Song, index: Int) {
visibility = View.VISIBLE
progressBar.progress = musicService.getSongProgress()!!
progressBar.max = song.duration!!
Util.setUrl(logo, song.image.url)
title.text = song.name
artist.text = song.artist
if (musicService.isPlaying())
incrementProgress()
}
private fun incrementProgress() {
handler?.postDelayed(incrementProgressRunnable, 1000)
}
private val incrementProgressRunnable: Runnable = Runnable {
incrementProgress()
progressBar.progress = musicService.getSongProgress()!!
}
override fun onResumed() {
playPause.setImageResource(R.drawable.ic_pause_accent_24dp)
playPause.setOnClickListener { musicService.pause() }
}
override fun onPaused() {
playPause.setImageResource(R.drawable.ic_play_arrow_accent_24dp)
playPause.setOnClickListener { musicService.resume() }
handler?.removeCallbacks(incrementProgressRunnable)
}
override fun onStopped() {
visibility = View.GONE
}
}
| gpl-3.0 | c61628955553408bf9314e03bee26182 | 35.931034 | 150 | 0.714908 | 4.413462 | false | false | false | false |
anrelic/Anci-OSS | util/src/main/kotlin/su/jfdev/anci/util/stream/StreamPairAssociate.kt | 1 | 1355 | package su.jfdev.anci.util.stream
import java.util.function.*
import java.util.function.Function
import java.util.stream.*
import java.util.stream.Collectors.*
fun <K, V> Stream<Pair<K, V>>.associate(): Map<K, V> = collect(PairCollectors.collector())
fun <K, V> Stream<Pair<K, V>>.overrideAssociate(): Map<K, V> = collect(PairCollectors.override())
@Suppress("UNCHECKED_CAST")
object PairCollectors {
private val keyExtractor: Function<Pair<*, *>, Any> = Function { it.first }
private val valueExtractor: Function<Pair<*, *>, Any> = Function { it.second }
private val collector: Collector<*, *, *> = toMap(keyExtractor, valueExtractor)
private val overrideMerger: BinaryOperator<Any> = BinaryOperator { first, second -> second }
private val overrideCollector: Collector<*, *, *> = toMap(keyExtractor, valueExtractor, overrideMerger)
fun <K, V> key() = keyExtractor as Function<Pair<K, V>, K>
fun <K, V> value() = valueExtractor as Function<Pair<K, V>, V>
fun <K, V> collector() = collector as Collector<Pair<K, V>, *, MutableMap<K, V>>
fun <K, V> override() = overrideCollector as Collector<Pair<K, V>, *, MutableMap<K, V>>
fun <K, V> merging(merger: (V, V) -> V): Collector<Pair<K, V>, *, MutableMap<K, V>> = toMap(
key<K, V>(),
value<K, V>(),
BinaryOperator(merger))
} | mit | 8853813d8cf504318c20ecbf058c5c57 | 41.375 | 107 | 0.659041 | 3.575198 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt | 1 | 13537 | package eu.kanade.tachiyomi.extension
import android.content.Context
import com.elvishew.xlog.XLog
import com.jakewharton.rxrelay.BehaviorRelay
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.extension.api.ExtensionGithubApi
import eu.kanade.tachiyomi.extension.model.Extension
import eu.kanade.tachiyomi.extension.model.InstallStep
import eu.kanade.tachiyomi.extension.model.LoadResult
import eu.kanade.tachiyomi.extension.util.ExtensionInstallReceiver
import eu.kanade.tachiyomi.extension.util.ExtensionInstaller
import eu.kanade.tachiyomi.extension.util.ExtensionLoader
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.util.launchNow
import exh.source.BlacklistedSources
import kotlinx.coroutines.async
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
/**
* The manager of extensions installed as another apk which extend the available sources. It handles
* the retrieval of remotely available extensions as well as installing, updating and removing them.
* To avoid malicious distribution, every extension must be signed and it will only be loaded if its
* signature is trusted, otherwise the user will be prompted with a warning to trust it before being
* loaded.
*
* @param context The application context.
* @param preferences The application preferences.
*/
class ExtensionManager(
private val context: Context,
private val preferences: PreferencesHelper = Injekt.get()
) {
/**
* API where all the available extensions can be found.
*/
private val api = ExtensionGithubApi()
/**
* The installer which installs, updates and uninstalls the extensions.
*/
private val installer by lazy { ExtensionInstaller(context) }
/**
* Relay used to notify the installed extensions.
*/
private val installedExtensionsRelay = BehaviorRelay.create<List<Extension.Installed>>()
/**
* List of the currently installed extensions.
*/
var installedExtensions = emptyList<Extension.Installed>()
private set(value) {
field = value
installedExtensionsRelay.call(value)
}
/**
* Relay used to notify the available extensions.
*/
private val availableExtensionsRelay = BehaviorRelay.create<List<Extension.Available>>()
/**
* List of the currently available extensions.
*/
var availableExtensions = emptyList<Extension.Available>()
private set(value) {
field = value
availableExtensionsRelay.call(value)
setUpdateFieldOfInstalledExtensions(value)
}
/**
* Relay used to notify the untrusted extensions.
*/
private val untrustedExtensionsRelay = BehaviorRelay.create<List<Extension.Untrusted>>()
/**
* List of the currently untrusted extensions.
*/
var untrustedExtensions = emptyList<Extension.Untrusted>()
private set(value) {
field = value
untrustedExtensionsRelay.call(value)
}
/**
* The source manager where the sources of the extensions are added.
*/
private lateinit var sourceManager: SourceManager
/**
* Initializes this manager with the given source manager.
*/
fun init(sourceManager: SourceManager) {
this.sourceManager = sourceManager
initExtensions()
ExtensionInstallReceiver(InstallationListener()).register(context)
}
/**
* Loads and registers the installed extensions.
*/
private fun initExtensions() {
val extensions = ExtensionLoader.loadExtensions(context)
installedExtensions = extensions
.filterIsInstance<LoadResult.Success>()
.map { it.extension }
.filterNotBlacklisted()
installedExtensions
.flatMap { it.sources }
// overwrite is needed until the bundled sources are removed
.forEach { sourceManager.registerSource(it, true) }
untrustedExtensions = extensions
.filterIsInstance<LoadResult.Untrusted>()
.map { it.extension }
.filterNotBlacklisted()
}
// EXH -->
fun <T : Extension> Iterable<T>.filterNotBlacklisted(): List<T> {
val blacklistEnabled = preferences.eh_enableSourceBlacklist().getOrDefault()
return filter {
if(it.isBlacklisted(blacklistEnabled)) {
XLog.d("[EXH] Removing blacklisted extension: (name: %s, pkgName: %s)!", it.name, it.pkgName)
false
} else true
}
}
fun Extension.isBlacklisted(blacklistEnabled: Boolean =
preferences.eh_enableSourceBlacklist().getOrDefault()): Boolean {
return pkgName in BlacklistedSources.BLACKLISTED_EXTENSIONS && blacklistEnabled
}
// EXH <--
/**
* Returns the relay of the installed extensions as an observable.
*/
fun getInstalledExtensionsObservable(): Observable<List<Extension.Installed>> {
return installedExtensionsRelay.asObservable()
}
/**
* Returns the relay of the available extensions as an observable.
*/
fun getAvailableExtensionsObservable(): Observable<List<Extension.Available>> {
return availableExtensionsRelay.asObservable()
}
/**
* Returns the relay of the untrusted extensions as an observable.
*/
fun getUntrustedExtensionsObservable(): Observable<List<Extension.Untrusted>> {
return untrustedExtensionsRelay.asObservable()
}
/**
* Finds the available extensions in the [api] and updates [availableExtensions].
*/
fun findAvailableExtensions() {
api.findExtensions()
.onErrorReturn { emptyList() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { availableExtensions = it.filterNotBlacklisted() }
}
/**
* Sets the update field of the installed extensions with the given [availableExtensions].
*
* @param availableExtensions The list of extensions given by the [api].
*/
private fun setUpdateFieldOfInstalledExtensions(availableExtensions: List<Extension.Available>) {
val mutInstalledExtensions = installedExtensions.toMutableList()
var changed = false
for ((index, installedExt) in mutInstalledExtensions.withIndex()) {
val pkgName = installedExt.pkgName
val availableExt = availableExtensions.find { it.pkgName == pkgName } ?: continue
val hasUpdate = availableExt.versionCode > installedExt.versionCode
if (installedExt.hasUpdate != hasUpdate) {
mutInstalledExtensions[index] = installedExt.copy(hasUpdate = hasUpdate)
changed = true
}
}
if (changed) {
installedExtensions = mutInstalledExtensions.filterNotBlacklisted()
}
}
/**
* Returns an observable of the installation process for the given extension. It will complete
* once the extension is installed or throws an error. The process will be canceled if
* unsubscribed before its completion.
*
* @param extension The extension to be installed.
*/
fun installExtension(extension: Extension.Available): Observable<InstallStep> {
return installer.downloadAndInstall(api.getApkUrl(extension), extension)
}
/**
* Returns an observable of the installation process for the given extension. It will complete
* once the extension is updated or throws an error. The process will be canceled if
* unsubscribed before its completion.
*
* @param extension The extension to be updated.
*/
fun updateExtension(extension: Extension.Installed): Observable<InstallStep> {
val availableExt = availableExtensions.find { it.pkgName == extension.pkgName }
?: return Observable.empty()
return installExtension(availableExt)
}
/**
* Sets the result of the installation of an extension.
*
* @param downloadId The id of the download.
* @param result Whether the extension was installed or not.
*/
fun setInstallationResult(downloadId: Long, result: Boolean) {
installer.setInstallationResult(downloadId, result)
}
/**
* Uninstalls the extension that matches the given package name.
*
* @param pkgName The package name of the application to uninstall.
*/
fun uninstallExtension(pkgName: String) {
installer.uninstallApk(pkgName)
}
/**
* Adds the given signature to the list of trusted signatures. It also loads in background the
* extensions that match this signature.
*
* @param signature The signature to whitelist.
*/
fun trustSignature(signature: String) {
val untrustedSignatures = untrustedExtensions.map { it.signatureHash }.toSet()
if (signature !in untrustedSignatures) return
ExtensionLoader.trustedSignatures += signature
val preference = preferences.trustedSignatures()
preference.set(preference.getOrDefault() + signature)
val nowTrustedExtensions = untrustedExtensions.filter { it.signatureHash == signature }
untrustedExtensions -= nowTrustedExtensions
val ctx = context
launchNow {
nowTrustedExtensions
.map { extension ->
async { ExtensionLoader.loadExtensionFromPkgName(ctx, extension.pkgName) }
}
.map { it.await() }
.forEach { result ->
if (result is LoadResult.Success) {
registerNewExtension(result.extension)
}
}
}
}
/**
* Registers the given extension in this and the source managers.
*
* @param extension The extension to be registered.
*/
private fun registerNewExtension(extension: Extension.Installed) {
if(extension.isBlacklisted()) {
XLog.d("[EXH] Removing blacklisted extension: (name: String, pkgName: %s)!", extension.name, extension.pkgName)
return
}
installedExtensions += extension
extension.sources.forEach { sourceManager.registerSource(it) }
}
/**
* Registers the given updated extension in this and the source managers previously removing
* the outdated ones.
*
* @param extension The extension to be registered.
*/
private fun registerUpdatedExtension(extension: Extension.Installed) {
if(extension.isBlacklisted()) {
XLog.d("[EXH] Removing blacklisted extension: (name: String, pkgName: %s)!", extension.name, extension.pkgName)
return
}
val mutInstalledExtensions = installedExtensions.toMutableList()
val oldExtension = mutInstalledExtensions.find { it.pkgName == extension.pkgName }
if (oldExtension != null) {
mutInstalledExtensions -= oldExtension
extension.sources.forEach { sourceManager.unregisterSource(it) }
}
mutInstalledExtensions += extension
installedExtensions = mutInstalledExtensions
extension.sources.forEach { sourceManager.registerSource(it) }
}
/**
* Unregisters the extension in this and the source managers given its package name. Note this
* method is called for every uninstalled application in the system.
*
* @param pkgName The package name of the uninstalled application.
*/
private fun unregisterExtension(pkgName: String) {
val installedExtension = installedExtensions.find { it.pkgName == pkgName }
if (installedExtension != null) {
installedExtensions -= installedExtension
installedExtension.sources.forEach { sourceManager.unregisterSource(it) }
}
val untrustedExtension = untrustedExtensions.find { it.pkgName == pkgName }
if (untrustedExtension != null) {
untrustedExtensions -= untrustedExtension
}
}
/**
* Listener which receives events of the extensions being installed, updated or removed.
*/
private inner class InstallationListener : ExtensionInstallReceiver.Listener {
override fun onExtensionInstalled(extension: Extension.Installed) {
registerNewExtension(extension.withUpdateCheck())
}
override fun onExtensionUpdated(extension: Extension.Installed) {
registerUpdatedExtension(extension.withUpdateCheck())
}
override fun onExtensionUntrusted(extension: Extension.Untrusted) {
untrustedExtensions += extension
}
override fun onPackageUninstalled(pkgName: String) {
unregisterExtension(pkgName)
}
}
/**
* Extension method to set the update field of an installed extension.
*/
private fun Extension.Installed.withUpdateCheck(): Extension.Installed {
val availableExt = availableExtensions.find { it.pkgName == pkgName }
if (availableExt != null && availableExt.versionCode > versionCode) {
return copy(hasUpdate = true)
}
return this
}
}
| apache-2.0 | d9f201a64070219c2faaa769a5b6f36a | 36.18956 | 123 | 0.665288 | 5.208542 | false | false | false | false |
CarlosEsco/tachiyomi | core/src/main/java/eu/kanade/tachiyomi/util/lang/RxCoroutineBridge.kt | 1 | 3227 | package eu.kanade.tachiyomi.util.lang
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import rx.Emitter
import rx.Observable
import rx.Subscriber
import rx.Subscription
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/*
* Util functions for bridging RxJava and coroutines. Taken from TachiyomiEH/SY.
*/
suspend fun <T> Observable<T>.awaitSingle(): T = single().awaitOne()
@OptIn(InternalCoroutinesApi::class)
private suspend fun <T> Observable<T>.awaitOne(): T = suspendCancellableCoroutine { cont ->
cont.unsubscribeOnCancellation(
subscribe(
object : Subscriber<T>() {
override fun onStart() {
request(1)
}
override fun onNext(t: T) {
cont.resume(t)
}
override fun onCompleted() {
if (cont.isActive) {
cont.resumeWithException(
IllegalStateException(
"Should have invoked onNext",
),
)
}
}
override fun onError(e: Throwable) {
/*
* Rx1 observable throws NoSuchElementException if cancellation happened before
* element emission. To mitigate this we try to atomically resume continuation with exception:
* if resume failed, then we know that continuation successfully cancelled itself
*/
val token = cont.tryResumeWithException(e)
if (token != null) {
cont.completeResume(token)
}
}
},
),
)
}
internal fun <T> CancellableContinuation<T>.unsubscribeOnCancellation(sub: Subscription) =
invokeOnCancellation { sub.unsubscribe() }
@OptIn(ExperimentalCoroutinesApi::class)
fun <T> runAsObservable(
backpressureMode: Emitter.BackpressureMode = Emitter.BackpressureMode.NONE,
block: suspend () -> T,
): Observable<T> {
return Observable.create(
{ emitter ->
val job = GlobalScope.launch(Dispatchers.Unconfined, start = CoroutineStart.ATOMIC) {
try {
emitter.onNext(block())
emitter.onCompleted()
} catch (e: Throwable) {
// Ignore `CancellationException` as error, since it indicates "normal cancellation"
if (e !is CancellationException) {
emitter.onError(e)
} else {
emitter.onCompleted()
}
}
}
emitter.setCancellation { job.cancel() }
},
backpressureMode,
)
}
| apache-2.0 | f00621929f9db74e748aa32355f288cd | 34.461538 | 114 | 0.576077 | 5.691358 | false | false | false | false |
boxtape/boxtape-api | src/main/java/io/boxtape/core/ansible/Playbook.kt | 2 | 1337 | package io.boxtape.core.ansible
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import io.boxtape.asJson
import io.boxtape.asYaml
public data class Playbook(
var hosts: String = "all",
JsonProperty("remote_user") var remoteUser: String = "vagrant",
JsonInclude(JsonInclude.Include.NON_EMPTY) var vars: List<Pair<String, String>> = emptyList(),
plays: List<AnsiblePlay> = emptyList()
) {
// TODO : Hack -- See http://stackoverflow.com/questions/31663592/applying-a-role-under-sudo-user/31664215#31664215
var sudo: Boolean = true;
var tasks: MutableList<AnsiblePlay> = plays.toArrayList()
private val roles: MutableList<AnsibleRole> = arrayListOf()
fun addPlays(plays: List<AnsiblePlay>) {
tasks.addAll(plays)
}
fun addRoles(roles: List<AnsibleRole>) {
this.roles.addAll(roles)
}
JsonInclude(JsonInclude.Include.NON_EMPTY)
JsonProperty("roles")
fun getRoleDeclarations(): List<Map<String, Any>> {
val result = this.roles.map { it.asPlaybookDeclaration() }
return result
}
JsonIgnore
fun getRequirementsYaml():String {
return roles.asSequence().map { it.asRequirement() }
.toList().asYaml()
}
}
| apache-2.0 | 822ac214dc3d7895f658b9d5f7499f73 | 30.833333 | 119 | 0.698579 | 3.82 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/LibraryFilesPackagingElementEntityImpl.kt | 2 | 10998 | package com.intellij.workspaceModel.storage.bridgeEntities.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.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
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.SoftLinkable
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.referrersx
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
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 LibraryFilesPackagingElementEntityImpl: LibraryFilesPackagingElementEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
@JvmField var _library: LibraryId? = null
override val library: LibraryId?
get() = _library
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: LibraryFilesPackagingElementEntityData?): ModifiableWorkspaceEntityBase<LibraryFilesPackagingElementEntity>(), LibraryFilesPackagingElementEntity.Builder {
constructor(): this(LibraryFilesPackagingElementEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity LibraryFilesPackagingElementEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field LibraryFilesPackagingElementEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentEntity: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
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 library: LibraryId?
get() = getEntityData().library
set(value) {
checkModificationAllowed()
getEntityData().library = value
changedProperty.add("library")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): LibraryFilesPackagingElementEntityData = result ?: super.getEntityData() as LibraryFilesPackagingElementEntityData
override fun getEntityClass(): Class<LibraryFilesPackagingElementEntity> = LibraryFilesPackagingElementEntity::class.java
}
}
class LibraryFilesPackagingElementEntityData : WorkspaceEntityData<LibraryFilesPackagingElementEntity>(), SoftLinkable {
var library: LibraryId? = null
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
val optionalLink_library = library
if (optionalLink_library != null) {
result.add(optionalLink_library)
}
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val optionalLink_library = library
if (optionalLink_library != null) {
index.index(this, optionalLink_library)
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val optionalLink_library = library
if (optionalLink_library != null) {
val removedItem_optionalLink_library = mutablePreviousSet.remove(optionalLink_library)
if (!removedItem_optionalLink_library) {
index.index(this, optionalLink_library)
}
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
var library_data_optional = if (library != null) {
val library___data = if (library!! == oldLink) {
changed = true
newLink as LibraryId
}
else {
null
}
library___data
}
else {
null
}
if (library_data_optional != null) {
library = library_data_optional
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LibraryFilesPackagingElementEntity> {
val modifiable = LibraryFilesPackagingElementEntityImpl.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): LibraryFilesPackagingElementEntity {
val entity = LibraryFilesPackagingElementEntityImpl()
entity._library = library
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return LibraryFilesPackagingElementEntity::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 LibraryFilesPackagingElementEntityData
if (this.library != other.library) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LibraryFilesPackagingElementEntityData
if (this.library != other.library) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + library.hashCode()
return result
}
} | apache-2.0 | b1e4275d9c23bae30fac378f6451ab12 | 40.821293 | 220 | 0.646027 | 6.144134 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/dfaassist/KotlinDfaAssistProvider.kt | 2 | 9771 | // 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.debugger.dfaassist
import com.intellij.codeInspection.dataFlow.TypeConstraint
import com.intellij.codeInspection.dataFlow.TypeConstraints
import com.intellij.codeInspection.dataFlow.lang.DfaAnchor
import com.intellij.codeInspection.dataFlow.lang.UnsatisfiedConditionProblem
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState
import com.intellij.codeInspection.dataFlow.types.DfTypes
import com.intellij.codeInspection.dataFlow.value.DfaValue
import com.intellij.codeInspection.dataFlow.value.DfaVariableValue
import com.intellij.debugger.engine.dfaassist.DebuggerDfaListener
import com.intellij.debugger.engine.dfaassist.DfaAssistProvider
import com.intellij.debugger.engine.dfaassist.DfaHint
import com.intellij.debugger.jdi.StackFrameProxyEx
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.util.ThreeState
import com.sun.jdi.Location
import com.sun.jdi.ObjectReference
import com.sun.jdi.Value
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.debugger.ClassNameCalculator
import org.jetbrains.kotlin.idea.debugger.evaluate.variables.EvaluatorValueConverter
import org.jetbrains.kotlin.idea.inspections.dfa.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.org.objectweb.asm.Type as AsmType
class KotlinDfaAssistProvider : DfaAssistProvider {
override fun locationMatches(element: PsiElement, location: Location): Boolean {
val jdiClassName = location.method().declaringType().name()
val file = element.containingFile
if (file !is KtFile) return false
val classNames = ClassNameCalculator.getClassNames(file)
val psiClassName = element.parentsWithSelf.firstNotNullOfOrNull { e -> classNames[e] }
return psiClassName == jdiClassName
}
override fun getAnchor(element: PsiElement): KtExpression? {
var cur = element
while (cur is PsiWhiteSpace || cur is PsiComment) {
cur = element.nextSibling
}
while (true) {
val parent = cur.parent
if (parent is KtBlockExpression || parent is KtFunction) {
return cur as? KtExpression
}
if (parent == null || cur.startOffsetInParent > 0) return null
cur = parent
}
}
override fun getCodeBlock(anchor: PsiElement): KtExpression? {
if (anchor !is KtExpression) return null
when (val parent = anchor.parent) {
is KtBlockExpression -> return parent
is KtFunction -> return anchor
else -> return null
}
}
override fun getJdiValueForDfaVariable(proxy: StackFrameProxyEx, dfaVar: DfaVariableValue, anchor: PsiElement): Value? {
val qualifier = dfaVar.qualifier
val psiVariable = dfaVar.psiVariable
if (qualifier == null) {
val descriptor = dfaVar.descriptor
if (descriptor is KtThisDescriptor) {
val declarationDescriptor = descriptor.descriptor
if (declarationDescriptor is FunctionDescriptor) {
val thisName = "\$this\$${declarationDescriptor.name}"
val thisVar = proxy.visibleVariableByName(thisName)
if (thisVar != null) {
return postprocess(proxy.getVariableValue(thisVar))
}
return null
}
val thisObject = proxy.thisObject()
if (thisObject != null) {
val signature = AsmType.getType(thisObject.referenceType().signature()).className
val jvmName = KotlinPsiHeuristics.getJvmName(declarationDescriptor.fqNameSafe)
if (signature == jvmName) {
return thisObject
}
}
// TODO: support `this` references for outer types, etc.
return null
}
else if (descriptor is KtVariableDescriptor && psiVariable is KtCallableDeclaration) {
// TODO: check/support inlined functions
val variable = proxy.visibleVariableByName((psiVariable as KtNamedDeclaration).name)
if (variable != null) {
return postprocess(proxy.getVariableValue(variable))
}
}
} else {
val jdiQualifier = getJdiValueForDfaVariable(proxy, qualifier, anchor)
if (jdiQualifier is ObjectReference && psiVariable is KtCallableDeclaration) {
val type = jdiQualifier.referenceType()
val field = type.fieldByName(psiVariable.name)
if (field != null) {
return postprocess(jdiQualifier.getValue(field))
}
}
}
return null
}
private fun postprocess(value: Value?): Value {
return DfaAssistProvider.wrap(EvaluatorValueConverter.unref(value))
}
override fun createListener(): DebuggerDfaListener {
return object : DebuggerDfaListener {
val hints = hashMapOf<PsiElement, DfaHint>()
override fun beforePush(args: Array<out DfaValue>, value: DfaValue, anchor: DfaAnchor, state: DfaMemoryState) {
val dfType = state.getDfType(value)
var psi = when (anchor) {
is KotlinAnchor.KotlinExpressionAnchor -> {
if (shouldTrackExpressionValue(anchor.expression) &&
!KotlinConstantConditionsInspection.shouldSuppress(dfType, anchor.expression)
) anchor.expression
else return
}
is KotlinAnchor.KotlinWhenConditionAnchor -> anchor.condition
else -> return
}
var hint = DfaHint.ANY_VALUE
if (dfType === DfTypes.TRUE) {
hint = DfaHint.TRUE
} else if (dfType === DfTypes.FALSE) {
hint = DfaHint.FALSE
} else if (dfType === DfTypes.NULL) {
val parent = psi.parent
if (parent is KtPostfixExpression && parent.operationToken == KtTokens.EXCLEXCL) {
hint = DfaHint.NPE
} else if (parent is KtBinaryExpressionWithTypeRHS && parent.operationReference.textMatches("as")) {
val typeReference = parent.right
val type =
typeReference?.getAbbreviatedTypeOrType(typeReference.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL))
if (type != null && !type.isMarkedNullable) {
hint = DfaHint.NPE
psi = parent.operationReference
}
} else if (parent is KtBinaryExpression && parent.operationToken == KtTokens.ELVIS) {
hint = DfaHint.NULL
} else if (psi is KtBinaryExpressionWithTypeRHS && psi.operationReference.textMatches("as?")) {
hint = DfaHint.NULL
}
}
hints.merge(psi, hint, DfaHint::merge)
}
override fun onCondition(problem: UnsatisfiedConditionProblem, value: DfaValue, failed: ThreeState, state: DfaMemoryState) {
if (problem is KotlinProblem.KotlinCastProblem) {
hints.merge(
problem.cast.operationReference,
if (failed == ThreeState.YES) DfaHint.CCE else DfaHint.NONE,
DfaHint::merge
)
}
}
private fun shouldTrackExpressionValue(expr: KtExpression): Boolean {
if (expr is KtBinaryExpression) {
val token = expr.operationToken
// Report right hand of assignment only
if (token == KtTokens.EQ) return false
// For boolean expression, report individual operands only, to avoid clutter
if (token == KtTokens.ANDAND || token == KtTokens.OROR) return false
}
var parent = expr.parent
while (parent is KtParenthesizedExpression) {
parent = parent.parent
}
if ((parent as? KtPrefixExpression)?.operationToken == KtTokens.EXCL) {
// It's enough to report for parent only
return false
}
return true
}
override fun computeHints(): Map<PsiElement, DfaHint> {
hints.values.removeIf { h -> h.title == null }
return hints
}
}
}
override fun constraintFromJvmClassName(anchor: PsiElement, jvmClassName: String): TypeConstraint {
val classDef = KtClassDef.fromJvmClassName(anchor as KtElement, jvmClassName) ?: return TypeConstraints.TOP
return TypeConstraints.exactClass(classDef)
}
} | apache-2.0 | f057a465488528ccdfdf29587b1dfd43 | 47.137931 | 136 | 0.613653 | 5.539116 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/OptionalParametersHelper.kt | 3 | 6347 | // 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.core
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.ValueArgument
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentsInParentheses
import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import java.util.*
object OptionalParametersHelper {
fun detectArgumentsToDropForDefaults(
resolvedCall: ResolvedCall<out CallableDescriptor>,
project: Project,
canDrop: (ValueArgument) -> Boolean = { true }
): Collection<ValueArgument> {
if (!resolvedCall.isReallySuccess()) return emptyList()
val descriptor = resolvedCall.resultingDescriptor
val parameterToDefaultValue = descriptor.valueParameters
.mapNotNull { parameter -> defaultParameterValue(parameter, project)?.let { parameter to it } }
.toMap()
if (parameterToDefaultValue.isEmpty()) return emptyList()
//TODO: drop functional literal out of parenthesis too
val arguments = resolvedCall.call.getValueArgumentsInParentheses()
val argumentsToDrop = ArrayList<ValueArgument>()
for (argument in arguments.asReversed()) {
if (!canDrop(argument) || !argument.matchesDefault(resolvedCall, parameterToDefaultValue)) {
if (!argument.isNamed()) break else continue // for a named argument we can try to drop arguments before it as well
}
argumentsToDrop.add(argument)
}
return argumentsToDrop
}
private fun ValueArgument.matchesDefault(
resolvedCall: ResolvedCall<out CallableDescriptor>,
parameterToDefaultValue: Map<ValueParameterDescriptor, DefaultValue>
): Boolean {
val parameter = resolvedCall.getParameterForArgument(this) ?: return false
val defaultValue = parameterToDefaultValue[parameter] ?: return false
val expression = defaultValue.substituteArguments(resolvedCall)
val argumentExpression = getArgumentExpression()!!
return argumentExpression.text == expression.text //TODO
}
private fun DefaultValue.substituteArguments(resolvedCall: ResolvedCall<out CallableDescriptor>): KtExpression {
if (parameterUsages.isEmpty()) return expression
val key = Key<KtExpression>("SUBSTITUTION")
for ((parameter, usages) in parameterUsages) {
val resolvedArgument = resolvedCall.valueArguments[parameter]!!
if (resolvedArgument is ExpressionValueArgument) {
val argument = resolvedArgument.valueArgument!!.getArgumentExpression()!!
usages.forEach { it.putCopyableUserData(key, argument) }
}
//TODO: vararg
}
var expressionCopy = expression.copied()
expression.forEachDescendantOfType<KtExpression> { it.putCopyableUserData(key, null) }
val replacements = ArrayList<Pair<KtExpression, KtExpression>>()
expressionCopy.forEachDescendantOfType<KtExpression> {
val replacement = it.getCopyableUserData(key)
if (replacement != null) {
replacements.add(it to replacement)
}
}
for ((expression, replacement) in replacements) {
val replaced = expression.replace(replacement) as KtExpression
if (expression == expressionCopy) {
expressionCopy = replaced
}
}
return expressionCopy
}
data class DefaultValue(
val expression: KtExpression,
val parameterUsages: Map<ValueParameterDescriptor, Collection<KtExpression>>
)
fun defaultParameterValueExpression(parameter: ValueParameterDescriptor, project: Project): KtExpression? {
if (!parameter.hasDefaultValue()) return null
if (!parameter.declaresDefaultValue()) {
val overridden = parameter.overriddenDescriptors.firstOrNull { it.hasDefaultValue() } ?: return null
return defaultParameterValueExpression(overridden, project)
}
//TODO: parameter in overriding method!
//TODO: it's a temporary code while we don't have default values accessible from descriptors
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, parameter)?.navigationElement as? KtParameter
return declaration?.defaultValue
}
//TODO: handle imports
//TODO: handle implicit receivers
fun defaultParameterValue(parameter: ValueParameterDescriptor, project: Project): DefaultValue? {
val expression = defaultParameterValueExpression(parameter, project) ?: return null
val allParameters = parameter.containingDeclaration.valueParameters.toSet()
val parameterUsages = HashMap<ValueParameterDescriptor, MutableCollection<KtExpression>>()
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
expression.forEachDescendantOfType<KtSimpleNameExpression> {
val target = bindingContext[BindingContext.REFERENCE_TARGET, it]
if (target is ValueParameterDescriptor && target in allParameters) {
parameterUsages.getOrPut(target) { ArrayList() }.add(it)
}
}
return DefaultValue(expression, parameterUsages)
}
} | apache-2.0 | 2ffed2cb846aac39598c29155b2a1365 | 44.342857 | 158 | 0.723334 | 5.577329 | false | false | false | false |
blindpirate/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/WorkNodeCodec.kt | 1 | 8177 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization.codecs
import org.gradle.api.internal.GradleInternal
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.decodePreservingIdentity
import org.gradle.configurationcache.serialization.encodePreservingIdentityOf
import org.gradle.configurationcache.serialization.readCollectionInto
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.configurationcache.serialization.withGradleIsolate
import org.gradle.configurationcache.serialization.writeCollection
import org.gradle.execution.plan.CompositeNodeGroup
import org.gradle.execution.plan.FinalizerGroup
import org.gradle.execution.plan.Node
import org.gradle.execution.plan.NodeGroup
import org.gradle.execution.plan.OrdinalGroup
import org.gradle.execution.plan.TaskInAnotherBuild
import org.gradle.execution.plan.TaskNode
internal
class WorkNodeCodec(
private val owner: GradleInternal,
private val internalTypesCodec: Codec<Any?>
) {
suspend fun WriteContext.writeWork(nodes: List<Node>) {
// Share bean instances across all nodes (except tasks, which have their own isolate)
withGradleIsolate(owner, internalTypesCodec) {
writeNodes(nodes)
}
}
suspend fun ReadContext.readWork(): List<Node> =
withGradleIsolate(owner, internalTypesCodec) {
readNodes()
}
private
suspend fun WriteContext.writeNodes(nodes: List<Node>) {
val nodeCount = nodes.size
writeSmallInt(nodeCount)
val scheduledNodeIds = HashMap<Node, Int>(nodeCount)
nodes.forEachIndexed { nodeId, node ->
writeNode(node, scheduledNodeIds)
scheduledNodeIds[node] = nodeId
}
nodes.forEach { node ->
writeNodeGroup(node.group, scheduledNodeIds)
}
}
private
suspend fun ReadContext.readNodes(): List<Node> {
val nodeCount = readSmallInt()
val nodes = ArrayList<Node>(nodeCount)
val nodesById = HashMap<Int, Node>(nodeCount)
for (nodeId in 0 until nodeCount) {
val node = readNode(nodesById)
nodesById[nodeId] = node
nodes.add(node)
}
nodes.forEach { node ->
node.group = readNodeGroup(nodesById)
}
return nodes
}
private
suspend fun WriteContext.writeNode(
node: Node,
scheduledNodeIds: Map<Node, Int>
) {
write(node)
writeSuccessorReferencesOf(node, scheduledNodeIds)
}
private
suspend fun ReadContext.readNode(nodesById: Map<Int, Node>): Node {
val node = readNonNull<Node>()
readSuccessorReferencesOf(node, nodesById)
node.require()
if (node !is TaskInAnotherBuild) {
// we want TaskInAnotherBuild dependencies to be processed later, so that the node is connected to its target task
node.dependenciesProcessed()
}
return node
}
private
fun WriteContext.writeNodeGroup(group: NodeGroup, nodesById: Map<Node, Int>) {
encodePreservingIdentityOf(group) {
when (group) {
is OrdinalGroup -> {
writeSmallInt(0)
writeSmallInt(group.ordinal)
}
is FinalizerGroup -> {
writeSmallInt(1)
writeSmallInt(nodesById.getValue(group.node))
writeNodeGroup(group.delegate, nodesById)
}
is CompositeNodeGroup -> {
writeSmallInt(2)
writeNodeGroup(group.ordinalGroup, nodesById)
writeCollection(group.finalizerGroups) {
writeNodeGroup(it, nodesById)
}
}
NodeGroup.DEFAULT_GROUP -> {
writeSmallInt(3)
}
else -> throw IllegalArgumentException()
}
}
}
private
fun ReadContext.readNodeGroup(nodesById: Map<Int, Node>): NodeGroup {
return decodePreservingIdentity { id ->
when (readSmallInt()) {
0 -> {
val ordinal = readSmallInt()
OrdinalGroup(ordinal)
}
1 -> {
val finalizerNode = nodesById.getValue(readSmallInt()) as TaskNode
val delegate = readNodeGroup(nodesById)
FinalizerGroup(finalizerNode, delegate)
}
2 -> {
val ordinalGroup = readNodeGroup(nodesById)
val groups = readCollectionInto(::HashSet) { readNodeGroup(nodesById) as FinalizerGroup }
CompositeNodeGroup(ordinalGroup, groups)
}
3 -> NodeGroup.DEFAULT_GROUP
else -> throw IllegalArgumentException()
}.also {
isolate.identities.putInstance(id, it)
}
}
}
private
fun WriteContext.writeSuccessorReferencesOf(node: Node, scheduledNodeIds: Map<Node, Int>) {
writeSuccessorReferences(node.dependencySuccessors, scheduledNodeIds)
when (node) {
is TaskNode -> {
writeSuccessorReferences(node.shouldSuccessors, scheduledNodeIds)
writeSuccessorReferences(node.mustSuccessors, scheduledNodeIds)
writeSuccessorReferences(node.finalizingSuccessors, scheduledNodeIds)
writeSuccessorReferences(node.lifecycleSuccessors, scheduledNodeIds)
}
}
}
private
fun ReadContext.readSuccessorReferencesOf(node: Node, nodesById: Map<Int, Node>) {
readSuccessorReferences(nodesById) {
node.addDependencySuccessor(it)
}
when (node) {
is TaskNode -> {
readSuccessorReferences(nodesById) {
node.addShouldSuccessor(it)
}
readSuccessorReferences(nodesById) {
require(it is TaskNode)
node.addMustSuccessor(it)
}
readSuccessorReferences(nodesById) {
require(it is TaskNode)
node.addFinalizingSuccessor(it)
}
val lifecycleSuccessors = mutableSetOf<Node>()
readSuccessorReferences(nodesById) {
lifecycleSuccessors.add(it)
}
node.lifecycleSuccessors = lifecycleSuccessors
}
}
}
private
fun WriteContext.writeSuccessorReferences(
successors: Collection<Node>,
scheduledNodeIds: Map<Node, Int>
) {
for (successor in successors) {
// Discard should/must run after relationships to nodes that are not scheduled to run
scheduledNodeIds[successor]?.let { successorId ->
writeSmallInt(successorId)
}
}
writeSmallInt(-1)
}
private
fun ReadContext.readSuccessorReferences(nodesById: Map<Int, Node>, onSuccessor: (Node) -> Unit) {
while (true) {
val successorId = readSmallInt()
if (successorId == -1) break
val successor = nodesById.getValue(successorId)
onSuccessor(successor)
}
}
}
| apache-2.0 | aa7d7d3a037c5a7543523a70134160cd | 35.504464 | 126 | 0.615262 | 4.864366 | false | false | false | false |
TomsUsername/Phoenix | src/main/kotlin/phoenix/bot/pogo/nRnMK9r/util/data/ItemData.kt | 1 | 761 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package phoenix.bot.pogo.nRnMK9r.util.data
import POGOProtos.Inventory.Item.ItemIdOuterClass
data class ItemData(
var itemId: Int? = null,
var itemName: String? = null,
var count: Int? = null
) {
fun buildFromItem(item: ItemIdOuterClass.ItemId, count: Int): ItemData {
this.itemId = item.number
this.itemName = item.name
this.count = count
return this
}
}
| gpl-3.0 | 60adcf8f8cd17302904b7408bea4090b | 30.708333 | 97 | 0.695138 | 4.047872 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-12/palette-app/app/src/main/java/dev/mfazio/palettetester/MainActivity.kt | 1 | 1752 | package dev.mfazio.palettetester
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.palette.graphics.Palette
import dev.mfazio.palettetester.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//TODO: Update this as needed to change images.
// No, it's not fancy, but it's just a sample app.
val imageId = R.drawable.ic_abl_logo_with_text
val imageDrawable = ContextCompat.getDrawable(this, imageId)
val image = imageDrawable?.toBitmap()
if(image != null) {
val palette = Palette.from(image).generate()
with(binding) {
mainImage.setImageDrawable(imageDrawable)
palette.dominantSwatch?.rgb?.let { dominantPalette.setBackgroundColor(it) }
palette.lightVibrantSwatch?.rgb?.let { lightVibrantPalette.setBackgroundColor(it) }
palette.vibrantSwatch?.rgb?.let { vibrantPalette.setBackgroundColor(it) }
palette.darkVibrantSwatch?.rgb?.let { darkVibrantPalette.setBackgroundColor(it) }
palette.lightMutedSwatch?.rgb?.let { lightMutedPalette.setBackgroundColor(it) }
palette.mutedSwatch?.rgb?.let { mutedPalette.setBackgroundColor(it) }
palette.darkMutedSwatch?.rgb?.let { darkMutedPalette.setBackgroundColor(it) }
}
}
}
} | apache-2.0 | d3d59178eedc7bc6c184217b65f0062f | 38.840909 | 99 | 0.694064 | 4.826446 | false | false | false | false |
wengelef/KotlinMVVM | app/src/main/java/com/wengelef/kotlinmvvmtest/util/SimpleConnectionObserver.kt | 1 | 1342 | package com.wengelef.kotlinmvvmtest.util
import android.content.Context
import android.net.ConnectivityManager
import com.jakewharton.rxrelay.BehaviorRelay
import rx.Observable
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit
class SimpleConnectionObserver(context: Context) : ConnectionObserver {
init {
Observable.interval(1000L, TimeUnit.MILLISECONDS)
.takeWhile { weakContext.get() != null }
.flatMap { Observable.just(weakContext.get()) }
.flatMap {
it?.let {
val connectiviyManager = it.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connectiviyManager.activeNetworkInfo
Observable.just(networkInfo != null && networkInfo.isConnectedOrConnecting)
} ?: Observable.just(false)
}
.distinctUntilChanged()
.subscribe { connectivityChanges.call(it) }
}
private val weakContext = WeakReference<Context>(context)
private val connectivityChanges = BehaviorRelay.create<Boolean>()
override fun networkChanges(): Observable<Boolean> = connectivityChanges.asObservable()
override fun getConnected(): Boolean = connectivityChanges.value
} | apache-2.0 | 6087b59e81983853b170858c934251ae | 38.5 | 121 | 0.671386 | 5.5 | false | false | false | false |
thaapasa/jalkametri-android | app/src/main/java/fi/tuska/jalkametri/data/FileDataBackup.kt | 1 | 4808 | package fi.tuska.jalkametri.data
import android.os.Environment
import fi.tuska.jalkametri.dao.DataBackup
import fi.tuska.jalkametri.db.DBAdapter
import fi.tuska.jalkametri.util.FileUtil
import fi.tuska.jalkametri.util.LogUtil
import java.io.File
import java.io.IOException
import java.util.Comparator
import java.util.Date
import java.util.Locale
import java.util.TreeSet
class FileDataBackup(private val db: DBAdapter) : DataBackup {
private val databaseFile: File
@Throws(IOException::class)
get() {
LogUtil.d(TAG, "Data dir is " + Environment.getDataDirectory())
val dbFile = File(Environment.getDataDirectory().toString()
+ "/data/fi.tuska.jalkametri/databases/" + db.databaseFilename)
if (!dbFile.exists()) {
LogUtil.w(TAG, "Database file %s does not exist", dbFile)
throw IOException("Database file does not exist")
}
return dbFile
}
private val backupDirectory: File?
@Throws(IOException::class)
get() {
if (!isBackupServiceAvailable)
return null
val dir = File(Environment.getExternalStorageDirectory(), "jAlcoMeter")
if (!dir.exists()) {
LogUtil.d(TAG, "Backup directory does not exist, creating %s", dir)
if (!dir.mkdirs()) {
LogUtil.w(TAG, "Backup dir doesn't exist and can't create: %s", dir)
throw IOException("Cannot create backup directory")
}
return dir
}
if (!dir.isDirectory) {
LogUtil.w(TAG, "Backup directory is not a directory: %s", dir)
throw IOException("Backup directory is not a directory")
}
return dir
}
override fun generateDataBackupName(): String? {
if (!isBackupServiceAvailable)
return null
val backups = backups
var tryNum = 1
while (true) {
val name = String.format(Locale.ENGLISH, "jAlcoMeter-backup.%1\$tY-%1\$tm-%1\$td.%2\$d.db",
Date(), tryNum)
if (!backups.contains(name))
return name
tryNum++
}
}
override fun backupData(targetName: String): Boolean {
if (!isBackupServiceAvailable)
return false
try {
db.lockDatabase()
val backupFile = File(backupDirectory, targetName)
val dbFile = databaseFile
FileUtil.copyFile(dbFile, backupFile)
return true
} catch (e: IOException) {
LogUtil.w(TAG, "Error when restoring backup file: %s (%s)", e.message ?: "", e)
return false
} finally {
db.unlockDatabase()
}
}
override val backups: Set<String>
get() {
val backups = TreeSet(BACKUP_ORDER)
if (!isBackupServiceAvailable)
return backups
return try {
val backupDir = backupDirectory
val fileList = backupDir!!.listFiles()
fileList
.filter { it.isFile }
.mapTo(backups) { it.name }
backups
} catch (e: IOException) {
LogUtil.w(TAG, "Error reading backup directory: %s (%s)", e.message ?: "", e)
backups
}
}
override fun restoreBackup(backupName: String): Boolean {
if (!isBackupServiceAvailable)
return false
try {
db.lockDatabase()
val backupFile = File(backupDirectory, backupName)
if (!backupFile.exists() || !backupFile.isFile) {
LogUtil.w(TAG, "Backup file %s does not exist or is not a file", backupFile)
return false
}
val dbFile = databaseFile
FileUtil.copyFile(backupFile, dbFile)
return true
} catch (e: IOException) {
LogUtil.w(TAG, "Error when restoring backup file: %s (%s)", e.message ?: "", e)
return false
} finally {
db.unlockDatabase()
}
}
override val isBackupServiceAvailable: Boolean
get() {
// Need to have a mounted external storage
return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
}
companion object {
private val TAG = "FileDataBackup"
/**
* Comparator that orders strings in reverse order.
*/
private val BACKUP_ORDER = Comparator<String> { object1, object2 ->
// Reverse order
if (object1 != null) -object1.compareTo(object2) else -1
}
}
}
| mit | 3204530eae2518a04b8b0fec423a5fcf | 32.158621 | 103 | 0.549917 | 4.640927 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/bundled/bundledGroovy.kt | 5 | 2215 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("BundledGroovy")
package org.jetbrains.plugins.groovy.bundled
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ClearableLazyValue
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.io.JarUtil.getJarAttribute
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFsConnectionListener
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.GlobalSearchScopesCore
import groovy.lang.GroovyObject
import org.jetbrains.plugins.groovy.config.AbstractConfigUtils.UNDEFINED_VERSION
import java.io.File
import java.util.jar.Attributes.Name.IMPLEMENTATION_VERSION
val bundledGroovyVersion: @NlsSafe String by lazy(::doGetBundledGroovyVersion)
private fun doGetBundledGroovyVersion(): String = getJarAttribute(bundledGroovyFile, IMPLEMENTATION_VERSION) ?: UNDEFINED_VERSION
val bundledGroovyFile: File by lazy(::doGetBundledGroovyFile)
private fun doGetBundledGroovyFile(): File {
val jarPath = PathManager.getJarPathForClass(GroovyObject::class.java) ?: error("Cannot find JAR containing groovy classes")
return File(jarPath)
}
val bundledGroovyJarRoot: ClearableLazyValue<Ref<VirtualFile>> = ClearableLazyValue.create { Ref.create(doGetBundledGroovyRoot()) }
private fun doGetBundledGroovyRoot(): VirtualFile? {
val jar = bundledGroovyFile
val jarFile = VfsUtil.findFileByIoFile(jar, false) ?: return null
return JarFileSystem.getInstance().getJarRootForLocalFile(jarFile)
}
fun createBundledGroovyScope(project: Project): GlobalSearchScope? {
val root = bundledGroovyJarRoot.value.get() ?: return null
return GlobalSearchScopesCore.directoryScope(project, root, true)
}
internal class BundledGroovyPersistentFsConnectionListener: PersistentFsConnectionListener {
override fun beforeConnectionClosed() {
bundledGroovyJarRoot.drop()
}
}
| apache-2.0 | 2c84f3316d6bfc1fb8776ec46252fc6c | 42.431373 | 140 | 0.828442 | 4.43 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveFile/moveFileWithoutPackageRename/before/_a/main.kt | 26 | 416 | package a
class Test {
val aFoo: Foo = Foo()
val bFoo: b.Foo = b.Foo()
val cFoo: c.Foo = c.Foo()
val aBar: Foo.Bar = Foo.Bar()
val bBar: b.Foo.Bar = b.Foo.Bar()
val cBar: c.Foo.Bar = c.Foo.Bar()
}
fun test() {
foo()
b.foo()
c.foo()
}
var TEST: String
get() = FOO + b.FOO + c.FOO
set(value: String) {
FOO = value
b.FOO = value
c.FOO = value
} | apache-2.0 | ab9c99fd76a1f103569184d6af860c17 | 16.375 | 37 | 0.495192 | 2.649682 | false | true | false | false |
GunoH/intellij-community | platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringAvailability.kt | 8 | 6313 | // 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.refactoring.suggested
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature
/**
* A service determining available refactoring for a given [SuggestedRefactoringState].
*/
abstract class SuggestedRefactoringAvailability(protected val refactoringSupport: SuggestedRefactoringSupport) {
/**
* Detects if we should suppress refactoring suggestion for this declaration.
*
* This method is supposed to use [SuggestedRefactoringState.restoredDeclarationCopy] in order to analyze the original declaration.
* It's allowed to use reference resolve in this method.
* If resolve is not needed then it's recommended to override [SuggestedRefactoringStateChanges.createInitialState] and do the checks there.
* This method should not be called if [SuggestedRefactoringState.errorLevel] == [SuggestedRefactoringState.ErrorLevel.INCONSISTENT].
* @return true, if the refactoring suggestion should be permanently disabled for this declaration
* and all further changes in the signature ignored.
*/
open fun shouldSuppressRefactoringForDeclaration(state: SuggestedRefactoringState): Boolean = false
/**
* Refines the old and the new signatures with use of resolve.
*
* Resolve may be useful, for example, to filter out annotation changes that are not supposed to be copied across method hierarchy.
* This method should be called only when [SuggestedRefactoringState.errorLevel] == [SuggestedRefactoringState.ErrorLevel.NO_ERRORS].
*/
open fun refineSignaturesWithResolve(state: SuggestedRefactoringState): SuggestedRefactoringState = state
/**
* Amends state with additional information by performing potentially slow computations such as usage search.
*
* Normally, the state is amended by modifying [SuggestedRefactoringState.additionalData]
* (see [SuggestedRefactoringState.withAdditionalData]). The additional data can be retrieved later and used by
* implementations of [detectAvailableRefactoring] and [shouldSuppressRefactoringForDeclaration].
* This method should not be called if [SuggestedRefactoringState.errorLevel] == [SuggestedRefactoringState.ErrorLevel.INCONSISTENT].
* @return lazy iterator over sequence of amended states
*/
open fun amendStateInBackground(state: SuggestedRefactoringState): Iterator<SuggestedRefactoringState> = iterator { }
/**
* Determines refactoring availability for a given state and returns instance of [SuggestedRefactoringData],
* providing information for presentation and execution of the refactoring.
*
* It's supposed that this method is called only when *state.oldSignature != state.newSignature* and *state.syntaxError == false*.
* @param state current state of accumulated changes
* @return An instance of [SuggestedRefactoringData] with information about available refactoring,
* or *null* if no refactoring is available.
*/
abstract fun detectAvailableRefactoring(state: SuggestedRefactoringState): SuggestedRefactoringData?
/**
* Use this implementation of [SuggestedRefactoringAvailability], if only Rename refactoring is supported for the language.
*/
open class RenameOnly(refactoringSupport: SuggestedRefactoringSupport) : SuggestedRefactoringAvailability(refactoringSupport) {
override fun detectAvailableRefactoring(state: SuggestedRefactoringState): SuggestedRefactoringData? {
val namedElement = state.anchor as? PsiNamedElement ?: return null
return SuggestedRenameData(namedElement, state.oldSignature.name)
}
}
protected fun hasParameterAddedRemovedOrReordered(oldSignature: Signature, newSignature: Signature): Boolean {
if (oldSignature.parameters.size != newSignature.parameters.size) return true
return oldSignature.parameters.zip(newSignature.parameters).any { (oldParam, newParam) ->
oldParam.id != newParam.id
}
}
protected open fun hasTypeChanges(oldSignature: Signature, newSignature: Signature): Boolean {
require(oldSignature.parameters.size == newSignature.parameters.size)
if (oldSignature.type != newSignature.type) return true
return oldSignature.parameters.zip(newSignature.parameters).any { (oldParam, newParam) ->
hasParameterTypeChanges(oldParam, newParam)
}
}
protected open fun hasParameterTypeChanges(oldParam: Parameter, newParam: Parameter): Boolean {
return oldParam.type != newParam.type
}
protected fun nameChanges(
oldSignature: Signature,
newSignature: Signature,
declaration: PsiElement,
parameters: List<PsiNamedElement>
): Pair<Int, SuggestedRenameData?> {
require(parameters.size == newSignature.parameters.size)
require(oldSignature.parameters.size == newSignature.parameters.size)
var nameChanges = 0
var renameData: SuggestedRenameData? = null
if (declaration is PsiNamedElement && oldSignature.name != newSignature.name) {
nameChanges++
renameData = SuggestedRenameData(declaration, oldSignature.name)
}
for (i in oldSignature.parameters.indices) {
val oldParam = oldSignature.parameters[i]
val newParam = newSignature.parameters[i]
if (oldParam.name != newParam.name) {
nameChanges++
renameData = SuggestedRenameData(parameters[i], oldParam.name)
}
}
return nameChanges to renameData?.takeIf { nameChanges == 1 }
}
companion object {
@Deprecated("Use RefactoringBundle.message(\"suggested.refactoring.usages\") explicitly")
@JvmField val USAGES = RefactoringBundle.message("suggested.refactoring.usages")
@Deprecated("Use RefactoringBundle.message(\"suggested.refactoring.overrides\") explicitly")
@JvmField val OVERRIDES = RefactoringBundle.message("suggested.refactoring.overrides")
@Deprecated("Use RefactoringBundle.message(\"suggested.refactoring.implementations\") explicitly")
@JvmField val IMPLEMENTATIONS = RefactoringBundle.message("suggested.refactoring.implementations")
}
} | apache-2.0 | 3c24d1e9f1bf470ebcf3a87af97ba3a0 | 50.333333 | 142 | 0.776176 | 5.204452 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/csharp/CSharpProcessLanguageService.kt | 1 | 1727 | package org.roylance.yaclib.core.services.csharp
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.services.IProcessLanguageService
import org.roylance.yaclib.core.services.common.ReadmeBuilder
import java.util.*
class CSharpProcessLanguageService : IProcessLanguageService {
override fun buildInterface(
projectInformation: YaclibModel.ProjectInformation): YaclibModel.AllFiles {
val returnList = YaclibModel.AllFiles.newBuilder()
val solutionGuid = UUID.randomUUID().toString().toUpperCase()
val projectGuid = UUID.randomUUID().toString().toUpperCase()
returnList.addFiles(ReadmeBuilder(projectInformation.mainDependency).build())
returnList.addFiles(XProjBuilder(projectGuid, projectInformation.mainDependency).build())
returnList.addFiles(IHttpClientBuilder(projectInformation.mainDependency).build())
returnList.addFiles(
SolutionBuilder(solutionGuid, projectGuid, projectInformation.mainDependency).build())
returnList.addFiles(ProjectJsonBuilder(projectInformation.mainDependency).build())
projectInformation.controllers.controllerDependenciesList
.filter { it.dependency.group == projectInformation.mainDependency.group && it.dependency.name == projectInformation.mainDependency.name }
.forEach { controllerDependency ->
controllerDependency.controllers.controllersList.forEach { controller ->
returnList.addFiles(
CSharpServiceBuilder(projectInformation.mainDependency, controller).build())
returnList.addFiles(CSharpServiceImplementationBuilder(controllerDependency.dependency,
controller).build())
}
}
return returnList.build()
}
} | mit | 9671769cd940e56265ef5545488bfdd5 | 47 | 146 | 0.770701 | 5.313846 | false | false | false | false |
marius-m/wt4 | components/src/main/java/lt/markmerkk/timeselect/TimePickerPresenter.kt | 1 | 1941 | package lt.markmerkk.timeselect
import lt.markmerkk.ViewProvider
import org.joda.time.LocalTime
class TimePickerPresenter(
private val view: ViewProvider<TimePickerContract.View>
): TimePickerContract.Presenter {
private var selection: LocalTime = LocalTime(0, 0)
override val timeSelection: LocalTime
get() = selection
override fun onAttach() {
}
override fun onDetach() {
}
override fun selectTime(time: LocalTime) {
this.selection = time
view.invoke { renderHeader(selection) }
view.invoke { renderSelection(selection) }
}
override fun selectHour(hour: Int) {
this.selection = this.selection.withHourOfDay(hour)
view.invoke { renderHeader(selection) }
// Don't change hour selection as this would re-render same UI component
}
override fun selectMinute(minute: Int) {
this.selection = this.selection.withMinuteOfHour(minute)
view.invoke { renderHeader(selection) }
// Don't change hour selection as this would re-render same UI component
}
override fun plusMinute(minuteStep: Int) {
this.selection = this.selection.plusMinutes(minuteStep)
view.invoke { renderHeader(selection) }
view.invoke { renderSelection(selection) }
}
override fun minusMinute(minuteStep: Int) {
this.selection = this.selection.minusMinutes(minuteStep)
view.invoke { renderHeader(selection) }
view.invoke { renderSelection(selection) }
}
override fun plusHour(hourStep: Int) {
this.selection = this.selection.plusHours(hourStep)
view.invoke { renderHeader(selection) }
view.invoke { renderSelection(selection) }
}
override fun minusHour(hourStep: Int) {
this.selection = this.selection.minusHours(hourStep)
view.invoke { renderHeader(selection) }
view.invoke { renderSelection(selection) }
}
} | apache-2.0 | f4ab942c7de16916bcf5e04e538ab409 | 30.322581 | 80 | 0.679547 | 4.421412 | false | true | false | false |
daviddenton/k2 | src/main/kotlin/io/github/daviddenton/k2/module/StaticModule.kt | 1 | 1513 | package io.github.daviddenton.k2.module
import io.github.daviddenton.k2.KFilter
import io.github.daviddenton.k2.Service
import io.github.daviddenton.k2.Svc
import io.github.daviddenton.k2.contract.ContentType
import io.github.daviddenton.k2.http.Path
import io.github.daviddenton.k2.http.Request
import io.github.daviddenton.k2.http.Response
import io.github.daviddenton.k2.http.Root
class StaticModule private constructor(private val basePath: Path, private val resourceLoader: ResourceLoader,
private val moduleFilter: KFilter) : Module {
override fun toService(): Svc =
Service.mk<Request, Response> {
ContentType.lookup(convertPath(Root))
Response(200)
}
// override protected < fintrospect > def serviceBinding: ServiceBinding {
// case Get -> path if exists(path) =>
// moduleFilter.andThen(Service.mk<Request, Response> {
// _ => HttpResponse(lookup(convertPath(path))).withCode(Ok).withContent(Owned(toByteArray(resourceLoader.load(convertPath(path)))))
// })
// }
private fun exists(path: Path) = if (path.startsWith(basePath)) resourceLoader.load(convertPath(path)) != null else false
private fun convertPath(path: Path): String {
val newPath = if (basePath == Root) path.toString() else path.toString().replace(basePath.toString(), "")
val resolved = if (newPath == "") "/index.html" else newPath
return resolved.replaceFirst("/", "")
}
}
| apache-2.0 | b971bd22fa89141bc2697ee6b488747b | 42.228571 | 143 | 0.689359 | 3.773067 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/database/models/LibraryManga.kt | 1 | 284 | package eu.kanade.tachiyomi.data.database.models
class LibraryManga : MangaImpl() {
var unreadCount: Int = 0
var readCount: Int = 0
val totalChapters
get() = readCount + unreadCount
val hasStarted
get() = readCount > 0
var category: Int = 0
}
| apache-2.0 | 7c5ba790f1b284332356583f3e13e79a | 17.933333 | 48 | 0.640845 | 4.238806 | false | false | false | false |
333fred/kotlin_lisp | src/com/fsilberberg/lisp/Value.kt | 1 | 1648 | package com.fsilberberg.lisp
enum class ValEnum {
NumV, ClosV, StringV, BoolV, SymV, BuiltInV
}
inline fun <reified T : Value> contextCast(value: Value, context: String): T {
return when (value) {
is T -> value
else -> throw RuntimeException("$context expected ${T::class}, got $value")
}
}
/**
* The com.fsilberberg.lisp.Value return types that can be used
*/
interface Value {
fun argString(): String
fun getEnum(): ValEnum
}
data class NumV(val num: Double) : Value {
override fun argString(): String = num.toString()
override fun getEnum(): ValEnum = ValEnum.NumV
}
data class ClosV(val args: List<SymV>, val body: SExpr, val env: Environment) : Value {
override fun argString(): String = toString()
override fun getEnum(): ValEnum = ValEnum.ClosV
}
data class StringV(val str: String) : Value {
override fun argString(): String = "\"$str\""
override fun getEnum(): ValEnum = ValEnum.StringV
}
data class SymV(val str: String) : Value {
override fun argString(): String = str
override fun getEnum(): ValEnum = ValEnum.SymV
}
data class BoolV(val bool: Boolean) : Value {
override fun argString(): String = bool.toString()
override fun getEnum(): ValEnum = ValEnum.BoolV
}
/**
* This class handles built-in functionality that can't be easily defined in terms of the language itself. This is
* things like math operations, let, and so on
*/
data class BuiltinV(val action: (vals: List<SExpr>, env: Environment) -> Value, val funName: String) : Value {
override fun argString(): String = funName
override fun getEnum(): ValEnum = ValEnum.BuiltInV
}
| mit | ab754bcfc7e711cdb73dcfbad9de8862 | 29.518519 | 114 | 0.682646 | 3.590414 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/core/src/templates/kotlin/core/macos/templates/CoreFoundation.kt | 4 | 7695 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package core.macos.templates
import org.lwjgl.generator.*
import core.macos.*
val ALLOCATOR = nullable..Parameter(
CFAllocatorRef,
"allocator",
"the allocator to use to allocate memory for the new object. Pass #NULL or {@code kCFAllocatorDefault} to use the current default allocator."
)
val CoreFoundation = "CoreFoundation".nativeClass(Module.CORE_MACOS, nativeSubPath = "macos") {
nativeImport("<CoreFoundation/CoreFoundation.h>")
documentation = "Native bindings to <CoreFoundation.h>."
// -----------------------------------------------
// CFBase.h
ByteConstant(
"Boolean values.",
"TRUE".."1",
"FALSE".."0"
)
macro..CFAllocatorRef("kCFAllocatorDefault", "This is a synonym for #NULL, if you'd rather use a named constant.", void())
macro..CFAllocatorRef("kCFAllocatorSystemDefault", "Default system allocator; you rarely need to use this.", void())
macro..CFAllocatorRef(
"kCFAllocatorMalloc",
"""
This allocator uses {@code malloc()}, {@code realloc()}, and {@code free()}. This should not be generally used; stick to #kCFAllocatorDefault()
whenever possible. This allocator is useful as the "bytesDeallocator" in {@code CFData} or "contentsDeallocator" in {@code CFString} where the memory
was obtained as a result of {@code malloc()} type functions.
""",
void()
)
macro..CFAllocatorRef(
"kCFAllocatorMallocZone",
"""
This allocator explicitly uses the default malloc zone, returned by {@code malloc_default_zone()}. It should only be used when an object is safe to be
allocated in non-scanned memory.
""",
void()
)
macro..CFAllocatorRef(
"kCFAllocatorNull",
"""
Null allocator which does nothing and allocates no memory. This allocator is useful as the "bytesDeallocator" in {@code CFData} or "contentsDeallocator"
in {@code CFString} where the memory should not be freed.
""",
void()
)
macro..CFAllocatorRef(
"kCFAllocatorUseContext",
"Special allocator argument to CFAllocatorCreate which means \"use the functions given in the context to allocate the allocator itself as well\".",
void()
)
CFTypeRef(
"CFRetain",
"""
Retains a Core Foundation object.
You should retain a Core Foundation object when you receive it from elsewhere (that is, you did not create or copy it) and you want it to persist. If
you retain a Core Foundation object you are responsible for releasing it.
""",
CFTypeRef("cf", "the CFType object to retain")
)
void(
"CFRelease",
"""
Releases a Core Foundation object.
If the retain count of {@code cf} becomes zero the memory allocated to the object is deallocated and the object is destroyed. If you create, copy, or
explicitly retain (see the #CFRetain() function) a Core Foundation object, you are responsible for releasing it when you no longer need it.
""",
CFTypeRef("cf", "the CFType object to release")
)
// -----------------------------------------------
// CFBundle.h
CFBundleRef(
"CFBundleCreate",
"Creates a {@code CFBundle} object.",
ALLOCATOR,
CFURLRef("bundleURL", "the location of the bundle for which to create a {@code CFBundle} object")
)
CFBundleRef(
"CFBundleGetBundleWithIdentifier",
"Locates a bundle given its program-defined identifier.",
CFStringRef("bundleID", "the identifier of the bundle to locate. Note that identifier names are case-sensitive.")
)
opaque_p(
"CFBundleGetFunctionPointerForName",
"Returns a pointer to a function in a bundleโs executable code using the function name as the search key.",
CFBundleRef("bundle", "the bundle to examine"),
CFStringRef("functionName", "the name of the function to locate")
)
// -----------------------------------------------
// CFString.h
val Encodings = IntConstant(
"Platform-independent built-in encodings; always available on all platforms.",
"kCFStringEncodingMacRoman".."0",
"kCFStringEncodingWindowsLatin1"..0x0500,
"kCFStringEncodingISOLatin1"..0x0201,
"kCFStringEncodingNextStepLatin"..0x0B01,
"kCFStringEncodingASCII"..0x0600,
"kCFStringEncodingUnicode"..0x0100,
"kCFStringEncodingUTF8"..0x08000100,
"kCFStringEncodingNonLossyASCII"..0x0BFF,
"kCFStringEncodingUTF16"..0x0100,
"kCFStringEncodingUTF16BE"..0x10000100,
"kCFStringEncodingUTF16LE"..0x14000100,
"kCFStringEncodingUTF32"..0x0c000100,
"kCFStringEncodingUTF32BE"..0x18000100,
"kCFStringEncodingUTF32LE"..0x1c000100
).javaDocLinks
CFStringRef(
"CFStringCreateWithCString",
"Creates an immutable string from a C string.",
ALLOCATOR,
Unsafe..char.const.p("cStr", "the #NULL-terminated C string to be used to create the {@code CFString} object. The string must use an 8-bit encoding."),
CFStringEncoding("encoding", "the encoding of the characters in the C string. The encoding must specify an 8-bit encoding.", Encodings)
)
CFStringRef(
"CFStringCreateWithCStringNoCopy",
"Creates a CFString object from an external C string buffer that might serve as the backing store for the object.",
ALLOCATOR,
Unsafe..char.const.p("cStr", "the #NULL-terminated C string to be used to create the {@code CFString} object. The string must use an 8-bit encoding."),
CFStringEncoding("encoding", "the encoding of the characters in the C string. The encoding must specify an 8-bit encoding.", Encodings),
nullable..CFAllocatorRef(
"contentsDeallocator",
"""
the {@code CFAllocator} object to use to deallocate the external string buffer when it is no longer needed. You can pass #NULL or
{@code kCFAllocatorDefault} to request the default allocator for this purpose. If the buffer does not need to be deallocated, or if you want to
assume responsibility for deallocating the buffer (and not have the {@code CFString} object deallocate it), pass {@code kCFAllocatorNull}.
"""
)
)
// -----------------------------------------------
// CFURL.h
val PathStyles = IntConstant(
"URL path styles.",
"kCFURLPOSIXPathStyle".."0",
"kCFURLHFSPathStyle".."1",
"kCFURLWindowsPathStyle".."2"
).javaDocLinks
CFURLRef(
"CFURLCreateWithFileSystemPath",
"Creates a {@code CFURL} object using a local file system path string.",
ALLOCATOR,
CFStringRef(
"filePath",
"""
the path string to convert to a {@code CFURL} object. If {@code filePath} is not absolute, the resulting URL will be considered relative to the
current working directory (evaluated when this function is being invoked).
"""
),
CFURLPathStyle("pathStyle", "the operating system path style used in {@code filePath}", PathStyles),
core.macos.Boolean(
"isDirectory",
"""
a Boolean value that specifies whether filePath is treated as a directory path when resolving against relative path components. Pass true if the
pathname indicates a directory, false otherwise.
"""
)
)
} | bsd-3-clause | c26dc9fd595699d7f5387c3822961845 | 38.45641 | 160 | 0.638373 | 4.46748 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/highlighter.kt | 1 | 2871 | package me.serce.solidity.ide
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SingleLazyInstanceSyntaxHighlighterFactory
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import me.serce.solidity.ide.colors.SolColor
import me.serce.solidity.lang.core.SolidityLexer
import me.serce.solidity.lang.core.SolidityTokenTypes.*
class SolHighlighterFactory : SingleLazyInstanceSyntaxHighlighterFactory() {
override fun createHighlighter() = SolHighlighter
}
object SolHighlighter : SyntaxHighlighterBase() {
override fun getHighlightingLexer() = SolidityLexer()
override fun getTokenHighlights(tokenType: IElementType): Array<out TextAttributesKey> {
return pack(tokenMapping[tokenType])
}
private val tokenMapping: Map<IElementType, TextAttributesKey> = mapOf(
COMMENT to SolColor.LINE_COMMENT,
NAT_SPEC_TAG to SolColor.NAT_SPEC_TAG,
LBRACE to SolColor.BRACES,
RBRACE to SolColor.BRACES,
LBRACKET to SolColor.BRACKETS,
RBRACKET to SolColor.BRACKETS,
LPAREN to SolColor.PARENTHESES,
RPAREN to SolColor.PARENTHESES,
SEMICOLON to SolColor.SEMICOLON,
SCIENTIFICNUMBER to SolColor.NUMBER,
FIXEDNUMBER to SolColor.NUMBER,
DECIMALNUMBER to SolColor.NUMBER,
HEXNUMBER to SolColor.NUMBER,
NUMBERUNIT to SolColor.NUMBER,
STRINGLITERAL to SolColor.STRING
).plus(
keywords().map { it to SolColor.KEYWORD }
).plus(
literals().map { it to SolColor.KEYWORD }
).plus(
operators().map { it to SolColor.OPERATION_SIGN }
).plus(
types().map { it to SolColor.TYPE }
).mapValues { it.value.textAttributesKey }
private fun keywords() = setOf<IElementType>(
// Note, the ERROR/REVERT are not keywords and are excluded
IMPORT, AS, PRAGMA, NEW, DELETE, EMIT, /*REVERT,*/ CONSTRUCTOR,
CONTRACT, LIBRARY, INTERFACE, IS, STRUCT, FUNCTION, ENUM,
PUBLIC, PRIVATE, INTERNAL, EXTERNAL, CONSTANT, PURE, VIEW,
IF, ELSE, FOR, WHILE, DO, BREAK, CONTINUE, THROW, USING, RETURN, RETURNS,
MAPPING, EVENT, /*ERROR,*/ ANONYMOUS, MODIFIER, ASSEMBLY,
VAR, STORAGE, MEMORY, WEI, ETHER, GWEI, SZABO, FINNEY, SECONDS, MINUTES, HOURS,
DAYS, WEEKS, YEARS, TYPE, VIRTUAL, OVERRIDE, IMMUTABLE, INDEXED
)
private fun types() = setOf<IElementType>(
BYTENUMTYPE, BYTESNUMTYPE, FIXEDNUMTYPE, INTNUMTYPE, UFIXEDNUMTYPE, UINTNUMTYPE,
STRING, BOOL, ADDRESS,
)
private fun literals() = setOf<IElementType>(BOOLEANLITERAL)
private fun operators() = setOf<IElementType>(
NOT, ASSIGN, PLUS_ASSIGN, MINUS_ASSIGN, MULT_ASSIGN, DIV_ASSIGN, PERCENT_ASSIGN,
PLUS, MINUS, MULT, DIV, EXPONENT, CARET,
LESS, MORE, LESSEQ, MOREEQ,
AND, ANDAND, OR, OROR,
EQ, NEQ, TO,
INC, DEC,
TILDE, PERCENT,
LSHIFT, RSHIFT,
LEFT_ASSEMBLY, RIGHT_ASSEMBLY
)
}
| mit | aaaeec10a2371254cdcd929190f17439 | 34.444444 | 90 | 0.734936 | 3.864065 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertJavaCopyPasteProcessor.kt | 1 | 14526 | // 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.conversion.copy
import com.intellij.codeInsight.editorActions.CopyPastePostProcessor
import com.intellij.codeInsight.editorActions.TextBlockTransferableData
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.refactoring.suggested.range
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInsight.KotlinCopyPasteReferenceProcessor
import org.jetbrains.kotlin.idea.codeInsight.KotlinReferenceData
import org.jetbrains.kotlin.idea.configuration.ExperimentalFeatures
import org.jetbrains.kotlin.idea.editor.KotlinEditorOptions
import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices
import org.jetbrains.kotlin.idea.statistics.ConversionType
import org.jetbrains.kotlin.idea.statistics.J2KFusCollector
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.j2k.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import java.awt.datatransfer.Transferable
import kotlin.system.measureTimeMillis
class ConvertJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransferableData>() {
private val LOG = Logger.getInstance(ConvertJavaCopyPasteProcessor::class.java)
override fun extractTransferableData(content: Transferable): List<TextBlockTransferableData> {
try {
if (content.isDataFlavorSupported(CopiedJavaCode.DATA_FLAVOR)) {
return listOf(content.getTransferData(CopiedJavaCode.DATA_FLAVOR) as TextBlockTransferableData)
}
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
LOG.error(e)
}
return listOf()
}
override fun collectTransferableData(
file: PsiFile,
editor: Editor,
startOffsets: IntArray,
endOffsets: IntArray
): List<TextBlockTransferableData> {
if (file !is PsiJavaFile) return listOf()
return listOf(CopiedJavaCode(file.getText()!!, startOffsets, endOffsets))
}
override fun processTransferableData(
project: Project,
editor: Editor,
bounds: RangeMarker,
caretOffset: Int,
indented: Ref<in Boolean>,
values: List<TextBlockTransferableData>
) {
if (DumbService.getInstance(project).isDumb) return
if (!KotlinEditorOptions.getInstance().isEnableJavaToKotlinConversion) return
val data = values.single() as CopiedJavaCode
val document = editor.document
val targetFile = PsiDocumentManager.getInstance(project).getPsiFile(document) as? KtFile ?: return
val useNewJ2k = checkUseNewJ2k(targetFile)
val targetModule = targetFile.module
if (isNoConversionPosition(targetFile, bounds.startOffset)) return
data class Result(
val text: String?,
val referenceData: Collection<KotlinReferenceData>,
val explicitImports: Set<FqName>,
val converterContext: ConverterContext?
)
val dataForConversion = DataForConversion.prepare(data, project)
fun doConversion(): Result {
val result = dataForConversion.elementsAndTexts.convertCodeToKotlin(project, targetModule, useNewJ2k)
val referenceData = buildReferenceData(result.text, result.parseContext, dataForConversion.importsAndPackage, targetFile)
val text = if (result.textChanged) result.text else null
return Result(text, referenceData, result.importsToAdd, result.converterContext)
}
fun insertImports(
bounds: TextRange,
referenceData: Collection<KotlinReferenceData>,
explicitImports: Collection<FqName>
): TextRange? {
if (referenceData.isEmpty() && explicitImports.isEmpty()) return bounds
PsiDocumentManager.getInstance(project).commitDocument(document)
val rangeMarker = document.createRangeMarker(bounds)
rangeMarker.isGreedyToLeft = true
rangeMarker.isGreedyToRight = true
KotlinCopyPasteReferenceProcessor()
.processReferenceData(project, editor, targetFile, bounds.startOffset, referenceData.toTypedArray())
runWriteAction {
explicitImports.forEach { fqName ->
targetFile.resolveImportReference(fqName).firstOrNull()?.let {
ImportInsertHelper.getInstance(project).importDescriptor(targetFile, it)
}
}
}
return rangeMarker.range
}
var conversionResult: Result? = null
fun doConversionAndInsertImportsIfUnchanged(): Boolean {
conversionResult = doConversion()
if (conversionResult!!.text != null) return false
insertImports(
bounds.range ?: return true,
conversionResult!!.referenceData,
conversionResult!!.explicitImports
)
return true
}
val textLength = data.startOffsets.indices.sumBy { data.endOffsets[it] - data.startOffsets[it] }
// if the text to convert is short enough, try to do conversion without permission from user and skip the dialog if nothing converted
if (textLength < 1000 && doConversionAndInsertImportsIfUnchanged()) return
fun convert() {
if (conversionResult == null && doConversionAndInsertImportsIfUnchanged()) return
val (text, referenceData, explicitImports) = conversionResult!!
text!! // otherwise we should get true from doConversionAndInsertImportsIfUnchanged and return above
val boundsAfterReplace = runWriteAction {
val startOffset = bounds.startOffset
document.replaceString(startOffset, bounds.endOffset, text)
val endOffsetAfterCopy = startOffset + text.length
editor.caretModel.moveToOffset(endOffsetAfterCopy)
TextRange(startOffset, endOffsetAfterCopy)
}
val newBounds = insertImports(boundsAfterReplace, referenceData, explicitImports)
PsiDocumentManager.getInstance(project).commitDocument(document)
runPostProcessing(project, targetFile, newBounds, conversionResult?.converterContext, useNewJ2k)
conversionPerformed = true
}
if (confirmConvertJavaOnPaste(project, isPlainText = false)) {
val conversionTime = measureTimeMillis {
convert()
}
J2KFusCollector.log(
ConversionType.PSI_EXPRESSION,
ExperimentalFeatures.NewJ2k.isEnabled,
conversionTime,
dataForConversion.elementsAndTexts.linesCount(),
filesCount = 1
)
}
}
private fun buildReferenceData(
text: String,
parseContext: ParseContext,
importsAndPackage: String,
targetFile: KtFile
): Collection<KotlinReferenceData> {
var blockStart: Int
var blockEnd: Int
val fileText = buildString {
append(importsAndPackage)
val (contextPrefix, contextSuffix) = when (parseContext) {
ParseContext.CODE_BLOCK -> "fun ${generateDummyFunctionName(text)}() {\n" to "\n}"
ParseContext.TOP_LEVEL -> "" to ""
}
append(contextPrefix)
blockStart = length
append(text)
blockEnd = length
append(contextSuffix)
}
val dummyFile = KtPsiFactory(targetFile.project).createAnalyzableFile("dummy.kt", fileText, targetFile)
val startOffset = blockStart
val endOffset = blockEnd
return KotlinCopyPasteReferenceProcessor().collectReferenceData(dummyFile, intArrayOf(startOffset), intArrayOf(endOffset)).map {
it.copy(startOffset = it.startOffset - startOffset, endOffset = it.endOffset - startOffset)
}
}
private fun generateDummyFunctionName(convertedCode: String): String {
var i = 0
while (true) {
val name = "dummy$i"
if (convertedCode.indexOf(name) < 0) return name
i++
}
}
companion object {
@get:TestOnly
var conversionPerformed: Boolean = false
}
}
internal class ConversionResult(
val text: String,
val parseContext: ParseContext,
val importsToAdd: Set<FqName>,
val textChanged: Boolean,
val converterContext: ConverterContext?
)
internal fun ElementAndTextList.convertCodeToKotlin(project: Project, targetModule: Module?, useNewJ2k: Boolean): ConversionResult {
val converter =
J2kConverterExtension.extension(useNewJ2k).createJavaToKotlinConverter(
project,
targetModule,
ConverterSettings.defaultSettings,
IdeaJavaToKotlinServices
)
val inputElements = toList().filterIsInstance<PsiElement>()
val (results, _, converterContext) =
ProgressManager.getInstance().runProcessWithProgressSynchronously(
ThrowableComputable<Result, Exception> {
runReadAction { converter.elementsToKotlin(inputElements) }
},
JavaToKotlinAction.title,
false,
project
)
val importsToAdd = LinkedHashSet<FqName>()
var resultIndex = 0
val convertedCodeBuilder = StringBuilder()
val originalCodeBuilder = StringBuilder()
var parseContext: ParseContext? = null
this.process(object : ElementsAndTextsProcessor {
override fun processElement(element: PsiElement) {
val originalText = element.text
originalCodeBuilder.append(originalText)
val result = results[resultIndex++]
if (result != null) {
convertedCodeBuilder.append(result.text)
if (parseContext == null) { // use parse context of the first converted element as parse context for the whole text
parseContext = result.parseContext
}
importsToAdd.addAll(result.importsToAdd)
} else { // failed to convert element to Kotlin, insert "as is"
convertedCodeBuilder.append(originalText)
}
}
override fun processText(string: String) {
originalCodeBuilder.append(string)
convertedCodeBuilder.append(string)
}
})
val convertedCode = convertedCodeBuilder.toString()
val originalCode = originalCodeBuilder.toString()
return ConversionResult(
convertedCode,
parseContext ?: ParseContext.CODE_BLOCK,
importsToAdd,
convertedCode != originalCode,
converterContext
)
}
internal fun isNoConversionPosition(file: KtFile, offset: Int): Boolean {
if (offset == 0) return false
val token = file.findElementAt(offset - 1) ?: return true
if (token !is PsiWhiteSpace && token.endOffset != offset) return true // pasting into the middle of token
for (element in token.parentsWithSelf) {
when (element) {
is PsiComment -> return element.node.elementType == KtTokens.EOL_COMMENT || offset != element.endOffset
is KtStringTemplateEntryWithExpression -> return false
is KtStringTemplateExpression -> return true
}
}
return false
}
internal fun confirmConvertJavaOnPaste(project: Project, isPlainText: Boolean): Boolean {
if (KotlinEditorOptions.getInstance().isDonTShowConversionDialog) return true
val dialog = KotlinPasteFromJavaDialog(project, isPlainText)
dialog.show()
return dialog.isOK
}
fun ElementAndTextList.linesCount() =
toList()
.filterIsInstance<PsiElement>()
.sumBy { StringUtil.getLineBreakCount(it.text) }
fun checkUseNewJ2k(targetFile: KtFile): Boolean {
if (targetFile is KtCodeFragment) return false
return ExperimentalFeatures.NewJ2k.isEnabled
}
fun runPostProcessing(
project: Project,
file: KtFile,
bounds: TextRange?,
converterContext: ConverterContext?,
useNewJ2k: Boolean
) {
val postProcessor = J2kConverterExtension.extension(useNewJ2k).createPostProcessor(formatCode = true)
if (useNewJ2k) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
val processor =
J2kConverterExtension.extension(useNewJ2k).createWithProgressProcessor(
ProgressManager.getInstance().progressIndicator!!,
emptyList(),
postProcessor.phasesCount
)
AfterConversionPass(project, postProcessor)
.run(
file,
converterContext,
bounds
) { phase, description ->
processor.updateState(0, phase, description)
}
},
@Suppress("DialogTitleCapitalization") KotlinBundle.message("copy.text.convert.java.to.kotlin.title"),
true,
project
)
} else {
AfterConversionPass(project, postProcessor)
.run(
file,
converterContext,
bounds
)
}
} | apache-2.0 | 3ed6aa571e61e7e8c78f0650d2ba9f91 | 37.329815 | 141 | 0.668594 | 5.420149 | false | false | false | false |
TheMrMilchmann/lwjgl3 | modules/lwjgl/bgfx/src/templates/kotlin/bgfx/templates/BGFX.kt | 1 | 116031 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package bgfx.templates
import bgfx.*
import org.lwjgl.generator.*
val BGFX = "BGFX".nativeClass(Module.BGFX, prefix = "BGFX", prefixMethod = "bgfx_", binding = BGFX_BINDING) {
documentation =
"Native bindings to the C API of the ${url("https://github.com/bkaradzic/bgfx", "bgfx")} library."
IntConstant(
"API version",
"API_VERSION".."115"
)
ShortConstant(
"Invalid handle",
"INVALID_HANDLE"..0xFFFF.s
)
val StateFlags = LongConstant(
"State",
"STATE_WRITE_R"..0x0000000000000001L,
"STATE_WRITE_G"..0x0000000000000002L,
"STATE_WRITE_B"..0x0000000000000004L,
"STATE_WRITE_A"..0x0000000000000008L,
"STATE_WRITE_Z"..0x0000004000000000L,
"STATE_WRITE_RGB".."BGFX_STATE_WRITE_R | BGFX_STATE_WRITE_G | BGFX_STATE_WRITE_B",
"STATE_WRITE_MASK".."BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A | BGFX_STATE_WRITE_Z",
"STATE_DEPTH_TEST_LESS"..0x0000000000000010L,
"STATE_DEPTH_TEST_LEQUAL"..0x0000000000000020L,
"STATE_DEPTH_TEST_EQUAL"..0x0000000000000030L,
"STATE_DEPTH_TEST_GEQUAL"..0x0000000000000040L,
"STATE_DEPTH_TEST_GREATER"..0x0000000000000050L,
"STATE_DEPTH_TEST_NOTEQUAL"..0x0000000000000060L,
"STATE_DEPTH_TEST_NEVER"..0x0000000000000070L,
"STATE_DEPTH_TEST_ALWAYS"..0x0000000000000080L,
"STATE_BLEND_ZERO"..0x0000000000001000L,
"STATE_BLEND_ONE"..0x0000000000002000L,
"STATE_BLEND_SRC_COLOR"..0x0000000000003000L,
"STATE_BLEND_INV_SRC_COLOR"..0x0000000000004000L,
"STATE_BLEND_SRC_ALPHA"..0x0000000000005000L,
"STATE_BLEND_INV_SRC_ALPHA"..0x0000000000006000L,
"STATE_BLEND_DST_ALPHA"..0x0000000000007000L,
"STATE_BLEND_INV_DST_ALPHA"..0x0000000000008000L,
"STATE_BLEND_DST_COLOR"..0x0000000000009000L,
"STATE_BLEND_INV_DST_COLOR"..0x000000000000a000L,
"STATE_BLEND_SRC_ALPHA_SAT"..0x000000000000b000L,
"STATE_BLEND_FACTOR"..0x000000000000c000L,
"STATE_BLEND_INV_FACTOR"..0x000000000000d000L,
"STATE_BLEND_EQUATION_ADD"..0x0000000000000000L,
"STATE_BLEND_EQUATION_SUB"..0x0000000010000000L,
"STATE_BLEND_EQUATION_REVSUB"..0x0000000020000000L,
"STATE_BLEND_EQUATION_MIN"..0x0000000030000000L,
"STATE_BLEND_EQUATION_MAX"..0x0000000040000000L,
"STATE_CULL_CW"..0x0000001000000000L,
"STATE_CULL_CCW"..0x0000002000000000L,
"STATE_PT_TRISTRIP"..0x0001000000000000L,
"STATE_PT_LINES"..0x0002000000000000L,
"STATE_PT_LINESTRIP"..0x0003000000000000L,
"STATE_PT_POINTS"..0x0004000000000000L,
"STATE_MSAA"..0x0100000000000000L,
"STATE_LINEAA"..0x0200000000000000L,
"STATE_CONSERVATIVE_RASTER"..0x0400000000000000L,
"STATE_NONE"..0x0000000000000000L,
"STATE_FRONT_CCW"..0x0000008000000000L,
"STATE_BLEND_INDEPENDENT"..0x0000000400000000L,
"STATE_BLEND_ALPHA_TO_COVERAGE"..0x0000000800000000L,
"STATE_DEFAULT".."""(0L
| BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
| BGFX_STATE_WRITE_Z
| BGFX_STATE_DEPTH_TEST_LESS
| BGFX_STATE_CULL_CW
| BGFX_STATE_MSAA)
"""
).javaDocLinks
LongConstant(
"State",
"STATE_DEPTH_TEST_MASK"..0x00000000000000f0L,
"STATE_BLEND_MASK"..0x000000000ffff000L,
"STATE_BLEND_EQUATION_MASK"..0x00000003f0000000L,
"STATE_CULL_MASK"..0x0000003000000000L,
"STATE_ALPHA_REF_MASK"..0x0000ff0000000000L,
"STATE_PT_MASK"..0x0007000000000000L,
"STATE_POINT_SIZE_MASK"..0x00f0000000000000L,
"STATE_RESERVED_MASK".."0xe000000000000000L",
"STATE_MASK".."0xffffffffffffffffL"
)
IntConstant(
"State",
"STATE_DEPTH_TEST_SHIFT".."4",
"STATE_BLEND_SHIFT".."12",
"STATE_BLEND_EQUATION_SHIFT".."28",
"STATE_CULL_SHIFT".."36",
"STATE_ALPHA_REF_SHIFT".."40",
"STATE_PT_SHIFT".."48",
"STATE_POINT_SIZE_SHIFT".."52",
"STATE_RESERVED_SHIFT".."61"
)
val StencilFlags = IntConstant(
"Stencil",
"STENCIL_TEST_LESS"..0x00010000,
"STENCIL_TEST_LEQUAL"..0x00020000,
"STENCIL_TEST_EQUAL"..0x00030000,
"STENCIL_TEST_GEQUAL"..0x00040000,
"STENCIL_TEST_GREATER"..0x00050000,
"STENCIL_TEST_NOTEQUAL"..0x00060000,
"STENCIL_TEST_NEVER"..0x00070000,
"STENCIL_TEST_ALWAYS"..0x00080000,
"STENCIL_OP_FAIL_S_ZERO"..0x00000000,
"STENCIL_OP_FAIL_S_KEEP"..0x00100000,
"STENCIL_OP_FAIL_S_REPLACE"..0x00200000,
"STENCIL_OP_FAIL_S_INCR"..0x00300000,
"STENCIL_OP_FAIL_S_INCRSAT"..0x00400000,
"STENCIL_OP_FAIL_S_DECR"..0x00500000,
"STENCIL_OP_FAIL_S_DECRSAT"..0x00600000,
"STENCIL_OP_FAIL_S_INVERT"..0x00700000,
"STENCIL_OP_FAIL_Z_ZERO"..0x00000000,
"STENCIL_OP_FAIL_Z_KEEP"..0x01000000,
"STENCIL_OP_FAIL_Z_REPLACE"..0x02000000,
"STENCIL_OP_FAIL_Z_INCR"..0x03000000,
"STENCIL_OP_FAIL_Z_INCRSAT"..0x04000000,
"STENCIL_OP_FAIL_Z_DECR"..0x05000000,
"STENCIL_OP_FAIL_Z_DECRSAT"..0x06000000,
"STENCIL_OP_FAIL_Z_INVERT"..0x07000000,
"STENCIL_OP_PASS_Z_ZERO"..0x00000000,
"STENCIL_OP_PASS_Z_KEEP"..0x10000000,
"STENCIL_OP_PASS_Z_REPLACE"..0x20000000,
"STENCIL_OP_PASS_Z_INCR"..0x30000000,
"STENCIL_OP_PASS_Z_INCRSAT"..0x40000000,
"STENCIL_OP_PASS_Z_DECR"..0x50000000,
"STENCIL_OP_PASS_Z_DECRSAT"..0x60000000,
"STENCIL_OP_PASS_Z_INVERT"..0x70000000,
"STENCIL_NONE"..0x00000000,
"STENCIL_DEFAULT"..0x00000000
).javaDocLinks
IntConstant(
"Stencil",
"STENCIL_FUNC_REF_SHIFT".."0",
"STENCIL_FUNC_REF_MASK"..0x000000ff,
"STENCIL_FUNC_RMASK_SHIFT".."8",
"STENCIL_FUNC_RMASK_MASK"..0x0000ff00,
"STENCIL_TEST_SHIFT".."16",
"STENCIL_TEST_MASK"..0x000f0000,
"STENCIL_OP_FAIL_S_SHIFT".."20",
"STENCIL_OP_FAIL_S_MASK"..0x00f00000,
"STENCIL_OP_FAIL_Z_SHIFT".."24",
"STENCIL_OP_FAIL_Z_MASK"..0x0f000000,
"STENCIL_OP_PASS_Z_SHIFT".."28",
"STENCIL_OP_PASS_Z_MASK".."0xf0000000",
"STENCIL_MASK".."0xffffffff"
)
val ClearFlags = IntConstant(
"Clear",
"CLEAR_NONE"..0x0000,
"CLEAR_COLOR"..0x0001,
"CLEAR_DEPTH"..0x0002,
"CLEAR_STENCIL"..0x0004,
"CLEAR_DISCARD_COLOR_0"..0x0008,
"CLEAR_DISCARD_COLOR_1"..0x0010,
"CLEAR_DISCARD_COLOR_2"..0x0020,
"CLEAR_DISCARD_COLOR_3"..0x0040,
"CLEAR_DISCARD_COLOR_4"..0x0080,
"CLEAR_DISCARD_COLOR_5"..0x0100,
"CLEAR_DISCARD_COLOR_6"..0x0200,
"CLEAR_DISCARD_COLOR_7"..0x0400,
"CLEAR_DISCARD_DEPTH"..0x0800,
"CLEAR_DISCARD_STENCIL"..0x1000,
"CLEAR_DISCARD_COLOR_MASK".."""(0
| BGFX_CLEAR_DISCARD_COLOR_0
| BGFX_CLEAR_DISCARD_COLOR_1
| BGFX_CLEAR_DISCARD_COLOR_2
| BGFX_CLEAR_DISCARD_COLOR_3
| BGFX_CLEAR_DISCARD_COLOR_4
| BGFX_CLEAR_DISCARD_COLOR_5
| BGFX_CLEAR_DISCARD_COLOR_6
| BGFX_CLEAR_DISCARD_COLOR_7)
""",
"CLEAR_DISCARD_MASK".."""(0
| BGFX_CLEAR_DISCARD_COLOR_MASK
| BGFX_CLEAR_DISCARD_DEPTH
| BGFX_CLEAR_DISCARD_STENCIL)
"""
).javaDocLinks
val DiscardFlags = ByteConstant(
"""
Rendering state discard.
When state is preserved in submit, rendering states can be discarded on a finer grain.
""",
"DISCARD_NONE"..0x00.b,
"DISCARD_BINDINGS"..0x01.b,
"DISCARD_INDEX_BUFFER"..0x02.b,
"DISCARD_INSTANCE_DATA"..0x04.b,
"DISCARD_STATE"..0x08.b,
"DISCARD_TRANSFORM"..0x10.b,
"DISCARD_VERTEX_STREAMS"..0x20.b,
"DISCARD_ALL"..0xff.b
).javaDocLinks
val DebugFlags = EnumConstant(
"Debug",
"DEBUG_NONE".enum("", 0x00000000),
"DEBUG_WIREFRAME".enum("Wireframe rendering. All rendering primitives will be rendered as lines.", 0x00000001),
"DEBUG_IFH".enum(
"""
Enable infinitely fast hardware test. No draw calls will be submitted to driver. It's useful when profiling to quickly assess bottleneck between
CPU and GPU.
""",
0x00000002
),
"DEBUG_STATS".enum("Display internal statistics.", 0x00000004),
"DEBUG_TEXT".enum("Display debug text.", 0x00000008),
"DEBUG_PROFILER".enum(
"""
Enable profiler.
This causes per-view statistics to be collected, available through ##BGFXViewStats. This is unrelated to the profiler functions in
##BGFXCallbackInterface.
""",
0x00000010
)
).javaDocLinks
val BufferFlags = IntConstant(
"Buffer creation flags",
"BUFFER_NONE"..0x0000,
"BUFFER_COMPUTE_READ"..0x0100,
"BUFFER_COMPUTE_WRITE"..0x0200,
"BUFFER_DRAW_INDIRECT"..0x0400,
"BUFFER_ALLOW_RESIZE"..0x0800,
"BUFFER_INDEX32"..0x1000,
"BUFFER_COMPUTE_READ_WRITE".."""(0
| BGFX_BUFFER_COMPUTE_READ
| BGFX_BUFFER_COMPUTE_WRITE)
"""
).javaDocLinks
ShortConstant(
"Buffer",
"BUFFER_COMPUTE_FORMAT_8x1"..0x0001.s,
"BUFFER_COMPUTE_FORMAT_8x2"..0x0002.s,
"BUFFER_COMPUTE_FORMAT_8x4"..0x0003.s,
"BUFFER_COMPUTE_FORMAT_16x1"..0x0004.s,
"BUFFER_COMPUTE_FORMAT_16x2"..0x0005.s,
"BUFFER_COMPUTE_FORMAT_16x4"..0x0006.s,
"BUFFER_COMPUTE_FORMAT_32x1"..0x0007.s,
"BUFFER_COMPUTE_FORMAT_32x2"..0x0008.s,
"BUFFER_COMPUTE_FORMAT_32x4"..0x0009.s,
"BUFFER_COMPUTE_FORMAT_SHIFT".."0",
"BUFFER_COMPUTE_FORMAT_MASK"..0x000f.s,
"BUFFER_COMPUTE_TYPE_INT"..0x0010.s,
"BUFFER_COMPUTE_TYPE_UINT"..0x0020.s,
"BUFFER_COMPUTE_TYPE_FLOAT"..0x0030.s,
"BUFFER_COMPUTE_TYPE_SHIFT".."4",
"BUFFER_COMPUTE_TYPE_MASK"..0x0030.s
)
val TextureFlags = LongConstant(
"Texture creation flags.",
"TEXTURE_NONE"..0x0000000000000000L,
"TEXTURE_MSAA_SAMPLE"..0x0000000800000000L,
"TEXTURE_RT"..0x0000001000000000L,
"TEXTURE_RT_MSAA_X2"..0x0000002000000000L,
"TEXTURE_RT_MSAA_X4"..0x0000003000000000L,
"TEXTURE_RT_MSAA_X8"..0x0000004000000000L,
"TEXTURE_RT_MSAA_X16"..0x0000005000000000L,
"TEXTURE_RT_WRITE_ONLY"..0x0000008000000000L,
"TEXTURE_COMPUTE_WRITE"..0x0000100000000000L,
"TEXTURE_SRGB"..0x0000200000000000L,
"TEXTURE_BLIT_DST"..0x0000400000000000L,
"TEXTURE_READ_BACK"..0x0000800000000000L
).javaDocLinks
IntConstant(
"Texture shifts.",
"TEXTURE_RT_MSAA_SHIFT".."36"
)
LongConstant(
"Texture masks.",
"TEXTURE_RT_MSAA_MASK"..0x0000007000000000L,
"TEXTURE_RT_MASK"..0x000000f000000000L
)
val SamplerFlags = IntConstant(
"Sample flags.",
"SAMPLER_NONE"..0x00000000,
"SAMPLER_U_MIRROR"..0x00000001,
"SAMPLER_U_CLAMP"..0x00000002,
"SAMPLER_U_BORDER"..0x00000003,
"SAMPLER_V_MIRROR"..0x00000004,
"SAMPLER_V_CLAMP"..0x00000008,
"SAMPLER_V_BORDER"..0x0000000c,
"SAMPLER_W_MIRROR"..0x00000010,
"SAMPLER_W_CLAMP"..0x00000020,
"SAMPLER_W_BORDER"..0x00000030,
"SAMPLER_UVW_MIRROR".."(0 | BGFX_SAMPLER_U_MIRROR | BGFX_SAMPLER_V_MIRROR | BGFX_SAMPLER_W_MIRROR)",
"SAMPLER_UVW_CLAMP".."(0 | BGFX_SAMPLER_U_CLAMP | BGFX_SAMPLER_V_CLAMP | BGFX_SAMPLER_W_CLAMP)",
"SAMPLER_UVW_BORDER".."(0 | BGFX_SAMPLER_U_BORDER | BGFX_SAMPLER_V_BORDER | BGFX_SAMPLER_W_BORDER)",
"SAMPLER_MIN_POINT"..0x00000040,
"SAMPLER_MIN_ANISOTROPIC"..0x00000080,
"SAMPLER_MAG_POINT"..0x00000100,
"SAMPLER_MAG_ANISOTROPIC"..0x00000200,
"SAMPLER_MIP_POINT"..0x00000400,
"SAMPLER_POINT".."(0 | BGFX_SAMPLER_MIN_POINT | BGFX_SAMPLER_MAG_POINT | BGFX_SAMPLER_MIP_POINT)",
"SAMPLER_COMPARE_LESS"..0x00010000,
"SAMPLER_COMPARE_LEQUAL"..0x00020000,
"SAMPLER_COMPARE_EQUAL"..0x00030000,
"SAMPLER_COMPARE_GEQUAL"..0x00040000,
"SAMPLER_COMPARE_GREATER"..0x00050000,
"SAMPLER_COMPARE_NOTEQUAL"..0x00060000,
"SAMPLER_COMPARE_NEVER"..0x00070000,
"SAMPLER_COMPARE_ALWAYS"..0x00080000,
"SAMPLER_SAMPLE_STENCIL"..0x00100000
).javaDocLinks
IntConstant(
"Sampler shifts/masks",
"SAMPLER_U_SHIFT".."0",
"SAMPLER_U_MASK"..0x00000003,
"SAMPLER_V_SHIFT".."2",
"SAMPLER_V_MASK"..0x0000000c,
"SAMPLER_W_SHIFT".."4",
"SAMPLER_W_MASK"..0x00000030,
"SAMPLER_MIN_SHIFT".."6",
"SAMPLER_MIN_MASK"..0x000000c0,
"SAMPLER_MAG_SHIFT".."8",
"SAMPLER_MAG_MASK"..0x00000300,
"SAMPLER_MIP_SHIFT".."10",
"SAMPLER_MIP_MASK"..0x00000400,
"SAMPLER_COMPARE_SHIFT".."16",
"SAMPLER_COMPARE_MASK"..0x000f0000,
"SAMPLER_BORDER_COLOR_SHIFT".."24",
"SAMPLER_BORDER_COLOR_MASK"..0x0f000000,
"SAMPLER_RESERVED_SHIFT".."28",
"SAMPLER_RESERVED_MASK".."0xF0000000",
"SAMPLER_SAMPLER_BITS_MASK".."""(0
| BGFX_SAMPLER_U_MASK
| BGFX_SAMPLER_V_MASK
| BGFX_SAMPLER_W_MASK
| BGFX_SAMPLER_MIN_MASK
| BGFX_SAMPLER_MAG_MASK
| BGFX_SAMPLER_MIP_MASK
| BGFX_SAMPLER_COMPARE_MASK)
"""
)
val ResetFlags = IntConstant(
"Reset",
"RESET_NONE"..0x00000000,
"RESET_FULLSCREEN"..0x00000001,
"RESET_FULLSCREEN_SHIFT".."0",
"RESET_FULLSCREEN_MASK"..0x00000001,
"RESET_MSAA_X2"..0x00000010,
"RESET_MSAA_X4"..0x00000020,
"RESET_MSAA_X8"..0x00000030,
"RESET_MSAA_X16"..0x00000040,
"RESET_MSAA_SHIFT".."4",
"RESET_MSAA_MASK"..0x00000070,
"RESET_VSYNC"..0x00000080,
"RESET_MAXANISOTROPY"..0x00000100,
"RESET_CAPTURE"..0x00000200,
"RESET_FLUSH_AFTER_RENDER"..0x00002000,
"RESET_FLIP_AFTER_RENDER"..0x00004000,
"RESET_SRGB_BACKBUFFER"..0x00008000,
"RESET_HDR10"..0x00010000,
"RESET_HIDPI"..0x00020000,
"RESET_DEPTH_CLAMP"..0x00040000,
"RESET_SUSPEND"..0x00080000,
"RESET_TRANSPARENT_BACKBUFFER"..0x00100000
).javaDocLinks
IntConstant(
"Reset",
"RESET_RESERVED_SHIFT".."31",
"RESET_RESERVED_MASK".."0x80000000"
)
LongConstant(
"Caps",
"CAPS_ALPHA_TO_COVERAGE"..0x0000000000000001L,
"CAPS_BLEND_INDEPENDENT"..0x0000000000000002L,
"CAPS_COMPUTE"..0x0000000000000004L,
"CAPS_CONSERVATIVE_RASTER"..0x0000000000000008L,
"CAPS_DRAW_INDIRECT"..0x0000000000000010L,
"CAPS_FRAGMENT_DEPTH"..0x0000000000000020L,
"CAPS_FRAGMENT_ORDERING"..0x0000000000000040L,
"CAPS_GRAPHICS_DEBUGGER"..0x0000000000000080L,
"CAPS_HDR10"..0x0000000000000100L,
"CAPS_HIDPI"..0x0000000000000200L,
"CAPS_IMAGE_RW"..0x0000000000000400L,
"CAPS_INDEX32"..0x000000000000800L,
"CAPS_INSTANCING"..0x0000000000001000L,
"CAPS_OCCLUSION_QUERY"..0x0000000000002000L,
"CAPS_RENDERER_MULTITHREADED"..0x0000000000004000L,
"CAPS_SWAP_CHAIN"..0x000000000008000L,
"CAPS_TEXTURE_2D_ARRAY"..0x0000000000010000L,
"CAPS_TEXTURE_3D"..0x0000000000020000L,
"CAPS_TEXTURE_BLIT"..0x0000000000040000L,
"CAPS_TRANSPARENT_BACKBUFFER"..0x0000000000080000L,
"CAPS_TEXTURE_COMPARE_RESERVED"..0x0000000000100000L,
"CAPS_TEXTURE_COMPARE_LEQUAL"..0x0000000000200000L,
"CAPS_TEXTURE_COMPARE_ALL".."BGFX_CAPS_TEXTURE_COMPARE_RESERVED | BGFX_CAPS_TEXTURE_COMPARE_LEQUAL",
"CAPS_TEXTURE_CUBE_ARRAY"..0x0000000000400000L,
"CAPS_TEXTURE_DIRECT_ACCESS"..0x0000000000800000L,
"CAPS_TEXTURE_READ_BACK"..0x0000000001000000L,
"CAPS_VERTEX_ATTRIB_HALF"..0x0000000002000000L,
"CAPS_VERTEX_ATTRIB_UINT10"..0x0000000004000000L,
"CAPS_VERTEX_ID"..0x0000000008000000L,
"CAPS_VIEWPORT_LAYER_ARRAY"..0x0000000010000000L
)
IntConstant(
"Format caps",
"CAPS_FORMAT_TEXTURE_NONE"..0x00000000,
"CAPS_FORMAT_TEXTURE_2D"..0x00000001,
"CAPS_FORMAT_TEXTURE_2D_SRGB"..0x00000002,
"CAPS_FORMAT_TEXTURE_2D_EMULATED"..0x00000004,
"CAPS_FORMAT_TEXTURE_3D"..0x00000008,
"CAPS_FORMAT_TEXTURE_3D_SRGB"..0x00000010,
"CAPS_FORMAT_TEXTURE_3D_EMULATED"..0x00000020,
"CAPS_FORMAT_TEXTURE_CUBE"..0x00000040,
"CAPS_FORMAT_TEXTURE_CUBE_SRGB"..0x00000080,
"CAPS_FORMAT_TEXTURE_CUBE_EMULATED"..0x00000100,
"CAPS_FORMAT_TEXTURE_VERTEX"..0x00000200,
"CAPS_FORMAT_TEXTURE_IMAGE_READ"..0x00000400,
"CAPS_FORMAT_TEXTURE_IMAGE_WRITE"..0x00000800,
"CAPS_FORMAT_TEXTURE_FRAMEBUFFER"..0x00001000,
"CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA"..0x00002000,
"CAPS_FORMAT_TEXTURE_MSAA"..0x00004000,
"CAPS_FORMAT_TEXTURE_MIP_AUTOGEN"..0x00008000
)
ByteConstant(
"Resolve flags.",
"RESOLVE_NONE"..0x00.b,
"RESOLVE_AUTO_GEN_MIPS"..0x01.b
)
ShortConstant(
"PCI",
"PCI_ID_NONE"..0x0000.s,
"PCI_ID_SOFTWARE_RASTERIZER"..0x0001.s,
"PCI_ID_AMD"..0x1002.s,
"PCI_ID_APPLE"..0x106b.s,
"PCI_ID_INTEL".."(short)0x8086",
"PCI_ID_NVIDIA"..0x10de.s,
"PCI_ID_MICROSOFT"..0x1414.s,
"PCI_ID_ARM"..0x13b5.s
)
val CubeMapSides = ByteConstant(
"Cubemap",
"CUBE_MAP_POSITIVE_X"..0x00.b,
"CUBE_MAP_NEGATIVE_X"..0x01.b,
"CUBE_MAP_POSITIVE_Y"..0x02.b,
"CUBE_MAP_NEGATIVE_Y"..0x03.b,
"CUBE_MAP_POSITIVE_Z"..0x04.b,
"CUBE_MAP_NEGATIVE_Z"..0x05.b
).javaDocLinks
EnumConstant(
"Fatal errors ({@code bgfx_fatal_t}).",
"FATAL_DEBUG_CHECK".enum,
"FATAL_INVALID_SHADER".enum,
"FATAL_UNABLE_TO_INITIALIZE".enum,
"FATAL_UNABLE_TO_CREATE_TEXTURE".enum,
"FATAL_DEVICE_LOST".enum,
"FATAL_COUNT".enum
)
val RendererType = EnumConstant(
"Renderer backend type. ({@code bgfx_renderer_type_t})",
"RENDERER_TYPE_NOOP".enum("No rendering."),
"RENDERER_TYPE_AGC".enum("AGC"),
"RENDERER_TYPE_DIRECT3D9".enum("Direct3D 9.0"),
"RENDERER_TYPE_DIRECT3D11".enum("Direct3D 11.0"),
"RENDERER_TYPE_DIRECT3D12".enum("Direct3D 12.0"),
"RENDERER_TYPE_GNM".enum("GNM"),
"RENDERER_TYPE_METAL".enum("Metal"),
"RENDERER_TYPE_NVN".enum("Nvn"),
"RENDERER_TYPE_OPENGLES".enum("OpenGL ES 2.0+"),
"RENDERER_TYPE_OPENGL".enum("OpenGL 2.1+"),
"RENDERER_TYPE_VULKAN".enum("Vulkan"),
"BGFX_RENDERER_TYPE_WEBGPU".enum("WebGPU"),
"RENDERER_TYPE_COUNT".enum
).javaDocLinks
val Access = EnumConstant(
"Access mode ({@code bgfx_access_t})",
"ACCESS_READ".enum("Read"),
"ACCESS_WRITE".enum("Write"),
"ACCESS_READWRITE".enum("Read and write"),
"ACCESS_COUNT".enum
).javaDocLinksSkipCount
val Attrib = EnumConstant(
"Vertex attribute ({@code bgfx_attrib_t}).",
"ATTRIB_POSITION".enum,
"ATTRIB_NORMAL".enum,
"ATTRIB_TANGENT".enum,
"ATTRIB_BITANGENT".enum,
"ATTRIB_COLOR0".enum,
"ATTRIB_COLOR1".enum,
"ATTRIB_COLOR2".enum,
"ATTRIB_COLOR3".enum,
"ATTRIB_INDICES".enum,
"ATTRIB_WEIGHT".enum,
"ATTRIB_TEXCOORD0".enum,
"ATTRIB_TEXCOORD1".enum,
"ATTRIB_TEXCOORD2".enum,
"ATTRIB_TEXCOORD3".enum,
"ATTRIB_TEXCOORD4".enum,
"ATTRIB_TEXCOORD5".enum,
"ATTRIB_TEXCOORD6".enum,
"ATTRIB_TEXCOORD7".enum,
"ATTRIB_COUNT".enum("", "BGFX_ATTRIB_TEXCOORD7 + 1")
).javaDocLinksSkipCount
val AttribType = EnumConstant(
"Vertex attribute type ({@code bgfx_attrib_type_t}).",
"ATTRIB_TYPE_UINT8".enum("Uint8"),
"ATTRIB_TYPE_UINT10".enum("Uint10, availability depends on: #CAPS_VERTEX_ATTRIB_UINT10."),
"ATTRIB_TYPE_INT16".enum("Int16"),
"ATTRIB_TYPE_HALF".enum("Half, availability depends on: #CAPS_VERTEX_ATTRIB_HALF`."),
"ATTRIB_TYPE_FLOAT".enum("Float"),
"ATTRIB_TYPE_COUNT".enum("", "BGFX_ATTRIB_TYPE_FLOAT + 1")
).javaDocLinks
val TextureFormat = EnumConstant(
"""
Texture format ({@code bgfx_texture_format_t}). Notation:
${codeBlock("""
RGBA16S
^ ^ ^
| | +-- [ ]Unorm
| | [F]loat
| | [S]norm
| | [I]nt
| | [U]int
| +---- Number of bits per component
+-------- Components""")}
Availability depends on Caps.
""",
"TEXTURE_FORMAT_BC1".enum("DXT1 R5G6B5A1"),
"TEXTURE_FORMAT_BC2".enum("DXT3 R5G6B5A4"),
"TEXTURE_FORMAT_BC3".enum("DXT5 R5G6B5A8"),
"TEXTURE_FORMAT_BC4".enum("LATC1/ATI1 R8"),
"TEXTURE_FORMAT_BC5".enum("LATC2/ATI2 RG8"),
"TEXTURE_FORMAT_BC6H".enum("BC6H RGB16F"),
"TEXTURE_FORMAT_BC7".enum("BC7 RGB 4-7 bits per color channel, 0-8 bits alpha"),
"TEXTURE_FORMAT_ETC1".enum("ETC1 RGB8"),
"TEXTURE_FORMAT_ETC2".enum("ETC2 RGB8"),
"TEXTURE_FORMAT_ETC2A".enum("ETC2 RGBA8"),
"TEXTURE_FORMAT_ETC2A1".enum("ETC2 RGB8A1"),
"TEXTURE_FORMAT_PTC12".enum("PVRTC1 RGB 2BPP"),
"TEXTURE_FORMAT_PTC14".enum("PVRTC1 RGB 4BPP"),
"TEXTURE_FORMAT_PTC12A".enum("PVRTC1 RGBA 2BPP"),
"TEXTURE_FORMAT_PTC14A".enum("PVRTC1 RGBA 4BPP"),
"TEXTURE_FORMAT_PTC22".enum("PVRTC2 RGBA 2BPP"),
"TEXTURE_FORMAT_PTC24".enum("PVRTC2 RGBA 4BPP"),
"TEXTURE_FORMAT_ATC".enum("ATC RGB 4BPP"),
"TEXTURE_FORMAT_ATCE".enum("ATCE RGBA 8 BPP explicit alpha"),
"TEXTURE_FORMAT_ATCI".enum("ATCI RGBA 8 BPP interpolated alpha"),
"TEXTURE_FORMAT_ASTC4x4".enum("ASTC 4x4 8.0 BPP"),
"TEXTURE_FORMAT_ASTC5x5".enum("ASTC 5x5 5.12 BPP"),
"TEXTURE_FORMAT_ASTC6x6".enum("ASTC 6x6 3.56 BPP"),
"TEXTURE_FORMAT_ASTC8x5".enum("ASTC 8x5 3.20 BPP"),
"TEXTURE_FORMAT_ASTC8x6".enum("ASTC 8x6 2.67 BPP"),
"TEXTURE_FORMAT_ASTC10x5".enum("ASTC 10x5 2.56 BPP"),
"TEXTURE_FORMAT_UNKNOWN".enum,
"TEXTURE_FORMAT_R1".enum,
"TEXTURE_FORMAT_A8".enum,
"TEXTURE_FORMAT_R8".enum,
"TEXTURE_FORMAT_R8I".enum,
"TEXTURE_FORMAT_R8U".enum,
"TEXTURE_FORMAT_R8S".enum,
"TEXTURE_FORMAT_R16".enum,
"TEXTURE_FORMAT_R16I".enum,
"TEXTURE_FORMAT_R16U".enum,
"TEXTURE_FORMAT_R16F".enum,
"TEXTURE_FORMAT_R16S".enum,
"TEXTURE_FORMAT_R32I".enum,
"TEXTURE_FORMAT_R32U".enum,
"TEXTURE_FORMAT_R32F".enum,
"TEXTURE_FORMAT_RG8".enum,
"TEXTURE_FORMAT_RG8I".enum,
"TEXTURE_FORMAT_RG8U".enum,
"TEXTURE_FORMAT_RG8S".enum,
"TEXTURE_FORMAT_RG16".enum,
"TEXTURE_FORMAT_RG16I".enum,
"TEXTURE_FORMAT_RG16U".enum,
"TEXTURE_FORMAT_RG16F".enum,
"TEXTURE_FORMAT_RG16S".enum,
"TEXTURE_FORMAT_RG32I".enum,
"TEXTURE_FORMAT_RG32U".enum,
"TEXTURE_FORMAT_RG32F".enum,
"TEXTURE_FORMAT_RGB8".enum,
"TEXTURE_FORMAT_RGB8I".enum,
"TEXTURE_FORMAT_RGB8U".enum,
"TEXTURE_FORMAT_RGB8S".enum,
"TEXTURE_FORMAT_RGB9E5F".enum,
"TEXTURE_FORMAT_BGRA8".enum,
"TEXTURE_FORMAT_RGBA8".enum,
"TEXTURE_FORMAT_RGBA8I".enum,
"TEXTURE_FORMAT_RGBA8U".enum,
"TEXTURE_FORMAT_RGBA8S".enum,
"TEXTURE_FORMAT_RGBA16".enum,
"TEXTURE_FORMAT_RGBA16I".enum,
"TEXTURE_FORMAT_RGBA16U".enum,
"TEXTURE_FORMAT_RGBA16F".enum,
"TEXTURE_FORMAT_RGBA16S".enum,
"TEXTURE_FORMAT_RGBA32I".enum,
"TEXTURE_FORMAT_RGBA32U".enum,
"TEXTURE_FORMAT_RGBA32F".enum,
"TEXTURE_FORMAT_R5G6B5".enum,
"TEXTURE_FORMAT_RGBA4".enum,
"TEXTURE_FORMAT_RGB5A1".enum,
"TEXTURE_FORMAT_RGB10A2".enum,
"TEXTURE_FORMAT_RG11B10F".enum,
"TEXTURE_FORMAT_UNKNOWN_DEPTH".enum,
"TEXTURE_FORMAT_D16".enum,
"TEXTURE_FORMAT_D24".enum,
"TEXTURE_FORMAT_D24S8".enum,
"TEXTURE_FORMAT_D32".enum,
"TEXTURE_FORMAT_D16F".enum,
"TEXTURE_FORMAT_D24F".enum,
"TEXTURE_FORMAT_D32F".enum,
"TEXTURE_FORMAT_D0S8".enum,
"TEXTURE_FORMAT_COUNT".enum("", "BGFX_TEXTURE_FORMAT_D0S8 + 1")
).javaDocLinksSkipCount
val UniformType = EnumConstant(
"Uniform type ({@code bgfx_uniform_type_t}).",
"UNIFORM_TYPE_SAMPLER".enum("Sampler."),
"UNIFORM_TYPE_END".enum("Reserved, do not use."),
"UNIFORM_TYPE_VEC4".enum("4 floats vector."),
"UNIFORM_TYPE_MAT3".enum("3x3 matrix."),
"UNIFORM_TYPE_MAT4".enum("4x4 matrix."),
"UNIFORM_TYPE_COUNT".enum
).javaDocLinksSkipCount
val BackbufferRatio = EnumConstant(
"Backbuffer ratio ({@code bgfx_backbuffer_ratio_t}).",
"BACKBUFFER_RATIO_EQUAL".enum("Equal to backbuffer."),
"BACKBUFFER_RATIO_HALF".enum("One half size of backbuffer."),
"BACKBUFFER_RATIO_QUARTER".enum("One quarter size of backbuffer."),
"BACKBUFFER_RATIO_EIGHTH".enum("One eighth size of backbuffer."),
"BACKBUFFER_RATIO_SIXTEENTH".enum("One sixteenth size of backbuffer."),
"BACKBUFFER_RATIO_DOUBLE".enum("Double size of backbuffer."),
"BACKBUFFER_RATIO_COUNT".enum
).javaDocLinksSkipCount
EnumConstant(
"Occlusion query result ({@code bgfx_occlusion_query_result_t}).",
"OCCLUSION_QUERY_RESULT_INVISIBLE".enum("Query failed test."),
"OCCLUSION_QUERY_RESULT_VISIBLE".enum("Query passed test."),
"OCCLUSION_QUERY_RESULT_NORESULT".enum("Query result is not available yet."),
"OCCLUSION_QUERY_RESULT_COUNT".enum
)
EnumConstant(
"{@code bgfx_topology}",
"TOPOLOGY_TRI_LIST".enum("Triangle list"),
"TOPOLOGY_TRI_STRIP".enum("Triangle strip"),
"TOPOLOGY_LINE_LIST".enum("Line list"),
"TOPOLOGY_LINE_STRIP".enum("Line strip"),
"TOPOLOGY_POINT_LIST".enum("Point list"),
"TOPOLOGY_COUNT".enum
)
val TopologyConvert = EnumConstant(
"Topology conversion function ({@code bgfx_topology_convert_t}).",
"TOPOLOGY_CONVERT_TRI_LIST_FLIP_WINDING".enum("Flip winding order of triangle list."),
"TOPOLOGY_CONVERT_TRI_STRIP_FLIP_WINDING".enum("Flip winding order of triangle strip."),
"TOPOLOGY_CONVERT_TRI_LIST_TO_LINE_LIST".enum("Convert triangle list to line list."),
"TOPOLOGY_CONVERT_TRI_STRIP_TO_TRI_LIST".enum("Convert triangle strip to triangle list."),
"TOPOLOGY_CONVERT_LINE_STRIP_TO_LINE_LIST".enum("Convert line strip to line list."),
"TOPOLOGY_CONVERT_COUNT".enum
).javaDocLinksSkipCount
val TopologySort = EnumConstant(
"Topology sort order ({@code bgfx_topology_sort_t}).",
"TOPOLOGY_SORT_DIRECTION_FRONT_TO_BACK_MIN".enum,
"TOPOLOGY_SORT_DIRECTION_FRONT_TO_BACK_AVG".enum,
"TOPOLOGY_SORT_DIRECTION_FRONT_TO_BACK_MAX".enum,
"TOPOLOGY_SORT_DIRECTION_BACK_TO_FRONT_MIN".enum,
"TOPOLOGY_SORT_DIRECTION_BACK_TO_FRONT_AVG".enum,
"TOPOLOGY_SORT_DIRECTION_BACK_TO_FRONT_MAX".enum,
"TOPOLOGY_SORT_DISTANCE_FRONT_TO_BACK_MIN".enum,
"TOPOLOGY_SORT_DISTANCE_FRONT_TO_BACK_AVG".enum,
"TOPOLOGY_SORT_DISTANCE_FRONT_TO_BACK_MAX".enum,
"TOPOLOGY_SORT_DISTANCE_BACK_TO_FRONT_MIN".enum,
"TOPOLOGY_SORT_DISTANCE_BACK_TO_FRONT_AVG".enum,
"TOPOLOGY_SORT_DISTANCE_BACK_TO_FRONT_MAX".enum,
"TOPOLOGY_SORT_COUNT".enum
).javaDocLinksSkipCount
val ViewMode = EnumConstant(
"View mode sets draw call sort order ({@code bgfx_view_mode_t}).",
"VIEW_MODE_DEFAULT".enum("Default sort order."),
"VIEW_MODE_SEQUENTIAL".enum("Sort in the same order in which submit calls were called."),
"VIEW_MODE_DEPTH_ASCENDING".enum("Sort draw call depth in ascending order."),
"VIEW_MODE_DEPTH_DESCENDING".enum("Sort draw call depth in descending order."),
"VIEW_MODE_COUNT".enum
).javaDocLinksSkipCount
void(
"attachment_init",
"Init attachment.",
bgfx_attachment_t.p("_this", ""),
bgfx_texture_handle_t("_handle", "render target texture handle"),
bgfx_access_t("_access", "access", Access),
MapToInt..uint16_t("_layer", "cubemap side or depth layer/slice to use"),
MapToInt..uint16_t("_numLayers", "number of texture layer/slice(s) in array to use"),
MapToInt..uint16_t("_mip", "mip level"),
MapToInt..uint8_t("_resolve", "resolve flags", "RESOLVE_\\w+")
)
bgfx_vertex_layout_t.p(
"vertex_layout_begin",
"Start a vertex layout.",
bgfx_vertex_layout_t.p("_this", "the vertex layout"),
bgfx_renderer_type_t("_renderer", "the renderer backend type", RendererType),
returnDoc = "itself"
)
bgfx_vertex_layout_t.p(
"vertex_layout_add",
"""
Adds attribute to a vertex layout.
Must be called between #vertex_layout_begin()/#vertex_layout_end().
""",
bgfx_vertex_layout_t.p("_this", "the vertex layout"),
bgfx_attrib_t("_attrib", "attribute semantics", Attrib),
MapToInt..uint8_t("_num", "number of elements", "1 2 3 4"),
bgfx_attrib_type_t("_type", "element type", AttribType),
bool(
"_normalized",
"""
when using fixed point attribute type (f.e. #ATTRIB_TYPE_UINT8) value will be normalized for vertex shader usage. When {@code normalized} is set to
true, #ATTRIB_TYPE_UINT8 value in range 0-255 will be in range 0.0-1.0 in vertex shader.
"""
),
bool(
"_asInt",
"""
packaging rule for {@code vertexPack}, {@code vertexUnpack}, and {@code vertexConvert} for #ATTRIB_TYPE_UINT8 and #ATTRIB_TYPE_INT16. Unpacking
code must be implemented inside vertex shader.
"""
),
returnDoc = "itself"
)
void(
"vertex_layout_decode",
"Decodes attribute.",
bgfx_vertex_layout_t.const.p("_this", "the vertex layout"),
bgfx_attrib_t("_attrib", "the attribute to decode"),
Check(1)..uint8_t.p("_num", "number of elements"),
Check(1)..bgfx_attrib_type_t.p("_type", "element type"),
Check(1)..bool.p("_normalized", "normalized flag"),
Check(1)..bool.p("_asInt", "packaging flag")
)
bool(
"vertex_layout_has",
"Returns true if {@code _this} contains attribute.",
bgfx_vertex_layout_t.const.p("_this", "the vertex layout"),
bgfx_attrib_t("_attr", "the attribute to query", Attrib),
returnDoc = "{@code true} if {@code VertexLayout} contains attribute"
)
bgfx_vertex_layout_t.p(
"vertex_layout_skip",
"Skips {@code _num} bytes in vertex stream.",
bgfx_vertex_layout_t.p("_this", "the vertex layout"),
MapToInt..uint8_t("_num", "the number of bytes to skip"),
returnDoc = "itself"
)
void(
"vertex_layout_end",
"Ends a vertex layout.",
bgfx_vertex_layout_t.p("_this", "the vertex layout")
)
void(
"vertex_pack",
"Packs vertex attribute into vertex stream format.",
Check(4)..float.const.p("_input", "value to be packed into vertex stream"),
bool("_inputNormalized", "true if input value is already normalized"),
bgfx_attrib_t("_attr", "attribute to pack", Attrib),
bgfx_vertex_layout_t.const.p("_layout", "vertex stream layout"),
Unsafe..void.p("_data", "destination vertex stream where data will be packed"),
uint32_t("_index", "vertex index that will be modified")
)
void(
"vertex_unpack",
"Unpacks vertex attribute from vertex stream format.",
Check(4)..float.p("_output", "result of unpacking"),
bgfx_attrib_t("_attr", "attribute to unpack", Attrib),
bgfx_vertex_layout_t.const.p("_layout", "vertex stream layout"),
Unsafe..void.const.p("_data", "source vertex stream from where data will be unpacked"),
uint32_t("_index", "vertex index that will be unpacked")
)
void(
"vertex_convert",
"Converts vertex stream data from one vertex stream format to another.",
bgfx_vertex_layout_t.const.p("_dstLayout", "destination vertex stream layout"),
Unsafe..void.p("_dstData", "destination vertex stream"),
bgfx_vertex_layout_t.const.p("_srcLayout", "source vertex stream layout"),
Unsafe..void.const.p("_srcData", "source vertex stream data"),
uint32_t("_num", "number of vertices to convert from source to destination")
)
uint32_t(
"weld_vertices",
"Welds vertices.",
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT
)..void.p("_output", "welded vertices remapping table. The size of buffer must be the same as number of vertices."),
bgfx_vertex_layout_t.const.p("_layout", "vertex stream layout"),
Unsafe..void.const.p("_data", "vertex stream"),
AutoSizeShr("(_index32 ? 2 : 1)", "_output")..uint32_t("_num", "number of vertices in vertex stream"),
bool("_index32", "set to {@code true} if input indices are 32-bit"),
float("_epsilon", "error tolerance for vertex position comparison"),
returnDoc = "number of unique vertices after vertex welding"
)
uint32_t(
"topology_convert",
"Converts index buffer for use with different primitive topologies.",
bgfx_topology_convert_t("_conversion", "conversion type", TopologyConvert),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT
)..nullable..void.p("_dst", "destination index buffer. If this argument is #NULL function will return number of indices after conversion"),
AutoSize("_dst")..uint32_t(
"_dstSize",
"""
destination index buffer in bytes. It must be large enough to contain output indices. If destination size is insufficient index buffer will be
truncated.
"""
),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT
)..void.const.p("_indices", "source indices"),
AutoSizeShr("(_index32 ? 2 : 1)", "_indices")..uint32_t("_numIndices", "number of input indices"),
bool("_index32", "set to {@code true} if input indices are 32-bit"),
returnDoc = "number of output indices after conversion"
)
void(
"topology_sort_tri_list",
"Sorts indices.",
bgfx_topology_sort_t("_sort", "sort order", TopologySort),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT
)..void.p("_dst", "destination index buffer"),
AutoSize("_dst")..uint32_t(
"_dstSize",
"""
destination index buffer in bytes. It must be large enough to contain output indices. If destination size is insufficient index buffer will be
truncated.
"""
),
Check(3)..float.const.p("_dir", "direction (vector must be normalized)"),
Check(3)..float.const.p("_pos", "position"),
Unsafe..void.const.p(
"_vertices",
"pointer to first vertex represented as float x, y, z. Must contain at least number of vertices referenced by index buffer."
),
uint32_t("_stride", "vertex stride"),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT
)..void.const.p("_indices", "source indices"),
AutoSizeShr("(_index32 ? 2 : 1)", "_indices")..uint32_t("_numIndices", "number of input indices"),
bool("_index32", "set to {@code true} if input indices are 32-bit")
)
uint8_t(
"get_supported_renderers",
"Returns supported backend API renderers.",
AutoSize("_enum")..MapToInt..uint8_t("_max", "maximum number of elements in {@code _enum} array"),
bgfx_renderer_type_t.p("_enum", "array where supported renderers will be written"),
returnDoc = "the number of renderers written to {@code _enum}"
)
charASCII.const.p(
"get_renderer_name",
"Returns name of renderer.",
bgfx_renderer_type_t("_type", "the renderer type", RendererType)
)
void(
"init_ctor",
"Updates the specified initialization parameters with default values.",
bgfx_init_t.p("_init", "initialization parameters")
)
bool(
"init",
"Initializes the bgfx library.",
bgfx_init_t.const.p("_init", "initialization parameters"),
returnDoc = "true if initialization was successful"
)
void(
"shutdown",
"Shuts down bgfx library."
)
void(
"reset",
"""
Resets graphic settings and back-buffer size.
This call doesnโt change the window size, it just resizes the back-buffer. Your windowing code controls the window size.
""",
uint32_t("_width", "back-buffer width"),
uint32_t("_height", "back-buffer height"),
uint32_t("_flags", "reset flags", ResetFlags, LinkMode.BITFIELD),
bgfx_texture_format_t("_format", "texture format", TextureFormat)
)
uint32_t(
"frame",
"""
Advances to next frame. When using multithreaded renderer, this call just swaps internal buffers, kicks render thread, and returns. In singlethreaded
renderer this call does frame rendering.
""",
bool("_capture", "capture frame with graphics debugger"),
returnDoc =
"""
current frame number. This might be used in conjunction with double/multi buffering data outside the library and passing it to library #make_ref()
calls.
"""
)
bgfx_renderer_type_t(
"get_renderer_type",
"Returns current renderer backend API type.",
void()
)
bgfx_caps_t.const.p(
"get_caps",
"Returns renderer capabilities.",
void()
)
bgfx_stats_t.const.p(
"get_stats",
"""
Returns performance counters.
The pointer returned is valid until #frame() is called.
""",
void()
)
bgfx_memory_t.const.p(
"alloc",
"Allocates buffer to pass to bgfx calls. Data will be freed inside bgfx.",
uint32_t("_size", "the number of bytes to allocate")
)
bgfx_memory_t.const.p(
"copy",
"Allocates buffer and copies data into it. Data will be freed inside bgfx.",
MultiTypeAll..void.const.p("_data", "pointer to data to be copied"),
AutoSize("_data")..uint32_t("_size", "size of data to be copied")
)
OffHeapOnly..bgfx_memory_t.const.p(
"make_ref",
"""
Makes reference to data to pass to bgfx. Unlike #alloc(), this call doesn't allocate memory for data. It just copies the {@code _data} pointer.
Data passed must be available for at least 2 #frame() calls.
""",
MultiTypeAll..void.const.p("_data", "the data to reference"),
AutoSize("_data")..uint32_t("_size", "the number of bytes to reference")
)
OffHeapOnly..bgfx_memory_t.const.p(
"make_ref_release",
"""
Makes reference to data to pass to bgfx. Unlike #alloc(), this call doesn't allocate memory for data. It just copies the {@code _data} pointer.
The {@code bgfx_release_fn_t} function pointer will release this memory after it's consumed. The {@code bgfx_release_fn_t} function must be able to be
called from any thread.
""",
MultiTypeAll..void.const.p("_data", "the data to reference"),
AutoSize("_data")..uint32_t("_size", "the number of bytes to reference"),
bgfx_release_fn_t("_releaseFn", "callback function to release memory after use"),
nullable..opaque_p("_userData", "user data to be passed to callback function")
)
void(
"set_debug",
"Sets debug flags.",
uint32_t("_debug", "the debug flags", DebugFlags, LinkMode.BITFIELD)
)
void(
"dbg_text_clear",
"Clears internal debug text buffer.",
MapToInt..uint8_t("_attr", "background color"),
bool("_small", "default 8x16 or 8x8 font")
)
void(
"dbg_text_printf",
"""
Prints into internal debug text character-buffer (VGA-compatible text mode).
<b>LWJGL note</b>: This is a vararg function that should be called with {@link Functions\#dbg_text_printf dbg_text_printf} via the libffi bindings.
""",
MapToInt..uint16_t("_x", "x coordinate"),
MapToInt..uint16_t("_y", "y coordinate"),
MapToInt..uint8_t(
"_attr",
"""
color palette. Where top 4-bits represent index of background, and bottom 4-bits represent foreground color from standard VGA text palette (ANSI
escape codes).
"""
),
charASCII.const.p("_format", "{@code printf} style format")
)
void(
"dbg_text_vprintf",
"Print into internal debug text character-buffer (VGA-compatible text mode).",
MapToInt..uint16_t("_x", "x coordinate"),
MapToInt..uint16_t("_y", "y coordinate"),
MapToInt..uint8_t(
"_attr",
"color palette. Where top 4-bits represent index of background, and bottom 4-bits represent foreground color from standard VGA text palette."
),
charASCII.const.p("_format", "{@code printf} style format"),
va_list("_argList", "additional arguments for format string")
)
void(
"dbg_text_image",
"Draws image into internal debug text buffer.",
MapToInt..uint16_t("_x", "x coordinate"),
MapToInt..uint16_t("_y", "y coordinate"),
MapToInt..uint16_t("_width", "image width"),
MapToInt..uint16_t("_height", "image height"),
Check("_height * _pitch")..void.const.p("_data", "raw image data (character/attribute raw encoding)"),
MapToInt..uint16_t("_pitch", "image pitch in bytes")
)
bgfx_index_buffer_handle_t(
"create_index_buffer",
"Creates static index buffer.",
bgfx_memory_t.const.p("_mem", "index buffer data"),
MapToInt..uint16_t("_flags", "buffer creation flags", BufferFlags, LinkMode.BITFIELD)
)
void(
"set_index_buffer_name",
"Set static index buffer debug name.",
bgfx_index_buffer_handle_t("_handle", "static index buffer handle"),
charASCII.const.p("_name", "static index buffer name"),
AutoSize("_name")..int32_t(
"_len",
"static index buffer name length (if length is {@code INT32_MAX}, it's expected that {@code _name} is zero terminated string)"
)
)
void(
"destroy_index_buffer",
"Destroys static index buffer.",
bgfx_index_buffer_handle_t("_handle", "the static index buffer to destroy")
)
bgfx_vertex_layout_handle_t(
"create_vertex_layout",
"Creates a vertex layout.",
bgfx_vertex_layout_t.const.p("_layout", "vertex layout")
)
void(
"destroy_vertex_layout",
"Destroys a vertex layout.",
bgfx_vertex_layout_handle_t("_handle", "vertex layout handle")
)
bgfx_vertex_buffer_handle_t(
"create_vertex_buffer",
"Creates static vertex buffer.",
bgfx_memory_t.const.p("_mem", "vertex buffer data"),
bgfx_vertex_layout_t.const.p("_layout", "vertex layout"),
MapToInt..uint16_t("_flags", "buffer creation flags", BufferFlags, LinkMode.BITFIELD)
)
void(
"set_vertex_buffer_name",
"Set static vertex buffer debug name.",
bgfx_vertex_buffer_handle_t("_handle", "static vertex buffer handle"),
charASCII.const.p("_name", "static vertex buffer name"),
AutoSize("_name")..int32_t(
"_len",
"static vertex buffer name length (if length is {@code INT32_MAX}, it's expected that {@code _name} is zero terminated string)"
)
)
void(
"destroy_vertex_buffer",
"Destroys static vertex buffer.",
bgfx_vertex_buffer_handle_t("_handle", "the static vertex buffer to destroy")
)
bgfx_dynamic_index_buffer_handle_t(
"create_dynamic_index_buffer",
"Creates empty dynamic index buffer.",
uint32_t("_num", "number of indices"),
MapToInt..uint16_t("_flags", "buffer creation flags", BufferFlags, LinkMode.BITFIELD)
)
bgfx_dynamic_index_buffer_handle_t(
"create_dynamic_index_buffer_mem",
"Creates a dynamic index buffer and initializes it.",
bgfx_memory_t.const.p("_mem", "index buffer data"),
MapToInt..uint16_t("_flags", "buffer creation flags", BufferFlags, LinkMode.BITFIELD)
)
void(
"update_dynamic_index_buffer",
"Updates dynamic index buffer.",
bgfx_dynamic_index_buffer_handle_t("_handle", "dynamic index buffer handle"),
uint32_t("_startIndex", "start index"),
bgfx_memory_t.const.p("_mem", "index buffer data")
)
void(
"destroy_dynamic_index_buffer",
"Destroys dynamic index buffer.",
bgfx_dynamic_index_buffer_handle_t("_handle", "the dynamic index buffer to destroy")
)
bgfx_dynamic_vertex_buffer_handle_t(
"create_dynamic_vertex_buffer",
"Creates empty dynamic vertex buffer.",
uint32_t("_num", "number of vertices"),
bgfx_vertex_layout_t.const.p("_layout", "vertex layout"),
MapToInt..uint16_t("_flags", "buffer creation flags", BufferFlags, LinkMode.BITFIELD)
)
bgfx_dynamic_vertex_buffer_handle_t(
"create_dynamic_vertex_buffer_mem",
"Creates dynamic vertex buffer and initializes it.",
bgfx_memory_t.const.p("_mem", "vertex buffer data"),
bgfx_vertex_layout_t.const.p("_layout", "vertex layout"),
MapToInt..uint16_t("_flags", "buffer creation flags", BufferFlags, LinkMode.BITFIELD)
)
void(
"update_dynamic_vertex_buffer",
"Updates dynamic vertex buffer.",
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer handle"),
uint32_t("_startVertex", "start vertex"),
bgfx_memory_t.const.p("_mem", "vertex buffer data")
)
void(
"destroy_dynamic_vertex_buffer",
"Destroys dynamic vertex buffer.",
bgfx_dynamic_vertex_buffer_handle_t("_handle", "the dynamic vertex buffer to destroy")
)
uint32_t(
"get_avail_transient_index_buffer",
"Returns number of requested or maximum available indices.",
uint32_t("_num", "number of required indices"),
bool("_index32", "set to {@code true} if input indices will be 32-bit")
)
uint32_t(
"get_avail_transient_vertex_buffer",
"Returns number of requested or maximum available vertices.",
uint32_t("_num", "number of required vertices"),
bgfx_vertex_layout_t.const.p("_layout", "vertex layout")
)
uint32_t(
"get_avail_instance_data_buffer",
"Returns number of requested or maximum available instance buffer slots.",
uint32_t("_num", "number of required instances"),
MapToInt..uint16_t("_stride", "stride per instance")
)
void(
"alloc_transient_index_buffer",
"Allocates transient index buffer.",
bgfx_transient_index_buffer_t.p(
"_tib",
"##BGFXTransientIndexBuffer structure will be filled, and will be valid for the duration of frame, and can be reused for multiple draw"
),
uint32_t("_num", "number of indices to allocate"),
bool("_index32", "set to {@code true} if input indices will be 32-bit")
)
void(
"alloc_transient_vertex_buffer",
"Allocates transient vertex buffer.",
bgfx_transient_vertex_buffer_t.p(
"_tvb",
"##BGFXTransientVertexBuffer structure will be filled, and will be valid for the duration of frame, and can be reused for multiple draw"
),
uint32_t("_num", "number of vertices to allocate"),
bgfx_vertex_layout_t.const.p("_layout", "vertex layout")
)
bool(
"alloc_transient_buffers",
"Checks for required space and allocates transient vertex and index buffers. If both space requirements are satisfied function returns true.",
bgfx_transient_vertex_buffer_t.p(
"_tvb",
"##BGFXTransientVertexBuffer structure will be filled, and will be valid for the duration of frame, and can be reused for multiple draw"
),
bgfx_vertex_layout_t.const.p("_layout", "vertex layout"),
uint32_t("_numVertices", "number of vertices to allocate"),
bgfx_transient_index_buffer_t.p(
"_tib",
"##BGFXTransientIndexBuffer structure will be filled, and will be valid for the duration of frame, and can be reused for multiple draw"
),
uint32_t("_numIndices", "number of indices to allocate"),
bool("_index32", "set to {@code true} if input indices will be 32-bit")
)
void(
"alloc_instance_data_buffer",
"Allocates instance data buffer.",
bgfx_instance_data_buffer_t.p(
"_idb",
"##BGFXInstanceDataBuffer structure will be filled, and will be valid for duration of frame, and can be reused for multiple draw"
),
uint32_t("_num", "number of instances"),
MapToInt..uint16_t("_stride", "instance stride. Must be multiple of 16")
)
bgfx_indirect_buffer_handle_t(
"create_indirect_buffer",
"Creates draw indirect buffer.",
uint32_t("_num", "number of indirect calls")
)
void(
"destroy_indirect_buffer",
"Destroys draw indirect buffer.",
bgfx_indirect_buffer_handle_t("_handle", "the draw indirect buffer to destroy")
)
bgfx_shader_handle_t(
"create_shader",
"Creates shader from memory buffer.",
bgfx_memory_t.const.p("_mem", ""),
returnDoc = "shader handle"
)
uint16_t(
"get_shader_uniforms",
"""
Returns the number of uniforms and uniform handles used inside shader.
Only non-predefined uniforms are returned.
""",
bgfx_shader_handle_t("_handle", "shader handle"),
bgfx_uniform_handle_t.p("_uniforms", "{@code bgfx_uniform_handle_t} array where data will be stored"),
AutoSize("_uniforms")..uint16_t("_max", "maximum capacity of {@code _uniforms}"),
returnDoc = "number of uniforms used by shader"
)
void(
"set_shader_name",
"Sets shader debug name.",
bgfx_shader_handle_t("_handle", "shader handle"),
charUTF8.const.p("_name", "shader name"),
AutoSize("_name")..int32_t(
"_len",
"shader name length (if length is {@code INT32_MAX}, it's expected that {@code _name} is zero terminated string)"
)
)
void(
"destroy_shader",
"Destroys shader. Once a shader program is created with {@code _handle}, it is safe to destroy that shader.",
bgfx_shader_handle_t("_handle", "the shader to destroy")
)
bgfx_program_handle_t(
"create_program",
"Creates program with vertex and fragment shaders.",
bgfx_shader_handle_t("_vsh", "vertex shader"),
bgfx_shader_handle_t("_fsh", "fragment shader"),
bool("_destroyShaders", "if true, shaders will be destroyed when program is destroyed"),
returnDoc = "program handle if vertex shader output and fragment shader input are matching, otherwise returns invalid program handle."
)
bgfx_program_handle_t(
"create_compute_program",
"Creates program with compute shader.",
bgfx_shader_handle_t("_csh", "compute shader"),
bool("_destroyShaders", "if true, shader will be destroyed when program is destroyed")
)
void(
"destroy_program",
"Destroy program.",
bgfx_program_handle_t("_handle", "the program to destroy")
)
bool(
"is_texture_valid",
"Validate texture parameters.",
MapToInt..uint16_t("_depth", "depth dimension of volume texture"),
bool("_cubeMap", "indicates that texture contains cubemap"),
MapToInt..uint16_t("_numLayers", "number of layers in texture array"),
bgfx_texture_format_t("_format", "texture format", TextureFormat),
uint64_t("_flags", "texture flags", TextureFlags, LinkMode.BITFIELD),
returnDoc = "true if a texture with the same parameters can be created"
)
bool(
"is_frame_buffer_valid",
"Validate frame buffer parameters.",
MapToInt..uint8_t("_num", "number of attachments"),
bgfx_attachment_t.const.p("_attachment", "attachment texture info"),
returnDoc = "true if a frame buffer with the same parameters can be created"
)
void(
"calc_texture_size",
"Calculates amount of memory required for texture.",
bgfx_texture_info_t_p("_info", "resulting texture info structure"),
MapToInt..uint16_t("_width", "width"),
MapToInt..uint16_t("_height", "height"),
MapToInt..uint16_t("_depth", "depth dimension of volume texture"),
bool("_cubeMap", "indicates that texture contains cubemap"),
bool("_hasMips", "indicates that texture contains full mip-map chain"),
MapToInt..uint16_t("_numLayers", "number of layers in texture array"),
bgfx_texture_format_t("_format", "texture format", TextureFormat)
)
bgfx_texture_handle_t(
"create_texture",
"Creates texture from memory buffer.",
bgfx_memory_t.const.p("_mem", "DDS, KTX or PVR texture data"),
uint64_t(
"_flags",
"texture creation and sampler flags. Default texture sampling mode is linear, and wrap mode is repeat.",
"$TextureFlags $SamplerFlags", LinkMode.BITFIELD
),
MapToInt..uint8_t("_skip", "skip top level mips when parsing texture"),
nullable..bgfx_texture_info_t_p("_info", "when non-#NULL is specified it returns parsed texture information")
)
bgfx_texture_handle_t(
"create_texture_2d",
"Creates 2D texture.",
MapToInt..uint16_t("_width", "width"),
MapToInt..uint16_t("_height", "height"),
bool("_hasMips", "indicates that texture contains full mip-map chain"),
MapToInt..uint16_t("_numLayers", "number of layers in texture array. Must be 1 if caps #CAPS_TEXTURE_2D_ARRAY flag is not set."),
bgfx_texture_format_t("_format", "texture format", TextureFormat),
uint64_t(
"_flags",
"texture creation and sampler flags. Default texture sampling mode is linear, and wrap mode is repeat.",
"$TextureFlags $SamplerFlags", LinkMode.BITFIELD
),
nullable..bgfx_memory_t.const.p(
"_mem",
"""
texture data. If {@code _mem} is non-#NULL, created texture will be immutable. When {@code _numLayers} is more than 1, expected memory layout is
texture and all mips together for each array element.
"""
)
)
bgfx_texture_handle_t(
"create_texture_2d_scaled",
"Creates texture with size based on back-buffer ratio. Texture will maintain ratio if back buffer resolution changes.",
bgfx_backbuffer_ratio_t("_ratio", "frame buffer size in respect to back-buffer size", BackbufferRatio),
bool("_hasMips", "indicates that texture contains full mip-map chain"),
MapToInt..uint16_t("_numLayers", "number of layers in texture array. Must be 1 if caps #CAPS_TEXTURE_2D_ARRAY flag is not set."),
bgfx_texture_format_t("_format", "texture format", TextureFormat),
uint64_t(
"_flags",
"texture creation and sampler flags. Default texture sampling mode is linear, and wrap mode is repeat.",
"$TextureFlags $SamplerFlags", LinkMode.BITFIELD
)
)
bgfx_texture_handle_t(
"create_texture_3d",
"Creates 3D texture.",
MapToInt..uint16_t("_width", "width"),
MapToInt..uint16_t("_height", "height"),
MapToInt..uint16_t("_depth", "depth"),
bool("_hasMips", "indicates that texture contains full mip-map chain"),
bgfx_texture_format_t("_format", "texture format", TextureFormat),
uint64_t(
"_flags",
"texture creation and sampler flags. Default texture sampling mode is linear, and wrap mode is repeat.",
"$TextureFlags $SamplerFlags", LinkMode.BITFIELD
),
nullable..bgfx_memory_t.const.p("_mem", "texture data. If {@code _mem} is non-#NULL, created texture will be immutable.")
)
bgfx_texture_handle_t(
"create_texture_cube",
"Creates Cube texture.",
MapToInt..uint16_t("_size", "cube side size"),
bool("_hasMips", "indicates that texture contains full mip-map chain"),
MapToInt..uint16_t("_numLayers", "number of layers in texture array. Must be 1 if caps #CAPS_TEXTURE_CUBE_ARRAY flag is not set."),
bgfx_texture_format_t("_format", "", TextureFormat),
uint64_t(
"_flags",
"texture creation and sampler flags. Default texture sampling mode is linear, and wrap mode is repeat.",
"$TextureFlags $SamplerFlags", LinkMode.BITFIELD
),
nullable..bgfx_memory_t.const.p(
"_mem",
"""
texture data. If {@code _mem} is non-#NULL, created texture will be immutable. When {@code _numLayers} is more than 1, expected memory layout is
cubemap texture and all mips together for each array element.
"""
)
)
void(
"update_texture_2d",
"""
Updates 2D texture.
It's valid to update only mutable texture. See #create_texture_2d() for more info.
""",
bgfx_texture_handle_t("_handle", "texture handle"),
MapToInt..uint16_t("_layer", "layers in texture array"),
MapToInt..uint8_t("_mip", "mip level"),
MapToInt..uint16_t("_x", "x offset in texture"),
MapToInt..uint16_t("_y", "y offset in texture"),
MapToInt..uint16_t("_width", "width of texture block"),
MapToInt..uint16_t("_height", "height of texture block"),
bgfx_memory_t.const.p("_mem", "texture update data"),
MapToInt..uint16_t(
"_pitch",
"pitch of input image (bytes). When {@code _pitch} is set to {@code UINT16_MAX}, it will be calculated internally based on {@code _width}."
)
)
void(
"update_texture_3d",
"""
Updates 3D texture.
It's valid to update only mutable texture. See #create_texture_3d() for more info.
""",
bgfx_texture_handle_t("_handle", "texture handle"),
MapToInt..uint8_t("_mip", "mip level"),
MapToInt..uint16_t("_x", "x offset in texture"),
MapToInt..uint16_t("_y", "y offset in texture"),
MapToInt..uint16_t("_z", "z offset in texture"),
MapToInt..uint16_t("_width", "width of texture block"),
MapToInt..uint16_t("_height", "height of texture block"),
MapToInt..uint16_t("_depth", "depth of texture block"),
bgfx_memory_t.const.p("_mem", "texture update data")
)
void(
"update_texture_cube",
"""
Updates Cube texture.
It's valid to update only mutable texture. See #create_texture_cube() for more info.
""",
bgfx_texture_handle_t("_handle", "texture handle"),
MapToInt..uint16_t("_layer", "layers in texture array"),
uint8_t(
"_side",
"""
cubemap side, where 0 is +X, 1 is -X, 2 is +Y, 3 is -Y, 4 is +Z, and 5 is -Z.
${codeBlock("""
+----------+
|-z 2|
| ^ +y |
| | | Unfolded cube:
| +---->+x |
+----------+----------+----------+----------+
|+y 1|+y 4|+y 0|+y 5|
| ^ -x | ^ +z | ^ +x | ^ -z |
| | | | | | | | |
| +---->+z | +---->+x | +---->-z | +---->-x |
+----------+----------+----------+----------+
|+z 3|
| ^ -y |
| | |
| +---->+x |
+----------+""")}
""",
CubeMapSides
),
MapToInt..uint8_t("_mip", "mip level"),
MapToInt..uint16_t("_x", "x offset in texture"),
MapToInt..uint16_t("_y", "y offset in texture"),
MapToInt..uint16_t("_width", "width of texture block"),
MapToInt..uint16_t("_height", "height of texture block"),
bgfx_memory_t.const.p("_mem", "texture update data"),
MapToInt..uint16_t(
"_pitch",
"pitch of input image (bytes). When {@code _pitch} is set to {@code UINT16_MAX}, it will be calculated internally based on {@code _width}."
)
)
uint32_t(
"read_texture",
"""
Reads back texture content.
Texture must be created with #TEXTURE_READ_BACK flag. Availability depends on #CAPS_TEXTURE_READ_BACK.
""",
bgfx_texture_handle_t("_handle", "texture handle"),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT
)..Unsafe..void.p("_data", "destination buffer"),
MapToInt..uint8_t("_mip", "mip level"),
returnDoc = "frame number when the result will be available"
)
void(
"set_texture_name",
"Sets texture debug name.",
bgfx_texture_handle_t("_handle", "texture handle"),
charUTF8.const.p("_name", "texture name"),
AutoSize("_name")..int32_t(
"_len",
"texture name length (if length is {@code INT32_MAX}, it's expected that {@code _name} is zero terminated string)"
)
)
opaque_p(
"get_direct_access_ptr",
"""
Returns texture direct access pointer.
Returns pointer to texture memory. If returned pointer is #NULL direct access is not available for this texture. If pointer is {@code UINTPTR_MAX}
sentinel value it means texture is pending creation. Pointer returned can be cached and it will be valid until texture is destroyed.
${note(
"Availability depends on: #CAPS_TEXTURE_DIRECT_ACCESS. This feature is available on GPUs that have unified memory architecture (UMA) support."
)}
""",
bgfx_texture_handle_t("_handle", "")
)
void(
"destroy_texture",
"Destroys texture.",
bgfx_texture_handle_t("_handle", "texture handle")
)
bgfx_frame_buffer_handle_t(
"create_frame_buffer",
"Creates frame buffer (simple).",
MapToInt..uint16_t("_width", "texture width"),
MapToInt..uint16_t("_height", "texture height"),
bgfx_texture_format_t("_format", "texture format", TextureFormat),
uint64_t("_textureFlags", "default texture sampling mode is linear, and wrap mode is repeat", "$TextureFlags $SamplerFlags"),
returnDoc = "handle to frame buffer object"
)
bgfx_frame_buffer_handle_t(
"create_frame_buffer_scaled",
"Creates frame buffer with size based on back-buffer ratio. Frame buffer will maintain ratio if back buffer resolution changes.",
bgfx_backbuffer_ratio_t("_ratio", "frame buffer size in respect to back-buffer size", BackbufferRatio),
bgfx_texture_format_t("_format", "texture format", TextureFormat),
uint64_t("_textureFlags", "default texture sampling mode is linear, and wrap mode is repeat", "$TextureFlags $SamplerFlags"),
returnDoc = "handle to frame buffer object"
)
bgfx_frame_buffer_handle_t(
"create_frame_buffer_from_handles",
"Creates MRT frame buffer from texture handles (simple).",
AutoSize("_handles")..uint8_t("_num", "number of texture attachments"),
bgfx_texture_handle_t.const.p("_handles", "texture attachments"),
bool("_destroyTextures", "if true, textures will be destroyed when frame buffer is destroyed"),
returnDoc = "handle to frame buffer object"
)
bgfx_frame_buffer_handle_t(
"create_frame_buffer_from_attachment",
"Create MRT frame buffer from texture handles with specific layer and mip level.",
AutoSize("_attachment")..uint8_t("_num", "number of attachments"),
bgfx_attachment_t.const.p("_attachment", "attachment texture info"),
bool("_destroyTextures", "if true, textures will be destroyed when frame buffer is destroyed"),
returnDoc = "handle to frame buffer object"
)
bgfx_frame_buffer_handle_t(
"create_frame_buffer_from_nwh",
"""
Creates frame buffer for multiple window rendering.
Frame buffer cannot be used for sampling.
""",
opaque_p("_nwh", "OS' target native window handle"),
MapToInt..uint16_t("_width", "window back buffer width"),
MapToInt..uint16_t("_height", "window back buffer height"),
bgfx_texture_format_t("_format", "window back buffer color format", TextureFormat),
bgfx_texture_format_t("_depthFormat", "window back buffer depth format", TextureFormat),
returnDoc = "handle to frame buffer object"
)
void(
"set_frame_buffer_name",
"Set frame buffer debug name.",
bgfx_frame_buffer_handle_t("_handle", "frame buffer handle"),
charASCII.const.p("_name", "frame buffer name"),
AutoSize("_name")..int32_t(
"_len",
"frame buffer name length (if length is {@code INT32_MAX}, it's expected that {@code _name} is zero terminated string)"
)
)
bgfx_texture_handle_t(
"get_texture",
"Obtains texture handle of frame buffer attachment.",
bgfx_frame_buffer_handle_t("_handle", "frame buffer handle"),
MapToInt..uint8_t("_attachment", "frame buffer attachment index"),
returnDoc = "invalid texture handle if attachment index is not correct, or frame buffer is created with native window handle"
)
void(
"destroy_frame_buffer",
"Destroys frame buffer.",
bgfx_frame_buffer_handle_t("_handle", "the frame buffer to destroy")
)
bgfx_uniform_handle_t(
"create_uniform",
"""
Creates shader uniform parameter.
Uniform names are unique. It's valid to call {@code bgfx_create_uniform} multiple times with the same uniform name. The library will always return the
same handle, but the handle reference count will be incremented. This means that the same number of #destroy_uniform() must be called to properly
destroy the uniform.
Predefined uniforms (declared in {@code bgfx_shader.sh}):
${ul(
"{@code u_viewRect vec4(x, y, width, height)} - view rectangle for current view, in pixels.",
"{@code u_viewTexel vec4(1.0/width, 1.0/height, undef, undef)} - inverse width and height",
"{@code u_view mat4} - view matrix",
"{@code u_invView mat4} - inverted view matrix",
"{@code u_proj mat4} - projection matrix",
"{@code u_invProj mat4} - inverted projection matrix",
"{@code u_viewProj mat4} - concatenated view projection matrix",
"{@code u_invViewProj mat4} - concatenated inverted view projection matrix",
"{@code u_model mat4[BGFX_CONFIG_MAX_BONES]} - array of model matrices.",
"{@code u_modelView mat4} - concatenated model view matrix, only first model matrix from array is used.",
"{@code u_modelViewProj mat4} - concatenated model view projection matrix.",
"{@code u_alphaRef float} - alpha reference value for alpha test."
)}
""",
charASCII.const.p("_name", "uniform name in shader"),
bgfx_uniform_type_t("_type", "type of uniform", UniformType),
MapToInt..uint16_t("_num", "number of elements in array"),
returnDoc = "handle to uniform object"
)
void(
"get_uniform_info",
"Retrieves uniform info.",
bgfx_uniform_handle_t("_handle", "handle to uniform object"),
bgfx_uniform_info_t_p("_info", "uniform info")
)
void(
"destroy_uniform",
"Destroys shader uniform parameter.",
bgfx_uniform_handle_t("_handle", "handle to uniform object")
)
bgfx_occlusion_query_handle_t(
"create_occlusion_query",
"Creates occlusion query.",
returnDoc = "handle to occlusion query object"
)
bgfx_occlusion_query_result_t(
"get_result",
"Retrieves occlusion query result from previous frame.",
bgfx_occlusion_query_handle_t("_handle", "handle to occlusion query object"),
Check(1)..nullable..int32_t.p(
"_result",
"number of pixels that passed test. This argument can be #NULL if result of occlusion query is not needed."
),
returnDoc = "occlusion query result"
)
void(
"destroy_occlusion_query",
"Destroys occlusion query.",
bgfx_occlusion_query_handle_t("_handle", "handle to occlusion query object")
)
void(
"set_palette_color",
"Sets palette color value.",
MapToInt..uint8_t("_index", "index into palette"),
Check(4)..float.const.p("_rgba", "RGBA floating point values")
)
void(
"set_palette_color_rgba8",
"Sets palette color value.",
MapToInt..uint8_t("_index", "index into palette"),
uint32_t("_rgba", "packed 32-bit RGBA value")
)
void(
"set_view_name",
"""
Sets view name.
This is debug only feature. In graphics debugger view name will appear as:
${codeBlock("""
"nnnce <view name>"
^ ^^ ^
| |+-- eye (L/R)
| +--- compute (C)
+------ view id""")}
""",
MapToInt..bgfx_view_id_t("_id", "view id"),
charASCII.const.p("_name", "view name")
)
void(
"set_view_rect",
"Sets view rectangle. Draw primitive outside view will be clipped.",
MapToInt..bgfx_view_id_t("_id", "view id"),
MapToInt..uint16_t("_x", "position x from the left corner of the window"),
MapToInt..uint16_t("_y", "position y from the top corner of the window"),
MapToInt..uint16_t("_width", "width of view port region"),
MapToInt..uint16_t("_height", "height of view port region")
)
void(
"set_view_rect_ratio",
"Sets view rectangle. Draw primitive outside view will be clipped.",
MapToInt..bgfx_view_id_t("_id", "view id"),
MapToInt..uint16_t("_x", "position x from the left corner of the window"),
MapToInt..uint16_t("_y", "position y from the top corner of the window"),
bgfx_backbuffer_ratio_t("_ratio", "width and height will be set in respect to back-buffer size", BackbufferRatio)
)
void(
"set_view_scissor",
"""
Sets view scissor. Draw primitive outside view will be clipped. When {@code _x}, {@code _y}, {@code _width} and {@code _height} are set to 0, scissor
will be disabled.
""",
MapToInt..bgfx_view_id_t("_id", "view id"),
MapToInt..uint16_t("_x", "position x from the left corner of the window"),
MapToInt..uint16_t("_y", "position y from the top corner of the window"),
MapToInt..uint16_t("_width", "width of scissor region"),
MapToInt..uint16_t("_height", "height of scissor region")
)
void(
"set_view_clear",
"Sets view clear flags.",
MapToInt..bgfx_view_id_t("_id", "view id"),
MapToInt..uint16_t("_flags", "clear flags. Use #CLEAR_NONE to remove any clear operation.", ClearFlags, LinkMode.BITFIELD),
uint32_t("_rgba", "color clear value"),
float("_depth", "depth clear value"),
MapToInt..uint8_t("_stencil", "stencil clear value")
)
void(
"set_view_clear_mrt",
"Sets view clear flags with different clear color for each frame buffer texture. #set_palette_color() must be used to set up a clear color palette.",
MapToInt..bgfx_view_id_t("_id", "view id"),
MapToInt..uint16_t("_flags", "clear flags. Use #CLEAR_NONE to remove any clear operation.", ClearFlags, LinkMode.BITFIELD),
float("_depth", "depth clear value"),
MapToInt..uint8_t("_stencil", "stencil clear value"),
uint8_t("_0", "palette index for frame buffer attachment 0"),
uint8_t("_1", "palette index for frame buffer attachment 1"),
uint8_t("_2", "palette index for frame buffer attachment 2"),
uint8_t("_3", "palette index for frame buffer attachment 3"),
uint8_t("_4", "palette index for frame buffer attachment 4"),
uint8_t("_5", "palette index for frame buffer attachment 5"),
uint8_t("_6", "palette index for frame buffer attachment 6"),
uint8_t("_7", "palette index for frame buffer attachment 7")
)
void(
"set_view_mode",
"Sets view sorting mode.",
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_view_mode_t("_mode", "view sort mode", ViewMode)
)
void(
"set_view_frame_buffer",
"""
Sets view frame buffer.
Not persistent after #reset() call.
""",
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_frame_buffer_handle_t(
"_handle",
"frame buffer handle. Passing #INVALID_HANDLE as frame buffer handle will draw primitives from this view into default back buffer."
)
)
void(
"set_view_transform",
"Sets view's view matrix and projection matrix, all draw primitives in this view will use these two matrices.",
MapToInt..bgfx_view_id_t("_id", "view id"),
MultiType(
PointerMapping.DATA_FLOAT
)..Check(4 x 4 x 4)..nullable..void.const.p("_view", "view matrix"),
MultiType(
PointerMapping.DATA_FLOAT
)..Check(4 x 4 x 4)..nullable..void.const.p("_proj", "projection matrix")
)
void(
"set_view_order",
"Post submit view reordering.",
MapToInt..bgfx_view_id_t("_id", "view id"),
MapToInt..uint16_t("_num", "number of views to remap"),
Check("_num")..nullable..bgfx_view_id_t.const.p("_order", "view remap id table. Passing #NULL will reset view ids to default state")
)
void(
"reset_view",
"Reset all view settings to default.",
MapToInt..bgfx_view_id_t("_id", "view id")
)
bgfx_encoder_s.p(
"encoder_begin",
"Begin submitting draw calls from thread.",
bool("_forThread", "explicitly request an encoder for a worker thread"),
returnDoc = "an encoder for submitting draw calls from multiple threads"
)
void(
"encoder_end",
"End submitting draw calls from thread.",
bgfx_encoder_s.p("_encoder", "the encoder")
)
void(
"encoder_set_marker",
"Sets debug marker.",
bgfx_encoder_s.p("_this", "the encoder"),
charASCII.const.p("_marker", "debug marker")
)
void(
"encoder_set_state",
"""
Sets render states for draw primitive.
Remarks:
${ol(
"""
To set up more complex states use:
${codeBlock("""
BGFX_STATE_ALPHA_REF(_ref),
BGFX_STATE_POINT_SIZE(_size),
BGFX_STATE_BLEND_FUNC(_src, _dst),
BGFX_STATE_BLEND_FUNC_SEPARATE(_srcRGB, _dstRGB, _srcA, _dstA)
BGFX_STATE_BLEND_EQUATION(_equation)
BGFX_STATE_BLEND_EQUATION_SEPARATE(_equationRGB, _equationA)""")}
""",
"#STATE_BLEND_EQUATION_ADD is set when no other blend equation is specified."
)}
""",
bgfx_encoder_s.p("_this", "the encoder"),
uint64_t("_state", "state flags", StateFlags, LinkMode.BITFIELD),
uint32_t("_rgba", "blend factor used by #STATE_BLEND_FACTOR and #STATE_BLEND_INV_FACTOR blend modes")
)
void(
"encoder_set_condition",
"Sets condition for rendering.",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_occlusion_query_handle_t("_handle", "occlusion query handle"),
bool("_visible", "render if occlusion query is visible")
)
void(
"encoder_set_stencil",
"Sets stencil test state.",
bgfx_encoder_s.p("_this", "the encoder"),
uint32_t("_fstencil", "front stencil state", StencilFlags, LinkMode.BITFIELD),
uint32_t(
"_bstencil",
"back stencil state. If back is set to #STENCIL_NONE {@code _fstencil} is applied to both front and back facing primitives.",
StencilFlags, LinkMode.BITFIELD
)
)
uint16_t(
"encoder_set_scissor",
"Sets scissor for draw primitive. To scissor for all primitives in view see #set_view_scissor().",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint16_t("_x", "position x from the left side of the window"),
MapToInt..uint16_t("_y", "position y from the top side of the window"),
MapToInt..uint16_t("_width", "width of scissor region"),
MapToInt..uint16_t("_height", "height of scissor region"),
returnDoc = "scissor cache index"
)
void(
"encoder_set_scissor_cached",
"Sets scissor from cache for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint16_t("_cache", "index in scissor cache. Pass {@code UINT16_MAX} to have primitive use view scissor instead.")
)
uint32_t(
"encoder_set_transform",
"Sets model matrix for draw primitive. If it is not called, the model will be rendered with identity model matrix.",
bgfx_encoder_s.p("_this", "the encoder"),
MultiType(
PointerMapping.DATA_FLOAT
)..void.const.p("_mtx", "pointer to first matrix in array"),
AutoSize(4 x 4 x 4, "_mtx")..uint16_t("_num", "number of matrices in array"),
returnDoc = "index into matrix cache in case the same model matrix has to be used for other draw primitive call"
)
void(
"encoder_set_transform_cached",
"Sets model matrix from matrix cache for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
uint32_t("_cache", "index in matrix cache"),
MapToInt..uint16_t("_num", "number of matrices from cache")
)
uint32_t(
"encoder_alloc_transform",
"""
Reserves {@code _num} matrices in internal matrix cache.
Pointer returned can be modified until #frame() is called.
""",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_transform_t.p("_transform", "pointer to ##BGFXTransform structure"),
MapToInt..uint16_t("_num", "number of matrices"),
returnDoc = "index into matrix cache"
)
void(
"encoder_set_uniform",
"Sets shader uniform parameter for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_uniform_handle_t("_handle", "uniform"),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..Unsafe..void.const.p("_value", "pointer to uniform data"),
MapToInt..uint16_t("_num", "number of elements. Passing {@code UINT16_MAX} will use the {@code _num} passed on uniform creation.")
)
void(
"encoder_set_index_buffer",
"Sets index buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_index_buffer_handle_t("_handle", "index buffer"),
uint32_t("_firstIndex", "first index to render"),
uint32_t("_numIndices", "number of indices to render")
)
void(
"encoder_set_dynamic_index_buffer",
"Sets index buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_dynamic_index_buffer_handle_t("_handle", "dynamic index buffer"),
uint32_t("_firstIndex", "first index to render"),
uint32_t("_numIndices", "number of indices to render")
)
void(
"encoder_set_transient_index_buffer",
"Sets index buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_transient_index_buffer_t.const.p("_tib", "transient index buffer"),
uint32_t("_firstIndex", "first index to render"),
uint32_t("_numIndices", "number of indices to render")
)
void(
"encoder_set_vertex_buffer",
"Sets vertex buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_vertex_buffer_handle_t("_handle", "vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render")
)
void(
"encoder_set_vertex_buffer_with_layout",
"Sets vertex buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_vertex_buffer_handle_t("_handle", "vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render"),
bgfx_vertex_layout_handle_t(
"_layoutHandle",
"vertex layout for aliasing vertex buffer. If invalid handle is used, vertex layout used for creation of vertex buffer will be used."
)
)
void(
"encoder_set_dynamic_vertex_buffer",
"Sets vertex buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render")
)
void(
"encoder_set_dynamic_vertex_buffer_with_layout",
"Sets vertex buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render"),
bgfx_vertex_layout_handle_t(
"_layoutHandle",
"vertex layout for aliasing vertex buffer. If invalid handle is used, vertex layout used for creation of vertex buffer will be used."
)
)
void(
"encoder_set_transient_vertex_buffer",
"Sets vertex buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_transient_vertex_buffer_t.const.p("_tvb", "transient vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render")
)
void(
"encoder_set_transient_vertex_buffer_with_layout",
"Sets vertex buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_transient_vertex_buffer_t.const.p("_tvb", "transient vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render"),
bgfx_vertex_layout_handle_t(
"_layoutHandle",
"vertex layout for aliasing vertex buffer. If invalid handle is used, vertex layout used for creation of vertex buffer will be used."
)
)
void(
"encoder_set_vertex_count",
"""
Set number of vertices for auto generated vertices use in conjunction with {@code gl_VertexID}.
Availability depends on: #CAPS_VERTEX_ID.
""",
bgfx_encoder_s.p("_this", "the encoder"),
uint32_t("_numVertices", "number of vertices")
)
void(
"encoder_set_instance_data_buffer",
"Sets instance data buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_instance_data_buffer_t.const.p("_idb", "transient instance data buffer"),
uint32_t("_start", "first instance data"),
uint32_t("_num", "number of data instances")
)
void(
"encoder_set_instance_data_from_vertex_buffer",
"Set instance data buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_vertex_buffer_handle_t("_handle", "vertex buffer"),
uint32_t("_start", "first instance data"),
uint32_t("_num", "number of data instances")
)
void(
"encoder_set_instance_data_from_dynamic_vertex_buffer",
"Set instance data buffer for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer"),
uint32_t("_start", "first instance data"),
uint32_t("_num", "number of data instances")
)
void(
"encoder_set_instance_count",
"""
Sets number of instances for auto generated instances use in conjuction with {@code gl_InstanceID}.
Availability depends on: #CAPS_VERTEX_ID.
""",
bgfx_encoder_s.p("_this", "the encoder"),
uint32_t("_numInstances", "number of instances")
)
void(
"encoder_set_texture",
"Sets texture stage for draw primitive.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stage", "texture unit"),
bgfx_uniform_handle_t("_sampler", "program sampler"),
bgfx_texture_handle_t("_handle", "texture handle"),
uint32_t("_flags", "texture sampling mode. {@code UINT32_MAX} uses texture sampling settings from the texture.", SamplerFlags)
)
void(
"encoder_touch",
"""
Submits an empty primitive for rendering.
Uniforms and draw state will be applied but no geometry will be submitted. Useful in cases when no other draw/compute primitive is submitted to view,
but it's desired to execute clear view.
These empty draw calls will sort before ordinary draw calls.
""",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..bgfx_view_id_t("_id", "view id")
)
void(
"encoder_submit",
"Submits primitive for rendering.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_handle", "program"),
uint32_t("_depth", "depth for sorting"),
MapToInt..uint8_t("_flags", "discard or preserve states", DiscardFlags, LinkMode.BITFIELD)
)
void(
"encoder_submit_occlusion_query",
"Submits primitive with occlusion query for rendering.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_program", "program"),
bgfx_occlusion_query_handle_t("_occlusionQuery", "occlusion query"),
uint32_t("_depth", "depth for sorting"),
MapToInt..uint8_t("_flags", "discard or preserve states", DiscardFlags, LinkMode.BITFIELD)
)
void(
"encoder_submit_indirect",
"Submits primitive for rendering with index and instance data info from indirect buffer.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_handle", "program"),
bgfx_indirect_buffer_handle_t("_indirectHandle", "indirect buffer"),
MapToInt..uint16_t("_start", "first element in indirect buffer"),
MapToInt..uint16_t("_num", "number of dispatches"),
uint32_t("_depth", "depth for sorting"),
MapToInt..uint8_t("_flags", "discard or preserve states", DiscardFlags, LinkMode.BITFIELD)
)
void(
"encoder_set_compute_index_buffer",
"Sets compute index buffer.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_index_buffer_handle_t("_handle", "index buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"encoder_set_compute_vertex_buffer",
"Sets compute vertex buffer.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_vertex_buffer_handle_t("_handle", "vertex buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"encoder_set_compute_dynamic_index_buffer",
"Sets compute dynamic index buffer.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_dynamic_index_buffer_handle_t("_handle", "dynamic index buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"encoder_set_compute_dynamic_vertex_buffer",
"Sets compute dynamic vertex buffer.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"encoder_set_compute_indirect_buffer",
"Sets compute indirect buffer.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_indirect_buffer_handle_t("_handle", "indirect buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"encoder_set_image",
"Sets compute image from texture.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_stage", "texture unit"),
bgfx_texture_handle_t("_handle", "texture handle"),
MapToInt..uint8_t("_mip", "mip level"),
bgfx_access_t("_access", "texture access", Access),
bgfx_texture_format_t("_format", "texture format", TextureFormat)
)
void(
"encoder_dispatch",
"Dispatches compute.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_handle", "compute program"),
uint32_t("_numX", "number of groups X"),
uint32_t("_numY", "number of groups Y"),
uint32_t("_numZ", "number of groups Z"),
MapToInt..uint8_t("_flags", "discard or preserve states", DiscardFlags, LinkMode.BITFIELD)
)
void(
"encoder_dispatch_indirect",
"Dispatches compute indirect.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_handle", "compute program"),
bgfx_indirect_buffer_handle_t("_indirectHandle", "indirect buffer"),
MapToInt..uint16_t("_start", "first element in indirect buffer"),
MapToInt..uint16_t("_num", "number of dispatches"),
MapToInt..uint8_t("_flags", "discard or preserve states", DiscardFlags, LinkMode.BITFIELD)
)
void(
"encoder_discard",
"Discards all previously set state for draw or compute call.",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..uint8_t("_flags", "discard or preserve states", DiscardFlags, LinkMode.BITFIELD)
)
void(
"encoder_blit",
"""
Blits texture region between two textures.
Destination texture must be created with #TEXTURE_BLIT_DST flag. Availability depends on #CAPS_TEXTURE_BLIT.
""",
bgfx_encoder_s.p("_this", "the encoder"),
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_texture_handle_t("_dst", "destination texture handle"),
MapToInt..uint8_t("_dstMip", "destination texture mip level"),
MapToInt..uint16_t("_dstX", "destination texture X position"),
MapToInt..uint16_t("_dstY", "destination texture Y position"),
MapToInt..uint16_t(
"_dstZ",
"""
if texture is 2D this argument should be 0. If destination texture is cube this argument represents destination texture cube face. For 3D texture
this argument represents destination texture Z position.
"""
),
bgfx_texture_handle_t("_src", "source texture handle"),
MapToInt..uint8_t("_srcMip", "source texture mip level"),
MapToInt..uint16_t("_srcX", "source texture X position"),
MapToInt..uint16_t("_srcY", "source texture Y position"),
MapToInt..uint16_t(
"_srcZ",
"""
if texture is 2D this argument should be 0. If destination texture is cube this argument represents destination texture cube face. For 3D texture
this argument represent destination texture Z position.
"""
),
MapToInt..uint16_t("_width", "width of region"),
MapToInt..uint16_t("_height", "height of region"),
MapToInt..uint16_t("_depth", "if texture is 3D this argument represents depth of region, otherwise it's unused")
)
void(
"request_screen_shot",
"Requests screen shot.",
bgfx_frame_buffer_handle_t("_handle", "frame buffer handle"),
charASCII.const.p("_filePath", "will be passed to ##BGFXScreenShotCallback")
)
void(
"set_marker",
"Sets debug marker.",
charASCII.const.p("_marker", "debug marker")
)
void(
"set_state",
"""
Sets render states for draw primitive.
Remarks:
${ol(
"""
To set up more complex states use:
${codeBlock("""
BGFX_STATE_ALPHA_REF(_ref),
BGFX_STATE_POINT_SIZE(_size),
BGFX_STATE_BLEND_FUNC(_src, _dst),
BGFX_STATE_BLEND_FUNC_SEPARATE(_srcRGB, _dstRGB, _srcA, _dstA)
BGFX_STATE_BLEND_EQUATION(_equation)
BGFX_STATE_BLEND_EQUATION_SEPARATE(_equationRGB, _equationA)""")}
""",
"#STATE_BLEND_EQUATION_ADD is set when no other blend equation is specified."
)}
""",
uint64_t("_state", "state flags", StateFlags, LinkMode.BITFIELD),
uint32_t("_rgba", "blend factor used by #STATE_BLEND_FACTOR and #STATE_BLEND_INV_FACTOR blend modes")
)
void(
"set_condition",
"Sets condition for rendering.",
bgfx_occlusion_query_handle_t("_handle", "occlusion query handle"),
bool("_visible", "render if occlusion query is visible")
)
void(
"set_stencil",
"Sets stencil test state.",
uint32_t("_fstencil", "front stencil state", StencilFlags, LinkMode.BITFIELD),
uint32_t(
"_bstencil",
"back stencil state. If back is set to #STENCIL_NONE {@code _fstencil} is applied to both front and back facing primitives.",
StencilFlags, LinkMode.BITFIELD
)
)
uint16_t(
"set_scissor",
"Sets scissor for draw primitive. For scissor for all primitives in view see #set_view_scissor().",
MapToInt..uint16_t("_x", "position x from the left corner of the window"),
MapToInt..uint16_t("_y", "position y from the top corner of the window"),
MapToInt..uint16_t("_width", "width of scissor region"),
MapToInt..uint16_t("_height", "height of scissor region"),
returnDoc = "scissor cache index"
)
void(
"set_scissor_cached",
"Sets scissor from cache for draw primitive.",
MapToInt..uint16_t("_cache", "index in scissor cache. Passing {@code UINT16_MAX} unsets primitive scissor and primitive will use view scissor instead.")
)
uint32_t(
"set_transform",
"Sets model matrix for draw primitive. If it is not called model will be rendered with identity model matrix.",
MultiType(
PointerMapping.DATA_FLOAT
)..void.const.p("_mtx", "pointer to first matrix in array"),
AutoSize(4 x 4 x 4, "_mtx")..uint16_t("_num", "number of matrices in array"),
returnDoc = "index into matrix cache in case the same model matrix has to be used for other draw primitive call"
)
void(
"set_transform_cached",
"Sets model matrix from matrix cache for draw primitive.",
uint32_t("_cache", "index in matrix cache"),
MapToInt..uint16_t("_num", "number of matrices from cache")
)
uint32_t(
"alloc_transform",
"""
Reserves {@code _num} matrices in internal matrix cache.
Pointer returned can be modified until #frame() is called.
""",
bgfx_transform_t.p("_transform", "pointer to ##BGFXTransform structure"),
MapToInt..uint16_t("_num", "number of matrices"),
returnDoc = "index into matrix cache"
)
void(
"set_uniform",
"Sets shader uniform parameter for draw primitive.",
bgfx_uniform_handle_t("_handle", "uniform"),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..Unsafe..void.const.p("_value", "pointer to uniform data"),
MapToInt..uint16_t("_num", "number of elements. Passing {@code UINT16_MAX} will use the {@code _num} passed on uniform creation.")
)
void(
"set_index_buffer",
"Sets index buffer for draw primitive.",
bgfx_index_buffer_handle_t("_handle", "index buffer"),
uint32_t("_firstIndex", "first index to render"),
uint32_t("_numIndices", "number of indices to render")
)
void(
"set_dynamic_index_buffer",
"Sets index buffer for draw primitive.",
bgfx_dynamic_index_buffer_handle_t("_handle", "dynamic index buffer"),
uint32_t("_firstIndex", "first index to render"),
uint32_t("_numIndices", "number of indices to render")
)
void(
"set_transient_index_buffer",
"Sets index buffer for draw primitive.",
bgfx_transient_index_buffer_t.const.p("_tib", "transient index buffer"),
uint32_t("_firstIndex", "first index to render"),
uint32_t("_numIndices", "number of indices to render")
)
void(
"set_vertex_buffer",
"Sets vertex buffer for draw primitive.",
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_vertex_buffer_handle_t("_handle", "vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render")
)
void(
"set_vertex_buffer_with_layout",
"Sets vertex buffer for draw primitive.",
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_vertex_buffer_handle_t("_handle", "vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render"),
bgfx_vertex_layout_handle_t(
"_layoutHandle",
"vertex layout for aliasing vertex buffer. If invalid handle is used, vertex layout used for creation of vertex buffer will be used."
)
)
void(
"set_dynamic_vertex_buffer",
"Sets vertex buffer for draw primitive.",
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render")
)
void(
"set_dynamic_vertex_buffer_with_layout",
"Sets vertex buffer for draw primitive.",
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render"),
bgfx_vertex_layout_handle_t(
"_layoutHandle",
"vertex layout for aliasing vertex buffer. If invalid handle is used, vertex layout used for creation of vertex buffer will be used."
)
)
void(
"set_transient_vertex_buffer",
"Sets vertex buffer for draw primitive.",
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_transient_vertex_buffer_t.const.p("_tvb", "transient vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render")
)
void(
"set_transient_vertex_buffer_with_layout",
"Sets vertex buffer for draw primitive.",
MapToInt..uint8_t("_stream", "vertex stream"),
bgfx_transient_vertex_buffer_t.const.p("_tvb", "transient vertex buffer"),
uint32_t("_startVertex", "first vertex to render"),
uint32_t("_numVertices", "number of vertices to render"),
bgfx_vertex_layout_handle_t(
"_layoutHandle",
"vertex layout for aliasing vertex buffer. If invalid handle is used, vertex layout used for creation of vertex buffer will be used."
)
)
void(
"set_vertex_count",
"""
Set number of vertices for auto generated vertices use in conjunction with {@code gl_VertexID}.
Availability depends on: #CAPS_VERTEX_ID.
""",
uint32_t("_numVertices", "number of vertices")
)
void(
"set_instance_data_buffer",
"Sets instance data buffer for draw primitive.",
bgfx_instance_data_buffer_t.const.p("_idb", "transient instance data buffer"),
uint32_t("_start", "first instance data"),
uint32_t("_num", "number of data instances")
)
void(
"set_instance_data_from_vertex_buffer",
"Set instance data buffer for draw primitive.",
bgfx_vertex_buffer_handle_t("_handle", "vertex buffer"),
uint32_t("_start", "first instance data"),
uint32_t("_num", "number of data instances")
)
void(
"set_instance_data_from_dynamic_vertex_buffer",
"Set instance data buffer for draw primitive.",
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer"),
uint32_t("_start", "first instance data"),
uint32_t("_num", "number of data instances")
)
void(
"set_instance_count",
"""
Sets number of instances for auto generated instances use in conjunction with {@code gl_InstanceID}.
Availability depends on: #CAPS_VERTEX_ID.
""",
uint32_t("_numInstances", "number of instances")
)
void(
"set_texture",
"Sets texture stage for draw primitive.",
MapToInt..uint8_t("_stage", "texture unit"),
bgfx_uniform_handle_t("_sampler", "program sampler"),
bgfx_texture_handle_t("_handle", "texture handle"),
uint32_t("_flags", "texture sampling mode. {@code UINT32_MAX} uses texture sampling settings from the texture.", SamplerFlags)
)
void(
"touch",
"""
Submits an empty primitive for rendering. Uniforms and draw state will be applied but no geometry will be submitted.
These empty draw calls will sort before ordinary draw calls.
""",
MapToInt..bgfx_view_id_t("_id", "view id")
)
void(
"submit",
"Submits primitive for rendering.",
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_program", "program"),
uint32_t("_depth", "depth for sorting"),
MapToInt..uint8_t("_flags", "which states to discard for next draw", DiscardFlags, LinkMode.BITFIELD)
)
void(
"submit_occlusion_query",
"Submits primitive with occlusion query for rendering.",
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_program", "program"),
bgfx_occlusion_query_handle_t("_occlusionQuery", "occlusion query"),
uint32_t("_depth", "depth for sorting"),
MapToInt..uint8_t("_flags", "which states to discard for next draw", DiscardFlags, LinkMode.BITFIELD)
)
void(
"submit_indirect",
"Submits primitive for rendering with index and instance data info from indirect buffer.",
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_program", "program"),
bgfx_indirect_buffer_handle_t("_indirectHandle", "indirect buffer"),
MapToInt..uint16_t("_start", "first element in indirect buffer"),
MapToInt..uint16_t("_num", "number of dispatches"),
uint32_t("_depth", "depth for sorting"),
MapToInt..uint8_t("_flags", "which states to discard for next draw", DiscardFlags, LinkMode.BITFIELD)
)
void(
"set_compute_index_buffer",
"Sets compute index buffer.",
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_index_buffer_handle_t("_handle", "index buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"set_compute_vertex_buffer",
"Sets compute vertex buffer.",
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_vertex_buffer_handle_t("_handle", "vertex buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"set_compute_dynamic_index_buffer",
"Sets compute dynamic index buffer.",
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_dynamic_index_buffer_handle_t("_handle", "dynamic index buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"set_compute_dynamic_vertex_buffer",
"Sets compute dynamic vertex buffer.",
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_dynamic_vertex_buffer_handle_t("_handle", "dynamic vertex buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"set_compute_indirect_buffer",
"Sets compute indirect buffer.",
MapToInt..uint8_t("_stage", "compute stage"),
bgfx_indirect_buffer_handle_t("_handle", "indirect buffer handle"),
bgfx_access_t("_access", "buffer access", Access)
)
void(
"set_image",
"Sets compute image from texture.",
MapToInt..uint8_t("_stage", "texture unit"),
bgfx_texture_handle_t("_handle", "texture handle"),
MapToInt..uint8_t("_mip", "mip level"),
bgfx_access_t("_access", "texture access", Access),
bgfx_texture_format_t("_format", "texture format", TextureFormat)
)
void(
"dispatch",
"Dispatches compute.",
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_program", "compute program"),
uint32_t("_numX", "number of groups X"),
uint32_t("_numY", "number of groups Y"),
uint32_t("_numZ", "number of groups Z"),
MapToInt..uint8_t("_flags", "discard or preserve states", DiscardFlags, LinkMode.BITFIELD)
)
void(
"dispatch_indirect",
"Dispatches compute indirect.",
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_program_handle_t("_program", "compute program"),
bgfx_indirect_buffer_handle_t("_indirectHandle", "indirect buffer"),
MapToInt..uint16_t("_start", "first element in indirect buffer"),
MapToInt..uint16_t("_num", "number of dispatches"),
MapToInt..uint8_t("_flags", "discard or preserve states", DiscardFlags, LinkMode.BITFIELD)
)
void(
"discard",
"Discards all previously set state for draw or compute call.",
MapToInt..uint8_t("_flags", "draw/compute states to discard", DiscardFlags, LinkMode.BITFIELD)
)
void(
"blit",
"""
Blits texture region between two textures.
Destination texture must be created with #TEXTURE_BLIT_DST flag. Availability depends on #CAPS_TEXTURE_BLIT.
""",
MapToInt..bgfx_view_id_t("_id", "view id"),
bgfx_texture_handle_t("_dst", "destination texture handle"),
MapToInt..uint8_t("_dstMip", "destination texture mip level"),
MapToInt..uint16_t("_dstX", "destination texture X position"),
MapToInt..uint16_t("_dstY", "destination texture Y position"),
MapToInt..uint16_t(
"_dstZ",
"""
if texture is 2D this argument should be 0. If destination texture is cube this argument represents destination texture cube face. For 3D texture
this argument represents destination texture Z position.
"""
),
bgfx_texture_handle_t("_src", "source texture handle"),
MapToInt..uint8_t("_srcMip", "source texture mip level"),
MapToInt..uint16_t("_srcX", "source texture X position"),
MapToInt..uint16_t("_srcY", "source texture Y position"),
MapToInt..uint16_t(
"_srcZ",
"""
if texture is 2D this argument should be 0. If destination texture is cube this argument represents destination texture cube face. For 3D texture
this argument represents destination texture Z position.
"""
),
MapToInt..uint16_t("_width", "width of region"),
MapToInt..uint16_t("_height", "height of region"),
MapToInt..uint16_t("_depth", "if texture is 3D this argument represents depth of region, otherwise it's unused")
)
macro(expression = "(_ref << BGFX_STATE_ALPHA_REF_SHIFT) & BGFX_STATE_ALPHA_REF_MASK")..uint64_t(
"BGFX_STATE_ALPHA_REF", "",
uint64_t("_ref", ""),
noPrefix = true
)
macro(expression = "(_size << BGFX_STATE_POINT_SIZE_SHIFT) & BGFX_STATE_POINT_SIZE_MASK")..uint64_t(
"BGFX_STATE_POINT_SIZE", "",
uint64_t("_size", ""),
noPrefix = true
)
macro(expression = "((_srcRGB | (_dstRGB << 4))) | ((_srcA | (_dstA << 4)) << 8)")..uint64_t(
"BGFX_STATE_BLEND_FUNC_SEPARATE", "",
uint64_t("_srcRGB", ""),
uint64_t("_dstRGB", ""),
uint64_t("_srcA", ""),
uint64_t("_dstA", ""),
noPrefix = true
)
macro(expression = "_rgb | (_a << 3)")..uint64_t(
"BGFX_STATE_BLEND_EQUATION_SEPARATE", "",
uint64_t("_rgb", ""),
uint64_t("_a", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_FUNC_SEPARATE(_src, _dst, _src, _dst)")..uint64_t(
"BGFX_STATE_BLEND_FUNC", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_EQUATION_SEPARATE(_equation, _equation)")..uint64_t(
"BGFX_STATE_BLEND_EQUATION", "",
uint64_t("_equation", ""),
noPrefix = true
)
LongConstant(
"Blend state macros",
"STATE_BLEND_ADD".."BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)",
"STATE_BLEND_ALPHA".."BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)",
"STATE_BLEND_DARKEN".."BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE) | BGFX_STATE_BLEND_EQUATION(BGFX_STATE_BLEND_EQUATION_MIN)",
"STATE_BLEND_LIGHTEN".."BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE) | BGFX_STATE_BLEND_EQUATION(BGFX_STATE_BLEND_EQUATION_MAX)",
"STATE_BLEND_MULTIPLY".."BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_DST_COLOR, BGFX_STATE_BLEND_ZERO)",
"STATE_BLEND_NORMAL".."BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_ALPHA)",
"STATE_BLEND_SCREEN".."BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_COLOR)",
"STATE_BLEND_LINEAR_BURN".."BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_DST_COLOR, BGFX_STATE_BLEND_INV_DST_COLOR) | BGFX_STATE_BLEND_EQUATION(BGFX_STATE_BLEND_EQUATION_SUB)"
)
macro(expression = "(_src >> BGFX_STATE_BLEND_SHIFT) | ((_dst >> BGFX_STATE_BLEND_SHIFT) << 4)")..uint64_t(
"BGFX_STATE_BLEND_FUNC_RT_x", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst) | ((_equation >> BGFX_STATE_BLEND_EQUATION_SHIFT) << 8)")..uint64_t(
"BGFX_STATE_BLEND_FUNC_RT_xE", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
uint64_t("_equation", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst) << 0")..uint64_t(
"BGFX_STATE_BLEND_FUNC_RT_1", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst) << 11")..uint64_t(
"BGFX_STATE_BLEND_FUNC_RT_2", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst) << 22")..uint64_t(
"BGFX_STATE_BLEND_FUNC_RT_3", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_FUNC_RT_xE(_src, _dst, _equation) << 0")..uint64_t(
"BGFX_STATE_BLEND_FUNC_RT_1E", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
uint64_t("_equation", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_FUNC_RT_xE(_src, _dst, _equation) << 11")..uint64_t(
"BGFX_STATE_BLEND_FUNC_RT_2E", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
uint64_t("_equation", ""),
noPrefix = true
)
macro(expression = "BGFX_STATE_BLEND_FUNC_RT_xE(_src, _dst, _equation) << 22")..uint64_t(
"BGFX_STATE_BLEND_FUNC_RT_3E", "",
uint64_t("_src", ""),
uint64_t("_dst", ""),
uint64_t("_equation", ""),
noPrefix = true
)
macro(expression = "(_ref << BGFX_STENCIL_FUNC_REF_SHIFT) & BGFX_STENCIL_FUNC_REF_MASK")..uint32_t(
"BGFX_STENCIL_FUNC_REF", "",
uint32_t("_ref", ""),
noPrefix = true
)
macro(expression = "(_mask << BGFX_STENCIL_FUNC_RMASK_SHIFT) & BGFX_STENCIL_FUNC_RMASK_MASK")..uint32_t(
"BGFX_STENCIL_FUNC_RMASK", "",
uint32_t("_mask", ""),
noPrefix = true
)
macro(expression = "(_index << BGFX_SAMPLER_BORDER_COLOR_SHIFT) & BGFX_SAMPLER_BORDER_COLOR_MASK")..uint32_t(
"BGFX_SAMPLER_BORDER_COLOR", "",
uint32_t("_index", ""),
noPrefix = true
)
macro(expression = "Short.toUnsignedInt(h) != 0xFFFF")..bool(
"BGFX_HANDLE_IS_VALID", "",
uint16_t("h", ""),
noPrefix = true
)
} | bsd-3-clause | 4c77133f82a8f5547409dec9bf4f4a15 | 35.418707 | 177 | 0.600083 | 3.84202 | false | false | false | false |
phylame/qaf | qaf-ixin/src/main/kotlin/qaf/ixin/Actions.kt | 1 | 5296 | /*
* Copyright 2015-2016 Peng Wan <[email protected]>
*
* This file is part of IxIn.
*
* 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 qaf.ixin
import jclp.util.Localizable
import qaf.core.App
import java.awt.event.ActionEvent
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.*
import javax.swing.AbstractAction
import javax.swing.Action
import javax.swing.KeyStroke
@Suppress("unchecked_cast")
operator fun <T : Any> Action.get(name: String): T? = getValue(name) as? T
operator fun <T : Any> Action.set(name: String, value: T?) {
putValue(name, value)
}
var Action.isSelected: Boolean get() = getValue(Action.SELECTED_KEY) == true
set(value) {
putValue(Action.SELECTED_KEY, value)
}
abstract class IAction(id: String,
translator: Localizable = App,
resource: Resource = Ixin.delegate.resource) : AbstractAction() {
companion object {
const val SELECTED_ICON_KEY = "IxinSelectedIcon"
const val SCOPE_KEY = "IxinScopeKey"
var scopeSuffix = ".scope"
var normalIconSuffix = ".icon"
var selectedIconSuffix = "-selected"
var showyIconSuffix = "-showy"
var shortcutKeySuffix = ".shortcut"
var tipTextSuffix = ".tip"
var detailsTextSuffix = ".details"
var iconPrefix = "actions/"
var iconSuffix = ".png"
}
init {
putValue(Action.ACTION_COMMAND_KEY, id)
// name and mnemonic
var text = translator.optTr(id, "")
if (text.isNotEmpty()) {
val result = Ixin.mnemonicOf(text)
putValue(Action.NAME, result.name)
if (result.isEnable) {
putValue(Action.MNEMONIC_KEY, result.mnemonic)
putValue(Action.DISPLAYED_MNEMONIC_INDEX_KEY, result.index)
}
}
// scope
text = translator.optTr(id + scopeSuffix, "")
if (text.isNotEmpty()) {
putValue(SCOPE_KEY, text)
}
// icons
val path = translator.optTr(id + normalIconSuffix, "") ?: iconPrefix + id + iconSuffix
putValue(Action.SMALL_ICON, resource.iconFor(path))
putValue(Action.LARGE_ICON_KEY, resource.iconFor(path, showyIconSuffix))
putValue(SELECTED_ICON_KEY, resource.iconFor(path, selectedIconSuffix))
// menu accelerator
text = translator.optTr(id + shortcutKeySuffix, "")
if (text.isNotEmpty()) {
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(text))
}
// tip
text = translator.optTr(id + tipTextSuffix, "")
if (text.isNotEmpty()) {
putValue(Action.SHORT_DESCRIPTION, text)
}
// details
text = translator.optTr(id + detailsTextSuffix, "")
if (text.isNotEmpty()) {
putValue(Action.LONG_DESCRIPTION, text)
}
}
}
class IgnoredAction(id: String,
translator: Localizable = App,
resource: Resource = Ixin.delegate.resource) : IAction(id, translator, resource) {
override fun actionPerformed(e: ActionEvent) {
// do nothing
}
}
interface CommandListener {
fun performed(command: String)
}
class DispatcherAction(id: String,
val listener: CommandListener,
translator: Localizable = App,
resource: Resource = Ixin.delegate.resource) : IAction(id, translator, resource) {
override fun actionPerformed(e: ActionEvent) {
listener.performed(e.actionCommand)
}
}
annotation class Command(val name: String = "")
/**
* Dispatches command to the proxy object.
*/
open class CommandDispatcher(proxies: Array<out Any>) : CommandListener {
private val invocations = HashMap<String, Invocation>()
init {
for (proxy in proxies) {
addProxy(proxy)
}
}
fun addProxy(proxy: Any) {
proxy.javaClass.methods.filter {
Modifier.isPublic(it.modifiers)
&& !Modifier.isStatic(it.modifiers)
&& !Modifier.isAbstract(it.modifiers)
&& it.parameterTypes.isEmpty()
}.forEach {
val command = it.getAnnotation(Command::class.java)
if (command != null) {
invocations.put(if (command.name.isNotEmpty()) command.name else it.name, Invocation(proxy, it))
}
}
}
override final fun performed(command: String) {
invocations[command]?.invoke() ?: throw RuntimeException("No such method of proxy for command: $command")
}
data class Invocation(val proxy: Any, val method: Method) {
fun invoke() {
method.invoke(proxy)
}
}
}
| apache-2.0 | e97e0aede7125e72db0dded122bc5c9b | 30.712575 | 113 | 0.618391 | 4.226656 | false | false | false | false |
paplorinc/intellij-community | java/java-impl/src/com/intellij/codeInsight/hints/JavaHintUtils.kt | 3 | 13067 | // 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.codeInsight.hints
import com.intellij.codeInsight.completion.CompletionMemory
import com.intellij.codeInsight.completion.JavaMethodCallElement
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.*
import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil
import com.intellij.psi.impl.source.tree.java.PsiEmptyExpressionImpl
import com.intellij.psi.impl.source.tree.java.PsiMethodCallExpressionImpl
import com.intellij.psi.impl.source.tree.java.PsiNewExpressionImpl
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.util.IncorrectOperationException
object JavaInlayHintsProvider {
fun hints(callExpression: PsiCall): Set<InlayInfo> {
if (JavaMethodCallElement.isCompletionMode(callExpression)) {
val argumentList = callExpression.argumentList?:return emptySet()
val text = argumentList.text
if (text == null || !text.startsWith('(') || !text.endsWith(')')) return emptySet()
val method = CompletionMemory.getChosenMethod(callExpression)?:return emptySet()
val params = method.parameterList.parameters
val arguments = argumentList.expressions
val limit = JavaMethodCallElement.getCompletionHintsLimit()
val trailingOffset = argumentList.textRange.endOffset - 1
val infos = ArrayList<InlayInfo>()
var lastIndex = 0
(if (arguments.isEmpty()) listOf(trailingOffset) else arguments.map { inlayOffset(it) }).forEachIndexed { i, offset ->
if (i < params.size) {
params[i].name?.let {
infos.add(InlayInfo(it, offset, false, params.size == 1, false))
}
lastIndex = i
}
}
if (Registry.`is`("editor.completion.hints.virtual.comma")) {
for (i in lastIndex + 1 until minOf(params.size, limit)) {
params[i].name?.let {
infos.add(createHintWithComma(it, trailingOffset))
}
lastIndex = i
}
}
if (method.isVarArgs && (arguments.isEmpty() && params.size == 2 || !arguments.isEmpty() && arguments.size == params.size - 1)) {
params[params.size - 1].name?.let {
infos.add(createHintWithComma(it, trailingOffset))
}
}
else if (Registry.`is`("editor.completion.hints.virtual.comma") && lastIndex < (params.size - 1) ||
limit == 1 && arguments.isEmpty() && params.size > 1 ||
limit <= arguments.size && arguments.size < params.size) {
infos.add(InlayInfo("...more", trailingOffset, false, false, true))
}
return infos.toSet()
}
if (!EditorSettingsExternalizable.getInstance().isShowParameterNameHints) return emptySet()
val resolveResult = callExpression.resolveMethodGenerics()
val hints = methodHints(callExpression, resolveResult)
if (hints.isNotEmpty()) return hints
return when (callExpression) {
is PsiMethodCallExpressionImpl -> mergedHints(callExpression, callExpression.methodExpression.multiResolve(false))
is PsiNewExpressionImpl -> mergedHints(callExpression, callExpression.constructorFakeReference.multiResolve(false))
else -> emptySet()
}
}
private fun createHintWithComma(parameterName: String, offset: Int): InlayInfo {
return InlayInfo(",$parameterName", offset, false, false, true,
HintWidthAdjustment(", ", parameterName, 1))
}
private fun mergedHints(callExpression: PsiCallExpression,
results: Array<out ResolveResult>): Set<InlayInfo> {
val resultSet = results
.filter { it.element != null }
.map { methodHints(callExpression, it) }
if (resultSet.isEmpty()) return emptySet()
if (resultSet.size == 1) {
return resultSet.first()
}
val chosenMethod: PsiMethod? = CompletionMemory.getChosenMethod(callExpression)
if (chosenMethod != null) {
val callInfo = callInfo(callExpression, chosenMethod)
return hintSet(callInfo, PsiSubstitutor.EMPTY)
}
//we can show hints for same named parameters of overloaded methods, even if don't know exact method
return resultSet.reduce { left, right -> left.intersect(right) }
.map { InlayInfo(it.text, it.offset, isShowOnlyIfExistedBefore = true) }
.toSet()
}
private fun methodHints(callExpression: PsiCall, resolveResult: ResolveResult): Set<InlayInfo> {
val element = resolveResult.element
val substitutor = (resolveResult as? JavaResolveResult)?.substitutor ?: PsiSubstitutor.EMPTY
if (element is PsiMethod && isMethodToShow(element, callExpression)) {
val info = callInfo(callExpression, element)
if (isCallInfoToShow(info)) {
return hintSet(info, substitutor)
}
}
return emptySet()
}
private fun isCallInfoToShow(info: CallInfo): Boolean {
val hintsProvider = JavaInlayParameterHintsProvider.getInstance()
if (hintsProvider.ignoreOneCharOneDigitHints.get() && info.allParamsSequential()) {
return false
}
return true
}
private fun String.decomposeOrderedParams(): Pair<String, Int>? {
val firstDigit = indexOfFirst { it.isDigit() }
if (firstDigit < 0) return null
val prefix = substring(0, firstDigit)
try {
val number = substring(firstDigit, length).toInt()
return prefix to number
}
catch (e: NumberFormatException) {
return null
}
}
private fun CallInfo.allParamsSequential(): Boolean {
val paramNames = regularArgs
.map { it.parameter.name?.decomposeOrderedParams() }
.filterNotNull()
if (paramNames.size > 1 && paramNames.size == regularArgs.size) {
val prefixes = paramNames.map { it.first }
if (prefixes.toSet().size != 1) return false
val numbers = paramNames.map { it.second }
val first = numbers.first()
if (first == 0 || first == 1) {
return numbers.areSequential()
}
}
return false
}
private fun hintSet(info: CallInfo, substitutor: PsiSubstitutor): Set<InlayInfo> {
val resultSet = mutableSetOf<InlayInfo>()
val varargInlay = info.varargsInlay(substitutor)
if (varargInlay != null) {
resultSet.add(varargInlay)
}
if (isShowForParamsWithSameType()) {
resultSet.addAll(info.sameTypeInlays())
}
resultSet.addAll(info.unclearInlays(substitutor))
return resultSet
}
private fun isShowForParamsWithSameType() = JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.get()
private fun isMethodToShow(method: PsiMethod, callExpression: PsiCall): Boolean {
val params = method.parameterList.parameters
if (params.isEmpty()) return false
if (params.size == 1) {
val hintsProvider = JavaInlayParameterHintsProvider.getInstance()
if (hintsProvider.isDoNotShowForBuilderLikeMethods.get()
&& isBuilderLike(callExpression, method)) {
return false
}
if (hintsProvider.isDoNotShowIfMethodNameContainsParameterName.get()
&& isParamNameContainedInMethodName(params[0], method)) {
return false
}
}
return true
}
private fun isBuilderLike(expression: PsiCall, method: PsiMethod): Boolean {
if (expression is PsiNewExpression) return false
val returnType = TypeConversionUtil.erasure(method.returnType) ?: return false
val calledMethodClassFqn = method.containingClass?.qualifiedName ?: return false
return returnType.equalsToText(calledMethodClassFqn)
}
private fun isParamNameContainedInMethodName(parameter: PsiParameter, method: PsiMethod): Boolean {
val parameterName = parameter.name ?: return false
if (parameterName.length > 1) {
return method.name.contains(parameterName, ignoreCase = true)
}
return false
}
private fun callInfo(callExpression: PsiCall, method: PsiMethod): CallInfo {
val params = method.parameterList.parameters
val hasVarArg = params.lastOrNull()?.isVarArgs ?: false
val regularParamsCount = if (hasVarArg) params.size - 1 else params.size
val arguments = callExpression.argumentList?.expressions ?: emptyArray()
val regularArgInfos = params
.take(regularParamsCount)
.zip(arguments)
.map { CallArgumentInfo(it.first, it.second) }
val varargParam = if (hasVarArg) params.last() else null
val varargExpressions = arguments.drop(regularParamsCount)
return CallInfo(regularArgInfos, varargParam, varargExpressions)
}
}
private fun List<Int>.areSequential(): Boolean {
if (size == 0) throw IncorrectOperationException("List is empty")
val ordered = (first()..first() + size - 1).toList()
if (ordered.size == size) {
return zip(ordered).all { it.first == it.second }
}
return false
}
private fun inlayInfo(info: CallArgumentInfo, showOnlyIfExistedBefore: Boolean = false): InlayInfo? {
return inlayInfo(info.argument, info.parameter, showOnlyIfExistedBefore)
}
private fun inlayInfo(callArgument: PsiExpression, methodParam: PsiParameter, showOnlyIfExistedBefore: Boolean = false): InlayInfo? {
val paramName = methodParam.name ?: return null
val paramToShow = (if (methodParam.type is PsiEllipsisType) "..." else "") + paramName
val offset = inlayOffset(callArgument)
return InlayInfo(paramToShow, offset, showOnlyIfExistedBefore)
}
fun inlayOffset(callArgument: PsiExpression): Int = inlayOffset(callArgument, false)
fun inlayOffset(callArgument: PsiExpression, atEnd: Boolean): Int {
if (callArgument.textRange.isEmpty) {
val next = callArgument.nextSibling as? PsiWhiteSpace
if (next != null) return next.textRange.endOffset
}
return if (atEnd) callArgument.textRange.endOffset else callArgument.textRange.startOffset
}
private fun shouldShowHintsForExpression(callArgument: PsiElement): Boolean {
if (JavaInlayParameterHintsProvider.getInstance().isShowHintWhenExpressionTypeIsClear.get()) return true
return when (callArgument) {
is PsiLiteralExpression -> true
is PsiThisExpression -> true
is PsiBinaryExpression -> true
is PsiPolyadicExpression -> true
is PsiPrefixExpression -> {
val tokenType = callArgument.operationTokenType
val isLiteral = callArgument.operand is PsiLiteralExpression
isLiteral && (JavaTokenType.MINUS == tokenType || JavaTokenType.PLUS == tokenType)
}
else -> false
}
}
private class CallInfo(val regularArgs: List<CallArgumentInfo>, val varArg: PsiParameter?, val varArgExpressions: List<PsiExpression>) {
fun unclearInlays(substitutor: PsiSubstitutor): List<InlayInfo> {
val inlays = mutableListOf<InlayInfo>()
for (callInfo in regularArgs) {
val inlay = when {
isErroneousArg(callInfo) -> null
shouldShowHintsForExpression(callInfo.argument) -> inlayInfo(callInfo)
!callInfo.isAssignable(substitutor) -> inlayInfo(callInfo, showOnlyIfExistedBefore = true)
else -> null
}
inlay?.let { inlays.add(inlay) }
}
return inlays
}
fun sameTypeInlays(): List<InlayInfo> {
val all = regularArgs.map { it.parameter.typeText() }
val duplicated = all.toMutableList()
all.distinct().forEach {
duplicated.remove(it)
}
return regularArgs
.filterNot { isErroneousArg(it) }
.filter { duplicated.contains(it.parameter.typeText()) && it.argument.text != it.parameter.name }
.mapNotNull { inlayInfo(it) }
}
fun isErroneousArg(arg : CallArgumentInfo): Boolean {
return arg.argument is PsiEmptyExpressionImpl || arg.argument.prevSibling is PsiEmptyExpressionImpl
}
fun varargsInlay(substitutor: PsiSubstitutor): InlayInfo? {
if (varArg == null) return null
var hasUnassignable = false
for (expr in varArgExpressions) {
if (shouldShowHintsForExpression(expr)) {
return inlayInfo(varArgExpressions.first(), varArg)
}
hasUnassignable = hasUnassignable || !varArg.isAssignable(expr, substitutor)
}
return if (hasUnassignable) inlayInfo(varArgExpressions.first(), varArg, showOnlyIfExistedBefore = true) else null
}
}
private class CallArgumentInfo(val parameter: PsiParameter, val argument: PsiExpression) {
fun isAssignable(substitutor: PsiSubstitutor): Boolean {
return parameter.isAssignable(argument, substitutor)
}
}
private fun PsiParameter.isAssignable(argument: PsiExpression, substitutor: PsiSubstitutor = PsiSubstitutor.EMPTY): Boolean {
val substitutedType = substitutor.substitute(type) ?: return false
if (PsiPolyExpressionUtil.isPolyExpression(argument)) return true
return argument.type?.isAssignableTo(substitutedType) ?: false
}
private fun PsiType.isAssignableTo(parameterType: PsiType): Boolean {
return TypeConversionUtil.isAssignable(parameterType, this)
}
private fun PsiParameter.typeText() = type.canonicalText | apache-2.0 | 4933cd5e7994301c6ec00c243eddead8 | 35.502793 | 140 | 0.706742 | 4.610797 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/liteloader/version/LiteLoaderVersion.kt | 1 | 1186 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.liteloader.version
import com.demonwav.mcdev.util.fromJson
import com.demonwav.mcdev.util.sortVersions
import com.google.gson.Gson
import java.io.IOException
import java.net.URL
class LiteLoaderVersion private constructor(private var map: Map<*, *>) {
val sortedMcVersions: List<String> by lazy {
val mcVersion = map["versions"] as Map<*, *>
@Suppress("UNCHECKED_CAST")
val keys = mcVersion.keys as Collection<String>
return@lazy sortVersions(keys)
}
companion object {
fun downloadData(): LiteLoaderVersion? {
try {
val text = URL("http://dl.liteloader.com/versions/versions.json").readText()
val map = Gson().fromJson<Map<*, *>>(text)
val liteLoaderVersion = LiteLoaderVersion(map)
liteLoaderVersion.sortedMcVersions
return liteLoaderVersion
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
}
}
| mit | ce2dbf56462a17610830318e7b356239 | 26.581395 | 92 | 0.620573 | 4.312727 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinConstantConditionsInspection.kt | 2 | 30459 | // 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.inspections.dfa
import com.intellij.codeInsight.PsiEquivalenceUtil
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.dataFlow.interpreter.RunnerResult
import com.intellij.codeInspection.dataFlow.interpreter.StandardDataFlowInterpreter
import com.intellij.codeInspection.dataFlow.jvm.JvmDfaMemoryStateImpl
import com.intellij.codeInspection.dataFlow.lang.DfaAnchor
import com.intellij.codeInspection.dataFlow.lang.DfaListener
import com.intellij.codeInspection.dataFlow.lang.UnsatisfiedConditionProblem
import com.intellij.codeInspection.dataFlow.lang.ir.DataFlowIRProvider
import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState
import com.intellij.codeInspection.dataFlow.types.DfType
import com.intellij.codeInspection.dataFlow.types.DfTypes
import com.intellij.codeInspection.dataFlow.value.DfaValue
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.siblings
import com.intellij.util.ThreeState
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.*
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isConstant
import org.jetbrains.kotlin.idea.intentions.negate
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isNull
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isNullableNothing
class KotlinConstantConditionsInspection : AbstractKotlinInspection() {
private enum class ConstantValue {
TRUE, FALSE, NULL, ZERO, UNKNOWN
}
private class KotlinDfaListener : DfaListener {
val constantConditions = hashMapOf<KotlinAnchor, ConstantValue>()
val problems = hashMapOf<KotlinProblem, ThreeState>()
override fun beforePush(args: Array<out DfaValue>, value: DfaValue, anchor: DfaAnchor, state: DfaMemoryState) {
if (anchor is KotlinAnchor) {
recordExpressionValue(anchor, state, value)
}
}
override fun onCondition(problem: UnsatisfiedConditionProblem, value: DfaValue, failed: ThreeState, state: DfaMemoryState) {
if (problem is KotlinProblem) {
problems.merge(problem, failed, ThreeState::merge)
}
}
private fun recordExpressionValue(anchor: KotlinAnchor, state: DfaMemoryState, value: DfaValue) {
val oldVal = constantConditions[anchor]
if (oldVal == ConstantValue.UNKNOWN) return
var newVal = when (val dfType = state.getDfType(value)) {
DfTypes.TRUE -> ConstantValue.TRUE
DfTypes.FALSE -> ConstantValue.FALSE
DfTypes.NULL -> ConstantValue.NULL
else -> {
val constVal: Number? = dfType.getConstantOfType(Number::class.java)
if (constVal != null && (constVal == 0 || constVal == 0L)) ConstantValue.ZERO
else ConstantValue.UNKNOWN
}
}
if (oldVal != null && oldVal != newVal) {
newVal = ConstantValue.UNKNOWN
}
constantConditions[anchor] = newVal
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
// Non-JVM is not supported now
if (holder.file.module?.platform?.isJvm() != true) return PsiElementVisitor.EMPTY_VISITOR
return object : KtVisitorVoid() {
override fun visitProperty(property: KtProperty) {
if (shouldAnalyzeProperty(property)) {
val initializer = property.delegateExpressionOrInitializer ?: return
analyze(initializer)
}
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
if (shouldAnalyzeProperty(accessor.property)) {
val bodyExpression = accessor.bodyExpression ?: accessor.bodyBlockExpression ?: return
analyze(bodyExpression)
}
}
override fun visitParameter(parameter: KtParameter) {
analyze(parameter.defaultValue ?: return)
}
private fun shouldAnalyzeProperty(property: KtProperty) =
property.isTopLevel || property.parent is KtClassBody
override fun visitClassInitializer(initializer: KtClassInitializer) {
analyze(initializer.body ?: return)
}
override fun visitNamedFunction(function: KtNamedFunction) {
val body = function.bodyExpression ?: function.bodyBlockExpression ?: return
analyze(body)
}
private fun analyze(body: KtExpression) {
val factory = DfaValueFactory(holder.project)
processDataflowAnalysis(factory, body, holder, listOf(JvmDfaMemoryStateImpl(factory)))
}
}
}
private fun processDataflowAnalysis(
factory: DfaValueFactory,
body: KtExpression,
holder: ProblemsHolder,
states: Collection<DfaMemoryState>
) {
val flow = DataFlowIRProvider.forElement(body, factory) ?: return
val listener = KotlinDfaListener()
val interpreter = StandardDataFlowInterpreter(flow, listener)
if (interpreter.interpret(states.map { s -> DfaInstructionState(flow.getInstruction(0), s) }) != RunnerResult.OK) return
reportProblems(listener, holder)
for ((closure, closureStates) in interpreter.closures.entrySet()) {
if (closure is KtExpression) {
processDataflowAnalysis(factory, closure, holder, closureStates)
}
}
}
private fun reportProblems(
listener: KotlinDfaListener,
holder: ProblemsHolder
) {
listener.constantConditions.forEach { (anchor, cv) ->
if (cv != ConstantValue.UNKNOWN) {
when (anchor) {
is KotlinExpressionAnchor -> {
val expr = anchor.expression
if (!shouldSuppress(cv, expr)) {
val key = when (cv) {
ConstantValue.TRUE ->
if (shouldReportAsValue(expr))
"inspection.message.value.always.true"
else if (logicalChain(expr))
"inspection.message.condition.always.true.when.reached"
else
"inspection.message.condition.always.true"
ConstantValue.FALSE ->
if (shouldReportAsValue(expr))
"inspection.message.value.always.false"
else if (logicalChain(expr))
"inspection.message.condition.always.false.when.reached"
else
"inspection.message.condition.always.false"
ConstantValue.NULL -> "inspection.message.value.always.null"
ConstantValue.ZERO -> "inspection.message.value.always.zero"
else -> throw IllegalStateException("Unexpected constant: $cv")
}
val highlightType =
if (shouldReportAsValue(expr)) ProblemHighlightType.WEAK_WARNING
else ProblemHighlightType.GENERIC_ERROR_OR_WARNING
holder.registerProblem(expr, KotlinBundle.message(key, expr.text), highlightType)
}
}
is KotlinWhenConditionAnchor -> {
val condition = anchor.condition
if (!shouldSuppressWhenCondition(cv, condition)) {
val message = KotlinBundle.message("inspection.message.when.condition.always.false")
if (cv == ConstantValue.FALSE) {
holder.registerProblem(condition, message)
} else if (cv == ConstantValue.TRUE) {
condition.siblings(forward = true, withSelf = false)
.filterIsInstance<KtWhenCondition>()
.forEach { cond -> holder.registerProblem(cond, message) }
val nextEntry = condition.parent as? KtWhenEntry ?: return@forEach
nextEntry.siblings(forward = true, withSelf = false)
.filterIsInstance<KtWhenEntry>()
.filterNot { entry -> entry.isElse }
.flatMap { entry -> entry.conditions.asSequence() }
.forEach { cond -> holder.registerProblem(cond, message) }
}
}
}
is KotlinForVisitedAnchor -> {
val loopRange = anchor.forExpression.loopRange!!
if (cv == ConstantValue.FALSE && !shouldSuppressForCondition(loopRange)) {
val message = KotlinBundle.message("inspection.message.for.never.visited")
holder.registerProblem(loopRange, message)
}
}
}
}
}
listener.problems.forEach { (problem, state) ->
if (state == ThreeState.YES) {
when (problem) {
is KotlinArrayIndexProblem ->
holder.registerProblem(problem.index, KotlinBundle.message("inspection.message.index.out.of.bounds"))
is KotlinNullCheckProblem -> {
val expr = problem.expr
if (expr.baseExpression?.isNull() != true) {
holder.registerProblem(expr.operationReference, KotlinBundle.message("inspection.message.nonnull.cast.will.always.fail"))
}
}
is KotlinCastProblem -> {
val anchor = (problem.cast as? KtBinaryExpressionWithTypeRHS)?.operationReference ?: problem.cast
if (!isCompilationWarning(anchor)) {
holder.registerProblem(anchor, KotlinBundle.message("inspection.message.cast.will.always.fail"))
}
}
}
}
}
}
private fun shouldSuppressForCondition(loopRange: KtExpression): Boolean {
if (loopRange is KtBinaryExpression) {
val left = loopRange.left
val right = loopRange.right
// Reported separately by EmptyRangeInspection
return left != null && right != null && left.isConstant() && right.isConstant()
}
return false
}
private fun shouldReportAsValue(expr: KtExpression) =
expr is KtSimpleNameExpression || expr is KtQualifiedExpression && expr.selectorExpression is KtSimpleNameExpression
private fun logicalChain(expr: KtExpression): Boolean {
var context = expr
var parent = context.parent
while (parent is KtParenthesizedExpression) {
context = parent
parent = context.parent
}
if (parent is KtBinaryExpression && parent.right == context) {
val token = parent.operationToken
return token == KtTokens.ANDAND || token == KtTokens.OROR
}
return false
}
private fun shouldSuppressWhenCondition(
cv: ConstantValue,
condition: KtWhenCondition
): Boolean {
if (cv != ConstantValue.FALSE && cv != ConstantValue.TRUE) return true
if (cv == ConstantValue.TRUE && isLastCondition(condition)) return true
if (condition.textLength == 0) return true
return isCompilationWarning(condition)
}
private fun isLastCondition(condition: KtWhenCondition): Boolean {
val entry = condition.parent as? KtWhenEntry ?: return false
val whenExpr = entry.parent as? KtWhenExpression ?: return false
if (entry.conditions.last() == condition) {
val entries = whenExpr.entries
val lastEntry = entries.last()
if (lastEntry == entry) return true
val size = entries.size
// Also, do not report the always reachable entry right before 'else',
// usually it's necessary for the smart-cast, or for definite assignment, and the report is just noise
if (lastEntry.isElse && size > 1 && entries[size - 2] == entry) return true
}
return false
}
companion object {
private fun areEquivalent(e1: KtElement, e2: KtElement): Boolean {
return PsiEquivalenceUtil.areElementsEquivalent(e1, e2,
{ref1, ref2 -> ref1.element.text.compareTo(ref2.element.text)},
null, null, false)
}
private tailrec fun isOppositeCondition(candidate: KtExpression?, template: KtBinaryExpression, expression: KtExpression): Boolean {
if (candidate !is KtBinaryExpression || candidate.operationToken !== KtTokens.ANDAND) return false
val left = candidate.left
val right = candidate.right
if (left == null || right == null) return false
val templateLeft = template.left
val templateRight = template.right
if (templateLeft == null || templateRight == null) return false
if (templateRight === expression) {
return areEquivalent(left, templateLeft) && areEquivalent(right.negate(false), templateRight)
}
if (!areEquivalent(right, templateRight)) return false
if (templateLeft === expression) {
return areEquivalent(left.negate(false), templateLeft)
}
if (templateLeft !is KtBinaryExpression || templateLeft.operationToken !== KtTokens.ANDAND) return false
return isOppositeCondition(left, templateLeft, expression)
}
private fun hasOppositeCondition(whenExpression: KtWhenExpression, topAnd: KtBinaryExpression, expression: KtExpression): Boolean {
for (entry in whenExpression.entries) {
for (condition in entry.conditions) {
if (condition is KtWhenConditionWithExpression) {
val candidate = condition.expression
if (candidate === topAnd) return false
if (isOppositeCondition(candidate, topAnd, expression)) return true
}
}
}
return false
}
/**
* Returns true if expression is part of when condition expression that looks like
* ```
* when {
* a && b -> ...
* a && !b -> ...
* }
* ```
* In this case, !b could be reported as 'always true' but such warnings are annoying
*/
private fun isPairingConditionInWhen(expression: KtExpression): Boolean {
val parent = expression.parent
if (parent is KtBinaryExpression && parent.operationToken == KtTokens.ANDAND) {
var topAnd: KtBinaryExpression = parent
while (true) {
val nextParent = topAnd.parent
if (nextParent is KtBinaryExpression && nextParent.operationToken == KtTokens.ANDAND) {
topAnd = nextParent
} else break
}
val topAndParent = topAnd.parent
if (topAndParent is KtWhenConditionWithExpression) {
val whenExpression = (topAndParent.parent as? KtWhenEntry)?.parent as? KtWhenExpression
if (whenExpression != null && hasOppositeCondition(whenExpression, topAnd, expression)) {
return true
}
}
}
return false
}
private fun isCompilationWarning(anchor: KtElement): Boolean
{
val context = anchor.analyze(BodyResolveMode.FULL)
if (context.diagnostics.forElement(anchor).any
{ it.factory == Errors.CAST_NEVER_SUCCEEDS
|| it.factory == Errors.SENSELESS_COMPARISON
|| it.factory == Errors.SENSELESS_NULL_IN_WHEN
|| it.factory == Errors.USELESS_IS_CHECK
|| it.factory == Errors.DUPLICATE_LABEL_IN_WHEN }
) {
return true
}
val rootElement = anchor.containingFile
val suppressionCache = KotlinCacheService.getInstance(anchor.project).getSuppressionCache()
return suppressionCache.isSuppressed(anchor, rootElement, "CAST_NEVER_SUCCEEDS", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_COMPARISON", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_NULL_IN_WHEN", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, rootElement, "USELESS_IS_CHECK", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, rootElement, "DUPLICATE_LABEL_IN_WHEN", Severity.WARNING)
}
private fun isCallToMethod(call: KtCallExpression, packageName: String, methodName: String): Boolean {
val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false
if (descriptor.name.asString() != methodName) return false
val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
return packageFragment.fqName.asString() == packageName
}
// Do not report x.let { true } or x.let { false } as it's pretty evident
private fun isLetConstant(expr: KtExpression): Boolean {
val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false
if (!isCallToMethod(call, "kotlin", "let")) return false
val lambda = call.lambdaArguments.singleOrNull()?.getLambdaExpression() ?: return false
return lambda.bodyExpression?.statements?.singleOrNull() is KtConstantExpression
}
// Do not report on also, as it always returns the qualifier. If necessary, qualifier itself will be reported
private fun isAlsoChain(expr: KtExpression): Boolean {
val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false
return isCallToMethod(call, "kotlin", "also")
}
private fun isAssertion(parent: PsiElement?, value: Boolean): Boolean {
return when (parent) {
is KtBinaryExpression ->
(parent.operationToken == KtTokens.ANDAND || parent.operationToken == KtTokens.OROR) && isAssertion(parent.parent, value)
is KtParenthesizedExpression ->
isAssertion(parent.parent, value)
is KtPrefixExpression ->
parent.operationToken == KtTokens.EXCL && isAssertion(parent.parent, !value)
is KtValueArgument -> {
if (!value) return false
val valueArgList = parent.parent as? KtValueArgumentList ?: return false
val call = valueArgList.parent as? KtCallExpression ?: return false
val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false
val name = descriptor.name.asString()
if (name != "assert" && name != "require" && name != "check") return false
val pkg = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
return pkg.fqName.asString() == "kotlin"
}
else -> false
}
}
private fun hasWritesTo(block: PsiElement?, variable: KtProperty): Boolean {
return !PsiTreeUtil.processElements(block, KtSimpleNameExpression::class.java) { ref ->
val write = ref.mainReference.isReferenceTo(variable) && ref.readWriteAccess(false).isWrite
!write
}
}
private fun isUpdateChain(expression: KtExpression): Boolean {
// x = x or ..., etc.
if (expression !is KtSimpleNameExpression) return false
val binOp = expression.parent as? KtBinaryExpression ?: return false
val op = binOp.operationReference.text
if (op != "or" && op != "and" && op != "xor" && op != "||" && op != "&&") return false
val assignment = binOp.parent as? KtBinaryExpression ?: return false
if (assignment.operationToken != KtTokens.EQ) return false
val left = assignment.left
if (left !is KtSimpleNameExpression || !left.textMatches(expression.text)) return false
val variable = expression.mainReference.resolve() as? KtProperty ?: return false
val varParent = variable.parent as? KtBlockExpression ?: return false
var context: PsiElement = assignment
var block = context.parent
while (block is KtContainerNode ||
block is KtBlockExpression && block.statements.first() == context ||
block is KtIfExpression && block.then?.parent == context && block.`else` == null && !hasWritesTo(block.condition, variable)
) {
context = block
block = context.parent
}
if (block !== varParent) return false
var curExpression = variable.nextSibling
while (curExpression != context) {
if (hasWritesTo(curExpression, variable)) return false
curExpression = curExpression.nextSibling
}
return true
}
fun shouldSuppress(value: DfType, expression: KtExpression): Boolean {
val constant = when(value) {
DfTypes.NULL -> ConstantValue.NULL
DfTypes.TRUE -> ConstantValue.TRUE
DfTypes.FALSE -> ConstantValue.FALSE
DfTypes.intValue(0), DfTypes.longValue(0) -> ConstantValue.ZERO
else -> ConstantValue.UNKNOWN
}
return shouldSuppress(constant, expression)
}
private fun shouldSuppress(value: ConstantValue, expression: KtExpression): Boolean {
// TODO: do something with always false branches in exhaustive when statements
// TODO: return x && y.let {return...}
var parent = expression.parent
if (parent is KtDotQualifiedExpression && parent.selectorExpression == expression) {
// Will be reported for parent qualified expression
return true
}
while (parent is KtParenthesizedExpression) {
parent = parent.parent
}
if (expression is KtConstantExpression ||
// If result of initialization is constant, then the initializer will be reported
expression is KtProperty ||
// If result of assignment is constant, then the right-hand part will be reported
expression is KtBinaryExpression && expression.operationToken == KtTokens.EQ ||
// Negation operand: negation itself will be reported
(parent as? KtPrefixExpression)?.operationToken == KtTokens.EXCL
) {
return true
}
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.ELVIS) {
// Left part of Elvis is Nothing?, so the right part is always executed
// Could be caused by code like return x?.let { return ... } ?: true
// While inner "return" is redundant, the "always true" warning is confusing
// probably separate inspection could report extra "return"
if (expression.left?.getKotlinType()?.isNullableNothing() == true) {
return true
}
}
if (isAlsoChain(expression) || isLetConstant(expression) || isUpdateChain(expression)) return true
when (value) {
ConstantValue.TRUE -> {
if (isSmartCastNecessary(expression, true)) return true
if (isPairingConditionInWhen(expression)) return true
if (isAssertion(parent, true)) return true
}
ConstantValue.FALSE -> {
if (isSmartCastNecessary(expression, false)) return true
if (isAssertion(parent, false)) return true
}
ConstantValue.ZERO -> {
if (expression.readWriteAccess(false).isWrite) {
// like if (x == 0) x++, warning would be somewhat annoying
return true
}
if (expression is KtDotQualifiedExpression && expression.selectorExpression?.textMatches("ordinal") == true) {
var receiver: KtExpression? = expression.receiverExpression
if (receiver is KtQualifiedExpression) {
receiver = receiver.selectorExpression
}
if (receiver is KtSimpleNameExpression && receiver.mainReference.resolve() is KtEnumEntry) {
// ordinal() call on explicit enum constant
return true
}
}
val bindingContext = expression.analyze()
if (ConstantExpressionEvaluator.getConstant(expression, bindingContext) != null) return true
if (expression is KtSimpleNameExpression &&
(parent is KtValueArgument || parent is KtContainerNode && parent.parent is KtArrayAccessExpression)
) {
// zero value is passed as argument to another method or used for array access. Often, such a warning is annoying
return true
}
}
ConstantValue.NULL -> {
if (parent is KtProperty && parent.typeReference == null && expression is KtSimpleNameExpression) {
// initialize other variable with null to copy type, like
// var x1 : X = null
// var x2 = x1 -- let's suppress this
return true
}
if (expression is KtBinaryExpressionWithTypeRHS && expression.left.isNull()) {
// like (null as? X)
return true
}
if (parent is KtBinaryExpression) {
val token = parent.operationToken
if ((token === KtTokens.EQEQ || token === KtTokens.EXCLEQ || token === KtTokens.EQEQEQ || token === KtTokens.EXCLEQEQEQ) &&
(parent.left?.isNull() == true || parent.right?.isNull() == true)
) {
// like if (x == null) when 'x' is known to be null: report 'always true' instead
return true
}
}
val kotlinType = expression.getKotlinType()
if (kotlinType.toDfType() == DfTypes.NULL) {
// According to type system, nothing but null could be stored in such an expression (likely "Void?" type)
return true
}
}
else -> {}
}
if (expression is KtSimpleNameExpression) {
val target = expression.mainReference.resolve()
if (target is KtProperty && !target.isVar && target.initializer is KtConstantExpression) {
// suppress warnings uses of boolean constant like 'val b = true'
return true
}
}
if (isCompilationWarning(expression)) {
return true
}
return expression.isUsedAsStatement(expression.analyze(BodyResolveMode.FULL))
}
}
} | apache-2.0 | a37e620e76133d9f6a640a1b8d8f1116 | 51.790295 | 158 | 0.582521 | 5.928182 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/LeftEntityImpl.kt | 1 | 13255 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
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(val dataSource: LeftEntityData) : 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)
internal val PARENT_CONNECTION_ID: ConnectionId = ConnectionId.create(HeadAbstractionEntity::class.java,
CompositeBaseEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
CHILDREN_CONNECTION_ID,
PARENT_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 val parent: HeadAbstractionEntity?
get() = snapshot.extractOneToAbstractOneParent(PARENT_CONNECTION_ID, this)
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
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
// 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")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as LeftEntity
this.entitySource = dataSource.entitySource
if (parents != null) {
this.parentEntity = parents.filterIsInstance<CompositeBaseEntity>().singleOrNull()
this.parent = parents.filterIsInstance<HeadAbstractionEntity>().singleOrNull()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
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 parent: HeadAbstractionEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(PARENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENT_CONNECTION_ID)] as? HeadAbstractionEntity
}
else {
this.entityLinks[EntityLink(false, PARENT_CONNECTION_ID)] as? HeadAbstractionEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(PARENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENT_CONNECTION_ID)] = value
}
changedProperty.add("parent")
}
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 {
return getCached(snapshot) {
val entity = LeftEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
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 createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return LeftEntity(entitySource) {
this.parentEntity = parents.filterIsInstance<CompositeBaseEntity>().singleOrNull()
this.parent = parents.filterIsInstance<HeadAbstractionEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
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
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | f0314510727fd39fd171f6046df664b6 | 39.910494 | 178 | 0.661184 | 5.506855 | false | false | false | false |
JetBrains/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/archetype/MavenArchetypeNewProjectWizard.kt | 1 | 19062 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.wizards.archetype
import com.intellij.codeInsight.lookup.impl.LookupCellRenderer.REGULAR_MATCHED_ATTRIBUTES
import com.intellij.execution.util.setEmptyState
import com.intellij.execution.util.setVisibleRowCount
import com.intellij.icons.AllIcons
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logVersionChanged
import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.MAVEN
import com.intellij.ide.projectWizard.NewProjectWizardConstants.Language.JAVA
import com.intellij.ide.projectWizard.generators.AssetsNewProjectWizardStep
import com.intellij.ide.projectWizard.generators.BuildSystemJavaNewProjectWizardData.Companion.buildSystem
import com.intellij.ide.starters.local.StandardAssetsProvider
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.*
import com.intellij.ide.wizard.LanguageNewProjectWizardData.Companion.language
import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.name
import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.path
import com.intellij.ide.wizard.util.NewProjectLinkNewProjectWizardStep
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl
import com.intellij.openapi.externalSystem.service.ui.completion.DefaultTextCompletionRenderer.Companion.append
import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionComboBox
import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionComboBoxConverter
import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionField
import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionRenderer.Cell
import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesTable
import com.intellij.openapi.externalSystem.service.ui.spinner.ComponentSpinnerExtension.Companion.setSpinning
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.observable.util.transform
import com.intellij.openapi.observable.util.trim
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.collectionModel
import com.intellij.openapi.ui.validation.CHECK_NON_EMPTY
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleTextAttributes.GRAYED_ATTRIBUTES
import com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES
import com.intellij.ui.components.JBLabel
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.layout.ValidationInfoBuilder
import com.intellij.util.containers.ContainerUtil.putIfNotNull
import com.intellij.util.text.nullize
import com.intellij.util.ui.update.UiNotifyConnector
import icons.OpenapiIcons
import org.jetbrains.idea.maven.indices.archetype.MavenCatalog
import org.jetbrains.idea.maven.model.MavenArchetype
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.wizards.InternalMavenModuleBuilder
import org.jetbrains.idea.maven.wizards.MavenNewProjectWizardStep
import org.jetbrains.idea.maven.wizards.MavenWizardBundle
import org.jetbrains.idea.maven.wizards.archetype.MavenArchetypeNewProjectWizardBackend.ArchetypeItem
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JList
class MavenArchetypeNewProjectWizard : GeneratorNewProjectWizard {
override val id: String = "MavenArchetype"
override val name: String = MavenWizardBundle.message("maven.new.project.wizard.archetype.generator.name")
override val icon: Icon = OpenapiIcons.RepositoryLibraryLogo
override fun createStep(context: WizardContext) =
RootNewProjectWizardStep(context).chain(
::CommentStep,
::newProjectWizardBaseStepWithoutGap,
::GitNewProjectWizardStep,
::Step
).chain(::AssetsStep)
private class CommentStep(parent: NewProjectWizardStep) : NewProjectLinkNewProjectWizardStep(parent) {
override fun getComment(name: String): String {
return MavenWizardBundle.message("maven.new.project.wizard.archetype.generator.comment", context.isCreatingNewProjectInt, name)
}
override fun onStepSelected(step: NewProjectWizardStep) {
step.language = JAVA
step.buildSystem = MAVEN
}
}
private class Step(parent: GitNewProjectWizardStep) : MavenNewProjectWizardStep<GitNewProjectWizardStep>(parent) {
private var isAutoReloadArchetypeModel = true
private val backend = MavenArchetypeNewProjectWizardBackend(context.projectOrDefault, context.disposable)
val catalogItemProperty = propertyGraph.property<MavenCatalog>(MavenCatalog.System.Internal)
val archetypeItemProperty = propertyGraph.property(ArchetypeItem.NONE)
val archetypeVersionProperty = propertyGraph.property("")
val archetypeDescriptorProperty = propertyGraph.property(emptyMap<String, String>())
var catalogItem by catalogItemProperty
var archetypeItem by archetypeItemProperty
var archetypeVersion by archetypeVersionProperty
var archetypeDescriptor by archetypeDescriptorProperty
private lateinit var catalogComboBox: ComboBox<MavenCatalog>
private lateinit var archetypeComboBox: TextCompletionComboBox<ArchetypeItem>
private lateinit var archetypeVersionComboBox: TextCompletionComboBox<String>
private lateinit var archetypeDescriptorTable: PropertiesTable
private lateinit var archetypeDescriptorPanel: JComponent
init {
catalogItemProperty.afterChange { if (isAutoReloadArchetypeModel) reloadArchetypes() }
archetypeItemProperty.afterChange { if (isAutoReloadArchetypeModel) reloadArchetypeVersions() }
archetypeVersionProperty.afterChange { if (isAutoReloadArchetypeModel) reloadArchetypeDescriptor() }
}
override fun setupSettingsUI(builder: Panel) {
super.setupSettingsUI(builder)
with(builder) {
row {
layout(RowLayout.LABEL_ALIGNED)
catalogComboBox = ComboBox(CollectionComboBoxModel())
label(MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.label"))
.applyToComponent { horizontalTextPosition = JBLabel.LEFT }
.applyToComponent { icon = AllIcons.General.ContextHelp }
.applyToComponent { toolTipText = MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.tooltip") }
cell(catalogComboBox)
.applyToComponent { renderer = CatalogRenderer() }
.applyToComponent { setSwingPopup(false) }
.bindItem(catalogItemProperty)
.columns(COLUMNS_MEDIUM)
.gap(RightGap.SMALL)
link(MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.manage.button")) {
manageCatalogs()
}
}.topGap(TopGap.SMALL)
row {
layout(RowLayout.LABEL_ALIGNED)
archetypeComboBox = TextCompletionComboBox(context.project, ArchetypeConverter())
label(MavenWizardBundle.message("maven.new.project.wizard.archetype.label"))
.applyToComponent { horizontalTextPosition = JBLabel.LEFT }
.applyToComponent { icon = AllIcons.General.ContextHelp }
.applyToComponent { toolTipText = MavenWizardBundle.message("maven.new.project.wizard.archetype.tooltip") }
cell(archetypeComboBox)
.applyToComponent { bindSelectedItem(archetypeItemProperty) }
.align(AlignX.FILL)
.resizableColumn()
.validationOnApply { validateArchetypeId() }
.gap(RightGap.SMALL)
button(MavenWizardBundle.message("maven.new.project.wizard.archetype.add.button")) {
addArchetype()
}
}.topGap(TopGap.SMALL)
row(MavenWizardBundle.message("maven.new.project.wizard.archetype.version.label")) {
archetypeVersionComboBox = TextCompletionComboBox(context.project, ArchetypeVersionConverter())
cell(archetypeVersionComboBox)
.applyToComponent { bindSelectedItem(archetypeVersionProperty) }
.validationOnApply { validateArchetypeVersion() }
.columns(10)
}.topGap(TopGap.SMALL)
group(MavenWizardBundle.message("maven.new.project.wizard.archetype.properties.title")) {
row {
archetypeDescriptorTable = PropertiesTable()
.setVisibleRowCount(3)
.setEmptyState(MavenWizardBundle.message("maven.new.project.wizard.archetype.properties.empty"))
.bindProperties(archetypeDescriptorProperty.transform(
{ it.map { (k, v) -> PropertiesTable.Property(k, v) } },
{ it.associate { (n, v) -> n to v } }
))
archetypeDescriptorPanel = archetypeDescriptorTable.component
cell(archetypeDescriptorPanel)
.align(Align.FILL)
.resizableColumn()
}.resizableRow()
}.resizableRow()
}
UiNotifyConnector.doWhenFirstShown(catalogComboBox) { reloadCatalogs() }
}
override fun setupAdvancedSettingsUI(builder: Panel) {
super.setupAdvancedSettingsUI(builder)
with(builder) {
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.version.label")) {
textField()
.bindText(versionProperty.trim())
.columns(COLUMNS_MEDIUM)
.trimmedTextValidation(CHECK_NON_EMPTY)
.whenTextChangedFromUi { logVersionChanged() }
}.bottomGap(BottomGap.SMALL)
}
}
fun ValidationInfoBuilder.validateArchetypeId(): ValidationInfo? {
val isEmptyGroupId = archetypeItem.groupId.isEmpty()
val isEmptyArtifactId = archetypeItem.artifactId.isEmpty()
if (isEmptyGroupId && isEmptyArtifactId) {
return error(MavenWizardBundle.message("maven.new.project.wizard.archetype.error.empty"))
}
if (isEmptyGroupId) {
return error(MavenWizardBundle.message("maven.new.project.wizard.archetype.group.id.error.empty"))
}
if (isEmptyArtifactId) {
return error(MavenWizardBundle.message("maven.new.project.wizard.archetype.artifact.id.error.empty"))
}
return null
}
fun ValidationInfoBuilder.validateArchetypeVersion(): ValidationInfo? {
if (archetypeVersion.isEmpty()) {
return error(MavenWizardBundle.message("maven.new.project.wizard.archetype.version.error.empty"))
}
return null
}
private fun reloadCatalogs() {
val catalogs = backend.getCatalogs()
val oldCatalogs = catalogComboBox.collectionModel.items
val addedCatalogs = catalogs.toSet() - oldCatalogs.toSet()
catalogComboBox.collectionModel.replaceAll(catalogs)
when {
addedCatalogs.isNotEmpty() ->
catalogItem = addedCatalogs.first()
catalogItem !in catalogs ->
catalogItem = catalogs.firstOrNull() ?: MavenCatalog.System.Internal
}
}
private fun manageCatalogs() {
val dialog = MavenManageCatalogsDialog(context.projectOrDefault)
if (dialog.showAndGet()) {
reloadCatalogs()
}
}
private fun reloadArchetypes() {
archetypeComboBox.setSpinning(true)
archetypeComboBox.collectionModel.removeAll()
archetypeItem = ArchetypeItem.NONE
backend.collectArchetypeIds(archetypeComboBox, catalogItem) { archetypes ->
archetypeComboBox.setSpinning(false)
archetypeComboBox.collectionModel.replaceAll(archetypes)
archetypeItem = ArchetypeItem.NONE
}
}
private fun addArchetype() {
val dialog = MavenAddArchetypeDialog(context.projectOrDefault)
if (dialog.showAndGet()) {
setArchetype(dialog.getArchetype())
}
}
private fun findOrAddCatalog(catalogLocation: String?): MavenCatalog? {
var catalog = catalogComboBox.collectionModel.items
.find { it.location == catalogLocation }
if (catalogLocation != null && catalog == null) {
catalog = createCatalog(catalogLocation)
catalogComboBox.collectionModel.add(catalog)
}
return catalog
}
private fun setArchetype(archetype: MavenArchetype) {
withDisableAutoReloadArchetypeModel {
archetypeComboBox.setSpinning(true)
catalogItem = findOrAddCatalog(archetype.repository) ?: MavenCatalog.System.Internal
archetypeItem = ArchetypeItem(archetype.groupId, archetype.artifactId)
archetypeVersion = archetype.version
archetypeComboBox.collectionModel.removeAll()
archetypeVersionComboBox.collectionModel.removeAll()
archetypeDescriptor = emptyMap()
backend.collectArchetypeIds(archetypeComboBox, catalogItem) { archetypes ->
archetypeComboBox.setSpinning(false)
withDisableAutoReloadArchetypeModel {
archetypeComboBox.collectionModel.replaceAll(archetypes)
backend.collectArchetypeVersions(archetypeVersionComboBox, catalogItem, archetypeItem) { versions ->
isAutoReloadArchetypeModel = false
withDisableAutoReloadArchetypeModel {
archetypeVersionComboBox.collectionModel.replaceAll(versions)
backend.collectArchetypeDescriptor(archetypeDescriptorPanel, catalogItem, archetypeItem, archetypeVersion) {
archetypeDescriptor = it + archetypeDescriptor
}
}
}
}
}
}
}
private fun <R> withDisableAutoReloadArchetypeModel(action: () -> R): R {
isAutoReloadArchetypeModel = false
try {
return action()
}
finally {
isAutoReloadArchetypeModel = true
}
}
private fun reloadArchetypeVersions() {
archetypeVersionComboBox.collectionModel.removeAll()
archetypeVersion = ""
backend.collectArchetypeVersions(archetypeVersionComboBox, catalogItem, archetypeItem) { versions ->
archetypeVersionComboBox.collectionModel.replaceAll(versions)
archetypeVersion = versions.firstOrNull() ?: ""
}
}
private fun reloadArchetypeDescriptor() {
archetypeDescriptor = emptyMap()
backend.collectArchetypeDescriptor(archetypeDescriptorPanel, catalogItem, archetypeItem, archetypeVersion) {
archetypeDescriptor = it
}
}
override fun setupProject(project: Project) {
super.setupProject(project)
val builder = InternalMavenModuleBuilder().apply {
moduleJdk = sdk
name = parentStep.name
contentEntryPath = "${parentStep.path}/${parentStep.name}"
parentProject = parentData
aggregatorProject = parentData
projectId = MavenId(groupId, artifactId, version)
isInheritGroupId = parentData?.mavenId?.groupId == groupId
isInheritVersion = parentData?.mavenId?.version == version
archetype = MavenArchetype(
archetypeItem.groupId,
archetypeItem.artifactId,
archetypeVersion,
catalogItem.location,
null
)
propertiesToCreateByArtifact = LinkedHashMap<String, String>().apply {
put("groupId", groupId)
put("artifactId", artifactId)
put("version", version)
put("archetypeGroupId", archetype.groupId)
put("archetypeArtifactId", archetype.artifactId)
put("archetypeVersion", archetype.version)
putIfNotNull("archetypeRepository", archetype.repository, this)
putAll(archetypeDescriptor)
}
}
ExternalProjectsManagerImpl.setupCreatedProject(project)
MavenProjectsManager.setupCreatedMavenProject(project)
project.putUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT, true)
builder.commit(project)
}
}
private class CatalogRenderer : ColoredListCellRenderer<MavenCatalog>() {
override fun customizeCellRenderer(
list: JList<out MavenCatalog>,
value: MavenCatalog?,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
val catalog = value ?: return
append(catalog.name)
}
}
private class ArchetypeConverter : TextCompletionComboBoxConverter<ArchetypeItem> {
override fun getItem(text: String) =
text.nullize(true)?.let {
ArchetypeItem(
groupId = text.substringBefore(':'),
artifactId = text.substringAfter(':', "")
)
} ?: ArchetypeItem.NONE
override fun getText(item: ArchetypeItem) =
item.run {
if (artifactId.isNotEmpty())
"$groupId:$artifactId"
else
groupId
}
override fun customizeCellRenderer(editor: TextCompletionField<ArchetypeItem>, cell: Cell<ArchetypeItem>) {
val item = cell.item
val text = editor.getTextToComplete()
with(cell.component) {
val groupIdSuffix = text.substringBefore(':')
val artifactIdPrefix = text.substringAfter(':', "")
if (':' in text && item.groupId.endsWith(groupIdSuffix) && item.artifactId.startsWith(artifactIdPrefix)) {
val groupIdPrefix = item.groupId.removeSuffix(groupIdSuffix)
val artifactIdSuffix = item.artifactId.removePrefix(artifactIdPrefix)
append(groupIdPrefix, GRAYED_ATTRIBUTES, text, REGULAR_MATCHED_ATTRIBUTES)
append(groupIdSuffix, REGULAR_MATCHED_ATTRIBUTES)
if (item.artifactId.isNotEmpty()) {
append(":", REGULAR_MATCHED_ATTRIBUTES)
append(artifactIdPrefix, REGULAR_MATCHED_ATTRIBUTES)
append(artifactIdSuffix, REGULAR_ATTRIBUTES, text, REGULAR_MATCHED_ATTRIBUTES)
}
}
else {
append(item.groupId, GRAYED_ATTRIBUTES, text, REGULAR_MATCHED_ATTRIBUTES)
if (item.artifactId.isNotEmpty()) {
append(":", GRAYED_ATTRIBUTES)
append(item.artifactId, REGULAR_ATTRIBUTES, text, REGULAR_MATCHED_ATTRIBUTES)
}
}
}
}
}
private class ArchetypeVersionConverter : TextCompletionComboBoxConverter<@NlsSafe String> {
override fun getItem(text: String) = text.trim()
override fun getText(item: String) = item
override fun customizeCellRenderer(editor: TextCompletionField<String>, cell: Cell<@NlsSafe String>) {
cell.component.append(cell.item, editor.getTextToComplete())
}
}
class Builder : GeneratorNewProjectWizardBuilderAdapter(MavenArchetypeNewProjectWizard()) {
override fun getWeight(): Int = JVM_WEIGHT + 100
}
private class AssetsStep(parent: NewProjectWizardStep) : AssetsNewProjectWizardStep(parent) {
override fun setupAssets(project: Project) {
outputDirectory = "$path/$name"
addAssets(StandardAssetsProvider().getMavenIgnoreAssets())
}
}
} | apache-2.0 | baf0cfb3e9476f4752df8ccca75381e2 | 42.622426 | 133 | 0.725212 | 4.978323 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/screen/AdvancedOptionsScreen.kt | 2 | 22503 | package io.github.chrislo27.rhre3.screen
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.Preferences
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.utils.Align
import io.github.chrislo27.rhre3.PreferenceKeys
import io.github.chrislo27.rhre3.RHRE3Application
import io.github.chrislo27.rhre3.RemixRecovery
import io.github.chrislo27.rhre3.analytics.AnalyticsHandler
import io.github.chrislo27.rhre3.modding.ModdingGame
import io.github.chrislo27.rhre3.modding.ModdingUtils
import io.github.chrislo27.rhre3.sfxdb.SFXDatabase
import io.github.chrislo27.rhre3.stage.GenericStage
import io.github.chrislo27.rhre3.stage.TrueCheckbox
import io.github.chrislo27.rhre3.util.FadeIn
import io.github.chrislo27.rhre3.util.FadeOut
import io.github.chrislo27.rhre3.util.Semitones
import io.github.chrislo27.toolboks.Toolboks
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.i18n.Localization
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.registry.ScreenRegistry
import io.github.chrislo27.toolboks.transition.TransitionScreen
import io.github.chrislo27.toolboks.ui.Button
import io.github.chrislo27.toolboks.ui.ImageLabel
import io.github.chrislo27.toolboks.ui.TextLabel
import io.github.chrislo27.toolboks.ui.UIElement
import io.github.chrislo27.toolboks.util.gdxutils.fillRect
import io.github.chrislo27.toolboks.util.gdxutils.getInputX
import io.github.chrislo27.toolboks.util.gdxutils.openFileExplorer
import java.util.*
import kotlin.math.sign
import kotlin.system.measureNanoTime
class AdvancedOptionsScreen(main: RHRE3Application) : ToolboksScreen<RHRE3Application, AdvancedOptionsScreen>(main) {
override val stage: GenericStage<AdvancedOptionsScreen>
private val preferences: Preferences
get() = main.preferences
private var didChangeSettings: Boolean = false
private val moddingGameLabel: TextLabel<AdvancedOptionsScreen>
private val moddingGameWarningLabel: TextLabel<AdvancedOptionsScreen>
private var seconds = 0f
private val reloadMetadataButton: Button<AdvancedOptionsScreen>
private val pitchStyleButton: Button<AdvancedOptionsScreen>
private val explodingEntitiesButton: Button<AdvancedOptionsScreen>
init {
val palette = main.uiPalette
stage = GenericStage(main.uiPalette, null, main.defaultCamera)
stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_adv_opts"))
stage.titleLabel.isLocalizationKey = false
stage.titleLabel.text = "Advanced Options"
stage.backButton.visible = true
stage.onBackButtonClick = {
main.screen = ScreenRegistry.getNonNull("info")
}
val bottom = stage.bottomStage
// Advanced Options setting
bottom.elements += TrueCheckbox(palette, bottom, bottom).apply {
this.checked = main.settings.advancedOptions
this.textLabel.apply {
this.isLocalizationKey = false
this.textWrapping = false
this.textAlign = Align.left
this.text = "Other Advanced Options Enabled"
}
this.leftClickAction = { _, _ ->
main.settings.advancedOptions = checked
didChangeSettings = true
main.settings.persist()
}
this.location.set(screenX = 0.15f, screenWidth = 0.7f)
}
val centre = stage.centreStage
val padding = 0.025f
val buttonWidth = 0.4f
val buttonHeight = 0.1f
val fontScale = 0.75f
moddingGameLabel = TextLabel(palette, centre, centre).apply {
this.isLocalizationKey = false
this.text = ""
this.textWrapping = false
this.fontScaleMultiplier = 0.85f
this.textAlign = Align.top or Align.center
this.location.set(screenX = padding,
screenY = padding,
screenWidth = buttonWidth,
screenHeight = buttonHeight * 3 + padding * 2)
}
centre.elements += moddingGameLabel
moddingGameWarningLabel = TextLabel(palette, centre, centre).apply {
this.isLocalizationKey = false
this.text = ""
this.textWrapping = false
this.fontScaleMultiplier = 0.85f
this.textAlign = Align.top or Align.center
this.location.set(screenX = padding,
screenY = padding * 4 + buttonHeight * 3,
screenWidth = buttonWidth,
screenHeight = buttonHeight * 2 + padding)
}
centre.elements += moddingGameWarningLabel
// Modding game reference
centre.elements += object : Button<AdvancedOptionsScreen>(palette, centre, centre) {
private fun updateText() {
val game = ModdingUtils.currentGame
val underdeveloped = game.underdeveloped
textLabel.text = "[LIGHT_GRAY]Modding utilities with reference to:[]\n${if (underdeveloped) "[ORANGE]" else ""}${game.fullName}${if (underdeveloped) "[]" else ""}"
updateLabels()
}
private fun persist() {
ModdingUtils.currentGame = ModdingGame.VALUES[index]
preferences.putString(PreferenceKeys.ADVOPT_REF_RH_GAME, ModdingUtils.currentGame.id).flush()
didChangeSettings = true
}
private var index: Int = run {
val default = ModdingGame.DEFAULT_GAME
val pref = preferences.getString(PreferenceKeys.ADVOPT_REF_RH_GAME, default.id)
val values = ModdingGame.VALUES
values.indexOf(values.find { it.id == pref } ?: default).coerceIn(0, values.size - 1)
}
private val textLabel: TextLabel<AdvancedOptionsScreen>
get() = labels.first() as TextLabel
override fun render(screen: AdvancedOptionsScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
if (textLabel.text.isEmpty()) {
updateText()
}
super.render(screen, batch, shapeRenderer)
}
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
index++
if (index >= ModdingGame.VALUES.size)
index = 0
persist()
updateText()
}
override fun onRightClick(xPercent: Float, yPercent: Float) {
super.onRightClick(xPercent, yPercent)
index--
if (index < 0)
index = ModdingGame.VALUES.size - 1
persist()
updateText()
}
init {
Localization.addListener {
updateText()
}
}
}.apply {
this.addLabel(TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = false
this.text = ""
this.textWrapping = false
this.fontScaleMultiplier = 0.8f
})
this.location.set(screenX = padding,
screenY = padding * 6 + buttonHeight * 5,
screenWidth = buttonWidth,
screenHeight = buttonHeight * 2 + padding)
}
// Reload modding metadata
reloadMetadataButton = object : Button<AdvancedOptionsScreen>(palette, centre, centre) {
private val textLabel: TextLabel<AdvancedOptionsScreen>
get() = labels.first() as TextLabel
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
var success: Boolean = false
val nano = measureNanoTime {
success = try {
SFXDatabase.data.loadModdingMetadata(true)
} catch (e: Exception) {
e.printStackTrace()
false
}
if (success) {
resetReloadMetadataButton()
textLabel.text = "[GREEN]Reloaded metadata successfully![]"
} else {
resetReloadMetadataButton()
textLabel.text = "[RED]Failed to reload modding metadata[]\n[LIGHT_GRAY]Check console for details[]"
textLabel.fontScaleMultiplier = 0.6f
}
}
Toolboks.LOGGER.info("Reloaded modding metadata ${if (!success) "un" else ""}successfully in ${nano / 1_000_000.0} ms")
}
}.apply {
this.addLabel(TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = false
this.text = "Reload modding metadata"
this.textWrapping = false
this.fontScaleMultiplier = 0.8f
})
this.location.set(screenX = padding,
screenY = padding * 8 + buttonHeight * 7,
screenWidth = buttonWidth,
screenHeight = buttonHeight)
}
centre.elements += reloadMetadataButton
// Open containing folder for modding metadata
centre.elements += Button(palette, centre, centre).apply {
val width = buttonWidth * 0.09f
this.location.set(screenX = padding * 0.5f - width,
screenY = padding * 8 + buttonHeight * 7,
screenWidth = width,
screenHeight = buttonHeight)
this.addLabel(ImageLabel(palette, this, this.stage).apply {
renderType = ImageLabel.ImageRendering.ASPECT_RATIO
image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_folder"))
})
this.leftClickAction = { _, _ ->
Gdx.net.openFileExplorer(SFXDatabase.CUSTOM_MODDING_METADATA_FOLDER)
}
}
// Semitone major/minor
pitchStyleButton = object : Button<AdvancedOptionsScreen>(palette, centre, centre) {
private val textLabel: TextLabel<AdvancedOptionsScreen>
get() = labels.first() as TextLabel
private fun cycle(dir: Int) {
val values = Semitones.PitchStyle.VALUES
val index = values.indexOf(Semitones.pitchStyle).coerceAtLeast(0)
val absNextIndex = index + sign(dir.toFloat()).toInt()
val nextIndex = if (absNextIndex < 0) values.size - 1 else if (absNextIndex >= values.size) 0 else absNextIndex
val next = values[nextIndex]
Semitones.pitchStyle = next
main.preferences.putString(PreferenceKeys.ADVOPT_PITCH_STYLE, next.name).flush()
updateLabels()
}
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
cycle(1)
}
override fun onRightClick(xPercent: Float, yPercent: Float) {
super.onRightClick(xPercent, yPercent)
cycle(-1)
}
}.apply {
this.addLabel(TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = false
this.text = "Pitch note style: "
this.textWrapping = false
this.fontScaleMultiplier = 0.8f
})
this.location.set(screenX = 1f - (padding + buttonWidth),
screenY = padding * 8 + buttonHeight * 7,
screenWidth = buttonWidth,
screenHeight = buttonHeight)
}
centre.elements += pitchStyleButton
// Exploding entities
explodingEntitiesButton = TrueCheckbox(palette, centre, centre).apply {
this.leftClickAction = { _, _ ->
main.settings.advExplodingEntities = [email protected]
main.settings.persist()
}
this.textLabel.also {
it.isLocalizationKey = false
it.text = "Entities explode when deleted"
it.textWrapping = false
it.fontScaleMultiplier = 0.8f
it.textAlign = Align.left
}
this.checked = main.settings.advExplodingEntities
this.location.set(screenX = 1f - (padding + buttonWidth),
screenY = padding * 7 + buttonHeight * 6,
screenWidth = buttonWidth,
screenHeight = buttonHeight)
}
centre.elements += explodingEntitiesButton
centre.elements += TrueCheckbox(palette, centre, centre).apply {
this.leftClickAction = { _, _ ->
main.settings.advIgnorePitchRestrictions = [email protected]
main.settings.persist()
}
this.textLabel.also {
it.isLocalizationKey = false
it.text = "Ignore entity pitching restrictions"
it.textWrapping = false
it.fontScaleMultiplier = 0.8f
it.textAlign = Align.left
}
this.checked = main.settings.advIgnorePitchRestrictions
this.location.set(screenX = 1f - (padding + buttonWidth),
screenY = padding * 6 + buttonHeight * 5,
screenWidth = buttonWidth,
screenHeight = buttonHeight)
}
// centre.elements += Button(palette, centre, centre).apply {
// this.leftClickAction = { _, _ ->
// val defaultCamera = main.defaultCamera
// val oldDim = defaultCamera.viewportWidth to defaultCamera.viewportHeight
// defaultCamera.setToOrtho(false, RHRE3.WIDTH.toFloat(), RHRE3.HEIGHT.toFloat())
// defaultCamera.update()
// ScreenRegistry["editor"]?.dispose()
// ScreenRegistry += "editor" to EditorScreen(main)
// defaultCamera.setToOrtho(false, oldDim.first, oldDim.second)
// defaultCamera.update()
// SFXDatabase.reset()
// main.screen = SFXDBLoadingScreen(main) { ScreenRegistry["editor"] }
// }
// this.location.set(screenX = 1f - (padding + buttonWidth),
// screenY = padding,
// screenWidth = buttonWidth,
// screenHeight = buttonHeight)
// this.addLabel(TextLabel(palette, this, this.stage).apply {
// this.isLocalizationKey = false
// this.text = "Reload SFX Database"
// this.textWrapping = false
// this.fontScaleMultiplier = 0.8f
// })
// tooltipTextIsLocalizationKey = false
// tooltipText = "[ORANGE]WARNING[]: This will clear the editor and discard all unsaved changes.\nReloads the entire SFX database. May fail (and crash) if there are errors.\nThis will also reload modding metadata from scratch."
// }
centre.elements += object : UIElement<AdvancedOptionsScreen>(centre, centre) {
private val percentX: Float
get() = (stage.camera.getInputX() - location.realX) / location.realWidth
private var beginDraw = false
private var completed = false
private var timeSinceBeginDraw = 0f
private fun drawLine(batch: SpriteBatch, progress: Float) {
val circle = AssetRegistry.get<Texture>("ui_circle")
val diameter = this.location.realHeight * 3f
val smallDia = this.location.realHeight
batch.draw(circle, this.location.realX, this.location.realY + this.location.realHeight / 2f - diameter / 2f, diameter, diameter)
batch.draw(circle, this.location.realX + (this.location.realWidth * progress) - smallDia / 2f, this.location.realY, smallDia, smallDia)
batch.fillRect(this.location.realX + diameter / 2f, this.location.realY, (this.location.realWidth * progress - diameter / 2f), this.location.realHeight)
}
override fun render(screen: AdvancedOptionsScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
batch.setColor(1f, 1f, 1f, 1f)
drawLine(batch, 1f)
batch.color = Color.ORANGE
if (beginDraw) {
drawLine(batch, (percentX).coerceIn(0.005f, 1f))
timeSinceBeginDraw += Gdx.graphics.deltaTime
if (timeSinceBeginDraw in 0f..0.75f) {
val circle = AssetRegistry.get<Texture>("ui_circle")
val a = (timeSinceBeginDraw / 0.75f).coerceIn(0f, 1f)
val fullDiameter = this.location.realHeight * 3f
val diameter = fullDiameter * (1f - a) * 3f
batch.setColor(1f, 1f, 1f, (1f - a) * 0.6f)
batch.draw(circle, this.location.realX + fullDiameter / 2f - diameter / 2f, this.location.realY + this.location.realHeight / 2f - diameter / 2f, diameter, diameter)
batch.setColor(1f, 1f, 1f, 1f)
}
} else if (completed) {
drawLine(batch, 1f)
}
batch.setColor(1f, 1f, 1f, 1f)
}
override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
if (visible) {
if (isMouseOver() && !beginDraw) {
if (percentX in 0f..0.019f) {
beginDraw = true
timeSinceBeginDraw = 0f
completed = false
return true
}
} else {
val wasDrawing = beginDraw
beginDraw = false
if ((stage.camera.getInputX() - location.realX) >= location.realWidth - 1f) {
completed = true
Gdx.app.postRunnable {
main.screen = TransitionScreen(main, this@AdvancedOptionsScreen, LinePuzzleEndScreen(main), FadeOut(2f, Color.BLACK), FadeIn(1f, Color.BLACK))
AssetRegistry.get<Sound>("etc_sfx_record").play()
}
}
return wasDrawing
}
return false
}
return false
}
}.apply {
this.location.set(screenX = -0.02f,
screenY = -buttonHeight * 0.275f,
screenWidth = 1.02f,
screenHeight = buttonHeight * 0.2f)
}
updateLabels()
}
private fun updateLabels() {
val game = ModdingUtils.currentGame
moddingGameWarningLabel.text = "[LIGHT_GRAY]${if (game.underdeveloped)
"[ORANGE]Warning:[] modding info for this game\nis very underdeveloped and may be\nextremely lacking in info or incorrect."
else
"[YELLOW]Caution:[] modding info for this game\nmay only be partially complete and\nsubject to change."}[]\n"
moddingGameLabel.text = "1 โฉ (quarter note) = ${game.beatsToTickflowString(1f)}${if (game.tickflowUnitName.isEmpty()) " rest units" else ""}"
(pitchStyleButton.labels.first() as TextLabel).text = "Pitch note style: [LIGHT_GRAY]${Semitones.pitchStyle.name.toLowerCase(Locale.ROOT).capitalize()} (ex: ${Semitones.pitchStyle.example})[]"
}
override fun tickUpdate() {
}
override fun dispose() {
}
override fun renderUpdate() {
super.renderUpdate()
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE) && stage.backButton.visible && stage.backButton.enabled) {
stage.onBackButtonClick()
}
seconds += Gdx.graphics.deltaTime * 2.5f
stage.titleIcon.rotation = (MathUtils.sin(MathUtils.sin(seconds * 2)) + seconds * 0.4f) * -90f
}
override fun hide() {
super.hide()
// Analytics
if (didChangeSettings) {
preferences.flush()
val map: Map<String, *> = preferences.get()
AnalyticsHandler.track("Exit Advanced Options",
mapOf(
"settings" to PreferenceKeys.allAdvOptsKeys.associate {
it.replace("advOpt_", "") to (map[it] ?: "null")
} + ("advancedOptions" to map[PreferenceKeys.SETTINGS_ADVANCED_OPTIONS])
))
}
didChangeSettings = false
}
override fun show() {
super.show()
seconds = 0f
resetReloadMetadataButton()
}
private fun resetReloadMetadataButton() {
(reloadMetadataButton.labels.first() as TextLabel).let {
it.text = "Reload modding metadata"
it.fontScaleMultiplier = 0.8f
}
}
}
class LinePuzzleEndScreen(main: RHRE3Application) : ToolboksScreen<RHRE3Application, LinePuzzleEndScreen>(main), HidesVersionText {
override fun show() {
super.show()
Gdx.app.postRunnable {
RemixRecovery.saveRemixInRecovery()
Gdx.app.postRunnable {
RHRE3Application.disableCloseWarning = true
Gdx.app.exit()
}
}
}
override fun tickUpdate() {
}
override fun dispose() {
}
}
| gpl-3.0 | 22187680315a7ed92b73f69951956863 | 43.556436 | 238 | 0.566242 | 4.855632 | false | false | false | false |
allotria/intellij-community | java/java-ml-local-models/src/com/intellij/java/ml/local/JavaClassesFrequencyModelFactory.kt | 1 | 2439 | // 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.java.ml.local
import com.intellij.ml.local.models.frequency.classes.ClassesFrequencyModelFactory
import com.intellij.ml.local.models.frequency.classes.ClassesUsagesTracker
import com.intellij.psi.*
import com.intellij.psi.util.PsiTypesUtil
class JavaClassesFrequencyModelFactory : ClassesFrequencyModelFactory() {
override fun fileVisitor(usagesTracker: ClassesUsagesTracker): PsiElementVisitor = object : JavaRecursiveElementWalkingVisitor() {
override fun visitNewExpression(expression: PsiNewExpression) {
val cls = expression.classReference?.resolve()
if (cls is PsiClass) {
addClassUsage(cls)
}
super.visitNewExpression(expression)
}
override fun visitClassObjectAccessExpression(expression: PsiClassObjectAccessExpression) {
PsiTypesUtil.getPsiClass(expression.operand.type)?.let { cls ->
addClassUsage(cls)
}
}
override fun visitTypeCastExpression(expression: PsiTypeCastExpression) {
val castType = expression.castType
if (castType != null) {
PsiTypesUtil.getPsiClass(castType.type)?.let { cls ->
addClassUsage(cls)
}
}
expression.operand?.accept(this)
}
override fun visitInstanceOfExpression(expression: PsiInstanceOfExpression) {
expression.operand.accept(this)
val checkType = expression.checkType ?: return
PsiTypesUtil.getPsiClass(checkType.type)?.let { cls ->
addClassUsage(cls)
}
}
override fun visitReferenceExpression(expression: PsiReferenceExpression) {
expression.qualifierExpression?.let { qualifier ->
if (qualifier is PsiReferenceExpression) {
qualifier.resolve()?.let { def ->
if (def is PsiClass) {
addClassUsage(def)
}
}
}
}
super.visitReferenceExpression(expression)
}
private fun addClassUsage(cls: PsiClass) {
JavaLocalModelsUtil.getClassName(cls)?.let {
usagesTracker.classUsed(it)
}
}
override fun visitReferenceElement(reference: PsiJavaCodeReferenceElement) = Unit
override fun visitImportStatement(statement: PsiImportStatement) = Unit
override fun visitImportStaticStatement(statement: PsiImportStaticStatement) = Unit
}
} | apache-2.0 | cf6d0a95c557c802ecf201681ab58190 | 35.41791 | 140 | 0.711767 | 4.89759 | false | false | false | false |
theunknownxy/mcdocs | src/main/kotlin/de/theunknownxy/mcdocs/utils/GuiUtils.kt | 1 | 5917 | package de.theunknownxy.mcdocs.utils
import de.theunknownxy.mcdocs.gui.base.BorderImageDescription
import de.theunknownxy.mcdocs.gui.base.Rectangle
import net.minecraft.client.renderer.OpenGlHelper
import net.minecraft.client.renderer.Tessellator
import org.lwjgl.opengl.GL11
object GuiUtils {
public fun drawColoredRect(x1: Int, y1: Int, x2: Int, y2: Int, color: Int, z: Double = 0.toDouble()) {
// Extract rgba components
var red = (color shr 24 and 255) / 255.0f
var green = (color shr 16 and 255) / 255.0f
var blue = (color shr 8 and 255) / 255.0f
var alpha = (color and 255) / 255.0f
val tessellator = Tessellator.instance
GL11.glEnable(GL11.GL_BLEND)
GL11.glDisable(GL11.GL_TEXTURE_2D)
OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO)
GL11.glColor4f(red, green, blue, alpha)
// Draw rectangle
tessellator.startDrawingQuads()
tessellator.addVertex(x1.toDouble(), y2.toDouble(), z)
tessellator.addVertex(x2.toDouble(), y2.toDouble(), z)
tessellator.addVertex(x2.toDouble(), y1.toDouble(), z)
tessellator.addVertex(x1.toDouble(), y1.toDouble(), z)
tessellator.draw()
GL11.glEnable(GL11.GL_TEXTURE_2D)
GL11.glDisable(GL11.GL_BLEND)
}
public fun drawTexturedModalRect(x: Int, y: Int, z: Double, u: Int, v: Int, width: Int, height: Int, texwidth: Int = width, texheight: Int = height) {
if (width == 0 || height == 0) return
val f = 0.00390625.toFloat()
val f1 = 0.00390625.toFloat()
val tessellator = Tessellator.instance
tessellator.startDrawingQuads()
tessellator.addVertexWithUV((x + 0).toDouble(), (y + height).toDouble(), z, ((u + 0).toFloat() * f).toDouble(), ((v + texheight).toFloat() * f1).toDouble())
tessellator.addVertexWithUV((x + width).toDouble(), (y + height).toDouble(), z, ((u + texwidth).toFloat() * f).toDouble(), ((v + texheight).toFloat() * f1).toDouble())
tessellator.addVertexWithUV((x + width).toDouble(), (y + 0).toDouble(), z, ((u + texwidth).toFloat() * f).toDouble(), ((v + 0).toFloat() * f1).toDouble())
tessellator.addVertexWithUV((x + 0).toDouble(), (y + 0).toDouble(), z, ((u + 0).toFloat() * f).toDouble(), ((v + 0).toFloat() * f1).toDouble())
tessellator.draw()
}
public fun drawBox(box: Rectangle, z: Double, descr: BorderImageDescription) {
drawBox(box, z, descr.texbox, descr.bordertop, descr.borderright, descr.borderbottom, descr.borderleft)
}
public fun drawBox(box: Rectangle, z: Double, texbox: Rectangle, bordertop: Int, borderright: Int, borderbottom: Int, borderleft: Int) {
// Draw topleft corner
drawTexturedModalRect(box.x.toInt(), box.y.toInt(), z, texbox.x.toInt(), texbox.y.toInt(), borderleft, bordertop)
// Draw topright corner
drawTexturedModalRect((box.x2() - borderright).toInt(), box.y.toInt(), z, (texbox.x2() - borderright).toInt(), texbox.y.toInt(), borderright, bordertop)
// Draw bottomleft corner
drawTexturedModalRect((box.x.toInt()), (box.y2() - borderbottom).toInt(), z, texbox.x.toInt(), (texbox.y2() - borderbottom).toInt(), borderleft, borderbottom)
// Draw bottomright corner
drawTexturedModalRect((box.x2() - borderright).toInt(), (box.y2() - borderbottom).toInt(), z, (texbox.x2() - borderright).toInt(), (texbox.y2() - borderbottom).toInt(), borderright, borderbottom)
// Draw top and bottom border
var xhorizontal: Int = (box.x + borderleft).toInt()
val x2horizontal: Int = (box.x2() - borderright).toInt()
val stephorizontal: Int = (texbox.width - borderleft - borderright).toInt()
while (xhorizontal < x2horizontal) {
val drawwidth = Math.min(stephorizontal, (x2horizontal - xhorizontal).toInt())
drawTexturedModalRect(xhorizontal.toInt(), box.y.toInt(), z, (texbox.x + borderright).toInt(), texbox.y.toInt(), drawwidth, bordertop)
drawTexturedModalRect(xhorizontal.toInt(), (box.y2() - borderbottom).toInt(), z, (texbox.x + borderright).toInt(), (texbox.y2() - borderbottom).toInt(), drawwidth, borderbottom)
xhorizontal += stephorizontal
}
// Draw left and right border
var yleft: Int = (box.y + bordertop).toInt()
val y2left: Int = (box.y2() - borderbottom).toInt()
val stepleft: Int = (texbox.height - bordertop - borderbottom).toInt()
while (yleft < y2left) {
val drawheight = Math.min(stepleft, (y2left - yleft).toInt())
drawTexturedModalRect(box.x.toInt(), yleft.toInt(), z, texbox.x.toInt(), (texbox.y + bordertop).toInt(), borderleft, drawheight)
drawTexturedModalRect((box.x2() - borderleft).toInt(), yleft.toInt(), z, (texbox.x2() - borderright).toInt(), (texbox.x + bordertop).toInt(), borderright, drawheight)
yleft += stepleft
}
// Draw center
val y2center: Int = (box.y2() - borderbottom).toInt()
val stepycenter: Int = (texbox.height - bordertop - borderbottom).toInt()
val x2center: Int = (box.x2() - borderright).toInt()
val stepxcenter: Int = (texbox.width - borderleft - borderright).toInt()
var ycenter: Int = (box.y + bordertop).toInt()
while (ycenter < y2center) {
var xcenter = (box.x + borderleft).toInt()
val drawheight = Math.min(stepycenter, y2center - ycenter)
while (xcenter < x2center) {
val drawwidth = Math.min(stepxcenter, x2center - xcenter)
drawTexturedModalRect(xcenter.toInt(), ycenter.toInt(), z, (texbox.x + borderleft).toInt(), (texbox.y + bordertop).toInt(), drawwidth, drawheight)
xcenter += stepxcenter
}
ycenter += stepycenter
}
}
} | mit | a030dc9726a9af479332583f767e95fd | 57.594059 | 203 | 0.633598 | 3.472418 | false | false | false | false |
sdeleuze/mixit | src/main/kotlin/mixit/model/Post.kt | 1 | 612 | package mixit.model
import mixit.util.toSlug
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDateTime
@Document
data class Post(
val authorId: String,
val addedAt: LocalDateTime = LocalDateTime.now(),
val title: Map<Language, String> = emptyMap(),
val headline: Map<Language, String> = emptyMap(),
val content: Map<Language, String>? = emptyMap(),
@Id val id: String? = null,
val slug: Map<Language, String> = title.entries.map { (k, v) -> Pair(k, v.toSlug()) }.toMap()
) | apache-2.0 | 1e05869d1ecd5aec349769015f9a57be | 33.055556 | 101 | 0.678105 | 3.873418 | false | false | false | false |
zdary/intellij-community | plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalOptionsProvider.kt | 2 | 3798 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.terminal
import com.intellij.execution.configuration.EnvironmentVariablesData
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.xmlb.annotations.Property
import org.jetbrains.annotations.Nls
@State(name = "TerminalOptionsProvider", storages = [(Storage("terminal.xml"))])
class TerminalOptionsProvider : PersistentStateComponent<TerminalOptionsProvider.State> {
private var myState = State()
override fun getState(): State? {
return myState
}
override fun loadState(state: State) {
myState = state
}
fun closeSessionOnLogout(): Boolean {
return myState.myCloseSessionOnLogout
}
fun enableMouseReporting(): Boolean {
return myState.myReportMouse
}
fun audibleBell(): Boolean {
return myState.mySoundBell
}
var tabName: String
@Nls
get() : String = myState.myTabName ?: TerminalBundle.message("local.terminal.default.name")
set(@Nls tabName) {
myState.myTabName = tabName
}
fun overrideIdeShortcuts(): Boolean {
return myState.myOverrideIdeShortcuts
}
fun setOverrideIdeShortcuts(overrideIdeShortcuts: Boolean) {
myState.myOverrideIdeShortcuts = overrideIdeShortcuts
}
fun shellIntegration(): Boolean {
return myState.myShellIntegration
}
fun setShellIntegration(shellIntegration: Boolean) {
myState.myShellIntegration = shellIntegration
}
class State {
var myShellPath: String? = null
@Nls
var myTabName: String? = null
var myCloseSessionOnLogout: Boolean = true
var myReportMouse: Boolean = true
var mySoundBell: Boolean = true
var myCopyOnSelection: Boolean = SystemInfo.isLinux
var myPasteOnMiddleMouseButton: Boolean = true
var myOverrideIdeShortcuts: Boolean = true
var myShellIntegration: Boolean = true
var myHighlightHyperlinks: Boolean = true
@get:Property(surroundWithTag = false, flat = true)
var envDataOptions = EnvironmentVariablesDataOptions()
}
fun setCloseSessionOnLogout(closeSessionOnLogout: Boolean) {
myState.myCloseSessionOnLogout = closeSessionOnLogout
}
fun setReportMouse(reportMouse: Boolean) {
myState.myReportMouse = reportMouse
}
fun setSoundBell(soundBell: Boolean) {
myState.mySoundBell = soundBell
}
fun copyOnSelection(): Boolean {
return myState.myCopyOnSelection
}
fun setCopyOnSelection(copyOnSelection: Boolean) {
myState.myCopyOnSelection = copyOnSelection
}
fun pasteOnMiddleMouseButton(): Boolean {
return myState.myPasteOnMiddleMouseButton
}
fun setPasteOnMiddleMouseButton(pasteOnMiddleMouseButton: Boolean) {
myState.myPasteOnMiddleMouseButton = pasteOnMiddleMouseButton
}
fun highlightHyperlinks(): Boolean {
return myState.myHighlightHyperlinks
}
fun setHighlightHyperlinks(highlight: Boolean) {
myState.myHighlightHyperlinks = highlight
}
fun getEnvData(): EnvironmentVariablesData {
return myState.envDataOptions.get()
}
fun setEnvData(envData: EnvironmentVariablesData) {
myState.envDataOptions.set(envData)
}
// replace with property delegate when Kotlin 1.4 arrives (KT-8658)
var shellPath: String?
get() = myState.myShellPath
set(value) {
myState.myShellPath = value
}
companion object {
val instance: TerminalOptionsProvider
@JvmStatic
get() = ApplicationManager.getApplication().getService(TerminalOptionsProvider::class.java)
}
}
| apache-2.0 | 2eae1c52261cff2bb184cad9796a227c | 27.772727 | 140 | 0.754344 | 4.390751 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/repository/AccountRepo.kt | 1 | 2022 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright ยฉ 2022 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package repository
import androidx.lifecycle.ViewModelProvider
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import model.Account
import model.Tab
import model.toAccountType
import service.ContextService
import ui.AccountViewModel
import ui.MainApplication
class AccountRepo {
private val context = ContextService
// TODO: This a hacky temporary way, it should be AccountRepo, maybe broke BackupAgent
private val accountVm by lazy {
val app = context.requireApp() as MainApplication
ViewModelProvider(app).get(AccountViewModel::class.java)
}
private val writeAccount = MutableStateFlow<Account?>(null)
private val writePreviousAccount = MutableStateFlow<Account?>(null)
val accountHot = writeAccount.filterNotNull()
val previousAccountHot = writePreviousAccount
val accountIdHot = accountHot.map { it.id }.distinctUntilChanged()
val accountTypeHot = accountHot.map { it.type.toAccountType() }.distinctUntilChanged()
val activeTabHot by lazy { Repos.nav.activeTabHot }
fun start() {
//GlobalScope.launch { hackyAccount() }
onSettingsTab_refreshAccount()
}
fun hackyAccount() {
accountVm.account.observeForever {
val previous = writeAccount.value
writePreviousAccount.value = previous
writeAccount.value = it
}
}
fun onSettingsTab_refreshAccount() {
GlobalScope.launch {
activeTabHot.filter { it == Tab.Settings }
.debounce(1000)
.collect {
accountVm.refreshAccount()
}
}
}
} | mpl-2.0 | c7c1bcff4e4b324458e2e87375094dfc | 28.304348 | 90 | 0.691737 | 4.511161 | false | false | false | false |
baz8080/folkets_android | app/src/test/kotlin/com/mbcdev/folkets/WordTypeTests.kt | 1 | 11277 | package com.mbcdev.folkets
import android.content.Context
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
/**
* Tests for [WordType]
*
* Created by barry on 28/09/2016.
*/
class WordTypeTests {
// Null, junk, and empty value lookup tests
@Test
fun lookupEmptyRawTypeShouldReturnUnknown() {
val wordType = WordType.lookup("")
assertThat(wordType).isSameAs(WordType.UNKNOWN)
}
@Test
fun lookupWhitespaceRawTypeShouldReturnUnknown() {
val wordType = WordType.lookup(" ")
assertThat(wordType).isSameAs(WordType.UNKNOWN)
}
@Test
fun lookupNullRawTypeShouldReturnUnknown() {
val wordType = WordType.lookup(null)
assertThat(wordType).isSameAs(WordType.UNKNOWN)
}
@Test
fun lookupJunkRawTypeShouldReturnUnknown() {
val wordType = WordType.lookup("Gazorpazorpfield")
assertThat(wordType).isSameAs(WordType.UNKNOWN)
}
@Test
fun lookupPaddedRawTypeShouldReturnNoun() {
val wordType = WordType.lookup(" nn\t ")
assertThat(wordType).isSameAs(WordType.NOUN)
}
// Happy path tests
@Test
fun lookupRawTypeShouldReturnNoun() {
val wordType = WordType.lookup("nn")
assertThat(wordType).isSameAs(WordType.NOUN)
}
@Test
fun lookupRawTypeShouldReturnAdjective() {
val wordType = WordType.lookup("jj")
assertThat(wordType).isSameAs(WordType.ADJECTIVE)
}
@Test
fun lookupRawTypeShouldReturnPronoun() {
val wordType = WordType.lookup("pn")
assertThat(wordType).isSameAs(WordType.PRONOUN)
}
@Test
fun lookupRawTypeShouldReturnPronounDeterminer() {
val wordType = WordType.lookup("hp")
assertThat(wordType).isSameAs(WordType.PRONOUN_DETERMINER)
}
@Test
fun lookupRawTypeShouldReturnPronounPossessive() {
val wordType = WordType.lookup("ps")
assertThat(wordType).isSameAs(WordType.PRONOUN_POSSESSIVE)
}
@Test
fun lookupRawTypeShouldReturnProperNoun() {
val wordType = WordType.lookup("pm")
assertThat(wordType).isSameAs(WordType.PROPER_NOUN)
}
@Test
fun lookupRawTypeShouldReturnVerb() {
val wordType = WordType.lookup("vb")
assertThat(wordType).isSameAs(WordType.VERB)
}
@Test
fun lookupRawTypeShouldReturnAdverb() {
val wordType = WordType.lookup("ab")
assertThat(wordType).isSameAs(WordType.ADVERB)
}
@Test
fun lookupRawTypeShouldReturnPrefix() {
val wordType = WordType.lookup("prefix")
assertThat(wordType).isSameAs(WordType.PREFIX)
}
@Test
fun lookupRawTypeShouldReturnSuffix() {
val wordType = WordType.lookup("suffix")
assertThat(wordType).isSameAs(WordType.SUFFIX)
}
@Test
fun lookupRawTypeShouldReturnArticle() {
val wordType = WordType.lookup("article")
assertThat(wordType).isSameAs(WordType.ARTICLE)
}
@Test
fun lookupRawTypeShouldReturnAbbreviation() {
val wordType = WordType.lookup("abbrev")
assertThat(wordType).isSameAs(WordType.ABBREVIATION)
}
@Test
fun lookupRawTypeShouldReturnPreposition() {
val wordType = WordType.lookup("pp")
assertThat(wordType).isSameAs(WordType.PREPOSITION)
}
@Test
fun lookupRawTypeShouldReturnInterjection() {
val wordType = WordType.lookup("in")
assertThat(wordType).isSameAs(WordType.INTERJECTION)
}
@Test
fun lookupRawTypeShouldReturnCardinalNumber() {
val wordType = WordType.lookup("rg")
assertThat(wordType).isSameAs(WordType.CARDINAL_NUMBER)
}
@Test
fun lookupRawTypeShouldReturnConjunction() {
val wordType = WordType.lookup("kn")
assertThat(wordType).isSameAs(WordType.CONJUNCTION)
}
@Test
fun lookupRawTypeShouldReturnInfinitivalMarker() {
val wordType = WordType.lookup("ie")
assertThat(wordType).isSameAs(WordType.INFINITIVAL_MARKER)
}
@Test
fun lookupRawTypeShouldReturnSubordinatingConjunction() {
val wordType = WordType.lookup("sn")
assertThat(wordType).isSameAs(WordType.SUBORDINATING_CONJUNCTION)
}
@Test
fun lookupRawTypeShouldReturnAuxiliaryVerb() {
val wordType = WordType.lookup("hjรคlpverb")
assertThat(wordType).isSameAs(WordType.AUXILIARY_VERB)
}
@Test
fun lookupRawTypeShouldReturnOrdinalNumber() {
val wordType = WordType.lookup("ro")
assertThat(wordType).isSameAs(WordType.ORDINAL_NUMBER)
}
@Test
fun lookupRawTypeShouldReturnLatin() {
val wordType = WordType.lookup("latin")
assertThat(wordType).isSameAs(WordType.LATIN)
}
@Test
fun lookupRawTypeShouldReturnParticiple() {
val wordType = WordType.lookup("pc")
assertThat(wordType).isSameAs(WordType.PARTICIPLE)
}
@Test
fun lookupRawTypeShouldReturnUnknown() {
val wordType = WordType.lookup("")
assertThat(wordType).isSameAs(WordType.UNKNOWN)
}
// String resource tests
@Test
fun nounShouldHaveCorrectStringResourceId() {
assertThat(WordType.NOUN.textResourceId).isEqualTo(R.string.word_type_noun)
}
@Test
fun adjectiveShouldHaveCorrectStringResourceId() {
assertThat(WordType.ADJECTIVE.textResourceId).isEqualTo(R.string.word_type_adjective)
}
@Test
fun pronounShouldHaveCorrectStringResourceId() {
assertThat(WordType.PRONOUN.textResourceId).isEqualTo(R.string.word_type_pronoun)
}
@Test
fun pronounDeterminerShouldHaveCorrectStringResourceId() {
assertThat(WordType.PRONOUN_DETERMINER.textResourceId).isEqualTo(R.string.word_type_pronoun_determiner)
}
@Test
fun pronounPossessiveShouldHaveCorrectStringResourceId() {
assertThat(WordType.PRONOUN_POSSESSIVE.textResourceId).isEqualTo(R.string.word_type_pronoun_possessive)
}
@Test
fun properNounShouldHaveCorrectStringResourceId() {
assertThat(WordType.PROPER_NOUN.textResourceId).isEqualTo(R.string.word_type_proper_noun)
}
@Test
fun verbShouldHaveCorrectStringResourceId() {
assertThat(WordType.VERB.textResourceId).isEqualTo(R.string.word_type_verb)
}
@Test
fun adverbShouldHaveCorrectStringResourceId() {
assertThat(WordType.ADVERB.textResourceId).isEqualTo(R.string.word_type_adverb)
}
@Test
fun prefixShouldHaveCorrectStringResourceId() {
assertThat(WordType.PREFIX.textResourceId).isEqualTo(R.string.word_type_prefix)
}
@Test
fun suffixShouldHaveCorrectStringResourceId() {
assertThat(WordType.SUFFIX.textResourceId).isEqualTo(R.string.word_type_suffix)
}
@Test
fun articleShouldHaveCorrectStringResourceId() {
assertThat(WordType.ARTICLE.textResourceId).isEqualTo(R.string.word_type_article)
}
@Test
fun abbreviationShouldHaveCorrectStringResourceId() {
assertThat(WordType.ABBREVIATION.textResourceId).isEqualTo(R.string.word_type_abbreviation)
}
@Test
fun prepositionShouldHaveCorrectStringResourceId() {
assertThat(WordType.PREPOSITION.textResourceId).isEqualTo(R.string.word_type_preposition)
}
@Test
fun interjectionShouldHaveCorrectStringResourceId() {
assertThat(WordType.INTERJECTION.textResourceId).isEqualTo(R.string.word_type_interjection)
}
@Test
fun cardinalNumberShouldHaveCorrectStringResourceId() {
assertThat(WordType.CARDINAL_NUMBER.textResourceId).isEqualTo(R.string.word_type_cardinal_number)
}
@Test
fun conjunctionShouldHaveCorrectStringResourceId() {
assertThat(WordType.CONJUNCTION.textResourceId).isEqualTo(R.string.word_type_conjunction)
}
@Test
fun infinitivalMarkerShouldHaveCorrectStringResourceId() {
assertThat(WordType.INFINITIVAL_MARKER.textResourceId).isEqualTo(R.string.word_type_infinitivial)
}
@Test
fun subordinatingConjunctionShouldHaveCorrectStringResourceId() {
assertThat(WordType.SUBORDINATING_CONJUNCTION.textResourceId).isEqualTo(R.string.word_type_subordinating_conjunction)
}
@Test
fun auxiliaryVerbShouldHaveCorrectStringResourceId() {
assertThat(WordType.AUXILIARY_VERB.textResourceId).isEqualTo(R.string.word_type_auxiliary_verb)
}
@Test
fun ordinalNumberShouldHaveCorrectStringResourceId() {
assertThat(WordType.ORDINAL_NUMBER.textResourceId).isEqualTo(R.string.word_type_ordinal)
}
@Test
fun latinShouldHaveCorrectStringResourceId() {
assertThat(WordType.LATIN.textResourceId).isEqualTo(R.string.word_type_latin)
}
@Test
fun participleShouldHaveCorrectStringResourceId() {
assertThat(WordType.PARTICIPLE.textResourceId).isEqualTo(R.string.word_type_participle)
}
@Test
fun unknownShouldHaveCorrectStringResourceId() {
assertThat(WordType.UNKNOWN.textResourceId).isEqualTo(R.string.word_type_unknown)
}
// formatting tests
@Test
fun formatWordTypesShouldBeNullSafeForContext() {
val formattedTypes = WordType.formatWordTypesForDisplay(null, listOf(WordType.NOUN))
assertThat(formattedTypes).isNotNull()
assertThat(formattedTypes).isEmpty()
}
@Test
fun formatWordTypesShouldBeNullSafeForWordTypes() {
val formattedTypes = WordType.formatWordTypesForDisplay(mockedContext(), null)
assertThat(formattedTypes).isNotNull()
assertThat(formattedTypes).isEmpty()
}
@Test
fun formatWordTypesShouldBeNullSafeWhenAllArgumentsAreNull() {
val formattedTypes = WordType.formatWordTypesForDisplay(null, null)
assertThat(formattedTypes).isNotNull()
assertThat(formattedTypes).isEmpty()
}
@Test
fun oneWordShouldBeFormattedCorrectly() {
val formattedTypes =
WordType.formatWordTypesForDisplay(mockedContext(), listOf(WordType.NOUN))
assertThat(formattedTypes).isNotNull()
assertThat(formattedTypes).isEqualTo("Noun")
}
@Test
fun twoWordsShouldBeFormattedCorrectly() {
val formattedTypes =
WordType.formatWordTypesForDisplay(
mockedContext(), listOf(WordType.NOUN, WordType.PRONOUN))
assertThat(formattedTypes).isNotNull()
assertThat(formattedTypes).isEqualTo("Noun, Pronoun")
}
@Test
fun threeWordsShouldBeFormattedCorrectly() {
val formattedTypes =
WordType.formatWordTypesForDisplay(
mockedContext(), listOf(WordType.NOUN, WordType.PRONOUN, WordType.ADVERB))
assertThat(formattedTypes).isNotNull()
assertThat(formattedTypes).isEqualTo("Noun, Pronoun, Adverb")
}
fun mockedContext(): Context {
val mockedContext = mock(Context::class.java)
`when`(mockedContext.getString(R.string.word_type_noun)).thenReturn("Noun")
`when`(mockedContext.getString(R.string.word_type_pronoun)).thenReturn("Pronoun")
`when`(mockedContext.getString(R.string.word_type_adverb)).thenReturn("Adverb")
return mockedContext
}
} | apache-2.0 | 0b3e3487e49e37b9d3117a7e3b7a013f | 29.72752 | 125 | 0.700337 | 4.231144 | false | true | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/run/target/PySdkTargetPaths.kt | 2 | 5556 | // 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.
@file:JvmName("PySdkTargetPaths")
package com.jetbrains.python.run.target
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.value.TargetEnvironmentFunction
import com.intellij.execution.target.value.constant
import com.intellij.execution.target.value.getTargetEnvironmentValueForLocalPath
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.remote.RemoteMappingsManager
import com.intellij.remote.RemoteSdkAdditionalData
import com.jetbrains.python.console.PyConsoleOptions
import com.jetbrains.python.console.PyConsoleOptions.PyConsoleSettings
import com.jetbrains.python.console.PydevConsoleRunner
import com.jetbrains.python.remote.PyRemotePathMapper
import com.jetbrains.python.remote.PythonRemoteInterpreterManager
import com.jetbrains.python.remote.PythonRemoteInterpreterManager.appendBasicMappings
import com.jetbrains.python.target.PyTargetAwareAdditionalData
/**
* @param pathMapper corresponds to the path mappings specified in the run configuration
* @throws IllegalArgumentException if [localPath] cannot be found neither in SDK additional data nor within the registered uploads in the
* request
*/
fun getTargetPathForPythonScriptExecution(targetEnvironmentRequest: TargetEnvironmentRequest,
project: Project,
sdk: Sdk?,
pathMapper: PyRemotePathMapper?,
localPath: String): TargetEnvironmentFunction<String> {
val initialPathMapper = pathMapper ?: PyRemotePathMapper()
val targetPath = initialPathMapper.extendPythonSdkPathMapper(project, sdk).convertToRemoteOrNull(localPath)
return targetPath?.let { constant(it) } ?: targetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(localPath)
}
private fun PyRemotePathMapper.extendPythonSdkPathMapper(project: Project, sdk: Sdk?): PyRemotePathMapper {
val pathMapper = PyRemotePathMapper.cloneMapper(this)
val sdkAdditionalData = sdk?.sdkAdditionalData as? RemoteSdkAdditionalData<*>
if (sdkAdditionalData != null) {
appendBasicMappings(project, pathMapper, sdkAdditionalData)
}
return pathMapper
}
/**
* Returns the function that resolves the given [localPath] to the path on the target by the target environment. The resolution happens in
* the following order:
* 1. Using the given [pathMapper]. This mapper usually encapsulates the path mappings declared by user in the run configuration.
* 2. Using the project-wide path mappings settings for Python Console.
* 3. Using the path mappings declared in the given [sdk] including the mappings for PyCharm helpers.
* 4. Using the uploads declared in the target environment.
*
* @param pathMapper corresponds to the path mappings specified in the run configuration
* @throws IllegalArgumentException if [localPath] cannot be found neither in SDK additional data nor within the registered uploads in the
* request
*/
fun getTargetPathForPythonConsoleExecution(targetEnvironmentRequest: TargetEnvironmentRequest,
project: Project,
sdk: Sdk?,
pathMapper: PyRemotePathMapper?,
localPath: String): TargetEnvironmentFunction<String> {
val targetPath = pathMapper?.convertToRemoteOrNull(localPath)
?: getPythonConsolePathMapper(project, sdk)?.convertToRemoteOrNull(localPath)
return targetPath?.let { constant(it) } ?: targetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(localPath)
}
/**
* Note that the returned mapper includes the path mappings collected by the execution of [appendBasicMappings].
*/
private fun getPythonConsolePathMapper(project: Project, sdk: Sdk?): PyRemotePathMapper? =
PydevConsoleRunner.getPathMapper(project, sdk, PyConsoleOptions.getInstance(project).pythonConsoleSettings)
private fun PyRemotePathMapper.convertToRemoteOrNull(localPath: String): String? =
takeIf { it.canReplaceLocal(localPath) }?.convertToRemote(localPath)
fun getPathMapper(project: Project, consoleSettings: PyConsoleSettings, data: PyTargetAwareAdditionalData): PyRemotePathMapper {
val remotePathMapper = appendBasicMappings(project, null, data)
consoleSettings.mappingSettings?.let { mappingSettings ->
remotePathMapper.addAll(mappingSettings.pathMappings, PyRemotePathMapper.PyPathMappingType.USER_DEFINED)
}
return remotePathMapper
}
private fun appendBasicMappings(project: Project?,
pathMapper: PyRemotePathMapper?,
data: PyTargetAwareAdditionalData): PyRemotePathMapper {
val newPathMapper = PyRemotePathMapper.cloneMapper(pathMapper)
PythonRemoteInterpreterManager.addHelpersMapping(data, newPathMapper)
newPathMapper.addAll(data.pathMappings.pathMappings, PyRemotePathMapper.PyPathMappingType.SYS_PATH)
if (project != null) {
val mappings = RemoteMappingsManager.getInstance(project).getForServer(PythonRemoteInterpreterManager.PYTHON_PREFIX, data.sdkId)
if (mappings != null) {
newPathMapper.addAll(mappings.settings, PyRemotePathMapper.PyPathMappingType.USER_DEFINED)
}
}
return newPathMapper
} | apache-2.0 | ba346a971f8e2157db4c66f96e62c3d3 | 55.704082 | 140 | 0.75252 | 5.383721 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GiftGemsActivity.kt | 1 | 5834 | package com.habitrpg.android.habitica.ui.activities
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.navigation.navArgs
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.events.ConsumablePurchasedEvent
import com.habitrpg.android.habitica.extensions.addOkButton
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.PurchaseHandler
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.proxy.CrashlyticsProxy
import com.habitrpg.android.habitica.ui.fragments.purchases.GiftBalanceGemsFragment
import com.habitrpg.android.habitica.ui.fragments.purchases.GiftPurchaseGemsFragment
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.Subscribe
import javax.inject.Inject
class GiftGemsActivity : BaseActivity() {
@Inject
lateinit var crashlyticsProxy: CrashlyticsProxy
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var appConfigManager: AppConfigManager
private var purchaseHandler: PurchaseHandler? = null
private val toolbar: Toolbar by bindView(R.id.toolbar)
internal val tabLayout: TabLayout by bindView(R.id.tab_layout)
internal val viewPager: ViewPager by bindView(R.id.viewPager)
private var giftedUsername: String? = null
private var giftedUserID: String? = null
private var purchaseFragment: GiftPurchaseGemsFragment? = null
private var balanceFragment: GiftBalanceGemsFragment? = null
override fun getLayoutResId(): Int {
return R.layout.activity_gift_gems
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitle(R.string.gift_gems)
setSupportActionBar(toolbar)
purchaseHandler = PurchaseHandler(this, crashlyticsProxy)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
giftedUserID = intent.getStringExtra("userID")
giftedUsername = intent.getStringExtra("username")
if (giftedUserID == null && giftedUsername == null) {
giftedUserID = navArgs<GiftGemsActivityArgs>().value.userID
giftedUsername = navArgs<GiftGemsActivityArgs>().value.username
}
setViewPagerAdapter()
compositeSubscription.add(socialRepository.getMember(giftedUsername ?: giftedUserID).firstElement().subscribe(Consumer {
giftedUserID = it.id
giftedUsername = it.username
purchaseFragment?.giftedMember = it
balanceFragment?.giftedMember = it
}, RxErrorHandler.handleEmptyError()))
}
override fun onStart() {
super.onStart()
purchaseHandler?.startListening()
}
override fun onStop() {
purchaseHandler?.stopListening()
super.onStop()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
purchaseHandler?.onResult(requestCode, resultCode, data)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
}
return super.onOptionsItemSelected(item)
}
private fun setViewPagerAdapter() {
val fragmentManager = supportFragmentManager
viewPager.adapter = object : FragmentPagerAdapter(fragmentManager) {
override fun getItem(position: Int): Fragment {
return if (position == 0) {
val fragment = GiftPurchaseGemsFragment()
fragment.setPurchaseHandler(purchaseHandler)
fragment.setupCheckout()
purchaseFragment = fragment
fragment
} else {
val fragment = GiftBalanceGemsFragment()
fragment.onCompleted = {
displayConfirmationDialog()
}
balanceFragment = fragment
fragment
}
}
override fun getCount(): Int {
return 2
}
override fun getPageTitle(position: Int): CharSequence? {
return when (position) {
0 -> getString(R.string.purchase)
1 -> getString(R.string.from_balance)
else -> ""
}
}
}
tabLayout.setupWithViewPager(viewPager)
}
@Subscribe
fun onConsumablePurchased(event: ConsumablePurchasedEvent) {
purchaseHandler?.consumePurchase(event.purchase)
runOnUiThread {
displayConfirmationDialog()
}
}
private fun displayConfirmationDialog() {
val message = getString(R.string.gift_confirmation_text_gems, giftedUsername)
val alert = HabiticaAlertDialog(this)
alert.setTitle(R.string.gift_confirmation_title)
alert.setMessage(message)
alert.addOkButton { dialog, _ ->
dialog.dismiss()
finish()
}
alert.enqueue()
}
} | gpl-3.0 | f58a250d566e85623243b141fe742fb2 | 34.150602 | 128 | 0.67878 | 5.208929 | false | false | false | false |
MarcinMoskala/ActivityStarter | activitystarter-compiler/src/main/java/activitystarter/compiler/processing/GetConvertersTypeMirrorsFunc.kt | 1 | 731 | package activitystarter.compiler.processing
import activitystarter.ActivityStarterConfig
import javax.lang.model.element.AnnotationValue
import javax.lang.model.element.Element
import javax.lang.model.type.TypeMirror
fun getConvertersTypeMirrors(element: Element): List<TypeMirror> {
val convertersValue: AnnotationValue = element.annotationMirrors
.filter { it.annotationType.toString() == ActivityStarterConfig::class.java.name }
.flatMap { it.elementValues.toList() }
.firstOrNull { (k, _) -> k.simpleName.toString() == "converters" }?.second ?: return emptyList()
val valueList = convertersValue.value as List<AnnotationValue>
return valueList.map { it.value as TypeMirror }
}
| apache-2.0 | 06048222746766e30cf9e315b0dec653 | 47.733333 | 108 | 0.749658 | 4.540373 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/test/org/jetbrains/kotlin/jps/build/RelocatableJpsCachesTest.kt | 1 | 5889 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.jps.build
import com.intellij.util.ThrowableRunnable
import org.jetbrains.jps.builders.*
import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor
import org.jetbrains.jps.cmdline.ProjectDescriptor
import org.jetbrains.jps.incremental.ModuleBuildTarget
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.incremental.KOTLIN_CACHE_DIRECTORY_NAME
import org.jetbrains.kotlin.incremental.testingUtils.assertEqualDirectories
import org.jetbrains.kotlin.jps.build.fixtures.EnableICFixture
import org.jetbrains.kotlin.jps.incremental.KotlinDataContainerTarget
import java.io.File
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.createTempDirectory
import kotlin.reflect.KFunction1
class RelocatableJpsCachesTest : BaseKotlinJpsBuildTestCase() {
private val enableICFixture = EnableICFixture()
private lateinit var workingDir: File
@OptIn(ExperimentalPathApi::class)
override fun setUp() {
super.setUp()
enableICFixture.setUp()
workingDir = createTempDirectory("RelocatableJpsCachesTest-" + getTestName(false)).toFile()
}
override fun tearDown() {
runAll(
ThrowableRunnable { workingDir.deleteRecursively() },
ThrowableRunnable { enableICFixture.tearDown() },
ThrowableRunnable { super.tearDown() }
)
}
fun testRelocatableCaches() {
buildTwiceAndCompare(RelocatableCacheTestCase::testRelocatableCaches)
}
private fun buildTwiceAndCompare(testMethod: KFunction1<RelocatableCacheTestCase, Unit>) {
val test1WorkingDir = workingDir.resolve("test1")
val test1KotlinCachesDir = workingDir.resolve("test1KotlinCaches")
val test2WorkingDir = workingDir.resolve("test2")
val test2KotlinCachesDir = workingDir.resolve("test2KotlinCaches")
runTestAndCopyKotlinCaches(test1WorkingDir, test1KotlinCachesDir, testMethod)
runTestAndCopyKotlinCaches(test2WorkingDir, test2KotlinCachesDir, testMethod)
assertEqualDirectories(test1KotlinCachesDir, test2KotlinCachesDir, forgiveExtraFiles = false)
}
private fun runTestAndCopyKotlinCaches(
projectWorkingDir: File,
dirToCopyKotlinCaches: File,
testMethod: KFunction1<RelocatableCacheTestCase, Unit>
) {
val testCase = object : RelocatableCacheTestCase(
projectWorkingDir = projectWorkingDir,
dirToCopyKotlinCaches = dirToCopyKotlinCaches
) {
override fun getName(): String = testMethod.name
}
testCase.exposedPrivateApi.setUp()
try {
testMethod.call(testCase)
} finally {
testCase.exposedPrivateApi.tearDown()
}
}
}
// the class should not be executed directly (hence it's abstract)
abstract class RelocatableCacheTestCase(
private val projectWorkingDir: File,
private val dirToCopyKotlinCaches: File
) : KotlinJpsBuildTestBase() {
val exposedPrivateApi = ExposedPrivateApi()
fun testRelocatableCaches() {
initProject(LibraryDependency.JVM_FULL_RUNTIME)
buildAllModules().assertSuccessful()
assertFilesExistInOutput(
myProject.modules.single(),
"MainKt.class", "Foo.class", "FooChild.class", "utils/Utils.class"
)
}
override fun copyTestDataToTmpDir(testDataDir: File): File {
testDataDir.copyRecursively(projectWorkingDir)
return projectWorkingDir
}
override fun doBuild(descriptor: ProjectDescriptor, scopeBuilder: CompileScopeTestBuilder?): BuildResult =
super.doBuild(descriptor, scopeBuilder).also {
copyKotlinCaches(descriptor)
}
private fun copyKotlinCaches(descriptor: ProjectDescriptor) {
val kotlinDataPaths = HashSet<File>()
val dataPaths = descriptor.dataManager.dataPaths
kotlinDataPaths.add(dataPaths.getTargetDataRoot(KotlinDataContainerTarget))
for (target in descriptor.buildTargetIndex.allTargets) {
if (!target.isKotlinTarget(descriptor)) continue
val targetDataRoot = descriptor.dataManager.dataPaths.getTargetDataRoot(target)
val kotlinDataRoot = targetDataRoot.resolve(KOTLIN_CACHE_DIRECTORY_NAME)
assert(kotlinDataRoot.isDirectory) { "Kotlin data root '$kotlinDataRoot' is not a directory" }
kotlinDataPaths.add(kotlinDataRoot)
}
dirToCopyKotlinCaches.deleteRecursively()
val originalStorageRoot = descriptor.dataManager.dataPaths.dataStorageRoot
for (kotlinCacheRoot in kotlinDataPaths) {
val relativePath = kotlinCacheRoot.relativeTo(originalStorageRoot).path
val targetDir = dirToCopyKotlinCaches.resolve(relativePath)
targetDir.parentFile.mkdirs()
kotlinCacheRoot.copyRecursively(targetDir)
}
}
private fun BuildTarget<*>.isKotlinTarget(descriptor: ProjectDescriptor): Boolean {
fun JavaSourceRootDescriptor.containsKotlinSources() = root.walk().any { it.isKotlinSourceFile }
if (this !is ModuleBuildTarget) return false
val rootDescriptors = computeRootDescriptors(
descriptor.model,
descriptor.moduleExcludeIndex,
descriptor.ignoredFileIndex,
descriptor.dataManager.dataPaths
)
return rootDescriptors.any { it is JavaSourceRootDescriptor && it.containsKotlinSources() }
}
// the famous Public Morozov pattern
inner class ExposedPrivateApi {
fun setUp() {
[email protected]()
}
fun tearDown() {
[email protected]()
}
}
} | apache-2.0 | f901967c64a9be498f907aaee9817ef5 | 37.75 | 158 | 0.715402 | 4.936295 | false | true | false | false |
siosio/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/HtmlEditorPane.kt | 1 | 4388 | package com.jetbrains.packagesearch.intellij.plugin.ui.util
import com.intellij.ide.ui.AntialiasingType
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.HyperlinkAdapter
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBHtmlEditorKit
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.Nls
import javax.swing.JEditorPane
import javax.swing.SizeRequirements
import javax.swing.event.HyperlinkEvent
import javax.swing.event.HyperlinkListener
import javax.swing.text.DefaultCaret
import javax.swing.text.Element
import javax.swing.text.ParagraphView
import javax.swing.text.View
import kotlin.math.max
@Suppress("LeakingThis")
internal open class HtmlEditorPane : JEditorPane() {
init {
@Suppress("MagicNumber") // UI code
editorKit = object : JBHtmlEditorKit(false) {
override fun getViewFactory() = HtmlEditorViewFactory()
}.apply {
//language=CSS
styleSheet.addRule(
"""
|ul {padding-left: ${8.scaled()}px;}
""".trimMargin()
)
//language=CSS
styleSheet.addRule(
"""
|a{color: ${JBUI.CurrentTheme.Link.Foreground.ENABLED.toCssHexColorString()};}
|a:link{color: ${JBUI.CurrentTheme.Link.Foreground.ENABLED.toCssHexColorString()};}
|a:visited{color: ${JBUI.CurrentTheme.Link.Foreground.VISITED.toCssHexColorString()};}
|a:active{color: ${JBUI.CurrentTheme.Link.Foreground.PRESSED.toCssHexColorString()};}
|a:hover{color: ${JBUI.CurrentTheme.Link.Foreground.HOVERED.toCssHexColorString()};}
""".trimMargin()
)
}
highlighter = null
isEditable = false
isOpaque = false
addHyperlinkListener(ProxyingHyperlinkListener(::onLinkClicked))
margin = JBUI.emptyInsets()
GraphicsUtil.setAntialiasingType(this, AntialiasingType.getAAHintForSwingComponent())
val caret = caret as DefaultCaret
caret.updatePolicy = DefaultCaret.NEVER_UPDATE
}
protected fun clearBody() {
setBody(emptyList())
}
fun setBody(chunks: Collection<HtmlChunk>) {
text = if (chunks.isEmpty()) {
""
} else {
createBodyHtmlChunk()
.children(*chunks.toTypedArray())
.toString()
}
}
fun setBodyText(@Nls text: String) {
this.text = createBodyHtmlChunk()
.addText(text)
.toString()
}
private fun createBodyHtmlChunk(): HtmlChunk.Element {
val style = buildString {
append("color: ")
append(foreground.toCssHexColorString())
append("; font-size: ")
append(font.size)
append("pt;")
}
return HtmlChunk.body().style(style)
}
protected open fun onLinkClicked(anchor: String) {
// No-op by default
}
final override fun addHyperlinkListener(listener: HyperlinkListener?) {
super.addHyperlinkListener(listener)
}
final override fun removeHyperlinkListener(listener: HyperlinkListener?) {
super.removeHyperlinkListener(listener)
}
private class HtmlEditorViewFactory : JBHtmlEditorKit.JBHtmlFactory() {
override fun create(elem: Element): View {
val view = super.create(elem)
if (view is ParagraphView) {
return SizeAdjustedParagraphView(elem)
}
return view
}
}
private class SizeAdjustedParagraphView(elem: Element) : ParagraphView(elem) {
@Suppress("MagicNumber") // UI code
override fun calculateMinorAxisRequirements(axis: Int, sizeRequirements: SizeRequirements?) =
(sizeRequirements ?: SizeRequirements()).apply {
minimum = layoutPool.getMinimumSpan(axis).toInt()
preferred = max(minimum, layoutPool.getPreferredSpan(axis).toInt())
maximum = Integer.MAX_VALUE
alignment = 0.5f
}
}
private class ProxyingHyperlinkListener(private val callback: (anchor: String) -> Unit) : HyperlinkAdapter() {
override fun hyperlinkActivated(e: HyperlinkEvent) {
callback(e.description)
}
}
}
| apache-2.0 | 5bda019acaf03d65240854b79aa14c9a | 32.753846 | 114 | 0.626253 | 4.795628 | false | false | false | false |
idea4bsd/idea4bsd | platform/script-debugger/backend/src/BreakpointManager.kt | 15 | 2908 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.openapi.util.Ref
import com.intellij.util.Url
import org.jetbrains.concurrency.Promise
import java.util.*
interface BreakpointManager {
enum class MUTE_MODE {
ALL,
ONE,
NONE
}
val breakpoints: Iterable<Breakpoint>
val regExpBreakpointSupported: Boolean
get() = false
fun setBreakpoint(target: BreakpointTarget,
line: Int,
column: Int = Breakpoint.EMPTY_VALUE,
url: Url? = null,
condition: String? = null,
ignoreCount: Int = Breakpoint.EMPTY_VALUE,
enabled: Boolean = true,
promiseRef: Ref<Promise<out Breakpoint>>? = null): Breakpoint
fun remove(breakpoint: Breakpoint): Promise<*>
/**
* Supports targets that refer to function text in form of function-returning
* JavaScript expression.
* E.g. you can set a breakpoint on the 5th line of user method addressed as
* 'PropertiesDialog.prototype.loadData'.
* Expression is calculated immediately and never recalculated again.
*/
val functionSupport: ((expression: String) -> BreakpointTarget)?
get() = null
// Could be called multiple times for breakpoint
fun addBreakpointListener(listener: BreakpointListener)
fun removeAll(): Promise<*>
fun getMuteMode() = BreakpointManager.MUTE_MODE.ONE
/**
* Flushes the breakpoint parameter changes (set* methods) into the browser
* and invokes the callback once the operation has finished. This method must
* be called for the set* method invocations to take effect.
*/
fun flush(breakpoint: Breakpoint): Promise<*>
/**
* Asynchronously enables or disables all breakpoints on remote. 'Enabled' means that
* breakpoints behave as normal, 'disabled' means that VM doesn't stop on breakpoints.
* It doesn't update individual properties of [Breakpoint]s. Method call
* with a null value and not null callback simply returns current value.
*/
fun enableBreakpoints(enabled: Boolean): Promise<*>
}
interface BreakpointListener : EventListener {
fun resolved(breakpoint: Breakpoint)
fun errorOccurred(breakpoint: Breakpoint, errorMessage: String?)
fun nonProvisionalBreakpointRemoved(breakpoint: Breakpoint) {
}
} | apache-2.0 | 76aa29969eac8a655294bf6c58567c0c | 32.436782 | 88 | 0.706327 | 4.637959 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/export/sheet/ExternalFolderSyncBottomSheet.kt | 1 | 4370 | package com.maubis.scarlet.base.export.sheet
import android.app.Dialog
import android.graphics.Typeface
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.widget.Text
import com.facebook.yoga.YogaEdge
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTypeface
import com.maubis.scarlet.base.export.support.ExternalFolderSync
import com.maubis.scarlet.base.export.support.sExternalFolderSync
import com.maubis.scarlet.base.export.support.sFolderSyncBackupLocked
import com.maubis.scarlet.base.export.support.sFolderSyncPath
import com.maubis.scarlet.base.support.sheets.LithoBottomSheet
import com.maubis.scarlet.base.support.sheets.LithoOptionsItem
import com.maubis.scarlet.base.support.sheets.OptionItemLayout
import com.maubis.scarlet.base.support.sheets.getLithoBottomSheetTitle
import com.maubis.scarlet.base.support.specs.BottomSheetBar
import com.maubis.scarlet.base.support.specs.separatorSpec
import com.maubis.scarlet.base.support.ui.ThemeColorType
class ExternalFolderSyncBottomSheet : LithoBottomSheet() {
override fun getComponent(componentContext: ComponentContext, dialog: Dialog): Component {
val component = Column.create(componentContext)
.widthPercent(100f)
.paddingDip(YogaEdge.VERTICAL, 8f)
.child(
getLithoBottomSheetTitle(componentContext)
.textRes(R.string.import_export_layout_folder_sync_title)
.paddingDip(YogaEdge.HORIZONTAL, 20f)
.marginDip(YogaEdge.HORIZONTAL, 0f))
.child(
Text.create(componentContext)
.textSizeRes(R.dimen.font_size_large)
.typeface(sAppTypeface.text())
.textRes(R.string.import_export_layout_folder_sync_description)
.paddingDip(YogaEdge.HORIZONTAL, 20f)
.textColor(sAppTheme.get(ThemeColorType.TERTIARY_TEXT)))
.child(separatorSpec(componentContext).alpha(0.5f))
.child(
Text.create(componentContext)
.textSizeRes(R.dimen.font_size_xlarge)
.typeface(sAppTypeface.title())
.textRes(R.string.import_export_layout_folder_sync_folder)
.paddingDip(YogaEdge.HORIZONTAL, 20f)
.textColor(sAppTheme.get(ThemeColorType.SECTION_HEADER)))
.child(
Text.create(componentContext)
.textSizeRes(R.dimen.font_size_large)
.text(sFolderSyncPath)
.typeface(Typeface.MONOSPACE)
.paddingDip(YogaEdge.HORIZONTAL, 20f)
.paddingDip(YogaEdge.VERTICAL, 8f)
.textColor(sAppTheme.get(ThemeColorType.TERTIARY_TEXT)))
.child(separatorSpec(componentContext).alpha(0.5f))
getOptions().forEach {
if (it.visible) {
component.child(OptionItemLayout.create(componentContext)
.option(it)
.onClick {
it.listener()
reset(componentContext.androidContext, dialog)
})
}
}
component.child(BottomSheetBar.create(componentContext)
.primaryActionRes(
if (sExternalFolderSync) R.string.import_export_layout_folder_sync_disable else R.string.import_export_layout_folder_sync_enable)
.isActionNegative(sExternalFolderSync)
.onPrimaryClick {
sExternalFolderSync = !sExternalFolderSync
ExternalFolderSync.enable(componentContext.androidContext, sExternalFolderSync)
reset(componentContext.androidContext, dialog)
}
.paddingDip(YogaEdge.HORIZONTAL, 20f)
.paddingDip(YogaEdge.VERTICAL, 8f))
return component.build()
}
fun getOptions(): List<LithoOptionsItem> {
val options = ArrayList<LithoOptionsItem>()
options.add(
LithoOptionsItem(
title = R.string.import_export_locked,
subtitle = R.string.import_export_locked_details,
icon = R.drawable.ic_action_lock,
listener = { sFolderSyncBackupLocked = !sFolderSyncBackupLocked },
isSelectable = true,
selected = sFolderSyncBackupLocked
))
return options
}
} | gpl-3.0 | 4c358b337766be750453536cb59a0e66 | 42.71 | 153 | 0.68833 | 4.35259 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/support/utils/ExceptionUtils.kt | 1 | 5181 | package com.maubis.scarlet.base.support.utils
import android.os.SystemClock
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.github.bijoysingh.starter.util.DateFormatter
import com.maubis.scarlet.base.BuildConfig
import com.maubis.scarlet.base.config.ApplicationBase.Companion.instance
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppPreferences
import com.maubis.scarlet.base.core.format.Format
import com.maubis.scarlet.base.core.format.FormatBuilder
import com.maubis.scarlet.base.core.format.FormatType
import com.maubis.scarlet.base.core.note.NoteBuilder
import com.maubis.scarlet.base.core.note.getFormats
import com.maubis.scarlet.base.core.note.isUnsaved
import com.maubis.scarlet.base.main.sheets.ExceptionBottomSheet
import com.maubis.scarlet.base.note.unsafeSave_INTERNAL_USE_ONLY
import com.maubis.scarlet.base.support.sheets.openSheet
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
const val KEY_INTERNAL_LOG_TRACES_TO_NOTE = "internal_log_traces_to_note"
var sInternalLogTracesToNote: Boolean
get() = sAppPreferences.get(KEY_INTERNAL_LOG_TRACES_TO_NOTE, false)
set(value) = sAppPreferences.put(KEY_INTERNAL_LOG_TRACES_TO_NOTE, value)
const val KEY_INTERNAL_SHOW_TRACES_IN_SHEET = "internal_show_traces_in_sheet"
var sInternalShowTracesInSheet: Boolean
get() = sAppPreferences.get(KEY_INTERNAL_SHOW_TRACES_IN_SHEET, false)
set(value) = sAppPreferences.put(KEY_INTERNAL_SHOW_TRACES_IN_SHEET, value)
const val KEY_INTERNAL_THROW_ON_EXCEPTION = "internal_throw_on_exception"
var sInternalThrowOnException: Boolean
get() = sAppPreferences.get(KEY_INTERNAL_THROW_ON_EXCEPTION, false)
set(value) = sAppPreferences.put(KEY_INTERNAL_THROW_ON_EXCEPTION, value)
const val KEY_INTERNAL_THROWN_EXCEPTION_COUNT = "internal_thrown_exception_count"
var sInternalThrownExceptionCount: Int
get() = sAppPreferences.get(KEY_INTERNAL_THROWN_EXCEPTION_COUNT, 0)
set(value) = sAppPreferences.put(KEY_INTERNAL_THROWN_EXCEPTION_COUNT, value)
/**
* Throws in debug builds and stores the log trace to a fixed note in case of 'internal debug mode'.
*/
fun maybeThrow(activity: AppCompatActivity, thrownException: Exception) {
if (sInternalShowTracesInSheet) {
openSheet(activity, ExceptionBottomSheet().apply { this.exception = thrownException })
}
maybeThrow(thrownException)
}
/**
* Throws in debug builds and stores the log trace to a fixed note in case of 'internal debug mode'.
*/
fun maybeThrow(exception: Exception) {
if (sInternalLogTracesToNote) {
storeToDebugNote(Log.getStackTraceString(exception))
}
if (sInternalThrowOnException) {
sInternalThrownExceptionCount += 1
if (sInternalThrownExceptionCount <= 5) {
GlobalScope.launch {
SystemClock.sleep(1000)
throw exception
}
}
sInternalThrownExceptionCount = 0
sInternalThrowOnException = false
}
if (BuildConfig.DEBUG) {
Log.e("Scarlet", "Exception Thrown and Recovered", exception)
}
}
/**
* Throws in debug builds and stores the log trace to a fixed note in case of 'internal debug mode'.
*/
fun maybeThrow(message: String) {
maybeThrow(IllegalStateException(message))
}
/**
* Throws in debug builds and stores the log trace to a fixed note in case of 'internal debug mode'.
* Else returns the provided value
*/
fun <DataType> throwOrReturn(message: String, result: DataType): DataType {
return throwOrReturn(IllegalStateException(message), result)
}
/**
* Throws in debug builds and stores the log trace to a fixed note in case of 'internal debug mode'.
* Else returns the provided value
*/
fun <DataType> throwOrReturn(exception: Exception, result: DataType): DataType {
maybeThrow(exception)
return result
}
private fun storeToDebugNote(trace: String) {
GlobalScope.launch {
storeToDebugNoteSync(trace)
}
}
const val EXCEPTION_NOTE_KEY = "debug-note"
const val EXCEPTION_NOTE_NUM_DATA_PER_EXCEPTION = 4
const val EXCEPTION_NOTE_MAX_EXCEPTIONS = 20
@Synchronized
private fun storeToDebugNoteSync(trace: String) {
val note = instance.notesDatabase().getByUUID(EXCEPTION_NOTE_KEY)
?: NoteBuilder().emptyNote().apply {
uuid = EXCEPTION_NOTE_KEY
disableBackup = true
}
val initialFormats = note.getFormats().toMutableList()
if (note.isUnsaved() || initialFormats.isEmpty()) {
initialFormats.add(Format(FormatType.HEADING, "Note Exceptions"))
}
val additionalFormats = emptyList<Format>().toMutableList()
additionalFormats.add(Format(FormatType.SUB_HEADING, "Exception"))
additionalFormats.add(
Format(
FormatType.QUOTE,
"Throw at ${DateFormatter.getDate(System.currentTimeMillis())}"))
additionalFormats.add(
Format(
FormatType.CODE,
trace))
additionalFormats.add(Format(FormatType.SEPARATOR))
val maxFormatCount = 1 + EXCEPTION_NOTE_MAX_EXCEPTIONS * EXCEPTION_NOTE_NUM_DATA_PER_EXCEPTION
if (initialFormats.size > maxFormatCount) {
initialFormats.subList(0, maxFormatCount)
}
initialFormats.addAll(1, additionalFormats)
note.description = FormatBuilder().getDescription(initialFormats)
note.unsafeSave_INTERNAL_USE_ONLY()
} | gpl-3.0 | 4ae893f249f9f2e3a67723127e7d7cc5 | 34.737931 | 100 | 0.767226 | 3.80676 | false | false | false | false |
jwren/intellij-community | platform/projectModel-impl/src/com/intellij/configurationStore/BaseXmlOutputter.kt | 6 | 2195 | // 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.configurationStore
import org.jdom.DocType
import org.jdom.ProcessingInstruction
import java.io.IOException
import java.io.Writer
abstract class BaseXmlOutputter(protected val lineSeparator: String) {
companion object {
fun doesNameSuggestSensitiveInformation(name: String): Boolean {
if (name.contains("password")) {
val isRemember = name.contains("remember", ignoreCase = true) ||
name.contains("keep", ignoreCase = true) ||
name.contains("use", ignoreCase = true) ||
name.contains("save", ignoreCase = true) ||
name.contains("stored", ignoreCase = true)
return !isRemember
}
return false
}
}
/**
* This handle printing the DOCTYPE declaration if one exists.
*
* @param docType `Document` whose declaration to write.
* @param out `Writer` to use.
*/
@Throws(IOException::class)
protected fun printDocType(out: Writer, docType: DocType) {
val publicID = docType.publicID
val systemID = docType.systemID
val internalSubset = docType.internalSubset
var hasPublic = false
out.write("<!DOCTYPE ")
out.write(docType.elementName)
if (publicID != null) {
out.write(" PUBLIC \"")
out.write(publicID)
out.write('"'.toInt())
hasPublic = true
}
if (systemID != null) {
if (!hasPublic) {
out.write(" SYSTEM")
}
out.write(" \"")
out.write(systemID)
out.write("\"")
}
if (!internalSubset.isNullOrEmpty()) {
out.write(" [")
out.write(lineSeparator)
out.write(docType.internalSubset)
out.write("]")
}
out.write(">")
}
@Throws(IOException::class)
protected fun writeProcessingInstruction(out: Writer, pi: ProcessingInstruction, target: String) {
out.write("<?")
out.write(target)
val rawData = pi.data
if (!rawData.isNullOrEmpty()) {
out.write(" ")
out.write(rawData)
}
out.write("?>")
}
} | apache-2.0 | 01bd0c600044e0d8a643ad1be2f37c1a | 28.28 | 140 | 0.616856 | 4.165085 | false | false | false | false |
androidx/androidx | graphics/graphics-core/src/main/java/androidx/opengl/EGLExt.kt | 3 | 31634 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.opengl
import android.hardware.HardwareBuffer
import android.opengl.EGLDisplay
import android.os.Build
import androidx.annotation.IntDef
import androidx.annotation.RequiresApi
import androidx.graphics.opengl.egl.EGLConfigAttributes
import androidx.hardware.SyncFence
import androidx.opengl.EGLExt.Companion.eglCreateSyncKHR
/**
* Utility class that provides some helper methods for interacting EGL Extension APIs
*/
@Suppress("AcronymName")
class EGLExt private constructor() {
companion object {
/**
* Determines if applications can query the age of the back buffer contents for an
* EGL surface as the number of frames elapsed since the contents were recently defined
*
* See:
* https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_buffer_age.txt
*/
const val EGL_EXT_BUFFER_AGE = "EGL_EXT_buffer_age"
/**
* Allows for efficient partial updates to an area of a **buffer** that has changed since
* the last time the buffer was used
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_partial_update.txt
*/
const val EGL_KHR_PARTIAL_UPDATE = "EGL_KHR_partial_update"
/**
* Allows for efficient partial updates to an area of a **surface** that changes between
* frames for the surface. This relates to the differences between two buffers, the current
* back buffer and the current front buffer.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_swap_buffers_with_damage.txt
*/
const val EGL_KHR_SWAP_BUFFERS_WITH_DAMAGE = "EGL_KHR_swap_buffers_with_damage"
/**
* Determines whether to use sRGB format default framebuffers to render sRGB
* content to display devices. Supports creation of EGLSurfaces which will be rendered to in
* sRGB by OpenGL contexts supporting that capability.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_gl_colorspace.txt
*/
const val EGL_KHR_GL_COLORSPACE = "EGL_KHR_gl_colorspace"
/**
* Determines whether creation of GL and ES contexts without an EGLConfig is allowed
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_no_config_context.txt
*/
const val EGL_KHR_NO_CONFIG_CONTEXT = "EGL_KHR_no_config_context"
/**
* Determines whether floating point RGBA components are supported
*
* See:
* https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_pixel_format_float.txt
*/
const val EGL_EXT_PIXEL_FORMAT_FLOAT = "EGL_EXT_pixel_format_float"
/**
* Determines whether extended sRGB color spaces are supported options for EGL Surfaces
*
* See:
* https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_gl_colorspace_scrgb.txt
*/
const val EGL_EXT_GL_COLORSPACE_SCRGB = "EGL_EXT_gl_colorspace_scrgb"
/**
* Determines whether the underlying platform can support rendering framebuffers in the
* non-linear Display-P3 color space
*
* See:
* https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_gl_colorspace_display_p3_passthrough.txt
*/
const val EGL_EXT_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH =
"EGL_EXT_gl_colorspace_display_p3_passthrough"
/**
* Determines whether the platform framebuffers support rendering in a larger color gamut
* specified in the BT.2020 color space
*
* See:
* https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_gl_colorspace_bt2020_linear.txt
*/
const val EGL_EXT_GL_COLORSPACE_BT2020_PQ = "EGL_EXT_gl_colorspace_bt2020_pq"
/**
* Determines whether an EGLContext can be created with a priority hint. Not all
* implementations are guaranteed to honor the hint.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/IMG/EGL_IMG_context_priority.txt
*/
const val EGL_IMG_CONTEXT_PRIORITY = "EGL_IMG_context_priority"
/**
* Determines whether creation of an EGL Context without a surface is supported.
* This is useful for applications that only want to render to client API targets (such as
* OpenGL framebuffer objects) and avoid the need to a throw-away EGL surface just to get
* a current context.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_surfaceless_context.txt
*/
const val EGL_KHR_SURFACELESS_CONTEXT = "EGL_KHR_surfaceless_context"
/**
* Determines whether sync objects are supported. Sync objects are synchronization
* primitives that represent events whose completion can be tested or waited upon.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*/
const val EGL_KHR_FENCE_SYNC = "EGL_KHR_fence_sync"
/**
* Determines whether waiting for signaling of sync objects is supported. This form of wait
* does not necessarily block the application thread which issued the wait. Therefore
* applications may continue to issue commands to the client API or perform other work
* in parallel leading to increased performance.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_wait_sync.txt
*/
const val EGL_KHR_WAIT_SYNC = "EGL_KHR_wait_sync"
/**
* Determines whether creation of platform specific sync objects are supported. These
* objects that are associated with a native synchronization fence object using a file
* descriptor.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/ANDROID/EGL_ANDROID_native_fence_sync.txt
*/
const val EGL_ANDROID_NATIVE_FENCE_SYNC = "EGL_ANDROID_native_fence_sync"
/**
* Enables using an Android window buffer (struct ANativeWindowBuffer) as an EGLImage source
*
* See: https://www.khronos.org/registry/EGL/extensions/ANDROID/EGL_ANDROID_image_native_buffer.txt
*/
const val EGL_ANDROID_IMAGE_NATIVE_BUFFER = "EGL_ANDROID_image_native_buffer"
/**
* Extension for supporting a new EGL resource type that is suitable for
* sharing 2D arrays of image data between client APIs, the EGLImage.
* Although the intended purpose is sharing 2D image data, the
* underlying interface makes no assumptions about the format or
* purpose of the resource being shared, leaving those decisions to
* the application and associated client APIs.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_image_base.txt
*/
const val EGL_KHR_IMAGE_BASE = "EGL_KHR_image_base"
/**
* Extension that allows creating an EGLClientBuffer from an Android [HardwareBuffer]
* object which can later be used to create an [EGLImageKHR] instance.
* See:
* https://registry.khronos.org/EGL/extensions/ANDROID/EGL_ANDROID_get_native_client_buffer.txt
*/
const val EGL_ANDROID_CLIENT_BUFFER = "EGL_ANDROID_get_native_client_buffer"
/**
* Extension that defines a new EGL resource type that is suitable for
* sharing 2D arrays of image data between client APIs, the EGLImage,
* and allows creating EGLImages from EGL native pixmaps.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_image.txt
*/
const val EGL_KHR_IMAGE = "EGL_KHR_image"
/**
* Specifies the types of attributes that can be queried in [eglGetSyncAttribKHR]
*
* @hide
*/
@Suppress("AcronymName")
@IntDef(value = [EGL_SYNC_TYPE_KHR, EGL_SYNC_STATUS_KHR, EGL_SYNC_CONDITION_KHR])
annotation class EGLSyncAttribute
/**
* Attribute that can be queried in [eglGetSyncAttribKHR].
* The results can be either [EGL_SYNC_FENCE_KHR] or [EGL_SYNC_NATIVE_FENCE_ANDROID].
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*/
const val EGL_SYNC_TYPE_KHR = 0x30F7
/**
* Attribute that can be queried in [eglGetSyncAttribKHR].
* The results can be either [EGL_SIGNALED_KHR] or [EGL_UNSIGNALED_KHR] representing
* whether or not the sync object has been signalled or not.
* This can be queried on all sync object types.
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*/
const val EGL_SYNC_STATUS_KHR = 0x30F1
/**
* Attribute that can be queried in [eglGetSyncAttribKHR].
* This attribute can only be queried on sync objects of the type [EGL_SYNC_FENCE_KHR].
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*/
const val EGL_SYNC_CONDITION_KHR = 0x30F8
/**
* Return value when [eglGetSyncAttribKHR] is called with [EGL_SYNC_STATUS_KHR] indicating
* that the sync object has already been signalled.
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*/
const val EGL_SIGNALED_KHR = 0x30F2
/**
* Return value when [eglGetSyncAttribKHR] is called with [EGL_SYNC_STATUS_KHR] indicating
* that the sync object has not yet been signalled.
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*/
const val EGL_UNSIGNALED_KHR = 0x30F3
/**
* Return value when [eglGetSyncAttribKHR] is called with [EGL_SYNC_CONDITION_KHR].
* This indicates that the sync object will signal on the condition of the completion
* of the fence command on the corresponding sync object and all preceding commands
* in th EGL client API's command stream.
*/
const val EGL_SYNC_PRIOR_COMMANDS_COMPLETE_KHR = 0x30F0
/**
* Specifies the type of fence to create in [eglCreateSyncKHR]
*
* @hide
*/
@Suppress("AcronymName")
@IntDef(value = [EGL_SYNC_FENCE_KHR, EGL_SYNC_NATIVE_FENCE_ANDROID])
annotation class EGLFenceType
/**
* Create an EGL fence sync object for signalling one time events. The fence object
* created is not associated with the Android Sync fence object and is not recommended
* for waiting for events in a portable manner across Android/EGL boundaries but rather
* other EGL primitives.
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*/
const val EGL_SYNC_FENCE_KHR = 0x30F9
/**
* This extension enables the creation of EGL fence sync objects that are
* associated with a native synchronization fence object that is referenced
* using a file descriptor. These EGL fence sync objects have nearly
* identical semantics to those defined by the KHR_fence_sync extension,
* except that they have an additional attribute storing the file descriptor
* referring to the native fence object. This differs from EGL_SYNC_FENCE_KHR
* as the fence sync object is associated with an Android Sync HAL fence object.
*
* This extension assumes the existence of a native fence synchronization
* object that behaves similarly to an EGL fence sync object. These native
* objects must have a signal status like that of an EGLSyncKHR object that
* indicates whether the fence has ever been signaled. Once signaled the
* native object's signal status may not change again.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/ANDROID/EGL_ANDROID_native_fence_sync.txt
*/
const val EGL_SYNC_NATIVE_FENCE_ANDROID = 0x3144
/**
* Value that can be sent as the timeoutNanos parameter of [eglClientWaitSyncKHR]
* indicating that waiting on the sync object to signal will never time out.
*/
// Note EGL has EGL_FOREVER_KHR defined as 0xFFFFFFFFFFFFFFFFuL. However, Java does not
// support unsigned long types. So use -1 as the constant value here as it will be casted
// as an EGLTimeKHR type which is uint64 in the corresponding JNI method
const val EGL_FOREVER_KHR = -1L
/**
* Specifies various return values for the [eglClientWaitSyncKHR] method
*
* @hide
*/
@Target(AnnotationTarget.TYPE)
@Suppress("AcronymName")
@IntDef(value = [EGL_CONDITION_SATISFIED_KHR, EGL_TIMEOUT_EXPIRED_KHR, EGL_FALSE])
annotation class EGLClientWaitResult
/**
* Return value used in [eglClientWaitSyncKHR] to indicate that the specified timeout period
* had expired before a sync object was signalled.
*/
const val EGL_TIMEOUT_EXPIRED_KHR = 0x30F5
/**
* Return value used in [eglClientWaitSyncKHR] to indicate that the sync object had
* signalled before the timeout expired. This includes the case where the sync object had
* already signalled before [eglClientWaitSyncKHR] was called.
*/
const val EGL_CONDITION_SATISFIED_KHR = 0x30F6
/**
* Accepted in the flags parameter of [eglClientWaitSyncKHR]. This will implicitly ensure
* pending commands are flushed to prevent [eglClientWaitSyncKHR] from potentially blocking
* forever. See [eglClientWaitSyncKHR] for details.
*/
const val EGL_SYNC_FLUSH_COMMANDS_BIT_KHR = 0x0001
/**
* Constant indicating true within EGL. This is often returned in success cases.
*/
const val EGL_TRUE = 1
/**
* Constant indicating false within EGL. This is often returned in failure cases.
*/
const val EGL_FALSE = 0
/**
* Creates an EGLImage from the provided [HardwareBuffer]. This handles
* internally creating an EGLClientBuffer and an [EGLImageKHR] from the client buffer.
*
* When this [EGLImageKHR] instance is no longer necessary, consumers should be sure to
* call the corresponding method [eglDestroyImageKHR] to deallocate the resource.
*
* @param eglDisplay EGLDisplay connection associated with the EGLImage to create
* @param hardwareBuffer Backing [HardwareBuffer] for the generated EGLImage instance
*
* @return an [EGLImageKHR] instance representing the [EGLImageKHR] created from the
* HardwareBuffer. Because this is created internally through EGL's eglCreateImageKR method,
* this has the KHR suffix.
*
* This can return null if the EGL_ANDROID_image_native_buffer and EGL_KHR_image_base
* extensions are not supported or if allocation of the buffer fails.
*
* See
* www.khronos.org/registry/EGL/extensions/ANDROID/EGL_ANDROID_get_native_client_buffer.txt
*/
@JvmStatic
@RequiresApi(Build.VERSION_CODES.O)
fun eglCreateImageFromHardwareBuffer(
eglDisplay: EGLDisplay,
hardwareBuffer: HardwareBuffer
): EGLImageKHR? {
val handle = EGLBindings.nCreateImageFromHardwareBuffer(
eglDisplay.obtainNativeHandle(), hardwareBuffer
)
return if (handle == 0L) {
null
} else {
EGLImageKHR(handle)
}
}
/**
* Destroy the given [EGLImageKHR] instance. Once destroyed, the image may not be used to
* create any additional [EGLImageKHR] target resources within any client API contexts,
* although existing [EGLImageKHR] siblings may continue to be used. `True` is returned
* if DestroyImageKHR succeeds, `false` indicates failure. This can return `false` if
* the [EGLImageKHR] is not associated with the default display.
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_image_base.txt
*
* @param eglDisplay EGLDisplay that this EGLImage is connected to
* @param image EGLImageKHR to be destroyed
*
* @return True if the destruction of the EGLImageKHR object was successful, false otherwise
*/
@JvmStatic
@Suppress("AcronymName")
fun eglDestroyImageKHR(
eglDisplay: EGLDisplay,
image: EGLImageKHR
): Boolean = EGLBindings.nDestroyImageKHR(
eglDisplay.obtainNativeHandle(),
image.nativeHandle
)
/**
* Upload a given EGLImage to the currently bound GLTexture
*
* This method requires either of the following EGL extensions to be supported:
* EGL_KHR_image_base or EGL_KHR_image
*
* See: https://www.khronos.org/registry/OpenGL/extensions/OES/OES_EGL_image_external.txt
*/
@JvmStatic
@Suppress("AcronymName")
fun glEGLImageTargetTexture2DOES(target: Int, image: EGLImageKHR) {
EGLBindings.nImageTargetTexture2DOES(target, image.nativeHandle)
}
/**
* Creates a sync object of the specified type associated with the
* specified display, and returns a handle to the new object.
* The configuration of the returned [EGLSyncKHR] object is specified by the provided
* attributes.
*
* Consumers should ensure that the EGL_KHR_fence_sync EGL extension is supported before
* invoking this method otherwise a null EGLSyncFenceKHR object is returned.
*
* Additionally when the [EGLSyncKHR] instance is no longer necessary, consumers are
* encouraged to call [eglDestroySyncKHR] to deallocate this resource.
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*
* @param eglDisplay EGLDisplay to associate the sync object with
* @param type Indicates the type of sync object that is returned
* @param attributes Specifies the configuration of the sync object returned
*
* @return the EGLSyncKHR object to be used as a fence or null if this extension
* is not supported
*/
@JvmStatic
@Suppress("AcronymName")
fun eglCreateSyncKHR(
eglDisplay: EGLDisplay,
@EGLFenceType type: Int,
attributes: EGLConfigAttributes?
): EGLSyncKHR? {
val handle = EGLBindings.nCreateSyncKHR(
eglDisplay.obtainNativeHandle(), type, attributes?.attrs
)
return if (handle == 0L) {
null
} else {
EGLSyncKHR(handle)
}
}
/**
* Query attributes of the provided sync object. Accepted attributes to query depend
* on the type of sync object. If no errors are generated, this returns true and the
* value of the queried attribute is stored in the value array at the offset position.
* If this method returns false, the provided value array is unmodified.
*
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*
* @param eglDisplay EGLDisplay to associate the sync object with
* @param sync EGLSyncKHR object to query attributes
* @param attribute Corresponding EGLSyncKHR attribute to query on [sync]
* @param value Integer array used to store the result of the query
* @param offset Index within the value array to store the result of the attribute query
*
* @return True if the attribute was queried successfully, false otherwise. Failure cases
* include attempting to call this method on an invalid sync object, or the display provided
* not matching the display that was used to create this sync object. Additionally if the
* queried attribute is not supported for the sync object, false is returned.
*/
@JvmStatic
@Suppress("AcronymName")
fun eglGetSyncAttribKHR(
eglDisplay: EGLDisplay,
sync: EGLSyncKHR,
@EGLSyncAttribute attribute: Int,
value: IntArray,
offset: Int
): Boolean =
EGLBindings.nGetSyncAttribKHR(
eglDisplay.obtainNativeHandle(),
sync.nativeHandle,
attribute,
value,
offset
)
/**
* Blocks the calling thread until the specified sync object is signalled or until
* [timeoutNanos] nanoseconds have passed.
* More than one [eglClientWaitSyncKHR] may be outstanding on the same [sync] at any given
* time. When there are multiple threads blocked on the same [sync] and the [sync] object
* has signalled, all such threads are released, but the order in which they are released is
* not defined.
*
* If the value of [timeoutNanos] is zero, then [eglClientWaitSyncKHR] simply tests the
* current status of sync. If the value of [timeoutNanos] is the special value
* [EGL_FOREVER_KHR], then [eglClientWaitSyncKHR] does not time out. For all other values,
* [timeoutNanos] is adjusted to the closest value allowed by the implementation-dependent
* timeout accuracy, which may be substantially longer than one nanosecond.
*
* [eglClientWaitSyncKHR] returns one of three status values describing the reason for
* returning. A return value of [EGL_TIMEOUT_EXPIRED_KHR] indicates that the specified
* timeout period expired before [sync] was signalled, or if [timeoutNanos] is zero,
* indicates that [sync] is not signaled. A return value of [EGL_CONDITION_SATISFIED_KHR]
* indicates that [sync] was signaled before the timeout expired, which includes the case
* when [sync] was already signaled when [eglClientWaitSyncKHR] was called. If an error
* occurs then an error is generated and [EGL_FALSE] is returned.
*
* If the sync object being blocked upon will not be signaled in finite time (for example
* by an associated fence command issued previously, but not yet flushed to the graphics
* pipeline), then [eglClientWaitSyncKHR] may wait forever. To help prevent this behavior,
* if the [EGL_SYNC_FLUSH_COMMANDS_BIT_KHR] is set on the flags parameter and the [sync] is
* unsignaled when [eglClientWaitSyncKHR] is called, then the equivalent flush will be
* performed for the current EGL context before blocking on sync. If no context is
* current bound for the API, the [EGL_SYNC_FLUSH_COMMANDS_BIT_KHR] bit is ignored.
*
* @param eglDisplay EGLDisplay to associate the sync object with
* @param sync EGLSyncKHR object to wait on
* @param flags Optional flags to provide to handle flushing of pending commands
* @param timeoutNanos Optional timeout value to wait before this method returns, measured
* in nanoseconds. This value is always consumed as an unsigned long value so even negative
* values will be converted to their unsigned equivalent.
*
* @return Result code indicating the status of the wait request. Either
* [EGL_CONDITION_SATISFIED_KHR], if the sync did signal within the specified timeout,
* [EGL_TIMEOUT_EXPIRED_KHR] if the sync did not signal within the specified timeout,
* or [EGL_FALSE] if an error occurs.
*/
@JvmStatic
@Suppress("AcronymName")
fun eglClientWaitSyncKHR(
eglDisplay: EGLDisplay,
sync: EGLSyncKHR,
flags: Int,
timeoutNanos: Long
): @EGLClientWaitResult Int =
EGLBindings.nClientWaitSyncKHR(
eglDisplay.obtainNativeHandle(),
sync.nativeHandle,
flags,
timeoutNanos
)
/**
* Creates a native synchronization fence referenced through a file descriptor
* that is associated with an EGL fence sync object.
*
* See:
* https://www.khronos.org/registry/EGL/extensions/ANDROID/EGL_ANDROID_native_fence_sync.txt
*
* @param display The EGLDisplay connection
* @param sync The EGLSyncKHR to fetch the [SyncFence] from
* @return A [SyncFence] representing the native fence.
* If [sync] is not a valid sync object for [display], an invalid [SyncFence]
* instance is returned and an EGL_BAD_PARAMETER error is generated.
* If the EGL_SYNC_NATIVE_FENCE_FD_ANDROID attribute of [sync] is
* EGL_NO_NATIVE_FENCE_FD_ANDROID, an invalid [SyncFence] is
* returned and an EGL_BAD_PARAMETER error is generated.
* If [display] does not match the display passed to [eglCreateSyncKHR]
* when [sync] was created, the behavior is undefined.
*/
@JvmStatic
@Suppress("AcronymName")
@RequiresApi(Build.VERSION_CODES.KITKAT)
fun eglDupNativeFenceFDANDROID(display: EGLDisplay, sync: EGLSyncKHR): SyncFence {
val fd = EGLBindings.nDupNativeFenceFDANDROID(
display.obtainNativeHandle(),
sync.nativeHandle
)
return if (fd >= 0) {
SyncFence(fd)
} else {
SyncFence(-1)
}
}
/**
* Destroys the given sync object associated with the specified display
*
* Consumers should ensure that the EGL_KHR_fence_sync EGL extension is supported before
* invoking this method otherwise a null EGLSyncFenceKHR object is returned.
* See: https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_fence_sync.txt
*
* @param eglDisplay EGLDisplay instance associated with the fence
* @param eglSync Fence object to be destroyed
*
* @return true if the EGLSyncKHR object was destroyed successfully false otherwise. This
* can return false if the sync object is not a valid sync object for the provided display
* or if the display provided in this method does not match the display used to create this
* sync in eglCreateSyncKHR.
*/
@JvmStatic
@Suppress("AcronymName")
fun eglDestroySyncKHR(
eglDisplay: EGLDisplay,
eglSync: EGLSyncKHR
): Boolean = EGLBindings.nDestroySyncKHR(
eglDisplay.obtainNativeHandle(),
eglSync.nativeHandle
)
/**
* Returns a set of supported supported extensions from a space separated string
* that represents the set of OpenGL extensions supported
*/
@JvmStatic
fun parseExtensions(queryString: String): Set<String> =
HashSet<String>().apply { addAll(queryString.split(' ')) }
/**
* Helper method to obtain the corresponding native handle. Newer versions of Android
* represent the native pointer as a long instead of an integer to support 64 bits.
* For OS levels that support the wider bit format, invoke it otherwise cast the int
* to a long.
*
* This is internal to avoid synthetic accessors
*/
internal fun EGLDisplay.obtainNativeHandle(): Long =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
EGLDisplayVerificationHelper.getNativeHandle(this)
} else {
@Suppress("DEPRECATION")
handle.toLong()
}
}
}
/**
* Helper class to configure JNI bindings to be invoked within the EGLUtils
* public API. This class is provided to separate responsibilities of jni method registration
* and helps to avoid synthetic accessor warnings
*/
internal class EGLBindings {
companion object {
external fun nCreateImageFromHardwareBuffer(
eglDisplayPtr: Long,
hardwareBuffer: HardwareBuffer
): Long
// Note this API is explicitly a GL API and not an EGL API which is the reason
// why this has the GL prefix vs EGL
external fun nImageTargetTexture2DOES(target: Int, eglImagePtr: Long)
external fun nDupNativeFenceFDANDROID(eglDisplayPtr: Long, syncPtr: Long): Int
external fun nCreateSyncKHR(eglDisplayPtr: Long, type: Int, attrs: IntArray?): Long
external fun nGetSyncAttribKHR(
eglDisplayPtr: Long,
syncPtr: Long,
attrib: Int,
result: IntArray,
offset: Int
): Boolean
external fun nClientWaitSyncKHR(
eglDisplayPtr: Long,
syncPtr: Long,
flags: Int,
timeout: Long
): Int
external fun nDestroySyncKHR(eglDisplayPtr: Long, syncPtr: Long): Boolean
external fun nDestroyImageKHR(eglDisplayPtr: Long, eglImagePtr: Long): Boolean
external fun nSupportsEglGetNativeClientBufferAndroid(): Boolean
external fun nSupportsDupNativeFenceFDANDROID(): Boolean
external fun nSupportsEglCreateImageKHR(): Boolean
external fun nSupportsEglDestroyImageKHR(): Boolean
external fun nSupportsGlImageTargetTexture2DOES(): Boolean
external fun nSupportsEglCreateSyncKHR(): Boolean
external fun nSupportsEglGetSyncAttribKHR(): Boolean
external fun nSupportsEglClientWaitSyncKHR(): Boolean
external fun nSupportsEglDestroySyncKHR(): Boolean
external fun nEqualToNativeForeverTimeout(timeoutNanos: Long): Boolean
init {
System.loadLibrary("graphics-core")
}
}
}
/**
* Helper class to avoid class verification failures
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private class EGLDisplayVerificationHelper private constructor() {
companion object {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
@androidx.annotation.DoNotInline
fun getNativeHandle(eglDisplay: EGLDisplay): Long = eglDisplay.nativeHandle
}
} | apache-2.0 | 858ff140bc6187926424b7efc9b868e7 | 44.192857 | 111 | 0.641209 | 4.630947 | false | false | false | false |
kotlinx/kotlinx.html | src/commonMain/kotlin/compatibility.kt | 1 | 2795 | package kotlinx.html
@Deprecated("use legend instead", ReplaceWith("legend(classes, block)"))
fun <T, C : TagConsumer<T>> C.legEnd(classes: String? = null, block: LEGEND.() -> Unit = {}): T = legend(classes, block)
@Deprecated("use legend instead", ReplaceWith("legend(classes, block)"))
fun DETAILS.legEnd(classes: String? = null, block: LEGEND.() -> Unit = {}): Unit = legend(classes, block)
@Deprecated("use legend instead", ReplaceWith("legend(classes, block)"))
fun FIELDSET.legEnd(classes: String? = null, block: LEGEND.() -> Unit = {}): Unit = legend(classes, block)
@Deprecated("use legend instead", ReplaceWith("legend(classes, block)"))
fun FIGURE.legEnd(classes: String? = null, block: LEGEND.() -> Unit = {}): Unit = legend(classes, block)
@Deprecated("", ReplaceWith("Draggable.htmlTrue"))
inline val Draggable.true_: Draggable
get() = Draggable.htmlTrue
@Deprecated("", ReplaceWith("Draggable.htmlFalse"))
inline val Draggable.false_: Draggable
get() = Draggable.htmlFalse
@Deprecated("Use OBJECT instead", ReplaceWith("OBJECT", "kotlinx.html.OBJECT"))
typealias OBJECT_ = OBJECT
@Deprecated("Use VAR type instead", ReplaceWith("VAR", "kotlinx.html.VAR"))
typealias VAR_ = VAR
@Deprecated("", ReplaceWith("htmlObject(classes, block)", "kotlinx.html.htmlObject"))
fun <T, C : TagConsumer<T>> C.object_(classes: String? = null, block: OBJECT.() -> Unit = {}): T =
htmlObject(classes, block)
@Deprecated("", ReplaceWith("htmlVar(classes, block)", "kotlinx.html.htmlVar"))
fun <T, C : TagConsumer<T>> C.var_(classes: String? = null, block: VAR.() -> Unit = {}): T =
htmlVar(classes, block)
@Deprecated("Use htmlVar instead", ReplaceWith("htmlVar(classes, block)", "kotlinx.html.htmlVar"))
fun FlowOrPhrasingContent.var_(classes: String? = null, block: VAR.() -> Unit) {
htmlVar(classes, block)
}
@Deprecated("Use htmlObject instead", ReplaceWith("htmlObject(classes, block)", "kotlinx.html.htmlObject"))
fun FlowOrInteractiveOrPhrasingContent.object_(classes: String? = null, block: OBJECT.() -> Unit = {}) =
htmlObject(classes, block)
@Deprecated("use htmlFor instead", ReplaceWith("htmlFor"))
var LABEL.for_: String
get() = htmlFor
set(value) {
htmlFor = value
}
@Deprecated("use htmlFor instead", ReplaceWith("htmlFor"))
var OUTPUT.for_: String
get() = htmlFor
set(value) {
htmlFor = value
}
@Deprecated("Use onTouchCancel instead", ReplaceWith("onTouchCancel"))
var CommonAttributeGroupFacade.onTouchcancel: String
get() = onTouchCancel
set(newValue) {
onTouchCancel = newValue
}
@Deprecated("Use onTouchMove instead", ReplaceWith("onTouchMove"))
var CommonAttributeGroupFacade.onTouchmove: String
get() = onTouchMove
set(newValue) {
onTouchMove = newValue
}
| apache-2.0 | 79f10fa4b0e59c40edb911bc62cc101c | 36.77027 | 120 | 0.693381 | 3.887344 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/searcheverywhere/KtSearchEverywhereEqualityProvider.kt | 8 | 4992 | // 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.searcheverywhere
import com.intellij.ide.actions.searcheverywhere.PSIPresentationBgRendererWrapper
import com.intellij.ide.actions.searcheverywhere.SEResultsEqualityProvider
import com.intellij.ide.actions.searcheverywhere.SEResultsEqualityProvider.SEEqualElementsActionType
import com.intellij.ide.actions.searcheverywhere.SEResultsEqualityProvider.SEEqualElementsActionType.*
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereFoundElementInfo
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.FakeFileForLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
/**
* @see org.jetbrains.kotlin.idea.searcheverywhere.NativePsiAndKtLightElementEqualityProviderTest
* @see org.jetbrains.kotlin.idea.searcheverywhere.KtSearchEverywhereEqualityProviderTest
*/
class KtSearchEverywhereEqualityProvider : SEResultsEqualityProvider {
override fun compareItems(
newItem: SearchEverywhereFoundElementInfo,
alreadyFoundItems: List<SearchEverywhereFoundElementInfo>
): SEEqualElementsActionType {
val newPsiElement = newItem.toPsi() ?: return DoNothing
val result = compareElements(newPsiElement) {
alreadyFoundItems.asSequence().map { it.toPsi() }
}
return when (result) {
null -> DoNothing
-1 -> Skip
else -> Replace(alreadyFoundItems[result])
}
}
companion object {
/**
* @return
* null if a rule is not applicable,
* -1 if [newItem] should be skipped,
* the index of [alreadyFoundItems] if an existent element should be replaced
*/
fun compareElements(
newItem: PsiElement,
alreadyFoundItems: () -> Sequence<PsiElement?>,
): Int? {
fun <T> reduce(
transformation: PsiElement.() -> T?,
shouldBeProcessed: (new: T, old: T) -> Boolean,
shouldBeReplaced: (new: T, old: T) -> Boolean,
): Int? {
val transformedNewItem = newItem.transformation() ?: return null
return alreadyFoundItems().mapIndexedNotNull(fun(index: Int, alreadyFoundItem: PsiElement?): Int? {
val transformedOldItem = alreadyFoundItem?.transformation() ?: return null
if (!shouldBeProcessed(transformedNewItem, transformedOldItem)) return null
return if (shouldBeReplaced(transformedNewItem, transformedOldItem)) index else -1
}).firstOrNull()
}
return reduce(
transformation = { this },
shouldBeProcessed = { new, old ->
// [com.intellij.ide.actions.searcheverywhere.TrivialElementsEqualityProvider] is responsible for "new == old" case
(new::class != old::class || new === old) && PsiManager.getInstance(new.project).areElementsEquivalent(new, old)
},
shouldBeReplaced = { new, old -> new is KtElement && old !is KtElement },
) ?: reduce(
transformation = { (this.unwrapped ?: this).withKind() },
shouldBeProcessed = { new, old ->
new.second != old.second && getGroupLeader(new.first)?.equals(getGroupLeader(old.first)) == true
},
shouldBeReplaced = { new, old -> minOf(new, old, compareBy { it.second }) === new },
)
}
}
}
private fun getGroupLeader(element: PsiElement): KtFile? {
if (element is KtFile) {
return element
}
if (element is KtLightClassForFacade &&
element.facadeClassFqName.shortName().asString().removeSuffix("Kt") == element.containingFile.virtualFile.nameWithoutExtension
) {
return when (val containingFile = element.containingFile) {
is FakeFileForLightClass -> containingFile.ktFile
else -> containingFile as? KtFile
}
}
if (element is KtClass && element.isTopLevel()) {
val file = element.parent
if (file is KtFile &&
element.name == file.virtualFile.nameWithoutExtension
) {
return file
}
}
return null
}
private fun SearchEverywhereFoundElementInfo.toPsi() = PSIPresentationBgRendererWrapper.toPsi(element)
private enum class Kind {
KtClass, KtFile, KtFacade
}
private fun PsiElement.withKind(): Pair<PsiElement, Kind>? = when (this) {
is KtFile -> this to Kind.KtFile
is KtClass -> this to Kind.KtClass
is KtLightClassForFacade -> this to Kind.KtFacade
else -> null
}
| apache-2.0 | 1a611e9306dca426ca8afb2a400a1c60 | 40.94958 | 135 | 0.658253 | 4.932806 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/actions/AbstractCommonCheckinAction.kt | 2 | 4111 | // 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.openapi.vcs.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.actions.commit.CheckinActionUtil
import com.intellij.openapi.vcs.changes.*
import com.intellij.vcs.commit.CommitModeManager
import com.intellij.vcs.commit.cleanActionText
import org.jetbrains.annotations.ApiStatus
import java.util.*
private val LOG = logger<AbstractCommonCheckinAction>()
abstract class AbstractCommonCheckinAction : AbstractVcsAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(vcsContext: VcsContext, presentation: Presentation) {
val project = vcsContext.project
if (project == null ||
!ProjectLevelVcsManager.getInstance(project).hasActiveVcss() ||
CommitModeManager.getInstance(project).getCurrentCommitMode().disableDefaultCommitAction()) {
presentation.isEnabledAndVisible = false
}
else if (!approximatelyHasRoots(vcsContext)) {
presentation.isEnabled = false
}
else {
getActionName(vcsContext)?.let { presentation.text = "$it..." }
presentation.isEnabled = !ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning
presentation.isVisible = true
}
}
protected abstract fun approximatelyHasRoots(dataContext: VcsContext): Boolean
protected open fun getActionName(dataContext: VcsContext): @NlsActions.ActionText String? = null
public override fun actionPerformed(context: VcsContext) {
LOG.debug("actionPerformed. ")
val project = context.project!!
val actionName = getActionName(context) ?: templatePresentation.text
val isFreezedDialogTitle = actionName?.let {
val operationName = cleanActionText(actionName)
VcsBundle.message("error.cant.perform.operation.now", operationName)
}
if (ChangeListManager.getInstance(project).isFreezedWithNotification(isFreezedDialogTitle)) {
LOG.debug("ChangeListManager is freezed. returning.")
return
}
if (ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning) {
LOG.debug("Background operation is running. returning.")
return
}
val selectedChanges = context.selectedChanges?.asList().orEmpty()
val selectedUnversioned = context.selectedUnversionedFilePaths
val initialChangeList = getInitiallySelectedChangeList(context, project)
val pathsToCommit = DescindingFilesFilter.filterDescindingFiles(getRoots(context), project).asList()
val executor = getExecutor(project)
val forceUpdateCommitStateFromContext = isForceUpdateCommitStateFromContext()
CheckinActionUtil.performCheckInAfterUpdate(project, selectedChanges, selectedUnversioned, initialChangeList, pathsToCommit,
executor, forceUpdateCommitStateFromContext)
}
@Deprecated("getActionName() will be used instead")
@ApiStatus.ScheduledForRemoval
protected open fun getMnemonicsFreeActionName(context: VcsContext): String? = null
protected abstract fun getRoots(dataContext: VcsContext): Array<FilePath>
protected open fun isForceUpdateCommitStateFromContext(): Boolean = false
protected open fun getInitiallySelectedChangeList(context: VcsContext, project: Project): LocalChangeList {
val manager = ChangeListManager.getInstance(project)
return context.selectedChangeLists?.firstOrNull()?.let { manager.findChangeList(it.name) }
?: context.selectedChanges?.firstOrNull()?.let { manager.getChangeList(it) }
?: manager.defaultChangeList
}
protected open fun getExecutor(project: Project): CommitExecutor? = null
}
| apache-2.0 | 96d834e19668216404099f364db314ca | 43.204301 | 140 | 0.773778 | 5.119552 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/kotlin/KotlinPlugin.kt | 1 | 10602 | // 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.tools.projectWizard.plugins.kotlin
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.service.*
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildFileIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.RepositoryIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.withIrs
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.ModuleConfigurator
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.buildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.pomIR
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.*
import java.nio.file.Path
class KotlinPlugin(context: Context) : Plugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "kotlin"
private val moduleDependenciesValidator = settingValidator<List<Module>> { modules ->
val allModules = modules.withAllSubModules(includeSourcesets = true).toSet()
val allModulePaths = allModules.map(Module::path).toSet()
allModules.flatMap { module ->
module.dependencies.map { dependency ->
val isValidModule = when (dependency) {
is ModuleReference.ByPath -> dependency.path in allModulePaths
is ModuleReference.ByModule -> dependency.module in allModules
}
ValidationResult.create(isValidModule) {
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.modules",
dependency,
module.path
)
}
}
}.fold()
}
val version by property(
// todo do not hardcode kind & repository
WizardKotlinVersion(
Versions.KOTLIN,
KotlinVersionKind.M,
Repositories.KOTLIN_EAP_MAVEN_CENTRAL,
KotlinVersionProviderService.getBuildSystemPluginRepository(
KotlinVersionKind.M,
devRepositories = listOf(Repositories.JETBRAINS_KOTLIN_DEV)
)
)
)
val initKotlinVersions by pipelineTask(GenerationPhase.PREPARE_GENERATION) {
title = KotlinNewProjectWizardBundle.message("plugin.kotlin.downloading.kotlin.versions")
withAction {
val version = service<KotlinVersionProviderService>().getKotlinVersion(projectKind.settingValue)
KotlinPlugin.version.update { version.asSuccess() }
}
}
val projectKind by enumSetting<ProjectKind>(
KotlinNewProjectWizardBundle.message("plugin.kotlin.setting.project.kind"),
GenerationPhase.FIRST_STEP,
)
private fun List<Module>.findDuplicatesByName() =
groupingBy { it.name }.eachCount().filter { it.value > 1 }
val modules by listSetting(
KotlinNewProjectWizardBundle.message("plugin.kotlin.setting.modules"),
GenerationPhase.SECOND_STEP,
Module.parser,
) {
validate { value ->
val allModules = value.withAllSubModules()
val duplicatedModules = allModules.findDuplicatesByName()
if (duplicatedModules.isEmpty()) ValidationResult.OK
else ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.modules",
duplicatedModules.values.first(),
duplicatedModules.keys.first()
)
)
}
validate { value ->
value.withAllSubModules().filter { it.kind == ModuleKind.multiplatform }.map { module ->
val duplicatedModules = module.subModules.findDuplicatesByName()
if (duplicatedModules.isEmpty()) ValidationResult.OK
else ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.targets",
duplicatedModules.values.first(),
duplicatedModules.keys.first()
)
)
}.fold()
}
validate(moduleDependenciesValidator)
}
val createModules by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(BuildSystemPlugin.createModules)
runAfter(StructurePlugin.createProjectDir)
withAction {
BuildSystemPlugin.buildFiles.update {
val modules = modules.settingValue
val (buildFiles) = createBuildFiles(modules)
buildFiles.map { it.withIrs(RepositoryIR(DefaultRepository.MAVEN_CENTRAL)) }.asSuccess()
}
}
}
val createPluginRepositories by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(BuildSystemPlugin.createModules)
withAction {
val version = version.propertyValue
if (version.kind.isStable) return@withAction UNIT_SUCCESS
val pluginRepository = version.buildSystemPluginRepository(buildSystemType)
BuildSystemPlugin.pluginRepositoreis.addValues(pluginRepository) andThen
updateBuildFiles { buildFile ->
buildFile.withIrs(
version.repositories
.map { RepositoryIR(it) }
).asSuccess()
}
}
}
val createResourceDirectories by booleanSetting("Generate Resource Folders", GenerationPhase.PROJECT_GENERATION) {
defaultValue = value(true)
}
val createSourcesetDirectories by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(createModules)
withAction {
fun Path?.createKotlinAndResourceDirectories(moduleConfigurator: ModuleConfigurator): TaskResult<Unit> {
if (this == null) return UNIT_SUCCESS
return with(service<FileSystemWizardService>()) {
createDirectory(this@createKotlinAndResourceDirectories / moduleConfigurator.kotlinDirectoryName) andThen
if (createResourceDirectories.settingValue) {
createDirectory(this@createKotlinAndResourceDirectories / moduleConfigurator.resourcesDirectoryName)
} else {
UNIT_SUCCESS
}
}
}
forEachModule { moduleIR ->
moduleIR.sourcesets.mapSequenceIgnore { sourcesetIR ->
sourcesetIR.path.createKotlinAndResourceDirectories(moduleIR.originalModule.configurator)
}
}
}
}
private fun Writer.createBuildFiles(modules: List<Module>): TaskResult<List<BuildFileIR>> =
with(
ModulesToIRsConverter(
ModulesToIrConversionData(
modules,
projectPath,
StructurePlugin.name.settingValue,
version.propertyValue,
buildSystemType,
pomIR()
)
)
) { createBuildFiles() }
}
override val settings: List<PluginSetting<*, *>> =
listOf(
projectKind,
modules,
createResourceDirectories,
)
override val pipelineTasks: List<PipelineTask> =
listOf(
initKotlinVersions,
createModules,
createPluginRepositories,
createSourcesetDirectories
)
override val properties: List<Property<*>> =
listOf(version)
}
enum class ProjectKind(
@Nls override val text: String,
val supportedBuildSystems: Set<BuildSystemType>,
val shortName: String = text,
val message: String? = null,
) : DisplayableSettingItem {
Singleplatform(
KotlinNewProjectWizardBundle.message("project.kind.singleplatform"),
supportedBuildSystems = BuildSystemType.values().toSet()
),
Multiplatform(KotlinNewProjectWizardBundle.message("project.kind.multiplatform"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
Android(KotlinNewProjectWizardBundle.message("project.kind.android"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
Js(KotlinNewProjectWizardBundle.message("project.kind.kotlin.js"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
}
fun List<Module>.withAllSubModules(includeSourcesets: Boolean = false): List<Module> = buildList {
fun handleModule(module: Module) {
+module
if (module.kind != ModuleKind.multiplatform
|| includeSourcesets && module.kind == ModuleKind.multiplatform
) {
module.subModules.forEach(::handleModule)
}
}
forEach(::handleModule)
}
| apache-2.0 | bf49b6dec83623e0be8ce73f1e6b1f23 | 44.502146 | 158 | 0.620921 | 6.142526 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/main/kotlin/entities/AllAttributeV2Entity.kt | 1 | 1556 | package entities
import com.onyx.extension.common.*
import com.onyx.persistence.annotations.Attribute
import com.onyx.persistence.annotations.Entity
import com.onyx.persistence.annotations.Identifier
import com.onyx.persistence.query.QueryCriteriaOperator
/**
* Created by Tim Osborn on 1/18/17.
*/
@Entity
class AllAttributeV2Entity : AllAttributeEntity() {
@Identifier
@Attribute(size = 64)
override var id: String? = null
@Attribute
var mutableFloat: Float? = null
@Attribute
var floatValue: Float = 0.toFloat()
@Attribute
var mutableByte: Byte? = null
@Attribute
var byteValue: Byte = 0
@Attribute
var mutableShort: Short? = null
@Attribute
var shortValue: Short = 0
@Attribute
var mutableChar: Char? = null
@Attribute
var charValue: Char = ' '
@Attribute
var entity: AllAttributeV2Entity? = null
@Attribute
var operator: QueryCriteriaOperator? = null
@Attribute
var bytes: ByteArray? = null
@Attribute
var shorts: ShortArray? = null
@Attribute
var aMutableBytes: Array<Byte>? = null
@Attribute
var mutableShorts: Array<Short>? = null
@Attribute
var strings: Array<String>? = null
@Attribute
var entityList: MutableList<AllAttributeEntity>? = null
@Attribute
var entitySet: MutableSet<AllAttributeEntity>? = null
override fun equals(other: Any?): Boolean = other is AllAttributeV2Entity && other.id.forceCompare(id)
override fun hashCode(): Int = if (id == null) 0 else id!!.hashCode()
}
| agpl-3.0 | e49ba95f4fcb76103f1f9f41932908b2 | 26.298246 | 106 | 0.694087 | 4.228261 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/rendering/TypeInferenceError.kt | 2 | 1002 | fun <K, V> testMutableMapEntry(<warning descr="[UNUSED_PARAMETER] Parameter 'map' is never used">map</warning>: MutableMap<K, V>, <warning descr="[UNUSED_PARAMETER] Parameter 'k1' is never used">k1</warning>: K, <warning descr="[UNUSED_PARAMETER] Parameter 'v' is never used">v</warning>: V) {
}
fun foo() {
testMutableMapEntry(hashMap(1 to 'a'), <error descr="[NO_VALUE_FOR_PARAMETER] No value passed for parameter 'v'">'b')</error>
}
//extract from library
fun <K, V> hashMap(<warning descr="[UNUSED_PARAMETER] Parameter 'p' is never used">p</warning>: Pair<K, V>): MutableMap<K, V> {<error descr="[NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY] A 'return' expression required in a function with a block body ('{...}')">}</error>
infix fun <K, V> K.to(<warning descr="[UNUSED_PARAMETER] Parameter 'v' is never used">v</warning>: V): Pair<K, V> {<error descr="[NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY] A 'return' expression required in a function with a block body ('{...}')">}</error>
class Pair<K, V> {} | apache-2.0 | f783934bd424d264b7b3a346c521673c | 90.181818 | 293 | 0.690619 | 3.34 | false | true | false | false |
GunoH/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/text/CommentProblemFilter.kt | 2 | 2378 | package com.intellij.grazie.text
import ai.grazie.nlp.tokenizer.sentence.StandardSentenceTokenizer
import com.intellij.grazie.text.TextContent.TextDomain.COMMENTS
import com.intellij.grazie.text.TextContent.TextDomain.DOCUMENTATION
import com.intellij.grazie.utils.Text
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.search.PsiTodoSearchHelper
import com.intellij.psi.util.CachedValuesManager
internal class CommentProblemFilter : ProblemFilter() {
private val tokenizer
get() = StandardSentenceTokenizer.Default
override fun shouldIgnore(problem: TextProblem): Boolean {
val text = problem.text
val domain = text.domain
if (domain == COMMENTS || domain == DOCUMENTATION) {
if (isTodoComment(text.containingFile, text)) {
return true
}
if (problem.rule.globalId.startsWith("LanguageTool.") && isAboutIdentifierParts(problem, text)) {
return true
}
if (isInFirstSentence(problem) && problem.fitsGroup(RuleGroup(RuleGroup.INCOMPLETE_SENTENCE))) {
return true
}
}
if (domain == COMMENTS) {
if (problem.fitsGroup(RuleGroup(RuleGroup.UNDECORATED_SENTENCE_SEPARATION))) {
return true
}
if (Text.isSingleSentence(text) && problem.fitsGroup(RuleGroup.UNDECORATED_SINGLE_SENTENCE)) {
return true
}
}
return false
}
private fun textAround(text: CharSequence, range: TextRange): CharSequence {
return text.subSequence((range.startOffset - 20).coerceAtLeast(0), (range.endOffset + 20).coerceAtMost(text.length))
}
private fun isInFirstSentence(problem: TextProblem) =
tokenizer.tokenize(problem.text.substring(0, problem.highlightRanges[0].startOffset)).size <= 1
private fun isAboutIdentifierParts(problem: TextProblem, text: TextContent): Boolean {
val ranges = problem.highlightRanges
return ranges.any { text.subSequence(0, it.startOffset).endsWith('_') || text.subSequence(it.endOffset, text.length).startsWith('_') }
}
// the _todo_ word spoils the grammar of what follows
private fun isTodoComment(file: PsiFile, text: TextContent): Boolean {
val todos = CachedValuesManager.getProjectPsiDependentCache(file) {
PsiTodoSearchHelper.getInstance(it.project).findTodoItems(it)
}
return todos.any { text.intersectsRange(it.textRange) }
}
}
| apache-2.0 | 7630c742fd15051141f728135935c276 | 37.983607 | 138 | 0.73381 | 4.201413 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/services/DbDumpServiceImpl.kt | 2 | 1930 | package com.github.kerubistan.kerub.services
import com.github.kerubistan.kerub.utils.createObjectMapper
import io.github.kerubistan.kroki.exceptions.getStackTraceAsString
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.infinispan.manager.EmbeddedCacheManager
import javax.ws.rs.core.Response
import javax.ws.rs.core.StreamingOutput
class DbDumpServiceImpl(private val cacheManager: EmbeddedCacheManager) : DbDumpService {
companion object {
private val mapper = createObjectMapper(true)
}
override fun dump(): Response =
Response.ok().header("content-disposition", """attachment; filename="dump.tar"""")
.entity(StreamingOutput { output ->
TarArchiveOutputStream(output).use { tar ->
cacheManager.cacheNames.map { name -> name to cacheManager.getCache<Any, Any>(name) }
.forEach { (cacheName, cache) ->
tar.putArchiveEntry(TarArchiveEntry("$cacheName/"))
tar.closeArchiveEntry()
cache.advancedCache.keys.forEach { key ->
val value = cache.advancedCache[key]
try {
val serialized =
mapper.writeValueAsString(value).toByteArray()
tar.putArchiveEntry(TarArchiveEntry("$cacheName/$key.json").apply {
size =
serialized.size.toLong()
})
tar.write(serialized)
tar.closeArchiveEntry()
} catch (t: Throwable) {
val stack =
"value $value \n for key $key \ncould not be serialized\n${t.getStackTraceAsString()}\n".toByteArray()
tar.putArchiveEntry(TarArchiveEntry("$cacheName/$key-error.txt").apply {
size =
stack.size.toLong()
})
tar.write(stack)
tar.closeArchiveEntry()
}
}
}
}
}).build()
} | apache-2.0 | 90b20180acb287bdddcc18e05f1384d7 | 36.862745 | 116 | 0.646632 | 4.269912 | false | false | false | false |
JetBrains/kotlin-native | tools/performance-server/ui/src/main/kotlin/main.kt | 1 | 24904 | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import kotlin.browser.*
import org.w3c.fetch.*
import org.jetbrains.report.json.*
import org.jetbrains.buildInfo.Build
import kotlin.js.*
import kotlin.math.ceil
import org.w3c.dom.*
// API for interop with JS library Chartist.
external class ChartistPlugins {
fun legend(data: dynamic): dynamic
fun ctAxisTitle(data: dynamic): dynamic
}
external object Chartist {
class Svg(form: String, parameters: dynamic, chartArea: String)
val plugins: ChartistPlugins
val Interpolation: dynamic
fun Line(query: String, data: dynamic, options: dynamic): dynamic
}
data class Commit(val revision: String, val developer: String)
fun sendGetRequest(url: String) = window.fetch(url, RequestInit("GET")).then { response ->
if (!response.ok)
error("Error during getting response from $url\n" +
"${response}")
else
response.text()
}.then { text -> text }
// Get data for chart in needed format.
fun getChartData(labels: List<String>, valuesList: Collection<List<*>>,
classNames: Array<String>? = null): dynamic {
val chartData: dynamic = object {}
chartData["labels"] = labels.toTypedArray()
chartData["series"] = valuesList.mapIndexed { index, it ->
val series: dynamic = object {}
series["data"] = it.toTypedArray()
classNames?.let { series["className"] = classNames[index] }
series
}.toTypedArray()
return chartData
}
// Create object with options of chart.
fun getChartOptions(samples: Array<String>, yTitle: String, classNames: Array<String>? = null): dynamic {
val chartOptions: dynamic = object {}
chartOptions["fullWidth"] = true
val paddingObject: dynamic = object {}
paddingObject["right"] = 40
chartOptions["chartPadding"] = paddingObject
val axisXObject: dynamic = object {}
axisXObject["offset"] = 40
axisXObject["labelInterpolationFnc"] = { value, index, labels ->
val labelsCount = 20
val skipNumber = ceil((labels.length as Int).toDouble() / labelsCount).toInt()
if (skipNumber > 1) {
if (index % skipNumber == 0) value else null
} else {
value
}
}
chartOptions["axisX"] = axisXObject
val axisYObject: dynamic = object {}
axisYObject["offset"] = 90
chartOptions["axisY"] = axisYObject
val legendObject: dynamic = object {}
legendObject["legendNames"] = samples
classNames?.let { legendObject["classNames"] = classNames.sliceArray(0 until samples.size) }
val titleObject: dynamic = object {}
val axisYTitle: dynamic = object {}
axisYTitle["axisTitle"] = yTitle
axisYTitle["axisClass"] = "ct-axis-title"
val titleOffset: dynamic = {}
titleOffset["x"] = 15
titleOffset["y"] = 15
axisYTitle["offset"] = titleOffset
axisYTitle["textAnchor"] = "middle"
axisYTitle["flipTitle"] = true
titleObject["axisY"] = axisYTitle
val interpolationObject: dynamic = {}
interpolationObject["fillHoles"] = true
chartOptions["lineSmooth"] = Chartist.Interpolation.simple(interpolationObject)
chartOptions["plugins"] = arrayOf(Chartist.plugins.legend(legendObject), Chartist.plugins.ctAxisTitle(titleObject))
return chartOptions
}
fun redirect(url: String) {
window.location.href = url
}
// Set customizations rules for chart.
fun customizeChart(chart: dynamic, chartContainer: String, jquerySelector: dynamic, builds: List<Build?>,
parameters: Map<String, String>) {
chart.on("draw", { data ->
var element = data.element
if (data.type == "point") {
val pointSize = 12
val currentBuild = builds.get(data.index)
currentBuild?.let { currentBuild ->
// Higlight builds with failures.
if (currentBuild.failuresNumber > 0) {
val svgParameters: dynamic = object {}
svgParameters["d"] = arrayOf("M", data.x, data.y - pointSize,
"L", data.x - pointSize, data.y + pointSize / 2,
"L", data.x + pointSize, data.y + pointSize / 2, "z").joinToString(" ")
svgParameters["style"] = "fill:rgb(255,0,0);stroke-width:0"
val triangle = Chartist.Svg("path", svgParameters, chartContainer)
element = data.element.replace(triangle)
} else if (currentBuild.buildNumber == parameters["build"]) {
// Higlight choosen build.
val svgParameters: dynamic = object {}
svgParameters["x"] = data.x - pointSize / 2
svgParameters["y"] = data.y - pointSize / 2
svgParameters["height"] = pointSize
svgParameters["width"] = pointSize
svgParameters["style"] = "fill:rgb(0,0,255);stroke-width:0"
val rectangle = Chartist.Svg("rect", svgParameters, "ct-point")
element = data.element.replace(rectangle)
}
// Add tooltips.
var shift = 1
var previousBuild: Build? = null
while (previousBuild == null && data.index - shift >= 0) {
previousBuild = builds.get(data.index - shift)
shift++
}
val linkToDetailedInfo = "https://kotlin-native-performance.labs.jb.gg/?report=" +
"${currentBuild.buildNumber}:${parameters["target"]}" +
"${previousBuild?.let {
"&compareTo=${previousBuild.buildNumber}:${parameters["target"]}"
} ?: ""}"
val information = buildString {
append("<a href=\"$linkToDetailedInfo\">${currentBuild.buildNumber}</a><br>")
append("Value: ${data.value.y.toFixed(4)}<br>")
if (currentBuild.failuresNumber > 0) {
append("failures: ${currentBuild.failuresNumber}<br>")
}
append("branch: ${currentBuild.branch}<br>")
append("date: ${currentBuild.date}<br>")
append("time: ${currentBuild.formattedStartTime}-${currentBuild.formattedFinishTime}<br>")
append("Commits:<br>")
val commitsList = (JsonTreeParser.parse("{${currentBuild.commits}}") as JsonObject).getArray("commits").map {
Commit(
(it as JsonObject).getPrimitive("revision").content,
(it as JsonObject).getPrimitive("developer").content
)
}
val commits = if (commitsList.size > 3) commitsList.slice(0..2) else commitsList
commits.forEach {
append("${it.revision.substring(0, 7)} by ${it.developer}<br>")
}
if (commitsList.size > 3) {
append("...")
}
}
element._node.setAttribute("title", information)
element._node.setAttribute("data-chart-tooltip", chartContainer)
element._node.addEventListener("click", {
redirect(linkToDetailedInfo)
})
}
}
})
chart.on("created", {
val currentChart = jquerySelector
val parameters: dynamic = object {}
parameters["selector"] = "[data-chart-tooltip=\"$chartContainer\"]"
parameters["container"] = "#$chartContainer"
parameters["html"] = true
currentChart.tooltip(parameters)
})
}
var buildsNumberToShow: Int = 200
var beforeDate: String? = null
var afterDate: String? = null
external fun decodeURIComponent(url: String): String
external fun encodeURIComponent(url: String): String
fun getDatesComponents() = "${beforeDate?.let {"&before=${encodeURIComponent(it)}"} ?: ""}" +
"${afterDate?.let {"&after=${encodeURIComponent(it)}"} ?: ""}"
fun main(args: Array<String>) {
val serverUrl = "https://kotlin-native-perf-summary.labs.jb.gg"
val zoomRatio = 2
// Get parameters from request.
val url = window.location.href
val parametersPart = url.substringAfter("?").split('&')
val parameters = mutableMapOf("target" to "Linux", "type" to "dev", "build" to "", "branch" to "master")
parametersPart.forEach {
val parsedParameter = it.split("=", limit = 2)
if (parsedParameter.size == 2) {
val (key, value) = parsedParameter
parameters[key] = value
}
}
buildsNumberToShow = parameters["count"]?.toInt() ?: buildsNumberToShow
beforeDate = parameters["before"]?.let { decodeURIComponent(it) }
afterDate = parameters["after"]?.let { decodeURIComponent(it) }
// Get branches.
val branchesUrl = "$serverUrl/branches"
sendGetRequest(branchesUrl).then { response ->
val branches: Array<String> = JSON.parse(response)
// Add release branches to selector.
branches.filter { it != "master" }.forEach {
if ("v(\\d|\\.)+(-M\\d)?-fixes".toRegex().matches(it)) {
val option = Option(it, it)
js("$('#inputGroupBranch')").append(js("$(option)"))
}
}
document.querySelector("#inputGroupBranch [value=\"${parameters["branch"]}\"]")?.setAttribute("selected", "true")
}
// Fill autocomplete list with build numbers.
val buildsNumbersUrl = "$serverUrl/buildsNumbers/${parameters["target"]}"
sendGetRequest(buildsNumbersUrl).then { response ->
val buildsNumbers: Array<String> = JSON.parse(response)
val autocompleteParameters: dynamic = object {}
autocompleteParameters["lookup"] = buildsNumbers
autocompleteParameters["onSelect"] = { suggestion ->
if (suggestion.value != parameters["build"]) {
val newLink = "http://${window.location.host}/?target=${parameters["target"]}&type=${parameters["type"]}" +
"${if ((suggestion.value as String).isEmpty()) "" else "&build=${suggestion.value}"}&count=$buildsNumberToShow" +
getDatesComponents()
window.location.href = newLink
}
}
js("$( \"#highligted_build\" )").autocomplete(autocompleteParameters)
js("$('#highligted_build')").change({ value ->
val newValue = js("$(this).val()").toString()
if (newValue.isEmpty() || newValue in buildsNumbers) {
val newLink = "http://${window.location.host}/?target=${parameters["target"]}&type=${parameters["type"]}" +
"${if (newValue.isEmpty()) "" else "&build=$newValue"}&count=$buildsNumberToShow" +
getDatesComponents()
window.location.href = newLink
}
})
}
// Change inputs values connected with parameters and add events listeners.
document.querySelector("#inputGroupTarget [value=\"${parameters["target"]}\"]")?.setAttribute("selected", "true")
document.querySelector("#inputGroupBuildType [value=\"${parameters["type"]}\"]")?.setAttribute("selected", "true")
(document.getElementById("highligted_build") as HTMLInputElement).value = parameters["build"]!!
// Add onChange events for fields.
// Don't use AJAX to have opportunity to share results with simple links.
js("$('#inputGroupTarget')").change({
val newValue = js("$(this).val()")
if (newValue != parameters["target"]) {
val newLink = "http://${window.location.host}/?target=$newValue&type=${parameters["type"]}&branch=${parameters["branch"]}" +
"${if (parameters["build"]!!.isEmpty()) "" else "&build=${parameters["build"]}"}&count=$buildsNumberToShow"
window.location.href = newLink
}
})
js("$('#inputGroupBuildType')").change({
val newValue = js("$(this).val()")
if (newValue != parameters["type"]) {
val newLink = "http://${window.location.host}/?target=${parameters["target"]}&type=$newValue&branch=${parameters["branch"]}" +
"${if (parameters["build"]!!.isEmpty()) "" else "&build=${parameters["build"]}"}&count=$buildsNumberToShow"
window.location.href = newLink
}
})
js("$('#inputGroupBranch')").change({
val newValue = js("$(this).val()")
if (newValue != parameters["branch"]) {
val newLink = "http://${window.location.host}/?target=${parameters["target"]}&type=${parameters["type"]}&branch=$newValue" +
"${if (parameters["build"]!!.isEmpty()) "" else "&build=${parameters["build"]}"}&count=$buildsNumberToShow"
window.location.href = newLink
}
})
val platformSpecificBenchs = if (parameters["target"] == "Mac_OS_X") ",FrameworkBenchmarksAnalyzer,SpaceFramework_iosX64" else
if (parameters["target"] == "Linux") ",kotlinx.coroutines" else ""
var execData = listOf<String>() to listOf<List<Double?>>()
var compileData = listOf<String>() to listOf<List<Double?>>()
var codeSizeData = listOf<String>() to listOf<List<Double?>>()
var bundleSizeData = listOf<String>() to listOf<List<Int?>>()
val sizeClassNames = arrayOf("ct-series-e", "ct-series-f", "ct-series-g")
// Draw charts.
var execChart: dynamic = null
var compileChart: dynamic = null
var codeSizeChart: dynamic = null
var bundleSizeChart: dynamic = null
val descriptionUrl = "$serverUrl/buildsDesc/${parameters["target"]}?type=${parameters["type"]}" +
"${if (parameters["branch"] != "all") "&branch=${parameters["branch"]}" else ""}&count=$buildsNumberToShow" +
getDatesComponents()
val metricUrl = "$serverUrl/metricValue/${parameters["target"]}/"
val unstableBenchmarksPromise = sendGetRequest("$serverUrl/unstable").then { response ->
val unstableList = response as String
val data = JsonTreeParser.parse(unstableList)
if (data !is JsonArray) {
error("Response is expected to be an array.")
}
data.jsonArray.map {
(it as JsonPrimitive).content
}
}
// Get builds description.
val buildsInfoPromise = sendGetRequest(descriptionUrl).then { response ->
val buildsInfo = response as String
val data = JsonTreeParser.parse(buildsInfo)
if (data !is JsonArray) {
error("Response is expected to be an array.")
}
data.jsonArray.map {
val element = it as JsonElement
if (element.isNull) null else Build.create(element as JsonObject)
}
}
unstableBenchmarksPromise.then { unstableBenchmarks ->
// Collect information for charts library.
val valuesToShow = mapOf("EXECUTION_TIME" to listOf(mapOf(
"normalize" to "true"
),
mapOf(
"normalize" to "true",
"exclude" to unstableBenchmarks.joinToString(",")
)),
"COMPILE_TIME" to listOf(mapOf(
"samples" to "HelloWorld,Videoplayer$platformSpecificBenchs",
"agr" to "samples"
)),
"CODE_SIZE" to listOf(mapOf(
"normalize" to "true",
"exclude" to if (parameters["target"] == "Linux")
"kotlinx.coroutines"
else if (parameters["target"] == "Mac_OS_X")
"SpaceFramework_iosX64"
else ""
), if (platformSpecificBenchs.isNotEmpty()) mapOf(
"normalize" to "true",
"agr" to "samples",
"samples" to platformSpecificBenchs.removePrefix(",")
) else null).filterNotNull(),
"BUNDLE_SIZE" to listOf(mapOf("samples" to "KotlinNative",
"agr" to "samples"))
)
// Send requests to get all needed metric values.
valuesToShow.map { (metric, listOfSettings) ->
val resultValues = listOfSettings.map { settings ->
val getParameters = with(StringBuilder()) {
if (settings.isNotEmpty()) {
append("?")
}
var prefix = ""
settings.forEach { (key, value) ->
if (value.isNotEmpty()) {
append("$prefix$key=$value")
prefix = "&"
}
}
toString()
}
val branchParameter = if (parameters["branch"] != "all")
(if (getParameters.isEmpty()) "?" else "&") + "branch=${parameters["branch"]}"
else ""
val url = "$metricUrl$metric$getParameters$branchParameter${
if (parameters["type"] != "all")
(if (getParameters.isEmpty() && branchParameter.isEmpty()) "?" else "&") + "type=${parameters["type"]}"
else ""
}&count=$buildsNumberToShow${getDatesComponents()}"
sendGetRequest(url)
}.toTypedArray()
// Get metrics values for charts.
Promise.all(resultValues).then { responses ->
val valuesList = responses.map { response ->
val results = (JsonTreeParser.parse(response) as JsonArray).map {
(it as JsonObject).getPrimitive("first").content to
it.getArray("second").map { (it as JsonPrimitive).doubleOrNull }
}
val labels = results.map { it.first }
val values = results[0]?.second?.size?.let { (0..it - 1).map { i -> results.map { it.second[i] } } }
?: emptyList()
labels to values
}
val labels = valuesList[0].first
val values = valuesList.map { it.second }.reduce { acc, valuesPart -> acc + valuesPart }
when (metric) {
// Update chart with gotten data.
"COMPILE_TIME" -> {
compileData = labels to values.map { it.map { it?.let { it / 1000 } } }
compileChart = Chartist.Line("#compile_chart",
getChartData(labels, compileData.second),
getChartOptions(valuesToShow["COMPILE_TIME"]!![0]!!["samples"]!!.split(',').toTypedArray(),
"Time, milliseconds"))
buildsInfoPromise.then { builds ->
customizeChart(compileChart, "compile_chart", js("$(\"#compile_chart\")"), builds, parameters)
compileChart.update(getChartData(compileData.first, compileData.second))
}
}
"EXECUTION_TIME" -> {
execData = labels to values
execChart = Chartist.Line("#exec_chart",
getChartData(labels, execData.second),
getChartOptions(arrayOf("Geometric Mean (All)", "Geometric mean (Stable)"),
"Normalized time"))
buildsInfoPromise.then { builds ->
customizeChart(execChart, "exec_chart", js("$(\"#exec_chart\")"), builds, parameters)
execChart.update(getChartData(execData.first, execData.second))
}
}
"CODE_SIZE" -> {
codeSizeData = labels to values
codeSizeChart = Chartist.Line("#codesize_chart",
getChartData(labels, codeSizeData.second),
getChartOptions(arrayOf("Geometric Mean") + platformSpecificBenchs.split(',')
.filter { it.isNotEmpty() },
"Normalized size",
arrayOf("ct-series-4", "ct-series-5", "ct-series-6")))
buildsInfoPromise.then { builds ->
customizeChart(codeSizeChart, "codesize_chart", js("$(\"#codesize_chart\")"), builds, parameters)
codeSizeChart.update(getChartData(codeSizeData.first, codeSizeData.second, sizeClassNames))
}
}
"BUNDLE_SIZE" -> {
bundleSizeData = labels to values.map { it.map { it?.let { it.toInt() / 1024 / 1024 } } }
bundleSizeChart = Chartist.Line("#bundlesize_chart",
getChartData(labels,
bundleSizeData.second, sizeClassNames),
getChartOptions(arrayOf("Bundle size"), "Size, MB", arrayOf("ct-series-4")))
buildsInfoPromise.then { builds ->
customizeChart(bundleSizeChart, "bundlesize_chart", js("$(\"#bundlesize_chart\")"), builds, parameters)
bundleSizeChart.update(getChartData(bundleSizeData.first, bundleSizeData.second, sizeClassNames))
}
}
else -> error("No chart for metric $metric")
}
true
}
}
}
// Update all charts with using same data.
val updateAllCharts: () -> Unit = {
execChart.update(getChartData(execData.first, execData.second))
compileChart.update(getChartData(compileData.first, compileData.second))
codeSizeChart.update(getChartData(codeSizeData.first, codeSizeData.second, sizeClassNames))
bundleSizeChart.update(getChartData(bundleSizeData.first, bundleSizeData.second, sizeClassNames))
}
js("$('#plusBtn')").click({
buildsNumberToShow =
if (buildsNumberToShow / zoomRatio > zoomRatio) {
buildsNumberToShow / zoomRatio
} else {
buildsNumberToShow
}
val newLink = "http://${window.location.host}/?target=${parameters["target"]}&type=${parameters["type"]}&branch=${parameters["branch"]}" +
"${if (parameters["build"]!!.isEmpty()) "" else "&build=${parameters["build"]}"}&count=$buildsNumberToShow" +
getDatesComponents()
window.location.href = newLink
Unit
})
js("$('#minusBtn')").click({
buildsNumberToShow = buildsNumberToShow * zoomRatio
val newLink = "http://${window.location.host}/?target=${parameters["target"]}&type=${parameters["type"]}&branch=${parameters["branch"]}" +
"${if (parameters["build"]!!.isEmpty()) "" else "&build=${parameters["build"]}"}&count=$buildsNumberToShow" +
getDatesComponents()
window.location.href = newLink
Unit
})
js("$('#prevBtn')").click({
buildsInfoPromise.then { builds ->
beforeDate = builds.firstOrNull()?.startTime
afterDate = null
val newLink = "http://${window.location.host}/?target=${parameters["target"]}&type=${parameters["type"]}&branch=${parameters["branch"]}" +
"${if (parameters["build"]!!.isEmpty()) "" else "&build=${parameters["build"]}"}&count=$buildsNumberToShow" +
"${beforeDate?.let {"&before=${encodeURIComponent(it)}"} ?: ""}"
window.location.href = newLink
}
})
js("$('#nextBtn')").click({
buildsInfoPromise.then { builds ->
beforeDate = null
afterDate = builds.lastOrNull()?.startTime
val newLink = "http://${window.location.host}/?target=${parameters["target"]}&type=${parameters["type"]}&branch=${parameters["branch"]}" +
"${if (parameters["build"]!!.isEmpty()) "" else "&build=${parameters["build"]}"}&count=$buildsNumberToShow" +
"${afterDate?.let {"&after=${encodeURIComponent(it)}"} ?: ""}"
window.location.href = newLink
}
})
// Auto reload.
parameters["refresh"]?.let {
// Set event.
window.setInterval({
window.location.reload()
}, it.toInt() * 1000)
}
} | apache-2.0 | f74967abf0cd3ba747d910af954346e9 | 46.894231 | 150 | 0.547623 | 4.760849 | false | false | false | false |
GunoH/intellij-community | platform/usageView/src/com/intellij/usages/impl/UsageViewStatisticsCollector.kt | 1 | 10655 | // 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.usages.impl
import com.intellij.ide.util.scopeChooser.ScopeIdMapper
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.PrimitiveEventField
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.lang.Language
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.search.SearchScope
import com.intellij.usageView.UsageInfo
import com.intellij.usages.Usage
import com.intellij.usages.UsageView
import com.intellij.usages.rules.PsiElementUsage
import org.jetbrains.annotations.Nls
enum class CodeNavigateSource {
ShowUsagesPopup,
FindToolWindow
}
enum class TooManyUsagesUserAction {
Shown,
Aborted,
Continued
}
class UsageViewStatisticsCollector : CounterUsagesCollector() {
override fun getGroup() = GROUP
companion object {
val GROUP = EventLogGroup("usage.view", 10)
val USAGE_VIEW = object : PrimitiveEventField<UsageView>() {
override val name: String = "usage_view"
override fun addData(fuData: FeatureUsageData, value: UsageView) {
fuData.addData(name, value.id)
}
override val validationRule: List<String>
get() = listOf("{regexp#integer}")
}
private val REFERENCE_CLASS = EventFields.Class("reference_class")
private val USAGE_SHOWN = GROUP.registerEvent("usage.shown", USAGE_VIEW, REFERENCE_CLASS, EventFields.Language)
private val USAGE_NAVIGATE = GROUP.registerEvent("usage.navigate", REFERENCE_CLASS, EventFields.Language)
private val UI_LOCATION = EventFields.Enum("ui_location", CodeNavigateSource::class.java)
private val itemChosen = GROUP.registerEvent("item.chosen", USAGE_VIEW, UI_LOCATION, EventFields.Language)
const val SCOPE_RULE_ID = "scopeRule"
private val SYMBOL_CLASS = EventFields.Class("symbol")
private val SEARCH_SCOPE = EventFields.StringValidatedByCustomRule("scope", ScopeRuleValidator::class.java)
private val RESULTS_TOTAL = EventFields.Int("results_total")
private val FIRST_RESULT_TS = EventFields.Long("duration_first_results_ms")
private val TOO_MANY_RESULTS = EventFields.Boolean("too_many_result_warning")
private val searchStarted = GROUP.registerVarargEvent("started", USAGE_VIEW, UI_LOCATION)
private val searchCancelled = GROUP.registerVarargEvent("cancelled",
SYMBOL_CLASS,
SEARCH_SCOPE,
EventFields.Language,
RESULTS_TOTAL,
FIRST_RESULT_TS,
EventFields.DurationMs,
TOO_MANY_RESULTS,
UI_LOCATION,
USAGE_VIEW)
private val searchFinished = GROUP.registerVarargEvent("finished",
SYMBOL_CLASS,
SEARCH_SCOPE,
EventFields.Language,
RESULTS_TOTAL,
FIRST_RESULT_TS,
EventFields.DurationMs,
TOO_MANY_RESULTS,
UI_LOCATION,
USAGE_VIEW)
private val tabSwitched = GROUP.registerEvent("switch.tab", USAGE_VIEW)
private val PREVIOUS_SCOPE = EventFields.StringValidatedByCustomRule("previous", ScopeRuleValidator::class.java)
private val NEW_SCOPE = EventFields.StringValidatedByCustomRule("new", ScopeRuleValidator::class.java)
private val scopeChanged = GROUP.registerVarargEvent("scope.changed", USAGE_VIEW, PREVIOUS_SCOPE, NEW_SCOPE, SYMBOL_CLASS)
private val OPEN_IN_FIND_TOOL_WINDOW = GROUP.registerEvent("open.in.tool.window", USAGE_VIEW)
private val USER_ACTION = EventFields.Enum("userAction", TooManyUsagesUserAction::class.java)
private val tooManyUsagesDialog = GROUP.registerVarargEvent("tooManyResultsDialog",
USAGE_VIEW,
USER_ACTION,
SYMBOL_CLASS,
SEARCH_SCOPE,
EventFields.Language
)
@JvmStatic
fun logSearchStarted(project: Project?, usageView: UsageView, source: CodeNavigateSource) {
searchStarted.log(project, USAGE_VIEW.with(usageView), UI_LOCATION.with(source))
}
@JvmStatic
fun logUsageShown(project: Project?, referenceClass: Class<out Any>, language: Language?, usageView:UsageView) {
USAGE_SHOWN.log(project, usageView, referenceClass, language)
}
@JvmStatic
fun logUsageNavigate(project: Project?, usage: Usage) {
UsageReferenceClassProvider.getReferenceClass(usage)?.let {
USAGE_NAVIGATE.log(
project,
it,
(usage as? PsiElementUsage)?.element?.language,
)
}
}
@JvmStatic
fun logUsageNavigate(project: Project?, usage: UsageInfo) {
usage.referenceClass?.let {
USAGE_NAVIGATE.log(
project,
it,
usage.element?.language,
)
}
}
@JvmStatic
fun logItemChosen(project: Project?, usageView: UsageView, source: CodeNavigateSource, language: Language) = itemChosen.log(project,
usageView,
source,
language)
@JvmStatic
fun logSearchCancelled(project: Project?,
targetClass: Class<*>,
scope: SearchScope?,
language: Language?,
results: Int,
durationFirstResults: Long,
duration: Long,
tooManyResult: Boolean,
source: CodeNavigateSource,
usageView: UsageView) {
searchCancelled.log(project,
SYMBOL_CLASS.with(targetClass),
SEARCH_SCOPE.with(scope?.let { ScopeIdMapper.instance.getScopeSerializationId(it.displayName) }),
EventFields.Language.with(language),
RESULTS_TOTAL.with(results),
FIRST_RESULT_TS.with(durationFirstResults),
EventFields.DurationMs.with(duration),
TOO_MANY_RESULTS.with(tooManyResult),
UI_LOCATION.with(source),
USAGE_VIEW.with(usageView))
}
@JvmStatic
fun logSearchFinished(
project: Project?,
targetClass: Class<*>,
scope: SearchScope?,
language: Language?,
results: Int,
durationFirstResults: Long,
duration: Long,
tooManyResult: Boolean,
source: CodeNavigateSource,
usageView : UsageView
) {
searchFinished.log(project,
USAGE_VIEW.with(usageView),
SYMBOL_CLASS.with(targetClass),
SEARCH_SCOPE.with(scope?.let { ScopeIdMapper.instance.getScopeSerializationId(it.displayName) }),
EventFields.Language.with(language),
RESULTS_TOTAL.with(results),
FIRST_RESULT_TS.with(durationFirstResults),
EventFields.DurationMs.with(duration),
TOO_MANY_RESULTS.with(tooManyResult),
UI_LOCATION.with(source))
}
@JvmStatic
fun logTabSwitched(project: Project?, usageView:UsageView) = tabSwitched.log(project, usageView)
@JvmStatic
fun logScopeChanged(
project: Project?,
usageView: UsageView,
previousScope: SearchScope?,
newScope: SearchScope?,
symbolClass: Class<*>,
) {
val scopeIdMapper = ScopeIdMapper.instance
scopeChanged.log(project, USAGE_VIEW.with(usageView),
PREVIOUS_SCOPE.with(previousScope?.let { scopeIdMapper.getScopeSerializationId(it.displayName) }),
NEW_SCOPE.with(newScope?.let { scopeIdMapper.getScopeSerializationId(it.displayName) }),
SYMBOL_CLASS.with(symbolClass))
}
@JvmStatic
fun logTooManyDialog(
project: Project?,
usageView: UsageView,
action: TooManyUsagesUserAction,
targetClass: Class<out PsiElement>?,
@Nls scope: String,
language: Language?,
) {
tooManyUsagesDialog.log(project,
USAGE_VIEW.with(usageView),
USER_ACTION.with(action),
SYMBOL_CLASS.with(targetClass ?: String::class.java),
SEARCH_SCOPE.with(ScopeIdMapper.instance.getScopeSerializationId(scope)),
EventFields.Language.with(language))
}
@JvmStatic
fun logOpenInFindToolWindow(project: Project?, usageView: UsageView) =
OPEN_IN_FIND_TOOL_WINDOW.log(project, usageView)
}
}
class ScopeRuleValidator : CustomValidationRule() {
override fun doValidate(data: String, context: EventContext): ValidationResultType =
if (ScopeIdMapper.standardNames.contains(data)) ValidationResultType.ACCEPTED else ValidationResultType.REJECTED
override fun getRuleId(): String = UsageViewStatisticsCollector.SCOPE_RULE_ID
} | apache-2.0 | b0ca1b091d1c3268f453621f71f4d3d7 | 44.152542 | 138 | 0.582825 | 5.458504 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/KotlinNewProjectWizard.kt | 1 | 4274 | // 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.tools.projectWizard
import com.intellij.ide.JavaUiBundle
import com.intellij.ide.wizard.*
import com.intellij.ide.wizard.util.LinkNewProjectWizardStep
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.util.SystemProperties
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.tools.projectWizard.core.asPath
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectTemplates.applyProjectTemplate
import org.jetbrains.kotlin.tools.projectWizard.projectTemplates.ConsoleApplicationProjectTemplate
import org.jetbrains.kotlin.tools.projectWizard.wizard.NewProjectWizardModuleBuilder
import java.util.*
class KotlinNewProjectWizard : LanguageNewProjectWizard {
override val ordinal = 100
companion object {
private const val DEFAULT_GROUP_ID = "me.user"
fun generateProject(
project: Project,
projectPath: String,
projectName: String,
sdk: Sdk?,
buildSystemType: BuildSystemType,
projectGroupId: String? = suggestGroupId(),
artifactId: String? = projectName,
version: String? = "1.0-SNAPSHOT"
) {
NewProjectWizardModuleBuilder()
.apply {
wizard.apply(emptyList(), setOf(GenerationPhase.PREPARE))
wizard.jdk = sdk
wizard.context.writeSettings {
StructurePlugin.name.reference.setValue(projectName)
StructurePlugin.projectPath.reference.setValue(projectPath.asPath())
projectGroupId?.let { StructurePlugin.groupId.reference.setValue(it) }
artifactId?.let { StructurePlugin.artifactId.reference.setValue(it) }
version?.let { StructurePlugin.version.reference.setValue(it) }
BuildSystemPlugin.type.reference.setValue(buildSystemType)
applyProjectTemplate(ConsoleApplicationProjectTemplate)
}
}.commit(project, null, null)
}
private fun suggestGroupId(): String {
val username = SystemProperties.getUserName()
if (!username.matches("[\\w\\s]+".toRegex())) return DEFAULT_GROUP_ID
val usernameAsGroupId = username.trim().lowercase(Locale.getDefault()).split("\\s+".toRegex()).joinToString(separator = ".")
return "me.$usernameAsGroupId"
}
}
override val name: String = "Kotlin"
override fun createStep(parent: NewProjectWizardLanguageStep) =
CommentStep(parent)
.chain(::Step)
class CommentStep(parent: NewProjectWizardLanguageStep) : LinkNewProjectWizardStep(parent), LanguageNewProjectWizardData by parent {
override val isFullWidth: Boolean = false
override val builderId: String = NewProjectWizardModuleBuilder.MODULE_BUILDER_ID
override val comment: String = KotlinBundle.message("project.wizard.new.project.kotlin.comment")
}
class Step(parent: CommentStep) :
AbstractNewProjectWizardMultiStep<Step, BuildSystemKotlinNewProjectWizard>(parent, BuildSystemKotlinNewProjectWizard.EP_NAME),
LanguageNewProjectWizardData by parent,
BuildSystemKotlinNewProjectWizardData {
override val self = this
override val label = JavaUiBundle.message("label.project.wizard.new.project.build.system")
override val buildSystemProperty by ::stepProperty
override var buildSystem by ::step
init {
data.putUserData(BuildSystemKotlinNewProjectWizardData.KEY, this)
}
}
} | apache-2.0 | a6cec4fbd15dc2cc765ec3c0be6c8588 | 44.478723 | 158 | 0.703088 | 5.250614 | false | false | false | false |
mr-max/anko | dsl/testData/functional/percent/ViewTest.kt | 2 | 2330 | public object `$$Anko$Factories$PercentViewGroup` {
public val PERCENT_FRAME_LAYOUT = { ctx: Context -> _PercentFrameLayout(ctx) }
public val PERCENT_RELATIVE_LAYOUT = { ctx: Context -> _PercentRelativeLayout(ctx) }
}
public inline fun ViewManager.percentFrameLayout(): android.support.percent.PercentFrameLayout = percentFrameLayout({})
public inline fun ViewManager.percentFrameLayout(init: _PercentFrameLayout.() -> Unit): android.support.percent.PercentFrameLayout {
return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_FRAME_LAYOUT) { init() }
}
public inline fun Context.percentFrameLayout(): android.support.percent.PercentFrameLayout = percentFrameLayout({})
public inline fun Context.percentFrameLayout(init: _PercentFrameLayout.() -> Unit): android.support.percent.PercentFrameLayout {
return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_FRAME_LAYOUT) { init() }
}
public inline fun Activity.percentFrameLayout(): android.support.percent.PercentFrameLayout = percentFrameLayout({})
public inline fun Activity.percentFrameLayout(init: _PercentFrameLayout.() -> Unit): android.support.percent.PercentFrameLayout {
return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_FRAME_LAYOUT) { init() }
}
public inline fun ViewManager.percentRelativeLayout(): android.support.percent.PercentRelativeLayout = percentRelativeLayout({})
public inline fun ViewManager.percentRelativeLayout(init: _PercentRelativeLayout.() -> Unit): android.support.percent.PercentRelativeLayout {
return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_RELATIVE_LAYOUT) { init() }
}
public inline fun Context.percentRelativeLayout(): android.support.percent.PercentRelativeLayout = percentRelativeLayout({})
public inline fun Context.percentRelativeLayout(init: _PercentRelativeLayout.() -> Unit): android.support.percent.PercentRelativeLayout {
return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_RELATIVE_LAYOUT) { init() }
}
public inline fun Activity.percentRelativeLayout(): android.support.percent.PercentRelativeLayout = percentRelativeLayout({})
public inline fun Activity.percentRelativeLayout(init: _PercentRelativeLayout.() -> Unit): android.support.percent.PercentRelativeLayout {
return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_RELATIVE_LAYOUT) { init() }
} | apache-2.0 | 0982b8cf4ba93f411d770085e77cd673 | 67.558824 | 141 | 0.793133 | 4.784394 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/_custom/view/RatioImageView.kt | 1 | 2328 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.ui._custom.view
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
/**
* ================================================
* ไธไธช่ฝไฟๆๆฏไพ็ ImageView
* ๆๆถๅชๆฏๆ็ปดๆๅฎฝๅบฆ้ๅบ้ซๅบฆ
*
* Created by NIRVANA on 2017/09/07
* Contact with <[email protected]>
* ================================================
*/
class RatioImageView : AppCompatImageView {
private var originalWidth: Int = 0
private var originalHeight: Int = 0
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
fun setOriginalSize(originalWidth: Int, originalHeight: Int) {
this.originalWidth = originalWidth
this.originalHeight = originalHeight
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (originalWidth > 0 && originalHeight > 0) {
val ratio = originalWidth.toFloat() / originalHeight.toFloat()
var width = MeasureSpec.getSize(widthMeasureSpec)
var height = MeasureSpec.getSize(heightMeasureSpec)
//็ฐๅจๅชๆฏๆๅบๅฎๅฎฝๅบฆ
if (width > 0) {
height = (width.toFloat() / ratio).toInt()
} else if (height > 0) {
width = (height.toFloat() * ratio).toInt()
}
setMeasuredDimension(width, height)
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
}
| apache-2.0 | fa294aa5af4852a9f41c82f7b23d7dc9 | 32.850746 | 111 | 0.640212 | 4.508946 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/_custom/view/LoadingView.kt | 1 | 4270 | package com.zwq65.unity.ui._custom.view
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.SizeUtils
import com.zwq65.unity.R
import com.zwq65.unity.ui._base.BaseSubView
/**
* ================================================
* ็จไบๆพ็คบLoading็[View]๏ผๆฏๆ้ข่ฒๅๅคงๅฐ็่ฎพ็ฝฎใ
*
* Created by NIRVANA on 2018/3/20
* Contact with <[email protected]>
* ================================================
*/
class LoadingView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: BaseSubView(context, attrs, defStyleAttr) {
private var mSize: Int = 0
private var mPaintColor: Int = 0
private var mAnimateValue = 0
private var mAnimator: ValueAnimator? = null
private var mPaint: Paint? = null
private val mUpdateListener = ValueAnimator.AnimatorUpdateListener { animation ->
mAnimateValue = animation.animatedValue as Int
invalidate()
}
override fun setUp(context: Context, attrs: AttributeSet?) {
mSize = SizeUtils.dp2px(16f)
mPaintColor = ContextCompat.getColor(context, R.color.dark_gray)
initPaint()
}
private fun initPaint() {
mPaint = Paint()
mPaint!!.color = mPaintColor
mPaint!!.isAntiAlias = true
mPaint!!.strokeCap = Paint.Cap.ROUND
}
fun setColor(color: Int) {
mPaintColor = color
mPaint!!.color = color
invalidate()
}
fun setSize(size: Int) {
mSize = size
requestLayout()
}
fun start() {
if (mAnimator == null) {
mAnimator = ValueAnimator.ofInt(0, LINE_COUNT - 1)
mAnimator!!.addUpdateListener(mUpdateListener)
mAnimator!!.duration = 600
mAnimator!!.repeatMode = ValueAnimator.RESTART
mAnimator!!.repeatCount = ValueAnimator.INFINITE
mAnimator!!.interpolator = LinearInterpolator()
mAnimator!!.start()
} else if (!mAnimator!!.isStarted) {
mAnimator!!.start()
}
}
fun stop() {
if (mAnimator != null) {
mAnimator!!.removeUpdateListener(mUpdateListener)
mAnimator!!.removeAllUpdateListeners()
mAnimator!!.cancel()
mAnimator = null
}
}
private fun drawLoading(canvas: Canvas, rotateDegrees: Int) {
val width = mSize / 12
val height = mSize / 6
mPaint!!.strokeWidth = width.toFloat()
canvas.rotate(rotateDegrees.toFloat(), (mSize / 2).toFloat(), (mSize / 2).toFloat())
canvas.translate((mSize / 2).toFloat(), (mSize / 2).toFloat())
for (i in 0 until LINE_COUNT) {
canvas.rotate(DEGREE_PER_LINE.toFloat())
mPaint!!.alpha = (255f * (i + 1) / LINE_COUNT).toInt()
canvas.translate(0f, (-mSize / 2 + width / 2).toFloat())
canvas.drawLine(0f, 0f, 0f, height.toFloat(), mPaint!!)
canvas.translate(0f, (mSize / 2 - width / 2).toFloat())
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
setMeasuredDimension(mSize, mSize)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val saveCount = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null, Canvas.ALL_SAVE_FLAG)
drawLoading(canvas, mAnimateValue * DEGREE_PER_LINE)
canvas.restoreToCount(saveCount)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
start()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
stop()
}
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility == View.VISIBLE) {
start()
} else {
stop()
}
}
companion object {
private val LINE_COUNT = 12
private val DEGREE_PER_LINE = 360 / LINE_COUNT
}
}
| apache-2.0 | 46930d1a4e22a9e10943d3aa38ee3583 | 30.147059 | 113 | 0.611662 | 4.440252 | false | false | false | false |
mhshams/yekan | vertx-lang-kotlin/src/main/kotlin/io/vertx/lang/kotlin/KotlinVerticleFactory.kt | 2 | 1228 | package io.vertx.lang.kotlin
import io.vertx.core.Verticle
import io.vertx.core.Vertx
import io.vertx.core.impl.verticle.CompilingClassLoader
import io.vertx.core.spi.VerticleFactory
/**
*/
public class KotlinVerticleFactory : VerticleFactory {
private var vertx: Vertx? = null
override fun init(vertx: Vertx) {
this.vertx = vertx
}
override fun prefix(): String {
return "kotlin"
}
override fun createVerticle(name: String, classLoader: ClassLoader): Verticle {
val verticleName = VerticleFactory.removePrefix(name)
val clazz = if (verticleName.endsWith(".kotlin")) {
val compilingLoader = CompilingClassLoader(classLoader, verticleName)
val className = compilingLoader.resolveMainClassName()
compilingLoader.loadClass(className)
} else {
classLoader.loadClass(verticleName)
}
val instance = clazz.newInstance()
return when (instance) {
is KotlinVerticle -> instance.asJavaVerticle
is Verticle -> instance
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
override fun close() {
vertx = null
}
}
| apache-2.0 | 36073bf4c395bf6ef96020193fe610a8 | 26.909091 | 83 | 0.655537 | 4.796875 | false | false | false | false |
android/midi-samples | MidiTools/src/main/java/com/example/android/miditools/MidiCiInitiator.kt | 1 | 9742 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.miditools
import android.media.midi.MidiInputPort
import android.util.Log
import java.time.LocalDateTime
import java.time.temporal.ChronoField
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit
import kotlin.experimental.and
import kotlin.random.Random
// The MIDI 2 API is currently experimental and likely to change.
class MidiCiInitiator {
private fun logByteArray(prefix: String, value: ByteArray, offset: Int, count: Int) {
val builder = StringBuilder(prefix)
for (i in offset until offset + count) {
builder.append(String.format("0x%02X", value[i]))
if (i != value.size - 1) {
builder.append(", ")
}
}
Log.d(TAG, builder.toString())
}
fun setupMidiCI(midiReceiver: WaitingMidiReceiver, inputPort: MidiInputPort, groupId : Int,
deviceManufacturer: ByteArray) : Boolean {
val discoveryHelper = MidiCIDiscoveryHelper()
val sysExConverter = MidiUmpSysExConverter()
discoveryHelper.setSourceMuid(generateSourceMuid())
if (deviceManufacturer.size != 3) {
Log.e(TAG, "Device Manufacturer invalid size")
return false
}
discoveryHelper.setSourceDeviceManufacturer(deviceManufacturer)
val discoveryMessage = discoveryHelper.generateDiscoveryMessage()
val discoveryMessageUmp = sysExConverter.addUmpFramingToSysExMessage(discoveryMessage, groupId)
inputPort.send(discoveryMessageUmp, 0, discoveryMessageUmp.size)
logByteArray("discoveryMessage: ", discoveryMessageUmp, 0, discoveryMessageUmp.size)
var discoveryReplyMessageUmp = waitForMessage(midiReceiver, DISCOVERY_REPLY_TIMEOUT_MILLIS, groupId)
while (discoveryReplyMessageUmp.isNotEmpty()) {
val discoveryReplyMessage =
sysExConverter.removeUmpFramingFromUmpSysExMessage(discoveryReplyMessageUmp)
logByteArray("discoveryReplyMessage: ", discoveryReplyMessageUmp, 0, discoveryReplyMessageUmp.size)
if (discoveryHelper.parseDiscoveryReply(discoveryReplyMessage)) {
break
}
// Try again if message is bad
discoveryReplyMessageUmp = waitForMessage(midiReceiver, DISCOVERY_REPLY_TIMEOUT_MILLIS, groupId)
}
if (discoveryReplyMessageUmp.isEmpty()) {
Log.e(TAG, "No discoveryReplyMessage received")
return false
}
val initiateProtocolMessage = discoveryHelper.generateInitiateProtocolNegotiationMessage()
val initiateProtocolMessageUmp = sysExConverter.addUmpFramingToSysExMessage(initiateProtocolMessage, groupId)
inputPort.send(initiateProtocolMessageUmp, 0, initiateProtocolMessageUmp.size)
logByteArray("initiateProtocolMessage: ", initiateProtocolMessageUmp, 0, initiateProtocolMessageUmp.size)
var initiateReplyMessageUmp = waitForMessage(midiReceiver, DISCOVERY_REPLY_TIMEOUT_MILLIS, groupId)
while (initiateReplyMessageUmp.isNotEmpty()) {
val initiateReplyMessage = sysExConverter.removeUmpFramingFromUmpSysExMessage(initiateReplyMessageUmp)
logByteArray("initiateReplyMessage: ", initiateReplyMessageUmp, 0, initiateReplyMessageUmp.size)
if (discoveryHelper.parseInitiateProtocolNegotiationReply(initiateReplyMessage)) {
break
}
// Try again if message is bad
initiateReplyMessageUmp = waitForMessage(midiReceiver, DISCOVERY_REPLY_TIMEOUT_MILLIS, groupId)
}
if (initiateReplyMessageUmp.isEmpty()) {
Log.e(TAG, "No initiateReplyMessage received")
return false
}
val setNewProtocolMessage = discoveryHelper.generateSetNewProtocolMessage()
val setNewProtocolMessageUmp = sysExConverter.addUmpFramingToSysExMessage(setNewProtocolMessage, groupId)
inputPort.send(setNewProtocolMessageUmp, 0, setNewProtocolMessageUmp.size)
logByteArray("setNewProtocolMessage: ", setNewProtocolMessageUmp, 0, setNewProtocolMessageUmp.size)
TimeUnit.MILLISECONDS.sleep(PAUSE_TIME_FOR_SWITCHING_MILLIS)
val newProtocolInitiatorMessage = discoveryHelper.generateNewProtocolInitiatorMessage()
val newProtocolInitiatorMessageUmp = sysExConverter.addUmpFramingToSysExMessage(newProtocolInitiatorMessage, groupId)
inputPort.send(newProtocolInitiatorMessageUmp, 0, newProtocolInitiatorMessageUmp.size)
logByteArray("newProtocolInitiatorMessage: ", newProtocolInitiatorMessageUmp, 0, newProtocolInitiatorMessageUmp.size)
var newProtocolReplyMessageUmp = waitForMessage(midiReceiver, NEW_PROTOCOL_REPLY_TIMEOUT_MILLIS, groupId)
while (newProtocolReplyMessageUmp.isNotEmpty()) {
val newProtocolReplyMessage = sysExConverter.removeUmpFramingFromUmpSysExMessage(newProtocolReplyMessageUmp)
logByteArray("newProtocolReplyMessage: ", newProtocolReplyMessageUmp, 0, newProtocolReplyMessageUmp.size)
if (discoveryHelper.parseNewProtocolResponderReply(newProtocolReplyMessage)) {
break
}
// Try again if message is bad
newProtocolReplyMessageUmp = waitForMessage(midiReceiver, NEW_PROTOCOL_REPLY_TIMEOUT_MILLIS, groupId)
}
if (newProtocolReplyMessageUmp.isEmpty()) {
Log.e(TAG, "No newProtocolReplyMessage received")
return false
}
val confirmationMessage = discoveryHelper.generateConfirmationNewProtocolMessage()
val confirmationMessageUmp = sysExConverter.addUmpFramingToSysExMessage(confirmationMessage, groupId)
inputPort.send(confirmationMessageUmp, 0, confirmationMessageUmp.size)
Log.d(TAG, "Done with CI")
return true
}
private fun verifyMessageIsMidiSysExMessage(message: ByteArray, groupId: Int): Boolean {
if ((message.isEmpty()) || (message.size % UMP_PACKET_MULTIPLE != 0)) {
return false
}
val targetFirstByte = (SYSEX_DATA_MESSAGE_TYPE shl 4) + groupId
return (message[0] == targetFirstByte.toByte())
}
private fun checkMessageStartsWithSysExStart(message: ByteArray): Boolean {
val curByte = 1
if (curByte < message.size) {
if ((message[curByte] and 0xF0.toByte()) == SYSEX_PACKET_START) {
return true
}
}
return false
}
private fun checkMessageContainsSysExEnd(message: ByteArray): Boolean {
var curByte = 1
while (curByte < message.size) {
if ((message[curByte] and 0xF0.toByte()) == SYSEX_PACKET_END) {
return true
}
curByte += 8
}
return false
}
private fun waitForMessage(midiReceiver: WaitingMidiReceiver, timeoutMs : Long, groupId: Int)
: ByteArray {
val startTime = LocalDateTime.now()
var currentTime = startTime
val endTime = startTime.plus(timeoutMs, ChronoField.MILLI_OF_DAY.baseUnit)
var outputMessage = ByteArray(0)
while (endTime > currentTime) {
val remainingDurationMs = ChronoUnit.MILLIS.between(currentTime, endTime)
midiReceiver.waitForMessages(midiReceiver.readCount + 1,
remainingDurationMs.toInt())
while (midiReceiver.readCount < midiReceiver.messageCount) {
val currentMessage = midiReceiver.getMessage(midiReceiver.readCount).data
logByteArray("received: ", currentMessage, 0, currentMessage.size)
midiReceiver.readCount++
// Assume that all SysEx messages from the intended group has to be the wanted reply
if (verifyMessageIsMidiSysExMessage(currentMessage, groupId)) {
if (checkMessageStartsWithSysExStart(currentMessage)) {
outputMessage = ByteArray(0)
}
outputMessage += currentMessage
if (checkMessageContainsSysExEnd(currentMessage)) {
return outputMessage
}
}
}
currentTime = LocalDateTime.now()
}
return outputMessage
}
private fun generateSourceMuid(): ByteArray {
// 28 bits in 4 bytes
val bytes = Random.Default.nextBytes(4)
bytes[0] = bytes[0] and 0x7F.toByte()
bytes[1] = bytes[1] and 0x7F.toByte()
bytes[2] = bytes[2] and 0x7F.toByte()
bytes[3] = bytes[3] and 0x7F.toByte()
return bytes
}
companion object {
const val TAG = "MidiCIInitiator"
const val SYSEX_DATA_MESSAGE_TYPE = 0x3
const val SYSEX_PACKET_END = 0x30.toByte()
const val SYSEX_PACKET_START = 0x10.toByte()
const val UMP_PACKET_MULTIPLE = 8
const val DISCOVERY_REPLY_TIMEOUT_MILLIS = 3000.toLong()
const val PAUSE_TIME_FOR_SWITCHING_MILLIS = 100.toLong()
const val NEW_PROTOCOL_REPLY_TIMEOUT_MILLIS = 300.toLong()
}
} | apache-2.0 | 3df14e1ff6d06f215121f5842c341235 | 45.617225 | 125 | 0.680456 | 4.539609 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.