repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
RuntimeModels/chazm
chazm-model/src/main/kotlin/runtimemodels/chazm/model/parser/entity/ParsePolicy.kt
2
1114
package runtimemodels.chazm.model.parser.entity import runtimemodels.chazm.api.entity.PolicyId import runtimemodels.chazm.api.organization.Organization import runtimemodels.chazm.model.entity.EntityFactory import runtimemodels.chazm.model.entity.impl.DefaultPolicyId import runtimemodels.chazm.model.parser.attribute import runtimemodels.chazm.model.parser.build import javax.inject.Inject import javax.inject.Singleton import javax.xml.namespace.QName import javax.xml.stream.events.StartElement @Singleton internal class ParsePolicy @Inject constructor( private val entityFactory: EntityFactory ) { fun canParse(qName: QName): Boolean = POLICY_ELEMENT == qName.localPart operator fun invoke(element: StartElement, organization: Organization, policies: MutableMap<String, PolicyId>) { val id = DefaultPolicyId(element attribute NAME_ATTRIBUTE) build(id, policies, element, entityFactory::build, organization::add) } companion object { private const val POLICY_ELEMENT = "Policy" //$NON-NLS-1$ private const val NAME_ATTRIBUTE = "name" //$NON-NLS-1$ } }
apache-2.0
martin-nordberg/KatyDOM
Katydid-Events-JS/src/main/kotlin/o/katydid/events/types/KatydidWheelEvent.kt
1
604
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.events.types //--------------------------------------------------------------------------------------------------------------------- interface KatydidWheelEvent : KatydidMouseEvent { enum class DeltaMode { DELTA_PIXEL, DELTA_LINE, DELTA_PAGE } val deltaMode: DeltaMode val deltaX: Double val deltaY: Double val deltaZ: Double } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
jitsi/jicofo
jicofo/src/main/kotlin/org/jitsi/jicofo/ConferenceStore.kt
1
1390
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2021 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo import org.jitsi.jicofo.conference.JitsiMeetConference import org.jxmpp.jid.EntityBareJid interface ConferenceStore { /** Get a list of all conferences. */ fun getAllConferences(): List<JitsiMeetConference> /** Get a conference for a specific [Jid] (i.e. name). */ fun getConference(jid: EntityBareJid): JitsiMeetConference? fun addListener(listener: Listener) {} fun removeListener(listener: Listener) {} interface Listener { fun conferenceEnded(name: EntityBareJid) } } class EmptyConferenceStore : ConferenceStore { override fun getAllConferences() = emptyList<JitsiMeetConference>() override fun getConference(jid: EntityBareJid): JitsiMeetConference? = null }
apache-2.0
cashapp/sqldelight
extensions/async-extensions/src/commonMain/kotlin/app/cash/sqldelight/async/coroutines/QueryExtensions.kt
1
692
package app.cash.sqldelight.async.coroutines import app.cash.sqldelight.ExecutableQuery suspend fun <T : Any> ExecutableQuery<T>.awaitAsList(): List<T> = execute { cursor -> val result = mutableListOf<T>() while (cursor.next()) result.add(mapper(cursor)) result }.await() suspend fun <T : Any> ExecutableQuery<T>.awaitAsOne(): T { return awaitAsOneOrNull() ?: throw NullPointerException("ResultSet returned null for $this") } suspend fun <T : Any> ExecutableQuery<T>.awaitAsOneOrNull(): T? = execute { cursor -> if (!cursor.next()) return@execute null val value = mapper(cursor) check(!cursor.next()) { "ResultSet returned more than 1 row for $this" } value }.await()
apache-2.0
apixandru/intellij-community
platform/projectModel-impl/src/com/intellij/configurationStore/StateStorageManager.kt
11
2103
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.StateStorageOperation import com.intellij.openapi.components.Storage import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.util.messages.Topic val STORAGE_TOPIC = Topic("STORAGE_LISTENER", StorageManagerListener::class.java, Topic.BroadcastDirection.TO_PARENT) interface StateStorageManager { val macroSubstitutor: TrackingPathMacroSubstitutor? get() = null fun getStateStorage(storageSpec: Storage): StateStorage fun addStreamProvider(provider: StreamProvider, first: Boolean = false) fun removeStreamProvider(clazz: Class<out StreamProvider>) /** * Rename file * @param path System-independent full old path (/project/bar.iml or collapse $MODULE_FILE$) * * * @param newName Only new file name (foo.iml) */ fun rename(path: String, newName: String) fun startExternalization(): ExternalizationSession? fun getOldStorage(component: Any, componentName: String, operation: StateStorageOperation): StateStorage? fun expandMacros(path: String): String interface ExternalizationSession { fun setState(storageSpecs: List<Storage>, component: Any, componentName: String, state: Any) fun setStateInOldStorage(component: Any, componentName: String, state: Any) /** * return empty list if nothing to save */ fun createSaveSessions(): List<StateStorage.SaveSession> } }
apache-2.0
DuckBoss/Programming-Challenges
Fibonacci_Numbers/FibonacciNumbers.kt
1
666
fun main(args: Array<String>) { if(args.size != 3) { println("This program requires 2 starting integers, and the max terms!") return } println("Program Started...") val start1: Int = args[0].toInt() val start2: Int = args[1].toInt() var maxCount: Int = args[2].toInt() if(maxCount < 2) { maxCount = 2 } val fullList = IntArray(maxCount) fullList[0] = start1 fullList[1] = start2 for(i in 2..maxCount-1) { fullList[i] = fullList[i-1]+fullList[i-2] } print("Result - {") for(fib in fullList) { print(" %d".format(fib)) } print(" }\n") println() }
unlicense
RocketChat/Rocket.Chat.Android.Lily
app/src/main/java/chat/rocket/android/dagger/LocalComponent.kt
2
772
package chat.rocket.android.dagger import android.content.Context import chat.rocket.android.chatroom.adapter.MessageReactionsAdapter import chat.rocket.android.dagger.module.LocalModule import dagger.BindsInstance import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = [LocalModule::class]) interface LocalComponent { @Component.Builder interface Builder { @BindsInstance fun context(applicationContext: Context): Builder fun build(): LocalComponent } fun inject(adapter: MessageReactionsAdapter.ReactionViewHolder) fun inject(adapter: MessageReactionsAdapter.AddReactionViewHolder) /*@Component.Builder abstract class Builder : AndroidInjector.Builder<RocketChatApplication>()*/ }
mit
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/health/service/HealthCareServices.kt
1
4022
package ffc.app.health.service import ffc.api.ApiErrorException import ffc.api.FfcCentral import ffc.app.mockRepository import ffc.app.util.RepoCallback import ffc.app.util.TaskCallback import ffc.entity.gson.toJson import ffc.entity.healthcare.HealthCareService import retrofit2.dsl.enqueue import timber.log.Timber import java.util.concurrent.ConcurrentHashMap internal interface HealthCareServices { fun add(services: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) fun all(dsl: RepoCallback<List<HealthCareService>>.() -> Unit) fun update(service: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) } private class InMemoryHealthCareServices(val personId: String) : HealthCareServices { override fun update(service: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) { val callback = TaskCallback<HealthCareService>().apply(dslCallback) repository[personId]?.let { it.remove(service) it.add(service) } callback.result(service) } override fun add(services: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) { require(services.patientId == personId) { "Not match patinet id" } Timber.d("homevisit = %s", services.toJson()) val callback = TaskCallback<HealthCareService>().apply(dslCallback) val list = repository[personId] ?: mutableListOf() list.add(services) repository[personId] = list callback.result.invoke(services) } override fun all(dsl: RepoCallback<List<HealthCareService>>.() -> Unit) { val callback = RepoCallback<List<HealthCareService>>().apply(dsl) callback.always?.invoke() val list = repository[personId] ?: listOf<HealthCareService>() if (list.isNotEmpty()) { callback.onFound!!.invoke(list) } else { callback.onNotFound!!.invoke() } } companion object { val repository: ConcurrentHashMap<String, MutableList<HealthCareService>> = ConcurrentHashMap() } } private class ApiHealthCareServices( val org: String, val person: String ) : HealthCareServices { override fun update(service: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) { val callback = TaskCallback<HealthCareService>().apply(dslCallback) api.put(org, service).enqueue { onSuccess { callback.result(body()!!) } onError { callback.expception?.invoke(ApiErrorException(this)) } onFailure { callback.expception?.invoke(it) } } } val api = FfcCentral().service<HealthCareServiceApi>() override fun add(services: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) { val callback = TaskCallback<HealthCareService>().apply(dslCallback) api.post(services, org).enqueue { onSuccess { callback.result.invoke(body()!!) } onError { callback.expception?.invoke(ApiErrorException(this)) } onFailure { callback.expception?.invoke(it) } } } override fun all(dsl: RepoCallback<List<HealthCareService>>.() -> Unit) { val callback = RepoCallback<List<HealthCareService>>().apply(dsl) api.get(org, person).enqueue { onSuccess { callback.onFound!!.invoke(body()!!) } onClientError { callback.onNotFound!!.invoke() } onServerError { callback.onFail!!.invoke(ApiErrorException(this)) } onFailure { callback.onFail!!.invoke(it) } } } } internal fun healthCareServicesOf(personId: String, orgId: String): HealthCareServices = if (mockRepository) InMemoryHealthCareServices(personId) else ApiHealthCareServices(orgId, personId)
apache-2.0
plombardi89/kbaseball
common/src/main/kotlin/kbaseball/email/SimpleEmailer.kt
1
1992
/* Copyright (C) 2015 Philip Lombardi <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package kbaseball.email import org.apache.commons.mail.HtmlEmail import org.slf4j.LoggerFactory import javax.mail.Authenticator /** * A class that can send emails and has limited customizability. * * @author [email protected] * @since 1.0 */ data class SimpleEmailer( val host: String, val port: Int, val authenticator: Authenticator, val from: String ): Emailer { private val log = LoggerFactory.getLogger(SimpleEmailer::class.java) private fun buildBaseEmail(): HtmlEmail { val base = HtmlEmail() base.hostName = host base.setSmtpPort(port) base.setAuthenticator(authenticator) base.setFrom(from) base.setStartTLSEnabled(true) return base } override fun sendEmail(to: Set<String>, subject: String, content: EmailContent, cc: Set<String>, bcc: Set<String>) { log.debug("sending email (to: {}, subject: {})", to, subject) val email = buildBaseEmail() email.setSubject(subject) email.addTo(*to.toTypedArray()) email.setHtmlMsg(content.html) if (content.alternateText != null) { email.setTextMsg(content.alternateText) } if (cc.isNotEmpty()) { email.addCc(*cc.toTypedArray()) } if (bcc.isNotEmpty()) { email.addBcc(*bcc.toTypedArray()) } email.send() } }
agpl-3.0
Popalay/Cardme
data/src/main/kotlin/com/popalay/cardme/data/PermissionChecker.kt
1
1801
package com.popalay.cardme.data import android.content.Context import com.kcode.permissionslib.main.OnRequestPermissionsCallBack import com.kcode.permissionslib.main.PermissionCompat import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.Single object PermissionChecker { fun check(context: Context, vararg permissions: String): Flowable<Boolean> = Flowable.create<Boolean>({ PermissionCompat.Builder(context) .addPermissions(permissions) .addRequestPermissionsCallBack(object : OnRequestPermissionsCallBack { override fun onGrant() { it.onNext(true) it.onComplete() } override fun onDenied(s: String) { it.onNext(false) } }) .build() .request() }, BackpressureStrategy.LATEST) fun checkSingle(context: Context, vararg permissions: String): Single<Boolean> = Single.create<Boolean> { PermissionCompat.Builder(context) .addPermissions(permissions) .addRequestPermissionsCallBack(object : OnRequestPermissionsCallBack { override fun onGrant() { it.onSuccess(true) } override fun onDenied(s: String) { it.onSuccess(false) } }) .build() .request() } }
apache-2.0
BilledTrain380/sporttag-psa
app/setup/src/main/kotlin/ch/schulealtendorf/psa/setup/UserDirApplicationDirectory.kt
1
352
package ch.schulealtendorf.psa.setup import org.springframework.context.annotation.Profile import org.springframework.stereotype.Component import java.io.File import java.nio.file.Path @Profile("prod") @Component class UserDirApplicationDirectory : ApplicationDirectory { override val path: Path = File(System.getProperty("user.dir")).toPath() }
gpl-3.0
stripe/stripe-android
paymentsheet/src/main/java/com/stripe/android/paymentsheet/PaymentSheetConfigurationKtx.kt
1
4527
package com.stripe.android.paymentsheet import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.sp import com.stripe.android.ui.core.PaymentsTheme import com.stripe.android.ui.core.PaymentsThemeDefaults import com.stripe.android.ui.core.PrimaryButtonColors import com.stripe.android.ui.core.PrimaryButtonShape import com.stripe.android.ui.core.PrimaryButtonTypography import java.security.InvalidParameterException internal fun PaymentSheet.Configuration.validate() { // These are not localized as they are not intended to be displayed to a user. when { merchantDisplayName.isBlank() -> { throw InvalidParameterException( "When a Configuration is passed to PaymentSheet," + " the Merchant display name cannot be an empty string." ) } customer?.id?.isBlank() == true -> { throw InvalidParameterException( "When a CustomerConfiguration is passed to PaymentSheet," + " the Customer ID cannot be an empty string." ) } customer?.ephemeralKeySecret?.isBlank() == true -> { throw InvalidParameterException( "When a CustomerConfiguration is passed to PaymentSheet, " + "the ephemeralKeySecret cannot be an empty string." ) } } } internal fun PaymentSheet.Appearance.parseAppearance() { PaymentsTheme.colorsLightMutable = PaymentsThemeDefaults.colorsLight.copy( component = Color(colorsLight.component), componentBorder = Color(colorsLight.componentBorder), componentDivider = Color(colorsLight.componentDivider), onComponent = Color(colorsLight.onComponent), subtitle = Color(colorsLight.subtitle), placeholderText = Color(colorsLight.placeholderText), appBarIcon = Color(colorsLight.appBarIcon), materialColors = lightColors( primary = Color(colorsLight.primary), surface = Color(colorsLight.surface), onSurface = Color(colorsLight.onSurface), error = Color(colorsLight.error) ) ) PaymentsTheme.colorsDarkMutable = PaymentsThemeDefaults.colorsDark.copy( component = Color(colorsDark.component), componentBorder = Color(colorsDark.componentBorder), componentDivider = Color(colorsDark.componentDivider), onComponent = Color(colorsDark.onComponent), subtitle = Color(colorsDark.subtitle), placeholderText = Color(colorsDark.placeholderText), appBarIcon = Color(colorsDark.appBarIcon), materialColors = darkColors( primary = Color(colorsDark.primary), surface = Color(colorsDark.surface), onSurface = Color(colorsDark.onSurface), error = Color(colorsDark.error) ) ) PaymentsTheme.shapesMutable = PaymentsThemeDefaults.shapes.copy( cornerRadius = shapes.cornerRadiusDp, borderStrokeWidth = shapes.borderStrokeWidthDp ) PaymentsTheme.typographyMutable = PaymentsThemeDefaults.typography.copy( fontFamily = typography.fontResId, fontSizeMultiplier = typography.sizeScaleFactor ) PaymentsTheme.primaryButtonStyle = PaymentsThemeDefaults.primaryButtonStyle.copy( colorsLight = PrimaryButtonColors( background = Color(primaryButton.colorsLight.background ?: colorsLight.primary), onBackground = Color(primaryButton.colorsLight.onBackground), border = Color(primaryButton.colorsLight.border) ), colorsDark = PrimaryButtonColors( background = Color(primaryButton.colorsDark.background ?: colorsDark.primary), onBackground = Color(primaryButton.colorsDark.onBackground), border = Color(primaryButton.colorsDark.border) ), shape = PrimaryButtonShape( cornerRadius = primaryButton.shape.cornerRadiusDp ?: shapes.cornerRadiusDp, borderStrokeWidth = primaryButton.shape.borderStrokeWidthDp ?: shapes.borderStrokeWidthDp ), typography = PrimaryButtonTypography( fontFamily = primaryButton.typography.fontResId ?: typography.fontResId, fontSize = primaryButton.typography.fontSizeSp?.sp ?: (PaymentsThemeDefaults.typography.largeFontSize * typography.sizeScaleFactor) ) ) }
mit
slartus/4pdaClient-plus
core-lib/src/androidTest/java/org/softeg/slartus/forpdaplus/core_lib/ExampleInstrumentedTest.kt
1
708
package org.softeg.slartus.forpdaplus.core_lib import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("org.softeg.slartus.forpdaplus.core_lib.test", appContext.packageName) } }
apache-2.0
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/tabs/TabsManager.kt
1
1657
package org.softeg.slartus.forpdaplus.tabs class TabsManager { private object Holder { val INSTANCE = TabsManager() } companion object { const val TAG = "TabsManager" @JvmStatic val instance by lazy { Holder.INSTANCE } } private var currentFragmentTag: String? = null private var tabIterator = 0 fun getTabIterator(): Int { return tabIterator } fun setTabIterator(tabIterator: Int) { this.tabIterator = tabIterator } fun clearTabIterator() { tabIterator = 0 } fun plusTabIterator() { tabIterator++ } fun getCurrentFragmentTag(): String? { return currentFragmentTag } fun setCurrentFragmentTag(s: String?) { currentFragmentTag = s } private val mTabItems = mutableListOf<TabItem>() fun getTabItems(): MutableList<TabItem> { return mTabItems } fun getLastTabPosition(delPos: Int): Int { var delPos = delPos if (mTabItems.size - 1 < delPos) delPos-- return delPos } fun isContainsByTag(tag: String?): Boolean { for (item in getTabItems()) if (item.tag == tag) return true return false } fun isContainsByUrl(url: String?): Boolean { for (item in getTabItems()) if (item.url == url) return true return false } fun getTabByTag(tag: String?): TabItem? { for (item in getTabItems()) if (item.tag == tag) return item return null } fun getTabByUrl(url: String): TabItem? { for (item in getTabItems()) if (item.url == url) return item return null } }
apache-2.0
ToucheSir/toy-browser-engine
src/com/brianc/style/MatchedRule.kt
1
157
package com.brianc.style import com.brianc.css.Rule import com.brianc.css.Specificity class MatchedRule(internal var s: Specificity, internal var r: Rule)
mit
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/ConnectExampleActivity.kt
1
1583
package com.stripe.example.activity import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import com.stripe.example.databinding.ConnectExampleActivityBinding class ConnectExampleActivity : StripeIntentActivity() { private val viewBinding: ConnectExampleActivityBinding by lazy { ConnectExampleActivityBinding.inflate(layoutInflater) } private val snackbarController: SnackbarController by lazy { SnackbarController(viewBinding.coordinator) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) viewModel.inProgress.observe(this, { enableUi(!it) }) viewModel.status.observe(this, Observer(viewBinding.status::setText)) viewBinding.payNow.setOnClickListener { viewBinding.cardWidget.paymentMethodCreateParams?.let { val connectAccount = viewBinding.connectAccount.text.toString().takeIf(String::isNotBlank) createAndConfirmPaymentIntent("us", it, stripeAccountId = connectAccount) } ?: showSnackbar("Missing card details") } } private fun showSnackbar(message: String) { snackbarController.show(message) } private fun enableUi(enable: Boolean) { viewBinding.progressBar.visibility = if (enable) View.INVISIBLE else View.VISIBLE viewBinding.payNow.isEnabled = enable viewBinding.cardWidget.isEnabled = enable viewBinding.connectAccount.isEnabled = enable } }
mit
ebean-orm-examples/example-kotlin
src/test/kotlin/org/example/domain/LoadExampleData.kt
1
4700
package org.example.domain import io.ebean.Ebean import io.ebean.EbeanServer class LoadExampleData { companion object Once { var runOnce: Boolean = false } private val server: EbeanServer = Ebean.getDefaultServer() private var contactEmailNum: Int = 1 fun load() { if (runOnce) { return } runOnce = true val txn = server.beginTransaction() try { if (Country.query().findCount() > 0) { return; } //deleteAll() insertCountries() insertProducts() insertTestCustAndOrders() txn.commit() } finally { txn.end() } } // private fun deleteAll() { // OrderDetail.query().delete() // Order.query().delete() // Contact.query().delete() // Customer.query().delete() // Address.query().delete() // Country.query().delete() // Product.query().delete() // } private fun insertCountries() { Country("NZ", "New Zealand").save() Country("AU", "Australia").save() } private fun insertProducts() { Product("Chair", "C001").save() Product("Desk", "DSK1").save() Product("C002", "Computer").save() val product = Product(sku = "C003", name = "Printer") product.description = "A Colour printer" product.save() } private fun insertTestCustAndOrders() { val cust1 = insertCustomer("Rob") val cust2 = insertCustomerNoAddress() insertCustomerFiona() insertCustomerNoContacts("NoContactsCust") insertCustomer("Roberto") createOrder1(cust1) createOrder2(cust2) createOrder3(cust1) createOrder4(cust1) } private fun insertCustomerFiona(): Customer { val c = createCustomer("Fiona", "12 Apple St", "West Coast Rd", 1) c.contacts.add(createContact("Fiona", "Black")) c.contacts.add(createContact("Tracy", "Red")) c.save() return c } private fun createContact(firstName: String, lastName: String): Contact { val contact = Contact(firstName, lastName) contact.email = (contact.lastName + (contactEmailNum++) + "@test.com").toLowerCase() return contact } private fun insertCustomerNoContacts(name: String): Customer { val customer = createCustomer(name, "15 Kumera Way", "Bos town", 1) customer.save() return customer } private fun insertCustomerNoAddress(): Customer { val customer = Customer("Customer NoAddress") customer.contacts.add(createContact("Jack", "Black")) customer.save() return customer } private fun insertCustomer(name: String): Customer { val customer = createCustomer(name, "1 Banana St", "P.O.Box 1234", 1) customer.save() return customer } private fun createCustomer(name: String, shippingStreet: String?, billingStreet: String?, contactSuffix: Int): Customer { val customer = Customer(name) if (contactSuffix > 0) { customer.contacts.add(Contact("Jim$contactSuffix", "Cricket")) customer.contacts.add(Contact("Fred$contactSuffix", "Blue")) customer.contacts.add(Contact("Bugs$contactSuffix", "Bunny")) } val nz = Country.ref("NZ") if (shippingStreet != null) { val shipAddress = Address(shippingStreet, nz) shipAddress.line2 = "Sandringham" shipAddress.city = "Auckland" customer.shippingAddress = shipAddress } if (billingStreet != null) { val address = Address( line1 = billingStreet, line2 = "St Lukes", city = "Auckland", country = nz) with(address) { line1 = billingStreet line2 = "St Lukes" city = "Auckland" country = nz } customer.billingAddress = with(Address(billingStreet, nz)) { line2 = "St Lukes" city = "Auckland" this } } return customer } private fun createOrder1(customer: Customer): Order { return with(Order(customer)) { addItem(Product.ref(1), 22, 12.0) details.add(OrderDetail(Product.ref(1), 5, 10.50)) details.add(OrderDetail(Product.ref(2), 3, 1.10)) details.add(OrderDetail(Product.ref(3), 1, 2.00)) save() this } } private fun createOrder2(customer: Customer) { with(Order(customer)) { status = Order.Status.SHIPPED this.details.add(OrderDetail(Product.ref(1), 4, 10.50)) save() } } private fun createOrder3(customer: Customer) { with(Order(customer)) { status = Order.Status.COMPLETE this.details.add(OrderDetail(Product.ref(1), 3, 10.50)) this.details.add(OrderDetail(Product.ref(3), 40, 2.10)) save() } } private fun createOrder4(customer: Customer) { with(Order(customer)) { save() } } }
apache-2.0
AndroidX/androidx
camera/camera-camera2/src/androidTest/java/androidx/camera/camera2/internal/Camera2CameraImplCameraReopenTest.kt
3
24855
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.internal import android.content.Context import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraDevice import android.hardware.camera2.CameraManager import android.hardware.camera2.CameraManager.AvailabilityCallback import android.os.Handler import android.os.HandlerThread import androidx.annotation.GuardedBy import androidx.annotation.RequiresApi import androidx.camera.camera2.AsyncCameraDevice import androidx.camera.camera2.Camera2Config import androidx.camera.camera2.internal.compat.CameraAccessExceptionCompat import androidx.camera.camera2.internal.compat.CameraManagerCompat import androidx.camera.core.CameraSelector import androidx.camera.core.CameraUnavailableException import androidx.camera.core.Logger import androidx.camera.core.impl.CameraInternal import androidx.camera.core.impl.CameraStateRegistry import androidx.camera.core.impl.Observable import androidx.camera.core.impl.utils.MainThreadAsyncHandler import androidx.camera.core.impl.utils.executor.CameraXExecutors import androidx.camera.testing.CameraUtil import androidx.camera.testing.CameraUtil.PreTestCameraIdList import androidx.core.os.HandlerCompat import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import com.google.common.truth.Truth import java.util.concurrent.ExecutionException import java.util.concurrent.Executor import java.util.concurrent.ExecutorService import java.util.concurrent.Semaphore import java.util.concurrent.TimeUnit import kotlin.math.ceil import org.junit.After import org.junit.AfterClass import org.junit.Assume import org.junit.Before import org.junit.BeforeClass import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.mock /** Contains [Camera2CameraImpl] tests for reopening the camera with failures. */ @LargeTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = 21) class Camera2CameraImplCameraReopenTest { @get:Rule val cameraRule = CameraUtil.grantCameraPermissionAndPreTest( PreTestCameraIdList(Camera2Config.defaultConfig()) ) private var camera2CameraImpl: Camera2CameraImpl? = null private var cameraId: String? = null private var anotherCameraDevice: AsyncCameraDevice? = null @Before fun setUp() { cameraId = CameraUtil.getCameraIdWithLensFacing(CameraSelector.LENS_FACING_BACK) Assume.assumeFalse("Device doesn't have an available back facing camera", cameraId == null) } @After @Throws(InterruptedException::class, ExecutionException::class) fun testTeardown() { // Release camera, otherwise the CameraDevice is not closed, which can cause problems that // interfere with other tests. if (camera2CameraImpl != null) { camera2CameraImpl!!.release().get() camera2CameraImpl = null } anotherCameraDevice?.closeAsync() anotherCameraDevice = null } @Test @Throws(Exception::class) fun openCameraAfterMultipleFailures_whenCameraReopenLimitNotReached() { // Set up the camera val cameraManagerImpl = FailCameraOpenCameraManagerImpl() setUpCamera(cameraManagerImpl) // Set up camera open attempt listener val cameraOpenSemaphore = Semaphore(0) cameraManagerImpl.onCameraOpenAttemptListener = object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener { override fun onCameraOpenAttempt() { cameraOpenSemaphore.release() } } // Try opening the camera. This will fail and trigger reopening attempts camera2CameraImpl!!.open() Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() // Wait for half the max reopen attempts to occur val maxReopenAttempts = ceil(REOPEN_LIMIT_MS / REOPEN_DELAY_MS.toDouble()).toInt() Truth.assertThat( cameraOpenSemaphore.tryAcquire( maxReopenAttempts / 2, REOPEN_LIMIT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() // Allow camera opening to succeed cameraManagerImpl.shouldFailCameraOpen = false // Verify the camera opens awaitCameraOpen() } @Test @Throws(Exception::class) fun doNotAttemptCameraReopen_whenCameraReopenLimitReached() { // Set up the camera val cameraManagerImpl = FailCameraOpenCameraManagerImpl() setUpCamera(cameraManagerImpl) // Set up camera open attempt listener val cameraOpenSemaphore = Semaphore(0) cameraManagerImpl.onCameraOpenAttemptListener = object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener { override fun onCameraOpenAttempt() { cameraOpenSemaphore.release() } } // Try opening the camera. This will fail and trigger reopening attempts camera2CameraImpl!!.open() Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() // Wait for max reopen attempts to occur awaitCameraMaxReopenAttemptsReached(cameraOpenSemaphore) // Verify 0 camera reopen attempts occurred. Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isFalse() } @Test @Throws(Exception::class) fun openCameraAfterReopenLimitReached_whenCameraExplicitlyOpened() { // Set up the camera val cameraManagerImpl = FailCameraOpenCameraManagerImpl() setUpCamera(cameraManagerImpl) // Set up camera open attempt listener val cameraOpenSemaphore = Semaphore(0) cameraManagerImpl.onCameraOpenAttemptListener = object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener { override fun onCameraOpenAttempt() { cameraOpenSemaphore.release() } } // Try opening the camera. This will fail and trigger reopening attempts camera2CameraImpl!!.open() Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() // Wait for max reopen attempts to occur awaitCameraMaxReopenAttemptsReached(cameraOpenSemaphore) // Allow camera opening to succeed cameraManagerImpl.shouldFailCameraOpen = false // Try opening the camera. This should succeed camera2CameraImpl!!.open() // Verify the camera opens awaitCameraOpen() } @Test @Throws(Exception::class) fun openCameraAfterReopenLimitReached_whenCameraBecomesAvailable() { // Set up the camera val cameraManagerImpl = FailCameraOpenCameraManagerImpl() setUpCamera(cameraManagerImpl) // Set up camera open attempt listener val cameraOpenSemaphore = Semaphore(0) cameraManagerImpl.onCameraOpenAttemptListener = object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener { override fun onCameraOpenAttempt() { cameraOpenSemaphore.release() } } // Try opening the camera. This will fail and trigger reopening attempts camera2CameraImpl!!.open() Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() // Wait for max reopen attempts to occur awaitCameraMaxReopenAttemptsReached(cameraOpenSemaphore) // Allow camera opening to succeed cameraManagerImpl.shouldFailCameraOpen = false // Make camera available camera2CameraImpl!!.cameraAvailability.onCameraAvailable(cameraId!!) // Verify the camera opens awaitCameraOpen() } @Test @Throws(Exception::class) fun activeResuming_openCameraAfterMultipleReopening_whenCameraUnavailable() { // Set up the camera val cameraManagerImpl = FailCameraOpenCameraManagerImpl() setUpCamera(cameraManagerImpl) // Set up camera open attempt listener val cameraOpenSemaphore = Semaphore(0) cameraManagerImpl.onCameraOpenAttemptListener = object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener { override fun onCameraOpenAttempt() { cameraOpenSemaphore.release() } } cameraManagerImpl.shouldEmitCameraInUseError = true // Enable active reopening which will open the camera even when camera is unavailable. camera2CameraImpl!!.setActiveResumingMode(true) // Try opening the camera. This will fail and trigger reopening attempts camera2CameraImpl!!.open() // make camera unavailable. cameraExecutor!!.execute { camera2CameraImpl!!.cameraAvailability.onCameraUnavailable( cameraId!! ) } Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() // Wait for half the max reopen attempts to occur val maxReopenAttempts = ceil(10000.0 / ACTIVE_REOPEN_DELAY_BASE_MS).toInt() Truth.assertThat( cameraOpenSemaphore.tryAcquire( maxReopenAttempts / 2, 10000, TimeUnit.MILLISECONDS ) ).isTrue() // Allow camera opening to succeed cameraManagerImpl.shouldFailCameraOpen = false // Verify the camera opens Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() awaitCameraOpen() } private fun openAnotherCamera() { val cameraManager = ApplicationProvider.getApplicationContext<Context>() .getSystemService(Context.CAMERA_SERVICE) as CameraManager anotherCameraDevice = AsyncCameraDevice(cameraManager, cameraId!!, cameraHandler!!).apply { openAsync() } } @SdkSuppress(minSdkVersion = 23) @Test @Throws(Exception::class) fun activeResuming_reopenCamera_whenCameraIsInterruptedInActiveResuming() { // Set up the camera val cameraManagerImpl = FailCameraOpenCameraManagerImpl() setUpCamera(cameraManagerImpl) // Set up camera open attempt listener val cameraOpenSemaphore = Semaphore(0) cameraManagerImpl.onCameraOpenAttemptListener = object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener { override fun onCameraOpenAttempt() { cameraOpenSemaphore.release() } } // Open camera will succeed. cameraManagerImpl.shouldFailCameraOpen = false camera2CameraImpl!!.open() Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() awaitCameraOpen() // Enable active resuming which will open the camera even when camera is unavailable. camera2CameraImpl!!.setActiveResumingMode(true) // Disconnect the current camera. openAnotherCamera() // Verify the camera opens Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() awaitCameraOpen() } @SdkSuppress(minSdkVersion = 23) @Test @Throws(Exception::class) fun activeResuming_reopenCamera_whenCameraPendingOpenThenResume() { // Set up the camera val cameraManagerImpl = FailCameraOpenCameraManagerImpl() setUpCamera(cameraManagerImpl) // Set up camera open attempt listener val cameraOpenSemaphore = Semaphore(0) cameraManagerImpl.onCameraOpenAttemptListener = object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener { override fun onCameraOpenAttempt() { cameraOpenSemaphore.release() } } // Open camera will succeed. cameraManagerImpl.shouldFailCameraOpen = false camera2CameraImpl!!.open() Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() awaitCameraOpen() // Disconnect the current camera. openAnotherCamera() // Wait until camera is pending_open which will wait for camera availability awaitCameraPendingOpen() // Enable active resuming to see if it can resume the camera. camera2CameraImpl!!.setActiveResumingMode(true) // Verify the camera opens Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() awaitCameraOpen() } @Test @Throws(Exception::class) fun activeResuming_doNotReopenCamera_whenCameraDeviceError() { // Set up the camera val cameraManagerImpl = FailCameraOpenCameraManagerImpl() setUpCamera(cameraManagerImpl) // Set up camera open attempt listener val cameraOpenSemaphore = Semaphore(0) cameraManagerImpl.onCameraOpenAttemptListener = object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener { override fun onCameraOpenAttempt() { cameraOpenSemaphore.release() } } // Open camera will succeed. cameraManagerImpl.shouldFailCameraOpen = false camera2CameraImpl!!.open() Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() // wait onOpened to get CameraDevice awaitCameraOpen() camera2CameraImpl!!.setActiveResumingMode(true) cameraExecutor!!.execute { cameraManagerImpl.deviceStateCallback!!.notifyOnError( CameraDevice.StateCallback.ERROR_CAMERA_DEVICE ) } // Make camera unavailable after onClosed so that we can verify if camera is not opened // again. For ERROR_CAMERA_DEVICE, it should not reopen the camera if the camera is // not available. cameraManagerImpl.deviceStateCallback!!.runWhenOnClosed { openAnotherCamera() } // 2nd camera open should not happen Truth.assertThat( cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isFalse() } @Throws(CameraAccessExceptionCompat::class, CameraUnavailableException::class) private fun setUpCamera(cameraManagerImpl: FailCameraOpenCameraManagerImpl) { // Build camera manager wrapper val cameraManagerCompat = CameraManagerCompat.from(cameraManagerImpl) // Build camera info val camera2CameraInfo = Camera2CameraInfoImpl( cameraId!!, cameraManagerCompat ) // Initialize camera instance camera2CameraImpl = Camera2CameraImpl( cameraManagerCompat, cameraId!!, camera2CameraInfo, CameraStateRegistry(1), cameraExecutor!!, cameraHandler!!, DisplayInfoManager.getInstance(ApplicationProvider.getApplicationContext()) ) } @Throws(InterruptedException::class) private fun awaitCameraOpen() { awaitCameraState(CameraInternal.State.OPEN) } @Throws(InterruptedException::class) private fun awaitCameraPendingOpen() { awaitCameraState(CameraInternal.State.PENDING_OPEN) } @Throws(InterruptedException::class) private fun awaitCameraState(state: CameraInternal.State) { val cameraStateSemaphore = Semaphore(0) val observer: Observable.Observer<CameraInternal.State?> = object : Observable.Observer<CameraInternal.State?> { override fun onNewData(newState: CameraInternal.State?) { if (newState == state) { cameraStateSemaphore.release() } } override fun onError(t: Throwable) { Logger.e("CameraReopenTest", "Camera state error: " + t.message) } } camera2CameraImpl!!.cameraState.addObserver( CameraXExecutors.directExecutor(), observer ) try { Truth.assertThat( cameraStateSemaphore.tryAcquire( WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) ).isTrue() } finally { camera2CameraImpl!!.cameraState.removeObserver(observer) } } @Throws(InterruptedException::class) private fun awaitCameraMaxReopenAttemptsReached(cameraOpenSemaphore: Semaphore) { while (true) { val cameraOpenAttempted = cameraOpenSemaphore.tryAcquire( 1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS ) if (!cameraOpenAttempted) { return } } } companion object { private const val REOPEN_DELAY_MS = Camera2CameraImpl.StateCallback.CameraReopenMonitor.REOPEN_DELAY_MS private const val REOPEN_LIMIT_MS = Camera2CameraImpl.StateCallback.CameraReopenMonitor.REOPEN_LIMIT_MS private const val ACTIVE_REOPEN_DELAY_BASE_MS = Camera2CameraImpl.StateCallback.CameraReopenMonitor.ACTIVE_REOPEN_DELAY_BASE_MS private const val WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS = 2000 private var cameraHandlerThread: HandlerThread? = null private var cameraHandler: Handler? = null private var cameraExecutor: ExecutorService? = null @BeforeClass @JvmStatic fun classSetup() { cameraHandlerThread = HandlerThread("cameraThread") cameraHandlerThread!!.start() cameraHandler = HandlerCompat.createAsync( cameraHandlerThread!!.looper ) cameraExecutor = CameraXExecutors.newHandlerExecutor( cameraHandler!! ) } @AfterClass @JvmStatic fun classTeardown() { cameraHandlerThread!!.quitSafely() } } } /** * Wraps a [CameraManagerCompat.CameraManagerCompatImpl] instance and controls camera opening * by either allowing it to succeed or fail. */ @RequiresApi(21) internal class FailCameraOpenCameraManagerImpl : CameraManagerCompat.CameraManagerCompatImpl { private val forwardCameraManagerCompatImpl: CameraManagerCompat.CameraManagerCompatImpl by lazy { CameraManagerCompat.CameraManagerCompatImpl.from( ApplicationProvider.getApplicationContext(), MainThreadAsyncHandler.getInstance() ) } private val lock = Any() @GuardedBy("lock") var onCameraOpenAttemptListener: OnCameraOpenAttemptListener? = null get() { synchronized(lock) { return field } } set(value) { synchronized(lock) { field = value } } @GuardedBy("lock") var shouldFailCameraOpen = true get() { synchronized(lock) { return field } } set(value) { synchronized(lock) { field = value } } @Volatile var shouldEmitCameraInUseError = false @GuardedBy("lock") var deviceStateCallback: CameraDeviceCallbackWrapper? = null get() { synchronized(lock) { return field } } set(value) { synchronized(lock) { field = value } } @Throws(CameraAccessExceptionCompat::class) override fun getCameraIdList(): Array<String> { return forwardCameraManagerCompatImpl.cameraIdList } override fun registerAvailabilityCallback( executor: Executor, callback: AvailabilityCallback ) { forwardCameraManagerCompatImpl.registerAvailabilityCallback(executor, callback) } override fun unregisterAvailabilityCallback( callback: AvailabilityCallback ) { forwardCameraManagerCompatImpl.unregisterAvailabilityCallback(callback) } @Throws(CameraAccessExceptionCompat::class) override fun getCameraCharacteristics(camId: String): CameraCharacteristics { return forwardCameraManagerCompatImpl.getCameraCharacteristics(camId) } override fun getCameraManager(): CameraManager { return forwardCameraManagerCompatImpl.cameraManager } @Throws(CameraAccessExceptionCompat::class) override fun openCamera( camId: String, executor: Executor, callback: CameraDevice.StateCallback ) { synchronized(lock) { deviceStateCallback = CameraDeviceCallbackWrapper(callback) if (onCameraOpenAttemptListener != null) { onCameraOpenAttemptListener!!.onCameraOpenAttempt() } if (shouldFailCameraOpen) { if (shouldEmitCameraInUseError) { executor.execute { callback.onError( mock(CameraDevice::class.java), CameraDevice.StateCallback.ERROR_CAMERA_IN_USE ) } } // Throw any exception throw SecurityException("Lacking privileges") } else { forwardCameraManagerCompatImpl .openCamera(camId, executor, deviceStateCallback!!) } } } interface OnCameraOpenAttemptListener { /** Triggered whenever an attempt to open the camera is made. */ fun onCameraOpenAttempt() } internal class CameraDeviceCallbackWrapper( private val deviceCallback: CameraDevice.StateCallback ) : CameraDevice.StateCallback() { private var cameraDevice: CameraDevice? = null private var runnableForOnClosed: Runnable? = null override fun onOpened(device: CameraDevice) { cameraDevice = device deviceCallback.onOpened(device) } override fun onClosed(camera: CameraDevice) { deviceCallback.onClosed(camera) if (runnableForOnClosed != null) { runnableForOnClosed!!.run() } } override fun onDisconnected(device: CameraDevice) { deviceCallback.onDisconnected(device) } override fun onError(device: CameraDevice, error: Int) { deviceCallback.onError(device, error) } fun notifyOnError(error: Int) { onError(cameraDevice!!, error) } fun runWhenOnClosed(runnable: Runnable) { runnableForOnClosed = runnable } } }
apache-2.0
Undin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/fixes/AddSelfFix.kt
3
1463
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator.fixes import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.rawValueParameters class AddSelfFix(function: RsFunction) : LocalQuickFixAndIntentionActionOnPsiElement(function) { override fun getFamilyName() = "Add self to function" override fun getText() = "Add self to function" override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) { val function = startElement as RsFunction val hasParameters = function.rawValueParameters.isNotEmpty() val psiFactory = RsPsiFactory(project) val valueParameterList = function.valueParameterList val lparen = valueParameterList?.firstChild val self = psiFactory.createSelfReference() valueParameterList?.addAfter(self, lparen) if (hasParameters) { // IDE error if use addAfter(comma, self) val parent = lparen?.parent parent?.addAfter(psiFactory.createComma(), parent.firstChild.nextSibling) } } }
mit
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsLifetimeParameter.kt
4
1562
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.search.SearchScope import com.intellij.psi.stubs.IStubElementType import org.rust.lang.core.psi.RsLifetime import org.rust.lang.core.psi.RsLifetimeParameter import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.RsPsiImplUtil import org.rust.lang.core.stubs.RsLifetimeParameterStub val RsLifetimeParameter.bounds: List<RsLifetime> get() { val owner = parent?.parent as? RsGenericDeclaration val whereBounds = owner?.whereClause?.wherePredList.orEmpty() .filter { it.lifetime?.reference?.resolve() == this } .flatMap { it.lifetimeParamBounds?.lifetimeList.orEmpty() } return lifetimeParamBounds?.lifetimeList.orEmpty() + whereBounds } abstract class RsLifetimeParameterImplMixin : RsStubbedNamedElementImpl<RsLifetimeParameterStub>, RsLifetimeParameter { constructor(node: ASTNode) : super(node) constructor(stub: RsLifetimeParameterStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getNameIdentifier(): PsiElement = quoteIdentifier override fun setName(name: String): PsiElement? { nameIdentifier.replace(RsPsiFactory(project).createQuoteIdentifier(name)) return this } override fun getUseScope(): SearchScope = RsPsiImplUtil.getParameterUseScope(this) ?: super.getUseScope() }
mit
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/receivers/TaskAlarmBootReceiver.kt
1
949
package com.habitrpg.android.habitica.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.SharedPreferences import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.helpers.TaskAlarmManager import com.habitrpg.shared.habitica.HLogger import com.habitrpg.shared.habitica.LogLevel import javax.inject.Inject class TaskAlarmBootReceiver : BroadcastReceiver() { @Inject lateinit var taskAlarmManager: TaskAlarmManager @Inject lateinit var sharedPreferences: SharedPreferences override fun onReceive(context: Context, arg1: Intent) { HabiticaBaseApplication.userComponent?.inject(this) taskAlarmManager.scheduleAllSavedAlarms(sharedPreferences.getBoolean("preventDailyReminder", false)) HLogger.log(LogLevel.INFO, this::javaClass.name, "onReceive") } }
gpl-3.0
arcuri82/testing_security_development_enterprise_systems
advanced/microservice/discovery/discovery-consumer/src/test/kotlin/org/tsdes/advanced/microservice/discovery/consumer/TestConfiguration.kt
1
434
package org.tsdes.advanced.microservice.discovery.consumer import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary import org.springframework.web.client.RestTemplate @Configuration class TestConfiguration { @Primary @Bean fun nonLoadBalancedRestTemplate(): RestTemplate { return RestTemplate() } }
lgpl-3.0
brianwernick/RecyclerExt
library/src/main/kotlin/com/devbrackets/android/recyclerext/decoration/header/UpdateListener.kt
1
722
/* * Copyright (C) 2018 Brian Wernick * * 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.devbrackets.android.recyclerext.decoration.header interface UpdateListener { fun onUpdateStickyHeader() }
apache-2.0
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/models/usecases/AddPlaylistItemUsecase.kt
1
659
package taiwan.no1.app.ssfm.models.usecases import io.reactivex.Observable import taiwan.no1.app.ssfm.models.data.IDataStore import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemUsecase.RequestValue /** * @author jieyi * @since 11/8/17 */ class AddPlaylistItemUsecase(repository: IDataStore) : BaseUsecase<Boolean, RequestValue>(repository) { override fun fetchUsecase(): Observable<Boolean> = (parameters ?: RequestValue()).let { repository.addPlaylistItem(it.entity) } data class RequestValue(val entity: PlaylistItemEntity = PlaylistItemEntity()) : RequestValues }
apache-2.0
androidx/androidx
compose/integration-tests/macrobenchmark/src/androidTest/java/androidx/compose/integration/macrobenchmark/DifferentTypesListScrollBenchmark.kt
3
3129
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.integration.macrobenchmark import android.content.Intent import android.graphics.Point import androidx.benchmark.macro.CompilationMode import androidx.benchmark.macro.FrameTimingMetric import androidx.benchmark.macro.junit4.MacrobenchmarkRule import androidx.test.filters.LargeTest import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until import androidx.testutils.createCompilationParams import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @LargeTest @RunWith(Parameterized::class) class DifferentTypesListScrollBenchmark( private val compilationMode: CompilationMode ) { @get:Rule val benchmarkRule = MacrobenchmarkRule() private lateinit var device: UiDevice @Before fun setUp() { val instrumentation = InstrumentationRegistry.getInstrumentation() device = UiDevice.getInstance(instrumentation) } @Test fun start() { benchmarkRule.measureRepeated( packageName = PACKAGE_NAME, metrics = listOf(FrameTimingMetric()), compilationMode = compilationMode, iterations = 10, setupBlock = { val intent = Intent() intent.action = ACTION startActivityAndWait(intent) } ) { val lazyColumn = device.findObject(By.desc(CONTENT_DESCRIPTION)) // Setting a gesture margin is important otherwise gesture nav is triggered. lazyColumn.setGestureMargin(device.displayWidth / 5) for (i in 1..10) { // From center we scroll 2/3 of it which is 1/3 of the screen. lazyColumn.drag(Point(0, lazyColumn.visibleCenter.y / 3)) device.wait(Until.findObject(By.desc(COMPOSE_IDLE)), 3000) } } } companion object { private const val PACKAGE_NAME = "androidx.compose.integration.macrobenchmark.target" private const val ACTION = "androidx.compose.integration.macrobenchmark.target.DIFFERENT_TYPES_LIST_ACTIVITY" private const val CONTENT_DESCRIPTION = "IamLazy" private const val COMPOSE_IDLE = "COMPOSE-IDLE" @Parameterized.Parameters(name = "compilation={0}") @JvmStatic fun parameters() = createCompilationParams() } }
apache-2.0
androidx/androidx
camera/camera-video/src/test/java/androidx/camera/video/VideoRecordEventTest.kt
3
4914
/* * 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.camera.video import android.net.Uri import android.os.Build import androidx.camera.video.VideoRecordEvent.Finalize.ERROR_NONE import androidx.camera.video.VideoRecordEvent.Finalize.ERROR_UNKNOWN import com.google.common.truth.Truth.assertThat import java.io.File import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.internal.DoNotInstrument private const val INVALID_FILE_PATH = "/invalid/file/path" private val TEST_OUTPUT_OPTION = FileOutputOptions.Builder(File(INVALID_FILE_PATH)).build() private val TEST_RECORDING_STATE = RecordingStats.of(0, 0, AudioStats.of(AudioStats.AUDIO_STATE_ACTIVE, null)) private val TEST_OUTPUT_RESULT = OutputResults.of(Uri.EMPTY) @RunWith(RobolectricTestRunner::class) @DoNotInstrument @Config(minSdk = Build.VERSION_CODES.LOLLIPOP) class VideoRecordEventTest { @Test fun canCreateStart() { val event = VideoRecordEvent.start( TEST_OUTPUT_OPTION, TEST_RECORDING_STATE ) assertThat(event).isInstanceOf(VideoRecordEvent.Start::class.java) assertThat(event.outputOptions).isEqualTo(TEST_OUTPUT_OPTION) assertThat(event.recordingStats).isEqualTo(TEST_RECORDING_STATE) } @Test fun canCreateFinalize() { val event = VideoRecordEvent.finalize( TEST_OUTPUT_OPTION, TEST_RECORDING_STATE, TEST_OUTPUT_RESULT ) assertThat(event).isInstanceOf(VideoRecordEvent.Finalize::class.java) assertThat(event.outputOptions).isEqualTo(TEST_OUTPUT_OPTION) assertThat(event.recordingStats).isEqualTo(TEST_RECORDING_STATE) assertThat(event.outputResults).isEqualTo(TEST_OUTPUT_RESULT) assertThat(event.hasError()).isFalse() assertThat(event.error).isEqualTo(ERROR_NONE) assertThat(event.cause).isNull() } @Test fun canCreateFinalizeWithError() { val error = ERROR_UNKNOWN val cause = RuntimeException() val event = VideoRecordEvent.finalizeWithError( TEST_OUTPUT_OPTION, TEST_RECORDING_STATE, TEST_OUTPUT_RESULT, error, cause ) assertThat(event).isInstanceOf(VideoRecordEvent.Finalize::class.java) assertThat(event.outputOptions).isEqualTo(TEST_OUTPUT_OPTION) assertThat(event.recordingStats).isEqualTo(TEST_RECORDING_STATE) assertThat(event.outputResults).isEqualTo(TEST_OUTPUT_RESULT) assertThat(event.hasError()).isTrue() assertThat(event.error).isEqualTo(error) assertThat(event.cause).isEqualTo(cause) } @Test fun createFinalizeWithError_withErrorNone_throwException() { Assert.assertThrows(IllegalArgumentException::class.java) { VideoRecordEvent.finalizeWithError( TEST_OUTPUT_OPTION, TEST_RECORDING_STATE, TEST_OUTPUT_RESULT, ERROR_NONE, RuntimeException() ) } } @Test fun canCreateStatus() { val event = VideoRecordEvent.status( TEST_OUTPUT_OPTION, TEST_RECORDING_STATE ) assertThat(event).isInstanceOf(VideoRecordEvent.Status::class.java) assertThat(event.outputOptions).isEqualTo(TEST_OUTPUT_OPTION) assertThat(event.recordingStats).isEqualTo(TEST_RECORDING_STATE) } @Test fun canCreatePause() { val event = VideoRecordEvent.pause( TEST_OUTPUT_OPTION, TEST_RECORDING_STATE ) assertThat(event).isInstanceOf(VideoRecordEvent.Pause::class.java) assertThat(event.outputOptions).isEqualTo(TEST_OUTPUT_OPTION) assertThat(event.recordingStats).isEqualTo(TEST_RECORDING_STATE) } @Test fun canCreateResume() { val event = VideoRecordEvent.resume( TEST_OUTPUT_OPTION, TEST_RECORDING_STATE ) assertThat(event).isInstanceOf(VideoRecordEvent.Resume::class.java) assertThat(event.outputOptions).isEqualTo(TEST_OUTPUT_OPTION) assertThat(event.recordingStats).isEqualTo(TEST_RECORDING_STATE) } }
apache-2.0
androidx/androidx
work/work-benchmark/src/androidTest/java/androidx/work/benchmark/DispatchingExecutor.kt
3
1345
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.benchmark import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import java.util.concurrent.Executor /** * An [Executor] where we can await termination of all commands. */ class DispatchingExecutor : Executor { private val job = CompletableDeferred<Unit>() private val scope = CoroutineScope(Dispatchers.Default + job) override fun execute(command: Runnable) { scope.launch { command.run() } } fun runAllCommands() { runBlocking { job.complete(Unit) job.join() } } }
apache-2.0
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/vulkan/ValidityProtos.kt
1
197542
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan import org.lwjgl.generator.* object ValidityProtos { @JvmField val vkAcquireNextImageKHR = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code swapchain} $must be a valid {@code VkSwapchainKHR} handle", "If {@code semaphore} is not #NULL_HANDLE, {@code semaphore} $must be a valid {@code VkSemaphore} handle", "If {@code fence} is not #NULL_HANDLE, {@code fence} $must be a valid {@code VkFence} handle", "{@code pImageIndex} $must be a pointer to a {@code uint32_t} value", "If {@code semaphore} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "If {@code fence} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "If {@code semaphore} is not #NULL_HANDLE it $must be unsignaled", """ If {@code fence} is not #NULL_HANDLE it $must be unsignaled and $must not be associated with any other queue command that has not yet completed execution on that queue """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code swapchain} $must be externally synchronized", "Host access to {@code semaphore} $must be externally synchronized", "Host access to {@code fence} $must be externally synchronized" )}""" @JvmField val vkAllocateCommandBuffers = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pAllocateInfo} $must be a pointer to a valid ##VkCommandBufferAllocateInfo structure", "{@code pCommandBuffers} $must be a pointer to an array of {@code pAllocateInfo}->commandBufferCount {@code VkCommandBuffer} handles" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pAllocateInfo}->commandPool $must be externally synchronized" )}""" @JvmField val vkAllocateDescriptorSets = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pAllocateInfo} $must be a pointer to a valid ##VkDescriptorSetAllocateInfo structure", "{@code pDescriptorSets} $must be a pointer to an array of {@code pAllocateInfo}->descriptorSetCount {@code VkDescriptorSet} handles" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pAllocateInfo}->descriptorPool $must be externally synchronized" )}""" @JvmField val vkAllocateMemory = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pAllocateInfo} $must be a pointer to a valid ##VkMemoryAllocateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pMemory} $must be a pointer to a {@code VkDeviceMemory} handle", """ The number of currently valid memory objects, allocated from {@code device}, $must be less than ##VkPhysicalDeviceLimits{@code ::maxMemoryAllocationCount} """ )}""" @JvmField val vkBeginCommandBuffer = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pBeginInfo} $must be a pointer to a valid ##VkCommandBufferBeginInfo structure", "{@code commandBuffer} $must not be in the recording state", "{@code commandBuffer} $must not currently be pending execution", """ If {@code commandBuffer} was allocated from a {@code VkCommandPool} which did not have the #COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT flag set, {@code commandBuffer} $must be in the initial state """, """ If {@code commandBuffer} is a secondary command buffer, the {@code pInheritanceInfo} member of {@code pBeginInfo} $must be a valid ##VkCommandBufferInheritanceInfo structure """, """ If {@code commandBuffer} is a secondary command buffer and either the {@code occlusionQueryEnable} member of the {@code pInheritanceInfo} member of {@code pBeginInfo} is #FALSE, or the precise occlusion queries feature is not enabled, the {@code queryFlags} member of the {@code pInheritanceInfo} member {@code pBeginInfo} $must not contain #QUERY_CONTROL_PRECISE_BIT """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkBindBufferMemory = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code buffer} $must be a valid {@code VkBuffer} handle", "{@code memory} $must be a valid {@code VkDeviceMemory} handle", "{@code buffer} $must have been created, allocated, or retrieved from {@code device}", "{@code memory} $must have been created, allocated, or retrieved from {@code device}", "{@code buffer} $must not already be backed by a memory object", "{@code buffer} $must not have been created with any sparse memory binding flags", "{@code memoryOffset} $must be less than the size of {@code memory}", """ If {@code buffer} was created with the #BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT or #BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, {@code memoryOffset} $must be a multiple of ##VkPhysicalDeviceLimits{@code ::minTexelBufferOffsetAlignment} """, """ If {@code buffer} was created with the #BUFFER_USAGE_UNIFORM_BUFFER_BIT, {@code memoryOffset} $must be a multiple of ##VkPhysicalDeviceLimits{@code ::minUniformBufferOffsetAlignment} """, """ If {@code buffer} was created with the #BUFFER_USAGE_STORAGE_BUFFER_BIT, {@code memoryOffset} $must be a multiple of ##VkPhysicalDeviceLimits{@code ::minStorageBufferOffsetAlignment} """, """ {@code memory} $must have been allocated using one of the memory types allowed in the {@code memoryTypeBits} member of the ##VkMemoryRequirements structure returned from a call to #GetBufferMemoryRequirements() with {@code buffer} """, """ {@code memoryOffset} $must be an integer multiple of the {@code alignment} member of the ##VkMemoryRequirements structure returned from a call to #GetBufferMemoryRequirements() with {@code buffer} """, """ The {@code size} member of the ##VkMemoryRequirements structure returned from a call to #GetBufferMemoryRequirements() with {@code buffer} $must be less than or equal to the size of {@code memory} minus {@code memoryOffset} """, """ If {@code buffer} was created with ##VkDedicatedAllocationBufferCreateInfoNV{@code ::dedicatedAllocation} equal to #TRUE, {@code memory} $must have been created with ##VkDedicatedAllocationMemoryAllocateInfoNV{@code ::buffer} equal to {@code buffer} and {@code memoryOffset} $must be zero """, """ If {@code buffer} was not created with ##VkDedicatedAllocationBufferCreateInfoNV{@code ::dedicatedAllocation} equal to #TRUE, {@code memory} $must not have been allocated dedicated for a specific buffer or image """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code buffer} $must be externally synchronized" )}""" @JvmField val vkBindImageMemory = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code image} $must be a valid {@code VkImage} handle", "{@code memory} $must be a valid {@code VkDeviceMemory} handle", "{@code image} $must have been created, allocated, or retrieved from {@code device}", "{@code memory} $must have been created, allocated, or retrieved from {@code device}", "{@code image} $must not already be backed by a memory object", "{@code image} $must not have been created with any sparse memory binding flags", "{@code memoryOffset} $must be less than the size of {@code memory}", """ {@code memory} $must have been allocated using one of the memory types allowed in the {@code memoryTypeBits} member of the ##VkMemoryRequirements structure returned from a call to #GetImageMemoryRequirements() with {@code image} """, """ {@code memoryOffset} $must be an integer multiple of the {@code alignment} member of the ##VkMemoryRequirements structure returned from a call to #GetImageMemoryRequirements() with {@code image} """, """ The {@code size} member of the ##VkMemoryRequirements structure returned from a call to #GetImageMemoryRequirements() with {@code image} $must be less than or equal to the size of {@code memory} minus {@code memoryOffset} """, """ If {@code image} was created with ##VkDedicatedAllocationImageCreateInfoNV{@code ::dedicatedAllocation} equal to #TRUE, {@code memory} $must have been created with ##VkDedicatedAllocationMemoryAllocateInfoNV{@code ::image} equal to {@code image} and {@code memoryOffset} $must be zero """, """ If {@code image} was not created with ##VkDedicatedAllocationImageCreateInfoNV{@code ::dedicatedAllocation} equal to #TRUE, {@code memory} $must not have been allocated dedicated for a specific buffer or image """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code image} $must be externally synchronized" )}""" @JvmField val vkCmdBeginQuery = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code queryPool} $must be a valid {@code VkQueryPool} handle", "{@code flags} $must be a valid combination of {@code VkQueryControlFlagBits} values", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "Both of {@code commandBuffer}, and {@code queryPool} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "The query identified by {@code queryPool} and {@code query} $must currently not be active", "The query identified by {@code queryPool} and {@code query} $must be unavailable", """ If the precise occlusion queries feature is not enabled, or the {@code queryType} used to create {@code queryPool} was not #QUERY_TYPE_OCCLUSION, {@code flags} $must not contain #QUERY_CONTROL_PRECISE_BIT """, """ {@code queryPool} $must have been created with a {@code queryType} that differs from that of any other queries that have been made active, and are currently still active within {@code commandBuffer} """, "{@code query} $must be less than the number of queries in {@code queryPool}", """ If the {@code queryType} used to create {@code queryPool} was #QUERY_TYPE_OCCLUSION, the {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations """, """ If the {@code queryType} used to create {@code queryPool} was #QUERY_TYPE_PIPELINE_STATISTICS and any of the {@code pipelineStatistics} indicate graphics operations, the {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations """, """ If the {@code queryType} used to create {@code queryPool} was #QUERY_TYPE_PIPELINE_STATISTICS and any of the {@code pipelineStatistics} indicate compute operations, the {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support compute operations """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdBeginRenderPass = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pRenderPassBegin} $must be a pointer to a valid ##VkRenderPassBeginInfo structure", "{@code contents} $must be a valid {@code VkSubpassContents} value", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called outside of a render pass instance", "{@code commandBuffer} $must be a primary {@code VkCommandBuffer}", """ If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL then the corresponding attachment image subresource of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} $must have been created with #IMAGE_USAGE_COLOR_ATTACHMENT_BIT set """, """ If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL or #IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL then the corresponding attachment image subresource of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} $must have been created with #IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT set """, """ If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL then the corresponding attachment image subresource of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} $must have been created with #IMAGE_USAGE_SAMPLED_BIT or #IMAGE_USAGE_INPUT_ATTACHMENT_BIT set """, """ If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL then the corresponding attachment image subresource of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} $must have been created with #IMAGE_USAGE_TRANSFER_SRC_BIT set """, """ If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL then the corresponding attachment image subresource of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} $must have been created with #IMAGE_USAGE_TRANSFER_DST_BIT set """, """ If any of the {@code initialLayout} members of the ##VkAttachmentDescription structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is not #IMAGE_LAYOUT_UNDEFINED, then each such {@code initialLayout} $must be equal to the current layout of the corresponding attachment image subresource of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdBindDescriptorSets = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pipelineBindPoint} $must be a valid {@code VkPipelineBindPoint} value", "{@code layout} $must be a valid {@code VkPipelineLayout} handle", "{@code pDescriptorSets} $must be a pointer to an array of {@code descriptorSetCount} valid {@code VkDescriptorSet} handles", """ If {@code dynamicOffsetCount} is not 0, {@code pDynamicOffsets} $must be a pointer to an array of {@code dynamicOffsetCount} {@code uint32_t} values """, "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "{@code descriptorSetCount} $must be greater than 0", """ Each of {@code commandBuffer}, {@code layout}, and the elements of {@code pDescriptorSets} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, """ Any given element of {@code pDescriptorSets} $must have been allocated with a {@code VkDescriptorSetLayout} that matches (is the same as, or defined identically to) the {@code VkDescriptorSetLayout} at set {@code n} in {@code layout}, where {@code n} is the sum of {@code firstSet} and the index into {@code pDescriptorSets} """, "{@code dynamicOffsetCount} $must be equal to the total number of dynamic descriptors in {@code pDescriptorSets}", """ The sum of {@code firstSet} and {@code descriptorSetCount} $must be less than or equal to ##VkPipelineLayoutCreateInfo{@code ::setLayoutCount} provided when {@code layout} was created """, "{@code pipelineBindPoint} $must be supported by the {@code commandBuffer}'s parent {@code VkCommandPool}'s queue family", "Any given element of {@code pDynamicOffsets} $must satisfy the required alignment for the corresponding descriptor binding's descriptor type" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdBindIndexBuffer = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code buffer} $must be a valid {@code VkBuffer} handle", "{@code indexType} $must be a valid {@code VkIndexType} value", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "Both of {@code buffer}, and {@code commandBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code offset} $must be less than the size of {@code buffer}", """ The sum of {@code offset} and the address of the range of {@code VkDeviceMemory} object that is backing {@code buffer}, $must be a multiple of the type indicated by {@code indexType} """, "{@code buffer} $must have been created with the #BUFFER_USAGE_INDEX_BUFFER_BIT flag" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdBindPipeline = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pipelineBindPoint} $must be a valid {@code VkPipelineBindPoint} value", "{@code pipeline} $must be a valid {@code VkPipeline} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "Both of {@code commandBuffer}, and {@code pipeline} $must have been created, allocated, or retrieved from the same {@code VkDevice}", """ If {@code pipelineBindPoint} is #PIPELINE_BIND_POINT_COMPUTE, the {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support compute operations """, """ If {@code pipelineBindPoint} is #PIPELINE_BIND_POINT_GRAPHICS, the {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations """, "If {@code pipelineBindPoint} is #PIPELINE_BIND_POINT_COMPUTE, {@code pipeline} $must be a compute pipeline", "If {@code pipelineBindPoint} is #PIPELINE_BIND_POINT_GRAPHICS, {@code pipeline} $must be a graphics pipeline", """ If the variable multisample rate feature is not supported, {@code pipeline} is a graphics pipeline, the current subpass has no attachments, and this is not the first call to this function with a graphics pipeline after transitioning to the current subpass, then the sample count specified by this pipeline $must match that set in the previous pipeline """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdBindVertexBuffers = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pBuffers} $must be a pointer to an array of {@code bindingCount} valid {@code VkBuffer} handles", "{@code pOffsets} $must be a pointer to an array of {@code bindingCount} {@code VkDeviceSize} values", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "{@code bindingCount} $must be greater than 0", """ Both of {@code commandBuffer}, and the elements of {@code pBuffers} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "{@code firstBinding} $must be less than ##VkPhysicalDeviceLimits{@code ::maxVertexInputBindings}", "The sum of {@code firstBinding} and {@code bindingCount} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxVertexInputBindings}", "All elements of {@code pOffsets} $must be less than the size of the corresponding element in {@code pBuffers}", "All elements of {@code pBuffers} $must have been created with the #BUFFER_USAGE_VERTEX_BUFFER_BIT flag" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdBlitImage = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code srcImage} $must be a valid {@code VkImage} handle", "{@code srcImageLayout} $must be a valid {@code VkImageLayout} value", "{@code dstImage} $must be a valid {@code VkImage} handle", "{@code dstImageLayout} $must be a valid {@code VkImageLayout} value", "{@code pRegions} $must be a pointer to an array of {@code regionCount} valid ##VkImageBlit structures", "{@code filter} $must be a valid {@code VkFilter} value", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called outside of a render pass instance", "{@code regionCount} $must be greater than 0", """ Each of {@code commandBuffer}, {@code dstImage}, and {@code srcImage} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "The source region specified by a given element of {@code pRegions} $must be a region that is contained within {@code srcImage}", "The destination region specified by a given element of {@code pRegions} $must be a region that is contained within {@code dstImage}", """ The union of all destination regions, specified by the elements of {@code pRegions}, $must not overlap in memory with any texel that $may be sampled during the blit operation """, """ {@code srcImage} $must use a format that supports #FORMAT_FEATURE_BLIT_SRC_BIT, which is indicated by ##VkFormatProperties{@code ::linearTilingFeatures} (for linear tiled images) or ##VkFormatProperties{@code ::optimalTilingFeatures} (for optimally tiled images) - as returned by #GetPhysicalDeviceFormatProperties() """, "{@code srcImage} $must have been created with #IMAGE_USAGE_TRANSFER_SRC_BIT usage flag", """ {@code srcImageLayout} $must specify the layout of the image subresources of {@code srcImage} specified in {@code pRegions} at the time this command is executed on a {@code VkDevice} """, "{@code srcImageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL or #IMAGE_LAYOUT_GENERAL", """ {@code dstImage} $must use a format that supports #FORMAT_FEATURE_BLIT_DST_BIT, which is indicated by ##VkFormatProperties{@code ::linearTilingFeatures} (for linear tiled images) or ##VkFormatProperties{@code ::optimalTilingFeatures} (for optimally tiled images) - as returned by #GetPhysicalDeviceFormatProperties() """, "{@code dstImage} $must have been created with #IMAGE_USAGE_TRANSFER_DST_BIT usage flag", """ {@code dstImageLayout} $must specify the layout of the image subresources of {@code dstImage} specified in {@code pRegions} at the time this command is executed on a {@code VkDevice} """, "{@code dstImageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL or #IMAGE_LAYOUT_GENERAL", "The sample count of {@code srcImage} and {@code dstImage} $must both be equal to #SAMPLE_COUNT_1_BIT", """ If either of {@code srcImage} or {@code dstImage} was created with a signed integer {@code VkFormat}, the other $must also have been created with a signed integer {@code VkFormat} """, """ If either of {@code srcImage} or {@code dstImage} was created with an unsigned integer {@code VkFormat}, the other $must also have been created with an unsigned integer {@code VkFormat} """, "If either of {@code srcImage} or {@code dstImage} was created with a depth/stencil format, the other $must have exactly the same format", "If {@code srcImage} was created with a depth/stencil format, {@code filter} $must be #FILTER_NEAREST", "{@code srcImage} $must have been created with a {@code samples} value of #SAMPLE_COUNT_1_BIT", "{@code dstImage} $must have been created with a {@code samples} value of #SAMPLE_COUNT_1_BIT", """ If {@code filter} is #FILTER_LINEAR, {@code srcImage} $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ If {@code filter} is #FILTER_CUBIC_IMG, {@code srcImage} $must be of a format which supports cubic filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, "If {@code filter} is #FILTER_CUBIC_IMG, {@code srcImage} $must have a {@code VkImageType} of #IMAGE_TYPE_3D" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdClearAttachments = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pAttachments} $must be a pointer to an array of {@code attachmentCount} valid ##VkClearAttachment structures", "{@code pRects} $must be a pointer to an array of {@code rectCount} ##VkClearRect structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", "{@code attachmentCount} $must be greater than 0", "{@code rectCount} $must be greater than 0", """ If the {@code aspectMask} member of any given element of {@code pAttachments} contains #IMAGE_ASPECT_COLOR_BIT, the {@code colorAttachment} member of those elements $must refer to a valid color attachment in the current subpass """, """ The rectangular region specified by a given element of {@code pRects} $must be contained within the render area of the current render pass instance """, "The layers specified by a given element of {@code pRects} $must be contained within every attachment that {@code pAttachments} refers to" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdClearColorImage = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code image} $must be a valid {@code VkImage} handle", "{@code imageLayout} $must be a valid {@code VkImageLayout} value", "{@code pColor} $must be a pointer to a valid {@code VkClearColorValue} union", "{@code pRanges} $must be a pointer to an array of {@code rangeCount} valid ##VkImageSubresourceRange structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "This command $must only be called outside of a render pass instance", "{@code rangeCount} $must be greater than 0", "Both of {@code commandBuffer}, and {@code image} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code image} $must have been created with #IMAGE_USAGE_TRANSFER_DST_BIT usage flag", """ {@code imageLayout} $must specify the layout of the image subresource ranges of {@code image} specified in {@code pRanges} at the time this command is executed on a {@code VkDevice} """, "{@code imageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL or #IMAGE_LAYOUT_GENERAL", "The image range of any given element of {@code pRanges} $must be an image subresource range that is contained within {@code image}", "{@code image} $must not have a compressed or depth/stencil format" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdClearDepthStencilImage = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code image} $must be a valid {@code VkImage} handle", "{@code imageLayout} $must be a valid {@code VkImageLayout} value", "{@code pDepthStencil} $must be a pointer to a valid ##VkClearDepthStencilValue structure", "{@code pRanges} $must be a pointer to an array of {@code rangeCount} valid ##VkImageSubresourceRange structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called outside of a render pass instance", "{@code rangeCount} $must be greater than 0", "Both of {@code commandBuffer}, and {@code image} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code image} $must have been created with #IMAGE_USAGE_TRANSFER_DST_BIT usage flag", """ {@code imageLayout} $must specify the layout of the image subresource ranges of {@code image} specified in {@code pRanges} at the time this command is executed on a {@code VkDevice} """, "{@code imageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL or #IMAGE_LAYOUT_GENERAL", "The image range of any given element of {@code pRanges} $must be an image subresource range that is contained within {@code image}", "{@code image} $must have a depth/stencil format" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdCopyBuffer = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code srcBuffer} $must be a valid {@code VkBuffer} handle", "{@code dstBuffer} $must be a valid {@code VkBuffer} handle", "{@code pRegions} $must be a pointer to an array of {@code regionCount} ##VkBufferCopy structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support transfer, graphics, or compute operations", "This command $must only be called outside of a render pass instance", "{@code regionCount} $must be greater than 0", """ Each of {@code commandBuffer}, {@code dstBuffer}, and {@code srcBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "The {@code size} member of a given element of {@code pRegions} $must be greater than 0", "The {@code srcOffset} member of a given element of {@code pRegions} $must be less than the size of {@code srcBuffer}", "The {@code dstOffset} member of a given element of {@code pRegions} $must be less than the size of {@code dstBuffer}", """ The {@code size} member of a given element of {@code pRegions} $must be less than or equal to the size of {@code srcBuffer} minus {@code srcOffset} """, """ The {@code size} member of a given element of {@code pRegions} $must be less than or equal to the size of {@code dstBuffer} minus {@code dstOffset} """, """ The union of the source regions, and the union of the destination regions, specified by the elements of {@code pRegions}, $must not overlap in memory """, "{@code srcBuffer} $must have been created with #BUFFER_USAGE_TRANSFER_SRC_BIT usage flag", "{@code dstBuffer} $must have been created with #BUFFER_USAGE_TRANSFER_DST_BIT usage flag" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdCopyBufferToImage = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code srcBuffer} $must be a valid {@code VkBuffer} handle", "{@code dstImage} $must be a valid {@code VkImage} handle", "{@code dstImageLayout} $must be a valid {@code VkImageLayout} value", "{@code pRegions} $must be a pointer to an array of {@code regionCount} valid ##VkBufferImageCopy structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support transfer, graphics, or compute operations", "This command $must only be called outside of a render pass instance", "{@code regionCount} $must be greater than 0", """ Each of {@code commandBuffer}, {@code dstImage}, and {@code srcBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "The buffer region specified by a given element of {@code pRegions} $must be a region that is contained within {@code srcBuffer}", "The image region specified by a given element of {@code pRegions} $must be a region that is contained within {@code dstImage}", """ The union of all source regions, and the union of all destination regions, specified by the elements of {@code pRegions}, $must not overlap in memory """, "{@code srcBuffer} $must have been created with #BUFFER_USAGE_TRANSFER_SRC_BIT usage flag", "{@code dstImage} $must have been created with #IMAGE_USAGE_TRANSFER_DST_BIT usage flag", "{@code dstImage} $must have a sample count equal to #SAMPLE_COUNT_1_BIT", """ {@code dstImageLayout} $must specify the layout of the image subresources of {@code dstImage} specified in {@code pRegions} at the time this command is executed on a {@code VkDevice} """, "{@code dstImageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL or #IMAGE_LAYOUT_GENERAL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdCopyImage = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code srcImage} $must be a valid {@code VkImage} handle", "{@code srcImageLayout} $must be a valid {@code VkImageLayout} value", "{@code dstImage} $must be a valid {@code VkImage} handle", "{@code dstImageLayout} $must be a valid {@code VkImageLayout} value", "{@code pRegions} $must be a pointer to an array of {@code regionCount} valid ##VkImageCopy structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support transfer, graphics, or compute operations", "This command $must only be called outside of a render pass instance", "{@code regionCount} $must be greater than 0", """ Each of {@code commandBuffer}, {@code dstImage}, and {@code srcImage} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "The source region specified by a given element of {@code pRegions} $must be a region that is contained within {@code srcImage}", "The destination region specified by a given element of {@code pRegions} $must be a region that is contained within {@code dstImage}", """ The union of all source regions, and the union of all destination regions, specified by the elements of {@code pRegions}, $must not overlap in memory """, "{@code srcImage} $must have been created with #IMAGE_USAGE_TRANSFER_SRC_BIT usage flag", """ {@code srcImageLayout} $must specify the layout of the image subresources of {@code srcImage} specified in {@code pRegions} at the time this command is executed on a {@code VkDevice} """, "{@code srcImageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL or #IMAGE_LAYOUT_GENERAL", "{@code dstImage} $must have been created with #IMAGE_USAGE_TRANSFER_DST_BIT usage flag", """ {@code dstImageLayout} $must specify the layout of the image subresources of {@code dstImage} specified in {@code pRegions} at the time this command is executed on a {@code VkDevice} """, "{@code dstImageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL or #IMAGE_LAYOUT_GENERAL", "The {@code VkFormat} of each of {@code srcImage} and {@code dstImage} $must be compatible, as defined below", "The sample count of {@code srcImage} and {@code dstImage} $must match" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdCopyImageToBuffer = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code srcImage} $must be a valid {@code VkImage} handle", "{@code srcImageLayout} $must be a valid {@code VkImageLayout} value", "{@code dstBuffer} $must be a valid {@code VkBuffer} handle", "{@code pRegions} $must be a pointer to an array of {@code regionCount} valid ##VkBufferImageCopy structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support transfer, graphics, or compute operations", "This command $must only be called outside of a render pass instance", "{@code regionCount} $must be greater than 0", """ Each of {@code commandBuffer}, {@code dstBuffer}, and {@code srcImage} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "The image region specified by a given element of {@code pRegions} $must be a region that is contained within {@code srcImage}", "The buffer region specified by a given element of {@code pRegions} $must be a region that is contained within {@code dstBuffer}", """ The union of all source regions, and the union of all destination regions, specified by the elements of {@code pRegions}, $must not overlap in memory """, "{@code srcImage} $must have been created with #IMAGE_USAGE_TRANSFER_SRC_BIT usage flag", "{@code srcImage} $must have a sample count equal to #SAMPLE_COUNT_1_BIT", """ {@code srcImageLayout} $must specify the layout of the image subresources of {@code srcImage} specified in {@code pRegions} at the time this command is executed on a {@code VkDevice} """, "{@code srcImageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL or #IMAGE_LAYOUT_GENERAL", "{@code dstBuffer} $must have been created with #BUFFER_USAGE_TRANSFER_DST_BIT usage flag" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdCopyQueryPoolResults = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code queryPool} $must be a valid {@code VkQueryPool} handle", "{@code dstBuffer} $must be a valid {@code VkBuffer} handle", "{@code flags} $must be a valid combination of {@code VkQueryResultFlagBits} values", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "This command $must only be called outside of a render pass instance", """ Each of {@code commandBuffer}, {@code dstBuffer}, and {@code queryPool} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "{@code dstOffset} $must be less than the size of {@code dstBuffer}", "{@code firstQuery} $must be less than the number of queries in {@code queryPool}", "The sum of {@code firstQuery} and {@code queryCount} $must be less than or equal to the number of queries in {@code queryPool}", "If #QUERY_RESULT_64_BIT is not set in {@code flags} then {@code dstOffset} and {@code stride} $must be multiples of 4", "If #QUERY_RESULT_64_BIT is set in {@code flags} then {@code dstOffset} and {@code stride} $must be multiples of 8", "{@code dstBuffer} $must have enough storage, from {@code dstOffset}, to contain the result of each query, as described here", "{@code dstBuffer} $must have been created with #BUFFER_USAGE_TRANSFER_DST_BIT usage flag", "If the {@code queryType} used to create {@code queryPool} was #QUERY_TYPE_TIMESTAMP, {@code flags} $must not contain #QUERY_RESULT_PARTIAL_BIT" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdDebugMarkerBeginEXT = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pMarkerInfo} $must be a pointer to a ##VkDebugMarkerMarkerInfoEXT structure", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations" )}""" @JvmField val vkCmdDebugMarkerEndEXT = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", """ There $must be an outstanding #CmdDebugMarkerBeginEXT() command prior to the #CmdDebugMarkerEndEXT() on the queue that {@code commandBuffer} is submitted to """, """ If the matching #CmdDebugMarkerBeginEXT() command was in a secondary command buffer, the #CmdDebugMarkerEndEXT() must be in the same {@code commandBuffer} """ )}""" @JvmField val vkCmdDebugMarkerInsertEXT = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pMarkerInfo} $must be a pointer to a ##VkDebugMarkerMarkerInfoEXT structure", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations" )}""" @JvmField val vkCmdDispatch = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support compute operations", "This command $must only be called outside of a render pass instance", "{@code x} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxComputeWorkGroupCount}[0]", "{@code y} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxComputeWorkGroupCount}[1]", "{@code z} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxComputeWorkGroupCount}[2]", """ For each set {@code n} that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE, a descriptor set $must have been bound to {@code n} at #PIPELINE_BIND_POINT_COMPUTE, with a {@code VkPipelineLayout} that is compatible for set {@code n}, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ Descriptors in each bound descriptor set, specified via #CmdBindDescriptorSets(), $must be valid if they are statically used by the currently bound {@code VkPipeline} object, specified via #CmdBindPipeline() """, "A valid compute pipeline $must be bound to the current command buffer with #PIPELINE_BIND_POINT_COMPUTE", """ For each push constant that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE, a push constant value $must have been set for #PIPELINE_BIND_POINT_COMPUTE, with a {@code VkPipelineLayout} that is compatible for push constants with the one used to create the current {@code VkPipeline} """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE uses unnormalized coordinates, it $must not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, #IMAGE_VIEW_TYPE_1D_ARRAY, #IMAGE_VIEW_TYPE_2D_ARRAY or #IMAGE_VIEW_TYPE_CUBE_ARRAY, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_COMPUTE accesses a uniform buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_COMPUTE accesses a storage buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ Any {@code VkImageView} being sampled with #FILTER_LINEAR as a result of this command $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must be of a format which supports cubic filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must not have a {@code VkImageViewType} of #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, or #IMAGE_VIEW_TYPE_CUBE_ARRAY """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdDispatchIndirect = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code buffer} $must be a valid {@code VkBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support compute operations", "This command $must only be called outside of a render pass instance", "Both of {@code buffer}, and {@code commandBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice}", """ For each set {@code n} that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE, a descriptor set $must have been bound to {@code n} at #PIPELINE_BIND_POINT_COMPUTE, with a {@code VkPipelineLayout} that is compatible for set {@code n}, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ Descriptors in each bound descriptor set, specified via #CmdBindDescriptorSets(), $must be valid if they are statically used by the currently bound {@code VkPipeline} object, specified via #CmdBindPipeline() """, "A valid compute pipeline $must be bound to the current command buffer with #PIPELINE_BIND_POINT_COMPUTE", "{@code buffer} $must have been created with the #BUFFER_USAGE_INDIRECT_BUFFER_BIT bit set", "{@code offset} $must be a multiple of 4", "The sum of {@code offset} and the size of {@code VkDispatchIndirectCommand} $must be less than or equal to the size of {@code buffer}", """ For each push constant that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE, a push constant value $must have been set for #PIPELINE_BIND_POINT_COMPUTE, with a {@code VkPipelineLayout} that is compatible for push constants with the one used to create the current {@code VkPipeline} """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE uses unnormalized coordinates, it $must not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, #IMAGE_VIEW_TYPE_1D_ARRAY, #IMAGE_VIEW_TYPE_2D_ARRAY or #IMAGE_VIEW_TYPE_CUBE_ARRAY, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_COMPUTE uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_COMPUTE accesses a uniform buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_COMPUTE accesses a storage buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ Any {@code VkImageView} being sampled with #FILTER_LINEAR as a result of this command $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must be of a format which supports cubic filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must not have a {@code VkImageViewType} of #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, or #IMAGE_VIEW_TYPE_CUBE_ARRAY """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdDraw = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", """ For each set {@code n} that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a descriptor set $must have been bound to {@code n} at #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for set {@code n}, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ For each push constant that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a push constant value $must have been set for #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ Descriptors in each bound descriptor set, specified via #CmdBindDescriptorSets(), $must be valid if they are statically used by the currently bound {@code VkPipeline} object, specified via #CmdBindPipeline() """, """ All vertex input bindings accessed via vertex input variables declared in the vertex shader entry point's interface $must have valid buffers bound """, "For a given vertex buffer binding, any attribute data fetched $must be entirely contained within the corresponding vertex buffer binding", "A valid graphics pipeline $must be bound to the current command buffer with #PIPELINE_BIND_POINT_GRAPHICS", """ If the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS requires any dynamic state, that state $must have been set on the current command buffer """, "Every input attachment used by the current subpass $must be bound to the pipeline via a descriptor set", """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, #IMAGE_VIEW_TYPE_1D_ARRAY, #IMAGE_VIEW_TYPE_2D_ARRAY or #IMAGE_VIEW_TYPE_CUBE_ARRAY, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a uniform buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a storage buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ Any {@code VkImageView} being sampled with #FILTER_LINEAR as a result of this command $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must be of a format which supports cubic filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must not have a {@code VkImageViewType} of #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, or #IMAGE_VIEW_TYPE_CUBE_ARRAY """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdDrawIndexed = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", """ For each set {@code n} that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a descriptor set $must have been bound to {@code n} at #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for set {@code n}, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ For each push constant that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a push constant value $must have been set for #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ Descriptors in each bound descriptor set, specified via #CmdBindDescriptorSets(), $must be valid if they are statically used by the currently bound {@code VkPipeline} object, specified via #CmdBindPipeline() """, """ All vertex input bindings accessed via vertex input variables declared in the vertex shader entry point's interface $must have valid buffers bound """, "For a given vertex buffer binding, any attribute data fetched $must be entirely contained within the corresponding vertex buffer binding", "A valid graphics pipeline $must be bound to the current command buffer with #PIPELINE_BIND_POINT_GRAPHICS", """ If the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS requires any dynamic state, that state $must have been set on the current command buffer """, """ ({@code indexSize} * ({@code firstIndex} + {@code indexCount}) + {@code offset}) $must be less than or equal to the size of the currently bound index buffer, with indexSize being based on the type specified by {@code indexType}, where the index buffer, {@code indexType}, and {@code offset} are specified via #CmdBindIndexBuffer() """, "Every input attachment used by the current subpass $must be bound to the pipeline via a descriptor set", """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, #IMAGE_VIEW_TYPE_1D_ARRAY, #IMAGE_VIEW_TYPE_2D_ARRAY or #IMAGE_VIEW_TYPE_CUBE_ARRAY, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a uniform buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a storage buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ Any {@code VkImageView} being sampled with #FILTER_LINEAR as a result of this command $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must be of a format which supports cubic filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must not have a {@code VkImageViewType} of #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, or #IMAGE_VIEW_TYPE_CUBE_ARRAY """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdDrawIndexedIndirect = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code buffer} $must be a valid {@code VkBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", "Both of {@code buffer}, and {@code commandBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code offset} $must be a multiple of 4", """ If {@code drawCount} is greater than 1, {@code stride} $must be a multiple of 4 and $must be greater than or equal to sizeof({@code VkDrawIndexedIndirectCommand}) """, "If the multi-draw indirect feature is not enabled, {@code drawCount} $must be 0 or 1", """ If the drawIndirectFirstInstance feature is not enabled, all the {@code firstInstance} members of the ##VkDrawIndexedIndirectCommand structures accessed by this command $must be 0 """, """ For each set {@code n} that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a descriptor set $must have been bound to {@code n} at #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for set {@code n}, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ For each push constant that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a push constant value $must have been set for #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ Descriptors in each bound descriptor set, specified via #CmdBindDescriptorSets(), $must be valid if they are statically used by the currently bound {@code VkPipeline} object, specified via #CmdBindPipeline() """, """ All vertex input bindings accessed via vertex input variables declared in the vertex shader entry point's interface $must have valid buffers bound """, "A valid graphics pipeline $must be bound to the current command buffer with #PIPELINE_BIND_POINT_GRAPHICS", """ If the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS requires any dynamic state, that state $must have been set on the current command buffer """, """ If {@code drawCount} is equal to 1, ({@code offset} + sizeof({@code VkDrawIndexedIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, """ If {@code drawCount} is greater than 1, ({@code stride} x ({@code drawCount} - 1) + {@code offset} + sizeof({@code VkDrawIndexedIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, "{@code drawCount} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxDrawIndirectCount}", "Every input attachment used by the current subpass $must be bound to the pipeline via a descriptor set", """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, #IMAGE_VIEW_TYPE_1D_ARRAY, #IMAGE_VIEW_TYPE_2D_ARRAY or #IMAGE_VIEW_TYPE_CUBE_ARRAY, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a uniform buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a storage buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ Any {@code VkImageView} being sampled with #FILTER_LINEAR as a result of this command $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must be of a format which supports cubic filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must not have a {@code VkImageViewType} of #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, or #IMAGE_VIEW_TYPE_CUBE_ARRAY """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdDrawIndexedIndirectCountAMD = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code buffer} $must be a valid {@code VkBuffer} handle", "{@code countBuffer} $must be a valid {@code VkBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", """ Each of {@code buffer}, {@code commandBuffer}, and {@code countBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "{@code offset} $must be a multiple of 4", "{@code countBufferOffset} $must be a multiple of 4", "{@code stride} $must be a multiple of 4 and $must be greater than or equal to sizeof({@code VkDrawIndirectCommand})", """ If {@code maxDrawCount} is greater than or equal to 1, ({@code stride} x ({@code maxDrawCount} - 1) + {@code offset} + sizeof({@code VkDrawIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, """ If the drawIndirectFirstInstance feature is not enabled, all the {@code firstInstance} members of the ##VkDrawIndexedIndirectCommand structures accessed by this command $must be 0 """, """ For each set {@code n} that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a descriptor set $must have been bound to {@code n} at #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for set {@code n}, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ For each push constant that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a push constant value $must have been set for #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ Descriptors in each bound descriptor set, specified via #CmdBindDescriptorSets(), $must be valid if they are statically used by the currently bound {@code VkPipeline} object, specified via #CmdBindPipeline() """, """ All vertex input bindings accessed via vertex input variables declared in the vertex shader entry point's interface $must have valid buffers bound """, "A valid graphics pipeline $must be bound to the current command buffer with #PIPELINE_BIND_POINT_GRAPHICS", """ If the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS requires any dynamic state, that state $must have been set on the current command buffer """, """ If count stored in {@code countBuffer} is equal to 1, ({@code offset} + sizeof({@code VkDrawIndexedIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, """ If count stored in {@code countBuffer} is greater than 1, ({@code stride} x ({@code drawCount} - 1) + {@code offset} + sizeof({@code VkDrawIndexedIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, "{@code drawCount} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxDrawIndirectCount}", "Every input attachment used by the current subpass $must be bound to the pipeline via a descriptor set", """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, #IMAGE_VIEW_TYPE_1D_ARRAY, #IMAGE_VIEW_TYPE_2D_ARRAY or #IMAGE_VIEW_TYPE_CUBE_ARRAY, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a uniform buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a storage buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ Any {@code VkImageView} being sampled with #FILTER_LINEAR as a result of this command $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdDrawIndirect = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code buffer} $must be a valid {@code VkBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", "Both of {@code buffer}, and {@code commandBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code offset} $must be a multiple of 4", """ If {@code drawCount} is greater than 1, {@code stride} $must be a multiple of 4 and $must be greater than or equal to sizeof({@code VkDrawIndirectCommand}) """, "If the multi-draw indirect feature is not enabled, {@code drawCount} $must be 0 or 1", """ If the drawIndirectFirstInstance feature is not enabled, all the {@code firstInstance} members of the ##VkDrawIndirectCommand structures accessed by this command $must be 0 """, """ For each set {@code n} that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a descriptor set $must have been bound to {@code n} at #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for set {@code n}, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ For each push constant that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a push constant value $must have been set for #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ Descriptors in each bound descriptor set, specified via #CmdBindDescriptorSets(), $must be valid if they are statically used by the currently bound {@code VkPipeline} object, specified via #CmdBindPipeline() """, """ All vertex input bindings accessed via vertex input variables declared in the vertex shader entry point's interface $must have valid buffers bound """, "A valid graphics pipeline $must be bound to the current command buffer with #PIPELINE_BIND_POINT_GRAPHICS", """ If the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS requires any dynamic state, that state $must have been set on the current command buffer """, """ If {@code drawCount} is equal to 1, ({@code offset} + sizeof({@code VkDrawIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, """ If {@code drawCount} is greater than 1, ({@code stride} x ({@code drawCount} - 1) + {@code offset} + sizeof({@code VkDrawIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, "{@code drawCount} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxDrawIndirectCount}", "Every input attachment used by the current subpass $must be bound to the pipeline via a descriptor set", """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, #IMAGE_VIEW_TYPE_1D_ARRAY, #IMAGE_VIEW_TYPE_2D_ARRAY or #IMAGE_VIEW_TYPE_CUBE_ARRAY, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a uniform buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a storage buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ Any {@code VkImageView} being sampled with #FILTER_LINEAR as a result of this command $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must be of a format which supports cubic filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """, """ Any {@code VkImageView} being sampled with #FILTER_CUBIC_IMG as a result of this command $must not have a {@code VkImageViewType} of #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, or #IMAGE_VIEW_TYPE_CUBE_ARRAY """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdDrawIndirectCountAMD = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code buffer} $must be a valid {@code VkBuffer} handle", "{@code countBuffer} $must be a valid {@code VkBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", """ Each of {@code buffer}, {@code commandBuffer}, and {@code countBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "{@code offset} $must be a multiple of 4", "{@code countBufferOffset} $must be a multiple of 4", "{@code stride} $must be a multiple of 4 and $must be greater than or equal to sizeof({@code VkDrawIndirectCommand})", """ If {@code maxDrawCount} is greater than or equal to 1, ({@code stride} x ({@code maxDrawCount} - 1) + {@code offset} + sizeof({@code VkDrawIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, """ If the drawIndirectFirstInstance feature is not enabled, all the {@code firstInstance} members of the ##VkDrawIndirectCommand structures accessed by this command $must be 0 """, """ For each set {@code n} that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a descriptor set $must have been bound to {@code n} at #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for set {@code n}, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ For each push constant that is statically used by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS, a push constant value $must have been set for #PIPELINE_BIND_POINT_GRAPHICS, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline} """, """ Descriptors in each bound descriptor set, specified via #CmdBindDescriptorSets(), $must be valid if they are statically used by the currently bound {@code VkPipeline} object, specified via #CmdBindPipeline() """, """ All vertex input bindings accessed via vertex input variables declared in the vertex shader entry point's interface $must have valid buffers bound """, "A valid graphics pipeline $must be bound to the current command buffer with #PIPELINE_BIND_POINT_GRAPHICS", """ If the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS requires any dynamic state, that state $must have been set on the current command buffer """, """ If the count stored in {@code countBuffer} is equal to 1, ({@code offset} + sizeof({@code VkDrawIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, """ If the count stored in {@code countBuffer} is greater than 1, ({@code stride} x ({@code drawCount} - 1) + {@code offset} + sizeof({@code VkDrawIndirectCommand})) $must be less than or equal to the size of {@code buffer} """, "The count stored in {@code countBuffer} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxDrawIndirectCount}", "Every input attachment used by the current subpass $must be bound to the pipeline via a descriptor set", """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type #IMAGE_VIEW_TYPE_3D, #IMAGE_VIEW_TYPE_CUBE, #IMAGE_VIEW_TYPE_1D_ARRAY, #IMAGE_VIEW_TYPE_2D_ARRAY or #IMAGE_VIEW_TYPE_CUBE_ARRAY, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage """, """ If any {@code VkSampler} object that is accessed from a shader by the {@code VkPipeline} currently bound to #PIPELINE_BIND_POINT_GRAPHICS uses unnormalized coordinates, it $must not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a uniform buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ If the robust buffer access feature is not enabled, and any shader stage in the {@code VkPipeline} object currently bound to #PIPELINE_BIND_POINT_GRAPHICS accesses a storage buffer, it $must not access values outside of the range of that buffer specified in the currently bound descriptor set """, """ Any {@code VkImageView} being sampled with #FILTER_LINEAR as a result of this command $must be of a format which supports linear filtering, as specified by the #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} (for a linear image) or ##VkFormatProperties{@code ::optimalTilingFeatures}(for an optimally tiled image) returned by #GetPhysicalDeviceFormatProperties() """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdEndQuery = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code queryPool} $must be a valid {@code VkQueryPool} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "Both of {@code commandBuffer}, and {@code queryPool} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "The query identified by {@code queryPool} and {@code query} $must currently be active", "{@code query} $must be less than the number of queries in {@code queryPool}" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdEndRenderPass = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", "{@code commandBuffer} $must be a primary {@code VkCommandBuffer}", "The current subpass index $must be equal to the number of subpasses in the render pass minus one" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdExecuteCommands = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pCommandBuffers} $must be a pointer to an array of {@code commandBufferCount} valid {@code VkCommandBuffer} handles", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support transfer, graphics, or compute operations", "{@code commandBuffer} $must be a primary {@code VkCommandBuffer}", "{@code commandBufferCount} $must be greater than 0", """ Both of {@code commandBuffer}, and the elements of {@code pCommandBuffers} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "{@code commandBuffer} $must have been allocated with a {@code level} of #COMMAND_BUFFER_LEVEL_PRIMARY", "Any given element of {@code pCommandBuffers} $must have been allocated with a {@code level} of #COMMAND_BUFFER_LEVEL_SECONDARY", """ Any given element of {@code pCommandBuffers} $must not be already pending execution in {@code commandBuffer}, or appear twice in {@code pCommandBuffers}, unless it was recorded with the #COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT flag """, """ Any given element of {@code pCommandBuffers} $must not be already pending execution in any other {@code VkCommandBuffer}, unless it was recorded with the #COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT flag """, "Any given element of {@code pCommandBuffers} $must be in the executable state", """ Any given element of {@code pCommandBuffers} $must have been allocated from a {@code VkCommandPool} that was created for the same queue family as the {@code VkCommandPool} from which {@code commandBuffer} was allocated """, """ If #CmdExecuteCommands() is being called within a render pass instance, that render pass instance $must have been begun with the {@code contents} parameter of #CmdBeginRenderPass() set to #SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS """, """ If #CmdExecuteCommands() is being called within a render pass instance, any given element of {@code pCommandBuffers} $must have been recorded with the #COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT """, """ If #CmdExecuteCommands() is being called within a render pass instance, any given element of {@code pCommandBuffers} $must have been recorded with ##VkCommandBufferInheritanceInfo{@code ::subpass} set to the index of the subpass which the given command buffer will be executed in """, """ If #CmdExecuteCommands() is being called within a render pass instance, any given element of {@code pCommandBuffers} $must have been recorded with a render pass that is compatible with the current render pass """, """ If #CmdExecuteCommands() is being called within a render pass instance, and any given element of {@code pCommandBuffers} was recorded with ##VkCommandBufferInheritanceInfo{@code ::framebuffer} not equal to #NULL_HANDLE, that {@code VkFramebuffer} $must match the {@code VkFramebuffer} used in the current render pass instance """, """ If #CmdExecuteCommands() is not being called within a render pass instance, any given element of {@code pCommandBuffers} $must not have been recorded with the #COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT """, "If the inherited queries feature is not enabled, {@code commandBuffer} $must not have any queries active", """ If {@code commandBuffer} has a #QUERY_TYPE_OCCLUSION query active, then each element of {@code pCommandBuffers} $must have been recorded with ##VkCommandBufferInheritanceInfo{@code ::occlusionQueryEnable} set to #TRUE """, """ If {@code commandBuffer} has a #QUERY_TYPE_OCCLUSION query active, then each element of {@code pCommandBuffers} $must have been recorded with ##VkCommandBufferInheritanceInfo{@code ::queryFlags} having all bits set that are set for the query """, """ If {@code commandBuffer} has a #QUERY_TYPE_PIPELINE_STATISTICS query active, then each element of {@code pCommandBuffers} $must have been recorded with ##VkCommandBufferInheritanceInfo{@code ::pipelineStatistics} having all bits set that are set in the {@code VkQueryPool} the query uses """, "Any given element of {@code pCommandBuffers} $must not begin any query types that are active in {@code commandBuffer}" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdFillBuffer = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code dstBuffer} $must be a valid {@code VkBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "This command $must only be called outside of a render pass instance", "Both of {@code commandBuffer}, and {@code dstBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code dstOffset} $must be less than the size of {@code dstBuffer}", "{@code dstOffset} $must be a multiple of 4", "If {@code size} is not equal to #WHOLE_SIZE, {@code size} $must be greater than 0", "If {@code size} is not equal to #WHOLE_SIZE, {@code size} $must be less than or equal to the size of {@code dstBuffer} minus {@code dstOffset}", "If {@code size} is not equal to #WHOLE_SIZE, {@code size} $must be a multiple of 4", "{@code dstBuffer} $must have been created with #BUFFER_USAGE_TRANSFER_DST_BIT usage flag" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdNextSubpass = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code contents} $must be a valid {@code VkSubpassContents} value", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called inside of a render pass instance", "{@code commandBuffer} $must be a primary {@code VkCommandBuffer}", "The current subpass index $must be less than the number of subpasses in the render pass minus one" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdPipelineBarrier = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code srcStageMask} $must be a valid combination of {@code VkPipelineStageFlagBits} values", "{@code srcStageMask} $must not be 0", "{@code dstStageMask} $must be a valid combination of {@code VkPipelineStageFlagBits} values", "{@code dstStageMask} $must not be 0", "{@code dependencyFlags} $must be a valid combination of {@code VkDependencyFlagBits} values", """ If {@code memoryBarrierCount} is not 0, {@code pMemoryBarriers} $must be a pointer to an array of {@code memoryBarrierCount} valid ##VkMemoryBarrier structures """, """ If {@code bufferMemoryBarrierCount} is not 0, {@code pBufferMemoryBarriers} $must be a pointer to an array of {@code bufferMemoryBarrierCount} valid ##VkBufferMemoryBarrier structures """, """ If {@code imageMemoryBarrierCount} is not 0, {@code pImageMemoryBarriers} $must be a pointer to an array of {@code imageMemoryBarrierCount} valid ##VkImageMemoryBarrier structures """, "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support transfer, graphics, or compute operations", "If the geometry shaders feature is not enabled, {@code srcStageMask} $must not contain #PIPELINE_STAGE_GEOMETRY_SHADER_BIT", "If the geometry shaders feature is not enabled, {@code dstStageMask} $must not contain #PIPELINE_STAGE_GEOMETRY_SHADER_BIT", """ If the tessellation shaders feature is not enabled, {@code srcStageMask} $must not contain #PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT or #PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT """, """ If the tessellation shaders feature is not enabled, {@code dstStageMask} $must not contain #PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT or #PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT """, """ If #CmdPipelineBarrier() is called within a render pass instance, the render pass $must have been created with a {@code VkSubpassDependency} instance in {@code pDependencies} that expresses a dependency from the current subpass to itself. Additionally: """, "If #CmdPipelineBarrier() is called within a render pass instance, {@code bufferMemoryBarrierCount} $must be 0", """ If #CmdPipelineBarrier() is called within a render pass instance, the {@code image} member of any element of {@code pImageMemoryBarriers} $must be equal to one of the elements of {@code pAttachments} that the current {@code framebuffer} was created with, that is also referred to by one of the elements of the {@code pColorAttachments}, {@code pResolveAttachments} or {@code pDepthStencilAttachment} members of the {@code VkSubpassDescription} instance that the current subpass was created with """, """ If #CmdPipelineBarrier() is called within a render pass instance, the {@code oldLayout} and {@code newLayout} members of any element of {@code pImageMemoryBarriers} $must be equal to the {@code layout} member of an element of the {@code pColorAttachments}, {@code pResolveAttachments} or {@code pDepthStencilAttachment} members of the {@code VkSubpassDescription} instance that the current subpass was created with, that refers to the same {@code image} """, """ If #CmdPipelineBarrier() is called within a render pass instance, the {@code oldLayout} and {@code newLayout} members of an element of {@code pImageMemoryBarriers} $must be equal """, """ If #CmdPipelineBarrier() is called within a render pass instance, the {@code srcQueueFamilyIndex} and {@code dstQueueFamilyIndex} members of any element of {@code pImageMemoryBarriers} $must be #QUEUE_FAMILY_IGNORED """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdPushConstants = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code layout} $must be a valid {@code VkPipelineLayout} handle", "{@code stageFlags} $must be a valid combination of {@code VkShaderStageFlagBits} values", "{@code stageFlags} $must not be 0", "{@code pValues} $must be a pointer to an array of {@code size} bytes", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "{@code size} $must be greater than 0", "Both of {@code commandBuffer}, and {@code layout} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code stageFlags} $must match exactly the shader stages used in {@code layout} for the range specified by {@code offset} and {@code size}", "{@code offset} $must be a multiple of 4", "{@code size} $must be a multiple of 4", "{@code offset} $must be less than ##VkPhysicalDeviceLimits{@code ::maxPushConstantsSize}", "{@code size} $must be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxPushConstantsSize} minus {@code offset}" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdResetEvent = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code event} $must be a valid {@code VkEvent} handle", "{@code stageMask} $must be a valid combination of {@code VkPipelineStageFlagBits} values", "{@code stageMask} $must not be 0", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "This command $must only be called outside of a render pass instance", "Both of {@code commandBuffer}, and {@code event} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "If the geometry shaders feature is not enabled, {@code stageMask} $must not contain #PIPELINE_STAGE_GEOMETRY_SHADER_BIT", """ If the tessellation shaders feature is not enabled, {@code stageMask} $must not contain #PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT or #PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT """, "When this command executes, {@code event} $must not be waited on by a #CmdWaitEvents() command that is currently executing" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdResetQueryPool = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code queryPool} $must be a valid {@code VkQueryPool} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "This command $must only be called outside of a render pass instance", "Both of {@code commandBuffer}, and {@code queryPool} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code firstQuery} $must be less than the number of queries in {@code queryPool}", "The sum of {@code firstQuery} and {@code queryCount} $must be less than or equal to the number of queries in {@code queryPool}" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdResolveImage = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code srcImage} $must be a valid {@code VkImage} handle", "{@code srcImageLayout} $must be a valid {@code VkImageLayout} value", "{@code dstImage} $must be a valid {@code VkImage} handle", "{@code dstImageLayout} $must be a valid {@code VkImageLayout} value", "{@code pRegions} $must be a pointer to an array of {@code regionCount} valid ##VkImageResolve structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "This command $must only be called outside of a render pass instance", "{@code regionCount} $must be greater than 0", """ Each of {@code commandBuffer}, {@code dstImage}, and {@code srcImage} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, "The source region specified by a given element of {@code pRegions} $must be a region that is contained within {@code srcImage}", "The destination region specified by a given element of {@code pRegions} $must be a region that is contained within {@code dstImage}", """ The union of all source regions, and the union of all destination regions, specified by the elements of {@code pRegions}, $must not overlap in memory """, "{@code srcImage} $must have a sample count equal to any valid sample count value other than #SAMPLE_COUNT_1_BIT", "{@code dstImage} $must have a sample count equal to #SAMPLE_COUNT_1_BIT", """ {@code srcImageLayout} $must specify the layout of the image subresources of {@code srcImage} specified in {@code pRegions} at the time this command is executed on a {@code VkDevice} """, "{@code srcImageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL or #IMAGE_LAYOUT_GENERAL", """ {@code dstImageLayout} $must specify the layout of the image subresources of {@code dstImage} specified in {@code pRegions} at the time this command is executed on a {@code VkDevice} """, "{@code dstImageLayout} $must be either of #IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL or #IMAGE_LAYOUT_GENERAL", """ If {@code dstImage} was created with {@code tiling} equal to #IMAGE_TILING_LINEAR, {@code dstImage} $must have been created with a {@code format} that supports being a color attachment, as specified by the #FORMAT_FEATURE_COLOR_ATTACHMENT_BIT flag in ##VkFormatProperties{@code ::linearTilingFeatures} returned by #GetPhysicalDeviceFormatProperties() """, """ If {@code dstImage} was created with {@code tiling} equal to #IMAGE_TILING_OPTIMAL, {@code dstImage} $must have been created with a {@code format} that supports being a color attachment, as specified by the #FORMAT_FEATURE_COLOR_ATTACHMENT_BIT flag in ##VkFormatProperties{@code ::optimalTilingFeatures} returned by #GetPhysicalDeviceFormatProperties() """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetBlendConstants = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_BLEND_CONSTANTS dynamic state enabled" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetDepthBias = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_DEPTH_BIAS dynamic state enabled", "If the depth bias clamping feature is not enabled, {@code depthBiasClamp} $must be 0.0" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetDepthBounds = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_DEPTH_BOUNDS dynamic state enabled", "{@code minDepthBounds} $must be between {@code 0.0} and {@code 1.0}, inclusive", "{@code maxDepthBounds} $must be between {@code 0.0} and {@code 1.0}, inclusive" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetEvent = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code event} $must be a valid {@code VkEvent} handle", "{@code stageMask} $must be a valid combination of {@code VkPipelineStageFlagBits} values", "{@code stageMask} $must not be 0", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "This command $must only be called outside of a render pass instance", "Both of {@code commandBuffer}, and {@code event} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "If the geometry shaders feature is not enabled, {@code stageMask} $must not contain #PIPELINE_STAGE_GEOMETRY_SHADER_BIT", """ If the tessellation shaders feature is not enabled, {@code stageMask} $must not contain #PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT or #PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetLineWidth = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_LINE_WIDTH dynamic state enabled", "If the wide lines feature is not enabled, {@code lineWidth} $must be {@code 1.0}" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetScissor = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pScissors} $must be a pointer to an array of {@code scissorCount} ##VkRect2D structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "{@code scissorCount} $must be greater than 0", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_SCISSOR dynamic state enabled", "{@code firstScissor} $must be less than ##VkPhysicalDeviceLimits{@code ::maxViewports}", "The sum of {@code firstScissor} and {@code scissorCount} $must be between 1 and ##VkPhysicalDeviceLimits{@code ::maxViewports}, inclusive", "The {@code x} and {@code y} members of {@code offset} $must be greater than or equal to 0", "Evaluation of ({@code offset.x} + {@code extent.width}) $must not cause a signed integer addition overflow", "Evaluation of ({@code offset.y} + {@code extent.height}) $must not cause a signed integer addition overflow" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetStencilCompareMask = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code faceMask} $must be a valid combination of {@code VkStencilFaceFlagBits} values", "{@code faceMask} $must not be 0", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_STENCIL_COMPARE_MASK dynamic state enabled" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetStencilReference = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code faceMask} $must be a valid combination of {@code VkStencilFaceFlagBits} values", "{@code faceMask} $must not be 0", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_STENCIL_REFERENCE dynamic state enabled" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetStencilWriteMask = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code faceMask} $must be a valid combination of {@code VkStencilFaceFlagBits} values", "{@code faceMask} $must not be 0", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_STENCIL_WRITE_MASK dynamic state enabled" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdSetViewport = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pViewports} $must be a pointer to an array of {@code viewportCount} valid ##VkViewport structures", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics operations", "{@code viewportCount} $must be greater than 0", "The currently bound graphics pipeline $must have been created with the #DYNAMIC_STATE_VIEWPORT dynamic state enabled", "{@code firstViewport} $must be less than ##VkPhysicalDeviceLimits{@code ::maxViewports}", "The sum of {@code firstViewport} and {@code viewportCount} $must be between 1 and ##VkPhysicalDeviceLimits{@code ::maxViewports}, inclusive" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdUpdateBuffer = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code dstBuffer} $must be a valid {@code VkBuffer} handle", "{@code pData} $must be a pointer to an array of {@code dataSize} bytes", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support transfer, graphics, or compute operations", "This command $must only be called outside of a render pass instance", "{@code dataSize} $must be greater than 0", "Both of {@code commandBuffer}, and {@code dstBuffer} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code dstOffset} $must be less than the size of {@code dstBuffer}", "{@code dataSize} $must be less than or equal to the size of {@code dstBuffer} minus {@code dstOffset}", "{@code dstBuffer} $must have been created with #BUFFER_USAGE_TRANSFER_DST_BIT usage flag", "{@code dstOffset} $must be a multiple of 4", "{@code dataSize} $must be less than or equal to 65536", "{@code dataSize} $must be a multiple of 4" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdWaitEvents = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pEvents} $must be a pointer to an array of {@code eventCount} valid {@code VkEvent} handles", "{@code srcStageMask} $must be a valid combination of {@code VkPipelineStageFlagBits} values", "{@code srcStageMask} $must not be 0", "{@code dstStageMask} $must be a valid combination of {@code VkPipelineStageFlagBits} values", "{@code dstStageMask} $must not be 0", """ If {@code memoryBarrierCount} is not 0, {@code pMemoryBarriers} $must be a pointer to an array of {@code memoryBarrierCount} valid ##VkMemoryBarrier structures """, """ If {@code bufferMemoryBarrierCount} is not 0, {@code pBufferMemoryBarriers} $must be a pointer to an array of {@code bufferMemoryBarrierCount} valid ##VkBufferMemoryBarrier structures """, """ If {@code imageMemoryBarrierCount} is not 0, {@code pImageMemoryBarriers} $must be a pointer to an array of {@code imageMemoryBarrierCount} valid ##VkImageMemoryBarrier structures """, "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "{@code eventCount} $must be greater than 0", """ Both of {@code commandBuffer}, and the elements of {@code pEvents} $must have been created, allocated, or retrieved from the same {@code VkDevice} """, """ {@code srcStageMask} $must be the bitwise OR of the {@code stageMask} parameter used in previous calls to #CmdSetEvent() with any of the members of {@code pEvents} and #PIPELINE_STAGE_HOST_BIT if any of the members of {@code pEvents} was set using #SetEvent() """, "If the geometry shaders feature is not enabled, {@code srcStageMask} $must not contain #PIPELINE_STAGE_GEOMETRY_SHADER_BIT", "If the geometry shaders feature is not enabled, {@code dstStageMask} $must not contain #PIPELINE_STAGE_GEOMETRY_SHADER_BIT", """ If the tessellation shaders feature is not enabled, {@code srcStageMask} $must not contain #PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT or #PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT """, """ If the tessellation shaders feature is not enabled, {@code dstStageMask} $must not contain #PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT or #PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT """, """ If {@code pEvents} includes one or more events that will be signaled by #SetEvent() after {@code commandBuffer} has been submitted to a queue, then #CmdWaitEvents() $must not be called inside a render pass instance """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCmdWriteTimestamp = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code pipelineStage} $must be a valid {@code VkPipelineStageFlagBits} value", "{@code queryPool} $must be a valid {@code VkQueryPool} handle", "{@code commandBuffer} $must be in the recording state", "The {@code VkCommandPool} that {@code commandBuffer} was allocated from $must support graphics, or compute operations", "Both of {@code commandBuffer}, and {@code queryPool} $must have been created, allocated, or retrieved from the same {@code VkDevice}", "The query identified by {@code queryPool} and {@code query} $must be {@code unavailable}", "The command pool's queue family $must support a non-zero {@code timestampValidBits}" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkCreateAndroidSurfaceKHR = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkAndroidSurfaceCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSurface} $must be a pointer to a {@code VkSurfaceKHR} handle" )}""" @JvmField val vkCreateBuffer = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkBufferCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pBuffer} $must be a pointer to a {@code VkBuffer} handle", """ If the {@code flags} member of {@code pCreateInfo} includes #BUFFER_CREATE_SPARSE_BINDING_BIT, creating this {@code VkBuffer} $must not cause the total required sparse memory for all currently valid sparse resources on the device to exceed ##VkPhysicalDeviceLimits{@code ::sparseAddressSpaceSize} """ )}""" @JvmField val vkCreateBufferView = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkBufferViewCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pView} $must be a pointer to a {@code VkBufferView} handle" )}""" @JvmField val vkCreateCommandPool = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkCommandPoolCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pCommandPool} $must be a pointer to a {@code VkCommandPool} handle" )}""" @JvmField val vkCreateComputePipelines = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code pipelineCache} is not #NULL_HANDLE, {@code pipelineCache} $must be a valid {@code VkPipelineCache} handle", "{@code pCreateInfos} $must be a pointer to an array of {@code createInfoCount} valid ##VkComputePipelineCreateInfo structures", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pPipelines} $must be a pointer to an array of {@code createInfoCount} {@code VkPipeline} handles", "{@code createInfoCount} $must be greater than 0", "If {@code pipelineCache} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", """ If the {@code flags} member of any given element of {@code pCreateInfos} contains the #PIPELINE_CREATE_DERIVATIVE_BIT flag, and the {@code basePipelineIndex} member of that same element is not {@code -1}, {@code basePipelineIndex} $must be less than the index into {@code pCreateInfos} that corresponds to that element """ )}""" @JvmField val vkCreateDebugReportCallbackEXT = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkDebugReportCallbackCreateInfoEXT structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pCallback} $must be a pointer to a {@code VkDebugReportCallbackEXT} handle" )}""" @JvmField val vkCreateDescriptorPool = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkDescriptorPoolCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pDescriptorPool} $must be a pointer to a {@code VkDescriptorPool} handle" )}""" @JvmField val vkCreateDescriptorSetLayout = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkDescriptorSetLayoutCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSetLayout} $must be a pointer to a {@code VkDescriptorSetLayout} handle" )}""" @JvmField val vkCreateDevice = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkDeviceCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pDevice} $must be a pointer to a {@code VkDevice} handle" )}""" @JvmField val vkCreateDisplayModeKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code display} $must be a valid {@code VkDisplayKHR} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkDisplayModeCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pMode} $must be a pointer to a {@code VkDisplayModeKHR} handle" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code display} $must be externally synchronized" )}""" @JvmField val vkCreateDisplayPlaneSurfaceKHR = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkDisplaySurfaceCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSurface} $must be a pointer to a {@code VkSurfaceKHR} handle" )}""" @JvmField val vkCreateEvent = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkEventCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pEvent} $must be a pointer to a {@code VkEvent} handle" )}""" @JvmField val vkCreateFence = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkFenceCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pFence} $must be a pointer to a {@code VkFence} handle" )}""" @JvmField val vkCreateFramebuffer = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkFramebufferCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pFramebuffer} $must be a pointer to a {@code VkFramebuffer} handle" )}""" @JvmField val vkCreateGraphicsPipelines = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code pipelineCache} is not #NULL_HANDLE, {@code pipelineCache} $must be a valid {@code VkPipelineCache} handle", "{@code pCreateInfos} $must be a pointer to an array of {@code createInfoCount} valid ##VkGraphicsPipelineCreateInfo structures", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pPipelines} $must be a pointer to an array of {@code createInfoCount} {@code VkPipeline} handles", "{@code createInfoCount} $must be greater than 0", "If {@code pipelineCache} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", """ If the {@code flags} member of any given element of {@code pCreateInfos} contains the #PIPELINE_CREATE_DERIVATIVE_BIT flag, and the {@code basePipelineIndex} member of that same element is not {@code -1}, {@code basePipelineIndex} $must be less than the index into {@code pCreateInfos} that corresponds to that element """ )}""" @JvmField val vkCreateImage = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkImageCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pImage} $must be a pointer to a {@code VkImage} handle", """ If the {@code flags} member of {@code pCreateInfo} includes #IMAGE_CREATE_SPARSE_BINDING_BIT, creating this {@code VkImage} $must not cause the total required sparse memory for all currently valid sparse resources on the device to exceed ##VkPhysicalDeviceLimits{@code ::sparseAddressSpaceSize} """ )}""" @JvmField val vkCreateImageView = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkImageViewCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pView} $must be a pointer to a {@code VkImageView} handle" )}""" @JvmField val vkCreateInstance = """<h5>Valid Usage</h5> ${ul( "{@code pCreateInfo} $must be a pointer to a valid ##VkInstanceCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pInstance} $must be a pointer to a {@code VkInstance} handle" )}""" @JvmField val vkCreateMirSurfaceKHR = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkMirSurfaceCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSurface} $must be a pointer to a {@code VkSurfaceKHR} handle" )}""" @JvmField val vkCreatePipelineCache = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkPipelineCacheCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pPipelineCache} $must be a pointer to a {@code VkPipelineCache} handle" )}""" @JvmField val vkCreatePipelineLayout = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkPipelineLayoutCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pPipelineLayout} $must be a pointer to a {@code VkPipelineLayout} handle" )}""" @JvmField val vkCreateQueryPool = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkQueryPoolCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pQueryPool} $must be a pointer to a {@code VkQueryPool} handle" )}""" @JvmField val vkCreateRenderPass = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkRenderPassCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pRenderPass} $must be a pointer to a {@code VkRenderPass} handle" )}""" @JvmField val vkCreateSampler = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkSamplerCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSampler} $must be a pointer to a {@code VkSampler} handle" )}""" @JvmField val vkCreateSemaphore = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkSemaphoreCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSemaphore} $must be a pointer to a {@code VkSemaphore} handle" )}""" @JvmField val vkCreateShaderModule = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkShaderModuleCreateInfo structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pShaderModule} $must be a pointer to a {@code VkShaderModule} handle" )}""" @JvmField val vkCreateSharedSwapchainsKHR = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfos} $must be a pointer to an array of {@code swapchainCount} valid ##VkSwapchainCreateInfoKHR structures", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSwapchains} $must be a pointer to an array of {@code swapchainCount} {@code VkSwapchainKHR} handles", "{@code swapchainCount} $must be greater than 0" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pCreateInfos}[].surface $must be externally synchronized", "Host access to {@code pCreateInfos}[].oldSwapchain $must be externally synchronized" )}""" @JvmField val vkCreateSwapchainKHR = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkSwapchainCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSwapchain} $must be a pointer to a {@code VkSwapchainKHR} handle" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pCreateInfo.surface} $must be externally synchronized", "Host access to {@code pCreateInfo.oldSwapchain} $must be externally synchronized" )}""" @JvmField val vkCreateWaylandSurfaceKHR = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkWaylandSurfaceCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSurface} $must be a pointer to a {@code VkSurfaceKHR} handle" )}""" @JvmField val vkCreateWin32SurfaceKHR = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkWin32SurfaceCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSurface} $must be a pointer to a {@code VkSurfaceKHR} handle" )}""" @JvmField val vkCreateXcbSurfaceKHR = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkXcbSurfaceCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSurface} $must be a pointer to a {@code VkSurfaceKHR} handle" )}""" @JvmField val vkCreateXlibSurfaceKHR = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pCreateInfo} $must be a pointer to a valid ##VkXlibSurfaceCreateInfoKHR structure", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code pSurface} $must be a pointer to a {@code VkSurfaceKHR} handle" )}""" @JvmField val vkDebugMarkerSetObjectNameEXT = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pNameInfo} $must be a pointer to a ##VkDebugMarkerObjectNameInfoEXT structure", "{@code pNameInfo.object} $must be a Vulkan object" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pNameInfo.object} $must be externally synchronized" )}""" @JvmField val vkDebugMarkerSetObjectTagEXT = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pTagInfo} $must be a pointer to a ##VkDebugMarkerObjectTagInfoEXT structure", "{@code pTagInfo.object} $must be a Vulkan object", "{@code pTagInfo.tagName} $must not be 0" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pTagInfo.object} $must be externally synchronized" )}""" @JvmField val vkDebugReportMessageEXT = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code flags} $must be a valid combination of {@code VkDebugReportFlagBitsEXT} values", "{@code flags} $must not be 0", "{@code objectType} $must be a valid {@code VkDebugReportObjectTypeEXT} value", "{@code pLayerPrefix} $must be a pointer to a valid ", "{@code pMessage} $must be a pointer to a valid ", "{@code instance} $must be a valid {@code VkInstance} handle", "{@code flags} $must be a combination of one or more of {@code VkDebugReportFlagBitsEXT}", "{@code objType} $must be one of {@code VkDebugReportObjectTypeEXT}, #DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT if {@code object} is $NULL", "{@code object} $may be a Vulkan object", "{@code pLayerPrefix} $must be a $NULL terminated string", "{@code pMsg} $must be a $NULL terminated string" )}""" @JvmField val vkDestroyBuffer = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code buffer} is not #NULL_HANDLE, {@code buffer} $must be a valid {@code VkBuffer} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code buffer} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code buffer}, either directly or via a {@code VkBufferView}, $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code buffer} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code buffer} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code buffer} $must be externally synchronized" )}""" @JvmField val vkDestroyBufferView = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code bufferView} is not #NULL_HANDLE, {@code bufferView} $must be a valid {@code VkBufferView} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code bufferView} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code bufferView} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code bufferView} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code bufferView} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code bufferView} $must be externally synchronized" )}""" @JvmField val vkDestroyCommandPool = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code commandPool} is not #NULL_HANDLE, {@code commandPool} $must be a valid {@code VkCommandPool} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code commandPool} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All {@code VkCommandBuffer} objects allocated from {@code commandPool} $must not be pending execution", "If {@code VkAllocationCallbacks} were provided when {@code commandPool} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code commandPool} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandPool} $must be externally synchronized" )}""" @JvmField val vkDestroyDebugReportCallbackEXT = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code callback} $must be a valid {@code VkDebugReportCallbackEXT} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "{@code callback} $must have been created, allocated, or retrieved from {@code instance}", "If {@code VkAllocationCallbacks} were provided when {@code instance} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code instance} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code callback} $must be externally synchronized" )}""" @JvmField val vkDestroyDescriptorPool = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code descriptorPool} is not #NULL_HANDLE, {@code descriptorPool} $must be a valid {@code VkDescriptorPool} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code descriptorPool} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code descriptorPool} (via any allocated descriptor sets) $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code descriptorPool} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code descriptorPool} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code descriptorPool} $must be externally synchronized" )}""" @JvmField val vkDestroyDescriptorSetLayout = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code descriptorSetLayout} is not #NULL_HANDLE, {@code descriptorSetLayout} $must be a valid {@code VkDescriptorSetLayout} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code descriptorSetLayout} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", """ If {@code VkAllocationCallbacks} were provided when {@code descriptorSetLayout} was created, a compatible set of callbacks $must be provided here """, "If no {@code VkAllocationCallbacks} were provided when {@code descriptorSetLayout} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code descriptorSetLayout} $must be externally synchronized" )}""" @JvmField val vkDestroyDevice = """<h5>Valid Usage</h5> ${ul( "If {@code device} is not $NULL, {@code device} $must be a valid {@code VkDevice} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "All child objects created on {@code device} $must have been destroyed prior to destroying {@code device}", "If {@code VkAllocationCallbacks} were provided when {@code device} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code device} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code device} $must be externally synchronized" )}""" @JvmField val vkDestroyEvent = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code event} is not #NULL_HANDLE, {@code event} $must be a valid {@code VkEvent} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code event} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code event} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code event} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code event} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code event} $must be externally synchronized" )}""" @JvmField val vkDestroyFence = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code fence} is not #NULL_HANDLE, {@code fence} $must be a valid {@code VkFence} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code fence} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "{@code fence} $must not be associated with any queue command that has not yet completed execution on that queue", "If {@code VkAllocationCallbacks} were provided when {@code fence} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code fence} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code fence} $must be externally synchronized" )}""" @JvmField val vkDestroyFramebuffer = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code framebuffer} is not #NULL_HANDLE, {@code framebuffer} $must be a valid {@code VkFramebuffer} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code framebuffer} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code framebuffer} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code framebuffer} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code framebuffer} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code framebuffer} $must be externally synchronized" )}""" @JvmField val vkDestroyImage = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code image} is not #NULL_HANDLE, {@code image} $must be a valid {@code VkImage} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code image} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code image}, either directly or via a {@code VkImageView}, $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code image} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code image} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code image} $must be externally synchronized" )}""" @JvmField val vkDestroyImageView = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code imageView} is not #NULL_HANDLE, {@code imageView} $must be a valid {@code VkImageView} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code imageView} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code imageView} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code imageView} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code imageView} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code imageView} $must be externally synchronized" )}""" @JvmField val vkDestroyInstance = """<h5>Valid Usage</h5> ${ul( "If {@code instance} is not $NULL, {@code instance} $must be a valid {@code VkInstance} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "All child objects created using {@code instance} $must have been destroyed prior to destroying {@code instance}", "If {@code VkAllocationCallbacks} were provided when {@code instance} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code instance} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code instance} $must be externally synchronized" )}""" @JvmField val vkDestroyPipeline = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code pipeline} is not #NULL_HANDLE, {@code pipeline} $must be a valid {@code VkPipeline} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code pipeline} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code pipeline} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code pipeline} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code pipeline} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pipeline} $must be externally synchronized" )}""" @JvmField val vkDestroyPipelineCache = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code pipelineCache} is not #NULL_HANDLE, {@code pipelineCache} $must be a valid {@code VkPipelineCache} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code pipelineCache} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "If {@code VkAllocationCallbacks} were provided when {@code pipelineCache} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code pipelineCache} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pipelineCache} $must be externally synchronized" )}""" @JvmField val vkDestroyPipelineLayout = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code pipelineLayout} is not #NULL_HANDLE, {@code pipelineLayout} $must be a valid {@code VkPipelineLayout} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code pipelineLayout} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "If {@code VkAllocationCallbacks} were provided when {@code pipelineLayout} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code pipelineLayout} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pipelineLayout} $must be externally synchronized" )}""" @JvmField val vkDestroyQueryPool = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code queryPool} is not #NULL_HANDLE, {@code queryPool} $must be a valid {@code VkQueryPool} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code queryPool} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code queryPool} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code queryPool} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code queryPool} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code queryPool} $must be externally synchronized" )}""" @JvmField val vkDestroyRenderPass = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code renderPass} is not #NULL_HANDLE, {@code renderPass} $must be a valid {@code VkRenderPass} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code renderPass} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code renderPass} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code renderPass} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code renderPass} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code renderPass} $must be externally synchronized" )}""" @JvmField val vkDestroySampler = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code sampler} is not #NULL_HANDLE, {@code sampler} $must be a valid {@code VkSampler} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code sampler} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code sampler} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code sampler} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code sampler} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code sampler} $must be externally synchronized" )}""" @JvmField val vkDestroySemaphore = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code semaphore} is not #NULL_HANDLE, {@code semaphore} $must be a valid {@code VkSemaphore} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code semaphore} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "{@code semaphore} $must not be associated with any queue command that has not yet completed execution on that queue", "If {@code VkAllocationCallbacks} were provided when {@code semaphore} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code semaphore} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code semaphore} $must be externally synchronized" )}""" @JvmField val vkDestroyShaderModule = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code shaderModule} is not #NULL_HANDLE, {@code shaderModule} $must be a valid {@code VkShaderModule} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code shaderModule} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "If {@code VkAllocationCallbacks} were provided when {@code shaderModule} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code shaderModule} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code shaderModule} $must be externally synchronized" )}""" @JvmField val vkDestroySurfaceKHR = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "If {@code surface} is not #NULL_HANDLE, {@code surface} $must be a valid {@code VkSurfaceKHR} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code surface} is a valid handle, it $must have been created, allocated, or retrieved from {@code instance}", "All {@code VkSwapchainKHR} objects created for {@code surface} $must have been destroyed prior to destroying {@code surface}", "If {@code VkAllocationCallbacks} were provided when {@code surface} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code surface} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code surface} $must be externally synchronized" )}""" @JvmField val vkDestroySwapchainKHR = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code swapchain} is not #NULL_HANDLE, {@code swapchain} $must be a valid {@code VkSwapchainKHR} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "All uses of presentable images acquired from {@code swapchain} $must have completed execution", "If {@code VkAllocationCallbacks} were provided when {@code swapchain} was created, a compatible set of callbacks $must be provided here", "If no {@code VkAllocationCallbacks} were provided when {@code swapchain} was created, {@code pAllocator} $must be $NULL" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code swapchain} $must be externally synchronized" )}""" @JvmField val vkDeviceWaitIdle = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle" )} <h5>Host Synchronization</h5> ${ul( "Host access to all {@code VkQueue} objects created from {@code device} $must be externally synchronized" )}""" @JvmField val vkEndCommandBuffer = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code commandBuffer} $must be in the recording state", "If {@code commandBuffer} is a primary command buffer, there $must not be an active render pass instance", "All queries made active during the recording of {@code commandBuffer} $must have been made inactive" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkEnumerateDeviceExtensionProperties = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "If {@code pLayerName} is not $NULL, {@code pLayerName} $must be a null-terminated string", "{@code pPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not $NULL, {@code pProperties} $must be a pointer to an array of {@code pPropertyCount} ##VkExtensionProperties structures """, "If {@code pLayerName} is not $NULL, it $must be the name of a layer returned by #EnumerateDeviceLayerProperties()" )}""" @JvmField val vkEnumerateDeviceLayerProperties = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not $NULL, {@code pProperties} $must be a pointer to an array of {@code pPropertyCount} ##VkLayerProperties structures """ )}""" @JvmField val vkEnumerateInstanceExtensionProperties = """<h5>Valid Usage</h5> ${ul( "If {@code pLayerName} is not $NULL, {@code pLayerName} $must be a null-terminated string", "{@code pPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not $NULL, {@code pProperties} $must be a pointer to an array of {@code pPropertyCount} ##VkExtensionProperties structures """, "If {@code pLayerName} is not $NULL, it $must be the name of a layer returned by #EnumerateInstanceLayerProperties()" )}""" @JvmField val vkEnumerateInstanceLayerProperties = """<h5>Valid Usage</h5> ${ul( "{@code pPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not $NULL, {@code pProperties} $must be a pointer to an array of {@code pPropertyCount} ##VkLayerProperties structures """ )}""" @JvmField val vkEnumeratePhysicalDevices = """<h5>Valid Usage</h5> ${ul( "{@code instance} $must be a valid {@code VkInstance} handle", "{@code pPhysicalDeviceCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPhysicalDeviceCount} is not 0, and {@code pPhysicalDevices} is not $NULL, {@code pPhysicalDevices} $must be a pointer to an array of {@code pPhysicalDeviceCount} {@code VkPhysicalDevice} handles """ )}""" @JvmField val vkFlushMappedMemoryRanges = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pMemoryRanges} $must be a pointer to an array of {@code memoryRangeCount} valid ##VkMappedMemoryRange structures", "{@code memoryRangeCount} $must be greater than 0" )}""" @JvmField val vkFreeCommandBuffers = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code commandPool} $must be a valid {@code VkCommandPool} handle", "{@code commandBufferCount} $must be greater than 0", "{@code commandPool} $must have been created, allocated, or retrieved from {@code device}", "Each element of {@code pCommandBuffers} that is a valid handle $must have been created, allocated, or retrieved from {@code commandPool}", "All elements of {@code pCommandBuffers} $must not be pending execution", """ {@code pCommandBuffers} $must be a pointer to an array of {@code commandBufferCount} {@code VkCommandBuffer} handles, each element of which $must either be a valid handle or {@code NULL} """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandPool} $must be externally synchronized", "Host access to each member of {@code pCommandBuffers} $must be externally synchronized" )}""" @JvmField val vkFreeDescriptorSets = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code descriptorPool} $must be a valid {@code VkDescriptorPool} handle", "{@code descriptorSetCount} $must be greater than 0", "{@code descriptorPool} $must have been created, allocated, or retrieved from {@code device}", "Each element of {@code pDescriptorSets} that is a valid handle $must have been created, allocated, or retrieved from {@code descriptorPool}", "All submitted commands that refer to any element of {@code pDescriptorSets} $must have completed execution", """ {@code pDescriptorSets} $must be a pointer to an array of {@code descriptorSetCount} {@code VkDescriptorSet} handles, each element of which $must either be a valid handle or #NULL_HANDLE """, "Each valid handle in {@code pDescriptorSets} $must have been allocated from {@code descriptorPool}", "{@code descriptorPool} $must have been created with the #DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT flag" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code descriptorPool} $must be externally synchronized", "Host access to each member of {@code pDescriptorSets} $must be externally synchronized" )}""" @JvmField val vkFreeMemory = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "If {@code memory} is not #NULL_HANDLE, {@code memory} $must be a valid {@code VkDeviceMemory} handle", "If {@code pAllocator} is not $NULL, {@code pAllocator} $must be a pointer to a valid ##VkAllocationCallbacks structure", "If {@code memory} is a valid handle, it $must have been created, allocated, or retrieved from {@code device}", "All submitted commands that refer to {@code memory} (via images or buffers) $must have completed execution" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code memory} $must be externally synchronized" )}""" @JvmField val vkGetBufferMemoryRequirements = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code buffer} $must be a valid {@code VkBuffer} handle", "{@code pMemoryRequirements} $must be a pointer to a ##VkMemoryRequirements structure", "{@code buffer} $must have been created, allocated, or retrieved from {@code device}" )}""" @JvmField val vkGetDeviceMemoryCommitment = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code memory} $must be a valid {@code VkDeviceMemory} handle", "{@code pCommittedMemoryInBytes} $must be a pointer to a {@code VkDeviceSize} value", "{@code memory} $must have been created, allocated, or retrieved from {@code device}", "{@code memory} $must have been created with a memory type that reports #MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT" )}""" @JvmField val vkGetDeviceProcAddr = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pName} $must be a null-terminated string" )}""" @JvmField val vkGetDeviceQueue = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pQueue} $must be a pointer to a {@code VkQueue} handle", """ {@code queueFamilyIndex} $must be one of the queue family indices specified when {@code device} was created, via the ##VkDeviceQueueCreateInfo structure """, """ {@code queueIndex} $must be less than the number of queues created for the specified queue family index when {@code device} was created, via the {@code queueCount} member of the ##VkDeviceQueueCreateInfo structure """ )}""" @JvmField val vkGetDisplayModePropertiesKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code display} $must be a valid {@code VkDisplayKHR} handle", "{@code pPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not $NULL, {@code pProperties} $must be a pointer to an array of {@code pPropertyCount} ##VkDisplayModePropertiesKHR structures """ )}""" @JvmField val vkGetDisplayPlaneCapabilitiesKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code mode} $must be a valid {@code VkDisplayModeKHR} handle", "{@code pCapabilities} $must be a pointer to a ##VkDisplayPlaneCapabilitiesKHR structure" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code mode} $must be externally synchronized" )}""" @JvmField val vkGetDisplayPlaneSupportedDisplaysKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pDisplayCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pDisplayCount} is not 0, and {@code pDisplays} is not $NULL, {@code pDisplays} $must be a pointer to an array of {@code pDisplayCount} {@code VkDisplayKHR} handles """, """ {@code planeIndex} $must be less than the number of display planes supported by the device as determined by calling #GetPhysicalDeviceDisplayPlanePropertiesKHR() """ )}""" @JvmField val vkGetEventStatus = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code event} $must be a valid {@code VkEvent} handle", "{@code event} $must have been created, allocated, or retrieved from {@code device}" )}""" @JvmField val vkGetFenceStatus = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code fence} $must be a valid {@code VkFence} handle", "{@code fence} $must have been created, allocated, or retrieved from {@code device}" )}""" @JvmField val vkGetImageMemoryRequirements = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code image} $must be a valid {@code VkImage} handle", "{@code pMemoryRequirements} $must be a pointer to a ##VkMemoryRequirements structure", "{@code image} $must have been created, allocated, or retrieved from {@code device}" )}""" @JvmField val vkGetImageSparseMemoryRequirements = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code image} $must be a valid {@code VkImage} handle", "{@code pSparseMemoryRequirementCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pSparseMemoryRequirementCount} is not 0, and {@code pSparseMemoryRequirements} is not $NULL, {@code pSparseMemoryRequirements} $must be a pointer to an array of {@code pSparseMemoryRequirementCount} ##VkSparseImageMemoryRequirements structures """, "{@code image} $must have been created, allocated, or retrieved from {@code device}" )}""" @JvmField val vkGetImageSubresourceLayout = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code image} $must be a valid {@code VkImage} handle", "{@code pSubresource} $must be a pointer to a valid ##VkImageSubresource structure", "{@code pLayout} $must be a pointer to a ##VkSubresourceLayout structure", "{@code image} $must have been created, allocated, or retrieved from {@code device}", "{@code image} $must have been created with {@code tiling} equal to #IMAGE_TILING_LINEAR", "The {@code aspectMask} member of {@code pSubresource} $must only have a single bit set" )}""" @JvmField val vkGetInstanceProcAddr = """<h5>Valid Usage</h5> ${ul( "If {@code instance} is not $NULL, {@code instance} $must be a valid {@code VkInstance} handle", "{@code pName} $must be a null-terminated string" )}""" @JvmField val vkGetMemoryWin32HandleNV = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code memory} $must be a valid {@code VkDeviceMemory} handle", "{@code handleType} $must be a valid combination of {@code VkExternalMemoryHandleTypeFlagBitsNV} values", "{@code handleType} $must not be 0", "{@code pHandle} $must be a pointer to a {@code HANDLE} value", "{@code memory} $must have been created, allocated, or retrieved from {@code device}", "{@code handleType} $must be a flag specified in {@code VkExportMemoryAllocateInfoNV}::{@code handleTypes} when allocating {@code memory}" )}""" @JvmField val vkGetPhysicalDeviceDisplayPlanePropertiesKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not $NULL, {@code pProperties} $must be a pointer to an array of {@code pPropertyCount} ##VkDisplayPlanePropertiesKHR structures """ )}""" @JvmField val vkGetPhysicalDeviceDisplayPropertiesKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not $NULL, {@code pProperties} $must be a pointer to an array of {@code pPropertyCount} ##VkDisplayPropertiesKHR structures """ )}""" @JvmField val vkGetPhysicalDeviceExternalImageFormatPropertiesNV = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code format} $must be a valid {@code VkFormat} value", "{@code type} $must be a valid {@code VkImageType} value", "{@code tiling} $must be a valid {@code VkImageTiling} value", "{@code usage} $must be a valid combination of {@code VkImageUsageFlagBits} values", "{@code usage} $must not be 0", "{@code flags} $must be a valid combination of {@code VkImageCreateFlagBits} values", "{@code flags} $must not be 0", "{@code externalHandleType} $must be a valid combination of {@code VkExternalMemoryHandleTypeFlagBitsNV} values", "{@code externalHandleType} $must not be 0", "{@code pExternalImageFormatProperties} $must be a pointer to a ##VkExternalImageFormatPropertiesNV structure" )}""" @JvmField val vkGetPhysicalDeviceFeatures = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pFeatures} $must be a pointer to a ##VkPhysicalDeviceFeatures structure" )}""" @JvmField val vkGetPhysicalDeviceFormatProperties = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code format} $must be a valid {@code VkFormat} value", "{@code pFormatProperties} $must be a pointer to a ##VkFormatProperties structure" )}""" @JvmField val vkGetPhysicalDeviceImageFormatProperties = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code format} $must be a valid {@code VkFormat} value", "{@code type} $must be a valid {@code VkImageType} value", "{@code tiling} $must be a valid {@code VkImageTiling} value", "{@code usage} $must be a valid combination of {@code VkImageUsageFlagBits} values", "{@code usage} $must not be 0", "{@code flags} $must be a valid combination of {@code VkImageCreateFlagBits} values", "{@code pImageFormatProperties} $must be a pointer to a ##VkImageFormatProperties structure" )}""" @JvmField val vkGetPhysicalDeviceMemoryProperties = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pMemoryProperties} $must be a pointer to a ##VkPhysicalDeviceMemoryProperties structure" )}""" @JvmField val vkGetPhysicalDeviceMirPresentationSupportKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code connection} $must be a pointer to a {@code MirConnection} value", """ {@code queueFamilyIndex} $must be less than {@code pQueueFamilyPropertyCount} returned by #GetPhysicalDeviceQueueFamilyProperties() for the given {@code physicalDevice} """ )}""" @JvmField val vkGetPhysicalDeviceProperties = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pProperties} $must be a pointer to a ##VkPhysicalDeviceProperties structure" )}""" @JvmField val vkGetPhysicalDeviceQueueFamilyProperties = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code pQueueFamilyPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pQueueFamilyPropertyCount} is not 0, and {@code pQueueFamilyProperties} is not $NULL, {@code pQueueFamilyProperties} $must be a pointer to an array of {@code pQueueFamilyPropertyCount} ##VkQueueFamilyProperties structures """ )}""" @JvmField val vkGetPhysicalDeviceSparseImageFormatProperties = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code format} $must be a valid {@code VkFormat} value", "{@code type} $must be a valid {@code VkImageType} value", "{@code samples} $must be a valid {@code VkSampleCountFlagBits} value", "{@code usage} $must be a valid combination of {@code VkImageUsageFlagBits} values", "{@code usage} $must not be 0", "{@code tiling} $must be a valid {@code VkImageTiling} value", "{@code pPropertyCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not $NULL, {@code pProperties} $must be a pointer to an array of {@code pPropertyCount} ##VkSparseImageFormatProperties structures """, """ {@code samples} $must be a bit value that is set in ##VkImageFormatProperties{@code ::sampleCounts} returned by #GetPhysicalDeviceImageFormatProperties() with {@code format}, {@code type}, {@code tiling}, and {@code usage} equal to those in this command and {@code flags} equal to the value that is set in sname::VkImageCreateInfo::pname::flags when the image is created """ )}""" @JvmField val vkGetPhysicalDeviceSurfaceCapabilitiesKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code surface} $must be a valid {@code VkSurfaceKHR} handle", "{@code pSurfaceCapabilities} $must be a pointer to a ##VkSurfaceCapabilitiesKHR structure" )}""" @JvmField val vkGetPhysicalDeviceSurfaceFormatsKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code surface} $must be a valid {@code VkSurfaceKHR} handle", "{@code pSurfaceFormatCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pSurfaceFormatCount} is not 0, and {@code pSurfaceFormats} is not $NULL, {@code pSurfaceFormats} $must be a pointer to an array of {@code pSurfaceFormatCount} ##VkSurfaceFormatKHR structures """ )}""" @JvmField val vkGetPhysicalDeviceSurfacePresentModesKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code surface} $must be a valid {@code VkSurfaceKHR} handle", "{@code pPresentModeCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pPresentModeCount} is not 0, and {@code pPresentModes} is not $NULL, {@code pPresentModes} $must be a pointer to an array of {@code pPresentModeCount} {@code VkPresentModeKHR} values """ )}""" @JvmField val vkGetPhysicalDeviceSurfaceSupportKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code surface} $must be a valid {@code VkSurfaceKHR} handle", "{@code pSupported} $must be a pointer to a {@code VkBool32} value", """ {@code queueFamilyIndex} $must be less than {@code pQueueFamilyPropertyCount} returned by #GetPhysicalDeviceQueueFamilyProperties() for the given {@code physicalDevice} """ )}""" @JvmField val vkGetPhysicalDeviceWaylandPresentationSupportKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code display} $must be a pointer to a {@code wl_display} value", """ {@code queueFamilyIndex} $must be less than {@code pQueueFamilyPropertyCount} returned by #GetPhysicalDeviceQueueFamilyProperties() for the given {@code physicalDevice} """ )}""" @JvmField val vkGetPhysicalDeviceWin32PresentationSupportKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", """ {@code queueFamilyIndex} $must be less than {@code pQueueFamilyPropertyCount} returned by #GetPhysicalDeviceQueueFamilyProperties() for the given {@code physicalDevice} """ )}""" @JvmField val vkGetPhysicalDeviceXcbPresentationSupportKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code connection} $must be a pointer to a {@code xcb_connection_t} value", """ {@code queueFamilyIndex} $must be less than {@code pQueueFamilyPropertyCount} returned by #GetPhysicalDeviceQueueFamilyProperties() for the given {@code physicalDevice} """ )}""" @JvmField val vkGetPhysicalDeviceXlibPresentationSupportKHR = """<h5>Valid Usage</h5> ${ul( "{@code physicalDevice} $must be a valid {@code VkPhysicalDevice} handle", "{@code dpy} $must be a pointer to a {@code Display} value", """ {@code queueFamilyIndex} $must be less than {@code pQueueFamilyPropertyCount} returned by #GetPhysicalDeviceQueueFamilyProperties() for the given {@code physicalDevice} """ )}""" @JvmField val vkGetPipelineCacheData = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pipelineCache} $must be a valid {@code VkPipelineCache} handle", "{@code pDataSize} $must be a pointer to a {@code size_t} value", """ If the value referenced by {@code pDataSize} is not 0, and {@code pData} is not $NULL, {@code pData} $must be a pointer to an array of {@code pDataSize} bytes """, "{@code pipelineCache} $must have been created, allocated, or retrieved from {@code device}" )}""" @JvmField val vkGetQueryPoolResults = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code queryPool} $must be a valid {@code VkQueryPool} handle", "{@code pData} $must be a pointer to an array of {@code dataSize} bytes", "{@code flags} $must be a valid combination of {@code VkQueryResultFlagBits} values", "{@code dataSize} $must be greater than 0", "{@code queryPool} $must have been created, allocated, or retrieved from {@code device}", "{@code firstQuery} $must be less than the number of queries in {@code queryPool}", "If #QUERY_RESULT_64_BIT is not set in {@code flags} then {@code pData} and {@code stride} $must be multiples of 4", "If #QUERY_RESULT_64_BIT is set in {@code flags} then {@code pData} and {@code stride} $must be multiples of 8", "The sum of {@code firstQuery} and {@code queryCount} $must be less than or equal to the number of queries in {@code queryPool}", "{@code dataSize} $must be large enough to contain the result of each query, as described here", "If the {@code queryType} used to create {@code queryPool} was #QUERY_TYPE_TIMESTAMP, {@code flags} $must not contain #QUERY_RESULT_PARTIAL_BIT" )}""" @JvmField val vkGetRenderAreaGranularity = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code renderPass} $must be a valid {@code VkRenderPass} handle", "{@code pGranularity} $must be a pointer to a ##VkExtent2D structure", "{@code renderPass} $must have been created, allocated, or retrieved from {@code device}" )}""" @JvmField val vkGetSwapchainImagesKHR = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code swapchain} $must be a valid {@code VkSwapchainKHR} handle", "{@code pSwapchainImageCount} $must be a pointer to a {@code uint32_t} value", """ If the value referenced by {@code pSwapchainImageCount} is not 0, and {@code pSwapchainImages} is not $NULL, {@code pSwapchainImages} $must be a pointer to an array of {@code pSwapchainImageCount} {@code VkImage} handles """ )}""" @JvmField val vkInvalidateMappedMemoryRanges = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pMemoryRanges} $must be a pointer to an array of {@code memoryRangeCount} valid ##VkMappedMemoryRange structures", "{@code memoryRangeCount} $must be greater than 0" )}""" @JvmField val vkMapMemory = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code memory} $must be a valid {@code VkDeviceMemory} handle", "{@code flags} $must be 0", "{@code ppData} $must be a pointer to a pointer", "{@code memory} $must have been created, allocated, or retrieved from {@code device}", "{@code memory} $must not currently be mapped", "{@code offset} $must be less than the size of {@code memory}", "If {@code size} is not equal to #WHOLE_SIZE, {@code size} $must be greater than 0", "If {@code size} is not equal to #WHOLE_SIZE, {@code size} $must be less than or equal to the size of the {@code memory} minus {@code offset}", "{@code memory} $must have been created with a memory type that reports #MEMORY_PROPERTY_HOST_VISIBLE_BIT" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code memory} $must be externally synchronized" )}""" @JvmField val vkMergePipelineCaches = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code dstCache} $must be a valid {@code VkPipelineCache} handle", "{@code pSrcCaches} $must be a pointer to an array of {@code srcCacheCount} valid {@code VkPipelineCache} handles", "{@code srcCacheCount} $must be greater than 0", "{@code dstCache} $must have been created, allocated, or retrieved from {@code device}", "Each element of {@code pSrcCaches} $must have been created, allocated, or retrieved from {@code device}", "{@code dstCache} $must not appear in the list of source caches" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code dstCache} $must be externally synchronized" )}""" @JvmField val vkQueueBindSparse = """<h5>Valid Usage</h5> ${ul( "{@code queue} $must be a valid {@code VkQueue} handle", "If {@code bindInfoCount} is not 0, {@code pBindInfo} $must be a pointer to an array of {@code bindInfoCount} valid ##VkBindSparseInfo structures", "If {@code fence} is not #NULL_HANDLE, {@code fence} $must be a valid {@code VkFence} handle", "The {@code queue} $must support sparse binding operations", "Both of {@code fence}, and {@code queue} that are valid handles $must have been created, allocated, or retrieved from the same {@code VkDevice}", "{@code fence} $must be unsignaled", "{@code fence} $must not be associated with any other queue command that has not yet completed execution on that queue" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code queue} $must be externally synchronized", "Host access to {@code pBindInfo}[].pWaitSemaphores[] $must be externally synchronized", "Host access to {@code pBindInfo}[].pSignalSemaphores[] $must be externally synchronized", "Host access to {@code pBindInfo}[].pBufferBinds[].buffer $must be externally synchronized", "Host access to {@code pBindInfo}[].pImageOpaqueBinds[].image $must be externally synchronized", "Host access to {@code pBindInfo}[].pImageBinds[].image $must be externally synchronized", "Host access to {@code fence} $must be externally synchronized" )}""" @JvmField val vkQueuePresentKHR = """<h5>Valid Usage</h5> ${ul( "{@code queue} $must be a valid {@code VkQueue} handle", "{@code pPresentInfo} $must be a pointer to a valid ##VkPresentInfoKHR structure", """ Any given element of {@code pSwapchains} member of {@code pPresentInfo} $must be a swapchain that is created for a surface for which presentation is supported from {@code queue} as determined using a call to #GetPhysicalDeviceSurfaceSupportKHR() """, """ If more than one member of 'pSwapchains' was created from a display surface, all display surfaces referenced that refer to the same display $must use the same display mode """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code queue} $must be externally synchronized", "Host access to {@code pPresentInfo.pWaitSemaphores}[] $must be externally synchronized", "Host access to {@code pPresentInfo.pSwapchains}[] $must be externally synchronized" )}""" @JvmField val vkQueueSubmit = """<h5>Valid Usage</h5> ${ul( "{@code queue} $must be a valid {@code VkQueue} handle", "If {@code submitCount} is not 0, {@code pSubmits} $must be a pointer to an array of {@code submitCount} valid ##VkSubmitInfo structures", "If {@code fence} is not #NULL_HANDLE, {@code fence} $must be a valid {@code VkFence} handle", "Both of {@code fence}, and {@code queue} that are valid handles $must have been created, allocated, or retrieved from the same {@code VkDevice}", "If {@code fence} is not #NULL_HANDLE, {@code fence} $must be unsignaled", """ If {@code fence} is not #NULL_HANDLE, {@code fence} $must not be associated with any other queue command that has not yet completed execution on that queue """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code queue} $must be externally synchronized", "Host access to {@code pSubmits}[].pWaitSemaphores[] $must be externally synchronized", "Host access to {@code pSubmits}[].pSignalSemaphores[] $must be externally synchronized", "Host access to {@code fence} $must be externally synchronized" )}""" @JvmField val vkQueueWaitIdle = """<h5>Valid Usage</h5> ${ul( "{@code queue} $must be a valid {@code VkQueue} handle" )}""" @JvmField val vkResetCommandBuffer = """<h5>Valid Usage</h5> ${ul( "{@code commandBuffer} $must be a valid {@code VkCommandBuffer} handle", "{@code flags} $must be a valid combination of {@code VkCommandBufferResetFlagBits} values", "{@code commandBuffer} $must not currently be pending execution", "{@code commandBuffer} $must have been allocated from a pool that was created with the #COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandBuffer} $must be externally synchronized" )}""" @JvmField val vkResetCommandPool = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code commandPool} $must be a valid {@code VkCommandPool} handle", "{@code flags} $must be a valid combination of {@code VkCommandPoolResetFlagBits} values", "{@code commandPool} $must have been created, allocated, or retrieved from {@code device}", "All {@code VkCommandBuffer} objects allocated from {@code commandPool} $must not currently be pending execution" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code commandPool} $must be externally synchronized" )}""" @JvmField val vkResetDescriptorPool = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code descriptorPool} $must be a valid {@code VkDescriptorPool} handle", "{@code flags} $must be 0", "{@code descriptorPool} $must have been created, allocated, or retrieved from {@code device}", "All uses of {@code descriptorPool} (via any allocated descriptor sets) $must have completed execution" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code descriptorPool} $must be externally synchronized", "Host access to any {@code VkDescriptorSet} objects allocated from {@code descriptorPool} $must be externally synchronized" )}""" @JvmField val vkResetEvent = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code event} $must be a valid {@code VkEvent} handle", "{@code event} $must have been created, allocated, or retrieved from {@code device}", "{@code event} $must not be waited on by a #CmdWaitEvents() command that is currently executing" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code event} $must be externally synchronized" )}""" @JvmField val vkResetFences = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pFences} $must be a pointer to an array of {@code fenceCount} valid {@code VkFence} handles", "{@code fenceCount} $must be greater than 0", "Each element of {@code pFences} $must have been created, allocated, or retrieved from {@code device}", "Any given element of {@code pFences} $must not currently be associated with any queue command that has not yet completed execution on that queue" )} <h5>Host Synchronization</h5> ${ul( "Host access to each member of {@code pFences} $must be externally synchronized" )}""" @JvmField val vkSetEvent = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code event} $must be a valid {@code VkEvent} handle", "{@code event} $must have been created, allocated, or retrieved from {@code device}" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code event} $must be externally synchronized" )}""" @JvmField val vkUnmapMemory = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code memory} $must be a valid {@code VkDeviceMemory} handle", "{@code memory} $must have been created, allocated, or retrieved from {@code device}", "{@code memory} $must currently be mapped" )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code memory} $must be externally synchronized" )}""" @JvmField val vkUpdateDescriptorSets = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", """ If {@code descriptorWriteCount} is not 0, {@code pDescriptorWrites} $must be a pointer to an array of {@code descriptorWriteCount} valid ##VkWriteDescriptorSet structures """, """ If {@code descriptorCopyCount} is not 0, {@code pDescriptorCopies} $must be a pointer to an array of {@code descriptorCopyCount} valid ##VkCopyDescriptorSet structures """ )} <h5>Host Synchronization</h5> ${ul( "Host access to {@code pDescriptorWrites}[].dstSet $must be externally synchronized", "Host access to {@code pDescriptorCopies}[].dstSet $must be externally synchronized" )}""" @JvmField val vkWaitForFences = """<h5>Valid Usage</h5> ${ul( "{@code device} $must be a valid {@code VkDevice} handle", "{@code pFences} $must be a pointer to an array of {@code fenceCount} valid {@code VkFence} handles", "{@code fenceCount} $must be greater than 0", "Each element of {@code pFences} $must have been created, allocated, or retrieved from {@code device}" )}""" }
bsd-3-clause
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/ANGLE_texture_usage.kt
1
1686
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengles.templates import org.lwjgl.generator.* import org.lwjgl.opengles.* val ANGLE_texture_usage = "ANGLETextureUsage".nativeClassGLES("ANGLE_texture_usage", postfix = ANGLE) { documentation = """ Native bindings to the $registryLink extension. In some implementations it is advantageous to know the expected usage of a texture before the backing storage for it is allocated. This can help to inform the implementation's choice of format and type of memory used for the allocation. If the usage is not known in advance, the implementation essentially has to make a guess as to how it will be used. If it is later proven wrong, it may need to perform costly re-allocations and/or reformatting of the texture data, resulting in reduced performance. This extension adds a texture usage flag that is specified via the TEXTURE_USAGE_ANGLE TexParameter. This can be used to indicate that the application knows that this texture will be used for rendering. """ IntConstant( """ Accepted as a value for {@code pname} for the TexParameter{if} and TexParameter{if}v commands and for the {@code value} parameter of GetTexParameter{if}v. """, "TEXTURE_USAGE_ANGLE"..0x93A2 ) IntConstant( """ Accepted as a value to {@code param} for the TexParameter{if} and to {@code params} for the TexParameter{if}v commands with a {@code pname} of TEXTURE_USAGE_ANGLE; returned as possible values for {@code data} when GetTexParameter{if}v is queried with a {@code value} of TEXTURE_USAGE_ANGLE. """, "FRAMEBUFFER_ATTACHMENT_ANGLE"..0x93A3 ) }
bsd-3-clause
codebutler/odyssey
retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/logging/TimberLoggingHandler.kt
1
1587
package com.codebutler.retrograde.lib.logging import android.util.Log import timber.log.Timber import java.util.logging.Handler import java.util.logging.Level import java.util.logging.LogRecord class TimberLoggingHandler : Handler() { @Throws(SecurityException::class) override fun close() { } override fun flush() {} override fun publish(record: LogRecord) { val tag = loggerNameToTag(record.loggerName) val level = getAndroidLevel(record.level) Timber.tag(tag).log(level, record.message) } // https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/com/android/internal/logging/AndroidHandler.java private fun getAndroidLevel(level: Level): Int { val value = level.intValue() return when { value >= 1000 -> Log.ERROR // SEVERE value >= 900 -> Log.WARN // WARNING value >= 800 -> Log.INFO // INFO else -> Log.DEBUG } } // https://android.googlesource.com/platform/libcore/+/master/dalvik/src/main/java/dalvik/system/DalvikLogging.java private fun loggerNameToTag(loggerName: String?): String { if (loggerName == null) { return "null" } val length = loggerName.length if (length <= 23) { return loggerName } val lastPeriod = loggerName.lastIndexOf(".") return if (length - (lastPeriod + 1) <= 23) { loggerName.substring(lastPeriod + 1) } else { loggerName.substring(loggerName.length - 23) } } }
gpl-3.0
goldmansachs/obevo
obevo-db/src/main/java/com/gs/obevo/db/api/appdata/Group.kt
2
678
/** * Copyright 2017 Goldman Sachs. * 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.gs.obevo.db.api.appdata data class Group( val name: String )
apache-2.0
IRA-Team/VKPlayer
app/src/main/java/com/irateam/vkplayer/ui/viewholder/DirectoryViewHolder.kt
1
1033
/* * Copyright (C) 2016 IRA-Team * * 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.irateam.vkplayer.ui.viewholder import android.support.v7.widget.RecyclerView import android.view.View import android.widget.CheckBox import android.widget.TextView import com.irateam.vkplayer.R import com.irateam.vkplayer.util.extension.getViewById class DirectoryViewHolder : FilePickerViewHolder { val filesCount: TextView constructor(v: View) : super(v) { this.filesCount = v.getViewById(R.id.files_count) } }
apache-2.0
burntcookie90/KotlinDaggerDataBinding
app/src/main/kotlin/io/dwak/kotlindaggerdatabinding/MainActivity.kt
1
858
package io.dwak.kotlindaggerdatabinding import android.support.v7.app.AppCompatActivity import android.os.Bundle import io.dwak.kotlindaggerdatabinding.databinding.ActivityMainBinding import android.databinding.DataBindingUtil import android.util.Log import dagger.component.DaggerTestComponent import dagger.module.TestModule import javax.inject.Inject class MainActivity : AppCompatActivity() { lateinit var testInjectionString : String @Inject set override fun onCreate(savedInstanceState : Bundle?) { super.onCreate(savedInstanceState) var binding : ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.helloWorld.text = "Hello!" DaggerTestComponent.builder().testModule(TestModule()).build().inject(this) Log.d("MainActivity", testInjectionString) } }
mit
gantsign/java-application-maven-archetype
kotlin-application-maven-archetype/src/main/resources/archetype-resources/src/main/kotlin/Main.kt
1
238
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package} import mu.KotlinLogging private val log = KotlinLogging.logger {} fun main(args: Array<String>) { log.info("Hello, World!") }
mit
esofthead/mycollab
mycollab-jackrabbit/src/main/java/com/mycollab/module/ecm/NodesUtil.kt
3
1105
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.ecm import javax.jcr.Node /** * Utility class relate to jackrabbit node processing. * * @author MyCollab Ltd. * @since 1.0 */ object NodesUtil { @JvmStatic @JvmOverloads fun getString(node: Node, property: String, defaultValue: String = "") = try { node.getProperty(property).string } catch (e: Exception) { defaultValue } }
agpl-3.0
CruGlobal/android-gto-support
gto-support-recyclerview/src/main/kotlin/org/ccci/gto/android/common/recyclerview/util/RecyclerViewLifecycleObserver.kt
2
520
package org.ccci.gto.android.common.recyclerview.util import androidx.annotation.MainThread import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.RecyclerView import org.ccci.gto.android.common.androidx.recyclerview.util.lifecycleOwner @Deprecated("Since v3.11.2, use lifecycleOwner from gto-support-androidx-recyclerview instead.") @get:MainThread @set:MainThread var RecyclerView.lifecycleOwner: LifecycleOwner? get() = lifecycleOwner set(value) { lifecycleOwner = value }
mit
daniloqueiroz/nsync
src/test/kotlin/nsync/kernel/SyncServerTest.kt
1
1514
package nsync.kernel import kotlinx.coroutines.experimental.runBlocking import nsync.* import nsync.DeleteFile import nsync.FileDeleted import nsync.LocalFile import nsync.SyncFolder import nsync.synchronization.SyncServer import org.assertj.core.api.Assertions.assertThat import org.assertj.core.util.Files import org.junit.Before import org.junit.Test import java.nio.file.Paths class SyncServerTest { private val dataFolder = Files.newTemporaryFolder().toPath() private var arbiter: SyncServer? = null private var bus: SimpleBus? = null private val id = "uid" private val folder = SyncFolder(id, "file:///tmp/a", "file:///tmp/b") @Before fun setup() = runBlocking<Unit>{ bus = SimpleBus() arbiter = SyncServer(bus!!) bus!!.signals.forEach { arbiter?.handle(it) } bus!!.reset() } @Test fun fileDeletedSignal_firesDeleteFileSignal() = asyncTest { val path = Paths.get("/tmp", "/a/file") arbiter?.handle(FileDeleted(LocalFile(id, path))) val published = bus?.signals?.first() as DeleteFile assertThat(published.payload.folder).isEqualTo(folder) assertThat(published.payload.localFilePath).isEqualTo(path) } @Test fun fileDeletedSignal_deletesFromIndex() = asyncTest { val path = Paths.get("/tmp", "/a/file") val file = LocalFile(id, path) arbiter?.handle(FileDeleted(file)) assertThat(bus?.signals?.size).isEqualTo(1) } }
gpl-3.0
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/cabal/psi/EMail.kt
1
561
package org.jetbrains.cabal.psi import com.intellij.lang.ASTNode import com.intellij.extapi.psi.ASTWrapperPsiElement import org.jetbrains.cabal.psi.Checkable import org.jetbrains.cabal.psi.PropertyValue import org.jetbrains.cabal.highlight.ErrorMessage public class EMail(node: ASTNode) : ASTWrapperPsiElement(node), Checkable, PropertyValue { public override fun check(): List<ErrorMessage> { if (!getNode().getText().matches("^.+@.+\\..+$".toRegex())) return listOf(ErrorMessage(this, "invalid value", "error")) return listOf() } }
apache-2.0
inorichi/tachiyomi-extensions
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/mangamainac/MangaMainac.kt
1
6248
package eu.kanade.tachiyomi.multisrc.mangamainac import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.util.Calendar // Based On TCBScans sources // MangaManiac is a network of sites built by Animemaniac.co. abstract class MangaMainac( override val name: String, override val baseUrl: String, override val lang: String, ) : ParsedHttpSource() { override val supportsLatest = false override val client: OkHttpClient = network.cloudflareClient // popular override fun popularMangaRequest(page: Int): Request { return GET(baseUrl) } override fun popularMangaSelector() = "#page" override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select(".mangainfo_body > img").attr("src") manga.url = "" //element.select("#primary-menu .menu-item:first-child").attr("href") manga.title = element.select(".intro_content h2").text() return manga } override fun popularMangaNextPageSelector(): String? = null // latest override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException() override fun latestUpdatesSelector(): String = throw UnsupportedOperationException() override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException() override fun latestUpdatesNextPageSelector(): String? = throw UnsupportedOperationException() // search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw UnsupportedOperationException() override fun searchMangaSelector(): String = throw UnsupportedOperationException() override fun searchMangaFromElement(element: Element): SManga = throw UnsupportedOperationException() override fun searchMangaNextPageSelector(): String? = throw UnsupportedOperationException() // manga details override fun mangaDetailsParse(document: Document) = SManga.create().apply { val info = document.select(".intro_content").text() thumbnail_url = document.select(".mangainfo_body > img").attr("src") title = document.select(".intro_content h2").text() author = if ("Author" in info) substringextract(info, "Author(s):", "Released") else null artist = author genre = if ("Genre" in info) substringextract(info, "Genre(s):", "Status") else null status = parseStatus(document.select(".intro_content").text()) description = if ("Description" in info) info.substringAfter("Description:").trim() else null } private fun substringextract(text: String, start: String, end: String): String = text.substringAfter(start).substringBefore(end).trim() private fun parseStatus(element: String): Int = when { element.toLowerCase().contains("ongoing (pub") -> SManga.ONGOING element.toLowerCase().contains("completed (pub") -> SManga.COMPLETED else -> SManga.UNKNOWN } // chapters override fun chapterListSelector() = "table.chap_tab tr" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = element.select("a").text() chapter.date_upload = element.select("#time i").last()?.text()?.let { parseChapterDate(it) } ?: 0 return chapter } private fun parseChapterDate(date: String): Long { val dateWords: List<String> = date.split(" ") if (dateWords.size == 3) { val timeAgo = Integer.parseInt(dateWords[0]) val dates: Calendar = Calendar.getInstance() when { dateWords[1].contains("minute") -> { dates.add(Calendar.MINUTE, -timeAgo) } dateWords[1].contains("hour") -> { dates.add(Calendar.HOUR_OF_DAY, -timeAgo) } dateWords[1].contains("day") -> { dates.add(Calendar.DAY_OF_YEAR, -timeAgo) } dateWords[1].contains("week") -> { dates.add(Calendar.WEEK_OF_YEAR, -timeAgo) } dateWords[1].contains("month") -> { dates.add(Calendar.MONTH, -timeAgo) } dateWords[1].contains("year") -> { dates.add(Calendar.YEAR, -timeAgo) } } return dates.timeInMillis } return 0L } override fun chapterListParse(response: Response): List<SChapter> { val document = response.asJsoup() val chapterList = document.select(chapterListSelector()).map { chapterFromElement(it) } return if (hasCountdown(chapterList[0])) chapterList.subList(1, chapterList.size) else chapterList } private fun hasCountdown(chapter: SChapter): Boolean { val document = client.newCall( GET( baseUrl + chapter.url, headersBuilder().build() ) ).execute().asJsoup() return document .select("iframe[src^=https://free.timeanddate.com/countdown/]") .isNotEmpty() } // pages override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() var i = 0 document.select(".container .img_container center img").forEach { element -> val url = element.attr("src") i++ if (url.isNotEmpty()) { pages.add(Page(i, "", url)) } } return pages } override fun imageUrlParse(document: Document) = "" }
apache-2.0
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/aliexpress/dto/AliexpressSocialFooter.kt
1
2187
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.aliexpress.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import com.vk.sdk.api.base.dto.BaseLinkButtonAction import kotlin.String import kotlin.collections.List /** * @param type * @param action - Block action * @param text * @param userIds */ data class AliexpressSocialFooter( @SerializedName("type") val type: AliexpressSocialFooter.Type? = null, @SerializedName("action") val action: BaseLinkButtonAction? = null, @SerializedName("text") val text: String? = null, @SerializedName("user_ids") val userIds: List<UserId>? = null ) { enum class Type( val value: String ) { @SerializedName("aliexpress_carousel") ALIEXPRESS_CAROUSEL("aliexpress_carousel"); } }
mit
develar/mapsforge-tile-server
pixi/src/bitmapFont.kt
1
7947
package org.develar.mapsforgeTileServer.pixi import com.carrotsearch.hppc.* import org.kxml2.io.KXmlParser import org.mapsforge.core.graphics.FontFamily import org.mapsforge.core.graphics.FontStyle import org.slf4j.Logger import org.slf4j.LoggerFactory import org.xmlpull.v1.XmlPullParser import java.awt.Point import java.awt.Rectangle import java.io.* import java.util.ArrayList private val LOG: Logger = LoggerFactory.getLogger(javaClass<FontManager>()) public fun KXmlParser.get(name: String): String = getAttributeValue(null, name)!! data public class FontInfo(public val index: Int, public val size: Int, public val style: FontStyle, val chars: List<CharInfo>, private val charToIndex: CharIntMap, val fontColor: Int, val strokeWidth: Float = -1f, val strokeColor: Int = -1) { fun getCharInfoByChar(char: Char): CharInfo? { val index = getCharIndex(char) return if (index == -1) null else chars.get(index) } fun getCharIndex(char: Char) = charToIndex.getOrDefault(char, -1) fun getCharInfoByIndex(index: Int) = chars.get(index) } data public class CharInfo(public val xOffset: Int, public val yOffset: Int, public val xAdvance: Int, public val rectangle: Rectangle) { val kerning = IntIntOpenHashMap() } // fonts - ordered by font size public class FontManager(private val fonts: List<FontInfo>) { fun measureText(text: String, font: FontInfo): Point { var x = 0 var height = 0 var prevCharIndex = -1; for (char in text) { val charIndex = font.getCharIndex(char) if (charIndex == -1) { LOG.warn("missed char: " + char + " " + char.toInt()) continue } val charInfo = font.getCharInfoByIndex(charIndex) if (prevCharIndex != -1) { x += charInfo.kerning.getOrDefault(prevCharIndex, 0); } x += charInfo.xAdvance; height = Math.max(height, charInfo.rectangle.height + charInfo.yOffset) prevCharIndex = charIndex } return Point(x, height) } fun getFont(@suppress("UNUSED_PARAMETER") family: FontFamily, style: FontStyle, size: Int): FontInfo? { for (font in fonts) { if (font.size == size && font.style == style) { return font } } return null } fun getFont(@suppress("UNUSED_PARAMETER") family: FontFamily, style: FontStyle, size: Int, fontColor: Int, strokeWidth: Float = -1f, strokeColor: Int = -1): FontInfo { for (font in fonts) { if (font.size == size && font.style == style && font.fontColor == fontColor && font.strokeWidth == strokeWidth && font.strokeColor == strokeColor) { return font } } throw Exception("Unknown font " + family + " " + style + " " + size) } } public fun parseFontInfo(file: File, fontIndex: Int): FontInfo { val parser = KXmlParser() parser.setInput(FileReader(file)) var eventType = parser.getEventType() var chars: MutableList<CharInfo>? = null var charToIndex: CharIntMap? = null var idToCharInfo: IntObjectMap<CharInfo>? = null var idToCharIndex: IntIntMap? = null var fontSize: Int? = null var fontStyle: FontStyle? = null do { when (eventType) { XmlPullParser.START_TAG -> { when (parser.getName()!!) { "info" -> { fontSize = parser["size"].toInt() val bold = parser["bold"] == "1" val italic = parser["italic"] == "1" fontStyle = when { bold && italic -> FontStyle.BOLD_ITALIC bold -> FontStyle.BOLD italic -> FontStyle.ITALIC else -> FontStyle.NORMAL } } "common" -> { if (parser["pages"] != "1") { throw UnsupportedOperationException("Only one page supported") } } "chars" -> { val charCount = parser["count"].toInt() charToIndex = CharIntOpenHashMap(charCount) chars = ArrayList(charCount) idToCharInfo = IntObjectOpenHashMap(charCount) idToCharIndex = IntIntOpenHashMap(charCount) } "char" -> { val rect = Rectangle(parser["x"].toInt(), parser["y"].toInt(), parser["width"].toInt(), parser["height"].toInt()) val charInfo = CharInfo(parser["xoffset"].toInt(), parser["yoffset"].toInt(), parser["xadvance"].toInt(), rect) val char: Char val letter = parser["letter"] char = when (letter) { "space" -> ' ' "&quot;" -> '"' "&lt;" -> '<' "&gt;" -> '>' "&amp;" -> '&' else -> { assert(letter.length() == 1) letter[0] } } charToIndex!!.put(char, chars!!.size()) chars.add(charInfo) idToCharInfo!!.put(parser["id"].toInt(), charInfo) } "kerning" -> { val charInfo = idToCharInfo!![parser["second"].toInt()] if (charInfo != null) { charInfo.kerning.put(idToCharIndex!![parser["first"].toInt()], parser["amount"].toInt()) } } } } } eventType = parser.next() } while (eventType != XmlPullParser.END_DOCUMENT) val fileName = file.name val items = fileName.substring(0, fileName.lastIndexOf('.')).split('-') val strokeWidth: Float val strokeColor: Int if (items.size() > 3) { strokeWidth = items[3].toFloat() strokeColor = getColor(items[4]) } else { strokeWidth = -1f strokeColor = -1 } return FontInfo(fontIndex, fontSize!!, fontStyle!!, chars!!, charToIndex!!, getColor(items[2]), strokeWidth, strokeColor) } private fun getColor(colorString: String): Int { val red = Integer.parseInt(colorString.substring(0, 2), 16); val green = Integer.parseInt(colorString.substring(2, 4), 16); val blue = Integer.parseInt(colorString.substring(4, 6), 16); return colorToRgba(255, red, green, blue); } public fun generateFontInfo(fonts: List<FontInfo>, outFile: File, textureAtlas: TextureAtlasInfo, fontToRegionName: Map<FontInfo, String>) { val out = BufferedOutputStream(FileOutputStream(outFile)) val buffer = ByteArrayOutput() buffer.writeUnsignedVarInt(fonts.size()) for (font in fonts) { //buffer.writeUnsighedVarInt(font.size) //buffer.write(font.style.ordinal()) //buffer.writeTo(out) //buffer.reset() val chars = font.chars buffer.writeUnsignedVarInt(chars.size()) buffer.writeTo(out) buffer.reset() var prevX = 0 var prevY = 0 val region = textureAtlas.getRegion(fontToRegionName[font]!!) for (charInfo in chars) { out.write(charInfo.xOffset) out.write(charInfo.yOffset) out.write(charInfo.xAdvance) val x = region.left + charInfo.rectangle.x val y = region.top + charInfo.rectangle.y buffer.writeSignedVarInt(x - prevX) buffer.writeSignedVarInt(y - prevY) buffer.writeTo(out) buffer.reset() prevX = x prevY = y out.write(charInfo.rectangle.width) out.write(charInfo.rectangle.height) writeKerningsInfo(charInfo, buffer, out) } } out.close() } private fun writeKerningsInfo(charInfo: CharInfo, buffer: ByteArrayOutput, out: OutputStream) { buffer.writeUnsignedVarInt(charInfo.kerning.size()) buffer.writeTo(out) buffer.reset() if (charInfo.kerning.isEmpty()) { return } val sortedKernings = charInfo.kerning.keys().toArray() sortedKernings.sort() var prevCharIndex = 0 for (i in 0..sortedKernings.size() - 1) { val charIndex = sortedKernings[i] buffer.writeUnsignedVarInt(charIndex - prevCharIndex) buffer.writeTo(out) buffer.reset() out.write(charInfo.kerning.get(charIndex)) prevCharIndex = charIndex } }
mit
cliffroot/awareness
app/src/main/java/hive/com/paradiseoctopus/awareness/App.kt
1
711
package hive.com.paradiseoctopus.awareness import android.app.Application import com.facebook.FacebookSdk import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import hive.com.paradiseoctopus.awareness.login.provider.FacebookProvider /** * Created by cliffroot on 27.09.16. */ class App : Application() { val firebaseAuth : FirebaseAuth by lazy { FirebaseAuth.getInstance() } lateinit var firebaseDatabase : FirebaseDatabase override fun onCreate() { super.onCreate() FacebookSdk.sdkInitialize(applicationContext, FacebookProvider.FACEBOOK_REQUEST_CODE) firebaseDatabase = FirebaseDatabase.getInstance() } }
apache-2.0
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/person/model/Contact.kt
1
872
package de.tum.`in`.tumcampusapp.component.tumui.person.model import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml import java.io.Serializable /** * Contact information of a TUM [Employee] or a generic [Person]. * Note: This model is based on the TUMOnline web service response format for a * corresponding request. */ @Xml data class Contact( @PropertyElement(name = "zusatz_info") var additionalInfo: String = "", @PropertyElement(name = "fax") var fax: String = "", @PropertyElement(name = "www_homepage") var homepage: String = "", @PropertyElement(name = "mobiltelefon") var mobilephone: String = "", @PropertyElement(name = "telefon") var telefon: String = "" ) : Serializable { companion object { private const val serialVersionUID = 4413581972047241018L } }
gpl-3.0
DemonWav/StatCraftGradle
statcraft-bukkit/src/main/kotlin/com/demonwav/statcraft/listeners/JoinsListener.kt
1
111
package com.demonwav.statcraft.listeners import org.bukkit.event.Listener class JoinsListener : Listener { }
mit
spamdr/astroants
src/main/kotlin/cz/richter/david/astroants/shortestpath/Dijkstra.kt
1
1575
package cz.richter.david.astroants.shortestpath import cz.richter.david.astroants.model.Astroants import cz.richter.david.astroants.model.MapLocation import cz.richter.david.astroants.model.Direction import cz.richter.david.astroants.model.Sugar import es.usc.citius.hipster.algorithm.Algorithm import es.usc.citius.hipster.algorithm.Hipster import es.usc.citius.hipster.graph.GraphSearchProblem import cz.richter.david.astroants.shortestpath.ShortestPathFinder.Companion.convertCoordinatesToIndex import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Qualifier import org.springframework.stereotype.Component @Component class Dijkstra @Autowired constructor( @Qualifier("concurrentHipsterGraphCreator") private val hipsterGraphCreator: HipsterGraphCreator ) : ShortestPathFinder { override fun find(map: List<MapLocation>, astroants: Astroants, sugar: Sugar): List<Direction> { val graphSize = Math.sqrt(map.size.toDouble()).toInt() val graph = hipsterGraphCreator.constructHipsterGraph(map, graphSize) val problem = GraphSearchProblem .startingFrom(map[convertCoordinatesToIndex(astroants.x, astroants.y, graphSize)]) .`in`(graph) .extractCostFromEdges { it.first.toDouble() } .build() val dijkstra = Hipster.createDijkstra(problem).search(map[convertCoordinatesToIndex(sugar.x, sugar.y, graphSize)]) return Algorithm.recoverActionPath(dijkstra.goalNode).map { it.second } } }
mit
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/remote/auth/model/UserRegistrationRequest.kt
2
256
package org.stepik.android.remote.auth.model import com.google.gson.annotations.SerializedName import org.stepik.android.model.user.RegistrationCredentials class UserRegistrationRequest( @SerializedName("user") val user: RegistrationCredentials )
apache-2.0
dhleong/ideavim
src/com/maddyhome/idea/vim/ex/handler/QuitHandler.kt
1
1566
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.ex.handler import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.ex.CommandHandler import com.maddyhome.idea.vim.ex.CommandHandler.Flag.DONT_REOPEN import com.maddyhome.idea.vim.ex.ExCommand import com.maddyhome.idea.vim.ex.commands import com.maddyhome.idea.vim.ex.flags class QuitHandler : CommandHandler.SingleExecution() { override val names = commands("q[uit]", "clo[se]", "hid[e]") override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, DONT_REOPEN) override fun execute(editor: Editor, context: DataContext, cmd: ExCommand): Boolean { VimPlugin.getFile().closeFile(editor, context) return true } }
gpl-2.0
marius-m/racer_test
core/src/main/java/lt/markmerkk/app/mvp/InputPresenter.kt
1
175
package lt.markmerkk.app.mvp /** * Translates raw input into car movement triggers through [CarInputInteractor] */ interface InputPresenter : Presenter { fun render() }
apache-2.0
FelixKlauke/mercantor
server/src/main/kotlin/de/d3adspace/mercantor/server/rest/JerseyRestManager.kt
1
1094
package de.d3adspace.mercantor.server.rest import de.d3adspace.mercantor.core.Mercantor import de.d3adspace.mercantor.server.application.MercantorServerApplication import de.d3adspace.mercantor.server.config.MercantorServerConfig import org.glassfish.grizzly.http.server.HttpServer import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory import org.glassfish.jersey.server.ResourceConfig import java.net.URI /** * @author Felix Klauke <[email protected]> */ class JerseyRestManager(private val mercantor: Mercantor, private val config: MercantorServerConfig) : RestManager { private lateinit var httpServer: HttpServer override fun startService() { val uri = URI.create(config.restURI) val resourceConfig = ResourceConfig.forApplication(MercantorServerApplication(mercantor)) httpServer = GrizzlyHttpServerFactory.createHttpServer(uri, resourceConfig) } override fun stopService() { httpServer.shutdownNow() } override fun isServiceRunning(): Boolean = this::httpServer.isInitialized && httpServer.isStarted }
mit
da1z/intellij-community
platform/script-debugger/backend/src/debugger/EvaluateContext.kt
6
1833
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.values.Value data class EvaluateResult(val value: Value, val wasThrown: Boolean = false) /** * A context in which watch expressions may be evaluated. Typically corresponds to stack frame * of suspended process, but may also be detached from any stack frame */ interface EvaluateContext { /** * Evaluates an arbitrary `expression` in the particular context. * Previously loaded [org.jetbrains.debugger.values.ObjectValue]s can be addressed from the expression if listed in * additionalContext parameter. */ fun evaluate(expression: String, additionalContext: Map<String, Any>? = null, enableBreak: Boolean = false): Promise<EvaluateResult> /** * optional to implement, some protocols, WIP for example, require you to release remote objects */ fun withValueManager(objectGroup: String): EvaluateContext /** * If you evaluate "foo.bar = 4" and want to update Variables view (and all other clients), you can use use this task * @param promise */ fun refreshOnDone(promise: Promise<*>): Promise<*> /** * call only if withLoader was called before */ fun releaseObjects() { } }
apache-2.0
apollostack/apollo-android
apollo-runtime-common/src/commonMain/kotlin/com/apollographql/apollo3/subscription/AppSyncOperationMessageSerializer.kt
1
2572
package com.apollographql.apollo3.subscription import com.apollographql.apollo3.api.internal.json.BufferedSinkJsonWriter import com.apollographql.apollo3.api.json.JsonWriter import com.apollographql.apollo3.api.internal.json.Utils import com.apollographql.apollo3.api.json.use import com.apollographql.apollo3.api.internal.json.writeObject import com.apollographql.apollo3.subscription.ApolloOperationMessageSerializer.writePayloadContentsTo import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.use as okioUse /** * An [OperationMessageSerializer] that uses the format used by * [AWS AppSync][https://docs.aws.amazon.com/appsync/latest/devguide/real-time-websocket-client.html]. * * AppSync uses a dialect of Apollo's format so parts of the implementation is delegated to [ApolloOperationMessageSerializer]. * * @param authorization The Authorization object as per the AWS AppSync documentation. */ class AppSyncOperationMessageSerializer( private val authorization: Map<String, Any?> ) : OperationMessageSerializer { override fun writeClientMessage(message: OperationClientMessage, sink: BufferedSink) { when (message) { is OperationClientMessage.Start -> BufferedSinkJsonWriter(sink).use { message.writeTo(it) } is OperationClientMessage.Init, is OperationClientMessage.Stop, is OperationClientMessage.Terminate -> ApolloOperationMessageSerializer.writeClientMessage(message, sink) } } override fun readServerMessage(source: BufferedSource): OperationServerMessage = ApolloOperationMessageSerializer.readServerMessage(source) private fun OperationClientMessage.Start.writeTo(writer: JsonWriter) { writer.writeObject { name(ApolloOperationMessageSerializer.JSON_KEY_ID).value(subscriptionId) name(ApolloOperationMessageSerializer.JSON_KEY_TYPE).value(OperationClientMessage.Start.TYPE) name(ApolloOperationMessageSerializer.JSON_KEY_PAYLOAD).writeObject { name(JSON_KEY_DATA).value(serializePayload()) name(ApolloOperationMessageSerializer.JSON_KEY_EXTENSIONS).writeObject { name("authorization") Utils.writeToJson(authorization, writer) } } } } private fun OperationClientMessage.Start.serializePayload(): String = Buffer().okioUse { buffer -> BufferedSinkJsonWriter(buffer).use { dataWriter -> dataWriter.writeObject { writePayloadContentsTo(dataWriter) } } buffer.readUtf8() } companion object { private const val JSON_KEY_DATA = "data" } }
mit
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.kt
1
2403
package info.nightscout.androidaps.plugins.insulin import android.content.Context import android.graphics.Color import android.util.AttributeSet import com.jjoe64.graphview.GraphView import com.jjoe64.graphview.series.DataPoint import com.jjoe64.graphview.series.LineGraphSeries import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.utils.T import java.util.* import kotlin.math.floor class ActivityGraph : GraphView { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) fun show(insulin: Insulin, diaSample: Double? = null) { removeAllSeries() val dia = diaSample ?: insulin.dia mSecondScale = null val hours = floor(dia + 1).toLong() val bolus = Bolus( timestamp = 0, amount = 1.0, type = Bolus.Type.NORMAL ) val activityArray: MutableList<DataPoint> = ArrayList() val iobArray: MutableList<DataPoint> = ArrayList() var time: Long = 0 while (time <= T.hours(hours).msecs()) { val iob = insulin.iobCalcForTreatment(bolus, time, dia) activityArray.add(DataPoint(T.msecs(time).mins().toDouble(), iob.activityContrib)) iobArray.add(DataPoint(T.msecs(time).mins().toDouble(), iob.iobContrib)) time += T.mins(5).msecs() } addSeries(LineGraphSeries(Array(activityArray.size) { i -> activityArray[i] }).also { it.thickness = 8 gridLabelRenderer.verticalLabelsColor = it.color }) viewport.isXAxisBoundsManual = true viewport.setMinX(0.0) viewport.setMaxX((hours * 60).toDouble()) viewport.isYAxisBoundsManual = true viewport.setMinY(0.0) viewport.setMaxY(0.01) gridLabelRenderer.numHorizontalLabels = (hours + 1).toInt() gridLabelRenderer.horizontalAxisTitle = "[min]" secondScale.addSeries(LineGraphSeries(Array(iobArray.size) { i -> iobArray[i] }).also { it.isDrawBackground = true it.color = Color.MAGENTA it.backgroundColor = Color.argb(70, 255, 0, 255) }) secondScale.minY = 0.0 secondScale.maxY = 1.0 gridLabelRenderer.verticalLabelsSecondScaleColor = Color.MAGENTA } }
agpl-3.0
Heiner1/AndroidAPS
database/src/main/java/info/nightscout/androidaps/database/daos/VersionChangeDao.kt
1
897
package info.nightscout.androidaps.database.daos import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import info.nightscout.androidaps.database.TABLE_TEMPORARY_TARGETS import info.nightscout.androidaps.database.TABLE_VERSION_CHANGES import info.nightscout.androidaps.database.entities.TemporaryTarget import info.nightscout.androidaps.database.entities.VersionChange import io.reactivex.rxjava3.core.Single @Dao interface VersionChangeDao { @Insert fun insert(versionChange: VersionChange) @Query("SELECT * FROM $TABLE_VERSION_CHANGES ORDER BY id DESC LIMIT 1") fun getMostRecentVersionChange(): VersionChange? @Query("SELECT * FROM $TABLE_VERSION_CHANGES WHERE timestamp > :since AND timestamp <= :until LIMIT :limit OFFSET :offset") suspend fun getNewEntriesSince(since: Long, until: Long, limit: Int, offset: Int): List<VersionChange> }
agpl-3.0
Deanveloper/SlaK
src/main/kotlin/com/deanveloper/slak/event/misc/EmojiChangeEvent.kt
1
232
package com.deanveloper.slak.event.misc import com.deanveloper.slak.event.Event import java.time.LocalDateTime class EmojiChangeEvent(ts: LocalDateTime) : Event { override val type = "emoji_changed" override val ts = ts }
mit
thecoshman/bblm
src/main/kotlin/com/thecoshman/bblm/webui/WebUI.kt
1
1623
package com.thecoshman.bblm.webui import org.springframework.beans.BeansException import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.web.servlet.ViewResolver import org.thymeleaf.TemplateEngine import org.thymeleaf.spring4.SpringTemplateEngine import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver import org.thymeleaf.spring4.view.ThymeleafViewResolver import org.thymeleaf.templateresolver.ITemplateResolver open class WebUI : ApplicationContextAware { private var appContext: ApplicationContext? = null @Throws(BeansException::class) override fun setApplicationContext(applicationContext: ApplicationContext) { appContext = applicationContext } fun viewResolver(): ViewResolver { with(ThymeleafViewResolver()) { templateEngine = templateEngine() as SpringTemplateEngine? characterEncoding = "UTF-8" contentType = "text/html; charset=UTF-8" return this } } fun templateEngine(): TemplateEngine { with (SpringTemplateEngine()) { setTemplateResolver(templateResolver()) return this } } fun templateResolver(): ITemplateResolver { with(SpringResourceTemplateResolver()) { setApplicationContext(appContext) prefix = "/main/WEB-INF/templates/" suffix = ".html" // templateMode = TemplateMode.HTML // This is default vOv characterEncoding = "UTF-8" return this } } }
mit
Adventech/sabbath-school-android-2
common/design-compose/src/main/kotlin/app/ss/design/compose/widget/DragHandle.kt
1
2155
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.design.compose.widget import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import app.ss.design.compose.theme.SsColor private object DragHandleDefaults { val width = 48.dp val height = 4.dp } @Composable fun DragHandle(modifier: Modifier = Modifier) { Box( modifier = modifier .size( width = DragHandleDefaults.width, height = DragHandleDefaults.height ) .background(backgroundColor(), CircleShape) ) } @Composable private fun backgroundColor(): Color = if (isSystemInDarkTheme()) { SsColor.BaseGrey2 } else { SsColor.BaseGrey1 }
mit
ahant-pabi/field-validator
src/main/kotlin/com/github/ahant/validator/validation/util/RequiredFieldValidator.kt
1
4919
package com.github.ahant.validator.validation.util import com.github.ahant.validator.annotation.CollectionType import com.github.ahant.validator.annotation.FieldInfo import com.github.ahant.validator.constants.ApplicationConstants.COLLECTION_MIN_SIZE_ERROR import com.github.ahant.validator.constants.ApplicationConstants.REQUIRED_FIELD_MISSING import com.github.ahant.validator.util.CommonUtil.isNotBlank import com.github.ahant.validator.validation.FieldValidationType import com.google.common.collect.Sets /** * Created by ahant on 8/14/2016. */ object RequiredFieldValidator { /** * Get all the declared fields of 'type' object and invoke their respective field validators. throw exception if validator returns false. * The thrown exception must be of type Application exception with message as required field missing along with field name. */ fun validate(type: Any, validationType: FieldValidationType): Set<String> { return performFieldValidation(type, validationType) } /** * Iterates over all declared fields and performs validation using their declared validator or default validator if none has been provided. * @param type type instance for which validation needs to be performed * * * @param validationType If `FieldValidationType.FAIL_FAST`, the process terminates as soon as it encounters a failed scenario else continues validation. * * * @param requiredAnnotationPresent indicates if the given type object has 'Required' annotation at class level. If present, all of it's fields are considered as required * * unless explicitly mentioned as 'optional'. * * * @return returns a set of error messages, if any or empty. It never returns `null`. */ private fun performFieldValidation(type: Any, validationType: FieldValidationType): Set<String> { val errors = Sets.newHashSet<String>() val fields = type.javaClass.declaredFields for (field in fields) { field.isAccessible = true val info = field.getAnnotation(FieldInfo::class.java) var fieldValue: Any? try { fieldValue = field.get(type) } catch (e: IllegalAccessException) { // ignore exception and either terminate or continue based on validationType. if (FieldValidationType.CONTINUE == validationType) { continue } else { errors.add(e.message) return errors } } val fieldName = if (info != null && isNotBlank(info.name)) info.name else field.name if (info != null && !info.optional && fieldValue == null) { errors.add(getExceptionMessage(fieldName)) } /** * continue if * 1) the field has a non null value * 2) there are no errors OR validation type is {@code FieldValidationType.CONTINUE} * 3) the field a validator type declared */ if (fieldValue != null && (FieldValidationType.CONTINUE == validationType || errors.isEmpty()) && (info != null)) { val validator = info.validatorType.get() validator.setCountry(info.countryCode) var fieldError: Set<String> = Sets.newHashSet<String>() val collectionAnnotation = field.getAnnotation(CollectionType::class.java) if (collectionAnnotation == null) { fieldError = validator.validate(fieldValue) } else { val collectionData = fieldValue as Collection<*> if (collectionData.size < collectionAnnotation.minSize) { errors.add(getCollectionErrorMessage(fieldName, collectionAnnotation.minSize)) } else { val collectionFieldIterator = collectionData.iterator() while (collectionFieldIterator.hasNext()) { val collectionValue = collectionFieldIterator.next() val tempErrors = validator.validate(collectionValue as Any) fieldError.plus(tempErrors) } } } errors.addAll(fieldError) } if (FieldValidationType.FAIL_FAST == validationType && !errors.isEmpty()) { break } } return errors } private fun getExceptionMessage(fieldName: String): String { return String.format(REQUIRED_FIELD_MISSING, fieldName) } private fun getCollectionErrorMessage(fieldName: String, minSize: Int): String { return String.format(COLLECTION_MIN_SIZE_ERROR, minSize, fieldName) } }
apache-2.0
k9mail/k-9
app/core/src/main/java/com/fsck/k9/autocrypt/KoinModule.kt
2
195
package com.fsck.k9.autocrypt import org.koin.dsl.module val autocryptModule = module { single { AutocryptTransferMessageCreator(get()) } single { AutocryptDraftStateHeaderParser() } }
apache-2.0
PolymerLabs/arcs
java/arcs/core/data/Annotation.kt
1
2330
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.data /** * An Arcs annotations containing additional information on an Arcs manifest element. * An Annotation may be attached to a plan, particle, handle, type etc. */ data class Annotation(val name: String, val params: Map<String, AnnotationParam> = emptyMap()) { fun getParam(name: String): AnnotationParam { return requireNotNull(params[name]) { "Annotation '$this.name' missing '$name' parameter" } } fun getStringParam(paramName: String): String { val paramValue = getParam(paramName) require(paramValue is AnnotationParam.Str) { "Annotation param $paramName must be string, instead got $paramValue" } return paramValue.value } fun getOptionalStringParam(paramName: String): String? { return if (params.containsKey(paramName)) getStringParam(paramName) else null } companion object { fun createArcId(id: String) = Annotation("arcId", mapOf("id" to AnnotationParam.Str(id))) fun createTtl(value: String) = Annotation( "ttl", mapOf("value" to AnnotationParam.Str(value)) ) fun createCapability(name: String) = Annotation(name) /** * Returns an annotation indicating that a particle is an egress particle. * * @param egressType optional egress type for the particle */ fun createEgress(egressType: String? = null): Annotation { val params = mutableMapOf<String, AnnotationParam>() if (egressType != null) { params["type"] = AnnotationParam.Str(egressType) } return Annotation("egress", params) } /** Returns an annotation indicating the name of the policy which governs a recipe. */ fun createPolicy(policyName: String): Annotation { return Annotation("policy", mapOf("name" to AnnotationParam.Str(policyName))) } /** Annotation indicating that a particle is isolated. */ val isolated = Annotation("isolated") /** Annotation indicating that a particle has ingress. */ val ingress = Annotation("ingress") } }
bsd-3-clause
Maccimo/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/actions/ConfigureKotlinInProjectAction.kt
2
3069
// 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.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.util.PlatformUtils import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.util.ProgressIndicatorUtils.underModalProgress import org.jetbrains.kotlin.idea.util.projectStructure.allModules import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.isJvm abstract class ConfigureKotlinInProjectAction : AnAction() { abstract fun getApplicableConfigurators(project: Project): Collection<KotlinProjectConfigurator> override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val (modules, configurators) = underModalProgress(project, KotlinJvmBundle.message("lookup.project.configurators.progress.text")) { val modules = getConfigurableModules(project) if (modules.all(::isModuleConfigured)) { return@underModalProgress modules to emptyList<KotlinProjectConfigurator>() } val configurators = getApplicableConfigurators(project) modules to configurators } if (modules.all(::isModuleConfigured)) { Messages.showInfoMessage(KotlinJvmBundle.message("all.modules.with.kotlin.files.are.configured"), e.presentation.text!!) return } when { configurators.size == 1 -> configurators.first().configure(project, emptyList()) configurators.isEmpty() -> Messages.showErrorDialog( KotlinJvmBundle.message("there.aren.t.configurators.available"), e.presentation.text!! ) else -> { val configuratorsPopup = KotlinSetupEnvironmentNotificationProvider.createConfiguratorsPopup(project, configurators.toList()) configuratorsPopup.showInBestPositionFor(e.dataContext) } } } } class ConfigureKotlinJsInProjectAction : ConfigureKotlinInProjectAction() { override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter { it.targetPlatform.isJs() } override fun update(e: AnActionEvent) { val project = e.project if (!PlatformUtils.isIntelliJ() && (project == null || project.allModules().all { it.buildSystemType != BuildSystemType.JPS }) ) { e.presentation.isEnabledAndVisible = false } } } class ConfigureKotlinJavaInProjectAction : ConfigureKotlinInProjectAction() { override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter { it.targetPlatform.isJvm() } }
apache-2.0
android/testing-samples
ui/espresso/FragmentScenarioSample/app/src/sharedTest/java/com/example/android/testing/espresso/fragmentscenario/SampleFragmentTest.kt
1
1108
package com.example.android.testing.espresso.fragmentscenario import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.LooperMode /** * A test using the androidx.test unified API, which can execute on an Android device or locally using Robolectric. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class SampleFragmentTest { @Test fun launchFragmentAndVerifyUI() { // use launchInContainer to launch the fragment with UI launchFragmentInContainer<SampleFragment>() // now use espresso to look for the fragment's text view and verify it is displayed onView(withId(R.id.textView)).check(matches(withText("I am a fragment"))); } }
apache-2.0
tommykw/wear
src/main/java/com/example/LoginScreen.kt
1
555
package com.example import javafx.scene.layout.VBox import tornadofx.* class LoginScreen : View() { override val root = VBox() init { title = "Login" with (root) { addClass(LoginStyle.wrapper) hbox { label("Username") textfield() } hbox { label("Password") passwordfield() } hbox { button("Login") } children.addClass(LoginStyle.row) } } }
apache-2.0
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/NotificationsPreference.kt
2
1911
package com.fsck.k9.ui.settings.account import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.os.Build import android.provider.Settings import android.util.AttributeSet import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat.startActivity import androidx.core.content.res.TypedArrayUtils import androidx.fragment.app.DialogFragment import androidx.preference.Preference import com.takisoft.preferencex.PreferenceFragmentCompat typealias NotificationChannelIdProvider = () -> String @SuppressLint("RestrictedApi") @RequiresApi(Build.VERSION_CODES.O) class NotificationsPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = TypedArrayUtils.getAttr( context, androidx.preference.R.attr.preferenceStyle, android.R.attr.preferenceStyle ), defStyleRes: Int = 0 ) : Preference(context, attrs, defStyleAttr, defStyleRes) { var notificationChannelIdProvider: NotificationChannelIdProvider? = null override fun onClick() { notificationChannelIdProvider.let { provider -> val intent = if (provider == null) { Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) } else { val notificationChannelId = provider.invoke() Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS).apply { putExtra(Settings.EXTRA_CHANNEL_ID, notificationChannelId) } } intent.putExtra(Settings.EXTRA_APP_PACKAGE, this.context.packageName) startActivity(this.context, intent, null) } } companion object { init { PreferenceFragmentCompat.registerPreferenceFragment( NotificationsPreference::class.java, DialogFragment::class.java ) } } }
apache-2.0
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/util/rex/REXLayer.kt
1
1729
package org.hexworks.zircon.internal.util.rex import org.hexworks.zircon.api.builder.data.TileBuilder import org.hexworks.zircon.api.builder.graphics.LayerBuilder import org.hexworks.zircon.api.color.TileColor import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.graphics.Layer import org.hexworks.zircon.api.resource.TilesetResource val TRANSPARENT_BACKGROUND = TileColor.create(255, 0, 255) /** * Represents a REX Paint Layer, which contains its size information (width, height) and a [List] of [REXCell]s. */ data class REXLayer( val width: Int, val height: Int, val cells: List<REXCell> ) { /** * Returns itself as a [REXLayer]. */ fun toLayer(tileset: TilesetResource): Layer { val layer = LayerBuilder.newBuilder() .withTileset(tileset) .withSize(Size.create(width, height)) .build() for (y in 0 until height) { for (x in 0 until width) { // Have to swap x and y due to how image data is stored val cell = cells[x * height + y] if (cell.backgroundColor == TRANSPARENT_BACKGROUND) { // Skip transparent characters continue } layer.draw( tile = TileBuilder.newBuilder() .withCharacter(cell.character) .withBackgroundColor(cell.backgroundColor) .withForegroundColor(cell.foregroundColor) .build(), drawPosition = Position.create(x, y) ) } } return layer } }
apache-2.0
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VirtualFile.kt
1
289
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.api interface VirtualFile { val path: String }
mit
fcostaa/kotlin-rxjava-android
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/UrlEntity.kt
1
599
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.* @Entity( tableName = "url", indices = [Index(value = ["url_character_id"], name = "url_character_index")], foreignKeys = [ForeignKey( entity = CharacterEntity::class, parentColumns = ["id"], childColumns = ["url_character_id"] )] ) data class UrlEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "url_id") var id: Long = 0L, var url: String = "", var type: String = "", @ColumnInfo(name = "url_character_id") var characterId: Long = 0L )
mit
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/stories/StoriesIntroViewModelTest.kt
1
3127
package org.wordpress.android.ui.stories import androidx.lifecycle.Observer import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.InternalCoroutinesApi import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq import org.mockito.kotlin.reset import org.mockito.kotlin.verify import org.wordpress.android.BaseUnitTest import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.test import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.ui.stories.intro.StoriesIntroViewModel import org.wordpress.android.util.NoDelayCoroutineDispatcher import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper @InternalCoroutinesApi @ExperimentalCoroutinesApi class StoriesIntroViewModelTest : BaseUnitTest() { private lateinit var viewModel: StoriesIntroViewModel @Mock lateinit var onDialogClosedObserver: Observer<Unit> @Mock lateinit var onCreateButtonClickedObserver: Observer<Unit> @Mock lateinit var onStoryOpenRequestedObserver: Observer<String> @Mock lateinit var analyticsTrackerWrapper: AnalyticsTrackerWrapper @Mock private lateinit var appPrefsWrapper: AppPrefsWrapper @Before fun setUp() = test { viewModel = StoriesIntroViewModel( analyticsTrackerWrapper, appPrefsWrapper, NoDelayCoroutineDispatcher() ) viewModel.onDialogClosed.observeForever(onDialogClosedObserver) viewModel.onCreateButtonClicked.observeForever(onCreateButtonClickedObserver) viewModel.onStoryOpenRequested.observeForever(onStoryOpenRequestedObserver) } @Test fun `pressing back button closes the dialog`() { viewModel.onBackButtonPressed() verify(onDialogClosedObserver).onChanged(anyOrNull()) } @Test fun `pressing create button triggers appropriate event`() { viewModel.onCreateStoryButtonPressed() verify(onCreateButtonClickedObserver).onChanged(anyOrNull()) } @Test fun `tapping preview images triggers request for opening story in browser`() { viewModel.onStoryPreviewTapped1() verify(onStoryOpenRequestedObserver).onChanged(any()) reset(onStoryOpenRequestedObserver) viewModel.onStoryPreviewTapped2() verify(onStoryOpenRequestedObserver).onChanged(any()) } @Test fun `opening is tracked when view model starts`() { viewModel.start() verify(analyticsTrackerWrapper).track(eq(Stat.STORY_INTRO_SHOWN)) } @Test fun `closing is tracked when view is dismissed`() { viewModel.onBackButtonPressed() verify(analyticsTrackerWrapper).track(eq(Stat.STORY_INTRO_DISMISSED)) } @Test fun `pref is updated when user taps create story button`() { viewModel.onCreateStoryButtonPressed() verify(appPrefsWrapper).shouldShowStoriesIntro = false verify(analyticsTrackerWrapper).track(eq(Stat.STORY_INTRO_CREATE_STORY_BUTTON_TAPPED)) } }
gpl-2.0
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/jetpack/scan/builders/ScanStateListItemsBuilder.kt
1
15048
package org.wordpress.android.ui.jetpack.scan.builders import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import dagger.Reusable import org.wordpress.android.Constants import org.wordpress.android.R import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.scan.ScanStateModel import org.wordpress.android.fluxc.model.scan.ScanStateModel.ScanProgressStatus import org.wordpress.android.fluxc.model.scan.threat.ThreatModel import org.wordpress.android.fluxc.store.ScanStore import org.wordpress.android.ui.jetpack.common.JetpackListItemState import org.wordpress.android.ui.jetpack.common.JetpackListItemState.ActionButtonState import org.wordpress.android.ui.jetpack.common.JetpackListItemState.DescriptionState import org.wordpress.android.ui.jetpack.common.JetpackListItemState.DescriptionState.ClickableTextInfo import org.wordpress.android.ui.jetpack.common.JetpackListItemState.HeaderState import org.wordpress.android.ui.jetpack.common.JetpackListItemState.IconState import org.wordpress.android.ui.jetpack.common.JetpackListItemState.ProgressState import org.wordpress.android.ui.jetpack.scan.ScanListItemState.FootnoteState import org.wordpress.android.ui.jetpack.scan.ScanListItemState.ThreatsHeaderItemState import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsListItemsBuilder import org.wordpress.android.ui.reader.utils.DateProvider import org.wordpress.android.ui.utils.HtmlMessageUtils import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.ui.utils.UiString.UiStringResWithParams import org.wordpress.android.ui.utils.UiString.UiStringText import org.wordpress.android.util.text.PercentFormatter import org.wordpress.android.viewmodel.ResourceProvider import javax.inject.Inject @Reusable class ScanStateListItemsBuilder @Inject constructor( private val dateProvider: DateProvider, private val htmlMessageUtils: HtmlMessageUtils, private val resourceProvider: ResourceProvider, private val threatItemBuilder: ThreatItemBuilder, private val threatDetailsListItemsBuilder: ThreatDetailsListItemsBuilder, private val scanStore: ScanStore, private val percentFormatter: PercentFormatter ) { @Suppress("LongParameterList") suspend fun buildScanStateListItems( model: ScanStateModel, site: SiteModel, fixingThreatIds: List<Long>, onScanButtonClicked: () -> Unit, onFixAllButtonClicked: () -> Unit, onThreatItemClicked: (threatId: Long) -> Unit, onHelpClicked: () -> Unit, onEnterServerCredsIconClicked: () -> Unit ): List<JetpackListItemState> { return if (fixingThreatIds.isNotEmpty()) { buildThreatsFixingStateItems(fixingThreatIds) } else when (model.state) { ScanStateModel.State.IDLE -> { model.threats?.takeIf { threats -> threats.isNotEmpty() }?.let { threats -> buildThreatsFoundStateItems( model, threats, site, onScanButtonClicked, onFixAllButtonClicked, onThreatItemClicked, onHelpClicked, onEnterServerCredsIconClicked ) } ?: buildThreatsNotFoundStateItems(model, onScanButtonClicked) } ScanStateModel.State.SCANNING -> buildScanningStateItems(model.mostRecentStatus, model.currentStatus) ScanStateModel.State.PROVISIONING -> buildProvisioningStateItems() ScanStateModel.State.UNAVAILABLE, ScanStateModel.State.UNKNOWN -> emptyList() } } private suspend fun buildThreatsFixingStateItems(fixingThreatIds: List<Long>): List<JetpackListItemState> { val items = mutableListOf<JetpackListItemState>() val scanIcon = buildScanIcon(R.drawable.ic_shield_warning_white, R.color.error) val scanHeaderResId = if (fixingThreatIds.size > 1) { R.string.scan_fixing_threats_title_plural } else R.string.scan_fixing_threats_title_singular val scanHeader = HeaderState(UiStringRes(scanHeaderResId)) val scanDescriptionResId = if (fixingThreatIds.size > 1) { R.string.scan_fixing_threats_description_plural } else R.string.scan_fixing_threats_description_singular val scanDescription = DescriptionState(UiStringRes(scanDescriptionResId)) val scanProgress = ProgressState(isIndeterminate = true, isVisible = fixingThreatIds.isNotEmpty()) items.add(scanIcon) items.add(scanHeader) items.add(scanDescription) items.add(scanProgress) items.add(ThreatsHeaderItemState(threatsCount = fixingThreatIds.size)) items.addAll( fixingThreatIds.mapNotNull { threatId -> scanStore.getThreatModelByThreatId(threatId)?.let { threatModel -> val threatItem = threatItemBuilder.buildThreatItem(threatModel).copy( isFixing = true, subHeader = threatDetailsListItemsBuilder.buildFixableThreatDescription( requireNotNull(threatModel.baseThreatModel.fixable) ).text ) threatItem } } ) return items } @Suppress("LongParameterList") private fun buildThreatsFoundStateItems( model: ScanStateModel, threats: List<ThreatModel>, site: SiteModel, onScanButtonClicked: () -> Unit, onFixAllButtonClicked: () -> Unit, onThreatItemClicked: (threatId: Long) -> Unit, onHelpClicked: () -> Unit, onEnterServerCredsIconClicked: () -> Unit ): List<JetpackListItemState> { val items = mutableListOf<JetpackListItemState>() val scanIcon = buildScanIcon(R.drawable.ic_shield_warning_white, R.color.error) val scanHeader = HeaderState(UiStringRes(R.string.scan_idle_threats_found_title)) val scanDescription = buildThreatsFoundDescription(site, threats.size, onHelpClicked) val scanButton = buildScanButtonAction(titleRes = R.string.scan_again, onClick = onScanButtonClicked) items.add(scanIcon) items.add(scanHeader) items.add(scanDescription) val fixableThreats = threats.filter { it.baseThreatModel.fixable != null } buildFixAllButtonAction( onFixAllButtonClicked = onFixAllButtonClicked, isEnabled = model.hasValidCredentials ).takeIf { fixableThreats.isNotEmpty() }?.let { items.add(it) } if (!model.hasValidCredentials && fixableThreats.isNotEmpty()) { items.add( buildEnterServerCredsMessageState( onEnterServerCredsIconClicked, iconResId = R.drawable.ic_plus_white_24dp, iconColorResId = R.color.colorPrimary, threatsCount = threats.size, siteId = site.siteId ) ) } items.add(scanButton) threats.takeIf { it.isNotEmpty() }?.let { items.add(ThreatsHeaderItemState(threatsCount = threats.size)) items.addAll(threats.map { threat -> threatItemBuilder.buildThreatItem(threat, onThreatItemClicked) }) } return items } private fun buildThreatsNotFoundStateItems( scanStateModel: ScanStateModel, onScanButtonClicked: () -> Unit ): List<JetpackListItemState> { val items = mutableListOf<JetpackListItemState>() val scanIcon = buildScanIcon(R.drawable.ic_shield_tick_white, R.color.jetpack_green_40) val scanHeader = HeaderState(UiStringRes(R.string.scan_idle_no_threats_found_title)) val scanDescription = scanStateModel.mostRecentStatus?.startDate?.time?.let { buildLastScanDescription(it) } ?: DescriptionState(UiStringRes(R.string.scan_idle_manual_scan_description)) val scanButton = buildScanButtonAction(titleRes = R.string.scan_now, onClick = onScanButtonClicked) items.add(scanIcon) items.add(scanHeader) items.add(scanDescription) items.add(scanButton) return items } @Suppress("ForbiddenComment") private fun buildScanningStateItems( mostRecentStatus: ScanProgressStatus?, currentProgress: ScanProgressStatus? ): List<JetpackListItemState> { val items = mutableListOf<JetpackListItemState>() // TODO: ashiagr replace icon with stroke, using direct icon (color = null) causing issues with dynamic tinting val progress = currentProgress?.progress ?: 0 val scanIcon = buildScanIcon(R.drawable.ic_shield_white, R.color.jetpack_green_5) val scanTitleRes = if (progress == 0) R.string.scan_preparing_to_scan_title else R.string.scan_scanning_title val scanHeader = HeaderState(UiStringRes(scanTitleRes)) val descriptionRes = if (mostRecentStatus?.isInitial == true) { R.string.scan_scanning_is_initial_description } else { R.string.scan_scanning_description } val scanDescription = DescriptionState(UiStringRes(descriptionRes)) val scanProgress = ProgressState( progress = progress, progressLabel = UiStringText(percentFormatter.format(progress)) ) items.add(scanIcon) items.add(scanHeader) items.add(scanDescription) items.add(scanProgress) return items } private fun buildProvisioningStateItems(): List<JetpackListItemState> { val items = mutableListOf<JetpackListItemState>() val scanIcon = buildScanIcon(R.drawable.ic_shield_white, R.color.jetpack_green_5) val scanHeader = HeaderState(UiStringRes(R.string.scan_preparing_to_scan_title)) val scanDescription = DescriptionState(UiStringRes(R.string.scan_provisioning_description)) items.add(scanIcon) items.add(scanHeader) items.add(scanDescription) return items } private fun buildScanIcon(@DrawableRes icon: Int, @ColorRes color: Int?) = IconState( icon = icon, colorResId = color, sizeResId = R.dimen.scan_icon_size, marginResId = R.dimen.scan_icon_margin, contentDescription = UiStringRes(R.string.scan_state_icon) ) private fun buildScanButtonAction(@StringRes titleRes: Int, onClick: () -> Unit) = ActionButtonState( text = UiStringRes(titleRes), onClick = onClick, contentDescription = UiStringRes(titleRes), isSecondary = true ) private fun buildFixAllButtonAction( onFixAllButtonClicked: () -> Unit, isEnabled: Boolean = true ): ActionButtonState { val title = UiStringRes(R.string.threats_fix_all) return ActionButtonState( text = title, onClick = onFixAllButtonClicked, contentDescription = title, isEnabled = isEnabled ) } private fun buildLastScanDescription(timeInMs: Long): DescriptionState { val durationInMs = dateProvider.getCurrentDate().time - timeInMs val hours = durationInMs / ONE_HOUR val minutes = durationInMs / ONE_MINUTE val displayDuration = when { hours > 0 -> UiStringResWithParams(R.string.scan_in_hours_ago, listOf(UiStringText("${hours.toInt()}"))) minutes > 0 -> UiStringResWithParams( R.string.scan_in_minutes_ago, listOf(UiStringText("${minutes.toInt()}")) ) else -> UiStringRes(R.string.scan_in_few_seconds) } return DescriptionState( UiStringResWithParams( R.string.scan_idle_last_scan_description, listOf(displayDuration, UiStringRes(R.string.scan_idle_manual_scan_description)) ) ) } private fun buildThreatsFoundDescription( site: SiteModel, threatsCount: Int, onHelpClicked: () -> Unit ): DescriptionState { val clickableText = resourceProvider.getString(R.string.scan_here_to_help) val descriptionText = if (threatsCount > 1) { htmlMessageUtils .getHtmlMessageFromStringFormatResId( R.string.scan_idle_threats_description_plural, "<b>$threatsCount</b>", "<b>${site.name ?: resourceProvider.getString(R.string.scan_this_site)}</b>", clickableText ) } else { htmlMessageUtils .getHtmlMessageFromStringFormatResId( R.string.scan_idle_threats_description_singular, "<b>${site.name ?: resourceProvider.getString(R.string.scan_this_site)}</b>", clickableText ) } val clickableTextStartIndex = descriptionText.indexOf(clickableText) val clickableTextEndIndex = clickableTextStartIndex + clickableText.length val clickableTextsInfo = listOf( ClickableTextInfo( startIndex = clickableTextStartIndex, endIndex = clickableTextEndIndex, onClick = onHelpClicked ) ) return DescriptionState( text = UiStringText(descriptionText), clickableTextsInfo = clickableTextsInfo ) } private fun buildEnterServerCredsMessageState( onEnterServerCredsIconClicked: () -> Unit, @DrawableRes iconResId: Int? = null, @ColorRes iconColorResId: Int? = null, threatsCount: Int, siteId: Long ): FootnoteState { val messageResId = if (threatsCount > 1) { R.string.threat_fix_enter_server_creds_msg_plural } else { R.string.threat_fix_enter_server_creds_msg_singular } return FootnoteState( iconResId = iconResId, iconColorResId = iconColorResId, text = UiStringText( htmlMessageUtils.getHtmlMessageFromStringFormatResId( messageResId, "${Constants.URL_JETPACK_SETTINGS}/$siteId" ) ), onIconClick = onEnterServerCredsIconClicked ) } companion object { private const val ONE_MINUTE = 60 * 1000L private const val ONE_HOUR = 60 * ONE_MINUTE } }
gpl-2.0
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/engagement/EngagedPeopleListViewModelTest.kt
1
18853
package org.wordpress.android.ui.engagement import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.InternalCoroutinesApi import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers.anyLong import org.mockito.Mock import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.TEST_DISPATCHER import org.wordpress.android.test import org.wordpress.android.ui.engagement.AuthorName.AuthorNameString import org.wordpress.android.ui.engagement.EngageItem.LikedItem import org.wordpress.android.ui.engagement.EngageItem.Liker import org.wordpress.android.ui.engagement.EngageItem.NextLikesPageLoader import org.wordpress.android.ui.engagement.EngagedListNavigationEvent.OpenUserProfileBottomSheet import org.wordpress.android.ui.engagement.EngagedListNavigationEvent.PreviewCommentInReader import org.wordpress.android.ui.engagement.EngagedListNavigationEvent.PreviewPostInReader import org.wordpress.android.ui.engagement.EngagedListNavigationEvent.PreviewSiteById import org.wordpress.android.ui.engagement.EngagedListNavigationEvent.PreviewSiteByUrl import org.wordpress.android.ui.engagement.EngagedListServiceRequestEvent.RequestBlogPost import org.wordpress.android.ui.engagement.EngagedListServiceRequestEvent.RequestComment import org.wordpress.android.ui.engagement.EngagedPeopleListViewModel.EngagedPeopleListUiState import org.wordpress.android.ui.engagement.EngagementNavigationSource.LIKE_NOTIFICATION_LIST import org.wordpress.android.ui.engagement.EngagementNavigationSource.LIKE_READER_LIST import org.wordpress.android.ui.engagement.GetLikesUseCase.GetLikesState import org.wordpress.android.ui.engagement.GetLikesUseCase.GetLikesState.Failure import org.wordpress.android.ui.engagement.GetLikesUseCase.GetLikesState.LikesData import org.wordpress.android.ui.engagement.GetLikesUseCase.LikeGroupFingerPrint import org.wordpress.android.ui.engagement.ListScenarioType.LOAD_COMMENT_LIKES import org.wordpress.android.ui.engagement.ListScenarioType.LOAD_POST_LIKES import org.wordpress.android.ui.engagement.utils.GetLikesTestConfig.TEST_CONFIG_1 import org.wordpress.android.ui.engagement.utils.GetLikesTestConfig.TEST_CONFIG_2 import org.wordpress.android.ui.engagement.utils.GetLikesTestConfig.TEST_CONFIG_3 import org.wordpress.android.ui.engagement.utils.GetLikesTestConfig.TEST_CONFIG_4 import org.wordpress.android.ui.engagement.utils.GetLikesTestConfig.TEST_CONFIG_5 import org.wordpress.android.ui.engagement.utils.generatesEquivalentLikedItem import org.wordpress.android.ui.engagement.utils.getGetLikesState import org.wordpress.android.ui.engagement.utils.isEqualTo import org.wordpress.android.ui.pages.SnackbarMessageHolder import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper import org.wordpress.android.util.analytics.AnalyticsUtilsWrapper import org.wordpress.android.viewmodel.Event @InternalCoroutinesApi class EngagedPeopleListViewModelTest : BaseUnitTest() { @Mock lateinit var getLikesHandler: GetLikesHandler @Mock lateinit var readerUtilsWrapper: ReaderUtilsWrapper @Mock lateinit var analyticsUtilsWrapper: AnalyticsUtilsWrapper @Mock lateinit var listScenario: ListScenario @Mock lateinit var headerData: HeaderData private lateinit var viewModel: EngagedPeopleListViewModel private val engagementUtils = EngagementUtils() private val snackbarEvents = MutableLiveData<Event<SnackbarMessageHolder>>() private val getLikesState = MutableLiveData<GetLikesState>() private var uiState: EngagedPeopleListUiState? = null private var navigationEvent: EngagedListNavigationEvent? = null private var serviceRequestEvent: MutableList<EngagedListServiceRequestEvent> = mutableListOf() private var holder: SnackbarMessageHolder? = null private val siteId = 100L private val postId = 1000L private val commentId = 10000L private val expectedNumLikes = 6 @Before fun setup() { setupMocksForPostOrComment(LOAD_POST_LIKES) whenever(getLikesHandler.snackbarEvents).thenReturn(snackbarEvents) whenever(getLikesHandler.likesStatusUpdate).thenReturn(getLikesState) viewModel = EngagedPeopleListViewModel( TEST_DISPATCHER, TEST_DISPATCHER, getLikesHandler, readerUtilsWrapper, engagementUtils, analyticsUtilsWrapper ) setupObservers() } @Test fun `onCleared call clear on likes handler`() { viewModel.onCleared() verify(getLikesHandler, times(1)).clear() } @Test fun `data refresh is requested on start`() = test { viewModel.start(listScenario) verify(getLikesHandler, times(1)).handleGetLikesForPost( LikeGroupFingerPrint( siteId, postId, expectedNumLikes ), false ) } @Test fun `post is requested for reader when post does not exist`() { whenever(readerUtilsWrapper.postExists(siteId, postId)).thenReturn(false) viewModel.start(listScenario) assertThat(serviceRequestEvent).isNotEmpty assertThat(serviceRequestEvent).isEqualTo(listOf(RequestBlogPost(siteId, postId))) } @Test fun `comment is requested for reader when comment does not exist`() { setupMocksForPostOrComment(LOAD_COMMENT_LIKES) whenever(readerUtilsWrapper.postExists(siteId, postId)).thenReturn(true) whenever(readerUtilsWrapper.commentExists(siteId, postId, commentId)).thenReturn(false) viewModel.start(listScenario) assertThat(serviceRequestEvent).isNotEmpty assertThat(serviceRequestEvent).isEqualTo(listOf(RequestComment(siteId, postId, commentId))) } @Test fun `post and comment are requested for reader when they do not exist`() { setupMocksForPostOrComment(LOAD_COMMENT_LIKES) whenever(readerUtilsWrapper.postExists(siteId, postId)).thenReturn(false) whenever(readerUtilsWrapper.commentExists(siteId, postId, commentId)).thenReturn(false) viewModel.start(listScenario) assertThat(serviceRequestEvent).isNotEmpty assertThat(serviceRequestEvent).isEqualTo( listOf( RequestBlogPost(siteId, postId), RequestComment(siteId, postId, commentId) ) ) } @Test fun `likes are requested for post`() = test { viewModel.start(listScenario) verify(getLikesHandler, times(1)).handleGetLikesForPost( LikeGroupFingerPrint( siteId, postId, expectedNumLikes ), false ) } @Test fun `likes are requested for comment`() = test { setupMocksForPostOrComment(LOAD_COMMENT_LIKES) viewModel.start(listScenario) verify(getLikesHandler, times(1)).handleGetLikesForComment( LikeGroupFingerPrint( siteId, commentId, expectedNumLikes ), false ) } @Test fun `uiState is updated with post liked item, likers and no page loader`() = test { val likesState = getGetLikesState(TEST_CONFIG_1) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { assertThat(it.showLoading).isFalse with(it.engageItemsList) { val likedItem = this.filterIsInstance<LikedItem>() val likerItems = this.filterIsInstance<Liker>() val pageLoader = this.filterIsInstance<NextLikesPageLoader>() assertThat(likedItem.size).isEqualTo(1) assertThat(listScenario.generatesEquivalentLikedItem(likedItem.first())) assertThat((likesState as LikesData).likes.isEqualTo(likerItems)).isTrue assertThat(pageLoader).isEmpty() } } } @Test fun `uiState is updated with post liked item, likers and page loader`() = test { val likesState = getGetLikesState(TEST_CONFIG_2) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { assertThat(it.showLoading).isFalse with(it.engageItemsList) { val likedItem = this.filterIsInstance<LikedItem>() val likerItems = this.filterIsInstance<Liker>() val pageLoader = this.filterIsInstance<NextLikesPageLoader>() assertThat(likedItem.size).isEqualTo(1) assertThat(listScenario.generatesEquivalentLikedItem(likedItem.first())) assertThat((likesState as LikesData).likes.isEqualTo(likerItems)).isTrue assertThat(pageLoader.size).isEqualTo(1) } } } @Test fun `uiState is updated with comment liked item, likers and no page loader`() = test { val likesState = getGetLikesState(TEST_CONFIG_3) setupMocksForPostOrComment(LOAD_COMMENT_LIKES) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { assertThat(it.showLoading).isFalse with(it.engageItemsList) { val likedItem = this.filterIsInstance<LikedItem>() val likerItems = this.filterIsInstance<Liker>() val pageLoader = this.filterIsInstance<NextLikesPageLoader>() assertThat(likedItem.size).isEqualTo(1) assertThat(listScenario.generatesEquivalentLikedItem(likedItem.first())) assertThat((likesState as LikesData).likes.isEqualTo(likerItems)).isTrue assertThat(pageLoader).isEmpty() } } } @Test fun `uiState is updated with comment liked item, likers and page loader`() = test { val likesState = getGetLikesState(TEST_CONFIG_4) setupMocksForPostOrComment(LOAD_COMMENT_LIKES) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { assertThat(it.showLoading).isFalse with(it.engageItemsList) { val likedItem = this.filterIsInstance<LikedItem>() val likerItems = this.filterIsInstance<Liker>() val pageLoader = this.filterIsInstance<NextLikesPageLoader>() assertThat(likedItem.size).isEqualTo(1) assertThat(listScenario.generatesEquivalentLikedItem(likedItem.first())) assertThat((likesState as LikesData).likes.isEqualTo(likerItems)).isTrue assertThat(pageLoader.size).isEqualTo(1) } } } @Test fun `uiState shows empty state on failure with no values in cache`() = test { val likesState = getGetLikesState(TEST_CONFIG_5) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { assertThat(it.showLoading).isFalse with(it.engageItemsList) { val likedItem = this.filterIsInstance<LikedItem>() val likerItems = this.filterIsInstance<Liker>() val pageLoader = this.filterIsInstance<NextLikesPageLoader>() assertThat(likedItem.size).isEqualTo(1) assertThat(listScenario.generatesEquivalentLikedItem(likedItem.first())) assertThat((likesState as Failure).cachedLikes.isEqualTo(likerItems)).isTrue assertThat(pageLoader.size).isEqualTo(0) } assertThat(it.showEmptyState).isTrue } } @Test fun `when user profile holder is clicked, sheet is opened`() { val likesState = getGetLikesState(TEST_CONFIG_1) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { (it.engageItemsList[1] as Liker).onClick!!.invoke(mock(), listScenario.source) requireNotNull(navigationEvent).let { assertThat(navigationEvent is OpenUserProfileBottomSheet).isTrue } } } @Test fun `when site holder with site id is clicked, the site is previewed in reader`() { val likesState = getGetLikesState(TEST_CONFIG_1) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { val likedItem = it.engageItemsList[0] as LikedItem likedItem.onGravatarClick.invoke( likedItem.authorPreferredSiteId, likedItem.authorPreferredSiteUrl, likedItem.blogPreviewSource ) requireNotNull(navigationEvent).let { assertThat(navigationEvent is PreviewSiteById).isTrue } } } @Test fun `when site holder with zero site id is clicked, the site is previewed in webview`() { val likesState = getGetLikesState(TEST_CONFIG_1) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { val likedItem = it.engageItemsList[0] as LikedItem likedItem.onGravatarClick.invoke( 0, likedItem.authorPreferredSiteUrl, likedItem.blogPreviewSource ) requireNotNull(navigationEvent).let { assertThat(navigationEvent is PreviewSiteByUrl).isTrue } } } @Test fun `when header holder for comment is clicked, reader is opened if data is available`() { setupMocksForPostOrComment(LOAD_COMMENT_LIKES) val likesState = getGetLikesState(TEST_CONFIG_2) whenever(readerUtilsWrapper.postAndCommentExists(anyLong(), anyLong(), anyLong())).thenReturn(true) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { val likedItem = it.engageItemsList[0] as LikedItem likedItem.onHeaderClicked.invoke( likedItem.likedItemSiteId, likedItem.likedItemSiteUrl, likedItem.likedItemId, likedItem.likedItemPostId ) requireNotNull(navigationEvent).let { assertThat(navigationEvent is PreviewCommentInReader).isTrue } } } @Test fun `when header holder for comment is clicked, webview is opened if data is not available`() { setupMocksForPostOrComment(LOAD_COMMENT_LIKES) val likesState = getGetLikesState(TEST_CONFIG_2) whenever(readerUtilsWrapper.postAndCommentExists(anyLong(), anyLong(), anyLong())).thenReturn(false) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { val likedItem = it.engageItemsList[0] as LikedItem likedItem.onHeaderClicked.invoke( likedItem.likedItemSiteId, likedItem.likedItemSiteUrl, likedItem.likedItemId, likedItem.likedItemPostId ) requireNotNull(navigationEvent).let { assertThat(navigationEvent is PreviewSiteByUrl).isTrue } } } @Test fun `when header holder for post is clicked, reader is opened`() { val likesState = getGetLikesState(TEST_CONFIG_1) viewModel.start(listScenario) getLikesState.value = likesState requireNotNull(uiState).let { val likedItem = it.engageItemsList[0] as LikedItem likedItem.onHeaderClicked.invoke( likedItem.likedItemSiteId, likedItem.likedItemSiteUrl, likedItem.likedItemId, likedItem.likedItemPostId ) requireNotNull(navigationEvent).let { assertThat(navigationEvent is PreviewPostInReader).isTrue } } } private fun setupMocksForPostOrComment(type: ListScenarioType) { whenever(headerData.authorName).thenReturn(AuthorNameString("authorName")) whenever(headerData.snippetText).thenReturn("snippetText") whenever(headerData.authorAvatarUrl).thenReturn("authorAvatarUrl") whenever(headerData.numLikes).thenReturn(expectedNumLikes) whenever(headerData.authorUserId).thenReturn(100) whenever(headerData.authorPreferredSiteId).thenReturn(1000) whenever(headerData.authorPreferredSiteUrl).thenReturn("authorPreferredSiteUrl") whenever(listScenario.commentSiteUrl).thenReturn("commentSiteUrl") when (type) { LOAD_POST_LIKES -> { whenever(listScenario.type).thenReturn(LOAD_POST_LIKES) whenever(listScenario.siteId).thenReturn(siteId) whenever(listScenario.postOrCommentId).thenReturn(postId) whenever(listScenario.commentPostId).thenReturn(0L) whenever(listScenario.headerData).thenReturn(headerData) whenever(listScenario.source).thenReturn(LIKE_READER_LIST) } LOAD_COMMENT_LIKES -> { whenever(listScenario.type).thenReturn(LOAD_COMMENT_LIKES) whenever(listScenario.siteId).thenReturn(siteId) whenever(listScenario.postOrCommentId).thenReturn(commentId) whenever(listScenario.commentPostId).thenReturn(postId) whenever(listScenario.headerData).thenReturn(headerData) whenever(listScenario.source).thenReturn(LIKE_NOTIFICATION_LIST) } } } private fun setupObservers() { uiState = null navigationEvent = null serviceRequestEvent.clear() holder = null viewModel.uiState.observeForever { uiState = it } viewModel.onNavigationEvent.observeForever { it.applyIfNotHandled { navigationEvent = this } } viewModel.onServiceRequestEvent.observeForever { it.applyIfNotHandled { serviceRequestEvent.add(this) } } viewModel.onSnackbarMessage.observeForever { it.applyIfNotHandled { holder = this } } } }
gpl-2.0
MER-GROUP/intellij-community
platform/script-debugger/protocol/protocol-model-generator/src/DomainGenerator.kt
1
12076
package org.jetbrains.protocolModelGenerator import com.intellij.util.SmartList import com.intellij.util.containers.isNullOrEmpty import org.jetbrains.jsonProtocol.ItemDescriptor import org.jetbrains.jsonProtocol.ProtocolMetaModel import org.jetbrains.protocolReader.FileUpdater import org.jetbrains.protocolReader.JSON_READER_PARAMETER_DEF import org.jetbrains.protocolReader.TextOutput import org.jetbrains.protocolReader.appendEnums internal class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Domain, val fileUpdater: FileUpdater) { fun registerTypes() { domain.types?.let { for (type in it) { generator.typeMap.getTypeData(domain.domain(), type.id()).type = type } } } fun generateCommandsAndEvents() { for (command in domain.commands()) { val hasResponse = command.returns != null val returnType = if (hasResponse) generator.naming.commandResult.getShortName(command.name()) else "Unit" generateTopLevelOutputClass(generator.naming.params, command.name(), command.description, "${generator.naming.requestClassName}<$returnType>", { append('"') if (!domain.domain().isEmpty()) { append(domain.domain()).append('.') } append(command.name()).append('"') }, command.parameters) if (hasResponse) { generateJsonProtocolInterface(generator.naming.commandResult.getShortName(command.name()), command.description, command.returns, null) generator.jsonProtocolParserClassNames.add(generator.naming.commandResult.getFullName(domain.domain(), command.name()).getFullText()) generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), command.name(), generator.naming.commandResult)) } } if (domain.events != null) { for (event in domain.events!!) { generateEvenData(event) generator.jsonProtocolParserClassNames.add(generator.naming.eventData.getFullName(domain.domain(), event.name()).getFullText()) generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), event.name(), generator.naming.eventData)) } } } fun generateCommandAdditionalParam(type: ProtocolMetaModel.StandaloneType) { generateTopLevelOutputClass(generator.naming.additionalParam, type.id(), type.description, null, null, type.properties) } private fun <P : ItemDescriptor.Named> generateTopLevelOutputClass(nameScheme: ClassNameScheme, baseName: String, description: String?, baseType: String?, methodName: (TextOutput.() -> Unit)?, properties: List<P>?) { generateOutputClass(fileUpdater.out.newLine().newLine(), nameScheme.getFullName(domain.domain(), baseName), description, baseType, methodName, properties) } private fun <P : ItemDescriptor.Named> generateOutputClass(out: TextOutput, classNamePath: NamePath, description: String?, baseType: String?, methodName: (TextOutput.() -> Unit)?, properties: List<P>?) { out.doc(description) out.append(if (baseType == null) "class" else "fun").space().append(classNamePath.lastComponent).append('(') val classScope = OutputClassScope(this, classNamePath) val (mandatoryParameters, optionalParameters) = getParametersInfo(classScope, properties) if (properties.isNullOrEmpty()) { assert(baseType != null) out.append(") = ") out.append(baseType ?: "org.jetbrains.jsonProtocol.OutMessage") out.append('(') methodName?.invoke(out) out.append(')') return } else { classScope.writeMethodParameters(out, mandatoryParameters, false) classScope.writeMethodParameters(out, optionalParameters, mandatoryParameters.isNotEmpty()) out.append(')') out.append(" : ").append(baseType ?: "org.jetbrains.jsonProtocol.OutMessage") if (baseType == null) { out.append("()").openBlock().append("init") } } out.block(baseType != null) { if (baseType != null) { out.append("val m = ").append(baseType) out.append('(') methodName?.invoke(out) out.append(')') } if (!properties.isNullOrEmpty()) { val qualifier = if (baseType == null) null else "m" classScope.writeWriteCalls(out, mandatoryParameters, qualifier) classScope.writeWriteCalls(out, optionalParameters, qualifier) if (baseType != null) { out.newLine().append("return m") } } } if (baseType == null) { // close class out.closeBlock() } classScope.writeAdditionalMembers(out) } private fun <P : ItemDescriptor.Named> getParametersInfo(classScope: OutputClassScope, properties: List<P>?): Pair<List<Pair<P, BoxableType>>, List<Pair<P, BoxableType>>> { if (properties.isNullOrEmpty()) { return Pair(emptyList(), emptyList()) } val mandatoryParameters = SmartList<Pair<P, BoxableType>>() val optionalParameters = SmartList<Pair<P, BoxableType>>() if (properties != null) { for (parameter in properties) { val type = MemberScope(classScope, parameter.name()).resolveType(parameter).type if (parameter.optional) { optionalParameters.add(parameter to type) } else { mandatoryParameters.add(parameter to type) } } } return Pair(mandatoryParameters, optionalParameters) } fun createStandaloneOutputTypeBinding(type: ProtocolMetaModel.StandaloneType, name: String) = switchByType(type, MyCreateStandaloneTypeBindingVisitorBase(this, type, name)) fun createStandaloneInputTypeBinding(type: ProtocolMetaModel.StandaloneType): StandaloneTypeBinding { return switchByType(type, object : CreateStandaloneTypeBindingVisitorBase(this, type) { override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?) = createStandaloneObjectInputTypeBinding(type, properties) override fun visitEnum(enumConstants: List<String>): StandaloneTypeBinding { val name = type.id() return object : StandaloneTypeBinding { override fun getJavaType() = StandaloneType(generator.naming.inputEnum.getFullName(domain.domain(), name), "writeEnum") override fun generate() { fileUpdater.out.doc(type.description) appendEnums(enumConstants, generator.naming.inputEnum.getShortName(name), true, fileUpdater.out) } override fun getDirection() = TypeData.Direction.INPUT } } override fun visitArray(items: ProtocolMetaModel.ArrayItemType): StandaloneTypeBinding { val resolveAndGenerateScope = object : ResolveAndGenerateScope { // This class is responsible for generating ad hoc type. // If we ever are to do it, we should generate into string buffer and put strings // inside TypeDef class. override fun getDomainName() = domain.domain() override fun getTypeDirection() = TypeData.Direction.INPUT override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = throw UnsupportedOperationException() } val arrayType = ListType(generator.resolveType(items, resolveAndGenerateScope).type) return createTypedefTypeBinding(type, object : Target { override fun resolve(context: Target.ResolveContext) = arrayType }, generator.naming.inputTypedef, TypeData.Direction.INPUT) } }) } fun createStandaloneObjectInputTypeBinding(type: ProtocolMetaModel.StandaloneType, properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding { val name = type.id() val fullTypeName = generator.naming.inputValue.getFullName(domain.domain(), name) generator.jsonProtocolParserClassNames.add(fullTypeName.getFullText()) return object : StandaloneTypeBinding { override fun getJavaType() = subMessageType(fullTypeName) override fun generate() { val className = generator.naming.inputValue.getFullName(domain.domain(), name) val out = fileUpdater.out out.newLine().newLine() descriptionAndRequiredImport(type.description, out) out.append("interface ").append(className.lastComponent).openBlock() val classScope = InputClassScope(this@DomainGenerator, className) if (properties != null) { classScope.generateDeclarationBody(out, properties) } classScope.writeAdditionalMembers(out) out.closeBlock() } override fun getDirection() = TypeData.Direction.INPUT } } /** * Typedef is an empty class that just holds description and * refers to an actual type (such as String). */ fun createTypedefTypeBinding(type: ProtocolMetaModel.StandaloneType, target: Target, nameScheme: ClassNameScheme, direction: TypeData.Direction?): StandaloneTypeBinding { val name = type.id() val typedefJavaName = nameScheme.getFullName(domain.domain(), name) val actualJavaType = target.resolve(object : Target.ResolveContext { override fun generateNestedObject(shortName: String, description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType { if (direction == null) { throw RuntimeException("Unsupported") } when (direction) { TypeData.Direction.INPUT -> throw RuntimeException("TODO") TypeData.Direction.OUTPUT -> generateOutputClass(TextOutput(StringBuilder()), NamePath(shortName, typedefJavaName), description, null, null, properties) } return subMessageType(NamePath(shortName, typedefJavaName)) } }) return object : StandaloneTypeBinding { override fun getJavaType() = actualJavaType override fun generate() { } override fun getDirection() = direction } } private fun generateEvenData(event: ProtocolMetaModel.Event) { val className = generator.naming.eventData.getShortName(event.name()) val domainName = domain.domain() val fullName = generator.naming.eventData.getFullName(domainName, event.name()).getFullText() generateJsonProtocolInterface(className, event.description, event.parameters) { out -> out.newLine().append("companion object TYPE : org.jetbrains.jsonProtocol.EventType<").append(fullName) if (event.optionalData || event.parameters.isNullOrEmpty()) { out.append('?') } out.append(", ").append(generator.naming.inputPackage).append('.').append(READER_INTERFACE_NAME).append('>') out.append("(\"") if (!domainName.isNullOrEmpty()) { out.append(domainName).append('.') } out.append(event.name()).append("\")").block() { out.append("override fun read(protocolReader: ") out.append(generator.naming.inputPackage).append('.').append(READER_INTERFACE_NAME).append(", ").append(JSON_READER_PARAMETER_DEF).append(")") out.append(" = protocolReader.").append(generator.naming.eventData.getParseMethodName(domainName, event.name())).append("(reader)") } } } private fun generateJsonProtocolInterface(className: String, description: String?, parameters: List<ProtocolMetaModel.Parameter>?, additionalMembersText: ((out: TextOutput) -> Unit)?) { val out = fileUpdater.out out.newLine().newLine() descriptionAndRequiredImport(description, out) out.append("interface ").append(className).block { val classScope = InputClassScope(this, NamePath(className, NamePath(getPackageName(generator.naming.inputPackage, domain.domain())))) if (additionalMembersText != null) { classScope.addMember(additionalMembersText) } if (parameters != null) { classScope.generateDeclarationBody(out, parameters) } classScope.writeAdditionalMembers(out) } } private fun descriptionAndRequiredImport(description: String?, out: TextOutput) { if (description != null) { out.doc(description) } // out.append("@JsonType").newLine() } } fun subMessageType(namePath: NamePath) = StandaloneType(namePath, "writeMessage", null)
apache-2.0
mdaniel/intellij-community
plugins/kotlin/idea/tests/testData/gradle/commonizerImportAndCheckHighlighting/singleSupportedNativeTargetDependencyPropagation/p1/src/commonMain/kotlin/CommonMain.kt
10
82
@file:Suppress("unused") fun commonMain(args: List<String>) { println(args) }
apache-2.0
MER-GROUP/intellij-community
platform/configuration-store-impl/src/FileBasedStorage.kt
4
10542
/* * 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 com.intellij.configurationStore import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.components.impl.stores.StorageUtil import com.intellij.openapi.components.store.ReadOnlyModificationException import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.LineSeparator import org.jdom.Element import org.jdom.JDOMException import org.jdom.Parent import java.io.File import java.io.FileNotFoundException import java.io.IOException import java.nio.ByteBuffer open class FileBasedStorage(file: File, fileSpec: String, rootElementName: String, pathMacroManager: TrackingPathMacroSubstitutor? = null, roamingType: RoamingType? = null, provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) { private @Volatile var cachedVirtualFile: VirtualFile? = null private var lineSeparator: LineSeparator? = null private var blockSavingTheContent = false @Volatile var file = file private set init { if (ApplicationManager.getApplication().isUnitTestMode && file.path.startsWith('$')) { throw AssertionError("It seems like some macros were not expanded for path: $file") } } protected open val isUseXmlProlog: Boolean = false // we never set io file to null fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: File?) { cachedVirtualFile = virtualFile if (ioFileIfChanged != null) { file = ioFileIfChanged } } override fun createSaveSession(states: StateMap) = FileSaveSession(states, this) protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) { override fun save() { if (!storage.blockSavingTheContent) { super.save() } } override fun saveLocally(element: Element?) { if (storage.lineSeparator == null) { storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator() } val virtualFile = storage.getVirtualFile() if (element == null) { deleteFile(storage.file, this, virtualFile) storage.cachedVirtualFile = null } else { storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog) } } } fun getVirtualFile(): VirtualFile? { var result = cachedVirtualFile if (result == null) { result = LocalFileSystem.getInstance().findFileByIoFile(file) cachedVirtualFile = result } return cachedVirtualFile } override fun loadLocalData(): Element? { blockSavingTheContent = false try { val file = getVirtualFile() if (file == null || file.isDirectory || !file.isValid) { LOG.debug { "Document was not loaded for $fileSpec file is ${if (file == null) "null" else "directory"}" } } else if (file.length == 0L) { processReadException(null) } else { val charBuffer = CharsetToolkit.UTF8_CHARSET.decode(ByteBuffer.wrap(file.contentsToByteArray())) lineSeparator = detectLineSeparators(charBuffer, if (isUseXmlProlog) null else LineSeparator.LF) return JDOMUtil.loadDocument(charBuffer).detachRootElement() } } catch (e: JDOMException) { processReadException(e) } catch (e: IOException) { processReadException(e) } return null } private fun processReadException(e: Exception?) { val contentTruncated = e == null blockSavingTheContent = !contentTruncated && (isProjectOrModuleFile(fileSpec) || fileSpec == StoragePathMacros.WORKSPACE_FILE) if (!ApplicationManager.getApplication().isUnitTestMode && !ApplicationManager.getApplication().isHeadlessEnvironment) { if (e != null) { LOG.info(e) } Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", "Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.getMessage()}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}", NotificationType.WARNING).notify(null) } } override fun toString() = file.systemIndependentPath } fun writeFile(file: File?, requestor: Any, virtualFile: VirtualFile?, element: Element, lineSeparator: LineSeparator, prependXmlProlog: Boolean): VirtualFile { val result = if (file != null && (virtualFile == null || !virtualFile.isValid)) { StorageUtil.getOrCreateVirtualFile(requestor, file) } else { virtualFile!! } if (LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) { val content = element.toBufferExposingByteArray(lineSeparator.separatorString) if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) { throw IllegalStateException("Content equals, but it must be handled not on this level: ${result.name}") } else if (StorageUtil.DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) { StorageUtil.DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}\n---------" } } doWrite(requestor, result, element, lineSeparator, prependXmlProlog) return result } private val XML_PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".toByteArray() private fun isEqualContent(result: VirtualFile, lineSeparator: LineSeparator, content: BufferExposingByteArrayOutputStream, prependXmlProlog: Boolean): Boolean { val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size() + lineSeparator.separatorBytes.size() if (result.length.toInt() != (headerLength + content.size())) { return false } val oldContent = result.contentsToByteArray() if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) || !ArrayUtil.startsWith(oldContent, XML_PROLOG.size(), lineSeparator.separatorBytes))) { return false } for (i in headerLength..oldContent.size() - 1) { if (oldContent[i] != content.internalBuffer[i - headerLength]) { return false } } return true } private fun doWrite(requestor: Any, file: VirtualFile, content: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) { LOG.debug { "Save ${file.presentableUrl}" } val token = WriteAction.start() try { val out = file.getOutputStream(requestor) try { if (prependXmlProlog) { out.write(XML_PROLOG) out.write(lineSeparator.separatorBytes) } if (content is Element) { JDOMUtil.writeParent(content, out, lineSeparator.separatorString) } else { (content as BufferExposingByteArrayOutputStream).writeTo(out) } } finally { out.close() } } catch (e: FileNotFoundException) { // may be element is not long-lived, so, we must write it to byte array val byteArray = if (content is Element) content.toBufferExposingByteArray(lineSeparator.separatorString) else (content as BufferExposingByteArrayOutputStream) throw ReadOnlyModificationException(file, e, object : StateStorage.SaveSession { override fun save() { doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog) } }) } finally { token.finish() } } fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream { val out = BufferExposingByteArrayOutputStream(512) JDOMUtil.writeParent(this, out, lineSeparator) return out } public fun isProjectOrModuleFile(fileSpec: String): Boolean = StoragePathMacros.PROJECT_FILE == fileSpec || fileSpec.startsWith(StoragePathMacros.PROJECT_CONFIG_DIR) || fileSpec == StoragePathMacros.MODULE_FILE fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator?): LineSeparator { for (c in chars) { if (c == '\r') { return LineSeparator.CRLF } else if (c == '\n') { // if we are here, there was no \r before return LineSeparator.LF } } return defaultSeparator ?: LineSeparator.getSystemLineSeparator() } private fun deleteFile(file: File, requestor: Any, virtualFile: VirtualFile?) { if (virtualFile == null) { LOG.warn("Cannot find virtual file ${file.absolutePath}") } if (virtualFile == null) { if (file.exists()) { FileUtil.delete(file) } } else if (virtualFile.exists()) { try { deleteFile(requestor, virtualFile) } catch (e: FileNotFoundException) { throw ReadOnlyModificationException(virtualFile, e, object : StateStorage.SaveSession { override fun save() { deleteFile(requestor, virtualFile) } }) } } } fun deleteFile(requestor: Any, virtualFile: VirtualFile) { runWriteAction { virtualFile.delete(requestor) } }
apache-2.0
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/explicitThis/differentReceiverInstanceExtension2.kt
9
161
// WITH_STDLIB // PROBLEM: none open class Foo class SubFoo : Foo() val Foo.bar: String get() = "" fun Foo.func() = Foo().apply { <caret>[email protected] }
apache-2.0
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertFunctionToProperty/noExplicitType.kt
13
21
fun foo<caret>() = ""
apache-2.0
hermantai/samples
kotlin/developer-android/sunflower-main/app/src/main/java/com/google/samples/apps/sunflower/HomeViewPagerFragment.kt
1
2572
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.google.android.material.tabs.TabLayoutMediator import com.google.samples.apps.sunflower.adapters.MY_GARDEN_PAGE_INDEX import com.google.samples.apps.sunflower.adapters.PLANT_LIST_PAGE_INDEX import com.google.samples.apps.sunflower.adapters.SunflowerPagerAdapter import com.google.samples.apps.sunflower.databinding.FragmentViewPagerBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class HomeViewPagerFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentViewPagerBinding.inflate(inflater, container, false) val tabLayout = binding.tabs val viewPager = binding.viewPager viewPager.adapter = SunflowerPagerAdapter(this) // Set the icon and text for each tab TabLayoutMediator(tabLayout, viewPager) { tab, position -> tab.setIcon(getTabIcon(position)) tab.text = getTabTitle(position) }.attach() (activity as AppCompatActivity).setSupportActionBar(binding.toolbar) return binding.root } private fun getTabIcon(position: Int): Int { return when (position) { MY_GARDEN_PAGE_INDEX -> R.drawable.garden_tab_selector PLANT_LIST_PAGE_INDEX -> R.drawable.plant_list_tab_selector else -> throw IndexOutOfBoundsException() } } private fun getTabTitle(position: Int): String? { return when (position) { MY_GARDEN_PAGE_INDEX -> getString(R.string.my_garden_title) PLANT_LIST_PAGE_INDEX -> getString(R.string.plant_list_title) else -> null } } }
apache-2.0
siarhei-luskanau/android-iot-doorbell
ui/ui_image_details/src/androidTest/kotlin/siarhei/luskanau/iot/doorbell/ui/imagedetails/ImageDetailsFragmentTest.kt
1
4275
package siarhei.luskanau.iot.doorbell.ui.imagedetails import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import androidx.fragment.app.testing.launchFragmentInContainer import androidx.lifecycle.Lifecycle import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.test.espresso.Espresso import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.ViewMatchers import androidx.viewpager2.adapter.FragmentStateAdapter import com.karumi.shot.ScreenshotTest import io.mockk.every import io.mockk.mockk import kotlin.test.Test import siarhei.luskanau.iot.doorbell.ui.common.R as CommonR class ImageDetailsFragmentTest : ScreenshotTest { companion object { const val EXPECTED_ERROR_MESSAGE = "Test Exception" } private fun createNormalFragmentFactory() = object : FragmentFactory() { override fun instantiate(classLoader: ClassLoader, className: String): Fragment = ImageDetailsFragment { fragment: Fragment -> mockk(relaxed = true, relaxUnitFun = true) { every { getImageDetailsStateData() } returns MutableLiveData<ImageDetailsState>().apply { value = NormalImageDetailsState( adapter = object : FragmentStateAdapter(fragment) { override fun getItemCount(): Int = 1 override fun createFragment(position: Int): Fragment = Fragment(R.layout.layout_image_details_slide_normal) } ) } } } } private fun createErrorFragmentFactory() = object : FragmentFactory() { override fun instantiate(classLoader: ClassLoader, className: String): Fragment = ImageDetailsFragment { object : ImageDetailsPresenter { override fun getImageDetailsStateData(): LiveData<ImageDetailsState> = MutableLiveData<ImageDetailsState>().apply { value = ErrorImageDetailsState( error = RuntimeException(EXPECTED_ERROR_MESSAGE) ) } } } } @Test fun testNormalState() { val fragmentFactory = createNormalFragmentFactory() val scenario = launchFragmentInContainer<ImageDetailsFragment>( factory = fragmentFactory, themeResId = CommonR.style.AppTheme ) scenario.moveToState(Lifecycle.State.RESUMED) // normal view is displayed Espresso.onView(ViewMatchers.withId(R.id.viewPager2)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) // error view does not exist Espresso.onView(ViewMatchers.withId(CommonR.id.error_message)) .check(ViewAssertions.doesNotExist()) scenario.onFragment { compareScreenshot( fragment = it, name = javaClass.simpleName + ".normal" ) } } @Test fun testErrorState() { val fragmentFactory = createErrorFragmentFactory() val scenario = launchFragmentInContainer<ImageDetailsFragment>( factory = fragmentFactory, themeResId = CommonR.style.AppTheme ) scenario.moveToState(Lifecycle.State.RESUMED) // error view is displayed Espresso.onView(ViewMatchers.withId(CommonR.id.error_message)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withText(EXPECTED_ERROR_MESSAGE)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) // normal view does not exist Espresso.onView(ViewMatchers.withId(R.id.viewPager2)) .check(ViewAssertions.doesNotExist()) scenario.onFragment { compareScreenshot( fragment = it, name = javaClass.simpleName + ".empty" ) } } }
mit
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/plugins/groovy/wizard/MavenGroovyNewProjectBuilder.kt
2
4811
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.maven.plugins.groovy.wizard import com.intellij.ide.util.EditorHelper import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.GitSilentFileAdderProvider import com.intellij.openapi.application.ModalityState import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.DumbAwareRunnable import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import org.jetbrains.idea.maven.model.MavenConstants import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenUtil import org.jetbrains.idea.maven.wizards.AbstractMavenModuleBuilder import org.jetbrains.idea.maven.wizards.MavenStructureWizardStep import org.jetbrains.idea.maven.wizards.MavenWizardBundle import org.jetbrains.idea.maven.wizards.SelectPropertiesStep import org.jetbrains.plugins.groovy.config.GroovyConfigUtils import org.jetbrains.plugins.groovy.config.wizard.createSampleGroovyCodeFile import java.util.* import kotlin.io.path.Path import kotlin.io.path.createDirectories /** * Currently used only for new project wizard, thus the functionality is rather limited */ class MavenGroovyNewProjectBuilder(private val groovySdkVersion: String) : AbstractMavenModuleBuilder() { var createSampleCode = false override fun createWizardSteps(wizardContext: WizardContext, modulesProvider: ModulesProvider): Array<ModuleWizardStep> = arrayOf( MavenStructureWizardStep(this, wizardContext), SelectPropertiesStep(wizardContext.project, this), ) override fun setupRootModel(rootModel: ModifiableRootModel) { val project = rootModel.project val contentPath = contentEntryPath ?: return val path = FileUtil.toSystemIndependentName(contentPath).also { Path(it).createDirectories() } val root = LocalFileSystem.getInstance().refreshAndFindFileByPath(path) ?: return rootModel.addContentEntry(root) if (myJdk != null) { rootModel.sdk = myJdk } else { rootModel.inheritSdk() } MavenUtil.runWhenInitialized(project, DumbAwareRunnable { setupMavenStructure (project, root) }) } private fun setupMavenStructure(project: Project, root: VirtualFile) { val vcsFileAdder = GitSilentFileAdderProvider.create(project) try { root.refresh(true, false) { val pom = WriteCommandAction.writeCommandAction(project) .withName(MavenWizardBundle.message("maven.new.project.wizard.groovy.creating.groovy.project")) .compute<VirtualFile, RuntimeException> { root.refresh(true, false) root.findChild(MavenConstants.POM_XML)?.delete(this) val file = root.createChildData(this, MavenConstants.POM_XML) vcsFileAdder.markFileForAdding(file) val properties = Properties() val conditions = Properties() properties.setProperty("GROOVY_VERSION", groovySdkVersion) properties.setProperty("GROOVY_REPOSITORY", GroovyConfigUtils.getMavenSdkRepository(groovySdkVersion)) conditions.setProperty("NEED_POM", (GroovyConfigUtils.compareSdkVersions(groovySdkVersion, GroovyConfigUtils.GROOVY2_5) >= 0).toString()) conditions.setProperty("CREATE_SAMPLE_CODE", "true") MavenUtil.runOrApplyMavenProjectFileTemplate(project, file, projectId, null, null, properties, conditions, MAVEN_GROOVY_XML_TEMPLATE, false) file } val sourceDirectory = VfsUtil.createDirectories(root.path + "/src/main/groovy") VfsUtil.createDirectories(root.path + "/src/main/resources") VfsUtil.createDirectories(root.path + "/src/test/groovy") if (createSampleCode) { vcsFileAdder.markFileForAdding(sourceDirectory) createSampleGroovyCodeFile(project, sourceDirectory) } MavenProjectsManager.getInstance(project).forceUpdateAllProjectsOrFindAllAvailablePomFiles() MavenUtil.invokeLater(project, ModalityState.NON_MODAL) { PsiManager.getInstance(project).findFile(pom)?.let(EditorHelper::openInEditor) } } } finally { vcsFileAdder.finish() } } } private const val MAVEN_GROOVY_XML_TEMPLATE = "Maven Groovy.xml"
apache-2.0
GunoH/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/items/AttachComponentsFocusUtil.kt
2
1135
package com.intellij.xdebugger.impl.ui.attach.dialog.items import com.intellij.ui.table.JBTable import com.intellij.util.application import java.awt.event.FocusEvent import java.awt.event.FocusListener internal fun JBTable.installSelectionOnFocus() { addFocusListener(object : FocusListener { override fun focusGained(e: FocusEvent) { if (e.cause != FocusEvent.Cause.TRAVERSAL && e.cause != FocusEvent.Cause.TRAVERSAL_BACKWARD && e.cause != FocusEvent.Cause.TRAVERSAL_FORWARD && e.cause != FocusEvent.Cause.TRAVERSAL_DOWN && e.cause != FocusEvent.Cause.TRAVERSAL_UP ) { return } focusFirst() application.invokeLater { updateUI() } } override fun focusLost(e: FocusEvent) { if (e.cause != FocusEvent.Cause.TRAVERSAL && e.cause != FocusEvent.Cause.TRAVERSAL_BACKWARD && e.cause != FocusEvent.Cause.TRAVERSAL_FORWARD && e.cause != FocusEvent.Cause.TRAVERSAL_DOWN && e.cause != FocusEvent.Cause.TRAVERSAL_UP ) { return } application.invokeLater { updateUI() } } }) }
apache-2.0
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/graphics/gles/GlWindowSurface.kt
1
1627
package com.haishinkit.graphics.gles import android.opengl.EGL14 import android.opengl.EGLConfig import android.opengl.EGLExt import android.opengl.GLES20 import android.util.Log import android.view.Surface import java.nio.ByteBuffer internal class GlWindowSurface { var config: EGLConfig? = null var display = EGL14.EGL_NO_DISPLAY var context = EGL14.EGL_NO_CONTEXT private var surface = EGL14.EGL_NO_SURFACE fun setSurface(surface: Surface?) { if (surface == null) { EGL14.eglDestroySurface(display, this.surface) this.surface = EGL14.EGL_NO_SURFACE } else { this.surface = EGL14.eglCreateWindowSurface(display, config, surface, SURFACE_ATTRIBUTES, 0) } makeCurrent() } fun swapBuffers(): Boolean { return EGL14.eglSwapBuffers(display, surface) } fun setPresentationTime(timestamp: Long): Boolean { return EGLExt.eglPresentationTimeANDROID(display, surface, timestamp) } fun readPixels(width: Int, height: Int, buffer: ByteBuffer) { buffer.clear() GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer) buffer.rewind() } private fun makeCurrent(): Boolean { if (!EGL14.eglMakeCurrent(display, surface, surface, context)) { Log.e(TAG, "eglMakeCurrent failed.") return false } return true } companion object { private val TAG = GlWindowSurface::class.java.simpleName private val SURFACE_ATTRIBUTES = intArrayOf(EGL14.EGL_NONE) } }
bsd-3-clause
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/moveMultiModule/moveSealedCheckTargetPackageHasNoMembersCrossModuleBig/before/B/src/sealed/HelloGitEmptyDir.kt
48
42
package sealed interface HelloGitEmptyDir
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/compiler/KotlinCompilableFileTypesProvider.kt
4
543
// 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.compiler import com.intellij.openapi.compiler.CompilableFileTypesProvider import com.intellij.openapi.fileTypes.FileType import org.jetbrains.kotlin.idea.KotlinFileType class KotlinCompilableFileTypesProvider : CompilableFileTypesProvider { override fun getCompilableFileTypes(): MutableSet<FileType> = mutableSetOf(KotlinFileType.INSTANCE) }
apache-2.0
GunoH/intellij-community
plugins/editorconfig/src/org/editorconfig/language/codeinsight/findusages/EditorConfigFindVariableUsagesHandler.kt
2
3218
// 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 org.editorconfig.language.codeinsight.findusages import com.intellij.find.findUsages.FindUsagesHandler import com.intellij.find.findUsages.FindUsagesOptions import com.intellij.openapi.application.runReadAction import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.PsiReference import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.util.PsiTreeUtil import com.intellij.usageView.UsageInfo import com.intellij.util.Processor import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement import org.editorconfig.language.schema.descriptors.impl.EditorConfigDeclarationDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigReferenceDescriptor import org.editorconfig.language.util.EditorConfigTextMatchingUtil.textMatchesToIgnoreCase import org.editorconfig.language.util.EditorConfigVfsUtil class EditorConfigFindVariableUsagesHandler(element: EditorConfigDescribableElement) : FindUsagesHandler(element) { override fun processElementUsages(element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions) = runReadAction { getId(element)?.let { id -> findAllUsages(element, id) } ?.map(::UsageInfo) ?.all(processor::process) == true } override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope) = runReadAction { if (searchScope !is LocalSearchScope) return@runReadAction emptyList<PsiReference>() val id = getId(target) ?: return@runReadAction emptyList<PsiReference>() searchScope.scope.asSequence() .flatMap { PsiTreeUtil.findChildrenOfType(it, EditorConfigDescribableElement::class.java).asSequence() } .filter { matches(it, id, target) } .mapNotNull(EditorConfigDescribableElement::getReference) .toList() } private fun findAllUsages(element: PsiElement, id: String) = EditorConfigVfsUtil.getEditorConfigFiles(element.project) .asSequence() .map(PsiManager.getInstance(element.project)::findFile) .flatMap { PsiTreeUtil.findChildrenOfType(it, EditorConfigDescribableElement::class.java).asSequence() } .filter { matches(it, id, element) } private fun matches(element: PsiElement, id: String, template: PsiElement): Boolean { if (element !is EditorConfigDescribableElement) return false if (!textMatchesToIgnoreCase(element, template)) return false return when (val descriptor = element.getDescriptor(false)) { is EditorConfigDeclarationDescriptor -> descriptor.id == id is EditorConfigReferenceDescriptor -> descriptor.id == id else -> false } } companion object { fun getId(element: PsiElement): String? { if (element !is EditorConfigDescribableElement) return null return when (val descriptor = element.getDescriptor(false)) { is EditorConfigDeclarationDescriptor -> descriptor.id is EditorConfigReferenceDescriptor -> descriptor.id else -> null } } } }
apache-2.0
jk1/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/migLayout/patched/SwingComponentWrapper.kt
3
8944
/* * License (BSD): * ============== * * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (miglayout (at) miginfocom (dot) com) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * Neither the name of the MiG InfoCom AB nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * @version 1.0 * @author Mikael Grev, MiG InfoCom AB * Date: 2006-sep-08 */ package com.intellij.ui.layout.migLayout.patched import com.intellij.ide.ui.laf.VisualPaddingsProvider import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.util.ThreeState import net.miginfocom.layout.ComponentWrapper import net.miginfocom.layout.ContainerWrapper import net.miginfocom.layout.LayoutUtil import net.miginfocom.layout.PlatformDefaults import java.awt.* import javax.swing.JComponent import javax.swing.JEditorPane import javax.swing.JTextArea import javax.swing.SwingUtilities import javax.swing.border.LineBorder import javax.swing.border.TitledBorder /** Debug color for component bounds outline. */ private val DB_COMP_OUTLINE = Color(0, 0, 200) internal open class SwingComponentWrapper(private val c: JComponent) : ComponentWrapper { private var hasBaseLine = ThreeState.UNSURE private var isPrefCalled = false private var visualPaddings: IntArray? = null override fun getBaseline(width: Int, height: Int): Int { var h = height val visualPaddings = visualPadding if (h < 0) { h = c.height } else if (visualPaddings != null) { h = height + visualPaddings[0] + visualPaddings[2] } var baseLine = c.getBaseline(if (width < 0) c.width else width, h) if (baseLine != -1 && visualPaddings != null) { baseLine -= visualPaddings[0] } return baseLine } override fun getComponent() = c override fun getPixelUnitFactor(isHor: Boolean): Float { throw RuntimeException("Do not use LPX/LPY") } override fun getX() = c.x override fun getY() = c.y override fun getHeight() = c.height override fun getWidth() = c.width override fun getScreenLocationX(): Int { val p = Point() SwingUtilities.convertPointToScreen(p, c) return p.x } override fun getScreenLocationY(): Int { val p = Point() SwingUtilities.convertPointToScreen(p, c) return p.y } override fun getMinimumHeight(sz: Int): Int { if (!isPrefCalled) { c.preferredSize // To defeat a bug where the minimum size is different before and after the first call to getPreferredSize(); isPrefCalled = true } return c.minimumSize.height } override fun getMinimumWidth(sz: Int): Int { if (!isPrefCalled) { c.preferredSize // To defeat a bug where the minimum size is different before and after the first call to getPreferredSize(); isPrefCalled = true } return c.minimumSize.width } override fun getPreferredHeight(sz: Int): Int { // If the component has not gotten size yet and there is a size hint, trick Swing to return a better height. if (c.width == 0 && c.height == 0 && sz != -1) { c.setBounds(c.x, c.y, sz, 1) } return c.preferredSize.height } override fun getPreferredWidth(sz: Int): Int { // If the component has not gotten size yet and there is a size hint, trick Swing to return a better height. if (c.width == 0 && c.height == 0 && sz != -1) { c.setBounds(c.x, c.y, 1, sz) } return c.preferredSize.width } override fun getMaximumHeight(sz: Int) = if (c.isMaximumSizeSet) c.maximumSize.height else Integer.MAX_VALUE override fun getMaximumWidth(sz: Int) = if (c.isMaximumSizeSet) c.maximumSize.width else Integer.MAX_VALUE override fun getParent(): ContainerWrapper? { val p = c.parent ?: return null return SwingContainerWrapper(p as JComponent) } override fun getHorizontalScreenDPI(): Int { try { return c.toolkit.screenResolution } catch (ex: HeadlessException) { return PlatformDefaults.getDefaultDPI() } } override fun getVerticalScreenDPI(): Int { try { return c.toolkit.screenResolution } catch (ex: HeadlessException) { return PlatformDefaults.getDefaultDPI() } } override fun getScreenWidth(): Int { try { return c.toolkit.screenSize.width } catch (ignore: HeadlessException) { return 1024 } } override fun getScreenHeight(): Int { try { return c.toolkit.screenSize.height } catch (ignore: HeadlessException) { return 768 } } override fun hasBaseline(): Boolean { if (hasBaseLine == ThreeState.UNSURE) { try { // do not use component dimensions since it made some components layout themselves to the minimum size // and that stuck after that. E.g. JLabel with HTML content and white spaces would be very tall. // Use large number but don't risk overflow or exposing size bugs with Integer.MAX_VALUE hasBaseLine = ThreeState.fromBoolean(getBaseline(8192, 8192) > -1) } catch (ignore: Throwable) { hasBaseLine = ThreeState.NO } } return hasBaseLine.toBoolean() } override fun getLinkId(): String? = c.name override fun setBounds(x: Int, y: Int, width: Int, height: Int) { c.setBounds(x, y, width, height) } override fun isVisible() = c.isVisible override fun getVisualPadding(): IntArray? { visualPaddings?.let { return it } val component = when (c) { is ComponentWithBrowseButton<*> -> c.childComponent else -> c } val border = component.border ?: return null if (border is LineBorder || border is TitledBorder) { return null } val paddings = when (border) { is VisualPaddingsProvider -> border.getVisualPaddings(c) else -> border.getBorderInsets(component) } ?: return null if (paddings.top == 0 && paddings.left == 0 && paddings.bottom == 0 && paddings.right == 0) { return null } visualPaddings = intArrayOf(paddings.top, paddings.left, paddings.bottom, paddings.right) return visualPaddings } override fun paintDebugOutline(showVisualPadding: Boolean) { if (!c.isShowing) { return } val g = c.graphics as? Graphics2D ?: return g.paint = DB_COMP_OUTLINE g.stroke = BasicStroke(1f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10f, floatArrayOf(2f, 4f), 0f) g.drawRect(0, 0, width - 1, height - 1) if (showVisualPadding) { val padding = visualPadding if (padding != null) { g.color = Color.GREEN g.drawRect(padding[1], padding[0], width - 1 - (padding[1] + padding[3]), height - 1 - (padding[0] + padding[2])) } } } override fun getComponentType(disregardScrollPane: Boolean): Int { throw RuntimeException("Should be not called and used") } override fun getLayoutHashCode(): Int { var d = c.maximumSize var hash = d.width + (d.height shl 5) d = c.preferredSize hash += (d.width shl 10) + (d.height shl 15) d = c.minimumSize hash += (d.width shl 20) + (d.height shl 25) if (c.isVisible) hash += 1324511 linkId?.let { hash += it.hashCode() } return hash } override fun hashCode() = component.hashCode() override fun equals(other: Any?) = other is ComponentWrapper && c == other.component override fun getContentBias(): Int { return when { c is JTextArea || c is JEditorPane || java.lang.Boolean.TRUE == c.getClientProperty("migLayout.dynamicAspectRatio") -> LayoutUtil.HORIZONTAL else -> -1 } } }
apache-2.0
luks91/prparadise
app/src/main/java/com/github/luks91/teambucket/connection/BitbucketApi.kt
2
4551
/** * Copyright (c) 2017-present, Team Bucket Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package com.github.luks91.teambucket.connection import com.github.luks91.teambucket.model.* import io.reactivex.Emitter import io.reactivex.Observable import io.reactivex.functions.BiConsumer import io.reactivex.subjects.BehaviorSubject import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Path import retrofit2.http.Query import java.util.concurrent.Callable interface BitbucketApi { @GET("/rest/api/1.0/projects/{projectName}/repos/{slug}/pull-requests") fun getPullRequests( @Header("Authorization") token: String, @Path("projectName") projectName: String, @Path("slug") slug: String, @Query("start") start: Int, @Query("limit") limit: Int = BitbucketApi.PAGE_SIZE, @PullRequestStatus @Query("state") status: String = STATUS_OPEN, @Query("avatarSize") avatarSize: Int = 92, @Order @Query("order") order: String = NEWEST ): Observable<PagedResponse<PullRequest>> @GET("/rest/api/1.0/projects/{projectName}/repos/{slug}/pull-requests/{id}/activities") fun getPullRequestActivities( @Header("Authorization") token: String, @Path("projectName") projectName: String, @Path("slug") slug: String, @Path("id") pullRequestId: Long, @Query("start") start: Int, @Query("limit") limit: Int = BitbucketApi.PAGE_SIZE ): Observable<PagedResponse<PullRequestActivity>> @GET("/rest/api/1.0/projects/{projectName}/repos/{slug}/participants") fun getRepositoryParticipants( @Header("Authorization") token: String, @Path("projectName") projectName: String, @Path("slug") slug: String, @Query("start") start: Int, @Query("limit") limit: Int = BitbucketApi.PAGE_SIZE ): Observable<PagedResponse<User>> @GET("/rest/api/1.0/projects/{projectName}/repos") fun getProjectRepositories( @Header("Authorization") token: String, @Path("projectName") projectName: String, @Query("start") start: Int, @Query("limit") limit: Int = BitbucketApi.PAGE_SIZE ): Observable<PagedResponse<Repository>> @GET("/rest/api/1.0/projects/") fun getProjects( @Header("Authorization") token: String, @Query("start") start: Int, @Query("limit") limit: Int = BitbucketApi.PAGE_SIZE ): Observable<PagedResponse<Project>> @GET("/rest/api/1.0/users/{userName}") fun getUser( @Header("Authorization") token: String, @Path("userName") userName: String ): Observable<User> companion object Utility { const val PAGE_SIZE = 50 fun <TData> queryPaged(generator: (start: Int) -> Observable<PagedResponse<TData>>): Observable<List<TData>> { return Observable.generate<List<TData>, BehaviorSubject<Int>>( Callable<BehaviorSubject<Int>> { BehaviorSubject.createDefault(0) }, BiConsumer<BehaviorSubject<Int>, Emitter<List<TData>>> { pageSubject, emitter -> pageSubject.take(1) .concatMap { start -> generator.invoke(start) } .blockingSubscribe({ data -> if (data.isLastPage) { if (!data.values.isEmpty()) { emitter.onNext(data.values) } emitter.onComplete() } else { emitter.onNext(data.values) pageSubject.onNext(data.nextPageStart) } }, { error -> emitter.onError(error) }) }) } } }
apache-2.0
jimandreas/BottomNavigationView-plus-LeakCanary
app/src/main/java/com/jimandreas/android/designlibdemo/SettingsFragment.kt
2
2430
package com.jimandreas.android.designlibdemo import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.preference.PreferenceManager import android.support.v7.app.AppCompatDelegate import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceFragmentCompat import timber.log.Timber class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { Timber.v("onSharedPrefChanged: key is %s", key) } internal interface RestartCallback { fun doRestart() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Load the preferences from an XML resource addPreferencesFromResource(R.xml.pref_sandbox) // Preferences.sync(getPreferenceManager()); // gist from: https://gist.github.com/yujikosuga/1234287 var pref = findPreference("fmi_key") pref.onPreferenceClickListener = Preference.OnPreferenceClickListener { preference -> val key = preference.key val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse( "https://github.com/jimandreas/BottomNavigationView-plus-LeakCanary/blob/master/README.md") startActivity(intent) true } pref = findPreference("nightmode") pref.onPreferenceClickListener = Preference.OnPreferenceClickListener { preference -> val key = preference.key val nightModeSetting = PreferenceManager .getDefaultSharedPreferences(activity) .getBoolean("nightmode", false) Timber.v("click listener: turn night mode: %s", if (nightModeSetting) "on" else "off") AppCompatDelegate .setDefaultNightMode(if (nightModeSetting) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO) (activity as RestartCallback).doRestart() true } } override fun onCreatePreferences(bundle: Bundle?, s: String?) {} override fun onPreferenceTreeClick(preference: Preference?): Boolean { val key = preference?.key return super.onPreferenceTreeClick(preference) } }
apache-2.0
jk1/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/utils/StatisticsUtil.kt
3
5256
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.internal.statistic.utils import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerMain import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.util.containers.ObjectIntHashMap import gnu.trove.THashSet import java.util.* fun isDevelopedByJetBrains(pluginId: PluginId?): Boolean { val plugin = PluginManager.getPlugin(pluginId) return plugin == null || plugin.isBundled || PluginManagerMain.isDevelopedByJetBrains(plugin.vendor) } /** * Constructs a proper UsageDescriptor for a boolean value, * by adding "enabled" or "disabled" suffix to the given key, depending on the value. */ fun getBooleanUsage(key: String, value: Boolean): UsageDescriptor { return UsageDescriptor(key + if (value) ".enabled" else ".disabled", 1) } fun getEnumUsage(key: String, value: Enum<*>?): UsageDescriptor { return UsageDescriptor(key + "." + value?.name?.toLowerCase(Locale.ENGLISH), 1) } /** * Constructs a proper UsageDescriptor for a counting value. * If one needs to know a number of some items in the project, there is no direct way to report usages per-project. * Therefore this workaround: create several keys representing interesting ranges, and report that key which correspond to the range * which the given value belongs to. * * For example, to report a number of commits in Git repository, you can call this method like that: * ``` * val usageDescriptor = getCountingUsage("git.commit.count", listOf(0, 1, 100, 10000, 100000), realCommitCount) * ``` * and if there are e.g. 50000 commits in the repository, one usage of the following key will be reported: `git.commit.count.10K+`. * * NB: * (1) the list of steps must be sorted ascendingly; If it is not, the result is undefined. * (2) the value should lay somewhere inside steps ranges. If it is below the first step, the following usage will be reported: * `git.commit.count.<1`. * * @key The key prefix which will be appended with "." and range code. * @steps Limits of the ranges. Each value represents the start of the next range. The list must be sorted ascendingly. * @value Value to be checked among the given ranges. */ fun getCountingUsage(key: String, value: Int, steps: List<Int>) : UsageDescriptor { if (steps.isEmpty()) return UsageDescriptor("$key.$value", 1) if (value < steps[0]) return UsageDescriptor("$key.<${steps[0]}", 1) var stepIndex = 0 while (stepIndex < steps.size - 1) { if (value < steps[stepIndex + 1]) break stepIndex++ } val step = steps[stepIndex] val addPlus = stepIndex == steps.size - 1 || steps[stepIndex + 1] != step + 1 val stepName = humanize(step) + if (addPlus) "+" else "" return UsageDescriptor("$key.$stepName", 1) } /** * [getCountingUsage] with steps (0, 1, 2, 3, 5, 10, 15, 30, 50, 100, 500, 1000, 5000, 10000, ...) */ fun getCountingUsage(key: String, value: Int): UsageDescriptor { if (value > Int.MAX_VALUE / 10) return UsageDescriptor("$key.MANY", 1) if (value < 0) return UsageDescriptor("$key.<0", 1) if (value < 3) return UsageDescriptor("$key.$value", 1) val fixedSteps = listOf(3, 5, 10, 15, 30, 50) var step = fixedSteps.last { it <= value } while (true) { if (value < step * 2) break step *= 2 if (value < step * 5) break step *= 5 } val stepName = humanize(step) return UsageDescriptor("$key.$stepName+", 1) } private val kilo = 1000 private val mega = kilo * kilo private fun humanize(number: Int): String { if (number == 0) return "0" val m = number / mega val k = (number % mega) / kilo val r = (number % kilo) val ms = if (m > 0) "${m}M" else "" val ks = if (k > 0) "${k}K" else "" val rs = if (r > 0) "${r}" else "" return ms + ks + rs } fun toUsageDescriptors(result: ObjectIntHashMap<String>): Set<UsageDescriptor> { if (result.isEmpty) { return emptySet() } else { val descriptors = THashSet<UsageDescriptor>(result.size()) result.forEachEntry { key, value -> descriptors.add(UsageDescriptor(key, value)) true } return descriptors } } fun merge(first: Set<UsageDescriptor>, second: Set<UsageDescriptor>): Set<UsageDescriptor> { if (first.isEmpty()) { return second } if (second.isEmpty()) { return first } val merged = ObjectIntHashMap<String>() addAll(merged, first) addAll(merged, second) return toUsageDescriptors(merged) } private fun addAll(result: ObjectIntHashMap<String>, usages: Set<UsageDescriptor>) { for (usage in usages) { val key = usage.key result.put(key, result.get(key, 0) + usage.value) } }
apache-2.0
eyneill777/SpacePirates
core/src/rustyice/physics/PhysicsComponent.kt
1
401
package rustyice.physics import rustyice.game.* /** * Created by gabek */ abstract class PhysicsComponent: GameLifecycle(), Collidable { @Transient open var parent: GameObject? = null val section: Section? get() = parent?.section val game: Game? get() = parent?.section?.game abstract var x: Float abstract var y: Float abstract var rotation: Float }
mit
marius-m/wt4
app/src/main/java/lt/markmerkk/widgets/list/ListLogStatusIndicatorCell.kt
1
620
package lt.markmerkk.widgets.list import javafx.scene.Parent import javafx.scene.paint.Color import javafx.scene.paint.Paint import javafx.scene.shape.Circle import tornadofx.* class ListLogStatusIndicatorCell: TableCellFragment<ListLogWidget.LogViewModel, String>() { private lateinit var viewStatusIndicator: Circle override val root: Parent = stackpane { viewStatusIndicator = circle { centerX = 12.0 centerY = 12.0 radius = 10.0 } } override fun onDock() { super.onDock() viewStatusIndicator.fill = Paint.valueOf(item) } }
apache-2.0
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupNotifier.kt
2
5563
package eu.kanade.tachiyomi.data.backup import android.content.Context import android.graphics.BitmapFactory import androidx.core.app.NotificationCompat import com.hippo.unifile.UniFile import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.notification.NotificationReceiver import eu.kanade.tachiyomi.data.notification.Notifications import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.util.storage.getUriCompat import eu.kanade.tachiyomi.util.system.notificationBuilder import eu.kanade.tachiyomi.util.system.notificationManager import uy.kohesive.injekt.injectLazy import java.io.File import java.util.concurrent.TimeUnit class BackupNotifier(private val context: Context) { private val preferences: PreferencesHelper by injectLazy() private val progressNotificationBuilder = context.notificationBuilder(Notifications.CHANNEL_BACKUP_RESTORE_PROGRESS) { setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)) setSmallIcon(R.drawable.ic_tachi) setAutoCancel(false) setOngoing(true) setOnlyAlertOnce(true) } private val completeNotificationBuilder = context.notificationBuilder(Notifications.CHANNEL_BACKUP_RESTORE_COMPLETE) { setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)) setSmallIcon(R.drawable.ic_tachi) setAutoCancel(false) } private fun NotificationCompat.Builder.show(id: Int) { context.notificationManager.notify(id, build()) } fun showBackupProgress(): NotificationCompat.Builder { val builder = with(progressNotificationBuilder) { setContentTitle(context.getString(R.string.creating_backup)) setProgress(0, 0, true) } builder.show(Notifications.ID_BACKUP_PROGRESS) return builder } fun showBackupError(error: String?) { context.notificationManager.cancel(Notifications.ID_BACKUP_PROGRESS) with(completeNotificationBuilder) { setContentTitle(context.getString(R.string.creating_backup_error)) setContentText(error) show(Notifications.ID_BACKUP_COMPLETE) } } fun showBackupComplete(unifile: UniFile) { context.notificationManager.cancel(Notifications.ID_BACKUP_PROGRESS) with(completeNotificationBuilder) { setContentTitle(context.getString(R.string.backup_created)) setContentText(unifile.filePath ?: unifile.name) // Clear old actions if they exist clearActions() addAction( R.drawable.ic_share_24dp, context.getString(R.string.action_share), NotificationReceiver.shareBackupPendingBroadcast(context, unifile.uri, Notifications.ID_BACKUP_COMPLETE) ) show(Notifications.ID_BACKUP_COMPLETE) } } fun showRestoreProgress(content: String = "", progress: Int = 0, maxAmount: Int = 100): NotificationCompat.Builder { val builder = with(progressNotificationBuilder) { setContentTitle(context.getString(R.string.restoring_backup)) if (!preferences.hideNotificationContent()) { setContentText(content) } setProgress(maxAmount, progress, false) setOnlyAlertOnce(true) // Clear old actions if they exist clearActions() addAction( R.drawable.ic_close_24dp, context.getString(R.string.action_stop), NotificationReceiver.cancelRestorePendingBroadcast(context, Notifications.ID_RESTORE_PROGRESS) ) } builder.show(Notifications.ID_RESTORE_PROGRESS) return builder } fun showRestoreError(error: String?) { context.notificationManager.cancel(Notifications.ID_RESTORE_PROGRESS) with(completeNotificationBuilder) { setContentTitle(context.getString(R.string.restoring_backup_error)) setContentText(error) show(Notifications.ID_RESTORE_COMPLETE) } } fun showRestoreComplete(time: Long, errorCount: Int, path: String?, file: String?) { context.notificationManager.cancel(Notifications.ID_RESTORE_PROGRESS) val timeString = context.getString( R.string.restore_duration, TimeUnit.MILLISECONDS.toMinutes(time), TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes(time) ) ) with(completeNotificationBuilder) { setContentTitle(context.getString(R.string.restore_completed)) setContentText(context.resources.getQuantityString(R.plurals.restore_completed_message, errorCount, timeString, errorCount)) // Clear old actions if they exist clearActions() if (errorCount > 0 && !path.isNullOrEmpty() && !file.isNullOrEmpty()) { val destFile = File(path, file) val uri = destFile.getUriCompat(context) val errorLogIntent = NotificationReceiver.openErrorLogPendingActivity(context, uri) setContentIntent(errorLogIntent) addAction( R.drawable.ic_folder_24dp, context.getString(R.string.action_show_errors), errorLogIntent, ) } show(Notifications.ID_RESTORE_COMPLETE) } } }
apache-2.0
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/Double/DoubleVec2.kt
1
20332
package glm data class DoubleVec2(val x: Double, val y: Double) { // Initializes each element by evaluating init from 0 until 1 constructor(init: (Int) -> Double) : this(init(0), init(1)) operator fun get(idx: Int): Double = when (idx) { 0 -> x 1 -> y else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators operator fun inc(): DoubleVec2 = DoubleVec2(x.inc(), y.inc()) operator fun dec(): DoubleVec2 = DoubleVec2(x.dec(), y.dec()) operator fun unaryPlus(): DoubleVec2 = DoubleVec2(+x, +y) operator fun unaryMinus(): DoubleVec2 = DoubleVec2(-x, -y) operator fun plus(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x + rhs.x, y + rhs.y) operator fun minus(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x - rhs.x, y - rhs.y) operator fun times(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x * rhs.x, y * rhs.y) operator fun div(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x / rhs.x, y / rhs.y) operator fun rem(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x % rhs.x, y % rhs.y) operator fun plus(rhs: Double): DoubleVec2 = DoubleVec2(x + rhs, y + rhs) operator fun minus(rhs: Double): DoubleVec2 = DoubleVec2(x - rhs, y - rhs) operator fun times(rhs: Double): DoubleVec2 = DoubleVec2(x * rhs, y * rhs) operator fun div(rhs: Double): DoubleVec2 = DoubleVec2(x / rhs, y / rhs) operator fun rem(rhs: Double): DoubleVec2 = DoubleVec2(x % rhs, y % rhs) inline fun map(func: (Double) -> Double): DoubleVec2 = DoubleVec2(func(x), func(y)) fun toList(): List<Double> = listOf(x, y) // Predefined vector constants companion object Constants { val zero: DoubleVec2 = DoubleVec2(0.0, 0.0) val ones: DoubleVec2 = DoubleVec2(1.0, 1.0) val unitX: DoubleVec2 = DoubleVec2(1.0, 0.0) val unitY: DoubleVec2 = DoubleVec2(0.0, 1.0) } // Conversions to Float fun toVec(): Vec2 = Vec2(x.toFloat(), y.toFloat()) inline fun toVec(conv: (Double) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat()) inline fun toVec2(conv: (Double) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec3(z: Float = 0f): Vec3 = Vec3(x.toFloat(), y.toFloat(), z) inline fun toVec3(z: Float = 0f, conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), z) fun toVec4(z: Float = 0f, w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z, w) inline fun toVec4(z: Float = 0f, w: Float = 0f, conv: (Double) -> Float): Vec4 = Vec4(conv(x), conv(y), z, w) // Conversions to Float fun toMutableVec(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat()) inline fun toMutableVec(conv: (Double) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat()) inline fun toMutableVec2(conv: (Double) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec3(z: Float = 0f): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z) inline fun toMutableVec3(z: Float = 0f, conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), z) fun toMutableVec4(z: Float = 0f, w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z, w) inline fun toMutableVec4(z: Float = 0f, w: Float = 0f, conv: (Double) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), z, w) // Conversions to Double fun toDoubleVec(): DoubleVec2 = DoubleVec2(x, y) inline fun toDoubleVec(conv: (Double) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x, y) inline fun toDoubleVec2(conv: (Double) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec3(z: Double = 0.0): DoubleVec3 = DoubleVec3(x, y, z) inline fun toDoubleVec3(z: Double = 0.0, conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), z) fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0): DoubleVec4 = DoubleVec4(x, y, z, w) inline fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Double) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), z, w) // Conversions to Double fun toMutableDoubleVec(): MutableDoubleVec2 = MutableDoubleVec2(x, y) inline fun toMutableDoubleVec(conv: (Double) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x, y) inline fun toMutableDoubleVec2(conv: (Double) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec3(z: Double = 0.0): MutableDoubleVec3 = MutableDoubleVec3(x, y, z) inline fun toMutableDoubleVec3(z: Double = 0.0, conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), z) fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x, y, z, w) inline fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Double) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), z, w) // Conversions to Int fun toIntVec(): IntVec2 = IntVec2(x.toInt(), y.toInt()) inline fun toIntVec(conv: (Double) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt()) inline fun toIntVec2(conv: (Double) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec3(z: Int = 0): IntVec3 = IntVec3(x.toInt(), y.toInt(), z) inline fun toIntVec3(z: Int = 0, conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), z) fun toIntVec4(z: Int = 0, w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z, w) inline fun toIntVec4(z: Int = 0, w: Int = 0, conv: (Double) -> Int): IntVec4 = IntVec4(conv(x), conv(y), z, w) // Conversions to Int fun toMutableIntVec(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt()) inline fun toMutableIntVec(conv: (Double) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt()) inline fun toMutableIntVec2(conv: (Double) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec3(z: Int = 0): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z) inline fun toMutableIntVec3(z: Int = 0, conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), z) fun toMutableIntVec4(z: Int = 0, w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z, w) inline fun toMutableIntVec4(z: Int = 0, w: Int = 0, conv: (Double) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), z, w) // Conversions to Long fun toLongVec(): LongVec2 = LongVec2(x.toLong(), y.toLong()) inline fun toLongVec(conv: (Double) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong()) inline fun toLongVec2(conv: (Double) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec3(z: Long = 0L): LongVec3 = LongVec3(x.toLong(), y.toLong(), z) inline fun toLongVec3(z: Long = 0L, conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), z) fun toLongVec4(z: Long = 0L, w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z, w) inline fun toLongVec4(z: Long = 0L, w: Long = 0L, conv: (Double) -> Long): LongVec4 = LongVec4(conv(x), conv(y), z, w) // Conversions to Long fun toMutableLongVec(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong()) inline fun toMutableLongVec(conv: (Double) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong()) inline fun toMutableLongVec2(conv: (Double) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec3(z: Long = 0L): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z) inline fun toMutableLongVec3(z: Long = 0L, conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), z) fun toMutableLongVec4(z: Long = 0L, w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z, w) inline fun toMutableLongVec4(z: Long = 0L, w: Long = 0L, conv: (Double) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), z, w) // Conversions to Short fun toShortVec(): ShortVec2 = ShortVec2(x.toShort(), y.toShort()) inline fun toShortVec(conv: (Double) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort()) inline fun toShortVec2(conv: (Double) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec3(z: Short = 0.toShort()): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z) inline fun toShortVec3(z: Short = 0.toShort(), conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), z) fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z, w) inline fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Double) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), z, w) // Conversions to Short fun toMutableShortVec(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort()) inline fun toMutableShortVec(conv: (Double) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort()) inline fun toMutableShortVec2(conv: (Double) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec3(z: Short = 0.toShort()): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z) inline fun toMutableShortVec3(z: Short = 0.toShort(), conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), z) fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z, w) inline fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Double) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), z, w) // Conversions to Byte fun toByteVec(): ByteVec2 = ByteVec2(x.toByte(), y.toByte()) inline fun toByteVec(conv: (Double) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte()) inline fun toByteVec2(conv: (Double) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec3(z: Byte = 0.toByte()): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z) inline fun toByteVec3(z: Byte = 0.toByte(), conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), z) fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z, w) inline fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Double) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), z, w) // Conversions to Byte fun toMutableByteVec(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte()) inline fun toMutableByteVec(conv: (Double) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte()) inline fun toMutableByteVec2(conv: (Double) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec3(z: Byte = 0.toByte()): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z) inline fun toMutableByteVec3(z: Byte = 0.toByte(), conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), z) fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z, w) inline fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Double) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), z, w) // Conversions to Char fun toCharVec(): CharVec2 = CharVec2(x.toChar(), y.toChar()) inline fun toCharVec(conv: (Double) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar()) inline fun toCharVec2(conv: (Double) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) fun toCharVec3(z: Char): CharVec3 = CharVec3(x.toChar(), y.toChar(), z) inline fun toCharVec3(z: Char, conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), z) fun toCharVec4(z: Char, w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z, w) inline fun toCharVec4(z: Char, w: Char, conv: (Double) -> Char): CharVec4 = CharVec4(conv(x), conv(y), z, w) // Conversions to Char fun toMutableCharVec(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar()) inline fun toMutableCharVec(conv: (Double) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar()) inline fun toMutableCharVec2(conv: (Double) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) fun toMutableCharVec3(z: Char): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z) inline fun toMutableCharVec3(z: Char, conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), z) fun toMutableCharVec4(z: Char, w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z, w) inline fun toMutableCharVec4(z: Char, w: Char, conv: (Double) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), z, w) // Conversions to Boolean fun toBoolVec(): BoolVec2 = BoolVec2(x != 0.0, y != 0.0) inline fun toBoolVec(conv: (Double) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.0, y != 0.0) inline fun toBoolVec2(conv: (Double) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec3(z: Boolean = false): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z) inline fun toBoolVec3(z: Boolean = false, conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), z) fun toBoolVec4(z: Boolean = false, w: Boolean = false): BoolVec4 = BoolVec4(x != 0.0, y != 0.0, z, w) inline fun toBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Double) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), z, w) // Conversions to Boolean fun toMutableBoolVec(): MutableBoolVec2 = MutableBoolVec2(x != 0.0, y != 0.0) inline fun toMutableBoolVec(conv: (Double) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.0, y != 0.0) inline fun toMutableBoolVec2(conv: (Double) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec3(z: Boolean = false): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z) inline fun toMutableBoolVec3(z: Boolean = false, conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), z) fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0.0, y != 0.0, z, w) inline fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Double) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), z, w) // Conversions to String fun toStringVec(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec(conv: (Double) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec2(conv: (Double) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(z: String = ""): StringVec3 = StringVec3(x.toString(), y.toString(), z) inline fun toStringVec3(z: String = "", conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), z) fun toStringVec4(z: String = "", w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z, w) inline fun toStringVec4(z: String = "", w: String = "", conv: (Double) -> String): StringVec4 = StringVec4(conv(x), conv(y), z, w) // Conversions to String fun toMutableStringVec(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec(conv: (Double) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec2(conv: (Double) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(z: String = ""): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z) inline fun toMutableStringVec3(z: String = "", conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), z) fun toMutableStringVec4(z: String = "", w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z, w) inline fun toMutableStringVec4(z: String = "", w: String = "", conv: (Double) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), z, w) // Conversions to T2 inline fun <T2> toTVec(conv: (Double) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec2(conv: (Double) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(z: T2, conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), z) inline fun <T2> toTVec4(z: T2, w: T2, conv: (Double) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), z, w) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (Double) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec2(conv: (Double) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(z: T2, conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), z) inline fun <T2> toMutableTVec4(z: T2, w: T2, conv: (Double) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), z, w) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: DoubleVec2 get() = DoubleVec2(x, x) val xy: DoubleVec2 get() = DoubleVec2(x, y) val yx: DoubleVec2 get() = DoubleVec2(y, x) val yy: DoubleVec2 get() = DoubleVec2(y, y) val xxx: DoubleVec3 get() = DoubleVec3(x, x, x) val xxy: DoubleVec3 get() = DoubleVec3(x, x, y) val xyx: DoubleVec3 get() = DoubleVec3(x, y, x) val xyy: DoubleVec3 get() = DoubleVec3(x, y, y) val yxx: DoubleVec3 get() = DoubleVec3(y, x, x) val yxy: DoubleVec3 get() = DoubleVec3(y, x, y) val yyx: DoubleVec3 get() = DoubleVec3(y, y, x) val yyy: DoubleVec3 get() = DoubleVec3(y, y, y) val xxxx: DoubleVec4 get() = DoubleVec4(x, x, x, x) val xxxy: DoubleVec4 get() = DoubleVec4(x, x, x, y) val xxyx: DoubleVec4 get() = DoubleVec4(x, x, y, x) val xxyy: DoubleVec4 get() = DoubleVec4(x, x, y, y) val xyxx: DoubleVec4 get() = DoubleVec4(x, y, x, x) val xyxy: DoubleVec4 get() = DoubleVec4(x, y, x, y) val xyyx: DoubleVec4 get() = DoubleVec4(x, y, y, x) val xyyy: DoubleVec4 get() = DoubleVec4(x, y, y, y) val yxxx: DoubleVec4 get() = DoubleVec4(y, x, x, x) val yxxy: DoubleVec4 get() = DoubleVec4(y, x, x, y) val yxyx: DoubleVec4 get() = DoubleVec4(y, x, y, x) val yxyy: DoubleVec4 get() = DoubleVec4(y, x, y, y) val yyxx: DoubleVec4 get() = DoubleVec4(y, y, x, x) val yyxy: DoubleVec4 get() = DoubleVec4(y, y, x, y) val yyyx: DoubleVec4 get() = DoubleVec4(y, y, y, x) val yyyy: DoubleVec4 get() = DoubleVec4(y, y, y, y) } val swizzle: Swizzle get() = Swizzle() } fun vecOf(x: Double, y: Double): DoubleVec2 = DoubleVec2(x, y) operator fun Double.plus(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this + rhs.x, this + rhs.y) operator fun Double.minus(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this - rhs.x, this - rhs.y) operator fun Double.times(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this * rhs.x, this * rhs.y) operator fun Double.div(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this / rhs.x, this / rhs.y) operator fun Double.rem(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this % rhs.x, this % rhs.y)
mit
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_occlusion_query2.kt
4
823
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_occlusion_query2 = "ARBOcclusionQuery2".nativeClassGL("ARB_occlusion_query2") { documentation = """ Native bindings to the $registryLink extension. This extension trivially adds a boolean occlusion query to ${ARB_occlusion_query.link}. While the counter-based occlusion query provided by ARB_occlusion_query is flexible, there is still value to a simple boolean, which is often sufficient for applications. ${GL33.promoted} """ IntConstant( "Accepted by the {@code target} parameter of BeginQuery, EndQuery, and GetQueryiv.", "ANY_SAMPLES_PASSED"..0x8C2F ) }
bsd-3-clause
code-disaster/lwjgl3
modules/lwjgl/assimp/src/templates/kotlin/assimp/AssimpTypes.kt
2
62779
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package assimp import org.lwjgl.generator.* import java.io.* val ASSIMP_BINDING = object : SimpleBinding(Module.ASSIMP, "ASSIMP") { override fun PrintWriter.generateFunctionSetup(nativeClass: NativeClass) { println("\n${t}private static final SharedLibrary DRACO = Library.loadNative(Assimp.class, \"${module.java}\", Configuration.ASSIMP_DRACO_LIBRARY_NAME.get(Platform.mapLibraryNameBundled(\"draco\")), true);") println("${t}private static final SharedLibrary ASSIMP = Library.loadNative(Assimp.class, \"${module.java}\", Configuration.ASSIMP_LIBRARY_NAME.get(Platform.mapLibraryNameBundled(\"assimp\")), true);") generateFunctionsClass(nativeClass, "\n$t/** Contains the function pointers loaded from the assimp {@link SharedLibrary}. */") println(""" /** Returns the assimp {@link SharedLibrary}. */ public static SharedLibrary getLibrary() { return ASSIMP; } /** Returns the Draco {@link SharedLibrary}. */ public static SharedLibrary getDraco() { return DRACO; }""") } } val ai_int32 = typedef(int32_t, "ai_int32") val ai_uint32 = typedef(uint32_t, "ai_uint32") val ai_real = typedef(float, "ai_real") /*val aiPlane = struct(Binding.ASSIMP, "AIPlane", nativeName = "struct aiPlane") { documentation = "Represents a plane in a three-dimensional, euclidean space." float("a", "Plane equation") float("b", "Plane equation") float("c", "Plane equation") float("d", "Plane equation") }*/ val aiVector2D = struct(Module.ASSIMP, "AIVector2D", nativeName = "struct aiVector2D", mutable = false) { float("x", "") float("y", "") } val aiVector3D = struct(Module.ASSIMP, "AIVector3D", nativeName = "struct aiVector3D") { float("x", "") float("y", "") float("z", "") } val aiAABB = struct(Module.ASSIMP, "AIAABB", nativeName = "struct aiAABB") { aiVector3D("mMin", "") aiVector3D("mMax", "") } /*val aiRay = struct(Binding.ASSIMP, "AIRay", nativeName = "struct aiRay") { documentation = "Represents a ray." aiVector3D("pos", "Position of the ray") aiVector3D("dir", "Direction of the ray") }*/ val aiColor3D = struct(Module.ASSIMP, "AIColor3D", nativeName = "struct aiColor3D", mutable = false) { documentation = "Represents a color in Red-Green-Blue space." float("r", "The red color value") float("g", "The green color value") float("b", "The blue color value") } val aiString = struct(Module.ASSIMP, "AIString", nativeName = "struct aiString") { documentation = "Represents an UTF-8 string, zero byte terminated." AutoSize("data")..ai_uint32("length", "Binary length of the string excluding the terminal 0.") NullTerminatedMember..charUTF8("data", "String buffer.")["Assimp.MAXLEN"] } val aiMemoryInfo = struct(Module.ASSIMP, "AIMemoryInfo", nativeName = "struct aiMemoryInfo", mutable = false) { documentation = "Stores the memory requirements for different components (e.g. meshes, materials, animations) of an import. All sizes are in bytes." unsigned_int("textures", "Storage allocated for texture data") unsigned_int("materials", "Storage allocated for material data") unsigned_int("meshes", "Storage allocated for mesh data") unsigned_int("nodes", "Storage allocated for node data") unsigned_int("animations", "Storage allocated for animation data") unsigned_int("cameras", "Storage allocated for camera data") unsigned_int("lights", "Storage allocated for light data") unsigned_int("total", "Total storage allocated for the full import.") } val aiTexel = struct(Module.ASSIMP, "AITexel", nativeName = "struct aiTexel", mutable = false) { documentation = "Helper structure to represent a texel in a ARGB8888 format. Used by aiTexture." unsigned_char("b", "The blue color component") unsigned_char("g", "The green color component") unsigned_char("r", "The red color component") unsigned_char("a", "The alpha color component") } private const val HINTMAXTEXTURELEN = 9 val aiTexture = struct(Module.ASSIMP, "AITexture", nativeName = "struct aiTexture", mutable = false) { documentation = """ Helper structure to describe an embedded texture. Normally textures are contained in external files but some file formats embed them directly in the model file. There are two types of embedded textures: ${ul( "Uncompressed textures. The color data is given in an uncompressed format.", "Compressed textures stored in a file format like png or jpg." )} The raw file bytes are given so the application must utilize an image decoder (e.g. DevIL) to get access to the actual color data. Embedded textures are referenced from materials using strings like "*0", "*1", etc. as the texture paths (a single asterisk character followed by the zero-based index of the texture in the ##AIScene{@code ::mTextures} array). """ AutoSize("pcData")..unsigned_int( "mWidth", """ Width of the texture, in pixels. If {@code mHeight} is zero the texture is compressed in a format like JPEG. In this case {@code mWidth} specifies the size of the memory area {@code pcData} is pointing to, in bytes. """ ) AutoSize("pcData")..unsigned_int( "mHeight", "Height of the texture, in pixels. If this value is zero, {@code pcData} points to an compressed texture in any format (e.g. JPEG)." ) charASCII( "achFormatHint", """ A hint from the loader to make it easier for applications to determine the type of embedded textures. If {@code mHeight != 0} this member is show how data is packed. Hint will consist of two parts: channel order and channel bitness (count of the bits for every color channel). For simple parsing by the viewer it's better to not omit absent color channel and just use 0 for bitness. For example: ${ol( "Image contain RGBA and 8 bit per channel, {@code achFormatHint == \"rgba8888\";}", "Image contain ARGB and 8 bit per channel, {@code achFormatHint == \"argb8888\";}", "Image contain RGB and 5 bit for R and B channels and 6 bit for G channel, {@code achFormatHint == \"rgba5650\";}", "One color image with B channel and 1 bit for it, {@code achFormatHint == \"rgba0010\";}" )} If {@code mHeight == 0} then {@code achFormatHint} is set set to '\0\0\0\0' if the loader has no additional information about the texture file format used OR the file extension of the format without a trailing dot. If there are multiple file extensions for a format, the shortest extension is chosen (JPEG maps to 'jpg', not to 'jpeg'). E.g. 'dds\0', 'pcx\0', 'jpg\0'. All characters are lower-case. The fourth character will always be '\0'. """ )[HINTMAXTEXTURELEN] // 8 for string + 1 for terminator. aiTexel.p( "pcData", """ Data of the texture. Points to an array of {@code mWidth * mHeight} ##AITexel's. The format of the texture data is always ARGB8888 to make the implementation for user of the library as easy as possible. If {@code mHeight = 0} this is a pointer to a memory buffer of size {@code mWidth} containing the compressed texture data. Good luck, have fun! """ ) aiString("mFilename", "texture original filename. Used to get the texture reference.") customMethod(""" /** Returns a {@code char *} view of the array pointed to by the {@code pcData} field. */ @NativeType("char *") public ByteBuffer pcDataCompressed() { return npcDataCompressed(address()); } /** Unsafe version of {@link #pcDataCompressed}. */ public static ByteBuffer npcDataCompressed(long struct) { return memByteBuffer(memGetAddress(struct + AITexture.PCDATA), nmWidth(struct)); }""") customMethodBuffer(""" $t/** Returns a {@code char *} view of the array pointed to by the {@code pcData} field. */ @NativeType("char *") public ByteBuffer pcDataCompressed() { return npcDataCompressed(address()); }""") } val aiColor4D = struct(Module.ASSIMP, "AIColor4D", nativeName = "struct aiColor4D") { documentation = "Represents a color in Red-Green-Blue space including an alpha component. Color values range from 0 to 1." float("r", "The red color component") float("g", "The green color component") float("b", "The blue color component") float("a", "The alpha color component") } val aiMatrix4x4 = struct(Module.ASSIMP, "AIMatrix4x4", nativeName = "struct aiMatrix4x4") { documentation = "Represents a row-major 4x4 matrix, use this for homogeneous coordinates." float("a1", "") float("a2", "") float("a3", "") float("a4", "") float("b1", "") float("b2", "") float("b3", "") float("b4", "") float("c1", "") float("c2", "") float("c3", "") float("c4", "") float("d1", "") float("d2", "") float("d3", "") float("d4", "") } val aiMatrix3x3 = struct(Module.ASSIMP, "AIMatrix3x3", nativeName = "struct aiMatrix3x3") { documentation = "Represents a row-major 3x3 matrix." float("a1", "") float("a2", "") float("a3", "") float("b1", "") float("b2", "") float("b3", "") float("c1", "") float("c2", "") float("c3", "") } val aiMetadataType = "aiMetadataType".enumType val aiMetadataEntry = struct(Module.ASSIMP, "AIMetaDataEntry", nativeName = "struct aiMetadataEntry") { aiMetadataType("mType", "") void.p("mData", "") } val aiMetadata = struct(Module.ASSIMP, "AIMetaData", nativeName = "struct aiMetadata") { AutoSize("mKeys", "mValues")..unsigned_int("mNumProperties", "Length of the {@code mKeys} and {@code mValues} arrays, respectively") aiString.p("mKeys", "Arrays of keys, may not be #NULL. Entries in this array may not be #NULL as well.") aiMetadataEntry.p( "mValues", "Arrays of values, may not be #NULL. Entries in this array may be #NULL if the corresponding property key has no assigned value." ) } private val _aiNode = struct(Module.ASSIMP, "AINode", nativeName = "struct aiNode") val aiNode = struct(Module.ASSIMP, "AINode", nativeName = "struct aiNode") { documentation = """ A node in the imported hierarchy. Each node has name, a parent node (except for the root node), a transformation relative to its parent and possibly several child nodes. Simple file formats don't support hierarchical structures - for these formats the imported scene does consist of only a single root node without children. """ aiString( "mName", """ The name of the node. The name might be empty (length of zero) but all nodes which need to be referenced by either bones or animations are named. Multiple nodes may have the same name, except for nodes which are referenced by bones (see ##AIBone and ##AIMesh{@code ::mBones}). Their names <b>must</b> be unique. Cameras and lights reference a specific node by name - if there are multiple nodes with this name, they are assigned to each of them. There are no limitations with regard to the characters contained in the name string as it is usually taken directly from the source file. Implementations should be able to handle tokens such as whitespace, tabs, line feeds, quotation marks, ampersands etc. Sometimes assimp introduces new nodes not present in the source file into the hierarchy (usually out of necessity because sometimes the source hierarchy format is simply not compatible). Their names are surrounded by {@code <>} e.g. {@code <DummyRootNode>}. """ ) aiMatrix4x4("mTransformation", "The transformation relative to the node's parent.") nullable.._aiNode.p("mParent", "Parent node. #NULL if this node is the root node.") AutoSize("mChildren", optional = true)..unsigned_int("mNumChildren", "The number of child nodes of this node.") _aiNode.p.p("mChildren", "The child nodes of this node. #NULL if {@code mNumChildren} is 0.") AutoSize("mMeshes", optional = true)..unsigned_int("mNumMeshes", "The number of meshes of this node.") unsigned_int.p("mMeshes", "The meshes of this node. Each entry is an index into the mesh list of the ##AIScene.") nullable..aiMetadata.p( "mMetadata", """ Metadata associated with this node or #NULL if there is no metadata. Whether any metadata is generated depends on the source file format. See the importer notes page for more information on every source file format. Importers that don't document any metadata don't write any. """ ) } val aiFace = struct(Module.ASSIMP, "AIFace", nativeName = "struct aiFace") { documentation = """ A single face in a mesh, referring to multiple vertices. If {@code mNumIndices} is 3, we call the face 'triangle', for {@code mNumIndices > 3} it's called 'polygon' (hey, that's just a definition!). ##AIMesh{@code ::mPrimitiveTypes} can be queried to quickly examine which types of primitive are actually present in a mesh. The #Process_SortByPType flag executes a special post-processing algorithm which splits meshes with *different* primitive types mixed up (e.g. lines and triangles) in several 'clean' submeshes. Furthermore there is a configuration option (#AI_CONFIG_PP_SBP_REMOVE) to force #Process_SortByPType to remove specific kinds of primitives from the imported scene, completely and forever. """ AutoSize("mIndices")..unsigned_int( "mNumIndices", "Number of indices defining this face. The maximum value for this member is #AI_MAX_FACE_INDICES." ) unsigned_int.p("mIndices", "Pointer to the indices array. Size of the array is given in {@code numIndices}.") } val aiVertexWeight = struct(Module.ASSIMP, "AIVertexWeight", nativeName = "struct aiVertexWeight") { documentation = "A single influence of a bone on a vertex." unsigned_int("mVertexId", "Index of the vertex which is influenced by the bone.") float("mWeight", "The strength of the influence in the range (0...1). The influence from all bones at one vertex amounts to 1.") } val aiBone = struct(Module.ASSIMP, "AIBone", nativeName = "struct aiBone") { documentation = """ A single bone of a mesh. A bone has a name by which it can be found in the frame hierarchy and by which it can be addressed by animations. In addition it has a number of influences on vertices, and a matrix relating the mesh position to the position of the bone at the time of binding. """ aiString("mName", "the name of the bone.") AutoSize("mWeights")..unsigned_int( "mNumWeights", "the number of vertices affected by this bone. The maximum value for this member is #AI_MAX_BONE_WEIGHTS." ) aiNode.p("mArmature", "the bone armature node - used for skeleton conversion you must enable #Process_PopulateArmatureData to populate this"); aiNode.p("mNode", "the bone node in the scene - used for skeleton conversion you must enable #Process_PopulateArmatureData to populate this"); aiVertexWeight.p("mWeights", "the influence weights of this bone, by vertex index") aiMatrix4x4( "mOffsetMatrix", """ matrix that transforms from mesh space to bone space in bind pose. This matrix describes the position of the mesh in the local space of this bone when the skeleton was bound. Thus it can be used directly to determine a desired vertex position, given the world-space transform of the bone when animated, and the position of the vertex in mesh space. It is sometimes called an inverse-bind matrix, or inverse bind pose matrix. """ ) } val aiAnimMesh = struct(Module.ASSIMP, "AIAnimMesh", nativeName = "struct aiAnimMesh") { documentation = """ An {@code AnimMesh} is an attachment to an ##AIMesh stores per-vertex animations for a particular frame. You may think of an {@code aiAnimMesh} as a `patch` for the host mesh, which replaces only certain vertex data streams at a particular time. Each mesh stores n attached attached meshes (##AIMesh{@code ::mAnimMeshes}). The actual relationship between the time line and anim meshes is established by {@code aiMeshAnim}, which references singular mesh attachments by their ID and binds them to a time offset. """ aiString("mName", "the {@code AnimMesh} name") nullable..aiVector3D.p( "mVertices", """ Replacement for ##AIMesh{@code ::mVertices}. If this array is non-#NULL, it *must* contain {@code mNumVertices} entries. The corresponding array in the host mesh must be non-#NULL as well - animation meshes may neither add or nor remove vertex components (if a replacement array is #NULL and the corresponding source array is not, the source data is taken instead). """ ) nullable..aiVector3D.p("mNormals", "Replacement for ##AIMesh{@code ::mNormals}.") nullable..aiVector3D.p("mTangents", "Replacement for ##AIMesh{@code ::mTangents}.") nullable..aiVector3D.p("mBitangents", "Replacement for ##AIMesh{@code ::mBitangents}.") nullable..aiColor4D.p("mColors", "Replacement for ##AIMesh{@code ::mColors}")["Assimp.AI_MAX_NUMBER_OF_COLOR_SETS"] nullable..aiVector3D.p("mTextureCoords", "Replacement for ##AIMesh{@code ::mTextureCoords}")["Assimp.AI_MAX_NUMBER_OF_TEXTURECOORDS"] AutoSize( "mVertices", "mNormals", "mTangents", "mBitangents" )..AutoSizeIndirect( "mColors", "mTextureCoords" )..unsigned_int( "mNumVertices", """ The number of vertices in the {@code aiAnimMesh}, and thus the length of all the member arrays. This has always the same value as the {@code mNumVertices} property in the corresponding ##AIMesh. It is duplicated here merely to make the length of the member arrays accessible even if the {@code aiMesh} is not known, e.g. from language bindings. """ ) float("mWeight", "Weight of the {@code AnimMesh}.") } val aiMesh = struct(Module.ASSIMP, "AIMesh", nativeName = "struct aiMesh") { javaImport("static org.lwjgl.assimp.Assimp.*") documentation = """ A mesh represents a geometry or model with a single material. It usually consists of a number of vertices and a series of primitives/faces referencing the vertices. In addition there might be a series of bones, each of them addressing a number of vertices with a certain weight. Vertex data is presented in channels with each channel containing a single per-vertex information such as a set of texture coordinates or a normal vector. If a data pointer is non-null, the corresponding data stream is present. A Mesh uses only a single material which is referenced by a material ID. """ unsigned_int( "mPrimitiveTypes", """ Bitwise combination of the members of the {@code aiPrimitiveType} enum. This specifies which types of primitives are present in the mesh. The "SortByPrimitiveType"-Step can be used to make sure the output meshes consist of one primitive type each. """ ).links("PrimitiveType_\\w+", LinkMode.BITFIELD) AutoSize( "mVertices", "mNormals", "mTangents", "mBitangents" )..AutoSizeIndirect( "mColors", "mTextureCoords" )..unsigned_int( "mNumVertices", """ The number of vertices in this mesh. This is also the size of all of the per-vertex data arrays. The maximum value for this member is #AI_MAX_VERTICES. """ ) AutoSize("mFaces")..unsigned_int( "mNumFaces", """ The number of primitives (triangles, polygons, lines) in this mesh. This is also the size of the {@code mFaces} array. The maximum value for this member is #AI_MAX_FACES. """ ) aiVector3D.p("mVertices", "Vertex positions. This array is always present in a mesh. The array is {@code mNumVertices} in size.") nullable..aiVector3D.p( "mNormals", """ Vertex normals. The array contains normalized vectors, #NULL if not present. The array is {@code mNumVertices} in size. Normals are undefined for point and line primitives. A mesh consisting of points and lines only may not have normal vectors. Meshes with mixed primitive types (i.e. lines and triangles) may have normals, but the normals for vertices that are only referenced by point or line primitives are undefined and set to {@code qNaN}. ${note(""" Normal vectors computed by Assimp are always unit-length. However, this needn't apply for normals that have been taken directly from the model file """)} """ ) nullable..aiVector3D.p( "mTangents", """ Vertex tangents. The tangent of a vertex points in the direction of the positive X texture axis. The array contains normalized vectors, #NULL if not present. The array is {@code mNumVertices} in size. A mesh consisting of points and lines only may not have normal vectors. Meshes with mixed primitive types (i.e. lines and triangles) may have normals, but the normals for vertices that are only referenced by point or line primitives are undefined and set to {@code qNaN}. ${note("If the mesh contains tangents, it automatically also contains bitangents.")} """ ) nullable..aiVector3D.p( "mBitangents", """ Vertex bitangents. The bitangent of a vertex points in the direction of the positive Y texture axis. The array contains normalized vectors, #NULL if not present. The array is {@code mNumVertices} in size. ${note("If the mesh contains tangents, it automatically also contains bitangents.")} """ ) nullable..aiColor4D.p( "mColors", """ Vertex color sets. A mesh may contain 0 to #AI_MAX_NUMBER_OF_COLOR_SETS vertex colors per vertex. #NULL if not present. Each array is {@code mNumVertices} in size if present. """ )["AI_MAX_NUMBER_OF_COLOR_SETS"] nullable..aiVector3D.p( "mTextureCoords", """ Vertex texture coordinates, also known as UV channels. A mesh may contain 0 to #AI_MAX_NUMBER_OF_TEXTURECOORDS per vertex. #NULL if not present. The array is {@code mNumVertices} in size. """ )["AI_MAX_NUMBER_OF_TEXTURECOORDS"] unsigned_int( "mNumUVComponents", """ Specifies the number of components for a given UV channel. Up to three channels are supported (UVW, for accessing volume or cube maps). If the value is 2 for a given channel n, the component {@code p.z} of {@code mTextureCoords[n][p]} is set to 0.0f. If the value is 1 for a given channel, {@code p.y} is set to 0.0f, too. Note: 4D coordinates are not supported. """ )["AI_MAX_NUMBER_OF_TEXTURECOORDS"] aiFace.p( "mFaces", """ The faces the mesh is constructed from. Each face refers to a number of vertices by their indices. This array is always present in a mesh, its size is given in {@code mNumFaces}. If the #AI_SCENE_FLAGS_NON_VERBOSE_FORMAT is NOT set each face references an unique set of vertices. """ ) AutoSize("mBones", optional = true)..unsigned_int( "mNumBones", "The number of bones this mesh contains. Can be 0, in which case the {@code mBones} array is #NULL." ) aiBone.p.p( "mBones", "The bones of this mesh. A bone consists of a name by which it can be found in the frame hierarchy and a set of vertex weights." ) unsigned_int( "mMaterialIndex", """ The material used by this mesh. A mesh uses only a single material. If an imported model uses multiple materials, the import splits up the mesh. Use this value as index into the scene's material list. """ ) aiString( "mName", """ Name of the mesh. Meshes can be named, but this is not a requirement and leaving this field empty is totally fine. There are mainly three uses for mesh names: ${ul( "some formats name nodes and meshes independently.", """ importers tend to split meshes up to meet the one-material-per-mesh requirement. Assigning the same (dummy) name to each of the result meshes aids the caller at recovering the original mesh partitioning. """, "vertex animations refer to meshes by their names." )} """ ) AutoSize("mAnimMeshes", optional = true)..unsigned_int( "mNumAnimMeshes", "The number of attachment meshes. Note! Currently only works with Collada loader." ) aiAnimMesh.p.p( "mAnimMeshes", """ Attachment meshes for this mesh, for vertex-based animation. Attachment meshes carry replacement data for some of the mesh'es vertex components (usually positions, normals). Note! Currently only works with Collada loader. """ ) unsigned_int("mMethod", "Method of morphing when anim-meshes are specified.").links("MorphingMethod_\\w+") aiAABB("mAABB", "the bounding box") Check("AI_MAX_NUMBER_OF_TEXTURECOORDS")..nullable..aiString.p.p( "mTextureCoordsNames", "Vertex UV stream names. Pointer to array of size #AI_MAX_NUMBER_OF_TEXTURECOORDS." ) } val aiSkeletonBone = struct(Module.ASSIMP, "AISkeletonBone", nativeName = "struct aiSkeletonBone") { int("mParent", "the parent bone index, is -1 one if this bone represents the root bone") nullable..aiNode.p( "mArmature", """ The bone armature node - used for skeleton conversion. You must enable #Process_PopulateArmatureData to populate this. """ ) nullable..aiNode.p( "mNode", """ The bone node in the scene - used for skeleton conversion. You must enable #Process_PopulateArmatureData to populate this. """ ) AutoSize("mMeshId", "mWeights")..unsigned_int("mNumnWeights", "the number of weights"); aiMesh.p("mMeshId", "the mesh index, which will get influenced by the weight") aiVertexWeight.p("mWeights", "the influence weights of this bone, by vertex index") aiMatrix4x4( "mOffsetMatrix", """ Matrix that transforms from bone space to mesh space in bind pose. This matrix describes the position of the mesh in the local space of this bone when the skeleton was bound. Thus it can be used directly to determine a desired vertex position, given the world-space transform of the bone when animated, and the position of the vertex in mesh space. It is sometimes called an inverse-bind matrix, or inverse bind pose matrix. """ ) aiMatrix4x4("mLocalMatrix", "matrix that transforms the local bone in bind pose") } val aiSkeleton = struct(Module.ASSIMP, "AISkeleton", nativeName = "struct aiSkeleton") { aiString("mName", "") AutoSize("mBones")..unsigned_int("mNumBones", "") aiSkeletonBone.p.p("mBones", ""); } val aiUVTransform = struct(Module.ASSIMP, "AIUVTransform", nativeName = "struct aiUVTransform", mutable = false) { documentation = """ Defines how an UV channel is transformed. This is just a helper structure for the #_AI_MATKEY_UVTRANSFORM_BASE key. See its documentation for more details. Typically you'll want to build a matrix of this information. However, we keep separate scaling/translation/rotation values to make it easier to process and optimize UV transformations internally. """ aiVector2D("mTranslation", "Translation on the u and v axes. The default value is (0|0).") aiVector2D("mScaling", "Scaling on the u and v axes. The default value is (1|1).") float( "mRotation", "Rotation - in counter-clockwise direction. The rotation angle is specified in radians. The rotation center is 0.5f|0.5f. The default value 0.f." ) } val aiPropertyTypeInfo = "aiPropertyTypeInfo".enumType val aiMaterialProperty = struct(Module.ASSIMP, "AIMaterialProperty", nativeName = "struct aiMaterialProperty", mutable = false) { documentation = """ Data structure for a single material property. As a user, you'll probably never need to deal with this data structure. Just use the provided {@code aiGetMaterialXXX()} family of functions to query material properties easily. Processing them manually is faster, but it is not the recommended way. It isn't worth the effort. Material property names follow a simple scheme: ${codeBlock(""" $<name> ?<name> A public property, there must be corresponding AI_MATKEY_XXX define 2nd: Public, but ignored by the aiProcess_RemoveRedundantMaterials post-processing step. ~<name> A temporary property for internal use. """)} """ aiString("mKey", "Specifies the name of the property (key). Keys are generally case insensitive.") unsigned_int( "mSemantic", "Textures: Specifies their exact usage semantic. For non-texture properties, this member is always 0 (or, better-said, #TextureType_NONE)." ) unsigned_int("mIndex", "Textures: Specifies the index of the texture. For non-texture properties, this member is always 0.") AutoSize("mData")..unsigned_int("mDataLength", "Size of the buffer {@code mData} is pointing to, in bytes. This value may not be 0.") aiPropertyTypeInfo( "mType", """ Type information for the property. Defines the data layout inside the data buffer. This is used by the library internally to perform debug checks and to utilize proper type conversions. (It's probably a hacky solution, but it works.) """ ) char.p("mData", "Binary buffer to hold the property's value. The size of the buffer is always mDataLength.") } val aiMaterial = struct(Module.ASSIMP, "AIMaterial", nativeName = "struct aiMaterial") { documentation = """ Data structure for a material. Material data is stored using a key-value structure. A single key-value pair is called a 'material property'. C++ users should use the provided member functions of {@code aiMaterial} to process material properties, C users have to stick with the {@code aiMaterialGetXXX} family of unbound functions. The library defines a set of standard keys (AI_MATKEY_XXX). """ aiMaterialProperty.p.p("mProperties", "List of all material properties loaded.") AutoSize("mProperties")..unsigned_int("mNumProperties", "Number of properties in the data base") unsigned_int("mNumAllocated", "Storage allocated") } val aiQuaternion = struct(Module.ASSIMP, "AIQuaternion", nativeName = "struct aiQuaternion") { documentation = "Represents a quaternion in a 4D vector." float("w", "The w component") float("x", "The x component") float("y", "The y component") float("z", "The z component") } val aiVectorKey = struct(Module.ASSIMP, "AIVectorKey", nativeName = "struct aiVectorKey") { documentation = "A time-value pair specifying a certain 3D vector for the given time." double("mTime", "The time of this key") aiVector3D("mValue", "The value of this key") } val aiQuatKey = struct(Module.ASSIMP, "AIQuatKey", nativeName = "struct aiQuatKey") { documentation = "A time-value pair specifying a rotation for the given time. Rotations are expressed with quaternions." double("mTime", "The time of this key") aiQuaternion("mValue", "The value of this key") } val aiMeshKey = struct(Module.ASSIMP, "AIMeshKey", nativeName = "struct aiMeshKey") { documentation = "Binds a anim mesh to a specific point in time." double("mTime", "The time of this key") unsigned_int( "mValue", """ Index into the ##AIMesh{@code ::mAnimMeshes} array of the mesh coresponding to the ##AIMeshAnim hosting this key frame. The referenced anim mesh is evaluated according to the rules defined in the docs for ##AIAnimMesh. """ ) } val aiMeshMorphKey = struct(Module.ASSIMP, "AIMeshMorphKey", nativeName = "struct aiMeshMorphKey") { documentation = "Binds a morph anim mesh to a specific point in time." double("mTime", "the time of this key") unsigned_int.p("mValues", "the values at the time of this key") double.p("mWeights", "the weights at the time of this key") AutoSize("mValues", "mWeights")..unsigned_int("mNumValuesAndWeights", "the number of values and weights") } val aiAnimBehaviour = "aiAnimBehaviour".enumType val aiNodeAnim = struct(Module.ASSIMP, "AINodeAnim", nativeName = "struct aiNodeAnim") { documentation = """ Describes the animation of a single node. The name specifies the bone/node which is affected by this animation channel. The keyframes are given in three separate series of values, one each for position, rotation and scaling. The transformation matrix computed from these values replaces the node's original transformation matrix at a specific time. This means all keys are absolute and not relative to the bone default pose. The order in which the transformations are applied is - as usual - scaling, rotation, translation. <h5>Note:</h5> All keys are returned in their correct, chronological order. Duplicate keys don't pass the validation step. Most likely there will be no negative time values, but they are not forbidden also ( so implementations need to cope with them! ) """ aiString("mNodeName", "The name of the node affected by this animation. The node must exist and it must be unique.") AutoSize("mPositionKeys", optional = true)..unsigned_int("mNumPositionKeys", "The number of position keys") aiVectorKey.p( "mPositionKeys", """ The position keys of this animation channel. Positions are specified as 3D vector. The array is {@code mNumPositionKeys} in size. If there are position keys, there will also be at least one scaling and one rotation key. """ ) AutoSize("mRotationKeys", optional = true)..unsigned_int("mNumRotationKeys", "The number of rotation keys") aiQuatKey.p( "mRotationKeys", """ The rotation keys of this animation channel. Rotations are given as quaternions, which are 4D vectors. The array is {@code mNumRotationKeys} in size. If there are rotation keys, there will also be at least one scaling and one position key. """ ) AutoSize("mScalingKeys", optional = true)..unsigned_int("mNumScalingKeys", "The number of scaling keys") aiVectorKey.p( "mScalingKeys", """ The scaling keys of this animation channel. Scalings are specified as 3D vector. The array is {@code mNumScalingKeys} in size. If there are scaling keys, there will also be at least one position and one rotation key. """ ) aiAnimBehaviour( "mPreState", """ Defines how the animation behaves before the first key is encountered. The default value is aiAnimBehaviour_DEFAULT (the original transformation matrix of the affected node is used). """ ).links("AnimBehaviour_\\w+") aiAnimBehaviour( "mPostState", """ Defines how the animation behaves after the last key was processed. The default value is aiAnimBehaviour_DEFAULT (the original transformation matrix of the affected node is taken). """ ).links("AnimBehaviour_\\w+") } val aiMeshAnim = struct(Module.ASSIMP, "AIMeshAnim", nativeName = "struct aiMeshAnim") { documentation = """ Describes vertex-based animations for a single mesh or a group of meshes. Meshes carry the animation data for each frame in their ##AIMesh{@code ::mAnimMeshes} array. The purpose of {@code aiMeshAnim} is to define keyframes linking each mesh attachment to a particular point in time. """ aiString( "mName", """ Name of the mesh to be animated. An empty string is not allowed, animated meshes need to be named (not necessarily uniquely, the name can basically serve as wildcard to select a group of meshes with similar animation setup) """) AutoSize("mKeys")..unsigned_int("mNumKeys", "Size of the {@code mKeys} array. Must be 1, at least.") aiMeshKey.p("mKeys", "Key frames of the animation. May not be #NULL.") } val aiMeshMorphAnim = struct(Module.ASSIMP, "AIMeshMorphAnim", nativeName = "struct aiMeshMorphAnim") { documentation = "Describes a morphing animation of a given mesh." aiString( "mName", """ Name of the mesh to be animated. An empty string is not allowed, animated meshes need to be named (not necessarily uniquely, the name can basically serve as wildcard to select a group of meshes with similar animation setup). """) AutoSize("mKeys")..unsigned_int("mNumKeys", "Size of the {@code mKeys} array. Must be 1, at least.") aiMeshMorphKey.p("mKeys", "Key frames of the animation. May not be #NULL.") } val aiAnimation = struct(Module.ASSIMP, "AIAnimation", nativeName = "struct aiAnimation") { documentation = """ An animation consists of keyframe data for a number of nodes. For each node affected by the animation a separate series of data is given. """ aiString( "mName", """ The name of the animation. If the modeling package this data was exported from does support only a single animation channel, this name is usually empty (length is zero). """ ) double("mDuration", "Duration of the animation in ticks.") double("mTicksPerSecond", "Ticks per second. 0 if not specified in the imported file") AutoSize("mChannels", optional = true)..unsigned_int("mNumChannels", "The number of bone animation channels. Each channel affects a single node.") aiNodeAnim.p.p("mChannels", "The node animation channels. Each channel affects a single node. The array is {@code mNumChannels} in size.") AutoSize("mMeshChannels", optional = true)..unsigned_int( "mNumMeshChannels", "The number of mesh animation channels. Each channel affects a single mesh and defines vertex-based animation." ) aiMeshAnim.p.p("mMeshChannels", "The mesh animation channels. Each channel affects a single mesh. The array is {@code mNumMeshChannels} in size.") AutoSize("mMorphMeshChannels", optional = true)..unsigned_int( "mNumMorphMeshChannels", "the number of mesh animation channels. Each channel affects a single mesh and defines morphing animation." ) aiMeshMorphAnim.p.p( "mMorphMeshChannels", "the morph mesh animation channels. Each channel affects a single mesh. The array is {@code mNumMorphMeshChannels} in size." ) } val aiLightSourceType = "aiLightSourceType".enumType val aiLight = struct(Module.ASSIMP, "AILight", nativeName = "struct aiLight", mutable = false) { documentation = """ Helper structure to describe a light source. Assimp supports multiple sorts of light sources, including directional, point and spot lights. All of them are defined with just a single structure and distinguished by their parameters. Note - some file formats (such as 3DS, ASE) export a "target point" - the point a spot light is looking at (it can even be animated). Assimp writes the target point as a sub-node of a spot-lights's main node, called "&lt;spotName&gt;.Target". However, this is just additional information then, the transformation tracks of the main node make the spot light already point in the right direction. """ aiString( "mName", """ The name of the light source. There must be a node in the scene-graph with the same name. This node specifies the position of the light in the scene hierarchy and can be animated. """ ) aiLightSourceType( "mType", "The type of the light source. #LightSource_UNDEFINED is not a valid value for this member." ).links("LightSource_(?!UNDEFINED)\\w+") aiVector3D( "mPosition", """ Position of the light source in space. Relative to the transformation of the node corresponding to the light. The position is undefined for directional lights. """ ) aiVector3D( "mDirection", """ Direction of the light source in space. Relative to the transformation of the node corresponding to the light. The direction is undefined for point lights. The vector may be normalized, but it needn't. """ ) aiVector3D( "mUp", """ Up direction of the light source in space. Relative to the transformation of the node corresponding to the light. The direction is undefined for point lights. The vector may be normalized, but it needn't. """ ) float( "mAttenuationConstant", """ Constant light attenuation factor. The intensity of the light source at a given distance 'd' from the light's position is {@code Atten = 1/( att0 + att1 * d + att2 * d*d)}. This member corresponds to the att0 variable in the equation. Naturally undefined for directional lights. """ ) float( "mAttenuationLinear", """ Linear light attenuation factor. The intensity of the light source at a given distance 'd' from the light's position is {@code Atten = 1/( att0 + att1 * d + att2 * d*d)}. This member corresponds to the att1 variable in the equation. Naturally undefined for directional lights. """ ) float( "mAttenuationQuadratic", """ Quadratic light attenuation factor. The intensity of the light source at a given distance 'd' from the light's position is {@code Atten = 1/( att0 + att1 * d + att2 * d*d)}. This member corresponds to the att2 variable in the equation. Naturally undefined for directional lights. """ ) aiColor3D( "mColorDiffuse", """ Diffuse color of the light source. The diffuse light color is multiplied with the diffuse material color to obtain the final color that contributes to the diffuse shading term. """ ) aiColor3D( "mColorSpecular", """ Specular color of the light source. The specular light color is multiplied with the specular material color to obtain the final color that contributes to the specular shading term. """ ) aiColor3D( "mColorAmbient", """ Ambient color of the light source. The ambient light color is multiplied with the ambient material color to obtain the final color that contributes to the ambient shading term. Most renderers will ignore this value it, is just a remaining of the fixed-function pipeline that is still supported by quite many file formats. """ ) float( "mAngleInnerCone", """ Inner angle of a spot light's light cone. The spot light has maximum influence on objects inside this angle. The angle is given in radians. It is 2PI for point lights and undefined for directional lights. """ ) float( "mAngleOuterCone", """ Outer angle of a spot light's light cone. The spot light does not affect objects outside this angle. The angle is given in radians. It is 2PI for point lights and undefined for directional lights. The outer angle must be greater than or equal to the inner angle. It is assumed that the application uses a smooth interpolation between the inner and the outer cone of the spot light. """ ) aiVector2D("mSize", "Size of area light source.") } val aiCamera = struct(Module.ASSIMP, "AICamera", nativeName = "struct aiCamera") { documentation = """ Helper structure to describe a virtual camera. Cameras have a representation in the node graph and can be animated. An important aspect is that the camera itself is also part of the scenegraph. This means, any values such as the look-at vector are not *absolute*, they're <b>relative</b> to the coordinate system defined by the node which corresponds to the camera. This allows for camera animations. For static cameras parameters like the 'look-at' or 'up' vectors are usually specified directly in {@code aiCamera}, but beware, they could also be encoded in the node transformation. """ aiString( "mName", """ The name of the camera. There must be a node in the scenegraph with the same name. This node specifies the position of the camera in the scene hierarchy and can be animated. """ ) aiVector3D("mPosition", "Position of the camera relative to the coordinate space defined by the corresponding node. The default value is 0|0|0.") aiVector3D( "mUp", """ 'Up' - vector of the camera coordinate system relative to the coordinate space defined by the corresponding node. The 'right' vector of the camera coordinate system is the cross product of the up and lookAt vectors. The default value is 0|1|0. The vector may be normalized, but it needn't. """ ) aiVector3D( "mLookAt", """ 'LookAt' - vector of the camera coordinate system relative to the coordinate space defined by the corresponding node. This is the viewing direction of the user. The default value is {@code 0|0|1}. The vector may be normalized, but it needn't. """ ) float( "mHorizontalFOV", """ Horizontal field of view angle, in radians. The field of view angle is the angle between the center line of the screen and the left or right border. The default value is {@code 1/4PI}. """ ) float( "mClipPlaneNear", """ Distance of the near clipping plane from the camera. The value may not be 0.f (for arithmetic reasons to prevent a division through zero). The default value is 0.1f. """ ) float( "mClipPlaneFar", """Distance of the far clipping plane from the camera. The far clipping plane must, of course, be further away than the near clipping plane. The default value is 1000.f. The ratio between the near and the far plane should not be too large (between 1000-10000 should be ok) to avoid floating-point inaccuracies which could lead to z-fighting. """ ) float( "mAspect", """ Screen aspect ratio. This is the ration between the width and the height of the screen. Typical values are 4/3, 1/2 or 1/1. This value is 0 if the aspect ratio is not defined in the source file. 0 is also the default value. """ ) float( "mOrthographicWidth", """ Half horizontal orthographic width, in scene units. The orthographic width specifies the half width of the orthographic view box. If non-zero the camera is orthographic and the {@code mAspect} should define to the ratio between the orthographic width and height and {@code mHorizontalFOV} should be set to 0. The default value is 0 (not orthographic). """ ) } val aiScene = struct(Module.ASSIMP, "AIScene", nativeName = "struct aiScene") { documentation = """ The root structure of the imported data. Everything that was imported from the given file can be accessed from here. Objects of this class are generally maintained and owned by Assimp, not by the caller. You shouldn't want to instance it, nor should you ever try to delete a given scene on your own. """ unsigned_int( "mFlags", """ Any combination of the AI_SCENE_FLAGS_XXX flags. By default this value is 0, no flags are set. Most applications will want to reject all scenes with the AI_SCENE_FLAGS_INCOMPLETE bit set. """ ).links("AI_SCENE_FLAGS_\\w+", LinkMode.BITFIELD) nullable..aiNode.p( "mRootNode", """ The root node of the hierarchy. There will always be at least the root node if the import was successful (and no special flags have been set). Presence of further nodes depends on the format and content of the imported file. """ ) AutoSize("mMeshes", optional = true)..unsigned_int("mNumMeshes", "The number of meshes in the scene.") aiMesh.p.p( "mMeshes", """ The array of meshes. Use the indices given in the ##AINode structure to access this array. The array is {@code mNumMeshes} in size. If the #AI_SCENE_FLAGS_INCOMPLETE flag is not set there will always be at least ONE material. """ ) AutoSize("mMaterials", optional = true)..unsigned_int("mNumMaterials", "The number of materials in the scene.") aiMaterial.p.p( "mMaterials", """ The array of materials. Use the index given in each ##AIMesh structure to access this array. The array is {@code mNumMaterials} in size. If the #AI_SCENE_FLAGS_INCOMPLETE flag is not set there will always be at least ONE material. """ ) AutoSize("mAnimations", optional = true)..unsigned_int("mNumAnimations", "The number of animations in the scene.") aiAnimation.p.p( "mAnimations", "The array of animations. All animations imported from the given file are listed here. The array is {@code mNumAnimations} in size." ) AutoSize("mTextures", optional = true)..unsigned_int("mNumTextures", "The number of textures embedded into the file") aiTexture.p.p( "mTextures", """ The array of embedded textures. Not many file formats embed their textures into the file. An example is Quake's MDL format (which is also used by some GameStudio versions) """ ) AutoSize("mLights", optional = true)..unsigned_int( "mNumLights", "The number of light sources in the scene. Light sources are fully optional, in most cases this attribute will be 0" ) aiLight.p.p( "mLights", "The array of light sources. All light sources imported from the given file are listed here. The array is {@code mNumLights} in size." ) AutoSize("mCameras", optional = true)..unsigned_int( "mNumCameras", "The number of cameras in the scene. Cameras are fully optional, in most cases this attribute will be 0" ) aiCamera.p.p( "mCameras", """ The array of cameras. All cameras imported from the given file are listed here. The array is {@code mNumCameras} in size. The first camera in the array (if existing) is the default camera view into the scene. """ ) nullable..aiMetadata.p( "mMetaData", """ The global metadata assigned to the scene itself. This data contains global metadata which belongs to the scene like unit-conversions, versions, vendors or other model-specific data. This can be used to store format-specific metadata as well. """ ) aiString("mName", "The name of the scene itself.") unsigned_int("mNumSkeletons", "") aiSkeleton.p.p("mSkeletons", "") char.p("mPrivate", "Internal use only, do not touch!").private() } val aiReturn = "aiReturn".enumType val aiTextureType = "aiTextureType".enumType val aiTextureMapping = "aiTextureMapping".enumType val aiTextureOp = "aiTextureOp".enumType val aiTextureMapMode = "aiTextureMapMode".enumType val aiImporterDesc = struct(Module.ASSIMP, "AIImporterDesc", nativeName = "struct aiImporterDesc") { documentation = """ Meta information about a particular importer. Importers need to fill this structure, but they can freely decide how talkative they are. A common use case for loader meta info is a user interface in which the user can choose between various import/export file formats. Building such an UI by hand means a lot of maintenance as importers / exporters are added to Assimp, so it might be useful to have a common mechanism to query some rough importer characteristics. """ charASCII.const.p("mName", "Full name of the importer (i.e. Blender3D importer)") charUTF8.const.p("mAuthor", "Original author (left blank if unknown or whole assimp team)") charUTF8.const.p("mMaintainer", "Current maintainer, left blank if the author maintains") charUTF8.const.p("mComments", "Implementation comments, i.e. unimplemented features") unsigned_int("mFlags", "These flags indicate some characteristics common to many importers.") unsigned_int("mMinMajor", "Minimum major format that can be loaded in major.minor style.") unsigned_int("mMinMinor", "Minimum minor format that can be loaded in major.minor style.") unsigned_int("mMaxMajor", "Maximum major format that can be loaded in major.minor style.") unsigned_int("mMaxMinor", "Maximum minor format that can be loaded in major.minor style.") charASCII.const.p( "mFileExtensions", """ List of file extensions this importer can handle. List entries are separated by space characters. All entries are lower case without a leading dot (i.e. "xml dae" would be a valid value. Note that multiple importers may respond to the same file extension - assimp calls all importers in the order in which they are registered and each importer gets the opportunity to load the file until one importer "claims" the file. Apart from file extension checks, importers typically use other methods to quickly reject files (i.e. magic words) so this does not mean that common or generic file extensions such as XML would be tediously slow. """ ) } private val _aiFile = struct(Module.ASSIMP, "AIFile", nativeName = "struct aiFile") private val _aiFileIO = struct(Module.ASSIMP, "AIFileIO", nativeName = "struct aiFileIO") val aiFileWriteProc = Module.ASSIMP.callback { size_t( "AIFileWriteProc", "File write procedure.", _aiFile.p("pFile", "file pointer to write to"), char.const.p("pBuffer", "the buffer to be written"), size_t("memB", "size of the individual element to be written"), size_t("count", "number of elements to be written"), returnDoc = "the number of elements written", nativeType = "aiFileWriteProc" ) } val aiFileReadProc = Module.ASSIMP.callback { size_t( "AIFileReadProc", "File read procedure", _aiFile.p("pFile", "file pointer to read from"), char.p("pBuffer", "the buffer to read the values"), size_t("size", "size in bytes of each element to be read"), size_t("count", "number of elements to be read"), returnDoc = "the number of elements read", nativeType = "aiFileReadProc" ) } val aiFileTellProc = Module.ASSIMP.callback { size_t( "AIFileTellProc", "File tell procedure.", _aiFile.p("pFile", "file pointer to query"), returnDoc = "the current file position", nativeType = "aiFileTellProc" ) } val aiFileFlushProc = Module.ASSIMP.callback { void( "AIFileFlushProc", "File flush procedure.", _aiFile.p("pFile", "file pointer to flush"), nativeType = "aiFileFlushProc" ) } val aiOrigin = "aiOrigin".enumType val aiFileSeek = Module.ASSIMP.callback { aiReturn( "AIFileSeek", "File seek procedure", _aiFile.p("pFile", "file pointer to seek"), size_t("offset", "number of bytes to shift from origin"), aiOrigin("origin", "position used as reference for the offset"), returnDoc = "an {@code aiReturn} value", nativeType = "aiFileSeek" ) } val aiFileOpenProc = Module.ASSIMP.callback { _aiFile.p( "AIFileOpenProc", "File open procedure", _aiFileIO.p("pFileIO", "{@code FileIO} pointer"), charUTF8.const.p("fileName", "name of the file to be opened"), charUTF8.const.p("openMode", "mode in which to open the file"), returnDoc = "pointer to an ##AIFile structure, or #NULL if the file could not be opened", nativeType = "aiFileOpenProc", ) } val aiFileCloseProc = Module.ASSIMP.callback { void( "AIFileCloseProc", "File close procedure", _aiFileIO.p("pFileIO", "{@code FileIO} pointer"), _aiFile.p("pFile", "file pointer to close"), nativeType = "aiFileCloseProc" ) } val aiUserData = typedef(opaque_p, "aiUserData") val aiFileIO = struct(Module.ASSIMP, "AIFileIO", nativeName = "struct aiFileIO") { documentation = """ Provided are functions to open and close files. Supply a custom structure to the import function. If you don't, a default implementation is used. Use custom file systems to enable reading from other sources, such as ZIPs or memory locations. """ aiFileOpenProc("OpenProc", "Function used to open a new file") aiFileCloseProc("CloseProc", "Function used to close an existing file") nullable..aiUserData("UserData", "User-defined, opaque data") } val aiFile = struct(Module.ASSIMP, "AIFile", nativeName = "struct aiFile") { documentation = """ Actually, it's a data structure to wrap a set of fXXXX (e.g fopen) replacement functions. The default implementation of the functions utilizes the fXXX functions from the CRT. However, you can supply a custom implementation to Assimp by delivering a custom ##AIFileIO. Use this to enable reading from other sources, such as ZIP archives or memory locations. """ aiFileReadProc("ReadProc", "Callback to read from a file") aiFileWriteProc("WriteProc", "Callback to write to a file") aiFileTellProc("TellProc", "Callback to retrieve the current position of the file cursor (ftell())") aiFileTellProc("FileSizeProc", "Callback to retrieve the size of the file, in bytes") aiFileSeek("SeekProc", "Callback to set the current position of the file cursor (fseek())") aiFileFlushProc("FlushProc", "Callback to flush the file contents") nullable..aiUserData("UserData", "User-defined, opaque data") } val aiLogStreamCallback = Module.ASSIMP.callback { void( "AILogStreamCallback", "Callback to be called for log stream messages", charUTF8.const.p("message", "The message to be logged"), Unsafe..nullable..char.p("user", "The user data from the log stream"), nativeType = "aiLogStreamCallback" ) } val aiLogStream = struct(Module.ASSIMP, "AILogStream", nativeName = "struct aiLogStream") { documentation = "Represents a log stream. A log stream receives all log messages and streams them somewhere" aiLogStreamCallback("callback", "callback to be called") nullable..char.p("user", "user data to be passed to the callback") } val aiPropertyStore = struct(Module.ASSIMP, "AIPropertyStore", nativeName = "struct aiPropertyStore") { documentation = "Represents an opaque set of settings to be used during importing." char("sentinel", "") } val aiBool = typedef(intb, "aiBool") val aiDefaultLogStream = "aiDefaultLogStream".enumType val aiExportFormatDesc = struct(Module.ASSIMP, "AIExportFormatDesc", nativeName = "struct aiExportFormatDesc") { documentation = """ Describes an file format which Assimp can export to. Use #GetExportFormatCount() to learn how many export-formats are supported by the current Assimp-build and #GetExportFormatDescription() to retrieve the description of the export format option. """ charUTF8.const.p( "id", """ a short string ID to uniquely identify the export format. Use this ID string to specify which file format you want to export to when calling #ExportScene(). Example: "dae" or "obj" """ ) charUTF8.const.p( "description", "A short description of the file format to present to users. Useful if you want to allow the user to select an export format." ) charUTF8.const.p("fileExtension", "Recommended file extension for the exported file in lower case.") } private val _aiExportDataBlob = struct(Module.ASSIMP, "AIExportDataBlob", nativeName = "struct aiExportDataBlob") val aiExportDataBlob = struct(Module.ASSIMP, "AIExportDataBlob", nativeName = "struct aiExportDataBlob") { documentation = """ Describes a blob of exported scene data. Use #ExportSceneToBlob() to create a blob containing an exported scene. The memory referred by this structure is owned by Assimp. to free its resources. Don't try to free the memory on your side - it will crash for most build configurations due to conflicting heaps. Blobs can be nested - each blob may reference another blob, which may in turn reference another blob and so on. This is used when exporters write more than one output file for a given ##AIScene. See the remarks for {@code aiExportDataBlob::name} for more information. """ AutoSize("data")..size_t("size", "Size of the data in bytes") void.p("data", "The data.") aiString( "name", """ Name of the blob. An empty string always indicates the first (and primary) blob, which contains the actual file data. Any other blobs are auxiliary files produced by exporters (i.e. material files). Existence of such files depends on the file format. Most formats don't split assets across multiple files. If used, blob names usually contain the file extension that should be used when writing the data to disc. The blob names generated can be influenced by setting the #AI_CONFIG_EXPORT_BLOB_NAME export property to the name that is used for the master blob. All other names are typically derived from the base name, by the file format exporter. """ ) nullable.._aiExportDataBlob.p("next", "Pointer to the next blob in the chain or NULL if there is none.") }
bsd-3-clause
dimagi/commcare-android
app/instrumentation-tests/src/org/commcare/androidTests/FormFilteringTest.kt
1
3012
package org.commcare.androidTests import androidx.test.espresso.Espresso import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.commcare.annotations.BrowserstackTests import org.commcare.utils.InstrumentationUtility import org.commcare.utils.areDisplayed import org.commcare.utils.doesNotExist import org.commcare.utils.isDisplayed import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest @BrowserstackTests class FormFilteringTest: BaseTest() { companion object { const val CCZ_NAME = "test_select_filters.ccz" const val APP_NAME = "Test: Select Filters" } @Before fun setup() { installApp(APP_NAME, CCZ_NAME) } @Test fun testFilter_usingCaseData() { val forms = arrayOf("Placeholder", "Case Data Filterable Form") InstrumentationUtility.login("test_filter", "123") matchCases() onView(withText("Select A")) .perform(click()) forms.areDisplayed() Espresso.pressBack() onView(withText("Select B")) .perform(click()) forms.areDisplayed() Espresso.pressBack() onView(withText("Select C")) .perform(click()) withText("Placeholder").isDisplayed() withText("Case Data Filterable Form").doesNotExist() } @Test fun testFilter_usingUserData() { val forms = arrayOf("Placeholder", "Case Data Filterable Form", "User Filterable Form") InstrumentationUtility.login("test_filters_user_data", "123") matchCases() onView(withText("Select A")) .perform(click()) forms.areDisplayed() Espresso.pressBack() onView(withText("Select B")) .perform(click()) forms.areDisplayed() Espresso.pressBack() onView(withText("Select C")) .perform(click()) withText("Placeholder").isDisplayed() withText("Case Data Filterable Form").doesNotExist() withText("User Filterable Form").isDisplayed() } @Test fun testFilter_usingUserData_withoutCase() { InstrumentationUtility.login("test_filter_without_case", "123") onView(withText("Start")) .perform(click()) onView(withText("Filter Tests")) .perform(click()) withText("Select A").doesNotExist() withText("Select B").isDisplayed() withText("Select C").isDisplayed() } private fun matchCases() { val cases = arrayOf("Select A", "Select B", "Select C") onView(withText("Start")) .perform(click()) onView(withText("Selection Tests")) .perform(click()) cases.areDisplayed() } }
apache-2.0
emoji-gen/Emoji-Android
lib-emoji/src/main/java/moe/pine/emoji/lib/emoji/model/Font.kt
1
267
package moe.pine.emoji.lib.emoji.model import com.google.gson.annotations.SerializedName /** * Model for font * Created by pine on May 7, 2017. */ data class Font( @SerializedName("name") val name: String, @SerializedName("key") val key: String )
mit
google/android-fhir
engine/src/main/java/com/google/android/fhir/search/filter/TokenParamFilterCriterion.kt
1
4091
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.search.filter import ca.uhn.fhir.rest.gclient.TokenClientParam import com.google.android.fhir.search.ConditionParam import com.google.android.fhir.search.Operation import com.google.android.fhir.search.SearchDslMarker import org.hl7.fhir.r4.model.CodeType import org.hl7.fhir.r4.model.CodeableConcept import org.hl7.fhir.r4.model.Coding import org.hl7.fhir.r4.model.ContactPoint import org.hl7.fhir.r4.model.Identifier import org.hl7.fhir.r4.model.UriType /** * Represents a criterion for filtering [TokenClientParam]. e.g. filter(Patient.GENDER, { value = * of(CodeType("male")) }) */ @SearchDslMarker data class TokenParamFilterCriterion(var parameter: TokenClientParam) : FilterCriterion { var value: TokenFilterValue? = null /** Returns [TokenFilterValue] from [Boolean]. */ fun of(boolean: Boolean) = TokenFilterValue().apply { tokenFilters.add(TokenParamFilterValueInstance(code = boolean.toString())) } /** Returns [TokenFilterValue] from [String]. */ fun of(string: String) = TokenFilterValue().apply { tokenFilters.add(TokenParamFilterValueInstance(code = string)) } /** Returns [TokenFilterValue] from [UriType]. */ fun of(uriType: UriType) = TokenFilterValue().apply { tokenFilters.add(TokenParamFilterValueInstance(code = uriType.value)) } /** Returns [TokenFilterValue] from [CodeType]. */ fun of(codeType: CodeType) = TokenFilterValue().apply { tokenFilters.add(TokenParamFilterValueInstance(code = codeType.value)) } /** Returns [TokenFilterValue] from [Coding]. */ fun of(coding: Coding) = TokenFilterValue().apply { tokenFilters.add(TokenParamFilterValueInstance(uri = coding.system, code = coding.code)) } /** Returns [TokenFilterValue] from [CodeableConcept]. */ fun of(codeableConcept: CodeableConcept) = TokenFilterValue().apply { codeableConcept.coding.forEach { tokenFilters.add(TokenParamFilterValueInstance(uri = it.system, code = it.code)) } } /** Returns [TokenFilterValue] from [Identifier]. */ fun of(identifier: Identifier) = TokenFilterValue().apply { tokenFilters.add( TokenParamFilterValueInstance(uri = identifier.system, code = identifier.value) ) } /** Returns [TokenFilterValue] from [ContactPoint]. */ fun of(contactPoint: ContactPoint) = TokenFilterValue().apply { tokenFilters.add( TokenParamFilterValueInstance(uri = contactPoint.use?.toCode(), code = contactPoint.value) ) } override fun getConditionalParams() = value!!.tokenFilters.map { ConditionParam( "index_value = ? ${ if (it.uri.isNullOrBlank()) "" else "AND IFNULL(index_system,'') = ?" }", listOfNotNull(it.code, it.uri) ) } } @SearchDslMarker class TokenFilterValue internal constructor() { internal val tokenFilters = mutableListOf<TokenParamFilterValueInstance>() } /** * A structure like [CodeableConcept] may contain multiple [Coding] values each of which will be a * filter value. We use [TokenParamFilterValueInstance] to represent individual filter value. */ @SearchDslMarker internal data class TokenParamFilterValueInstance(var uri: String? = null, var code: String) internal data class TokenParamFilterCriteria( var parameter: TokenClientParam, override val filters: List<TokenParamFilterCriterion>, override val operation: Operation, ) : FilterCriteria(filters, operation, parameter, "TokenIndexEntity")
apache-2.0
code-disaster/lwjgl3
modules/lwjgl/opencl/src/templates/kotlin/opencl/templates/khr_mipmap_image.kt
4
763
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opencl.templates import org.lwjgl.generator.* import opencl.* val khr_mipmap_image = "KHRMipmapImage".nativeClassCL("khr_mipmap_image", KHR) { documentation = """ Native bindings to the $extensionName extension. This extension adds support to create a mip-mapped image, enqueue commands to read/write/copy/map a region of a mipmapped image and built-in functions that can be used to read a mip-mapped image in an OpenCL C program. """ IntConstant( "cl_sampler_info", "SAMPLER_MIP_FILTER_MODE_KHR"..0x1155, "SAMPLER_LOD_MIN_KHR"..0x1156, "SAMPLER_LOD_MAX_KHR"..0x1157 ) }
bsd-3-clause
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/suggestededits/ImageRecsFragment.kt
1
24980
package org.wikipedia.suggestededits import android.content.pm.ActivityInfo import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.GradientDrawable import android.icu.text.ListFormatter import android.net.Uri import android.os.Build import android.os.Bundle import android.os.SystemClock import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.View.* import android.view.ViewGroup import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import androidx.core.widget.NestedScrollView import androidx.palette.graphics.Palette import com.google.android.material.bottomsheet.BottomSheetBehavior import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.activity.FragmentUtil import org.wikipedia.analytics.ImageRecommendationsFunnel import org.wikipedia.analytics.eventplatform.ImageRecommendationsEvent import org.wikipedia.auth.AccountUtil import org.wikipedia.commons.FilePageActivity import org.wikipedia.databinding.FragmentSuggestedEditsImageRecommendationItemBinding import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.SiteMatrix import org.wikipedia.dataclient.page.PageSummary import org.wikipedia.dataclient.restbase.ImageRecommendationResponse import org.wikipedia.history.HistoryEntry import org.wikipedia.page.PageActivity import org.wikipedia.page.PageTitle import org.wikipedia.settings.Prefs import org.wikipedia.suggestededits.provider.EditingSuggestionsProvider import org.wikipedia.util.* import org.wikipedia.util.log.L import org.wikipedia.views.FaceAndColorDetectImageView import org.wikipedia.views.ImageZoomHelper import org.wikipedia.views.ViewAnimations import java.util.* class ImageRecsFragment : SuggestedEditsItemFragment(), ImageRecsDialog.Callback { private var _binding: FragmentSuggestedEditsImageRecommendationItemBinding? = null private val binding get() = _binding!! private var publishing = false private var publishSuccess = false private var recommendation: ImageRecommendationResponse? = null private var recommendationSequence = 0 private val funnel = ImageRecommendationsFunnel() private var startMillis = 0L private var buttonClickedMillis = 0L private var infoClicked = false private var detailsClicked = false private var scrolled = false private lateinit var bottomSheetBehavior: BottomSheetBehavior<CoordinatorLayout> override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) _binding = FragmentSuggestedEditsImageRecommendationItemBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT recommendationSequence = Prefs.getImageRecsItemSequence() Prefs.setImageRecsItemSequence(recommendationSequence + 1) binding.cardItemErrorView.backClickListener = OnClickListener { requireActivity().finish() } binding.cardItemErrorView.retryClickListener = OnClickListener { binding.cardItemProgressBar.visibility = VISIBLE binding.cardItemErrorView.visibility = GONE getNextItem() } binding.cardItemErrorView.nextClickListener = OnClickListener { callback().nextPage(this) } val transparency = 0xd8000000 binding.publishOverlayContainer.setBackgroundColor(transparency.toInt() or (ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color) and 0xffffff)) binding.publishOverlayContainer.visibility = GONE binding.publishBackgroundView.alpha = if (WikipediaApp.getInstance().currentTheme.isDark) 0.3f else 0.1f binding.imageCard.elevation = 0f binding.imageCard.strokeColor = ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_border_color) binding.imageCard.strokeWidth = DimenUtil.roundedDpToPx(0.5f) binding.acceptButton.setOnClickListener { buttonClickedMillis = SystemClock.uptimeMillis() doPublish(ImageRecommendationsFunnel.RESPONSE_ACCEPT, emptyList()) } binding.rejectButton.setOnClickListener { buttonClickedMillis = SystemClock.uptimeMillis() ImageRecsDialog.newInstance(ImageRecommendationsFunnel.RESPONSE_REJECT) .show(childFragmentManager, null) } binding.notSureButton.setOnClickListener { buttonClickedMillis = SystemClock.uptimeMillis() ImageRecsDialog.newInstance(ImageRecommendationsFunnel.RESPONSE_NOT_SURE) .show(childFragmentManager, null) } binding.imageCard.setOnClickListener { recommendation?.let { startActivity(FilePageActivity.newIntent(requireActivity(), PageTitle("File:" + it.image, WikiSite(Service.COMMONS_URL)), false, getSuggestionReason())) detailsClicked = true } } binding.imageCard.setOnLongClickListener { if (ImageZoomHelper.isZooming) { // Dispatch a fake CANCEL event to the container view, so that the long-press ripple is cancelled. binding.imageCard.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)) } false } binding.articleContentContainer.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, _, _, _ -> scrolled = true }) binding.readMoreButton.setOnClickListener { recommendation?.let { val title = PageTitle(it.pageTitle, WikipediaApp.getInstance().wikiSite) startActivity(PageActivity.newIntentForNewTab(requireActivity(), HistoryEntry(title, HistoryEntry.SOURCE_SUGGESTED_EDITS), title)) } } ImageZoomHelper.setViewZoomable(binding.imageView) binding.dailyProgressView.setMaximum(DAILY_COUNT_TARGET) bottomSheetBehavior = BottomSheetBehavior.from(binding.bottomSheetCoordinatorLayout).apply { state = BottomSheetBehavior.STATE_EXPANDED } getNextItem() updateContents(null) } override fun onResume() { super.onResume() startMillis = SystemClock.uptimeMillis() } override fun onStart() { super.onStart() callback().updateActionButton() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun maybeShowTooltipSequence() { binding.root.post { if (!isResumed || !isAdded) { return@post } if (Prefs.shouldShowImageRecsOnboarding()) { Prefs.setShowImageRecsOnboarding(false) val balloon = FeedbackUtil.getTooltip(requireContext(), getString(R.string.image_recommendations_tooltip1), autoDismiss = true, showDismissButton = true) balloon.showAlignBottom(binding.articleTitlePlaceholder) balloon.relayShowAlignBottom(FeedbackUtil.getTooltip(requireContext(), getString(R.string.image_recommendations_tooltip2), autoDismiss = true, showDismissButton = true), binding.instructionText) .relayShowAlignBottom(FeedbackUtil.getTooltip(requireContext(), getString(R.string.image_recommendations_tooltip3), autoDismiss = true, showDismissButton = true), binding.acceptButton) } } } private fun getNextItem() { if (recommendation != null) { return } disposables.add(EditingSuggestionsProvider.getNextArticleWithMissingImage(WikipediaApp.getInstance().appOrSystemLanguageCode, recommendationSequence) .subscribeOn(Schedulers.io()) .flatMap { recommendation = it ServiceFactory.get(WikipediaApp.getInstance().wikiSite).getInfoByPageId(recommendation!!.pageId.toString()) } .flatMap { recommendation!!.pageTitle = it.query()!!.firstPage()!!.displayTitle(WikipediaApp.getInstance().appOrSystemLanguageCode) if (recommendation!!.pageTitle.isEmpty()) { throw ThrowableUtil.EmptyException() } ServiceFactory.getRest(WikipediaApp.getInstance().wikiSite).getSummary(null, recommendation!!.pageTitle).subscribeOn(Schedulers.io()) } .observeOn(AndroidSchedulers.mainThread()) .retry(10) .subscribe({ summary -> updateContents(summary) }, { this.setErrorState(it) })) } private fun setErrorState(t: Throwable) { L.e(t) recommendation = null binding.cardItemErrorView.setError(t) binding.cardItemErrorView.visibility = VISIBLE binding.cardItemProgressBar.visibility = GONE binding.articleContentContainer.visibility = GONE binding.imageSuggestionContainer.visibility = GONE } private fun updateContents(summary: PageSummary?) { binding.cardItemErrorView.visibility = GONE binding.articleContentContainer.visibility = if (recommendation != null) VISIBLE else GONE binding.imageSuggestionContainer.visibility = GONE binding.readMoreButton.visibility = GONE binding.cardItemProgressBar.visibility = VISIBLE if (recommendation == null || summary == null) { return } disposables.add((if (siteInfoList == null) ServiceFactory.get(WikiSite(Service.COMMONS_URL)).siteMatrix .subscribeOn(Schedulers.io()) .map { siteInfoList = SiteMatrix.getSites(it) siteInfoList!! } else Observable.just(siteInfoList!!)) .flatMap { ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getImageInfo("File:" + recommendation!!.image, WikipediaApp.getInstance().appOrSystemLanguageCode) .subscribeOn(Schedulers.io()) } .observeOn(AndroidSchedulers.mainThread()) .retry(5) .subscribe({ response -> binding.cardItemProgressBar.visibility = GONE val imageInfo = response.query()!!.firstPage()!!.imageInfo()!! binding.articleTitle.text = StringUtil.fromHtml(summary.displayTitle) binding.articleDescription.text = summary.description binding.articleExtract.text = StringUtil.fromHtml(summary.extractHtml).trim() binding.readMoreButton.visibility = VISIBLE binding.imageView.loadImage(Uri.parse(ImageUrlUtil.getUrlForPreferredSize(imageInfo.thumbUrl, Constants.PREFERRED_CARD_THUMBNAIL_SIZE)), roundedCorners = false, cropped = false, listener = object : FaceAndColorDetectImageView.OnImageLoadListener { override fun onImageLoaded(palette: Palette, bmpWidth: Int, bmpHeight: Int) { if (isAdded) { var color1 = palette.getLightVibrantColor(ContextCompat.getColor(requireContext(), R.color.base70)) var color2 = palette.getLightMutedColor(ContextCompat.getColor(requireContext(), R.color.base30)) if (WikipediaApp.getInstance().currentTheme.isDark) { color1 = ResourceUtil.darkenColor(color1) color2 = ResourceUtil.darkenColor(color2) } val gradientDrawable = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, arrayOf(color1, color2).toIntArray()) binding.imageViewContainer.background = gradientDrawable val params = binding.imageInfoButton.layoutParams as FrameLayout.LayoutParams val containerAspect = binding.imageViewContainer.width.toFloat() / binding.imageViewContainer.height.toFloat() val bmpAspect = bmpWidth.toFloat() / bmpHeight.toFloat() if (bmpAspect > containerAspect) { params.marginEnd = DimenUtil.roundedDpToPx(8f) } else { val width = binding.imageViewContainer.height.toFloat() * bmpAspect params.marginEnd = DimenUtil.roundedDpToPx(8f) + (binding.imageViewContainer.width / 2 - width.toInt() / 2) } binding.imageInfoButton.layoutParams = params } } override fun onImageFailed() {} }) binding.imageCaptionText.text = if (imageInfo.metadata == null) null else StringUtil.removeHTMLTags(imageInfo.metadata!!.imageDescription()) binding.articleScrollSpacer.post { if (isAdded) { binding.articleScrollSpacer.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, bottomSheetBehavior.peekHeight) // Collapse bottom sheet if the article title is not visible when loaded binding.suggestedEditsItemRootView.doViewsOverlap(binding.articleTitle, binding.bottomSheetCoordinatorLayout).run { if (this) { bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED } } } } val arr = imageInfo.commonsUrl.split('/') binding.imageFileNameText.text = StringUtil.removeUnderscores(UriUtil.decodeURL(arr[arr.size - 1])) binding.imageSuggestionReason.text = StringUtil.fromHtml(getString(R.string.image_recommendations_task_suggestion_reason, getSuggestionReason())) ViewAnimations.fadeIn(binding.imageSuggestionContainer) maybeShowTooltipSequence() }, { setErrorState(it) })) callback().updateActionButton() } override fun publish() { // the "Publish" button in our case is actually the "skip" button. callback().nextPage(this) } override fun onDialogSubmit(response: Int, selectedItems: List<Int>) { doPublish(response, selectedItems) } private fun doPublish(response: Int, reasons: List<Int>) { if (publishing || publishSuccess || recommendation == null) { return } // -- point of no return -- publishing = true publishSuccess = false binding.publishProgressCheck.visibility = GONE binding.publishOverlayContainer.visibility = VISIBLE binding.publishBoltView.visibility = GONE binding.publishProgressBar.visibility = VISIBLE funnel.logSubmit(WikipediaApp.getInstance().language().appLanguageCodes.joinToString(","), recommendation!!.pageTitle, recommendation!!.image, getFunnelReason(), response, reasons, detailsClicked, infoClicked, scrolled, buttonClickedMillis - startMillis, SystemClock.uptimeMillis() - startMillis, if (Prefs.isImageRecsConsentEnabled() && AccountUtil.isLoggedIn) AccountUtil.userName else null, Prefs.isImageRecsTeacherMode()) ImageRecommendationsEvent.logImageRecommendationInteraction(WikipediaApp.getInstance().language().appLanguageCodes.joinToString(","), recommendation!!.pageTitle, recommendation!!.image, getFunnelReason(), response, reasons, detailsClicked, infoClicked, scrolled, buttonClickedMillis - startMillis, SystemClock.uptimeMillis() - startMillis, if (Prefs.isImageRecsConsentEnabled() && AccountUtil.isLoggedIn) AccountUtil.userName else null, Prefs.isImageRecsTeacherMode()) publishSuccess = true onSuccess() } private fun onSuccess() { val pair = updateDailyCount(1) val oldCount = pair.first val newCount = pair.second Prefs.setImageRecsItemSequenceSuccess(recommendationSequence + 1) val waitUntilNextMillis = when (newCount) { DAILY_COUNT_TARGET -> 2500L else -> 1500L } val checkDelayMillis = 700L val checkAnimationDuration = 300L val progressText = when { newCount < DAILY_COUNT_TARGET -> getString(R.string.suggested_edits_image_recommendations_task_goal_progress) newCount == DAILY_COUNT_TARGET -> getString(R.string.suggested_edits_image_recommendations_task_goal_complete) else -> getString(R.string.suggested_edits_image_recommendations_task_goal_surpassed) } binding.dailyProgressView.update(oldCount, oldCount, DAILY_COUNT_TARGET, getString(R.string.image_recommendations_task_processing)) showConfetti(newCount == DAILY_COUNT_TARGET) updateNavBarColor(true) var progressCount = 0 binding.publishProgressBar.post(object : Runnable { override fun run() { if (isAdded) { if (binding.publishProgressBar.progress >= 100) { binding.dailyProgressView.update(oldCount, newCount, DAILY_COUNT_TARGET, progressText) binding.publishProgressCheck.alpha = 0f binding.publishProgressCheck.visibility = VISIBLE binding.publishProgressCheck.animate() .alpha(1f) .withEndAction { if (newCount >= DAILY_COUNT_TARGET) { binding.publishProgressCheck.postDelayed({ if (isAdded) { binding.publishProgressBar.visibility = INVISIBLE binding.publishProgressCheck.visibility = GONE binding.publishBoltView.visibility = VISIBLE } }, checkDelayMillis) } binding.publishProgressBar.postDelayed({ if (isAdded) { showConfetti(false) updateNavBarColor(false) binding.publishOverlayContainer.visibility = GONE callback().nextPage(this@ImageRecsFragment) callback().logSuccess() } }, waitUntilNextMillis + checkDelayMillis) } .duration = checkAnimationDuration } else { binding.publishProgressBar.progress = ++progressCount * 3 binding.publishProgressBar.post(this) } } } }) } private fun showConfetti(enable: Boolean) { binding.successConfettiImage.visibility = if (enable) VISIBLE else GONE if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Change statusBar and actionBar color requireActivity().window.statusBarColor = if (enable) ResourceUtil.getThemedColor(requireContext(), R.attr.color_group_70) else Color.TRANSPARENT (requireActivity() as AppCompatActivity).supportActionBar?.setBackgroundDrawable(if (enable) ColorDrawable(ResourceUtil.getThemedColor(requireContext(), R.attr.color_group_70)) else null) } // Update actionbar menu items requireActivity().window.decorView.findViewById<TextView>(R.id.menu_help).apply { visibility = if (enable) GONE else VISIBLE } (requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(!enable) } private fun updateNavBarColor(enable: Boolean) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Change navigationBar color requireActivity().window.navigationBarColor = if (enable) ResourceUtil.getThemedColor(requireContext(), R.attr.color_group_69) else Color.TRANSPARENT } } override fun publishEnabled(): Boolean { return true } override fun publishOutlined(): Boolean { return false } private fun getSuggestionReason(): String { val hasWikidata = recommendation!!.foundOnWikis.contains("wd") val langWikis = recommendation!!.foundOnWikis .sortedBy { WikipediaApp.getInstance().language().getLanguageCodeIndex(it) } .take(3) .mapNotNull { getCanonicalName(it) } if (langWikis.isNotEmpty()) { return getString(R.string.image_recommendations_task_suggestion_reason_wikilist, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ListFormatter.getInstance().format(langWikis) } else { langWikis.joinToString(separator = ", ") }) } else if (hasWikidata) { return getString(R.string.image_recommendations_task_suggestion_reason_wikidata) } return getString(R.string.image_recommendations_task_suggestion_reason_commons) } private fun getFunnelReason(): String { val hasWikidata = recommendation!!.foundOnWikis.contains("wd") val langWikis = recommendation!!.foundOnWikis.filter { it != "wd" && it != "com" && it != "species" } return when { langWikis.isNotEmpty() -> { "wikipedia" } hasWikidata -> { "wikidata" } else -> "commons" } } private fun getCanonicalName(code: String): String? { var canonicalName = siteInfoList?.find { it.code() == code }?.localName() if (canonicalName.isNullOrEmpty()) { canonicalName = WikipediaApp.getInstance().language().getAppLanguageCanonicalName(code) } return canonicalName } private fun callback(): Callback { return FragmentUtil.getCallback(this, Callback::class.java)!! } fun onInfoClicked() { infoClicked = true } companion object { private val SUPPORTED_LANGUAGES = arrayOf("ar", "arz", "bn", "cs", "de", "en", "es", "eu", "fa", "fr", "he", "hu", "hy", "it", "ko", "pl", "pt", "ru", "sr", "sv", "tr", "uk", "vi") private var siteInfoList: List<SiteMatrix.SiteInfo>? = null const val DAILY_COUNT_TARGET = 10 fun isFeatureEnabled(): Boolean { return AccountUtil.isLoggedIn && SUPPORTED_LANGUAGES.any { it == WikipediaApp.getInstance().appOrSystemLanguageCode } } fun updateDailyCount(increaseCount: Int = 0): Pair<Int, Int> { val day = Calendar.getInstance().get(Calendar.DAY_OF_YEAR) var oldCount = Prefs.getImageRecsDailyCount() if (day != Prefs.getImageRecsDayId()) { // it's a brand new day! Prefs.setImageRecsDayId(day) oldCount = 0 } val newCount = oldCount + increaseCount Prefs.setImageRecsDailyCount(newCount) return oldCount to newCount } fun newInstance(): SuggestedEditsItemFragment { return ImageRecsFragment() } } }
apache-2.0
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/effect/EffectType.kt
1
5608
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.effect import com.mcmoonlake.api.Valuable import com.mcmoonlake.api.adapter.AdapterBukkit import com.mcmoonlake.api.version.MinecraftVersion import org.bukkit.potion.PotionEffectType /** * * EffectType (效果类型) * * * Enum the type of effect in minecraft. * * 枚举在 Minecraft 中的效果类型. * * @see [AdapterBukkit] * @see [Valuable] * @author lgou2w * @since 2.0 */ enum class EffectType( /** * * The id of this effect type. * * 此效果类型的 Id. */ val id: Int, /** * * The type name of this effect type. * * 此效果类型的类型名称. */ val type: String, /** * * Supported versions for this effect type. * * 此效果类型支持的版本. */ val mcVer: MinecraftVersion? = null ) : AdapterBukkit<PotionEffectType>, Valuable<Int> { /** * * Effect Type: Speed. * * 效果类型: 速度. */ SPEED(1, "SPEED"), /** * * Effect Type: Slow. * * 效果类型: 缓慢. */ SLOW(2, "SLOW"), /** * * Effect Type: Fast Digging. * * 效果类型: 急迫. */ FAST_DIGGING(3, "FAST_DIGGING"), /** * * Effect Type: Slow Digging. * * 效果类型: 挖掘疲劳. */ SLOW_DIGGING(4, "SLOW_DIGGING"), /** * * Effect Type: Increase Damage. * * 效果类型: 力量. */ INCREASE_DAMAGE(5, "INCREASE_DAMAGE"), /** * * Effect Type: Heal. * * 效果类型: 瞬间治疗. */ HEAL(6, "HEAL"), /** * * Effect Type: Harm. * * 效果类型: 瞬间伤害. */ HARM(7, "HARM"), /** * * Effect Type: Jump. * * 效果类型: 跳跃提升. */ JUMP(8, "JUMP"), /** * * Effect Type: Confusion. * * 效果类型: 反胃. */ CONFUSION(9, "CONFUSION"), /** * * Effect Type: Regeneration. * * 效果类型: 生命恢复. */ REGENERATION(10, "REGENERATION"), /** * * Effect Type: Damage Resistance. * * 效果类型: 抗性提升. */ DAMAGE_RESISTANCE(11, "DAMAGE_RESISTANCE"), /** * * Effect Type: Fire Resistance. * * 效果类型: 防火. */ FIRE_RESISTANCE(12, "FIRE_RESISTANCE"), /** * * Effect Type: Water Breathing. * * 效果类型: 水下呼吸. */ WATER_BREATHING(13, "WATER_BREATHING"), /** * * Effect Type: Invisibility. * * 效果类型: 隐身. */ INVISIBILITY(14, "INVISIBILITY"), /** * * Effect Type: Blindness. * * 效果类型: 失明. */ BLINDNESS(15, "BLINDNESS"), /** * * Effect Type: Night Vision. * * 效果类型: 夜视. */ NIGHT_VISION(16, "NIGHT_VISION"), /** * * Effect Type: Hunger. * * 效果类型: 饥饿. */ HUNGER(17, "HUNGER"), /** * * Effect Type: Weakness. * * 效果类型: 虚弱. */ WEAKNESS(18, "WEAKNESS"), /** * * Effect Type: Poison. * * 效果类型: 中毒. */ POISON(19, "POISON"), /** * * Effect Type: Wither. * * 效果类型: 凋零. */ WITHER(20, "WITHER"), /** * * Effect Type: Health Boost. * * 效果类型: 生命提升. */ HEALTH_BOOST(21, "HEALTH_BOOST"), /** * * Effect Type: Absorption. * * 效果类型: 伤害吸收. */ ABSORPTION(22, "ABSORPTION"), /** * * Effect Type: Saturation. * * 效果类型: 饱和. */ SATURATION(23, "SATURATION"), /** * * Effect Type: Glowing. * * 效果类型: 发光. */ GLOWING(24, "GLOWING", MinecraftVersion.V1_9), /** * * Effect Type: Levitation. * * 效果类型: 漂浮. */ LEVITATION(25, "LEVITATION", MinecraftVersion.V1_9), /** * * Effect Type: Luck. * * 效果类型: 幸运. */ LUCK(26, "LUCK", MinecraftVersion.V1_9), /** * * Effect Type: Un Luck. * * 效果类型: 霉运. */ UNLUCK(27, "UNLUCK", MinecraftVersion.V1_9), ; override fun value(): Int = id override fun cast(): PotionEffectType = PotionEffectType.getByName(type) companion object { /** * * Get the effect type from the specified type name. * * 从指定类型名称获取效果类型. * * @param name Effect type. * @param name 效果类型名称. * @throws IllegalArgumentException If the given type name is invalid. * @throws IllegalArgumentException 如果给定的类型名称是无效的. */ @JvmStatic @JvmName("fromName") @Throws(IllegalArgumentException::class) fun fromName(name: String): EffectType = EffectType.valueOf(name.toUpperCase()) } }
gpl-3.0
meik99/CoffeeList
app/src/main/java/rynkbit/tk/coffeelist/contract/entity/Invoice.kt
1
277
package rynkbit.tk.coffeelist.contract.entity import java.util.* interface Invoice { val id: Int val customerId: Int? val customerName: String val itemId: Int? val itemName: String val itemPrice: Double val date: Date val state: InvoiceState }
mit
retomerz/intellij-community
platform/configuration-store-impl/src/StorageBaseEx.kt
1
3082
/* * 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 com.intellij.configurationStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.impl.stores.StateStorageBase import com.intellij.openapi.util.JDOMUtil import org.jdom.Element abstract class StorageBaseEx<T : Any> : StateStorageBase<T>() { fun <S : Any> createGetSession(component: PersistentStateComponent<S>, componentName: String, stateClass: Class<S>, reload: Boolean = false) = StateGetter(component, componentName, getStorageData(reload), stateClass, this) /** * serializedState is null if state equals to default (see XmlSerializer.serializeIfNotDefault) */ abstract fun archiveState(storageData: T, componentName: String, serializedState: Element?) } class StateGetter<S : Any, T : Any>(private val component: PersistentStateComponent<S>, private val componentName: String, private val storageData: T, private val stateClass: Class<S>, private val storage: StorageBaseEx<T>) { var serializedState: Element? = null fun getState(mergeInto: S? = null): S? { LOG.assertTrue(serializedState == null) serializedState = storage.getSerializedState(storageData, component, componentName, false) return storage.deserializeState(serializedState, stateClass, mergeInto) } fun close() { if (serializedState == null) { return } val stateAfterLoad: S? try { stateAfterLoad = component.state } catch (e: Throwable) { LOG.error("Cannot get state after load", e) stateAfterLoad = null } val serializedStateAfterLoad = if (stateAfterLoad == null) { serializedState } else { serializeState(stateAfterLoad)?.normalizeRootName().let { if (JDOMUtil.isEmpty(it)) null else it } } if (ApplicationManager.getApplication().isUnitTestMode && serializedState != serializedStateAfterLoad && (serializedStateAfterLoad == null || !JDOMUtil.areElementsEqual(serializedState, serializedStateAfterLoad))) { LOG.warn("$componentName state changed after load. \nOld: ${JDOMUtil.writeElement(serializedState!!)}\n\nNew: ${serializedStateAfterLoad?.let { JDOMUtil.writeElement(it) } ?: "null"}\n") } storage.archiveState(storageData, componentName, serializedStateAfterLoad) } }
apache-2.0