content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.workflow import org.hl7.elm.r1.VersionedIdentifier import org.hl7.fhir.instance.model.api.IBaseResource import org.hl7.fhir.r4.model.Library import org.opencds.cqf.cql.evaluator.cql2elm.content.fhir.BaseFhirLibrarySourceProvider import org.opencds.cqf.cql.evaluator.fhir.adapter.r4.AdapterFactory class FhirEngineLibraryContentProvider(adapterFactory: AdapterFactory) : BaseFhirLibrarySourceProvider(adapterFactory) { val libs = mutableMapOf<String, Library>() override fun getLibrary(libraryIdentifier: VersionedIdentifier): IBaseResource? { return libs[libraryIdentifier.id] } }
workflow/src/main/java/com/google/android/fhir/workflow/FhirEngineLibraryContentProvider.kt
3408151860
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.views import android.view.ViewGroup import android.widget.CheckBox import android.widget.FrameLayout import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.children import com.google.android.fhir.datacapture.ChoiceOrientationTypes import com.google.android.fhir.datacapture.EXTENSION_CHOICE_ORIENTATION_URL import com.google.android.fhir.datacapture.EXTENSION_OPTION_EXCLUSIVE_URL import com.google.android.fhir.datacapture.R import com.google.android.fhir.datacapture.validation.Invalid import com.google.android.fhir.datacapture.validation.NotValidated import com.google.common.truth.Truth.assertThat import org.hl7.fhir.r4.model.BooleanType import org.hl7.fhir.r4.model.CodeType import org.hl7.fhir.r4.model.Coding import org.hl7.fhir.r4.model.Extension import org.hl7.fhir.r4.model.Questionnaire import org.hl7.fhir.r4.model.QuestionnaireResponse import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment @RunWith(RobolectricTestRunner::class) class QuestionnaireItemCheckBoxGroupViewHolderFactoryTest { private val parent = FrameLayout( RuntimeEnvironment.getApplication().apply { setTheme(R.style.Theme_Material3_DayNight) } ) private val viewHolder = QuestionnaireItemCheckBoxGroupViewHolderFactory.create(parent) @Test fun bind_shouldSetQuestionHeader() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.itemView.findViewById<TextView>(R.id.question).text.toString()) .isEqualTo("Question?") } @Test fun bind_vertical_shouldCreateCheckBoxButtons() { val questionnaire = Questionnaire.QuestionnaireItemComponent().apply { repeats = true addExtension( EXTENSION_CHOICE_ORIENTATION_URL, CodeType(ChoiceOrientationTypes.VERTICAL.extensionCode) ) addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { display = "Coding 1" } } ) addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { display = "Coding 2" } } ) } viewHolder.bind( QuestionnaireItemViewItem( questionnaire, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group) val children = checkBoxGroup.children.asIterable().filterIsInstance<CheckBox>() children.forEachIndexed { index, view -> assertThat(view.text).isEqualTo(questionnaire.answerOption[index].valueCoding.display) assertThat(view.layoutParams.width).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT) } } @Test fun bind_horizontal_shouldCreateCheckBoxButtons() { val questionnaire = Questionnaire.QuestionnaireItemComponent().apply { repeats = true addExtension( EXTENSION_CHOICE_ORIENTATION_URL, CodeType(ChoiceOrientationTypes.HORIZONTAL.extensionCode) ) addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { display = "Coding 1" } } ) addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { display = "Coding 2" } } ) } viewHolder.bind( QuestionnaireItemViewItem( questionnaire, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group) val children = checkBoxGroup.children.asIterable().filterIsInstance<CheckBox>() children.forEachIndexed { index, view -> assertThat(view.text).isEqualTo(questionnaire.answerOption[index].valueCoding.display) assertThat(view.layoutParams.width).isEqualTo(ViewGroup.LayoutParams.WRAP_CONTENT) } } @Test fun bind_noAnswer_shouldLeaveCheckButtonsUnchecked() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { display = "Coding 1" } } ) }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group) val checkBox = checkBoxGroup.getChildAt(1) as CheckBox assertThat(checkBox.isChecked).isFalse() } @Test fun bind_answer_shouldSetCheckBoxButton() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { code = "code 1" display = "Coding 1" } } ) }, QuestionnaireResponse.QuestionnaireResponseItemComponent().apply { addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply { value = Coding().apply { code = "code 1" display = "Coding 1" } } ) }, validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group) val checkBox = checkBoxGroup.getChildAt(1) as CheckBox assertThat(checkBox.isChecked).isTrue() } @Test fun click_shouldAddQuestionnaireResponseItemAnswer() { var answerHolder: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null val questionnaireItemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { code = "code 1" display = "Coding 1" } } ) }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, answers -> answerHolder = answers }, ) viewHolder.bind(questionnaireItemViewItem) val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group) val checkBox = checkBoxGroup.getChildAt(1) as CheckBox checkBox.performClick() assertThat(answerHolder!!.single().valueCoding.display).isEqualTo("Coding 1") } @Test fun optionExclusiveAnswerOption_click_deselectsOtherAnswerOptions() { var answerHolder: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null val questionnaireItemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { code = "code-1" display = "display-1" } extension = listOf(Extension(EXTENSION_OPTION_EXCLUSIVE_URL, BooleanType(true))) } ) addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { code = "code-2" display = "display-2" } } ) }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, answers -> answerHolder = answers }, ) viewHolder.bind(questionnaireItemViewItem) val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group) (checkBoxGroup.getChildAt(2) as CheckBox).performClick() (checkBoxGroup.getChildAt(1) as CheckBox).performClick() assertThat(answerHolder!!.single().valueCoding.display).isEqualTo("display-1") } @Test fun answerOption_click_deselectsOptionExclusiveAnswerOption() { var answerHolder: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null val questionnaireItemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { code = "code-1" display = "display-1" } extension = listOf(Extension(EXTENSION_OPTION_EXCLUSIVE_URL, BooleanType(true))) } ) addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { code = "code-2" display = "display-2" } } ) }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, answers -> answerHolder = answers }, ) viewHolder.bind(questionnaireItemViewItem) val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group) (checkBoxGroup.getChildAt(1) as CheckBox).performClick() (checkBoxGroup.getChildAt(2) as CheckBox).performClick() assertThat(answerHolder!!.single().valueCoding.display).isEqualTo("display-2") } @Test fun click_shouldRemoveQuestionnaireResponseItemAnswer() { var answerHolder: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null val questionnaireItemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true answerValueSet = "http://coding-value-set-url" }, QuestionnaireResponse.QuestionnaireResponseItemComponent().apply { addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply { value = Coding().apply { code = "code 1" display = "Coding 1" } } ) }, resolveAnswerValueSet = { if (it == "http://coding-value-set-url") { listOf( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { code = "code 1" display = "Coding 1" } } ) } else { emptyList() } }, validationResult = NotValidated, answersChangedCallback = { _, _, answers -> answerHolder = answers }, ) viewHolder.bind(questionnaireItemViewItem) val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group) val checkBox = checkBoxGroup.getChildAt(1) as CheckBox checkBox.performClick() assertThat(answerHolder).isEmpty() } @Test fun displayValidationResult_error_shouldShowErrorMessage() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true required = true }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = Invalid(listOf("Missing answer for required field.")), answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.itemView.findViewById<TextView>(R.id.error_text_at_header).text) .isEqualTo("Missing answer for required field.") } @Test fun displayValidationResult_noError_shouldShowNoErrorMessage() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true required = true addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { display = "display" } } ) }, QuestionnaireResponse.QuestionnaireResponseItemComponent().apply { addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply { value = Coding().apply { display = "display" } } ) }, validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.itemView.findViewById<TextView>(R.id.error_text_at_header).text.isEmpty()) .isTrue() } @Test fun bind_readOnly_shouldDisableView() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { repeats = true readOnly = true addAnswerOption( Questionnaire.QuestionnaireItemAnswerOptionComponent().apply { value = Coding().apply { display = "Coding 1" } } ) }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat( (viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group).getChildAt(1) as CheckBox) .isEnabled ) .isFalse() } }
datacapture/src/test/java/com/google/android/fhir/datacapture/views/QuestionnaireItemCheckBoxGroupViewHolderFactoryTest.kt
2490813036
@file:JvmName("Gensokyo") @file:JvmMultifileClass package charlie.gensokyo import java.awt.BorderLayout import java.awt.Container import java.awt.GridLayout import java.awt.IllegalComponentStateException import javax.swing.JComponent import javax.swing.JDialog import javax.swing.JFrame import javax.swing.JLabel inline val Container.abstractLayout: Unit get() { layout = null } inline val JFrame.abstractLayout: Unit get() = contentPane.abstractLayout inline val JDialog.abstractLayout: Unit get() = contentPane.abstractLayout inline val Container.borderLayout: Unit get() { layout = BorderLayout() } inline val JFrame.borderLayout: Unit get() = contentPane.abstractLayout inline val JDialog.borderLayout: Unit get() = contentPane.abstractLayout inline fun Container.gridLayout(block: GridLayoutHelper.() -> Unit) { layout = BorderLayout() removeAll() add(GridLayoutHelper().apply(block)) } inline fun JFrame.gridLayout(block: GridLayoutHelper.() -> Unit) = contentPane.gridLayout(block) inline fun JDialog.gridLayout(block: GridLayoutHelper.() -> Unit) = contentPane.gridLayout(block) class GridLayoutHelper: JComponent() { private var rowIndex = -1 private var columnIndex = 0 private var firstRowInserted = false fun row(block: GridLayoutHelper.() -> Unit) { if (firstRowInserted) (layout as GridLayout).rows++ columnIndex = 0 rowIndex++ block() firstRowInserted = true } val gap: Unit get() { JLabel().apply { [email protected](this) add(this) } } internal fun ensureColumns() { if (++columnIndex > (layout as GridLayout).columns) { if (!firstRowInserted) (layout as GridLayout).columns++ else throw IllegalComponentStateException("columns of row under the first row is more than the first row. add gaps. ") } } private fun beforeAddingComponent(comp: JComponent) = ensureColumns() init { layout = GridLayout() } }
src/main/kotlin/charlie/gensokyo/LayoutExtension.kt
803141497
package net.pureal.traits.math import java.math.BigInteger public trait RealPrimitive : Real { val value: InternalReal override fun toString() = "real(\"${value.toMathematicalString()}\")" override fun approximate() = value override fun equals(other: Any?): Boolean { return when (other) { is RealPrimitive -> value == other.value is Real -> false is Number -> value == other else -> false } } override fun minus(): Real = real(-value) override val isPositive: Boolean get() = value > 0 override val isZero: Boolean get() = value equals 0 }
traits/src/net/pureal/traits/math/RealPrimitive.kt
2048473909
package org.wikipedia.descriptions import android.content.Context import android.net.Uri import android.util.AttributeSet import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import org.wikipedia.databinding.ViewDescriptionEditReviewBinding import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_ARTICLE_DESCRIPTION import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_DEFAULT import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_IMAGE_CAPTION import org.wikipedia.suggestededits.PageSummaryForEdit import org.wikipedia.util.L10nUtil import org.wikipedia.util.StringUtil import org.wikipedia.views.ViewUtil class DescriptionEditReviewView constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) { private val binding = ViewDescriptionEditReviewBinding.inflate(LayoutInflater.from(context), this) val isShowing: Boolean get() = visibility == VISIBLE fun show() { visibility = VISIBLE } fun hide() { visibility = GONE } fun setSummary(summaryForEdit: PageSummaryForEdit, description: String, captionReview: Boolean) { L10nUtil.setConditionalLayoutDirection(this, summaryForEdit.lang) if (captionReview) { setGalleryReviewView(summaryForEdit, description) binding.licenseView.buildLicenseNotice(ARG_NOTICE_IMAGE_CAPTION) } else { setDescriptionReviewView(summaryForEdit, description) binding.licenseView.buildLicenseNotice(if (summaryForEdit.description.isNullOrEmpty()) ARG_NOTICE_ARTICLE_DESCRIPTION else ARG_NOTICE_DEFAULT, summaryForEdit.lang) } } private fun setDescriptionReviewView(summaryForEdit: PageSummaryForEdit, description: String) { binding.galleryContainer.visibility = GONE binding.articleTitle.text = StringUtil.fromHtml(summaryForEdit.displayTitle) binding.articleSubtitle.text = description binding.articleExtract.text = StringUtil.fromHtml(summaryForEdit.extractHtml) if (summaryForEdit.thumbnailUrl.isNullOrBlank()) { binding.articleImage.visibility = GONE binding.articleExtract.maxLines = ARTICLE_EXTRACT_MAX_LINE_WITHOUT_IMAGE } else { binding.articleImage.visibility = VISIBLE binding.articleImage.loadImage(Uri.parse(summaryForEdit.getPreferredSizeThumbnailUrl())) binding.articleExtract.maxLines = ARTICLE_EXTRACT_MAX_LINE_WITH_IMAGE } } private fun setGalleryReviewView(summaryForEdit: PageSummaryForEdit, description: String) { binding.articleContainer.visibility = GONE binding.indicatorDivider.visibility = GONE binding.galleryDescriptionText.text = StringUtil.fromHtml(description) if (summaryForEdit.thumbnailUrl.isNullOrBlank()) { binding.galleryImage.visibility = GONE } else { binding.galleryImage.visibility = VISIBLE ViewUtil.loadImage(binding.galleryImage, summaryForEdit.getPreferredSizeThumbnailUrl()) } binding.licenseView.darkLicenseView() } companion object { const val ARTICLE_EXTRACT_MAX_LINE_WITH_IMAGE = 5 const val ARTICLE_EXTRACT_MAX_LINE_WITHOUT_IMAGE = 15 } }
app/src/main/java/org/wikipedia/descriptions/DescriptionEditReviewView.kt
1866229711
package com.phapps.elitedangerous.companion.api.edc.dtos data class EdcHealthDto(val hull: Long, val shield: Long, val shieldup: String, val integrity: Int, val paintwork: Int)
app/src/main/java/com/phapps/elitedangerous/companion/api/edc/dtos/EdcHealthDto.kt
3331268914
package org.wikipedia.crash import org.wikipedia.activity.SingleFragmentActivity class CrashReportActivity : SingleFragmentActivity<CrashReportFragment>() { override fun createFragment(): CrashReportFragment { return CrashReportFragment.newInstance() } }
app/src/main/java/org/wikipedia/crash/CrashReportActivity.kt
2582633177
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.persistence.remote.firestore.schema import com.google.android.ground.model.Survey import com.google.android.ground.model.basemap.BaseMap import com.google.android.ground.model.job.Job import com.google.android.ground.persistence.remote.DataStoreException import com.google.android.ground.persistence.remote.firestore.schema.JobConverter.toJob import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.google.firebase.firestore.DocumentSnapshot import java.net.MalformedURLException import java.net.URL import timber.log.Timber /** Converts between Firestore documents and [Survey] instances. */ internal object SurveyConverter { @Throws(DataStoreException::class) fun toSurvey(doc: DocumentSnapshot): Survey { val pd = DataStoreException.checkNotNull(doc.toObject(SurveyDocument::class.java), "surveyDocument") val jobMap = ImmutableMap.builder<String, Job>() if (pd.jobs != null) { pd.jobs.forEach { (id: String, obj: JobNestedObject) -> jobMap.put(id, toJob(id, obj)) } } val baseMaps = ImmutableList.builder<BaseMap>() if (pd.baseMaps != null) { convertOfflineBaseMapSources(pd, baseMaps) } return Survey( doc.id, pd.title.orEmpty(), pd.description.orEmpty(), jobMap.build(), baseMaps.build(), ImmutableMap.copyOf(pd.acl) ) } private fun convertOfflineBaseMapSources( pd: SurveyDocument, builder: ImmutableList.Builder<BaseMap> ) { for ((url) in pd.baseMaps!!) { if (url == null) { Timber.d("Skipping base map source in survey with missing URL") continue } try { builder.add(BaseMap(URL(url), BaseMap.typeFromExtension(url))) } catch (e: MalformedURLException) { Timber.d("Skipping base map source in survey with malformed URL") } } } }
ground/src/main/java/com/google/android/ground/persistence/remote/firestore/schema/SurveyConverter.kt
2775424589
package org.spekframework.intellij import com.intellij.execution.Executor import com.intellij.execution.configurations.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.options.SettingsEditor import org.jdom.Element import org.spekframework.intellij.support.SpekJvmCommonRunConfigurationParameters import java.util.* class SpekJvmRunConfiguration(name: String, module: JavaRunConfigurationModule, factory: ConfigurationFactory) : ModuleBasedConfiguration<JavaRunConfigurationModule, RunConfigurationOptions>(name, module, factory) , SpekBaseJvmRunConfiguration { override val data: SpekJvmCommonRunConfigurationParameters = SpekJvmCommonRunConfigurationParameters(project) override fun getConfigurationEditor(): SettingsEditor<out RunConfiguration> { return SpekJvmSettingsEditor(project) } override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? { return SpekRunnnerCommandLineState(environment, this) } override fun getValidModules(): MutableCollection<Module> { return mutableListOf(*ModuleManager.getInstance(project).modules) } override val configurationModule: JavaRunConfigurationModule get() = super.getConfigurationModule() override fun configureForModule(module: Module) { setModule(module) setGeneratedName() } override fun writeExternal(element: Element) { super<ModuleBasedConfiguration>.writeExternal(element) data.writeExternal(element) } override fun readExternal(element: Element) { super<ModuleBasedConfiguration>.readExternal(element) data.readExternal(element) } }
spek-ide-plugin-intellij-idea/src/IJ183/kotlin/org/spekframework/intellij/SpekJvmRunConfiguration.kt
1516653583
package activity.example.yuan.cn.exampletools.utils /** * Created by Administrator on 2018/10/5. */ enum class Colors { red,green }
app/src/main/java/activity/example/yuan/cn/exampletools/utils/Colors.kt
2939766713
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.streams.lib.impl import com.intellij.debugger.streams.lib.LibrarySupport import com.intellij.debugger.streams.lib.LibrarySupportProvider import com.intellij.debugger.streams.psi.impl.JavaChainTransformerImpl import com.intellij.debugger.streams.psi.impl.JavaStreamChainBuilder import com.intellij.debugger.streams.psi.impl.PackageChainDetector import com.intellij.debugger.streams.trace.TraceExpressionBuilder import com.intellij.debugger.streams.trace.dsl.impl.DslImpl import com.intellij.debugger.streams.trace.dsl.impl.java.JavaStatementFactory import com.intellij.debugger.streams.trace.impl.JavaTraceExpressionBuilder import com.intellij.debugger.streams.wrapper.StreamChainBuilder import com.intellij.openapi.project.Project /** * @author Vitaliy.Bibaev */ class StreamExLibrarySupportProvider : LibrarySupportProvider { private val librarySupport = StreamExLibrarySupport() private val javaDsl = DslImpl(JavaStatementFactory()) override fun getLanguageId(): String = "JAVA" override fun getLibrarySupport(): LibrarySupport = librarySupport override fun getExpressionBuilder(project: Project): TraceExpressionBuilder = JavaTraceExpressionBuilder(project, librarySupport.createHandlerFactory(javaDsl), javaDsl) override fun getChainBuilder(): StreamChainBuilder = JavaStreamChainBuilder(JavaChainTransformerImpl(), PackageChainDetector.forJavaStreams("one.util.streamex")) }
plugins/stream-debugger/src/com/intellij/debugger/streams/lib/impl/StreamExLibrarySupportProvider.kt
3153353382
/* * 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.jetbrains.python.sdk.skeletons import com.jetbrains.python.sdk.skeletons.DefaultPregeneratedSkeletonsProvider.getPrebuiltSkeletonsName import com.jetbrains.python.sdk.skeletons.DefaultPregeneratedSkeletonsProvider.isApplicableZippedSkeletonsFileName import junit.framework.TestCase /** * @author traff */ class PySkeletonsRefresherTest : TestCase() { fun testZippedSkeletonsName() { val fileName = getPrebuiltSkeletonsName(0, "3.6.2", true, true) val minorVersionAware = getPrebuiltSkeletonsName(0, "3.6.2", true, false) val minorVersionAgnostic = getPrebuiltSkeletonsName(0, "3.6.2", false, false) assertTrue(isApplicableZippedSkeletonsFileName(minorVersionAware, fileName)) assertTrue(isApplicableZippedSkeletonsFileName(minorVersionAgnostic, fileName)) assertFalse(isApplicableZippedSkeletonsFileName(minorVersionAgnostic, getPrebuiltSkeletonsName(0, "3.5.2", true, true))) } }
python/testSrc/com/jetbrains/python/sdk/skeletons/PySkeletonsRefresherTest.kt
1678492995
package com.tungnui.abccomputer.activity import android.app.Activity import android.content.Context import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.MenuItem import android.view.View import com.travijuu.numberpicker.library.Enums.ActionEnum import com.tungnui.abccomputer.R import com.tungnui.abccomputer.adapter.CartListAdapter import com.tungnui.abccomputer.adapter.CartRecyclerInterface import com.tungnui.abccomputer.data.sqlite.* import com.tungnui.abccomputer.listeners.OnSingleClickListener import com.tungnui.abccomputer.models.Cart import com.tungnui.abccomputer.utils.ActivityUtils import com.tungnui.abccomputer.utils.formatPrice import kotlinx.android.synthetic.main.activity_cart_list.* import com.tungnui.abccomputer.R.id.cartList import com.tungnui.abccomputer.R.string.quantity import android.R.attr.name import com.tungnui.abccomputer.SettingsMy import com.tungnui.abccomputer.data.constant.AppConstants import com.tungnui.abccomputer.models.LineItem class CartListActivity : BaseActivity() { // initialize variables private var mContext: Context? = null private var mActivity: Activity? = null private var cartListAdapter: CartListAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initVariables() initView() loadCartData() initLister() } private fun initVariables() { mContext = applicationContext mActivity = this@CartListActivity } private fun initView() { setContentView(R.layout.activity_cart_list) initToolbar() enableBackButton() setToolbarTitle(getString(R.string.cart_list)) initLoader() // init RecyclerView rvCartList?.setHasFixedSize(true) rvCartList?.layoutManager = LinearLayoutManager(this) cartListAdapter = CartListAdapter(object :CartRecyclerInterface{ override fun onQuantityChange(cart: Cart, quantity: Int, actionEnum: ActionEnum) { cart.id?.let{applicationContext.DbHelper.updateCartQuantity(it,quantity)} loadCartData() } override fun onProductDelete(cart: Cart) { cart.id?.let { applicationContext.DbHelper.deleteCart(it) } loadCartData() } override fun onProductSelect(productId: Int) { /* if (activity is MainActivity) (activity as MainActivity).onProductSelected(productId)*/ } }) rvCartList?.adapter = cartListAdapter } private fun initLister() { btnOrder.setOnClickListener(object : OnSingleClickListener() { override fun onSingleClick(v: View) { val user = SettingsMy.getActiveUser() if(user == null) ActivityUtils.instance.invokeLoginAndOrder(this@CartListActivity) else ActivityUtils.instance.invokeOrderShipping(this@CartListActivity) } }) } private fun setCartVisibility(visible: Boolean) { if (visible) { cart_empty.visibility = View.GONE cart_recycler.visibility = View.VISIBLE cart_footer.visibility = View.VISIBLE } else { cartListAdapter?.cleatCart() cart_empty.visibility = View.VISIBLE cart_recycler.visibility = View.GONE cart_footer.visibility = View.GONE } } private fun loadCartData() { val carts = applicationContext.DbHelper.getAllCart(); if (carts.isEmpty()) { setCartVisibility(false) } else { cartListAdapter?.refreshItems(carts); cart_footer_price.text =applicationContext.DbHelper.totalCart().toString().formatPrice(); setCartVisibility(true) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } else -> return super.onOptionsItemSelected(item) } } }
app/src/main/java/com/tungnui/abccomputer/activity/CartListActivity.kt
1072077851
package stepIntoLibWithSources import java.io.StringReader fun main() { //Breakpoint! val text = StringReader("OK").readText() } // SMART_STEP_INTO_BY_INDEX: 2
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/stepIntoLibWithSources.kt
2764303699
package org.intellij.markdown.parser.markerblocks.impl import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkdownParserUtil import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl public class ListItemMarkerBlock(myConstraints: MarkdownConstraints, marker: ProductionHolder.Marker) : MarkerBlockImpl(myConstraints, marker) { override fun allowsSubBlocks(): Boolean = true override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = pos.char == '\n' override fun getDefaultAction(): MarkerBlock.ClosingAction { return MarkerBlock.ClosingAction.DONE } override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int { return pos.nextLineOffset ?: -1 } override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult { assert(pos.char == '\n') val eolN = MarkdownParserUtil.calcNumberOfConsequentEols(pos, constraints) if (eolN >= 3) { return MarkerBlock.ProcessingResult.DEFAULT } val nonemptyPos = MarkdownParserUtil.getFirstNonWhitespaceLinePos(pos, eolN) ?: return MarkerBlock.ProcessingResult.DEFAULT val nextLineConstraints = MarkdownConstraints.fromBase(nonemptyPos, constraints) if (!nextLineConstraints.extendsPrev(constraints)) { return MarkerBlock.ProcessingResult.DEFAULT } return MarkerBlock.ProcessingResult.CANCEL } override fun getDefaultNodeType(): IElementType { return MarkdownElementTypes.LIST_ITEM } }
src/org/intellij/markdown/parser/markerblocks/impl/ListItemMarkerBlock.kt
1323588927
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package openxr import org.lwjgl.generator.* import openxr.XRFunctionType.* import java.io.* private val NativeClass.capName: String get() = if (templateName.startsWith(prefix)) { if (prefix == "XR") "OpenXR${templateName.substring(2)}" else templateName } else { "${prefixTemplate}_$templateName" } private enum class XRFunctionType { PROC, GLOBAL, INSTANCE } private val Func.type: XRFunctionType get() = when { name == "xrGetInstanceProcAddr" -> PROC // dlsym/GetProcAddress parameters[0].nativeType !is WrappedPointerType -> GLOBAL // xrGetInstanceProcAddr: XR_NULL_HANDLE else -> INSTANCE // xrGetDeviceProcAddr: instance handle } private val Func.isInstanceFunction get() = type === INSTANCE && !has<Macro>() private val EXTENSION_NAME = "[A-Za-z0-9_]+".toRegex() private fun getFunctionDependencyExpression(func: Func) = func.get<DependsOn>() .reference .let { expression -> if (EXTENSION_NAME.matches(expression)) "ext.contains(\"$expression\")" else expression } private fun PrintWriter.printCheckFunctions( nativeClass: NativeClass, commands: Map<String, Int>, dependencies: LinkedHashMap<String, Int>, filter: (Func) -> Boolean ) { print("checkFunctions(provider, caps, new int[] {") nativeClass.printPointers(this, { func -> val index = commands[func.name] if (func.has<DependsOn>()) { "flag${dependencies[getFunctionDependencyExpression(func)]} + $index" } else{ index.toString() } }, filter) print("},") nativeClass.printPointers(this, { "\"${it.name}\"" }, filter) print(")") } val XR_BINDING_INSTANCE = Generator.register(object : APIBinding(Module.OPENXR, "XRCapabilities", APICapabilities.PARAM_CAPABILITIES) { override fun shouldCheckFunctionAddress(function: Func): Boolean = function.nativeClass.templateName != "XR10" override fun generateFunctionAddress(writer: PrintWriter, function: Func) { writer.print("$t${t}long $FUNCTION_ADDRESS = ") writer.println(if (function.has<Capabilities>()) "${function.get<Capabilities>().expression}.${function.name};" else "${function.getParams { it.nativeType is WrappedPointerType }.first().name}.getCapabilities().${function.name};" ) } private fun PrintWriter.checkExtensionFunctions(nativeClass: NativeClass, commands: Map<String, Int>) { val capName = nativeClass.capName print(""" private static boolean check_${nativeClass.templateName}(FunctionProvider provider, long[] caps, java.util.Set<String> ext) { if (!ext.contains("$capName")) { return false; }""") val dependencies = nativeClass.functions .filter { it.isInstanceFunction && it.has<DependsOn>() } .map(::getFunctionDependencyExpression) .foldIndexed(LinkedHashMap<String, Int>()) { index, map, expression -> if (!map.containsKey(expression)) { map[expression] = index } map } if (dependencies.isNotEmpty()) { println() dependencies.forEach { (expression, index) -> print("\n$t${t}int flag$index = $expression ? 0 : Integer.MIN_VALUE;") } } print("\n\n$t${t}return ") printCheckFunctions(nativeClass, commands, dependencies) { it.isInstanceFunction } println(" || reportMissing(\"XR\", \"$capName\");") println("$t}") } init { javaImport("static org.lwjgl.system.Checks.*") documentation = "Defines the capabilities of an OpenXR {@code XrInstance}." } override fun PrintWriter.generateJava() { generateJavaPreamble() println("@SuppressWarnings(\"SimplifiableIfStatement\")") println("public class XRCapabilities {") val classes = super.getClasses("XR") val instanceCommands = LinkedHashMap<String, Int>() classes.asSequence() .filter { it.hasNativeFunctions } .forEach { val functions = it.functions.asSequence() .filter { cmd -> if (cmd.isInstanceFunction) { if (!instanceCommands.contains(cmd.name)) { instanceCommands[cmd.name] = instanceCommands.size return@filter true } } false } .joinToString(",\n$t$t") { cmd -> cmd.name } if (functions.isNotEmpty()) { println("\n$t// ${it.templateName}") println("${t}public final long") println("$t$t$functions;") } } println( """ /** The OpenXR API version number. */ public final long apiVersion; """ ) classes .forEach { println(it.getCapabilityJavadoc()) println("${t}public final boolean ${it.capName};") } print( """ XRCapabilities(FunctionProvider provider, long apiVersion, Set<String> ext) { this.apiVersion = apiVersion; long[] caps = new long[${instanceCommands.size}]; """ ) classes.forEach { val capName = it.capName if (it.functions.any { func -> func.isInstanceFunction }) { print("\n$t$t$capName = check_${it.templateName}(provider, caps, ext);") } else { print("\n$t$t$capName = ext.contains(\"$capName\");") } } println() instanceCommands.forEach { (it, index) -> print("\n$t$t$it = caps[$index];") } print( """ } """) for (extension in classes) { if (extension.functions.any { it.isInstanceFunction }) { checkExtensionFunctions(extension, instanceCommands) } } println("\n}") } }) // DSL Extensions val GlobalCommand = Capabilities("XR.getGlobalCommands()") fun String.nativeClassXR( templateName: String, type: String, prefix: String = "XR", prefixMethod: String = prefix.lowercase(), postfix: String = "", init: (NativeClass.() -> Unit)? = null ): NativeClass { check(type == "instance") return nativeClass( Module.OPENXR, templateName, prefix = prefix, prefixMethod = prefixMethod, postfix = postfix, binding = XR_BINDING_INSTANCE, init = init ) }
modules/lwjgl/openxr/src/templates/kotlin/openxr/XRBinding.kt
33732128
/* * 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 VK12 = "VK12".nativeClass(Module.VULKAN, "VK12", prefix = "VK", binding = VK_BINDING_INSTANCE) { extends = VK11 documentation = """ The core Vulkan 1.2 functionality. """ EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES".."49", "STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES".."50", "STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES".."51", "STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES".."52" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO".."1000147000" ) EnumConstant( "Extends {@code VkSamplerAddressMode}.", "SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE".."4" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2".."1000109000", "STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2".."1000109001", "STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2".."1000109002", "STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2".."1000109003", "STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2".."1000109004", "STRUCTURE_TYPE_SUBPASS_BEGIN_INFO".."1000109005", "STRUCTURE_TYPE_SUBPASS_END_INFO".."1000109006" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES".."1000177000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES".."1000196000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES".."1000180000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES".."1000082000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES".."1000197000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO".."1000161000", "STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES".."1000161001", "STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES".."1000161002", "STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO".."1000161003", "STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_LAYOUT_SUPPORT".."1000161004" ) EnumConstant( "Extends {@code VkDescriptorPoolCreateFlagBits}.", "DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT".enum(0x00000002) ) EnumConstant( "Extends {@code VkDescriptorSetLayoutCreateFlagBits}.", "DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT".enum(0x00000002) ) EnumConstant( "Extends {@code VkResult}.", "ERROR_FRAGMENTATION".."-1000161000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES".."1000199000", "STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE".."1000199001" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES".."1000221000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_IMAGE_STENCIL_USAGE_CREATE_INFO".."1000246000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES".."1000130000", "STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO".."1000130001" ) EnumConstant( "Extends {@code VkFormatFeatureFlagBits}.", "FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT".enum(0x00010000) ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES".."1000211000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGELESS_FRAMEBUFFER_FEATURES".."1000108000", "STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENTS_CREATE_INFO".."1000108001", "STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENT_IMAGE_INFO".."1000108002", "STRUCTURE_TYPE_RENDER_PASS_ATTACHMENT_BEGIN_INFO".."1000108003" ) EnumConstant( "Extends {@code VkFramebufferCreateFlagBits}.", "FRAMEBUFFER_CREATE_IMAGELESS_BIT".enum(0x00000001) ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES".."1000253000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_EXTENDED_TYPES_FEATURES".."1000175000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_SEPARATE_DEPTH_STENCIL_LAYOUTS_FEATURES".."1000241000", "STRUCTURE_TYPE_ATTACHMENT_REFERENCE_STENCIL_LAYOUT".."1000241001", "STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_STENCIL_LAYOUT".."1000241002" ) EnumConstant( "Extends {@code VkImageLayout}.", "IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL".."1000241000", "IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL".."1000241001", "IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL".."1000241002", "IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL".."1000241003" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES".."1000261000" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES".."1000207000", "STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_PROPERTIES".."1000207001", "STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO".."1000207002", "STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO".."1000207003", "STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO".."1000207004", "STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO".."1000207005" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES".."1000257000", "STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO".."1000244001", "STRUCTURE_TYPE_BUFFER_OPAQUE_CAPTURE_ADDRESS_CREATE_INFO".."1000257002", "STRUCTURE_TYPE_MEMORY_OPAQUE_CAPTURE_ADDRESS_ALLOCATE_INFO".."1000257003", "STRUCTURE_TYPE_DEVICE_MEMORY_OPAQUE_CAPTURE_ADDRESS_INFO".."1000257004" ) EnumConstant( "Extends {@code VkBufferUsageFlagBits}.", "BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT".enum(0x00020000) ) EnumConstant( "Extends {@code VkBufferCreateFlagBits}.", "BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT".enum(0x00000010) ) EnumConstant( "Extends {@code VkMemoryAllocateFlagBits}.", "MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT".enum(0x00000002), "MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT".enum(0x00000004) ) EnumConstant( "Extends {@code VkResult}.", "ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS".."-1000257000" ) EnumConstant( """ VkDriverId - Khronos driver IDs <h5>Description</h5> <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5> Khronos driver IDs may be allocated by vendors at any time. There may be multiple driver IDs for the same vendor, representing different drivers (for e.g. different platforms, proprietary or open source, etc.). Only the latest canonical versions of this Specification, of the corresponding {@code vk.xml} API Registry, and of the corresponding {@code vulkan_core.h} header file <b>must</b> contain all reserved Khronos driver IDs. Only driver IDs registered with Khronos are given symbolic names. There <b>may</b> be unregistered driver IDs returned. </div> <h5>See Also</h5> ##VkPhysicalDeviceDriverProperties, ##VkPhysicalDeviceVulkan12Properties """, "DRIVER_ID_AMD_PROPRIETARY".."1", "DRIVER_ID_AMD_OPEN_SOURCE".."2", "DRIVER_ID_MESA_RADV".."3", "DRIVER_ID_NVIDIA_PROPRIETARY".."4", "DRIVER_ID_INTEL_PROPRIETARY_WINDOWS".."5", "DRIVER_ID_INTEL_OPEN_SOURCE_MESA".."6", "DRIVER_ID_IMAGINATION_PROPRIETARY".."7", "DRIVER_ID_QUALCOMM_PROPRIETARY".."8", "DRIVER_ID_ARM_PROPRIETARY".."9", "DRIVER_ID_GOOGLE_SWIFTSHADER".."10", "DRIVER_ID_GGP_PROPRIETARY".."11", "DRIVER_ID_BROADCOM_PROPRIETARY".."12", "DRIVER_ID_MESA_LLVMPIPE".."13", "DRIVER_ID_MOLTENVK".."14", "DRIVER_ID_COREAVI_PROPRIETARY".."15", "DRIVER_ID_JUICE_PROPRIETARY".."16", "DRIVER_ID_VERISILICON_PROPRIETARY".."17", "DRIVER_ID_MESA_TURNIP".."18", "DRIVER_ID_MESA_V3DV".."19", "DRIVER_ID_MESA_PANVK".."20", "DRIVER_ID_SAMSUNG_PROPRIETARY".."21", "DRIVER_ID_MESA_VENUS".."22", "DRIVER_ID_MESA_DOZEN".."23" ) EnumConstant( """ VkShaderFloatControlsIndependence - Bitmask specifying whether, and how, shader float controls can be set separately <h5>Description</h5> <ul> <li>#SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY specifies that shader float controls for 32-bit floating point <b>can</b> be set independently; other bit widths <b>must</b> be set identically to each other.</li> <li>#SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL specifies that shader float controls for all bit widths <b>can</b> be set independently.</li> <li>#SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE specifies that shader float controls for all bit widths <b>must</b> be set identically.</li> </ul> <h5>See Also</h5> ##VkPhysicalDeviceFloatControlsProperties, ##VkPhysicalDeviceVulkan12Properties """, "SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY".."0", "SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL".."1", "SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE".."2" ) EnumConstant( """ VkResolveModeFlagBits - Bitmask indicating supported depth and stencil resolve modes <h5>Description</h5> <ul> <li>#RESOLVE_MODE_NONE indicates that no resolve operation is done.</li> <li>#RESOLVE_MODE_SAMPLE_ZERO_BIT indicates that result of the resolve operation is equal to the value of sample 0.</li> <li>#RESOLVE_MODE_AVERAGE_BIT indicates that result of the resolve operation is the average of the sample values.</li> <li>#RESOLVE_MODE_MIN_BIT indicates that result of the resolve operation is the minimum of the sample values.</li> <li>#RESOLVE_MODE_MAX_BIT indicates that result of the resolve operation is the maximum of the sample values.</li> </ul> <h5>See Also</h5> ##VkRenderingAttachmentInfo, ##VkSubpassDescriptionDepthStencilResolve """, "RESOLVE_MODE_NONE".."0", "RESOLVE_MODE_SAMPLE_ZERO_BIT".enum(0x00000001), "RESOLVE_MODE_AVERAGE_BIT".enum(0x00000002), "RESOLVE_MODE_MIN_BIT".enum(0x00000004), "RESOLVE_MODE_MAX_BIT".enum(0x00000008) ) EnumConstant( """ VkDescriptorBindingFlagBits - Bitmask specifying descriptor set layout binding properties <h5>Description</h5> <ul> <li>#DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT indicates that if descriptors in this binding are updated between when the descriptor set is bound in a command buffer and when that command buffer is submitted to a queue, then the submission will use the most recently set descriptors for this binding and the updates do not invalidate the command buffer. Descriptor bindings created with this flag are also partially exempt from the external synchronization requirement in #UpdateDescriptorSetWithTemplateKHR() and #UpdateDescriptorSets(). Multiple descriptors with this flag set <b>can</b> be updated concurrently in different threads, though the same descriptor <b>must</b> not be updated concurrently by two threads. Descriptors with this flag set <b>can</b> be updated concurrently with the set being bound to a command buffer in another thread, but not concurrently with the set being reset or freed.</li> <li>#DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT indicates that descriptors in this binding that are not <em>dynamically used</em> need not contain valid descriptors at the time the descriptors are consumed. A descriptor is dynamically used if any shader invocation executes an instruction that performs any memory access using the descriptor. If a descriptor is not dynamically used, any resource referenced by the descriptor is not considered to be referenced during command execution.</li> <li>#DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT indicates that descriptors in this binding <b>can</b> be updated after a command buffer has bound this descriptor set, or while a command buffer that uses this descriptor set is pending execution, as long as the descriptors that are updated are not used by those command buffers. If #DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT is also set, then descriptors <b>can</b> be updated as long as they are not dynamically used by any shader invocations. If #DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT is not set, then descriptors <b>can</b> be updated as long as they are not statically used by any shader invocations.</li> <li>#DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT indicates that this is a <em>variable-sized descriptor binding</em> whose size will be specified when a descriptor set is allocated using this layout. The value of {@code descriptorCount} is treated as an upper bound on the size of the binding. This <b>must</b> only be used for the last binding in the descriptor set layout (i.e. the binding with the largest value of {@code binding}). For the purposes of counting against limits such as {@code maxDescriptorSet}* and {@code maxPerStageDescriptor}*, the full value of {@code descriptorCount} is counted, except for descriptor bindings with a descriptor type of #DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK. In this case, {@code descriptorCount} specifies the upper bound on the byte size of the binding; thus it counts against the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-maxInlineUniformBlockSize">{@code maxInlineUniformBlockSize}</a> and <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#limits-maxInlineUniformTotalSize">{@code maxInlineUniformTotalSize}</a> limits instead.</li> </ul> <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5> Note that while #DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT and #DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT both involve updates to descriptor sets after they are bound, #DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT is a weaker requirement since it is only about descriptors that are not used, whereas #DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT requires the implementation to observe updates to descriptors that are used. </div> """, "DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT".enum(0x00000001), "DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT".enum(0x00000002), "DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT".enum(0x00000004), "DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT".enum(0x00000008) ) EnumConstant( """ VkSamplerReductionMode - Specify reduction mode for texture filtering <h5>Description</h5> <ul> <li>#SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE specifies that texel values are combined by computing a weighted average of values in the footprint, using weights as specified in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-unnormalized-to-integer">the image operations chapter</a>.</li> <li>#SAMPLER_REDUCTION_MODE_MIN specifies that texel values are combined by taking the component-wise minimum of values in the footprint with non-zero weights.</li> <li>#SAMPLER_REDUCTION_MODE_MAX specifies that texel values are combined by taking the component-wise maximum of values in the footprint with non-zero weights.</li> </ul> <h5>See Also</h5> ##VkSamplerReductionModeCreateInfo """, "SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE".."0", "SAMPLER_REDUCTION_MODE_MIN".."1", "SAMPLER_REDUCTION_MODE_MAX".."2" ) EnumConstant( """ VkSemaphoreType - Sepcifies the type of a semaphore object <h5>Description</h5> <ul> <li>#SEMAPHORE_TYPE_BINARY specifies a <em>binary semaphore</em> type that has a boolean payload indicating whether the semaphore is currently signaled or unsignaled. When created, the semaphore is in the unsignaled state.</li> <li>#SEMAPHORE_TYPE_TIMELINE specifies a <em>timeline semaphore</em> type that has a strictly increasing 64-bit unsigned integer payload indicating whether the semaphore is signaled with respect to a particular reference value. When created, the semaphore payload has the value given by the {@code initialValue} field of ##VkSemaphoreTypeCreateInfo.</li> </ul> <h5>See Also</h5> ##VkSemaphoreTypeCreateInfo """, "SEMAPHORE_TYPE_BINARY".."0", "SEMAPHORE_TYPE_TIMELINE".."1" ) EnumConstant( """ VkSemaphoreWaitFlagBits - Bitmask specifying additional parameters of a semaphore wait operation <h5>Description</h5> <ul> <li>#SEMAPHORE_WAIT_ANY_BIT specifies that the semaphore wait condition is that at least one of the semaphores in ##VkSemaphoreWaitInfo{@code ::pSemaphores} has reached the value specified by the corresponding element of ##VkSemaphoreWaitInfo{@code ::pValues}. If #SEMAPHORE_WAIT_ANY_BIT is not set, the semaphore wait condition is that all of the semaphores in ##VkSemaphoreWaitInfo{@code ::pSemaphores} have reached the value specified by the corresponding element of ##VkSemaphoreWaitInfo{@code ::pValues}.</li> </ul> """, "SEMAPHORE_WAIT_ANY_BIT".enum(0x00000001) ) // Promoted from VK_KHR_draw_indirect_count (extension 170) void( "CmdDrawIndirectCount", """ Draw primitives with indirect parameters and draw count. <h5>C Specification</h5> To record a non-indexed draw call with a draw call count sourced from a buffer, call: <pre><code> ￿void vkCmdDrawIndirectCount( ￿ VkCommandBuffer commandBuffer, ￿ VkBuffer buffer, ￿ VkDeviceSize offset, ￿ VkBuffer countBuffer, ￿ VkDeviceSize countBufferOffset, ￿ uint32_t maxDrawCount, ￿ uint32_t stride);</code></pre> or the equivalent command <pre><code> ￿void vkCmdDrawIndirectCountKHR( ￿ VkCommandBuffer commandBuffer, ￿ VkBuffer buffer, ￿ VkDeviceSize offset, ￿ VkBuffer countBuffer, ￿ VkDeviceSize countBufferOffset, ￿ uint32_t maxDrawCount, ￿ uint32_t stride);</code></pre> or the equivalent command <pre><code> ￿void vkCmdDrawIndirectCountAMD( ￿ VkCommandBuffer commandBuffer, ￿ VkBuffer buffer, ￿ VkDeviceSize offset, ￿ VkBuffer countBuffer, ￿ VkDeviceSize countBufferOffset, ￿ uint32_t maxDrawCount, ￿ uint32_t stride);</code></pre> <h5>Description</h5> {@code vkCmdDrawIndirectCount} behaves similarly to #CmdDrawIndirect() 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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-depth-compare-operation">depth comparison</a>, the image view’s <a target="_blank" href="https://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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>Any {@code VkImageView} or {@code VkBufferView} being written as a storage image or storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} then the view’s format feature <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT</li> <li>Any {@code VkImageView} or {@code VkBufferView} being read as a storage image or storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} then the view’s format feature <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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li> <li>If the <a target="_blank" href="https://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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>The current render pass <b>must</b> be <a target="_blank" href="https://www.khronos.org/registry/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>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://www.khronos.org/registry/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://www.khronos.org/registry/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 {@code VkPipelineVieportCreateInfo}, 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 {@code VkPipelineVieportCreateInfo}, 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://www.khronos.org/registry/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://www.khronos.org/registry/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 neither the {@link AMDMixedAttachmentSamples VK_AMD_mixed_attachment_samples} nor the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extensions 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 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 ##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 ##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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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> </ul> <ul> <li>All vertex input bindings accessed via vertex input variables declared in the vertex shader entry point’s interface <b>must</b> have either valid or #NULL_HANDLE buffers bound</li> <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-nullDescriptor">{@code nullDescriptor}</a> feature is not enabled, all vertex input bindings accessed via vertex input variables declared in the vertex shader entry point’s interface <b>must</b> not be #NULL_HANDLE</li> <li>For a given vertex buffer binding, any attribute data fetched <b>must</b> be entirely contained within the corresponding vertex buffer binding, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#fxvertex-input">Vertex Input Description</a></li> <li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT dynamic state enabled then #CmdSetPrimitiveTopologyEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code primitiveTopology} parameter of {@code vkCmdSetPrimitiveTopologyEXT} <b>must</b> be of the same <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#drawing-primitive-topology-class">topology class</a> as the pipeline ##VkPipelineInputAssemblyStateCreateInfo{@code ::topology} state</li> <li>If the bound graphics pipeline was created with both the #DYNAMIC_STATE_VERTEX_INPUT_EXT and #DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT dynamic states enabled, then #CmdSetVertexInputEXT() <b>must</b> have been called in the current command buffer prior to this draw command</li> <li>If the bound graphics pipeline was created with the #DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT dynamic state enabled, but not the #DYNAMIC_STATE_VERTEX_INPUT_EXT dynamic state enabled, then #CmdBindVertexBuffers2EXT() <b>must</b> have been called in the current command buffer prior to this draw command, and the {@code pStrides} parameter of #CmdBindVertexBuffers2EXT() <b>must</b> not be {@code NULL}</li> <li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VERTEX_INPUT_EXT dynamic state enabled, then #CmdSetVertexInputEXT() <b>must</b> have been called in the current command buffer prior to this draw command</li> <li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT dynamic state enabled then #CmdSetPatchControlPointsEXT() <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_PRIMITIVE_RESTART_ENABLE_EXT dynamic state enabled then #CmdSetPrimitiveRestartEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command</li> <li>The bound graphics pipeline <b>must</b> not have been created with the ##VkPipelineShaderStageCreateInfo{@code ::stage} member of an element of ##VkGraphicsPipelineCreateInfo{@code ::pStages} set to #SHADER_STAGE_TASK_BIT_NV or #SHADER_STAGE_MESH_BIT_NV</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://www.khronos.org/registry/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 sizeof(##VkDrawIndirectCommand)</li> <li>If {@code maxDrawCount} is greater than or equal to 1, <code>(stride × (maxDrawCount - 1) + offset + sizeof(##VkDrawIndirectCommand))</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(##VkDrawIndirectCommand))</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(##VkDrawIndirectCommand))</code> <b>must</b> be less than or equal to the size of {@code buffer}</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://www.khronos.org/registry/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>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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkQueueFlagBits">Supported Queue Types</a></th></tr></thead> <tbody><tr><td>Primary Secondary</td><td>Inside</td><td>Graphics</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.") ) void( "CmdDrawIndexedIndirectCount", """ Draw parameters with indirect parameters, indexed vertices, and draw count. <h5>C Specification</h5> To record an indexed draw call with a draw call count sourced from a buffer, call: <pre><code> ￿void vkCmdDrawIndexedIndirectCount( ￿ VkCommandBuffer commandBuffer, ￿ VkBuffer buffer, ￿ VkDeviceSize offset, ￿ VkBuffer countBuffer, ￿ VkDeviceSize countBufferOffset, ￿ uint32_t maxDrawCount, ￿ uint32_t stride);</code></pre> or the equivalent command <pre><code> ￿void vkCmdDrawIndexedIndirectCountKHR( ￿ VkCommandBuffer commandBuffer, ￿ VkBuffer buffer, ￿ VkDeviceSize offset, ￿ VkBuffer countBuffer, ￿ VkDeviceSize countBufferOffset, ￿ uint32_t maxDrawCount, ￿ uint32_t stride);</code></pre> or the equivalent command <pre><code> ￿void vkCmdDrawIndexedIndirectCountAMD( ￿ VkCommandBuffer commandBuffer, ￿ VkBuffer buffer, ￿ VkDeviceSize offset, ￿ VkBuffer countBuffer, ￿ VkDeviceSize countBufferOffset, ￿ uint32_t maxDrawCount, ￿ uint32_t stride);</code></pre> <h5>Description</h5> {@code vkCmdDrawIndexedIndirectCount} behaves similarly to #CmdDrawIndexedIndirect() 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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-depth-compare-operation">depth comparison</a>, the image view’s <a target="_blank" href="https://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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>Any {@code VkImageView} or {@code VkBufferView} being written as a storage image or storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} then the view’s format feature <b>must</b> contain #FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT</li> <li>Any {@code VkImageView} or {@code VkBufferView} being read as a storage image or storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} then the view’s format feature <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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li> <li>If the <a target="_blank" href="https://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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>The current render pass <b>must</b> be <a target="_blank" href="https://www.khronos.org/registry/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>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://www.khronos.org/registry/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://www.khronos.org/registry/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 {@code VkPipelineVieportCreateInfo}, 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 {@code VkPipelineVieportCreateInfo}, 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://www.khronos.org/registry/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://www.khronos.org/registry/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 neither the {@link AMDMixedAttachmentSamples VK_AMD_mixed_attachment_samples} nor the {@link NVFramebufferMixedSamples VK_NV_framebuffer_mixed_samples} extensions 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 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 ##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 ##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://www.khronos.org/registry/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://www.khronos.org/registry/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://www.khronos.org/registry/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> </ul> <ul> <li>All vertex input bindings accessed via vertex input variables declared in the vertex shader entry point’s interface <b>must</b> have either valid or #NULL_HANDLE buffers bound</li> <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-nullDescriptor">{@code nullDescriptor}</a> feature is not enabled, all vertex input bindings accessed via vertex input variables declared in the vertex shader entry point’s interface <b>must</b> not be #NULL_HANDLE</li> <li>For a given vertex buffer binding, any attribute data fetched <b>must</b> be entirely contained within the corresponding vertex buffer binding, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#fxvertex-input">Vertex Input Description</a></li> <li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT dynamic state enabled then #CmdSetPrimitiveTopologyEXT() <b>must</b> have been called in the current command buffer prior to this drawing command, and the {@code primitiveTopology} parameter of {@code vkCmdSetPrimitiveTopologyEXT} <b>must</b> be of the same <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#drawing-primitive-topology-class">topology class</a> as the pipeline ##VkPipelineInputAssemblyStateCreateInfo{@code ::topology} state</li> <li>If the bound graphics pipeline was created with both the #DYNAMIC_STATE_VERTEX_INPUT_EXT and #DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT dynamic states enabled, then #CmdSetVertexInputEXT() <b>must</b> have been called in the current command buffer prior to this draw command</li> <li>If the bound graphics pipeline was created with the #DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT dynamic state enabled, but not the #DYNAMIC_STATE_VERTEX_INPUT_EXT dynamic state enabled, then #CmdBindVertexBuffers2EXT() <b>must</b> have been called in the current command buffer prior to this draw command, and the {@code pStrides} parameter of #CmdBindVertexBuffers2EXT() <b>must</b> not be {@code NULL}</li> <li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_VERTEX_INPUT_EXT dynamic state enabled, then #CmdSetVertexInputEXT() <b>must</b> have been called in the current command buffer prior to this draw command</li> <li>If the bound graphics pipeline state was created with the #DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT dynamic state enabled then #CmdSetPatchControlPointsEXT() <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_PRIMITIVE_RESTART_ENABLE_EXT dynamic state enabled then #CmdSetPrimitiveRestartEnableEXT() <b>must</b> have been called in the current command buffer prior to this drawing command</li> <li>The bound graphics pipeline <b>must</b> not have been created with the ##VkPipelineShaderStageCreateInfo{@code ::stage} member of an element of ##VkGraphicsPipelineCreateInfo{@code ::pStages} set to #SHADER_STAGE_TASK_BIT_NV or #SHADER_STAGE_MESH_BIT_NV</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://www.khronos.org/registry/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 sizeof(##VkDrawIndexedIndirectCommand)</li> <li>If {@code maxDrawCount} is greater than or equal to 1, <code>(stride × (maxDrawCount - 1) + offset + sizeof(##VkDrawIndexedIndirectCommand))</code> <b>must</b> be less than or equal to the size of {@code buffer}</li> <li>If count stored in {@code countBuffer} is equal to 1, <code>(offset + sizeof(##VkDrawIndexedIndirectCommand))</code> <b>must</b> be less than or equal to the size of {@code buffer}</li> <li>If count stored in {@code countBuffer} is greater than 1, <code>(stride × (drawCount - 1) + offset + sizeof(##VkDrawIndexedIndirectCommand))</code> <b>must</b> be less than or equal to the size of {@code buffer}</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://www.khronos.org/registry/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>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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkQueueFlagBits">Supported Queue Types</a></th></tr></thead> <tbody><tr><td>Primary Secondary</td><td>Inside</td><td>Graphics</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.") ) // Promoted from VK_KHR_create_renderpass2 (extension 110) VkResult( "CreateRenderPass2", """ Create a new render pass object. <h5>C Specification</h5> To create a render pass, call: <pre><code> ￿VkResult vkCreateRenderPass2( ￿ VkDevice device, ￿ const VkRenderPassCreateInfo2* pCreateInfo, ￿ const VkAllocationCallbacks* pAllocator, ￿ VkRenderPass* pRenderPass);</code></pre> or the equivalent command <pre><code> ￿VkResult vkCreateRenderPass2KHR( ￿ VkDevice device, ￿ const VkRenderPassCreateInfo2* pCreateInfo, ￿ const VkAllocationCallbacks* pAllocator, ￿ VkRenderPass* pRenderPass);</code></pre> <h5>Description</h5> This command is functionally identical to #CreateRenderPass(), but includes extensible sub-structures that include {@code sType} and {@code pNext} parameters, allowing them to be more easily extended. <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid ##VkRenderPassCreateInfo2 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 pRenderPass} <b>must</b> be a valid pointer to a {@code VkRenderPass} 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, ##VkRenderPassCreateInfo2 """, VkDevice("device", "the logical device that creates the render pass."), VkRenderPassCreateInfo2.const.p("pCreateInfo", "a pointer to a ##VkRenderPassCreateInfo2 structure describing the parameters of the render pass."), nullable..VkAllocationCallbacks.const.p("pAllocator", "controls host memory allocation as described in the <a target=\"_blank\" href=\"https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\\#memory-allocation\">Memory Allocation</a> chapter."), Check(1)..VkRenderPass.p("pRenderPass", "a pointer to a {@code VkRenderPass} handle in which the resulting render pass object is returned.") ) void( "CmdBeginRenderPass2", """ Begin a new render pass. <h5>C Specification</h5> Alternatively to begin a render pass, call: <pre><code> ￿void vkCmdBeginRenderPass2( ￿ VkCommandBuffer commandBuffer, ￿ const VkRenderPassBeginInfo* pRenderPassBegin, ￿ const VkSubpassBeginInfo* pSubpassBeginInfo);</code></pre> or the equivalent command <pre><code> ￿void vkCmdBeginRenderPass2KHR( ￿ VkCommandBuffer commandBuffer, ￿ const VkRenderPassBeginInfo* pRenderPassBegin, ￿ const VkSubpassBeginInfo* pSubpassBeginInfo);</code></pre> <h5>Description</h5> After beginning a render pass instance, the command buffer is ready to record the commands for the first subpass of that render pass. <h5>Valid Usage</h5> <ul> <li>Both the {@code framebuffer} and {@code renderPass} members of {@code pRenderPassBegin} <b>must</b> have been created on the same {@code VkDevice} that {@code commandBuffer} was allocated on</li> <li>If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL then the corresponding attachment image view of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} <b>must</b> have been created with a {@code usage} value including #IMAGE_USAGE_COLOR_ATTACHMENT_BIT</li> <li>If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, #IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, #IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, or #IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL then the corresponding attachment image view of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} <b>must</b> have been created with a {@code usage} value including #IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT</li> <li>If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, or #IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, #IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL, or #IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL then the corresponding attachment image view of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} <b>must</b> have been created with a {@code usage} value including #IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT</li> <li>If any of the {@code stencilInitialLayout} or {@code stencilFinalLayout} member of the ##VkAttachmentDescriptionStencilLayout structures or the {@code stencilLayout} member of the ##VkAttachmentReferenceStencilLayout structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL, or #IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL then the corresponding attachment image view of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} <b>must</b> have been created with a {@code usage} value including #IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT</li> <li>If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL then the corresponding attachment image view of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} <b>must</b> have been created with a {@code usage} value including #IMAGE_USAGE_SAMPLED_BIT or #IMAGE_USAGE_INPUT_ATTACHMENT_BIT</li> <li>If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL then the corresponding attachment image view of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} <b>must</b> have been created with a {@code usage} value including #IMAGE_USAGE_TRANSFER_SRC_BIT</li> <li>If any of the {@code initialLayout} or {@code finalLayout} member of the ##VkAttachmentDescription structures or the {@code layout} member of the ##VkAttachmentReference structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is #IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL then the corresponding attachment image view of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin} <b>must</b> have been created with a {@code usage} value including #IMAGE_USAGE_TRANSFER_DST_BIT</li> <li>If the {@code initialLayout} member of any of the ##VkAttachmentDescription structures specified when creating the render pass specified in the {@code renderPass} member of {@code pRenderPassBegin} is not #IMAGE_LAYOUT_UNDEFINED, then each such {@code initialLayout} <b>must</b> be equal to the current layout of the corresponding attachment image subresource of the framebuffer specified in the {@code framebuffer} member of {@code pRenderPassBegin}</li> <li>The {@code srcStageMask} members of any element of the {@code pDependencies} member of ##VkRenderPassCreateInfo used to create {@code renderPass} <b>must</b> be supported by the capabilities of the queue family identified by the {@code queueFamilyIndex} member of the ##VkCommandPoolCreateInfo used to create the command pool which {@code commandBuffer} was allocated from</li> <li>The {@code dstStageMask} members of any element of the {@code pDependencies} member of ##VkRenderPassCreateInfo used to create {@code renderPass} <b>must</b> be supported by the capabilities of the queue family identified by the {@code queueFamilyIndex} member of the ##VkCommandPoolCreateInfo used to create the command pool which {@code commandBuffer} was allocated from</li> <li>For any attachment in {@code framebuffer} that is used by {@code renderPass} and is bound to memory locations that are also bound to another attachment used by {@code renderPass}, and if at least one of those uses causes either attachment to be written to, both attachments <b>must</b> have had the #ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT set</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li> <li>{@code pRenderPassBegin} <b>must</b> be a valid pointer to a valid ##VkRenderPassBeginInfo structure</li> <li>{@code pSubpassBeginInfo} <b>must</b> be a valid pointer to a valid ##VkSubpassBeginInfo structure</li> <li>{@code commandBuffer} <b>must</b> be in the <a target="_blank" href="https://www.khronos.org/registry/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 outside of a render pass instance</li> <li>{@code commandBuffer} <b>must</b> be a primary {@code VkCommandBuffer}</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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkQueueFlagBits">Supported Queue Types</a></th></tr></thead> <tbody><tr><td>Primary</td><td>Outside</td><td>Graphics</td></tr></tbody> </table> <h5>See Also</h5> ##VkRenderPassBeginInfo, ##VkSubpassBeginInfo """, VkCommandBuffer("commandBuffer", "the command buffer in which to record the command."), VkRenderPassBeginInfo.const.p("pRenderPassBegin", "a pointer to a ##VkRenderPassBeginInfo structure specifying the render pass to begin an instance of, and the framebuffer the instance uses."), VkSubpassBeginInfo.const.p("pSubpassBeginInfo", "a pointer to a ##VkSubpassBeginInfo structure containing information about the subpass which is about to begin rendering.") ) void( "CmdNextSubpass2", """ Transition to the next subpass of a render pass. <h5>C Specification</h5> To transition to the next subpass in the render pass instance after recording the commands for a subpass, call: <pre><code> ￿void vkCmdNextSubpass2( ￿ VkCommandBuffer commandBuffer, ￿ const VkSubpassBeginInfo* pSubpassBeginInfo, ￿ const VkSubpassEndInfo* pSubpassEndInfo);</code></pre> or the equivalent command <pre><code> ￿void vkCmdNextSubpass2KHR( ￿ VkCommandBuffer commandBuffer, ￿ const VkSubpassBeginInfo* pSubpassBeginInfo, ￿ const VkSubpassEndInfo* pSubpassEndInfo);</code></pre> <h5>Description</h5> {@code vkCmdNextSubpass2} is semantically identical to #CmdNextSubpass(), except that it is extensible, and that {@code contents} is provided as part of an extensible structure instead of as a flat parameter. <h5>Valid Usage</h5> <ul> <li>The current subpass index <b>must</b> be less than the number of subpasses in the render pass minus one</li> <li>This command <b>must</b> not be recorded when transform feedback is active</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li> <li>{@code pSubpassBeginInfo} <b>must</b> be a valid pointer to a valid ##VkSubpassBeginInfo structure</li> <li>{@code pSubpassEndInfo} <b>must</b> be a valid pointer to a valid ##VkSubpassEndInfo structure</li> <li>{@code commandBuffer} <b>must</b> be in the <a target="_blank" href="https://www.khronos.org/registry/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>{@code commandBuffer} <b>must</b> be a primary {@code VkCommandBuffer}</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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkQueueFlagBits">Supported Queue Types</a></th></tr></thead> <tbody><tr><td>Primary</td><td>Inside</td><td>Graphics</td></tr></tbody> </table> <h5>See Also</h5> ##VkSubpassBeginInfo, ##VkSubpassEndInfo """, VkCommandBuffer("commandBuffer", "the command buffer in which to record the command."), VkSubpassBeginInfo.const.p("pSubpassBeginInfo", "a pointer to a ##VkSubpassBeginInfo structure containing information about the subpass which is about to begin rendering."), VkSubpassEndInfo.const.p("pSubpassEndInfo", "a pointer to a ##VkSubpassEndInfo structure containing information about how the previous subpass will be ended.") ) void( "CmdEndRenderPass2", """ End the current render pass. <h5>C Specification</h5> To record a command to end a render pass instance after recording the commands for the last subpass, call: <pre><code> ￿void vkCmdEndRenderPass2( ￿ VkCommandBuffer commandBuffer, ￿ const VkSubpassEndInfo* pSubpassEndInfo);</code></pre> or the equivalent command <pre><code> ￿void vkCmdEndRenderPass2KHR( ￿ VkCommandBuffer commandBuffer, ￿ const VkSubpassEndInfo* pSubpassEndInfo);</code></pre> <h5>Description</h5> {@code vkCmdEndRenderPass2} is semantically identical to #CmdEndRenderPass(), except that it is extensible. <h5>Valid Usage</h5> <ul> <li>The current subpass index <b>must</b> be equal to the number of subpasses in the render pass minus one</li> <li>This command <b>must</b> not be recorded when transform feedback is active</li> <li>The current render pass instance <b>must</b> not have been begun with #CmdBeginRendering()</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li> <li>{@code pSubpassEndInfo} <b>must</b> be a valid pointer to a valid ##VkSubpassEndInfo structure</li> <li>{@code commandBuffer} <b>must</b> be in the <a target="_blank" href="https://www.khronos.org/registry/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>{@code commandBuffer} <b>must</b> be a primary {@code VkCommandBuffer}</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://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#VkQueueFlagBits">Supported Queue Types</a></th></tr></thead> <tbody><tr><td>Primary</td><td>Inside</td><td>Graphics</td></tr></tbody> </table> <h5>See Also</h5> ##VkSubpassEndInfo """, VkCommandBuffer("commandBuffer", "the command buffer in which to end the current render pass instance."), VkSubpassEndInfo.const.p("pSubpassEndInfo", "a pointer to a ##VkSubpassEndInfo structure containing information about how the previous subpass will be ended.") ) // Promoted from VK_EXT_host_query_reset (extension 262) void( "ResetQueryPool", """ Reset queries in a query pool. <h5>C Specification</h5> To reset a range of queries in a query pool on the host, call: <pre><code> ￿void vkResetQueryPool( ￿ VkDevice device, ￿ VkQueryPool queryPool, ￿ uint32_t firstQuery, ￿ uint32_t queryCount);</code></pre> or the equivalent command <pre><code> ￿void vkResetQueryPoolEXT( ￿ VkDevice device, ￿ VkQueryPool queryPool, ￿ uint32_t firstQuery, ￿ uint32_t queryCount);</code></pre> <h5>Description</h5> This command sets the status of query indices <code>[firstQuery, firstQuery + queryCount - 1]</code> to unavailable. If {@code queryPool} is #QUERY_TYPE_PERFORMANCE_QUERY_KHR this command sets the status of query indices <code>[firstQuery, firstQuery + queryCount - 1]</code> to unavailable for each pass. <h5>Valid Usage</h5> <ul> <li>The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-hostQueryReset">{@code hostQueryReset}</a> feature <b>must</b> be enabled</li> <li>{@code firstQuery} <b>must</b> be less than the number of queries in {@code queryPool}</li> <li>The sum of {@code firstQuery} and {@code queryCount} <b>must</b> be less than or equal to the number of queries in {@code queryPool}</li> <li>Submitted commands that refer to the range specified by {@code firstQuery} and {@code queryCount} in {@code queryPool} <b>must</b> have completed execution</li> <li>The range of queries specified by {@code firstQuery} and {@code queryCount} in {@code queryPool} <b>must</b> not be in use by calls to #GetQueryPoolResults() or {@code vkResetQueryPool} in other threads</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code queryPool} <b>must</b> be a valid {@code VkQueryPool} handle</li> <li>{@code queryPool} <b>must</b> have been created, allocated, or retrieved from {@code device}</li> </ul> """, VkDevice("device", "the logical device that owns the query pool."), VkQueryPool("queryPool", "the handle of the query pool managing the queries being reset."), uint32_t("firstQuery", "the initial query index to reset."), uint32_t("queryCount", "the number of queries to reset.") ) // Promoted from VK_KHR_timeline_semaphore (extension 208) VkResult( "GetSemaphoreCounterValue", """ Query the current state of a timeline semaphore. <h5>C Specification</h5> To query the current counter value of a semaphore created with a {@code VkSemaphoreType} of #SEMAPHORE_TYPE_TIMELINE from the host, call: <pre><code> ￿VkResult vkGetSemaphoreCounterValue( ￿ VkDevice device, ￿ VkSemaphore semaphore, ￿ uint64_t* pValue);</code></pre> or the equivalent command <pre><code> ￿VkResult vkGetSemaphoreCounterValueKHR( ￿ VkDevice device, ￿ VkSemaphore semaphore, ￿ uint64_t* pValue);</code></pre> <h5>Description</h5> <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5> If a <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#devsandqueues-submission">queue submission</a> command is pending execution, then the value returned by this command <b>may</b> immediately be out of date. </div> <h5>Valid Usage</h5> <ul> <li>{@code semaphore} <b>must</b> have been created with a {@code VkSemaphoreType} of #SEMAPHORE_TYPE_TIMELINE</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code semaphore} <b>must</b> be a valid {@code VkSemaphore} handle</li> <li>{@code pValue} <b>must</b> be a valid pointer to a {@code uint64_t} value</li> <li>{@code semaphore} <b>must</b> have been created, allocated, or retrieved from {@code device}</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> <li>#ERROR_DEVICE_LOST</li> </ul></dd> </dl> """, VkDevice("device", "the logical device that owns the semaphore."), VkSemaphore("semaphore", "the handle of the semaphore to query."), Check(1)..uint64_t.p("pValue", "a pointer to a 64-bit integer value in which the current counter value of the semaphore is returned.") ) VkResult( "WaitSemaphores", """ Wait for timeline semaphores on the host. <h5>C Specification</h5> To wait for a set of semaphores created with a {@code VkSemaphoreType} of #SEMAPHORE_TYPE_TIMELINE to reach particular counter values on the host, call: <pre><code> ￿VkResult vkWaitSemaphores( ￿ VkDevice device, ￿ const VkSemaphoreWaitInfo* pWaitInfo, ￿ uint64_t timeout);</code></pre> or the equivalent command <pre><code> ￿VkResult vkWaitSemaphoresKHR( ￿ VkDevice device, ￿ const VkSemaphoreWaitInfo* pWaitInfo, ￿ uint64_t timeout);</code></pre> <h5>Description</h5> If the condition is satisfied when {@code vkWaitSemaphores} is called, then {@code vkWaitSemaphores} returns immediately. If the condition is not satisfied at the time {@code vkWaitSemaphores} is called, then {@code vkWaitSemaphores} will block and wait until the condition is satisfied or the {@code timeout} has expired, whichever is sooner. If {@code timeout} is zero, then {@code vkWaitSemaphores} does not wait, but simply returns information about the current state of the semaphores. #TIMEOUT will be returned in this case if the condition is not satisfied, even though no actual wait was performed. If the condition is satisfied before the {@code timeout} has expired, {@code vkWaitSemaphores} returns #SUCCESS. Otherwise, {@code vkWaitSemaphores} returns #TIMEOUT after the {@code timeout} has expired. If device loss occurs (see <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#devsandqueues-lost-device">Lost Device</a>) before the timeout has expired, {@code vkWaitSemaphores} <b>must</b> return in finite time with either #SUCCESS or #ERROR_DEVICE_LOST. <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code pWaitInfo} <b>must</b> be a valid pointer to a valid ##VkSemaphoreWaitInfo structure</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> <li>#TIMEOUT</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> <li>#ERROR_DEVICE_LOST</li> </ul></dd> </dl> <h5>See Also</h5> ##VkSemaphoreWaitInfo """, VkDevice("device", "the logical device that owns the semaphores."), VkSemaphoreWaitInfo.const.p("pWaitInfo", "a pointer to a ##VkSemaphoreWaitInfo structure containing information about the wait condition."), uint64_t("timeout", "the timeout period in units of nanoseconds. {@code timeout} is adjusted to the closest value allowed by the implementation-dependent timeout accuracy, which <b>may</b> be substantially longer than one nanosecond, and <b>may</b> be longer than the requested period.") ) VkResult( "SignalSemaphore", """ Signal a timeline semaphore on the host. <h5>C Specification</h5> To signal a semaphore created with a {@code VkSemaphoreType} of #SEMAPHORE_TYPE_TIMELINE with a particular counter value, on the host, call: <pre><code> ￿VkResult vkSignalSemaphore( ￿ VkDevice device, ￿ const VkSemaphoreSignalInfo* pSignalInfo);</code></pre> or the equivalent command <pre><code> ￿VkResult vkSignalSemaphoreKHR( ￿ VkDevice device, ￿ const VkSemaphoreSignalInfo* pSignalInfo);</code></pre> <h5>Description</h5> When {@code vkSignalSemaphore} is executed on the host, it defines and immediately executes a <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#synchronization-semaphores-signaling"><em>semaphore signal operation</em></a> which sets the timeline semaphore to the given value. The first synchronization scope is defined by the host execution model, but includes execution of {@code vkSignalSemaphore} on the host and anything that happened-before it. The second synchronization scope is empty. <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code pSignalInfo} <b>must</b> be a valid pointer to a valid ##VkSemaphoreSignalInfo structure</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> ##VkSemaphoreSignalInfo """, VkDevice("device", "the logical device that owns the semaphore."), VkSemaphoreSignalInfo.const.p("pSignalInfo", "a pointer to a ##VkSemaphoreSignalInfo structure containing information about the signal operation.") ) // Promoted from VK_KHR_buffer_device_address (extension 258) VkDeviceAddress( "GetBufferDeviceAddress", """ Query an address of a buffer. <h5>C Specification</h5> To query a 64-bit buffer device address value through which buffer memory <b>can</b> be accessed in a shader, call: <pre><code> ￿VkDeviceAddress vkGetBufferDeviceAddress( ￿ VkDevice device, ￿ const VkBufferDeviceAddressInfo* pInfo);</code></pre> or the equivalent command <pre><code> ￿VkDeviceAddress vkGetBufferDeviceAddressKHR( ￿ VkDevice device, ￿ const VkBufferDeviceAddressInfo* pInfo);</code></pre> or the equivalent command <pre><code> ￿VkDeviceAddress vkGetBufferDeviceAddressEXT( ￿ VkDevice device, ￿ const VkBufferDeviceAddressInfo* pInfo);</code></pre> <h5>Description</h5> The 64-bit return value is an address of the start of {@code pInfo→buffer}. The address range starting at this value and whose size is the size of the buffer <b>can</b> be used in a shader to access the memory bound to that buffer, using the {@code SPV_KHR_physical_storage_buffer} extension or the equivalent {@code SPV_EXT_physical_storage_buffer} extension and the {@code PhysicalStorageBuffer} storage class. For example, this value <b>can</b> be stored in a uniform buffer, and the shader <b>can</b> read the value from the uniform buffer and use it to do a dependent read/write to this buffer. A value of zero is reserved as a “{@code null}” pointer and <b>must</b> not be returned as a valid buffer device address. All loads, stores, and atomics in a shader through {@code PhysicalStorageBuffer} pointers <b>must</b> access addresses in the address range of some buffer. If the buffer was created with a non-zero value of ##VkBufferOpaqueCaptureAddressCreateInfo{@code ::opaqueCaptureAddress} or ##VkBufferDeviceAddressCreateInfoEXT{@code ::deviceAddress}, the return value will be the same address that was returned at capture time. <h5>Valid Usage</h5> <ul> <li>The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-bufferDeviceAddress">{@code bufferDeviceAddress}</a> or <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-bufferDeviceAddressEXT">##VkPhysicalDeviceBufferDeviceAddressFeaturesEXT{@code ::bufferDeviceAddress}</a> feature <b>must</b> be enabled</li> <li>If {@code device} was created with multiple physical devices, then the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-bufferDeviceAddressMultiDevice">{@code bufferDeviceAddressMultiDevice}</a> or <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-bufferDeviceAddressMultiDeviceEXT">##VkPhysicalDeviceBufferDeviceAddressFeaturesEXT{@code ::bufferDeviceAddressMultiDevice}</a> feature <b>must</b> be enabled</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code pInfo} <b>must</b> be a valid pointer to a valid ##VkBufferDeviceAddressInfo structure</li> </ul> <h5>See Also</h5> ##VkBufferDeviceAddressInfo """, VkDevice("device", "the logical device that the buffer was created on."), VkBufferDeviceAddressInfo.const.p("pInfo", "a pointer to a ##VkBufferDeviceAddressInfo structure specifying the buffer to retrieve an address for.") ) uint64_t( "GetBufferOpaqueCaptureAddress", """ Query an opaque capture address of a buffer. <h5>C Specification</h5> To query a 64-bit buffer opaque capture address, call: <pre><code> ￿uint64_t vkGetBufferOpaqueCaptureAddress( ￿ VkDevice device, ￿ const VkBufferDeviceAddressInfo* pInfo);</code></pre> or the equivalent command <pre><code> ￿uint64_t vkGetBufferOpaqueCaptureAddressKHR( ￿ VkDevice device, ￿ const VkBufferDeviceAddressInfo* pInfo);</code></pre> <h5>Description</h5> The 64-bit return value is an opaque capture address of the start of {@code pInfo→buffer}. If the buffer was created with a non-zero value of ##VkBufferOpaqueCaptureAddressCreateInfo{@code ::opaqueCaptureAddress} the return value <b>must</b> be the same address. <h5>Valid Usage</h5> <ul> <li>The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-bufferDeviceAddress">{@code bufferDeviceAddress}</a> feature <b>must</b> be enabled</li> <li>If {@code device} was created with multiple physical devices, then the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-bufferDeviceAddressMultiDevice">{@code bufferDeviceAddressMultiDevice}</a> feature <b>must</b> be enabled</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code pInfo} <b>must</b> be a valid pointer to a valid ##VkBufferDeviceAddressInfo structure</li> </ul> <h5>See Also</h5> ##VkBufferDeviceAddressInfo """, VkDevice("device", "the logical device that the buffer was created on."), VkBufferDeviceAddressInfo.const.p("pInfo", "a pointer to a ##VkBufferDeviceAddressInfo structure specifying the buffer to retrieve an address for.") ) uint64_t( "GetDeviceMemoryOpaqueCaptureAddress", """ Query an opaque capture address of a memory object. <h5>C Specification</h5> To query a 64-bit opaque capture address value from a memory object, call: <pre><code> ￿uint64_t vkGetDeviceMemoryOpaqueCaptureAddress( ￿ VkDevice device, ￿ const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo);</code></pre> or the equivalent command <pre><code> ￿uint64_t vkGetDeviceMemoryOpaqueCaptureAddressKHR( ￿ VkDevice device, ￿ const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo);</code></pre> <h5>Description</h5> The 64-bit return value is an opaque address representing the start of {@code pInfo→memory}. If the memory object was allocated with a non-zero value of ##VkMemoryOpaqueCaptureAddressAllocateInfo{@code ::opaqueCaptureAddress}, the return value <b>must</b> be the same address. <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5> The expected usage for these opaque addresses is only for trace capture/replay tools to store these addresses in a trace and subsequently specify them during replay. </div> <h5>Valid Usage</h5> <ul> <li>The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-bufferDeviceAddress">{@code bufferDeviceAddress}</a> feature <b>must</b> be enabled</li> <li>If {@code device} was created with multiple physical devices, then the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#features-bufferDeviceAddressMultiDevice">{@code bufferDeviceAddressMultiDevice}</a> feature <b>must</b> be enabled</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code pInfo} <b>must</b> be a valid pointer to a valid ##VkDeviceMemoryOpaqueCaptureAddressInfo structure</li> </ul> <h5>See Also</h5> ##VkDeviceMemoryOpaqueCaptureAddressInfo """, VkDevice("device", "the logical device that the memory object was allocated on."), VkDeviceMemoryOpaqueCaptureAddressInfo.const.p("pInfo", "a pointer to a ##VkDeviceMemoryOpaqueCaptureAddressInfo structure specifying the memory object to retrieve an address for.") ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/VK12.kt
1938576341
package rx.lang.kotlin.examples.retrofit import retrofit.RestAdapter import retrofit.http.GET import retrofit.http.Query import rx.Observable data class SearchResultEntry(val id : String, val latestVersion : String) data class SearchResults(val docs : List<SearchResultEntry>) data class MavenSearchResponse(val response : SearchResults) interface MavenSearchService { @GET("/solrsearch/select?wt=json") fun search(@Query("q") s : String, @Query("rows") rows : Int = 20) : Observable<MavenSearchResponse> } fun main(args: Array<String>) { val service = RestAdapter.Builder(). setEndpoint("http://search.maven.org"). build(). create(MavenSearchService::class.java) service.search("rxkotlin"). flatMapIterable { it.response.docs }. doAfterTerminate { System.exit(0) }. // we need this otherwise Rx's executor service will shutdown a minute after request completion subscribe { artifact -> println("${artifact.id} (${artifact.latestVersion})") } }
src/examples/kotlin/rx/lang/kotlin/examples/retrofit/retrofit.kt
977139119
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.debug import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolder val MIXIN_DEBUG_KEY = Key.create<Boolean>("mixin.debug") fun UserDataHolder.hasMixinDebugKey(): Boolean = getUserData(MIXIN_DEBUG_KEY) == true
src/main/kotlin/com/demonwav/mcdev/platform/mixin/debug/MixinDebug.kt
1871810859
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.actions import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.changes.patch.CreatePatchCommitExecutor class CreatePatchAction : AbstractCommitChangesAction() { override fun getExecutor(project: Project): CommitExecutor? = CreatePatchCommitExecutor.getInstance(project) }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/CreatePatchAction.kt
543441756
package com.zeyad.rxredux.core.v2 import android.util.Log import androidx.lifecycle.* import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import org.reactivestreams.Subscriber import java.util.concurrent.TimeUnit import kotlin.properties.Delegates.observable const val ARG_STATE = "arg_state" class AsyncOutcomeFlowable(val flowable: Flowable<RxOutcome>) : Flowable<RxOutcome>() { override fun subscribeActual(s: Subscriber<in RxOutcome>?) = Unit } data class InputOutcomeStream(val input: Input, val outcomes: Flowable<RxOutcome>) internal object EmptyInput : Input() open class RxOutcome(open var input: Input = EmptyInput) object EmptyOutcome : RxOutcome() private data class RxProgress(val progress: Progress) : RxOutcome() internal data class RxError(var error: Error) : RxOutcome() { override var input: Input = EmptyInput set(value) { error = error.copy(input = value) field = value } } abstract class RxReduxViewModel<I : Input, R : Result, S : State, E : Effect>( private val reducer: Reducer<S, R>, private val inputHandler: InputHandler<I, S>, private val savedStateHandle: SavedStateHandle?, ) : ViewModel() { private data class RxState<S>(val state: S) : RxOutcome() internal data class RxEffect<E>(val effect: E) : RxOutcome() internal data class RxResult<R>(val result: R) : RxOutcome() private lateinit var disposable: Disposable private lateinit var currentState: S private var viewModelListener: ViewModelListener<S, E>? = null set(value) { value?.states?.invoke(currentState) field = value } private var progress: Progress by observable(Progress(false, EmptyInput), { _, oldValue, newValue -> if (newValue != oldValue) notifyProgressChanged(newValue) }) private val inputs: PublishSubject<I> = PublishSubject.create() private val throttledInputs: PublishSubject<I> = PublishSubject.create() private val debouncedInputs: PublishSubject<I> = PublishSubject.create() private val trackingListener: TrackingListener<I, R, S, E> = this.initTracking() private val loggingListener: LoggingListener<I, R, S, E> = this.initLogging() fun bind(initialState: S, inputs: () -> Observable<I>): RxReduxViewModel<I, R, S, E> { currentState = savedStateHandle?.get(ARG_STATE) ?: initialState bindInputs(inputs) return this } fun observe(lifecycleOwner: LifecycleOwner, init: ViewModelListenerHelper<S, E>.() -> Unit) { val helper = ViewModelListenerHelper<S, E>() helper.init() viewModelListener = helper removeObservers(lifecycleOwner) } /** * Input source provider. By default it returns empty * It can be overwritten to provide other inputs into the stream */ fun inputSource(): Observable<I> = Observable.empty() fun process(input: I, inputStrategy: InputStrategy = InputStrategy.NONE) = when (inputStrategy) { InputStrategy.NONE -> inputs InputStrategy.THROTTLE -> throttledInputs InputStrategy.DEBOUNCE -> debouncedInputs }.onNext(input) fun log(): LoggingListenerHelper<I, R, S, E>.() -> Unit = { inputs { Log.d(this@RxReduxViewModel::class.simpleName, " - Input: $it") } progress { Log.d(this@RxReduxViewModel::class.simpleName, " - Progress: $it") } results { Log.d(this@RxReduxViewModel::class.simpleName, " - Result: $it") } effects { Log.d(this@RxReduxViewModel::class.simpleName, " - Effect: $it") } states { Log.d(this@RxReduxViewModel::class.simpleName, " - State: $it") } } fun track(): TrackingListenerHelper<I, R, S, E>.() -> Unit = { /*empty*/ } private fun bindInputs(inputs: () -> Observable<I>) { val outcome = createOutcomes(inputs) val stateResult = outcome.filter { it is RxResult<*> }.map { it as RxResult<R> } .scan(RxState(currentState)) { state: RxState<S>, result: RxResult<R> -> RxState(reducer.reduce(state.state, result.result)).apply { input = result.input } }.doOnNext { trackState(it.state, it.input as I) logState(it.state) } disposable = Flowable.merge(outcome.filter { it !is RxResult<*> }, stateResult) .observeOn(AndroidSchedulers.mainThread()) .map { trackEvents(it) logEvents(it) handleResult(it) }.subscribe() } private fun createOutcomes(inputs: () -> Observable<I>): Flowable<RxOutcome> { val streamsToProcess = Observable.merge( inputs(), inputSource(), this.inputs, //throttledInputs.throttle(InputStrategy.THROTTLE.interval), debouncedInputs.debounce(InputStrategy.DEBOUNCE.interval, TimeUnit.MILLISECONDS) ).observeOn(Schedulers.computation()) .toFlowable(BackpressureStrategy.BUFFER) .doOnNext { trackInput(it) logInput(it) }.map { InputOutcomeStream(it, inputHandler.handleInputs(it, currentState)) } .share() val asyncOutcomes = streamsToProcess.filter { it.outcomes is AsyncOutcomeFlowable } .map { it.copy(outcomes = (it.outcomes as AsyncOutcomeFlowable).flowable) } .flatMap { processInputOutcomeStream(it) } val sequentialOutcomes = streamsToProcess.filter { it.outcomes !is AsyncOutcomeFlowable } .concatMap { processInputOutcomeStream(it) } return Flowable.merge(asyncOutcomes, sequentialOutcomes) } private fun processInputOutcomeStream(inputOutcomeStream: InputOutcomeStream): Flowable<RxOutcome> { val result = inputOutcomeStream.outcomes .map { it.apply { input = inputOutcomeStream.input } } .onErrorReturn { createRxError(it, inputOutcomeStream.input as I) } return if (inputOutcomeStream.input.showProgress.not()) { result } else { result.startWith(RxProgress(Progress(isLoading = true, input = inputOutcomeStream.input))) } } private fun trackEvents(event: RxOutcome) { when (event) { is RxProgress -> trackingListener.progress(event.progress) is RxEffect<*> -> trackingListener.effects(event.effect as E, event.input as I) is RxError -> trackingListener.errors(event.error) is RxResult<*> -> trackingListener.results(event.result as R, event.input as I) } } private fun logEvents(event: RxOutcome) { when (event) { is RxProgress -> loggingListener.progress(event.progress) is RxEffect<*> -> loggingListener.effects(event.effect as E) is RxError -> loggingListener.errors(event.error) is RxResult<*> -> loggingListener.results(event.result as R) } } private fun trackInput(input: I) = trackingListener.inputs(input) private fun logInput(input: I) = loggingListener.inputs(input) private fun trackState(state: S, input: I) = trackingListener.states(state, input) private fun logState(state: S) = loggingListener.states(state) private fun createRxError(throwable: Throwable, input: I): RxError = RxError(Error(throwable.message.orEmpty(), throwable, input)).apply { this.input = input } private fun handleResult(result: RxOutcome) { if (result is RxProgress) { notifyProgressChanged(result.progress) } else { dismissProgressDependingOnInput(result.input as I) } when (result) { is RxError -> notifyError(result.error) is RxEffect<*> -> notifyEffect(result.effect as E) is RxState<*> -> { saveState(result.state as S) notifyNewState(result.state) } } } private fun dismissProgressDependingOnInput(input: I?) { if (input?.showProgress == true) { notifyProgressChanged(Progress(false, input)) } } private fun notifyProgressChanged(progress: Progress) = viewModelListener?.progress?.invoke(progress) private fun notifyEffect(effect: E) = viewModelListener?.effects?.invoke(effect) private fun notifyError(error: Error) = viewModelListener?.errors?.invoke(error) private fun notifyNewState(state: S) { currentState = state viewModelListener?.states?.invoke(state) } private fun initTracking(): TrackingListener<I, R, S, E> { val trackingListenerHelper = TrackingListenerHelper<I, R, S, E>() val init: TrackingListenerHelper<I, R, S, E>.() -> Unit = track() trackingListenerHelper.init() return trackingListenerHelper } private fun initLogging(): LoggingListener<I, R, S, E> { val loggingListenerHelper = LoggingListenerHelper<I, R, S, E>() val init: LoggingListenerHelper<I, R, S, E>.() -> Unit = log() loggingListenerHelper.init() return loggingListenerHelper } private fun saveState(state: S) = savedStateHandle?.set(ARG_STATE, state) ?: Unit private fun removeObservers(lifecycleOwner: LifecycleOwner) = lifecycleOwner.lifecycle.addObserver(object : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { unBind() lifecycleOwner.lifecycle.removeObserver(this) } }) override fun onCleared() = unBind() private fun unBind() { viewModelListener = null disposable.dispose() } }
core/src/main/java/com/zeyad/rxredux/core/v2/RxReduxViewModel.kt
3393488544
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jps.builders.java import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtil import com.intellij.util.containers.MultiMap import com.intellij.util.io.EnumeratorStringDescriptor import com.intellij.util.io.directoryContent import com.intellij.util.io.java.AccessModifier import com.intellij.util.io.java.ClassFileBuilder import com.intellij.util.io.java.classFile import gnu.trove.THashSet import org.jetbrains.jps.ModuleChunk import org.jetbrains.jps.builders.DirtyFilesHolder import org.jetbrains.jps.builders.storage.StorageProvider import org.jetbrains.jps.incremental.BuilderCategory import org.jetbrains.jps.incremental.CompileContext import org.jetbrains.jps.incremental.ModuleBuildTarget import org.jetbrains.jps.incremental.ModuleLevelBuilder import org.jetbrains.jps.incremental.storage.AbstractStateStorage import org.jetbrains.jps.incremental.storage.PathStringDescriptor import org.jetbrains.jps.model.java.LanguageLevel import org.jetbrains.org.objectweb.asm.ClassReader import java.io.File import java.util.* import java.util.regex.Pattern /** * Mock builder which produces class file from several source files to test that our build infrastructure handle such cases properly. * * The builder processes *.p file, generates empty class for each such file and generates 'PackageFacade' class for each package * which references all classes from that package. Package name is derived from 'package <name>;' statement from a file or set to empty * if no such statement is found * * @author nik */ class MockPackageFacadeGenerator : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) { override fun build(context: CompileContext, chunk: ModuleChunk, dirtyFilesHolder: DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget>, outputConsumer: ModuleLevelBuilder.OutputConsumer): ModuleLevelBuilder.ExitCode { val filesToCompile = MultiMap.createLinked<ModuleBuildTarget, File>() dirtyFilesHolder.processDirtyFiles { target, file, root -> if (isCompilable(file)) { filesToCompile.putValue(target, file) } true } val allFilesToCompile = ArrayList(filesToCompile.values()) if (allFilesToCompile.isEmpty() && chunk.targets.all { dirtyFilesHolder.getRemovedFiles(it).all { !isCompilable(File(it)) } }) return ModuleLevelBuilder.ExitCode.NOTHING_DONE if (JavaBuilderUtil.isCompileJavaIncrementally(context)) { val logger = context.loggingManager.projectBuilderLogger if (logger.isEnabled) { if (!filesToCompile.isEmpty) { logger.logCompiledFiles(allFilesToCompile, "MockPackageFacadeGenerator", "Compiling files:") } } } val mappings = context.projectDescriptor.dataManager.mappings val callback = JavaBuilderUtil.getDependenciesRegistrar(context) fun generateClass(packageName: String, className: String, target: ModuleBuildTarget, sources: Collection<String>, allSources: Collection<String>, content: (ClassFileBuilder.() -> Unit)? = null) { val fullClassName = StringUtil.getQualifiedName(packageName, className) directoryContent { classFile(fullClassName) { javaVersion = LanguageLevel.JDK_1_6 if (content != null) { content() } } }.generate(target.outputDir!!) val outputFile = File(target.outputDir, "${fullClassName.replace('.', '/')}.class") outputConsumer.registerOutputFile(target, outputFile, sources) callback.associate(fullClassName, allSources, ClassReader(outputFile.readBytes())) } for (target in chunk.targets) { val packagesStorage = context.projectDescriptor.dataManager.getStorage(target, PACKAGE_CACHE_STORAGE_PROVIDER) for (file in filesToCompile[target]) { val sources = listOf(file.absolutePath) generateClass(getPackageName(file), FileUtil.getNameWithoutExtension(file), target, sources, sources) } val packagesToGenerate = LinkedHashMap<String, MutableList<File>>() filesToCompile[target].forEach { val currentName = getPackageName(it) if (currentName !in packagesToGenerate) packagesToGenerate[currentName] = ArrayList() packagesToGenerate[currentName]!!.add(it) val oldName = packagesStorage.getState(it.absolutePath) if (oldName != null && oldName != currentName && oldName !in packagesToGenerate) { packagesToGenerate[oldName] = ArrayList() } } val packagesFromDeletedFiles = dirtyFilesHolder.getRemovedFiles(target).filter { isCompilable(File(it)) }.map { packagesStorage.getState(it) }.filterNotNull() packagesFromDeletedFiles.forEach { if (it !in packagesToGenerate) { packagesToGenerate[it] = ArrayList() } } val getParentFile: (File) -> File = { it.parentFile } val dirsToCheck = filesToCompile[target].mapTo(THashSet(FileUtil.FILE_HASHING_STRATEGY), getParentFile) packagesFromDeletedFiles.flatMap { mappings.getClassSources(mappings.getName(StringUtil.getQualifiedName(it, "PackageFacade"))) ?: emptyList() }.map(getParentFile).filterNotNullTo(dirsToCheck) for ((packageName, dirtyFiles) in packagesToGenerate) { val files = dirsToCheck.map { it.listFiles() }.filterNotNull().flatMap { it.toList() }.filter { isCompilable(it) && packageName == getPackageName(it) } if (files.isEmpty()) continue val classNames = files.map { FileUtilRt.getNameWithoutExtension(it.name) }.sorted() val dirtySource = dirtyFiles.map { it.absolutePath } val allSources = files.map { it.absolutePath } generateClass(packageName, "PackageFacade", target, dirtySource, allSources) { for (fileName in classNames) { val fieldClass = StringUtil.getQualifiedName(packageName, fileName) field(StringUtil.decapitalize(fileName), fieldClass, AccessModifier.PUBLIC) } } for (source in dirtySource) { packagesStorage.update(FileUtil.toSystemIndependentName(source), packageName) } } } JavaBuilderUtil.registerFilesToCompile(context, allFilesToCompile) JavaBuilderUtil.registerSuccessfullyCompiled(context, allFilesToCompile) return ModuleLevelBuilder.ExitCode.OK } override fun getCompilableFileExtensions(): List<String> { return listOf("p") } override fun getPresentableName(): String { return "Mock Package Facade Generator" } companion object { private val PACKAGE_CACHE_STORAGE_PROVIDER = object : StorageProvider<AbstractStateStorage<String, String>>() { override fun createStorage(targetDataDir: File): AbstractStateStorage<String, String> { val storageFile = File(targetDataDir, "mockPackageFacade/packages") return object : AbstractStateStorage<String, String>(storageFile, PathStringDescriptor(), EnumeratorStringDescriptor()) { } } } private fun getPackageName(sourceFile: File): String { val text = String(FileUtil.loadFileText(sourceFile)) val matcher = Pattern.compile("\\p{javaWhitespace}*package\\p{javaWhitespace}+([^;]*);.*").matcher(text) if (matcher.matches()) { return matcher.group(1) } return "" } private fun isCompilable(file: File): Boolean { return FileUtilRt.extensionEquals(file.name, "p") } } }
jps/jps-builders/testSrc/org/jetbrains/jps/builders/java/MockPackageFacadeBuilder.kt
2993185954
package ru.ltcnt.lfg_player_android.data.repository import javax.inject.Inject /** * Author aev * Since 22.10.2017. */ interface PlaylistRepositoryInterface { fun getPlaylist() fun addPlaylist() fun deletePlaylist() } class PlaylistRepository @Inject constructor( ): PlaylistRepositoryInterface { override fun getPlaylist() { } override fun addPlaylist() { } override fun deletePlaylist() { } }
app/src/main/java/ru/ltcnt/lfg_player_android/data/repository/PlaylistRepository.kt
4030026009
// 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.refactoring.changeSignature import com.intellij.lang.Language import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolderBase import com.intellij.psi.* import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.refactoring.changeSignature.* import com.intellij.refactoring.util.CanonicalTypes import com.intellij.usageView.UsageInfo import com.intellij.util.VisibilityUtil import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.builtins.isNonExtensionFunctionType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.DescriptorVisibility import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor import org.jetbrains.kotlin.idea.j2k.j2k import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor.Kind import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallerUsage import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isIdentifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.utils.keysToMap open class KotlinChangeInfo( val methodDescriptor: KotlinMethodDescriptor, private var name: String = methodDescriptor.name, var newReturnTypeInfo: KotlinTypeInfo = KotlinTypeInfo(true, methodDescriptor.baseDescriptor.returnType), var newVisibility: DescriptorVisibility = methodDescriptor.visibility, parameterInfos: List<KotlinParameterInfo> = methodDescriptor.parameters, receiver: KotlinParameterInfo? = methodDescriptor.receiver, val context: PsiElement, primaryPropagationTargets: Collection<PsiElement> = emptyList(), var checkUsedParameters: Boolean = false, ) : ChangeInfo, UserDataHolder by UserDataHolderBase() { private val innerChangeInfo: MutableList<KotlinChangeInfo> = mutableListOf() fun registerInnerChangeInfo(changeInfo: KotlinChangeInfo) { innerChangeInfo += changeInfo } private class JvmOverloadSignature( val method: PsiMethod, val mandatoryParams: Set<KtParameter>, val defaultValues: Set<KtExpression> ) { fun constrainBy(other: JvmOverloadSignature): JvmOverloadSignature { return JvmOverloadSignature( method, mandatoryParams.intersect(other.mandatoryParams), defaultValues.intersect(other.defaultValues) ) } } private val originalReturnTypeInfo = methodDescriptor.returnTypeInfo private val originalReceiverTypeInfo = methodDescriptor.receiver?.originalTypeInfo var receiverParameterInfo: KotlinParameterInfo? = receiver set(value) { if (value != null && value !in newParameters) { newParameters.add(value) } field = value } private val newParameters = parameterInfos.toMutableList() private val originalPsiMethods = method.toLightMethods() private val originalParameters = (method as? KtFunction)?.valueParameters ?: emptyList() private val originalSignatures = makeSignatures(originalParameters, originalPsiMethods, { it }, { it.defaultValue }) private val oldNameToParameterIndex: Map<String, Int> by lazy { val map = HashMap<String, Int>() val parameters = methodDescriptor.baseDescriptor.valueParameters parameters.indices.forEach { i -> map[parameters[i].name.asString()] = i } map } private val isParameterSetOrOrderChangedLazy: Boolean by lazy { val signatureParameters = getNonReceiverParameters() methodDescriptor.receiver != receiverParameterInfo || signatureParameters.size != methodDescriptor.parametersCount || signatureParameters.indices.any { i -> signatureParameters[i].oldIndex != i } } private var isPrimaryMethodUpdated: Boolean = false private var javaChangeInfos: List<JavaChangeInfo>? = null var originalToCurrentMethods: Map<PsiMethod, PsiMethod> = emptyMap() private set val parametersToRemove: BooleanArray get() { val originalReceiver = methodDescriptor.receiver val hasReceiver = methodDescriptor.receiver != null val receiverShift = if (hasReceiver) 1 else 0 val toRemove = BooleanArray(receiverShift + methodDescriptor.parametersCount) { true } if (hasReceiver) { toRemove[0] = receiverParameterInfo == null && hasReceiver && originalReceiver !in getNonReceiverParameters() } for (parameter in newParameters) { parameter.oldIndex.takeIf { it >= 0 }?.let { oldIndex -> toRemove[receiverShift + oldIndex] = false } } return toRemove } fun getOldParameterIndex(oldParameterName: String): Int? = oldNameToParameterIndex[oldParameterName] override fun isParameterTypesChanged(): Boolean = true override fun isParameterNamesChanged(): Boolean = true override fun isParameterSetOrOrderChanged(): Boolean = isParameterSetOrOrderChangedLazy fun getNewParametersCount(): Int = newParameters.size fun hasAppendedParametersOnly(): Boolean { val oldParamCount = originalBaseFunctionDescriptor.valueParameters.size return newParameters.asSequence().withIndex().all { (i, p) -> if (i < oldParamCount) p.oldIndex == i else p.isNewParameter } } override fun getNewParameters(): Array<KotlinParameterInfo> = newParameters.toTypedArray() fun getNonReceiverParametersCount(): Int = newParameters.size - (if (receiverParameterInfo != null) 1 else 0) fun getNonReceiverParameters(): List<KotlinParameterInfo> { methodDescriptor.baseDeclaration.let { if (it is KtProperty || it is KtParameter) return emptyList() } return receiverParameterInfo?.let { receiver -> newParameters.filter { it != receiver } } ?: newParameters } fun setNewParameter(index: Int, parameterInfo: KotlinParameterInfo) { newParameters[index] = parameterInfo } @JvmOverloads fun addParameter(parameterInfo: KotlinParameterInfo, atIndex: Int = -1) { if (atIndex >= 0) { newParameters.add(atIndex, parameterInfo) } else { newParameters.add(parameterInfo) } } fun removeParameter(index: Int) { val parameterInfo = newParameters.removeAt(index) if (parameterInfo == receiverParameterInfo) { receiverParameterInfo = null } } fun clearParameters() { newParameters.clear() receiverParameterInfo = null } fun hasParameter(parameterInfo: KotlinParameterInfo): Boolean = parameterInfo in newParameters override fun isGenerateDelegate(): Boolean = false override fun getNewName(): String = name.takeIf { it != "<no name provided>" }?.quoteIfNeeded() ?: name fun setNewName(value: String) { name = value } override fun isNameChanged(): Boolean = name != methodDescriptor.name fun isVisibilityChanged(): Boolean = newVisibility != methodDescriptor.visibility override fun getMethod(): PsiElement { return methodDescriptor.method } override fun isReturnTypeChanged(): Boolean = !newReturnTypeInfo.isEquivalentTo(originalReturnTypeInfo) fun isReceiverTypeChanged(): Boolean { val receiverInfo = receiverParameterInfo ?: return originalReceiverTypeInfo != null return originalReceiverTypeInfo == null || !receiverInfo.currentTypeInfo.isEquivalentTo(originalReceiverTypeInfo) } override fun getLanguage(): Language = KotlinLanguage.INSTANCE var propagationTargetUsageInfos: List<UsageInfo> = ArrayList() private set var primaryPropagationTargets: Collection<PsiElement> = emptyList() set(value) { field = value val result = LinkedHashSet<UsageInfo>() fun add(element: PsiElement) { element.unwrapped?.let { val usageInfo = when (it) { is KtNamedFunction, is KtConstructor<*>, is KtClassOrObject -> KotlinCallerUsage(it as KtNamedDeclaration) is PsiMethod -> CallerUsageInfo(it, true, true) else -> return } result.add(usageInfo) } } for (caller in value) { add(caller) OverridingMethodsSearch.search(caller.getRepresentativeLightMethod() ?: continue).forEach(::add) } propagationTargetUsageInfos = result.toList() } init { this.primaryPropagationTargets = primaryPropagationTargets } private fun renderReturnTypeIfNeeded(): String? { val typeInfo = newReturnTypeInfo if (kind != Kind.FUNCTION) return null if (typeInfo.type?.isUnit() == true) return null return typeInfo.render() } fun getNewSignature(inheritedCallable: KotlinCallableDefinitionUsage<PsiElement>): String { val buffer = StringBuilder() val isCustomizedVisibility = newVisibility != DescriptorVisibilities.DEFAULT_VISIBILITY if (kind == Kind.PRIMARY_CONSTRUCTOR) { buffer.append(newName) if (isCustomizedVisibility) { buffer.append(' ').append(newVisibility).append(" constructor ") } } else { if (!DescriptorUtils.isLocal(inheritedCallable.originalCallableDescriptor) && isCustomizedVisibility) { buffer.append(newVisibility).append(' ') } buffer.append(if (kind == Kind.SECONDARY_CONSTRUCTOR) KtTokens.CONSTRUCTOR_KEYWORD else KtTokens.FUN_KEYWORD).append(' ') if (kind == Kind.FUNCTION) { receiverParameterInfo?.let { val typeInfo = it.currentTypeInfo if (typeInfo.type != null && typeInfo.type.isNonExtensionFunctionType) { buffer.append("(${typeInfo.render()})") } else { buffer.append(typeInfo.render()) } buffer.append('.') } buffer.append(newName) } } buffer.append(getNewParametersSignature(inheritedCallable)) renderReturnTypeIfNeeded()?.let { buffer.append(": ").append(it) } return buffer.toString() } fun getNewParametersSignature(inheritedCallable: KotlinCallableDefinitionUsage<*>): String { return "(" + getNewParametersSignatureWithoutParentheses(inheritedCallable) + ")" } fun getNewParametersSignatureWithoutParentheses( inheritedCallable: KotlinCallableDefinitionUsage<*> ): String { val signatureParameters = getNonReceiverParameters() val isLambda = inheritedCallable.declaration is KtFunctionLiteral if (isLambda && signatureParameters.size == 1 && !signatureParameters[0].requiresExplicitType(inheritedCallable)) { return signatureParameters[0].getDeclarationSignature(0, inheritedCallable).text } return signatureParameters.indices.joinToString(separator = ", ") { i -> signatureParameters[i].getDeclarationSignature(i, inheritedCallable).text } } fun renderReceiverType(inheritedCallable: KotlinCallableDefinitionUsage<*>): String? { val receiverTypeText = receiverParameterInfo?.currentTypeInfo?.render() ?: return null val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return receiverTypeText val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return receiverTypeText val receiverType = currentBaseFunction.extensionReceiverParameter!!.type if (receiverType.isError) return receiverTypeText return receiverType.renderTypeWithSubstitution(typeSubstitutor, receiverTypeText, false) } fun renderReturnType(inheritedCallable: KotlinCallableDefinitionUsage<*>): String { val defaultRendering = newReturnTypeInfo.render() val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return defaultRendering val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return defaultRendering val returnType = currentBaseFunction.returnType!! if (returnType.isError) return defaultRendering return returnType.renderTypeWithSubstitution(typeSubstitutor, defaultRendering, false) } fun primaryMethodUpdated() { isPrimaryMethodUpdated = true javaChangeInfos = null for (info in innerChangeInfo) { info.primaryMethodUpdated() } } private fun <Parameter> makeSignatures( parameters: List<Parameter>, psiMethods: List<PsiMethod>, getPsi: (Parameter) -> KtParameter, getDefaultValue: (Parameter) -> KtExpression? ): List<JvmOverloadSignature> { val defaultValueCount = parameters.count { getDefaultValue(it) != null } if (psiMethods.size != defaultValueCount + 1) return emptyList() val mandatoryParams = parameters.toMutableList() val defaultValues = ArrayList<KtExpression>() return psiMethods.map { method -> JvmOverloadSignature(method, mandatoryParams.asSequence().map(getPsi).toSet(), defaultValues.toSet()).apply { val param = mandatoryParams.removeLast { getDefaultValue(it) != null } ?: return@apply defaultValues.add(getDefaultValue(param)!!) } } } private fun <T> MutableList<T>.removeLast(condition: (T) -> Boolean): T? { val index = indexOfLast(condition) return if (index >= 0) removeAt(index) else null } fun getOrCreateJavaChangeInfos(): List<JavaChangeInfo>? { fun initCurrentSignatures(currentPsiMethods: List<PsiMethod>): List<JvmOverloadSignature> { val parameterInfoToPsi = methodDescriptor.original.parameters.zip(originalParameters).toMap() val dummyParameter = KtPsiFactory(method).createParameter("dummy") return makeSignatures( parameters = newParameters, psiMethods = currentPsiMethods, getPsi = { parameterInfoToPsi[it] ?: dummyParameter }, getDefaultValue = { it.defaultValue }, ) } fun matchOriginalAndCurrentMethods(currentPsiMethods: List<PsiMethod>): Map<PsiMethod, PsiMethod> { if (!(isPrimaryMethodUpdated && originalBaseFunctionDescriptor is FunctionDescriptor && originalBaseFunctionDescriptor.findJvmOverloadsAnnotation() != null)) { return (originalPsiMethods.zip(currentPsiMethods)).toMap() } if (originalPsiMethods.isEmpty() || currentPsiMethods.isEmpty()) return emptyMap() currentPsiMethods.singleOrNull()?.let { method -> return originalPsiMethods.keysToMap { method } } val currentSignatures = initCurrentSignatures(currentPsiMethods) return originalSignatures.associateBy({ it.method }) { originalSignature -> var constrainedCurrentSignatures = currentSignatures.map { it.constrainBy(originalSignature) } val maxMandatoryCount = constrainedCurrentSignatures.maxOf { it.mandatoryParams.size } constrainedCurrentSignatures = constrainedCurrentSignatures.filter { it.mandatoryParams.size == maxMandatoryCount } val maxDefaultCount = constrainedCurrentSignatures.maxOf { it.defaultValues.size } constrainedCurrentSignatures.last { it.defaultValues.size == maxDefaultCount }.method } } /* * When primaryMethodUpdated is false, changes to the primary Kotlin declaration are already confirmed, but not yet applied. * It means that originalPsiMethod has already expired, but new one can't be created until Kotlin declaration is updated * (signified by primaryMethodUpdated being true). It means we can't know actual PsiType, visibility, etc. * to use in JavaChangeInfo. However they are not actually used at this point since only parameter count and order matters here * So we resort to this hack and pass around "default" type (void) and visibility (package-local) */ fun createJavaChangeInfo( originalPsiMethod: PsiMethod, currentPsiMethod: PsiMethod, newName: String, newReturnType: PsiType?, newParameters: Array<ParameterInfoImpl> ): JavaChangeInfo? { if (!newName.unquoteKotlinIdentifier().isIdentifier()) return null val newVisibility = if (isPrimaryMethodUpdated) VisibilityUtil.getVisibilityModifier(currentPsiMethod.modifierList) else PsiModifier.PACKAGE_LOCAL val propagationTargets = primaryPropagationTargets.asSequence() .mapNotNull { it.getRepresentativeLightMethod() } .toSet() val javaChangeInfo = ChangeSignatureProcessor( method.project, originalPsiMethod, false, newVisibility, newName, CanonicalTypes.createTypeWrapper(newReturnType ?: PsiType.VOID), newParameters, arrayOf<ThrownExceptionInfo>(), propagationTargets, emptySet() ).changeInfo javaChangeInfo.updateMethod(currentPsiMethod) return javaChangeInfo } fun getJavaParameterInfos( originalPsiMethod: PsiMethod, currentPsiMethod: PsiMethod, newParameterList: List<KotlinParameterInfo> ): MutableList<ParameterInfoImpl> { val defaultValuesToSkip = newParameterList.size - currentPsiMethod.parameterList.parametersCount val defaultValuesToRetain = newParameterList.count { it.defaultValue != null } - defaultValuesToSkip val oldIndices = newParameterList.map { it.oldIndex }.toIntArray() // TODO: Ugly code, need to refactor Change Signature data model var defaultValuesRemained = defaultValuesToRetain for (param in newParameterList) { if (param.isNewParameter || param.defaultValue == null || defaultValuesRemained-- > 0) continue newParameterList.asSequence() .withIndex() .filter { it.value.oldIndex >= param.oldIndex } .toList() .forEach { oldIndices[it.index]-- } } defaultValuesRemained = defaultValuesToRetain val oldParameterCount = originalPsiMethod.parameterList.parametersCount var indexInCurrentPsiMethod = 0 return newParameterList.asSequence().withIndex().mapNotNullTo(ArrayList()) map@{ pair -> val (i, info) = pair if (info.defaultValue != null && defaultValuesRemained-- <= 0) return@map null val oldIndex = oldIndices[i] val javaOldIndex = when { methodDescriptor.receiver == null -> oldIndex info == methodDescriptor.receiver -> 0 oldIndex >= 0 -> oldIndex + 1 else -> -1 } if (javaOldIndex >= oldParameterCount) return@map null val type = if (isPrimaryMethodUpdated) currentPsiMethod.parameterList.parameters[indexInCurrentPsiMethod++].type else PsiType.VOID val defaultValue = info.defaultValueForCall ?: info.defaultValue ParameterInfoImpl(javaOldIndex, info.name, type, defaultValue?.text ?: "") } } fun createJavaChangeInfoForFunctionOrGetter( originalPsiMethod: PsiMethod, currentPsiMethod: PsiMethod, isGetter: Boolean ): JavaChangeInfo? { val newParameterList = listOfNotNull(receiverParameterInfo) + getNonReceiverParameters() val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, newParameterList).toTypedArray() val newName = if (isGetter) JvmAbi.getterName(newName) else newName return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, currentPsiMethod.returnType, newJavaParameters) } fun createJavaChangeInfoForSetter(originalPsiMethod: PsiMethod, currentPsiMethod: PsiMethod): JavaChangeInfo? { val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, listOfNotNull(receiverParameterInfo)) val oldIndex = if (methodDescriptor.receiver != null) 1 else 0 val parameters = currentPsiMethod.parameterList.parameters if (isPrimaryMethodUpdated) { val newIndex = if (receiverParameterInfo != null) 1 else 0 val setterParameter = parameters[newIndex] newJavaParameters.add(ParameterInfoImpl(oldIndex, setterParameter.name, setterParameter.type)) } else { if (receiverParameterInfo != null) { if (newJavaParameters.isEmpty()) { newJavaParameters.add(ParameterInfoImpl(oldIndex, "receiver", PsiType.VOID)) } } if (oldIndex < parameters.size) { val setterParameter = parameters[oldIndex] newJavaParameters.add(ParameterInfoImpl(oldIndex, setterParameter.name, setterParameter.type)) } } val newName = JvmAbi.setterName(newName) return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, PsiType.VOID, newJavaParameters.toTypedArray()) } if (!(method.containingFile as KtFile).platform.isJvm()) return null if (javaChangeInfos == null) { val method = method originalToCurrentMethods = matchOriginalAndCurrentMethods(method.toLightMethods()) javaChangeInfos = originalToCurrentMethods.entries.mapNotNull { val (originalPsiMethod, currentPsiMethod) = it when (method) { is KtFunction, is KtClassOrObject -> createJavaChangeInfoForFunctionOrGetter(originalPsiMethod, currentPsiMethod, false) is KtProperty, is KtParameter -> { val accessorName = originalPsiMethod.name when { JvmAbi.isGetterName(accessorName) -> createJavaChangeInfoForFunctionOrGetter(originalPsiMethod, currentPsiMethod, true) JvmAbi.isSetterName(accessorName) -> createJavaChangeInfoForSetter(originalPsiMethod, currentPsiMethod) else -> null } } else -> null } } } return javaChangeInfos } } val KotlinChangeInfo.originalBaseFunctionDescriptor: CallableDescriptor get() = methodDescriptor.baseDescriptor val KotlinChangeInfo.kind: Kind get() = methodDescriptor.kind val KotlinChangeInfo.oldName: String? get() = (methodDescriptor.method as? KtFunction)?.name fun KotlinChangeInfo.getAffectedCallables(): Collection<UsageInfo> = methodDescriptor.affectedCallables + propagationTargetUsageInfos fun ChangeInfo.toJetChangeInfo( originalChangeSignatureDescriptor: KotlinMethodDescriptor, resolutionFacade: ResolutionFacade ): KotlinChangeInfo { val method = method as PsiMethod val functionDescriptor = method.getJavaOrKotlinMemberDescriptor(resolutionFacade) as CallableDescriptor val parameterDescriptors = functionDescriptor.valueParameters //noinspection ConstantConditions val originalParameterDescriptors = originalChangeSignatureDescriptor.baseDescriptor.valueParameters val newParameters = newParameters.withIndex().map { pair -> val (i, info) = pair val oldIndex = info.oldIndex val currentType = parameterDescriptors[i].type val defaultValueText = info.defaultValue val defaultValueExpr = when { info is KotlinAwareJavaParameterInfoImpl -> info.kotlinDefaultValue language.`is`(JavaLanguage.INSTANCE) && !defaultValueText.isNullOrEmpty() -> { PsiElementFactory.getInstance(method.project).createExpressionFromText(defaultValueText, null).j2k() } else -> null } val parameterType = if (oldIndex >= 0) originalParameterDescriptors[oldIndex].type else currentType val originalKtParameter = originalParameterDescriptors.getOrNull(oldIndex)?.source?.getPsi() as? KtParameter val valOrVar = originalKtParameter?.valOrVarKeyword?.toValVar() ?: KotlinValVar.None KotlinParameterInfo( callableDescriptor = functionDescriptor, originalIndex = oldIndex, name = info.name, originalTypeInfo = KotlinTypeInfo(false, parameterType), defaultValueForCall = defaultValueExpr, valOrVar = valOrVar ).apply { currentTypeInfo = KotlinTypeInfo(false, currentType) } } return KotlinChangeInfo( originalChangeSignatureDescriptor, newName, KotlinTypeInfo(true, functionDescriptor.returnType), functionDescriptor.visibility, newParameters, null, method ) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeInfo.kt
3155492701
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jetbrains.packagesearch.intellij.plugin.ui import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.ExperimentalUI import com.intellij.ui.Gray import com.intellij.ui.JBColor import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBValue import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import com.jetbrains.packagesearch.intellij.plugin.ui.components.BrowsableLinkLabel import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScalableUnits import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import org.jetbrains.annotations.Nls import java.awt.CardLayout import java.awt.Color import java.awt.Component import java.awt.Dimension import java.awt.FlowLayout import java.awt.Rectangle import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.BorderFactory import javax.swing.BoxLayout import javax.swing.Icon import javax.swing.JCheckBox import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JMenuItem import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.JTextField import javax.swing.KeyStroke import javax.swing.Scrollable object PackageSearchUI { internal object Colors { val border = JBColor.border() val separator = JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground() private val mainBackground: Color = JBColor.namedColor("Plugins.background", UIUtil.getListBackground()) val infoLabelForeground: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135)) val headerBackground = mainBackground val sectionHeaderBackground = JBColor.namedColor("Plugins.SectionHeader.background", 0xF7F7F7, 0x3C3F41) val panelBackground get() = if (isNewUI) JBColor.namedColor("Panel.background") else mainBackground interface StatefulColor { fun background(isSelected: Boolean, isHover: Boolean): Color fun foreground(isSelected: Boolean, isHover: Boolean): Color } object PackagesTable : StatefulColor { override fun background(isSelected: Boolean, isHover: Boolean) = when { isSelected -> tableSelectedBackground isHover -> tableHoverBackground else -> tableBackground } override fun foreground(isSelected: Boolean, isHover: Boolean) = when { isSelected -> tableSelectedForeground else -> tableForeground } private val tableBackground = JBColor.namedColor("Table.background") private val tableForeground = JBColor.namedColor("Table.foreground") private val tableHoverBackground get() = color( propertyName = "PackageSearch.SearchResult.hoverBackground", newUILight = 0x2C3341, newUIDark = 0xDBE1EC, oldUILight = 0xF2F5F9, oldUIDark = 0x4C5052 ) private val tableSelectedBackground = JBColor.namedColor("Table.selectionBackground") private val tableSelectedForeground = JBColor.namedColor("Table.selectionForeground") object SearchResult : StatefulColor { override fun background(isSelected: Boolean, isHover: Boolean) = when { isSelected -> searchResultSelectedBackground isHover -> searchResultHoverBackground else -> searchResultBackground } override fun foreground(isSelected: Boolean, isHover: Boolean) = when { isSelected -> searchResultSelectedForeground else -> searchResultForeground } private val searchResultBackground get() = color( propertyName = "PackageSearch.SearchResult.background", newUILight = 0xE8EEFA, newUIDark = 0x1C2433, oldUILight = 0xE4FAFF, oldUIDark = 0x3F4749 ) private val searchResultForeground = tableForeground private val searchResultSelectedBackground = tableSelectedBackground private val searchResultSelectedForeground = tableSelectedForeground private val searchResultHoverBackground get() = color( propertyName = "PackageSearch.SearchResult.hoverBackground", newUILight = 0xDBE1EC, newUIDark = 0x2C3341, oldUILight = 0xF2F5F9, oldUIDark = 0x4C5052 ) object Tag : StatefulColor { override fun background(isSelected: Boolean, isHover: Boolean) = when { isSelected -> searchResultTagSelectedBackground isHover -> searchResultTagHoverBackground else -> searchResultTagBackground } override fun foreground(isSelected: Boolean, isHover: Boolean) = when { isSelected -> searchResultTagSelectedForeground else -> searchResultTagForeground } private val searchResultTagBackground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.background", newUILight = 0xD5DBE6, newUIDark = 0x2E3643, oldUILight = 0xD2E6EB, oldUIDark = 0x4E5658 ) private val searchResultTagForeground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.foreground", newUILight = 0x000000, newUIDark = 0xDFE1E5, oldUILight = 0x000000, oldUIDark = 0x8E8F8F ) private val searchResultTagHoverBackground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.hoverBackground", newUILight = 0xC9CFD9, newUIDark = 0x3D4350, oldUILight = 0xBFD0DB, oldUIDark = 0x55585B ) private val searchResultTagSelectedBackground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.selectedBackground", newUILight = 0xA0BDF8, newUIDark = 0x375FAD, oldUILight = 0x4395E2, oldUIDark = 0x2F65CA ) private val searchResultTagSelectedForeground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.selectedForeground", newUILight = 0x000000, newUIDark = 0x1E1F22, oldUILight = 0xFFFFFF, oldUIDark = 0xBBBBBB ) } } object Tag : StatefulColor { override fun background(isSelected: Boolean, isHover: Boolean) = when { isSelected -> tagSelectedBackground isHover -> tagHoverBackground else -> tagBackground } override fun foreground(isSelected: Boolean, isHover: Boolean) = when { isSelected -> tagSelectedForeground else -> tagForeground } private val tagBackground get() = color( propertyName = "PackageSearch.PackageTag.background", newUILight = 0xDFE1E5, newUIDark = 0x43454A, oldUILight = 0xEBEBEB, oldUIDark = 0x4C4E50 ) private val tagForeground get() = color( propertyName = "PackageSearch.PackageTag.foreground", newUILight = 0x5A5D6B, newUIDark = 0x9DA0A8, oldUILight = 0x000000, oldUIDark = 0x9C9C9C ) private val tagHoverBackground get() = color( propertyName = "PackageSearch.PackageTag.hoverBackground", newUILight = 0xF7F8FA, newUIDark = 0x4A4C4E, oldUILight = 0xC9D2DB, oldUIDark = 0x55585B ) private val tagSelectedBackground get() = color( propertyName = "PackageSearch.PackageTag.selectedBackground", newUILight = 0x88ADF7, newUIDark = 0x43454A, oldUILight = 0x4395E2, oldUIDark = 0x2F65CA ) private val tagSelectedForeground get() = color( propertyName = "PackageSearch.PackageTag.selectedForeground", newUILight = 0x000000, newUIDark = 0x9DA0A8, oldUILight = 0xFFFFFF, oldUIDark = 0xBBBBBB ) } } object InfoBanner { val background = JBUI.CurrentTheme.Banner.INFO_BACKGROUND val border = JBUI.CurrentTheme.Banner.INFO_BORDER_COLOR } private fun color( propertyName: String? = null, newUILight: Int, newUIDark: Int, oldUILight: Int, oldUIDark: Int ) = if (propertyName != null) { JBColor.namedColor( propertyName, if (isNewUI) newUILight else oldUILight, if (isNewUI) newUIDark else oldUIDark ) } else { JBColor( if (isNewUI) newUILight else oldUILight, if (isNewUI) newUIDark else oldUIDark ) } } internal val mediumHeaderHeight = JBValue.Float(30f) internal val smallHeaderHeight = JBValue.Float(24f) val isNewUI get() = ExperimentalUI.isNewUI() @Suppress("MagicNumber") // Thanks, Swing internal fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() { init { border = JBEmptyBorder(2, 0, 2, 12) init() } override fun getBackground() = Colors.headerBackground } internal fun cardPanel(cards: List<JPanel> = emptyList(), backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) = object : JPanel() { init { layout = CardLayout() cards.forEach { add(it) } init() } override fun getBackground() = backgroundColor } internal fun borderPanel(backgroundColor: Color = Colors.panelBackground, init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() { init { init() } override fun getBackground() = backgroundColor } internal fun boxPanel(axis: Int = BoxLayout.Y_AXIS, backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) = object : JPanel() { init { layout = BoxLayout(this, axis) init() } override fun getBackground() = backgroundColor } internal fun flowPanel(backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) = object : JPanel() { init { layout = FlowLayout(FlowLayout.LEFT) init() } override fun getBackground() = backgroundColor } fun checkBox(@Nls title: String, init: JCheckBox.() -> Unit = {}) = object : JCheckBox(title) { init { init() } override fun getBackground() = Colors.panelBackground } fun textField(init: JTextField.() -> Unit): JTextField = JTextField().apply { init() } internal fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem { if (icon != null) { return JMenuItem(title, icon).apply { addActionListener { handler() } } } return JMenuItem(title).apply { addActionListener { handler() } } } fun createLabel(@Nls text: String? = null, init: JLabel.() -> Unit = {}) = JLabel().apply { font = StartupUiUtil.getLabelFont() if (text != null) this.text = text init() } internal fun createLabelWithLink(init: BrowsableLinkLabel.() -> Unit = {}) = BrowsableLinkLabel().apply { font = StartupUiUtil.getLabelFont() init() } internal fun getTextColorPrimary(isSelected: Boolean = false): Color = when { isSelected -> JBColor.lazy { UIUtil.getListSelectionForeground(true) } else -> JBColor.lazy { UIUtil.getListForeground() } } internal fun getTextColorSecondary(isSelected: Boolean = false): Color = when { isSelected -> getTextColorPrimary(true) else -> Colors.infoLabelForeground } internal fun setHeight(component: JComponent, @ScalableUnits height: Int, keepWidth: Boolean = false) { setHeightPreScaled(component, height.scaled(), keepWidth) } internal fun setHeightPreScaled(component: JComponent, @ScaledPixels height: Int, keepWidth: Boolean = false) { component.apply { preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, height) minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, height) maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, height) } } internal fun verticalScrollPane(c: Component) = object : JScrollPane( VerticalScrollPanelWrapper(c), VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER ) { init { border = BorderFactory.createEmptyBorder() viewport.background = Colors.panelBackground } } internal fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action) internal fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) { val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED) inputMap.put(KeyStroke.getKeyStroke(stroke), key) c.actionMap.put( key, object : AbstractAction() { override fun actionPerformed(arg: ActionEvent) { action() } } ) } private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable { init { layout = BoxLayout(this, BoxLayout.Y_AXIS) add(content) } override fun getPreferredScrollableViewportSize(): Dimension = preferredSize override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10 override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100 override fun getScrollableTracksViewportWidth() = true override fun getScrollableTracksViewportHeight() = false override fun getBackground() = Colors.panelBackground } } internal class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(), CustomComponentAction { override fun createCustomComponent(presentation: Presentation, place: String) = myComponentCreator() override fun actionPerformed(e: AnActionEvent) { // No-op } } internal fun JComponent.updateAndRepaint() { invalidate() repaint() }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/PackageSearchUI.kt
3098225171
// 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.uast.kotlin import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.kinds.KotlinSpecialExpressionKinds @ApiStatus.Internal class KotlinSupertypeDelegationUExpression( override val sourcePsi: KtDelegatedSuperTypeEntry, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UExpressionList { override val psi: PsiElement get() = sourcePsi val typeReference: UTypeReferenceExpression? by lz { sourcePsi.typeReference?.let { KotlinUTypeReferenceExpression(it, this) { baseResolveProviderService.resolveToType(it, this, boxed = false) ?: UastErrorType } } } val delegateExpression: UExpression? by lz { sourcePsi.delegateExpression?.let { languagePlugin?.convertElement(it, this, UExpression::class.java) as? UExpression } } override val expressions: List<UExpression> get() = listOfNotNull(typeReference, delegateExpression) override val kind: UastSpecialExpressionKind get() = KotlinSpecialExpressionKinds.SUPER_DELEGATION }
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinSupertypeDelegationUExpression.kt
3743900658
// 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.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class FacetEntityImpl(val dataSource: FacetEntityData) : FacetEntity, WorkspaceEntityBase() { companion object { internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val UNDERLYINGFACET_CONNECTION_ID: ConnectionId = ConnectionId.create(FacetEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) val connections = listOf<ConnectionId>( MODULE_CONNECTION_ID, UNDERLYINGFACET_CONNECTION_ID, ) } override val name: String get() = dataSource.name override val module: ModuleEntity get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!! override val facetType: String get() = dataSource.facetType override val configurationXmlTag: String? get() = dataSource.configurationXmlTag override val moduleId: ModuleId get() = dataSource.moduleId override val underlyingFacet: FacetEntity? get() = snapshot.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: FacetEntityData?) : ModifiableWorkspaceEntityBase<FacetEntity>(), FacetEntity.Builder { constructor() : this(FacetEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity FacetEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isNameInitialized()) { error("Field FacetEntity#name should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) { error("Field FacetEntity#module should be initialized") } } else { if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) { error("Field FacetEntity#module should be initialized") } } if (!getEntityData().isFacetTypeInitialized()) { error("Field FacetEntity#facetType should be initialized") } if (!getEntityData().isModuleIdInitialized()) { error("Field FacetEntity#moduleId should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as FacetEntity this.entitySource = dataSource.entitySource this.name = dataSource.name this.facetType = dataSource.facetType this.configurationXmlTag = dataSource.configurationXmlTag this.moduleId = dataSource.moduleId if (parents != null) { this.module = parents.filterIsInstance<ModuleEntity>().single() this.underlyingFacet = parents.filterIsInstance<FacetEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var name: String get() = getEntityData().name set(value) { checkModificationAllowed() getEntityData().name = value changedProperty.add("name") } override var module: ModuleEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } else { this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value } changedProperty.add("module") } override var facetType: String get() = getEntityData().facetType set(value) { checkModificationAllowed() getEntityData().facetType = value changedProperty.add("facetType") } override var configurationXmlTag: String? get() = getEntityData().configurationXmlTag set(value) { checkModificationAllowed() getEntityData().configurationXmlTag = value changedProperty.add("configurationXmlTag") } override var moduleId: ModuleId get() = getEntityData().moduleId set(value) { checkModificationAllowed() getEntityData().moduleId = value changedProperty.add("moduleId") } override var underlyingFacet: FacetEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity } else { this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(UNDERLYINGFACET_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] = value } changedProperty.add("underlyingFacet") } override fun getEntityData(): FacetEntityData = result ?: super.getEntityData() as FacetEntityData override fun getEntityClass(): Class<FacetEntity> = FacetEntity::class.java } } class FacetEntityData : WorkspaceEntityData.WithCalculablePersistentId<FacetEntity>(), SoftLinkable { lateinit var name: String lateinit var facetType: String var configurationXmlTag: String? = null lateinit var moduleId: ModuleId fun isNameInitialized(): Boolean = ::name.isInitialized fun isFacetTypeInitialized(): Boolean = ::facetType.isInitialized fun isModuleIdInitialized(): Boolean = ::moduleId.isInitialized override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() result.add(moduleId) return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { index.index(this, moduleId) } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val removedItem_moduleId = mutablePreviousSet.remove(moduleId) if (!removedItem_moduleId) { index.index(this, moduleId) } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false val moduleId_data = if (moduleId == oldLink) { changed = true newLink as ModuleId } else { null } if (moduleId_data != null) { moduleId = moduleId_data } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FacetEntity> { val modifiable = FacetEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): FacetEntity { return getCached(snapshot) { val entity = FacetEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun persistentId(): PersistentEntityId<*> { return FacetId(name, facetType, moduleId) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return FacetEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return FacetEntity(name, facetType, moduleId, entitySource) { this.configurationXmlTag = [email protected] this.module = parents.filterIsInstance<ModuleEntity>().single() this.underlyingFacet = parents.filterIsInstance<FacetEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ModuleEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FacetEntityData if (this.entitySource != other.entitySource) return false if (this.name != other.name) return false if (this.facetType != other.facetType) return false if (this.configurationXmlTag != other.configurationXmlTag) return false if (this.moduleId != other.moduleId) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FacetEntityData if (this.name != other.name) return false if (this.facetType != other.facetType) return false if (this.configurationXmlTag != other.configurationXmlTag) return false if (this.moduleId != other.moduleId) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + name.hashCode() result = 31 * result + facetType.hashCode() result = 31 * result + configurationXmlTag.hashCode() result = 31 * result + moduleId.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + name.hashCode() result = 31 * result + facetType.hashCode() result = 31 * result + configurationXmlTag.hashCode() result = 31 * result + moduleId.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(ModuleId::class.java) collector.sameForAllEntities = true } }
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/FacetEntityImpl.kt
4015296815
package com.intellij.codeInspection.tests.kotlin.test.junit import com.intellij.codeInspection.tests.ULanguage import com.intellij.codeInspection.tests.test.junit.JUnitMalformedDeclarationInspectionTestBase import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ContentEntry import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.PsiTestUtil import com.intellij.util.PathUtil import java.io.File class KotlinJUnitMalformedDeclarationInspectionTest : JUnitMalformedDeclarationInspectionTestBase() { override fun getProjectDescriptor(): LightProjectDescriptor = object : JUnitProjectDescriptor(sdkLevel) { override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) { super.configureModule(module, model, contentEntry) val jar = File(PathUtil.getJarPathForClass(JvmStatic::class.java)) PsiTestUtil.addLibrary(model, "kotlin-stdlib", jar.parent, jar.name) } } /* Malformed extensions */ fun `test malformed extension no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class A { @org.junit.jupiter.api.extension.RegisterExtension val myRule5 = Rule5() class Rule5 : org.junit.jupiter.api.extension.Extension { } } """.trimIndent()) } fun `test malformed extension highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class A { @org.junit.jupiter.api.extension.RegisterExtension val <warning descr="'A.Rule5' should implement 'org.junit.jupiter.api.extension.Extension'">myRule5</warning> = Rule5() class Rule5 { } } """.trimIndent()) } /* Malformed nested class */ fun `test malformed nested no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class A { @org.junit.jupiter.api.Nested inner class B { } } """.trimIndent()) } fun `test malformed nested class highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class A { @org.junit.jupiter.api.Nested class <warning descr="Only non-static nested classes can serve as '@Nested' test classes">B</warning> { } } """.trimIndent()) } /* Malformed parameterized */ fun `test malformed parameterized no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ enum class TestEnum { FIRST, SECOND, THIRD } class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(ints = [1]) fun testWithIntValues(i: Int) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(longs = [1L]) fun testWithIntValues(i: Long) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(doubles = [0.5]) fun testWithDoubleValues(d: Double) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = [""]) fun testWithStringValues(s: String) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["foo"]) fun implicitParameter(argument: String, testReporter: org.junit.jupiter.api.TestInfo) { } @org.junit.jupiter.api.extension.ExtendWith(org.junit.jupiter.api.extension.TestExecutionExceptionHandler::class) annotation class RunnerExtension { } @RunnerExtension abstract class AbstractValueSource { } class ValueSourcesWithCustomProvider : AbstractValueSource() { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(ints = [1]) fun testWithIntValues(i: Int, fromExtension: String) { } } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["FIRST"]) fun implicitConversionEnum(e: TestEnum) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["1"]) fun implicitConversionString(i: Int) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["title"]) fun implicitConversionClass(book: Book) { } class Book(val title: String) { } } class MethodSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("stream") fun simpleStream(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("iterable") fun simpleIterable(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["stream", "iterator", "iterable"]) fun parametersArray(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["stream", "iterator"]) fun implicitValueArray(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["argumentsArrayProvider"]) fun argumentsArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["anyArrayProvider"]) fun anyArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["any2DArrayProvider"]) fun any2DArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("intStreamProvider") fun intStream(x: Int) { System.out.println(x) } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("intStreamProvider") fun injectTestReporter(x: Int, testReporter: org.junit.jupiter.api.TestReporter) { System.out.println("${'$'}x, ${'$'}testReporter") } companion object { @JvmStatic fun stream(): java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments>? { return null } @JvmStatic fun iterable(): Iterable<org.junit.jupiter.params.provider.Arguments>? { return null } @JvmStatic fun argumentsArrayProvider(): Array<org.junit.jupiter.params.provider.Arguments> { return arrayOf(org.junit.jupiter.params.provider.Arguments.of(1, "one")) } @JvmStatic fun anyArrayProvider(): Array<Any> { return arrayOf(org.junit.jupiter.params.provider.Arguments.of(1, "one")) } @JvmStatic fun any2DArrayProvider(): Array<Array<Any>> { return arrayOf(arrayOf(1, "s")) } @JvmStatic fun intStreamProvider(): java.util.stream.IntStream? { return null } } } @org.junit.jupiter.api.TestInstance(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS) class TestWithMethodSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("getParameters") public fun shouldExecuteWithParameterizedMethodSource(arguments: String) { } public fun getParameters(): java.util.stream.Stream<String> { return java.util.Arrays.asList( "Another execution", "Last execution").stream() } } class EnumSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource(names = ["FIRST"]) fun runTest(value: TestEnum) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource( value = TestEnum::class, names = ["regexp-value"], mode = org.junit.jupiter.params.provider.EnumSource.Mode.MATCH_ALL ) fun disable() { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource(value = TestEnum::class, names = ["SECOND", "FIRST"/*, "commented"*/]) fun array() { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource(TestEnum::class) fun testWithEnumSourceCorrect(value: TestEnum) { } } class CsvSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.CsvSource(value = ["src, 1"]) fun testWithCsvSource(first: String, second: Int) { } } class NullSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.NullSource fun testWithNullSrc(o: Any) { } } class EmptySource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EmptySource fun testFooSet(input: Set<String>) {} @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EmptySource fun testFooList(input: List<String>) {} @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EmptySource fun testFooMap(input: Map<String, String>) {} } """.trimIndent() ) } fun `test malformed parameterized value source wrong type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(booleans = [ <warning descr="No implicit conversion found to convert 'boolean' to 'int'">false</warning> ]) fun testWithBooleanSource(argument: Int) { } } """.trimIndent()) } fun `test malformed parameterized enum source wrong type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ enum class TestEnum { FIRST, SECOND, THIRD } class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource(<warning descr="No implicit conversion found to convert 'TestEnum' to 'int'">TestEnum::class</warning>) fun testWithEnumSource(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized multiple types`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.<warning descr="Exactly one type of input must be provided">ValueSource</warning>( ints = [1], strings = ["str"] ) fun testWithMultipleValues(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized no value defined`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.<warning descr="No value source is defined">ValueSource</warning>() fun testWithNoValues(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized no argument defined`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest <warning descr="'@NullSource' cannot provide an argument to method because method doesn't have parameters">@org.junit.jupiter.params.provider.NullSource</warning> fun testWithNullSrcNoParam() {} } """.trimIndent()) } fun `test method source in another class`() { myFixture.addFileToProject("SampleTest.kt", """" open class SampleTest { companion object { @kotlin.jvm.JvmStatic fun squares() : List<org.junit.jupiter.params.provider.Arguments> { return listOf( org.junit.jupiter.params.provider.Arguments.of(1, 1) ) } } }""".trimIndent()) myFixture.testHighlighting(ULanguage.JAVA, """ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; class MethodSourceUsage { @ParameterizedTest @MethodSource("SampleTest#squares") void testSquares(int input, int expected) {} } """.trimIndent()) } fun `test malformed parameterized value source multiple parameters`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["foo"]) fun <warning descr="Multiple parameters are not supported by this source">testWithMultipleParams</warning>(argument: String, i: Int) { } } """.trimIndent()) } fun `test malformed parameterized and test annotation defined`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(ints = [1]) @org.junit.jupiter.api.Test fun <warning descr="Suspicious combination of '@Test' and '@ParameterizedTest'">testWithTestAnnotation</warning>(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized and value source defined`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.provider.ValueSource(ints = [1]) @org.junit.jupiter.api.Test fun <warning descr="Suspicious combination of '@ValueSource' and '@Test'">testWithTestAnnotationNoParameterized</warning>(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized no argument source provided`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ArgumentsSources() fun <warning descr="No sources are provided, the suite would be empty">emptyArgs</warning>(param: String) { } } """.trimIndent()) } fun `test malformed parameterized method source should be static`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("<warning descr="Method source 'a' must be static">a</warning>") fun foo(param: String) { } fun a(): Array<String> { return arrayOf("a", "b") } } """.trimIndent()) } fun `test malformed parameterized method source should have no parameters`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("<warning descr="Method source 'a' should have no parameters">a</warning>") fun foo(param: String) { } companion object { @JvmStatic fun a(i: Int): Array<String> { return arrayOf("a", i.toString()) } } } """.trimIndent()) } fun `test malformed parameterized method source wrong return type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource( "<warning descr="Method source 'a' must have one of the following return types: 'Stream<?>', 'Iterator<?>', 'Iterable<?>' or 'Object[]'">a</warning>" ) fun foo(param: String) { } companion object { @JvmStatic fun a(): Any { return arrayOf("a", "b") } } } """.trimIndent()) } fun `test malformed parameterized method source not found`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("<warning descr="Cannot resolve target method source: 'a'">a</warning>") fun foo(param: String) { } } """.trimIndent()) } fun `test malformed parameterized enum source unresolvable entry`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class EnumSourceTest { private enum class Foo { AAA, AAX, BBB } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource( value = Foo::class, names = ["<warning descr="Can't resolve 'enum' constant reference.">invalid-value</warning>"], mode = org.junit.jupiter.params.provider.EnumSource.Mode.INCLUDE ) fun invalid() { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource( value = Foo::class, names = ["<warning descr="Can't resolve 'enum' constant reference.">invalid-value</warning>"] ) fun invalidDefault() { } } """.trimIndent()) } fun `test malformed parameterized add test instance quick fix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream; class Test { private fun parameters(): Stream<Arguments>? { return null; } @MethodSource("param<caret>eters") @ParameterizedTest fun foo(param: String) { } } """.trimIndent(), """ import org.junit.jupiter.api.TestInstance import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class Test { private fun parameters(): Stream<Arguments>? { return null; } @MethodSource("param<caret>eters") @ParameterizedTest fun foo(param: String) { } } """.trimIndent(), "Annotate as @TestInstance") } fun `test malformed parameterized introduce method source quick fix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource class Test { @MethodSource("para<caret>meters") @ParameterizedTest fun foo(param: String) { } } """.trimIndent(), """ import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream class Test { @MethodSource("parameters") @ParameterizedTest fun foo(param: String) { } companion object { @JvmStatic fun parameters(): Stream<Arguments> { TODO("Not yet implemented") } } } """.trimIndent(), "Add method 'parameters' to 'Test'") } fun `test malformed parameterized create csv source quick fix`() { val file = myFixture.addFileToProject("CsvFile.kt", """ class CsvFile { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.CsvFileSource(resources = "two-<caret>column.txt") fun testWithCsvFileSource(first: String, second: Int) { } } """.trimIndent()) myFixture.configureFromExistingVirtualFile(file.virtualFile) val intention = myFixture.findSingleIntention("Create file two-column.txt") assertNotNull(intention) myFixture.launchAction(intention) assertNotNull(myFixture.findFileInTempDir("two-column.txt")) } /* Malformed repeated test*/ fun `test malformed repeated test no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ object WithRepeated { @org.junit.jupiter.api.RepeatedTest(1) fun repeatedTestNoParams() { } @org.junit.jupiter.api.RepeatedTest(1) fun repeatedTestWithRepetitionInfo(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } @org.junit.jupiter.api.BeforeEach fun config(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } } class WithRepeatedAndCustomNames { @org.junit.jupiter.api.RepeatedTest(value = 1, name = "{displayName} {currentRepetition}/{totalRepetitions}") fun repeatedTestWithCustomName() { } } class WithRepeatedAndTestInfo { @org.junit.jupiter.api.BeforeEach fun beforeEach(testInfo: org.junit.jupiter.api.TestInfo, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {} @org.junit.jupiter.api.RepeatedTest(1) fun repeatedTestWithTestInfo(testInfo: org.junit.jupiter.api.TestInfo) { } @org.junit.jupiter.api.AfterEach fun afterEach(testInfo: org.junit.jupiter.api.TestInfo, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {} } class WithRepeatedAndTestReporter { @org.junit.jupiter.api.BeforeEach fun beforeEach(testReporter: org.junit.jupiter.api.TestReporter, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {} @org.junit.jupiter.api.RepeatedTest(1) fun repeatedTestWithTestInfo(testReporter: org.junit.jupiter.api.TestReporter) { } @org.junit.jupiter.api.AfterEach fun afterEach(testReporter: org.junit.jupiter.api.TestReporter, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {} } """.trimIndent()) } fun `test malformed repeated test combination of @Test and @RepeatedTest`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class WithRepeatedAndTests { @org.junit.jupiter.api.Test @org.junit.jupiter.api.RepeatedTest(1) fun <warning descr="Suspicious combination of '@Test' and '@RepeatedTest'">repeatedTestAndTest</warning>() { } } """.trimIndent()) } fun `test malformed repeated test with injected RepeatedInfo for @Test method`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class WithRepeatedInfoAndTest { @org.junit.jupiter.api.BeforeEach fun beforeEach(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } @org.junit.jupiter.api.Test fun <warning descr="Method 'nonRepeated' annotated with '@Test' should not declare parameter 'repetitionInfo'">nonRepeated</warning>(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } } """.trimIndent() ) } fun `test malformed repeated test with injected RepetitionInfo for @BeforeAll method`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class WithBeforeEach { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun <warning descr="Method 'beforeAllWithRepetitionInfo' annotated with '@BeforeAll' should not declare parameter 'repetitionInfo'">beforeAllWithRepetitionInfo</warning>(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } } } """.trimIndent()) } fun `test malformed repeated test with non-positive repetitions`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class WithRepeated { @org.junit.jupiter.api.RepeatedTest(<warning descr="The number of repetitions must be greater than zero">-1</warning>) fun repeatedTestNegative() { } @org.junit.jupiter.api.RepeatedTest(<warning descr="The number of repetitions must be greater than zero">0</warning>) fun repeatedTestBoundaryZero() { } } """.trimIndent()) } /* Malformed before after */ fun `test malformed before highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { @org.junit.Before fun <warning descr="Method 'before' annotated with '@Before' should be of type 'void' and not declare parameter 'i'">before</warning>(i: Int): String { return "${'$'}i" } } """.trimIndent()) } fun `test malformed before each highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { @org.junit.jupiter.api.BeforeEach fun <warning descr="Method 'beforeEach' annotated with '@BeforeEach' should be of type 'void' and not declare parameter 'i'">beforeEach</warning>(i: Int): String { return "" } } """.trimIndent()) } fun `test malformed before each remove private quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class MainTest { @org.junit.jupiter.api.BeforeEach private fun bef<caret>oreEach() { } } """.trimIndent(), """ import org.junit.jupiter.api.BeforeEach class MainTest { @BeforeEach fun bef<caret>oreEach(): Unit { } } """.trimIndent(), "Fix 'beforeEach' method signature") } fun `test malformed before class no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class BeforeClassStatic { companion object { @JvmStatic @org.junit.BeforeClass fun beforeClass() { } } } @org.junit.jupiter.api.TestInstance(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS) class BeforeAllTestInstancePerClass { @org.junit.jupiter.api.BeforeAll fun beforeAll() { } } class BeforeAllStatic { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun beforeAll() { } } } class TestParameterResolver : org.junit.jupiter.api.extension.ParameterResolver { override fun supportsParameter( parameterContext: org.junit.jupiter.api.extension.ParameterContext, extensionContext: org.junit.jupiter.api.extension.ExtensionContext ): Boolean = true override fun resolveParameter( parameterContext: org.junit.jupiter.api.extension.ParameterContext, extensionContext: org.junit.jupiter.api.extension.ExtensionContext ): Any = "" } @org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class) class ParameterResolver { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun beforeAll(foo: String) { println(foo) } } } @org.junit.jupiter.api.extension.ExtendWith(value = [TestParameterResolver::class]) class ParameterResolverArray { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun beforeAll(foo: String) { println(foo) } } } @org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class) open class AbstractTest { } class TestImplementation: AbstractTest() { @org.junit.jupiter.api.BeforeEach fun beforeEach(valueBox : String){ } } @org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class) annotation class CustomTestAnnotation @CustomTestAnnotation class MetaParameterResolver { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun beforeAll(foo: String) { println(foo) } } } """.trimIndent()) } fun `test malformed before class method that is non-static`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { @org.junit.BeforeClass fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be static">beforeClass</warning>() { } } """.trimIndent()) } fun `test malformed before class method that is not private`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.BeforeClass private fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be public">beforeClass</warning>() { } } } """.trimIndent()) } fun `test malformed before class method that has parameters`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.BeforeClass fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should not declare parameter 'i'">beforeClass</warning>(i: Int) { System.out.println(i) } } } """.trimIndent()) } fun `test malformed before class method with a non void return type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.BeforeClass fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be of type 'void'">beforeClass</warning>(): String { return "" } } } """.trimIndent()) } fun `test malformed before all method that is non-static`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { @org.junit.jupiter.api.BeforeAll fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be static">beforeAll</warning>() { } } """.trimIndent()) } fun `test malformed before all method that is not private`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll private fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be public">beforeAll</warning>() { } } } """.trimIndent()) } fun `test malformed before all method that has parameters`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should not declare parameter 'i'">beforeAll</warning>(i: Int) { System.out.println(i) } } } """.trimIndent()) } fun `test malformed before all method with a non void return type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be of type 'void'">beforeAll</warning>(): String { return "" } } } """.trimIndent()) } fun `test malformed before all quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ import org.junit.jupiter.api.BeforeAll class MainTest { @BeforeAll fun before<caret>All(i: Int): String { return "" } } """.trimIndent(), """ import org.junit.jupiter.api.BeforeAll class MainTest { companion object { @JvmStatic @BeforeAll fun beforeAll(): Unit { return "" } } } """.trimIndent(), "Fix 'beforeAll' method signature") } /* Malformed datapoint(s) */ fun `test malformed datapoint no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { companion object { @JvmField @org.junit.experimental.theories.DataPoint val f1: Any? = null } } """.trimIndent()) } fun `test malformed datapoint non-static highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { @JvmField @org.junit.experimental.theories.DataPoint val <warning descr="Field 'f1' annotated with '@DataPoint' should be static">f1</warning>: Any? = null } """.trimIndent()) } fun `test malformed datapoint non-public highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { companion object { @JvmStatic @org.junit.experimental.theories.DataPoint private val <warning descr="Field 'f1' annotated with '@DataPoint' should be public">f1</warning>: Any? = null } } """.trimIndent()) } fun `test malformed datapoint field highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoint private val <warning descr="Field 'f1' annotated with '@DataPoint' should be static and public">f1</warning>: Any? = null } """.trimIndent()) } fun `test malformed datapoint method highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoint private fun <warning descr="Method 'f1' annotated with '@DataPoint' should be static and public">f1</warning>(): Any? = null } """.trimIndent()) } fun `test malformed datapoints method highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoints private fun <warning descr="Method 'f1' annotated with '@DataPoints' should be static and public">f1</warning>(): Any? = null } """.trimIndent()) } fun `test malformed datapoint make field public quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class Test { companion object { @org.junit.experimental.theories.DataPoint val f<caret>1: Any? = null } } """.trimIndent(), """ class Test { companion object { @JvmField @org.junit.experimental.theories.DataPoint val f1: Any? = null } } """.trimIndent(), "Fix 'f1' field signature") } fun `test malformed datapoint make field public and static quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoint val f<caret>1: Any? = null } """.trimIndent(), """ class Test { companion object { @JvmField @org.junit.experimental.theories.DataPoint val f1: Any? = null } } """.trimIndent(), "Fix 'f1' field signature") } fun `test malformed datapoint make method public and static quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoint private fun f<caret>1(): Any? = null } """.trimIndent(), """ class Test { companion object { @JvmStatic @org.junit.experimental.theories.DataPoint fun f1(): Any? = null } } """.trimIndent(), "Fix 'f1' method signature") } /* Malformed setup/teardown */ fun `test malformed setup no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class C : junit.framework.TestCase() { override fun setUp() { } } """.trimIndent()) } fun `test malformed setup highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class C : junit.framework.TestCase() { private fun <warning descr="Method 'setUp' should be a non-private, non-static, have no parameters and be of type void">setUp</warning>(i: Int) { System.out.println(i) } } """.trimIndent()) } fun `test malformed setup quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class C : junit.framework.TestCase() { private fun set<caret>Up(i: Int) { } } """.trimIndent(), """ class C : junit.framework.TestCase() { fun setUp(): Unit { } } """.trimIndent(), "Fix 'setUp' method signature") } /* Malformed rule */ fun `test malformed rule field non-public highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } class PrivateRule { @org.junit.Rule var <warning descr="Field 'x' annotated with '@Rule' should be public">x</warning> = SomeTestRule() } """.trimIndent()) } fun `test malformed rule object inherited rule highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object OtherRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object ObjRule { @org.junit.Rule private var <warning descr="Field 'x' annotated with '@Rule' should be non-static and public">x</warning> = SomeTestRule() } class ClazzRule { @org.junit.Rule fun x() = OtherRule @org.junit.Rule fun <warning descr="Method 'y' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">y</warning>() = 0 @org.junit.Rule public fun z() = object : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } @org.junit.Rule public fun <warning descr="Method 'a' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">a</warning>() = object { } } """.trimIndent()) } fun `test malformed rule method static highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } class PrivateRule { @org.junit.Rule private fun <warning descr="Method 'x' annotated with '@Rule' should be public">x</warning>() = SomeTestRule() } """.trimIndent()) } fun `test malformed rule method non TestRule type highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class PrivateRule { @org.junit.Rule fun <warning descr="Method 'x' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">x</warning>() = 0 } """.trimIndent()) } fun `test malformed class rule field highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object PrivateClassRule { @org.junit.ClassRule private var <warning descr="Field 'x' annotated with '@ClassRule' should be public">x</warning> = SomeTestRule() @org.junit.ClassRule private var <warning descr="Field 'y' annotated with '@ClassRule' should be public and be of type 'org.junit.rules.TestRule'">y</warning> = 0 } """.trimIndent()) } fun `test malformed rule make field public quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class PrivateRule { @org.junit.Rule var x<caret> = 0 } """.trimIndent(), """ class PrivateRule { @JvmField @org.junit.Rule var x = 0 } """.trimIndent(), "Fix 'x' field signature") } fun `test malformed class rule make field public quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object PrivateClassRule { @org.junit.ClassRule private var x<caret> = SomeTestRule() } """.trimIndent(), """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object PrivateClassRule { @JvmField @org.junit.ClassRule var x = SomeTestRule() } """.trimIndent(), "Fix 'x' field signature") } /* Malformed test */ fun `test malformed test for JUnit 3 highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ public class JUnit3TestMethodIsPublicVoidNoArg : junit.framework.TestCase() { fun testOne() { } public fun <warning descr="Method 'testTwo' should be a public, non-static, have no parameters and be of type void">testTwo</warning>(): Int { return 2 } public fun <warning descr="Method 'testFour' should be a public, non-static, have no parameters and be of type void">testFour</warning>(i: Int) { println(i) } public fun testFive() { } private fun testSix(i: Int) { println(i) } //ignore when method doesn't look like test anymore companion object { @JvmStatic public fun <warning descr="Method 'testThree' should be a public, non-static, have no parameters and be of type void">testThree</warning>() { } } } """.trimIndent()) } fun `test malformed test for JUnit 4 highlighting`() { myFixture.addClass(""" package mockit; public @interface Mocked { } """.trimIndent()) myFixture.testHighlighting(ULanguage.KOTLIN, """ public class JUnit4TestMethodIsPublicVoidNoArg { @org.junit.Test fun testOne() { } @org.junit.Test public fun <warning descr="Method 'testTwo' annotated with '@Test' should be of type 'void'">testTwo</warning>(): Int { return 2 } @org.junit.Test public fun <warning descr="Method 'testFour' annotated with '@Test' should not declare parameter 'i'">testFour</warning>(i: Int) { } @org.junit.Test public fun testFive() { } @org.junit.Test public fun testMock(@mockit.Mocked s: String) { } companion object { @JvmStatic @org.junit.Test public fun <warning descr="Method 'testThree' annotated with '@Test' should be non-static">testThree</warning>() { } } } """.trimIndent()) } fun `test malformed test for JUnit 4 runWith highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ @org.junit.runner.RunWith(org.junit.runner.Runner::class) class JUnit4RunWith { @org.junit.Test public fun <warning descr="Method 'testMe' annotated with '@Test' should be of type 'void' and not declare parameter 'i'">testMe</warning>(i: Int): Int { return -1 } } """.trimIndent()) } /* Malformed suite */ fun `test malformed suite no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Junit3Suite : junit.framework.TestCase() { companion object { @JvmStatic fun suite() = junit.framework.TestSuite() } } """.trimIndent()) } fun `test malformed suite highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Junit3Suite : junit.framework.TestCase() { fun <warning descr="Method 'suite' should be a non-private, static and have no parameters">suite</warning>() = junit.framework.TestSuite() } """.trimIndent()) } fun `test malformed suite quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class Junit3Suite : junit.framework.TestCase() { fun sui<caret>te() = junit.framework.TestSuite() } """.trimIndent(), """ class Junit3Suite : junit.framework.TestCase() { companion object { @JvmStatic fun suite() = junit.framework.TestSuite() } } """.trimIndent(), "Fix 'suite' method signature") } /* Suspending test function */ fun `test malformed suspending test JUnit 3 function`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class JUnit3Test : junit.framework.TestCase() { suspend fun <warning descr="Method 'testFoo' should not be a suspending function">testFoo</warning>() { } } """.trimIndent()) } fun `test malformed suspending test JUnit 4 function`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class JUnit4Test { @org.junit.Test suspend fun <warning descr="Method 'testFoo' annotated with '@Test' should not be a suspending function">testFoo</warning>() { } } """.trimIndent()) } fun `test malformed suspending test JUnit 5 function`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class JUnit5Test { @org.junit.jupiter.api.Test suspend fun <warning descr="Method 'testFoo' annotated with '@Test' should not be a suspending function">testFoo</warning>() { } } """.trimIndent()) } }
jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/test/junit/KotlinJUnitMalformedDeclarationInspectionTest.kt
497845357
// 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.intentions.declarations import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiMethodCallExpression import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.SmartList import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getReturnTypeReference import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.util.* import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.addIfNotNull private val LOG = Logger.getInstance(ConvertMemberToExtensionIntention::class.java) class ConvertMemberToExtensionIntention : SelfTargetingRangeIntention<KtCallableDeclaration>( KtCallableDeclaration::class.java, KotlinBundle.lazyMessage("convert.member.to.extension") ), LowPriorityAction { private fun isApplicable(element: KtCallableDeclaration): Boolean { val classBody = element.parent as? KtClassBody ?: return false if (classBody.parent !is KtClass) return false if (element.receiverTypeReference != null) return false if (element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false when (element) { is KtProperty -> if (element.hasInitializer() || element.hasDelegate()) return false is KtSecondaryConstructor -> return false } return true } override fun applicabilityRange(element: KtCallableDeclaration): TextRange? { if (!element.withExpectedActuals().all { it is KtCallableDeclaration && isApplicable(it) }) return null return (element.nameIdentifier ?: return null).textRange } override fun startInWriteAction() = false //TODO: local class override fun applyTo(element: KtCallableDeclaration, editor: Editor?) { if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return var allowExpected = true element.liftToExpected()?.actualsForExpected()?.let { if (it.isEmpty()) { allowExpected = askIfExpectedIsAllowed(element.containingKtFile) } } val (extension, bodyTypeToSelect) = createExtensionCallableAndPrepareBodyToSelect(element, allowExpected) runWriteAction { editor?.apply { unblockDocument() if (extension.isValid) { if (bodyTypeToSelect != GeneratedBodyType.NOTHING) { val bodyToSelect = getBodyForSelection(extension, bodyTypeToSelect) if (bodyToSelect != null) { val range = bodyToSelect.textRange moveCaret(range.startOffset, ScrollType.CENTER) val parent = bodyToSelect.parent val lastSibling = if (parent is KtBlockExpression) parent.rBrace?.siblings(forward = false, withItself = false)?.first { it !is PsiWhiteSpace } else bodyToSelect.siblings(forward = true, withItself = false).lastOrNull() val endOffset = lastSibling?.endOffset ?: range.endOffset selectionModel.setSelection(range.startOffset, endOffset) } else { LOG.error("Extension created with new method body but this body was not found after document commit. Extension text: \"${extension.text}\"") moveCaret(extension.textOffset, ScrollType.CENTER) } } else { moveCaret(extension.textOffset, ScrollType.CENTER) } } else { LOG.error("Extension invalidated during document commit. Extension text \"${extension.text}\"") } } } } private fun getBodyForSelection(extension: KtCallableDeclaration, bodyTypeToSelect: GeneratedBodyType): KtExpression? { fun selectBody(declaration: KtDeclarationWithBody): KtExpression? { if (!declaration.hasBody()) return extension return declaration.bodyExpression?.let { (it as? KtBlockExpression)?.statements?.singleOrNull() ?: it } } return when (bodyTypeToSelect) { GeneratedBodyType.FUNCTION -> (extension as? KtFunction)?.let { selectBody(it) } GeneratedBodyType.GETTER -> (extension as? KtProperty)?.getter?.let { selectBody(it) } GeneratedBodyType.SETTER -> (extension as? KtProperty)?.setter?.let { selectBody(it) } else -> null } } private enum class GeneratedBodyType { NOTHING, FUNCTION, SETTER, GETTER } private fun processSingleDeclaration( element: KtCallableDeclaration, allowExpected: Boolean ): Pair<KtCallableDeclaration, GeneratedBodyType> { val descriptor = element.unsafeResolveToDescriptor() val containingClass = descriptor.containingDeclaration as ClassDescriptor val isEffectivelyExpected = allowExpected && element.isExpectDeclaration() val file = element.containingKtFile val project = file.project val outermostParent = KtPsiUtil.getOutermostParent(element, file, false) val ktFilesToAddImports = LinkedHashSet<KtFile>() val javaCallsToFix = SmartList<PsiMethodCallExpression>() for (ref in ReferencesSearch.search(element)) { when (ref) { is KtReference -> { val refFile = ref.element.containingKtFile if (refFile != file) { ktFilesToAddImports.add(refFile) } } is PsiReferenceExpression -> javaCallsToFix.addIfNotNull(ref.parent as? PsiMethodCallExpression) } } val typeParameterList = newTypeParameterList(element) val psiFactory = KtPsiFactory(project) val (extension, bodyTypeToSelect) = runWriteAction { val extension = file.addAfter(element, outermostParent) as KtCallableDeclaration file.addAfter(psiFactory.createNewLine(), outermostParent) file.addAfter(psiFactory.createNewLine(), outermostParent) element.delete() extension.setReceiverType(containingClass.defaultType) if (typeParameterList != null) { if (extension.typeParameterList != null) { extension.typeParameterList!!.replace(typeParameterList) } else { extension.addBefore(typeParameterList, extension.receiverTypeReference) extension.addBefore(psiFactory.createWhiteSpace(), extension.receiverTypeReference) } } extension.modifierList?.getModifier(KtTokens.PROTECTED_KEYWORD)?.delete() extension.modifierList?.getModifier(KtTokens.ABSTRACT_KEYWORD)?.delete() extension.modifierList?.getModifier(KtTokens.OPEN_KEYWORD)?.delete() extension.modifierList?.getModifier(KtTokens.FINAL_KEYWORD)?.delete() if (isEffectivelyExpected && !extension.hasExpectModifier()) { extension.addModifier(KtTokens.EXPECT_KEYWORD) } var bodyTypeToSelect = GeneratedBodyType.NOTHING val bodyText = getFunctionBodyTextFromTemplate( project, if (extension is KtFunction) TemplateKind.FUNCTION else TemplateKind.PROPERTY_INITIALIZER, extension.name, extension.getReturnTypeReference()?.text ?: "Unit", extension.containingClassOrObject?.fqName ) when (extension) { is KtFunction -> { if (!extension.hasBody() && !isEffectivelyExpected) { //TODO: methods in PSI for setBody extension.add(psiFactory.createBlock(bodyText)) bodyTypeToSelect = GeneratedBodyType.FUNCTION } } is KtProperty -> { val templateProperty = psiFactory.createDeclaration<KtProperty>("var v: Any\nget()=$bodyText\nset(value){\n$bodyText\n}") if (!isEffectivelyExpected) { val templateGetter = templateProperty.getter!! val templateSetter = templateProperty.setter!! var getter = extension.getter if (getter == null) { getter = extension.addAfter(templateGetter, extension.typeReference) as KtPropertyAccessor extension.addBefore(psiFactory.createNewLine(), getter) bodyTypeToSelect = GeneratedBodyType.GETTER } else if (!getter.hasBody()) { getter = getter.replace(templateGetter) as KtPropertyAccessor bodyTypeToSelect = GeneratedBodyType.GETTER } if (extension.isVar) { var setter = extension.setter if (setter == null) { setter = extension.addAfter(templateSetter, getter) as KtPropertyAccessor extension.addBefore(psiFactory.createNewLine(), setter) if (bodyTypeToSelect == GeneratedBodyType.NOTHING) { bodyTypeToSelect = GeneratedBodyType.SETTER } } else if (!setter.hasBody()) { setter.replace(templateSetter) as KtPropertyAccessor if (bodyTypeToSelect == GeneratedBodyType.NOTHING) { bodyTypeToSelect = GeneratedBodyType.SETTER } } } } } } extension to bodyTypeToSelect } if (ktFilesToAddImports.isNotEmpty()) { val newDescriptor = extension.unsafeResolveToDescriptor() val importInsertHelper = ImportInsertHelper.getInstance(project) for (ktFileToAddImport in ktFilesToAddImports) { importInsertHelper.importDescriptor(ktFileToAddImport, newDescriptor) } } if (javaCallsToFix.isNotEmpty()) { val lightMethod = extension.toLightMethods().first() for (javaCallToFix in javaCallsToFix) { javaCallToFix.methodExpression.qualifierExpression?.let { val argumentList = javaCallToFix.argumentList argumentList.addBefore(it, argumentList.expressions.firstOrNull()) } val newRef = javaCallToFix.methodExpression.bindToElement(lightMethod) JavaCodeStyleManager.getInstance(project).shortenClassReferences(newRef) } } return extension to bodyTypeToSelect } private fun askIfExpectedIsAllowed(file: KtFile): Boolean { if (isUnitTestMode()) { return file.allChildren.any { it is PsiComment && it.text.trim() == "// ALLOW_EXPECT_WITHOUT_ACTUAL" } } return Messages.showYesNoDialog( KotlinBundle.message("do.you.want.to.make.new.extension.an.expected.declaration"), text, Messages.getQuestionIcon() ) == Messages.YES } private fun createExtensionCallableAndPrepareBodyToSelect( element: KtCallableDeclaration, allowExpected: Boolean = true ): Pair<KtCallableDeclaration, GeneratedBodyType> { val expectedDeclaration = element.liftToExpected() as? KtCallableDeclaration if (expectedDeclaration != null) { element.withExpectedActuals().filterIsInstance<KtCallableDeclaration>().forEach { if (it != element) { processSingleDeclaration(it, allowExpected) } } } val classVisibility = element.containingClass()?.visibilityModifierType() val (extension, bodyTypeToSelect) = processSingleDeclaration(element, allowExpected) if (classVisibility != null && extension.visibilityModifier() == null) { runWriteAction { extension.addModifier(classVisibility) } } return extension to bodyTypeToSelect } private fun newTypeParameterList(member: KtCallableDeclaration): KtTypeParameterList? { val classElement = member.parent.parent as KtClass val classParams = classElement.typeParameters if (classParams.isEmpty()) return null val allTypeParameters = classParams + member.typeParameters val text = allTypeParameters.joinToString(",", "<", ">") { it.textWithoutVariance() } return KtPsiFactory(member.project).createDeclaration<KtFunction>("fun $text foo()").typeParameterList } private fun KtTypeParameter.textWithoutVariance(): String { if (variance == Variance.INVARIANT) return text val copied = this.copy() as KtTypeParameter copied.modifierList?.getModifier(KtTokens.OUT_KEYWORD)?.delete() copied.modifierList?.getModifier(KtTokens.IN_KEYWORD)?.delete() return copied.text } companion object { fun convert(element: KtCallableDeclaration): KtCallableDeclaration = ConvertMemberToExtensionIntention().createExtensionCallableAndPrepareBodyToSelect(element).first } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/declarations/ConvertMemberToExtensionIntention.kt
2221314472
/* * Copyright (C) 2022 Square, 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 okhttp3.internal.connection /** * Used when we were unsuccessful in the planning phase of a connection: * * * A DNS lookup failed * * The configuration is incapable of carrying the request, such as when the client is configured * to use `H2_PRIOR_KNOWLEDGE` but the URL's scheme is `https:`. * * Preemptive proxy authentication failed. * * Planning failures are not necessarily fatal. For example, even if we can't DNS lookup the first * proxy in a list, looking up a subsequent one may succeed. */ internal class FailedPlan(e: Throwable) : RoutePlanner.Plan { val result = RoutePlanner.ConnectResult(plan = this, throwable = e) override val isReady = false override fun connectTcp() = result override fun connectTlsEtc() = result override fun handleSuccess() = error("unexpected call") override fun cancel() = error("unexpected cancel") override fun retry() = error("unexpected retry") }
okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/FailedPlan.kt
177753607
package io.github.chrislo27.rhre3.desktop import com.beust.jcommander.Parameter class Arguments { @Parameter(names = ["--help", "-h", "-?"], description = "Prints this usage menu.", help = true) var printHelp: Boolean = false // ----------------------------------------------------------- @Parameter(names = ["--force-lazy-sound-load"], description = "Forces lazy-loaded sounds to be loaded when initialized.") var lazySoundsForceLoad: Boolean = false @Parameter(names = ["--fps"], description = "Manually sets the target FPS. Will always be at least 30.") var fps: Int = 60 @Parameter(names = ["--log-missing-localizations"], description = "Logs any missing localizations. Other locales are checked against the default properties file.") var logMissingLocalizations: Boolean = false @Parameter(names = ["--skip-git"], description = "Skips checking the online Git repository for the SFX Database completely. This is overridden by --force-git-check.") var skipGit: Boolean = false @Parameter(names = ["--force-git-fetch"], description = "Forces a fetch for the online Git repository for the SFX Database.") var forceGitFetch: Boolean = false @Parameter(names = ["--force-git-check"], description = "Forces checking the online Git repository for the SFX Database.") var forceGitCheck: Boolean = false @Parameter(names = ["--verify-sfxdb"], description = "Verifies and reports warnings/errors for the entire SFX Database after loading.") var verifySfxdb: Boolean = false @Parameter(names = ["--no-analytics"], description = "Disables sending of analytics and crash reports.") var noAnalytics: Boolean = false @Parameter(names = ["--no-online-counter"], description = "Disables the online user count feature.") var noOnlineCounter: Boolean = false @Parameter(names = ["--output-generated-datamodels"], description = "Writes out games that are generated internally in JSON format to console on start-up.") var outputGeneratedDatamodels: Boolean = false @Parameter(names = ["--output-custom-sfx"], description = "Writes out custom SFX that don't have data.json (i.e.: just sound files in a folder) in JSON format to console on start-up.") var outputCustomSfx: Boolean = false @Parameter(names = ["--show-tapalong-markers"], description = "Shows tapalong tap markers by default.") var showTapalongMarkers: Boolean = false @Parameter(names = ["--midi-recording"], description = "Enables MIDI recording, a hidden feature. Using a MIDI device while the remix is playing will write notes to the remix.") var midiRecording: Boolean = false @Parameter(names = ["--portable-mode"], description = "Puts the `.rhre3/` folder and preferences locally next to the RHRE.jar file.") var portableMode: Boolean = false @Parameter(names = ["--disable-custom-sounds"], description = "Disables loading of custom sounds.") var disableCustomSounds: Boolean = false @Parameter(names = ["--trigger-update-screen"], description = "Triggers the \"new version available\" screen on startup. Requires that the latest version be known, however.") var triggerUpdateScreen: Boolean = false // ----------------------------------------------------------- @Parameter(names = ["--immmediate-anniversary"], hidden = true) var eventImmediateAnniversary: Boolean = false @Parameter(names = ["--immmediate-anniversary-like-new"], hidden = true) var eventImmediateAnniversaryLikeNew: Boolean = false @Parameter(names = ["--immmediate-xmas"], hidden = true) var eventImmediateXmas: Boolean = false // ----------------------------------------------------------- @Parameter(names = ["--lc"], hidden = true) var lc: String? = null }
desktop/src/main/kotlin/io/github/chrislo27/rhre3/desktop/Arguments.kt
3092601290
package org.stepik.android.data.mobile_tiers.source import io.reactivex.Completable import io.reactivex.Single import org.stepik.android.domain.mobile_tiers.model.LightSku interface LightSkuCacheDataSource { fun getLightInventory(skuIds: List<String>): Single<List<LightSku>> fun saveLightInventory(lightSkus: List<LightSku>): Completable }
app/src/main/java/org/stepik/android/data/mobile_tiers/source/LightSkuCacheDataSource.kt
2373221807
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.robotservices.scheduling import android.util.Log import com.neatorobotics.sdk.android.clients.Resource import com.neatorobotics.sdk.android.clients.nucleo.Nucleo import com.neatorobotics.sdk.android.clients.nucleo.json.NucleoJSONParser import com.neatorobotics.sdk.android.models.Robot import com.neatorobotics.sdk.android.models.RobotSchedule import com.neatorobotics.sdk.android.models.ScheduleEvent import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.ArrayList class SchedulingAdvanced2Service : SchedulingService() { override val cleaningModeSupported: Boolean get() = true override val singleZoneSupported: Boolean get() = false override val multipleZoneSupported: Boolean get() = true override suspend fun getSchedule(robot: Robot): Resource<RobotSchedule> { val result = nucleoRepository.executeCommand(robot, JSONObject(Nucleo.GET_ROBOT_SCHEDULE_COMMAND)) return when(result.status) { Resource.Status.SUCCESS -> Resource.success(NucleoJSONParser.parseSchedule(result.data)) else -> Resource.error(result.code, result.message) } } override suspend fun setSchedule(robot: Robot, schedule: RobotSchedule): Resource<Boolean> { val command = Nucleo.SET_SCHEDULE_COMMAND.replace("EVENTS_PLACEHOLDER", "events:" + convertEventsToJSON(schedule.events, true)) val result = nucleoRepository.executeCommand(robot, JSONObject(command)) return when(result.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(result.code, result.message) } } private fun convertEventsToJSON(events: ArrayList<ScheduleEvent>, toSendToTheRobot: Boolean): String { val array = JSONArray() for (i in events.indices) { array.put(convertEventToJSON(events[i], toSendToTheRobot)) } return array.toString() } fun convertEventToJSON(event: ScheduleEvent, toSendToTheRobot: Boolean = false): JSONObject? { val json = JSONObject() try { json.put("mode", event.mode.value) json.put("day", event.day) json.put("startTime", event.startTime) if (toSendToTheRobot) { if (event.boundaryIds?.size != null && event.boundaryIds?.size!! > 0) { val ids = JSONArray() for(b in event.boundaryIds!!) ids.put(b) json.put("boundaryIds", ids) } } else { if (event.boundaryIds?.size != null && event.boundaryIds?.size!! > 0) { val boundaries = JSONArray() for((id, name) in event.boundaryIds!!.zip(event.boundaryNames!!)) { val b = JSONObject().apply { put("id", id) put("name", name) } boundaries.put(b) } json.put("boundaries", boundaries) } if (!event.mapId.isNullOrEmpty()) { json.put("mapId", event.mapId) } } } catch (e: JSONException) { Log.e(TAG, "Exception", e) return null } return json } companion object { private const val TAG = "SchedulingAdv2Service" } }
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/scheduling/SchedulingAdvanced2Service.kt
2498432497
package io.github.chrislo27.toolboks.util interface CloseListener { /** * @return True if we can close the application */ fun attemptClose(): Boolean }
core/src/main/kotlin/io/github/chrislo27/toolboks/util/CloseListener.kt
2145314459
package main import common.OsUtils import javafx.application.Application import javafx.application.Platform import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.fxml.FXMLLoader import javafx.scene.Node import javafx.stage.Stage import network.client.NetClient import ui.StageController import ui.debugmenu.DebugMenu import ui.notification.NotificationController import java.awt.* import java.io.IOException import java.util.ArrayList /** * Created by brian on 8/29/15. */ class PushLocal : Application() { var trayIcon: TrayIcon? = null val icon: Image = Toolkit.getDefaultToolkit().getImage(javaClass.getResource("/PL.png")) private val filteredNotifications: ObservableList<String> = FXCollections.observableArrayList<String>() private val stageController: StageController = StageController() private val notificationNodes: ArrayList<Node> = ArrayList() private val logger = SimpleStringProperty("Application initializing...") private var netClient: NetClient? = null init { singleton = this; } @Throws(Exception::class) override fun start(primaryStage: Stage) { addToSystemTray() primaryStage.close() // Get rid of useless init stage stageController.stage = DebugMenu(filteredNotifications, logger, 1024, 768, notificationNodes) stageController.stage?.icons?.add(javafx.scene.image.Image("PL.png")) stageController.showStage() log("Application initialized") if (trayIcon != null) trayIcon!!.addActionListener { e -> Platform.runLater { stageController.showStage() } } netClient = NetClient(this) netClient!!.isDaemon = true netClient!!.start() postNotification("PushLocal.Desktop", "Test", "First Line", "Second Line") } private fun addToSystemTray() { if (SystemTray.isSupported()) { val systemTray = SystemTray.getSystemTray() trayIcon = TrayIcon(icon, "Push Local") trayIcon!!.isImageAutoSize = true try { systemTray.add(trayIcon) } catch (e: AWTException) { log(e.message as String) } } } @Synchronized fun log(text: String) { Platform.runLater { logger.value = logger.valueSafe + "\n" + text } } // main & TCP thread @Synchronized @Throws(IOException::class) fun postNotification(origin: String, title: String, text: String, subText: String) { var filtered = false for (s in filteredNotifications) { if (s.contains(origin)) filtered = true } if (!filtered) { OsUtils.postNotification(title, text, subText) var loader: FXMLLoader = FXMLLoader(javaClass.getResource("/notification.fxml")) val notification = loader.load<Node>() val controller = loader.getController<NotificationController>() controller.origin = origin controller.setTitle(title) controller.setText(text) controller.setSubText(if (subText.contains("null")) "" else subText) notificationNodes.add(notification) if (stageController.stage is DebugMenu) { println("Is intance of debugMenu") Platform.runLater { (stageController.stage as DebugMenu).addNotification(notification) } } } } fun addFilteredNotification(origin: String) { filteredNotifications.add(origin) } @Throws(Exception::class) override fun stop() { super.stop() netClient?.dispose() if (trayIcon != null) SystemTray.getSystemTray().remove(trayIcon) } companion object { var singleton : PushLocal? = null get() { return field } set(value) { if (singleton == null) { field = value } } @JvmStatic fun main(args: Array<String>) { launch(PushLocal::class.java) } } }
src/main/PushLocal.kt
4108704637
package io.github.ranolp.kubo.telegram.bot.objects class ReplyMarkup {}
Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/bot/objects/ReplyMarkup.kt
3789767490
// 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.idea.maven.importing.worktree import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.* import org.jetbrains.idea.maven.importing.MavenFoldersImporter import org.jetbrains.idea.maven.importing.MavenModelUtil import org.jetbrains.idea.maven.model.MavenArtifact import org.jetbrains.idea.maven.model.MavenConstants import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.project.MavenProjectsTree import org.jetbrains.idea.maven.project.SupportedRequestType import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer class WorkspaceModuleImporter(private val project: Project, private val mavenProject: MavenProject, private val projectsTree: MavenProjectsTree, private val diff: WorkspaceEntityStorageBuilder) { private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private lateinit var moduleEntity: ModuleEntity fun importModule() { val dependencies = collectDependencies(); moduleEntity = diff.addModuleEntity(mavenProject.displayName, dependencies, MavenExternalSource.INSTANCE) val contentRootEntity = diff.addContentRootEntity(virtualFileManager.fromPath(mavenProject.directory), emptyList(), emptyList(), moduleEntity) importFolders(contentRootEntity) importLanguageLevel(); } private fun importLanguageLevel() { } private fun collectDependencies(): List<ModuleDependencyItem> { val dependencyTypes = MavenProjectsManager.getInstance(project).importingSettings.dependencyTypesAsSet; dependencyTypes.addAll(mavenProject.getDependencyTypesFromImporters(SupportedRequestType.FOR_IMPORT)) return listOf(ModuleDependencyItem.ModuleSourceDependency, ModuleDependencyItem.InheritedSdkDependency) + mavenProject.dependencies.filter { dependencyTypes.contains(it.type) }.mapNotNull(this::createDependency) } private fun createDependency(artifact: MavenArtifact): ModuleDependencyItem? { val depProject = projectsTree.findProject(artifact.mavenId) if (depProject == null) { if (artifact.scope == "system") { return createSystemDependency(artifact) } if (artifact.type == "bundle") { return addBundleDependency(artifact) } return createLibraryDependency(artifact) } if (depProject === mavenProject) { return null } if (projectsTree.isIgnored(depProject)) { TODO() } return createModuleDependency(artifact, depProject) } private fun addBundleDependency(artifact: MavenArtifact): ModuleDependencyItem? { val newArtifact = MavenArtifact( artifact.groupId, artifact.artifactId, artifact.version, artifact.baseVersion, "jar", artifact.classifier, artifact.scope, artifact.isOptional, "jar", null, mavenProject.getLocalRepository(), false, false ); return createLibraryDependency(newArtifact); } private fun createSystemDependency(artifact: MavenArtifact): ModuleDependencyItem.Exportable.LibraryDependency { assert(MavenConstants.SCOPE_SYSTEM == artifact.scope) val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)), LibraryRootTypeId.COMPILED)) val libraryTableId = LibraryTableId.ModuleLibraryTableId(moduleId = ModuleId(mavenProject.displayName)); //(ModuleId(moduleEntity.name)) diff.addLibraryEntity(artifact.libraryName, libraryTableId, roots, emptyList(), MavenExternalSource.INSTANCE) return ModuleDependencyItem.Exportable.LibraryDependency(LibraryId(artifact.libraryName, libraryTableId), false, toEntityScope(artifact.scope)) } private fun createModuleDependency(artifact: MavenArtifact, depProject: MavenProject): ModuleDependencyItem { val isTestJar = MavenConstants.TYPE_TEST_JAR == artifact.type || "tests" == artifact.classifier return ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(depProject.displayName), false, toEntityScope(artifact.scope), isTestJar) } private fun createLibraryDependency(artifact: MavenArtifact): ModuleDependencyItem.Exportable.LibraryDependency { assert(MavenConstants.SCOPE_SYSTEM != artifact.scope) if (!libraryExists(artifact)) { addLibraryToProjectTable(artifact) } val libraryTableId = LibraryTableId.ProjectLibraryTableId; //(ModuleId(moduleEntity.name)) return ModuleDependencyItem.Exportable.LibraryDependency(LibraryId(artifact.libraryName, libraryTableId), false, toEntityScope(artifact.scope)) } private fun libraryExists(artifact: MavenArtifact): Boolean { return diff.entities(LibraryEntity::class.java).any { it.name == artifact.libraryName } } private fun addLibraryToProjectTable(artifact: MavenArtifact): LibraryEntity { val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)), LibraryRootTypeId.COMPILED)) roots.add( LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "javadoc", "jar")), JAVADOC_TYPE)) roots.add( LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "sources", "jar")), LibraryRootTypeId.SOURCES)) val libraryTableId = LibraryTableId.ProjectLibraryTableId; //(ModuleId(moduleEntity.name)) return diff.addLibraryEntity(artifact.libraryName, libraryTableId, roots, emptyList(), MavenExternalSource.INSTANCE) } private fun importFolders(contentRootEntity: ContentRootEntity) { MavenFoldersImporter.getSourceFolders(mavenProject).forEach { entry -> val serializer = (JpsModelSerializerExtension.getExtensions() .flatMap { it.moduleSourceRootPropertiesSerializers } .firstOrNull { it.type == entry.value }) as? JpsModuleSourceRootPropertiesSerializer ?: error("Module source root type ${entry}.value is not registered as JpsModelSerializerExtension") val sourceRootEntity = diff.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(VfsUtilCore.pathToUrl(entry.key)), entry.value.isForTests, serializer.typeId, MavenExternalSource.INSTANCE) when (entry.value) { is JavaSourceRootType -> diff.addJavaSourceRootEntity(sourceRootEntity, false, "") is JavaResourceRootType -> diff.addJavaResourceRootEntity(sourceRootEntity, false, "") else -> TODO() } } } fun toEntityScope(mavenScope: String): ModuleDependencyItem.DependencyScope { if (MavenConstants.SCOPE_RUNTIME == mavenScope) return ModuleDependencyItem.DependencyScope.RUNTIME if (MavenConstants.SCOPE_TEST == mavenScope) return ModuleDependencyItem.DependencyScope.TEST return if (MavenConstants.SCOPE_PROVIDED == mavenScope) ModuleDependencyItem.DependencyScope.PROVIDED else ModuleDependencyItem.DependencyScope.COMPILE } companion object { internal val JAVADOC_TYPE: LibraryRootTypeId = LibraryRootTypeId("JAVADOC") } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/worktree/WorkspaceModuleImporter.kt
388286590
package ch.difty.scipamato.publ.entity data class Keyword( val id: Int = 0, val keywordId: Int = 0, val langCode: String? = null, val name: String? = null, val searchOverride: String? = null, ) : PublicDbEntity { val displayValue: String? get() = name companion object { private const val serialVersionUID = 1L } }
public/public-entity/src/main/kotlin/ch/difty/scipamato/publ/entity/Keyword.kt
1576685481
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.stash.ui import com.intellij.dvcs.ui.RepositoryChangesBrowserNode import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.ui.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.SimpleTextAttributes import com.intellij.util.Processor import com.intellij.vcs.log.Hash import git4idea.i18n.GitBundle import git4idea.repo.GitRepositoryManager import git4idea.stash.GitStashCache import git4idea.stash.GitStashTracker import git4idea.stash.GitStashTrackerListener import git4idea.stash.ui.GitStashUi.Companion.GIT_STASH_UI_PLACE import git4idea.ui.StashInfo import org.jetbrains.annotations.NonNls import java.util.stream.Stream import javax.swing.event.TreeExpansionEvent import javax.swing.event.TreeExpansionListener import javax.swing.event.TreeSelectionEvent import javax.swing.tree.TreePath import kotlin.streams.toList class GitStashTree(project: Project, parentDisposable: Disposable) : ChangesTree(project, false, false) { private val stashTracker get() = project.service<GitStashTracker>() private val stashCache get() = project.service<GitStashCache>() init { isKeepTreeState = true isScrollToSelection = false setEmptyText(GitBundle.message("stash.empty.text")) doubleClickHandler = Processor { e -> val diffAction = ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_DIFF_COMMON) val dataContext = DataManager.getInstance().getDataContext(this) val event = AnActionEvent.createFromAnAction(diffAction, e, GIT_STASH_UI_PLACE, dataContext) val isEnabled = ActionUtil.lastUpdateAndCheckDumb(diffAction, event, true) if (isEnabled) performActionDumbAwareWithCallbacks(diffAction, event) isEnabled } project.messageBus.connect(parentDisposable).subscribe(GitStashCache.GIT_STASH_LOADED, object : GitStashCache.StashLoadedListener { override fun stashLoaded(root: VirtualFile, hash: Hash) { rebuildTree() } }) stashTracker.addListener(object : GitStashTrackerListener { override fun stashesUpdated() { rebuildTree() } }, parentDisposable) addTreeExpansionListener(object : TreeExpansionListener { override fun treeExpanded(event: TreeExpansionEvent) { loadStash(event.path) } override fun treeCollapsed(event: TreeExpansionEvent) = Unit }) addTreeSelectionListener { event: TreeSelectionEvent -> loadStash(event.path) } } private fun loadStash(treePath: TreePath) { val node = treePath.lastPathComponent as? ChangesBrowserNode<*> ?: return val stashInfo = node.userObject as? StashInfo ?: return stashCache.loadStashData(stashInfo) } override fun rebuildTree() { val modelBuilder = TreeModelBuilder(project, groupingSupport.grouping) val stashesMap = stashTracker.stashes for ((root, stashesList) in stashesMap) { val rootNode = if (stashesMap.size > 1) { createRootNode(root).also { modelBuilder.insertSubtreeRoot(it) } } else { modelBuilder.myRoot } when (stashesList) { is GitStashTracker.Stashes.Error -> { modelBuilder.insertErrorNode(stashesList.error, rootNode) } is GitStashTracker.Stashes.Loaded -> { for (stash in stashesList.stashes) { val stashNode = StashInfoChangesBrowserNode(stash) modelBuilder.insertSubtreeRoot(stashNode, rootNode) when (val stashData = stashCache.getCachedStashData(stash)) { is GitStashCache.StashData.ChangeList -> { modelBuilder.insertChanges(stashData.changeList.changes, stashNode) } is GitStashCache.StashData.Error -> { modelBuilder.insertErrorNode(stashData.error, stashNode) } null -> { modelBuilder.insertSubtreeRoot(ChangesBrowserStringNode(IdeBundle.message("treenode.loading")), stashNode) } } } } } } updateTreeModel(modelBuilder.build()) } private fun createRootNode(root: VirtualFile): ChangesBrowserNode<*> { val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(root) ?: return ChangesBrowserNode.createFile(project, root) return RepositoryChangesBrowserNode(repository) } private fun TreeModelBuilder.insertErrorNode(error: VcsException, parent: ChangesBrowserNode<*>) { val errorNode = ChangesBrowserStringNode(error.localizedMessage, SimpleTextAttributes.ERROR_ATTRIBUTES) insertSubtreeRoot(errorNode, parent) } override fun resetTreeState() { expandDefaults() } override fun installGroupingSupport(): ChangesGroupingSupport { val groupingSupport = object : ChangesGroupingSupport(myProject, this, false) { override fun isAvailable(groupingKey: String): Boolean { return groupingKey != REPOSITORY_GROUPING && super.isAvailable(groupingKey) } } installGroupingSupport(this, groupingSupport, GROUPING_PROPERTY_NAME, *DEFAULT_GROUPING_KEYS) return groupingSupport } override fun getData(dataId: String): Any? { if (STASH_INFO.`is`(dataId)) return selectedStashes().toList() if (GIT_STASH_TREE_FLAG.`is`(dataId)) return true return VcsTreeModelData.getData(myProject, this, dataId) ?: super.getData(dataId) } private fun selectedStashes(): Stream<StashInfo> { return VcsTreeModelData.selected(this).userObjectsStream(StashInfo::class.java) } class StashInfoChangesBrowserNode(private val stash: StashInfo) : ChangesBrowserNode<StashInfo>(stash) { override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) { renderer.append(stash.stash, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) renderer.append(": ") stash.branch?.let { renderer.append(it, SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES) renderer.append(": ") } renderer.append(stash.message) } override fun getTextPresentation(): String = stash.stash override fun shouldExpandByDefault() = false } companion object { val GIT_STASH_TREE_FLAG = DataKey.create<Boolean>("GitStashTreeFlag") @NonNls private const val GROUPING_PROPERTY_NAME = "GitStash.ChangesTree.GroupingKeys" } }
plugins/git4idea/src/git4idea/stash/ui/GitStashTree.kt
2156593268
package org.mrlem.happycows.ui.screens import com.badlogic.gdx.Gdx import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import org.mrlem.happycows.common.rx.addTo // TODO - medium - inheriting from AbstractScreen is dodgy, at best /** * @author Sébastien Guillemin <[email protected]> */ abstract class AbstractChoregrapher<S : AbstractScreen?>( protected val screen: S ) : AbstractScreen(screen!!.game) { private val disposeOnDispose = CompositeDisposable() override fun render(delta: Float) { // no call to super doUpdate(delta) doRender(delta) } override fun dispose() { disposeOnDispose.clear() super.dispose() } fun <T> Observable<T>.bind() = subscribe( { Unit }, { Gdx.app.log("ui", "choregrapher observable failed", it) } ) .addTo(disposeOnDispose) }
core/src/org/mrlem/happycows/ui/screens/AbstractChoregrapher.kt
1588341338
package pl.edu.amu.wmi.erykandroidcommon.recycler.grouping enum class ListItemType constructor(val type: Int) { TYPE_HEADER(0), TYPE_ITEM(1) }
src/main/java/pl/edu/amu/wmi/erykandroidcommon/recycler/grouping/ListItemType.kt
4190327464
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.nativ.libbcm_host import org.freedesktop.jaccall.Lib import org.freedesktop.jaccall.Ptr import javax.inject.Singleton @Singleton @Lib("bcm_host") class Libbcm_host { external fun bcm_host_init() external fun vc_dispmanx_display_get_info(display: Int, @Ptr pinfo: Long): Int /** * Opens a display on the given device * @param device c * * * * * @return */ external fun vc_dispmanx_display_open(device: Int): Int /** * Start a new update, DISPMANX_NO_HANDLE on error * @param priority * * * * * @return */ external fun vc_dispmanx_update_start(priority: Int): Int /** * Add an elment to a display as part of an update */ external fun vc_dispmanx_element_add(update: Int, display: Int, layer: Int, @Ptr dest_rect: Long, src: Int, @Ptr src_rect: Long, protection: Int, @Ptr alpha: Long, @Ptr clamp: Long, transform: Int): Int /** * End an update and wait for it to complete */ external fun vc_dispmanx_update_submit_sync(update: Int): Int external fun vc_dispmanx_rect_set(@Ptr rect: Long, x_offset: Int, y_offset: Int, width: Int, height: Int): Int external fun graphics_get_display_size(display_number: Int, @Ptr width: Long, @Ptr height: Long): Int companion object { val DISPMANX_ID_MAIN_LCD = 0 val DISPMANX_ID_AUX_LCD = 1 val DISPMANX_ID_HDMI = 2 val DISPMANX_ID_SDTV = 3 val DISPMANX_ID_FORCE_LCD = 4 val DISPMANX_ID_FORCE_TV = 5 val DISPMANX_ID_FORCE_OTHER = 6/* non-default display */ val DISPMANX_PROTECTION_MAX = 0x0f val DISPMANX_PROTECTION_NONE = 0 val DISPMANX_PROTECTION_HDCP = 11 val DISPMANX_FLAGS_ALPHA_FROM_SOURCE = 0 val DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS = 1 val DISPMANX_FLAGS_ALPHA_FIXED_NON_ZERO = 2 val DISPMANX_FLAGS_ALPHA_FIXED_EXCEED_0X07 = 3 val DISPMANX_FLAGS_ALPHA_PREMULT = 1 shl 16 val DISPMANX_FLAGS_ALPHA_MIX = 1 shl 17 val DISPMANX_NO_ROTATE = 0 val DISPMANX_ROTATE_90 = 1 val DISPMANX_ROTATE_180 = 2 val DISPMANX_ROTATE_270 = 3 val DISPMANX_FLIP_HRIZ = 1 shl 16 val DISPMANX_FLIP_VERT = 1 shl 17 /* invert left/right images */ val DISPMANX_STEREOSCOPIC_INVERT = 1 shl 19 /* extra flags for controlling 3d duplication behaviour */ val DISPMANX_STEREOSCOPIC_NONE = 0 shl 20 val DISPMANX_STEREOSCOPIC_MONO = 1 shl 20 val DISPMANX_STEREOSCOPIC_SBS = 2 shl 20 val DISPMANX_STEREOSCOPIC_TB = 3 shl 20 val DISPMANX_STEREOSCOPIC_MASK = 15 shl 20 /* extra flags for controlling snapshot behaviour */ val DISPMANX_SNAPSHOT_NO_YUV = 1 shl 24 val DISPMANX_SNAPSHOT_NO_RGB = 1 shl 25 val DISPMANX_SNAPSHOT_FILL = 1 shl 26 val DISPMANX_SNAPSHOT_SWAP_RED_BLUE = 1 shl 27 val DISPMANX_SNAPSHOT_PACK = 1 shl 28 val VCOS_DISPLAY_INPUT_FORMAT_INVALID = 0 val VCOS_DISPLAY_INPUT_FORMAT_RGB888 = 1 val VCOS_DISPLAY_INPUT_FORMAT_RGB565 = 2 } }
compositor/src/main/kotlin/org/westford/nativ/libbcm_host/Libbcm_host.kt
2882139287
package jetbrains.buildServer.dotcover import jetbrains.buildServer.agent.runner.ParameterType import jetbrains.buildServer.agent.runner.ParametersService import jetbrains.buildServer.dotnet.CoverageConstants import java.util.* class CoverageFilterProviderImpl( private val _parametersService: ParametersService, private val _coverageFilterConverter: DotCoverFilterConverter) : CoverageFilterProvider { override val filters: Sequence<CoverageFilter> get() { val filters = ArrayList<CoverageFilter>() _parametersService.tryGetParameter(ParameterType.Runner, CoverageConstants.PARAM_DOTCOVER_FILTERS)?.let { for (filter in _coverageFilterConverter.convert(it).map { toModuleFilter(it) }) { filters.add(filter) } } if (filters.size == 0) { filters.addAll(0, DefaultIncludeFilters) } addAdditionalAnyFilterWhenHasOutdatedAnyFilter(filters, CoverageFilter.CoverageFilterType.Include) addAdditionalAnyFilterWhenHasOutdatedAnyFilter(filters, CoverageFilter.CoverageFilterType.Exclude) filters.addAll(DefaultExcludeFilters) return filters.asSequence() } override val attributeFilters: Sequence<CoverageFilter> get() = sequence { _parametersService.tryGetParameter(ParameterType.Runner, CoverageConstants.PARAM_DOTCOVER_ATTRIBUTE_FILTERS)?.let { for (filter in _coverageFilterConverter.convert(it).map { toAttributeFilter(it) }) { if (filter.type == CoverageFilter.CoverageFilterType.Exclude && CoverageFilter.Any != filter.classMask) { yield(filter) } } } yieldAll(DefaultExcludeAttributeFilters) } private fun addAdditionalAnyFilterWhenHasOutdatedAnyFilter(filters: MutableList<CoverageFilter>, type: CoverageFilter.CoverageFilterType) { val outdatedFilter = CoverageFilter(type, CoverageFilter.Any, "*.*", CoverageFilter.Any, CoverageFilter.Any) val additionalFilter = CoverageFilter(type, CoverageFilter.Any, CoverageFilter.Any, CoverageFilter.Any, CoverageFilter.Any) val anyIncludeFilter = filters.indexOf(outdatedFilter) if (anyIncludeFilter >= 0) { filters.add(anyIncludeFilter, additionalFilter) } } private fun getMask(mask: String, defaultMask: String): String { if (CoverageFilter.Any == mask) { return defaultMask } return mask } private fun toModuleFilter(filter: CoverageFilter): CoverageFilter { return CoverageFilter( filter.type, CoverageFilter.Any, getMask(filter.moduleMask, filter.defaultMask), filter.classMask, filter.functionMask) } private fun toAttributeFilter(filter: CoverageFilter): CoverageFilter { return CoverageFilter( filter.type, CoverageFilter.Any, CoverageFilter.Any, getMask(filter.classMask, filter.defaultMask), CoverageFilter.Any) } companion object { internal val DefaultIncludeFilters = listOf(CoverageFilter(CoverageFilter.CoverageFilterType.Include, CoverageFilter.Any, CoverageFilter.Any, CoverageFilter.Any, CoverageFilter.Any)) internal val DefaultExcludeFilters = listOf( CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, "TeamCity.VSTest.TestAdapter", CoverageFilter.Any, CoverageFilter.Any), CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, "TeamCity.MSBuild.Logger", CoverageFilter.Any, CoverageFilter.Any), CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, CoverageFilter.Any, "AutoGeneratedProgram", CoverageFilter.Any)) internal val DefaultExcludeAttributeFilters = listOf( CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, CoverageFilter.Any, "System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute", CoverageFilter.Any)) } }
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotcover/CoverageFilterProviderImpl.kt
1098544710
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.http.codec.json import kotlinx.serialization.Serializable import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.core.Ordered import org.springframework.core.ResolvableType import org.springframework.core.io.buffer.DataBuffer import org.springframework.core.testfixture.codec.AbstractDecoderTests import org.springframework.http.MediaType import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.test.StepVerifier import reactor.test.StepVerifier.FirstStep import java.lang.UnsupportedOperationException import java.nio.charset.Charset import java.nio.charset.StandardCharsets /** * Tests for the JSON decoding using kotlinx.serialization. * * @author Sebastien Deleuze */ class KotlinSerializationJsonDecoderTests : AbstractDecoderTests<KotlinSerializationJsonDecoder>(KotlinSerializationJsonDecoder()) { @Suppress("UsePropertyAccessSyntax", "DEPRECATION") @Test override fun canDecode() { val jsonSubtype = MediaType("application", "vnd.test-micro-type+json") assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), MediaType.APPLICATION_JSON)).isTrue() assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), jsonSubtype)).isTrue() assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), null)).isTrue() assertThat(decoder.canDecode(ResolvableType.forClass(String::class.java), null)).isFalse() assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), MediaType.APPLICATION_XML)).isFalse() assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), MediaType("application", "json", StandardCharsets.UTF_8))).isTrue() assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), MediaType("application", "json", StandardCharsets.US_ASCII))).isTrue() assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), MediaType("application", "json", StandardCharsets.ISO_8859_1))).isTrue() assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(List::class.java, Int::class.java), MediaType.APPLICATION_JSON)).isTrue() assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(List::class.java, Ordered::class.java), MediaType.APPLICATION_JSON)).isFalse() assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(List::class.java, Pojo::class.java), MediaType.APPLICATION_JSON)).isTrue() assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(ArrayList::class.java, Int::class.java), MediaType.APPLICATION_JSON)).isTrue() assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(ArrayList::class.java, Int::class.java), MediaType.APPLICATION_PDF)).isFalse() assertThat(decoder.canDecode(ResolvableType.forClass(Ordered::class.java), MediaType.APPLICATION_JSON)).isFalse() assertThat(decoder.canDecode(ResolvableType.NONE, MediaType.APPLICATION_JSON)).isFalse() } @Test override fun decode() { val output = decoder.decode(Mono.empty(), ResolvableType.forClass(Pojo::class.java), null, emptyMap()) StepVerifier .create(output) .expectError(UnsupportedOperationException::class.java) } @Test override fun decodeToMono() { val input = Flux.concat( stringBuffer("[{\"bar\":\"b1\",\"foo\":\"f1\"},"), stringBuffer("{\"bar\":\"b2\",\"foo\":\"f2\"}]")) val elementType = ResolvableType.forClassWithGenerics(List::class.java, Pojo::class.java) testDecodeToMonoAll(input, elementType, { step: FirstStep<Any> -> step .expectNext(listOf(Pojo("f1", "b1"), Pojo("f2", "b2"))) .expectComplete() .verify() }, null, null) } private fun stringBuffer(value: String): Mono<DataBuffer> { return stringBuffer(value, StandardCharsets.UTF_8) } private fun stringBuffer(value: String, charset: Charset): Mono<DataBuffer> { return Mono.defer { val bytes = value.toByteArray(charset) val buffer = bufferFactory.allocateBuffer(bytes.size) buffer.write(bytes) Mono.just(buffer) } } @Serializable data class Pojo(val foo: String, val bar: String, val pojo: Pojo? = null) }
spring-web/src/test/kotlin/org/springframework/http/codec/json/KotlinSerializationJsonDecoderTests.kt
456680462
// 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 io.netty.bootstrap import io.netty.channel.Channel import io.netty.channel.ChannelFuture object BootstrapUtil { @Throws(Throwable::class) fun initAndRegister(channel: Channel, bootstrap: Bootstrap): ChannelFuture { try { bootstrap.init(channel) } catch (e: Throwable) { channel.unsafe().closeForcibly() throw e } val registrationFuture = bootstrap.group().register(channel) if (registrationFuture.cause() != null) { if (channel.isRegistered) { channel.close() } else { channel.unsafe().closeForcibly() } } return registrationFuture } }
platform/platform-util-io/src/BootstrapUtil.kt
1703619843
package org.http4k.aws.lambda import org.http4k.core.HttpHandler /** * Http4k app loader - instantiate the application from the environment config */ interface AppLoader : (Map<String, String>) -> HttpHandler
http4k-aws/src/main/kotlin/org/http4k/aws/lambda/AppLoader.kt
449767559
// 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 training.learn.lesson.general import com.intellij.psi.PsiComment import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import training.dsl.LessonContext import training.dsl.LessonSample import training.dsl.TaskRuntimeContext import training.learn.LessonsBundle import training.learn.course.KLesson class SingleLineCommentLesson(private val sample: LessonSample) : KLesson("Comment line", LessonsBundle.message("comment.line.lesson.name")) { override val lessonContent: LessonContext.() -> Unit get() = { fun TaskRuntimeContext.countCommentedLines(): Int = calculateComments(PsiDocumentManager.getInstance(project).getPsiFile(editor.document)!!) prepareSample(sample) actionTask("CommentByLineComment") { LessonsBundle.message("comment.line.comment.any.line", action(it)) } task("CommentByLineComment") { text(LessonsBundle.message("comment.line.uncomment.that.line", action(it))) trigger(it, { countCommentedLines() }, { _, now -> now == 0 }) test { actions("EditorUp", it) } } task("CommentByLineComment") { text(LessonsBundle.message("comment.line.comment.several.lines", action(it))) trigger(it, { countCommentedLines() }, { before, now -> now >= before + 2 }) test { actions("EditorDownWithSelection", "EditorDownWithSelection", it) } } } private fun calculateComments(psiElement: PsiElement): Int { return when { psiElement is PsiComment -> 1 psiElement.children.isEmpty() -> 0 else -> { var result = 0 for (astChild in psiElement.node.getChildren(null)) { val psiChild = astChild.psi result += calculateComments(psiChild) } result } } } }
plugins/ide-features-trainer/src/training/learn/lesson/general/SingleLineCommentLesson.kt
385084641
/* * 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 androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.macrobenchmark_codelab.R import com.example.macrobenchmark_codelab.model.OrderLine import com.example.macrobenchmark_codelab.model.SnackRepo import com.example.macrobenchmark_codelab.model.SnackbarManager import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow /** * Holds the contents of the cart and allows changes to it. * * TODO: Move data to Repository so it can be displayed and changed consistently throughout the app. */ class CartViewModel( private val snackbarManager: SnackbarManager, snackRepository: SnackRepo ) : ViewModel() { private val _orderLines: MutableStateFlow<List<OrderLine>> = MutableStateFlow(snackRepository.getCart()) val orderLines: StateFlow<List<OrderLine>> get() = _orderLines // Logic to show errors every few requests private var requestCount = 0 private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0 fun increaseSnackCount(snackId: Long) { if (!shouldRandomlyFail()) { val currentCount = _orderLines.value.first { it.snack.id == snackId }.count updateSnackCount(snackId, currentCount + 1) } else { snackbarManager.showMessage(R.string.cart_increase_error) } } fun decreaseSnackCount(snackId: Long) { if (!shouldRandomlyFail()) { val currentCount = _orderLines.value.first { it.snack.id == snackId }.count if (currentCount == 1) { // remove snack from cart removeSnack(snackId) } else { // update quantity in cart updateSnackCount(snackId, currentCount - 1) } } else { snackbarManager.showMessage(R.string.cart_decrease_error) } } fun removeSnack(snackId: Long) { _orderLines.value = _orderLines.value.filter { it.snack.id != snackId } } private fun updateSnackCount(snackId: Long, count: Int) { _orderLines.value = _orderLines.value.map { if (it.snack.id == snackId) { it.copy(count = count) } else { it } } } /** * Factory for CartViewModel that takes SnackbarManager as a dependency */ companion object { fun provideFactory( snackbarManager: SnackbarManager = SnackbarManager, snackRepository: SnackRepo = SnackRepo ): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return CartViewModel(snackbarManager, snackRepository) as T } } } }
benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/home/cart/CartViewModel.kt
2205189217
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte.widget import android.content.Context import android.util.AttributeSet import android.view.MotionEvent /** * Created by moko256 on 2018/02/18. * * @author moko256 */ class ViewPager : androidx.viewpager.widget.ViewPager { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { return try { super.onInterceptTouchEvent(ev) } catch (ignore: IllegalArgumentException) { false } } }
app/src/main/java/com/github/moko256/twitlatte/widget/ViewPager.kt
1496696101
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.util interface UByteList { operator fun get(index: Int): Int operator fun set(index: Int, value: Int) }
platform/platform-impl/src/com/intellij/diagnostic/hprof/util/UByteList.kt
4092942301
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.ml.md.kotlin.barcodedetection import android.content.DialogInterface import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.FragmentManager import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.google.firebase.ml.md.R import com.google.firebase.ml.md.kotlin.camera.WorkflowModel import com.google.firebase.ml.md.kotlin.camera.WorkflowModel.WorkflowState /** Displays the bottom sheet to present barcode fields contained in the detected barcode. */ class BarcodeResultFragment : BottomSheetDialogFragment() { override fun onCreateView( layoutInflater: LayoutInflater, viewGroup: ViewGroup?, bundle: Bundle? ): View { val view = layoutInflater.inflate(R.layout.barcode_bottom_sheet, viewGroup) val arguments = arguments val barcodeFieldList: ArrayList<BarcodeField> = if (arguments?.containsKey(ARG_BARCODE_FIELD_LIST) == true) { arguments.getParcelableArrayList(ARG_BARCODE_FIELD_LIST) ?: ArrayList() } else { Log.e(TAG, "No barcode field list passed in!") ArrayList() } view.findViewById<RecyclerView>(R.id.barcode_field_recycler_view).apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(activity) adapter = BarcodeFieldAdapter(barcodeFieldList) } return view } override fun onDismiss(dialogInterface: DialogInterface) { activity?.let { // Back to working state after the bottom sheet is dismissed. ViewModelProviders.of(it).get<WorkflowModel>(WorkflowModel::class.java) .setWorkflowState(WorkflowState.DETECTING) } super.onDismiss(dialogInterface) } companion object { private const val TAG = "BarcodeResultFragment" private const val ARG_BARCODE_FIELD_LIST = "arg_barcode_field_list" fun show(fragmentManager: FragmentManager, barcodeFieldArrayList: ArrayList<BarcodeField>) { val barcodeResultFragment = BarcodeResultFragment() barcodeResultFragment.arguments = Bundle().apply { putParcelableArrayList(ARG_BARCODE_FIELD_LIST, barcodeFieldArrayList) } barcodeResultFragment.show(fragmentManager, TAG) } fun dismiss(fragmentManager: FragmentManager) { (fragmentManager.findFragmentByTag(TAG) as BarcodeResultFragment?)?.dismiss() } } }
app/src/main/java/com/google/firebase/ml/md/kotlin/barcodedetection/BarcodeResultFragment.kt
2011139527
/* * Copyright (C) 2016 MGaetan89 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.kolumbus.activity import android.content.Context import io.realm.RealmModel class TableActivity { companion object { fun start(context: Context, table: Class<out RealmModel>?) = Unit fun <T : RealmModel> start(context: Context, table: Class<out T>?, items: Array<out T>?) = Unit } }
kolumbus-no-op/src/main/kotlin/io/kolumbus/activity/TableActivity.kt
2801342298
// TARGET_BACKEND: JVM // FILE: test.kt // WITH_RUNTIME // LANGUAGE_VERSION: 1.2 import kotlin.test.* operator fun A.inc() = A() fun box(): String { assertFailsWith<IllegalArgumentException> { var aNull = A.n() aNull++ } return "OK" } // FILE: A.java public class A { public static A n() { return null; } }
backend.native/tests/external/codegen/box/javaInterop/notNullAssertions/incWithNullabilityAssertionOnExtensionReceiver_lv12.kt
2522380188
typealias BoolArray = Array<Boolean> typealias IArray = IntArray typealias MyArray<T> = Array<T> fun box(): String { val ba = BoolArray(1) { true } if (!ba[0]) return "Fail #1" val ia = IArray(1) { 42 } if (ia[0] != 42) return "Fail #2" val ma = MyArray<Int>(1) { 42 } if (ma[0] != 42) return "Fail #2" return "OK" }
backend.native/tests/external/codegen/box/typealias/typeAliasConstructorForArray.kt
357575014
/* * Copyright (C) 2019 Square, 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 app.cash.paparazzi.internal import app.cash.paparazzi.Snapshot import app.cash.paparazzi.TestName import com.squareup.moshi.FromJson import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.ToJson import com.squareup.moshi.Types import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter import java.util.Date internal object PaparazziJson { val moshi = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter()) .add(this) .build()!! val listOfShotsAdapter: JsonAdapter<List<Snapshot>> = moshi .adapter<List<Snapshot>>( Types.newParameterizedType(List::class.java, Snapshot::class.java) ) .indent(" ") val listOfStringsAdapter: JsonAdapter<List<String>> = moshi .adapter<List<String>>( Types.newParameterizedType(List::class.java, String::class.java) ) .indent(" ") @ToJson fun testNameToJson(testName: TestName): String { return "${testName.packageName}.${testName.className}#${testName.methodName}" } @FromJson fun testNameFromJson(json: String): TestName { val regex = Regex("(.*)\\.([^.]*)#([^.]*)") val (packageName, className, methodName) = regex.matchEntire(json)!!.destructured return TestName(packageName, className, methodName) } }
external/paparazzi/paparazzi/src/main/java/app/cash/paparazzi/internal/PaparazziJson.kt
2045380049
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.pager import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.DecayAnimationSpec import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.Spring import androidx.compose.animation.core.calculateTargetValue import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.animation.rememberSplineBasedDecay import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.ScrollScope import androidx.compose.foundation.gestures.snapping.SnapFlingBehavior import androidx.compose.foundation.gestures.snapping.SnapLayoutInfoProvider import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyList import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.remember import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.filter /** * A Pager that scrolls horizontally. Pages are lazily placed in accordance to the available * viewport size. You can use [beyondBoundsPageCount] to place more pages before and after the * visible pages. * @param pageCount The number of pages this Pager will contain * @param modifier A modifier instance to be applied to this Pager outer layout * @param state The state to control this pager * @param contentPadding a padding around the whole content. This will add padding for the * content after it has been clipped, which is not possible via [modifier] param. You can use it * to add a padding before the first page or after the last one. Use [pageSpacing] to add spacing * between the pages. * @param pageSize Use this to change how the pages will look like inside this pager. * @param beyondBoundsPageCount Pages to load before and after the list of visible * pages. Note: Be aware that using a large value for [beyondBoundsPageCount] will cause a lot of * pages to be composed, measured and placed which will defeat the purpose of using Lazy loading. * This should be used as an optimization to pre-load a couple of pages before and after the visible * ones. * @param pageSpacing The amount of space to be used to separate the pages in this Pager * @param verticalAlignment How pages are aligned vertically in this Pager. * @param flingBehavior The [FlingBehavior] to be used for post scroll gestures. * @param userScrollEnabled whether the scrolling via the user gestures or accessibility actions * is allowed. You can still scroll programmatically using [PagerState.scroll] even when it is * disabled. * @param reverseLayout reverse the direction of scrolling and layout. * @param pageContent This Pager's page Composable. */ @Composable @ExperimentalFoundationApi internal fun HorizontalPager( pageCount: Int, modifier: Modifier = Modifier, state: PagerState = rememberPagerState(), contentPadding: PaddingValues = PaddingValues(0.dp), pageSize: PageSize = PageSize.Fill, beyondBoundsPageCount: Int = 0, pageSpacing: Dp = 0.dp, verticalAlignment: Alignment.Vertical = Alignment.CenterVertically, flingBehavior: SnapFlingBehavior = PagerDefaults.flingBehavior(state = state), userScrollEnabled: Boolean = true, reverseLayout: Boolean = false, pageContent: @Composable (page: Int) -> Unit ) { Pager( modifier = modifier, state = state, pageCount = pageCount, pageSpacing = pageSpacing, userScrollEnabled = userScrollEnabled, orientation = Orientation.Horizontal, verticalAlignment = verticalAlignment, reverseLayout = reverseLayout, contentPadding = contentPadding, beyondBoundsPageCount = beyondBoundsPageCount, pageSize = pageSize, flingBehavior = flingBehavior, pageContent = pageContent ) } /** * A Pager that scrolls vertically. Tha backing mechanism for this is a LazyList, therefore * pages are lazily placed in accordance to the available viewport size. You can use * [beyondBoundsPageCount] to place more pages before and after the visible pages. * * @param pageCount The number of pages this Pager will contain * @param modifier A modifier instance to be apply to this Pager outer layout * @param state The state to control this pager * @param contentPadding a padding around the whole content. This will add padding for the * content after it has been clipped, which is not possible via [modifier] param. You can use it * to add a padding before the first page or after the last one. Use [pageSpacing] to add spacing * between the pages. * @param pageSize Use this to change how the pages will look like inside this pager. * @param beyondBoundsPageCount Pages to load before and after the list of visible * pages. Note: Be aware that using a large value for [beyondBoundsPageCount] will cause a lot of * pages to be composed, measured and placed which will defeat the purpose of using Lazy loading. * This should be used as an optimization to pre-load a couple of pages before and after the visible * ones. * @param pageSpacing The amount of space to be used to separate the pages in this Pager * @param horizontalAlignment How pages are aligned horizontally in this Pager. * @param flingBehavior The [FlingBehavior] to be used for post scroll gestures. * @param userScrollEnabled whether the scrolling via the user gestures or accessibility actions * is allowed. You can still scroll programmatically using [PagerState.scroll] even when it is * disabled. * @param reverseLayout reverse the direction of scrolling and layout. * @param pageContent This Pager's page Composable. */ @Composable @ExperimentalFoundationApi internal fun VerticalPager( pageCount: Int, modifier: Modifier = Modifier, state: PagerState = rememberPagerState(), contentPadding: PaddingValues = PaddingValues(0.dp), pageSize: PageSize = PageSize.Fill, beyondBoundsPageCount: Int = 0, pageSpacing: Dp = 0.dp, horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally, flingBehavior: SnapFlingBehavior = PagerDefaults.flingBehavior(state = state), userScrollEnabled: Boolean = true, reverseLayout: Boolean = false, pageContent: @Composable (page: Int) -> Unit ) { Pager( modifier = modifier, state = state, pageCount = pageCount, pageSpacing = pageSpacing, horizontalAlignment = horizontalAlignment, userScrollEnabled = userScrollEnabled, orientation = Orientation.Vertical, reverseLayout = reverseLayout, contentPadding = contentPadding, beyondBoundsPageCount = beyondBoundsPageCount, pageSize = pageSize, flingBehavior = flingBehavior, pageContent = pageContent ) } @OptIn(ExperimentalFoundationApi::class) @Composable internal fun Pager( modifier: Modifier, state: PagerState, pageCount: Int, pageSize: PageSize, pageSpacing: Dp, orientation: Orientation, beyondBoundsPageCount: Int, verticalAlignment: Alignment.Vertical = Alignment.CenterVertically, horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally, contentPadding: PaddingValues, flingBehavior: SnapFlingBehavior, userScrollEnabled: Boolean, reverseLayout: Boolean, pageContent: @Composable (page: Int) -> Unit ) { require(beyondBoundsPageCount >= 0) { "beyondBoundsPageCount should be greater than or equal to 0, " + "you selected $beyondBoundsPageCount" } val isVertical = orientation == Orientation.Vertical val density = LocalDensity.current val layoutDirection = LocalLayoutDirection.current val calculatedContentPaddings = remember(contentPadding, orientation, layoutDirection) { calculateContentPaddings( contentPadding, orientation, layoutDirection ) } val pagerFlingBehavior = remember(flingBehavior, state) { PagerWrapperFlingBehavior(flingBehavior, state) } LaunchedEffect(density, state, pageSpacing) { with(density) { state.pageSpacing = pageSpacing.roundToPx() } } LaunchedEffect(state) { snapshotFlow { state.isScrollInProgress } .filter { !it } .drop(1) // Initial scroll is false .collect { state.updateOnScrollStopped() } } BoxWithConstraints(modifier = modifier) { val mainAxisSize = if (isVertical) constraints.maxHeight else constraints.maxWidth // Calculates how pages are shown across the main axis val pageAvailableSize = remember( density, mainAxisSize, pageSpacing, calculatedContentPaddings ) { with(density) { val pageSpacingPx = pageSpacing.roundToPx() val contentPaddingPx = calculatedContentPaddings.roundToPx() with(pageSize) { density.calculateMainAxisPageSize( mainAxisSize - contentPaddingPx, pageSpacingPx ) }.toDp() } } val horizontalAlignmentForSpacedArrangement = if (!reverseLayout) Alignment.Start else Alignment.End val verticalAlignmentForSpacedArrangement = if (!reverseLayout) Alignment.Top else Alignment.Bottom LazyList( modifier = Modifier, state = state.lazyListState, contentPadding = contentPadding, flingBehavior = pagerFlingBehavior, horizontalAlignment = horizontalAlignment, horizontalArrangement = Arrangement.spacedBy( pageSpacing, horizontalAlignmentForSpacedArrangement ), verticalArrangement = Arrangement.spacedBy( pageSpacing, verticalAlignmentForSpacedArrangement ), verticalAlignment = verticalAlignment, isVertical = isVertical, reverseLayout = reverseLayout, userScrollEnabled = userScrollEnabled, beyondBoundsItemCount = beyondBoundsPageCount ) { items(pageCount) { val pageMainAxisSizeModifier = if (isVertical) { Modifier.height(pageAvailableSize) } else { Modifier.width(pageAvailableSize) } Box( modifier = Modifier.then(pageMainAxisSizeModifier), contentAlignment = Alignment.Center ) { pageContent(it) } } } } } private fun calculateContentPaddings( contentPadding: PaddingValues, orientation: Orientation, layoutDirection: LayoutDirection ): Dp { val startPadding = if (orientation == Orientation.Vertical) { contentPadding.calculateTopPadding() } else { contentPadding.calculateLeftPadding(layoutDirection) } val endPadding = if (orientation == Orientation.Vertical) { contentPadding.calculateBottomPadding() } else { contentPadding.calculateRightPadding(layoutDirection) } return startPadding + endPadding } /** * This is used to determine how Pages are laid out in [Pager]. By changing the size of the pages * one can change how many pages are shown. */ @ExperimentalFoundationApi internal interface PageSize { /** * Based on [availableSpace] pick a size for the pages * @param availableSpace The amount of space the pages in this Pager can use. * @param pageSpacing The amount of space used to separate pages. */ fun Density.calculateMainAxisPageSize(availableSpace: Int, pageSpacing: Int): Int /** * Pages take up the whole Pager size. */ @ExperimentalFoundationApi object Fill : PageSize { override fun Density.calculateMainAxisPageSize(availableSpace: Int, pageSpacing: Int): Int { return availableSpace } } /** * Multiple pages in a viewport * @param pageSize A fixed size for pages */ @ExperimentalFoundationApi class Fixed(val pageSize: Dp) : PageSize { override fun Density.calculateMainAxisPageSize(availableSpace: Int, pageSpacing: Int): Int { return pageSize.roundToPx() } } } @ExperimentalFoundationApi internal object PagerDefaults { /** * @param state The [PagerState] that controls the which to which this FlingBehavior will * be applied to. * @param pagerSnapDistance A way to control the snapping destination for this [Pager]. * The default behavior will result in any fling going to the next page in the direction of the * fling (if the fling has enough velocity, otherwise we'll bounce back). Use * [PagerSnapDistance.atMost] to define a maximum number of pages this [Pager] is allowed to * fling after scrolling is finished and fling has started. * @param lowVelocityAnimationSpec The animation spec used to approach the target offset. When * the fling velocity is not large enough. Large enough means large enough to naturally decay. * @param highVelocityAnimationSpec The animation spec used to approach the target offset. When * the fling velocity is large enough. Large enough means large enough to naturally decay. * @param snapAnimationSpec The animation spec used to finally snap to the position. * * @return An instance of [FlingBehavior] that will perform Snapping to the next page. The * animation will be governed by the post scroll velocity and we'll use either * [lowVelocityAnimationSpec] or [highVelocityAnimationSpec] to approach the snapped position * and the last step of the animation will be performed by [snapAnimationSpec]. */ @Composable fun flingBehavior( state: PagerState, pagerSnapDistance: PagerSnapDistance = PagerSnapDistance.atMost(1), lowVelocityAnimationSpec: AnimationSpec<Float> = tween(easing = LinearOutSlowInEasing), highVelocityAnimationSpec: DecayAnimationSpec<Float> = rememberSplineBasedDecay(), snapAnimationSpec: AnimationSpec<Float> = spring(stiffness = Spring.StiffnessMediumLow), ): SnapFlingBehavior { val density = LocalDensity.current return remember( lowVelocityAnimationSpec, highVelocityAnimationSpec, snapAnimationSpec, pagerSnapDistance, density ) { val snapLayoutInfoProvider = SnapLayoutInfoProvider(state, pagerSnapDistance, highVelocityAnimationSpec) SnapFlingBehavior( snapLayoutInfoProvider = snapLayoutInfoProvider, lowVelocityAnimationSpec = lowVelocityAnimationSpec, highVelocityAnimationSpec = highVelocityAnimationSpec, snapAnimationSpec = snapAnimationSpec, density = density ) } } } /** * [PagerSnapDistance] defines the way the [Pager] will treat the distance between the current * page and the page where it will settle. */ @ExperimentalFoundationApi @Stable internal interface PagerSnapDistance { /** Provides a chance to change where the [Pager] fling will settle. * * @param startPage The current page right before the fling starts. * @param suggestedTargetPage The proposed target page where this fling will stop. This target * will be the page that will be correctly positioned (snapped) after naturally decaying with * [velocity] using a [DecayAnimationSpec]. * @param velocity The initial fling velocity. * @param pageSize The page size for this [Pager]. * @param pageSpacing The spacing used between pages. * * @return An updated target page where to settle. Note that this value needs to be between 0 * and the total count of pages in this pager. If an invalid value is passed, the pager will * coerce within the valid values. */ fun calculateTargetPage( startPage: Int, suggestedTargetPage: Int, velocity: Float, pageSize: Int, pageSpacing: Int ): Int companion object { /** * Limits the maximum number of pages that can be flung per fling gesture. * @param pages The maximum number of extra pages that can be flung at once. */ fun atMost(pages: Int): PagerSnapDistance { require(pages >= 0) { "pages should be greater than or equal to 0. You have used $pages." } return PagerSnapDistanceMaxPages(pages) } } } /** * Limits the maximum number of pages that can be flung per fling gesture. * @param pagesLimit The maximum number of extra pages that can be flung at once. */ @OptIn(ExperimentalFoundationApi::class) internal class PagerSnapDistanceMaxPages(private val pagesLimit: Int) : PagerSnapDistance { override fun calculateTargetPage( startPage: Int, suggestedTargetPage: Int, velocity: Float, pageSize: Int, pageSpacing: Int, ): Int { return suggestedTargetPage.coerceIn(startPage - pagesLimit, startPage + pagesLimit) } override fun equals(other: Any?): Boolean { return if (other is PagerSnapDistanceMaxPages) { this.pagesLimit == other.pagesLimit } else { false } } override fun hashCode(): Int { return pagesLimit.hashCode() } } @OptIn(ExperimentalFoundationApi::class) private fun SnapLayoutInfoProvider( pagerState: PagerState, pagerSnapDistance: PagerSnapDistance, decayAnimationSpec: DecayAnimationSpec<Float> ): SnapLayoutInfoProvider { return object : SnapLayoutInfoProvider by SnapLayoutInfoProvider( lazyListState = pagerState.lazyListState, positionInLayout = SnapAlignmentStartToStart ) { override fun Density.calculateApproachOffset(initialVelocity: Float): Float { val effectivePageSize = pagerState.pageSize + pagerState.pageSpacing val initialOffset = pagerState.currentPageOffset * effectivePageSize val animationOffset = decayAnimationSpec.calculateTargetValue(0f, initialVelocity) val startPage = pagerState.currentPage val startPageOffset = startPage * effectivePageSize val targetOffset = (startPageOffset + initialOffset + animationOffset) / effectivePageSize val targetPage = targetOffset.toInt() val correctedTargetPage = pagerSnapDistance.calculateTargetPage( startPage, targetPage, initialVelocity, pagerState.pageSize, pagerState.pageSpacing ).coerceIn(0, pagerState.pageCount) val finalOffset = (correctedTargetPage - startPage) * effectivePageSize return (finalOffset - initialOffset) } } } @OptIn(ExperimentalFoundationApi::class) private class PagerWrapperFlingBehavior( val originalFlingBehavior: SnapFlingBehavior, val pagerState: PagerState ) : FlingBehavior { override suspend fun ScrollScope.performFling(initialVelocity: Float): Float { return with(originalFlingBehavior) { performFling(initialVelocity) { remainingScrollOffset -> pagerState.snapRemainingScrollOffset = remainingScrollOffset } } } }
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/pager/Pager.kt
3628242526
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.text.caches.LruCache import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.constrain import kotlin.math.ceil /** * Use cases that converge to this number; * - Static text is drawn on canvas for legend and labels. * - Text toggles between enumerated states bold, italic. * - Multiple texts drawn but only their colors are animated. * * If text layout is always called with different inputs, this number is a good stopping point so * that cache does not becomes unnecessarily large and miss penalty stays low. Of course developers * should be aware that in a use case like that the cache should explicitly be disabled. */ private val DefaultCacheSize = 8 /** * TextMeasurer is responsible for measuring a text in its entirety so that it's ready to be drawn. * * A TextMeasurer instance should be created via `androidx.compose.ui.rememberTextMeasurer` in a * Composable context to use fallback values from default composition locals. * * Text layout is a computationally expensive task. Therefore, this class holds an internal LRU * Cache of layout input and output pairs to optimize the repeated measure calls that use the same * input parameters. * * Although most input parameters have a direct influence on layout, some parameters like color, * brush, and shadow can be ignored during layout and set at the end. Using TextMeasurer with * appropriate [cacheSize] should provide significant improvements while animating * non-layout-affecting attributes like color. * * Moreover, if there is a need to render multiple static texts, you can provide the number of texts * by [cacheSize] and their layouts should be cached for repeating calls. Be careful that even a * slight change in input parameters like fontSize, maxLines, an additional character in text would * create a distinct set of input parameters. As a result, a new layout would be calculated and a * new set of input and output pair would be placed in LRU Cache, possibly evicting an earlier * result. * * [FontFamily.Resolver], [LayoutDirection], and [Density] are required parameters to construct a * text layout but they have no safe fallbacks outside of composition. These parameters must be * provided during the construction of a [TextMeasurer] to be used as default values when they * are skipped in [TextMeasurer.measure] call. * * @param fallbackFontFamilyResolver to be used to load fonts given in [TextStyle] and [SpanStyle]s * in [AnnotatedString]. * @param fallbackLayoutDirection layout direction of the measurement environment. * @param fallbackDensity density of the measurement environment. Density controls the scaling * factor for fonts. * @param cacheSize Capacity of internal cache inside TextMeasurer. Size unit is the number of * unique text layout inputs that are measured. Value of this parameter highly depends on the * consumer use case. Provide a cache size that is in line with how many distinct text layouts are * going to be calculated by this measurer repeatedly. If you are animating font attributes, or any * other layout affecting input, cache can be skipped because most repeated measure calls would miss * the cache. */ @ExperimentalTextApi @Immutable class TextMeasurer constructor( private val fallbackFontFamilyResolver: FontFamily.Resolver, private val fallbackDensity: Density, private val fallbackLayoutDirection: LayoutDirection, private val cacheSize: Int = DefaultCacheSize ) { private val textLayoutCache: TextLayoutCache? = if (cacheSize > 0) { TextLayoutCache(cacheSize) } else null /** * Creates a [TextLayoutResult] according to given parameters. * * This function supports laying out text that consists of multiple paragraphs, includes * placeholders, wraps around soft line breaks, and might overflow outside the specified size. * * Most parameters for text affect the final text layout. One pixel change in [constraints] * boundaries can displace a word to another line which would cause a chain reaction that * completely changes how text is rendered. * * On the other hand, some attributes only play a role when drawing the created text layout. * For example text layout can be created completely in black color but we can apply * [TextStyle.color] later in draw phase. This also means that animating text color shouldn't * invalidate text layout. * * Thus, [textLayoutCache] helps in the process of converting a set of text layout inputs to * a text layout while ignoring non-layout-affecting attributes. Iterative calls that use the * same input parameters should benefit from substantial performance improvements. * * @param text the text to be laid out * @param style the [TextStyle] to be applied to the whole text * @param overflow How visual overflow should be handled. * @param softWrap Whether the text should break at soft line breaks. If false, the glyphs in * the text will be positioned as if there was unlimited horizontal space. If [softWrap] is * false, [overflow] and TextAlign may have unexpected effects. * @param maxLines An optional maximum number of lines for the text to span, wrapping if * necessary. If the text exceeds the given number of lines, it will be truncated according to * [overflow] and [softWrap]. If it is not null, then it must be greater than zero. * @param placeholders a list of [Placeholder]s that specify ranges of text which will be * skipped during layout and replaced with [Placeholder]. It's required that the range of each * [Placeholder] doesn't cross paragraph boundary, otherwise [IllegalArgumentException] is * thrown. * @param constraints how wide and tall the text is allowed to be. [Constraints.maxWidth] * will define the width of the MultiParagraph. [Constraints.maxHeight] helps defining the * number of lines that fit with ellipsis is true. [Constraints.minWidth] defines the minimum * width the resulting [TextLayoutResult.size] will report. [Constraints.minHeight] is no-op. * @param layoutDirection layout direction of the measurement environment. If not specified, * defaults to the value that was given during initialization of this [TextMeasurer]. * @param density density of the measurement environment. If not specified, defaults to * the value that was given during initialization of this [TextMeasurer]. * @param fontFamilyResolver to be used to load the font given in [SpanStyle]s. If not * specified, defaults to the value that was given during initialization of this [TextMeasurer]. * @param skipCache Disables cache optimization if it is passed as true. */ @Stable fun measure( text: AnnotatedString, style: TextStyle = TextStyle.Default, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, placeholders: List<AnnotatedString.Range<Placeholder>> = emptyList(), constraints: Constraints = Constraints(), layoutDirection: LayoutDirection = this.fallbackLayoutDirection, density: Density = this.fallbackDensity, fontFamilyResolver: FontFamily.Resolver = this.fallbackFontFamilyResolver, skipCache: Boolean = false ): TextLayoutResult { val requestedTextLayoutInput = TextLayoutInput( text, style, placeholders, maxLines, softWrap, overflow, density, layoutDirection, fontFamilyResolver, constraints ) val cacheResult = if (!skipCache && textLayoutCache != null) { textLayoutCache.get(requestedTextLayoutInput) } else null return if (cacheResult != null) { cacheResult.copy( layoutInput = requestedTextLayoutInput, size = constraints.constrain( IntSize( cacheResult.multiParagraph.width.ceilToInt(), cacheResult.multiParagraph.height.ceilToInt() ) ) ) } else { layout(requestedTextLayoutInput).also { textLayoutCache?.put(requestedTextLayoutInput, it) } } } internal companion object { /** * Computes the visual position of the glyphs for painting the text. * * The text will layout with a width that's as close to its max intrinsic width as possible * while still being greater than or equal to `minWidth` and less than or equal to * `maxWidth`. */ private fun layout( textLayoutInput: TextLayoutInput ): TextLayoutResult = with(textLayoutInput) { val nonNullIntrinsics = MultiParagraphIntrinsics( annotatedString = text, style = resolveDefaults(style, layoutDirection), density = density, fontFamilyResolver = fontFamilyResolver, placeholders = placeholders ) val minWidth = constraints.minWidth val widthMatters = softWrap || overflow == TextOverflow.Ellipsis val maxWidth = if (widthMatters && constraints.hasBoundedWidth) { constraints.maxWidth } else { Constraints.Infinity } // This is a fallback behavior because native text layout doesn't support multiple // ellipsis in one text layout. // When softWrap is turned off and overflow is ellipsis, it's expected that each line // that exceeds maxWidth will be ellipsized. // For example, // input text: // "AAAA\nAAAA" // maxWidth: // 3 * fontSize that only allow 3 characters to be displayed each line. // expected output: // AA… // AA… // Here we assume there won't be any '\n' character when softWrap is false. And make // maxLines 1 to implement the similar behavior. val overwriteMaxLines = !softWrap && overflow == TextOverflow.Ellipsis val finalMaxLines = if (overwriteMaxLines) 1 else maxLines // if minWidth == maxWidth the width is fixed. // therefore we can pass that value to our paragraph and use it // if minWidth != maxWidth there is a range // then we should check if the max intrinsic width is in this range to decide the // width to be passed to Paragraph // if max intrinsic width is between minWidth and maxWidth // we can use it to layout // else if max intrinsic width is greater than maxWidth, we can only use maxWidth // else if max intrinsic width is less than minWidth, we should use minWidth val width = if (minWidth == maxWidth) { maxWidth } else { nonNullIntrinsics.maxIntrinsicWidth.ceilToInt().coerceIn(minWidth, maxWidth) } val multiParagraph = MultiParagraph( intrinsics = nonNullIntrinsics, constraints = Constraints(maxWidth = width, maxHeight = constraints.maxHeight), // This is a fallback behavior for ellipsis. Native maxLines = finalMaxLines, ellipsis = overflow == TextOverflow.Ellipsis ) return TextLayoutResult( layoutInput = textLayoutInput, multiParagraph = multiParagraph, size = constraints.constrain( IntSize( ceil(multiParagraph.width).toInt(), ceil(multiParagraph.height).toInt() ) ) ) } } } /** * Keeps an LRU layout cache of TextLayoutInput, TextLayoutResult pairs. Any non-layout affecting * change in TextLayoutInput (color, brush, shadow, TextDecoration) is ignored by this cache. * * @param capacity Maximum size of LRU cache. Size unit is the number of [CacheTextLayoutInput] * and [TextLayoutResult] pairs. * * @throws IllegalArgumentException if capacity is not a positive integer. */ internal class TextLayoutCache(capacity: Int = DefaultCacheSize) { private val lruCache = LruCache<CacheTextLayoutInput, TextLayoutResult>(capacity) fun get(key: TextLayoutInput): TextLayoutResult? { val resultFromCache = lruCache.get(CacheTextLayoutInput(key)) ?: return null if (resultFromCache.multiParagraph.intrinsics.hasStaleResolvedFonts) { // one of the resolved fonts has updated, and this MeasuredText is no longer valid for // measure or display return null } return resultFromCache } fun put(key: TextLayoutInput, value: TextLayoutResult): TextLayoutResult? { return lruCache.put(CacheTextLayoutInput(key), value) } fun remove(key: TextLayoutInput): TextLayoutResult? { return lruCache.remove(CacheTextLayoutInput(key)) } } /** * Provides custom hashCode and equals function that are only interested in layout affecting * attributes in TextLayoutInput. Used as a key in [TextLayoutCache]. */ @Immutable internal class CacheTextLayoutInput(val textLayoutInput: TextLayoutInput) { override fun hashCode(): Int = with(textLayoutInput) { var result = text.hashCode() result = 31 * result + style.hashCodeLayoutAffectingAttributes() result = 31 * result + placeholders.hashCode() result = 31 * result + maxLines result = 31 * result + softWrap.hashCode() result = 31 * result + overflow.hashCode() result = 31 * result + density.hashCode() result = 31 * result + layoutDirection.hashCode() result = 31 * result + fontFamilyResolver.hashCode() result = 31 * result + constraints.maxWidth.hashCode() result = 31 * result + constraints.maxHeight.hashCode() return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CacheTextLayoutInput) return false with(textLayoutInput) { if (text != other.textLayoutInput.text) return false if (!style.hasSameLayoutAffectingAttributes(other.textLayoutInput.style)) return false if (placeholders != other.textLayoutInput.placeholders) return false if (maxLines != other.textLayoutInput.maxLines) return false if (softWrap != other.textLayoutInput.softWrap) return false if (overflow != other.textLayoutInput.overflow) return false if (density != other.textLayoutInput.density) return false if (layoutDirection != other.textLayoutInput.layoutDirection) return false if (fontFamilyResolver !== other.textLayoutInput.fontFamilyResolver) return false if (constraints.maxWidth != other.textLayoutInput.constraints.maxWidth) return false if (constraints.maxHeight != other.textLayoutInput.constraints.maxHeight) return false } return true } }
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/TextMeasurer.kt
521179045
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum /** * A port of non_zero.py from onnx tensorflow for samediff: * https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/non_zero.py * * @author Adam Gibson */ @PreHookRule(nodeNames = [],opNames = ["NonZero"],frameworkName = "onnx") class NonZero : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>, dynamicVariables: Map<String, GeneratedMessageV3> ): Map<String, List<SDVariable>> { // Parameter docs below are from the onnx operator docs: // https://github.com/onnx/onnx/blob/master/docs/Operators.md#non var inputVariable = sd.getVariable(op.inputsToOp[0]) val condition = sd.neq(inputVariable,sd.zerosLike(inputVariable)) val nonZeroIndices = sd.where(condition) val outputVar = sd.permute(outputNames[0],nonZeroIndices) return mapOf(outputVar.name() to listOf(outputVar)) } }
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/NonZero.kt
3166237178
package chat.willow.kale.irc.message.extension.cap import chat.willow.kale.core.message.IrcMessage import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test class CapEndMessageTests { lateinit var messageParser: CapMessage.End.Command.Parser lateinit var messageSerialiser: CapMessage.End.Command.Serialiser @Before fun setUp() { messageParser = CapMessage.End.Command.Parser messageSerialiser = CapMessage.End.Command.Serialiser } @Test fun test_parse() { val message = messageParser.parse(IrcMessage(command = "CAP", parameters = listOf("END"))) assertEquals(CapMessage.End.Command, message) } @Test fun test_parse_TooFewParameters() { val messageOne = messageParser.parse(IrcMessage(command = "CAP", parameters = listOf())) assertNull(messageOne) } @Test fun test_serialise() { val message = messageSerialiser.serialise(CapMessage.End.Command) assertEquals(IrcMessage(command = "CAP", parameters = listOf("END")), message) } }
src/test/kotlin/chat/willow/kale/irc/message/extension/cap/CapEndMessageTests.kt
2440088625
class Foo(val f: () -> Unit) fun test(foo: Foo?) { <caret>if (foo != null) { foo.f() } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/branched/ifThenToSafeAccess/callVariable2.kt
3309682332
// MOVE: up fun foo(x: Boolean) { if (x) { } <caret>if (x) { } }
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/expressions/ifToBlock2.kt
78606960
// WITH_LIBRARY: copyPaste/imports/KotlinLibrary package d <selection> /* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ import foo.Bar /** * Some kdoc for class Foo */ class Foo(val a: A) { } </selection>
plugins/kotlin/idea/tests/testData/copyPaste/imports/ImportDirectiveAndClassBody.kt
2740738621
package com.intellij.settingsSync import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAwareAction class ManualPushAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val facade = service<SettingsSyncFacade>() facade.pushSettingsToServer() } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isSettingsSyncEnabled() } }
plugins/settings-sync/src/com/intellij/settingsSync/ManualPushAction.kt
3277471040
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.TextBrowseFolderListener import com.intellij.openapi.ui.TextFieldWithBrowseButton import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.asPath import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.withOnUpdatedListener import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.nio.file.Path import java.nio.file.Paths import javax.swing.JComponent class PathFieldComponent( context: Context, labelText: String? = null, description: String? = null, initialValue: Path? = null, validator: SettingValidator<Path>? = null, onValueUpdate: (Path, isByUser: Boolean) -> Unit = { _, _ -> } ) : UIComponent<Path>( context, labelText, validator, onValueUpdate ) { private val textFieldWithBrowseButton = TextFieldWithBrowseButton().apply { textField.text = initialValue?.toString().orEmpty() textField.withOnUpdatedListener { path -> fireValueUpdated(path.trim().asPath()) } addBrowseFolderListener( TextBrowseFolderListener( FileChooserDescriptorFactory.createSingleFolderDescriptor(), null ) ) } fun onUserType(action: () -> Unit) { textFieldWithBrowseButton.textField.addKeyListener(object : KeyAdapter() { override fun keyReleased(e: KeyEvent?) = action() }) } override val alignTarget: JComponent? get() = textFieldWithBrowseButton override val uiComponent = componentWithCommentAtBottom(textFieldWithBrowseButton, description) override fun getValidatorTarget(): JComponent = textFieldWithBrowseButton.textField override fun updateUiValue(newValue: Path) = safeUpdateUi { textFieldWithBrowseButton.text = newValue.toString() } override fun getUiValue(): Path = Paths.get(textFieldWithBrowseButton.text.trim()) override fun focusOn() { textFieldWithBrowseButton.textField.requestFocus() } }
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/PathFieldComponent.kt
331280247
// IS_APPLICABLE: false class MySuperClass() { val <caret>prop5 = this::test fun test() { } }
plugins/kotlin/idea/tests/testData/intentions/movePropertyToConstructor/methodReference.kt
3451744425
object Main { fun test() { val type1 = Main val type = Main if (type === CONST1 || type == CONST2 && type === CONST3) return if (type === CONST1 || type == CONST2 && (type === CONST3)) return if (type === CONST1 || type == CONST2 && !(type === CONST3)) return if (type === CONST1 || type1 == CONST2 && type === CONST3) return if (type === CONST1 || type1 == CONST1 && type === CONST3) return val type2: Main? = null if (type2 == null || type === type2) return val type3: Main? = null if (type3 === null || type == type3) return val type4: Main? = null if (type4 == null || type === type2 || type1 == type) return } val CONST1 = Main; val CONST2 = Main; val CONST3 = Main; }
plugins/kotlin/idea/tests/testData/inspections/suspiciousEqualsCombination/test.kt
2844338887
// "Replace usages of 'contains(String) on C: Boolean' in whole project" "true" class C @Deprecated("", ReplaceWith("checkContains(s)")) operator fun C.contains(s: String) = true fun C.checkContains(s: String) = true fun f(c: C) { if ("" <caret>!in c) { } } fun g(c: C) { if ("" in c) { } }
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/operatorCalls/in.kt
1671590096
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.evaluate import com.intellij.debugger.DebuggerManagerEx import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.JavaDebuggerEvaluator import com.intellij.debugger.engine.evaluation.CodeFragmentFactory import com.intellij.debugger.engine.evaluation.TextWithImports import com.intellij.debugger.engine.events.DebuggerCommandImpl import com.intellij.debugger.impl.DebuggerContextImpl import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiTypesUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.concurrency.Semaphore import com.sun.jdi.AbsentInformationException import com.sun.jdi.InvalidStackFrameException import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.core.util.getKotlinJvmRuntimeMarkerClass import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider import org.jetbrains.kotlin.idea.debugger.getContextElement import org.jetbrains.kotlin.idea.debugger.hopelessAware import org.jetbrains.kotlin.idea.j2k.J2kPostProcessor import org.jetbrains.kotlin.idea.j2k.convertToKotlin import org.jetbrains.kotlin.idea.j2k.j2kText import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.j2k.AfterConversionPass import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.types.KotlinType import java.util.concurrent.atomic.AtomicReference class KotlinCodeFragmentFactory : CodeFragmentFactory() { override fun createCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment { val contextElement = getContextElement(context) val codeFragment = KtBlockCodeFragment(project, "fragment.kt", item.text, initImports(item.imports), contextElement) supplyDebugInformation(item, codeFragment, context) codeFragment.putCopyableUserData(KtCodeFragment.RUNTIME_TYPE_EVALUATOR) { expression: KtExpression -> val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context val debuggerSession = debuggerContext.debuggerSession if (debuggerSession == null || debuggerContext.suspendContext == null) { null } else { val semaphore = Semaphore() semaphore.down() val nameRef = AtomicReference<KotlinType>() val worker = object : KotlinRuntimeTypeEvaluator( null, expression, debuggerContext, ProgressManager.getInstance().progressIndicator!! ) { override fun typeCalculationFinished(type: KotlinType?) { nameRef.set(type) semaphore.up() } } debuggerContext.debugProcess?.managerThread?.invoke(worker) for (i in 0..50) { ProgressManager.checkCanceled() if (semaphore.waitFor(20)) break } nameRef.get() } } if (contextElement != null && contextElement !is KtElement) { codeFragment.putCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) { val emptyFile = createFakeFileWithJavaContextElement("", contextElement) val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context val debuggerSession = debuggerContext.debuggerSession if ((debuggerSession == null || debuggerContext.suspendContext == null) && !isUnitTestMode() ) { LOG.warn("Couldn't create fake context element for java file, debugger isn't paused on breakpoint") return@putCopyableUserData emptyFile } val frameInfo = getFrameInfo(contextElement, debuggerContext) ?: run { val position = "${debuggerContext.sourcePosition?.file?.name}:${debuggerContext.sourcePosition?.line}" LOG.warn("Couldn't get info about 'this' and local variables for $position") return@putCopyableUserData emptyFile } val fakeFunctionText = buildString { append("fun ") val thisType = frameInfo.thisObject?.asProperty()?.typeReference?.typeElement?.unwrapNullableType() if (thisType != null) { append(thisType.text).append('.') } append(FAKE_JAVA_CONTEXT_FUNCTION_NAME).append("() {\n") for (variable in frameInfo.variables) { val text = variable.asProperty()?.text ?: continue append(" ").append(text).append("\n") } // There should be at least one declaration inside the function (or 'fakeContext' below won't work). append(" val _debug_context_val = 1\n") append("}") } val fakeFile = createFakeFileWithJavaContextElement(fakeFunctionText, contextElement) val fakeFunction = fakeFile.declarations.firstOrNull() as? KtFunction val fakeContext = fakeFunction?.bodyBlockExpression?.statements?.lastOrNull() return@putCopyableUserData fakeContext ?: emptyFile } } return codeFragment } private fun KtTypeElement.unwrapNullableType(): KtTypeElement { return if (this is KtNullableType) innerType ?: this else this } private fun supplyDebugInformation(item: TextWithImports, codeFragment: KtCodeFragment, context: PsiElement?) { val project = codeFragment.project val debugProcess = getDebugProcess(project, context) ?: return DebugLabelPropertyDescriptorProvider(codeFragment, debugProcess).supplyDebugLabels() @Suppress("MoveVariableDeclarationIntoWhen") val evaluator = debugProcess.session.xDebugSession?.currentStackFrame?.evaluator val evaluationType = when (evaluator) { is KotlinDebuggerEvaluator -> evaluator.getType(item) is JavaDebuggerEvaluator -> KotlinDebuggerEvaluator.EvaluationType.FROM_JAVA else -> KotlinDebuggerEvaluator.EvaluationType.UNKNOWN } codeFragment.putUserData(EVALUATION_TYPE, evaluationType) } private fun getDebugProcess(project: Project, context: PsiElement?): DebugProcessImpl? { return if (isUnitTestMode()) { context?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.debugProcess } else { DebuggerManagerEx.getInstanceEx(project).context.debugProcess } } private fun getFrameInfo(contextElement: PsiElement?, debuggerContext: DebuggerContextImpl): FrameInfo? { val semaphore = Semaphore() semaphore.down() var frameInfo: FrameInfo? = null val worker = object : DebuggerCommandImpl() { override fun action() { try { val frameProxy = hopelessAware { if (isUnitTestMode()) { contextElement?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.frameProxy } else { debuggerContext.frameProxy } } frameInfo = FrameInfo.from(debuggerContext.project, frameProxy) } catch (ignored: AbsentInformationException) { // Debug info unavailable } catch (ignored: InvalidStackFrameException) { // Thread is resumed, the frame we have is not valid anymore } finally { semaphore.up() } } } debuggerContext.debugProcess?.managerThread?.invoke(worker) for (i in 0..50) { if (semaphore.waitFor(20)) break } return frameInfo } private fun initImports(imports: String?): String? { if (imports != null && imports.isNotEmpty()) { return imports.split(KtCodeFragment.IMPORT_SEPARATOR) .mapNotNull { fixImportIfNeeded(it) } .joinToString(KtCodeFragment.IMPORT_SEPARATOR) } return null } private fun fixImportIfNeeded(import: String): String? { // skip arrays if (import.endsWith("[]")) { return fixImportIfNeeded(import.removeSuffix("[]").trim()) } // skip primitive types if (PsiTypesUtil.boxIfPossible(import) != import) { return null } return import } override fun createPresentationCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment { val kotlinCodeFragment = createCodeFragment(item, context, project) if (PsiTreeUtil.hasErrorElements(kotlinCodeFragment) && kotlinCodeFragment is KtCodeFragment) { val javaExpression = try { PsiElementFactory.getInstance(project).createExpressionFromText(item.text, context) } catch (e: IncorrectOperationException) { null } val importList = try { kotlinCodeFragment.importsAsImportList()?.let { (PsiFileFactory.getInstance(project).createFileFromText( "dummy.java", JavaFileType.INSTANCE, it.text ) as? PsiJavaFile)?.importList } } catch (e: IncorrectOperationException) { null } if (javaExpression != null && !PsiTreeUtil.hasErrorElements(javaExpression)) { var convertedFragment: KtExpressionCodeFragment? = null project.executeWriteCommand(KotlinDebuggerEvaluationBundle.message("j2k.expression")) { try { val (elementResults, _, conversionContext) = javaExpression.convertToKotlin() ?: return@executeWriteCommand val newText = elementResults.singleOrNull()?.text val newImports = importList?.j2kText() if (newText != null) { convertedFragment = KtExpressionCodeFragment( project, kotlinCodeFragment.name, newText, newImports, kotlinCodeFragment.context ) AfterConversionPass(project, J2kPostProcessor(formatCode = false)) .run( convertedFragment!!, conversionContext, range = null, onPhaseChanged = null ) } } catch (e: Throwable) { // ignored because text can be invalid LOG.error("Couldn't convert expression:\n`${javaExpression.text}`", e) } } return convertedFragment ?: kotlinCodeFragment } } return kotlinCodeFragment } override fun isContextAccepted(contextElement: PsiElement?): Boolean = runReadAction { when { // PsiCodeBlock -> DummyHolder -> originalElement contextElement is PsiCodeBlock -> isContextAccepted(contextElement.context?.context) contextElement == null -> false contextElement.language == KotlinFileType.INSTANCE.language -> true contextElement.language == JavaFileType.INSTANCE.language -> { getKotlinJvmRuntimeMarkerClass(contextElement.project, contextElement.resolveScope) != null } else -> false } } override fun getFileType(): KotlinFileType = KotlinFileType.INSTANCE override fun getEvaluatorBuilder() = KotlinEvaluatorBuilder companion object { private val LOG = Logger.getInstance(this::class.java) @get:TestOnly val DEBUG_CONTEXT_FOR_TESTS: Key<DebuggerContextImpl> = Key.create("DEBUG_CONTEXT_FOR_TESTS") val EVALUATION_TYPE: Key<KotlinDebuggerEvaluator.EvaluationType> = Key.create("DEBUG_EVALUATION_TYPE") const val FAKE_JAVA_CONTEXT_FUNCTION_NAME = "_java_locals_debug_fun_" } private fun createFakeFileWithJavaContextElement(funWithLocalVariables: String, javaContext: PsiElement): KtFile { val javaFile = javaContext.containingFile as? PsiJavaFile val sb = StringBuilder() javaFile?.packageName?.takeUnless { it.isBlank() }?.let { sb.append("package ").append(it.quoteIfNeeded()).append("\n") } javaFile?.importList?.let { sb.append(it.text).append("\n") } sb.append(funWithLocalVariables) return KtPsiFactory(javaContext.project).createAnalyzableFile("fakeFileForJavaContextInDebugger.kt", sb.toString(), javaContext) } }
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt
1563187082
// p.ActualTypeAliasKt // FIR_COMPARISON package p actual typealias B = List<Int>
plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/compilationErrors/ActualTypeAlias.kt
3112450836
package de.fabmax.kool.demo.physics.vehicle import de.fabmax.kool.physics.* import de.fabmax.kool.physics.geometry.TriangleMeshGeometry import de.fabmax.kool.physics.vehicle.VehicleUtils import de.fabmax.kool.pipeline.deferred.DeferredPipeline import de.fabmax.kool.pipeline.deferred.deferredPbrShader import de.fabmax.kool.scene.Node import de.fabmax.kool.scene.Scene import de.fabmax.kool.scene.colorMesh import de.fabmax.kool.scene.geometry.IndexedVertexList import de.fabmax.kool.scene.group import de.fabmax.kool.util.Color class VehicleWorld(val scene: Scene, val physics: PhysicsWorld, val deferredPipeline: DeferredPipeline) { val defaultMaterial = Material(0.5f) val groundSimFilterData = FilterData(VehicleUtils.COLLISION_FLAG_GROUND, VehicleUtils.COLLISION_FLAG_GROUND_AGAINST) val groundQryFilterData = FilterData { VehicleUtils.setupDrivableSurface(this) } val obstacleSimFilterData = FilterData(VehicleUtils.COLLISION_FLAG_DRIVABLE_OBSTACLE, VehicleUtils.COLLISION_FLAG_DRIVABLE_OBSTACLE_AGAINST) val obstacleQryFilterData = FilterData { VehicleUtils.setupDrivableSurface(this) } fun toPrettyMesh(actor: RigidActor, meshColor: Color, rough: Float = 0.8f, metal: Float = 0f): Node = group { +colorMesh { generate { color = meshColor actor.shapes.forEach { shape -> withTransform { transform.mul(shape.localPose) shape.geometry.generateMesh(this) } } } shader = deferredPbrShader { roughness = rough metallic = metal } onUpdate += { [email protected](actor.transform) [email protected]() } } } fun addStaticCollisionBody(mesh: IndexedVertexList): RigidStatic { val body = RigidStatic().apply { simulationFilterData = obstacleSimFilterData queryFilterData = obstacleQryFilterData attachShape(Shape(TriangleMeshGeometry(mesh), defaultMaterial)) } physics.addActor(body) return body } fun release() { physics.clear() physics.release() defaultMaterial.release() } }
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/vehicle/VehicleWorld.kt
3918683436
package com.kelsos.mbrc.repository.data import com.kelsos.mbrc.data.Data import com.raizlabs.android.dbflow.list.FlowCursorList interface LocalDataSource<T : Data> { suspend fun deleteAll() suspend fun saveAll(list: List<T>) suspend fun loadAllCursor(): FlowCursorList<T> suspend fun search(term: String): FlowCursorList<T> suspend fun isEmpty(): Boolean suspend fun count(): Long suspend fun removePreviousEntries(epoch: Long) }
app/src/main/kotlin/com/kelsos/mbrc/repository/data/LocalDataSource.kt
2896633833
// PROBLEM: none // WITH_STDLIB fun foo(s: String, i: Int) = s.length + i fun test() { val s = "" s.length.let<caret> { foo("", it) } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/simpleRedundantLet/functionCall5.kt
1511177940
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.comment.ui import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.panels.Wrapper import com.intellij.util.ui.UI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import icons.GithubIcons import net.miginfocom.layout.AC import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.pullrequest.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.pullrequest.data.service.GHPRReviewServiceAdapter import org.jetbrains.plugins.github.ui.InlineIconButton import org.jetbrains.plugins.github.ui.util.HtmlEditorPane import org.jetbrains.plugins.github.util.GithubUIUtil import org.jetbrains.plugins.github.util.handleOnEdt import org.jetbrains.plugins.github.util.successOnEdt import java.awt.event.ActionListener import javax.swing.JComponent import javax.swing.JEditorPane import javax.swing.JPanel import javax.swing.text.BadLocationException import javax.swing.text.Utilities object GHPRReviewCommentComponent { fun create(reviewService: GHPRReviewServiceAdapter, thread: GHPRReviewThreadModel, comment: GHPRReviewCommentModel, avatarIconsProvider: GHAvatarIconsProvider): JComponent { val avatarLabel: LinkLabel<*> = LinkLabel.create("") { comment.authorLinkUrl?.let { BrowserUtil.browse(it) } }.apply { icon = avatarIconsProvider.getIcon(comment.authorAvatarUrl) isFocusable = true putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) } val href = comment.authorLinkUrl?.let { """href='${it}'""" }.orEmpty() //language=HTML val title = """<a $href>${comment.authorUsername ?: "unknown"}</a> commented ${GithubUIUtil.formatActionDate(comment.dateCreated)}""" val titlePane: HtmlEditorPane = HtmlEditorPane(title).apply { foreground = UIUtil.getContextHelpForeground() putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) } val textPane: HtmlEditorPane = HtmlEditorPane(comment.body).apply { putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) } comment.addChangesListener { textPane.setBody(comment.body) } val editorWrapper = Wrapper() val editButton = createEditButton(reviewService, comment, editorWrapper, textPane).apply { isVisible = comment.canBeUpdated } val deleteButton = createDeleteButton(reviewService, thread, comment).apply { isVisible = comment.canBeDeleted } val contentPanel = BorderLayoutPanel().andTransparent().addToCenter(textPane).addToBottom(editorWrapper) return JPanel(null).apply { isOpaque = false layout = MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fill(), AC().gap("${UI.scale(8)}")) add(avatarLabel, CC().pushY()) add(titlePane, CC().minWidth("0").split(3).alignX("left")) add(editButton, CC().hideMode(3).gapBefore("${UI.scale(12)}")) add(deleteButton, CC().hideMode(3).gapBefore("${UI.scale(8)}")) add(contentPanel, CC().newline().skip().grow().push().minWidth("0").minHeight("0")) } } private fun createDeleteButton(reviewService: GHPRReviewServiceAdapter, thread: GHPRReviewThreadModel, comment: GHPRReviewCommentModel): JComponent { val icon = GithubIcons.Delete val hoverIcon = GithubIcons.DeleteHovered return InlineIconButton(icon, hoverIcon, tooltip = "Delete").apply { actionListener = ActionListener { if (Messages.showConfirmationDialog(this, "Are you sure you want to delete this comment?", "Delete Comment", Messages.getYesButton(), Messages.getNoButton()) == Messages.YES) { reviewService.deleteComment(EmptyProgressIndicator(), comment.id) thread.removeComment(comment) } } } } private fun createEditButton(reviewService: GHPRReviewServiceAdapter, comment: GHPRReviewCommentModel, editorWrapper: Wrapper, textPane: JEditorPane): JComponent { val action = ActionListener { val linesCount = calcLines(textPane) val text = StringUtil.repeatSymbol('\n', linesCount - 1) val model = GHPRSubmittableTextField.Model { newText -> reviewService.updateComment(EmptyProgressIndicator(), comment.id, newText).successOnEdt { comment.update(it) }.handleOnEdt { _, _ -> editorWrapper.setContent(null) editorWrapper.revalidate() } } with(model.document) { runWriteAction { setText(text) setReadOnly(true) } reviewService.getCommentMarkdownBody(EmptyProgressIndicator(), comment.id).successOnEdt { runWriteAction { setReadOnly(false) setText(it) } } } val editor = GHPRSubmittableTextField.create(model, "Submit", onCancel = { editorWrapper.setContent(null) editorWrapper.revalidate() }) editorWrapper.setContent(editor) GithubUIUtil.focusPanel(editor) } val icon = AllIcons.General.Inline_edit val hoverIcon = AllIcons.General.Inline_edit_hovered return InlineIconButton(icon, hoverIcon, tooltip = "Edit").apply { actionListener = action } } private fun calcLines(textPane: JEditorPane): Int { var lineCount = 0 var offset = 0 while (true) { try { offset = Utilities.getRowEnd(textPane, offset) + 1 lineCount++ } catch (e: BadLocationException) { break } } return lineCount } fun factory(thread: GHPRReviewThreadModel, reviewService: GHPRReviewServiceAdapter, avatarIconsProvider: GHAvatarIconsProvider) : (GHPRReviewCommentModel) -> JComponent { return { comment -> create(reviewService, thread, comment, avatarIconsProvider) } } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRReviewCommentComponent.kt
3867420235
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01 /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ interface IViabilityCondition { }
src/main/java/cc/altruix/econsimtr01/IViabilityCondition.kt
3019601304
package test abstract class AbstractFlagAdded class AbstractFlagRemoved abstract class AbstractFlagUnchanged annotation class AnnotationFlagAdded class AnnotationFlagRemoved annotation class AnnotationFlagUnchanged data class DataFlagAdded(val x: Int) class DataFlagRemoved(val x: Int) data class DataFlagUnchanged(val x: Int) enum class EnumFlagAdded class EnumFlagRemoved enum class EnumFlagUnchanged final class FinalFlagAdded class FinalFlagRemoved final class FinalFlagUnchanged class InnerClassHolder { inner class InnerFlagAdded class InnerFlagRemoved inner class InnerFlagUnchanged } internal class InternalFlagAdded class InternalFlagRemoved internal class InternalFlagUnchanged open class OpenFlagAdded class OpenFlagRemoved open class OpenFlagUnchanged private class PrivateFlagAdded class PrivateFlagRemoved private class PrivateFlagUnchanged class ProtectedClassHolder { protected class ProtectedFlagAdded class ProtectedFlagRemoved protected class ProtectedFlagUnchanged } public class PublicFlagAdded class PublicFlagRemoved public class PublicFlagUnchanged sealed class SealedFlagAdded class SealedFlagRemoved sealed class SealedFlagUnchanged class UnchangedNoFlags
plugins/kotlin/jps/jps-plugin/tests/testData/comparison/classSignatureChange/classFlagsChanged/new.kt
2893378382
/* * 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.openapi.util.io import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PathUtilRt import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.attribute.PosixFileAttributeView import java.nio.file.attribute.PosixFilePermission private val LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil") val File.systemIndependentPath: String get() = path.replace(File.separatorChar, '/') val File.parentSystemIndependentPath: String get() = parent.replace(File.separatorChar, '/') // PathUtilRt.getParentPath returns empty string if no parent path, but in Kotlin "null" is better because elvis operator could be used fun getParentPath(path: String) = StringUtil.nullize(PathUtilRt.getParentPath(path)) fun endsWithSlash(path: String) = path.getOrNull(path.length - 1) == '/' fun endsWithName(path: String, name: String) = path.endsWith(name) && (path.length == name.length || path.getOrNull(path.length - name.length - 1) == '/') fun Path.setOwnerPermissions() { Files.getFileAttributeView(this, PosixFileAttributeView::class.java)?.let { try { it.setPermissions(setOf(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)) } catch (e: IOException) { LOG.warn(e) } } }
platform/platform-impl/src/com/intellij/openapi/util/io/fileUtil.kt
1168829915
fun test(a: Int) {} fun some() { tes<caret> } // EXIST: { lookupString:"test", itemText:"test", tailText:"(a: Int) (<root>)" }
plugins/kotlin/completion/tests/testData/basic/common/FunctionCompletionFormatting.kt
1902882037
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.codeInsight.template.* import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.impl.FinishMarkAction import com.intellij.openapi.command.impl.StartMarkAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.HelpID import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.introduce.inplace.OccurrencesChooser import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.util.SmartList import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.analysis.analyzeInContext import org.jetbrains.kotlin.idea.analysis.computeTypeInfoInContext import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention import org.jetbrains.kotlin.idea.refactoring.* import org.jetbrains.kotlin.idea.refactoring.introduce.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier import org.jetbrains.kotlin.idea.util.psi.patternMatching.toRange import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTraceContext import org.jetbrains.kotlin.resolve.ObservableBindingTrace import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.checker.ClassicTypeCheckerContext import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.checker.NewKotlinTypeChecker import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.ifEmpty import org.jetbrains.kotlin.utils.sure import kotlin.math.min object KotlinIntroduceVariableHandler : RefactoringActionHandler { val INTRODUCE_VARIABLE get() = KotlinBundle.message("introduce.variable") private val EXPRESSION_KEY = Key.create<Boolean>("EXPRESSION_KEY") private val REPLACE_KEY = Key.create<Boolean>("REPLACE_KEY") private val COMMON_PARENT_KEY = Key.create<Boolean>("COMMON_PARENT_KEY") private var KtExpression.isOccurrence: Boolean by NotNullablePsiCopyableUserDataProperty(Key.create("OCCURRENCE"), false) private class TypeCheckerImpl(private val project: Project) : KotlinTypeChecker by KotlinTypeChecker.DEFAULT { private inner class ContextImpl : ClassicTypeCheckerContext(false) { override fun areEqualTypeConstructors(a: TypeConstructor, b: TypeConstructor): Boolean = compareDescriptors(project, a.declarationDescriptor, b.declarationDescriptor) } override fun equalTypes(a: KotlinType, b: KotlinType): Boolean = with(NewKotlinTypeChecker.Default) { ContextImpl().equalTypes(a.unwrap(), b.unwrap()) } } private class IntroduceVariableContext( private val expression: KtExpression, private val nameSuggestions: List<Collection<String>>, private val allReplaces: List<KtExpression>, private val commonContainer: PsiElement, private val commonParent: PsiElement, private val replaceOccurrence: Boolean, private val noTypeInference: Boolean, private val expressionType: KotlinType?, private val componentFunctions: List<FunctionDescriptor>, private val bindingContext: BindingContext, private val resolutionFacade: ResolutionFacade ) { private val psiFactory = KtPsiFactory(expression) var propertyRef: KtDeclaration? = null var reference: SmartPsiElementPointer<KtExpression>? = null val references = ArrayList<SmartPsiElementPointer<KtExpression>>() private fun findElementByOffsetAndText(offset: Int, text: String, newContainer: PsiElement): PsiElement? = newContainer.findElementAt(offset)?.parentsWithSelf?.firstOrNull { (it as? KtExpression)?.text == text } private fun replaceExpression(expressionToReplace: KtExpression, addToReferences: Boolean): KtExpression { val isActualExpression = expression == expressionToReplace val replacement = psiFactory.createExpression(nameSuggestions.single().first()) val substringInfo = expressionToReplace.extractableSubstringInfo var result = when { expressionToReplace.isLambdaOutsideParentheses() -> { val functionLiteralArgument = expressionToReplace.getStrictParentOfType<KtLambdaArgument>()!! val newCallExpression = functionLiteralArgument.moveInsideParenthesesAndReplaceWith(replacement, bindingContext) newCallExpression.valueArguments.last().getArgumentExpression()!! } substringInfo != null -> substringInfo.replaceWith(replacement) else -> expressionToReplace.replace(replacement) as KtExpression } result = result.removeTemplateEntryBracesIfPossible() if (addToReferences) { references.addIfNotNull(SmartPointerManager.createPointer(result)) } if (isActualExpression) { reference = SmartPointerManager.createPointer(result) } return result } private fun runRefactoring( isVar: Boolean, expression: KtExpression, commonContainer: PsiElement, commonParent: PsiElement, allReplaces: List<KtExpression> ) { val initializer = (expression as? KtParenthesizedExpression)?.expression ?: expression val initializerText = if (initializer.mustBeParenthesizedInInitializerPosition()) "(${initializer.text})" else initializer.text val varOvVal = if (isVar) "var" else "val" var property: KtDeclaration = if (componentFunctions.isNotEmpty()) { buildString { componentFunctions.indices.joinTo(this, prefix = "$varOvVal (", postfix = ")") { nameSuggestions[it].first() } append(" = ") append(initializerText) }.let { psiFactory.createDestructuringDeclaration(it) } } else { buildString { append("$varOvVal ") append(nameSuggestions.single().first()) if (noTypeInference) { val typeToRender = expressionType ?: resolutionFacade.moduleDescriptor.builtIns.anyType append(": ").append(IdeDescriptorRenderers.SOURCE_CODE.renderType(typeToRender)) } append(" = ") append(initializerText) }.let { psiFactory.createProperty(it) } } var anchor = calculateAnchor(commonParent, commonContainer, allReplaces) ?: return val needBraces = commonContainer !is KtBlockExpression && commonContainer !is KtClassBody && commonContainer !is KtFile if (!needBraces) { property = commonContainer.addBefore(property, anchor) as KtDeclaration commonContainer.addBefore(psiFactory.createNewLine(), anchor) } else { var emptyBody: KtExpression = psiFactory.createEmptyBody() val firstChild = emptyBody.firstChild emptyBody.addAfter(psiFactory.createNewLine(), firstChild) if (replaceOccurrence) { for (replace in allReplaces) { val exprAfterReplace = replaceExpression(replace, false) exprAfterReplace.isOccurrence = true if (anchor == replace) { anchor = exprAfterReplace } } var oldElement: PsiElement = commonContainer if (commonContainer is KtWhenEntry) { val body = commonContainer.expression if (body != null) { oldElement = body } } else if (commonContainer is KtContainerNode) { val children = commonContainer.children for (child in children) { if (child is KtExpression) { oldElement = child } } } //ugly logic to make sure we are working with right actual expression var actualExpression = reference?.element ?: return var diff = actualExpression.textRange.startOffset - oldElement.textRange.startOffset var actualExpressionText = actualExpression.text val newElement = emptyBody.addAfter(oldElement, firstChild) var elem: PsiElement? = findElementByOffsetAndText(diff, actualExpressionText, newElement) if (elem != null) { reference = SmartPointerManager.createPointer(elem as KtExpression) } emptyBody.addAfter(psiFactory.createNewLine(), firstChild) property = emptyBody.addAfter(property, firstChild) as KtDeclaration emptyBody.addAfter(psiFactory.createNewLine(), firstChild) actualExpression = reference?.element ?: return diff = actualExpression.textRange.startOffset - emptyBody.textRange.startOffset actualExpressionText = actualExpression.text emptyBody = anchor.replace(emptyBody) as KtBlockExpression elem = findElementByOffsetAndText(diff, actualExpressionText, emptyBody) if (elem != null) { reference = SmartPointerManager.createPointer(elem as KtExpression) } emptyBody.accept( object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { if (!expression.isOccurrence) return expression.isOccurrence = false references.add(SmartPointerManager.createPointer(expression)) } }) } else { val parent = anchor.parent val copyTo = parent.lastChild val copyFrom = anchor.nextSibling property = emptyBody.addAfter(property, firstChild) as KtDeclaration emptyBody.addAfter(psiFactory.createNewLine(), firstChild) if (copyFrom != null && copyTo != null) { emptyBody.addRangeAfter(copyFrom, copyTo, property) parent.deleteChildRange(copyFrom, copyTo) } emptyBody = anchor.replace(emptyBody) as KtBlockExpression } for (child in emptyBody.children) { if (child is KtProperty) { property = child } } if (commonContainer is KtContainerNode) { if (commonContainer.parent is KtIfExpression) { val next = commonContainer.nextSibling if (next != null) { val nextnext = next.nextSibling if (nextnext != null && nextnext.node.elementType == KtTokens.ELSE_KEYWORD) { if (next is PsiWhiteSpace) { next.replace(psiFactory.createWhiteSpace()) } } } } } } if (!needBraces) { for (i in allReplaces.indices) { val replace = allReplaces[i] if (if (i != 0) replaceOccurrence else replace.shouldReplaceOccurrence(bindingContext, commonContainer)) { replaceExpression(replace, true) } else { val sibling = PsiTreeUtil.skipSiblingsBackward(replace, PsiWhiteSpace::class.java) if (sibling == property) { replace.parent.deleteChildRange(property.nextSibling, replace) } else { replace.delete() } } } } propertyRef = property if (noTypeInference) { ShortenReferences.DEFAULT.process(property) } } fun runRefactoring(isVar: Boolean) { if (commonContainer !is KtDeclarationWithBody) return runRefactoring( isVar, expression, commonContainer, commonParent, allReplaces ) commonContainer.bodyExpression.sure { "Original body is not found: $commonContainer" } expression.putCopyableUserData(EXPRESSION_KEY, true) for (replace in allReplaces) { replace.substringContextOrThis.putCopyableUserData(REPLACE_KEY, true) } commonParent.putCopyableUserData(COMMON_PARENT_KEY, true) val newDeclaration = ConvertToBlockBodyIntention.convert(commonContainer) val newCommonContainer = newDeclaration.bodyBlockExpression.sure { "New body is not found: $newDeclaration" } val newExpression = newCommonContainer.findExpressionByCopyableDataAndClearIt(EXPRESSION_KEY) val newCommonParent = newCommonContainer.findElementByCopyableDataAndClearIt(COMMON_PARENT_KEY) val newAllReplaces = (allReplaces zip newCommonContainer.findExpressionsByCopyableDataAndClearIt(REPLACE_KEY)).map { val (originalReplace, newReplace) = it originalReplace.extractableSubstringInfo?.let { originalReplace.apply { extractableSubstringInfo = it.copy(newReplace as KtStringTemplateExpression) } } ?: newReplace } runRefactoring( isVar, newExpression ?: return, newCommonContainer, newCommonParent ?: return, newAllReplaces ) } } private fun calculateAnchor(commonParent: PsiElement, commonContainer: PsiElement, allReplaces: List<KtExpression>): PsiElement? { if (commonParent != commonContainer) return commonParent.parentsWithSelf.firstOrNull { it.parent == commonContainer } val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr -> min(offset, expr.substringContextOrThis.startOffset) } return commonContainer.allChildren.lastOrNull { it.textRange.contains(startOffset) } } private fun PsiElement.isAssignmentLHS(): Boolean = parents.any { KtPsiUtil.isAssignment(it) && (it as KtBinaryExpression).left == this } private fun KtExpression.findOccurrences(occurrenceContainer: PsiElement): List<KtExpression> = toRange().match(occurrenceContainer, KotlinPsiUnifier.DEFAULT).mapNotNull { val candidate = it.range.elements.first() if (candidate.isAssignmentLHS()) return@mapNotNull null when (candidate) { is KtExpression -> candidate is KtStringTemplateEntryWithExpression -> candidate.expression else -> throw KotlinExceptionWithAttachments("Unexpected candidate element ${candidate::class.java}") .withAttachment("candidate.kt", candidate.text) } } private fun KtExpression.shouldReplaceOccurrence(bindingContext: BindingContext, container: PsiElement?): Boolean { val effectiveParent = (parent as? KtScriptInitializer)?.parent ?: parent return isUsedAsExpression(bindingContext) || container != effectiveParent } private fun KtElement.getContainer(): KtElement? { if (this is KtBlockExpression) return this return (parentsWithSelf.zip(parents)).firstOrNull { val (place, parent) = it when (parent) { is KtContainerNode -> !parent.isBadContainerNode(place) is KtBlockExpression -> true is KtWhenEntry -> place == parent.expression is KtDeclarationWithBody -> parent.bodyExpression == place is KtClassBody -> true is KtFile -> true else -> false } }?.second as? KtElement } private fun KtContainerNode.isBadContainerNode(place: PsiElement): Boolean = when (val parent = parent) { is KtIfExpression -> parent.condition == place is KtLoopExpression -> parent.body != place is KtArrayAccessExpression -> true else -> false } private fun KtExpression.getOccurrenceContainer(): KtElement? { var result: KtElement? = null for ((place, parent) in parentsWithSelf.zip(parents)) { when { parent is KtContainerNode && place !is KtBlockExpression && !parent.isBadContainerNode(place) -> result = parent parent is KtClassBody || parent is KtFile -> return result ?: parent as? KtElement parent is KtBlockExpression -> result = parent parent is KtWhenEntry && place !is KtBlockExpression -> result = parent parent is KtDeclarationWithBody && parent.bodyExpression == place && place !is KtBlockExpression -> result = parent } } return null } private fun showErrorHint(project: Project, editor: Editor?, @NlsContexts.DialogMessage message: String) { CommonRefactoringUtil.showErrorHint(project, editor, message, INTRODUCE_VARIABLE, HelpID.INTRODUCE_VARIABLE) } private fun KtExpression.chooseApplicableComponentFunctionsForVariableDeclaration( haveOccurrencesToReplace: Boolean, editor: Editor?, callback: (List<FunctionDescriptor>) -> Unit ) { if (haveOccurrencesToReplace) return callback(emptyList()) return chooseApplicableComponentFunctions(this, editor, callback = callback) } private fun executeMultiDeclarationTemplate( project: Project, editor: Editor, declaration: KtDestructuringDeclaration, suggestedNames: List<Collection<String>>, postProcess: (KtDeclaration) -> Unit ) { StartMarkAction.canStart(editor)?.let { return } val builder = TemplateBuilderImpl(declaration) for ((index, entry) in declaration.entries.withIndex()) { val templateExpression = object : Expression() { private val lookupItems = suggestedNames[index].map { LookupElementBuilder.create(it) }.toTypedArray() override fun calculateQuickResult(context: ExpressionContext?) = TextResult(suggestedNames[index].first()) override fun calculateResult(context: ExpressionContext?) = calculateQuickResult(context) override fun calculateLookupItems(context: ExpressionContext?) = lookupItems } builder.replaceElement(entry, templateExpression) } val startMarkAction = StartMarkAction.start(editor, project, INTRODUCE_VARIABLE) editor.caretModel.moveToOffset(declaration.startOffset) project.executeWriteCommand(INTRODUCE_VARIABLE) { TemplateManager.getInstance(project).startTemplate( editor, builder.buildInlineTemplate(), object : TemplateEditingAdapter() { private fun finishMarkAction() = FinishMarkAction.finish(project, editor, startMarkAction) override fun templateFinished(template: Template, brokenOff: Boolean) { if (!brokenOff) postProcess(declaration) finishMarkAction() } override fun templateCancelled(template: Template?) = finishMarkAction() } ) } } private fun doRefactoring( project: Project, editor: Editor?, expression: KtExpression, container: KtElement, occurrenceContainer: KtElement, resolutionFacade: ResolutionFacade, bindingContext: BindingContext, isVar: Boolean, occurrencesToReplace: List<KtExpression>?, onNonInteractiveFinish: ((KtDeclaration) -> Unit)? ) { val substringInfo = expression.extractableSubstringInfo val physicalExpression = expression.substringContextOrThis val parent = physicalExpression.parent when { parent is KtQualifiedExpression -> { if (parent.receiverExpression != physicalExpression) { return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression")) } } physicalExpression is KtStatementExpression -> return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression")) parent is KtOperationExpression && parent.operationReference == physicalExpression -> return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression")) } PsiTreeUtil.getNonStrictParentOfType( physicalExpression, KtTypeReference::class.java, KtConstructorCalleeExpression::class.java, KtSuperExpression::class.java, KtConstructorDelegationReferenceExpression::class.java, KtAnnotationEntry::class.java )?.let { return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.container")) } val expressionType = substringInfo?.type ?: bindingContext.getType(physicalExpression) //can be null or error type val scope = physicalExpression.getResolutionScope(bindingContext, resolutionFacade) val dataFlowInfo = bindingContext.getDataFlowInfoAfter(physicalExpression) val bindingTrace = ObservableBindingTrace(BindingTraceContext()) val typeNoExpectedType = substringInfo?.type ?: physicalExpression.computeTypeInfoInContext(scope, physicalExpression, bindingTrace, dataFlowInfo).type val noTypeInference = expressionType != null && typeNoExpectedType != null && !TypeCheckerImpl(project).equalTypes(expressionType, typeNoExpectedType) if (expressionType == null && bindingContext.get(BindingContext.QUALIFIER, physicalExpression) != null) { return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.package.expression")) } if (expressionType != null && KotlinBuiltIns.isUnit(expressionType)) { return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.expression.has.unit.type")) } val typeArgumentList = getQualifiedTypeArgumentList(KtPsiUtil.safeDeparenthesize(physicalExpression)) val isInplaceAvailable = editor != null && !ApplicationManager.getApplication().isUnitTestMode val allOccurrences = occurrencesToReplace ?: expression.findOccurrences(occurrenceContainer) val callback = Pass<OccurrencesChooser.ReplaceChoice> { replaceChoice -> val allReplaces = when (replaceChoice) { OccurrencesChooser.ReplaceChoice.ALL -> allOccurrences else -> listOf(expression) } val replaceOccurrence = substringInfo != null || expression.shouldReplaceOccurrence(bindingContext, container) || allReplaces.size > 1 val commonParent = if (allReplaces.isNotEmpty()) { PsiTreeUtil.findCommonParent(allReplaces.map { it.substringContextOrThis }) as KtElement } else { expression.parent as KtElement } var commonContainer = commonParent as? KtFile ?: commonParent.getContainer()!! if (commonContainer != container && container.isAncestor(commonContainer, true)) { commonContainer = container } fun postProcess(declaration: KtDeclaration) { if (typeArgumentList != null) { val initializer = when (declaration) { is KtProperty -> declaration.initializer is KtDestructuringDeclaration -> declaration.initializer else -> null } ?: return runWriteAction { addTypeArgumentsIfNeeded(initializer, typeArgumentList) } } if (editor != null && !replaceOccurrence) { editor.caretModel.moveToOffset(declaration.endOffset) } } physicalExpression.chooseApplicableComponentFunctionsForVariableDeclaration(replaceOccurrence, editor) { componentFunctions -> val validator = NewDeclarationNameValidator( commonContainer, calculateAnchor(commonParent, commonContainer, allReplaces), NewDeclarationNameValidator.Target.VARIABLES ) val suggestedNames = if (componentFunctions.isNotEmpty()) { val collectingValidator = CollectingNameValidator(filter = validator) componentFunctions.map { suggestNamesForComponent(it, project, collectingValidator) } } else { KotlinNameSuggester.suggestNamesByExpressionAndType( expression, substringInfo?.type, bindingContext, validator, "value" ).let(::listOf) } val introduceVariableContext = IntroduceVariableContext( expression, suggestedNames, allReplaces, commonContainer, commonParent, replaceOccurrence, noTypeInference, expressionType, componentFunctions, bindingContext, resolutionFacade ) project.executeCommand(INTRODUCE_VARIABLE, null) { runWriteAction { introduceVariableContext.runRefactoring(isVar) } val property = introduceVariableContext.propertyRef ?: return@executeCommand if (editor == null) { onNonInteractiveFinish?.invoke(property) return@executeCommand } editor.caretModel.moveToOffset(property.textOffset) editor.selectionModel.removeSelection() if (!isInplaceAvailable) { postProcess(property) return@executeCommand } PsiDocumentManager.getInstance(project).commitDocument(editor.document) PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) when (property) { is KtProperty -> { KotlinVariableInplaceIntroducer( property, introduceVariableContext.reference?.element, introduceVariableContext.references.mapNotNull { it.element }.toTypedArray(), suggestedNames.single(), isVar, /*todo*/ false, expressionType, noTypeInference, project, editor, ::postProcess ).startInplaceIntroduceTemplate() } is KtDestructuringDeclaration -> { executeMultiDeclarationTemplate(project, editor, property, suggestedNames, ::postProcess) } else -> throw AssertionError("Unexpected declaration: ${property.getElementTextWithContext()}") } } } } if (isInplaceAvailable && occurrencesToReplace == null) { val chooser = object : OccurrencesChooser<KtExpression>(editor) { override fun getOccurrenceRange(occurrence: KtExpression): TextRange? { return occurrence.extractableSubstringInfo?.contentRange ?: occurrence.textRange } } ApplicationManager.getApplication().invokeLater { chooser.showChooser(expression, allOccurrences, callback) } } else { callback.pass(OccurrencesChooser.ReplaceChoice.ALL) } } private fun PsiElement.isFunExpressionOrLambdaBody(): Boolean { if (isFunctionalExpression()) return true val parent = parent as? KtFunction ?: return false return parent.bodyExpression == this && (parent is KtFunctionLiteral || parent.isFunctionalExpression()) } private fun KtExpression.getCandidateContainers( resolutionFacade: ResolutionFacade, originalContext: BindingContext ): List<Pair<KtElement, KtElement>> { val physicalExpression = substringContextOrThis val contentRange = extractableSubstringInfo?.contentRange val file = physicalExpression.containingKtFile val references = physicalExpression.collectDescendantsOfType<KtReferenceExpression> { contentRange == null || contentRange.contains(it.textRange) } fun isResolvableNextTo(neighbour: KtExpression): Boolean { val scope = neighbour.getResolutionScope(originalContext, resolutionFacade) val newContext = physicalExpression.analyzeInContext(scope, neighbour) val project = file.project return references.all { val originalDescriptor = originalContext[BindingContext.REFERENCE_TARGET, it] if (originalDescriptor is ValueParameterDescriptor && (originalContext[BindingContext.AUTO_CREATED_IT, originalDescriptor] == true)) { return@all originalDescriptor.containingDeclaration.source.getPsi().isAncestor(neighbour, true) } val newDescriptor = newContext[BindingContext.REFERENCE_TARGET, it] compareDescriptors(project, newDescriptor, originalDescriptor) } } val firstContainer = physicalExpression.getContainer() ?: return emptyList() val firstOccurrenceContainer = physicalExpression.getOccurrenceContainer() ?: return emptyList() val containers = SmartList(firstContainer) val occurrenceContainers = SmartList(firstOccurrenceContainer) if (!firstContainer.isFunExpressionOrLambdaBody()) return listOf(firstContainer to firstOccurrenceContainer) val lambdasAndContainers = ArrayList<Pair<KtExpression, KtElement>>().apply { var container = firstContainer do { var lambda: KtExpression = container.getNonStrictParentOfType<KtFunction>()!! if (lambda is KtFunctionLiteral) lambda = lambda.parent as? KtLambdaExpression ?: return@apply if (!isResolvableNextTo(lambda)) return@apply container = lambda.getContainer() ?: return@apply add(lambda to container) } while (container.isFunExpressionOrLambdaBody()) } lambdasAndContainers.mapTo(containers) { it.second } lambdasAndContainers.mapTo(occurrenceContainers) { it.first.getOccurrenceContainer() } return ArrayList<Pair<KtElement, KtElement>>().apply { for ((container, occurrenceContainer) in (containers zip occurrenceContainers)) { if (occurrenceContainer == null) continue add(container to occurrenceContainer) } } } fun doRefactoring( project: Project, editor: Editor?, expressionToExtract: KtExpression?, isVar: Boolean, occurrencesToReplace: List<KtExpression>?, onNonInteractiveFinish: ((KtDeclaration) -> Unit)? ) { val expression = expressionToExtract?.let { KtPsiUtil.safeDeparenthesize(it) } ?: return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression")) if (expression.isAssignmentLHS()) { return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression")) } if (!CommonRefactoringUtil.checkReadOnlyStatus(project, expression)) return val physicalExpression = expression.substringContextOrThis val resolutionFacade = physicalExpression.getResolutionFacade() val bindingContext = resolutionFacade.analyze(physicalExpression, BodyResolveMode.FULL) fun runWithChosenContainers(container: KtElement, occurrenceContainer: KtElement) { doRefactoring( project, editor, expression, container, occurrenceContainer, resolutionFacade, bindingContext, isVar, occurrencesToReplace, onNonInteractiveFinish ) } val candidateContainers = expression.getCandidateContainers(resolutionFacade, bindingContext).ifEmpty { return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.container")) } if (editor == null) { return candidateContainers.first().let { runWithChosenContainers(it.first, it.second) } } if (ApplicationManager.getApplication().isUnitTestMode) { return candidateContainers.last().let { runWithChosenContainers(it.first, it.second) } } chooseContainerElementIfNecessary(candidateContainers, editor, KotlinBundle.message("text.select.target.code.block"), true, { it.first }) { runWithChosenContainers(it.first, it.second) } } override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) { if (file !is KtFile) return try { selectElement(editor, file, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) { doRefactoring(project, editor, it as KtExpression?, false, null, null) } } catch (e: IntroduceRefactoringException) { showErrorHint(project, editor, e.message!!) } } override fun invoke(project: Project, elements: Array<PsiElement>, dataContext: DataContext) { //do nothing } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt
1234953295
// 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 com.intellij.internal.statistic.collectors.fus.os import com.intellij.internal.DebugAttachDetector import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventId1 import com.intellij.internal.statistic.eventLog.events.EventId2 import com.intellij.internal.statistic.eventLog.events.EventId3 import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.utils.StatisticsUtil import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.Version import com.intellij.util.containers.ContainerUtil import com.intellij.util.lang.JavaVersion import com.intellij.util.system.CpuArch import com.sun.management.OperatingSystemMXBean import java.lang.management.ManagementFactory import java.util.* import kotlin.math.min import kotlin.math.roundToInt class SystemRuntimeCollector : ApplicationUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP override fun getMetrics(): Set<MetricEvent> { val result = HashSet<MetricEvent>() result.add(CORES.metric(StatisticsUtil.getUpperBound(Runtime.getRuntime().availableProcessors(), intArrayOf(1, 2, 4, 6, 8, 12, 16, 20, 24, 32, 64)))) val osMxBean = ManagementFactory.getOperatingSystemMXBean() as OperatingSystemMXBean val totalPhysicalMemory = StatisticsUtil.getUpperBound((osMxBean.totalPhysicalMemorySize.toDouble() / (1 shl 30)).roundToInt(), intArrayOf(1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 128, 256)) result.add(MEMORY_SIZE.metric(totalPhysicalMemory)) var totalSwapSize = (osMxBean.totalSwapSpaceSize.toDouble() / (1 shl 30)).roundToInt() totalSwapSize = min(totalSwapSize, totalPhysicalMemory) result.add(SWAP_SIZE.metric(if (totalSwapSize > 0) StatisticsUtil.getNextPowerOfTwo(totalSwapSize) else 0)) try { val totalSpace = PathManager.getIndexRoot().toFile().totalSpace if (totalSpace > 0L) { val indexDirPartitionSize = min(1 shl 14, // currently max available consumer hard drive size is around 16 Tb StatisticsUtil.getNextPowerOfTwo((totalSpace shr 30).toInt())) val indexDirPartitionFreeSpace = ((PathManager.getIndexRoot().toFile().usableSpace.toDouble() / totalSpace) * 100).toInt() result.add(DISK_SIZE.metric(indexDirPartitionSize, indexDirPartitionFreeSpace)) } } catch (uoe : UnsupportedOperationException) { // In case of some custom FS } catch (se : SecurityException) { // In case of Security Manager denies read of FS attributes } for (gc in ManagementFactory.getGarbageCollectorMXBeans()) { result.add(GC.metric(gc.name)) } result.add(JVM.metric( Version(1, JavaVersion.current().feature, 0), CpuArch.CURRENT.name.toLowerCase(Locale.ENGLISH), getJavaVendor()) ) val options: HashMap<String, Long> = collectJvmOptions() for (option in options) { result.add(JVM_OPTION.metric(option.key, option.value)) } for (clientProperty in splashClientProperties) { val value = System.getProperty(clientProperty) if (value != null) { result.add(JVM_CLIENT_PROPERTIES.metric(clientProperty, value.toBoolean())) } } result.add(DEBUG_AGENT.metric(DebugAttachDetector.isDebugEnabled())) return result } private fun collectJvmOptions(): HashMap<String, Long> { val options: HashMap<String, Long> = hashMapOf() for (argument in ManagementFactory.getRuntimeMXBean().inputArguments) { val data = convertOptionToData(argument) if (data != null) { options[data.first] = data.second } } return options } private fun getJavaVendor() : String { return when { SystemInfo.isJetBrainsJvm -> "JetBrains" SystemInfo.isOracleJvm -> "Oracle" SystemInfo.isIbmJvm -> "IBM" SystemInfo.isAzulJvm -> "Azul" else -> "Other" } } companion object { private val knownOptions = ContainerUtil.newHashSet( "-Xms", "-Xmx", "-XX:SoftRefLRUPolicyMSPerMB", "-XX:ReservedCodeCacheSize" ) //No -D prefix is required here private val splashClientProperties = arrayListOf( "splash", "nosplash" ) private val GROUP: EventLogGroup = EventLogGroup("system.runtime", 12) private val DEBUG_AGENT: EventId1<Boolean> = GROUP.registerEvent("debug.agent", EventFields.Enabled) private val CORES: EventId1<Int> = GROUP.registerEvent("cores", EventFields.Int("value")) private val MEMORY_SIZE: EventId1<Int> = GROUP.registerEvent("memory.size", EventFields.Int("gigabytes")) private val SWAP_SIZE: EventId1<Int> = GROUP.registerEvent("swap.size", EventFields.Int("gigabytes")) private val DISK_SIZE: EventId2<Int, Int> = GROUP.registerEvent("disk.size", EventFields.Int("index_partition_size"), EventFields.Int("index_partition_free")) private val GC: EventId1<String?> = GROUP.registerEvent("garbage.collector", EventFields.String( "name", arrayListOf("Shenandoah", "G1_Young_Generation", "G1_Old_Generation", "Copy", "MarkSweepCompact", "PS_MarkSweep", "PS_Scavenge", "ParNew", "ConcurrentMarkSweep") ) ) private val JVM: EventId3<Version?, String?, String?> = GROUP.registerEvent("jvm", EventFields.VersionByObject, EventFields.String("arch", arrayListOf("x86", "x86_64", "arm64", "other", "unknown")), EventFields.String("vendor", arrayListOf( "JetBrains", "Apple", "Oracle", "Sun", "IBM", "Azul", "Other")) ) private val JVM_OPTION: EventId2<String?, Long> = GROUP.registerEvent("jvm.option", EventFields.String("name", arrayListOf("Xmx", "Xms", "SoftRefLRUPolicyMSPerMB", "ReservedCodeCacheSize")), EventFields.Long("value") ) private val JVM_CLIENT_PROPERTIES: EventId2<String?, Boolean> = GROUP.registerEvent("jvm.client.properties", EventFields.String("name", splashClientProperties), EventFields.Boolean("value") ) fun convertOptionToData(arg: String): Pair<String, Long>? { val value = getMegabytes(arg).toLong() if (value < 0) return null when { arg.startsWith("-Xmx") -> { return "Xmx" to roundDown(value, 512, 750, 1000, 1024, 1500, 2000, 2048, 3000, 4000, 4096, 6000, 8000) } arg.startsWith("-Xms") -> { return "Xms" to roundDown(value, 64, 128, 256, 512) } arg.startsWith("-XX:SoftRefLRUPolicyMSPerMB") -> { return "SoftRefLRUPolicyMSPerMB" to roundDown(value, 50, 100) } arg.startsWith("-XX:ReservedCodeCacheSize") -> { return "ReservedCodeCacheSize" to roundDown(value, 240, 300, 400, 500) } else -> { return null } } } private fun getMegabytes(s: String): Int { var num = knownOptions.firstOrNull { s.startsWith(it) } ?.let { s.substring(it.length).toUpperCase().trim() } if (num == null) return -1 if (num.startsWith("=")) num = num.substring(1) if (num.last().isDigit()) { return try { Integer.parseInt(num) } catch (e: Exception) { -1 } } try { val size = Integer.parseInt(num.substring(0, num.length - 1)) when (num.last()) { 'B' -> return size / (1024 * 1024) 'K' -> return size / 1024 'M' -> return size 'G' -> return size * 1024 } } catch (e: Exception) { return -1 } return -1 } fun roundDown(value: Long, vararg steps: Long): Long { val length = steps.size if (length == 0 || steps[0] < 0) return -1 var ind = 0 while (ind < length && value >= steps[ind]) { ind++ } return if (ind == 0) 0 else steps[ind - 1] } } }
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/os/SystemRuntimeCollector.kt
2212341285
fun test(i: Int) { if (i == 1) { println(1) } else if (i == 2) { println(2) } else<caret> { println(3) } } fun println(i: Int) {}
plugins/kotlin/idea/tests/testData/intentions/removeBracesFromAllBranches/else.kt
1647565394
// "Create property 'foo'" "false" // ACTION: Rename reference // ERROR: Unresolved reference: foo class A<T>(val n: T) fun test() { val a: Int = A.<caret>foo }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/property/valOnClassNoClassObject.kt
661228312
// PROBLEM: none fun test(x:Int?, y:Int) { if (x != null && <caret>y >= x) { } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/dfa/intBoxed.kt
2380055192
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs import com.intellij.ui.tabs.impl.JBTabsImpl import com.intellij.util.ui.JBUI import java.awt.Component import java.awt.Insets import javax.swing.border.Border abstract class JBTabsBorder(val tabs: JBTabsImpl) : Border { val thickness: Int get() = if (tabs.tabPainter == null) JBUI.scale(1) else tabs.tabPainter.getTabTheme().topBorderThickness override fun getBorderInsets(c: Component?): Insets = JBUI.emptyInsets() override fun isBorderOpaque(): Boolean { return true } open val effectiveBorder: Insets get() = JBUI.emptyInsets() }
platform/platform-api/src/com/intellij/ui/tabs/JBTabsBorder.kt
2394706932
// 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 com.intellij.vcs.commit import com.intellij.diff.DiffContext import com.intellij.diff.DiffExtension import com.intellij.diff.FrameDiffTool import com.intellij.diff.actions.impl.OpenInEditorAction import com.intellij.diff.requests.DiffRequest import com.intellij.diff.requests.MessageDiffRequest import com.intellij.diff.tools.util.DiffDataKeys import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.diff.util.DiffUtil import com.intellij.internal.statistic.StructuredIdeActivity import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.AnActionResult import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.ChangesViewManager import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.ui.TreeActions import com.intellij.util.containers.ContainerUtil import java.awt.event.HierarchyEvent import java.awt.event.MouseEvent import java.util.* import javax.swing.JTree class CommitSessionCounterUsagesCollector : CounterUsagesCollector() { companion object { val GROUP = EventLogGroup("commit.interactions", 3) val FILES_TOTAL = EventFields.RoundedInt("files_total") val FILES_INCLUDED = EventFields.RoundedInt("files_included") val UNVERSIONED_TOTAL = EventFields.RoundedInt("unversioned_total") val UNVERSIONED_INCLUDED = EventFields.RoundedInt("unversioned_included") val SESSION = GROUP.registerIdeActivity("session", startEventAdditionalFields = arrayOf(FILES_TOTAL, FILES_INCLUDED, UNVERSIONED_TOTAL, UNVERSIONED_INCLUDED), finishEventAdditionalFields = arrayOf()) val EXCLUDE_FILE = GROUP.registerEvent("exclude.file", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent) val INCLUDE_FILE = GROUP.registerEvent("include.file", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent) val SELECT_FILE = GROUP.registerEvent("select.item", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent) val SHOW_DIFF = GROUP.registerEvent("show.diff") val CLOSE_DIFF = GROUP.registerEvent("close.diff") val JUMP_TO_SOURCE = GROUP.registerEvent("jump.to.source", EventFields.InputEventByAnAction) val COMMIT = GROUP.registerEvent("commit", FILES_INCLUDED, UNVERSIONED_INCLUDED) val COMMIT_AND_PUSH = GROUP.registerEvent("commit.and.push", FILES_INCLUDED, UNVERSIONED_INCLUDED) } override fun getGroup(): EventLogGroup = GROUP } @Service(Service.Level.PROJECT) class CommitSessionCollector(val project: Project) { companion object { @JvmStatic fun getInstance(project: Project): CommitSessionCollector = project.service() } private var activity: StructuredIdeActivity? = null private fun shouldTrackEvents(): Boolean { val mode = CommitModeManager.getInstance(project).getCurrentCommitMode() val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.COMMIT_TOOLWINDOW_ID) return toolWindow != null && mode is CommitMode.NonModalCommitMode && !mode.isToggleMode } private fun updateToolWindowState() { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.COMMIT_TOOLWINDOW_ID) val isSessionActive = shouldTrackEvents() && toolWindow?.isVisible == true if (!isSessionActive) { finishActivity() } else if (activity == null) { val changesViewManager = ChangesViewManager.getInstance(project) as ChangesViewManager val commitUi = changesViewManager.commitWorkflowHandler?.ui ?: return activity = CommitSessionCounterUsagesCollector.SESSION.started(project) { listOf( CommitSessionCounterUsagesCollector.FILES_TOTAL.with(commitUi.getDisplayedChanges().size), CommitSessionCounterUsagesCollector.FILES_INCLUDED.with(commitUi.getIncludedChanges().size), CommitSessionCounterUsagesCollector.UNVERSIONED_TOTAL.with(commitUi.getDisplayedUnversionedFiles().size), CommitSessionCounterUsagesCollector.UNVERSIONED_INCLUDED.with(commitUi.getIncludedUnversionedFiles().size) ) } } } private fun finishActivity() { activity?.finished() activity = null } fun logFileSelected(event: MouseEvent) { if (!shouldTrackEvents()) return CommitSessionCounterUsagesCollector.SELECT_FILE.log(project, null, event) } fun logFileSelected(event: AnActionEvent) { if (!shouldTrackEvents()) return CommitSessionCounterUsagesCollector.SELECT_FILE.log(project, event, null) } fun logInclusionToggle(excluded: Boolean, event: AnActionEvent) { if (!shouldTrackEvents()) return if (excluded) { CommitSessionCounterUsagesCollector.EXCLUDE_FILE.log(project, event, null) } else { CommitSessionCounterUsagesCollector.INCLUDE_FILE.log(project, event, null) } } fun logInclusionToggle(excluded: Boolean, event: MouseEvent) { if (!shouldTrackEvents()) return if (excluded) { CommitSessionCounterUsagesCollector.EXCLUDE_FILE.log(project, null, event) } else { CommitSessionCounterUsagesCollector.INCLUDE_FILE.log(project, null, event) } } fun logCommit(executorId: String?, includedChanges: Int, includedUnversioned: Int) { if (!shouldTrackEvents()) return if (executorId == "Git.Commit.And.Push.Executor") { CommitSessionCounterUsagesCollector.COMMIT_AND_PUSH.log(project, includedChanges, includedUnversioned) } else { CommitSessionCounterUsagesCollector.COMMIT.log(project, includedChanges, includedUnversioned) } finishActivity() updateToolWindowState() } fun logDiffViewer(isShown: Boolean) { if (!shouldTrackEvents()) return if (isShown) { CommitSessionCounterUsagesCollector.SHOW_DIFF.log(project) } else { CommitSessionCounterUsagesCollector.CLOSE_DIFF.log(project) } } fun logJumpToSource(event: AnActionEvent) { if (!shouldTrackEvents()) return CommitSessionCounterUsagesCollector.JUMP_TO_SOURCE.log(project, event) } internal class MyToolWindowManagerListener(val project: Project) : ToolWindowManagerListener { override fun stateChanged(toolWindowManager: ToolWindowManager) { getInstance(project).updateToolWindowState() } } internal class MyDiffExtension : DiffExtension() { private val HierarchyEvent.isShowingChanged get() = (changeFlags and HierarchyEvent.SHOWING_CHANGED.toLong()) != 0L override fun onViewerCreated(viewer: FrameDiffTool.DiffViewer, context: DiffContext, request: DiffRequest) { val project = context.project ?: return if (!DiffUtil.isUserDataFlagSet(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, context)) return if (request is MessageDiffRequest) return viewer.component.addHierarchyListener { e -> if (e.isShowingChanged) { if (e.component.isShowing) { getInstance(project).logDiffViewer(true) } else { getInstance(project).logDiffViewer(false) } } } } } /** * See [com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl] */ internal class MyAnActionListener : AnActionListener { private val ourStats: MutableMap<AnActionEvent, Project> = WeakHashMap() override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) { val project = event.project ?: return if (action is OpenInEditorAction) { val context = event.getData(DiffDataKeys.DIFF_CONTEXT) ?: return if (!DiffUtil.isUserDataFlagSet(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, context)) return ourStats[event] = project } if (action is TreeActions) { val component = event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as? JTree ?: return if (component.getClientProperty(ChangesTree.LOG_COMMIT_SESSION_EVENTS) != true) return ourStats[event] = project } } override fun afterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) { val project = ourStats.remove(event) ?: return if (!result.isPerformed) return if (action is OpenInEditorAction) { getInstance(project).logJumpToSource(event) } if (action is TreeActions) { getInstance(project).logFileSelected(event) } } } }
platform/vcs-impl/src/com/intellij/vcs/commit/CommitSessionCollector.kt
391750830
/* * Copyright 2010-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.kotlin.backend.konan import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.konan.file.File import org.jetbrains.kotlin.konan.target.CompilerOutputKind import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.library.KotlinLibrary import org.jetbrains.kotlin.library.resolver.KotlinLibraryResolveResult class CacheSupport( val configuration: CompilerConfiguration, resolvedLibraries: KotlinLibraryResolveResult, target: KonanTarget, produce: CompilerOutputKind ) { private val allLibraries = resolvedLibraries.getFullList() // TODO: consider using [FeaturedLibraries.kt]. private val fileToLibrary = allLibraries.associateBy { it.libraryFile } private val implicitCacheDirectories = configuration.get(KonanConfigKeys.CACHE_DIRECTORIES)!! .map { File(it).takeIf { it.isDirectory } ?: configuration.reportCompilationError("cache directory $it is not found or not a directory") } internal fun tryGetImplicitOutput(): String? { val libraryToAddToCache = configuration.get(KonanConfigKeys.LIBRARY_TO_ADD_TO_CACHE) ?: return null // Put the resulting library in the first cache directory. val cacheDirectory = implicitCacheDirectories.firstOrNull() ?: return null val libraryToAddToCacheFile = File(libraryToAddToCache) val library = allLibraries.single { it.libraryFile == libraryToAddToCacheFile } return cacheDirectory.child(CachedLibraries.getCachedLibraryName(library)).absolutePath } internal val cachedLibraries: CachedLibraries = run { val explicitCacheFiles = configuration.get(KonanConfigKeys.CACHED_LIBRARIES)!! val explicitCaches = explicitCacheFiles.entries.associate { (libraryPath, cachePath) -> val library = fileToLibrary[File(libraryPath)] ?: configuration.reportCompilationError("cache not applied: library $libraryPath in $cachePath") library to cachePath } val optimized = configuration.getBoolean(KonanConfigKeys.OPTIMIZATION) if (optimized && (explicitCacheFiles.isNotEmpty() || implicitCacheDirectories.isNotEmpty())) configuration.report(CompilerMessageSeverity.WARNING, "Cached libraries will not be used for optimized compilation") CachedLibraries( target = target, allLibraries = allLibraries, explicitCaches = if (optimized) emptyMap() else explicitCaches, implicitCacheDirectories = if (optimized) emptyList() else implicitCacheDirectories ) } private fun getLibrary(file: File) = fileToLibrary[file] ?: error("library to cache\n" + " ${file.absolutePath}\n" + "not found among resolved libraries:\n " + allLibraries.joinToString("\n ") { it.libraryFile.absolutePath }) internal val librariesToCache: Set<KotlinLibrary> = run { val libraryToAddToCachePath = configuration.get(KonanConfigKeys.LIBRARY_TO_ADD_TO_CACHE) if (libraryToAddToCachePath.isNullOrEmpty()) { configuration.get(KonanConfigKeys.LIBRARIES_TO_CACHE)!! .map { getLibrary(File(it)) } .toSet() .also { if (!produce.isCache) check(it.isEmpty()) } } else { val libraryToAddToCacheFile = File(libraryToAddToCachePath) val libraryToAddToCache = getLibrary(libraryToAddToCacheFile) val libraryCache = cachedLibraries.getLibraryCache(libraryToAddToCache) if (libraryCache == null) setOf(libraryToAddToCache) else emptySet() } } internal val preLinkCaches: Boolean = configuration.get(KonanConfigKeys.PRE_LINK_CACHES, false) init { // Ensure dependencies of every cached library are cached too: resolvedLibraries.getFullList { libraries -> libraries.map { library -> val cache = cachedLibraries.getLibraryCache(library.library) if (cache != null || library.library in librariesToCache) { library.resolvedDependencies.forEach { if (!cachedLibraries.isLibraryCached(it.library) && it.library !in librariesToCache) { val description = if (cache != null) { "cached (in ${cache.path})" } else { "going to be cached" } configuration.reportCompilationError( "${library.library.libraryName} is $description, " + "but its dependency isn't: ${it.library.libraryName}" ) } } } library } } // Ensure not making cache for libraries that are already cached: librariesToCache.forEach { val cache = cachedLibraries.getLibraryCache(it) if (cache != null) { configuration.reportCompilationError("Can't cache library '${it.libraryName}' " + "that is already cached in '${cache.path}'") } } if ((librariesToCache.isNotEmpty() || cachedLibraries.hasDynamicCaches || cachedLibraries.hasStaticCaches) && configuration.getBoolean(KonanConfigKeys.OPTIMIZATION)) { configuration.reportCompilationError("Cache cannot be used in optimized compilation") } } }
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/CacheSupport.kt
2362035297
package com.maubis.scarlet.base.main.sheets import android.app.Dialog import com.facebook.litho.ComponentContext import com.maubis.scarlet.base.support.sheets.LithoChooseOptionBottomSheet import com.maubis.scarlet.base.support.sheets.LithoChooseOptionsItem class GenericOptionsBottomSheet : LithoChooseOptionBottomSheet() { var title: Int = 0 var options: List<LithoChooseOptionsItem> = emptyList() override fun title(): Int = title override fun getOptions(componentContext: ComponentContext, dialog: Dialog): List<LithoChooseOptionsItem> = options }
base/src/main/java/com/maubis/scarlet/base/main/sheets/GenericOptionsBottomSheet.kt
1314692129
// FIR_IDENTICAL // FIR_COMPARISON class JustClass<T>(val p: T) fun <T, U> JustClass<T>.chainExt(p: U): JustClass<U> = TODO() // T - inferrable from 'JustClass<T>' => (T) // U - inferrable from 'p' => (T, U) fun test() { val chainExt: JustClass<String> = JustClass(1).chainExt("").<caret> } // ELEMENT: p
plugins/kotlin/completion/tests/testData/handlers/basic/typeArgsForGenericFun/Extension_receiverSufficient.kt
3804926267
// IS_APPLICABLE: false fun foo() { <caret>bar() } fun bar() { }
plugins/kotlin/fir/testData/intentions/useExpressionBody/convertToExpressionBody/funWithUnitType.kt
2348720664
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.graph import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CaptureRequest import android.hardware.camera2.CaptureResult import android.hardware.camera2.params.MeteringRectangle import android.os.Build import androidx.camera.camera2.pipe.FrameNumber import androidx.camera.camera2.pipe.Lock3ABehavior import androidx.camera.camera2.pipe.RequestNumber import androidx.camera.camera2.pipe.Result3A import androidx.camera.camera2.pipe.testing.FakeCameraMetadata import androidx.camera.camera2.pipe.testing.FakeFrameMetadata import androidx.camera.camera2.pipe.testing.FakeRequestMetadata import androidx.camera.camera2.pipe.testing.RobolectricCameraPipeTestRunner import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricCameraPipeTestRunner::class) @Config(minSdk = Build.VERSION_CODES.LOLLIPOP) internal class Controller3ALock3ATest { private val graphTestContext = GraphTestContext() private val graphState3A = graphTestContext.graphProcessor.graphState3A private val graphProcessor = graphTestContext.graphProcessor private val captureSequenceProcessor = graphTestContext.captureSequenceProcessor private val listener3A = Listener3A() private val fakeMetadata = FakeCameraMetadata( mapOf( CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES to intArrayOf(CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) ), ) private val controller3A = Controller3A(graphProcessor, fakeMetadata, graphState3A, listener3A) @After fun teardown() { graphTestContext.close() } @Test fun testAfImmediateAeImmediate() = runTest { val result = controller3A.lock3A( afLockBehavior = Lock3ABehavior.IMMEDIATE, aeLockBehavior = Lock3ABehavior.IMMEDIATE ) assertThat(result.isCompleted).isFalse() // Since requirement of to lock both AE and AF immediately, the requests to lock AE and AF // are sent right away. The result of lock3A call will complete once AE and AF have reached // their desired states. In this response i.e cameraResponse1, AF is still scanning so the // result won't be complete. val cameraResponse = async { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_PASSIVE_SCAN, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } cameraResponse.await() assertThat(result.isCompleted).isFalse() // One we we are notified that the AE and AF are in locked state, the result of lock3A call // will complete. launch { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_FOCUSED_LOCKED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } val result3A = result.await() assertThat(result3A.frameMetadata!!.frameNumber.value).isEqualTo(101L) assertThat(result3A.status).isEqualTo(Result3A.Status.OK) // We not check if the correct sequence of requests were submitted by lock3A call. The // request should be a repeating request to lock AE. val request1 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request1!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) // The second request should be a single request to lock AF. val request2 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request2!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_START ) assertThat(request2.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) } @Test fun testAfImmediateAeAfterCurrentScan() = runTest { val globalScope = CoroutineScope(UnconfinedTestDispatcher()) val lock3AAsyncTask = globalScope.async { controller3A.lock3A( afLockBehavior = Lock3ABehavior.IMMEDIATE, aeLockBehavior = Lock3ABehavior.AFTER_CURRENT_SCAN ) } assertThat(lock3AAsyncTask.isCompleted).isFalse() // Launch a task to repeatedly invoke a given capture result. globalScope.launch { while (true) { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult.CONTROL_AF_STATE_PASSIVE_SCAN, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_CONVERGED ) ) ) delay(FRAME_RATE_MS) } } val result = lock3AAsyncTask.await() // Result of lock3A call shouldn't be complete yet since the AE and AF are not locked yet. assertThat(result.isCompleted).isFalse() // Check the correctness of the requests submitted by lock3A. // One repeating request was sent to monitor the state of AE to get converged. captureSequenceProcessor.nextEvent().requestSequence // Once AE is converged, another repeatingrequest is sent to lock AE. val request1 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request1!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) globalScope.launch { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_FOCUSED_LOCKED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } val result3A = result.await() assertThat(result3A.frameMetadata!!.frameNumber.value).isEqualTo(101L) assertThat(result3A.status).isEqualTo(Result3A.Status.OK) // A single request to lock AF must have been used as well. val request2 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request2!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_START ) globalScope.cancel() } @Test fun testAfImmediateAeAfterNewScan() = runTest { val globalScope = CoroutineScope(UnconfinedTestDispatcher()) val lock3AAsyncTask = globalScope.async { controller3A.lock3A( afLockBehavior = Lock3ABehavior.IMMEDIATE, aeLockBehavior = Lock3ABehavior.AFTER_NEW_SCAN ) } assertThat(lock3AAsyncTask.isCompleted).isFalse() globalScope.launch { while (true) { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult.CONTROL_AF_STATE_PASSIVE_SCAN, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_CONVERGED ) ) ) delay(FRAME_RATE_MS) } } val result = lock3AAsyncTask.await() assertThat(result.isCompleted).isFalse() // For a new AE scan we first send a request to unlock AE just in case it was // previously or internally locked. val request1 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request1!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( false ) globalScope.launch { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_FOCUSED_LOCKED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } val result3A = result.await() assertThat(result3A.frameMetadata!!.frameNumber.value).isEqualTo(101L) assertThat(result3A.status).isEqualTo(Result3A.Status.OK) // There should be one more request to lock AE after new scan is done. val request2 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request2!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) // And one request to lock AF. val request3 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request3!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_START ) assertThat(request3.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) globalScope.cancel() } @Test fun testAfAfterCurrentScanAeImmediate() = runTest { val globalScope = CoroutineScope(UnconfinedTestDispatcher()) val lock3AAsyncTask = globalScope.async { controller3A.lock3A( afLockBehavior = Lock3ABehavior.AFTER_CURRENT_SCAN, aeLockBehavior = Lock3ABehavior.IMMEDIATE ) } assertThat(lock3AAsyncTask.isCompleted).isFalse() globalScope.launch { while (true) { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_CONVERGED ) ) ) delay(FRAME_RATE_MS) } } val result = lock3AAsyncTask.await() assertThat(result.isCompleted).isFalse() globalScope.launch { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_FOCUSED_LOCKED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } val result3A = result.await() assertThat(result3A.frameMetadata!!.frameNumber.value).isEqualTo(101L) assertThat(result3A.status).isEqualTo(Result3A.Status.OK) // There should be one request to monitor AF to finish it's scan. captureSequenceProcessor.nextEvent() // One request to lock AE val request2 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request2!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) // And one request to lock AF. val request3 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request3!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_START ) assertThat(request3.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) globalScope.cancel() } @Test fun testAfAfterNewScanScanAeImmediate() = runTest { val globalScope = CoroutineScope(UnconfinedTestDispatcher()) val lock3AAsyncTask = globalScope.async { controller3A.lock3A( afLockBehavior = Lock3ABehavior.AFTER_NEW_SCAN, aeLockBehavior = Lock3ABehavior.IMMEDIATE ) } assertThat(lock3AAsyncTask.isCompleted).isFalse() globalScope.launch { while (true) { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_CONVERGED ) ) ) delay(FRAME_RATE_MS) } } val result = lock3AAsyncTask.await() assertThat(result.isCompleted).isFalse() globalScope.launch { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_FOCUSED_LOCKED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } val result3A = result.await() assertThat(result3A.frameMetadata!!.frameNumber.value).isEqualTo(101L) assertThat(result3A.status).isEqualTo(Result3A.Status.OK) // One request to cancel AF to start a new scan. val request1 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request1!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_CANCEL ) // There should be one request to monitor AF to finish it's scan. captureSequenceProcessor.nextEvent() // There should be one request to monitor lock AE. val request2 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request2!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) // And one request to lock AF. val request3 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request3!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_START ) assertThat(request3.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) globalScope.cancel() } @Test fun testAfAfterCurrentScanAeAfterCurrentScan() = runTest { val globalScope = CoroutineScope(UnconfinedTestDispatcher()) val lock3AAsyncTask = globalScope.async { controller3A.lock3A( afLockBehavior = Lock3ABehavior.AFTER_CURRENT_SCAN, aeLockBehavior = Lock3ABehavior.AFTER_CURRENT_SCAN ) } assertThat(lock3AAsyncTask.isCompleted).isFalse() globalScope.launch { while (true) { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_CONVERGED ) ) ) delay(FRAME_RATE_MS) } } val result = lock3AAsyncTask.await() assertThat(result.isCompleted).isFalse() globalScope.launch { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_FOCUSED_LOCKED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } val result3A = result.await() assertThat(result3A.frameMetadata!!.frameNumber.value).isEqualTo(101L) assertThat(result3A.status).isEqualTo(Result3A.Status.OK) // There should be one request to monitor AF to finish it's scan. val event = captureSequenceProcessor.nextEvent() assertThat(event.requestSequence!!.repeating).isTrue() assertThat(event.rejected).isFalse() assertThat(event.abort).isFalse() assertThat(event.close).isFalse() assertThat(event.submit).isTrue() // One request to lock AE val request2Event = captureSequenceProcessor.nextEvent() assertThat(request2Event.requestSequence!!.repeating).isTrue() assertThat(request2Event.submit).isTrue() val request2 = request2Event.requestSequence!! assertThat(request2).isNotNull() assertThat(request2.requiredParameters).isNotEmpty() assertThat(request2.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) // And one request to lock AF. val request3Event = captureSequenceProcessor.nextEvent() assertThat(request3Event.requestSequence!!.repeating).isFalse() assertThat(request3Event.submit).isTrue() val request3 = request3Event.requestSequence!! assertThat(request3.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_START ) assertThat(request3.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) globalScope.cancel() } @Test fun testAfAfterNewScanScanAeAfterNewScan() = runTest { val globalScope = CoroutineScope(UnconfinedTestDispatcher()) val lock3AAsyncTask = globalScope.async { controller3A.lock3A( afLockBehavior = Lock3ABehavior.AFTER_NEW_SCAN, aeLockBehavior = Lock3ABehavior.AFTER_NEW_SCAN ) } assertThat(lock3AAsyncTask.isCompleted).isFalse() globalScope.launch { while (true) { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_CONVERGED ) ) ) delay(FRAME_RATE_MS) } } val result = lock3AAsyncTask.await() assertThat(result.isCompleted).isFalse() globalScope.launch { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_FOCUSED_LOCKED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } val result3A = result.await() assertThat(result3A.frameMetadata!!.frameNumber.value).isEqualTo(101L) assertThat(result3A.status).isEqualTo(Result3A.Status.OK) // One request to cancel AF to start a new scan. val request1 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request1!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_CANCEL ) // There should be one request to unlock AE and monitor the current AF scan to finish. val request2 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request2!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( false ) // There should be one request to monitor lock AE. val request3 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request3!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) // And one request to lock AF. val request4 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request4!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_START ) assertThat(request4.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) globalScope.cancel() } @Test fun testLock3AWithRegions() = runTest { val afMeteringRegion = MeteringRectangle(1, 1, 100, 100, 2) val aeMeteringRegion = MeteringRectangle(10, 15, 140, 140, 3) val result = controller3A.lock3A( aeRegions = listOf(aeMeteringRegion), afRegions = listOf(afMeteringRegion), afLockBehavior = Lock3ABehavior.IMMEDIATE, aeLockBehavior = Lock3ABehavior.IMMEDIATE ) assertThat(result.isCompleted).isFalse() // Since requirement of to lock both AE and AF immediately, the requests to lock AE and AF // are sent right away. The result of lock3A call will complete once AE and AF have reached // their desired states. In this response i.e cameraResponse1, AF is still scanning so the // result won't be complete. val cameraResponse = async { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_PASSIVE_SCAN, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } cameraResponse.await() assertThat(result.isCompleted).isFalse() // One we we are notified that the AE and AF are in locked state, the result of lock3A call // will complete. launch { listener3A.onRequestSequenceCreated( FakeRequestMetadata( requestNumber = RequestNumber(1) ) ) listener3A.onPartialCaptureResult( FakeRequestMetadata(requestNumber = RequestNumber(1)), FrameNumber(101L), FakeFrameMetadata( frameNumber = FrameNumber(101L), resultMetadata = mapOf( CaptureResult.CONTROL_AF_STATE to CaptureResult .CONTROL_AF_STATE_FOCUSED_LOCKED, CaptureResult.CONTROL_AE_STATE to CaptureResult.CONTROL_AE_STATE_LOCKED ) ) ) } val result3A = result.await() assertThat(result3A.frameMetadata!!.frameNumber.value).isEqualTo(101L) assertThat(result3A.status).isEqualTo(Result3A.Status.OK) val aeRegions = graphState3A.aeRegions!! assertThat(aeRegions.size).isEqualTo(1) assertThat(aeRegions[0]).isEqualTo(aeMeteringRegion) val afRegions = graphState3A.afRegions!! assertThat(afRegions.size).isEqualTo(1) assertThat(afRegions[0]).isEqualTo(afMeteringRegion) // We not check if the correct sequence of requests were submitted by lock3A call. The // request should be a repeating request to lock AE. val request1 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request1!!.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) // The second request should be a single request to lock AF. val request2 = captureSequenceProcessor.nextEvent().requestSequence assertThat(request2!!.requiredParameters[CaptureRequest.CONTROL_AF_TRIGGER]).isEqualTo( CaptureRequest.CONTROL_AF_TRIGGER_START ) assertThat(request2.requiredParameters[CaptureRequest.CONTROL_AE_LOCK]).isEqualTo( true ) } @Test fun testLock3AWithUnsupportedAutoFocusTrigger() = runTest { val fakeMetadata = FakeCameraMetadata( mapOf( CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES to intArrayOf(CaptureRequest.CONTROL_AF_MODE_OFF) ), ) val controller3A = Controller3A(graphProcessor, fakeMetadata, graphState3A, listener3A) val result = controller3A.lock3A(afLockBehavior = Lock3ABehavior.AFTER_NEW_SCAN).await() assertThat(result.status).isEqualTo(Result3A.Status.OK) assertThat(result.frameMetadata).isEqualTo(null) } companion object { // The time duration in milliseconds between two frame results. private const val FRAME_RATE_MS = 33L } }
camera/camera-camera2-pipe/src/test/java/androidx/camera/camera2/pipe/graph/Controller3ALock3ATest.kt
944770193
package charlie.laplacian.output interface OutputMethod { fun init() fun destroy() fun openDevice(outputSettings: OutputSettings): OutputDevice fun getMetadata(): OutputMethodMetadata fun getDeviceInfos(): Array<out OutputDeviceInfo> } interface OutputMethodMetadata { fun getName(): String fun getVersion(): String fun getVersionID(): Int } interface OutputDevice { fun openLine(): OutputLine fun closeLine(channel: OutputLine) } interface OutputDeviceInfo { fun getName(): String fun getAvailableSettings(): Array<OutputSettings> }
Laplacian.Framework/src/main/kotlin/charlie/laplacian/output/OutputDevice.kt
1971650646
class Yatzy(d1: Int, d2: Int, d3: Int, d4: Int, _5: Int) { protected var dice: IntArray = IntArray(5) init { dice[0] = d1 dice[1] = d2 dice[2] = d3 dice[3] = d4 dice[4] = _5 } fun fours(): Int { var sum: Int = 0 for (at in 0..4) { if (dice[at] == 4) { sum += 4 } } return sum } fun fives(): Int { var s = 0 var i: Int = 0 while (i < dice.size) { if (dice[i] == 5) s = s + 5 i++ } return s } fun sixes(): Int { var sum = 0 for (at in dice.indices) if (dice[at] == 6) sum = sum + 6 return sum } companion object { fun chance(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { var total = 0 total += d1 total += d2 total += d3 total += d4 total += d5 return total } fun yatzy(vararg dice: Int): Int { val counts = IntArray(6) for (die in dice) counts[die - 1]++ for (i in 0..5) if (counts[i] == 5) return 50 return 0 } fun ones(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { var sum = 0 if (d1 == 1) sum++ if (d2 == 1) sum++ if (d3 == 1) sum++ if (d4 == 1) sum++ if (d5 == 1) sum++ return sum } fun twos(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { var sum = 0 if (d1 == 2) sum += 2 if (d2 == 2) sum += 2 if (d3 == 2) sum += 2 if (d4 == 2) sum += 2 if (d5 == 2) sum += 2 return sum } fun threes(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { var s: Int = 0 if (d1 == 3) s += 3 if (d2 == 3) s += 3 if (d3 == 3) s += 3 if (d4 == 3) s += 3 if (d5 == 3) s += 3 return s } fun score_pair(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { val counts = IntArray(6) counts[d1 - 1]++ counts[d2 - 1]++ counts[d3 - 1]++ counts[d4 - 1]++ counts[d5 - 1]++ var at: Int at = 0 while (at != 6) { if (counts[6 - at - 1] >= 2) return (6 - at) * 2 at++ } return 0 } fun two_pair(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { val counts = IntArray(6) counts[d1 - 1]++ counts[d2 - 1]++ counts[d3 - 1]++ counts[d4 - 1]++ counts[d5 - 1]++ var n = 0 var score = 0 var i = 0 while (i < 6) { if (counts[6 - i - 1] >= 2) { n++ score += 6 - i } i += 1 } return if (n == 2) score * 2 else 0 } fun four_of_a_kind(_1: Int, _2: Int, d3: Int, d4: Int, d5: Int): Int { val tallies: IntArray = IntArray(6) tallies[_1 - 1]++ tallies[_2 - 1]++ tallies[d3 - 1]++ tallies[d4 - 1]++ tallies[d5 - 1]++ for (i in 0..5) if (tallies[i] >= 4) return (i + 1) * 4 return 0 } fun three_of_a_kind(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { val t: IntArray = IntArray(6) t[d1 - 1]++ t[d2 - 1]++ t[d3 - 1]++ t[d4 - 1]++ t[d5 - 1]++ for (i in 0..5) if (t[i] >= 3) return (i + 1) * 3 return 0 } fun smallStraight(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { val tallies: IntArray = IntArray(6) tallies[d1 - 1] += 1 tallies[d2 - 1] += 1 tallies[d3 - 1] += 1 tallies[d4 - 1] += 1 tallies[d5 - 1] += 1 return if (tallies[0] == 1 && tallies[1] == 1 && tallies[2] == 1 && tallies[3] == 1 && tallies[4] == 1 ) 15 else 0 } fun largeStraight(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { val tallies: IntArray = IntArray(6) tallies[d1 - 1] += 1 tallies[d2 - 1] += 1 tallies[d3 - 1] += 1 tallies[d4 - 1] += 1 tallies[d5 - 1] += 1 return if (tallies[1] == 1 && tallies[2] == 1 && tallies[3] == 1 && tallies[4] == 1 && tallies[5] == 1 ) 20 else 0 } fun fullHouse(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int { val tallies: IntArray var _2 = false var i: Int var _2_at = 0 var _3 = false var _3_at = 0 tallies = IntArray(6) tallies[d1 - 1] += 1 tallies[d2 - 1] += 1 tallies[d3 - 1] += 1 tallies[d4 - 1] += 1 tallies[d5 - 1] += 1 i = 0 while (i != 6) { if (tallies[i] == 2) { _2 = true _2_at = i + 1 } i += 1 } i = 0 while (i != 6) { if (tallies[i] == 3) { _3 = true _3_at = i + 1 } i += 1 } return if (_2 && _3) _2_at * 2 + _3_at * 3 else 0 } } }
kotlin/src/main/kotlin/Yatzy.kt
2032845083
// 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.completion.test.handlers import com.intellij.testFramework.common.runAll import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractKeywordCompletionHandlerTest import org.jetbrains.kotlin.idea.fir.invalidateCaches import org.jetbrains.kotlin.test.utils.IgnoreTests import org.jetbrains.kotlin.test.utils.withExtension import java.io.File abstract class AbstractFirKeywordCompletionHandlerTest : AbstractKeywordCompletionHandlerTest() { override val captureExceptions: Boolean = false override fun isFirPlugin(): Boolean = true override fun handleTestPath(path: String): File = IgnoreTests.getFirTestFileIfFirPassing(File(path), IgnoreTests.DIRECTIVES.FIR_COMPARISON, ".after") override fun tearDown() { runAll( { project.invalidateCaches() }, { super.tearDown() }, ) } override fun doTest(testPath: String) { IgnoreTests.runTestIfEnabledByFileDirective(dataFilePath(), IgnoreTests.DIRECTIVES.FIR_COMPARISON, ".after") { super.doTest(testPath) val originalTestFile = dataFile() IgnoreTests.cleanUpIdenticalFirTestFile( originalTestFile, additionalFileToMarkFirIdentical = originalTestFile.withExtension("kt.after"), additionalFileToDeleteIfIdentical = originalTestFile.withExtension("fir.kt.after"), additionalFilesToCompare = listOf(originalTestFile.withExtension("kt.after") to originalTestFile.withExtension("fir.kt.after")), ) } } }
plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/fir/completion/test/handlers/AbstractFirKeywordCompletionHandlerTest.kt
1744370652
// 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.openapi.vcs.changes.actions.diff import com.intellij.diff.tools.combined.* import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.Wrapper import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.toListIfNotMany import com.intellij.openapi.vcs.changes.ui.PresentableChange class CombinedChangeDiffComponentFactoryProvider : CombinedDiffComponentFactoryProvider { override fun create(model: CombinedDiffModel): CombinedDiffComponentFactory = MyFactory(model) private inner class MyFactory(model: CombinedDiffModel) : CombinedDiffComponentFactory(model) { init { model.init() } override fun createGoToChangeAction(): AnAction = MyGoToChangePopupAction() private inner class MyGoToChangePopupAction : PresentableGoToChangePopupAction.Default<PresentableChange>() { val viewer get() = model.context.getUserData(COMBINED_DIFF_VIEWER_KEY) override fun getChanges(): ListSelection<out PresentableChange> { val changes = if (model is CombinedDiffPreviewModel) model.iterateAllChanges().toList() else model.requests.values.filterIsInstance<PresentableChange>() val selected = viewer?.getCurrentBlockId() as? CombinedPathBlockId val selectedIndex = when { selected != null -> changes.indexOfFirst { it.tag == selected.tag && it.fileStatus == selected.fileStatus && it.filePath == selected.path } else -> -1 } return ListSelection.createAt(changes, selectedIndex) } override fun canNavigate(): Boolean { if (model is CombinedDiffPreviewModel) { val allChanges = toListIfNotMany(model.iterateAllChanges(), true) return allChanges == null || allChanges.size > 1 } return super.canNavigate() } override fun onSelected(change: PresentableChange) { if (model is CombinedDiffPreviewModel && change is Wrapper) { model.selected = change } else { viewer?.selectDiffBlock(CombinedPathBlockId(change.filePath, change.fileStatus, change.tag), ScrollPolicy.DIFF_BLOCK, true) } } } } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/CombinedChangeDiffComponentFactoryProvider.kt
1734125034
// WITH_DEFAULT_VALUE: false fun foo(vararg a: Int): Int { return (<selection>a.size + 1</selection>) * 2 } fun test() { foo() foo(1) foo(1, 2) }
plugins/kotlin/idea/tests/testData/refactoring/introduceParameter/varargs.kt
1700816418
class A { <caret>inner class B }
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantInnerClassModifier/noOuterClassMemberReference.kt
1480882674
// 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.ide.navbar.ui import com.intellij.ide.actions.OpenInRightSplitAction import com.intellij.ide.navbar.ide.NavBarVmItem import com.intellij.ide.navbar.impl.PsiNavBarItem import com.intellij.ide.navbar.vm.NavBarPopupItem import com.intellij.ide.navbar.vm.NavBarPopupVm import com.intellij.ide.navigationToolbar.NavBarListWrapper import com.intellij.ide.ui.UISettings import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.ThrowableComputable import com.intellij.ui.CollectionListModel import com.intellij.ui.LightweightHint import com.intellij.ui.PopupHandler import com.intellij.ui.popup.HintUpdateSupply import com.intellij.ui.speedSearch.ListWithFilter import com.intellij.util.SlowOperations import com.intellij.util.ui.JBUI import java.awt.Component import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.JComponent import javax.swing.JList internal fun createNavBarPopup(list: JList<NavBarPopupItem>): LightweightHint { // TODO implement async hint update supply HintUpdateSupply.installHintUpdateSupply(list) { item -> SlowOperations.allowSlowOperations(ThrowableComputable { ((item as? NavBarVmItem)?.pointer?.dereference() as? PsiNavBarItem)?.data }) } val popupComponent = list.withSpeedSearch() val popup = object : LightweightHint(popupComponent) { override fun onPopupCancel() { HintUpdateSupply.hideHint(list) } } popup.setFocusRequestor(popupComponent) popup.setForceShowAsPopup(true) return popup } internal fun navBarPopupList( vm: NavBarPopupVm, contextComponent: Component, floating: Boolean, ): JList<NavBarPopupItem> { val list = ContextJBList<NavBarPopupItem>(contextComponent) list.model = CollectionListModel(vm.items) list.cellRenderer = NavBarPopupListCellRenderer(floating) list.border = JBUI.Borders.empty(5) list.background = JBUI.CurrentTheme.Popup.BACKGROUND list.addListSelectionListener { vm.itemsSelected(list.selectedValuesList) } PopupHandler.installPopupMenu(list, NavBarContextMenuActionGroup(), ActionPlaces.NAVIGATION_BAR_POPUP) list.addMouseListener(object : MouseAdapter() { override fun mousePressed(e: MouseEvent) { if (!SystemInfo.isWindows) { click(e) } } override fun mouseReleased(e: MouseEvent) { if (SystemInfo.isWindows) { click(e) } } private fun click(e: MouseEvent) { if (!e.isPopupTrigger && e.clickCount == 1 && e.button == MouseEvent.BUTTON1) { vm.complete() } } }) return list } private fun JList<NavBarPopupItem>.withSpeedSearch(): JComponent { val wrapper = NavBarListWrapper(this) val component = ListWithFilter.wrap(this, wrapper) { item -> item.presentation.popupText ?: item.presentation.text } as ListWithFilter<*> wrapper.updateViewportPreferredSizeIfNeeded() // this fixes IDEA-301848 for some reason component.setAutoPackHeight(!UISettings.getInstance().showNavigationBarInBottom) OpenInRightSplitAction.overrideDoubleClickWithOneClick(component) return component }
platform/lang-impl/src/com/intellij/ide/navbar/ui/popup.kt
3327781193
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.merge import com.intellij.dvcs.DvcsUtil import com.intellij.ide.ui.laf.darcula.DarculaUIUtil.BW import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.CollectionComboBoxModel import com.intellij.ui.MutableCollectionComboBoxModel import com.intellij.ui.ScrollPaneFactory.createScrollPane import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.components.DropDownLink import com.intellij.ui.components.JBTextArea import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import git4idea.GitBranch import git4idea.branch.GitBranchUtil import git4idea.branch.GitBranchUtil.equalBranches import git4idea.commands.Git import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.config.GitExecutableManager import git4idea.config.GitMergeSettings import git4idea.config.GitVersionSpecialty.NO_VERIFY_SUPPORTED import git4idea.i18n.GitBundle import git4idea.merge.dialog.* import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.repo.GitRepositoryReader import git4idea.ui.ComboBoxWithAutoCompletion import net.miginfocom.layout.AC import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Insets import java.awt.event.ItemEvent import java.awt.event.KeyEvent import java.util.Collections.synchronizedMap import java.util.regex.Pattern import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED import javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED internal const val GIT_REF_PROTOTYPE_VALUE = "origin/long-enough-branch-name" internal fun createRepositoryField(repositories: List<GitRepository>, defaultRoot: VirtualFile? = null) = ComboBox(CollectionComboBoxModel(repositories)).apply { item = repositories.find { repo -> repo.root == defaultRoot } ?: repositories.first() renderer = SimpleListCellRenderer.create("") { DvcsUtil.getShortRepositoryName(it) } setUI(FlatComboBoxUI(outerInsets = Insets(BW.get(), BW.get(), BW.get(), 0))) } internal fun createSouthPanelWithOptionsDropDown(southPanel: JComponent, optionDropDown: DropDownLink<*>) = southPanel.apply { (southPanel.components[0] as JPanel).apply { (layout as BorderLayout).hgap = JBUI.scale(5) add(optionDropDown, BorderLayout.EAST) } } internal fun validateBranchExists(branchField: ComboBoxWithAutoCompletion<String>, emptyFieldMessage: @NlsContexts.DialogMessage String): ValidationInfo? { val value = branchField.getText() if (value.isNullOrEmpty()) { return ValidationInfo(emptyFieldMessage, branchField) } val items = (branchField.model as CollectionComboBoxModel).items if (items.none { equalBranches(it, value) }) { return ValidationInfo(GitBundle.message("merge.no.matching.branch.error"), branchField) } return null } class GitMergeDialog(private val project: Project, private val defaultRoot: VirtualFile, private val roots: List<VirtualFile>) : DialogWrapper(project) { val selectedOptions = mutableSetOf<GitMergeOption>() private val mergeSettings = project.service<GitMergeSettings>() private val repositories = DvcsUtil.sortRepositories(GitRepositoryManager.getInstance(project).repositories) private val allBranches = collectAllBranches() private val unmergedBranches = synchronizedMap(HashMap<GitRepository, Set<GitBranch>?>()) private val optionInfos = mutableMapOf<GitMergeOption, OptionInfo<GitMergeOption>>() private val popupBuilder = createPopupBuilder() private val repositoryField = createRepoField() private val branchField = createBranchField() private val commandPanel = createCommandPanel() private val optionsPanel = GitOptionsPanel(::optionChosen, ::getOptionInfo) private val commitMsgField = JBTextArea("") private val commitMsgPanel = createCommitMsgPanel() private val panel = createPanel() private val isNoVerifySupported = NO_VERIFY_SUPPORTED.existsIn(GitExecutableManager.getInstance().getVersion(project)) init { loadUnmergedBranchesInBackground() updateDialogTitle() setOKButtonText(GitBundle.message("merge.action.name")) loadSettings() updateBranchesField() // We call pack() manually. isAutoAdjustable = false init() window.minimumSize = JBDimension(200, 60) updateUi() validate() pack() } override fun createCenterPanel() = panel override fun getPreferredFocusedComponent() = branchField override fun doValidateAll(): List<ValidationInfo> = listOf(::validateBranchField).mapNotNull { it() } override fun createSouthPanel() = createSouthPanelWithOptionsDropDown(super.createSouthPanel(), createOptionsDropDown()) override fun getHelpId() = "reference.VersionControl.Git.MergeBranches" override fun doOKAction() { try { saveSettings() } finally { super.doOKAction() } } @NlsSafe fun getCommitMessage(): String = commitMsgField.text fun getSelectedRoot(): VirtualFile = repositoryField.item.root fun getSelectedBranch(): GitBranch = tryGetSelectedBranch() ?: error("Unable to find branch: ${branchField.getText().orEmpty()}") private fun tryGetSelectedBranch() = getSelectedRepository().branches.findBranchByName(branchField.getText().orEmpty()) fun shouldCommitAfterMerge() = !isOptionSelected(GitMergeOption.NO_COMMIT) private fun saveSettings() { mergeSettings.branch = branchField.getText() mergeSettings.options = selectedOptions } private fun loadSettings() { branchField.item = mergeSettings.branch mergeSettings.options .filter { option -> option != GitMergeOption.NO_VERIFY || isNoVerifySupported } .forEach { option -> selectedOptions += option } } private fun collectAllBranches() = repositories.associateWith { repo -> repo.branches .let { it.localBranches + it.remoteBranches } .map { it.name } } private fun loadUnmergedBranchesInBackground() { ProgressManager.getInstance().run( object : Task.Backgroundable(project, GitBundle.message("merge.branch.loading.branches.progress"), true) { override fun run(indicator: ProgressIndicator) { val sortedRoots = LinkedHashSet<VirtualFile>(roots.size).apply { add(defaultRoot) addAll(roots) } sortedRoots.forEach { root -> val repository = getRepository(root) loadUnmergedBranchesForRoot(repository)?.let { branches -> unmergedBranches[repository] = branches } } } }) } /** * ``` * $ git branch --all --format=... * |refs/heads/master [] * |refs/heads/feature [] * |refs/heads/checked-out [] * |refs/heads/checked-out-by-worktree [] * |refs/remotes/origin/master [] * |refs/remotes/origin/feature [] * |refs/remotes/origin/HEAD [refs/remotes/origin/master] * ``` */ @RequiresBackgroundThread private fun loadUnmergedBranchesForRoot(repository: GitRepository): Set<GitBranch>? { val root = repository.root try { val handler = GitLineHandler(project, root, GitCommand.BRANCH) handler.addParameters(UNMERGED_BRANCHES_FORMAT, "--no-color", "--all", "--no-merged") val result = Git.getInstance().runCommand(handler) result.throwOnError() val remotes = repository.remotes return result.output.asSequence() .mapNotNull { line -> val matcher = BRANCH_NAME_REGEX.matcher(line) when { matcher.matches() -> matcher.group(1) else -> null } } .mapNotNull { refName -> GitRepositoryReader.parseBranchRef(remotes, refName) } .toSet() } catch (e: Exception) { LOG.warn("Failed to load unmerged branches for root: ${root}", e) return null } } private fun validateBranchField(): ValidationInfo? { val validationInfo = validateBranchExists(branchField, GitBundle.message("merge.no.branch.selected.error")) if (validationInfo != null) return validationInfo val selectedBranch = tryGetSelectedBranch() ?: return ValidationInfo(GitBundle.message("merge.no.matching.branch.error")) val selectedRepository = getSelectedRepository() val unmergedBranches = unmergedBranches[selectedRepository] ?: return null val selectedBranchMerged = !unmergedBranches.contains(selectedBranch) if (selectedBranchMerged) { return ValidationInfo(GitBundle.message("merge.branch.already.merged", selectedBranch), branchField) } return null } private fun updateBranchesField() { var branchToSelect = branchField.item val branches = splitAndSortBranches(getBranches()) val model = branchField.model as MutableCollectionComboBoxModel model.update(branches) if (branchToSelect == null || branchToSelect !in branches) { val repository = getSelectedRepository() val currentRemoteBranch = repository.currentBranch?.findTrackedBranch(repository)?.nameForRemoteOperations branchToSelect = branches.find { branch -> branch == currentRemoteBranch } ?: branches.getOrElse(0) { "" } } branchField.item = branchToSelect branchField.selectAll() } private fun splitAndSortBranches(branches: List<@NlsSafe String>): List<@NlsSafe String> { val local = mutableListOf<String>() val remote = mutableListOf<String>() for (branch in branches) { if (branch.startsWith(REMOTE_REF)) { remote += branch.substring(REMOTE_REF.length) } else { local += branch } } return GitBranchUtil.sortBranchNames(local) + GitBranchUtil.sortBranchNames(remote) } private fun getBranches(): List<@NlsSafe String> { val repository = getSelectedRepository() return allBranches[repository] ?: emptyList() } private fun getRepository(root: VirtualFile) = repositories.find { repo -> repo.root == root } ?: error("Unable to find repository for root: ${root.presentableUrl}") private fun getSelectedRepository() = getRepository(getSelectedRoot()) private fun updateDialogTitle() { val currentBranchName = getSelectedRepository().currentBranchName title = (if (currentBranchName.isNullOrEmpty()) GitBundle.message("merge.branch.title") else GitBundle.message("merge.branch.into.current.title", currentBranchName)) } private fun createPanel() = JPanel().apply { layout = MigLayout(LC().insets("0").hideMode(3), AC().grow()) add(commandPanel, CC().growX()) add(optionsPanel, CC().newline().width("100%").alignY("top")) add(commitMsgPanel, CC().newline().push().grow()) } private fun showRootField() = roots.size > 1 private fun createCommandPanel() = JPanel().apply { val colConstraints = if (showRootField()) AC().grow(100f, 0, 2) else AC().grow(100f, 1) layout = MigLayout( LC() .fillX() .insets("0") .gridGap("0", "0") .noVisualPadding(), colConstraints) if (showRootField()) { add(repositoryField, CC() .gapAfter("0") .minWidth("${JBUI.scale(135)}px") .growX()) } add(createCmdLabel(), CC() .gapAfter("0") .alignY("top") .minWidth("${JBUI.scale(100)}px")) add(branchField, CC() .alignY("top") .minWidth("${JBUI.scale(300)}px") .growX()) } private fun createRepoField() = createRepositoryField(repositories, defaultRoot).apply { addItemListener { e -> if (e.stateChange == ItemEvent.SELECTED && e.item != null) { updateDialogTitle() updateBranchesField() } } } private fun createCmdLabel() = CmdLabel("git merge", Insets(1, if (showRootField()) 0 else 1, 1, 0), JBDimension(JBUI.scale(100), branchField.preferredSize.height, true)) private fun createBranchField() = ComboBoxWithAutoCompletion(MutableCollectionComboBoxModel(mutableListOf<String>()), project).apply { prototypeDisplayValue = GIT_REF_PROTOTYPE_VALUE setPlaceholder(GitBundle.message("merge.branch.field.placeholder")) setUI(FlatComboBoxUI( outerInsets = Insets(BW.get(), 0, BW.get(), BW.get()), popupEmptyText = GitBundle.message("merge.branch.popup.empty.text"))) } private fun createCommitMsgPanel() = JPanel().apply { layout = MigLayout(LC().insets("0").fill()) isVisible = false add(JLabel(GitBundle.message("merge.commit.message.label")), CC().alignY("top").wrap()) add(createScrollPane(commitMsgField, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED), CC() .alignY("top") .grow() .push() .minHeight("${JBUI.scale(75)}px")) } private fun createPopupBuilder() = GitOptionsPopupBuilder( project, GitBundle.message("merge.options.modify.popup.title"), ::getOptions, ::getOptionInfo, ::isOptionSelected, ::isOptionEnabled, ::optionChosen ) private fun createOptionsDropDown() = DropDownLink(GitBundle.message("merge.options.modify")) { popupBuilder.createPopup() }.apply { mnemonic = KeyEvent.VK_M } private fun isOptionSelected(option: GitMergeOption) = option in selectedOptions private fun getOptionInfo(option: GitMergeOption) = optionInfos.computeIfAbsent(option) { OptionInfo(option, option.option, option.description) } private fun getOptions(): List<GitMergeOption> = GitMergeOption.values().toMutableList().apply { if (!isNoVerifySupported) { remove(GitMergeOption.NO_VERIFY) } } private fun isOptionEnabled(option: GitMergeOption) = selectedOptions.all { it.isOptionSuitable(option) } private fun optionChosen(option: GitMergeOption) { if (!isOptionSelected(option)) { selectedOptions += option } else { selectedOptions -= option } updateUi() validate() pack() } private fun updateUi() { optionsPanel.rerender(selectedOptions) updateCommitMessagePanel() panel.invalidate() } private fun updateCommitMessagePanel() { val useCommitMsg = isOptionSelected(GitMergeOption.COMMIT_MESSAGE) commitMsgPanel.isVisible = useCommitMsg if (!useCommitMsg) { commitMsgField.text = "" } } companion object { private val LOG = logger<GitMergeDialog>() /** * Filter out 'symrefs' (ex: 'remotes/origin/HEAD -> origin/master') */ @Suppress("SpellCheckingInspection") private val UNMERGED_BRANCHES_FORMAT = "--format=%(refname) [%(symref)]" private val BRANCH_NAME_REGEX = Pattern.compile("(\\S+) \\[]") @NlsSafe private const val REMOTE_REF = "remotes/" } }
plugins/git4idea/src/git4idea/merge/GitMergeDialog.kt
2703987339
// 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.plugins.gradle.frameworkSupport.script import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.ArgumentElement import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.Statement.* import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.Statement.Expression.* import java.util.function.Consumer interface ScriptElementBuilder { fun newLine(): NewLineElement fun ScriptElement?.ln(): NewLineElement? fun int(value: Int): IntElement fun boolean(value: Boolean): BooleanElement fun string(value: String): StringElement fun list(elements: List<Expression>) : ListElement fun list(vararg elements: Expression) : ListElement fun list(vararg elements: String) : ListElement fun code(text: List<String>): CodeElement fun code(vararg text: String): CodeElement fun assign(left: Expression, right: Expression): AssignElement fun assign(left: Expression, right: String): AssignElement fun assign(left: Expression, right: Int): AssignElement fun assign(left: Expression, right: Boolean): AssignElement fun assign(name: String, value: Expression): AssignElement fun assign(name: String, value: String): AssignElement fun assign(name: String, value: Int): AssignElement fun assign(name: String, value: Boolean): AssignElement fun assignIfNotNull(name: String, expression: Expression?): AssignElement? fun assignIfNotNull(name: String, value: String?): AssignElement? fun plusAssign(name: String, value: Expression): PlusAssignElement fun plusAssign(name: String, value: String): PlusAssignElement fun property(name: String, value: Expression): PropertyElement fun property(name: String, value: String): PropertyElement fun property(name: String, value: Int): PropertyElement fun property(name: String, value: Boolean): PropertyElement fun call(name: Expression, arguments: List<ArgumentElement>): CallElement fun call(name: String, arguments: List<ArgumentElement>): CallElement fun call(name: String, arguments: List<ArgumentElement>, configure: ScriptTreeBuilder.() -> Unit): CallElement fun call(name: String): CallElement fun call(name: String, configure: Consumer<ScriptTreeBuilder>): CallElement fun call(name: String, configure: ScriptTreeBuilder.() -> Unit): CallElement fun call(name: String, vararg arguments: ArgumentElement): CallElement fun call(name: String, vararg arguments: ArgumentElement, configure: ScriptTreeBuilder.() -> Unit): CallElement fun call(name: String, vararg arguments: Expression): CallElement fun call(name: String, vararg arguments: Expression, configure: ScriptTreeBuilder.() -> Unit): CallElement fun call(name: String, vararg arguments: String): CallElement fun call(name: String, vararg arguments: String, configure: ScriptTreeBuilder.() -> Unit): CallElement fun call(name: String, vararg arguments: Pair<String, String>): CallElement fun call(name: String, vararg arguments: Pair<String, String>, configure: ScriptTreeBuilder.() -> Unit): CallElement fun callIfNotEmpty(name: String, block: BlockElement): CallElement? fun callIfNotEmpty(name: String, builder: ScriptTreeBuilder): CallElement? fun callIfNotEmpty(name: String, configure: ScriptTreeBuilder.() -> Unit): CallElement? fun infixCall(left: Expression, name: String, right: Expression): InfixCall fun argument(name: String?, value: Expression): ArgumentElement fun argument(name: String?, value: String): ArgumentElement fun argument(argument: Pair<String, String>): ArgumentElement fun argument(value: Expression): ArgumentElement fun argument(value: String): ArgumentElement fun argument(configure: ScriptTreeBuilder.() -> Unit): ArgumentElement fun block(configure: ScriptTreeBuilder.() -> Unit): BlockElement }
plugins/gradle/src/org/jetbrains/plugins/gradle/frameworkSupport/script/ScriptElementBuilder.kt
66498684
package de.mineformers.vanillaimmersion import de.mineformers.vanillaimmersion.block.Anvil import de.mineformers.vanillaimmersion.block.Beacon import de.mineformers.vanillaimmersion.block.BrewingStand import de.mineformers.vanillaimmersion.block.CraftingTable import de.mineformers.vanillaimmersion.block.EnchantingTable import de.mineformers.vanillaimmersion.block.Furnace import de.mineformers.vanillaimmersion.client.BeaconHandler import de.mineformers.vanillaimmersion.client.CraftingDragHandler import de.mineformers.vanillaimmersion.client.renderer.AnvilRenderer import de.mineformers.vanillaimmersion.client.renderer.BeaconRenderer import de.mineformers.vanillaimmersion.client.renderer.BrewingStandRenderer import de.mineformers.vanillaimmersion.client.renderer.CraftingTableRenderer import de.mineformers.vanillaimmersion.client.renderer.EnchantingTableRenderer import de.mineformers.vanillaimmersion.client.renderer.FurnaceRenderer import de.mineformers.vanillaimmersion.client.renderer.Shaders import de.mineformers.vanillaimmersion.config.Configuration import de.mineformers.vanillaimmersion.immersion.CraftingHandler import de.mineformers.vanillaimmersion.immersion.EnchantingHandler import de.mineformers.vanillaimmersion.item.Hammer import de.mineformers.vanillaimmersion.network.AnvilLock import de.mineformers.vanillaimmersion.network.AnvilText import de.mineformers.vanillaimmersion.network.BeaconScroll import de.mineformers.vanillaimmersion.network.CraftingDrag import de.mineformers.vanillaimmersion.network.GuiHandler import de.mineformers.vanillaimmersion.network.OpenGui import de.mineformers.vanillaimmersion.tileentity.AnvilLogic import de.mineformers.vanillaimmersion.tileentity.BeaconLogic import de.mineformers.vanillaimmersion.tileentity.BrewingStandLogic import de.mineformers.vanillaimmersion.tileentity.CraftingTableLogic import de.mineformers.vanillaimmersion.tileentity.EnchantingTableLogic import de.mineformers.vanillaimmersion.tileentity.FurnaceLogic import de.mineformers.vanillaimmersion.util.SubSelectionHandler import de.mineformers.vanillaimmersion.util.SubSelectionRenderer import net.minecraft.block.Block import net.minecraft.block.state.IBlockState import net.minecraft.client.renderer.block.model.ModelResourceLocation import net.minecraft.client.renderer.block.statemap.StateMapperBase import net.minecraft.init.Blocks import net.minecraft.item.Item import net.minecraft.tileentity.TileEntity import net.minecraft.util.ResourceLocation import net.minecraft.util.SoundEvent import net.minecraftforge.client.event.ModelRegistryEvent import net.minecraftforge.client.model.ModelLoader import net.minecraftforge.client.model.obj.OBJLoader import net.minecraftforge.common.MinecraftForge import net.minecraftforge.event.RegistryEvent import net.minecraftforge.fml.client.registry.ClientRegistry import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.common.Mod.EventHandler import net.minecraftforge.fml.common.SidedProxy import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.network.NetworkRegistry import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper import net.minecraftforge.fml.common.registry.ForgeRegistries import net.minecraftforge.fml.common.registry.GameRegistry import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.registries.IForgeRegistryEntry import org.apache.logging.log4j.LogManager /** * Main entry point for Vanilla Immersion */ @Mod(modid = VanillaImmersion.MODID, name = VanillaImmersion.MOD_NAME, version = VanillaImmersion.VERSION, acceptedMinecraftVersions = "*", dependencies = "required-after:forge;required-after:forgelin", updateJSON = "@UPDATE_URL@", modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter", guiFactory = "de.mineformers.vanillaimmersion.config.gui.GuiFactory", certificateFingerprint = "6c67ec97cb96c64a0bbd82a3cb1ec48cbde61bb2") object VanillaImmersion { const val MOD_NAME = "Vanilla Immersion" const val MODID = "vimmersion" const val VERSION = "@VERSION@" /** * Proxy for client- or server-specific code */ @SidedProxy lateinit var PROXY: Proxy /** * SimpleImpl network instance for client-server communication */ val NETWORK by lazy { SimpleNetworkWrapper(MODID) } /** * Logger for the mod to inform people about things. */ val LOG by lazy { LogManager.getLogger(MODID) } init { MinecraftForge.EVENT_BUS.register(BlockRegistration) MinecraftForge.EVENT_BUS.register(Items) MinecraftForge.EVENT_BUS.register(Sounds) } /** * Runs during the pre-initialization phase of mod loading, registers blocks, items etc. */ @EventHandler fun preInit(event: FMLPreInitializationEvent) { Configuration.load(event.modConfigurationDirectory, "vimmersion") if (!Configuration.shouldKeepVanilla("crafting_table")) { MinecraftForge.EVENT_BUS.register(CraftingHandler) } if (!Configuration.shouldKeepVanilla("enchanting_table")) { MinecraftForge.EVENT_BUS.register(EnchantingHandler) } MinecraftForge.EVENT_BUS.register(SubSelectionHandler) // Register messages and handlers NETWORK.registerMessage(AnvilLock.Handler, AnvilLock.Message::class.java, 0, Side.CLIENT) NETWORK.registerMessage(AnvilText.Handler, AnvilText.Message::class.java, 1, Side.SERVER) NETWORK.registerMessage(CraftingDrag.Handler, CraftingDrag.Message::class.java, 2, Side.SERVER) NETWORK.registerMessage(OpenGui.Handler, OpenGui.Message::class.java, 3, Side.SERVER) NETWORK.registerMessage(BeaconScroll.Handler, BeaconScroll.Message::class.java, 4, Side.SERVER) NetworkRegistry.INSTANCE.registerGuiHandler(this, GuiHandler()) PROXY.preInit(event) } /** * Verifies the JAR signature and logs a major warning if it is not present or invalid. * Note that this is *not* a viable security measure and only serves for users to verify the files they've downloaded. */ @EventHandler fun onFingerprintViolation(event: FMLFingerprintViolationEvent) { LOG.warn("Vanilla Immersion is running with an invalid JAR fingerprint, the version of the mod you're using may have been tampered with by third parties!") } /** * Holder object for all blocks introduced by this mod. */ object BlockRegistration { /** * Initializes and registers blocks and related data */ @SubscribeEvent fun init(event: RegistryEvent.Register<Block>) { // TODO: Unify interaction handling? if (!Configuration.shouldKeepVanilla("furnace")) { LOG.info("Overriding furnace with immersive version!") event.registry.register(Furnace(false)) event.registry.register(Furnace(true)) registerTileEntity(FurnaceLogic::class.java, "furnace") } if (!Configuration.shouldKeepVanilla("crafting_table")) { LOG.info("Overriding crafting table with immersive version!") event.registry.register(CraftingTable()) registerTileEntity(CraftingTableLogic::class.java, "crafting_table") } if (!Configuration.shouldKeepVanilla("anvil")) { LOG.info("Overriding anvil with immersive version!") event.registry.register(Anvil()) registerTileEntity(AnvilLogic::class.java, "anvil") } if (!Configuration.shouldKeepVanilla("enchanting_table")) { LOG.info("Overriding enchantment table with immersive version!") event.registry.register(EnchantingTable()) registerTileEntity(EnchantingTableLogic::class.java, "enchanting_table") } if (!Configuration.shouldKeepVanilla("brewing_stand")) { LOG.info("Overriding brewing stand with immersive version!") event.registry.register(BrewingStand()) registerTileEntity(BrewingStandLogic::class.java, "brewing_stand") } if (!Configuration.shouldKeepVanilla("beacon")) { LOG.info("Overriding beacon with immersive version!") event.registry.register(Beacon()) registerTileEntity(BeaconLogic::class.java, "beacon") } } private fun <T : TileEntity> registerTileEntity(clazz: Class<T>, name: String) { GameRegistry.registerTileEntity(clazz, "minecraft:$name") } } object Items { /** * Hammer for interaction with Anvil */ @JvmStatic @ObjectHolder("vimmersion:hammer") lateinit var HAMMER: Item /** * Initializes and registers blocks and related data */ @SubscribeEvent fun init(event: RegistryEvent.Register<Item>) { event.registry.register(Hammer()) } } /** * Holder object for all sound (events) added by this mod. */ object Sounds { /** * Page turn sound for enchantment table */ val ENCHANTING_PAGE_TURN = SoundEvent(ResourceLocation("$MODID:enchanting.page_turn")) /** * Initializes and registers sounds and related data */ @SubscribeEvent fun init(event: RegistryEvent.Register<SoundEvent>) { event.registry.register(ENCHANTING_PAGE_TURN.setRegistryName(ResourceLocation("$MODID:enchanting.page_turn"))) } } /** * Interface for client & server proxies */ interface Proxy { /** * Performs pre-initialization tasks for the proxy's side. */ fun preInit(event: FMLPreInitializationEvent) } /** * The client proxy serves as client-specific interface for the mod. * Code that may only be accessed on the client should be put here. */ @Mod.EventBusSubscriber(Side.CLIENT, modid = MODID) class ClientProxy : Proxy { override fun preInit(event: FMLPreInitializationEvent) { OBJLoader.INSTANCE.addDomain(MODID) // We don't have OBJ models yet, but maybe in the future? // Initialize (i.e. compile) shaders now, removes delay on initial use later on Shaders.init() // Register client-side block features if (!Configuration.shouldKeepVanilla("furnace")) { ClientRegistry.bindTileEntitySpecialRenderer(FurnaceLogic::class.java, FurnaceRenderer()) } if (!Configuration.shouldKeepVanilla("crafting_table")) { ClientRegistry.bindTileEntitySpecialRenderer(CraftingTableLogic::class.java, CraftingTableRenderer()) MinecraftForge.EVENT_BUS.register(CraftingDragHandler) } if (!Configuration.shouldKeepVanilla("anvil")) { ClientRegistry.bindTileEntitySpecialRenderer(AnvilLogic::class.java, AnvilRenderer()) } if (!Configuration.shouldKeepVanilla("enchanting_table")) { ClientRegistry.bindTileEntitySpecialRenderer(EnchantingTableLogic::class.java, EnchantingTableRenderer()) } if (!Configuration.shouldKeepVanilla("brewing_stand")) { ClientRegistry.bindTileEntitySpecialRenderer(BrewingStandLogic::class.java, BrewingStandRenderer()) } if (!Configuration.shouldKeepVanilla("beacon")) { ClientRegistry.bindTileEntitySpecialRenderer(BeaconLogic::class.java, BeaconRenderer()) MinecraftForge.EVENT_BUS.register(BeaconHandler) } // Register client-specific event handlers MinecraftForge.EVENT_BUS.register(SubSelectionRenderer) } companion object { private object OverrideStateMapper : StateMapperBase() { override fun getModelResourceLocation(state: IBlockState) = ModelResourceLocation(ResourceLocation(MODID, state.block.registryName!!.resourcePath), getPropertyString(state.properties)) } inline fun <T : IForgeRegistryEntry<T>> ifOwner(entry: IForgeRegistryEntry<T>, action: (T) -> Unit) { //TODO: Add proper override owner support } @JvmStatic @SubscribeEvent fun registerModels(event: ModelRegistryEvent) { ModelLoader.setCustomModelResourceLocation(Items.HAMMER, 0, ModelResourceLocation("$MODID:hammer", "inventory")) if (!Configuration.shouldKeepVanilla("furnace")) { ModelLoader.setCustomStateMapper(Blocks.FURNACE, OverrideStateMapper) ModelLoader.setCustomStateMapper(Blocks.LIT_FURNACE, OverrideStateMapper) } if (!Configuration.shouldKeepVanilla("crafting_table")) { ModelLoader.setCustomStateMapper(Blocks.CRAFTING_TABLE, OverrideStateMapper) } if (!Configuration.shouldKeepVanilla("anvil")) { ModelLoader.setCustomStateMapper(Blocks.ANVIL, OverrideStateMapper) } if (!Configuration.shouldKeepVanilla("enchanting_table")) { ModelLoader.setCustomStateMapper(Blocks.ENCHANTING_TABLE, OverrideStateMapper) } if (!Configuration.shouldKeepVanilla("brewing_stand")) { ModelLoader.setCustomStateMapper(Blocks.BREWING_STAND, OverrideStateMapper) } if (!Configuration.shouldKeepVanilla("beacon")) { ModelLoader.setCustomStateMapper(Blocks.BEACON, OverrideStateMapper) } } } } /** * The server proxy serves as server-specific interface for the mod. * Code that may only be accessed on the sver should be put here. */ class ServerProxy : Proxy { override fun preInit(event: FMLPreInitializationEvent) { } } }
src/main/kotlin/de/mineformers/vanillaimmersion/VanillaImmersion.kt
2725346218
// 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.refactoring.rename import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchScope import com.intellij.refactoring.rename.RenameJavaMethodProcessor import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReference import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReferenceDescriptorImpl import org.jetbrains.kotlin.idea.search.canHaveSyntheticGetter import org.jetbrains.kotlin.idea.search.canHaveSyntheticSetter import org.jetbrains.kotlin.idea.search.restrictToKotlinSources import org.jetbrains.kotlin.idea.search.syntheticGetter import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.filterIsInstanceWithChecker class KotlinAwareJavaGetterRenameProcessor : RenameJavaMethodProcessor() { override fun canProcessElement(element: PsiElement) = super.canProcessElement(element) && element !is KtLightMethod && element.cast<PsiMethod>().canHaveSyntheticGetter override fun findReferences( element: PsiElement, searchScope: SearchScope, searchInCommentsAndStrings: Boolean ): Collection<PsiReference> { val getters = super.findReferences(element, searchScope, searchInCommentsAndStrings) val setters = findSetterReferences(element, searchScope, searchInCommentsAndStrings).orEmpty() return getters + setters } private fun findSetterReferences( element: PsiElement, searchScope: SearchScope, searchInCommentsAndStrings: Boolean ): Collection<PsiReference>? { val getter = element as? PsiMethod ?: return null val propertyName = getter.syntheticGetter ?: return null val containingClass = getter.containingClass ?: return null val setterName = JvmAbi.setterName(propertyName.asString()) val restrictedToKotlinScope by lazy { searchScope.restrictToKotlinSources() } return containingClass .findMethodsByName(setterName, false) .filter { it.canHaveSyntheticSetter } .asSequence() .flatMap { super.findReferences(it, restrictedToKotlinScope, searchInCommentsAndStrings) .filterIsInstanceWithChecker<SyntheticPropertyAccessorReference> { accessor -> !accessor.getter } } .map { SyntheticPropertyAccessorReferenceDescriptorImpl(it.expression, getter = true) } .toList() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinAwareJavaGetterRenameProcessor.kt
1241769950