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 |
---|---|---|---|---|---|
tasomaniac/OpenLinkWith | resolver/src/main/kotlin/com/tasomaniac/openwith/util/IntentFixer.kt | 1 | 2049 | package com.tasomaniac.openwith.util
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import com.tasomaniac.openwith.extensions.extractAmazonASIN
object IntentFixer {
private val INTENT_FIXERS = arrayOf<Fixer>(
AmazonFixer()
)
@JvmStatic
fun fixIntents(context: Context, originalIntent: Intent): Intent {
var intent = originalIntent
for (intentFixer in INTENT_FIXERS) {
val fixedIntent = intentFixer.fix(context, intent)
if (context.packageManager.hasHandler(fixedIntent)) {
intent = fixedIntent
}
}
return intent
}
/**
* Queries on-device packages for a handler for the supplied [intent].
*/
private fun PackageManager.hasHandler(intent: Intent) = queryIntentActivities(intent, 0).isNotEmpty()
internal interface Fixer {
fun fix(context: Context, intent: Intent): Intent
}
private class AmazonFixer : Fixer {
/**
* If link contains amazon and it has ASIN in it, create a specific intent to open Amazon App.
*
* @param intent Original Intent with amazon link in it.
* @return Specific Intent for Amazon app.
*/
override fun fix(context: Context, intent: Intent): Intent {
val dataString = intent.dataString
if (dataString != null && dataString.contains("amazon")) {
val asin = extractAmazonASIN(dataString)
if (asin != null) {
return if ("0000000000" == asin) {
context.packageManager.getLaunchIntentForPackage(intent.component!!.packageName)!!
} else Intent(Intent.ACTION_VIEW).setDataAndType(
Uri.parse("mshop://featured?ASIN=$asin"),
"vnd.android.cursor.item/vnd.amazon.mShop.featured"
)
}
}
return intent
}
}
}
| apache-2.0 |
mike-neck/kuickcheck | example/src/test/kotlin/org/mikeneck/example/java/lang/ByteCheck.kt | 1 | 992 | /*
* Copyright 2016 Shinya Mochida
*
* Licensed under the Apache License,Version2.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.mikeneck.example.java.lang
import org.mikeneck.kuickcheck.Property
import org.mikeneck.kuickcheck.byte
import org.mikeneck.kuickcheck.forAll
class ByteCheck {
fun receive(b: Byte): Int {
return if (b < 0x10.toByte() || 0x1f.toByte() < b) -1
else 0
}
@Property
val `can receive From 0x10 To 0x1f` = forAll (byte(0x10, 0x1f)).satisfy { receive(it) == 0 }
}
| apache-2.0 |
spamdr/astroants | src/main/kotlin/cz/richter/david/astroants/parser/ConcurrentInputMapParser.kt | 1 | 1359 | package cz.richter.david.astroants.parser
import cz.richter.david.astroants.indexedArrayListSpliterator
import cz.richter.david.astroants.model.MapLocation
import cz.richter.david.astroants.model.InputMapSettings
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*
import java.util.stream.Collectors
import java.util.stream.StreamSupport
/**
* Implementation of [InputMapParser] which uses parallel stream processing to parse all [MapLocation]s from [String]s
* Usage of parallel stream allows for better scalability and bigger inputs to be parsed faster and more efficiently
*/
@Component
class ConcurrentInputMapParser @Autowired constructor(private val mapLocationParser: MapLocationParser) : InputMapParser {
override fun parse(inputMapSettings: InputMapSettings): List<MapLocation> {
val gridSize = Math.sqrt(inputMapSettings.areas.size.toDouble()).toInt()
return StreamSupport.stream(indexedArrayListSpliterator(inputMapSettings.areas.withIndex(), inputMapSettings.areas.size), true)
.map { mapLocationParser.parse(it.index % gridSize, it.index / gridSize, it.value) }
.sorted(Comparator.comparing { location: MapLocation -> location.x + location.y * gridSize })
.collect(Collectors.toList())
}
} | mit |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/segregated/AddCyclewaySegregation.kt | 1 | 1484 | package de.westnordost.streetcomplete.quests.segregated
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.ANYTHING_PAVED
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.ktx.toYesNo
class AddCyclewaySegregation : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
ways with
(
(highway = path and bicycle = designated and foot = designated)
or (highway = footway and bicycle = designated)
or (highway = cycleway and foot ~ designated|yes)
)
and surface ~ ${ANYTHING_PAVED.joinToString("|")}
and area != yes
and !sidewalk
and (!segregated or segregated older today -8 years)
"""
override val commitMessage = "Add segregated status for combined footway with cycleway"
override val wikiLink = "Key:segregated"
override val icon = R.drawable.ic_quest_path_segregation
override val isSplitWayEnabled = true
override fun getTitle(tags: Map<String, String>) = R.string.quest_segregated_title
override fun createForm() = AddCyclewaySegregationForm()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("segregated", answer.toYesNo())
}
}
| gpl-3.0 |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/xpath/XPathReverseStep.kt | 1 | 893 | /*
* Copyright (C) 2016, 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.ast.xpath
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xpm.optree.path.XpmPathStep
/**
* An XPath 2.0 and XQuery 1.0 `ReverseStep` node in the XQuery AST.
*/
interface XPathReverseStep : PsiElement, XpmPathStep
| apache-2.0 |
Ilya-Skiba/kotlin-boot | src/main/kotlin/by/kotlin/test/app/App.kt | 1 | 235 | package by.kotlin.test.app
import by.kotlin.test.app.config.BootApp
import org.springframework.boot.SpringApplication
fun main(args: Array<String>) {
println("Hello World!")
SpringApplication.run(BootApp::class.java, *args)
} | apache-2.0 |
rhdunn/xquery-intellij-plugin | src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/test/TestSuite.kt | 1 | 764 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.processor.test
interface TestSuite {
val name: String
val testCases: Sequence<TestCase>
val error: Throwable?
}
| apache-2.0 |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/theme/ThemeManager.kt | 1 | 3211 | package wangdaye.com.geometricweather.theme
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.graphics.Color
import android.util.TypedValue
import androidx.annotation.AttrRes
import androidx.appcompat.app.AppCompatDelegate
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.livedata.EqualtableLiveData
import wangdaye.com.geometricweather.common.basic.models.options.DarkMode
import wangdaye.com.geometricweather.settings.SettingsManager
import wangdaye.com.geometricweather.theme.weatherView.WeatherThemeDelegate
import wangdaye.com.geometricweather.theme.weatherView.materialWeatherView.MaterialWeatherThemeDelegate
class ThemeManager private constructor(
val weatherThemeDelegate: WeatherThemeDelegate,
var darkMode: DarkMode,
) {
companion object {
@Volatile
private var instance: ThemeManager? = null
@JvmStatic
fun getInstance(context: Context): ThemeManager {
if (instance == null) {
synchronized(ThemeManager::class) {
if (instance == null) {
instance = ThemeManager(
weatherThemeDelegate = MaterialWeatherThemeDelegate(),
darkMode = SettingsManager.getInstance(context).darkMode,
)
}
}
}
return instance!!
}
private fun generateGlobalUIMode(
darkMode: DarkMode
): Int = when (darkMode) {
DarkMode.LIGHT -> AppCompatDelegate.MODE_NIGHT_NO
DarkMode.DARK -> AppCompatDelegate.MODE_NIGHT_YES
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
}
val uiMode: EqualtableLiveData<Int> = EqualtableLiveData(
generateGlobalUIMode(darkMode = darkMode)
)
private val typedValue = TypedValue()
fun update(darkMode: DarkMode) {
this.darkMode = darkMode
uiMode.setValue(
generateGlobalUIMode(
darkMode = this.darkMode
)
)
}
fun getThemeColor(context: Context, @AttrRes id: Int): Int {
context.theme.resolveAttribute(id, typedValue, true)
return typedValue.data
}
@SuppressLint("ResourceType")
fun getThemeColors(context: Context, @AttrRes ids: IntArray): IntArray {
val a = context.theme.obtainStyledAttributes(ids)
val colors = ids.mapIndexed { index, _ ->
a.getColor(index, Color.TRANSPARENT)
}
a.recycle()
return colors.toIntArray()
}
fun generateThemeContext(
context: Context,
lightTheme: Boolean
): Context = context.createConfigurationContext(
Configuration(context.resources.configuration).apply {
uiMode = uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()
uiMode = uiMode or if (lightTheme) {
Configuration.UI_MODE_NIGHT_NO
} else {
Configuration.UI_MODE_NIGHT_YES
}
}
).apply {
setTheme(R.style.GeometricWeatherTheme)
}
} | lgpl-3.0 |
FelixKlauke/mercantor | client/src/main/kotlin/de/d3adspace/mercantor/client/util/RoundRobinList.kt | 1 | 935 | package de.d3adspace.mercantor.client.util
/**
* @author Felix Klauke <[email protected]>
*/
class RoundRobinList<ContentType>(private var content: MutableList<ContentType>) {
private var currentPosition: Int = 0
val isEmpty: Boolean
get() = content.isEmpty()
fun getContent(): List<ContentType> = content
fun setContent(content: MutableList<ContentType>) {
this.content = content
}
fun size(): Int = content.size
fun add(element: ContentType): Boolean = content.add(element)
fun remove(element: ContentType) = content.remove(element)
fun get(): ContentType {
if (content.isEmpty()) {
throw IllegalStateException("I don't have any elements.")
}
if (currentPosition == content.size) {
currentPosition = 0
}
val element = content[currentPosition]
currentPosition++
return element
}
}
| mit |
ScheNi/android-material-stepper | sample/src/main/java/com/stepstone/stepper/sample/step/view/StepViewSample.kt | 2 | 2228 | package com.stepstone.stepper.sample.step.view
import android.content.Context
import android.text.Html
import android.view.LayoutInflater
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.FrameLayout
import com.stepstone.stepper.Step
import com.stepstone.stepper.VerificationError
import com.stepstone.stepper.sample.OnNavigationBarListener
import com.stepstone.stepper.sample.R
/**
* Created by leonardo on 18/12/16.
*/
class StepViewSample(context: Context) : FrameLayout(context), Step {
companion object {
private const val TAP_THRESHOLD = 2
}
private var i = 0
private var onNavigationBarListener: OnNavigationBarListener? = null
private var button: Button? = null
init {
init(context)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val c = context
if (c is OnNavigationBarListener) {
this.onNavigationBarListener = c
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
this.onNavigationBarListener = null
}
@Suppress("DEPRECATION")
private fun init(context: Context) {
val v = LayoutInflater.from(context).inflate(R.layout.fragment_step, this, true)
button = v.findViewById(R.id.button) as Button
updateNavigationBar()
button = v.findViewById(R.id.button) as Button
button?.text = Html.fromHtml("Taps: <b>$i</b>")
button?.setOnClickListener {
button?.text = Html.fromHtml("Taps: <b>${++i}</b>")
updateNavigationBar()
}
}
private val isAboveThreshold: Boolean
get() = i >= TAP_THRESHOLD
override fun verifyStep(): VerificationError? {
return if (isAboveThreshold) null else VerificationError("Click ${TAP_THRESHOLD - i} more times!")
}
private fun updateNavigationBar() {
onNavigationBarListener?.onChangeEndButtonsEnabled(isAboveThreshold)
}
override fun onSelected() {
updateNavigationBar()
}
override fun onError(error: VerificationError) {
button?.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake_error))
}
}
| apache-2.0 |
apollostack/apollo-android | apollo-normalized-cache-api/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/CacheKey.kt | 1 | 658 | package com.apollographql.apollo3.cache.normalized
import kotlin.jvm.JvmField
import kotlin.jvm.JvmStatic
/**
* A key for a [Record] used for normalization in a [NormalizedCache].
* If the json object which the [Record] corresponds to does not have a suitable
* key, return use [NO_KEY].
*/
class CacheKey(val key: String) {
override fun equals(other: Any?): Boolean {
return key == (other as? CacheKey)?.key
}
override fun hashCode(): Int = key.hashCode()
override fun toString(): String = key
companion object {
@JvmField
val NO_KEY = CacheKey("")
@JvmStatic
fun from(key: String): CacheKey = CacheKey(key)
}
}
| mit |
almapp/uc-access-android-old | app/src/main/java/com/lopezjuri/uc_accesss/WebPageDetailFragment.kt | 1 | 2198 | package com.lopezjuri.uc_accesss
import android.app.Activity
import android.support.design.widget.CollapsingToolbarLayout
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.lopezjuri.uc_accesss.dummy.DummyContent
/**
* A fragment representing a single WebPage detail screen.
* This fragment is either contained in a [WebPageListActivity]
* in two-pane mode (on tablets) or a [WebPageDetailActivity]
* on handsets.
*/
class WebPageDetailFragment : Fragment() {
/**
* The dummy content this fragment is presenting.
*/
private var mItem: DummyContent.DummyItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments.containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = DummyContent.ITEM_MAP[arguments.getString(ARG_ITEM_ID)]
val activity = this.activity
val appBarLayout = activity.findViewById(R.id.toolbar_layout) as CollapsingToolbarLayout
if (appBarLayout != null) {
appBarLayout.title = mItem!!.content
}
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater!!.inflate(R.layout.webpage_detail, container, false)
// Show the dummy content as text in a TextView.
if (mItem != null) {
(rootView.findViewById(R.id.webpage_detail) as TextView).text = mItem!!.details
}
return rootView
}
companion object {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
val ARG_ITEM_ID = "item_id"
}
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
| gpl-3.0 |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingResponsePacket.kt | 1 | 1398 | package info.nightscout.androidaps.diaconn.packet
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.diaconn.DiaconnG8Pump
import info.nightscout.shared.logging.LTag
import javax.inject.Inject
/**
* SoundSettingResponsePacket
*/
class SoundSettingResponsePacket(
injector: HasAndroidInjector
) : DiaconnG8Packet(injector ) {
@Inject lateinit var diaconnG8Pump: DiaconnG8Pump
var result = 0
init {
msgType = 0x8D.toByte()
aapsLogger.debug(LTag.PUMPCOMM, "SoundSettingResponsePacket init")
}
override fun handleMessage(data: ByteArray?) {
val defectCheck = defect(data)
if (defectCheck != 0) {
aapsLogger.debug(LTag.PUMPCOMM, "SoundSettingResponsePacket Got some Error")
failed = true
return
} else failed = false
val bufferData = prefixDecode(data)
result = getByteToInt(bufferData)
if(!isSuccSettingResponseResult(result)) {
diaconnG8Pump.resultErrorCode = result
failed = true
return
}
diaconnG8Pump.otpNumber = getIntToInt(bufferData)
aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result")
aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}")
}
override fun getFriendlyName(): String {
return "PUMP_SOUND_SETTING_RESPONSE"
}
} | agpl-3.0 |
wesamhaboush/kotlin-algorithms | src/main/kotlin/algorithms/coded-triangle-words.kt | 1 | 1419 | package algorithms
import java.io.File
/*
Coded triangle numbers
Problem 42
The nth term of the sequence of triangle numbers is given by, t(n) = (1/2)(n)(n+1);
so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical position
and adding these values we form a word value. For example, the word value for SKY is
19 + 11 + 25 = 55 = t(10).
If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly
two-thousand common English words, how many are triangle words?
*/
fun readFile(): Sequence<String> =
File(ClassLoader.getSystemResource("p042_words.txt").file)
.bufferedReader()
.lineSequence()
fun fileAsWords(): Sequence<String> = readFile()
.flatMap { it.split(',').asSequence() }
fun letterToNumber(letter: Char): Int = letter.toLowerCase().toInt() - 96
fun wordToNumber(word: String): Int = word.map { letterToNumber(it) }.sum()
fun countNumberOfTriangularWords(): Int = fileAsWords()
.map { unquote(it) }
.filter { isTriangularNumber(wordToNumber(it).toLong()) }
// .onEach { println("word: $it, number: ${wordToNumber(it)}") }
.count()
fun unquote(word: String) = word.substring(1, word.length - 1)
| gpl-3.0 |
kvakil/venus | src/main/kotlin/venus/riscv/insts/sub.kt | 1 | 277 | package venus.riscv.insts
import venus.riscv.insts.dsl.RTypeInstruction
val sub = RTypeInstruction(
name = "sub",
opcode = 0b0110011,
funct3 = 0b000,
funct7 = 0b0100000,
eval32 = { a, b -> a - b },
eval64 = { a, b -> a - b }
)
| mit |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/favorite/FavoriteButton.kt | 1 | 1752 | package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.favorite
import android.content.Context
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.widget.ImageView
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.ui.dialogs.showExceptionDialog
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import javax.inject.Inject
abstract class FavoriteButton : ImageView, FavoriteButtonView {
constructor(context: Context) : super(context, null, R.attr.MirkoButtonStyle)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs, R.attr.MirkoButtonStyle)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@Inject lateinit var userManager : UserManagerApi
init {
WykopApp.uiInjector.inject(this)
setBackgroundResource(R.drawable.button_background_state_list)
isVisible = userManager.isUserAuthorized()
}
override var isFavorite : Boolean
get() = isSelected
set(value) {
if (value) {
isSelected = true
setImageDrawable(
ContextCompat.getDrawable(context, R.drawable.ic_favorite_selected)
)
} else {
isSelected = false
setImageDrawable(
ContextCompat.getDrawable(context, R.drawable.ic_favorite)
)
}
}
override fun showErrorDialog(e: Throwable) =
context.showExceptionDialog(e)
} | mit |
esqr/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/loginscreen/LoginScreenView.kt | 2 | 199 | package io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen
import io.github.feelfreelinux.wykopmobilny.base.BaseView
interface LoginScreenView : BaseView {
fun goBackToSplashScreen()
} | mit |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/navigationbar/NavigationBarModule.kt | 2 | 6923 | package abi44_0_0.expo.modules.navigationbar
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowInsets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsControllerCompat
import abi44_0_0.expo.modules.core.ExportedModule
import abi44_0_0.expo.modules.core.ModuleRegistry
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.errors.CurrentActivityNotFoundException
import abi44_0_0.expo.modules.core.interfaces.ActivityProvider
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
import abi44_0_0.expo.modules.core.interfaces.services.EventEmitter
class NavigationBarModule(context: Context) : ExportedModule(context) {
private lateinit var mActivityProvider: ActivityProvider
private lateinit var mEventEmitter: EventEmitter
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
?: throw IllegalStateException("Could not find implementation for ActivityProvider.")
mEventEmitter = moduleRegistry.getModule(EventEmitter::class.java) ?: throw IllegalStateException("Could not find implementation for EventEmitter.")
}
// Ensure that rejections are passed up to JS rather than terminating the native client.
private fun safeRunOnUiThread(promise: Promise, block: (activity: Activity) -> Unit) {
val activity = mActivityProvider.currentActivity
if (activity == null) {
promise.reject(CurrentActivityNotFoundException())
return
}
activity.runOnUiThread {
block(activity)
}
}
@ExpoMethod
fun setBackgroundColorAsync(color: Int, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBackgroundColor(it, color, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBackgroundColorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
val color = colorToHex(it.window.navigationBarColor)
promise.resolve(color)
}
}
@ExpoMethod
fun setBorderColorAsync(color: Int, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBorderColor(it, color, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBorderColorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val color = colorToHex(it.window.navigationBarDividerColor)
promise.resolve(color)
} else {
promise.reject(ERROR_TAG, "'getBorderColorAsync' is only available on Android API 28 or higher")
}
}
}
@ExpoMethod
fun setButtonStyleAsync(buttonStyle: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setButtonStyle(
it, buttonStyle,
{
promise.resolve(null)
},
{ m -> promise.reject(ERROR_TAG, m) }
)
}
}
@ExpoMethod
fun getButtonStyleAsync(promise: Promise) {
safeRunOnUiThread(promise) {
WindowInsetsControllerCompat(it.window, it.window.decorView).let { controller ->
val style = if (controller.isAppearanceLightNavigationBars) "dark" else "light"
promise.resolve(style)
}
}
}
@ExpoMethod
fun setVisibilityAsync(visibility: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setVisibility(it, visibility, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getVisibilityAsync(promise: Promise) {
safeRunOnUiThread(promise) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val visibility = if (it.window.decorView.rootWindowInsets.isVisible(WindowInsets.Type.navigationBars())) "visible" else "hidden"
promise.resolve(visibility)
} else {
// TODO: Verify this works
@Suppress("DEPRECATION") val visibility = if ((View.SYSTEM_UI_FLAG_HIDE_NAVIGATION and it.window.decorView.systemUiVisibility) == 0) "visible" else "hidden"
promise.resolve(visibility)
}
}
}
@ExpoMethod
fun setPositionAsync(position: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setPosition(it, position, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun unstable_getPositionAsync(promise: Promise) {
safeRunOnUiThread(promise) {
val position = if (ViewCompat.getFitsSystemWindows(it.window.decorView)) "relative" else "absolute"
promise.resolve(position)
}
}
@ExpoMethod
fun setBehaviorAsync(behavior: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBehavior(it, behavior, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBehaviorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
WindowInsetsControllerCompat(it.window, it.window.decorView).let { controller ->
val behavior = when (controller.systemBarsBehavior) {
// TODO: Maybe relative / absolute
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE -> "overlay-swipe"
WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE -> "inset-swipe"
// WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH -> "inset-touch"
else -> "inset-touch"
}
promise.resolve(behavior)
}
}
}
/* Events */
@ExpoMethod
fun startObserving(promise: Promise) {
safeRunOnUiThread(promise) {
val decorView = it.window.decorView
@Suppress("DEPRECATION")
decorView.setOnSystemUiVisibilityChangeListener { visibility: Int ->
var isNavigationBarVisible = (visibility and View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
var stringVisibility = if (isNavigationBarVisible) "visible" else "hidden"
mEventEmitter.emit(
VISIBILITY_EVENT_NAME,
Bundle().apply {
putString("visibility", stringVisibility)
putInt("rawVisibility", visibility)
}
)
}
promise.resolve(null)
}
}
@ExpoMethod
fun stopObserving(promise: Promise) {
safeRunOnUiThread(promise) {
val decorView = it.window.decorView
@Suppress("DEPRECATION")
decorView.setOnSystemUiVisibilityChangeListener(null)
promise.resolve(null)
}
}
companion object {
private const val NAME = "ExpoNavigationBar"
private const val VISIBILITY_EVENT_NAME = "ExpoNavigationBar.didChange"
private const val ERROR_TAG = "ERR_NAVIGATION_BAR"
fun colorToHex(color: Int): String {
return String.format("#%02x%02x%02x", Color.red(color), Color.green(color), Color.blue(color))
}
}
}
| bsd-3-clause |
notsyncing/lightfur | lightfur-integration-jdbc-ql/src/main/kotlin/io/github/notsyncing/lightfur/integration/jdbc/ql/JdbcRawQueryProcessor.kt | 1 | 1868 | package io.github.notsyncing.lightfur.integration.jdbc.ql
import io.github.notsyncing.lightfur.DataSession
import io.github.notsyncing.lightfur.entity.dsl.EntitySelectDSL
import io.github.notsyncing.lightfur.integration.jdbc.JdbcDataSession
import io.github.notsyncing.lightfur.ql.RawQueryProcessor
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.future.future
import java.sql.Array
import java.sql.ResultSet
import java.util.concurrent.CompletableFuture
class JdbcRawQueryProcessor : RawQueryProcessor {
private lateinit var db: JdbcDataSession
private fun currentRowToMap(rs: ResultSet): Map<String, Any?> {
val count = rs.metaData.columnCount
val map = mutableMapOf<String, Any?>()
for (i in 1..count) {
map.put(rs.metaData.getColumnLabel(i), rs.getObject(i))
}
return map
}
override fun resultSetToList(resultSet: Any?): List<Map<String, Any?>> {
if (resultSet is ResultSet) {
val list = mutableListOf<Map<String, Any?>>()
while (resultSet.next()) {
list.add(currentRowToMap(resultSet))
}
return list
} else {
throw UnsupportedOperationException("$resultSet is not an ${ResultSet::class.java}")
}
}
override fun processValue(value: Any?): Any? {
if (value is Array) {
return value.array
}
return value
}
override fun query(dsl: EntitySelectDSL<*>) = future {
db = DataSession.start()
try {
dsl.queryRaw(db).await()
} catch (e: Exception) {
e.printStackTrace()
db.end().await()
throw e
}
}
override fun end(): CompletableFuture<Unit> {
return db.end()
.thenApply { }
}
} | gpl-3.0 |
thatadamedwards/kotlin-koans | src/iv_properties/_32_Properties_.kt | 1 | 638 | package iv_properties
import util.TODO
import util.doc32
class PropertyExample {
var counter = 0
private var _propertyWithCounter: Int? = 0
var propertyWithCounter: Int?
get() = _propertyWithCounter
set(value) {
counter++
_propertyWithCounter = value
}
}
fun todoTask32(): Nothing = TODO(
"""
Task 32.
Add a custom setter to PropertyExample.propertyWithCounter so that
the 'counter' property is incremented every time 'propertyWithCounter' is assigned to.
""",
documentation = doc32(),
references = { PropertyExample() }
)
| mit |
ThoseGrapefruits/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustTraitMethodImplMixin.kt | 1 | 979 | package org.rust.lang.core.psi.impl.mixin
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.Iconable
import org.rust.lang.core.psi.RustTraitMethod
import org.rust.lang.core.psi.RustTypeMethod
import org.rust.lang.core.psi.impl.RustCompositeElementImpl
import org.rust.lang.icons.*
import javax.swing.Icon
abstract class RustTraitMethodImplMixin(node: ASTNode) : RustCompositeElementImpl(node), RustTraitMethod {
override fun getIcon(flags: Int): Icon? {
var icon = if (isAbstract()) RustIcons.ABSTRACT_METHOD else RustIcons.METHOD
if (isStatic())
icon = icon.addStaticMark()
if ((flags and Iconable.ICON_FLAG_VISIBILITY) == 0)
return icon;
return icon.addVisibilityIcon(isPublic())
}
fun isPublic(): Boolean {
return vis != null;
}
fun isAbstract(): Boolean {
return this is RustTypeMethod;
}
fun isStatic(): Boolean {
return self == null;
}
} | mit |
pyamsoft/pydroid | billing/src/main/java/com/pyamsoft/pydroid/billing/BillingInteractor.kt | 1 | 1036 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.billing
/** Abstracts the Play Store Billing client */
public interface BillingInteractor {
/** Get the list of SKU */
public suspend fun watchSkuList(onSkuListReceived: (BillingState, List<BillingSku>) -> Unit)
/** Watch for errors in the billing client */
public suspend fun watchErrors(onErrorReceived: (Throwable) -> Unit)
/** Refresh the SKU list */
public suspend fun refresh()
}
| apache-2.0 |
JetBrains/ideavim | src/test/java/ui/pages/WelcomeFrame.kt | 1 | 1529 | /*
* 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 ui.pages
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.data.RemoteComponent
import com.intellij.remoterobot.fixtures.CommonContainerFixture
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.fixtures.DefaultXpath
import com.intellij.remoterobot.fixtures.FixtureName
import com.intellij.remoterobot.search.locators.byXpath
import java.time.Duration
fun RemoteRobot.welcomeFrame(function: WelcomeFrame.() -> Unit) {
find(WelcomeFrame::class.java, Duration.ofSeconds(10)).apply(function)
}
@FixtureName("Welcome Frame")
@DefaultXpath("type", "//div[@class='FlatWelcomeFrame']")
class WelcomeFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) :
CommonContainerFixture(remoteRobot, remoteComponent) {
val createNewProjectLink
get() = actionLink(
byXpath(
"New Project",
"//div[(@class='MainButton' and @text='New Project') or (@accessiblename='New Project' and @class='JButton')]"
)
)
@Suppress("unused")
val moreActions
get() = button(byXpath("More Action", "//div[@accessiblename='More Actions' and @class='ActionButton']"))
@Suppress("unused")
val heavyWeightPopup
get() = remoteRobot.find(ComponentFixture::class.java, byXpath("//div[@class='HeavyWeightWindow']"))
}
| mit |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/prefs/language/LocalePickerListViewHolder.kt | 1 | 272 | package org.wordpress.android.ui.prefs.language
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
abstract class LocalePickerListViewHolder<T : ViewBinding>(protected val binding: T) :
RecyclerView.ViewHolder(binding.root)
| gpl-2.0 |
Turbo87/intellij-rust | src/main/kotlin/org/rust/lang/core/RustParserDefinition.kt | 1 | 1777 | package org.rust.lang.core
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import org.rust.lang.RustLanguage
import org.rust.lang.core.lexer.RustLexer
import org.rust.lang.core.lexer.RustTokenElementTypes
import org.rust.lang.core.lexer.RustTokenElementTypes.*
import org.rust.lang.core.parser.RustParser
import org.rust.lang.core.psi.RustCompositeElementTypes
import org.rust.lang.core.psi.impl.RustFileImpl
public class RustParserDefinition : ParserDefinition {
override fun createFile(viewProvider: FileViewProvider): PsiFile? =
RustFileImpl(viewProvider)
override fun spaceExistanceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements? {
// TODO(kudinkin): Fix
return ParserDefinition.SpaceRequirements.MUST
}
override fun getFileNodeType(): IFileElementType? = RustFileElementType
override fun getStringLiteralElements(): TokenSet =
TokenSet.create(STRING_LITERAL)
override fun getWhitespaceTokens(): TokenSet =
TokenSet.create(TokenType.WHITE_SPACE)
override fun getCommentTokens() = RustTokenElementTypes.COMMENTS_TOKEN_SET
override fun createElement(node: ASTNode?): PsiElement =
RustCompositeElementTypes.Factory.createElement(node)
override fun createLexer(project: Project?): Lexer = RustLexer()
override fun createParser(project: Project?): PsiParser = RustParser()
}
| mit |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/reader/services/discover/ReaderDiscoverService.kt | 1 | 2438 | package org.wordpress.android.ui.reader.services.discover
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import org.wordpress.android.WordPress
import org.wordpress.android.ui.reader.services.ServiceCompletionListener
import org.wordpress.android.ui.reader.services.discover.ReaderDiscoverLogic.DiscoverTasks
import org.wordpress.android.ui.reader.services.discover.ReaderDiscoverServiceStarter.ARG_DISCOVER_TASK
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T.READER
import org.wordpress.android.util.LocaleManager
import javax.inject.Inject
import javax.inject.Named
import kotlin.coroutines.CoroutineContext
/**
* Service which updates data for discover tab in Reader, relies on EventBus to notify of changes.
*/
class ReaderDiscoverService : Service(), ServiceCompletionListener, CoroutineScope {
@Inject @field:Named("IO_THREAD") lateinit var ioDispatcher: CoroutineDispatcher
private lateinit var readerDiscoverLogic: ReaderDiscoverLogic
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = ioDispatcher + job
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleManager.setLocale(newBase))
}
override fun onCreate() {
super.onCreate()
val component = (application as WordPress).component()
component.inject(this)
readerDiscoverLogic = ReaderDiscoverLogic(this, this, component)
AppLog.i(READER, "reader discover service > created")
}
override fun onDestroy() {
AppLog.i(READER, "reader discover service > destroyed")
job.cancel()
super.onDestroy()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null && intent.hasExtra(ARG_DISCOVER_TASK)) {
val task = intent.getSerializableExtra(ARG_DISCOVER_TASK) as DiscoverTasks
readerDiscoverLogic.performTasks(task, null)
}
return START_NOT_STICKY
}
override fun onCompleted(companion: Any?) {
AppLog.i(READER, "reader discover service > all tasks completed")
stopSelf()
}
}
| gpl-2.0 |
theScrabi/NewPipe | app/src/main/java/org/schabi/newpipe/ktx/OffsetDateTime.kt | 1 | 1045 | package org.schabi.newpipe.ktx
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.time.temporal.ChronoField
import java.util.Calendar
import java.util.Date
import java.util.GregorianCalendar
import java.util.TimeZone
// This method is a modified version of GregorianCalendar.from(ZonedDateTime).
// Math.addExact() and Math.multiplyExact() are desugared even though lint displays a warning.
@SuppressWarnings("NewApi")
fun OffsetDateTime.toCalendar(): Calendar {
val cal = GregorianCalendar(TimeZone.getTimeZone("UTC"))
val offsetDateTimeUTC = withOffsetSameInstant(ZoneOffset.UTC)
cal.gregorianChange = Date(Long.MIN_VALUE)
cal.firstDayOfWeek = Calendar.MONDAY
cal.minimalDaysInFirstWeek = 4
try {
cal.timeInMillis = Math.addExact(
Math.multiplyExact(offsetDateTimeUTC.toEpochSecond(), 1000),
offsetDateTimeUTC[ChronoField.MILLI_OF_SECOND].toLong()
)
} catch (ex: ArithmeticException) {
throw IllegalArgumentException(ex)
}
return cal
}
| gpl-3.0 |
mdaniel/intellij-community | platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/ModifiableRootModelBridgeTest.kt | 2 | 3965 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.ide
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.module.EmptyModuleType
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.impl.RootConfigurationAccessor
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.toBuilder
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
class ModifiableRootModelBridgeTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule(true)
@Test(expected = Test.None::class)
fun `removing module with modifiable model`() {
runWriteActionAndWait {
val module = projectModel.createModule()
val moduleRootManager = ModuleRootManager.getInstance(module) as ModuleRootComponentBridge
val diff = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.toBuilder()
val modifiableModel = moduleRootManager.getModifiableModel(diff,
RootConfigurationAccessor.DEFAULT_INSTANCE) as ModifiableRootModelBridge
(ModuleManager.getInstance(projectModel.project) as ModuleManagerBridgeImpl).getModifiableModel(diff).disposeModule(module)
modifiableModel.prepareForCommit()
modifiableModel.postCommit()
}
}
@Test(expected = Test.None::class)
fun `getting module root model from modifiable module`() {
runWriteActionAndWait {
val moduleModifiableModel = ModuleManager.getInstance(projectModel.project).getModifiableModel()
val newModule = moduleModifiableModel.newModule(projectModel.projectRootDir.resolve("myModule/myModule.iml"),
EmptyModuleType.EMPTY_MODULE) as ModuleBridge
val moduleRootManager = ModuleRootManager.getInstance(newModule) as ModuleRootComponentBridge
// Assert no exceptions
val model = moduleRootManager.getModifiableModel(newModule.diff!! as MutableEntityStorage,
RootConfigurationAccessor.DEFAULT_INSTANCE)
model.dispose()
moduleModifiableModel.dispose()
}
}
@Test(expected = Test.None::class)
fun `get modifiable models of renamed module`() {
runWriteActionAndWait {
val moduleModifiableModel = ModuleManager.getInstance(projectModel.project).getModifiableModel()
val newModule = moduleModifiableModel.newModule(projectModel.projectRootDir.resolve("myModule/myModule.iml"),
EmptyModuleType.EMPTY_MODULE) as ModuleBridge
moduleModifiableModel.commit()
val builder = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.toBuilder()
val anotherModifiableModel = (ModuleManager.getInstance(projectModel.project) as ModuleManagerBridgeImpl).getModifiableModel(builder)
anotherModifiableModel.renameModule(newModule, "newName")
val moduleRootManager = ModuleRootManager.getInstance(newModule) as ModuleRootComponentBridge
// Assert no exceptions
val model = moduleRootManager.getModifiableModel(builder, RootConfigurationAccessor.DEFAULT_INSTANCE)
anotherModifiableModel.dispose()
}
}
}
| apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/util/test-generator/test/org/jetbrains/kotlin/testGenerator/model/TAnnotation.kt | 6 | 1174 | // 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.testGenerator.model
sealed class TAnnotationValue {
companion object {
fun from(value: Any): TAnnotationValue {
return when (value) {
is String -> StringValue(value)
is Class<*> -> ClassValue(value)
else -> error("Unexpected annotation value: $value")
}
}
}
abstract fun render(): String
class StringValue(private val value: String): TAnnotationValue() {
override fun render() = '"' + value + '"'
}
class ClassValue(private val value: Class<*>): TAnnotationValue() {
override fun render() = value.simpleName + ".class"
}
}
class TAnnotation(className: String, val args: List<TAnnotationValue>) {
val simpleName = className.substringAfterLast('.')
}
@Suppress("TestFunctionName")
inline fun <reified T : Annotation> TAnnotation(vararg args: Any): TAnnotation {
return TAnnotation(T::class.java.name, args.map { TAnnotationValue.from(it) })
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/unifier/equivalence/expressions/calls/unresolved.kt | 13 | 108 | // DISABLE-ERRORS
fun foo() {
<selection>bar(1, 2)</selection>
bar(2, 1)
bar(1, 2)
bar(1)
}
| apache-2.0 |
ksmirenko/telegram-proger-bot | src/main/java/telegram/request/InputFile.kt | 1 | 678 | package telegram.request
import retrofit.mime.TypedFile
import java.io.File
class InputFile(mimeType : String, file : File) : TypedFile(mimeType, file) {
companion object {
fun photo(file : File) : InputFile {
return InputFile(InputFileBytes.PHOTO_MIME_TYPE, file)
}
fun audio(file : File) : InputFile {
return InputFile(InputFileBytes.AUDIO_MIME_TYPE, file)
}
fun video(file : File) : InputFile {
return InputFile(InputFileBytes.VIDEO_MIME_TYPE, file)
}
fun voice(file : File) : InputFile {
return InputFile(InputFileBytes.VOICE_MIME_TYPE, file)
}
}
}
| apache-2.0 |
SneakSpeak/sp-android | app/src/main/kotlin/io/sneakspeak/sneakspeak/adapters/UserListAdapter.kt | 1 | 1956 | package io.sneakspeak.sneakspeak.adapters
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.sneakspeak.sneakspeak.R
import io.sneakspeak.sneakspeak.activities.ChatActivity
import io.sneakspeak.sneakspeak.data.User
import kotlinx.android.synthetic.main.item_user.view.*
class UserListAdapter(ctx: Context) : RecyclerView.Adapter<UserListAdapter.ViewHolder>(),
View.OnClickListener {
val TAG = "UserListAdapter"
val context = ctx
class ViewHolder(userView: View) : RecyclerView.ViewHolder(userView) {
val name = userView.name
}
private var users: List<User>? = null
fun setUsers(userList: List<User>) {
users = userList
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val context = parent.context
val inflater = LayoutInflater.from(context)
// Inflate the custom layout
val userItem = inflater.inflate(R.layout.item_user, parent, false)
userItem.setOnClickListener(this)
// Return a new holder instance
return ViewHolder(userItem)
}
// Involves populating data into the item through holder
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
val user = users?.get(position)
with(viewHolder) {
name.text = user?.name
}
}
override fun getItemCount() = users?.size ?: 0
override fun onClick(view: View?) {
val name = view?.name ?: return
Log.d(TAG, name.text.toString())
val intent = Intent(context, ChatActivity::class.java)
val bundle = Bundle()
bundle.putString("name", name.text.toString())
intent.putExtras(bundle)
context.startActivity(intent)
}
}
| mit |
thaapasa/jalkametri-android | app/src/main/java/fi/tuska/jalkametri/gui/IconAdapter.kt | 1 | 1090 | package fi.tuska.jalkametri.gui
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import fi.tuska.jalkametri.R
import fi.tuska.jalkametri.dao.NamedIcon
import fi.tuska.jalkametri.gui.DrinkIconUtils.getDrinkIconRes
class IconAdapter<out T : NamedIcon>(c: Context, icons: List<T>, defaultIconRes: Int) :
NamedIconAdapter<T>(c, icons, defaultIconRes) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view: LinearLayout = convertView as LinearLayout? ?: (inflater().inflate(R.layout.icon_area, null) as LinearLayout).apply {
val size = resources.getDimension(R.dimen.icon_area_size).toInt()
layoutParams = ViewGroup.LayoutParams(size, size)
}
val imageView = view.findViewById(R.id.icon) as ImageView
val icon = getItem(position)
val res = getDrinkIconRes(icon.icon)
imageView.setImageResource(if (res != 0) res else defaultIconRes)
return view
}
}
| mit |
JavaEden/Orchid-Core | plugins/OrchidKotlindoc/src/mockKotlin/com/eden/orchid/mock/KotlinExceptionClass.kt | 2 | 217 | package com.eden.orchid.mock
/**
* This is the `TestKotlinException` comment text. It contains `code snippets`, **bold text tags**, and
* also **bold markdown things**.
*/
class KotlinExceptionClass : Exception()
| mit |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/store/sideeffect/StoreSideEffectHandler.kt | 1 | 1419 | package io.ipoli.android.store.sideeffect
import io.ipoli.android.common.AppSideEffectHandler
import io.ipoli.android.common.AppState
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.view.ColorPickerAction
import io.ipoli.android.common.view.IconPickerAction
import io.ipoli.android.player.usecase.BuyColorPackUseCase
import io.ipoli.android.player.usecase.BuyIconPackUseCase
import space.traversal.kapsule.required
object StoreSideEffectHandler : AppSideEffectHandler() {
private val buyColorPackUseCase by required { buyColorPackUseCase }
private val buyIconPackUseCase by required { buyIconPackUseCase }
override suspend fun doExecute(action: Action, state: AppState) {
when (action) {
is ColorPickerAction.BuyColorPack -> {
val result =
buyColorPackUseCase.execute(BuyColorPackUseCase.Params(action.colorPack))
dispatch(ColorPickerAction.BuyColorPackTransactionComplete(result))
}
is IconPickerAction.BuyIconPack -> {
val result =
buyIconPackUseCase.execute(BuyIconPackUseCase.Params(action.iconPack))
dispatch(IconPickerAction.BuyIconPackTransactionComplete(result))
}
}
}
override fun canHandle(action: Action) =
action is ColorPickerAction
|| action is IconPickerAction
} | gpl-3.0 |
GunoH/intellij-community | python/testSrc/com/jetbrains/env/debug/smokeTests/PythonDebuggerCythonSpeedupsTest.kt | 2 | 1050 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.env.debug
import com.jetbrains.env.PyEnvTestCase
import org.junit.Test
class PythonDebuggerCythonSpeedupsTest : PyEnvTestCase() {
@Test
fun `ensure speedups available`() {
runPythonTest(object : PyDebuggerTaskPython3Only("/debug", "test2.py") {
override fun testing() {
waitForOutput(USING_CYTHON_SPEEDUPS_MESSAGE)
}
// Printing of the debug message happens on early stages when the debugger command line
// is not parsed yet. Setting the environment variable forces the debug output print.
override fun getEnvs() = mapOf("PYCHARM_DEBUG" to "True")
})
}
companion object {
const val USING_CYTHON_SPEEDUPS_MESSAGE = "Using Cython speedups"
}
}
private open class PyDebuggerTaskPython3Only(relativeTestDataPath: String, scriptName: String)
: PyDebuggerTask(relativeTestDataPath, scriptName) {
override fun getTags() = setOf("-python2.7")
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/wordSelection/ClassMember3/1.kt | 13 | 133 | class C {
constructor()
init {
}
<selection><caret>fun</selection> foo() {
}
// comment
val bar = 1
} | apache-2.0 |
GunoH/intellij-community | platform/webSymbols/src/com/intellij/webSymbols/query/WebSymbolsQueryConfigurator.kt | 1 | 1269 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.webSymbols.query
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.webSymbols.WebSymbolsScope
import com.intellij.webSymbols.context.WebSymbolsContext
import com.intellij.webSymbols.context.WebSymbolsContextRulesProvider
/*
* DEPRECATION -> @JvmDefault
**/
@Suppress("DEPRECATION")
interface WebSymbolsQueryConfigurator {
fun getScope(project: Project, element: PsiElement?, context: WebSymbolsContext, allowResolve: Boolean): List<WebSymbolsScope> =
emptyList()
fun getContextRulesProviders(project: Project, dir: VirtualFile): List<WebSymbolsContextRulesProvider> =
emptyList()
fun getNameConversionRulesProviders(project: Project, element: PsiElement?, context: WebSymbolsContext): List<WebSymbolNameConversionRulesProvider> =
emptyList()
fun beforeQueryExecutorCreation(project: Project) {
}
companion object {
internal val EP_NAME = ExtensionPointName<WebSymbolsQueryConfigurator>("com.intellij.webSymbols.queryConfigurator")
}
} | apache-2.0 |
jk1/intellij-community | java/java-impl/src/com/intellij/codeInsight/hints/MethodChainHintsPassFactory.kt | 2 | 1397 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints
import com.intellij.codeHighlighting.TextEditorHighlightingPass
import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar
import com.intellij.openapi.components.AbstractProjectComponent
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
class MethodChainHintsPassFactory(project: Project, registrar: TextEditorHighlightingPassRegistrar) : AbstractProjectComponent(
project), TextEditorHighlightingPassFactory {
init {
registrar.registerTextEditorHighlightingPass(this, null, null, false, -1)
}
override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? {
if (editor.isOneLineMode
|| file !is PsiJavaFile
|| modificationStampHolder.isNotChanged(editor, file)) return null
return MethodChainHintsPass(modificationStampHolder, file, editor)
}
companion object {
val modificationStampHolder: ModificationStampHolder = ModificationStampHolder(Key.create("METHOD_CHAIN_PASS_LAST_MODIFICATION_TIMESTAMP"))
}
} | apache-2.0 |
walleth/kethereum | crypto_api/src/main/kotlin/org/kethereum/crypto/api/ec/ECDSASignature.kt | 1 | 130 | package org.kethereum.crypto.api.ec
import java.math.BigInteger
data class ECDSASignature(val r: BigInteger, val s: BigInteger)
| mit |
jonathanlermitage/tikione-c2e | src/main/kotlin/fr/tikione/c2e/core/model/web/Magazine.kt | 1 | 451 | package fr.tikione.c2e.core.model.web
/**
* CanardPC web magazine.
*/
class Magazine {
var number: String = ""
var title: String? = null
var login: String? = null
var edito: Edito? = null
var toc = ArrayList<TocCategory>()
var authorsPicture: Map<String, AuthorPicture> = HashMap()
override fun toString(): String {
return "Magazine(number=$number, title=$title, login=$login, edito=$edito, toc=$toc)"
}
}
| mit |
code-disaster/lwjgl3 | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_headless_surface.kt | 3 | 5606 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val EXT_headless_surface = "EXTHeadlessSurface".nativeClassVK("EXT_headless_surface", type = "instance", postfix = "EXT") {
documentation =
"""
The {@code VK_EXT_headless_surface} extension is an instance extension. It provides a mechanism to create {@code VkSurfaceKHR} objects independently of any window system or display device. The presentation operation for a swapchain created from a headless surface is by default a no-op, resulting in no externally-visible result.
Because there is no real presentation target, future extensions can layer on top of the headless surface to introduce arbitrary or customisable sets of restrictions or features. These could include features like saving to a file or restrictions to emulate a particular presentation target.
This functionality is expected to be useful for application and driver development because it allows any platform to expose an arbitrary or customisable set of restrictions and features of a presentation engine. This makes it a useful portable test target for applications targeting a wide range of presentation engines where the actual target presentation engines might be scarce, unavailable or otherwise undesirable or inconvenient to use for general Vulkan application development.
<h5>VK_EXT_headless_surface</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_headless_surface}</dd>
<dt><b>Extension Type</b></dt>
<dd>Instance extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>257</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link KHRSurface VK_KHR_surface} to be enabled</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Lisa Wu <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_headless_surface]%20@chengtianww%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_headless_surface%20extension*">chengtianww</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2019-03-21</dd>
<dt><b>IP Status</b></dt>
<dd>No known IP claims.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Ray Smith, Arm</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_HEADLESS_SURFACE_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"EXT_HEADLESS_SURFACE_EXTENSION_NAME".."VK_EXT_headless_surface"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_HEADLESS_SURFACE_CREATE_INFO_EXT".."1000256000"
)
VkResult(
"CreateHeadlessSurfaceEXT",
"""
Create a headless {@code VkSurfaceKHR} object.
<h5>C Specification</h5>
To create a headless {@code VkSurfaceKHR} object, call:
<pre><code>
VkResult vkCreateHeadlessSurfaceEXT(
VkInstance instance,
const VkHeadlessSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface);</code></pre>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code instance} <b>must</b> be a valid {@code VkInstance} handle</li>
<li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid ##VkHeadlessSurfaceCreateInfoEXT structure</li>
<li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid ##VkAllocationCallbacks structure</li>
<li>{@code pSurface} <b>must</b> be a valid pointer to a {@code VkSurfaceKHR} handle</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_OUT_OF_HOST_MEMORY</li>
<li>#ERROR_OUT_OF_DEVICE_MEMORY</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##VkAllocationCallbacks, ##VkHeadlessSurfaceCreateInfoEXT
""",
VkInstance("instance", "the instance to associate the surface with."),
VkHeadlessSurfaceCreateInfoEXT.const.p("pCreateInfo", "a pointer to a ##VkHeadlessSurfaceCreateInfoEXT structure containing parameters affecting the creation of the surface object."),
nullable..VkAllocationCallbacks.const.p("pAllocator", "the allocator used for host memory allocated for the surface object when there is no more specific allocator available (see <a target=\"_blank\" href=\"https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\\#memory-allocation\">Memory Allocation</a>)."),
Check(1)..VkSurfaceKHR.p("pSurface", "a pointer to a {@code VkSurfaceKHR} handle in which the created surface object is returned.")
)
} | bsd-3-clause |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/util/GithubApiUrlQueryBuilder.kt | 4 | 1120 | // 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.jetbrains.plugins.github.api.util
import com.intellij.util.io.URLUtil
import org.jetbrains.plugins.github.api.requests.GithubRequestPagination
@DslMarker
private annotation class UrlQueryDsl
@UrlQueryDsl
class GithubApiUrlQueryBuilder {
private val builder = StringBuilder()
fun param(name: String, value: String?) {
if (value != null) append("$name=${URLUtil.encodeURIComponent(value)}")
}
fun param(pagination: GithubRequestPagination?) {
if (pagination != null) {
param("page", pagination.pageNumber.toString())
param("per_page", pagination.pageSize.toString())
}
}
private fun append(part: String) {
if (builder.isEmpty()) builder.append("?") else builder.append("&")
builder.append(part)
}
companion object {
@JvmStatic
fun urlQuery(init: GithubApiUrlQueryBuilder.() -> Unit) : String {
val query = GithubApiUrlQueryBuilder()
init(query)
return query.builder.toString()
}
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/canBeParameter/usedPrivateInInitializer.kt | 13 | 153 | // "Remove 'val' from parameter" "true"
class UsedInProperty(private <caret>val x: Int) {
var y: String
init {
y = x.toString()
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinClassesWithAnnotatedMembersSearcher.kt | 2 | 1969 | // 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.search.ideaExtensions
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ClassesWithAnnotatedMembersSearch
import com.intellij.psi.search.searches.ScopedQueryExecutor
import com.intellij.util.Processor
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
class KotlinClassesWithAnnotatedMembersSearcher : ScopedQueryExecutor<PsiClass, ClassesWithAnnotatedMembersSearch.Parameters> {
override fun getScope(param: ClassesWithAnnotatedMembersSearch.Parameters): GlobalSearchScope {
return GlobalSearchScope.getScopeRestrictedByFileTypes(param.annotationClass.project.allScope(), KotlinFileType.INSTANCE)
}
override fun execute(queryParameters: ClassesWithAnnotatedMembersSearch.Parameters, consumer: Processor<in PsiClass>): Boolean {
val processed = hashSetOf<KtClassOrObject>()
return KotlinAnnotatedElementsSearcher.processAnnotatedMembers(queryParameters.annotationClass,
queryParameters.scope,
{ it.getNonStrictParentOfType<KtClassOrObject>() !in processed }) { declaration ->
val ktClass = declaration.getNonStrictParentOfType<KtClassOrObject>()
if (ktClass != null && processed.add(ktClass)) {
val lightClass = ktClass.toLightClass()
if (lightClass != null) consumer.process(lightClass) else true
} else
true
}
}
}
| apache-2.0 |
Reacto-Rx/reactorx-core | library/src/test/java/org/reactorx/rx/TypeBehaviorSubjectTest.kt | 1 | 1850 | package cz.filipproch.reactor.rx
import cz.filipproch.reactor.base.view.UiModel
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
class TypeBehaviorSubjectTest {
private lateinit var subject: TypeBehaviorSubject
@Before
fun setupInstance() {
subject = TypeBehaviorSubject.create()
}
@Test
fun testObjectBeingPersisted() {
val test = TestObject()
subject.onNext(test)
val observable = subject
val result = observable.take(1).blockingFirst()
assertThat(test).isEqualTo(result)
}
@Test
fun testRememberTwoDifferentTypes() {
val test = TestObject()
val test2 = TestObject2()
subject.onNext(test)
subject.onNext(test2)
val observable = subject
val results = observable.take(2).blockingIterable()
assertThat(results).hasSize(2)
assertThat(results).containsAll(listOf(
test, test2
))
}
@Test
fun testEmitCorrectItemWhenThereAreMultipleTypes() {
val test = TestObject()
val test2 = TestObject2()
val emittedItems = mutableListOf<Any>()
val observable = subject
observable.subscribe {
emittedItems.add(it)
}
subject.onNext(test)
assertThat(emittedItems).hasSize(1)
assertThat(emittedItems.last()).isEqualTo(test)
subject.onNext(test2)
assertThat(emittedItems).hasSize(2)
assertThat(emittedItems.last()).isEqualTo(test2)
}
class TestObject : UiModel {
override fun getType(): Class<*> {
return TestObject::class.java
}
}
class TestObject2 : UiModel {
override fun getType(): Class<*> {
return TestObject2::class.java
}
}
} | mit |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToStringTemplateIntention.kt | 1 | 7181 | // 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.intentions
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.util.PsiUtilCore
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ConvertToStringTemplateInspection : IntentionBasedInspection<KtBinaryExpression>(
ConvertToStringTemplateIntention::class,
ConvertToStringTemplateIntention::shouldSuggestToConvert,
problemText = KotlinBundle.message("convert.concatenation.to.template.before.text")
), CleanupLocalInspectionTool
open class ConvertToStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("convert.concatenation.to.template")
) {
override fun isApplicableTo(element: KtBinaryExpression): Boolean {
if (!isApplicableToNoParentCheck(element)) return false
val parent = element.parent
if (parent is KtBinaryExpression && isApplicableToNoParentCheck(parent)) return false
return true
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val replacement = buildReplacement(element)
runWriteActionIfPhysical(element) {
element.replaced(replacement)
}
}
companion object {
fun shouldSuggestToConvert(expression: KtBinaryExpression): Boolean {
val entries = buildReplacement(expression).entries
return entries.none { it is KtBlockStringTemplateEntry }
&& !entries.all { it is KtLiteralStringTemplateEntry || it is KtEscapeStringTemplateEntry }
&& entries.count { it is KtLiteralStringTemplateEntry } >= 1
&& !expression.textContains('\n')
}
@JvmStatic
fun buildReplacement(expression: KtBinaryExpression): KtStringTemplateExpression {
val rightText = buildText(expression.right, false)
return fold(expression.left, rightText, KtPsiFactory(expression))
}
private fun fold(left: KtExpression?, right: String, factory: KtPsiFactory): KtStringTemplateExpression {
val forceBraces = right.isNotEmpty() && right.first() != '$' && right.first().isJavaIdentifierPart()
return if (left is KtBinaryExpression && isApplicableToNoParentCheck(left)) {
val leftRight = buildText(left.right, forceBraces)
fold(left.left, leftRight + right, factory)
} else {
val leftText = buildText(left, forceBraces)
factory.createExpression("\"$leftText$right\"") as KtStringTemplateExpression
}
}
fun buildText(expr: KtExpression?, forceBraces: Boolean): String {
if (expr == null) return ""
val expression = KtPsiUtil.safeDeparenthesize(expr).let {
when {
(it as? KtDotQualifiedExpression)?.isToString() == true && it.receiverExpression !is KtSuperExpression ->
it.receiverExpression
it is KtLambdaExpression && it.parent is KtLabeledExpression -> expr
else -> it
}
}
val expressionText = expression.text
when (expression) {
is KtConstantExpression -> {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val type = bindingContext.getType(expression)!!
val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext)
if (constant != null) {
val stringValue = constant.getValue(type).toString()
if (KotlinBuiltIns.isChar(type) || stringValue == expressionText) {
return buildString {
StringUtil.escapeStringCharacters(stringValue.length, stringValue, if (forceBraces) "\"$" else "\"", this)
}
}
}
}
is KtStringTemplateExpression -> {
val base = if (expressionText.startsWith("\"\"\"") && expressionText.endsWith("\"\"\"")) {
val unquoted = expressionText.substring(3, expressionText.length - 3)
StringUtil.escapeStringCharacters(unquoted)
} else {
StringUtil.unquoteString(expressionText)
}
if (forceBraces) {
if (base.endsWith('$')) {
return base.dropLast(1) + "\\$"
} else {
val lastPart = expression.children.lastOrNull()
if (lastPart is KtSimpleNameStringTemplateEntry) {
return base.dropLast(lastPart.textLength) + "\${" + lastPart.text.drop(1) + "}"
}
}
}
return base
}
is KtNameReferenceExpression ->
return "$" + (if (forceBraces) "{$expressionText}" else expressionText)
is KtThisExpression ->
return "$" + (if (forceBraces || expression.labelQualifier != null) "{$expressionText}" else expressionText)
}
return "\${$expressionText}"
}
private fun isApplicableToNoParentCheck(expression: KtBinaryExpression): Boolean {
if (expression.operationToken != KtTokens.PLUS) return false
val expressionType = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL).getType(expression)
if (!KotlinBuiltIns.isString(expressionType)) return false
return isSuitable(expression)
}
private fun isSuitable(expression: KtExpression): Boolean {
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.PLUS) {
return isSuitable(expression.left ?: return false) && isSuitable(expression.right ?: return false)
}
if (PsiUtilCore.hasErrorElementChild(expression)) return false
if (expression.textContains('\n')) return false
return true
}
}
}
| apache-2.0 |
MarkusAmshove/Kluent | jvm/src/main/kotlin/org/amshove/kluent/CharSequenceBacktick.kt | 1 | 3481 | package org.amshove.kluent
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
infix fun <T : CharSequence> T.`should start with`(expected: CharSequence) = this.shouldStartWith(expected)
infix fun <T : CharSequence> T.`should end with`(expected: CharSequence) = this.shouldEndWith(expected)
infix fun <T : CharSequence> T.`should contain`(char: Char) = this.shouldContain(char)
infix fun <T : CharSequence> T.`should contain some`(things: Iterable<CharSequence>) = this.shouldContainSome(things)
infix fun <T : CharSequence> T.`should contain none`(things: Iterable<CharSequence>) = this.shouldContainNone(things)
infix fun <T : CharSequence> T.`should contain`(expected: CharSequence) = this.shouldContain(expected)
infix fun <T : CharSequence> T.`should not contain`(char: Char) = this.shouldNotContain(char)
infix fun <T : CharSequence> T.`should not contain any`(things: Iterable<CharSequence>) =
this.shouldNotContainAny(things)
infix fun <T : CharSequence> T.`should match`(regex: String) = this.shouldMatch(regex)
infix fun <T : CharSequence> T.`should match`(regex: Regex) = this.shouldMatch(regex)
fun <T : CharSequence> T.`should be empty`() = this.shouldBeEmpty()
fun <T : CharSequence> T?.`should be null or empty`() = this.shouldBeNullOrEmpty()
fun <T : CharSequence> T.`should be blank`() = this.shouldBeBlank()
fun <T : CharSequence> T?.`should be null or blank`() = this.shouldBeNullOrBlank()
@Deprecated("Use #`should be equal to`", ReplaceWith("this.`should be equal to`(expected)"))
infix fun String.`should equal to`(expected: String) = this.`should be equal to`(expected)
infix fun String.`should be equal to`(expected: String) = this.shouldBeEqualTo(expected)
@Deprecated("Use #`should not be equal to`", ReplaceWith("this.`should not be equal to`(expected)"))
infix fun String.`should not equal to`(expected: String) = this.`should not be equal to`(expected)
infix fun String.`should not be equal to`(expected: String) = this.shouldNotBeEqualTo(expected)
infix fun <T : CharSequence> T.`should not start with`(expected: CharSequence) = this.shouldNotStartWith(expected)
infix fun <T : CharSequence> T.`should not end with`(expected: CharSequence) = this.shouldNotEndWith(expected)
infix fun <T : CharSequence> T.`should not contain`(expected: CharSequence) = this.shouldNotContain(expected)
infix fun <T : CharSequence> T.`should not match`(regex: String) = this.shouldNotMatch(regex)
infix fun <T : CharSequence> T.`should not match`(regex: Regex) = this.shouldNotMatch(regex)
fun <T : CharSequence> T.`should not be empty`(): T = this.shouldNotBeEmpty()
@UseExperimental(ExperimentalContracts::class)
fun <T : CharSequence> T?.`should not be null or empty`(): T {
contract {
returns() implies (this@`should not be null or empty` != null)
}
return this.shouldNotBeNullOrEmpty()
}
fun <T : CharSequence> T.`should not be blank`(): T = this.shouldNotBeBlank()
@UseExperimental(ExperimentalContracts::class)
fun <T : CharSequence> T?.`should not be null or blank`(): T {
contract {
returns() implies (this@`should not be null or blank` != null)
}
return this.shouldNotBeNullOrBlank()
}
infix fun <T : CharSequence> T.`should contain all`(items: Iterable<CharSequence>): CharSequence =
this.shouldContainAll(items)
infix fun <T : CharSequence> T.`should not contain all`(items: Iterable<CharSequence>): CharSequence =
this.shouldNotContainAll(items)
| mit |
elpassion/el-space-android | el-space-app/src/main/java/pl/elpassion/elspace/hub/report/add/ReportAddController.kt | 1 | 5081 | package pl.elpassion.elspace.hub.report.add
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.withLatestFrom
import pl.elpassion.elspace.common.CurrentTimeProvider
import pl.elpassion.elspace.common.SchedulersSupplier
import pl.elpassion.elspace.common.extensions.catchOnError
import pl.elpassion.elspace.common.extensions.getDateString
import pl.elpassion.elspace.common.extensions.getTimeFrom
import pl.elpassion.elspace.hub.project.Project
import pl.elpassion.elspace.hub.project.last.LastSelectedProjectRepository
import pl.elpassion.elspace.hub.report.PaidVacationsViewModel
import pl.elpassion.elspace.hub.report.RegularViewModel
import pl.elpassion.elspace.hub.report.ReportType
import pl.elpassion.elspace.hub.report.ReportViewModel
class ReportAddController(private val date: String?,
private val view: ReportAdd.View,
private val api: ReportAdd.Api,
private val repository: LastSelectedProjectRepository,
private val schedulers: SchedulersSupplier) {
private val subscriptions = CompositeDisposable()
fun onCreate() {
repository.getLastProject()?.let {
view.showSelectedProject(it)
}
view.showDate(date ?: getCurrentDatePerformedAtString())
view.projectClickEvents()
.subscribe { view.openProjectChooser() }
.addTo(subscriptions)
addReportClicks()
.subscribe()
.addTo(subscriptions)
}
fun onDestroy() {
subscriptions.clear()
}
fun onDateChanged(date: String) {
view.showDate(date)
}
fun onProjectChanged(project: Project) {
view.showSelectedProject(project)
}
private fun getCurrentDatePerformedAtString() = getTimeFrom(timeInMillis = CurrentTimeProvider.get()).getDateString()
private fun addReportClicks() = view.addReportClicks()
.withLatestFrom(reportTypeChanges(), { model, handler -> model to handler })
.switchMap { callApi(it) }
.doOnNext { view.close() }
private fun reportTypeChanges() = view.reportTypeChanges()
.doOnNext { onReportTypeChanged(it) }
.startWith(ReportType.REGULAR)
.map { chooseReportHandler(it) }
private fun chooseReportHandler(reportType: ReportType) = when (reportType) {
ReportType.REGULAR -> regularReportHandler
ReportType.PAID_VACATIONS -> paidVacationReportHandler
ReportType.UNPAID_VACATIONS -> unpaidVacationReportHandler
ReportType.SICK_LEAVE -> sickLeaveReportHandler
ReportType.PAID_CONFERENCE -> paidConferenceReportHandler
}
private fun callApi(modelCallPair: Pair<ReportViewModel, (ReportViewModel) -> Observable<Unit>>) = modelCallPair.second(modelCallPair.first)
.subscribeOn(schedulers.backgroundScheduler)
.observeOn(schedulers.uiScheduler)
.addLoader()
.catchOnError { view.showError(it) }
private val regularReportHandler = { model: ReportViewModel ->
(model as RegularViewModel).run {
when {
hasNoProject() -> {
view.showEmptyProjectError()
Observable.empty()
}
hasNoDescription() -> {
view.showEmptyDescriptionError()
Observable.empty()
}
else -> addRegularReportObservable(this)
}
}
}
private fun addRegularReportObservable(model: RegularViewModel) =
api.addRegularReport(model.selectedDate, model.project!!.id, model.hours, model.description)
private val paidVacationReportHandler = { model: ReportViewModel ->
api.addPaidVacationsReport(model.selectedDate, (model as PaidVacationsViewModel).hours)
}
private val unpaidVacationReportHandler = { model: ReportViewModel ->
api.addUnpaidVacationsReport(model.selectedDate)
}
private val sickLeaveReportHandler = { model: ReportViewModel ->
api.addSickLeaveReport(model.selectedDate)
}
private val paidConferenceReportHandler = { model: ReportViewModel ->
api.addPaidConferenceReport(model.selectedDate)
}
private fun onReportTypeChanged(reportType: ReportType) = when (reportType) {
ReportType.REGULAR -> view.showRegularForm()
ReportType.PAID_VACATIONS -> view.showPaidVacationsForm()
ReportType.UNPAID_VACATIONS -> view.showUnpaidVacationsForm()
ReportType.SICK_LEAVE -> view.showSickLeaveForm()
ReportType.PAID_CONFERENCE -> view.showPaidConferenceForm()
}
private fun RegularViewModel.hasNoDescription() = description.isBlank()
private fun RegularViewModel.hasNoProject() = project == null
private fun Observable<Unit>.addLoader() = this
.doOnSubscribe { view.showLoader() }
.doFinally { view.hideLoader() }
}
| gpl-3.0 |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/nbt/lang/psi/mixins/impl/NbttLongImplMixin.kt | 1 | 639 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.psi.mixins.impl
import com.demonwav.mcdev.nbt.lang.psi.mixins.NbttLongMixin
import com.demonwav.mcdev.nbt.tags.TagLong
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import org.apache.commons.lang3.StringUtils
abstract class NbttLongImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), NbttLongMixin {
override fun getLongTag(): TagLong {
return TagLong(StringUtils.replaceChars(text.trim(), "lL", null).toLong())
}
}
| mit |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/contents/Text.kt | 1 | 2736 | // Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr 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.
//
// PdfLayoutMgr 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 PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.contents
import com.planbase.pdf.lm2.attributes.TextStyle
import com.planbase.pdf.lm2.lineWrapping.LineWrappable
import com.planbase.pdf.lm2.lineWrapping.LineWrapper
import org.organicdesign.indented.StringUtils.stringify
/**
Represents styled text kind of like a #Text node in HTML.
*/
data class Text(val textStyle: TextStyle,
private val initialText: String = "") : LineWrappable {
constructor(textStyle: TextStyle) : this(textStyle, "")
// This removes all tabs, transforms all line-terminators into "\n", and removes all runs of spaces that
// precede line terminators. This should simplify the subsequent line-breaking algorithm.
val text: String = cleanStr(initialText)
fun avgCharsForWidth(width: Double): Int = (width * 1220.0 / textStyle.avgCharWidth).toInt()
fun maxWidth(): Double = textStyle.stringWidthInDocUnits(text.trim())
override fun toString() = "Text($textStyle, ${stringify(text)})"
override fun lineWrapper(): LineWrapper = TextLineWrapper(this)
companion object {
// From: https://docs.google.com/document/d/1vpbFYqfW7XmJplSwwLLo7zSPOztayO7G4Gw5_EHfpfI/edit#
//
// 1. Remove all tabs. There is no way to make a good assumption about how to turn them into spaces.
//
// 2. Transform all line-terminators into "\n". Also remove spaces before every line terminator (hard break).
//
// The wrapping algorithm will remove all consecutive spaces on an automatic line-break. Otherwise, we want
// to preserve consecutive spaces within a line.
//
// Non-breaking spaces are ignored here.
fun cleanStr(s:String):String = s.replace(Regex("\t"), "")
.replace(Regex("[ ]*(\r\n|[\r\n\u0085\u2028\u2029])"), "\n")
}
}
| agpl-3.0 |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/PdfLayoutMgr.kt | 1 | 14793 | // Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr 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.
//
// PdfLayoutMgr 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 PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2
import com.planbase.pdf.lm2.attributes.Orientation
import com.planbase.pdf.lm2.attributes.Orientation.LANDSCAPE
import com.planbase.pdf.lm2.attributes.PageArea
import com.planbase.pdf.lm2.contents.ScaledImage.WrappedImage
import com.planbase.pdf.lm2.pages.PageGrouping
import com.planbase.pdf.lm2.pages.SinglePage
import com.planbase.pdf.lm2.utils.Dim
import org.apache.fontbox.ttf.TTFParser
import org.apache.fontbox.ttf.TrueTypeFont
import org.apache.pdfbox.cos.COSArray
import org.apache.pdfbox.cos.COSString
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.PDDocumentInformation
import org.apache.pdfbox.pdmodel.PDPage
import org.apache.pdfbox.pdmodel.PDPageContentStream
import org.apache.pdfbox.pdmodel.font.PDType0Font
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace
import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject
import org.apache.pdfbox.util.Matrix
import java.awt.image.BufferedImage
import java.io.File
import java.io.IOException
import java.io.OutputStream
import java.lang.IllegalArgumentException
import java.util.HashMap
/**
* Manages a PDF document. You need one of these to do almost anything useful.
*
* ## Usage (Example taken from TestBasics.kt)
* ```kotlin
* // Make a manager with the given color model and starting page size.
* val pageMgr = PdfLayoutMgr(PDDeviceCMYK.INSTANCE, Dim(LETTER))
*
* // Declare a text style to use.
* val bodyText = TextStyle(TIMES_ITALIC, 36.0, CMYK_BLACK)
*
* // Start a bunch of pages (add more text to use more than one)
* val lp = pageMgr.startPageGrouping(PORTRAIT, letterPortraitBody)
*
* // Stick some text on the page(s)
* lp.appendCell(0.0, CellStyle(Align.TOP_LEFT_JUSTIFY, BoxStyle.NO_PAD_NO_BORDER),
* listOf(Text(bodyText, "\"Darkness within darkness: the gateway to all" +
* " understanding.\" — Lao Tzu")))
*
* // Commit all your work and write it to a file
* pageMgr.commit()
* pageMgr.save(FileOutputStream("helloWorld.pdf"))
* ```
*
* # Note:
*
* Because this class buffers and writes to an underlying stream, it is mutable, has side effects,
* and is NOT thread-safe!
*
* @param colorSpace the color-space for the document. Often PDDeviceCMYK.INSTANCE or PDDeviceRGB.INSTANCE
* @param pageDim Returns the width and height of the paper-size where THE HEIGHT IS ALWAYS THE LONGER DIMENSION.
* You may need to swap these for landscape: `pageDim().swapWh()`. For this reason, it's not a
* good idea to use this directly. Use the corrected values through a [PageGrouping] instead.
* @param pageReactor Takes a page number and returns an x-offset for that page. Use this for effects like page
* numbering or different offsets or headers/footers for even and odd pages or the start of a chapter.
*/
class PdfLayoutMgr(private val colorSpace: PDColorSpace,
val pageDim: Dim,
private var pageReactor:((Int, SinglePage) -> Double)? = null) {
private val doc = PDDocument()
init {
val docInf = PDDocumentInformation()
docInf.producer = "PlanBase PdfLayoutMgr2"
doc.documentInformation = docInf
}
/**
* This returns the wrapped PDDocument instance. This is a highly mutable data structure.
* Accessing it directly while also using PdfLayoutMgr is inherently unsafe and untested.
* This method is provided so you can do things like add encryption or use other features of PDFBox not yet
* directly supported by PdfLayoutMgr.
*/
@Suppress("unused") // Required part of public API
fun getPDDocButBeCareful(): PDDocument = doc
// You can have many PDImageXObject backed by only a few images - it is a flyweight, and this
// hash map keeps track of the few underlying images, even as instances of PDImageXObject
// represent all the places where these images are used.
// CRITICAL: This means that the the set of PDImageXObject must be thrown out and created anew for each
// document!
private val imageCache = HashMap<BufferedImage, PDImageXObject>()
private val pages:MutableList<SinglePage> = mutableListOf()
private val uncommittedPageGroupings:MutableList<PageGrouping> = mutableListOf()
class TrueAndZeroFonts(val trueType:TrueTypeFont, val typeZero:PDType0Font)
private val openFontFiles: MutableMap<File,TrueAndZeroFonts> = mutableMapOf()
// pages.size() counts the first page as 1, so 0 is the appropriate sentinel value
private var unCommittedPageIdx:Int = 0
fun unCommittedPageIdx():Int = unCommittedPageIdx
internal fun ensureCached(sj: WrappedImage): PDImageXObject {
val bufferedImage = sj.bufferedImage
var temp: PDImageXObject? = imageCache[bufferedImage]
if (temp == null) {
val problems:MutableList<Throwable> = mutableListOf()
temp = try {
LosslessFactory.createFromImage(doc, bufferedImage)
} catch (t: Throwable) {
problems.plus(t)
try {
JPEGFactory.createFromImage(doc, bufferedImage)
} catch (u: Throwable) {
if (problems.isEmpty()) {
throw Exception("Caught exception creating a JPEG from a bufferedImage", u)
} else {
problems.plus(u)
throw Exception("Caught exceptions creating Lossless/JPEG PDImageXObjects from" +
" a bufferedImage: $problems")
}
}
}
imageCache[bufferedImage] = temp!!
}
return temp
}
// TODO: Is this a good idea?
fun numPages():Int = pages.size
fun hasAnyPages():Boolean = pages.size > 0
fun page(idx:Int):SinglePage = pages[idx]
/**
* Allows inserting a single page before already created pages.
* @param page the page to insert
* @param idx the index to insert at (shifting the pages currently at that index and all greater indices up one.
* This must be >= 0, <= pages.size, and >= the unCommittedPageIdx.
* The last means that you cannot insert before already committed pages.
*/
fun insertPageAt(page:SinglePage, idx:Int) {
if (idx < 0) {
throw IllegalArgumentException("Insert index cannot be less than 0")
}
if (idx > pages.size) {
throw IllegalArgumentException("Insert index cannot be greater than the number" +
" of pages (if index == pages.size it's a legal" +
" append, but not technically an insert).")
}
if (idx < unCommittedPageIdx) {
throw IllegalStateException("Can't insert page at $idx before already" +
" committed pages at $unCommittedPageIdx.")
}
pages.add(idx, page)
}
fun ensurePageIdx(idx:Int, body:PageArea) {
while (pages.size <= idx) {
pages.add(SinglePage(pages.size + 1, this, pageReactor, body))
}
}
/**
* Call this to commit the PDF information to the underlying stream after it is completely built.
* This also frees any open font file descriptors (that were opened by PdfLayoutMgr2).
*/
@Throws(IOException::class)
fun save(os: OutputStream) {
doc.save(os)
doc.close()
openFontFiles.values.forEach { ttt0 ->
ttt0.trueType.close()
}
openFontFiles.clear()
}
/**
* Tells this PdfLayoutMgr that you want to start a new logical page (which may be broken across
* two or more physical pages) in the requested page orientation.
*/
// Part of end-user public interface
fun startPageGrouping(orientation: Orientation,
body:PageArea,
pr: ((Int, SinglePage) -> Double)? = null): PageGrouping {
pageReactor = pr
val pb = SinglePage(pages.size + 1, this, pageReactor, body)
pages.add(pb)
val pg = PageGrouping(this, orientation, body)
uncommittedPageGroupings.add(pg)
return pg
}
// private fun pageArea(o: Orientation, margins:Padding = Padding(DEFAULT_MARGIN)):PageArea {
// val bodyDim:Dim = margins.subtractFrom(if (o == Orientation.PORTRAIT) {
// pageDim
// } else {
// pageDim.swapWh()
// })
// return PageArea(Coord(margins.left, margins.bottom + bodyDim.height),
// bodyDim)
// }
// fun startPageGrouping(orientation: Orientation,
// body:PageArea): PageGrouping = startPageGrouping(orientation, body, null)
/**
* Loads a TrueType font and automatically embeds (the part you use?) into the document from the given file,
* returning a PDType0Font object. The underlying TrueTypeFont object holds the file descriptor open while you
* are working, presumably to embed only the glyphs you need. PdfLayoutMgr2 will explicitly close the file
* descriptor when you call [save]. Calling this method twice on the same PdfLayoutMgr with the same file will
* return the same (already open) font.
*/
@Throws(IOException::class)
fun loadTrueTypeFont(fontFile: File): PDType0Font {
var ttt0:TrueAndZeroFonts? = openFontFiles[fontFile]
if (ttt0 == null) {
val tt = TTFParser().parse(fontFile)
val t0 = PDType0Font.load(doc, tt, true)
ttt0 = TrueAndZeroFonts(tt, t0)
openFontFiles[fontFile] = ttt0
}
return ttt0.typeZero
}
fun commit() {
uncommittedPageGroupings.forEach { logicalPageEnd(it) }
uncommittedPageGroupings.clear()
}
/** Returns a COSArray of two COSString's. See [setFileIdentifiers] for details */
fun getFileIdentifiers() : COSArray? = doc.document.documentID
/**
* This an optional value in the PDF spec designed to hold two hashcode for later file compares.
* The first represents the original state of the file, the second the latest.
* If left null, PDFBox fills it in with an md5 hash of the file info plus timestamp.
* Construct a COSString like: COSString("Whatever".toByteArray(Charsets.ISO_8859_1))
* or just by passing it a byte array directly.
*/
fun setFileIdentifiers(original: COSString, latest: COSString) {
val ca = COSArray()
ca.add(original)
ca.add(latest)
doc.document.documentID = ca
}
/**
* Call this when you are through with your current set of pages to commit all pending text and
* drawing operations. This is the only method that throws an IOException because the purpose of
* PdfLayoutMgr is to buffer all operations until a page is complete so that it can safely be
* written to the underlying stream. This method turns the potential pages into real output.
* Call when you need a page break, or your document is done and you need to write it out.
*
* Once you call this method, you cannot insert or modify earlier pages.
*
* @throws IOException if there is a failure writing to the underlying stream.
*/
@Throws(IOException::class)
private fun logicalPageEnd(lp: PageGrouping) {
// Write out all uncommitted pages.
while (unCommittedPageIdx < pages.size) {
val pdPage = PDPage(pageDim.toRect())
if (lp.orientation === LANDSCAPE) {
pdPage.rotation = 90
}
var stream: PDPageContentStream? = null
try {
stream = PDPageContentStream(doc, pdPage)
doc.addPage(pdPage)
if (lp.orientation === LANDSCAPE) {
stream.transform(Matrix(0f, 1f, -1f, 0f, pageDim.width.toFloat(), 0f))
}
stream.setStrokingColor(colorSpace.initialColor)
stream.setNonStrokingColor(colorSpace.initialColor)
val pb = pages[unCommittedPageIdx]
pb.commit(stream)
lp.commitBorderItems(stream)
stream.close()
// Set to null to show that no exception was thrown and no need to close again.
stream = null
} finally {
// Let it throw an exception if the closing doesn't work.
stream?.close()
}
unCommittedPageIdx++
}
lp.invalidate()
}
override fun equals(other: Any?): Boolean {
// First, the obvious...
if (this === other) {
return true
}
if ( (other == null) ||
(other !is PdfLayoutMgr) ) {
return false
}
// Details...
return this.doc == other.doc && this.pages == other.pages
}
override fun hashCode(): Int = doc.hashCode() + pages.hashCode()
companion object {
/**
* If you use no scaling when printing the output PDF, PDFBox shows approximately 72
* Document-Units Per Inch. This makes one pixel on an average desktop monitor correspond to
* roughly one document unit. This is a useful constant for page layout math.
*/
const val DOC_UNITS_PER_INCH: Double = 72.0
/**
* Some printers need at least 1/2" of margin (36 "pixels") in order to accept a print job.
* This amount seems to accommodate all printers.
*/
const val DEFAULT_MARGIN: Double = 37.0
// private val DEFAULT_DOUBLE_MARGIN_DIM = Dim(DEFAULT_MARGIN * 2, DEFAULT_MARGIN * 2)
}
}
| agpl-3.0 |
cd1/motofretado | app/src/main/java/com/gmail/cristiandeives/motofretado/TrackBusFragment.kt | 1 | 10346 | package com.gmail.cristiandeives.motofretado
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.support.annotation.MainThread
import android.support.annotation.UiThread
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.app.LoaderManager
import android.support.v4.content.ContextCompat
import android.support.v4.content.Loader
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import com.gmail.cristiandeives.motofretado.http.Bus
import kotlinx.android.synthetic.main.fragment_track_bus.*
import java.util.Arrays
@MainThread
internal class TrackBusFragment : Fragment(), LoaderManager.LoaderCallbacks<TrackBusMvp.Presenter>, TrackBusMvp.View, AddBusDialogFragment.OnClickListener {
companion object {
private val TAG = TrackBusFragment::class.java.simpleName
private const val REQUEST_PERMISSION_LOCATION_UPDATE = 0
private const val REQUEST_PERMISSION_ACTIVITY_DETECTION = 1
private const val TRACK_BUS_LOADER_ID = 0
}
private lateinit var mSpinnerAdapter: BusSpinnerAdapter
private var mPresenter: TrackBusMvp.Presenter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
Log.v(TAG, "> onCreateView(inflater=$inflater, container=$container, savedInstanceState=$savedInstanceState)")
val rootView = inflater.inflate(R.layout.fragment_track_bus, container, false)
mSpinnerAdapter = BusSpinnerAdapter(context)
mPresenter = null;
Log.v(TAG, "< onCreateView(inflater=$inflater, container=$container, savedInstanceState=$savedInstanceState): $rootView")
return rootView
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
Log.v(TAG, "> onViewCreated(view=$view, savedInstanceState=$savedInstanceState)")
spinnerBusID.adapter = mSpinnerAdapter
buttonAddBus.setOnClickListener {
val fragment = AddBusDialogFragment()
fragment.setTargetFragment(this@TrackBusFragment, 0)
fragment.show(fragmentManager, AddBusDialogFragment::class.java.name)
}
buttonEnterBus.setOnClickListener(this::buttonEnterBusClick)
buttonLeaveBus.setOnClickListener { mPresenter?.stopLocationUpdate() }
switchDetectAutomatically.setOnCheckedChangeListener(this::switchDetectAutomaticallyChange)
disableBusId()
Log.v(TAG, "< onViewCreated(view=$view, savedInstanceState=$savedInstanceState)")
}
override fun onDestroyView() {
Log.v(TAG, "> onDestroyView()")
super.onDestroyView()
mPresenter?.onDetach()
Log.v(TAG, "< onDestroyView()")
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
Log.v(TAG, "> onActivityCreated(savedInstanceState=$savedInstanceState)")
super.onActivityCreated(savedInstanceState)
loaderManager.initLoader(TRACK_BUS_LOADER_ID, null, this)
Log.v(TAG, "< onActivityCreated(savedInstanceState=$savedInstanceState)")
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "> onRequestPermissionsResult(requestCode=$requestCode, permissions=${Arrays.toString(permissions)}, grantResults=${Arrays.toString(grantResults)})")
}
when (requestCode) {
REQUEST_PERMISSION_LOCATION_UPDATE, REQUEST_PERMISSION_ACTIVITY_DETECTION -> {
if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "user granted permission")
mPresenter?.let { presenter ->
when (requestCode) {
REQUEST_PERMISSION_LOCATION_UPDATE -> presenter.startLocationUpdate()
REQUEST_PERMISSION_ACTIVITY_DETECTION -> presenter.startActivityDetection()
}
}
} else {
uncheckSwitchDetectAutomatically()
if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
Log.d(TAG, "user did NOT grant permission")
displayMessage(getString(R.string.fine_location_permission_rationale))
} else {
view?.let { rootView ->
val snackIntent = Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.parse("package:${activity.packageName}")
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
Snackbar.make(rootView, R.string.fine_location_permission_rationale, Snackbar.LENGTH_LONG)
.setAction(R.string.snackbar_action_settings) { startActivity(snackIntent) }
.show()
}
}
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "> onRequestPermissionsResult(requestCode=$requestCode, permissions=${Arrays.toString(permissions)}, grantResults=${Arrays.toString(grantResults)})")
}
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<TrackBusMvp.Presenter> {
Log.v(TAG, "> onCreateLoader(id=$id, args=$args)")
val loader = TrackBusPresenterLoader(context.applicationContext)
Log.v(TAG, "< onCreateLoader(id=$id, args=$args): $loader")
return loader
}
override fun onLoaderReset(loader: Loader<TrackBusMvp.Presenter>) {
Log.v(TAG, "> onLoaderReset(loader=$loader)")
mPresenter?.let { presenter ->
presenter.onDetach()
mPresenter = null
}
Log.v(TAG, "< onLoaderReset(loader=$loader)")
}
override fun onLoadFinished(loader: Loader<TrackBusMvp.Presenter>, data: TrackBusMvp.Presenter) {
Log.v(TAG, "> onLoadFinished(loader=$loader, data=$data)")
mPresenter = data
data.onAttach(this)
Log.v(TAG, "< onLoadFinished(loader=$loader, data=$data)")
}
@UiThread
override fun getBusId(): String? {
return if (mSpinnerAdapter.hasActualBusData()) {
spinnerBusID.selectedItem.toString()
} else {
null
}
}
@UiThread
override fun displayMessage(text: String) {
Log.d(TAG, "displaying message: $text")
context.toast(text)
}
@UiThread
override fun enableBusId() {
spinnerBusID.isEnabled = true
buttonAddBus.isEnabled = true
buttonAddBus.setImageDrawable(context.getDrawable(R.drawable.ic_add))
}
@UiThread
override fun disableBusId() {
spinnerBusID.isEnabled = false
buttonAddBus.isEnabled = false
// change button icon to grayscale
val drawable = context.getDrawable(R.drawable.ic_add).mutate()
drawable.setColorFilter(Color.LTGRAY, PorterDuff.Mode.SRC_IN)
buttonAddBus.setImageDrawable(drawable)
}
@UiThread
override fun uncheckSwitchDetectAutomatically() {
switchDetectAutomatically.isChecked = false
}
@UiThread
override fun setAvailableBuses(buses: List<Bus>, selectedBusId: String?) {
mSpinnerAdapter.clear()
mSpinnerAdapter.addAll(buses)
if (!selectedBusId.isNullOrEmpty()) {
val selectedBusIndex = buses.indexOfFirst { it.id == selectedBusId }
spinnerBusID.setSelection(selectedBusIndex)
}
}
@UiThread
override fun setBusError(errorMessage: String) {
mSpinnerAdapter.setErrorMessage(errorMessage)
spinnerBusID.adapter = mSpinnerAdapter
mSpinnerAdapter.notifyDataSetChanged()
disableBusId()
}
@UiThread
override fun onPositiveButtonClick(text: String) {
mPresenter?.createBus(Bus(id = text))
}
@UiThread
private fun buttonEnterBusClick(view: View) {
if (getBusId().isNullOrEmpty()) {
Log.d(TAG, "empty bus ID; cannot trigger location updates")
displayMessage(getString(R.string.empty_bus_id_message))
return
}
mPresenter?.let { presenter ->
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
presenter.startLocationUpdate()
} else {
Log.d(TAG, "the app doesn't have location permission; requesting it to the user")
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION_LOCATION_UPDATE)
}
}
}
@UiThread
private fun switchDetectAutomaticallyChange(buttonView: CompoundButton, isChecked: Boolean) {
mPresenter?.let { presenter ->
if (isChecked && getBusId().isNullOrEmpty()) {
Log.d(TAG, "empty bus ID; cannot trigger activity detection")
displayMessage(getString(R.string.empty_bus_id_message))
uncheckSwitchDetectAutomatically()
return
}
if (isChecked) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
presenter.startActivityDetection()
} else {
Log.d(TAG, "the app doesn't have location permission; requesting it to the user")
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION_ACTIVITY_DETECTION)
}
} else {
presenter.stopActivityDetection()
}
}
}
} | gpl-3.0 |
google/intellij-community | plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/fir/search/AbstractHLImplementationSearcherTest.kt | 3 | 1951 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.fir.search
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.search.searches.DefinitionsScopedSearch
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import java.nio.file.Paths
abstract class AbstractHLImplementationSearcherTest : KotlinLightCodeInsightFixtureTestCase() {
override fun isFirPlugin(): Boolean = true
fun doTest(testFilePath: String) {
myFixture.configureByFile(testFilePath) as KtFile
val declarationAtCaret = myFixture.elementAtCaret.parentOfType<KtDeclaration>(withSelf = true)
?: error("No declaration found at caret")
val result = DefinitionsScopedSearch.search(declarationAtCaret).toList()
val actual = render(result)
KotlinTestUtils.assertEqualsToSibling(Paths.get(testFilePath), ".result.kt", actual)
}
@OptIn(ExperimentalStdlibApi::class)
private fun render(declarations: List<PsiElement>): String = buildList {
for (declaration in declarations) {
val name = declaration.kotlinFqName ?: declaration.declarationName()
add(declaration::class.simpleName!! + ": " + name)
}
}.sorted().joinToString(separator = "\n")
private fun PsiElement.declarationName() = when (this) {
is KtNamedDeclaration -> nameAsSafeName.asString()
is PsiNameIdentifierOwner -> nameIdentifier?.text ?: "<no name>"
else -> error("Unknown declaration ${this::class.simpleName}")
}
} | apache-2.0 |
google/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinMethodSmartStepTarget.kt | 2 | 3228 | // 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.debugger.stepping.smartStepInto
import com.intellij.debugger.engine.MethodFilter
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.util.Range
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
import org.jetbrains.kotlin.renderer.PropertyAccessorRenderingPolicy
import javax.swing.Icon
class KotlinMethodSmartStepTarget(
lines: Range<Int>,
highlightElement: PsiElement,
label: String,
declaration: KtDeclaration?,
val ordinal: Int,
val methodInfo: CallableMemberInfo
) : KotlinSmartStepTarget(label, highlightElement, false, lines) {
companion object {
private val renderer = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE
withoutReturnType = true
propertyAccessorRenderingPolicy = PropertyAccessorRenderingPolicy.PRETTY
startFromName = true
modifiers = emptySet()
}
fun calcLabel(descriptor: DeclarationDescriptor): String {
return renderer.render(descriptor)
}
}
private val declarationPtr = declaration?.let(SourceNavigationHelper::getNavigationElement)?.createSmartPointer()
init {
assert(declaration != null || methodInfo.isInvoke)
}
override fun getIcon(): Icon = if (methodInfo.isExtension) KotlinIcons.EXTENSION_FUNCTION else KotlinIcons.FUNCTION
fun getDeclaration(): KtDeclaration? =
declarationPtr.getElementInReadAction()
override fun createMethodFilter(): MethodFilter {
val declaration = declarationPtr.getElementInReadAction()
return KotlinMethodFilter(declaration, callingExpressionLines, methodInfo)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is KotlinMethodSmartStepTarget) return false
if (methodInfo.isInvoke && other.methodInfo.isInvoke) {
// Don't allow to choose several invoke targets in smart step into as we can't distinguish them reliably during debug
return true
}
return highlightElement === other.highlightElement
}
override fun hashCode(): Int {
if (methodInfo.isInvoke) {
// Predefined value to make all FunctionInvokeDescriptor targets equal
return 42
}
return highlightElement.hashCode()
}
}
internal fun <T : PsiElement> SmartPsiElementPointer<T>?.getElementInReadAction(): T? =
this?.let { runReadAction { element } }
| apache-2.0 |
apollographql/apollo-android | build-logic/src/main/kotlin/Mpp.kt | 1 | 3997 | import org.gradle.api.Project
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
fun Project.configureMppDefaults(withJs: Boolean = true, withLinux: Boolean = true) {
// See https://kotlinlang.org/docs/mpp-dsl-reference.html#targets
val kotlinExtension = extensions.findByName("kotlin") as? KotlinMultiplatformExtension
check(kotlinExtension != null) {
"No multiplatform extension found"
}
kotlinExtension.apply {
/**
* configure targets
*/
jvm()
if (withJs) {
js(BOTH) {
nodejs()
}
}
if (System.getProperty("idea.sync.active") == null) {
val appleMain = sourceSets.create("appleMain")
val appleTest = sourceSets.create("appleTest")
macosX64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
macosArm64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
iosArm64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
iosX64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
iosSimulatorArm64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
watchosArm64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
watchosSimulatorArm64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
tvosArm64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
tvosX64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
tvosSimulatorArm64().apply {
compilations.getByName("main").source(appleMain)
compilations.getByName("test").source(appleTest)
}
} else {
// We are in intelliJ
// Make intelliJ believe we have a single target with all the code in "apple" sourceSets
macosX64("apple")
}
if (withLinux) {
linuxX64("linux")
}
addTestDependencies(withJs)
if (System.getProperty("idea.sync.active") == null) {
/**
* Evil tasks to fool IntelliJ into running the appropriate tests when clicking the green triangle in the gutter
* IntelliJ "sees" apple during sync but the actual tasks are macosX64
*/
tasks.register("cleanAppleTest") {
it.dependsOn("cleanMacosX64Test")
}
tasks.register("appleTest") {
it.dependsOn("macosX64Test")
}
}
}
}
/**
* Same as [configureMppDefaults] but without iOS or Linux targets.
* Tests only run on the JVM, JS and MacOS
*/
fun Project.configureMppTestsDefaults(withJs: Boolean = true) {
val kotlinExtension = extensions.findByName("kotlin") as? KotlinMultiplatformExtension
check(kotlinExtension != null) {
"No multiplatform extension found"
}
kotlinExtension.apply {
/**
* configure targets
*/
jvm()
if (withJs) {
js(IR) {
nodejs()
}
}
macosX64("apple")
addTestDependencies(withJs)
}
}
fun KotlinMultiplatformExtension.addTestDependencies(withJs: Boolean) {
sourceSets.getByName("commonTest") {
it.dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
if (withJs) {
sourceSets.getByName("jsTest") {
it.dependencies {
implementation(kotlin("test-js"))
}
}
}
sourceSets.getByName("jvmTest") {
it.dependencies {
implementation(kotlin("test-junit"))
}
}
}
| mit |
JetBrains/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/presentation/DeclarationPresentersTest.kt | 1 | 2701 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.presentation
import com.intellij.ide.IconProvider
import com.intellij.openapi.extensions.LoadingOrder
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinIconProvider
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import java.awt.Component
import java.awt.Graphics
import javax.swing.Icon
class DeclarationPresentersTest : KotlinLightCodeInsightFixtureTestCase() {
fun testGetIconWithNoExtraIconProviders() {
myFixture.configureByText("Foo.kt", "class <caret>Foo")
val element = myFixture.elementAtCaret as KtNamedDeclaration
// By default, we expect whatever the first KotlinIconProvider returns.
val firstProvider = IconProvider.EXTENSION_POINT_NAME.findFirstSafe { it is KotlinIconProvider }!!
val expectedIcon = firstProvider.getIcon(element, Iconable.ICON_FLAG_VISIBILITY or Iconable.ICON_FLAG_READ_STATUS)
assertEquals(expectedIcon, KotlinDefaultNamedDeclarationPresentation(element).getIcon(false))
}
fun testGetIconWithAdditionalIconProvider() {
myFixture.configureByText("Foo.kt", "class <caret>Foo")
val element = myFixture.elementAtCaret as KtNamedDeclaration
val defaultIcon = KotlinDefaultNamedDeclarationPresentation(element).getIcon(false)
val iconProvider = object : KotlinIconProvider() {
override fun isMatchingExpected(declaration: KtDeclaration) = false
var icon: Icon? = null
override fun getIcon(psiElement: PsiElement, flags: Int) = icon
}
val fakeIcon: Icon = object : Icon {
override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) {}
override fun getIconWidth() = 0
override fun getIconHeight() = 0
}
IconProvider.EXTENSION_POINT_NAME.point.registerExtension(iconProvider, LoadingOrder.FIRST, testRootDisposable)
// When the provider has an icon, it should be returned since the provider is first.
iconProvider.icon = fakeIcon
assertEquals(fakeIcon, KotlinDefaultNamedDeclarationPresentation(element).getIcon(false))
// When the provider returns null, execution should continue to the next provider (which returns the original default).
iconProvider.icon = null
assertEquals(defaultIcon, KotlinDefaultNamedDeclarationPresentation(element).getIcon(false))
}
}
| apache-2.0 |
youdonghai/intellij-community | java/java-tests/testSrc/com/intellij/testFramework/fixtures/MultiModuleJava9ProjectDescriptor.kt | 1 | 4188 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework.fixtures
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.ex.temp.TempFileSystem
import com.intellij.pom.java.LanguageLevel
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.LightPlatformTestCase
/**
* Dependencies: 'main' -> 'm2', 'main' -> 'm4', 'main' -> 'm5', 'main' -> 'm6' => 'm7'
*/
object MultiModuleJava9ProjectDescriptor : DefaultLightProjectDescriptor() {
enum class ModuleDescriptor(internal val moduleName: String, internal val rootName: String) {
MAIN(TEST_MODULE_NAME, "/not_used/"),
M2("${TEST_MODULE_NAME}_m2", "src_m2"),
M3("${TEST_MODULE_NAME}_m3", "src_m3"),
M4("${TEST_MODULE_NAME}_m4", "src_m4"),
M5("${TEST_MODULE_NAME}_m5", "src_m5"),
M6("${TEST_MODULE_NAME}_m6", "src_m6"),
M7("${TEST_MODULE_NAME}_m7", "src_m7");
fun root(): VirtualFile =
if (this == MAIN) LightPlatformTestCase.getSourceRoot() else TempFileSystem.getInstance().findFileByPath("/$rootName")!!
}
override fun getSdk(): Sdk = IdeaTestUtil.getMockJdk18()
override fun setUpProject(project: Project, handler: SetupHandler) {
super.setUpProject(project, handler)
runWriteAction {
val main = ModuleManager.getInstance(project).findModuleByName(TEST_MODULE_NAME)!!
val m2 = makeModule(project, ModuleDescriptor.M2)
ModuleRootModificationUtil.addDependency(main, m2)
makeModule(project, ModuleDescriptor.M3)
val m4 = makeModule(project, ModuleDescriptor.M4)
ModuleRootModificationUtil.addDependency(main, m4)
val m5 = makeModule(project, ModuleDescriptor.M5)
ModuleRootModificationUtil.addDependency(main, m5)
val m6 = makeModule(project, ModuleDescriptor.M6)
ModuleRootModificationUtil.addDependency(main, m6)
val m7 = makeModule(project, ModuleDescriptor.M7)
ModuleRootModificationUtil.addDependency(m6, m7, DependencyScope.COMPILE, true)
val libDir = "jar://${PathManagerEx.getTestDataPath()}/codeInsight/jigsaw"
ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-named-1.0.jar!/")
ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-auto-1.0.jar!/")
ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-auto-2.0.jar!/")
ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-multi-release.jar!/")
}
}
private fun makeModule(project: Project, descriptor: ModuleDescriptor): Module {
val path = FileUtil.join(FileUtil.getTempDirectory(), "${descriptor.moduleName}.iml")
val module = createModule(project, path)
val sourceRoot = createSourceRoot(module, descriptor.rootName)
createContentEntry(module, sourceRoot)
return module
}
override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) {
model.getModuleExtension(LanguageLevelModuleExtension::class.java).languageLevel = LanguageLevel.JDK_1_9
}
fun cleanupSourceRoots() = runWriteAction {
ModuleDescriptor.values().asSequence()
.filter { it != ModuleDescriptor.MAIN }
.flatMap { it.root().children.asSequence() }
.forEach { it.delete(this) }
}
} | apache-2.0 |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/preferences/PreferencesBasic1Service.kt | 1 | 172 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.robotservices.preferences
class PreferencesBasic1Service: PreferencesService() | mit |
exercism/xkotlin | exercises/practice/two-fer/.meta/src/reference/kotlin/TwoFer.kt | 1 | 84 | fun twofer(name: String = "you"): String {
return "One for $name, one for me."
} | mit |
sheaam30/setlist | app/src/androidTest/java/setlist/shea/setlist/ExampleInstrumentedTest.kt | 1 | 642 | package setlist.shea.setlist
import android.support.test.InstrumentationRegistry
import android.support.test.runner.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.getTargetContext()
assertEquals("setlist.shea.setlist", appContext.packageName)
}
}
| apache-2.0 |
LWJGL-CI/lwjgl3 | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_mesh_shader.kt | 2 | 185169 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val EXT_mesh_shader = "EXTMeshShader".nativeClassVK("EXT_mesh_shader", type = "device", postfix = "EXT") {
documentation =
"""
This extension provides a new mechanism allowing applications to generate collections of geometric primitives via programmable mesh shading. It is an alternative to the existing programmable primitive shading pipeline, which relied on generating input primitives by a fixed function assembler as well as fixed function vertex fetch.
This extension also adds support for the following SPIR-V extension in Vulkan:
<ul>
<li><a target="_blank" href="https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/EXT/SPV_EXT_mesh_shader.html">{@code SPV_EXT_mesh_shader}</a></li>
</ul>
<h5>VK_EXT_mesh_shader</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_mesh_shader}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>329</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality</li>
<li>Requires {@link KHRSpirv14 VK_KHR_spirv_1_4} to be enabled for any device-level functionality</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Christoph Kubisch <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_mesh_shader]%20@pixeljetstream%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_mesh_shader%20extension*">pixeljetstream</a></li>
</ul></dd>
<dt><b>Extension Proposal</b></dt>
<dd><a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/tree/main/proposals/VK_EXT_mesh_shader.adoc">VK_EXT_mesh_shader</a></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2022-01-20</dd>
<dt><b>Interactions and External Dependencies</b></dt>
<dd><ul>
<li>This extension requires <a target="_blank" href="https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/EXT/SPV_EXT_mesh_shader.html">{@code SPV_EXT_mesh_shader}</a></li>
<li>This extension provides API support for <a target="_blank" href="https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GLSL_EXT_mesh_shader.txt">{@code GLSL_EXT_mesh_shader}</a></li>
<li>Interacts with Vulkan 1.1</li>
<li>Interacts with {@link KHRMultiview VK_KHR_multiview}</li>
<li>Interacts with {@link KHRFragmentShadingRate VK_KHR_fragment_shading_rate}</li>
</ul></dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Christoph Kubisch, NVIDIA</li>
<li>Pat Brown, NVIDIA</li>
<li>Jeff Bolz, NVIDIA</li>
<li>Daniel Koch, NVIDIA</li>
<li>Piers Daniell, NVIDIA</li>
<li>Pierre Boudier, NVIDIA</li>
<li>Patrick Mours, NVIDIA</li>
<li>David Zhao Akeley, NVIDIA</li>
<li>Kedarnath Thangudu, NVIDIA</li>
<li>Timur Kristóf, Valve</li>
<li>Hans-Kristian Arntzen, Valve</li>
<li>Philip Rebohle, Valve</li>
<li>Mike Blumenkrantz, Valve</li>
<li>Slawomir Grajewski, Intel</li>
<li>Michal Pietrasiuk, Intel</li>
<li>Mariusz Merecki, Intel</li>
<li>Tom Olson, ARM</li>
<li>Jan-Harald Fredriksen, ARM</li>
<li>Sandeep Kakarlapudi, ARM</li>
<li>Ruihao Zhang, QUALCOMM</li>
<li>Ricardo Garcia, Igalia, S.L.</li>
<li>Tobias Hector, AMD</li>
<li>Stu Smith, AMD</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_MESH_SHADER_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"EXT_MESH_SHADER_EXTENSION_NAME".."VK_EXT_mesh_shader"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT".."1000328000",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT".."1000328001"
)
EnumConstant(
"Extends {@code VkShaderStageFlagBits}.",
"SHADER_STAGE_TASK_BIT_EXT".enum(0x00000040),
"SHADER_STAGE_MESH_BIT_EXT".enum(0x00000080)
)
EnumConstant(
"Extends {@code VkPipelineStageFlagBits}.",
"PIPELINE_STAGE_TASK_SHADER_BIT_EXT".enum(0x00080000),
"PIPELINE_STAGE_MESH_SHADER_BIT_EXT".enum(0x00100000)
)
EnumConstant(
"Extends {@code VkQueryType}.",
"QUERY_TYPE_MESH_PRIMITIVES_GENERATED_EXT".."1000328000"
)
EnumConstant(
"Extends {@code VkQueryPipelineStatisticFlagBits}.",
"QUERY_PIPELINE_STATISTIC_TASK_SHADER_INVOCATIONS_BIT_EXT".enum(0x00000800),
"QUERY_PIPELINE_STATISTIC_MESH_SHADER_INVOCATIONS_BIT_EXT".enum(0x00001000)
)
EnumConstant(
"Extends {@code VkIndirectCommandsTokenTypeNV}.",
"INDIRECT_COMMANDS_TOKEN_TYPE_DRAW_MESH_TASKS_NV".."1000328000"
)
void(
"CmdDrawMeshTasksEXT",
"""
Draw mesh task work items.
<h5>C Specification</h5>
To record a mesh tasks drawing command, call:
<pre><code>
void vkCmdDrawMeshTasksEXT(
VkCommandBuffer commandBuffer,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ);</code></pre>
<h5>Description</h5>
When the command is executed, a global workgroup consisting of <code>groupCountX × groupCountY × groupCountZ</code> local workgroups is assembled.
<h5>Valid Usage</h5>
<ul>
<li>If a {@code VkSampler} created with {@code magFilter} or {@code minFilter} equal to #FILTER_LINEAR and {@code compareEnable} equal to #FALSE is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT</li>
<li>If a {@code VkSampler} created with {@code mipmapMode} equal to #SAMPLER_MIPMAP_MODE_LINEAR and {@code compareEnable} equal to #FALSE is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT</li>
<li>If a {@code VkImageView} is sampled with <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-depth-compare-operation">depth comparison</a>, the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_SAMPLED_IMAGE_DEPTH_COMPARISON_BIT</li>
<li>If a {@code VkImageView} is accessed using atomic operations as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT</li>
<li>If a {@code VkImageView} is sampled with #FILTER_CUBIC_EXT as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT</li>
<li>Any {@code VkImageView} being sampled with #FILTER_CUBIC_EXT as a result of this command <b>must</b> have a {@code VkImageViewType} and format that supports cubic filtering, as specified by ##VkFilterCubicImageViewImageFormatPropertiesEXT{@code ::filterCubic} returned by {@code vkGetPhysicalDeviceImageFormatProperties2}</li>
<li>Any {@code VkImageView} being sampled with #FILTER_CUBIC_EXT with a reduction mode of either #SAMPLER_REDUCTION_MODE_MIN or #SAMPLER_REDUCTION_MODE_MAX as a result of this command <b>must</b> have a {@code VkImageViewType} and format that supports cubic filtering together with minmax filtering, as specified by ##VkFilterCubicImageViewImageFormatPropertiesEXT{@code ::filterCubicMinmax} returned by {@code vkGetPhysicalDeviceImageFormatProperties2}</li>
<li>Any {@code VkImage} created with a ##VkImageCreateInfo{@code ::flags} containing #IMAGE_CREATE_CORNER_SAMPLED_BIT_NV sampled as a result of this command <b>must</b> only be sampled using a {@code VkSamplerAddressMode} of #SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE</li>
<li>For any {@code VkImageView} being written as a storage image where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT</li>
<li>For any {@code VkImageView} being read as a storage image where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT</li>
<li>For any {@code VkBufferView} being written as a storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkFormatProperties3">buffer features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT</li>
<li>Any {@code VkBufferView} being read as a storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} then the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkFormatProperties3">buffer features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT</li>
<li>For each set <em>n</em> that is statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command, a descriptor set <b>must</b> have been bound to <em>n</em> at the same pipeline bind point, with a {@code VkPipelineLayout} that is compatible for set <em>n</em>, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline}, as described in <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-maintenance4">{@code maintenance4}</a> feature is not enabled, then for each push constant that is statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command, a push constant value <b>must</b> have been set for the same pipeline bind point, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline}, as described in <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li>
<li>Descriptors in each bound descriptor set, specified via {@code vkCmdBindDescriptorSets}, <b>must</b> be valid if they are statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command</li>
<li>A valid pipeline <b>must</b> be bound to the pipeline bind point used by this command</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command requires any dynamic state, that state <b>must</b> have been set or inherited (if the {@link NVInheritedViewportScissor VK_NV_inherited_viewport_scissor} extension is enabled) for {@code commandBuffer}, and done so after any previously bound pipeline with the corresponding state not specified as dynamic</li>
<li>There <b>must</b> not have been any calls to dynamic state setting commands for any state not specified as dynamic in the {@code VkPipeline} object bound to the pipeline bind point used by this command, since that pipeline was bound</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If any stage of the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a uniform buffer, and that stage was created without enabling either #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT or #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT for {@code uniformBuffers}, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess">{@code robustBufferAccess}</a> feature is not enabled, that stage <b>must</b> not access values outside of the range of the buffer as specified in the descriptor set bound to the same pipeline bind point</li>
<li>If any stage of the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a storage buffer, and that stage was created without enabling either #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT or #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT for {@code storageBuffers}, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess">{@code robustBufferAccess}</a> feature is not enabled, that stage <b>must</b> not access values outside of the range of the buffer as specified in the descriptor set bound to the same pipeline bind point</li>
<li>If {@code commandBuffer} is an unprotected command buffer and <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-protectedNoFault">{@code protectedNoFault}</a> is not supported, any resource accessed by the {@code VkPipeline} object bound to the pipeline bind point used by this command <b>must</b> not be a protected resource</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} or {@code VkImageView} object that enables <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#samplers-YCbCr-conversion">sampler Y′C<sub>B</sub>C<sub>R</sub> conversion</a>, that object <b>must</b> only be used with {@code OpImageSample*} or {@code OpImageSparseSample*} instructions</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} or {@code VkImageView} object that enables <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#samplers-YCbCr-conversion">sampler Y′C<sub>B</sub>C<sub>R</sub> conversion</a>, that object <b>must</b> not use the {@code ConstOffset} and {@code Offset} operands</li>
<li>If a {@code VkImageView} is accessed using {@code OpImageWrite} as a result of this command, then the {@code Type} of the {@code Texel} operand of that instruction <b>must</b> have at least as many components as the image view’s format</li>
<li>If a {@code VkBufferView} is accessed using {@code OpImageWrite} as a result of this command, then the {@code Type} of the {@code Texel} operand of that instruction <b>must</b> have at least as many components as the buffer view’s format</li>
<li>If a {@code VkImageView} with a {@code VkFormat} that has a 64-bit component width is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 64</li>
<li>If a {@code VkImageView} with a {@code VkFormat} that has a component width less than 64-bit is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 32</li>
<li>If a {@code VkBufferView} with a {@code VkFormat} that has a 64-bit component width is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 64</li>
<li>If a {@code VkBufferView} with a {@code VkFormat} that has a component width less than 64-bit is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 32</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-sparseImageInt64Atomics">{@code sparseImageInt64Atomics}</a> feature is not enabled, {@code VkImage} objects created with the #IMAGE_CREATE_SPARSE_RESIDENCY_BIT flag <b>must</b> not be accessed by atomic instructions through an {@code OpTypeImage} with a {@code SampledType} with a {@code Width} of 64 by this command</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-sparseImageInt64Atomics">{@code sparseImageInt64Atomics}</a> feature is not enabled, {@code VkBuffer} objects created with the #BUFFER_CREATE_SPARSE_RESIDENCY_BIT flag <b>must</b> not be accessed by atomic instructions through an {@code OpTypeImage} with a {@code SampledType} with a {@code Width} of 64 by this command</li>
<li>If {@code OpImageWeightedSampleQCOM} is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_WEIGHT_SAMPLED_IMAGE_BIT_QCOM</li>
<li>If {@code OpImageWeightedSampleQCOM} uses a {@code VkImageView} as a sample weight image as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_WEIGHT_IMAGE_BIT_QCOM</li>
<li>If {@code OpImageBoxFilterQCOM} is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BOX_FILTER_SAMPLED_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSSDQCOM} is used to read from an {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BLOCK_MATCHING_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSADQCOM} is used to read from an {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BLOCK_MATCHING_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSADQCOM} or OpImageBlockMatchSSDQCOM is used to read from a reference image as result of this command, then the specified reference coordinates <b>must</b> not fail <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-integer-coordinate-validation">integer texel coordinate validation</a>.</li>
<li>If {@code OpImageWeightedSampleQCOM}, {@code OpImageBoxFilterQCOM}, {@code OpImageBlockMatchSSDQCOM}, or {@code OpImageBlockMatchSADQCOM} uses a {@code VkSampler} as a result of this command, then the sampler <b>must</b> have been created with #SAMPLER_CREATE_IMAGE_PROCESSING_BIT_QCOM.</li>
<li>If any command other than {@code OpImageWeightedSampleQCOM}, {@code OpImageBoxFilterQCOM}, {@code OpImageBlockMatchSSDQCOM}, or {@code OpImageBlockMatchSADQCOM} uses a {@code VkSampler} as a result of this command, then the sampler <b>must</b> not have been created with #SAMPLER_CREATE_IMAGE_PROCESSING_BIT_QCOM.</li>
<li>Any shader invocation executed by this command <b>must</b> <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#shaders-termination">terminate</a></li>
<li>The current render pass <b>must</b> be <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#renderpass-compatibility">compatible</a> with the {@code renderPass} member of the ##VkGraphicsPipelineCreateInfo structure specified when creating the {@code VkPipeline} bound to #PIPELINE_BIND_POINT_GRAPHICS</li>
<li>The subpass index of the current render pass <b>must</b> be equal to the {@code subpass} member of the ##VkGraphicsPipelineCreateInfo structure specified when creating the {@code VkPipeline} bound to #PIPELINE_BIND_POINT_GRAPHICS</li>
<li>Every input attachment used by the current subpass <b>must</b> be bound to the pipeline via a descriptor set</li>
<li>If any shader executed by this pipeline accesses an {@code OpTypeImage} variable with a {@code Dim} operand of {@code SubpassData}, it <b>must</b> be decorated with an {@code InputAttachmentIndex} that corresponds to a valid input attachment in the current subpass</li>
<li>Input attachment views accessed in a subpass <b>must</b> be created with the same {@code VkFormat} as the corresponding subpass definition be created with a {@code VkImageView} that is an attachment in the currently bound {@code VkFramebuffer} at an index that corresponds to a valid input attachment in the current subpass</li>
<li>Memory backing image subresources used as attachments in the current render pass <b>must</b> not be written in any way other than as an attachment by this command</li>
<li>If any recorded command in the current subpass will write to an image subresource as an attachment, this command <b>must</b> not read from the memory backing that image subresource in any other way than as an attachment</li>
<li>If any recorded command in the current subpass will read from an image subresource used as an attachment in any way other than as an attachment, this command <b>must</b> not write to that image subresource as an attachment</li>
<li>If the current render pass instance uses a depth/stencil attachment with a read-only layout for the depth aspect, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fragops-depth-write">depth writes</a> <b>must</b> be disabled</li>
<li>If the current render pass instance uses a depth/stencil attachment with a read-only layout for the stencil aspect and stencil test is enabled, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fragops-stencil">all stencil ops</a> <b>must</b> be #STENCIL_OP_KEEP</li>
<li>If the draw is recorded in a render pass instance with multiview enabled, the maximum instance index <b>must</b> be less than or equal to ##VkPhysicalDeviceMultiviewProperties{@code ::maxMultiviewInstanceIndex}</li>
<li>If the bound graphics pipeline was created with ##VkPipelineSampleLocationsStateCreateInfoEXT{@code ::sampleLocationsEnable} set to #TRUE and the current subpass has a depth/stencil attachment, then that attachment <b>must</b> have been created with the #IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT bit set</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT dynamic state enabled then #CmdSetSampleLocationsEXT() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_SCISSOR_WITH_COUNT dynamic state enabled, then #CmdSetViewportWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> match the ##VkPipelineViewportStateCreateInfo{@code ::scissorCount} of the pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SCISSOR_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, then #CmdSetScissorWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code scissorCount} parameter of {@code vkCmdSetScissorWithCount} <b>must</b> match the ##VkPipelineViewportStateCreateInfo{@code ::viewportCount} of the pipeline</li>
<li>If the bound graphics pipeline state was created with both the #DYNAMIC_STATE_SCISSOR_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic states enabled then both #CmdSetViewportWithCount() and #CmdSetScissorWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> match the {@code scissorCount} parameter of {@code vkCmdSetScissorWithCount}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_W_SCALING_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportWScalingStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_W_SCALING_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportWScalingNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportShadingRateImageStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportShadingRatePaletteNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled and a ##VkPipelineViewportSwizzleStateCreateInfoNV structure chained from ##VkPipelineViewportStateCreateInfo, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportSwizzleStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled and a ##VkPipelineViewportExclusiveScissorStateCreateInfoNV structure chained from ##VkPipelineViewportStateCreateInfo, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportExclusiveScissorStateCreateInfoNV{@code ::exclusiveScissorCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE dynamic state enabled then #CmdSetRasterizerDiscardEnable() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_DEPTH_BIAS_ENABLE dynamic state enabled then #CmdSetDepthBiasEnable() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LOGIC_OP_EXT dynamic state enabled then #CmdSetLogicOpEXT() <b>must</b> have been called in the current command buffer prior to this drawing command and the {@code logicOp} <b>must</b> be a valid {@code VkLogicOp} value</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-primitiveFragmentShadingRateWithMultipleViewports">{@code primitiveFragmentShadingRateWithMultipleViewports}</a> limit is not supported, the bound graphics pipeline was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, and any of the shader stages of the bound graphics pipeline write to the {@code PrimitiveShadingRateKHR} built-in, then #CmdSetViewportWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> be 1</li>
<li>If rasterization is not disabled in the bound graphics pipeline, then for each color attachment in the subpass, if the corresponding image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> do not contain #FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT, then the {@code blendEnable} member of the corresponding element of the {@code pAttachments} member of {@code pColorBlendState} <b>must</b> be #FALSE</li>
<li>If rasterization is not disabled in the bound graphics pipeline, and none of the {@link AMDMixedAttachmentSamples VK_AMD_mixed_attachment_samples} extension, the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension, or the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature are enabled, then ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} <b>must</b> be the same as the current subpass color and/or depth/stencil attachments</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound graphics pipeline <b>must</b> have been created with a ##VkPipelineRenderingCreateInfo{@code ::viewMask} equal to ##VkRenderingInfo{@code ::viewMask}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound graphics pipeline <b>must</b> have been created with a ##VkPipelineRenderingCreateInfo{@code ::colorAttachmentCount} equal to ##VkRenderingInfo{@code ::colorAttachmentCount}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::colorAttachmentCount} greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a {@code VkFormat} equal to the corresponding element of ##VkPipelineRenderingCreateInfo{@code ::pColorAttachmentFormats} used to create the currently bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT dynamic state enabled then #CmdSetColorWriteEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code attachmentCount} parameter of {@code vkCmdSetColorWriteEnableEXT} <b>must</b> be greater than or equal to the ##VkPipelineColorBlendStateCreateInfo{@code ::attachmentCount} of the currently bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT dynamic state enabled then #CmdSetColorWriteEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code attachmentCount} parameter of {@code vkCmdSetColorWriteEnableEXT} <b>must</b> be less than or equal to the {@code maxColorAttachments} member of ##VkPhysicalDeviceLimits</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineRenderingCreateInfo{@code ::depthAttachmentFormat} used to create the currently bound graphics pipeline <b>must</b> be equal to the {@code VkFormat} used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineRenderingCreateInfo{@code ::stencilAttachmentFormat} used to create the currently bound graphics pipeline <b>must</b> be equal to the {@code VkFormat} used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingFragmentShadingRateAttachmentInfoKHR{@code ::imageView} was not #NULL_HANDLE, the currently bound graphics pipeline <b>must</b> have been created with #PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingFragmentDensityMapAttachmentInfoEXT{@code ::imageView} was not #NULL_HANDLE, the currently bound graphics pipeline <b>must</b> have been created with #PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT</li>
<li>If the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the current render pass instance was begun with #CmdBeginRendering() with a ##VkRenderingInfo{@code ::colorAttachmentCount} parameter greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a sample count equal to the corresponding element of the {@code pColorAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of the {@code depthStencilAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of the {@code depthStencilAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and the current render pass instance was begun with #CmdBeginRendering() with a ##VkRenderingInfo{@code ::colorAttachmentCount} parameter greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a sample count equal to the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline <b>must</b> have been created with a ##VkGraphicsPipelineCreateInfo{@code ::renderPass} equal to #NULL_HANDLE</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithRasterizerDiscard">{@code primitivesGeneratedQueryWithRasterizerDiscard}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#primsrast-discard">rasterization discard</a> <b>must</b> not be enabled.</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithNonZeroStreams">{@code primitivesGeneratedQueryWithNonZeroStreams}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, the bound graphics pipeline <b>must</b> not have been created with a non-zero value in ##VkPipelineRasterizationStateStreamCreateInfoEXT{@code ::rasterizationStream}.</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT state enabled and the last call to #CmdSetColorBlendEnableEXT() set {@code pColorBlendEnables} for any attachment to #TRUE, then for those attachments in the subpass the corresponding image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, and the current subpass does not use any color and/or depth/stencil attachments, then the {@code rasterizationSamples} in the last call to #CmdSetRasterizationSamplesEXT() <b>must</b> follow the rules for a <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#renderpass-noattachments">zero-attachment subpass</a></li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_MASK_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state disabled, then the {@code samples} parameter in the last call to #CmdSetSampleMaskEXT() <b>must</b> be greater or equal to the ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} parameter used to create the bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_MASK_EXT state and #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT states enabled, then the {@code samples} parameter in the last call to #CmdSetSampleMaskEXT() <b>must</b> be greater or equal to the {@code rasterizationSamples} parameter in the last call to #CmdSetRasterizationSamplesEXT()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, and none of the {@link AMDMixedAttachmentSamples VK_AMD_mixed_attachment_samples} extension, {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension, or the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is enabled, then the {@code rasterizationSamples} in the last call to #CmdSetRasterizationSamplesEXT() <b>must</b> be the same as the current subpass color and/or depth/stencil attachments</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT dynamic state enabled then #CmdSetColorBlendEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendEnableEXT} calls <b>must</b> specify an enable for all active color attachments in the current subpass</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_EQUATION_EXT dynamic state enabled then #CmdSetColorBlendEquationEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendEquationEXT} calls <b>must</b> specify the blend equations for all active color attachments in the current subpass where blending is enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_MASK_EXT dynamic state enabled then #CmdSetColorWriteMaskEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorWriteMaskEXT} calls <b>must</b> specify the color write mask for all active color attachments in the current subpass</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ADVANCED_EXT dynamic state enabled then #CmdSetColorBlendAdvancedEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendAdvancedEXT} calls <b>must</b> specify the advanced blend equations for all active color attachments in the current subpass where blending is enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ADVANCED_EXT and #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT dynamic states enabled and the last calls to #CmdSetColorBlendEnableEXT() and #CmdSetColorBlendAdvancedEXT() have enabled advanced blending, then the number of active color attachments in the current subpass must not exceed <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-advancedBlendMaxColorAttachments">{@code advancedBlendMaxColorAttachments}</a></li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithNonZeroStreams">{@code primitivesGeneratedQueryWithNonZeroStreams}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, and the bound graphics pipeline was created with #DYNAMIC_STATE_RASTERIZATION_STREAM_EXT state enabled, the last call to #CmdSetRasterizationStreamEXT() <b>must</b> have set the {@code rasterizationStream} to zero</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state disabled, then the {@code sampleLocationsPerPixel} member of {@code pSampleLocationsInfo} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> equal the {@code rasterizationSamples} member of the ##VkPipelineMultisampleStateCreateInfo structure the bound graphics pipeline has been created with</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, then the {@code sampleLocationsPerPixel} member of {@code pSampleLocationsInfo} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> equal the {@code rasterizationSamples} parameter of the last call to #CmdSetRasterizationSamplesEXT()</li>
<li>If the bound graphics pipeline was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), and the current subpass has a depth/stencil attachment, then that attachment <b>must</b> have been created with the #IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT bit set</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), then the {@code sampleLocationsInfo.sampleLocationGridSize.width} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> evenly divide ##VkMultisamplePropertiesEXT{@code ::sampleLocationGridSize.width} as returned by #GetPhysicalDeviceMultisamplePropertiesEXT() with a {@code samples} parameter equaling {@code rasterizationSamples}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), then the {@code sampleLocationsInfo.sampleLocationGridSize.height} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> evenly divide ##VkMultisamplePropertiesEXT{@code ::sampleLocationGridSize.height} as returned by #GetPhysicalDeviceMultisamplePropertiesEXT() with a {@code samples} parameter equaling {@code rasterizationSamples}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), the fragment shader code <b>must</b> not statically use the extended instruction {@code InterpolateAtSample}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_MODULATION_TABLE_ENABLE_NV state enabled and the last call to #CmdSetCoverageModulationTableEnableNV() set {@code coverageModulationTableEnable} to #TRUE, then the {@code coverageModulationTableCount} parameter in the last call to #CmdSetCoverageModulationTableNV() <b>must</b> equal the current {@code rasterizationSamples} divided by the number of color samples in the current subpass</li>
<li>If the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension is enabled, and if current subpass has a depth/stencil attachment and depth test, stencil test, or depth bounds test are enabled in the currently bound pipeline state, then the current {@code rasterizationSamples} must be the same as the sample count of the depth/stencil attachment</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_TO_COLOR_ENABLE_NV state enabled and the last call to #CmdSetCoverageToColorEnableNV() set the {@code coverageToColorEnable} to #TRUE, then the current subpass must have a color attachment at the location selected by the last call to #CmdSetCoverageToColorLocationNV() {@code coverageToColorLocation}, with a {@code VkFormat} of #FORMAT_R8_UINT, #FORMAT_R8_SINT, #FORMAT_R16_UINT, #FORMAT_R16_SINT, #FORMAT_R32_UINT, or #FORMAT_R32_SINT</li>
<li>If this {@link NVCoverageReductionMode VK_NV_coverage_reduction_mode} extension is enabled, the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_TO_COLOR_ENABLE_NV and #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT states enabled, the current coverage reduction mode {@code coverageReductionMode}, then the current {@code rasterizationSamples}, and the sample counts for the color and depth/stencil attachments (if the subpass has them) must be a valid combination returned by #GetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_SWIZZLE_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportSwizzleStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_SWIZZLE_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportSwizzleNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension is enabled, and if the current subpass has any color attachments and {@code rasterizationSamples} of the last call to #CmdSetRasterizationSamplesEXT() is greater than the number of color samples, then the pipeline {@code sampleShadingEnable} <b>must</b> be #FALSE</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_RECTANGULAR_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledRectangularLines">{@code stippledRectangularLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_BRESENHAM_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledBresenhamLines">{@code stippledBresenhamLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledSmoothLines">{@code stippledSmoothLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_DEFAULT_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledRectangularLines">{@code stippledRectangularLines}</a> feature <b>must</b> be enabled and ##VkPhysicalDeviceLimits{@code ::strictLines} must be VK_TRUE</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_CONSERVATIVE_RASTERIZATION_MODE_EXT dynamic state enabled, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-conservativePointAndLineRasterization">{@code conservativePointAndLineRasterization}</a> is not supported, and the effective primitive topology output by the last pre-rasterization shader stage is a line or point, then the {@code conservativeRasterizationMode} set by the last call to #CmdSetConservativeRasterizationModeEXT() <b>must</b> be #CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT</li>
<li>If the currently bound pipeline was created with the ##VkPipelineShaderStageCreateInfo{@code ::stage} member of an element of ##VkGraphicsPipelineCreateInfo{@code ::pStages} set to #SHADER_STAGE_VERTEX_BIT, #SHADER_STAGE_TESSELLATION_CONTROL_BIT, #SHADER_STAGE_TESSELLATION_EVALUATION_BIT or #SHADER_STAGE_GEOMETRY_BIT, then <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#queries-mesh-shader">Mesh Shader Queries</a> must not be active</li>
</ul>
<ul>
<li>If the current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS contains a shader using the {@code TaskEXT} {@code Execution} {@code Model}, {@code groupCountX} <b>must</b> be less than or equal to ##VkPhysicalDeviceMeshShaderPropertiesEXT{@code ::maxTaskWorkGroupCount}[0]</li>
<li>If the current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS contains a shader using the {@code TaskEXT} {@code Execution} {@code Model}, {@code groupCountY} <b>must</b> be less than or equal to ##VkPhysicalDeviceMeshShaderPropertiesEXT{@code ::maxTaskWorkGroupCount}[1]</li>
<li>If the current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS contains a shader using the {@code TaskEXT} {@code Execution} {@code Model}, {@code groupCountZ} <b>must</b> be less than or equal to ##VkPhysicalDeviceMeshShaderPropertiesEXT{@code ::maxTaskWorkGroupCount}[2]</li>
<li>If the current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS contains a shader using the {@code TaskEXT} {@code Execution} {@code Model}, The product of {@code groupCountX}, {@code groupCountY} and {@code groupCountZ} <b>must</b> be less than or equal to ##VkPhysicalDeviceMeshShaderPropertiesEXT{@code ::maxTaskWorkGroupTotalCount}</li>
<li>If the current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS does not contain a shader using the {@code TaskEXT} {@code Execution} {@code Model}, {@code groupCountX} <b>must</b> be less than or equal to ##VkPhysicalDeviceMeshShaderPropertiesEXT{@code ::maxMeshWorkGroupCount}[0]</li>
<li>If the current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS does not contain a shader using the {@code TaskEXT} {@code Execution} {@code Model}, {@code groupCountY} <b>must</b> be less than or equal to ##VkPhysicalDeviceMeshShaderPropertiesEXT{@code ::maxMeshWorkGroupCount}[1]</li>
<li>If the current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS does not contain a shader using the {@code TaskEXT} {@code Execution} {@code Model}, {@code groupCountZ} <b>must</b> be less than or equal to ##VkPhysicalDeviceMeshShaderPropertiesEXT{@code ::maxMeshWorkGroupCount}[2]</li>
<li>If the current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS does not contain a shader using the {@code TaskEXT} {@code Execution} {@code Model}, The product of {@code groupCountX}, {@code groupCountY} and {@code groupCountZ} <b>must</b> be less than or equal to ##VkPhysicalDeviceMeshShaderPropertiesEXT{@code ::maxMeshWorkGroupTotalCount}</li>
</ul>
<ul>
<li>The current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS <b>must</b> contain a shader stage using the {@code MeshEXT} {@code Execution} {@code Model}</li>
</ul>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
<li>{@code commandBuffer} <b>must</b> be in the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#commandbuffers-lifecycle">recording state</a></li>
<li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics operations</li>
<li>This command <b>must</b> only be called inside of a render pass instance</li>
<li>This command <b>must</b> only be called outside of a video coding scope</li>
</ul>
<h5>Host Synchronization</h5>
<ul>
<li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
<li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
</ul>
<h5>Command Properties</h5>
<table class="lwjgl">
<thead><tr><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkQueueFlagBits">Supported Queue Types</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
<tbody><tr><td>Primary Secondary</td><td>Inside</td><td>Outside</td><td>Graphics</td><td>Action</td></tr></tbody>
</table>
""",
VkCommandBuffer("commandBuffer", "the command buffer into which the command will be recorded."),
uint32_t("groupCountX", "the number of local workgroups to dispatch in the X dimension."),
uint32_t("groupCountY", "the number of local workgroups to dispatch in the Y dimension."),
uint32_t("groupCountZ", "the number of local workgroups to dispatch in the Z dimension.")
)
void(
"CmdDrawMeshTasksIndirectEXT",
"""
Issue an indirect mesh tasks draw into a command buffer.
<h5>C Specification</h5>
To record an indirect mesh tasks drawing command, call:
<pre><code>
void vkCmdDrawMeshTasksIndirectEXT(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride);</code></pre>
<h5>Description</h5>
{@code vkCmdDrawMeshTasksIndirectEXT} behaves similarly to #CmdDrawMeshTasksEXT() except that the parameters are read by the device from a buffer during execution. {@code drawCount} draws are executed by the command, with parameters taken from {@code buffer} starting at {@code offset} and increasing by {@code stride} bytes for each successive draw. The parameters of each draw are encoded in an array of ##VkDrawMeshTasksIndirectCommandEXT structures. If {@code drawCount} is less than or equal to one, {@code stride} is ignored.
<h5>Valid Usage</h5>
<ul>
<li>If a {@code VkSampler} created with {@code magFilter} or {@code minFilter} equal to #FILTER_LINEAR and {@code compareEnable} equal to #FALSE is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT</li>
<li>If a {@code VkSampler} created with {@code mipmapMode} equal to #SAMPLER_MIPMAP_MODE_LINEAR and {@code compareEnable} equal to #FALSE is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT</li>
<li>If a {@code VkImageView} is sampled with <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-depth-compare-operation">depth comparison</a>, the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_SAMPLED_IMAGE_DEPTH_COMPARISON_BIT</li>
<li>If a {@code VkImageView} is accessed using atomic operations as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT</li>
<li>If a {@code VkImageView} is sampled with #FILTER_CUBIC_EXT as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT</li>
<li>Any {@code VkImageView} being sampled with #FILTER_CUBIC_EXT as a result of this command <b>must</b> have a {@code VkImageViewType} and format that supports cubic filtering, as specified by ##VkFilterCubicImageViewImageFormatPropertiesEXT{@code ::filterCubic} returned by {@code vkGetPhysicalDeviceImageFormatProperties2}</li>
<li>Any {@code VkImageView} being sampled with #FILTER_CUBIC_EXT with a reduction mode of either #SAMPLER_REDUCTION_MODE_MIN or #SAMPLER_REDUCTION_MODE_MAX as a result of this command <b>must</b> have a {@code VkImageViewType} and format that supports cubic filtering together with minmax filtering, as specified by ##VkFilterCubicImageViewImageFormatPropertiesEXT{@code ::filterCubicMinmax} returned by {@code vkGetPhysicalDeviceImageFormatProperties2}</li>
<li>Any {@code VkImage} created with a ##VkImageCreateInfo{@code ::flags} containing #IMAGE_CREATE_CORNER_SAMPLED_BIT_NV sampled as a result of this command <b>must</b> only be sampled using a {@code VkSamplerAddressMode} of #SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE</li>
<li>For any {@code VkImageView} being written as a storage image where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT</li>
<li>For any {@code VkImageView} being read as a storage image where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT</li>
<li>For any {@code VkBufferView} being written as a storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkFormatProperties3">buffer features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT</li>
<li>Any {@code VkBufferView} being read as a storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} then the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkFormatProperties3">buffer features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT</li>
<li>For each set <em>n</em> that is statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command, a descriptor set <b>must</b> have been bound to <em>n</em> at the same pipeline bind point, with a {@code VkPipelineLayout} that is compatible for set <em>n</em>, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline}, as described in <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-maintenance4">{@code maintenance4}</a> feature is not enabled, then for each push constant that is statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command, a push constant value <b>must</b> have been set for the same pipeline bind point, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline}, as described in <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li>
<li>Descriptors in each bound descriptor set, specified via {@code vkCmdBindDescriptorSets}, <b>must</b> be valid if they are statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command</li>
<li>A valid pipeline <b>must</b> be bound to the pipeline bind point used by this command</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command requires any dynamic state, that state <b>must</b> have been set or inherited (if the {@link NVInheritedViewportScissor VK_NV_inherited_viewport_scissor} extension is enabled) for {@code commandBuffer}, and done so after any previously bound pipeline with the corresponding state not specified as dynamic</li>
<li>There <b>must</b> not have been any calls to dynamic state setting commands for any state not specified as dynamic in the {@code VkPipeline} object bound to the pipeline bind point used by this command, since that pipeline was bound</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If any stage of the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a uniform buffer, and that stage was created without enabling either #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT or #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT for {@code uniformBuffers}, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess">{@code robustBufferAccess}</a> feature is not enabled, that stage <b>must</b> not access values outside of the range of the buffer as specified in the descriptor set bound to the same pipeline bind point</li>
<li>If any stage of the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a storage buffer, and that stage was created without enabling either #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT or #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT for {@code storageBuffers}, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess">{@code robustBufferAccess}</a> feature is not enabled, that stage <b>must</b> not access values outside of the range of the buffer as specified in the descriptor set bound to the same pipeline bind point</li>
<li>If {@code commandBuffer} is an unprotected command buffer and <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-protectedNoFault">{@code protectedNoFault}</a> is not supported, any resource accessed by the {@code VkPipeline} object bound to the pipeline bind point used by this command <b>must</b> not be a protected resource</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} or {@code VkImageView} object that enables <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#samplers-YCbCr-conversion">sampler Y′C<sub>B</sub>C<sub>R</sub> conversion</a>, that object <b>must</b> only be used with {@code OpImageSample*} or {@code OpImageSparseSample*} instructions</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} or {@code VkImageView} object that enables <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#samplers-YCbCr-conversion">sampler Y′C<sub>B</sub>C<sub>R</sub> conversion</a>, that object <b>must</b> not use the {@code ConstOffset} and {@code Offset} operands</li>
<li>If a {@code VkImageView} is accessed using {@code OpImageWrite} as a result of this command, then the {@code Type} of the {@code Texel} operand of that instruction <b>must</b> have at least as many components as the image view’s format</li>
<li>If a {@code VkBufferView} is accessed using {@code OpImageWrite} as a result of this command, then the {@code Type} of the {@code Texel} operand of that instruction <b>must</b> have at least as many components as the buffer view’s format</li>
<li>If a {@code VkImageView} with a {@code VkFormat} that has a 64-bit component width is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 64</li>
<li>If a {@code VkImageView} with a {@code VkFormat} that has a component width less than 64-bit is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 32</li>
<li>If a {@code VkBufferView} with a {@code VkFormat} that has a 64-bit component width is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 64</li>
<li>If a {@code VkBufferView} with a {@code VkFormat} that has a component width less than 64-bit is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 32</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-sparseImageInt64Atomics">{@code sparseImageInt64Atomics}</a> feature is not enabled, {@code VkImage} objects created with the #IMAGE_CREATE_SPARSE_RESIDENCY_BIT flag <b>must</b> not be accessed by atomic instructions through an {@code OpTypeImage} with a {@code SampledType} with a {@code Width} of 64 by this command</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-sparseImageInt64Atomics">{@code sparseImageInt64Atomics}</a> feature is not enabled, {@code VkBuffer} objects created with the #BUFFER_CREATE_SPARSE_RESIDENCY_BIT flag <b>must</b> not be accessed by atomic instructions through an {@code OpTypeImage} with a {@code SampledType} with a {@code Width} of 64 by this command</li>
<li>If {@code OpImageWeightedSampleQCOM} is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_WEIGHT_SAMPLED_IMAGE_BIT_QCOM</li>
<li>If {@code OpImageWeightedSampleQCOM} uses a {@code VkImageView} as a sample weight image as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_WEIGHT_IMAGE_BIT_QCOM</li>
<li>If {@code OpImageBoxFilterQCOM} is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BOX_FILTER_SAMPLED_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSSDQCOM} is used to read from an {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BLOCK_MATCHING_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSADQCOM} is used to read from an {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BLOCK_MATCHING_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSADQCOM} or OpImageBlockMatchSSDQCOM is used to read from a reference image as result of this command, then the specified reference coordinates <b>must</b> not fail <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-integer-coordinate-validation">integer texel coordinate validation</a>.</li>
<li>If {@code OpImageWeightedSampleQCOM}, {@code OpImageBoxFilterQCOM}, {@code OpImageBlockMatchSSDQCOM}, or {@code OpImageBlockMatchSADQCOM} uses a {@code VkSampler} as a result of this command, then the sampler <b>must</b> have been created with #SAMPLER_CREATE_IMAGE_PROCESSING_BIT_QCOM.</li>
<li>If any command other than {@code OpImageWeightedSampleQCOM}, {@code OpImageBoxFilterQCOM}, {@code OpImageBlockMatchSSDQCOM}, or {@code OpImageBlockMatchSADQCOM} uses a {@code VkSampler} as a result of this command, then the sampler <b>must</b> not have been created with #SAMPLER_CREATE_IMAGE_PROCESSING_BIT_QCOM.</li>
<li>Any shader invocation executed by this command <b>must</b> <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#shaders-termination">terminate</a></li>
<li>The current render pass <b>must</b> be <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#renderpass-compatibility">compatible</a> with the {@code renderPass} member of the ##VkGraphicsPipelineCreateInfo structure specified when creating the {@code VkPipeline} bound to #PIPELINE_BIND_POINT_GRAPHICS</li>
<li>The subpass index of the current render pass <b>must</b> be equal to the {@code subpass} member of the ##VkGraphicsPipelineCreateInfo structure specified when creating the {@code VkPipeline} bound to #PIPELINE_BIND_POINT_GRAPHICS</li>
<li>Every input attachment used by the current subpass <b>must</b> be bound to the pipeline via a descriptor set</li>
<li>If any shader executed by this pipeline accesses an {@code OpTypeImage} variable with a {@code Dim} operand of {@code SubpassData}, it <b>must</b> be decorated with an {@code InputAttachmentIndex} that corresponds to a valid input attachment in the current subpass</li>
<li>Input attachment views accessed in a subpass <b>must</b> be created with the same {@code VkFormat} as the corresponding subpass definition be created with a {@code VkImageView} that is an attachment in the currently bound {@code VkFramebuffer} at an index that corresponds to a valid input attachment in the current subpass</li>
<li>Memory backing image subresources used as attachments in the current render pass <b>must</b> not be written in any way other than as an attachment by this command</li>
<li>If any recorded command in the current subpass will write to an image subresource as an attachment, this command <b>must</b> not read from the memory backing that image subresource in any other way than as an attachment</li>
<li>If any recorded command in the current subpass will read from an image subresource used as an attachment in any way other than as an attachment, this command <b>must</b> not write to that image subresource as an attachment</li>
<li>If the current render pass instance uses a depth/stencil attachment with a read-only layout for the depth aspect, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fragops-depth-write">depth writes</a> <b>must</b> be disabled</li>
<li>If the current render pass instance uses a depth/stencil attachment with a read-only layout for the stencil aspect and stencil test is enabled, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fragops-stencil">all stencil ops</a> <b>must</b> be #STENCIL_OP_KEEP</li>
<li>If the draw is recorded in a render pass instance with multiview enabled, the maximum instance index <b>must</b> be less than or equal to ##VkPhysicalDeviceMultiviewProperties{@code ::maxMultiviewInstanceIndex}</li>
<li>If the bound graphics pipeline was created with ##VkPipelineSampleLocationsStateCreateInfoEXT{@code ::sampleLocationsEnable} set to #TRUE and the current subpass has a depth/stencil attachment, then that attachment <b>must</b> have been created with the #IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT bit set</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT dynamic state enabled then #CmdSetSampleLocationsEXT() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_SCISSOR_WITH_COUNT dynamic state enabled, then #CmdSetViewportWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> match the ##VkPipelineViewportStateCreateInfo{@code ::scissorCount} of the pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SCISSOR_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, then #CmdSetScissorWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code scissorCount} parameter of {@code vkCmdSetScissorWithCount} <b>must</b> match the ##VkPipelineViewportStateCreateInfo{@code ::viewportCount} of the pipeline</li>
<li>If the bound graphics pipeline state was created with both the #DYNAMIC_STATE_SCISSOR_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic states enabled then both #CmdSetViewportWithCount() and #CmdSetScissorWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> match the {@code scissorCount} parameter of {@code vkCmdSetScissorWithCount}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_W_SCALING_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportWScalingStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_W_SCALING_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportWScalingNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportShadingRateImageStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportShadingRatePaletteNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled and a ##VkPipelineViewportSwizzleStateCreateInfoNV structure chained from ##VkPipelineViewportStateCreateInfo, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportSwizzleStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled and a ##VkPipelineViewportExclusiveScissorStateCreateInfoNV structure chained from ##VkPipelineViewportStateCreateInfo, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportExclusiveScissorStateCreateInfoNV{@code ::exclusiveScissorCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE dynamic state enabled then #CmdSetRasterizerDiscardEnable() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_DEPTH_BIAS_ENABLE dynamic state enabled then #CmdSetDepthBiasEnable() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LOGIC_OP_EXT dynamic state enabled then #CmdSetLogicOpEXT() <b>must</b> have been called in the current command buffer prior to this drawing command and the {@code logicOp} <b>must</b> be a valid {@code VkLogicOp} value</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-primitiveFragmentShadingRateWithMultipleViewports">{@code primitiveFragmentShadingRateWithMultipleViewports}</a> limit is not supported, the bound graphics pipeline was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, and any of the shader stages of the bound graphics pipeline write to the {@code PrimitiveShadingRateKHR} built-in, then #CmdSetViewportWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> be 1</li>
<li>If rasterization is not disabled in the bound graphics pipeline, then for each color attachment in the subpass, if the corresponding image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> do not contain #FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT, then the {@code blendEnable} member of the corresponding element of the {@code pAttachments} member of {@code pColorBlendState} <b>must</b> be #FALSE</li>
<li>If rasterization is not disabled in the bound graphics pipeline, and none of the {@link AMDMixedAttachmentSamples VK_AMD_mixed_attachment_samples} extension, the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension, or the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature are enabled, then ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} <b>must</b> be the same as the current subpass color and/or depth/stencil attachments</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound graphics pipeline <b>must</b> have been created with a ##VkPipelineRenderingCreateInfo{@code ::viewMask} equal to ##VkRenderingInfo{@code ::viewMask}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound graphics pipeline <b>must</b> have been created with a ##VkPipelineRenderingCreateInfo{@code ::colorAttachmentCount} equal to ##VkRenderingInfo{@code ::colorAttachmentCount}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::colorAttachmentCount} greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a {@code VkFormat} equal to the corresponding element of ##VkPipelineRenderingCreateInfo{@code ::pColorAttachmentFormats} used to create the currently bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT dynamic state enabled then #CmdSetColorWriteEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code attachmentCount} parameter of {@code vkCmdSetColorWriteEnableEXT} <b>must</b> be greater than or equal to the ##VkPipelineColorBlendStateCreateInfo{@code ::attachmentCount} of the currently bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT dynamic state enabled then #CmdSetColorWriteEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code attachmentCount} parameter of {@code vkCmdSetColorWriteEnableEXT} <b>must</b> be less than or equal to the {@code maxColorAttachments} member of ##VkPhysicalDeviceLimits</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineRenderingCreateInfo{@code ::depthAttachmentFormat} used to create the currently bound graphics pipeline <b>must</b> be equal to the {@code VkFormat} used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineRenderingCreateInfo{@code ::stencilAttachmentFormat} used to create the currently bound graphics pipeline <b>must</b> be equal to the {@code VkFormat} used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingFragmentShadingRateAttachmentInfoKHR{@code ::imageView} was not #NULL_HANDLE, the currently bound graphics pipeline <b>must</b> have been created with #PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingFragmentDensityMapAttachmentInfoEXT{@code ::imageView} was not #NULL_HANDLE, the currently bound graphics pipeline <b>must</b> have been created with #PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT</li>
<li>If the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the current render pass instance was begun with #CmdBeginRendering() with a ##VkRenderingInfo{@code ::colorAttachmentCount} parameter greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a sample count equal to the corresponding element of the {@code pColorAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of the {@code depthStencilAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of the {@code depthStencilAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and the current render pass instance was begun with #CmdBeginRendering() with a ##VkRenderingInfo{@code ::colorAttachmentCount} parameter greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a sample count equal to the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline <b>must</b> have been created with a ##VkGraphicsPipelineCreateInfo{@code ::renderPass} equal to #NULL_HANDLE</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithRasterizerDiscard">{@code primitivesGeneratedQueryWithRasterizerDiscard}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#primsrast-discard">rasterization discard</a> <b>must</b> not be enabled.</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithNonZeroStreams">{@code primitivesGeneratedQueryWithNonZeroStreams}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, the bound graphics pipeline <b>must</b> not have been created with a non-zero value in ##VkPipelineRasterizationStateStreamCreateInfoEXT{@code ::rasterizationStream}.</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT state enabled and the last call to #CmdSetColorBlendEnableEXT() set {@code pColorBlendEnables} for any attachment to #TRUE, then for those attachments in the subpass the corresponding image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, and the current subpass does not use any color and/or depth/stencil attachments, then the {@code rasterizationSamples} in the last call to #CmdSetRasterizationSamplesEXT() <b>must</b> follow the rules for a <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#renderpass-noattachments">zero-attachment subpass</a></li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_MASK_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state disabled, then the {@code samples} parameter in the last call to #CmdSetSampleMaskEXT() <b>must</b> be greater or equal to the ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} parameter used to create the bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_MASK_EXT state and #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT states enabled, then the {@code samples} parameter in the last call to #CmdSetSampleMaskEXT() <b>must</b> be greater or equal to the {@code rasterizationSamples} parameter in the last call to #CmdSetRasterizationSamplesEXT()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, and none of the {@link AMDMixedAttachmentSamples VK_AMD_mixed_attachment_samples} extension, {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension, or the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is enabled, then the {@code rasterizationSamples} in the last call to #CmdSetRasterizationSamplesEXT() <b>must</b> be the same as the current subpass color and/or depth/stencil attachments</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT dynamic state enabled then #CmdSetColorBlendEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendEnableEXT} calls <b>must</b> specify an enable for all active color attachments in the current subpass</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_EQUATION_EXT dynamic state enabled then #CmdSetColorBlendEquationEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendEquationEXT} calls <b>must</b> specify the blend equations for all active color attachments in the current subpass where blending is enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_MASK_EXT dynamic state enabled then #CmdSetColorWriteMaskEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorWriteMaskEXT} calls <b>must</b> specify the color write mask for all active color attachments in the current subpass</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ADVANCED_EXT dynamic state enabled then #CmdSetColorBlendAdvancedEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendAdvancedEXT} calls <b>must</b> specify the advanced blend equations for all active color attachments in the current subpass where blending is enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ADVANCED_EXT and #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT dynamic states enabled and the last calls to #CmdSetColorBlendEnableEXT() and #CmdSetColorBlendAdvancedEXT() have enabled advanced blending, then the number of active color attachments in the current subpass must not exceed <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-advancedBlendMaxColorAttachments">{@code advancedBlendMaxColorAttachments}</a></li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithNonZeroStreams">{@code primitivesGeneratedQueryWithNonZeroStreams}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, and the bound graphics pipeline was created with #DYNAMIC_STATE_RASTERIZATION_STREAM_EXT state enabled, the last call to #CmdSetRasterizationStreamEXT() <b>must</b> have set the {@code rasterizationStream} to zero</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state disabled, then the {@code sampleLocationsPerPixel} member of {@code pSampleLocationsInfo} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> equal the {@code rasterizationSamples} member of the ##VkPipelineMultisampleStateCreateInfo structure the bound graphics pipeline has been created with</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, then the {@code sampleLocationsPerPixel} member of {@code pSampleLocationsInfo} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> equal the {@code rasterizationSamples} parameter of the last call to #CmdSetRasterizationSamplesEXT()</li>
<li>If the bound graphics pipeline was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), and the current subpass has a depth/stencil attachment, then that attachment <b>must</b> have been created with the #IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT bit set</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), then the {@code sampleLocationsInfo.sampleLocationGridSize.width} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> evenly divide ##VkMultisamplePropertiesEXT{@code ::sampleLocationGridSize.width} as returned by #GetPhysicalDeviceMultisamplePropertiesEXT() with a {@code samples} parameter equaling {@code rasterizationSamples}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), then the {@code sampleLocationsInfo.sampleLocationGridSize.height} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> evenly divide ##VkMultisamplePropertiesEXT{@code ::sampleLocationGridSize.height} as returned by #GetPhysicalDeviceMultisamplePropertiesEXT() with a {@code samples} parameter equaling {@code rasterizationSamples}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), the fragment shader code <b>must</b> not statically use the extended instruction {@code InterpolateAtSample}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_MODULATION_TABLE_ENABLE_NV state enabled and the last call to #CmdSetCoverageModulationTableEnableNV() set {@code coverageModulationTableEnable} to #TRUE, then the {@code coverageModulationTableCount} parameter in the last call to #CmdSetCoverageModulationTableNV() <b>must</b> equal the current {@code rasterizationSamples} divided by the number of color samples in the current subpass</li>
<li>If the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension is enabled, and if current subpass has a depth/stencil attachment and depth test, stencil test, or depth bounds test are enabled in the currently bound pipeline state, then the current {@code rasterizationSamples} must be the same as the sample count of the depth/stencil attachment</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_TO_COLOR_ENABLE_NV state enabled and the last call to #CmdSetCoverageToColorEnableNV() set the {@code coverageToColorEnable} to #TRUE, then the current subpass must have a color attachment at the location selected by the last call to #CmdSetCoverageToColorLocationNV() {@code coverageToColorLocation}, with a {@code VkFormat} of #FORMAT_R8_UINT, #FORMAT_R8_SINT, #FORMAT_R16_UINT, #FORMAT_R16_SINT, #FORMAT_R32_UINT, or #FORMAT_R32_SINT</li>
<li>If this {@link NVCoverageReductionMode VK_NV_coverage_reduction_mode} extension is enabled, the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_TO_COLOR_ENABLE_NV and #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT states enabled, the current coverage reduction mode {@code coverageReductionMode}, then the current {@code rasterizationSamples}, and the sample counts for the color and depth/stencil attachments (if the subpass has them) must be a valid combination returned by #GetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_SWIZZLE_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportSwizzleStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_SWIZZLE_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportSwizzleNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension is enabled, and if the current subpass has any color attachments and {@code rasterizationSamples} of the last call to #CmdSetRasterizationSamplesEXT() is greater than the number of color samples, then the pipeline {@code sampleShadingEnable} <b>must</b> be #FALSE</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_RECTANGULAR_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledRectangularLines">{@code stippledRectangularLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_BRESENHAM_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledBresenhamLines">{@code stippledBresenhamLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledSmoothLines">{@code stippledSmoothLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_DEFAULT_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledRectangularLines">{@code stippledRectangularLines}</a> feature <b>must</b> be enabled and ##VkPhysicalDeviceLimits{@code ::strictLines} must be VK_TRUE</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_CONSERVATIVE_RASTERIZATION_MODE_EXT dynamic state enabled, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-conservativePointAndLineRasterization">{@code conservativePointAndLineRasterization}</a> is not supported, and the effective primitive topology output by the last pre-rasterization shader stage is a line or point, then the {@code conservativeRasterizationMode} set by the last call to #CmdSetConservativeRasterizationModeEXT() <b>must</b> be #CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT</li>
<li>If the currently bound pipeline was created with the ##VkPipelineShaderStageCreateInfo{@code ::stage} member of an element of ##VkGraphicsPipelineCreateInfo{@code ::pStages} set to #SHADER_STAGE_VERTEX_BIT, #SHADER_STAGE_TESSELLATION_CONTROL_BIT, #SHADER_STAGE_TESSELLATION_EVALUATION_BIT or #SHADER_STAGE_GEOMETRY_BIT, then <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#queries-mesh-shader">Mesh Shader Queries</a> must not be active</li>
</ul>
<ul>
<li>If {@code buffer} is non-sparse then it <b>must</b> be bound completely and contiguously to a single {@code VkDeviceMemory} object</li>
<li>{@code buffer} <b>must</b> have been created with the #BUFFER_USAGE_INDIRECT_BUFFER_BIT bit set</li>
<li>{@code offset} <b>must</b> be a multiple of 4</li>
<li>{@code commandBuffer} <b>must</b> not be a protected command buffer</li>
</ul>
<ul>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multiDrawIndirect">{@code multiDrawIndirect}</a> feature is not enabled, {@code drawCount} <b>must</b> be 0 or 1</li>
<li>{@code drawCount} <b>must</b> be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxDrawIndirectCount}</li>
<li>If {@code drawCount} is greater than 1, {@code stride} <b>must</b> be a multiple of 4 and <b>must</b> be greater than or equal to {@code sizeof}(##VkDrawMeshTasksIndirectCommandEXT)</li>
<li>If {@code drawCount} is equal to 1, <code>(offset + sizeof(##VkDrawMeshTasksIndirectCommandEXT))</code> <b>must</b> be less than or equal to the size of {@code buffer}</li>
<li>If {@code drawCount} is greater than 1, <code>(stride × (drawCount - 1) + offset + sizeof(##VkDrawMeshTasksIndirectCommandEXT))</code> <b>must</b> be less than or equal to the size of {@code buffer}</li>
<li>The current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS <b>must</b> contain a shader stage using the {@code MeshEXT} {@code Execution} {@code Model}</li>
</ul>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
<li>{@code buffer} <b>must</b> be a valid {@code VkBuffer} handle</li>
<li>{@code commandBuffer} <b>must</b> be in the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#commandbuffers-lifecycle">recording state</a></li>
<li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics operations</li>
<li>This command <b>must</b> only be called inside of a render pass instance</li>
<li>This command <b>must</b> only be called outside of a video coding scope</li>
<li>Both of {@code buffer}, and {@code commandBuffer} <b>must</b> have been created, allocated, or retrieved from the same {@code VkDevice}</li>
</ul>
<h5>Host Synchronization</h5>
<ul>
<li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
<li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
</ul>
<h5>Command Properties</h5>
<table class="lwjgl">
<thead><tr><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkQueueFlagBits">Supported Queue Types</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
<tbody><tr><td>Primary Secondary</td><td>Inside</td><td>Outside</td><td>Graphics</td><td>Action</td></tr></tbody>
</table>
""",
VkCommandBuffer("commandBuffer", "the command buffer into which the command is recorded."),
VkBuffer("buffer", "the buffer containing draw parameters."),
VkDeviceSize("offset", "the byte offset into {@code buffer} where parameters begin."),
uint32_t("drawCount", "the number of draws to execute, and <b>can</b> be zero."),
uint32_t("stride", "the byte stride between successive sets of draw parameters.")
)
void(
"CmdDrawMeshTasksIndirectCountEXT",
"""
Perform an indirect mesh tasks draw with the draw count sourced from a buffer.
<h5>C Specification</h5>
To record an indirect mesh tasks drawing command with the draw count sourced from a buffer, call:
<pre><code>
void vkCmdDrawMeshTasksIndirectCountEXT(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride);</code></pre>
<h5>Description</h5>
{@code vkCmdDrawMeshTasksIndirectCountEXT} behaves similarly to #CmdDrawMeshTasksIndirectEXT() except that the draw count is read by the device from a buffer during execution. The command will read an unsigned 32-bit integer from {@code countBuffer} located at {@code countBufferOffset} and use this as the draw count.
<h5>Valid Usage</h5>
<ul>
<li>If a {@code VkSampler} created with {@code magFilter} or {@code minFilter} equal to #FILTER_LINEAR and {@code compareEnable} equal to #FALSE is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT</li>
<li>If a {@code VkSampler} created with {@code mipmapMode} equal to #SAMPLER_MIPMAP_MODE_LINEAR and {@code compareEnable} equal to #FALSE is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT</li>
<li>If a {@code VkImageView} is sampled with <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-depth-compare-operation">depth comparison</a>, the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_SAMPLED_IMAGE_DEPTH_COMPARISON_BIT</li>
<li>If a {@code VkImageView} is accessed using atomic operations as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT</li>
<li>If a {@code VkImageView} is sampled with #FILTER_CUBIC_EXT as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT</li>
<li>Any {@code VkImageView} being sampled with #FILTER_CUBIC_EXT as a result of this command <b>must</b> have a {@code VkImageViewType} and format that supports cubic filtering, as specified by ##VkFilterCubicImageViewImageFormatPropertiesEXT{@code ::filterCubic} returned by {@code vkGetPhysicalDeviceImageFormatProperties2}</li>
<li>Any {@code VkImageView} being sampled with #FILTER_CUBIC_EXT with a reduction mode of either #SAMPLER_REDUCTION_MODE_MIN or #SAMPLER_REDUCTION_MODE_MAX as a result of this command <b>must</b> have a {@code VkImageViewType} and format that supports cubic filtering together with minmax filtering, as specified by ##VkFilterCubicImageViewImageFormatPropertiesEXT{@code ::filterCubicMinmax} returned by {@code vkGetPhysicalDeviceImageFormatProperties2}</li>
<li>Any {@code VkImage} created with a ##VkImageCreateInfo{@code ::flags} containing #IMAGE_CREATE_CORNER_SAMPLED_BIT_NV sampled as a result of this command <b>must</b> only be sampled using a {@code VkSamplerAddressMode} of #SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE</li>
<li>For any {@code VkImageView} being written as a storage image where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT</li>
<li>For any {@code VkImageView} being read as a storage image where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT</li>
<li>For any {@code VkBufferView} being written as a storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown}, the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkFormatProperties3">buffer features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT</li>
<li>Any {@code VkBufferView} being read as a storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} then the view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkFormatProperties3">buffer features</a> <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT</li>
<li>For each set <em>n</em> that is statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command, a descriptor set <b>must</b> have been bound to <em>n</em> at the same pipeline bind point, with a {@code VkPipelineLayout} that is compatible for set <em>n</em>, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline}, as described in <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-maintenance4">{@code maintenance4}</a> feature is not enabled, then for each push constant that is statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command, a push constant value <b>must</b> have been set for the same pipeline bind point, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline}, as described in <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li>
<li>Descriptors in each bound descriptor set, specified via {@code vkCmdBindDescriptorSets}, <b>must</b> be valid if they are statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command</li>
<li>A valid pipeline <b>must</b> be bound to the pipeline bind point used by this command</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command requires any dynamic state, that state <b>must</b> have been set or inherited (if the {@link NVInheritedViewportScissor VK_NV_inherited_viewport_scissor} extension is enabled) for {@code commandBuffer}, and done so after any previously bound pipeline with the corresponding state not specified as dynamic</li>
<li>There <b>must</b> not have been any calls to dynamic state setting commands for any state not specified as dynamic in the {@code VkPipeline} object bound to the pipeline bind point used by this command, since that pipeline was bound</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> 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</li>
<li>If any stage of the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a uniform buffer, and that stage was created without enabling either #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT or #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT for {@code uniformBuffers}, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess">{@code robustBufferAccess}</a> feature is not enabled, that stage <b>must</b> not access values outside of the range of the buffer as specified in the descriptor set bound to the same pipeline bind point</li>
<li>If any stage of the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a storage buffer, and that stage was created without enabling either #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT or #PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT for {@code storageBuffers}, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess">{@code robustBufferAccess}</a> feature is not enabled, that stage <b>must</b> not access values outside of the range of the buffer as specified in the descriptor set bound to the same pipeline bind point</li>
<li>If {@code commandBuffer} is an unprotected command buffer and <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-protectedNoFault">{@code protectedNoFault}</a> is not supported, any resource accessed by the {@code VkPipeline} object bound to the pipeline bind point used by this command <b>must</b> not be a protected resource</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} or {@code VkImageView} object that enables <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#samplers-YCbCr-conversion">sampler Y′C<sub>B</sub>C<sub>R</sub> conversion</a>, that object <b>must</b> only be used with {@code OpImageSample*} or {@code OpImageSparseSample*} instructions</li>
<li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} or {@code VkImageView} object that enables <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#samplers-YCbCr-conversion">sampler Y′C<sub>B</sub>C<sub>R</sub> conversion</a>, that object <b>must</b> not use the {@code ConstOffset} and {@code Offset} operands</li>
<li>If a {@code VkImageView} is accessed using {@code OpImageWrite} as a result of this command, then the {@code Type} of the {@code Texel} operand of that instruction <b>must</b> have at least as many components as the image view’s format</li>
<li>If a {@code VkBufferView} is accessed using {@code OpImageWrite} as a result of this command, then the {@code Type} of the {@code Texel} operand of that instruction <b>must</b> have at least as many components as the buffer view’s format</li>
<li>If a {@code VkImageView} with a {@code VkFormat} that has a 64-bit component width is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 64</li>
<li>If a {@code VkImageView} with a {@code VkFormat} that has a component width less than 64-bit is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 32</li>
<li>If a {@code VkBufferView} with a {@code VkFormat} that has a 64-bit component width is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 64</li>
<li>If a {@code VkBufferView} with a {@code VkFormat} that has a component width less than 64-bit is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 32</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-sparseImageInt64Atomics">{@code sparseImageInt64Atomics}</a> feature is not enabled, {@code VkImage} objects created with the #IMAGE_CREATE_SPARSE_RESIDENCY_BIT flag <b>must</b> not be accessed by atomic instructions through an {@code OpTypeImage} with a {@code SampledType} with a {@code Width} of 64 by this command</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-sparseImageInt64Atomics">{@code sparseImageInt64Atomics}</a> feature is not enabled, {@code VkBuffer} objects created with the #BUFFER_CREATE_SPARSE_RESIDENCY_BIT flag <b>must</b> not be accessed by atomic instructions through an {@code OpTypeImage} with a {@code SampledType} with a {@code Width} of 64 by this command</li>
<li>If {@code OpImageWeightedSampleQCOM} is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_WEIGHT_SAMPLED_IMAGE_BIT_QCOM</li>
<li>If {@code OpImageWeightedSampleQCOM} uses a {@code VkImageView} as a sample weight image as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_WEIGHT_IMAGE_BIT_QCOM</li>
<li>If {@code OpImageBoxFilterQCOM} is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BOX_FILTER_SAMPLED_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSSDQCOM} is used to read from an {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BLOCK_MATCHING_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSADQCOM} is used to read from an {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_2_BLOCK_MATCHING_BIT_QCOM</li>
<li>If {@code OpImageBlockMatchSADQCOM} or OpImageBlockMatchSSDQCOM is used to read from a reference image as result of this command, then the specified reference coordinates <b>must</b> not fail <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-integer-coordinate-validation">integer texel coordinate validation</a>.</li>
<li>If {@code OpImageWeightedSampleQCOM}, {@code OpImageBoxFilterQCOM}, {@code OpImageBlockMatchSSDQCOM}, or {@code OpImageBlockMatchSADQCOM} uses a {@code VkSampler} as a result of this command, then the sampler <b>must</b> have been created with #SAMPLER_CREATE_IMAGE_PROCESSING_BIT_QCOM.</li>
<li>If any command other than {@code OpImageWeightedSampleQCOM}, {@code OpImageBoxFilterQCOM}, {@code OpImageBlockMatchSSDQCOM}, or {@code OpImageBlockMatchSADQCOM} uses a {@code VkSampler} as a result of this command, then the sampler <b>must</b> not have been created with #SAMPLER_CREATE_IMAGE_PROCESSING_BIT_QCOM.</li>
<li>Any shader invocation executed by this command <b>must</b> <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#shaders-termination">terminate</a></li>
<li>The current render pass <b>must</b> be <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#renderpass-compatibility">compatible</a> with the {@code renderPass} member of the ##VkGraphicsPipelineCreateInfo structure specified when creating the {@code VkPipeline} bound to #PIPELINE_BIND_POINT_GRAPHICS</li>
<li>The subpass index of the current render pass <b>must</b> be equal to the {@code subpass} member of the ##VkGraphicsPipelineCreateInfo structure specified when creating the {@code VkPipeline} bound to #PIPELINE_BIND_POINT_GRAPHICS</li>
<li>Every input attachment used by the current subpass <b>must</b> be bound to the pipeline via a descriptor set</li>
<li>If any shader executed by this pipeline accesses an {@code OpTypeImage} variable with a {@code Dim} operand of {@code SubpassData}, it <b>must</b> be decorated with an {@code InputAttachmentIndex} that corresponds to a valid input attachment in the current subpass</li>
<li>Input attachment views accessed in a subpass <b>must</b> be created with the same {@code VkFormat} as the corresponding subpass definition be created with a {@code VkImageView} that is an attachment in the currently bound {@code VkFramebuffer} at an index that corresponds to a valid input attachment in the current subpass</li>
<li>Memory backing image subresources used as attachments in the current render pass <b>must</b> not be written in any way other than as an attachment by this command</li>
<li>If any recorded command in the current subpass will write to an image subresource as an attachment, this command <b>must</b> not read from the memory backing that image subresource in any other way than as an attachment</li>
<li>If any recorded command in the current subpass will read from an image subresource used as an attachment in any way other than as an attachment, this command <b>must</b> not write to that image subresource as an attachment</li>
<li>If the current render pass instance uses a depth/stencil attachment with a read-only layout for the depth aspect, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fragops-depth-write">depth writes</a> <b>must</b> be disabled</li>
<li>If the current render pass instance uses a depth/stencil attachment with a read-only layout for the stencil aspect and stencil test is enabled, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fragops-stencil">all stencil ops</a> <b>must</b> be #STENCIL_OP_KEEP</li>
<li>If the draw is recorded in a render pass instance with multiview enabled, the maximum instance index <b>must</b> be less than or equal to ##VkPhysicalDeviceMultiviewProperties{@code ::maxMultiviewInstanceIndex}</li>
<li>If the bound graphics pipeline was created with ##VkPipelineSampleLocationsStateCreateInfoEXT{@code ::sampleLocationsEnable} set to #TRUE and the current subpass has a depth/stencil attachment, then that attachment <b>must</b> have been created with the #IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT bit set</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT dynamic state enabled then #CmdSetSampleLocationsEXT() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_SCISSOR_WITH_COUNT dynamic state enabled, then #CmdSetViewportWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> match the ##VkPipelineViewportStateCreateInfo{@code ::scissorCount} of the pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SCISSOR_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, then #CmdSetScissorWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code scissorCount} parameter of {@code vkCmdSetScissorWithCount} <b>must</b> match the ##VkPipelineViewportStateCreateInfo{@code ::viewportCount} of the pipeline</li>
<li>If the bound graphics pipeline state was created with both the #DYNAMIC_STATE_SCISSOR_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic states enabled then both #CmdSetViewportWithCount() and #CmdSetScissorWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> match the {@code scissorCount} parameter of {@code vkCmdSetScissorWithCount}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_W_SCALING_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportWScalingStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_W_SCALING_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportWScalingNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportShadingRateImageStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportShadingRatePaletteNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled and a ##VkPipelineViewportSwizzleStateCreateInfoNV structure chained from ##VkPipelineViewportStateCreateInfo, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportSwizzleStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled and a ##VkPipelineViewportExclusiveScissorStateCreateInfoNV structure chained from ##VkPipelineViewportStateCreateInfo, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportExclusiveScissorStateCreateInfoNV{@code ::exclusiveScissorCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE dynamic state enabled then #CmdSetRasterizerDiscardEnable() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_DEPTH_BIAS_ENABLE dynamic state enabled then #CmdSetDepthBiasEnable() <b>must</b> have been called in the current command buffer prior to this drawing command</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LOGIC_OP_EXT dynamic state enabled then #CmdSetLogicOpEXT() <b>must</b> have been called in the current command buffer prior to this drawing command and the {@code logicOp} <b>must</b> be a valid {@code VkLogicOp} value</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-primitiveFragmentShadingRateWithMultipleViewports">{@code primitiveFragmentShadingRateWithMultipleViewports}</a> limit is not supported, the bound graphics pipeline was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, and any of the shader stages of the bound graphics pipeline write to the {@code PrimitiveShadingRateKHR} built-in, then #CmdSetViewportWithCount() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code viewportCount} parameter of {@code vkCmdSetViewportWithCount} <b>must</b> be 1</li>
<li>If rasterization is not disabled in the bound graphics pipeline, then for each color attachment in the subpass, if the corresponding image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> do not contain #FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT, then the {@code blendEnable} member of the corresponding element of the {@code pAttachments} member of {@code pColorBlendState} <b>must</b> be #FALSE</li>
<li>If rasterization is not disabled in the bound graphics pipeline, and none of the {@link AMDMixedAttachmentSamples VK_AMD_mixed_attachment_samples} extension, the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension, or the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature are enabled, then ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} <b>must</b> be the same as the current subpass color and/or depth/stencil attachments</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pDepthAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pDepthAttachment} is #IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the depth attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the {@code imageView} member of {@code pStencilAttachment} is not #NULL_HANDLE, and the {@code layout} member of {@code pStencilAttachment} is #IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL, this command <b>must</b> not write any values to the stencil attachment</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound graphics pipeline <b>must</b> have been created with a ##VkPipelineRenderingCreateInfo{@code ::viewMask} equal to ##VkRenderingInfo{@code ::viewMask}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound graphics pipeline <b>must</b> have been created with a ##VkPipelineRenderingCreateInfo{@code ::colorAttachmentCount} equal to ##VkRenderingInfo{@code ::colorAttachmentCount}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::colorAttachmentCount} greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a {@code VkFormat} equal to the corresponding element of ##VkPipelineRenderingCreateInfo{@code ::pColorAttachmentFormats} used to create the currently bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT dynamic state enabled then #CmdSetColorWriteEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code attachmentCount} parameter of {@code vkCmdSetColorWriteEnableEXT} <b>must</b> be greater than or equal to the ##VkPipelineColorBlendStateCreateInfo{@code ::attachmentCount} of the currently bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT dynamic state enabled then #CmdSetColorWriteEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code attachmentCount} parameter of {@code vkCmdSetColorWriteEnableEXT} <b>must</b> be less than or equal to the {@code maxColorAttachments} member of ##VkPhysicalDeviceLimits</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineRenderingCreateInfo{@code ::depthAttachmentFormat} used to create the currently bound graphics pipeline <b>must</b> be equal to the {@code VkFormat} used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineRenderingCreateInfo{@code ::stencilAttachmentFormat} used to create the currently bound graphics pipeline <b>must</b> be equal to the {@code VkFormat} used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingFragmentShadingRateAttachmentInfoKHR{@code ::imageView} was not #NULL_HANDLE, the currently bound graphics pipeline <b>must</b> have been created with #PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR</li>
<li>If the current render pass instance was begun with #CmdBeginRendering() and ##VkRenderingFragmentDensityMapAttachmentInfoEXT{@code ::imageView} was not #NULL_HANDLE, the currently bound graphics pipeline <b>must</b> have been created with #PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT</li>
<li>If the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the current render pass instance was begun with #CmdBeginRendering() with a ##VkRenderingInfo{@code ::colorAttachmentCount} parameter greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a sample count equal to the corresponding element of the {@code pColorAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of the {@code depthStencilAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created with a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of the {@code depthStencilAttachmentSamples} member of ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and the current render pass instance was begun with #CmdBeginRendering() with a ##VkRenderingInfo{@code ::colorAttachmentCount} parameter greater than 0, then each element of the ##VkRenderingInfo{@code ::pColorAttachments} array with a {@code imageView} not equal to #NULL_HANDLE <b>must</b> have been created with a sample count equal to the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and ##VkRenderingInfo{@code ::pDepthAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pDepthAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline was created without a ##VkAttachmentSampleCountInfoAMD or ##VkAttachmentSampleCountInfoNV structure, and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is not enabled, and ##VkRenderingInfo{@code ::pStencilAttachment→imageView} was not #NULL_HANDLE, the value of ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} used to create the currently bound graphics pipeline <b>must</b> be equal to the sample count used to create ##VkRenderingInfo{@code ::pStencilAttachment→imageView}</li>
<li>If the current render pass instance was begun with #CmdBeginRendering(), the currently bound pipeline <b>must</b> have been created with a ##VkGraphicsPipelineCreateInfo{@code ::renderPass} equal to #NULL_HANDLE</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithRasterizerDiscard">{@code primitivesGeneratedQueryWithRasterizerDiscard}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#primsrast-discard">rasterization discard</a> <b>must</b> not be enabled.</li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithNonZeroStreams">{@code primitivesGeneratedQueryWithNonZeroStreams}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, the bound graphics pipeline <b>must</b> not have been created with a non-zero value in ##VkPipelineRasterizationStateStreamCreateInfoEXT{@code ::rasterizationStream}.</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT state enabled and the last call to #CmdSetColorBlendEnableEXT() set {@code pColorBlendEnables} for any attachment to #TRUE, then for those attachments in the subpass the corresponding image view’s <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#resources-image-view-format-features">format features</a> <b>must</b> contain #FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, and the current subpass does not use any color and/or depth/stencil attachments, then the {@code rasterizationSamples} in the last call to #CmdSetRasterizationSamplesEXT() <b>must</b> follow the rules for a <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#renderpass-noattachments">zero-attachment subpass</a></li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_MASK_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state disabled, then the {@code samples} parameter in the last call to #CmdSetSampleMaskEXT() <b>must</b> be greater or equal to the ##VkPipelineMultisampleStateCreateInfo{@code ::rasterizationSamples} parameter used to create the bound graphics pipeline</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_MASK_EXT state and #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT states enabled, then the {@code samples} parameter in the last call to #CmdSetSampleMaskEXT() <b>must</b> be greater or equal to the {@code rasterizationSamples} parameter in the last call to #CmdSetRasterizationSamplesEXT()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, and none of the {@link AMDMixedAttachmentSamples VK_AMD_mixed_attachment_samples} extension, {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension, or the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-multisampledRenderToSingleSampled">{@code multisampledRenderToSingleSampled}</a> feature is enabled, then the {@code rasterizationSamples} in the last call to #CmdSetRasterizationSamplesEXT() <b>must</b> be the same as the current subpass color and/or depth/stencil attachments</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT dynamic state enabled then #CmdSetColorBlendEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendEnableEXT} calls <b>must</b> specify an enable for all active color attachments in the current subpass</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_EQUATION_EXT dynamic state enabled then #CmdSetColorBlendEquationEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendEquationEXT} calls <b>must</b> specify the blend equations for all active color attachments in the current subpass where blending is enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_WRITE_MASK_EXT dynamic state enabled then #CmdSetColorWriteMaskEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorWriteMaskEXT} calls <b>must</b> specify the color write mask for all active color attachments in the current subpass</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ADVANCED_EXT dynamic state enabled then #CmdSetColorBlendAdvancedEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the attachments specified by the {@code firstAttachment} and {@code attachmentCount} parameters of {@code vkCmdSetColorBlendAdvancedEXT} calls <b>must</b> specify the advanced blend equations for all active color attachments in the current subpass where blending is enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COLOR_BLEND_ADVANCED_EXT and #DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT dynamic states enabled and the last calls to #CmdSetColorBlendEnableEXT() and #CmdSetColorBlendAdvancedEXT() have enabled advanced blending, then the number of active color attachments in the current subpass must not exceed <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-advancedBlendMaxColorAttachments">{@code advancedBlendMaxColorAttachments}</a></li>
<li>If the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-primitivesGeneratedQueryWithNonZeroStreams">{@code primitivesGeneratedQueryWithNonZeroStreams}</a> feature is not enabled and the #QUERY_TYPE_PRIMITIVES_GENERATED_EXT query is active, and the bound graphics pipeline was created with #DYNAMIC_STATE_RASTERIZATION_STREAM_EXT state enabled, the last call to #CmdSetRasterizationStreamEXT() <b>must</b> have set the {@code rasterizationStream} to zero</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state disabled, then the {@code sampleLocationsPerPixel} member of {@code pSampleLocationsInfo} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> equal the {@code rasterizationSamples} member of the ##VkPipelineMultisampleStateCreateInfo structure the bound graphics pipeline has been created with</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT state enabled, then the {@code sampleLocationsPerPixel} member of {@code pSampleLocationsInfo} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> equal the {@code rasterizationSamples} parameter of the last call to #CmdSetRasterizationSamplesEXT()</li>
<li>If the bound graphics pipeline was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), and the current subpass has a depth/stencil attachment, then that attachment <b>must</b> have been created with the #IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT bit set</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), then the {@code sampleLocationsInfo.sampleLocationGridSize.width} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> evenly divide ##VkMultisamplePropertiesEXT{@code ::sampleLocationGridSize.width} as returned by #GetPhysicalDeviceMultisamplePropertiesEXT() with a {@code samples} parameter equaling {@code rasterizationSamples}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT state enabled and the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), then the {@code sampleLocationsInfo.sampleLocationGridSize.height} in the last call to #CmdSetSampleLocationsEXT() <b>must</b> evenly divide ##VkMultisamplePropertiesEXT{@code ::sampleLocationGridSize.height} as returned by #GetPhysicalDeviceMultisamplePropertiesEXT() with a {@code samples} parameter equaling {@code rasterizationSamples}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT state enabled, and if {@code sampleLocationsEnable} was #TRUE in the last call to #CmdSetSampleLocationsEnableEXT(), the fragment shader code <b>must</b> not statically use the extended instruction {@code InterpolateAtSample}</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_MODULATION_TABLE_ENABLE_NV state enabled and the last call to #CmdSetCoverageModulationTableEnableNV() set {@code coverageModulationTableEnable} to #TRUE, then the {@code coverageModulationTableCount} parameter in the last call to #CmdSetCoverageModulationTableNV() <b>must</b> equal the current {@code rasterizationSamples} divided by the number of color samples in the current subpass</li>
<li>If the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension is enabled, and if current subpass has a depth/stencil attachment and depth test, stencil test, or depth bounds test are enabled in the currently bound pipeline state, then the current {@code rasterizationSamples} must be the same as the sample count of the depth/stencil attachment</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_TO_COLOR_ENABLE_NV state enabled and the last call to #CmdSetCoverageToColorEnableNV() set the {@code coverageToColorEnable} to #TRUE, then the current subpass must have a color attachment at the location selected by the last call to #CmdSetCoverageToColorLocationNV() {@code coverageToColorLocation}, with a {@code VkFormat} of #FORMAT_R8_UINT, #FORMAT_R8_SINT, #FORMAT_R16_UINT, #FORMAT_R16_SINT, #FORMAT_R32_UINT, or #FORMAT_R32_SINT</li>
<li>If this {@link NVCoverageReductionMode VK_NV_coverage_reduction_mode} extension is enabled, the bound graphics pipeline state was created with the #DYNAMIC_STATE_COVERAGE_TO_COLOR_ENABLE_NV and #DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT states enabled, the current coverage reduction mode {@code coverageReductionMode}, then the current {@code rasterizationSamples}, and the sample counts for the color and depth/stencil attachments (if the subpass has them) must be a valid combination returned by #GetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT dynamic state enabled, but not the #DYNAMIC_STATE_VIEWPORT_SWIZZLE_NV dynamic state enabled, then the bound graphics pipeline <b>must</b> have been created with ##VkPipelineViewportSwizzleStateCreateInfoNV{@code ::viewportCount} greater or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VIEWPORT_WITH_COUNT and #DYNAMIC_STATE_VIEWPORT_SWIZZLE_NV dynamic states enabled then the {@code viewportCount} parameter in the last call to #CmdSetViewportSwizzleNV() <b>must</b> be greater than or equal to the {@code viewportCount} parameter in the last call to #CmdSetViewportWithCount()</li>
<li>If the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extension is enabled, and if the current subpass has any color attachments and {@code rasterizationSamples} of the last call to #CmdSetRasterizationSamplesEXT() is greater than the number of color samples, then the pipeline {@code sampleShadingEnable} <b>must</b> be #FALSE</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_RECTANGULAR_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledRectangularLines">{@code stippledRectangularLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_BRESENHAM_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledBresenhamLines">{@code stippledBresenhamLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledSmoothLines">{@code stippledSmoothLines}</a> feature <b>must</b> be enabled</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT or #DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT dynamic states enabled, and if the current {@code stippledLineEnable} state is #TRUE and the current {@code lineRasterizationMode} state is #LINE_RASTERIZATION_MODE_DEFAULT_EXT, then the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-stippledRectangularLines">{@code stippledRectangularLines}</a> feature <b>must</b> be enabled and ##VkPhysicalDeviceLimits{@code ::strictLines} must be VK_TRUE</li>
<li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_CONSERVATIVE_RASTERIZATION_MODE_EXT dynamic state enabled, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-conservativePointAndLineRasterization">{@code conservativePointAndLineRasterization}</a> is not supported, and the effective primitive topology output by the last pre-rasterization shader stage is a line or point, then the {@code conservativeRasterizationMode} set by the last call to #CmdSetConservativeRasterizationModeEXT() <b>must</b> be #CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT</li>
<li>If the currently bound pipeline was created with the ##VkPipelineShaderStageCreateInfo{@code ::stage} member of an element of ##VkGraphicsPipelineCreateInfo{@code ::pStages} set to #SHADER_STAGE_VERTEX_BIT, #SHADER_STAGE_TESSELLATION_CONTROL_BIT, #SHADER_STAGE_TESSELLATION_EVALUATION_BIT or #SHADER_STAGE_GEOMETRY_BIT, then <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#queries-mesh-shader">Mesh Shader Queries</a> must not be active</li>
</ul>
<ul>
<li>If {@code buffer} is non-sparse then it <b>must</b> be bound completely and contiguously to a single {@code VkDeviceMemory} object</li>
<li>{@code buffer} <b>must</b> have been created with the #BUFFER_USAGE_INDIRECT_BUFFER_BIT bit set</li>
<li>{@code offset} <b>must</b> be a multiple of 4</li>
<li>{@code commandBuffer} <b>must</b> not be a protected command buffer</li>
</ul>
<ul>
<li>If {@code countBuffer} is non-sparse then it <b>must</b> be bound completely and contiguously to a single {@code VkDeviceMemory} object</li>
<li>{@code countBuffer} <b>must</b> have been created with the #BUFFER_USAGE_INDIRECT_BUFFER_BIT bit set</li>
<li>{@code countBufferOffset} <b>must</b> be a multiple of 4</li>
<li>The count stored in {@code countBuffer} <b>must</b> be less than or equal to ##VkPhysicalDeviceLimits{@code ::maxDrawIndirectCount}</li>
<li><code>(countBufferOffset + sizeof(uint32_t))</code> <b>must</b> be less than or equal to the size of {@code countBuffer}</li>
<li>If <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-drawIndirectCount">{@code drawIndirectCount}</a> is not enabled this function <b>must</b> not be used</li>
<li>{@code stride} <b>must</b> be a multiple of 4 and <b>must</b> be greater than or equal to {@code sizeof}(##VkDrawMeshTasksIndirectCommandEXT)</li>
<li>If {@code maxDrawCount} is greater than or equal to 1, <code>(stride × (maxDrawCount - 1) + offset + sizeof(##VkDrawMeshTasksIndirectCommandEXT))</code> <b>must</b> be less than or equal to the size of {@code buffer}</li>
<li>If the count stored in {@code countBuffer} is equal to 1, <code>(offset + sizeof(##VkDrawMeshTasksIndirectCommandEXT))</code> <b>must</b> be less than or equal to the size of {@code buffer}</li>
<li>If the count stored in {@code countBuffer} is greater than 1, <code>(stride × (drawCount - 1) + offset + sizeof(##VkDrawMeshTasksIndirectCommandEXT))</code> <b>must</b> be less than or equal to the size of {@code buffer}</li>
<li>The current pipeline bound to #PIPELINE_BIND_POINT_GRAPHICS <b>must</b> contain a shader stage using the {@code MeshEXT} {@code Execution} {@code Model}</li>
</ul>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
<li>{@code buffer} <b>must</b> be a valid {@code VkBuffer} handle</li>
<li>{@code countBuffer} <b>must</b> be a valid {@code VkBuffer} handle</li>
<li>{@code commandBuffer} <b>must</b> be in the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#commandbuffers-lifecycle">recording state</a></li>
<li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics operations</li>
<li>This command <b>must</b> only be called inside of a render pass instance</li>
<li>This command <b>must</b> only be called outside of a video coding scope</li>
<li>Each of {@code buffer}, {@code commandBuffer}, and {@code countBuffer} <b>must</b> have been created, allocated, or retrieved from the same {@code VkDevice}</li>
</ul>
<h5>Host Synchronization</h5>
<ul>
<li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
<li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
</ul>
<h5>Command Properties</h5>
<table class="lwjgl">
<thead><tr><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkQueueFlagBits">Supported Queue Types</a></th><th><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
<tbody><tr><td>Primary Secondary</td><td>Inside</td><td>Outside</td><td>Graphics</td><td>Action</td></tr></tbody>
</table>
""",
VkCommandBuffer("commandBuffer", "the command buffer into which the command is recorded."),
VkBuffer("buffer", "the buffer containing draw parameters."),
VkDeviceSize("offset", "the byte offset into {@code buffer} where parameters begin."),
VkBuffer("countBuffer", "the buffer containing the draw count."),
VkDeviceSize("countBufferOffset", "the byte offset into {@code countBuffer} where the draw count begins."),
uint32_t("maxDrawCount", "specifies the maximum number of draws that will be executed. The actual number of executed draw calls is the minimum of the count specified in {@code countBuffer} and {@code maxDrawCount}."),
uint32_t("stride", "the byte stride between successive sets of draw parameters.")
)
} | bsd-3-clause |
allotria/intellij-community | platform/testFramework/src/com/intellij/testFramework/ServiceContainerUtil.kt | 1 | 2775 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("ServiceContainerUtil")
package com.intellij.testFramework
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.extensions.BaseExtensionPointName
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.util.messages.ListenerDescriptor
import com.intellij.util.messages.MessageBusOwner
import org.jetbrains.annotations.TestOnly
private val testDescriptor by lazy { DefaultPluginDescriptor("test") }
@TestOnly
fun <T : Any> ComponentManager.registerServiceInstance(serviceInterface: Class<T>, instance: T) {
(this as ComponentManagerImpl).registerServiceInstance(serviceInterface, instance, testDescriptor)
}
@TestOnly
fun <T : Any> ComponentManager.replaceService(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) {
(this as ComponentManagerImpl).replaceServiceInstance(serviceInterface, instance, parentDisposable)
}
/**
* Returns old instance.
*/
@TestOnly
fun <T : Any> ComponentManager.registerComponentInstance(componentInterface: Class<T>, instance: T, parentDisposable: Disposable?): T? {
return (this as ComponentManagerImpl).replaceComponentInstance(componentInterface, instance, parentDisposable)
}
@Suppress("DeprecatedCallableAddReplaceWith")
@TestOnly
@Deprecated("Pass parentDisposable")
fun <T : Any> ComponentManager.registerComponentInstance(componentInterface: Class<T>, instance: T): T? {
return (this as ComponentManagerImpl).replaceComponentInstance(componentInterface, instance, null)
}
@TestOnly
@JvmOverloads
fun ComponentManager.registerComponentImplementation(componentInterface: Class<*>, componentImplementation: Class<*>, shouldBeRegistered: Boolean = false) {
(this as ComponentManagerImpl).registerComponentImplementation(componentInterface, componentImplementation, shouldBeRegistered)
}
@TestOnly
fun <T : Any> ComponentManager.registerExtension(name: BaseExtensionPointName<*>, instance: T, parentDisposable: Disposable) {
extensionArea.getExtensionPoint<T>(name.name).registerExtension(instance, parentDisposable)
}
@TestOnly
fun ComponentManager.getServiceImplementationClassNames(prefix: String): List<String> {
return (this as ComponentManagerImpl).getServiceImplementationClassNames(prefix)
}
fun createSimpleMessageBusOwner(owner: String): MessageBusOwner {
return object : MessageBusOwner {
override fun createListener(descriptor: ListenerDescriptor) = throw UnsupportedOperationException()
override fun isDisposed() = false
override fun toString() = owner
}
} | apache-2.0 |
pattyjogal/MusicScratchpad | app/src/main/java/com/viviose/musicscratchpad/EditorView.kt | 2 | 9913 | package com.viviose.musicscratchpad
import android.annotation.TargetApi
import android.content.Context
import android.graphics.*
import android.graphics.drawable.VectorDrawable
import android.media.MediaPlayer
import android.net.Uri
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
/**
* Created by Patrick on 2/2/2016.
*/
class EditorView : View {
fun pxdp(dp: Float): Float {
val px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics)
return px
}
internal var DEBUG_TAG = "MusicDebug"
internal var navigationBarHeight = 0
internal var conx: Context
val NOTE_WIDTH = 150f
val NOTE_HEIGHT = 100f
internal var paint = Paint()
private val mBitmap: Bitmap? = null
private val mCanvas: Canvas? = null
internal var metrics = context.resources.displayMetrics
internal var density = metrics.density
internal var x: Float = 0.toFloat()
internal var y: Float = 0.toFloat()
internal var ma = context as MainActivity
private var mDetector: GestureDetector? = null
internal var accidental = 0
internal var renderableNote: Note = Note(0f,0f,0)
internal var touchX: Float = 0.toFloat()
internal var touchY: Float = 0.toFloat()
internal var drawNote: Boolean = false
//Loading note images
internal var qnh: Bitmap? = null
internal var hnh: Bitmap? = null
internal var drawDot: Boolean = false
constructor(con: Context) : super(con) {
conx = con
isFocusable = true
isFocusableInTouchMode = true
paint.color = Color.BLACK
}
constructor(con: Context, attrs: AttributeSet) : super(con, attrs) {
conx = con
isFocusable = true
isFocusableInTouchMode = true
paint.color = Color.BLACK
}
constructor(con: Context, attrs: AttributeSet, defStyle: Int) : super(con, attrs, defStyle) {
conx = con
isFocusable = true
isFocusableInTouchMode = true
paint.color = Color.BLACK
}
@TargetApi(21)
public override fun onDraw(c: Canvas) {
// navigation bar height
mDetector = GestureDetector(this.context, mListener())
val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
if (resourceId > 0) {
navigationBarHeight = resources.getDimensionPixelSize(resourceId)
DensityMetrics.navBarHeight = (navigationBarHeight.toFloat())
}
x = width.toFloat()
y = height.toFloat()
DensityMetrics.spaceHeight = ((y - DensityMetrics.getToolbarHeight()) / 8)
paint.strokeWidth = 10f
for (i in 2..6) {
c.drawLine(20f, DensityMetrics.spaceHeight * i + DensityMetrics.getToolbarHeight(), x - 20, DensityMetrics.spaceHeight * i + DensityMetrics.getToolbarHeight(), paint)
}
val altoClef = DensityMetrics.getToolbarHeight() + 2 * DensityMetrics.spaceHeight
if (ClefSetting.clef == Clef.ALTO) {
val b = BitmapFactory.decodeResource(resources, R.drawable.alto_clef)
c.drawBitmap(Bitmap.createScaledBitmap(b, (4 * DensityMetrics.spaceHeight.toInt() / 1.5).toInt(), 4 * DensityMetrics.spaceHeight.toInt(), true), 20f, altoClef, paint)
} else if (ClefSetting.clef == Clef.TREBLE) {
val b = BitmapFactory.decodeResource(resources, R.drawable.treble_clef)
c.drawBitmap(Bitmap.createScaledBitmap(b, 420, 1200, true), 1f, 380f, paint)
} else if (ClefSetting.clef == Clef.BASS) {
val b = BitmapFactory.decodeResource(resources, R.drawable.bass_clef)
c.drawBitmap(Bitmap.createScaledBitmap(b, 420, 610, true), 20f, 500f, paint)
}
if (drawNote) {
drawNoteHead(renderableNote, c)
drawNote = false
}
}
//TODO: Make noteheads for different note values AND stack x values
override fun onTouchEvent(event: MotionEvent): Boolean {
val result = mDetector!!.onTouchEvent(event)
if (!result) {
Log.d("What", "is this gesture?")
}
val x = event.x
val y = event.y - DensityMetrics.getToolbarHeight()
//rhythmBar.setVisibility(View.GONE);
when (event.action) {
MotionEvent.ACTION_DOWN -> {
touchX = x
touchY = y
}
MotionEvent.ACTION_UP -> {
drawNote = true
invalidate()
renderableNote = Note(touchX, touchY, accidental)
var renderNote = true
for (note in MusicStore.activeNotes) {
if (renderableNote.name == note.name && renderableNote.octave == note.octave) {
renderNote = false
Log.d("Note", "Dupe note skipped!")
}
}
if (renderNote) {
MusicStore.activeNotes.add(renderableNote)
}
if (Settings.piano) {
val main = MainActivity()
main.nextInput()
}
}
}
return result
}
@TargetApi(21)
private fun drawNoteHead(note: Note, canvas: Canvas) {
val mediaPlayer = MediaPlayer()
try {
mediaPlayer.setDataSource(context, Uri.parse("android.resource://com.viviose.musicscratchpad/raw/" + note.name.toString() + Integer.toString(note.octave)))
} catch (e: Exception) {
}
Log.i("Media Playing:", "Player created!")
mediaPlayer.setOnPreparedListener { player -> player.start() }
mediaPlayer.setOnCompletionListener { mp -> mp.release() }
try {
mediaPlayer.prepareAsync()
} catch (e: Exception) {
}
//Gotta love gradle build times. Thanks Kotlin lmao
if (note.y - DensityMetrics.getToolbarHeight() <= DensityMetrics.spaceHeight * 2) {
canvas.drawLine(note.x - 200, DensityMetrics.spaceHeight + DensityMetrics.getToolbarHeight(), note.x + 200, DensityMetrics.spaceHeight + DensityMetrics.getToolbarHeight(), paint)
}
if (note.y - DensityMetrics.getToolbarHeight() >= DensityMetrics.spaceHeight * 6) {
canvas.drawLine(note.x - 200, DensityMetrics.spaceHeight * 7 + DensityMetrics.getToolbarHeight(), note.x + 200, DensityMetrics.spaceHeight * 7 + DensityMetrics.getToolbarHeight(), paint)
}
//canvas.drawOval(note.x - NOTE_WIDTH, note.y - DensityMetrics.spaceHeight / 2, note.x + NOTE_WIDTH, note.y + DensityMetrics.spaceHeight / 2, paint);
val headBmap: Bitmap
if (note.rhythm == 2.0) {
headBmap = NoteBitmap.hnh
} else {
headBmap = NoteBitmap.qnh
}
canvas.drawBitmap(Bitmap.createScaledBitmap(headBmap, (DensityMetrics.spaceHeight * 1.697).toInt(), DensityMetrics.spaceHeight.toInt(), true), (note.x - DensityMetrics.spaceHeight * 1.697 / 2).toInt().toFloat(), note.y - DensityMetrics.spaceHeight / 2, paint)
if (LastRhythm.dot) {
//TODO: I don't want these hardcoded obviously
canvas.drawCircle(note.x + 20, note.y + 20, 5f, paint)
LastRhythm.dot = false
}
if ((accidental == 1 && note.name != Note.NoteName.b && note.name != Note.NoteName.e) || note.accidental == 1) {
val vd = ContextCompat.getDrawable(context, R.drawable.sharp) as VectorDrawable
val b = NoteBitmap.getBitmap(vd)
canvas.drawBitmap(Bitmap.createScaledBitmap(b, (NOTE_HEIGHT * 3 / 2).toInt(), NOTE_HEIGHT.toInt() * 3, true), note.x - NOTE_WIDTH * 2, note.y - NOTE_HEIGHT * 3 / 2, paint)
}else if (accidental == -1 && note.name != Note.NoteName.f && note.name != Note.NoteName.c){
val vd = ContextCompat.getDrawable(context, R.drawable.flat) as VectorDrawable
val b = NoteBitmap.getBitmap(vd)
canvas.drawBitmap(Bitmap.createScaledBitmap(b, (NOTE_HEIGHT * 1.35).toInt(), NOTE_HEIGHT.toInt() * 3, true), note.x - NOTE_WIDTH * 2, note.y - NOTE_HEIGHT * 3 / 2, paint)
}
accidental = 0
//Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.alto_clef);
//c.drawBitmap(Bitmap.createScaledBitmap(b, (int) ((4 * (int) DensityMetrics.spaceHeight) / 1.5), 4 * (int) DensityMetrics.spaceHeight, true), 20, altoClef, paint);
}
internal inner class mListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(event: MotionEvent): Boolean {
Log.d(DEBUG_TAG, "onDown: " + event.toString())
return true
}
override fun onFling(ev1: MotionEvent, ev2: MotionEvent, velX: Float, velY: Float): Boolean {
if (velY > 5000) {
accidental = -1
}
if (velY < -5000) {
accidental = 1
}
if (velX < -5000) {
LastRhythm.dot = true;
}
return true
}
override fun onLongPress(event: MotionEvent) {
Log.d(DEBUG_TAG, "onLongPress: " + event.toString())
}
override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float,
distanceY: Float): Boolean {
return true
}
override fun onShowPress(event: MotionEvent) {
Log.d(DEBUG_TAG, "onShowPress: " + event.toString())
}
override fun onSingleTapUp(event: MotionEvent): Boolean {
Log.d(DEBUG_TAG, "onSingleTapUp: " + event.toString())
return true
}
}
companion object {
private val TAG = "EditorView"
}
} | gpl-3.0 |
allotria/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigPairAcceptabilityInspection.kt | 6 | 1124 | // 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.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import org.editorconfig.language.codeinsight.quickfixes.EditorConfigRemoveOptionQuickFix
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigOptionValuePair
import org.editorconfig.language.psi.EditorConfigVisitor
class EditorConfigPairAcceptabilityInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() {
override fun visitOptionValuePair(pair: EditorConfigOptionValuePair) {
if (pair.getDescriptor(false) != null) return
pair.describableParent?.getDescriptor(false) ?: return
val message = EditorConfigBundle["inspection.value.pair.acceptability.message"]
holder.registerProblem(pair, message, EditorConfigRemoveOptionQuickFix())
}
}
}
| apache-2.0 |
matrix-org/matrix-android-sdk | matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoStoreTest.kt | 1 | 3984 | /*
* Copyright 2018 New Vector Ltd
*
* 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.matrix.androidsdk.crypto
import org.junit.Assert.*
import org.junit.Test
import org.matrix.androidsdk.crypto.cryptostore.IMXCryptoStore
import org.matrix.androidsdk.crypto.data.MXOlmSession
import org.matrix.olm.OlmAccount
import org.matrix.olm.OlmManager
import org.matrix.olm.OlmSession
private const val DUMMY_DEVICE_KEY = "DeviceKey"
class CryptoStoreTest {
private val cryptoStoreHelper = CryptoStoreHelper()
@Test
fun test_metadata_file_ok() {
test_metadata_ok(false)
}
@Test
fun test_metadata_realm_ok() {
test_metadata_ok(true)
}
private fun test_metadata_ok(useRealm: Boolean) {
val cryptoStore: IMXCryptoStore = cryptoStoreHelper.createStore(useRealm)
assertFalse(cryptoStore.hasData())
cryptoStore.open()
assertEquals("deviceId_sample", cryptoStore.deviceId)
assertTrue(cryptoStore.hasData())
// Cleanup
cryptoStore.close()
cryptoStore.deleteStore()
}
@Test
fun test_lastSessionUsed() {
// Ensure Olm is initialized
OlmManager()
val cryptoStore: IMXCryptoStore = cryptoStoreHelper.createStore(true)
assertNull(cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
val olmAccount1 = OlmAccount().apply {
generateOneTimeKeys(1)
}
val olmSession1 = OlmSession().apply {
initOutboundSession(olmAccount1,
olmAccount1.identityKeys()[OlmAccount.JSON_KEY_IDENTITY_KEY],
olmAccount1.oneTimeKeys()[OlmAccount.JSON_KEY_ONE_TIME_KEY]?.values?.first())
}
val sessionId1 = olmSession1.sessionIdentifier()
val mxOlmSession1 = MXOlmSession(olmSession1)
cryptoStore.storeSession(mxOlmSession1, DUMMY_DEVICE_KEY)
assertEquals(sessionId1, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
val olmAccount2 = OlmAccount().apply {
generateOneTimeKeys(1)
}
val olmSession2 = OlmSession().apply {
initOutboundSession(olmAccount2,
olmAccount2.identityKeys()[OlmAccount.JSON_KEY_IDENTITY_KEY],
olmAccount2.oneTimeKeys()[OlmAccount.JSON_KEY_ONE_TIME_KEY]?.values?.first())
}
val sessionId2 = olmSession2.sessionIdentifier()
val mxOlmSession2 = MXOlmSession(olmSession2)
cryptoStore.storeSession(mxOlmSession2, DUMMY_DEVICE_KEY)
// Ensure sessionIds are distinct
assertNotEquals(sessionId1, sessionId2)
// Note: we cannot be sure what will be the result of getLastUsedSessionId() here
mxOlmSession2.onMessageReceived()
cryptoStore.storeSession(mxOlmSession2, DUMMY_DEVICE_KEY)
// sessionId2 is returned now
assertEquals(sessionId2, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
Thread.sleep(2)
mxOlmSession1.onMessageReceived()
cryptoStore.storeSession(mxOlmSession1, DUMMY_DEVICE_KEY)
// sessionId1 is returned now
assertEquals(sessionId1, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
// Cleanup
olmSession1.releaseSession()
olmSession2.releaseSession()
olmAccount1.releaseAccount()
olmAccount2.releaseAccount()
}
companion object {
private const val LOG_TAG = "CryptoStoreTest"
}
} | apache-2.0 |
stevesea/RPGpad | adventuresmith-core/src/test/java/org/stevesea/adventuresmith/core/TestHelpers.kt | 2 | 1651 | /*
* Copyright (c) 2016 Steve Christensen
*
* This file is part of Adventuresmith.
*
* Adventuresmith 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.
*
* Adventuresmith 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 Adventuresmith. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.stevesea.adventuresmith.core
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.bind
import com.github.salomonbrys.kodein.instance
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import java.security.SecureRandom
import java.util.Random
fun getMockRandom(mockRandomVal: Int = 1) : Random {
val mockRandom : Random = mock()
whenever(mockRandom.nextInt(any())).thenReturn(mockRandomVal)
return mockRandom
}
fun getKodein(random: Random) = Kodein {
import(adventureSmithModule)
bind<Random>(overrides = true) with instance (random)
}
fun getGenerator(genName: String, mockRandomVal: Int = -1) : Generator {
if (mockRandomVal < 0)
return getKodein(SecureRandom()).instance(genName)
return getKodein(getMockRandom(mockRandomVal)).instance(genName)
}
| gpl-3.0 |
romannurik/muzei | extensions/src/main/java/com/google/android/apps/muzei/util/FlowExt.kt | 1 | 2342 | /*
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.util
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* A convenience wrapper around [androidx.lifecycle.LifecycleCoroutineScope.launch]
* that calls [collect] with [action], all wrapped in a lifecycle-aware
* [repeatOnLifecycle]. Think of it as [kotlinx.coroutines.flow.launchIn], but for
* collecting.
*
* ```
* uiStateFlow.collectIn(owner) { uiState ->
* updateUi(uiState)
* }
* ```
*/
inline fun <T> Flow<T>.collectIn(
owner: LifecycleOwner,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
coroutineContext: CoroutineContext = EmptyCoroutineContext,
crossinline action: suspend (T) -> Unit
) = owner.lifecycleScope.launch(coroutineContext) {
owner.lifecycle.repeatOnLifecycle(minActiveState) {
collect { action(it) }
}
}
/**
* A convenience wrapper around [androidx.lifecycle.LifecycleCoroutineScope.launch]
* that calls [collect], all wrapped in a lifecycle-aware
* [repeatOnLifecycle]. Think of it as [kotlinx.coroutines.flow.launchIn], but for
* collecting.
*
* ```
* uiStateFlow.collectIn(owner)
* ```
*/
fun <T> Flow<T>.collectIn(
owner: LifecycleOwner,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
coroutineContext: CoroutineContext = EmptyCoroutineContext
) = owner.lifecycleScope.launch(coroutineContext) {
owner.lifecycle.repeatOnLifecycle(minActiveState) {
collect()
}
} | apache-2.0 |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineEventComponentFactoryImpl.kt | 1 | 10335 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.timeline
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent
import com.intellij.ui.ColorUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.GithubIcons
import org.intellij.lang.annotations.Language
import org.jetbrains.plugins.github.api.data.GHLabel
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHGitRefName
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestState
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.*
import org.jetbrains.plugins.github.pullrequest.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.ui.timeline.GHPRTimelineItemComponentFactory.Item
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import org.jetbrains.plugins.github.util.GithubUIUtil
import javax.swing.Icon
class GHPRTimelineEventComponentFactoryImpl(private val avatarIconsProvider: GHAvatarIconsProvider)
: GHPRTimelineEventComponentFactory<GHPRTimelineEvent> {
private val simpleEventDelegate = SimpleEventComponentFactory()
private val stateEventDelegate = StateEventComponentFactory()
private val branchEventDelegate = BranchEventComponentFactory()
private val complexEventDelegate = ComplexEventComponentFactory()
override fun createComponent(event: GHPRTimelineEvent): Item {
return when (event) {
is GHPRTimelineEvent.Simple -> simpleEventDelegate.createComponent(event)
is GHPRTimelineEvent.State -> stateEventDelegate.createComponent(event)
is GHPRTimelineEvent.Branch -> branchEventDelegate.createComponent(event)
is GHPRTimelineEvent.Complex -> complexEventDelegate.createComponent(event)
else -> throwUnknownType(event)
}
}
private fun throwUnknownType(item: GHPRTimelineEvent): Nothing {
throw IllegalStateException("""Unknown event type "${item.javaClass.canonicalName}"""")
}
private abstract inner class EventComponentFactory<T : GHPRTimelineEvent> : GHPRTimelineEventComponentFactory<T> {
protected fun eventItem(item: GHPRTimelineEvent, @Language("HTML") titleHTML: String): Item {
return eventItem(GithubIcons.Timeline, item, titleHTML)
}
protected fun eventItem(markerIcon: Icon,
item: GHPRTimelineEvent,
@Language("HTML") titleHTML: String): Item {
return Item(markerIcon, GHPRTimelineItemComponentFactory.actionTitle(avatarIconsProvider, item.actor, titleHTML, item.createdAt))
}
}
private inner class SimpleEventComponentFactory : EventComponentFactory<GHPRTimelineEvent.Simple>() {
override fun createComponent(event: GHPRTimelineEvent.Simple): Item {
return when (event) {
is GHPRAssignedEvent ->
eventItem(event, assigneesHTML(assigned = listOf(event.user)))
is GHPRUnassignedEvent ->
eventItem(event, assigneesHTML(unassigned = listOf(event.user)))
is GHPRReviewRequestedEvent ->
eventItem(event, reviewersHTML(added = listOf(event.requestedReviewer)))
is GHPRReviewUnrequestedEvent ->
eventItem(event, reviewersHTML(removed = listOf(event.requestedReviewer)))
is GHPRLabeledEvent ->
eventItem(event, labelsHTML(added = listOf(event.label)))
is GHPRUnlabeledEvent ->
eventItem(event, labelsHTML(removed = listOf(event.label)))
is GHPRRenamedTitleEvent ->
eventItem(event, renameHTML(event.previousTitle, event.currentTitle))
is GHPRTimelineMergedSimpleEvents -> {
val builder = StringBuilder()
.appendParagraph(labelsHTML(event.addedLabels, event.removedLabels))
.appendParagraph(assigneesHTML(event.assignedPeople, event.unassignedPeople))
.appendParagraph(reviewersHTML(event.addedReviewers, event.removedReviewers))
.appendParagraph(event.rename?.let { renameHTML(it.first, it.second) }.orEmpty())
Item(GithubIcons.Timeline, GHPRTimelineItemComponentFactory.actionTitle(avatarIconsProvider, event.actor, "", event.createdAt),
HtmlEditorPane(builder.toString()).apply {
border = JBUI.Borders.emptyLeft(28)
foreground = UIUtil.getContextHelpForeground()
})
}
else -> throwUnknownType(event)
}
}
private fun assigneesHTML(assigned: Collection<GHUser> = emptyList(), unassigned: Collection<GHUser> = emptyList()): String {
val builder = StringBuilder()
if (assigned.isNotEmpty()) {
builder.append(assigned.joinToString(prefix = "assigned ") { "<b>${it.login}</b>" })
}
if (unassigned.isNotEmpty()) {
if (builder.isNotEmpty()) builder.append(" and ")
builder.append(unassigned.joinToString(prefix = "unassigned ") { "<b>${it.login}</b>" })
}
return builder.toString()
}
private fun reviewersHTML(added: Collection<GHPullRequestRequestedReviewer> = emptyList(),
removed: Collection<GHPullRequestRequestedReviewer> = emptyList()): String {
val builder = StringBuilder()
if (added.isNotEmpty()) {
builder.append(added.joinToString(prefix = "requested a review from ") { "<b>${it.shortName}</b>" })
}
if (removed.isNotEmpty()) {
if (builder.isNotEmpty()) builder.append(" and ")
builder.append(removed.joinToString(prefix = "removed review request from ") { "<b>${it.shortName}</b>" })
}
return builder.toString()
}
private fun labelsHTML(added: Collection<GHLabel> = emptyList(), removed: Collection<GHLabel> = emptyList()): String {
val builder = StringBuilder()
if (added.isNotEmpty()) {
if (added.size > 1) {
builder.append(added.joinToString(prefix = "added labels ") { labelHTML(it) })
}
else {
builder.append("added the ").append(labelHTML(added.first())).append(" label")
}
}
if (removed.isNotEmpty()) {
if (builder.isNotEmpty()) builder.append(" and ")
if (removed.size > 1) {
builder.append(removed.joinToString(prefix = "removed labels ") { labelHTML(it) })
}
else {
builder.append("removed the ").append(labelHTML(removed.first())).append(" label")
}
}
return builder.toString()
}
private fun labelHTML(label: GHLabel): String {
val background = GithubUIUtil.getLabelBackground(label)
val foreground = GithubUIUtil.getLabelForeground(background)
//language=HTML
return """<span style='color: #${ColorUtil.toHex(foreground)}; background: #${ColorUtil.toHex(background)}'>
${StringUtil.escapeXmlEntities(label.name)} </span>"""
}
private fun renameHTML(oldName: String, newName: String) = "renamed this from <b>$oldName</b> to <b>$newName</b>"
}
private inner class StateEventComponentFactory : EventComponentFactory<GHPRTimelineEvent.State>() {
override fun createComponent(event: GHPRTimelineEvent.State): Item {
val icon = when (event.newState) {
GHPullRequestState.CLOSED -> GithubIcons.PullRequestClosed
GHPullRequestState.MERGED -> GithubIcons.PullRequestMerged
GHPullRequestState.OPEN -> GithubIcons.PullRequestOpen
}
val text = when (event.newState) {
GHPullRequestState.CLOSED -> "closed this"
GHPullRequestState.MERGED -> "merged this"
GHPullRequestState.OPEN -> "reopened this"
}
return eventItem(icon, event, text)
}
}
private inner class BranchEventComponentFactory : EventComponentFactory<GHPRTimelineEvent.Branch>() {
override fun createComponent(event: GHPRTimelineEvent.Branch): Item {
return when (event) {
is GHPRBaseRefChangedEvent ->
eventItem(event, "changed the base branch")
is GHPRBaseRefForcePushedEvent ->
eventItem(event, "force-pushed the ${branchHTML(event.ref) ?: "base"} branch")
is GHPRHeadRefForcePushedEvent ->
eventItem(event, "force-pushed the ${branchHTML(event.ref) ?: "head"} branch")
is GHPRHeadRefDeletedEvent ->
eventItem(event, "deleted the ${branchHTML(event.headRefName)} branch")
is GHPRHeadRefRestoredEvent ->
eventItem(event, "restored head branch")
else -> throwUnknownType(event)
}
}
private fun branchHTML(ref: GHGitRefName?) = ref?.name?.let { branchHTML(it) }
//language=HTML
private fun branchHTML(name: String): String {
val foreground = CurrentBranchComponent.TEXT_COLOR
val background = CurrentBranchComponent.getBranchPresentationBackground(UIUtil.getListBackground())
return """<span style='color: #${ColorUtil.toHex(foreground)}; background: #${ColorUtil.toHex(background)}'>
<icon-inline src='GithubIcons.Branch'/>$name </span>"""
}
}
private inner class ComplexEventComponentFactory : EventComponentFactory<GHPRTimelineEvent.Complex>() {
override fun createComponent(event: GHPRTimelineEvent.Complex): Item {
return when (event) {
is GHPRReviewDismissedEvent ->
Item(GithubIcons.Timeline, GHPRTimelineItemComponentFactory.actionTitle(avatarIconsProvider, event.actor,
"dismissed <b>${event.reviewAuthor?.login}</b>`s stale review",
event.createdAt),
event.dismissalMessageHTML?.let {
HtmlEditorPane(it).apply {
border = JBUI.Borders.emptyLeft(28)
}
})
else -> throwUnknownType(event)
}
}
}
companion object {
private fun StringBuilder.appendParagraph(text: String): StringBuilder {
if (text.isNotEmpty()) this.append("<p>").append(text).append("</p>")
return this
}
}
}
| apache-2.0 |
googlecodelabs/android-performance | benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/home/cart/Cart.kt | 1 | 19783 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark_codelab.ui.home.cart
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.macrobenchmark_codelab.R
import com.example.macrobenchmark_codelab.model.OrderLine
import com.example.macrobenchmark_codelab.model.SnackCollection
import com.example.macrobenchmark_codelab.model.SnackRepo
import com.example.macrobenchmark_codelab.ui.components.JetsnackButton
import com.example.macrobenchmark_codelab.ui.components.JetsnackDivider
import com.example.macrobenchmark_codelab.ui.components.JetsnackSurface
import com.example.macrobenchmark_codelab.ui.components.QuantitySelector
import com.example.macrobenchmark_codelab.ui.components.SnackCollection
import com.example.macrobenchmark_codelab.ui.components.SnackImage
import com.example.macrobenchmark_codelab.ui.home.DestinationBar
import com.example.macrobenchmark_codelab.ui.theme.AlphaNearOpaque
import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme
import com.example.macrobenchmark_codelab.ui.utils.formatPrice
@Composable
fun Cart(
onSnackClick: (Long) -> Unit,
modifier: Modifier = Modifier,
viewModel: CartViewModel = viewModel(factory = CartViewModel.provideFactory())
) {
val orderLines by viewModel.orderLines.collectAsState()
val inspiredByCart = remember { SnackRepo.getInspiredByCart() }
Cart(
orderLines = orderLines,
removeSnack = viewModel::removeSnack,
increaseItemCount = viewModel::increaseSnackCount,
decreaseItemCount = viewModel::decreaseSnackCount,
inspiredByCart = inspiredByCart,
onSnackClick = onSnackClick,
modifier = modifier
)
}
@Composable
fun Cart(
orderLines: List<OrderLine>,
removeSnack: (Long) -> Unit,
increaseItemCount: (Long) -> Unit,
decreaseItemCount: (Long) -> Unit,
inspiredByCart: SnackCollection,
onSnackClick: (Long) -> Unit,
modifier: Modifier = Modifier
) {
JetsnackSurface(modifier = modifier.fillMaxSize()) {
Box {
CartContent(
orderLines = orderLines,
removeSnack = removeSnack,
increaseItemCount = increaseItemCount,
decreaseItemCount = decreaseItemCount,
inspiredByCart = inspiredByCart,
onSnackClick = onSnackClick,
modifier = Modifier.align(Alignment.TopCenter)
)
DestinationBar(modifier = Modifier.align(Alignment.TopCenter))
CheckoutBar(modifier = Modifier.align(Alignment.BottomCenter))
}
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
private fun CartContent(
orderLines: List<OrderLine>,
removeSnack: (Long) -> Unit,
increaseItemCount: (Long) -> Unit,
decreaseItemCount: (Long) -> Unit,
inspiredByCart: SnackCollection,
onSnackClick: (Long) -> Unit,
modifier: Modifier = Modifier
) {
val resources = LocalContext.current.resources
val snackCountFormattedString = remember(orderLines.size, resources) {
resources.getQuantityString(
R.plurals.cart_order_count,
orderLines.size, orderLines.size
)
}
LazyColumn(modifier) {
item {
Spacer(
Modifier.windowInsetsTopHeight(
WindowInsets.statusBars.add(WindowInsets(top = 56.dp))
)
)
Text(
text = stringResource(R.string.cart_order_header, snackCountFormattedString),
style = MaterialTheme.typography.h6,
color = JetsnackTheme.colors.brand,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.heightIn(min = 56.dp)
.padding(horizontal = 24.dp, vertical = 4.dp)
.wrapContentHeight()
)
}
items(orderLines) { orderLine ->
SwipeDismissItem(
background = { offsetX ->
/*Background color changes from light gray to red when the
swipe to delete with exceeds 160.dp*/
val backgroundColor = if (offsetX < -160.dp) {
JetsnackTheme.colors.error
} else {
JetsnackTheme.colors.uiFloated
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(backgroundColor),
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.Center
) {
// Set 4.dp padding only if offset is bigger than 160.dp
val padding: Dp by animateDpAsState(
if (offsetX > -160.dp) 4.dp else 0.dp
)
Box(
Modifier
.width(offsetX * -1)
.padding(padding)
) {
// Height equals to width removing padding
val height = (offsetX + 8.dp) * -1
Surface(
modifier = Modifier
.fillMaxWidth()
.height(height)
.align(Alignment.Center),
shape = CircleShape,
color = JetsnackTheme.colors.error
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
// Icon must be visible while in this width range
if (offsetX < -40.dp && offsetX > -152.dp) {
// Icon alpha decreases as it is about to disappear
val iconAlpha: Float by animateFloatAsState(
if (offsetX < -120.dp) 0.5f else 1f
)
Icon(
imageVector = Icons.Filled.DeleteForever,
modifier = Modifier
.size(16.dp)
.graphicsLayer(alpha = iconAlpha),
tint = JetsnackTheme.colors.uiBackground,
contentDescription = null,
)
}
/*Text opacity increases as the text is supposed to appear in
the screen*/
val textAlpha by animateFloatAsState(
if (offsetX > -144.dp) 0.5f else 1f
)
if (offsetX < -120.dp) {
Text(
text = stringResource(id = R.string.remove_item),
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.uiBackground,
textAlign = TextAlign.Center,
modifier = Modifier
.graphicsLayer(
alpha = textAlpha
)
)
}
}
}
}
}
},
) {
CartItem(
orderLine = orderLine,
removeSnack = removeSnack,
increaseItemCount = increaseItemCount,
decreaseItemCount = decreaseItemCount,
onSnackClick = onSnackClick
)
}
}
item {
SummaryItem(
subtotal = orderLines.map { it.snack.price * it.count }.sum(),
shippingCosts = 369
)
}
item {
SnackCollection(
snackCollection = inspiredByCart,
onSnackClick = onSnackClick,
highlight = false
)
Spacer(Modifier.height(56.dp))
}
}
}
@Composable
fun CartItem(
orderLine: OrderLine,
removeSnack: (Long) -> Unit,
increaseItemCount: (Long) -> Unit,
decreaseItemCount: (Long) -> Unit,
onSnackClick: (Long) -> Unit,
modifier: Modifier = Modifier
) {
val snack = orderLine.snack
ConstraintLayout(
modifier = modifier
.fillMaxWidth()
.clickable { onSnackClick(snack.id) }
.background(JetsnackTheme.colors.uiBackground)
.padding(horizontal = 24.dp)
) {
val (divider, image, name, tag, priceSpacer, price, remove, quantity) = createRefs()
createVerticalChain(name, tag, priceSpacer, price, chainStyle = ChainStyle.Packed)
SnackImage(
imageUrl = snack.imageUrl,
contentDescription = null,
modifier = Modifier
.size(100.dp)
.constrainAs(image) {
top.linkTo(parent.top, margin = 16.dp)
bottom.linkTo(parent.bottom, margin = 16.dp)
start.linkTo(parent.start)
}
)
Text(
text = snack.name,
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.textSecondary,
modifier = Modifier.constrainAs(name) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = remove.start,
endMargin = 16.dp,
bias = 0f
)
}
)
IconButton(
onClick = { removeSnack(snack.id) },
modifier = Modifier
.constrainAs(remove) {
top.linkTo(parent.top)
end.linkTo(parent.end)
}
.padding(top = 12.dp)
) {
Icon(
imageVector = Icons.Filled.Close,
tint = JetsnackTheme.colors.iconSecondary,
contentDescription = stringResource(R.string.label_remove)
)
}
Text(
text = snack.tagline,
style = MaterialTheme.typography.body1,
color = JetsnackTheme.colors.textHelp,
modifier = Modifier.constrainAs(tag) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = parent.end,
endMargin = 16.dp,
bias = 0f
)
}
)
Spacer(
Modifier
.height(8.dp)
.constrainAs(priceSpacer) {
linkTo(top = tag.bottom, bottom = price.top)
}
)
Text(
text = formatPrice(snack.price),
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.textPrimary,
modifier = Modifier.constrainAs(price) {
linkTo(
start = image.end,
end = quantity.start,
startMargin = 16.dp,
endMargin = 16.dp,
bias = 0f
)
}
)
QuantitySelector(
count = orderLine.count,
decreaseItemCount = { decreaseItemCount(snack.id) },
increaseItemCount = { increaseItemCount(snack.id) },
modifier = Modifier.constrainAs(quantity) {
baseline.linkTo(price.baseline)
end.linkTo(parent.end)
}
)
JetsnackDivider(
Modifier.constrainAs(divider) {
linkTo(start = parent.start, end = parent.end)
top.linkTo(parent.bottom)
}
)
}
}
@Composable
fun SummaryItem(
subtotal: Long,
shippingCosts: Long,
modifier: Modifier = Modifier
) {
Column(modifier) {
Text(
text = stringResource(R.string.cart_summary_header),
style = MaterialTheme.typography.h6,
color = JetsnackTheme.colors.brand,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.padding(horizontal = 24.dp)
.heightIn(min = 56.dp)
.wrapContentHeight()
)
Row(modifier = Modifier.padding(horizontal = 24.dp)) {
Text(
text = stringResource(R.string.cart_subtotal_label),
style = MaterialTheme.typography.body1,
modifier = Modifier
.weight(1f)
.wrapContentWidth(Alignment.Start)
.alignBy(LastBaseline)
)
Text(
text = formatPrice(subtotal),
style = MaterialTheme.typography.body1,
modifier = Modifier.alignBy(LastBaseline)
)
}
Row(modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) {
Text(
text = stringResource(R.string.cart_shipping_label),
style = MaterialTheme.typography.body1,
modifier = Modifier
.weight(1f)
.wrapContentWidth(Alignment.Start)
.alignBy(LastBaseline)
)
Text(
text = formatPrice(shippingCosts),
style = MaterialTheme.typography.body1,
modifier = Modifier.alignBy(LastBaseline)
)
}
Spacer(modifier = Modifier.height(8.dp))
JetsnackDivider()
Row(modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) {
Text(
text = stringResource(R.string.cart_total_label),
style = MaterialTheme.typography.body1,
modifier = Modifier
.weight(1f)
.padding(end = 16.dp)
.wrapContentWidth(Alignment.End)
.alignBy(LastBaseline)
)
Text(
text = formatPrice(subtotal + shippingCosts),
style = MaterialTheme.typography.subtitle1,
modifier = Modifier.alignBy(LastBaseline)
)
}
JetsnackDivider()
}
}
@Composable
private fun CheckoutBar(modifier: Modifier = Modifier) {
Column(
modifier.background(
JetsnackTheme.colors.uiBackground.copy(alpha = AlphaNearOpaque)
)
) {
JetsnackDivider()
Row {
Spacer(Modifier.weight(1f))
JetsnackButton(
onClick = { /* todo */ },
shape = RectangleShape,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 8.dp)
.weight(1f)
) {
Text(
text = stringResource(id = R.string.cart_checkout),
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Left,
maxLines = 1
)
}
}
}
}
@Preview("default")
@Preview("dark theme", uiMode = UI_MODE_NIGHT_YES)
@Preview("large font", fontScale = 2f)
@Composable
private fun CartPreview() {
JetsnackTheme {
Cart(
orderLines = SnackRepo.getCart(),
removeSnack = {},
increaseItemCount = {},
decreaseItemCount = {},
inspiredByCart = SnackRepo.getInspiredByCart(),
onSnackClick = {}
)
}
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/controlStructures/tryCatchInExpressions/kt17572_ext.kt | 3 | 187 | fun zap(s: String) = s
inline fun tryZap(string: String, fn: String.() -> String) =
fn(try { zap(string) } catch (e: Exception) { "" })
fun box(): String = tryZap("OK") { this } | apache-2.0 |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/collections/Collections.kt | 2 | 89873 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
import kotlin.comparisons.*
internal object EmptyIterator : ListIterator<Nothing> {
override fun hasNext(): Boolean = false
override fun hasPrevious(): Boolean = false
override fun nextIndex(): Int = 0
override fun previousIndex(): Int = -1
override fun next(): Nothing = throw NoSuchElementException()
override fun previous(): Nothing = throw NoSuchElementException()
}
internal object EmptyList : List<Nothing>, RandomAccess {
override fun equals(other: Any?): Boolean = other is List<*> && other.isEmpty()
override fun hashCode(): Int = 1
override fun toString(): String = "[]"
override val size: Int get() = 0
override fun isEmpty(): Boolean = true
override fun contains(element: Nothing): Boolean = false
override fun containsAll(elements: Collection<Nothing>): Boolean = elements.isEmpty()
override fun get(index: Int): Nothing = throw IndexOutOfBoundsException("Empty list doesn't contain element at index $index.")
override fun indexOf(element: Nothing): Int = -1
override fun lastIndexOf(element: Nothing): Int = -1
override fun iterator(): Iterator<Nothing> = EmptyIterator
override fun listIterator(): ListIterator<Nothing> = EmptyIterator
override fun listIterator(index: Int): ListIterator<Nothing> {
if (index != 0) throw IndexOutOfBoundsException("Index: $index")
return EmptyIterator
}
override fun subList(fromIndex: Int, toIndex: Int): List<Nothing> {
if (fromIndex == 0 && toIndex == 0) return this
throw IndexOutOfBoundsException("fromIndex: $fromIndex, toIndex: $toIndex")
}
private fun readResolve(): Any = EmptyList
}
internal fun <T> Array<out T>.asCollection(): Collection<T> = ArrayAsCollection(this, isVarargs = false)
private class ArrayAsCollection<T>(val values: Array<out T>, val isVarargs: Boolean): Collection<T> {
override val size: Int get() = values.size
override fun isEmpty(): Boolean = values.isEmpty()
override fun contains(element: T): Boolean = values.contains(element)
override fun containsAll(elements: Collection<T>): Boolean = elements.all { contains(it) }
override fun iterator(): Iterator<T> = values.iterator()
// override hidden toArray implementation to prevent copying of values array
public fun toArray(): Array<out Any?> = values.copyToArrayOfAny(isVarargs)
}
/** Returns an empty read-only list. */
public fun <T> emptyList(): List<T> = EmptyList
/** Returns a new read-only list of given elements. */
public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elements.asList() else emptyList()
/** Returns an empty read-only list. */
@kotlin.internal.InlineOnly
public inline fun <T> listOf(): List<T> = emptyList()
/** Returns a new [MutableList] with the given elements. */
public fun <T> mutableListOf(vararg elements: T): MutableList<T>
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
// This part is from generated _Collections.kt.
/** Returns a new [ArrayList] with the given elements. */
public fun <T> arrayListOf(vararg elements: T): ArrayList<T>
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
/** Returns a new read-only list either of single given element, if it is not null,
* or empty list it the element is null.*/
public fun <T : Any> listOfNotNull(element: T?): List<T> =
if (element != null) listOf(element) else emptyList()
/** Returns a new read-only list only of those given elements, that are not null. */
public fun <T : Any> listOfNotNull(vararg elements: T?): List<T> = elements.filterNotNull()
/**
* Creates a new read-only list with the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns a list element given its index.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T> = MutableList(size, init)
/**
* Creates a new mutable list with the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns a list element given its index.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> {
val list = ArrayList<T>(size)
repeat(size) { index -> list.add(init(index)) }
return list
}
/**
* Returns an [IntRange] of the valid indices for this collection.
*/
public val Collection<*>.indices: IntRange
get() = 0..size - 1
/**
* Returns the index of the last item in the list or -1 if the list is empty.
*
* @sample samples.collections.Collections.Lists.lastIndexOfList
*/
public val <T> List<T>.lastIndex: Int
get() = this.size - 1
/** Returns `true` if the collection is not empty. */
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.isNotEmpty(): Boolean = !isEmpty()
/** Returns this Collection if it's not `null` and the empty list otherwise. */
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>?.orEmpty(): Collection<T> = this ?: emptyList()
@kotlin.internal.InlineOnly
public inline fun <T> List<T>?.orEmpty(): List<T> = this ?: emptyList()
/**
* Checks if all elements in the specified collection are contained in this collection.
*
* Allows to overcome type-safety restriction of `containsAll` that requires to pass a collection of type `Collection<E>`.
*/
@kotlin.internal.InlineOnly
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public inline fun <@kotlin.internal.OnlyInputTypes T> Collection<T>.containsAll(
elements: Collection<T>): Boolean = this.containsAll(elements)
// copies typed varargs array to array of objects
// TODO: generally wrong, wrt specialization.
@FixmeSpecialization
private fun <T> Array<out T>.copyToArrayOfAny(isVarargs: Boolean): Array<Any?> =
if (isVarargs)
// if the array came from varargs and already is array of Any, copying isn't required.
@Suppress("UNCHECKED_CAST") (this as Array<Any?>)
else
@Suppress("UNCHECKED_CAST") (this.copyOfUninitializedElements(this.size) as Array<Any?>)
/**
* Classes that inherit from this interface can be represented as a sequence of elements that can
* be iterated over.
* @param T the type of element being iterated over.
*/
public interface Iterable<out T> {
/**
* Returns an iterator over the elements of this object.
*/
public operator fun iterator(): Iterator<T>
}
/**
* Classes that inherit from this interface can be represented as a sequence of elements that can
* be iterated over and that supports removing elements during iteration.
*/
public interface MutableIterable<out T> : Iterable<T> {
/**
* Returns an iterator over the elementrs of this sequence that supports removing elements during iteration.
*/
override fun iterator(): MutableIterator<T>
}
public fun <T> Array<out T>.asList(): List<T> {
return object : AbstractList<T>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: T): Boolean = [email protected](element)
override fun get(index: Int): T = this@asList[index]
override fun indexOf(element: T): Int = [email protected](element)
override fun lastIndexOf(element: T): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun ByteArray.asList(): List<Byte> {
return object : AbstractList<Byte>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Byte): Boolean = [email protected](element)
override fun get(index: Int): Byte = this@asList[index]
override fun indexOf(element: Byte): Int = [email protected](element)
override fun lastIndexOf(element: Byte): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun ShortArray.asList(): List<Short> {
return object : AbstractList<Short>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Short): Boolean = [email protected](element)
override fun get(index: Int): Short = this@asList[index]
override fun indexOf(element: Short): Int = [email protected](element)
override fun lastIndexOf(element: Short): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun IntArray.asList(): List<Int> {
return object : AbstractList<Int>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Int): Boolean = [email protected](element)
override fun get(index: Int): Int = this@asList[index]
override fun indexOf(element: Int): Int = [email protected](element)
override fun lastIndexOf(element: Int): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun LongArray.asList(): List<Long> {
return object : AbstractList<Long>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Long): Boolean = [email protected](element)
override fun get(index: Int): Long = this@asList[index]
override fun indexOf(element: Long): Int = [email protected](element)
override fun lastIndexOf(element: Long): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun FloatArray.asList(): List<Float> {
return object : AbstractList<Float>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Float): Boolean = [email protected](element)
override fun get(index: Int): Float = this@asList[index]
override fun indexOf(element: Float): Int = [email protected](element)
override fun lastIndexOf(element: Float): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun DoubleArray.asList(): List<Double> {
return object : AbstractList<Double>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Double): Boolean = [email protected](element)
override fun get(index: Int): Double = this@asList[index]
override fun indexOf(element: Double): Int = [email protected](element)
override fun lastIndexOf(element: Double): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun BooleanArray.asList(): List<Boolean> {
return object : AbstractList<Boolean>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Boolean): Boolean = [email protected](element)
override fun get(index: Int): Boolean = this@asList[index]
override fun indexOf(element: Boolean): Int = [email protected](element)
override fun lastIndexOf(element: Boolean): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun CharArray.asList(): List<Char> {
return object : AbstractList<Char>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Char): Boolean = [email protected](element)
override fun get(index: Int): Char = this@asList[index]
override fun indexOf(element: Char): Int = [email protected](element)
override fun lastIndexOf(element: Char): Int = [email protected](element)
}
}
@Fixme
internal fun <T> List<T>.optimizeReadOnlyList() = this
/**
* Searches this list or its range for the provided [element] using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the Comparable natural ordering of its elements,
* otherwise the result is undefined.
*
* If the list contains multiple elements equal to the specified [element], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public fun <T: Comparable<T>> List<T?>.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int {
rangeCheck(size, fromIndex, toIndex)
var lowBorder = fromIndex
var highBorder = toIndex - 1
while (lowBorder <= highBorder) {
val middleIndex = (lowBorder + highBorder).ushr(1) // safe from overflows
val middleValue = get(middleIndex)
val comparisonResult = compareValues(middleValue, element)
if (comparisonResult < 0)
lowBorder = middleIndex + 1
else if (comparisonResult > 0)
highBorder = middleIndex - 1
else
return middleIndex // key found
}
return -(lowBorder + 1) // key not found
}
/**
* Searches this list or its range for the provided [element] using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the specified [comparator],
* otherwise the result is undefined.
*
* If the list contains multiple elements equal to the specified [element], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted according to the specified [comparator].
*/
public fun <T> List<T>.binarySearch(element: T, comparator: Comparator<in T>, fromIndex: Int = 0, toIndex: Int = size): Int {
rangeCheck(size, fromIndex, toIndex)
var lowBorder = fromIndex
var highBorder = toIndex - 1
while (lowBorder <= highBorder) {
val middleIndex = (lowBorder + highBorder).ushr(1) // safe from overflows
val middleValue = get(middleIndex)
val comparisonResult = comparator.compare(middleValue, element)
if (comparisonResult < 0)
lowBorder = middleIndex + 1
else if (comparisonResult > 0)
highBorder = middleIndex - 1
else
return middleIndex // key found
}
return -(lowBorder + 1) // key not found
}
/**
* Searches this list or its range for an element having the key returned by the specified [selector] function
* equal to the provided [key] value using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the Comparable natural ordering of keys of its elements.
* otherwise the result is undefined.
*
* If the list contains multiple elements with the specified [key], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element with the specified [key], if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size, crossinline selector: (T) -> K?): Int =
binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) }
/**
* Searches this list or its range for an element for which [comparison] function returns zero using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the provided [comparison],
* otherwise the result is undefined.
*
* If the list contains multiple elements for which [comparison] returns zero, there is no guarantee which one will be found.
*
* @param comparison function that compares an element of the list with the element being searched.
*
* @return the index of the found element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public fun <T> List<T>.binarySearch(fromIndex: Int = 0, toIndex: Int = size, comparison: (T) -> Int): Int {
rangeCheck(size, fromIndex, toIndex)
var lowBorder = fromIndex
var highBorder = toIndex - 1
while (lowBorder <= highBorder) {
val middleIndex = (lowBorder + highBorder).ushr(1) // safe from overflows
val middleValue = get(middleIndex)
val comparisonResult = comparison(middleValue)
if (comparisonResult < 0)
lowBorder = middleIndex + 1
else if (comparisonResult > 0)
highBorder = middleIndex - 1
else
return middleIndex // key found
}
return -(lowBorder + 1) // key not found
}
/**
* Checks that `from` and `to` are in
* the range of [0..size] and throws an appropriate exception, if they aren't.
*/
private fun rangeCheck(size: Int, fromIndex: Int, toIndex: Int) {
when {
fromIndex > toIndex -> throw IllegalArgumentException("fromIndex ($fromIndex) is greater than toIndex ($toIndex).")
fromIndex < 0 -> throw IndexOutOfBoundsException("fromIndex ($fromIndex) is less than zero.")
toIndex > size -> throw IndexOutOfBoundsException("toIndex ($toIndex) is greater than size ($size).")
}
}
// From generated _Collections.kt.
/////////
/**
* Returns 1st *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component1(): T {
return get(0)
}
/**
* Returns 2nd *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component2(): T {
return get(1)
}
/**
* Returns 3rd *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component3(): T {
return get(2)
}
/**
* Returns 4th *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component4(): T {
return get(3)
}
/**
* Returns 5th *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component5(): T {
return get(4)
}
/**
* Returns `true` if [element] is found in the collection.
*/
public operator fun <@kotlin.internal.OnlyInputTypes T> Iterable<T>.contains(element: T): Boolean {
if (this is Collection)
return contains(element)
return indexOf(element) >= 0
}
/**
* Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this collection.
*/
public fun <T> Iterable<T>.elementAt(index: Int): T {
if (this is List)
return get(index)
return elementAtOrElse(index) { throw IndexOutOfBoundsException("Collection doesn't contain element at index $index.") }
}
/**
* Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this list.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.elementAt(index: Int): T {
return get(index)
}
/**
* Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this collection.
*/
public fun <T> Iterable<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
if (this is List)
return this.getOrElse(index, defaultValue)
if (index < 0)
return defaultValue(index)
val iterator = iterator()
var count = 0
while (iterator.hasNext()) {
val element = iterator.next()
if (index == count++)
return element
}
return defaultValue(index)
}
/**
* Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this list.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}
/**
* Returns an element at the given [index] or `null` if the [index] is out of bounds of this collection.
*/
public fun <T> Iterable<T>.elementAtOrNull(index: Int): T? {
if (this is List)
return this.getOrNull(index)
if (index < 0)
return null
val iterator = iterator()
var count = 0
while (iterator.hasNext()) {
val element = iterator.next()
if (index == count++)
return element
}
return null
}
/**
* Returns an element at the given [index] or `null` if the [index] is out of bounds of this list.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.elementAtOrNull(index: Int): T? {
return this.getOrNull(index)
}
/**
* Returns the first element matching the given [predicate], or `null` if no such element was found.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? {
return firstOrNull(predicate)
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.findLast(predicate: (T) -> Boolean): T? {
return lastOrNull(predicate)
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.findLast(predicate: (T) -> Boolean): T? {
return lastOrNull(predicate)
}
/**
* Returns first element.
* @throws [NoSuchElementException] if the collection is empty.
*/
public fun <T> Iterable<T>.first(): T {
when (this) {
is List -> return this.first()
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty.")
return iterator.next()
}
}
}
/**
* Returns first element.
* @throws [NoSuchElementException] if the list is empty.
*/
public fun <T> List<T>.first(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[0]
}
/**
* Returns the first element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
public inline fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T {
for (element in this) if (predicate(element)) return element
throw NoSuchElementException("Collection contains no element matching the predicate.")
}
/**
* Returns the first element, or `null` if the collection is empty.
*/
public fun <T> Iterable<T>.firstOrNull(): T? {
when (this) {
is List -> {
if (isEmpty())
return null
else
return this[0]
}
else -> {
val iterator = iterator()
if (!iterator.hasNext())
return null
return iterator.next()
}
}
}
/**
* Returns the first element, or `null` if the list is empty.
*/
public fun <T> List<T>.firstOrNull(): T? {
return if (isEmpty()) null else this[0]
}
/**
* Returns the first element matching the given [predicate], or `null` if element was not found.
*/
public inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this list.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.getOrElse(index: Int, defaultValue: (Int) -> T): T {
return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}
/**
* Returns an element at the given [index] or `null` if the [index] is out of bounds of this list.
*/
public fun <T> List<T>.getOrNull(index: Int): T? {
return if (index >= 0 && index <= lastIndex) get(index) else null
}
/**
* Returns first index of [element], or -1 if the collection does not contain element.
*/
public fun <@kotlin.internal.OnlyInputTypes T> Iterable<T>.indexOf(element: T): Int {
if (this is List) return this.indexOf(element)
var index = 0
for (item in this) {
if (element == item)
return index
index++
}
return -1
}
/**
* Returns first index of [element], or -1 if the list does not contain element.
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun <@kotlin.internal.OnlyInputTypes T> List<T>.indexOf(element: T): Int {
return indexOf(element)
}
/**
* Returns index of the first element matching the given [predicate], or -1 if the collection does not contain such element.
*/
public inline fun <T> Iterable<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
var index = 0
for (item in this) {
if (predicate(item))
return index
index++
}
return -1
}
/**
* Returns index of the first element matching the given [predicate], or -1 if the list does not contain such element.
*/
public inline fun <T> List<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
var index = 0
for (item in this) {
if (predicate(item))
return index
index++
}
return -1
}
/**
* Returns index of the last element matching the given [predicate], or -1 if the collection does not contain such element.
*/
public inline fun <T> Iterable<T>.indexOfLast(predicate: (T) -> Boolean): Int {
var lastIndex = -1
var index = 0
for (item in this) {
if (predicate(item))
lastIndex = index
index++
}
return lastIndex
}
/**
* Returns index of the last element matching the given [predicate], or -1 if the list does not contain such element.
*/
public inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (predicate(iterator.previous())) {
return iterator.nextIndex()
}
}
return -1
}
/**
* Returns the last element.
* @throws [NoSuchElementException] if the collection is empty.
*/
public fun <T> Iterable<T>.last(): T {
when (this) {
is List -> return this.last()
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty.")
var last = iterator.next()
while (iterator.hasNext())
last = iterator.next()
return last
}
}
}
/**
* Returns the last element.
* @throws [NoSuchElementException] if the list is empty.
*/
public fun <T> List<T>.last(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[lastIndex]
}
/**
* Returns the last element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
public inline fun <T> Iterable<T>.last(predicate: (T) -> Boolean): T {
var last: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
last = element
found = true
}
}
if (!found) throw NoSuchElementException("Collection contains no element matching the predicate.")
@Suppress("UNCHECKED_CAST")
return last as T
}
/**
* Returns the last element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
public inline fun <T> List<T>.last(predicate: (T) -> Boolean): T {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
throw NoSuchElementException("List contains no element matching the predicate.")
}
/**
* Returns last index of [element], or -1 if the collection does not contain element.
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun <@kotlin.internal.OnlyInputTypes T> Iterable<T>.lastIndexOf(element: T): Int {
if (this is List) return this.lastIndexOf(element)
var lastIndex = -1
var index = 0
for (item in this) {
if (element == item)
lastIndex = index
index++
}
return lastIndex
}
/**
* Returns last index of [element], or -1 if the list does not contain element.
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun <@kotlin.internal.OnlyInputTypes T> List<T>.lastIndexOf(element: T): Int {
return lastIndexOf(element)
}
/**
* Returns the last element, or `null` if the collection is empty.
*/
public fun <T> Iterable<T>.lastOrNull(): T? {
when (this) {
is List -> return if (isEmpty()) null else this[size - 1]
else -> {
val iterator = iterator()
if (!iterator.hasNext())
return null
var last = iterator.next()
while (iterator.hasNext())
last = iterator.next()
return last
}
}
}
/**
* Returns the last element, or `null` if the list is empty.
*/
public fun <T> List<T>.lastOrNull(): T? {
return if (isEmpty()) null else this[size - 1]
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
public inline fun <T> Iterable<T>.lastOrNull(predicate: (T) -> Boolean): T? {
var last: T? = null
for (element in this) {
if (predicate(element)) {
last = element
}
}
return last
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
public inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
return null
}
/**
* Returns the single element, or throws an exception if the collection is empty or has more than one element.
*/
public fun <T> Iterable<T>.single(): T {
when (this) {
is List -> return this.single()
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty.")
val single = iterator.next()
if (iterator.hasNext())
throw IllegalArgumentException("Collection has more than one element.")
return single
}
}
}
/**
* Returns the single element, or throws an exception if the list is empty or has more than one element.
*/
public fun <T> List<T>.single(): T {
return when (size) {
0 -> throw NoSuchElementException("List is empty.")
1 -> this[0]
else -> throw IllegalArgumentException("List has more than one element.")
}
}
/**
* Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element.
*/
public inline fun <T> Iterable<T>.single(predicate: (T) -> Boolean): T {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) throw IllegalArgumentException("Collection contains more than one matching element.")
single = element
found = true
}
}
if (!found) throw NoSuchElementException("Collection contains no element matching the predicate.")
@Suppress("UNCHECKED_CAST")
return single as T
}
/**
* Returns single element, or `null` if the collection is empty or has more than one element.
*/
public fun <T> Iterable<T>.singleOrNull(): T? {
when (this) {
is List -> return if (size == 1) this[0] else null
else -> {
val iterator = iterator()
if (!iterator.hasNext())
return null
val single = iterator.next()
if (iterator.hasNext())
return null
return single
}
}
}
/**
* Returns single element, or `null` if the list is empty or has more than one element.
*/
public fun <T> List<T>.singleOrNull(): T? {
return if (size == 1) this[0] else null
}
/**
* Returns the single element matching the given [predicate], or `null` if element was not found or more than one element was found.
*/
public inline fun <T> Iterable<T>.singleOrNull(predicate: (T) -> Boolean): T? {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) return null
single = element
found = true
}
}
if (!found) return null
return single
}
/**
* Returns a list containing all elements except first [n] elements.
*/
public fun <T> Iterable<T>.drop(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return toList()
val list: ArrayList<T>
if (this is Collection<*>) {
val resultSize = size - n
if (resultSize <= 0)
return emptyList()
if (resultSize == 1)
return listOf(last())
list = ArrayList<T>(resultSize)
if (this is List<T>) {
if (this is RandomAccess) {
for (index in n..size - 1)
list.add(this[index])
} else {
for (item in this.listIterator(n))
list.add(item)
}
return list
}
}
else {
list = ArrayList<T>()
}
var count = 0
for (item in this) {
if (count++ >= n) list.add(item)
}
return list.optimizeReadOnlyList()
}
/**
* Returns a list containing all elements except last [n] elements.
*/
public fun <T> List<T>.dropLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return take((size - n).coerceAtLeast(0))
}
/**
* Returns a list containing all elements except last elements that satisfy the given [predicate].
*/
public inline fun <T> List<T>.dropLastWhile(predicate: (T) -> Boolean): List<T> {
if (!isEmpty()) {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
return take(iterator.nextIndex() + 1)
}
}
}
return emptyList()
}
/**
* Returns a list containing all elements except first elements that satisfy the given [predicate].
*/
public inline fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean): List<T> {
var yielding = false
val list = ArrayList<T>()
for (item in this)
if (yielding)
list.add(item)
else if (!predicate(item)) {
list.add(item)
yielding = true
}
return list
}
/**
* Returns a list containing only elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing only elements matching the given [predicate].
* @param [predicate] function that takes the index of an element and the element itself
* and returns the result of predicate evaluation on the element.
*/
public inline fun <T> Iterable<T>.filterIndexed(predicate: (Int, T) -> Boolean): List<T> {
return filterIndexedTo(ArrayList<T>(), predicate)
}
/**
* Appends all elements matching the given [predicate] to the given [destination].
* @param [predicate] function that takes the index of an element and the element itself
* and returns the result of predicate evaluation on the element.
*/
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterIndexedTo(destination: C, predicate: (Int, T) -> Boolean): C {
forEachIndexed { index, element ->
if (predicate(index, element)) destination.add(element)
}
return destination
}
/**
* Returns a list containing all elements that are instances of specified type parameter R.
*/
public inline fun <reified R> Iterable<*>.filterIsInstance(): List<@kotlin.internal.NoInfer R> {
return filterIsInstanceTo(ArrayList<R>())
}
/**
* Appends all elements that are instances of specified type parameter R to the given [destination].
*/
public inline fun <reified R, C : MutableCollection<in R>> Iterable<*>.filterIsInstanceTo(destination: C): C {
for (element in this) if (element is R) destination.add(element)
return destination
}
/**
* Returns a list containing all elements not matching the given [predicate].
*/
public inline fun <T> Iterable<T>.filterNot(predicate: (T) -> Boolean): List<T> {
return filterNotTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing all elements that are not `null`.
*/
public fun <T : Any> Iterable<T?>.filterNotNull(): List<T> {
return filterNotNullTo(ArrayList<T>())
}
/**
* Appends all elements that are not `null` to the given [destination].
*/
public fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo(destination: C): C {
for (element in this) if (element != null) destination.add(element)
return destination
}
/**
* Appends all elements not matching the given [predicate] to the given [destination].
*/
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (!predicate(element)) destination.add(element)
return destination
}
/**
* Appends all elements matching the given [predicate] to the given [destination].
*/
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (predicate(element)) destination.add(element)
return destination
}
/**
* Returns a list containing elements at indices in the specified [indices] range.
*/
public fun <T> List<T>.slice(indices: IntRange): List<T> {
if (indices.isEmpty()) return listOf()
return this.subList(indices.start, indices.endInclusive + 1).toList()
}
/**
* Returns a list containing elements at specified [indices].
*/
public fun <T> List<T>.slice(indices: Iterable<Int>): List<T> {
val size = indices.collectionSizeOrDefault(10)
if (size == 0) return emptyList()
val list = ArrayList<T>(size)
for (index in indices) {
list.add(get(index))
}
return list
}
/**
* Returns a list containing first [n] elements.
*/
public fun <T> Iterable<T>.take(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
if (this is Collection<T>) {
if (n >= size) return toList()
if (n == 1) return listOf(first())
}
var count = 0
val list = ArrayList<T>(n)
for (item in this) {
if (count++ == n)
break
list.add(item)
}
return list.optimizeReadOnlyList()
}
/**
* Returns a list containing last [n] elements.
*/
public fun <T> List<T>.takeLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
val size = size
if (n >= size) return toList()
if (n == 1) return listOf(last())
val list = ArrayList<T>(n)
if (this is RandomAccess) {
for (index in size - n .. size - 1)
list.add(this[index])
} else {
for (item in this.listIterator(n))
list.add(item)
}
return list
}
/**
* Returns a list containing last elements satisfying the given [predicate].
*/
public inline fun <T> List<T>.takeLastWhile(predicate: (T) -> Boolean): List<T> {
if (isEmpty())
return emptyList()
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
iterator.next()
val expectedSize = size - iterator.nextIndex()
if (expectedSize == 0) return emptyList()
return ArrayList<T>(expectedSize).apply {
while (iterator.hasNext())
add(iterator.next())
}
}
}
return toList()
}
/**
* Returns a list containing first elements satisfying the given [predicate].
*/
public inline fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
if (!predicate(item))
break
list.add(item)
}
return list
}
/**
* Reverses elements in the list in-place.
*/
public fun <T> MutableList<T>.reverse(): Unit {
val median = size / 2
var leftIndex = 0
var rightIndex = size - 1
while (leftIndex < median) {
val tmp = this[leftIndex]
this[leftIndex] = this[rightIndex]
this[rightIndex] = tmp
leftIndex++
rightIndex--
}
}
/**
* Returns a list with elements in reversed order.
*/
public fun <T> Iterable<T>.reversed(): List<T> {
if (this is Collection && size <= 1) return toList()
val list = toMutableList()
list.reverse()
return list
}
/**
* Sorts elements in the list in-place according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) -> R?): Unit {
if (size > 1) sortWith(compareBy(selector))
}
/**
* Sorts elements in the list in-place descending according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> MutableList<T>.sortByDescending(crossinline selector: (T) -> R?): Unit {
if (size > 1) sortWith(compareByDescending(selector))
}
/**
* Sorts elements in the list in-place descending according to their natural sort order.
*/
public fun <T : Comparable<T>> MutableList<T>.sortDescending(): Unit {
sortWith(reverseOrder())
}
/**
* Replaces each element in the list with a result of a transformation specified.
*/
public fun <T> MutableList<T>.replaceAll(transformation: (T) -> T) {
val it = listIterator()
while (it.hasNext()) {
val element = it.next()
it.set(transformation(element))
}
}
/**
* Returns a list of all elements sorted according to their natural sort order.
*/
public fun <T : Comparable<T>> Iterable<T>.sorted(): List<T> {
if (this is Collection) {
if (size <= 1) return this.toList()
@Suppress("UNCHECKED_CAST")
return (toTypedArray<Comparable<T>>() as Array<T>).apply { sort() }.asList()
}
return toMutableList().apply { sort() }
}
/**
* Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
return sortedWith(compareBy(selector))
}
/**
* Returns a list of all elements sorted descending according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(crossinline selector: (T) -> R?): List<T> {
return sortedWith(compareByDescending(selector))
}
/**
* Returns a list of all elements sorted descending according to their natural sort order.
*/
public fun <T : Comparable<T>> Iterable<T>.sortedDescending(): List<T> {
return sortedWith(reverseOrder())
}
/**
* Returns a list of all elements sorted according to the specified [comparator].
*/
public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T> {
if (this is Collection) {
if (size <= 1) return this.toList()
@Suppress("UNCHECKED_CAST")
return (toTypedArray<Any?>() as Array<T>).apply { sortWith(comparator) }.asList()
}
return toMutableList().apply { sortWith(comparator) }
}
/**
* Returns an array of Boolean containing all of the elements of this collection.
*/
public fun Collection<Boolean>.toBooleanArray(): BooleanArray {
val result = BooleanArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Byte containing all of the elements of this collection.
*/
public fun Collection<Byte>.toByteArray(): ByteArray {
val result = ByteArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Char containing all of the elements of this collection.
*/
public fun Collection<Char>.toCharArray(): CharArray {
val result = CharArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Double containing all of the elements of this collection.
*/
public fun Collection<Double>.toDoubleArray(): DoubleArray {
val result = DoubleArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Float containing all of the elements of this collection.
*/
public fun Collection<Float>.toFloatArray(): FloatArray {
val result = FloatArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Int containing all of the elements of this collection.
*/
public fun Collection<Int>.toIntArray(): IntArray {
val result = IntArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Long containing all of the elements of this collection.
*/
public fun Collection<Long>.toLongArray(): LongArray {
val result = LongArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Short containing all of the elements of this collection.
*/
public fun Collection<Short>.toShortArray(): ShortArray {
val result = ShortArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns a [Map] containing key-value pairs provided by [transform] function
* applied to elements of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
public inline fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V> {
val capacity = mapCapacity(collectionSizeOrDefault(10)).coerceAtLeast(16)
return associateTo(LinkedHashMap<K, V>(capacity), transform)
}
/**
* Returns a [Map] containing the elements from the given collection indexed by the key
* returned from [keySelector] function applied to each element.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
public inline fun <T, K> Iterable<T>.associateBy(keySelector: (T) -> K): Map<K, T> {
val capacity = mapCapacity(collectionSizeOrDefault(10)).coerceAtLeast(16)
return associateByTo(LinkedHashMap<K, T>(capacity), keySelector)
}
/**
* Returns a [Map] containing the values provided by [valueTransform] and indexed by [keySelector] functions applied to elements of the given collection.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
public inline fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V> {
val capacity = mapCapacity(collectionSizeOrDefault(10)).coerceAtLeast(16)
return associateByTo(LinkedHashMap<K, V>(capacity), keySelector, valueTransform)
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function applied to each element of the given collection
* and value is the element itself.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*/
public inline fun <T, K, M : MutableMap<in K, in T>> Iterable<T>.associateByTo(destination: M, keySelector: (T) -> K): M {
for (element in this) {
destination.put(keySelector(element), element)
}
return destination
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function and
* and value is provided by the [valueTransform] function applied to elements of the given collection.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*/
public inline fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateByTo(destination: M, keySelector: (T) -> K, valueTransform: (T) -> V): M {
for (element in this) {
destination.put(keySelector(element), valueTransform(element))
}
return destination
}
/**
* Populates and returns the [destination] mutable map with key-value pairs
* provided by [transform] function applied to each element of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map.
*/
public inline fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateTo(destination: M, transform: (T) -> Pair<K, V>): M {
for (element in this) {
destination += transform(element)
}
return destination
}
/**
* Appends all elements to the given [destination] collection.
*/
public fun <T, C : MutableCollection<in T>> Iterable<T>.toCollection(destination: C): C {
for (item in this) {
destination.add(item)
}
return destination
}
/**
* Returns a [HashSet] of all elements.
*/
public fun <T> Iterable<T>.toHashSet(): HashSet<T> {
return toCollection(HashSet<T>(mapCapacity(collectionSizeOrDefault(12))))
}
/**
* Returns a [List] containing all elements.
*/
public fun <T> Iterable<T>.toList(): List<T> {
if (this is Collection) {
return when (size) {
0 -> emptyList()
1 -> listOf(if (this is List) get(0) else iterator().next())
else -> this.toMutableList()
}
}
return this.toMutableList().optimizeReadOnlyList()
}
/**
* Returns a [MutableList] filled with all elements of this collection.
*/
public fun <T> Iterable<T>.toMutableList(): MutableList<T> {
if (this is Collection<T>)
return this.toMutableList()
return toCollection(ArrayList<T>())
}
/**
* Returns a [MutableList] filled with all elements of this collection.
*/
public fun <T> Collection<T>.toMutableList(): MutableList<T> {
return ArrayList(this)
}
/**
* Returns a [Set] of all elements.
*
* The returned set preserves the element iteration order of the original collection.
*/
public fun <T> Iterable<T>.toSet(): Set<T> {
if (this is Collection) {
return when (size) {
0 -> emptySet()
1 -> setOf(if (this is List) this[0] else iterator().next())
else -> toCollection(LinkedHashSet<T>(mapCapacity(size)))
}
}
return toCollection(LinkedHashSet<T>()).optimizeReadOnlySet()
}
/**
* Returns a [SortedSet] of all elements.
*/
//public fun <T: Comparable<T>> Iterable<T>.toSortedSet(): SortedSet<T> {
// return toCollection(TreeSet<T>())
//}
/**
* Returns a [SortedSet] of all elements.
*
* Elements in the set returned are sorted according to the given [comparator].
*/
//public fun <T> Iterable<T>.toSortedSet(comparator: Comparator<in T>): SortedSet<T> {
// return toCollection(TreeSet<T>(comparator))
//}
/**
* Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
*/
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination].
*/
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) -> Iterable<R>): C {
for (element in this) {
val list = transform(element)
destination.addAll(list)
}
return destination
}
/**
* Groups elements of the original collection by the key returned by the given [keySelector] function
* applied to each element and returns a map where each group key is associated with a list of corresponding elements.
*
* The returned map preserves the entry iteration order of the keys produced from the original collection.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
public inline fun <T, K> Iterable<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>> {
return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
}
/**
* Groups values returned by the [valueTransform] function applied to each element of the original collection
* by the key returned by the given [keySelector] function applied to the element
* and returns a map where each group key is associated with a list of corresponding values.
*
* The returned map preserves the entry iteration order of the keys produced from the original collection.
*
* @sample samples.collections.Collections.Transformations.groupByKeysAndValues
*/
public inline fun <T, K, V> Iterable<T>.groupBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, List<V>> {
return groupByTo(LinkedHashMap<K, MutableList<V>>(), keySelector, valueTransform)
}
/**
* Groups elements of the original collection by the key returned by the given [keySelector] function
* applied to each element and puts to the [destination] map each group key associated with a list of corresponding elements.
*
* @return The [destination] map.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return destination
}
/**
* Groups values returned by the [valueTransform] function applied to each element of the original collection
* by the key returned by the given [keySelector] function applied to the element
* and puts to the [destination] map each group key associated with a list of corresponding values.
*
* @return The [destination] map.
*
* @sample samples.collections.Collections.Transformations.groupByKeysAndValues
*/
public inline fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K, valueTransform: (T) -> V): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<V>() }
list.add(valueTransform(element))
}
return destination
}
/**
* Creates a [Grouping] source from a collection to be used later with one of group-and-fold operations
* using the specified [keySelector] function to extract a key from each element.
*
* @sample samples.collections.Collections.Transformations.groupingByEachCount
*/
@SinceKotlin("1.1")
public inline fun <T, K> Iterable<T>.groupingBy(crossinline keySelector: (T) -> K): Grouping<T, K> {
return object : Grouping<T, K> {
override fun sourceIterator(): Iterator<T> = [email protected]()
override fun keyOf(element: T): K = keySelector(element)
}
}
/**
* Returns a list containing the results of applying the given [transform] function
* to each element in the original collection.
*/
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
/**
* Returns a list containing the results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R> Iterable<T>.mapIndexed(transform: (Int, T) -> R): List<R> {
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
return mapIndexedTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R : Any> Iterable<T>.mapIndexedNotNull(transform: (Int, T) -> R?): List<R> {
return mapIndexedNotNullTo(ArrayList<R>(), transform)
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends only the non-null results to the given [destination].
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapIndexedNotNullTo(destination: C, transform: (Int, T) -> R?): C {
forEachIndexed { index, element -> transform(index, element)?.let { destination.add(it) } }
return destination
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends the results to the given [destination].
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo(destination: C, transform: (Int, T) -> R): C {
var index = 0
for (item in this)
destination.add(transform(index++, item))
return destination
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element in the original collection.
*/
public inline fun <T, R : Any> Iterable<T>.mapNotNull(transform: (T) -> R?): List<R> {
return mapNotNullTo(ArrayList<R>(), transform)
}
/**
* Applies the given [transform] function to each element in the original collection
* and appends only the non-null results to the given [destination].
*/
public inline fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapNotNullTo(destination: C, transform: (T) -> R?): C {
forEach { element -> transform(element)?.let { destination.add(it) } }
return destination
}
/**
* Applies the given [transform] function to each element of the original collection
* and appends the results to the given [destination].
*/
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) -> R): C {
for (item in this)
destination.add(transform(item))
return destination
}
/**
* Returns a lazy [Iterable] of [IndexedValue] for each element of the original collection.
*/
public fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> {
return IndexingIterable { iterator() }
}
/**
* Returns a list containing only distinct elements from the given collection.
*
* The elements in the resulting list are in the same order as they were in the source collection.
*/
public fun <T> Iterable<T>.distinct(): List<T> {
return this.toMutableSet().toList()
}
/**
* Returns a list containing only elements from the given collection
* having distinct keys returned by the given [selector] function.
*
* The elements in the resulting list are in the same order as they were in the source collection.
*/
public inline fun <T, K> Iterable<T>.distinctBy(selector: (T) -> K): List<T> {
val set = HashSet<K>()
val list = ArrayList<T>()
for (e in this) {
val key = selector(e)
if (set.add(key))
list.add(e)
}
return list
}
/**
* Returns a set containing all elements that are contained by both this set and the specified collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
public infix fun <T> Iterable<T>.intersect(other: Iterable<T>): Set<T> {
val set = this.toMutableSet()
set.retainAll(other)
return set
}
/**
* Returns a set containing all elements that are contained by this collection and not contained by the specified collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
public infix fun <T> Iterable<T>.subtract(other: Iterable<T>): Set<T> {
val set = this.toMutableSet()
set.removeAll(other)
return set
}
/**
* Returns a mutable set containing all distinct elements from the given collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
public fun <T> Iterable<T>.toMutableSet(): MutableSet<T> {
return when (this) {
is Collection<T> -> LinkedHashSet(this)
else -> toCollection(LinkedHashSet<T>())
}
}
/**
* Returns a set containing all distinct elements from both collections.
*
* The returned set preserves the element iteration order of the original collection.
* Those elements of the [other] collection that are unique are iterated in the end
* in the order of the [other] collection.
*/
public infix fun <T> Iterable<T>.union(other: Iterable<T>): Set<T> {
val set = this.toMutableSet()
set.addAll(other)
return set
}
/**
* Returns `true` if all elements match the given [predicate].
*/
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns `true` if collection has at least one element.
*/
public fun <T> Iterable<T>.any(): Boolean {
for (element in this) return true
return false
}
/**
* Returns `true` if at least one element matches the given [predicate].
*/
public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Returns the number of elements in this collection.
* Returns the number of elements in this collection.
*/
public fun <T> Iterable<T>.count(): Int {
var count = 0
for (element in this) count++
return count
}
/**
* Returns the number of elements in this collection.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.count(): Int {
return size
}
/**
* Returns the number of elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <T, R> Iterable<T>.fold(initial: R, operation: (R, T) -> R): R {
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right
* to current accumulator value and each element with its index in the original collection.
* @param [operation] function that takes the index of an element, current accumulator value
* and the element itself, and calculates the next accumulator value.
*/
public inline fun <T, R> Iterable<T>.foldIndexed(initial: R, operation: (Int, R, T) -> R): R {
var index = 0
var accumulator = initial
for (element in this) accumulator = operation(index++, accumulator, element)
return accumulator
}
/**
* Accumulates value starting with [initial] value and applying [operation] from right to left to each element and current accumulator value.
*/
public inline fun <T, R> List<T>.foldRight(initial: R, operation: (T, R) -> R): R {
var accumulator = initial
if (!isEmpty()) {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
}
return accumulator
}
/**
* Accumulates value starting with [initial] value and applying [operation] from right to left
* to each element with its index in the original list and current accumulator value.
* @param [operation] function that takes the index of an element, the element itself
* and current accumulator value, and calculates the next accumulator value.
*/
public inline fun <T, R> List<T>.foldRightIndexed(initial: R, operation: (Int, T, R) -> R): R {
var accumulator = initial
if (!isEmpty()) {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
}
return accumulator
}
/**
* Performs the given [action] on each element.
*/
@kotlin.internal.HidesMembers
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
/**
* Performs the given [action] on each element, providing sequential index with the element.
* @param [action] function that takes the index of an element and the element itself
* and performs the desired action on the element.
*/
public inline fun <T> Iterable<T>.forEachIndexed(action: (Int, T) -> Unit): Unit {
var index = 0
for (item in this) action(index++, item)
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
public fun Iterable<Double>.max(): Double? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
if (max.isNaN()) return max
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (max < e) max = e
}
return max
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
public fun Iterable<Float>.max(): Float? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
if (max.isNaN()) return max
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (max < e) max = e
}
return max
}
/**
* Returns the largest element or `null` if there are no elements.
*/
public fun <T : Comparable<T>> Iterable<T>.max(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or `null` if there are no elements.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
var maxValue = selector(maxElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the first element having the largest value according to the provided [comparator] or `null` if there are no elements.
*/
public fun <T> Iterable<T>.maxWith(comparator: Comparator<in T>): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (comparator.compare(max, e) < 0) max = e
}
return max
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
public fun Iterable<Double>.min(): Double? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
if (min.isNaN()) return min
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (min > e) min = e
}
return min
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
public fun Iterable<Float>.min(): Float? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
if (min.isNaN()) return min
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (min > e) min = e
}
return min
}
/**
* Returns the smallest element or `null` if there are no elements.
*/
public fun <T : Comparable<T>> Iterable<T>.min(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or `null` if there are no elements.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.minBy(selector: (T) -> R): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var minValue = selector(minElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Returns the first element having the smallest value according to the provided [comparator] or `null` if there are no elements.
*/
public fun <T> Iterable<T>.minWith(comparator: Comparator<in T>): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (comparator.compare(min, e) > 0) min = e
}
return min
}
/**
* Returns `true` if the collection has no elements.
*/
public fun <T> Iterable<T>.none(): Boolean {
for (element in this) return false
return true
}
/**
* Returns `true` if no elements match the given [predicate].
*/
public inline fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return false
return true
}
/**
* Performs the given [action] on each element and returns the collection itself afterwards.
*/
@SinceKotlin("1.1")
public inline fun <T, C : Iterable<T>> C.onEach(action: (T) -> Unit): C {
return apply { for (element in this) action(element) }
}
/**
* Accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <S, T: S> Iterable<T>.reduce(operation: (S, T) -> S): S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
}
/**
* Accumulates value starting with the first element and applying [operation] from left to right
* to current accumulator value and each element with its index in the original collection.
* @param [operation] function that takes the index of an element, current accumulator value
* and the element itself and calculates the next accumulator value.
*/
public inline fun <S, T: S> Iterable<T>.reduceIndexed(operation: (Int, S, T) -> S): S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
var index = 1
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(index++, accumulator, iterator.next())
}
return accumulator
}
/**
* Accumulates value starting with last element and applying [operation] from right to left to each element and current accumulator value.
*/
public inline fun <S, T: S> List<T>.reduceRight(operation: (T, S) -> S): S {
val iterator = listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
return accumulator
}
/**
* Accumulates value starting with last element and applying [operation] from right to left
* to each element with its index in the original list and current accumulator value.
* @param [operation] function that takes the index of an element, the element itself
* and current accumulator value, and calculates the next accumulator value.
*/
public inline fun <S, T: S> List<T>.reduceRightIndexed(operation: (Int, T, S) -> S): S {
val iterator = this.listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
return accumulator
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
public inline fun <T> Iterable<T>.sumBy(selector: (T) -> Int): Int {
var sum: Int = 0
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
public inline fun <T> Iterable<T>.sumByDouble(selector: (T) -> Double): Double {
var sum: Double = 0.0
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Returns an original collection containing all the non-`null` elements, throwing an [IllegalArgumentException] if there are any `null` elements.
*/
public fun <T : Any> Iterable<T?>.requireNoNulls(): Iterable<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this.")
}
}
@Suppress("UNCHECKED_CAST")
return this as Iterable<T>
}
/**
* Returns an original collection containing all the non-`null` elements, throwing an [IllegalArgumentException] if there are any `null` elements.
*/
public fun <T : Any> List<T?>.requireNoNulls(): List<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this.")
}
}
@Suppress("UNCHECKED_CAST")
return this as List<T>
}
/**
* Returns a list containing all elements of the original collection without the first occurrence of the given [element].
*/
public operator fun <T> Iterable<T>.minus(element: T): List<T> {
val result = ArrayList<T>(collectionSizeOrDefault(10))
var removed = false
return this.filterTo(result) { if (!removed && it == element) { removed = true; false } else true }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] array.
*/
public operator fun <T> Iterable<T>.minus(elements: Array<out T>): List<T> {
if (elements.isEmpty()) return this.toList()
val other = elements.toHashSet()
return this.filterNot { it in other }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] collection.
*/
public operator fun <T> Iterable<T>.minus(elements: Iterable<T>): List<T> {
val other = elements.convertToSetForSetOperationWith(this)
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] sequence.
*/
public operator fun <T> Iterable<T>.minus(elements: Sequence<T>): List<T> {
val other = elements.toHashSet()
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
}
/**
* Returns a list containing all elements of the original collection without the first occurrence of the given [element].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.minusElement(element: T): List<T> {
return minus(element)
}
/**
* Splits the original collection into pair of lists,
* where *first* list contains elements for which [predicate] yielded `true`,
* while *second* list contains elements for which [predicate] yielded `false`.
*/
public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
public operator fun <T> Iterable<T>.plus(element: T): List<T> {
if (this is Collection) return this.plus(element)
val result = ArrayList<T>()
result.addAll(this)
result.add(element)
return result
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
public operator fun <T> Collection<T>.plus(element: T): List<T> {
val result = ArrayList<T>(size + 1)
result.addAll(this)
result.add(element)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] array.
*/
public operator fun <T> Iterable<T>.plus(elements: Array<out T>): List<T> {
if (this is Collection) return this.plus(elements)
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] array.
*/
public operator fun <T> Collection<T>.plus(elements: Array<out T>): List<T> {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] collection.
*/
public operator fun <T> Iterable<T>.plus(elements: Iterable<T>): List<T> {
if (this is Collection) return this.plus(elements)
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] collection.
*/
public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
if (elements is Collection) {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
} else {
val result = ArrayList<T>(this)
result.addAll(elements)
return result
}
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] sequence.
*/
public operator fun <T> Iterable<T>.plus(elements: Sequence<T>): List<T> {
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] sequence.
*/
public operator fun <T> Collection<T>.plus(elements: Sequence<T>): List<T> {
val result = ArrayList<T>(this.size + 10)
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.plusElement(element: T): List<T> {
return plus(element)
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.plusElement(element: T): List<T> {
return plus(element)
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public infix fun <T, R> Iterable<T>.zip(other: Array<out R>): List<Pair<T, R>> {
return zip(other) { t1, t2 -> t1 to t2 }
}
@Suppress("NOTHING_TO_INLINE")
inline fun min(x1: Int, x2: Int) = if (x1 < x2) x1 else x2
/**
* Returns a list of values built from elements of both collections with same indexes using provided [transform]. List has length of shortest collection.
*/
public inline fun <T, R, V> Iterable<T>.zip(other: Array<out R>, transform: (T, R) -> V): List<V> {
val arraySize = other.size
val list = ArrayList<V>(min(collectionSizeOrDefault(10), arraySize))
var i = 0
for (element in this) {
if (i >= arraySize) break
list.add(transform(element, other[i++]))
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public infix fun <T, R> Iterable<T>.zip(other: Iterable<R>): List<Pair<T, R>> {
return zip(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of values built from elements of both collections with same indexes using provided [transform]. List has length of shortest collection.
*/
public inline fun <T, R, V> Iterable<T>.zip(other: Iterable<R>, transform: (T, R) -> V): List<V> {
val first = iterator()
val second = other.iterator()
val list = ArrayList<V>(min(collectionSizeOrDefault(10), other.collectionSizeOrDefault(10)))
while (first.hasNext() && second.hasNext()) {
list.add(transform(first.next(), second.next()))
}
return list
}
/**
* Appends the string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T, A : Appendable> Iterable<T>.joinTo(buffer: A, separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): A {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
if (transform != null)
buffer.append(transform(element))
else
buffer.append(if (element == null) "null" else element.toString())
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
return buffer
}
/**
* Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T> Iterable<T>.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): String {
return joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated, transform).toString()
}
/**
* Returns this collection as an [Iterable].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.asIterable(): Iterable<T> {
return this
}
/**
* Creates a [Sequence] instance that wraps the original collection returning its elements when being iterated.
*/
public fun <T> Iterable<T>.asSequence(): Sequence<T> {
return Sequence { this.iterator() }
}
/**
* Returns a list containing all elements that are instances of specified class.
*/
//public fun <R> Iterable<*>.filterIsInstance(klass: Class<R>): List<R> {
// return filterIsInstanceTo(ArrayList<R>(), klass)
//}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Byte>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Short>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Int>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Long>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Float>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Double>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Byte>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Short>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Int>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Long>.sum(): Long {
var sum: Long = 0L
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Float>.sum(): Float {
var sum: Float = 0.0f
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Double>.sum(): Double {
var sum: Double = 0.0
for (element in this) {
sum += element
}
return sum
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/primitiveTypes/comparisonWithNaN.kt | 2 | 1841 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// This test checks that our bytecode is consistent with javac bytecode
fun _assert(condition: Boolean) {
if (!condition) throw AssertionError("Fail")
}
fun _assertFalse(condition: Boolean) = _assert(!condition)
fun box(): String {
var dnan = java.lang.Double.NaN
if (System.nanoTime() < 0) dnan = 3.14 // To avoid possible compile-time const propagation
_assertFalse(0.0 < dnan)
_assertFalse(0.0 > dnan)
_assertFalse(0.0 <= dnan)
_assertFalse(0.0 >= dnan)
_assertFalse(0.0 == dnan)
_assertFalse(dnan < 0.0)
_assertFalse(dnan > 0.0)
_assertFalse(dnan <= 0.0)
_assertFalse(dnan >= 0.0)
_assertFalse(dnan == 0.0)
_assertFalse(dnan < dnan)
_assertFalse(dnan > dnan)
_assertFalse(dnan <= dnan)
_assertFalse(dnan >= dnan)
_assertFalse(dnan == dnan)
// Double.compareTo: "NaN is considered by this method to be equal to itself and greater than all other values"
_assert(0.0.compareTo(dnan) == -1)
_assert(dnan.compareTo(0.0) == 1)
_assert(dnan.compareTo(dnan) == 0)
var fnan = java.lang.Float.NaN
if (System.nanoTime() < 0) fnan = 3.14f
_assertFalse(0.0f < fnan)
_assertFalse(0.0f > fnan)
_assertFalse(0.0f <= fnan)
_assertFalse(0.0f >= fnan)
_assertFalse(0.0f == fnan)
_assertFalse(fnan < 0.0f)
_assertFalse(fnan > 0.0f)
_assertFalse(fnan <= 0.0f)
_assertFalse(fnan >= 0.0f)
_assertFalse(fnan == 0.0f)
_assertFalse(fnan < fnan)
_assertFalse(fnan > fnan)
_assertFalse(fnan <= fnan)
_assertFalse(fnan >= fnan)
_assertFalse(fnan == fnan)
_assert(0.0.compareTo(fnan) == -1)
_assert(fnan.compareTo(0.0) == 1)
_assert(fnan.compareTo(fnan) == 0)
return "OK"
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/operatorConventions/infixFunctionOverBuiltinMember.kt | 5 | 348 | infix fun Int.rem(other: Int) = 10
infix operator fun Int.minus(other: Int): Int = 20
fun box(): String {
val a = 5 rem 2
if (a != 10) return "fail 1"
val b = 5 minus 3
if (b != 20) return "fail 2"
val a1 = 5.rem(2)
if (a1 != 1) return "fail 3"
val b2 = 5.minus(3)
if (b2 != 2) return "fail 4"
return "OK"
} | apache-2.0 |
hannesa2/owncloud-android | owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/GetShareAsLiveDataUseCase.kt | 2 | 1338 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.domain.sharing.shares.usecases
import androidx.lifecycle.LiveData
import com.owncloud.android.domain.BaseUseCase
import com.owncloud.android.domain.sharing.shares.ShareRepository
import com.owncloud.android.domain.sharing.shares.model.OCShare
class GetShareAsLiveDataUseCase(
private val shareRepository: ShareRepository
) : BaseUseCase<LiveData<OCShare>, GetShareAsLiveDataUseCase.Params>() {
override fun run(params: Params): LiveData<OCShare> =
shareRepository.getShareAsLiveData(
params.remoteId
)
data class Params(
val remoteId: String
)
}
| gpl-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/copy/copySingleClass/after/bar/A.kt | 13 | 39 | package bar
// test
class A
// test2 | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/outputValues/singleOutputValueWithWhen.kt | 13 | 433 | // PARAM_TYPES: kotlin.Int, kotlin.Comparable<kotlin.Int>
// PARAM_TYPES: kotlin.Int
// PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var b: kotlin.Int defined in foo
// SIBLING:
fun foo(a: Int): Int {
var b: Int = 1
<selection> when {
a > 0 -> {
b = b + 1
}
a < 0 -> {
b = b - 1
}
}
println(b)</selection>
return b
} | apache-2.0 |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/config/ProjectConfigFacade.kt | 1 | 651 | package zielu.gittoolbox.config
import com.intellij.openapi.project.Project
import zielu.gittoolbox.util.PrjBaseFacade
internal class ProjectConfigFacade(
private val project: Project
) : PrjBaseFacade(project) {
fun migrate(appConfig: GitToolBoxConfig2, state: GitToolBoxConfigPrj): Boolean {
val timer = getMetrics().timer("project-config.migrate")
return timer.timeSupplierKt { ConfigMigrator().migrate(project, appConfig, state) }
}
fun publishUpdated(previous: GitToolBoxConfigPrj, current: GitToolBoxConfigPrj) {
publishSync { it.syncPublisher(ProjectConfigNotifier.CONFIG_TOPIC).configChanged(previous, current) }
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/usePropertyAccessSyntax/set.kt | 9 | 145 | // PROBLEM: "Use of setter method instead of property access syntax"
// WITH_STDLIB
fun foo(thread: Thread) {
thread.setName<caret>("name")
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/constructorParameter/annotationWithCustomParameter/ImplicitNamedParameter.kt | 18 | 32 | @KAnn("abc")
class ImplicitUsage | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/mutableCollections/Iterator.kt | 12 | 530 | internal class IteratorTest {
var mutableMap1: MutableMap<String, String> = HashMap()
var mutableMap2: MutableMap<String, String> = HashMap()
fun testFields() {
mutableMap1.values.add("")
mutableMap2.entries.iterator().remove()
}
fun testFunctionParameters(immutableCollection: Collection<String?>, mutableList: MutableList<Int?>) {
val it = immutableCollection.iterator()
while (it.hasNext()) {
it.next()
}
mutableList.listIterator().add(2)
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantNullableReturnType/property/initializer.kt | 12 | 70 | // PROBLEM: 'foo' is always non-null type
val foo: String?<caret> = "" | apache-2.0 |
smmribeiro/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInspection/JavaReflectionMemberAccessTest.kt | 13 | 1921 | /*
* 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.java.codeInspection
import com.intellij.JavaTestUtil
import com.intellij.codeInspection.reflectiveAccess.JavaReflectionMemberAccessInspection
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
/**
* @author Pavel.Dolgov
*/
class JavaReflectionMemberAccessTest : LightJavaCodeInsightFixtureTestCase() {
private val inspection = JavaReflectionMemberAccessInspection()
override fun setUp() {
super.setUp()
myFixture.enableInspections(inspection)
}
override fun getProjectDescriptor(): LightProjectDescriptor = JAVA_8 // older mock JREs are missing some bits
override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/inspection/javaReflectionMemberAccess"
fun testFields() = doTest()
fun testMethods() = doTest()
fun testConstructors() = doTest()
fun testFieldExists() = doTest(true)
fun testMethodExists() = doTest(true)
fun testConstructorExists() = doTest(true)
fun testNewInstance() = doTest(true)
fun testBugs() = doTest(true)
fun testClassArray() = doTest(true)
private fun doTest(checkExists: Boolean = false) {
inspection.checkMemberExistsInNonFinalClasses = checkExists
myFixture.testHighlighting("${getTestName(false)}.java")
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/trailingComma/addComma4.kt | 13 | 114 | // COMPILER_ARGUMENTS: -XXLanguage:+TrailingCommas
// PROBLEM: none
fun a(i: Int,
b: Boolean <caret>
) = Unit | apache-2.0 |
Flank/flank | test_runner/src/test/kotlin/ftl/cli/firebase/test/TestCommandUtils.kt | 1 | 140 | package ftl.cli.firebase.test
const val SUCCESS_VALIDATION_MESSAGE = "Valid yml file\n"
const val INVALID_YML_PATH = "./flank-invalid.yml"
| apache-2.0 |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/codegen/model/ModelFromAPIGenerator.kt | 1 | 13794 | package uy.kohesive.iac.model.aws.codegen.model
import com.amazonaws.codegen.C2jModels
import com.amazonaws.codegen.CodeGenerator
import com.amazonaws.codegen.model.config.BasicCodeGenConfig
import com.amazonaws.codegen.model.config.customization.CustomizationConfig
import com.amazonaws.codegen.model.service.*
import com.amazonaws.http.HttpMethodName
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import com.github.javaparser.ast.type.ClassOrInterfaceType
import org.reflections.Reflections
import org.reflections.scanners.TypeElementsScanner
import uy.klutter.core.common.mustNotStartWith
import uy.kohesive.iac.model.aws.utils.firstLetterToUpperCase
import uy.kohesive.iac.model.aws.utils.namespace
import uy.kohesive.iac.model.aws.utils.simpleName
import java.util.*
data class EnumHandler(
val enumClass: Class<*>,
val keys: List<String>
)
class ModelFromAPIGenerator(
val serviceInterface: Class<*>,
val serviceMetadata: ServiceMetadata,
val outputDir: String,
val verbToHttpMethod: Map<String, HttpMethodName>,
val fileNamePrefix: String,
val enumHandlers: List<EnumHandler>,
serviceSourcesDir: String
) {
private val interfaceSimpleName: String = serviceInterface.simpleName
private val packageName: String = serviceInterface.canonicalName.namespace()
private val modelPackage = packageName + ".model"
private val modelClassFqNamesBySimpleName = TypeElementsScanner().apply {
Reflections(modelPackage, this)
}.store.keySet().associateBy(String::simpleName).mapKeys {
if (it.key.contains("$")) {
it.key.substring(it.key.lastIndexOf('$') + 1)
} else {
it.key
}
} + listOf(
java.lang.String::class.java,
java.lang.Boolean::class.java,
java.lang.Integer::class.java,
java.lang.Long::class.java,
java.lang.Object::class.java
).associate { it.simpleName to it.name }
private val sources = SourceCache(serviceSourcesDir)
private val codeGenConfig = BasicCodeGenConfig(
interfaceSimpleName,
packageName,
null,
null,
null
)
private val classFqNameToShape = HashMap<String, Pair<String, Shape>>()
private fun getModelClassBySimpleName(simpleName: String) = modelClassFqNamesBySimpleName[simpleName]?.let { fqName ->
Class.forName(fqName)
} ?: throw IllegalArgumentException("Unknown model class: $simpleName")
private fun getOrCreateShape(
clazz: Class<*>,
typeParameterFqNames: List<Class<*>> = emptyList(),
shapeNameOverride: String? = null
): Pair<String, Shape> =
(clazz.name + (if (typeParameterFqNames.isEmpty()) "" else "<${typeParameterFqNames.joinToString(", ")}>")).let { classFqName ->
var fillWithMembers = false
classFqNameToShape.getOrPut(classFqName) {
val nameAndShape = if (clazz.isPrimitive) {
clazz.name.firstLetterToUpperCase() to Shape().apply { type = clazz.name.toLowerCase() }
} else if (clazz.isEnum) {
val enumHandler = enumHandlers.firstOrNull { it.enumClass == clazz}
?: throw IllegalArgumentException("No enum handler defined for ${clazz.simpleName}")
clazz.simpleName to Shape().apply {
enumValues = enumHandler.keys.filterNotNull()
type = "structure"
}
} else if (clazz.name == "java.lang.Object") {
// Looks weird, but seems to be correct. Raw Objects are used in Map values mapped to Strings.
"String" to Shape().apply { type = "string" }
} else if (clazz.name.startsWith("java.lang.")) {
clazz.simpleName to Shape().apply { type = clazz.simpleName.toLowerCase() }
} else if (clazz.name == "java.util.Date") {
"Date" to Shape().apply { type = "timestamp" }
} else if (clazz.name.endsWith("[]") || clazz.name.namespace().let { it == "java.io" || it == "java.net" }) {
throw UnModelableOperation()
} else if (List::class.java.isAssignableFrom(clazz) || Set::class.java.isAssignableFrom(clazz)) {
if (typeParameterFqNames.isEmpty()) {
throw IllegalStateException("Un-parameterized list")
}
val listParameter = typeParameterFqNames.first()
(listParameter.simpleName + if (Set::class.java.isAssignableFrom(clazz)) "Set" else "List") to Shape().apply {
type = "list"
listMember = Member().apply {
shape = getOrCreateShape(listParameter).first
}
}
} else if (Map::class.java.isAssignableFrom(clazz)) {
if (typeParameterFqNames.isEmpty()) {
throw UnModelableOperation("Un-parameterized map")
}
val mapKeyParameter = typeParameterFqNames[0]
val mapValueParameter = typeParameterFqNames[1]
mapValueParameter.simpleName + "Map" to Shape().apply {
type = "map"
mapKeyType = Member().apply {
shape = getOrCreateShape(mapKeyParameter).first
}
mapValueType = Member().apply {
shape = getOrCreateShape(mapValueParameter).first
}
}
} else {
fillWithMembers = true
clazz.simpleName to Shape().apply {
type = "structure"
}
}
// Override shape name
shapeNameOverride?.let { it to nameAndShape.second } ?: nameAndShape
}.apply {
// We fill shape members after shape is added to map to avoid infinite loops
if (fillWithMembers) {
val membersByGetters = clazz.declaredMethods.filter { method ->
method.name.startsWith("get") || method.name.startsWith("is")
}.map { getter ->
getter.name.mustNotStartWith("get").mustNotStartWith("is") to getter.returnType
}.toMap()
second.members = membersByGetters.mapValues {
val member = it.key
val memberClass = it.value
val typeArguments = getCollectionTypeArguments(clazz, "get$member", memberClass)
Member().apply {
shape = getOrCreateShape(memberClass, typeParameterFqNames = typeArguments).first
}
}
}
}
}
private fun getCollectionTypeArguments(clazz: Class<*>, memberName: String, memberClass: Class<*>): List<Class<*>> =
if (memberClass.simpleName.let { it == "List" || it == "Set" || it == "Map" }) {
val classifierFromSources = sources.get(clazz.name).let { compilationUnit ->
if (clazz.name.contains('$')) {
val pathArray = clazz.name.simpleName().split('$')
val initialType = compilationUnit.types.filterIsInstance<ClassOrInterfaceDeclaration>().first {
it.nameAsString == pathArray[0]
}
pathArray.drop(1).fold(initialType) { classifier, pathElement ->
classifier.childNodes.filterIsInstance<ClassOrInterfaceDeclaration>().first {
it.nameAsString == pathElement
}
}
} else {
if (clazz.isInterface) {
compilationUnit.getInterfaceByName(clazz.simpleName).get()
} else {
compilationUnit.getClassByName(clazz.simpleName).get()
}
}
}
classifierFromSources.getMethodsByName(memberName)?.firstOrNull()?.let { getter ->
(getter.type as? ClassOrInterfaceType)?.typeArguments?.get()?.map { typeArgument ->
(typeArgument as? ClassOrInterfaceType)?.nameAsString?.let { simpleName ->
getModelClassBySimpleName(simpleName)
}
}
}.orEmpty().filterNotNull()
} else {
emptyList()
}
private fun createOperations(): List<Operation> {
val requestMethodsToRequestClasses = serviceInterface.methods.groupBy { it.name }.mapValues {
// Here we take the method -> request class pair where request class is not null
it.value.map { method ->
method to method.parameters.firstOrNull { parameter ->
parameter.type.simpleName.endsWith("Request")
}?.type
}.firstOrNull {
it.second != null // it.second is request class
}
}.values.filterNotNull().toMap().filterValues { it != null }.mapValues { it.value!! }.filter {
"${it.key.name.firstLetterToUpperCase()}Request" == it.value.simpleName
}
return requestMethodsToRequestClasses.map {
try {
val requestMethod = it.key
val requestClass = it.value
val resultClass = it.key.returnType
val operationName = requestMethod.name.firstLetterToUpperCase()
val httpMethod = verbToHttpMethod.keys.firstOrNull { operationName.startsWith(it) }?.let { verb ->
verbToHttpMethod[verb]
}?.name ?: throw IllegalStateException("Can't figure out HTTP method for $operationName")
val http = Http()
.withMethod(httpMethod)
.withRequestUri("/")
val input = Input().apply {
shape = operationName + "Input"
}
getOrCreateShape(requestClass, shapeNameOverride = input.shape)
val output = Output().apply {
shape = if (resultClass.simpleName.endsWith("Result")) {
operationName + "Output"
} else {
resultClass.simpleName
}
}
val typeArguments = getCollectionTypeArguments(serviceInterface, requestMethod.name, resultClass)
getOrCreateShape(resultClass, shapeNameOverride = output.shape, typeParameterFqNames = typeArguments)
Operation()
.withName(operationName)
.withInput(input)
.withHttp(http).apply { setOutput(output) }
} catch (umo: UnModelableOperation) {
// ignore this operation
null
}
}.filterNotNull()
}
fun generate() {
// Create operations and shapes used in operations
val operations = createOperations().sortedBy { it.name }.associateBy { it.name }
val shapesFromOps = classFqNameToShape.values.toMap()
// Create shapes for the rest of model classes
val modelsClassesWithNoShape = (modelClassFqNamesBySimpleName - (modelClassFqNamesBySimpleName.keys.intersect(shapesFromOps.keys))).filter {
val simpleName = it.key
val fqName = it.value
fqName.namespace() == modelPackage &&
!simpleName.endsWith("marshaller", ignoreCase = true) &&
!simpleName.endsWith("Request") &&
!simpleName.startsWith("Abstract") &&
simpleName.first().isJavaIdentifierStart() &&
simpleName.all(Char::isJavaIdentifierPart)
}
val shapeFromModelsNames = modelsClassesWithNoShape.map {
try {
getOrCreateShape(getModelClassBySimpleName(it.key)).first
} catch (umo: UnModelableOperation) {
null
}
}.filterNotNull()
// Create a fake operation to reference the model shapes not used in real operations
val preserveModelsShape = "KohesiveModelPreserveInput" to Shape().apply {
type = "structure"
members = shapeFromModelsNames.associate { shapeName ->
shapeName to Member().apply {
shape = shapeName
}
}
}
val preserveModelsOp = "KohesivePreserveShapesOperation" to Operation()
.withName("KohesivePreserveShapesOperation")
.withInput(Input().apply {
shape = "KohesiveModelPreserveInput"
})
.withHttp(Http()
.withMethod("GET")
.withRequestUri("/")
)
// Build the models
val c2jModels = C2jModels.builder()
.codeGenConfig(codeGenConfig)
.customizationConfig(CustomizationConfig.DEFAULT)
.serviceModel(ServiceModel(
serviceMetadata,
operations + preserveModelsOp,
(classFqNameToShape.values.toMap() + preserveModelsShape).toSortedMap(),
emptyMap()
)
).build()
// Generate models JSON and service API
CodeGenerator(c2jModels, outputDir, outputDir, fileNamePrefix).execute()
}
}
class UnModelableOperation(override val message: String? = null) : Exception() | mit |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/logging/LTag.kt | 1 | 975 | package info.nightscout.androidaps.logging
enum class LTag(val tag: String, val defaultValue : Boolean = true, val requiresRestart: Boolean = false) {
CORE("CORE"),
APS("APS"),
AUTOSENS("AUTOSENS", defaultValue = false),
AUTOMATION("AUTOMATION"),
BGSOURCE("BGSOURCE"),
CONFIGBUILDER("CONFIGBUILDER"),
CONSTRAINTS("CONSTRAINTS"),
DATABASE("DATABASE"),
DATAFOOD("DATAFOOD", defaultValue = false),
DATASERVICE("DATASERVICE"),
DATATREATMENTS("DATATREATMENTS"),
EVENTS("EVENTS", defaultValue = false, requiresRestart = true),
GLUCOSE("GLUCOSE"),
LOCATION("LOCATION"),
NOTIFICATION("NOTIFICATION"),
NSCLIENT("NSCLIENT"),
OHUPLOADER("OHUPLOADER"),
PUMP("PUMP"),
PUMPBTCOMM("PUMPBTCOMM", defaultValue = true),
PUMPCOMM("PUMPCOMM"),
PUMPQUEUE("PUMPQUEUE"),
PROFILE("PROFILE"),
SMS("SMS"),
TIDEPOOL("TIDEPOOL"),
UI("UI", defaultValue = false),
WEAR("WEAR", defaultValue = false)
} | agpl-3.0 |
MyPureCloud/platform-client-sdk-common | resources/sdk/purecloudkotlin/extensions/extensions/notifications/Metadata.kt | 1 | 285 | package com.mypurecloud.sdk.v2.extensions.notifications
import com.fasterxml.jackson.annotation.JsonProperty
class Metadata {
@JsonProperty("CorrelationId")
private val correlationId: String? = null
fun getCorrelationId(): String? {
return correlationId
}
}
| mit |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Review_Bolus_Avg.kt | 1 | 1900 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_Review_Bolus_Avg(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
var dataIndex = DATA_START
var dataSize = 2
val bolusAvg03 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg07 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg14 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg21 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg28 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
val required = ((1 and 0x000000FF shl 8) + (1 and 0x000000FF)) / 100.0
if (bolusAvg03 == bolusAvg07 && bolusAvg07 == bolusAvg14 && bolusAvg14 == bolusAvg21 && bolusAvg21 == bolusAvg28 && bolusAvg28 == required) failed = true
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 3d: $bolusAvg03 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 7d: $bolusAvg07 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 14d: $bolusAvg14 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 21d: $bolusAvg21 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 28d: $bolusAvg28 U")
}
override fun getFriendlyName(): String {
return "REVIEW__BOLUS_AVG"
}
} | agpl-3.0 |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAWSHealth.kt | 1 | 460 | package uy.kohesive.iac.model.aws.clients
import com.amazonaws.services.health.AbstractAWSHealth
import com.amazonaws.services.health.AWSHealth
import com.amazonaws.services.health.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.proxy.makeProxy
open class BaseDeferredAWSHealth(val context: IacContext) : AbstractAWSHealth(), AWSHealth {
}
class DeferredAWSHealth(context: IacContext) : BaseDeferredAWSHealth(context)
| mit |
proff/teamcity-cachedSubversion | cachedSubversion-agent/src/main/java/com/proff/teamcity/cachedSubversion/cacheRule.kt | 1 | 1436 | package com.proff.teamcity.cachedSubversion
import org.tmatesoft.svn.core.SVNException
import org.tmatesoft.svn.core.SVNURL
import java.io.File
class cacheRule(rule: String) {
val source: SVNURL
val name: String?
val target: cacheTarget?
init {
val arr = rule.split(' ')
source = SVNURL.parseURIEncoded(arr[0])
name = if (arr.count() > 1) arr[1] else null
if (arr.count() > 2) {
var t: cacheTarget
try {
t = cacheTarget(SVNURL.parseURIEncoded(arr[2]))
} catch(e: SVNException) {
//is not url, try parse as File
t = cacheTarget(File(arr[2]))
}
target = t
} else
target = null
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as cacheRule
if (source != other.source) return false
if (name != other.name) return false
if (target != other.target) return false
return true
}
override fun hashCode(): Int {
var result = source.hashCode()
result = 31 * result + (name?.hashCode() ?: 0)
result = 31 * result + (target?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "cacheRule(source=$source, name=$name, target=$target)"
}
} | mit |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/dataClassInsideDataClass.0.kt | 5 | 447 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages
data class A(val <caret>x: Int, val y: Int, val z: String)
data class B(val a: A, val n: Int)
class C {
operator fun component1(): A = TODO()
operator fun component2() = 0
}
fun f(b: B, c: C) {
val (a, n) = b
val (x, y, z) = a
val (a1, n1) = c
val (x1, y1, z1) = a1
}
// FIR_COMPARISON
// FIR_COMPARISON_WITH_DISABLED_COMPONENTS
// IGNORE_FIR_LOG
| apache-2.0 |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/assets/FormatNotSupportedException.kt | 1 | 762 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.assets
/**
* @author Marcus Brummer
* @version 24-11-2015
*/
class FormatNotSupportedException : RuntimeException()
| apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantWith/simple2.kt | 9 | 109 | // WITH_STDLIB
fun test(s: String) {
with<caret> (s, {
println("1")
println("2")
})
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/pureKotlin/classSignatureUnchanged/class.kt | 5 | 73 | package test
class Klass {
fun foo() = ":)"
fun bar() = ":("
}
| apache-2.0 |
HenningLanghorst/fancy-kotlin-stuff | src/main/kotlin/de/henninglanghorst/kotlinstuff/coroutines/Coroutines.kt | 1 | 2620 | package de.henninglanghorst.kotlinstuff.coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
import java.io.PrintStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.stream.Collectors
private val logger = LoggerFactory.getLogger(Exception().stackTrace[0].className)
fun main(args: Array<String>) {
val message1 = httpRequestAsync("https://postman-echo.com/post?hhhhh=5") {
requestMethod = "POST"
setRequestProperty("Authorization", "Basic d2lraTpwZWRpYQ==")
setRequestProperty("Content-Type", "application/json; charset=utf-8")
body = json(6, "Miller")
}
val message2 = httpRequestAsync("https://postman-echo.com/get?s=5&aaa=43") {
requestMethod = "GET"
setRequestProperty("Authorization", "Basic d2lraTpwZWRpYQ==")
}
val message3 = httpRequestAsync("https://postman-echo.com/status/400") {
requestMethod = "GET"
setRequestProperty("Authorization", "Basic d2lraTpwZWRpYQ==")
}
runBlocking {
println(message1.await())
println(message2.await())
}
runBlocking { println(message3.await()) }
}
private fun json(id: Int, name: String) = """{"id": $id, "name": "$name"}"""
private fun httpRequestAsync(url: String, setup: HttpURLConnection.() -> Unit) = GlobalScope.async { httpRequest(url, setup) }
private fun httpRequest(url: String, setup: HttpURLConnection.() -> Unit): String {
return URL(url).openConnection()
.let { it as HttpURLConnection }
.apply { doInput = true }
.apply(setup)
.also { logger.info("HTTP ${it.requestMethod} call to $url") }
.run {
responseStream.bufferedReader(Charsets.UTF_8)
.lines()
.collect(Collectors.joining(System.lineSeparator()))
}
}
private val HttpURLConnection.responseStream: InputStream
get() =
try {
inputStream
} catch (e: IOException) {
errorStream ?: ByteArrayInputStream(byteArrayOf())
}
private var HttpURLConnection.body: String
set(value) {
doOutput = requestMethod != "GET" && value.isNotEmpty()
if (doOutput)
PrintStream(outputStream).use {
it.println(value)
it.flush()
}
}
get() = ""
private fun return5(): Int {
Thread.sleep(4000)
return 5
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertFilteringFunctionWithDemorgansLaw/callToOpposite/allToNone/simple.kt | 2 | 85 | // WITH_RUNTIME
fun test(list: List<Int>) {
val b = list.<caret>all { it != 1 }
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/cocoapods/KotlinCocoaPodsModelResolver.kt | 1 | 900 | // 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.cocoapods
import org.jetbrains.kotlin.gradle.EnablePodImportTask
import org.jetbrains.plugins.gradle.model.ClassSetProjectImportModelProvider
import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
class KotlinCocoaPodsModelResolver : AbstractProjectResolverExtension() {
override fun getToolingExtensionsClasses(): Set<Class<out Any>> {
return setOf(EnablePodImportTask::class.java)
}
override fun getProjectsLoadedModelProvider(): ProjectImportModelProvider {
return ClassSetProjectImportModelProvider(
setOf(EnablePodImportTask::class.java)
)
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/variable/plusAssignFun.0.kt | 3 | 346 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtProperty
// OPTIONS: usages
class C
operator fun C.plusAssign(p: Int) = this
fun foo() {
val <caret>c = C()
c += 10
}
// ERROR: 'operator' modifier is inapplicable on this function: must return Unit
// ERROR: Function 'plusAssign' should return Unit to be used by corresponding operator '+='
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/map/mapAndFilterIndexed.kt | 4 | 365 | // WITH_RUNTIME
// INTENTION_TEXT: "Replace with 'map{}.filterIndexed{}.firstOrNull()'"
// INTENTION_TEXT_2: "Replace with 'asSequence().map{}.filterIndexed{}.firstOrNull()'"
fun foo(list: List<String>): Int? {
<caret>for ((index, s) in list.withIndex()) {
val l = s.length
if (l > index) {
return l
}
}
return null
} | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.