From 6632a5741fb50ac8efb15426491bee762e11ce11 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 23 Oct 2026 15:45:51 +0200 Subject: [PATCH 01/23] fix(projectional-editor): keep side transforms when the completion pattern changes A completion menu opened by typing next to a cell offers the side transforms of that border. When the pattern changed, the entries were rebuilt from the substitute actions of the anchor cell instead, so the side transforms were lost after the first key and a transform longer than one character could never be completed by typing it. The update now reuses the providers of the menu that was opened, as hasCodeCompletionActions already does. Co-Authored-By: Claude Opus 5.5 --- .../modelix/editor/text/backend/TextEditorServiceImpl.kt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt index 02e08222..662434e6 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt @@ -298,10 +298,14 @@ class TextEditorServiceImpl( pattern: String, ): EditorUpdateData = runWithCell(editorId, cellId) { updateChannel, cell -> - val providers = cell.getSubstituteActions().toList() + // The menu that was opened knows its providers: the side transforms of the anchor's border if it was + // opened by typing next to a cell, which the substitute actions of the cell do not include. + val entries = + updateChannel.editor.completionMenu?.updateActions(pattern) + ?: updateChannel.editor.loadCompletionEntries(cell.getSubstituteActions().toList(), pattern) updateChannel.createUpdate().copy( completionEntries = - updateChannel.editor.loadCompletionEntries(providers, pattern).mapIndexed { index, entry -> + entries.mapIndexed { index, entry -> CompletionMenuEntryData( id = index, matchingText = entry.getMatchingText(), From e7ac2b9f39483deba619312a9f80bfe15914e666 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 23 Oct 2026 15:48:12 +0200 Subject: [PATCH 02/23] feat(projectional-editor): support node attributes Node attributes (jetbrains.mps.lang.core.structure.NodeAttribute) wrap the cell of the node they are attached to, the first attribute outermost as in MPS. The notation of an attribute says where that node goes with the new `attributed` cell. Each layer is an ordinary cell creation call. The `attributed` cell derives the next layer inward from the model (the attribute's parent and its next attribute), so nothing is handed down while rendering and adding or removing an attribute only rebuilds the layers next to it. An attribute whose notation has no `attributed` cell is not rendered, and its check messages stay on the attributed node. Without any notation the reflective editor shows it around the node. The reflective editor no longer lists `smodelAttribute` as a child role. Adding an attribute needs no intention: typing the first constant in front of the `attributed` cell in front of a node adds it, and the first constant behind it behind the node. Where the caret is decides how it nests with the existing ones, the attributed concepts and `multiple` of the attribute info are respected, and where several nodes start at the same position the outermost one gets it. Deleting the attribute's own text removes it and keeps the node. In the notation language, `AttributedCell` is generated to `attributed { attributedConcept(...); multiple(...) }` from the concept's `@attribute info`. ReviewMigration gets a notation that uses it. Co-Authored-By: Claude Opus 5.5 --- .../editor/kernelf/CodeCompletionTest.kt | 6 +- .../editor/kernelf/NodeAttributeTest.kt | 293 ++++++++++++++ ...mps.notation.impl.baseLanguage.modelix.mps | 30 +- ...notation.generator.templates@generator.mps | 193 +++++++++ .../org.modelix.mps.notation.behavior.mps | 379 ++++++++++++++++++ .../org.modelix.mps.notation.constraints.mps | 145 +++++++ .../org.modelix.mps.notation.editor.mps | 15 + .../org.modelix.mps.notation.structure.mps | 7 + .../editor/ssr/mps/BaseLanguageTests.kt | 68 ++++ .../ssr/mps/LanguageAspectsFromMPSModules.kt | 5 + .../kotlin/org/modelix/editor/CellSpecBase.kt | 10 +- .../org/modelix/editor/CellTemplateBuilder.kt | 32 ++ .../org/modelix/editor/ConceptEditor.kt | 8 +- .../kotlin/org/modelix/editor/EditorAspect.kt | 2 + .../kotlin/org/modelix/editor/EditorEngine.kt | 143 +++++-- .../kotlin/org/modelix/editor/ICellAction.kt | 43 ++ .../org/modelix/editor/NodeAttributes.kt | 43 ++ .../celltemplate/AttributedCellTemplate.kt | 152 +++++++ .../text/backend/BackendEditorComponent.kt | 11 +- 19 files changed, 1545 insertions(+), 40 deletions(-) create mode 100644 kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt create mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/NodeAttributes.kt create mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/AttributedCellTemplate.kt diff --git a/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/CodeCompletionTest.kt b/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/CodeCompletionTest.kt index 334a6e73..5e84125c 100644 --- a/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/CodeCompletionTest.kt +++ b/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/CodeCompletionTest.kt @@ -140,9 +140,9 @@ class CodeCompletionTest { val knownDuplicates = setOf( "it", - "ParamRef { }", - "StripUnitExpression { }", - "ValExpression { }" + "ParamRef { }", + "StripUnitExpression { }", + "ValExpression { }" ) val actualDuplicates = actions.groupBy { it.getCompletionPattern() }.filter { it.value.size > 1 }.map { it.key } val unexpectedDuplicates = actualDuplicates - knownDuplicates diff --git a/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt b/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt new file mode 100644 index 00000000..2fd41633 --- /dev/null +++ b/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt @@ -0,0 +1,293 @@ +package org.modelix.editor.kernelf + +import kotlinx.coroutines.test.runTest +import org.iets3.core.expr.adt.C_NameAnnotation +import org.iets3.core.expr.base.C_ParensExpression +import org.iets3.core.expr.doc.C_BookmarkAnnotation +import org.iets3.core.expr.doc.C_DotDotDot +import org.iets3.core.expr.lambda.C_AttachedConstraint +import org.iets3.core.expr.simpleTypes.C_NumberLiteral +import org.iets3.core.expr.tests.C_OldNodeAnnotation +import org.modelix.editor.CaretSelection +import org.modelix.editor.Cell +import org.modelix.editor.EditorAspect +import org.modelix.editor.EditorEngine +import org.modelix.editor.FrontendEditorComponent +import org.modelix.editor.JSKeyboardEvent +import org.modelix.editor.JSKeyboardEventType +import org.modelix.editor.KeyLocation +import org.modelix.editor.Modifiers +import org.modelix.editor.descendants +import org.modelix.editor.layoutable +import org.modelix.editor.text.backend.TextEditorServiceImpl +import org.modelix.editor.text.frontend.getVisibleText +import org.modelix.incremental.IncrementalEngine +import org.modelix.kernelf.KernelfLanguages +import org.modelix.metamodel.untyped +import org.modelix.model.ModelFacade +import org.modelix.model.api.IBranch +import org.modelix.model.api.IConcept +import org.modelix.model.api.INode +import org.modelix.model.area.PArea +import org.modelix.model.withIncrementalComputationSupport +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Node attributes wrap the cell of the node they are attached to. The notation of an attribute says where that node + * goes with an `attributed` cell, and it is also how the attribute is added: typing the text in front of the + * `attributed` cell in front of the node, or the text behind it behind the node. + */ +class NodeAttributeTest { + private lateinit var literal: INode + private lateinit var parens: INode + private lateinit var editor: FrontendEditorComponent + private lateinit var service: TextEditorServiceImpl + private lateinit var branch: IBranch + + @Test + fun anAttributeWrapsTheNodeItIsAttachedTo() = + runAttributeTest { + addAttribute(C_BookmarkAnnotation.untyped()) { it.setPropertyValue("label", "b1") } + + assertEquals("(bookmark b1 200)", renderedText()) + } + + @Test + fun theFirstAttributeIsTheOutermost() = + runAttributeTest { + addAttribute(C_BookmarkAnnotation.untyped()) { it.setPropertyValue("label", "b1") } + addAttribute(C_DotDotDot.untyped()) + + assertEquals("(bookmark b1 todo 200)", renderedText()) + } + + @Test + fun anAttributeCanWriteSomethingBehindTheNode() = + runAttributeTest { + addAttribute(C_OldNodeAnnotation.untyped()) + addAttribute(C_DotDotDot.untyped()) + + assertEquals("(todo 200 !!)", renderedText()) + } + + @Test + fun anAttributeWhoseNotationHasNoAttributedCellIsNotRendered() = + runAttributeTest({ conceptEditor(C_NameAnnotation) { "name".constant() } }) { + // Rendering it would hide the node it is attached to. + addAttribute(C_NameAnnotation.untyped()) + + assertEquals("(200)", renderedText()) + } + + @Test + fun anAttributeWithoutANotationIsRenderedReflectivelyAroundTheNode() = + runAttributeTest { + addAttribute(C_AttachedConstraint.untyped()) + + val text = renderedText() + assertTrue(text.contains("attributed node:"), text) + assertTrue(text.contains("200"), text) + } + + @Test + fun removingAnAttributeUnwrapsTheNode() = + runAttributeTest { + val attribute = addAttribute(C_BookmarkAnnotation.untyped()) { it.setPropertyValue("label", "b1") } + branch.runWrite { literal.removeChild(attribute) } + editor.flushAndUpdateSelection { null } + + assertEquals("(200)", renderedText()) + } + + @Test + fun typingTheNotationInFrontOfANodeAddsTheAttribute() = + runAttributeTest { + typeBefore(cellWithText("200"), "bookmark") + + assertEquals(listOf("BookmarkAnnotation"), attributeConcepts()) + assertEquals("(bookmark 200)", renderedText()) + } + + @Test + fun typingTheNotationKeyByKeyAddsTheAttribute() = + runAttributeTest { + // As in the browser: the first key opens the completion menu of the left transform, the others extend + // its pattern until the single entry matches exactly. + editor.flushAndUpdateSelection { CaretSelection(editor, cellWithText("200").layoutable()!!, 0) } + editor.flush() + for (c in "bookmark") { + editor.processKeyEvent( + JSKeyboardEvent( + JSKeyboardEventType.KEYDOWN, + c.toString(), + null, + c.toString(), + Modifiers.NONE, + KeyLocation.STANDARD, + false, + false + ), + ) + editor.flush() + } + + assertEquals(listOf("BookmarkAnnotation"), attributeConcepts()) + } + + @Test + fun typingTheNotationBehindANodeAddsTheAttribute() = + runAttributeTest { + typeAfter(cellWithText("200"), "!!") + + assertEquals(listOf("OldNodeAnnotation"), attributeConcepts()) + } + + @Test + fun anAttributeTypedInFrontOfAnotherOneGoesOutsideOfIt() = + runAttributeTest { + addAttribute(C_DotDotDot.untyped()) + + typeBefore(cellWithText("todo"), "bookmark") + + assertEquals(listOf("BookmarkAnnotation", "DotDotDot"), attributeConcepts()) + } + + @Test + fun anAttributeTypedInFrontOfTheNodeGoesInsideTheExistingOnes() = + runAttributeTest { + addAttribute(C_DotDotDot.untyped()) + + typeBefore(cellWithText("200"), "bookmark") + + assertEquals(listOf("DotDotDot", "BookmarkAnnotation"), attributeConcepts()) + } + + @Test + fun anAttributeThatCannotBeRepeatedIsNotOfferedTwice() = + runAttributeTest { + addAttribute(C_BookmarkAnnotation.untyped()) { it.setPropertyValue("label", "b1") } + + typeBefore(cellWithText("200"), "bookmark") + + assertEquals(listOf("BookmarkAnnotation"), attributeConcepts()) + } + + @Test + fun anAttributeIsOnlyOfferedForTheConceptsItCanBeAttachedTo() = + runAttributeTest({ + conceptEditor(C_NameAnnotation) { + attributed { attributedConcept(C_ParensExpression.untyped()) } + "??".constant() + } + }) { + typeAfter(cellWithText("200"), "??") + + assertEquals(emptyList(), attributeConcepts()) + } + + @Test + fun deletingTheTextOfAnAttributeRemovesTheAttributeButNotTheNode() = + runAttributeTest { + addAttribute(C_BookmarkAnnotation.untyped()) { it.setPropertyValue("label", "b1") } + + editor.enqueueUpdate(service.executeDelete(editor.editorId, cellWithText("bookmark").getId())).await() + editor.flushAndUpdateSelection { null } + + assertEquals(emptyList(), attributeConcepts()) + branch.computeRead { assertEquals(listOf(literal), parens.getChildren("expr").toList()) } + assertEquals("(200)", renderedText()) + } + + private suspend fun addAttribute( + concept: IConcept, + init: (INode) -> Unit = {}, + ): INode { + val attribute = branch.computeWrite { literal.addNewChild("smodelAttribute", -1, concept).also(init) } + editor.flushAndUpdateSelection { null } + return attribute + } + + private suspend fun typeBefore( + cell: Cell, + text: String, + ) { + editor.enqueueUpdate(service.processTypedText(editor.editorId, cell.getId(), 0, -1, text)).await() + editor.flushAndUpdateSelection { null } + } + + private suspend fun typeAfter( + cell: Cell, + text: String, + ) { + val length = cell.getVisibleText()!!.length + editor.enqueueUpdate(service.processTypedText(editor.editorId, cell.getId(), length, length - 1, text)).await() + editor.flushAndUpdateSelection { null } + } + + private fun attributeConcepts(): List = + branch.computeRead { literal.getChildren("smodelAttribute").map { it.concept!!.getShortName() }.toList() } + + private fun cellWithText(text: String): Cell = + assertNotNull( + editor.getRootCell().descendants().firstOrNull { it.getVisibleText() == text }, + "No cell '$text' in ${renderedText()}" + ) + + private fun renderedText(): String = + editor + .getRootCell() + .layout + .toString() + .trim() + + private fun runAttributeTest( + extraNotations: EditorAspect.() -> Unit = {}, + body: suspend () -> Unit, + ) = runTest { + KernelfLanguages.registerAll() + branch = + ModelFacade + .toLocalBranch(ModelFacade.newLocalTree(useRoleIds = false)) + .withIncrementalComputationSupport() + branch.runWrite { + parens = PArea(branch).getRoot().addNewChild("root", -1, C_ParensExpression.untyped()) + literal = parens.addNewChild("expr", -1, C_NumberLiteral.untyped()) + literal.setPropertyValue("value", "200") + } + + val engine = EditorEngine(IncrementalEngine()) + KernelfEditor.register(engine) + attributeNotations().apply(extraNotations).register(engine) + service = TextEditorServiceImpl(engine, parens.asWritableNode().getModel(), backgroundScope) + editor = FrontendEditorComponent(service) + editor.editNode(parens.reference) + editor.flushAndUpdateSelection { null } + try { + body() + } finally { + editor.dispose() + service.dispose() + KernelfLanguages.languages.forEach { it.unregister() } + } + } + + private fun attributeNotations() = + EditorAspect().apply { + conceptEditor(C_BookmarkAnnotation) { + "bookmark".constant() + concept.label.cell() + attributed() + } + conceptEditor(C_DotDotDot) { + "todo".constant() + attributed { multiple(true) } + } + conceptEditor(C_OldNodeAnnotation) { + attributed { attributedConcept(C_NumberLiteral.untyped()) } + "!!".constant() + } + } +} diff --git a/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps b/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps index 3946cd56..2250c932 100644 --- a/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps +++ b/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps @@ -117,6 +117,7 @@ + @@ -8506,8 +8507,33 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps b/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps index 7b019044..57e3f23a 100644 --- a/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps +++ b/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps @@ -747,6 +747,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.behavior.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.behavior.mps index b362230f..83b45d3e 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.behavior.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.behavior.mps @@ -123,6 +123,7 @@ + @@ -169,12 +170,17 @@ + + + + + @@ -241,6 +247,7 @@ + @@ -2070,5 +2077,377 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.constraints.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.constraints.mps index cc6b471d..6b14ceb3 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.constraints.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.constraints.mps @@ -11,6 +11,7 @@ + @@ -26,6 +27,7 @@ + @@ -41,6 +43,7 @@ + @@ -48,15 +51,20 @@ + + + + + @@ -72,6 +80,9 @@ + + + @@ -142,6 +153,14 @@ + + + + + + + + @@ -158,6 +177,7 @@ + @@ -755,5 +775,130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps index fac11703..44373fae 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps @@ -1282,5 +1282,20 @@ + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps index dd463af4..879a637f 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps @@ -680,5 +680,12 @@ + + + + + + + diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index 27132553..300469a3 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -807,9 +807,77 @@ class BaseLanguageTests : TestBase("SimpleProject") { assertEquals("Inner", referenceCellText(classifierType, "classifier")) } + fun `test node attribute wraps the node it is attached to`() = + kotlinx.coroutines.test.runTest { + writeAction { + methodNode + .addNewChild(SMODEL_ATTRIBUTE, -1, REVIEW_MIGRATION) + .setPropertyValue(IPropertyReference.fromName("reasonShort"), "check") + } + assertFinalEditorText(""" + public class Class1 { + @Review(check) + public void method1() { + + } + } + """) + } + + fun `test typing the notation of a node attribute in front of a node adds it`() = + kotlinx.coroutines.test.runTest { + // The method's `public`, not the class's: both start the cells of several nodes, and the attribute goes + // to the outermost one, the method. + val methodPublic = + editor + .resolveCell(NodeCellReference(methodNode.getNodeReference())) + .single() + .descendantsAndSelf() + .first { it.getVisibleText() == "public" } + editor.doChangeSelection(CaretSelection(methodPublic.layoutable()!!, 0)) + // Typed key by key, as in the browser: the first key opens the completion menu of the left transform. + typeText("@Review") + editor.flush() + assertEquals( + listOf("ReviewMigration"), + readAction { + methodNode.getAllChildren().filter { it.getContainmentLink().getSimpleName() == "smodelAttribute" }.map { + it + .getConceptReference() + .getUID() + } + }.map { if (it == REVIEW_MIGRATION.getUID()) "ReviewMigration" else it }, + ) + assertFinalEditorText(""" + public class Class1 { + @Review + public void method1() { + + } + } + """) + } + + fun `test deleting the text of a node attribute removes it but keeps the node`() = + kotlinx.coroutines.test.runTest { + writeAction { methodNode.addNewChild(SMODEL_ATTRIBUTE, -1, REVIEW_MIGRATION) } + editor.flush() + placeCaretIntoCellWithText("@Review", 0) + pressKey(KnownKeys.Backspace) + assertFinalEditorText(""" + public class Class1 { + public void method1() { + + } + } + """) + } + companion object { /** `jetbrains.mps.baseLanguage`, as modelix spells a concept reference: `mps:/`. */ private const val BL = "mps:f3061a53-9226-4cc5-a443-f952ceaf5816/" + private val SMODEL_ATTRIBUTE = IChildLinkReference.fromName("smodelAttribute") + private val REVIEW_MIGRATION = ConceptReference("mps:ceab5195-25ea-4f22-9b92-103b95ca8c0c/8703179436979359238") private val TRIM_KIND = IPropertyReference.fromName("trimKind") } } diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/LanguageAspectsFromMPSModules.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/LanguageAspectsFromMPSModules.kt index 867ec394..484617ba 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/LanguageAspectsFromMPSModules.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/LanguageAspectsFromMPSModules.kt @@ -97,4 +97,9 @@ class LanguageAspectsFromMPSModules( if (needsUpdate) updateDescriptors() return conceptEditors[concept] ?: emptyList() } + + override fun getAllConceptEditors(): List { + if (needsUpdate) updateDescriptors() + return conceptEditors.values.flatten() + } } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellSpecBase.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellSpecBase.kt index 9797b607..a6cab073 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellSpecBase.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellSpecBase.kt @@ -46,9 +46,15 @@ fun Cell.isVisible() = sealed interface ILocalOrChildNodeCell +/** + * A cell that is created by its own [CellCreationCall], and therefore cached and updated independently of the cell + * that embeds it. That is a child node, or the node an attribute is attached to. + */ class ChildSpecReference( - val childNode: INode, -) : ILocalOrChildNodeCell + val call: CellCreationCall, +) : ILocalOrChildNodeCell { + constructor(childNode: INode) : this(NodeCellCreationCall(childNode.asWritableNode())) +} class CellSpec : CellSpecBase() diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellTemplateBuilder.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellTemplateBuilder.kt index fdf7c6c8..3035acd9 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellTemplateBuilder.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellTemplateBuilder.kt @@ -1,6 +1,7 @@ package org.modelix.editor import io.github.oshai.kotlinlogging.KotlinLogging +import org.modelix.editor.celltemplate.AttributedCellTemplate import org.modelix.editor.celltemplate.CellTemplate import org.modelix.editor.celltemplate.ChildCellTemplate import org.modelix.editor.celltemplate.ChoiceCellTemplate @@ -485,6 +486,16 @@ open class CellTemplateBuilder( .also(template::addChild) } + /** + * In the notation of a node attribute: the node the attribute is attached to. See [AttributedCellTemplate]. + */ + fun attributed(body: AttributedCellTemplateBuilder.() -> Unit = {}) { + AttributedCellTemplateBuilder(AttributedCellTemplate(template.concept), concept, nodeConverter) + .also(body) + .template + .also(template::addChild) + } + fun modelAccess(body: ModelAccessBuilder.() -> Unit) { var setter: ((String?) -> Unit)? = null var getter: () -> String? = { "" } @@ -572,6 +583,27 @@ class PropertyCellTemplateBuilder( } } +class AttributedCellTemplateBuilder( + template: AttributedCellTemplate, + concept: ConceptT, + nodeConverter: INodeConverter, +) : CellTemplateBuilder(template, concept, nodeConverter) { + /** + * Restricts the concepts the attribute can be attached to. Called once per concept of the attribute's + * `@attribute info`. Without any call, the attribute can be attached to any node. + */ + fun attributedConcept(attributedConcept: IConcept) { + (template as AttributedCellTemplate).attributedConcepts += attributedConcept + } + + /** + * Allows a node to have several attributes of this concept. + */ + fun multiple(value: Boolean) { + (template as AttributedCellTemplate).multiple = value + } +} + class ChoiceCellTemplateBuilder( template: ChoiceCellTemplate, concept: ConceptT, diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ConceptEditor.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ConceptEditor.kt index 6decc8ba..baeaed2e 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ConceptEditor.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ConceptEditor.kt @@ -65,7 +65,8 @@ val defaultConceptEditor = // model, so an unnamed target is worth more as its node id than as a placeholder. link.cell(presentation = { defaultReferencePresentation() ?: reference.serialize() }) } - for (link in subConcept.getAllChildLinks()) { + // Node attributes wrap the node's cell instead of being listed as its children. + for (link in subConcept.getAllChildLinks().filterNot { it.isSmodelAttribute() }) { newLine() label(link.getSimpleName() + ":") if (link.isMultiple) { @@ -77,6 +78,11 @@ val defaultConceptEditor = link.cell() } } + if (subConcept.isNodeAttribute()) { + newLine() + label("attributed node:") + attributed() + } } }.template as NotationRootCellTemplate } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorAspect.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorAspect.kt index 79ed937b..08690365 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorAspect.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorAspect.kt @@ -51,4 +51,6 @@ class EditorAspect : ILanguageAspect { interface IConceptEditorRegistry { fun getConceptEditors(concept: IConceptReference): List + + fun getAllConceptEditors(): List } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt index 00e0f8a5..1ef3e91a 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt @@ -4,8 +4,11 @@ import org.modelix.checks.CheckMessage import org.modelix.checks.CheckMessageTarget import org.modelix.checks.ModelCheckAspect import org.modelix.checks.addCheckMessages +import org.modelix.editor.celltemplate.AttributedCellTemplate import org.modelix.editor.celltemplate.CellTemplate +import org.modelix.editor.celltemplate.NotationRootCellTemplate import org.modelix.editor.celltemplate.ParserForEditor +import org.modelix.editor.celltemplate.descendants import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.editor.text.shared.celltree.IMutableCellTree import org.modelix.editor.text.shared.celltree.cellReferences @@ -62,26 +65,87 @@ class EditorEngine( when (call) { is NodeCellCreationCall -> { val node = call.node.asLegacyNode() - val cellData = doCreateCellData(editorState, node) - cellData.properties[CommonCellProperties.node] = node.toNonExisting() - cellData.properties[CommonCellProperties.cellCall] = call - // Messages whose target cell (a property or reference cell) is rendered are attached to that - // cell by the respective cell template. Everything else is attached here, to the node's own cell: - // - whole-node messages (they underline the node's whole cell range; the range is derived by - // the renderer, which walks up the cell tree from each layoutable), - // - targeted messages whose feature cell the editor does not render, - // - all messages of descendants that are not rendered at all (this is the nearest visible ancestor). - val messages = - collectUnattachedOwnMessages(node, cellData) + - collectHiddenDescendantMessages(node, cellData) - if (messages.isNotEmpty()) applyCheckMessages(cellData, messages) - cellData.freeze() - LOG.trace { "Cell created for $node: $cellData" } - cellData + createAttributeLayerSpec(editorState, node, getNodeAttributeLayers(node).firstOrNull()) + } + + is AttributedNodeCellCreationCall -> { + createAttributeLayerSpec(editorState, call.node.asLegacyNode(), call.attribute?.asLegacyNode()) } } } + /** + * The cell of [node] wrapped by its node attributes from [attribute] inward. + * + * An attribute is rendered by its own notation, which contains an `attributed` cell for the next layer inward + * (see [AttributedCellTemplate]). So the layer *is* the attribute's node cell, and attributes of the attribute + * apply to it the same way. Below the innermost attribute is the node's own notation. + */ + private fun createAttributeLayerSpec( + cellTreeState: CellTreeState, + node: INode, + attribute: INode?, + ): CellSpecBase { + if (attribute != null) { + return createCellSpecIncremental(cellTreeState, NodeCellCreationCall(attribute.asWritableNode())) + } + + val cellData = doCreateCellData(cellTreeState, node) + cellData.properties[CommonCellProperties.node] = node.toNonExisting() + cellData.properties[CommonCellProperties.cellCall] = AttributedNodeCellCreationCall(node.asWritableNode(), null) + // Messages whose target cell (a property or reference cell) is rendered are attached to that + // cell by the respective cell template. Everything else is attached here, to the node's own cell: + // - whole-node messages (they underline the node's whole cell range; the range is derived by + // the renderer, which walks up the cell tree from each layoutable), + // - targeted messages whose feature cell the editor does not render, + // - all messages of descendants that are not rendered at all (this is the nearest visible ancestor). + val messages = + collectUnattachedOwnMessages(node, cellData) + + collectHiddenDescendantMessages(node, cellData) + if (messages.isNotEmpty()) applyCheckMessages(cellData, messages) + cellData.freeze() + LOG.trace { "Cell created for $node: $cellData" } + return cellData + } + + /** + * The node attributes of [node] that wrap its cell, outermost first. This is the order MPS uses: the first + * attribute is the outermost one. + * + * An attribute only wraps the node if its notation contains an `attributed` cell. Otherwise rendering it would + * hide the node it is attached to, so it is not rendered at all, as before node attributes were supported. Its + * check messages are then shown on the attributed node. + */ + fun getNodeAttributeLayers(node: INode): List = node.getAttributes().filter { isRenderedAsLayer(it) } + + private fun isRenderedAsLayer(attribute: INode): Boolean { + val concept = attribute.concept ?: return false + if (!concept.isNodeAttribute()) return false + val template = + resolveConceptEditor(concept) + .asSequence() + .map { it.apply(concept) } + .firstOrNull { it.condition?.invoke(attribute) != false } ?: return false + return template.descendants(includeSelf = true).any { it is AttributedCellTemplate } + } + + /** + * The notations of node attributes that can be added in the editor, by typing the text of their notation next to + * the node they wrap. Only notations that render the attributed node qualify. + */ + fun getNodeAttributeTemplates(): List = + getAllConceptEditors() + .asSequence() + .mapNotNull { editor -> editor.declaredConcept?.let { editor to it } } + .filter { (_, concept) -> !concept.isAbstract() && concept.isNodeAttribute() } + .map { (editor, concept) -> editor.apply(concept) } + .filter { template -> template.descendants(includeSelf = true).any { it is AttributedCellTemplate } } + .distinctBy { it.concept.getUID() } + .toList() + + private fun getAllConceptEditors(): List = + editorsForConcept.values.flatten() + conceptEditorRegistries.flatMap { it.getAllConceptEditors() } + fun addRegistry(registry: IConceptEditorRegistry) { conceptEditorRegistries += registry } @@ -173,7 +237,7 @@ class EditorEngine( } is ChildSpecReference -> { - createCell(cellTreeState, childRef.childNode) + createCell(cellTreeState, childRef.call) } } if (childCell.getParent() != cell) { @@ -208,8 +272,13 @@ class EditorEngine( data.properties[CellActionProperties.substitute] = ReplaceNodeActionProvider(ExistingNode(node)) data.cellReferences += NodeCellReference(node.reference) - data.properties[CellActionProperties.transformBefore] = SideTransformNode(true, node) - data.properties[CellActionProperties.transformAfter] = SideTransformNode(false, node) + if (node.getAttributedNode() != null && node.concept?.isNodeAttribute() == true) { + data.properties[CellActionProperties.transformBefore] = AttributeLayerSideTransform(true, node) + data.properties[CellActionProperties.transformAfter] = AttributeLayerSideTransform(false, node) + } else { + data.properties[CellActionProperties.transformBefore] = SideTransformNode(true, node) + data.properties[CellActionProperties.transformAfter] = SideTransformNode(false, node) + } data.properties[CommonCellProperties.selectable] = true data.properties[CellActionProperties.delete] = DeleteNodeCellAction(node) return data @@ -239,6 +308,8 @@ class EditorEngine( ): List { val renderedChildren = HashSet() collectRenderedChildNodes(cellData, renderedChildren) + // Node attributes are not referenced by the node's own cell, they wrap it. + getNodeAttributeLayers(node).forEach { renderedChildren.add(it.reference) } return node.allChildren .filter { it.reference !in renderedChildren } .flatMap { allSubtreeMessages(it) } @@ -249,8 +320,17 @@ class EditorEngine( acc: MutableSet, ) { when (spec) { - is ChildSpecReference -> acc.add(spec.childNode.reference) - is CellSpecBase -> spec.children.forEach { collectRenderedChildNodes(it, acc) } + is ChildSpecReference -> { + acc.add( + spec.call.node + .asLegacyNode() + .reference + ) + } + + is CellSpecBase -> { + spec.children.forEach { collectRenderedChildNodes(it, acc) } + } } } @@ -379,8 +459,25 @@ private class RenderedFeatures { val references: MutableList = ArrayList() } -sealed class CellCreationCall +sealed class CellCreationCall { + abstract val node: IWritableNode +} +/** + * The cell of [node] as its parent embeds it: wrapped by all of its node attributes. + */ data class NodeCellCreationCall( - val node: IWritableNode, + override val node: IWritableNode, +) : CellCreationCall() + +/** + * The cell of [node] wrapped only by its node attributes from [attribute] inward, or the node's own notation if + * [attribute] is null. This is what the `attributed` cell of the attribute one layer further out renders. + * + * The next attribute is part of the call, rather than its position, so that adding or removing an attribute only + * changes the layers next to it. The cells of all other layers are reused. + */ +data class AttributedNodeCellCreationCall( + override val node: IWritableNode, + val attribute: IWritableNode?, ) : CellCreationCall() diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt index 6d1fe5ed..a18e7e11 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt @@ -1,5 +1,8 @@ package org.modelix.editor +import org.modelix.editor.celltemplate.NotationRootCellTemplate +import org.modelix.editor.celltemplate.getAttributeSideTransformActions +import org.modelix.editor.celltemplate.hasSymbolsBesideAttributedCell import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.model.api.INode import org.modelix.model.api.getInstantiatableSubConcepts @@ -64,6 +67,10 @@ class SideTransformNode( ) : ICodeCompletionActionProvider { override fun getApplicableActions(parameters: CodeCompletionParameters): List { val engine = parameters.editor.engine ?: return emptyList() + return getWrapperActions(engine) + getAttributeActions(engine) + } + + fun getWrapperActions(engine: EditorEngine): List { val location = ExistingNode(node) val expectedConcept = location.expectedConcept() ?: return emptyList() val allowedConcepts = expectedConcept.getInstantiatableSubConcepts() @@ -75,6 +82,42 @@ class SideTransformNode( it.getSideTransformActions(before, node) ?: emptyList() } } + + /** + * Node attributes added on the border of the node's own cell go inside all existing ones. + */ + private fun getAttributeActions(engine: EditorEngine): List { + val innermostLayer = engine.getNodeAttributeLayers(node).lastOrNull() + val index = innermostLayer?.let { layer -> node.getAttributes().indexOfFirst { it.reference == layer.reference } + 1 } ?: 0 + return engine.getNodeAttributeTemplates().flatMap { it.getAttributeSideTransformActions(before, node, index) } + } +} + +/** + * The side transforms on the border of a node attribute's cell, which wraps the cell of the node it is attached to. + * + * A node attribute added here goes directly outside of [attribute]. On the border of the outermost attribute the + * side transforms of the attributed node apply as well, because that border is where its parent sees it. + */ +class AttributeLayerSideTransform( + val before: Boolean, + val attribute: INode, +) : ICodeCompletionActionProvider { + override fun getApplicableActions(parameters: CodeCompletionParameters): List { + val engine = parameters.editor.engine ?: return emptyList() + val attributedNode = attribute.getAttributedNode() ?: return emptyList() + val attributeConcept = attribute.concept ?: return emptyList() + val template = engine.createCellModel(attributeConcept) as? NotationRootCellTemplate ?: return emptyList() + // Otherwise this border is the border of the next layer inward, which offers the same actions. + if (!template.hasSymbolsBesideAttributedCell(before)) return emptyList() + + val isOutermost = engine.getNodeAttributeLayers(attributedNode).firstOrNull()?.reference == attribute.reference + val wrapperActions = if (isOutermost) SideTransformNode(before, attributedNode).getWrapperActions(engine) else emptyList() + val index = attributedNode.getAttributes().indexOfFirst { it.reference == attribute.reference } + val attributeActions = + engine.getNodeAttributeTemplates().flatMap { it.getAttributeSideTransformActions(before, attributedNode, index) } + return wrapperActions + attributeActions + } } fun Cell.getSubstituteActions() = diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/NodeAttributes.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/NodeAttributes.kt new file mode 100644 index 00000000..18172181 --- /dev/null +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/NodeAttributes.kt @@ -0,0 +1,43 @@ +package org.modelix.editor + +import org.modelix.model.api.BuiltinLanguages +import org.modelix.model.api.IChildLink +import org.modelix.model.api.IConcept +import org.modelix.model.api.INode +import org.modelix.model.api.getAllConcepts + +/** + * Node attributes (`jetbrains.mps.lang.core.structure.NodeAttribute`) are children in the `smodelAttribute` role that + * annotate the node they are attached to. Their notation wraps the notation of that node: an `attributed` cell + * ([org.modelix.editor.celltemplate.AttributedCellTemplate]) stands for it. + * + * Concepts are compared by UID, because the same concept can be represented by different [IConcept] implementations + * (generated, MPS, simple). + */ +internal val smodelAttributeLink: IChildLink = BuiltinLanguages.jetbrains_mps_lang_core.BaseConcept.smodelAttribute + +private val nodeAttributeUID = BuiltinLanguages.jetbrains_mps_lang_core.NodeAttribute.getUID() + +fun IConcept.isNodeAttribute(): Boolean = getAllConcepts().any { it.getUID() == nodeAttributeUID } + +fun IConcept.isSubConceptOfUID(uid: String): Boolean = getAllConcepts().any { it.getUID() == uid } + +fun IChildLink.isSmodelAttribute(): Boolean = toReference().matches(smodelAttributeLink.toReference()) + +/** + * All attributes of [this] node, node attributes or not, in the order MPS stores them. + * + * Read through [INode.allChildren], because a model may store the role by name or by ID. Reading one specific role + * records a dependency on that spelling only, and the incremental engine would miss attributes added with the other. + */ +fun INode.getAttributes(): List = allChildren.filter { it.getContainmentLink()?.isSmodelAttribute() == true } + +/** + * The node an attribute is attached to. + */ +fun INode.getAttributedNode(): INode? = parent?.takeIf { getContainmentLink()?.isSmodelAttribute() == true } + +/** + * Follows [getAttributedNode] for attributes of attributes, up to the node that is not an attribute. + */ +fun INode.getUltimateAttributedNode(): INode = generateSequence(this) { it.getAttributedNode() }.last() diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/AttributedCellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/AttributedCellTemplate.kt new file mode 100644 index 00000000..cef260ac --- /dev/null +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/AttributedCellTemplate.kt @@ -0,0 +1,152 @@ +package org.modelix.editor.celltemplate + +import org.modelix.editor.AttributedNodeCellCreationCall +import org.modelix.editor.CaretPositionPolicy +import org.modelix.editor.CellCreationContext +import org.modelix.editor.CellSpec +import org.modelix.editor.CellSpecBase +import org.modelix.editor.ChildSpecReference +import org.modelix.editor.IActionOrProvider +import org.modelix.editor.ICodeCompletionAction +import org.modelix.editor.ICompletionTokenOrList +import org.modelix.editor.IParseTreeToAstBuilder +import org.modelix.editor.NodeCellReference +import org.modelix.editor.TemplateCellReference +import org.modelix.editor.TextCellSpec +import org.modelix.editor.getAttributedNode +import org.modelix.editor.getAttributes +import org.modelix.editor.isSubConceptOfUID +import org.modelix.editor.smodelAttributeLink +import org.modelix.editor.text.backend.BackendEditorComponent +import org.modelix.model.api.BuiltinLanguages +import org.modelix.model.api.IConcept +import org.modelix.model.api.INode +import org.modelix.model.api.upcast +import org.modelix.parser.ISymbol +import org.modelix.parser.SubConceptsSymbol + +/** + * Stands for the node a node attribute is attached to, inside the notation of that attribute. + * + * It renders the next layer inward: the next node attribute of the same node, or the node's own notation below the + * innermost one. Which one that is follows from the model alone (the attribute's parent and its next sibling + * attribute), so the cell is created by its own [AttributedNodeCellCreationCall] like any child cell, instead of + * being handed down by whoever renders the attribute. + */ +class AttributedCellTemplate( + concept: IConcept, +) : CellTemplate(concept), + IGrammarSymbol { + /** + * The concepts the attribute can be attached to, from its `@attribute info`. Empty means any concept. + */ + val attributedConcepts: MutableList = ArrayList() + + /** + * Whether a node can have several attributes of this concept. + */ + var multiple: Boolean = false + + fun isApplicableTo(attributedNode: INode): Boolean { + val attributedConcept = attributedNode.concept ?: return false + if (attributedConcepts.isNotEmpty() && attributedConcepts.none { attributedConcept.isSubConceptOfUID(it.getUID()) }) { + return false + } + if (!multiple && attributedNode.getAttributes().any { it.concept?.getUID() == concept.getUID() }) return false + return true + } + + override fun createCell( + context: CellCreationContext, + node: INode, + ): CellSpecBase { + val attributedNode = node.getAttributedNode() ?: return TextCellSpec("", "") + val layers = context.editorEngine.getNodeAttributeLayers(attributedNode) + val nextLayer = layers.getOrNull(layers.indexOfFirst { it.reference == node.reference } + 1) + return CellSpec().also { + it.addChild(ChildSpecReference(AttributedNodeCellCreationCall(attributedNode.asWritableNode(), nextLayer?.asWritableNode()))) + } + } + + override fun toCompletionToken(): ICompletionTokenOrList? = null + + override fun getSymbolTransformationAction( + node: INode, + optionalCell: TemplateCellReference, + ): IActionOrProvider? = null + + // Not part of any grammar yet: no child cell offers attributes, so the parser never reaches an attribute's rule. + override fun toParserSymbol(): ISymbol = + SubConceptsSymbol(attributedConcepts.singleOrNull() ?: BuiltinLanguages.jetbrains_mps_lang_core.BaseConcept) + + override fun consumeTokens(builder: IParseTreeToAstBuilder) {} +} + +/** + * Adding a node attribute by typing its notation next to the node it is attached to: the first constant before the + * `attributed` cell when typed in front of the node, the first constant after it when typed behind the node. What + * the notation has between that constant and the `attributed` cell is left empty, the same way a side transform + * leaves the other operand of a binary operator empty. + * + * [index] is the position in the `smodelAttribute` role. It decides how the new attribute nests with the existing + * ones (the first one is the outermost) and is derived from where the caret is. + */ +fun NotationRootCellTemplate.getAttributeSideTransformActions( + before: Boolean, + attributedNode: INode, + index: Int, +): List { + val symbols = getGrammarSymbols().toList() + val attributedIndex = symbols.indexOfFirst { it is AttributedCellTemplate } + if (attributedIndex < 0) return emptyList() + val attributedCell = symbols[attributedIndex] as AttributedCellTemplate + if (!attributedCell.isApplicableTo(attributedNode)) return emptyList() + val sideSymbols = if (before) symbols.take(attributedIndex) else symbols.drop(attributedIndex + 1) + val token = sideSymbols.filterIsInstance().firstOrNull() ?: return emptyList() + return listOf(AddNodeAttributeAction(token.text, concept, attributedNode, index)) +} + +/** + * Whether the notation writes something on that side of the `attributed` cell. If not, the border of the attribute's + * cell on that side coincides with the border of the layer inside it, and only the inner one offers actions. + */ +fun NotationRootCellTemplate.hasSymbolsBesideAttributedCell(before: Boolean): Boolean { + val symbols = getGrammarSymbols().toList() + val attributedIndex = symbols.indexOfFirst { it is AttributedCellTemplate } + if (attributedIndex < 0) return false + return if (before) attributedIndex > 0 else attributedIndex < symbols.lastIndex +} + +class AddNodeAttributeAction( + val text: String, + val attributeConcept: IConcept, + val attributedNode: INode, + val index: Int, +) : ICodeCompletionAction { + override fun getMatchingText(): String = text + + override fun getDescription(): String = attributeConcept.getShortName() + + override fun execute(editor: BackendEditorComponent): CaretPositionPolicy { + val attribute = + attributedNode + .asWritableNode() + .addNewChild(smodelAttributeLink.toReference(), index, attributeConcept.getReference().upcast()) + return CaretPositionPolicy(attribute.asLegacyNode()) + .avoid(NodeCellReference(attributedNode.reference)) + } + + /** + * Where the cells of several nodes start at the same position (a method and its first keyword), the attribute + * is attached to the outermost one, the construct as a whole. + */ + override fun shadows(shadowed: ICodeCompletionAction): Boolean { + if (shadowed !is AddNodeAttributeAction) return false + if (shadowed.attributeConcept.getUID() != attributeConcept.getUID()) return false + return shadowed.attributedNode + .ancestors() + .any { it.reference == attributedNode.reference } + } +} + +private fun INode.ancestors(): Sequence = generateSequence(parent) { it.parent } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/BackendEditorComponent.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/BackendEditorComponent.kt index f856a1ec..25ad81e7 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/BackendEditorComponent.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/BackendEditorComponent.kt @@ -7,7 +7,6 @@ import org.modelix.editor.CodeCompletionParameters import org.modelix.editor.EditorEngine import org.modelix.editor.ICodeCompletionAction import org.modelix.editor.ICodeCompletionActionProvider -import org.modelix.editor.NodeCellCreationCall import org.modelix.editor.Selection import org.modelix.editor.applyShadowing import org.modelix.editor.getCompletionPattern @@ -55,15 +54,9 @@ class BackendEditorComponent( it.updateActions(pattern) } - fun runWrite(body: () -> R): R = - when (rootCall) { - is NodeCellCreationCall -> rootCall.node.getModel().executeWrite(body) - } + fun runWrite(body: () -> R): R = rootCall.node.getModel().executeWrite(body) - fun runRead(body: () -> R): R = - when (rootCall) { - is NodeCellCreationCall -> rootCall.node.getModel().executeRead(body) - } + fun runRead(body: () -> R): R = rootCall.node.getModel().executeRead(body) inner class CompletionMenuBackend( val providers: List, From daa49d7e9b1ff50e4f33dd2580221e84c62029fc Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 30 Oct 2026 13:37:18 +0100 Subject: [PATCH 03/23] perf(projectional-editor): run the MPS model checkers in the background Rendering the editor after a model change ran the typesystem and constraints checks of the whole root node while holding the incremental engine's lock. An edit like pressing Enter had to wait for it, which took more than two seconds in larger root nodes. The editor now only reads the messages published by the last completed check. The checks run in the background in an incremental engine of their own and in a read action that a write action cancels. The messages are published per node, so a new check result only re-renders the cells of the affected nodes. IncrementalModelChecker can now be cancelled. MPS executes model access in a non-cancelable section, so the cancellation is checked explicitly instead of through the ProgressManager. Cancelled checks are re-executed after retryCancelledChecks() instead of staying cached as failed. Co-Authored-By: Claude Opus 5.5 --- .../editor/common/IncrementalModelChecker.kt | 119 +++++++++-- .../editor/ssr/mps/BaseLanguageTests.kt | 58 +++++ .../editor/ssr/mps/AsyncMPSModelChecker.kt | 199 ++++++++++++++++++ .../editor/ssr/mps/EditorIntegrationForMPS.kt | 9 +- .../modelix/editor/ssr/mps/MPSModelChecker.kt | 2 +- 5 files changed, 367 insertions(+), 20 deletions(-) create mode 100644 projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/AsyncMPSModelChecker.kt diff --git a/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/IncrementalModelChecker.kt b/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/IncrementalModelChecker.kt index 99c581e0..c642d5cc 100644 --- a/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/IncrementalModelChecker.kt +++ b/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/IncrementalModelChecker.kt @@ -12,10 +12,12 @@ import jetbrains.mps.typechecking.TypecheckingFacade import jetbrains.mps.typechecking.TypecheckingSession import jetbrains.mps.typesystem.LegacyTypecheckingQueries import jetbrains.mps.typesystem.inference.TypeCheckingContext +import jetbrains.mps.util.Cancellable import org.jetbrains.mps.openapi.language.SConceptFeature import org.jetbrains.mps.openapi.model.SNode import org.jetbrains.mps.openapi.util.Consumer import org.modelix.incremental.IIncrementalEngine +import org.modelix.incremental.TrackableValue import org.modelix.incremental.incrementalFunction import org.modelix.model.api.BuiltinLanguages import org.modelix.model.api.INode @@ -29,15 +31,23 @@ import org.modelix.model.mpsadapters.tomps.ModelixNodeAsMPSNode * * The typesystem and non-typesystem rules are cached per root node, because type inference is root-wide. * The constraints are cached per node, so a model change only re-executes them for the nodes whose input changed. + * + * The checks can be cancelled with [runCancellable], e.g. to run them in the background. A cancelled check is not + * cached as failed forever, but re-executed after [retryCancelledChecks]. */ class IncrementalModelChecker( private val engine: IIncrementalEngine, ) { private val constraintsChecker = ConstraintsChecker(null) + /** + * Only read by checks that were cancelled, so that modifying it invalidates exactly those. + */ + private val cancellations = TrackableValue(0) + private val fCheckTypesystemForRoot = incrementalFunction, INode>("checkTypesystemForRoot") { context, node -> - runTypesystemChecks(ModelixNodeAsMPSNode.toMPSNode(node)) + cancellable { runTypesystemChecks(ModelixNodeAsMPSNode.toMPSNode(node)) } } /** @@ -45,7 +55,7 @@ class IncrementalModelChecker( */ private val fCheckNodeConstraints = incrementalFunction, INode>("checkNodeConstraints") { context, node -> - runConstraintsCheck(ModelixNodeAsMPSNode.toMPSNode(node)) + cancellable { runConstraintsCheck(ModelixNodeAsMPSNode.toMPSNode(node)) } } /** @@ -55,25 +65,26 @@ class IncrementalModelChecker( */ private val fCheckSubtreeConstraints = incrementalFunction, INode>("checkSubtreeConstraints") { context, node -> - val skipCondition = constraintsChecker.skipCondition() - val mpsNode = ModelixNodeAsMPSNode.toMPSNode(node) - if (skipCondition.skipSubtree(mpsNode)) { - emptyList() - } else { - val ownMessages = if (skipCondition.skipSingleNode(mpsNode)) emptyList() else checkNodeConstraints(node) - ownMessages + node.allChildren.flatMap { checkSubtreeConstraints(it) } + cancellable { + val skipCondition = constraintsChecker.skipCondition() + val mpsNode = ModelixNodeAsMPSNode.toMPSNode(node) + if (skipCondition.skipSubtree(mpsNode)) { + emptyList() + } else { + val ownMessages = if (skipCondition.skipSingleNode(mpsNode)) emptyList() else checkNodeConstraints(node) + ownMessages + node.allChildren.flatMap { checkSubtreeConstraints(it) } + } } } private val fGetRootNode = incrementalFunction("getRootNode") { context, node -> - if (node.getContainmentLink()?.getUID() == - BuiltinLanguages.MPSRepositoryConcepts.Model.rootNodes - .getUID() - ) { - node - } else { - getRootNode(node.parent ?: return@incrementalFunction node) + cancellable { + if (node.isRootNode()) { + node + } else { + node.parent?.let { getRootNode(it) } ?: node + } } } @@ -91,6 +102,46 @@ class IncrementalModelChecker( target: MessageTarget, ): List = getAllMessages(node).filter { it.messageTarget.sameAs(target) } + /** + * The messages of all nodes in the root node that contains [node], grouped by node. + * Returns null if [node] is not part of a model. + */ + fun getMessagesOfRoot(node: INode): Map>? = getRootNodeOrNull(node)?.let { checkRoot(it) } + + /** + * The root node that contains [node], or null if [node] is not part of a model. + */ + fun getRootNodeOrNull(node: INode): INode? = getRootNode(node).takeIf { it.isRootNode() } + + /** + * Executes [body] so that the checks it runs stop early when [isCancelled] returns true. + * Returns null if they were cancelled. + * + * MPS executes model access in a non-cancelable section, so the checks can't be cancelled through the + * ProgressManager. + */ + fun runCancellable( + isCancelled: () -> Boolean, + body: () -> R, + ): R? { + val previous = cancellationCheck.get() + cancellationCheck.set(isCancelled) + try { + return body() + } catch (ex: CheckCancelledException) { + return null + } finally { + cancellationCheck.set(previous) + } + } + + /** + * Re-executes the checks that were cancelled when they are requested the next time. + */ + fun retryCancelledChecks() { + cancellations.setValue(cancellations.getValue() + 1) + } + private fun checkRoot(rootNode: INode): Map> { val messages = checkTypesystemForRoot(rootNode) + checkSubtreeConstraints(rootNode) return messages.groupBy { it.node.toModelix() } @@ -104,6 +155,35 @@ class IncrementalModelChecker( private fun getRootNode(node: INode): INode = fGetRootNode(node).bind(engine).invoke() + /** + * Executes the body of an incremental function so that a cancellation isn't cached as its result. + * A cancelled MPS checker returns an incomplete result, which is why the cancellation is checked again afterward. + */ + private fun cancellable(body: () -> R): R { + try { + checkCancelled() + val result = body() + checkCancelled() + return result + } catch (ex: CheckCancelledException) { + cancellations.getValue() + throw ex + } + } + + private fun isCancelled() = cancellationCheck.get()?.invoke() == true + + private fun checkCancelled() { + if (isCancelled()) throw CheckCancelledException() + } + + private class CheckCancelledException : RuntimeException("Model check cancelled") + + private fun INode.isRootNode() = + getContainmentLink()?.getUID() == + BuiltinLanguages.MPSRepositoryConcepts.Model.rootNodes + .getUID() + /** * Checks the typesystem and the non-typesystem rules in a single typechecking session. * [jetbrains.mps.typesystemEngine.checker.TypesystemChecker] and @@ -147,7 +227,10 @@ class IncrementalModelChecker( val typeCheckingContext = legacyQueries.typeCheckingContext try { typeCheckingContext.setNonTypesystemComputationMode(TypeCheckingContext.NonTypesystemComputationMode.NORMAL) - typeCheckingContext.baseNodeTypesComponent.applyNonTypesystemRulesToRoot(typeCheckingContext) + typeCheckingContext.baseNodeTypesComponent.applyNonTypesystemRulesToRoot( + typeCheckingContext, + Cancellable { isCancelled() }, + ) } finally { typeCheckingContext.setNonTypesystemComputationMode(TypeCheckingContext.NonTypesystemComputationMode.OFF) } @@ -189,6 +272,8 @@ class IncrementalModelChecker( private val instances = java.util.WeakHashMap() + private val cancellationCheck = ThreadLocal<(() -> Boolean)?>() + /** * Returns a checker whose results are cached in the given engine. */ diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index 300469a3..0bde2d11 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -41,6 +41,7 @@ import org.modelix.model.api.IWritableNode import org.modelix.model.api.getDescendants import org.modelix.model.mpsadapters.MPSArea import org.modelix.model.mpsadapters.MPSWritableNode +import org.modelix.mps.editor.common.IncrementalModelChecker /** * Test editor for MPS baseLanguage ClassConcept @@ -649,6 +650,63 @@ class BaseLanguageTests : TestBase("SimpleProject") { assertEquals(emptyList(), errorMessages()) } + fun `test model check messages are shown in the editor after the check finished in the background`() = + kotlinx.coroutines.test.runTest { + assertEquals(emptyList(), awaitErrorMessagesInEditor(present = false)) + + placeCaretIntoPlaceholderOf(methodBodyNode, "statement") + typeText("return") + typeText("10") + assertNotEmpty(awaitErrorMessagesInEditor(present = true)) + + pressKey(KnownKeys.Delete) + placeCaretIntoCellWithText("return") + pressKey(KnownKeys.Delete) + assertEditorText(""" + public class Class1 { + public void method1() { + + } + } + """) + assertEquals(emptyList(), awaitErrorMessagesInEditor(present = false)) + } + + fun `test a cancelled model check is executed again after retrying it`() { + val engine = IncrementalEngine() + try { + val checker = IncrementalModelChecker(engine) + val root = classNode.asLegacyNode() + assertNull(readAction { checker.runCancellable({ true }) { checkNotNull(checker.getMessagesOfRoot(root)) } }) + // Without retrying, the cancelled checks would still be cached as failed. + assertNull(readAction { checker.runCancellable({ false }) { checkNotNull(checker.getMessagesOfRoot(root)) } }) + + checker.retryCancelledChecks() + assertNotNull(readAction { checker.runCancellable({ false }) { checkNotNull(checker.getMessagesOfRoot(root)) } }) + } finally { + engine.dispose() + } + } + + /** + * The model checker publishes its messages asynchronously, so they are only shown eventually. + */ + private suspend fun awaitErrorMessagesInEditor(present: Boolean): List { + val deadline = System.currentTimeMillis() + 30_000 + while (true) { + editor.flush() + val messages = + editor + .getRootCell() + .descendantsAndSelf() + .mapNotNull { it.getProperty(CommonCellProperties.errorMessage) } + .toList() + if (messages.isNotEmpty() == present || System.currentTimeMillis() > deadline) return messages + // Not delay(), because runTest skips it in virtual time. + Thread.sleep(100) + } + } + /** * MPS holds an enumeration value as `/` and its editor shows the name, converting in * `PropertyAccessor` rather than in the model - so that persistence and synchronisation keep seeing the stored diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/AsyncMPSModelChecker.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/AsyncMPSModelChecker.kt new file mode 100644 index 00000000..9ef03a91 --- /dev/null +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/AsyncMPSModelChecker.kt @@ -0,0 +1,199 @@ +package org.modelix.editor.ssr.mps + +import com.intellij.openapi.progress.EmptyProgressIndicator +import com.intellij.openapi.progress.ProcessCanceledException +import com.intellij.openapi.progress.ProgressManager +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import org.jetbrains.mps.openapi.module.SRepository +import org.modelix.checks.CheckMessage +import org.modelix.checks.IModelChecker +import org.modelix.editor.ssr.mps.MPSModelChecker.toCheckMessage +import org.modelix.editor.text.backend.Validator +import org.modelix.incremental.DependencyTracking +import org.modelix.incremental.IDependencyListener +import org.modelix.incremental.IIncrementalEngine +import org.modelix.incremental.IInternalStateVariableReference +import org.modelix.incremental.IStateVariableGroup +import org.modelix.incremental.IStateVariableReference +import org.modelix.incremental.IncrementalEngine +import org.modelix.model.api.INode +import org.modelix.model.api.INodeReference +import org.modelix.mps.editor.common.IncrementalModelChecker +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ConcurrentLinkedQueue +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds + +/** + * Runs the MPS model checkers in the background, so that they don't delay the editor's response to user input. + * + * The editor only reads the messages published by the last completed check, which makes them eventually consistent + * with the model. Messages are published per node, so a new check result only re-renders the cells of the nodes + * whose messages changed. + * + * The checks are cached in an [IncrementalEngine] of their own. A check holds the engine's lock while it runs and + * would otherwise block the rendering of the editor. + * + * The checks run in a read action that is cancelled when a write action is requested, so that a running check doesn't + * delay model changes either. Only the type inference of a root node can't be cancelled. + */ +class AsyncMPSModelChecker( + private val repository: SRepository, + private val debounceDelay: Duration = 300.milliseconds, +) : IModelChecker { + private val checkEngine = IncrementalEngine() + private val checker = IncrementalModelChecker(checkEngine) + private val coroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + private val validator = Validator(coroutineScope) { checkRequestedRoots() } + + /** + * Nodes rendered by the editor since the last check. Their root nodes are checked. + */ + private val requestedNodes = ConcurrentLinkedQueue() + + // Only accessed by the validator, which never runs concurrently with itself. + private val checkedRoots = LinkedHashMap() + private val publishedNodesByRoot = HashMap>() + + private val publishedMessages = ConcurrentHashMap>() + + private val modelChangeListener = + object : IDependencyListener { + override fun accessed(key: IStateVariableReference<*>) {} + + override fun parentGroupChanged(childGroup: IStateVariableGroup) {} + + override fun modified(key: IStateVariableReference<*>) { + // Changes of cached values and of the published messages are a consequence of the checks. + if (key is IInternalStateVariableReference<*, *> || key is MessagesOfNode) return + validator.invalidate() + } + } + + init { + DependencyTracking.registerListener(modelChangeListener) + validator.start() + } + + override fun getMessages( + engine: IIncrementalEngine, + node: INode, + ): List { + requestedNodes.add(node) + validator.invalidate() + val messages = MessagesOfNode(this, node.reference) + DependencyTracking.accessed(messages) + return messages.read() + } + + fun dispose() { + DependencyTracking.removeListener(modelChangeListener) + validator.stop() + coroutineScope.cancel("disposed") + checkEngine.dispose() + publishedMessages.clear() + } + + private suspend fun checkRequestedRoots() { + delay(debounceDelay) + while (true) { + val messages = runCancellableRead { checkRoots() } + if (messages != null) { + publish(messages) + return + } + checker.retryCancelledChecks() + // Give the write action that cancelled the check the chance to finish. + delay(debounceDelay) + } + } + + /** + * Returns null if a write action cancelled [body]. + */ + private fun runCancellableRead(body: () -> R): R? { + var result: R? = null + // Requesting a write action cancels the indicator. + val indicator = EmptyProgressIndicator() + val completed = + try { + ProgressManager.getInstance().runInReadActionWithWriteActionPriority( + { repository.modelAccess.runReadAction { result = checker.runCancellable(indicator::isCanceled, body) } }, + indicator, + ) + } catch (ex: ProcessCanceledException) { + false + } + return if (completed) result else null + } + + /** + * The messages of the checked root nodes, grouped by root node and node. + */ + private fun checkRoots(): Map>> { + while (true) { + val node = requestedNodes.poll() ?: break + if (!node.isValid) continue + val root = checker.getRootNodeOrNull(node) ?: continue + checkedRoots[root.reference] = root + } + val result = LinkedHashMap>>() + val iterator = checkedRoots.values.iterator() + while (iterator.hasNext()) { + val root = iterator.next() + val messages = root.takeIf { it.isValid }?.let { checker.getMessagesOfRoot(it) } + if (messages == null) { + // The root node was deleted. + iterator.remove() + continue + } + result[root.reference] = + messages + .mapValues { (_, items) -> items.mapNotNull { it.toCheckMessage() } } + .filterValues { it.isNotEmpty() } + } + return result + } + + private fun publish(messagesByRoot: Map>>) { + for (root in publishedNodesByRoot.keys - messagesByRoot.keys) { + publishedNodesByRoot.remove(root)?.forEach { publish(it, null) } + } + for ((root, messagesByNode) in messagesByRoot) { + val previousNodes = publishedNodesByRoot[root].orEmpty() + for (node in previousNodes - messagesByNode.keys) { + publish(node, null) + } + for ((node, messages) in messagesByNode) { + publish(node, messages) + } + publishedNodesByRoot[root] = messagesByNode.keys + } + } + + private fun publish( + node: INodeReference, + messages: List?, + ) { + val previous = if (messages == null) publishedMessages.remove(node) else publishedMessages.put(node, messages) + if (previous != messages) { + DependencyTracking.modified(MessagesOfNode(this, node)) + } + } + + /** + * The published messages of a node. Reading it in a cell makes the cell depend on that node's messages only. + */ + private data class MessagesOfNode( + val checker: AsyncMPSModelChecker, + val node: INodeReference, + ) : IStateVariableReference> { + override fun read(): List = checker.publishedMessages[node] ?: emptyList() + + override fun getGroup(): IStateVariableGroup? = null + } +} diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt index af97c8fb..79e42c5a 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt @@ -16,6 +16,7 @@ class EditorIntegrationForMPS( private var aspectsFromMPS: LanguageAspectsFromMPSModules? = null private var mpsChangeTranslator: MPSChangeTranslator? = null private var mpsLanguageRepository: MPSLanguageRepository? = null + private var modelChecker: AsyncMPSModelChecker? = null fun init(repository: SRepository) { mpsLanguageRepository = MPSLanguageRepository(repository) @@ -26,7 +27,7 @@ class EditorIntegrationForMPS( ScopeAspect.registerScopeProvider(MPSScopeProvider) ConstraintsAspect.checkers.add(MPSConstraints) PropertyPresentationAspect.providers.add(MPSPropertyPresentation) - ModelCheckAspect.checkers.add(MPSModelChecker) + modelChecker = AsyncMPSModelChecker(repository).also { ModelCheckAspect.checkers.add(it) } editorEngine.addRegistry(aspectsFromMPS!!) } @@ -37,7 +38,11 @@ class EditorIntegrationForMPS( ScopeAspect.unregisterScopeProvider(MPSScopeProvider) ConstraintsAspect.checkers.remove(MPSConstraints) PropertyPresentationAspect.providers.remove(MPSPropertyPresentation) - ModelCheckAspect.checkers.remove(MPSModelChecker) + modelChecker?.let { + ModelCheckAspect.checkers.remove(it) + it.dispose() + } + modelChecker = null // The change translator and the aspects registry attach listeners to MPS. Leaving them registered would keep // this plugin's classes referenced from MPS and prevent the plugin from being unloaded. diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSModelChecker.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSModelChecker.kt index e90dbb8f..dba5e446 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSModelChecker.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSModelChecker.kt @@ -21,7 +21,7 @@ object MPSModelChecker : IModelChecker { node: INode, ): List = IncrementalModelChecker.getInstance(engine).getAllMessages(node).mapNotNull { it.toCheckMessage() } - private fun NodeReportItem.toCheckMessage(): CheckMessage? { + internal fun NodeReportItem.toCheckMessage(): CheckMessage? { val severity = when (severity) { MessageStatus.ERROR -> CheckSeverity.ERROR From 288fecfb9fe20b1b8c31577b29c25e61110be885 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 30 Oct 2026 16:29:20 +0100 Subject: [PATCH 04/23] fix(mps-plugin): don't block the MPS shutdown while a web editor page is open Services are disposed inside a write action. Stopping the Ktor server there waited for the Netty event loops, without any timeout, while a request handler on one of them waited for a read action. MPS could only be killed. The servers are now stopped when the application is about to close or the plugin is about to be unloaded, which is before that write action. Stopping them in dispose() remains as a fallback and gives up after a bounded time. Co-Authored-By: Claude Opus 5.5 --- .../modelix/mps/editor/common/KtorUtils.kt | 71 +++++++++++++++++++ .../mps/editor/image/ImageEditorForMPS.kt | 13 +++- .../modelix/editor/ssr/mps/ServerStopTest.kt | 54 ++++++++++++++ .../editor/ssr/mps/ModelixSSRServerForMPS.kt | 13 +++- .../react/ssr/mps/ReactSSRServerForMPS.kt | 13 +++- 5 files changed, 158 insertions(+), 6 deletions(-) create mode 100644 projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ServerStopTest.kt diff --git a/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/KtorUtils.kt b/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/KtorUtils.kt index 867a6573..49823594 100644 --- a/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/KtorUtils.kt +++ b/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/KtorUtils.kt @@ -1,5 +1,12 @@ package org.modelix.mps.editor.common +import com.intellij.ide.AppLifecycleListener +import com.intellij.ide.plugins.DynamicPluginListener +import com.intellij.ide.plugins.IdeaPluginDescriptor +import com.intellij.ide.plugins.PluginManager +import com.intellij.openapi.Disposable +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.diagnostic.Logger import io.ktor.server.application.Application import io.ktor.server.application.serverConfig import io.ktor.server.engine.EmbeddedServer @@ -9,6 +16,9 @@ import io.ktor.server.netty.Netty import io.ktor.server.netty.NettyApplicationEngine import io.ktor.util.logging.KtorSimpleLogger import kotlinx.coroutines.GlobalScope +import kotlin.concurrent.thread + +private val LOG = Logger.getInstance("org.modelix.mps.editor.common.KtorUtils") fun embeddedServer( port: Int, @@ -33,3 +43,64 @@ fun embeddedServer( this.connectors += EngineConnectorBuilder().also { it.port = portParam } }) } + +/** + * Like [EmbeddedServer.stop], but returns after [maxWaitMillis] even if the server isn't stopped yet. + * + * Netty terminates an event loop only after the task it is currently running returned. [EmbeddedServer.stop] waits + * for that without any timeout, [gracePeriodMillis] and [timeoutMillis] only apply between tasks. A request handler + * that is blocked in an MPS read action, while stop is called inside a write action, blocks it forever. + */ +fun EmbeddedServer<*, *>.stopBounded( + gracePeriodMillis: Long, + timeoutMillis: Long, + maxWaitMillis: Long, +) { + val stopThread = + thread(name = "modelix-ktor-server-stop", isDaemon = true) { + try { + stop(gracePeriodMillis, timeoutMillis) + } catch (ex: Throwable) { + LOG.warn("Failed to stop the server", ex) + } + } + stopThread.join(maxWaitMillis) + if (stopThread.isAlive) { + LOG.warn("Server didn't stop within $maxWaitMillis ms. A request handler is probably blocked.") + } +} + +/** + * Calls [stop] when the application is about to close or when the plugin that contains [pluginClass] is about to be + * unloaded, as long as [parentDisposable] isn't disposed. + * + * Both happen before the services are disposed. That happens inside a write action, where request handlers that wait + * for a read action can't finish and stopping a server has to give up on them (see [stopBounded]). + */ +fun stopBeforeDisposal( + parentDisposable: Disposable, + pluginClass: Class<*>, + stop: () -> Unit, +) { + val pluginId = PluginManager.getPluginByClass(pluginClass)?.pluginId + val connection = ApplicationManager.getApplication().messageBus.connect(parentDisposable) + connection.subscribe( + AppLifecycleListener.TOPIC, + object : AppLifecycleListener { + override fun appWillBeClosed(isRestart: Boolean) { + stop() + } + }, + ) + connection.subscribe( + DynamicPluginListener.TOPIC, + object : DynamicPluginListener { + override fun beforePluginUnload( + pluginDescriptor: IdeaPluginDescriptor, + isUpdate: Boolean, + ) { + if (pluginId != null && pluginDescriptor.pluginId == pluginId) stop() + } + }, + ) +} diff --git a/mps-image-editor-server/src/main/kotlin/org/modelix/mps/editor/image/ImageEditorForMPS.kt b/mps-image-editor-server/src/main/kotlin/org/modelix/mps/editor/image/ImageEditorForMPS.kt index b71dc84b..4e369018 100644 --- a/mps-image-editor-server/src/main/kotlin/org/modelix/mps/editor/image/ImageEditorForMPS.kt +++ b/mps-image-editor-server/src/main/kotlin/org/modelix/mps/editor/image/ImageEditorForMPS.kt @@ -38,6 +38,8 @@ import org.modelix.model.mpsadapters.MPSArea import org.modelix.model.mpsadapters.MPSRepositoryAsNode import org.modelix.model.mpsadapters.MPSWritableNode import org.modelix.model.mpsadapters.tomps.ModelixNodeAsMPSNode +import org.modelix.mps.editor.common.stopBeforeDisposal +import org.modelix.mps.editor.common.stopBounded import svg.plugin.RenderSession import svg.plugin.optBoolean import java.net.URLDecoder @@ -74,10 +76,17 @@ class ImageEditorForMPS : Disposable { companion object { private const val SHUTDOWN_GRACE_PERIOD_MS = 1_000L private const val SHUTDOWN_TIMEOUT_MS = 5_000L + private const val SHUTDOWN_MAX_WAIT_MS = 10_000L fun getInstance() = ApplicationManager.getApplication().getService(ImageEditorForMPS::class.java) } + init { + // Stopping the server in dispose() is only the fallback. dispose() is called inside a write action, where + // request handlers that wait for a read action can't finish. + stopBeforeDisposal(this, javaClass) { ensureStopped() } + } + private var ktorServer: EmbeddedServer<*, *>? = null private val projects: MutableSet = Collections.synchronizedSet(HashSet()) private val commandLister = @@ -150,9 +159,9 @@ class ImageEditorForMPS : Disposable { if (ktorServer == null) return println("stopping image editor server") MPSModuleRepository.getInstance().modelAccess.removeCommandListener(commandLister) - // A bounded timeout is required. An unbounded stop() can block forever, which would block the plugin + // A bounded wait is required. An unbounded stop() can block forever, which would block the plugin // unloading and the MPS shutdown. - ktorServer?.stop(SHUTDOWN_GRACE_PERIOD_MS, SHUTDOWN_TIMEOUT_MS) + ktorServer?.stopBounded(SHUTDOWN_GRACE_PERIOD_MS, SHUTDOWN_TIMEOUT_MS, SHUTDOWN_MAX_WAIT_MS) ktorServer = null } } diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ServerStopTest.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ServerStopTest.kt new file mode 100644 index 00000000..2c5b9119 --- /dev/null +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ServerStopTest.kt @@ -0,0 +1,54 @@ +package org.modelix.editor.ssr.mps + +import io.ktor.server.response.respondText +import io.ktor.server.routing.get +import io.ktor.server.routing.routing +import kotlinx.coroutines.runBlocking +import org.modelix.mps.editor.common.embeddedServer +import org.modelix.mps.editor.common.stopBounded +import java.net.URI +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread +import kotlin.system.measureTimeMillis + +/** + * MPS didn't shut down while a page with live updates was open. Services are disposed inside a write action and a + * request handler of the server was waiting for a read action at the same time. Stopping the server waited for the + * handler and the handler waited for the write action to finish. + */ +@Suppress("ktlint:standard:function-naming") +class ServerStopTest : TestBase("SimpleProject") { + fun `test stopping inside a write action doesn't wait for a handler that waits for a read action`() { + val handlerStarted = CountDownLatch(1) + val server = + embeddedServer(port = 0) { + routing { + get("read") { + handlerStarted.countDown() + mpsProject.modelAccess.runReadAction { } + call.respondText("OK") + } + } + } + server.start() + val port = + runBlocking { + server.engine + .resolvedConnectors() + .first() + .port + } + + val stopDuration = + writeActionOnEdt { + thread(isDaemon = true) { + runCatching { URI("http://localhost:$port/read").toURL().readText() } + } + assertTrue(handlerStarted.await(30, TimeUnit.SECONDS)) + measureTimeMillis { server.stopBounded(100, 500, 3_000) } + } + + assertTrue("Stopping the server took $stopDuration ms", stopDuration < 10_000) + } +} diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt index 3ce4e769..026fc7ff 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt @@ -83,6 +83,8 @@ import org.modelix.model.mpsadapters.MPSProperty import org.modelix.model.mpsadapters.MPSReferenceLink import org.modelix.model.mpsadapters.MPSRepositoryAsNode import org.modelix.model.mpsadapters.MPSWritableNode +import org.modelix.mps.editor.common.stopBeforeDisposal +import org.modelix.mps.editor.common.stopBounded import org.modelix.presentation.IPropertyPresentation import org.modelix.scopes.IScope import org.modelix.scopes.IScopeProvider @@ -116,6 +118,13 @@ class ModelixSSRServerForMPS : Disposable { companion object { private const val SHUTDOWN_GRACE_PERIOD_MS = 1_000L private const val SHUTDOWN_TIMEOUT_MS = 5_000L + private const val SHUTDOWN_MAX_WAIT_MS = 10_000L + } + + init { + // Stopping the server in dispose() is only the fallback. dispose() is called inside a write action, where + // request handlers that wait for a read action can't finish. + stopBeforeDisposal(this, javaClass) { ensureStopped() } } private var ssrServer: ModelixSSRServer? = null @@ -259,9 +268,9 @@ class ModelixSSRServerForMPS : Disposable { runSynchronized(this) { if (ktorServer == null) return println("stopping projectional editor SSR server") - // A bounded timeout is required. An unbounded stop() can block forever, which would block the plugin + // A bounded wait is required. An unbounded stop() can block forever, which would block the plugin // unloading and the MPS shutdown. - ktorServer?.stop(SHUTDOWN_GRACE_PERIOD_MS, SHUTDOWN_TIMEOUT_MS) + ktorServer?.stopBounded(SHUTDOWN_GRACE_PERIOD_MS, SHUTDOWN_TIMEOUT_MS, SHUTDOWN_MAX_WAIT_MS) ktorServer = null ssrServer?.dispose() ssrServer = null diff --git a/react-ssr-mps/src/main/kotlin/org/modelix/react/ssr/mps/ReactSSRServerForMPS.kt b/react-ssr-mps/src/main/kotlin/org/modelix/react/ssr/mps/ReactSSRServerForMPS.kt index a08a109a..7a6e22bf 100644 --- a/react-ssr-mps/src/main/kotlin/org/modelix/react/ssr/mps/ReactSSRServerForMPS.kt +++ b/react-ssr-mps/src/main/kotlin/org/modelix/react/ssr/mps/ReactSSRServerForMPS.kt @@ -41,6 +41,8 @@ import org.modelix.model.api.INode import org.modelix.model.api.runSynchronized import org.modelix.model.mpsadapters.MPSChangeTranslator import org.modelix.model.mpsadapters.MPSRepositoryAsNode +import org.modelix.mps.editor.common.stopBeforeDisposal +import org.modelix.mps.editor.common.stopBounded import org.modelix.react.ApiGenLanguages import org.modelix.react.ssr.server.ReactSSRServer import java.awt.image.BufferedImage @@ -76,10 +78,17 @@ class ReactSSRServerForMPS : Disposable { companion object { private const val SHUTDOWN_GRACE_PERIOD_MS = 1_000L private const val SHUTDOWN_TIMEOUT_MS = 5_000L + private const val SHUTDOWN_MAX_WAIT_MS = 10_000L fun getInstance() = ApplicationManager.getApplication().getService(ReactSSRServerForMPS::class.java) } + init { + // Stopping the server in dispose() is only the fallback. dispose() is called inside a write action, where + // request handlers that wait for a read action can't finish. + stopBeforeDisposal(this, javaClass) { ensureStopped() } + } + private var ssrServer: ReactSSRServer? = null private var ktorServer: EmbeddedServer<*, *>? = null private var rendererFactory: MPSRendererFactory? = null @@ -191,9 +200,9 @@ class ReactSSRServerForMPS : Disposable { if (ktorServer == null) return println("stopping react SSR server") MPSModuleRepository.getInstance().modelAccess.removeCommandListener(commandLister) - // A bounded timeout is required. An unbounded stop() can block forever, which would block the plugin + // A bounded wait is required. An unbounded stop() can block forever, which would block the plugin // unloading and the MPS shutdown. - ktorServer?.stop(SHUTDOWN_GRACE_PERIOD_MS, SHUTDOWN_TIMEOUT_MS) + ktorServer?.stopBounded(SHUTDOWN_GRACE_PERIOD_MS, SHUTDOWN_TIMEOUT_MS, SHUTDOWN_MAX_WAIT_MS) ktorServer = null ssrServer?.dispose() ssrServer = null From 7f275cccdfd93948c6bd0c43accecdb85a169728 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 30 Oct 2026 17:00:25 +0100 Subject: [PATCH 05/23] fix(mps-plugin): write a reference target as its MPS presentation A reference cell generated from an MPS notation writes its target as NodePresentationUtil.presentation, which ends in SNode.getPresentation(). ModelixNodeAsMPSNode answered that with the stored name and otherwise with the toString() of the modelix node. A target whose name is derived by a property getter in the constraints, like an optionally named BlockInstance, has no stored name and was written as `MPSWritableNode(node=(instance of ...))`. getPresentation() now does what MPS's SNode does: it calls the getPresentation behavior, which reads the name through SNodeAccessUtil and so applies the property getter. The behavior runs on the wrapper instead of the unwrapped SNode, so every read it makes is still dependency tracked and the cell follows changes of the name. Co-Authored-By: Claude Opus 5.5 --- .../editor/ssr/mps/BaseLanguageTests.kt | 51 +++++++++++++++++++ .../mpsadapters/tomps/ModelixNodeAsMPSNode.kt | 7 ++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index 0bde2d11..942193a5 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -812,6 +812,57 @@ class BaseLanguageTests : TestBase("SimpleProject") { """) } + /** + * The presentation of a target is asked for on the tracked wrapper of the node, not the node itself: MPS's + * `getPresentation` behavior, which reads the name the way MPS code does - honouring a property getter in the + * constraints, as an optionally named concept has. A target whose name is not stored used to be written as the + * `toString()` of the modelix node (`MPSWritableNode(node=...)`), and naming it later has to update the cell, + * which it only does if the reads the behavior makes are dependency tracked. + */ + fun `test a reference to an unnamed target is written as its presentation and follows its name`() = + kotlinx.coroutines.test.runTest { + lateinit var declaration: IWritableNode + lateinit var variableReference: IWritableNode + writeAction { + declaration = + methodBodyNode + .addNewChild( + IChildLinkReference.fromName("statement"), + -1, + ConceptReference(BL + "1068581242864") + ).addNewChild( + IChildLinkReference.fromName("localVariableDeclaration"), + -1, + ConceptReference(BL + "1068581242863") + ) + variableReference = + methodBodyNode + .addNewChild( + IChildLinkReference.fromName("statement"), + -1, + ConceptReference(BL + "1068580123155") + ).addNewChild( + IChildLinkReference.fromName("expression"), + -1, + ConceptReference(BL + "1068498886296") + ) + // Declared by a super concept, which a link looked up by name alone does not find. + val link = + variableReference + .getConcept() + .getAllReferenceLinks() + .first { it.getSimpleName() == "variableDeclaration" } + variableReference.setReferenceTarget(link.toReference(), declaration) + } + editor.flush() + // What MPS writes for an unnamed node: the alias of LocalVariableDeclaration is ` `. + assertEquals("[ ]", referenceCellText(variableReference, "variableDeclaration")) + + writeAction { declaration.setPropertyValue(IPropertyReference.fromName("name"), "x") } + editor.flush() + assertEquals("x", referenceCellText(variableReference, "variableDeclaration")) + } + /** * The text of the cell that shows [node]'s reference in [linkName]. */ diff --git a/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt b/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt index 2f1af193..bb5b3b0b 100644 --- a/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt +++ b/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt @@ -140,7 +140,12 @@ data class ModelixNodeAsMPSNode( override fun isInstanceOfConcept(superConcept: SAbstractConcept): Boolean = node.getConcept().isSubConceptOf(MPSConcept(superConcept)) - override fun getPresentation(): String = getName() ?: node.toString() + /** + * What [jetbrains.mps.smodel.SNode.getPresentation] does: the `getPresentation` behavior, which also honours + * property getters in the constraints (a derived `name`). It runs on this wrapper rather than the unwrapped node, + * so every read it makes is dependency tracked. + */ + override fun getPresentation(): String = SNodeUtil.getPresentation(this).orEmpty() override fun getName(): String? = getProperty(SNodeUtil.property_INamedConcept_name) From 36825c5c17afdc1ef0beaf2242d48b3621001dc6 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 30 Oct 2026 17:24:00 +0100 Subject: [PATCH 06/23] fix(mps-plugin): support user objects, setReference and broken references on wrapped nodes ModelixNodeAsMPSNode left some SNode methods to SNodeBase, which throws, and reduced others to what modelix can resolve: - putUserObject threw and getUserObject always returned null. Behaviors of iets3 and other languages cache data in user objects, and since the presentation of a node is computed by its behavior, they also run on wrapped nodes now. User objects are kept on the MPS node, or on the wrapper for a node of another kind. - setReference with an SNodeReference, a ResolveInfo or an SReference threw. The node reference is stored through modelix. A ResolveInfo that holds a node is set as that node, so that a wrapper never ends up in an MPS node, and the other ones are passed to the MPS node. An SReference is stored as what it points to, because MPS only accepts its own references of the node. - getReference returned null for a reference whose target cannot be resolved, and the target node reference of a reference was computed by resolving it. MPS code finds broken references as ones that exist without a target and writes them with their resolve info, so the reference now exists as long as it points somewhere, says where it points to without resolving, and has the resolve info of the MPS reference. Co-Authored-By: Claude Opus 5.5 --- .../ssr/mps/ModelixNodeAsMPSNodeTest.kt | 133 ++++++++++++++++++ .../mpsadapters/tomps/ModelixNodeAsMPSNode.kt | 115 +++++++++++++-- 2 files changed, 239 insertions(+), 9 deletions(-) create mode 100644 projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt new file mode 100644 index 00000000..ed10376c --- /dev/null +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt @@ -0,0 +1,133 @@ +package org.modelix.editor.ssr.mps + +import jetbrains.mps.smodel.SNodePointer +import org.jetbrains.mps.openapi.language.SReferenceLink +import org.jetbrains.mps.openapi.model.ResolveInfo +import org.jetbrains.mps.openapi.model.SNode +import org.jetbrains.mps.openapi.persistence.PersistenceFacade +import org.modelix.model.api.ConceptReference +import org.modelix.model.api.IChildLinkReference +import org.modelix.model.api.IWritableNode +import org.modelix.model.mpsadapters.MPSWritableNode +import org.modelix.model.mpsadapters.tomps.ModelixNodeAsMPSNode + +/** + * The parts of [ModelixNodeAsMPSNode] that MPS code reaches beyond reading the model: user objects and the ways of + * setting a reference other than to a node, and references whose target cannot be resolved. + */ +@Suppress("ktlint:standard:function-naming") +class ModelixNodeAsMPSNodeTest : TestBase("SimpleProject") { + private lateinit var classNode: MPSWritableNode + + override fun setUp() { + super.setUp() + readAction { + val solution = mpsProject.projectModules.first { it.moduleName == "Solution1" } + classNode = + MPSWritableNode( + solution.models + .first() + .rootNodes + .first() + ) + } + } + + private fun wrap(node: IWritableNode): SNode = ModelixNodeAsMPSNode.toMPSNode(node) + + private val rawClass: SNode get() = classNode.node + + /** + * A `Class1 x;` in the body of the first method, whose `ClassifierType` has no target yet. + */ + private fun newClassifierType(): MPSWritableNode { + val method = classNode.getAllChildren().first { it.getContainmentLink().getSimpleName() == "member" } + val body = method.getAllChildren().first { it.getContainmentLink().getSimpleName() == "body" } + return body + .addNewChild(IChildLinkReference.fromName("statement"), -1, ConceptReference(BL + "1068581242864")) + .addNewChild(IChildLinkReference.fromName("localVariableDeclaration"), -1, ConceptReference(BL + "1068581242863")) + .addNewChild(IChildLinkReference.fromName("type"), -1, ConceptReference(BL + "1107535904670")) as MPSWritableNode + } + + private fun classifierLink(type: MPSWritableNode): SReferenceLink = + type.node.concept.referenceLinks + .first { it.name == "classifier" } + + /** + * A pointer into the model of the class to a node that is not there. + */ + private fun missingNode() = SNodePointer(rawClass.model!!.reference, PersistenceFacade.getInstance().createNodeId("1234567")) + + fun `test user objects are kept on the MPS node`() { + readAction { + val wrapper = wrap(classNode) + wrapper.putUserObject("key", "value") + assertEquals("value", wrapper.getUserObject("key")) + assertEquals("value", rawClass.getUserObject("key")) + assertTrue(wrapper.userObjectKeys.contains("key")) + + wrapper.putUserObject("key", null) + assertNull(rawClass.getUserObject("key")) + } + } + + fun `test a reference is set to a node reference`() { + writeAction { + val type = newClassifierType() + wrap(type).setReference(classifierLink(type), rawClass.reference) + assertSame(rawClass, type.node.getReferenceTarget(classifierLink(type))) + } + } + + fun `test a reference of another node is set as what it points to`() { + writeAction { + val source = newClassifierType() + source.node.setReferenceTarget(classifierLink(source), rawClass) + val type = newClassifierType() + wrap(type).setReference(classifierLink(type), wrap(source).getReference(classifierLink(source))) + assertSame(rawClass, type.node.getReferenceTarget(classifierLink(type))) + } + } + + /** + * The node of the resolve info may be a wrapper, but what ends up in the MPS node has to be the MPS node. + */ + fun `test a resolve info with a wrapped node stores the MPS node`() { + writeAction { + val type = newClassifierType() + wrap(type).setReference(classifierLink(type), ResolveInfo.of(wrap(classNode))) + assertSame(rawClass, type.node.getReferenceTarget(classifierLink(type))) + } + } + + /** + * MPS finds a broken reference as one that exists but has no target, and writes it with its resolve info. + */ + fun `test a reference that cannot be resolved still exists and says where it points to`() { + writeAction { + val type = newClassifierType() + val wrapper = wrap(type) + wrapper.setReference(classifierLink(type), ResolveInfo.of(missingNode(), "Missing")) + + val reference = checkNotNull(wrapper.getReference(classifierLink(type))) { "The broken reference is gone" } + assertNull(reference.targetNode) + assertEquals(missingNode(), reference.targetNodeReference) + assertEquals("Missing", (reference as jetbrains.mps.smodel.SReference).resolveInfo) + assertEquals(1, wrapper.references.count()) + } + } + + fun `test a dropped reference is gone`() { + writeAction { + val type = newClassifierType() + val wrapper = wrap(type) + wrapper.setReference(classifierLink(type), rawClass.reference) + wrapper.setReference(classifierLink(type), null as org.jetbrains.mps.openapi.model.SReference?) + assertNull(wrapper.getReference(classifierLink(type))) + } + } + + companion object { + private const val BL = "mps:f3061a53-9226-4cc5-a443-f952ceaf5816/" + } +} diff --git a/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt b/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt index bb5b3b0b..645cc161 100644 --- a/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt +++ b/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt @@ -6,10 +6,12 @@ import org.jetbrains.mps.openapi.language.SConcept import org.jetbrains.mps.openapi.language.SContainmentLink import org.jetbrains.mps.openapi.language.SProperty import org.jetbrains.mps.openapi.language.SReferenceLink +import org.jetbrains.mps.openapi.model.ResolveInfo import org.jetbrains.mps.openapi.model.SModelReference import org.jetbrains.mps.openapi.model.SNode import org.jetbrains.mps.openapi.model.SNodeId import org.jetbrains.mps.openapi.model.SNodeReference +import org.jetbrains.mps.openapi.model.SReference import org.modelix.model.api.BuiltinLanguages import org.modelix.model.api.IChildLinkReference import org.modelix.model.api.INode @@ -26,6 +28,9 @@ import org.modelix.model.mpsadapters.MPSNode import org.modelix.model.mpsadapters.MPSProperty import org.modelix.model.mpsadapters.MPSReferenceLink import org.modelix.model.mpsadapters.MPSWritableNode +import org.modelix.model.mpsadapters.toMPS +import org.modelix.model.mpsadapters.toModelix +import org.modelix.mps.multiplatform.model.MPSNodeReference data class ModelixNodeAsMPSNode( val node: IReadableNode, @@ -127,10 +132,16 @@ data class ModelixNodeAsMPSNode( override fun getReference(): SNodeReference = forceUnwrapMPSNode(this).reference - override fun getReference(link: SReferenceLink): jetbrains.mps.smodel.SReference? = - ReferenceAdapter(link).takeIf { - node.getReferenceTarget(MPSReferenceLink(link).toReference()) != null + /** + * A reference exists as soon as it points somewhere, whether or not the target can be resolved, as in MPS: a + * broken reference is how MPS code finds out that it is broken. + */ + override fun getReference(link: SReferenceLink): jetbrains.mps.smodel.SReference? { + val linkReference = MPSReferenceLink(link).toReference() + return ReferenceAdapter(link).takeIf { + node.getReferenceTargetRef(linkReference) != null || node.getReferenceTarget(linkReference) != null } + } override fun getConcept(): SConcept { val concept = node.getConcept() @@ -257,6 +268,50 @@ data class ModelixNodeAsMPSNode( writableNode.setReferenceTargetRef(MPSReferenceLink(link).toReference(), null) } + override fun setReference( + link: SReferenceLink, + target: SNodeReference, + ) { + writableNode.setReferenceTargetRef(MPSReferenceLink(link).toReference(), target.toModelix()) + } + + /** + * Only a [ResolveInfo] that names the target node can be stored by modelix. The others carry the text MPS + * resolves the target from, which only the MPS node can store. + */ + override fun setReference( + link: SReferenceLink, + resolveInfo: ResolveInfo?, + ) { + when (resolveInfo) { + null -> dropReference(link) + + // Its node may be one of these wrappers, which must not end up stored in the MPS node. + is ResolveInfo.N -> setReferenceTarget(link, resolveInfo.targetNode) + + else -> forceUnwrapMPSNode(this).setReference(link, resolveInfo) + } + } + + /** + * MPS only accepts a reference that already belongs to this node and copies its internal data. A reference that + * comes from elsewhere, like one of another node that is copied, is stored as what it points to instead. + */ + override fun setReference( + link: SReferenceLink, + reference: SReference?, + ) { + if (reference == null) return dropReference(link) + val target = reference.targetNodeReference + val resolveInfo = (reference as? jetbrains.mps.smodel.SReference)?.resolveInfo + when { + target != null && resolveInfo != null -> setReference(link, ResolveInfo.of(target, resolveInfo)) + target != null -> setReference(link, target) + resolveInfo != null -> setReference(link, ResolveInfo.of(resolveInfo)) + else -> dropReference(link) + } + } + override fun getReferences(): List = node .getReferenceLinks() @@ -294,11 +349,35 @@ data class ModelixNodeAsMPSNode( writableNode.setPropertyValue(IPropertyReference.fromName(role), value) } - override fun getUserObject(key: Any?): Any? = null + /** + * User objects are caches that MPS code attaches to a node, not model content, so they need no dependency + * tracking. They are kept on the MPS node, where they outlive this wrapper and are shared with code that uses the + * MPS node directly. Only a node of another kind keeps them here. + */ + private val ownUserObjects = java.util.concurrent.ConcurrentHashMap() - override fun toString(): String = "ModelixNodeAsMPSNode[$node]" + private fun userObjectHolder(): SNode? = (node as? MPSWritableNode)?.node + + override fun getUserObject(key: Any?): Any? { + userObjectHolder()?.let { return it.getUserObject(key) } + return ownUserObjects[key ?: return null] + } - override fun getUserObjectKeys(): MutableIterable = mutableListOf() + override fun putUserObject( + key: Any?, + value: Any?, + ) { + userObjectHolder()?.let { return it.putUserObject(key, value) } + if (key == null) return + if (value == null) ownUserObjects.remove(key) else ownUserObjects[key] = value + } + + override fun getUserObjectKeys(): MutableIterable { + userObjectHolder()?.let { return it.userObjectKeys.toMutableList() } + return ownUserObjects.keys.toMutableList() + } + + override fun toString(): String = "ModelixNodeAsMPSNode[$node]" override fun getRoleInParent(): String? = containmentLink?.name @@ -326,10 +405,28 @@ data class ModelixNodeAsMPSNode( override fun getTargetNode_internal(reporter: jetbrains.mps.smodel.SReference.ProblemReporter?): SNode? = this@ModelixNodeAsMPSNode.getReferenceTarget(link) - override fun getTargetNodeReference(): SNodeReference? = targetNode?.reference + /** + * What the reference points to as it is stored, without resolving it, so that a reference that cannot be + * resolved still says where it points to. Only a target that is not an MPS node is resolved for it. + */ + override fun getTargetNodeReference(): SNodeReference? { + val stored = node.getReferenceTargetRef(MPSReferenceLink(link).toReference()) + stored?.let { MPSNodeReference.tryConvert(it) }?.let { return it.toMPS() } + return targetNode?.reference + } - override fun getTargetSModelReference(): SModelReference? = targetNode?.reference?.modelReference + override fun getTargetSModelReference(): SModelReference? = targetNodeReference?.modelReference - override fun getTargetNodeId(): SNodeId? = targetNode?.reference?.nodeId + override fun getTargetNodeId(): SNodeId? = targetNodeReference?.nodeId + + /** + * The name MPS keeps for the target, which it shows for a reference that cannot be resolved. + */ + override fun getResolveInfo(): String? { + // Only for the dependency: the MPS reference the name is read from changes together with the target. + node.getReferenceTargetRef(MPSReferenceLink(link).toReference()) + val mpsNode = (node as? MPSWritableNode)?.node as? jetbrains.mps.smodel.SNode ?: return null + return mpsNode.getReference(link)?.resolveInfo + } } } From 743131a717fbf279c9e2053334e58ebe57de6379 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 30 Oct 2026 17:24:12 +0100 Subject: [PATCH 07/23] test(mps-plugin): set the variable reference by link name The link of a super concept is found by its name. The test failed only because of a concept id that doesn't exist, not because of the lookup. Co-Authored-By: Claude Opus 5.5 --- .../org/modelix/editor/ssr/mps/BaseLanguageTests.kt | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index 942193a5..b8a9ffce 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -846,13 +846,7 @@ class BaseLanguageTests : TestBase("SimpleProject") { -1, ConceptReference(BL + "1068498886296") ) - // Declared by a super concept, which a link looked up by name alone does not find. - val link = - variableReference - .getConcept() - .getAllReferenceLinks() - .first { it.getSimpleName() == "variableDeclaration" } - variableReference.setReferenceTarget(link.toReference(), declaration) + variableReference.setReferenceTarget(IReferenceLinkReference.fromName("variableDeclaration"), declaration) } editor.flush() // What MPS writes for an unnamed node: the alias of LocalVariableDeclaration is ` `. From bd43a50f22f8e4fac1aa0fe96ed3c5d9947f664c Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 6 Nov 2026 13:00:05 +0100 Subject: [PATCH 08/23] feat(projectional-editor): cell parameters for notation components A component can declare parameters and place them with a `slot` cell, and whoever includes it passes a cell for each. This makes wrapper notations possible, and it is how a shared layout gets around the `attributed` cell, which has to stay out of a component: the `@attribute info` is declared on the concrete attribute concept, and an argument keeps the notation it is written in as its ancestor, so every scope sees the concrete concept. Components are now inlined by a pre-processing script instead of a reduction rule, because a reduction under $COPY_SRC$ starts with a new template context and cannot tell which ComponentCell included it. Co-Authored-By: Claude Opus 5.5 --- ...notation.generator.templates@generator.mps | 564 ++++++++++-- .../org.modelix.mps.notation.behavior.mps | 862 +++++++++++++++++- .../org.modelix.mps.notation.constraints.mps | 141 +++ .../org.modelix.mps.notation.editor.mps | 195 +++- .../org.modelix.mps.notation.structure.mps | 58 ++ .../org.modelix.mps.notation.typesystem.mps | 158 ++++ 6 files changed, 1908 insertions(+), 70 deletions(-) diff --git a/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps b/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps index 57e3f23a..4467e642 100644 --- a/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps +++ b/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps @@ -36,14 +36,31 @@ + + + + + + + + + + + + + + + + + @@ -81,6 +98,7 @@ + @@ -98,6 +116,11 @@ + + + + + @@ -108,6 +131,7 @@ + @@ -135,6 +159,7 @@ + @@ -167,6 +192,7 @@ + @@ -196,6 +222,15 @@ + + + + + + + + + @@ -216,6 +251,11 @@ + + + + + @@ -239,6 +279,9 @@ + + + @@ -251,9 +294,13 @@ + + + + @@ -270,8 +317,13 @@ + + + - + + + @@ -281,6 +333,7 @@ + @@ -311,15 +364,28 @@ + + + + + + + + + + + + + @@ -6102,70 +6168,8 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + @@ -6481,5 +6485,435 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.behavior.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.behavior.mps index 83b45d3e..60a86c62 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.behavior.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.behavior.mps @@ -191,6 +191,10 @@ + + + + @@ -232,6 +236,7 @@ + @@ -2076,6 +2081,171 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2348,7 +2518,7 @@ - + @@ -2374,7 +2544,7 @@ - + @@ -2425,7 +2595,7 @@ - + @@ -2437,7 +2607,7 @@ - + @@ -2449,5 +2619,689 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.constraints.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.constraints.mps index 6b14ceb3..59b7c2e1 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.constraints.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.constraints.mps @@ -144,6 +144,12 @@ + + + + + + @@ -900,5 +906,140 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps index 44373fae..50ff3f76 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps @@ -21,8 +21,10 @@ + + @@ -124,6 +126,9 @@ + + + @@ -150,6 +155,9 @@ + + + @@ -159,6 +167,9 @@ + + + @@ -1232,6 +1243,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1252,7 +1293,7 @@ - + @@ -1280,6 +1321,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1297,5 +1421,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps index 879a637f..cf720bf1 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps @@ -658,6 +658,13 @@ + + + + + + + @@ -670,6 +677,13 @@ + + + + + + + @@ -687,5 +701,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.typesystem.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.typesystem.mps index 591bcf88..107ddf86 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.typesystem.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.typesystem.mps @@ -32,6 +32,7 @@ + @@ -70,6 +71,7 @@ + @@ -105,6 +107,9 @@ + + + @@ -1257,6 +1262,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1365,5 +1426,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 68668161d62de900247fcd8a2b4c943954a8f726 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 6 Nov 2026 13:00:09 +0100 Subject: [PATCH 09/23] refactor(projectional-editor): share baseLanguage wrappers with cell parameters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wrappers around a single cell (`alias ( … )`, `alias < … >`, `< … >`) are components now, and so are the two pairs of notations that only differ in the links they name, which a component without parameters could not share. The generated notations are unchanged. Co-Authored-By: Claude Opus 5.5 --- ...mps.notation.impl.baseLanguage.modelix.mps | 1108 ++++++++--------- 1 file changed, 502 insertions(+), 606 deletions(-) diff --git a/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps b/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps index 2250c932..6bbae5c6 100644 --- a/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps +++ b/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps @@ -38,10 +38,19 @@ + + + + + + + + + @@ -95,6 +104,7 @@ + @@ -647,24 +657,20 @@ - - - - - - - - - - - - + + + + + + + + + + + + - - - - @@ -742,24 +748,20 @@ - - - - - - - - - - - - + + + + + + + + + + + + - - - - @@ -2221,38 +2223,20 @@ - - - - - + + + + + + - - - - - - - - - - - - - - - - - - + + + - - - - @@ -2363,38 +2347,20 @@ - - - - - + + + + + + - - - - - - - - - - - - - - - - - - + + + - - - - @@ -3188,48 +3154,14 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - - - - @@ -3294,22 +3226,18 @@ - - - - - - - - - - + + + + + + + + + + - - - - @@ -3346,48 +3274,14 @@ - - - - - - - - - - - - - + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -3925,10 +3819,13 @@ - - - - + + + + + + + @@ -3953,13 +3850,16 @@ - - - - - - - + + + + + + + + + + @@ -3967,10 +3867,13 @@ - - - - + + + + + + + @@ -4161,6 +4064,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4266,23 +4265,17 @@ - - - - - - - - - - - + + + + + + + + + - - - - @@ -4627,19 +4620,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -4762,37 +4749,25 @@ - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + @@ -5375,37 +5350,25 @@ - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + @@ -5929,25 +5892,21 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + - - - - @@ -6072,19 +6031,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -6114,19 +6067,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -6183,37 +6130,25 @@ - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + @@ -6285,19 +6220,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -6341,55 +6270,37 @@ - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + @@ -6423,19 +6334,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -6604,19 +6509,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -6708,19 +6607,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -6759,37 +6652,25 @@ - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + @@ -6837,17 +6718,13 @@ - - - - - - - - - - - + + + + + + + @@ -6883,19 +6760,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -7061,55 +6932,37 @@ - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + @@ -7169,38 +7022,26 @@ - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + @@ -7226,19 +7067,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -8590,6 +8425,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -8789,27 +8701,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + - - - - @@ -9682,17 +9588,13 @@ - - - - - - - - - - - + + + + + + + @@ -9730,19 +9632,13 @@ - - - - - - - - - - - - - + + + + + + + From 8af1936ed3cc2cbd67d2b5dc16370e0ad1d483a3 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 6 Nov 2026 13:21:33 +0100 Subject: [PATCH 10/23] feat(projectional-editor): notations for the node attributes of baseLanguage Every NodeAttribute subconcept of the languages this model covers had a placeholder that was not rendered at all. The notations follow the MPS editors. Attributes that share a layout pass their `attributed` cell to a component as an argument, and the doc comments and imports bring the notations of the concepts inside them. Attributes that nobody adds by typing write their text with a label, because a constant next to the `attributed` cell is offered on every node the attribute can be attached to. Co-Authored-By: Claude Opus 5.5 --- ...mps.notation.impl.baseLanguage.modelix.mps | 641 +++++++++++++++--- 1 file changed, 545 insertions(+), 96 deletions(-) diff --git a/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps b/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps index 6bbae5c6..35b16e4c 100644 --- a/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps +++ b/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps @@ -18,6 +18,7 @@ + @@ -26,6 +27,7 @@ + @@ -33,9 +35,25 @@ + + + + + + + + + + + + + + + + @@ -79,6 +97,9 @@ + + + @@ -106,6 +127,7 @@ + @@ -143,12 +165,18 @@ + + + + + + @@ -3421,9 +3449,7 @@ - - - + @@ -3456,8 +3482,37 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -3513,15 +3568,42 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + @@ -3543,14 +3625,34 @@ - - + + + + + + + + + + + + + + - - + + + + + + + + + + @@ -7422,8 +7524,12 @@ - - + + + + + + @@ -7494,8 +7600,21 @@ - - + + + + + + + + + + + + + + + @@ -7614,8 +7733,21 @@ - - + + + + + + + + + + + + + + + @@ -7682,8 +7814,34 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -7776,9 +7934,7 @@ - - - + @@ -7896,8 +8052,12 @@ - - + + + + + + @@ -8007,8 +8167,12 @@ - - + + + + + + @@ -8198,8 +8362,12 @@ - - + + + + + + @@ -8295,6 +8463,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -8324,9 +8520,7 @@ - - - + @@ -8342,46 +8536,105 @@ - - - - - - + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - + + + + - - + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + @@ -8502,6 +8755,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -8772,14 +9063,18 @@ - - + + + + + + - - + + @@ -8825,8 +9120,11 @@ - - + + + + + @@ -8842,38 +9140,107 @@ - - + + - - + + + + + + + + - + - - + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -8924,14 +9291,26 @@ - - + + + + + + - - + + + + + + + + + + @@ -8986,14 +9365,17 @@ - - + + - - + + + + + @@ -9030,6 +9412,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -9196,12 +9631,16 @@ - - + + + + - - + + + + @@ -9210,9 +9649,12 @@ - - + + + + + @@ -9236,12 +9678,16 @@ - - + + + + - - + + + + @@ -9250,9 +9696,12 @@ - - + + + + + From f07221107807ac6c35664414e8e2f4064dd66398 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 6 Nov 2026 18:27:35 +0100 Subject: [PATCH 11/23] feat(projectional-editor): context actions menu for adding node attributes Alt+Enter opens a menu of actions for the selected node, which currently offers the node attributes that are applicable to it. Cells provide the actions through the new contextActions cell property. The menu shares its keyboard handling, filtering and positioning with the code completion menu through the new ActionMenu base class, but has its own look, so the two can't be confused. It opens below the line and leaves the cell text visible. ActionMenuTrigger is a sealed type with one implementation per menu. CodeCompletionMenuUI is folded into ActionMenu. The completion menu now keeps its selection within the filtered entries, and its caret no longer overlaps the last character of the pattern. Co-Authored-By: Claude Opus 5.5 --- .../editor/kernelf/NodeAttributeTest.kt | 200 +++++++++++++- .../src/jsMain/resources/editor.css | 62 +++++ .../editor/ssr/mps/BaseLanguageTests.kt | 21 ++ .../kotlin/org/modelix/editor/ActionMenu.kt | 254 ++++++++++++++++++ .../org/modelix/editor/CaretSelection.kt | 7 +- .../org/modelix/editor/CellSelection.kt | 7 + .../org/modelix/editor/CodeCompletionMenu.kt | 221 +++------------ .../modelix/editor/CodeCompletionMenuUI.kt | 58 ---- .../org/modelix/editor/ContextActions.kt | 42 +++ .../org/modelix/editor/ContextActionsMenu.kt | 61 +++++ .../kotlin/org/modelix/editor/EditorEngine.kt | 12 +- .../modelix/editor/FrontendEditorComponent.kt | 83 +++--- .../kotlin/org/modelix/editor/ICellAction.kt | 4 +- .../celltemplate/AttributedCellTemplate.kt | 20 ++ .../text/backend/TextEditorServiceImpl.kt | 56 ++-- .../editor/text/shared/TextEditorService.kt | 44 ++- .../src/components/ModelixTextEditor.css | 62 +++++ 17 files changed, 901 insertions(+), 313 deletions(-) create mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/ActionMenu.kt delete mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenuUI.kt create mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActions.kt create mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt diff --git a/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt b/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt index 2fd41633..bf330e31 100644 --- a/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt +++ b/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt @@ -10,13 +10,17 @@ import org.iets3.core.expr.simpleTypes.C_NumberLiteral import org.iets3.core.expr.tests.C_OldNodeAnnotation import org.modelix.editor.CaretSelection import org.modelix.editor.Cell +import org.modelix.editor.CellSelection +import org.modelix.editor.ContextActionsMenu import org.modelix.editor.EditorAspect import org.modelix.editor.EditorEngine import org.modelix.editor.FrontendEditorComponent import org.modelix.editor.JSKeyboardEvent import org.modelix.editor.JSKeyboardEventType import org.modelix.editor.KeyLocation +import org.modelix.editor.KnownKeys import org.modelix.editor.Modifiers +import org.modelix.editor.NodeCellReference import org.modelix.editor.descendants import org.modelix.editor.layoutable import org.modelix.editor.text.backend.TextEditorServiceImpl @@ -32,7 +36,9 @@ import org.modelix.model.area.PArea import org.modelix.model.withIncrementalComputationSupport import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertIs import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue /** @@ -201,6 +207,190 @@ class NodeAttributeTest { assertEquals("(200)", renderedText()) } + @Test + fun altEnterOffersTheAttributesOfTheSelectedNode() = + runAttributeTest { + openContextActions(cellWithText("200")) + + assertEquals(listOf(ADD_BOOKMARK, ADD_TODO, ADD_OLD_NODE), contextActions()) + assertEquals(emptyList(), attributeConcepts()) + } + + @Test + fun enterExecutesTheSelectedContextAction() = + runAttributeTest { + openContextActions(cellWithText("200")) + pressKey(KnownKeys.ArrowDown) + pressKey(KnownKeys.Enter) + + assertEquals(listOf("DotDotDot"), attributeConcepts()) + assertEquals("(todo 200)", renderedText()) + assertNull(editor.getActionMenu()) + } + + @Test + fun escapeClosesTheContextActionsMenu() = + runAttributeTest { + openContextActions(cellWithText("200")) + pressKey(KnownKeys.Escape) + + assertNull(editor.getActionMenu()) + assertEquals(emptyList(), attributeConcepts()) + } + + @Test + fun enterWithoutAltDoesNotOpenTheContextActionsMenu() = + runAttributeTest { + selectText(cellWithText("200")) + pressKey(KnownKeys.Enter) + + assertNull(editor.getActionMenu()) + } + + @Test + fun searchingUsesTheWholePatternWhereverTheCaretIs() = + runAttributeTest { + openContextActions(cellWithText("200")) + typeIntoMenu("mark") + pressKey(KnownKeys.ArrowLeft) + + assertEquals(listOf(ADD_BOOKMARK), contextActions()) + } + + @Test + fun typingSearchesTheContextActionsAnywhereInTheirTextIgnoringTheCase() = + runAttributeTest { + openContextActions(cellWithText("200")) + typeIntoMenu("MARK") + + assertEquals(listOf(ADD_BOOKMARK), contextActions()) + } + + @Test + fun aContextActionIsNotExecutedBeforeItIsConfirmed() = + runAttributeTest { + openContextActions(cellWithText("200")) + typeIntoMenu(ADD_BOOKMARK) + + assertEquals(emptyList(), attributeConcepts()) + pressKey(KnownKeys.Enter) + assertEquals(listOf("BookmarkAnnotation"), attributeConcepts()) + } + + @Test + fun narrowingTheContextActionsKeepsAnEntrySelected() = + runAttributeTest { + openContextActions(cellWithText("200")) + pressKey(KnownKeys.ArrowUp) // wraps around to the last one + typeIntoMenu("bookmark") + pressKey(KnownKeys.Enter) + + assertEquals(listOf("BookmarkAnnotation"), attributeConcepts()) + } + + @Test + fun anAttributeWithoutTextOfItsOwnCanBeAddedWithAContextAction() = + runAttributeTest({ conceptEditor(C_NameAnnotation) { attributed() } }) { + openContextActions(cellWithText("200")) + typeIntoMenu(C_NameAnnotation.untyped().getShortName()) + pressKey(KnownKeys.Enter) + + assertEquals(listOf("NameAnnotation"), attributeConcepts()) + assertEquals("(200)", renderedText()) + } + + @Test + fun aContextActionIsOnlyOfferedForAnAttributeThatCanBeAdded() = + runAttributeTest { + addAttribute(C_BookmarkAnnotation.untyped()) { it.setPropertyValue("label", "b1") } + + openContextActions(cellWithText("200")) + + assertEquals(listOf(ADD_TODO, ADD_OLD_NODE), contextActions()) + } + + @Test + fun aContextActionAppliesToTheSelectedParentNode() = + runAttributeTest { + // OldNodeAnnotation can only be attached to a number literal. + val parensCell = editor.resolveCell(NodeCellReference(parens.reference)).single() + editor.doChangeSelection(CellSelection(editor, parensCell, true, null)) + pressKey(KnownKeys.Enter, Modifiers.ALT) + assertEquals(listOf(ADD_BOOKMARK, ADD_TODO), contextActions()) + + pressKey(KnownKeys.Enter) + + assertEquals(emptyList(), attributeConcepts()) + assertEquals(listOf("BookmarkAnnotation"), attributeConcepts(parens)) + } + + @Test + fun anAttributeAddedOnTheNodeGoesInsideTheExistingOnes() = + runAttributeTest { + addAttribute(C_DotDotDot.untyped()) + + openContextActions(cellWithText("200")) + typeIntoMenu("bookmark") + pressKey(KnownKeys.Enter) + + assertEquals(listOf("DotDotDot", "BookmarkAnnotation"), attributeConcepts()) + } + + @Test + fun anAttributeAddedOnAnotherOneGoesOutsideOfIt() = + runAttributeTest { + addAttribute(C_DotDotDot.untyped()) + + openContextActions(cellWithText("todo")) + typeIntoMenu("bookmark") + pressKey(KnownKeys.Enter) + + assertEquals(listOf("BookmarkAnnotation", "DotDotDot"), attributeConcepts()) + } + + private suspend fun selectText(cell: Cell) { + editor.flushAndUpdateSelection { CaretSelection(editor, cell.layoutable()!!, 0) } + editor.flush() + } + + private suspend fun openContextActions(cell: Cell) { + selectText(cell) + pressKey(KnownKeys.Enter, Modifiers.ALT) + } + + private suspend fun pressKey( + key: KnownKeys, + modifiers: Modifiers = Modifiers.NONE, + ) { + editor.processKeyEvent( + JSKeyboardEvent(JSKeyboardEventType.KEYDOWN, null, key, key.name, modifiers, KeyLocation.STANDARD, false, false), + ) + editor.flush() + } + + private suspend fun typeIntoMenu(text: String) { + for (c in text) { + editor.processKeyEvent( + JSKeyboardEvent( + JSKeyboardEventType.KEYDOWN, + c.toString(), + null, + c.toString(), + Modifiers.NONE, + KeyLocation.STANDARD, + false, + false + ), + ) + editor.flush() + } + } + + private fun contextActions(): List = + assertIs(editor.getActionMenu(), "The context actions menu is not open") + .getVisibleEntries() + .map { it.matchingText } + private suspend fun addAttribute( concept: IConcept, init: (INode) -> Unit = {}, @@ -227,8 +417,8 @@ class NodeAttributeTest { editor.flushAndUpdateSelection { null } } - private fun attributeConcepts(): List = - branch.computeRead { literal.getChildren("smodelAttribute").map { it.concept!!.getShortName() }.toList() } + private fun attributeConcepts(node: INode = literal): List = + branch.computeRead { node.getChildren("smodelAttribute").map { it.concept!!.getShortName() }.toList() } private fun cellWithText(text: String): Cell = assertNotNull( @@ -290,4 +480,10 @@ class NodeAttributeTest { "!!".constant() } } + + private companion object { + const val ADD_BOOKMARK = "Add BookmarkAnnotation" + const val ADD_TODO = "Add DotDotDot" + const val ADD_OLD_NODE = "Add OldNodeAnnotation" + } } diff --git a/projectional-editor-ssr-client/src/jsMain/resources/editor.css b/projectional-editor-ssr-client/src/jsMain/resources/editor.css index f5799dda..a083f452 100644 --- a/projectional-editor-ssr-client/src/jsMain/resources/editor.css +++ b/projectional-editor-ssr-client/src/jsMain/resources/editor.css @@ -142,6 +142,68 @@ padding: 3px 6px; } +.editor .context-actions-menu { + position: absolute; + z-index: 1; + min-width: 200px; + white-space: nowrap; + font-family: sans-serif; + font-size: 10pt; + color: black; + background-color: white; + border: 1px solid #acacac; + border-radius: 4px; + overflow: hidden; + box-shadow: 2px 2px 12px 0 rgba(0, 0, 0, 0.35); +} + +.editor .context-actions-menu .context-actions-title { + padding: 2px 8px; + font-size: 9pt; + color: #555; + background-color: #ededed; + border-bottom: 1px solid #d0d0d0; +} + +.editor .context-actions-menu .context-actions-search { + padding: 2px 8px; + border-bottom: 1px solid #d0d0d0; +} + +.editor .context-actions-menu .context-actions-pattern { + display: inline-block; +} + +.editor .context-actions-menu .context-actions-entries { + max-height: 200px; + overflow-y: auto; +} + +.editor .context-actions-menu .context-action { + display: flex; + justify-content: space-between; + gap: 24px; + padding: 3px 8px; +} + +.editor .context-actions-menu .context-action.selected { + background-color: #1055d1; + color: white; +} + +.editor .context-actions-menu .context-action-description { + color: #808080; +} + +.editor .context-actions-menu .context-action.selected .context-action-description { + color: #d5e0f5; +} + +.editor .context-actions-menu .context-actions-empty { + padding: 3px 8px; + color: #808080; +} + /* Cmd/Ctrl+click navigates to the target of a reference. While the modifier is held, the reference cell under the mouse is marked as clickable, like MPS does. The class on the container is set by the client that dispatches the keyboard events. */ diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index b8a9ffce..cd47fdaf 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -17,6 +17,7 @@ import org.modelix.editor.ICodeCompletionActionProvider import org.modelix.editor.JSKeyboardEvent import org.modelix.editor.JSKeyboardEventType import org.modelix.editor.KnownKeys +import org.modelix.editor.Modifiers import org.modelix.editor.NodeCellReference import org.modelix.editor.ReferencedNodeCellReference import org.modelix.editor.ancestors @@ -961,6 +962,26 @@ class BaseLanguageTests : TestBase("SimpleProject") { """) } + fun `test the context actions menu adds a node attribute to the selected node`() = + kotlinx.coroutines.test.runTest { + placeCaretIntoCellWithText("method1", 0) + editor.processKeyEvent( + JSKeyboardEvent(JSKeyboardEventType.KEYDOWN, null, KnownKeys.Enter, KnownKeys.Enter.name, Modifiers.ALT), + ) + editor.flush() + typeText("review") + pressEnter() + editor.flush() + assertFinalEditorText(""" + public class Class1 { + @Review + public void method1() { + + } + } + """) + } + fun `test deleting the text of a node attribute removes it but keeps the node`() = kotlinx.coroutines.test.runTest { writeAction { methodNode.addNewChild(SMODEL_ATTRIBUTE, -1, REVIEW_MIGRATION) } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ActionMenu.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ActionMenu.kt new file mode 100644 index 00000000..6f796cf0 --- /dev/null +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ActionMenu.kt @@ -0,0 +1,254 @@ +package org.modelix.editor + +import io.github.oshai.kotlinlogging.KotlinLogging +import kotlinx.html.TagConsumer +import kotlinx.html.div +import org.modelix.editor.text.shared.CompletionMenuEntryData +import org.modelix.editor.text.shared.celltree.cellReferences + +private val LOG = KotlinLogging.logger { } + +class ReresolvableLayoutable( + initial: LayoutableCell, +) { + private var current: LayoutableCell = initial + private var references = initial.cell.cellReferences + + fun get(editor: FrontendEditorComponent): LayoutableCell { + if (!current.cell.isAttached()) { + val resolvedCell = + checkNotNull(references.firstNotNullOfOrNull { editor.resolveCell(it).firstOrNull() }) { + "Cell not found: $references" + } + current = + checkNotNull(editor.resolveLayoutable(resolvedCell)) { + "Layoutable not found for cell $resolvedCell" + } + } + return current + } +} + +/** + * A popup at a cell with a list of actions, which is navigated with the keyboard and narrowed down by typing. + * What the actions are for decides how they are matched, what typing does and how the menu looks. + * + * @see CodeCompletionMenu + * @see ContextActionsMenu + */ +abstract class ActionMenu( + val editor: FrontendEditorComponent, + anchor: LayoutableCell, + initialEntries: List, + initialPattern: String = "", + initialCaretPosition: Int? = null, +) : IProducesHtml, + IKeyboardHandler { + val patternEditor = PatternEditor(initialPattern, initialCaretPosition) + protected var selectedIndex: Int = 0 + private set + protected var allEntries: List = initialEntries + private set + protected var filteredEntries: List = allEntries + private set + private val anchor = ReresolvableLayoutable(anchor) + + init { + applyFilter() + } + + /** + * The CSS class of the element that contains the text of the pattern. + */ + protected abstract val patternClass: String + + /** + * The CSS class of the element of the selected entry. + */ + protected abstract val selectedEntryClass: String + + /** + * Invoked from the constructor of this class, so it can't use any state of the subclass. + */ + protected abstract fun matches(entry: CompletionMenuEntryData): Boolean + + /** + * Brings the entries in line with the pattern after it or the caret changed. + */ + protected abstract suspend fun updateEntries() + + /** + * The position of the menu relative to the main layer, given the bounds of the anchor relative to the same layer. + */ + protected abstract fun getPosition(anchorBounds: Bounds): Position + + protected open suspend fun onPatternEdited() = updateEntries() + + protected open suspend fun onTextInserted( + oldTextBeforeCaret: String, + remainingText: String, + ) = onPatternEdited() + + fun getAnchor() = anchor.get(editor) + + override fun isHtmlOutputValid(): Boolean = false + + fun loadEntries(newActions: List) { + allEntries = newActions + applyFilter() + } + + fun applyFilter() { + filteredEntries = allEntries.filter { matches(it) } + selectedIndex = selectedIndex.coerceAtMost(filteredEntries.lastIndex).coerceAtLeast(0) + } + + fun selectNext() { + selectedIndex++ + if (selectedIndex >= filteredEntries.size) selectedIndex = 0 + editor.invalidateActionMenu() + } + + fun selectPrevious() { + selectedIndex-- + if (selectedIndex < 0) selectedIndex = (filteredEntries.size - 1).coerceAtLeast(0) + editor.invalidateActionMenu() + } + + fun getSelectedEntry(): CompletionMenuEntryData? = filteredEntries.getOrNull(selectedIndex) + + fun getVisibleEntries(): List = filteredEntries + + override suspend fun processKeyDown(event: JSKeyboardEvent): Boolean { + when (event.knownKey) { + KnownKeys.ArrowUp -> { + selectPrevious() + } + + KnownKeys.ArrowDown -> { + selectNext() + } + + KnownKeys.ArrowLeft -> { + patternEditor.moveCaret(-1) + } + + KnownKeys.ArrowRight -> { + patternEditor.moveCaret(1) + } + + KnownKeys.Escape -> { + editor.closeActionMenu() + } + + KnownKeys.Enter -> { + getSelectedEntry()?.let { execute(it) } + } + + KnownKeys.Backspace -> { + patternEditor.deleteText(true) + } + + KnownKeys.Delete -> { + patternEditor.deleteText(false) + } + + else -> { + if (event.typedText.isNullOrEmpty()) return false + if (event.typedText == " " && event.modifiers.ctrl) { + patternEditor.moveCaret(-patternEditor.caretPos) + } else { + patternEditor.insertText(event.typedText) + } + } + } + editor.flushLocalLater() + return true + } + + protected suspend fun execute(entry: CompletionMenuEntryData) { + editor.serviceCall { + executeCodeCompletionAction(editor.editorId, entry.id) + } + editor.closeActionMenu() + } + + fun updateBounds() { + LOG.trace { "ActionMenu.updateBounds()" } + val containerElement = editor.getHtmlElement(this) ?: return + val anchorElement = editor.getHtmlElement(getAnchor()) ?: return + val anchorBounds = anchorElement.getOuterBounds().relativeTo(editor.getMainLayer()?.getOuterBounds() ?: Bounds.ZERO) + val position = getPosition(anchorBounds) + containerElement.style.left = "${position.left}px" + containerElement.style.top = "${position.top}px" + + getPatternElement()?.let { patternElement -> + CaretSelectionView.updateCaretBounds( + patternElement, + patternEditor.caretPos, + containerElement, + containerElement.elementsWithClass("caret").first(), + ) + } + + editor.scrollIntoViewLater { editor.getHtmlElement(this)?.elementsWithClass(selectedEntryClass)?.firstOrNull() } + } + + protected fun getPatternElement(): IVirtualDom.HTMLElement? = + editor.getHtmlElement(this)?.elementsWithClass(patternClass)?.firstOrNull() + + private fun IVirtualDom.HTMLElement.elementsWithClass(cssClass: String): Sequence = + descendants().filterIsInstance().filter { it.getClasses().contains(cssClass) } + + data class Position( + val left: Double, + val top: Double, + ) + + inner class PatternEditor( + initialPattern: String, + initialCaretPosition: Int?, + ) : IProducesHtml { + var caretPos: Int = initialCaretPosition ?: initialPattern.length + var pattern: String = initialPattern + + override fun isHtmlOutputValid(): Boolean = false + + fun getTextBeforeCaret() = pattern.substring(0, caretPos) + + suspend fun deleteText(before: Boolean): Boolean { + if (before) { + if (caretPos == 0) return false + pattern = pattern.removeRange((caretPos - 1) until caretPos) + caretPos-- + } else { + if (caretPos == pattern.length) return false + pattern = pattern.removeRange(caretPos..caretPos) + } + onPatternEdited() + return true + } + + suspend fun insertText(text: String) { + val oldTextBeforeCaret = getTextBeforeCaret() + pattern = pattern.replaceRange(caretPos until caretPos, text) + val remainingText = pattern.substring(caretPos) + caretPos += text.length + onTextInserted(oldTextBeforeCaret, remainingText) + } + + suspend fun moveCaret(delta: Int) { + caretPos = (caretPos + delta).coerceIn(0..pattern.length) + updateEntries() + } + + override fun produceHtml(consumer: TagConsumer) { + consumer.div { + div(patternClass) { + +pattern.useNbsp() + } + div(if (caretPos > 0 && caretPos == pattern.length) "caret own rightend" else "caret own") { } + } + } + } +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CaretSelection.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CaretSelection.kt index e222114d..8e244b57 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CaretSelection.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CaretSelection.kt @@ -154,7 +154,12 @@ class CaretSelection( } KnownKeys.Enter -> { - editor.serviceCall { executeInsert(editor.editorId, layoutable.cell.getId()) } + val cellId = layoutable.cell.getId() + if (event.modifiers == Modifiers.ALT) { + editor.serviceCall { triggerContextActions(editor.editorId, cellId, cellId) } + } else { + editor.serviceCall { executeInsert(editor.editorId, cellId) } + } } else -> { diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellSelection.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellSelection.kt index f6092a47..5a0efa6b 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellSelection.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellSelection.kt @@ -74,6 +74,13 @@ data class CellSelection( } } + KnownKeys.Enter -> { + val anchor = getLayoutables().filterIsInstance().firstOrNull() + if (event.modifiers == Modifiers.ALT && anchor != null) { + editor.serviceCall { triggerContextActions(editor.editorId, cell.getId(), anchor.cell.getId()) } + } + } + else -> { val typedText = event.typedText if (!typedText.isNullOrEmpty()) { diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt index ffecd2fe..d7c524f4 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt @@ -7,133 +7,66 @@ import kotlinx.html.td import kotlinx.html.tr import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.editor.text.shared.CompletionMenuEntryData -import org.modelix.editor.text.shared.celltree.cellReferences - -class ReresolvableLayoutable( - initial: LayoutableCell, -) { - private var current: LayoutableCell = initial - private var references = initial.cell.cellReferences - - fun get(editor: FrontendEditorComponent): LayoutableCell { - if (!current.cell.isAttached()) { - val resolvedCell = - checkNotNull(references.firstNotNullOfOrNull { editor.resolveCell(it).firstOrNull() }) { - "Cell not found: $references" - } - current = - checkNotNull(editor.resolveLayoutable(resolvedCell)) { - "Layoutable not found for cell $resolvedCell" - } - } - return current - } -} class CodeCompletionMenu( - val editor: FrontendEditorComponent, + editor: FrontendEditorComponent, anchor: LayoutableCell, val completionPosition: CompletionPosition, initialEntries: List, initialPattern: String = "", initialCaretPosition: Int? = null, -) : IProducesHtml, - IKeyboardHandler { - val patternEditor = PatternEditor(initialPattern, initialCaretPosition) - private var selectedIndex: Int = 0 - private var allEntries: List = initialEntries - private var filteredEntries: List = allEntries - private val anchor = ReresolvableLayoutable(anchor) - - init { - applyFilter() - } +) : ActionMenu(editor, anchor, initialEntries, initialPattern, initialCaretPosition) { + override val patternClass: String get() = "ccmenu-pattern" + override val selectedEntryClass: String get() = "ccSelectedEntry" - fun getAnchor() = anchor.get(editor) + override fun matches(entry: CompletionMenuEntryData): Boolean = entry.matches(patternEditor.getTextBeforeCaret()) - override fun isHtmlOutputValid(): Boolean = false - - fun loadEntries(newActions: List) { - allEntries = newActions - applyFilter() - } - - fun applyFilter() { - val pattern = patternEditor.getTextBeforeCaret() - filteredEntries = allEntries.filter { it.matches(pattern) } - } - - suspend fun updateActions() { + override suspend fun updateEntries() { editor.updateCodeCompletionActions(getAnchor().cell, patternEditor.getTextBeforeCaret()) } - fun selectNext() { - selectedIndex++ - if (selectedIndex >= filteredEntries.size) selectedIndex = 0 - editor.invalidateCompletionMenu() - } - - fun selectPrevious() { - selectedIndex-- - if (selectedIndex < 0) selectedIndex = (filteredEntries.size - 1).coerceAtLeast(0) - editor.invalidateCompletionMenu() + override suspend fun onPatternEdited() { + updateEntries() + executeIfSingleAction() } - fun getSelectedEntry(): CompletionMenuEntryData? = filteredEntries.getOrNull(selectedIndex) - - override suspend fun processKeyDown(event: JSKeyboardEvent): Boolean { - when (event.knownKey) { - KnownKeys.ArrowUp -> { - selectPrevious() - } - - KnownKeys.ArrowDown -> { - selectNext() - } - - KnownKeys.ArrowLeft -> { - patternEditor.moveCaret(-1) - } - - KnownKeys.ArrowRight -> { - patternEditor.moveCaret(1) - } - - KnownKeys.Escape -> { - editor.closeCodeCompletionMenu() - } - - KnownKeys.Enter -> { - getSelectedEntry()?.execute() - } - - KnownKeys.Backspace -> { - patternEditor.deleteText(true) - } - - KnownKeys.Delete -> { - patternEditor.deleteText(false) + override suspend fun onTextInserted( + oldTextBeforeCaret: String, + remainingText: String, + ) { + val exactMatches = allEntries.filter { it.matchesExactly(oldTextBeforeCaret) } + if (exactMatches.size == 1 && + !editor.serviceCall { + hasCodeCompletionActions(editor.editorId, getAnchor().cell.getId(), patternEditor.getTextBeforeCaret()) } - - else -> { - if (event.typedText.isNullOrEmpty()) return false - if (event.typedText == " " && event.modifiers.ctrl) { - patternEditor.moveCaret(-patternEditor.caretPos) - } else { - patternEditor.insertText(event.typedText) + ) { + execute(exactMatches.single()) + editor.closeActionMenu() + if (remainingText.isNotEmpty()) { + editor.enqueueUpdate { + (editor.getSelection() as CaretSelection).processTypedText(remainingText) } } + } else { + onPatternEdited() } - editor.flushLocalLater() - return true } - private suspend fun CompletionMenuEntryData.execute() { - val entry = this - editor.serviceCall { - executeCodeCompletionAction(editor.editorId, entry.id) + suspend fun executeIfSingleAction() { + val singleEntry = filteredEntries.singleOrNull() ?: return + if (singleEntry.matchesExactly(patternEditor.getTextBeforeCaret())) { + execute(singleEntry) } - editor.closeCodeCompletionMenu() + } + + override fun getPosition(anchorBounds: Bounds): Position { + val left = + when (completionPosition) { + CompletionPosition.CENTER -> anchorBounds.x + CompletionPosition.LEFT -> anchorBounds.x - (getPatternElement()?.getOuterBounds()?.width ?: 0.0) + CompletionPosition.RIGHT -> anchorBounds.maxX() + } + return Position(left, anchorBounds.y) } override fun produceHtml(consumer: TagConsumer) { @@ -142,7 +75,7 @@ class CodeCompletionMenu( div("ccmenu") { table { filteredEntries.forEachIndexed { index, action -> - tr("ccSelectedEntry".takeIf { index == selectedIndex }) { + tr(selectedEntryClass.takeIf { index == selectedIndex }) { td("matchingText") { +action.matchingText } @@ -162,80 +95,6 @@ class CodeCompletionMenu( } } } - - suspend fun executeIfSingleAction() { - val singleEntry = filteredEntries.singleOrNull() ?: return - if (singleEntry.matchesExactly(patternEditor.getTextBeforeCaret())) { - singleEntry.execute() - } - } - - inner class PatternEditor( - initialPattern: String, - initialCaretPosition: Int?, - ) : IProducesHtml { - private var patternCell: Cell? = null - var caretPos: Int = initialCaretPosition ?: initialPattern.length - var pattern: String = initialPattern - - override fun isHtmlOutputValid(): Boolean = false - - fun getTextBeforeCaret() = pattern.substring(0, caretPos) - - suspend fun deleteText(before: Boolean): Boolean { - if (before) { - if (caretPos == 0) return false - pattern = pattern.removeRange((caretPos - 1) until caretPos) - caretPos-- - } else { - if (caretPos == pattern.length) return false - pattern = pattern.removeRange(caretPos..caretPos) - } - updateActions() - executeIfSingleAction() - return true - } - - suspend fun insertText(text: String) { - val oldTextBeforeCaret = pattern.substring(0, caretPos) - pattern = pattern.replaceRange(caretPos until caretPos, text) - val remainingText = pattern.substring(caretPos) - caretPos += text.length - val newTextBeforeCaret = pattern.substring(0, caretPos) - - val exactMatches = allEntries.filter { it.matchesExactly(oldTextBeforeCaret) } - if (exactMatches.size == 1 && - !editor.serviceCall { - hasCodeCompletionActions(editor.editorId, getAnchor().cell.getId(), newTextBeforeCaret) - } - ) { - exactMatches.single().execute() - editor.closeCodeCompletionMenu() - if (remainingText.isNotEmpty()) { - editor.enqueueUpdate { - (editor.getSelection() as CaretSelection).processTypedText(remainingText) - } - } - } else { - updateActions() - executeIfSingleAction() - } - } - - suspend fun moveCaret(delta: Int) { - caretPos = (caretPos + delta).coerceIn(0..pattern.length) - updateActions() - } - - override fun produceHtml(consumer: TagConsumer) { - consumer.div { - div("ccmenu-pattern") { - +pattern.useNbsp() - } - div("caret own") { } - } - } - } } class CachedCodeCompletionActions( diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenuUI.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenuUI.kt deleted file mode 100644 index e6b44705..00000000 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenuUI.kt +++ /dev/null @@ -1,58 +0,0 @@ -package org.modelix.editor - -import io.github.oshai.kotlinlogging.KotlinLogging - -private val LOG = KotlinLogging.logger { } - -class CodeCompletionMenuUI( - val ccmenu: CodeCompletionMenu, - val editor: FrontendEditorComponent, -) { - fun updateBounds() { - LOG.trace { "CodeCompletionMenuUI.updateBounds()" } - val ccContainerElement = editor.getHtmlElement(ccmenu) ?: return - val layoutable = ccmenu.getAnchor() - val anchorElement = editor.getHtmlElement(layoutable) ?: return - val anchorAbsoluteBounds = anchorElement.getOuterBounds() - val anchorRelativeBounds = - anchorAbsoluteBounds.relativeTo(editor.getMainLayer()?.getOuterBounds() ?: Bounds.ZERO) - val patternElement = - ccContainerElement - .descendants() - .filterIsInstance() - .first { it.getClasses().contains("ccmenu-pattern") } - val left: Double = - when (ccmenu.completionPosition) { - CompletionPosition.CENTER -> { - anchorRelativeBounds.x - } - - CompletionPosition.LEFT -> { - anchorRelativeBounds.x - patternElement.getOuterBounds().width - } - - CompletionPosition.RIGHT -> { - anchorRelativeBounds.maxX() - } - } - ccContainerElement.style.left = "${left}px" - ccContainerElement.style.top = "${anchorRelativeBounds.y}px" - - val caretElement = - ccContainerElement.descendants().filterIsInstance().first { it.getClasses().contains("caret") } - CaretSelectionView.updateCaretBounds( - patternElement, - ccmenu.patternEditor.caretPos, - ccContainerElement, - caretElement, - ) - - editor.scrollIntoViewLater { - editor - .getHtmlElement(ccmenu) - ?.descendants() - ?.filterIsInstance() - ?.firstOrNull { it.`class`.orEmpty().contains("ccSelectedEntry") } - } - } -} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActions.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActions.kt new file mode 100644 index 00000000..61879ed8 --- /dev/null +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActions.kt @@ -0,0 +1,42 @@ +package org.modelix.editor + +import org.modelix.editor.celltemplate.getAddAttributeContextAction +import org.modelix.model.api.INode + +/** + * Context actions are what is offered in a menu for the selection instead of being reached by typing, like the + * intentions of MPS. They are the place for everything a projectional editor has no natural gesture for. + * + * The menu is opened with Alt+Enter and shows the context actions of the node the selected cell belongs to, so that + * selecting a parent node (Cmd+Up) offers the actions of that one. A context action is an [ICodeCompletionAction] whose + * [ICodeCompletionAction.getMatchingText] is what the menu shows, and a cell offers them through + * [CellActionProperties.contextActions]. + */ +fun Cell.getContextActions(): ICodeCompletionActionProvider? = + ancestors(true).firstNotNullOfOrNull { it.getProperty(CellActionProperties.contextActions) } + +/** + * The context actions of [node], which are set on its cell. + */ +class NodeContextActions( + val node: INode, +) : ICodeCompletionActionProvider { + override fun getApplicableActions(parameters: CodeCompletionParameters): List = + getAddAttributeActions(parameters.editor.engine) + + /** + * Same placement as the side transforms: a new attribute goes directly outside of the selected attribute, and + * inside all existing ones if the node itself is selected. + */ + private fun getAddAttributeActions(engine: EditorEngine): List { + val attributedNode = node.getAttributedNode().takeIf { node.concept?.isNodeAttribute() == true } + val target = attributedNode ?: node + val index = + if (attributedNode != null) { + attributedNode.getAttributes().indexOfFirst { it.reference == node.reference } + } else { + engine.getIndexInsideNodeAttributes(node) + } + return engine.getNodeAttributeTemplates().mapNotNull { it.getAddAttributeContextAction(target, index) } + } +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt new file mode 100644 index 00000000..a4517046 --- /dev/null +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt @@ -0,0 +1,61 @@ +package org.modelix.editor + +import kotlinx.html.TagConsumer +import kotlinx.html.div +import org.modelix.editor.text.shared.CompletionMenuEntryData + +/** + * The menu of the context actions of the selection (see [getContextActions]). + * + * Nothing is being completed here, so unlike the [CodeCompletionMenu] it leaves the text of the selected cell alone: it + * opens below the cell, and what is typed only searches the entries, anywhere in their text and ignoring the case. An + * action is only executed once the user confirmed it. The entries don't depend on the pattern, so they are filtered + * here instead of being loaded again from the backend. + */ +class ContextActionsMenu( + editor: FrontendEditorComponent, + anchor: LayoutableCell, + initialEntries: List, +) : ActionMenu(editor, anchor, initialEntries) { + override val patternClass: String get() = "context-actions-pattern" + override val selectedEntryClass: String get() = "selected" + + override fun matches(entry: CompletionMenuEntryData): Boolean = entry.matches(patternEditor.pattern, ignoreCase = true) + + override suspend fun updateEntries() { + applyFilter() + editor.invalidateActionMenu() + } + + override fun getPosition(anchorBounds: Bounds): Position = Position(anchorBounds.x, anchorBounds.y + anchorBounds.height) + + override fun produceHtml(consumer: TagConsumer) { + consumer.div("context-actions-menu") { + div("context-actions-title") { + +"Context Actions" + } + if (patternEditor.pattern.isNotEmpty()) { + div("context-actions-search") { + produceChild(patternEditor) + } + } + div("context-actions-entries") { + filteredEntries.forEachIndexed { index, entry -> + div(if (index == selectedIndex) "context-action $selectedEntryClass" else "context-action") { + div("context-action-text") { + +entry.matchingText + } + div("context-action-description") { + +entry.description + } + } + } + if (filteredEntries.isEmpty()) { + div("context-actions-empty") { + +(if (allEntries.isEmpty()) "No actions available" else "No matches found") + } + } + } + } + } +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt index 1ef3e91a..b2fe90ac 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt @@ -118,6 +118,15 @@ class EditorEngine( */ fun getNodeAttributeLayers(node: INode): List = node.getAttributes().filter { isRenderedAsLayer(it) } + /** + * The position in the `smodelAttribute` role of a new attribute of [node] that goes inside all its existing layers, + * directly around the node's own cell. + */ + fun getIndexInsideNodeAttributes(node: INode): Int { + val innermostLayer = getNodeAttributeLayers(node).lastOrNull() ?: return 0 + return node.getAttributes().indexOfFirst { it.reference == innermostLayer.reference } + 1 + } + private fun isRenderedAsLayer(attribute: INode): Boolean { val concept = attribute.concept ?: return false if (!concept.isNodeAttribute()) return false @@ -131,7 +140,7 @@ class EditorEngine( /** * The notations of node attributes that can be added in the editor, by typing the text of their notation next to - * the node they wrap. Only notations that render the attributed node qualify. + * the node they wrap or with a context action. Only notations that render the attributed node qualify. */ fun getNodeAttributeTemplates(): List = getAllConceptEditors() @@ -281,6 +290,7 @@ class EditorEngine( } data.properties[CommonCellProperties.selectable] = true data.properties[CellActionProperties.delete] = DeleteNodeCellAction(node) + data.properties[CellActionProperties.contextActions] = NodeContextActions(node) return data } catch (ex: Exception) { LOG.error(ex) { "Failed to create cell for $node" } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt index 5f17247d..24287cb9 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt @@ -18,8 +18,10 @@ import kotlinx.html.div import org.modelix.editor.text.backend.AtomicReference import org.modelix.editor.text.frontend.FrontendCellTree import org.modelix.editor.text.frontend.getSelectableText +import org.modelix.editor.text.shared.ActionMenuTrigger import org.modelix.editor.text.shared.CompletionMenuEntryData import org.modelix.editor.text.shared.CompletionMenuTrigger +import org.modelix.editor.text.shared.ContextActionsMenuTrigger import org.modelix.editor.text.shared.EditorId import org.modelix.editor.text.shared.EditorUpdateData import org.modelix.editor.text.shared.ServiceCallResult @@ -151,8 +153,8 @@ open class FrontendEditorComponent( LOG.trace { "enqueueUpdate $updateData" } runSynchronized(state) { state.updateCellTree(updateData.cellTreeChanges) - if (updateData.completionMenuTrigger != null) { - state.triggerCodeCompletionMenu(updateData.completionMenuTrigger) + if (updateData.menuTrigger != null) { + state.triggerActionMenu(updateData.menuTrigger) } if (updateData.completionEntries != null) { state.updateCompletionEntries(updateData.completionEntries) @@ -192,7 +194,7 @@ open class FrontendEditorComponent( fun doChangeSelection(newSelection: Selection) { state.setSelection(newSelection) - state.closeCompletionMenu() + state.closeActionMenu() } fun changeSelectionLater(newSelection: Selection): UIEventDispatcher.Event = @@ -212,9 +214,11 @@ open class FrontendEditorComponent( state.showCodeCompletionMenu(anchor, position, entries, pattern, caretPosition) } - fun closeCodeCompletionMenu() = + fun getActionMenu(): ActionMenu? = state.getActionMenu() + + fun closeActionMenu() = eventQueue.invokeLater { - state.closeCompletionMenu() + state.closeActionMenu() } open fun dispose() { @@ -246,7 +250,7 @@ open class FrontendEditorComponent( // state.reset() return true } - for (handler in listOfNotNull(state.getCodeCompletionMenu(), state.getSelection())) { + for (handler in listOfNotNull(state.getActionMenu(), state.getSelection())) { if (handler.processKeyDown(event)) return true } return false @@ -404,7 +408,7 @@ open class FrontendEditorComponent( produceChild(state.getSelectionView()) } div("popup-layer relative-layer") { - produceChild(state.getCodeCompletionMenu()) + produceChild(state.getActionMenu()) } } } @@ -416,10 +420,10 @@ open class FrontendEditorComponent( serviceCall { this.updateCodeCompletionActions(editorId, anchorCell.getId(), pattern) } - state.getCodeCompletionMenu() // flus pending updates of completion entries + state.getActionMenu() // flus pending updates of completion entries } - fun invalidateCompletionMenu() = state.invalidateCompletionMenu() + fun invalidateActionMenu() = state.invalidateActionMenu() fun scrollIntoViewLater(element: () -> IVirtualDom.HTMLElement?) { eventQueue.invokeLater { element()?.let { scrollIntoView(it) } } @@ -603,20 +607,29 @@ class FrontendEditorComponentState( }.also { it.addDependency(cellTree) } - private val codeCompletionMenu = - Substate(CompletionMenuState()) { oldState -> + private val actionMenu = + Substate(ActionMenuState()) { oldState -> for (trigger in oldState.pendingTriggers.asReversed()) { val anchor = getCell(trigger.anchor).layoutable() ?: continue + val entries = oldState.pendingEntriesUpdate.orEmpty() return@Substate oldState.copy( menu = - CodeCompletionMenu( - editorComponent, - anchor, - trigger.completionPosition, - oldState.pendingEntriesUpdate.orEmpty(), - trigger.pattern, - trigger.caretPosition, - ), + when (trigger) { + is CompletionMenuTrigger -> { + CodeCompletionMenu( + editorComponent, + anchor, + trigger.completionPosition, + entries, + trigger.pattern, + trigger.caretPosition, + ) + } + + is ContextActionsMenuTrigger -> { + ContextActionsMenu(editorComponent, anchor, entries) + } + }, pendingTriggers = emptyList(), pendingEntriesUpdate = null ) @@ -671,7 +684,7 @@ class FrontendEditorComponentState( newHighlightedCell?.addClass("highlighted-cell") selectionView.getValidState()?.update() - codeCompletionMenu.getValidState().menu?.let { CodeCompletionMenuUI(it, editorComponent).updateBounds() } + actionMenu.getValidState().menu?.updateBounds() oldState.copy( highlightedLine = newHighlightedLine, @@ -685,7 +698,7 @@ class FrontendEditorComponentState( it.addDependency(layoutablesIndex) it.addDependency(selection) it.addDependency(selectionView) - it.addDependency(codeCompletionMenu) + it.addDependency(actionMenu) } @JvmSynchronized @@ -703,8 +716,8 @@ class FrontendEditorComponentState( } @JvmSynchronized - fun invalidateCompletionMenu() { - codeCompletionMenu.invalidate() + fun invalidateActionMenu() { + actionMenu.invalidate() } @JvmSynchronized @@ -727,7 +740,7 @@ class FrontendEditorComponentState( fun resetCellTree() { cellTree.setState(CellTreeState(FrontendCellTree(editorComponent), emptyList())) selection.setState(SelectionState()) - codeCompletionMenu.setState(CompletionMenuState()) + actionMenu.setState(ActionMenuState()) } @JvmSynchronized @@ -739,7 +752,7 @@ class FrontendEditorComponentState( } @JvmSynchronized - fun getCodeCompletionMenu() = codeCompletionMenu.getValidState().menu + fun getActionMenu() = actionMenu.getValidState().menu @JvmSynchronized fun getSelectionView() = selectionView.getValidState() @@ -762,8 +775,8 @@ class FrontendEditorComponentState( fun getSelection() = selection.getValidState().selection @JvmSynchronized - fun closeCompletionMenu() { - codeCompletionMenu.changeState { CompletionMenuState() } + fun closeActionMenu() { + actionMenu.changeState { ActionMenuState() } } @JvmSynchronized @@ -774,21 +787,21 @@ class FrontendEditorComponentState( pattern: String = "", caretPosition: Int? = null, ) { - codeCompletionMenu.setState( - CompletionMenuState( + actionMenu.setState( + ActionMenuState( menu = CodeCompletionMenu(editorComponent, anchor, position, entries, pattern, caretPosition) ) ) } @JvmSynchronized - fun triggerCodeCompletionMenu(trigger: CompletionMenuTrigger) { - codeCompletionMenu.changeState { it.copy(pendingTriggers = it.pendingTriggers + trigger) } + fun triggerActionMenu(trigger: ActionMenuTrigger) { + actionMenu.changeState { it.copy(pendingTriggers = it.pendingTriggers + trigger) } } @JvmSynchronized fun updateCompletionEntries(newEntries: List) { - codeCompletionMenu.changeState { it.copy(pendingEntriesUpdate = newEntries) } + actionMenu.changeState { it.copy(pendingEntriesUpdate = newEntries) } } data class CellTreeState( @@ -807,9 +820,9 @@ class FrontendEditorComponentState( val pendingSelectionUpdates: List = emptyList(), ) - data class CompletionMenuState( - val menu: CodeCompletionMenu? = null, - val pendingTriggers: List = emptyList(), + data class ActionMenuState( + val menu: ActionMenu? = null, + val pendingTriggers: List = emptyList(), val pendingEntriesUpdate: List? = null, ) } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt index a18e7e11..fa038276 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt @@ -59,6 +59,7 @@ object CellActionProperties { val delete = BackendCellPropertyKey("delete", null) val show = BackendCellPropertyKey("show", null) val replaceText = BackendCellPropertyKey("replaceText", null) + val contextActions = BackendCellPropertyKey("contextActions", null) } class SideTransformNode( @@ -87,8 +88,7 @@ class SideTransformNode( * Node attributes added on the border of the node's own cell go inside all existing ones. */ private fun getAttributeActions(engine: EditorEngine): List { - val innermostLayer = engine.getNodeAttributeLayers(node).lastOrNull() - val index = innermostLayer?.let { layer -> node.getAttributes().indexOfFirst { it.reference == layer.reference } + 1 } ?: 0 + val index = engine.getIndexInsideNodeAttributes(node) return engine.getNodeAttributeTemplates().flatMap { it.getAttributeSideTransformActions(before, node, index) } } } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/AttributedCellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/AttributedCellTemplate.kt index cef260ac..dcbc96fd 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/AttributedCellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/AttributedCellTemplate.kt @@ -6,6 +6,7 @@ import org.modelix.editor.CellCreationContext import org.modelix.editor.CellSpec import org.modelix.editor.CellSpecBase import org.modelix.editor.ChildSpecReference +import org.modelix.editor.CodeCompletionActionWithDescription import org.modelix.editor.IActionOrProvider import org.modelix.editor.ICodeCompletionAction import org.modelix.editor.ICompletionTokenOrList @@ -21,6 +22,7 @@ import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.model.api.BuiltinLanguages import org.modelix.model.api.IConcept import org.modelix.model.api.INode +import org.modelix.model.api.conceptAlias import org.modelix.model.api.upcast import org.modelix.parser.ISymbol import org.modelix.parser.SubConceptsSymbol @@ -106,6 +108,24 @@ fun NotationRootCellTemplate.getAttributeSideTransformActions( return listOf(AddNodeAttributeAction(token.text, concept, attributedNode, index)) } +/** + * Adding a node attribute with a context action. Unlike [getAttributeSideTransformActions] this doesn't depend on the + * notation having text on the side of the caret, so it also covers notations with no constant at all. + */ +fun NotationRootCellTemplate.getAddAttributeContextAction( + attributedNode: INode, + index: Int, +): ICodeCompletionAction? { + val attributedCell = descendants(includeSelf = true).filterIsInstance().firstOrNull() ?: return null + if (!attributedCell.isApplicableTo(attributedNode)) return null + // An alias can be a symbol (`...`), which reads as nothing in a menu entry. + val attributeName = concept.conceptAlias()?.takeIf { alias -> alias.any { it.isLetterOrDigit() } } ?: concept.getShortName() + return CodeCompletionActionWithDescription( + AddNodeAttributeAction("Add $attributeName", concept, attributedNode, index), + "Attribute of ${attributedNode.concept?.getShortName()}", + ) +} + /** * Whether the notation writes something on that side of the `attributed` cell. If not, the border of the attribute's * cell on that side coincides with the border of the layer inside it, and only the inner one offers actions. diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt index 662434e6..22142c2f 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt @@ -27,6 +27,7 @@ import org.modelix.editor.getActionsAfter import org.modelix.editor.getActionsBefore import org.modelix.editor.getBordersBetween import org.modelix.editor.getCompletionPattern +import org.modelix.editor.getContextActions import org.modelix.editor.getSubstituteActions import org.modelix.editor.isTabTarget import org.modelix.editor.isVisible @@ -39,6 +40,7 @@ import org.modelix.editor.text.frontend.getSelectableText import org.modelix.editor.text.frontend.type import org.modelix.editor.text.shared.CompletionMenuEntryData import org.modelix.editor.text.shared.CompletionMenuTrigger +import org.modelix.editor.text.shared.ContextActionsMenuTrigger import org.modelix.editor.text.shared.EditorId import org.modelix.editor.text.shared.EditorUpdateData import org.modelix.editor.text.shared.ServiceCallResult @@ -242,21 +244,14 @@ class TextEditorServiceImpl( return@runWithCell matchingActions.first().executeAndUpdateSelection(updateChannel) } return@runWithCell updateChannel.createUpdate().copy( - completionMenuTrigger = + menuTrigger = CompletionMenuTrigger( anchor = cell.getId(), completionPosition = completionPosition, pattern = replacement, caretPosition = replacement.length ), - completionEntries = - updateChannel.editor.loadCompletionEntries(providers, replacement).mapIndexed { index, entry -> - CompletionMenuEntryData( - id = index, - matchingText = entry.getMatchingText(), - description = entry.getDescription() - ) - } + completionEntries = updateChannel.editor.loadCompletionEntries(providers, replacement).toEntryData() ) } } @@ -274,21 +269,26 @@ class TextEditorServiceImpl( val pattern = fullPattern.take(caretPosition) val providers = cell.getSubstituteActions().toList() updateChannel.createUpdate().copy( - completionMenuTrigger = + menuTrigger = CompletionMenuTrigger( anchor = cell.getId(), completionPosition = CompletionPosition.CENTER, pattern = fullPattern, caretPosition = caretPosition ), - completionEntries = - updateChannel.editor.loadCompletionEntries(providers, pattern).mapIndexed { index, entry -> - CompletionMenuEntryData( - id = index, - matchingText = entry.getMatchingText(), - description = entry.getDescription() - ) - } + completionEntries = updateChannel.editor.loadCompletionEntries(providers, pattern).toEntryData() + ) + } + + override suspend fun triggerContextActions( + editorId: Int, + cellId: CellInstanceId, + anchorCellId: CellInstanceId, + ): EditorUpdateData = + runWithCell(editorId, cellId) { updateChannel, cell -> + updateChannel.createUpdate().copy( + menuTrigger = ContextActionsMenuTrigger(anchorCellId), + completionEntries = updateChannel.editor.loadCompletionEntries(listOfNotNull(cell.getContextActions()), "").toEntryData() ) } @@ -303,16 +303,7 @@ class TextEditorServiceImpl( val entries = updateChannel.editor.completionMenu?.updateActions(pattern) ?: updateChannel.editor.loadCompletionEntries(cell.getSubstituteActions().toList(), pattern) - updateChannel.createUpdate().copy( - completionEntries = - entries.mapIndexed { index, entry -> - CompletionMenuEntryData( - id = index, - matchingText = entry.getMatchingText(), - description = entry.getDescription() - ) - } - ) + updateChannel.createUpdate().copy(completionEntries = entries.toEntryData()) } override suspend fun hasCodeCompletionActions( @@ -420,6 +411,15 @@ class TextEditorServiceImpl( override suspend fun flush(editorId: Int): EditorUpdateData = runWithEditor(editorId) { updateChannel, editor -> updateChannel.createUpdate() } + private fun List.toEntryData(): List = + mapIndexed { index, entry -> + CompletionMenuEntryData( + id = index, + matchingText = entry.getMatchingText(), + description = entry.getDescription() + ) + } + private fun ICellAction.executeAndUpdateSelection(channel: EditorUpdateChannel): EditorUpdateData = channel.createSelection(execute(channel.editor)) diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt index 133b8923..1c6698a0 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt @@ -55,6 +55,16 @@ interface TextEditorService { caretPosition: Int, ): EditorUpdateData + /** + * Opens the context actions menu with the actions of [cellId]. [anchorCellId] is the text cell the menu is shown + * at. They differ if a whole node is selected, which has no text cell of its own. + */ + suspend fun triggerContextActions( + editorId: Int, + cellId: CellInstanceId, + anchorCellId: CellInstanceId, + ): EditorUpdateData + suspend fun updateCodeCompletionActions( editorId: Int, cellId: CellInstanceId, @@ -136,6 +146,14 @@ class NullTextEditorService : TextEditorService { TODO("Not yet implemented") } + override suspend fun triggerContextActions( + editorId: Int, + cellId: CellInstanceId, + anchorCellId: CellInstanceId, + ): EditorUpdateData { + TODO("Not yet implemented") + } + override suspend fun updateCodeCompletionActions( editorId: Int, cellId: CellInstanceId, @@ -187,17 +205,30 @@ data class ServiceCallResult( data class EditorUpdateData( val cellTreeChanges: List = emptyList(), val selectionChange: ICaretPositionPolicy? = null, - val completionMenuTrigger: CompletionMenuTrigger? = null, + val menuTrigger: ActionMenuTrigger? = null, val completionEntries: List? = null, ) +/** + * Opens an [org.modelix.editor.ActionMenu] at the cell [anchor]. + */ +@Serializable +sealed interface ActionMenuTrigger { + val anchor: CellInstanceId +} + @Serializable data class CompletionMenuTrigger( - val anchor: CellInstanceId, + override val anchor: CellInstanceId, val completionPosition: CompletionPosition = CompletionPosition.CENTER, val pattern: String = "", val caretPosition: Int = 0, -) +) : ActionMenuTrigger + +@Serializable +data class ContextActionsMenuTrigger( + override val anchor: CellInstanceId, +) : ActionMenuTrigger @Serializable data class CompletionMenuEntryData( @@ -205,9 +236,12 @@ data class CompletionMenuEntryData( val matchingText: String, val description: String, ) { - fun matches(pattern: String): Boolean { + fun matches( + pattern: String, + ignoreCase: Boolean = false, + ): Boolean { // TODO more sophisticated pattern matching - return matchingText.contains(pattern) + return matchingText.contains(pattern, ignoreCase) } fun matchesExactly(pattern: String): Boolean = matchingText == pattern diff --git a/react-ssr-client/src/components/ModelixTextEditor.css b/react-ssr-client/src/components/ModelixTextEditor.css index 3d0bedec..03497927 100644 --- a/react-ssr-client/src/components/ModelixTextEditor.css +++ b/react-ssr-client/src/components/ModelixTextEditor.css @@ -148,6 +148,68 @@ padding: 3px 6px; } +.modelix-text-editor .context-actions-menu { + position: absolute; + z-index: 1; + min-width: 200px; + white-space: nowrap; + font-family: sans-serif; + font-size: 10pt; + color: black; + background-color: white; + border: 1px solid #acacac; + border-radius: 4px; + overflow: hidden; + box-shadow: 2px 2px 12px 0 rgba(0, 0, 0, 0.35); +} + +.modelix-text-editor .context-actions-menu .context-actions-title { + padding: 2px 8px; + font-size: 9pt; + color: #555; + background-color: #ededed; + border-bottom: 1px solid #d0d0d0; +} + +.modelix-text-editor .context-actions-menu .context-actions-search { + padding: 2px 8px; + border-bottom: 1px solid #d0d0d0; +} + +.modelix-text-editor .context-actions-menu .context-actions-pattern { + display: inline-block; +} + +.modelix-text-editor .context-actions-menu .context-actions-entries { + max-height: 200px; + overflow-y: auto; +} + +.modelix-text-editor .context-actions-menu .context-action { + display: flex; + justify-content: space-between; + gap: 24px; + padding: 3px 8px; +} + +.modelix-text-editor .context-actions-menu .context-action.selected { + background-color: #1055d1; + color: white; +} + +.modelix-text-editor .context-actions-menu .context-action-description { + color: #808080; +} + +.modelix-text-editor .context-actions-menu .context-action.selected .context-action-description { + color: #d5e0f5; +} + +.modelix-text-editor .context-actions-menu .context-actions-empty { + padding: 3px 8px; + color: #808080; +} + /* Cmd/Ctrl+click navigates to the target of a reference. While the modifier is held, the reference cell under the mouse is marked as clickable, like MPS does. The class on the container is set by the client that dispatches the keyboard events. */ From fa2f74d07e4a81b2fba33fb809240ab0a0f09ab5 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 13 Nov 2026 12:38:37 +0100 Subject: [PATCH 12/23] feat(projectional-editor): MPS intentions in the context actions menu The context actions menu (Alt+Enter) now also offers the intentions of the MPS languages, the same ones the intentions menu of MPS shows for the node. They are collected by the IntentionsManager of MPS with a headless editor on the root of the node, which an intention also gets when it is executed, and what it selects there is selected in the web editor afterwards. Context actions come from the new ContextActionsAspect extension point. A headless MPS editor can only be created on the UI thread, so the actions are collected in the ContextActionsAspect.loadingContext, which the MPS integration sets to the UI thread. The menu groups its entries like the intentions menu of MPS-extensions: the actions without a group first, then a heading per group. The section of an intention is taken from its description the same way. The actions for adding node attributes have a group of their own. Instead of a description, an entry shows an icon, which for an intention is the one MPS shows for its kind. Co-Authored-By: Claude Opus 5.5 --- .../editor/kernelf/NodeAttributeTest.kt | 125 ++++++++++++ .../src/jsMain/resources/editor.css | 48 ++++- .../editor/ssr/mps/BaseLanguageTests.kt | 80 ++++++++ .../editor/ssr/mps/EditorIntegrationForMPS.kt | 8 + .../modelix/editor/ssr/mps/MPSIntentions.kt | 180 ++++++++++++++++++ .../editor/CodeCompletionActionWrapper.kt | 19 ++ .../org/modelix/editor/CodeCompletionMenu.kt | 13 ++ .../org/modelix/editor/ContextActions.kt | 66 ++++++- .../org/modelix/editor/ContextActionsMenu.kt | 15 +- .../text/backend/BackendEditorComponent.kt | 12 +- .../text/backend/TextEditorServiceImpl.kt | 15 +- .../editor/text/shared/TextEditorService.kt | 24 +++ .../src/components/ModelixTextEditor.css | 48 ++++- 13 files changed, 627 insertions(+), 26 deletions(-) create mode 100644 projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSIntentions.kt diff --git a/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt b/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt index bf330e31..ad4a3440 100644 --- a/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt +++ b/kernelf-editor/src/commonTest/kotlin/org/modelix/editor/kernelf/NodeAttributeTest.kt @@ -1,6 +1,7 @@ package org.modelix.editor.kernelf import kotlinx.coroutines.test.runTest +import kotlinx.html.stream.createHTML import org.iets3.core.expr.adt.C_NameAnnotation import org.iets3.core.expr.base.C_ParensExpression import org.iets3.core.expr.doc.C_BookmarkAnnotation @@ -11,20 +12,30 @@ import org.iets3.core.expr.tests.C_OldNodeAnnotation import org.modelix.editor.CaretSelection import org.modelix.editor.Cell import org.modelix.editor.CellSelection +import org.modelix.editor.CodeCompletionParameters +import org.modelix.editor.ContextActionsAspect import org.modelix.editor.ContextActionsMenu import org.modelix.editor.EditorAspect import org.modelix.editor.EditorEngine import org.modelix.editor.FrontendEditorComponent +import org.modelix.editor.IActionOrProvider +import org.modelix.editor.ICaretPositionPolicy +import org.modelix.editor.ICodeCompletionAction +import org.modelix.editor.IContextActionsProvider import org.modelix.editor.JSKeyboardEvent import org.modelix.editor.JSKeyboardEventType import org.modelix.editor.KeyLocation import org.modelix.editor.KnownKeys import org.modelix.editor.Modifiers import org.modelix.editor.NodeCellReference +import org.modelix.editor.NodeContextActions import org.modelix.editor.descendants import org.modelix.editor.layoutable +import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.editor.text.backend.TextEditorServiceImpl import org.modelix.editor.text.frontend.getVisibleText +import org.modelix.editor.text.shared.ActionIcon +import org.modelix.editor.toHtml import org.modelix.incremental.IncrementalEngine import org.modelix.kernelf.KernelfLanguages import org.modelix.metamodel.untyped @@ -348,6 +359,100 @@ class NodeAttributeTest { assertEquals(listOf("BookmarkAnnotation", "DotDotDot"), attributeConcepts()) } + @Test + fun theActionsForNodeAttributesAreListedInTheirOwnGroup() = + runAttributeTest { + openContextActions(cellWithText("200")) + + assertEquals(listOf(NODE_ATTRIBUTES, NODE_ATTRIBUTES, NODE_ATTRIBUTES), contextActionGroups()) + assertEquals(List(3) { ActionIcon.NODE_ATTRIBUTE }, contextActionIcons()) + assertEquals(listOf(NODE_ATTRIBUTES), renderedGroupHeadings()) + } + + @Test + fun aContextActionIsShownWithItsIconInsteadOfItsDescription() = + runAttributeTest { + openContextActions(cellWithText("200")) + typeIntoMenu("bookmark") + + val html = renderedMenu() + assertTrue(html.contains("""
"""), html) + assertTrue(!html.contains("context-action-description"), html) + assertTrue(!html.contains("Attribute of"), html) + } + + @Test + fun contextActionsOfOtherProvidersAreOfferedWithTheirGroups() = + runAttributeTest { + val executedOn = mutableListOf() + withContextActionsProvider({ node -> + listOf( + TestContextAction("Zzz without group", null) { executedOn.add(node) }, + TestContextAction("Refactor it", "Refactoring") { executedOn.add(node) }, + ) + }) { + openContextActions(cellWithText("200")) + + // Without a group first, then the groups by name, like the sections of the MPS intentions menu. + assertEquals(listOf("Zzz without group", ADD_BOOKMARK, ADD_TODO, ADD_OLD_NODE, "Refactor it"), contextActions()) + assertEquals(listOf(null, NODE_ATTRIBUTES, NODE_ATTRIBUTES, NODE_ATTRIBUTES, "Refactoring"), contextActionGroups()) + assertEquals(listOf(NODE_ATTRIBUTES, "Refactoring"), renderedGroupHeadings()) + + typeIntoMenu("refactor") + assertEquals(listOf("Refactoring"), renderedGroupHeadings()) + pressKey(KnownKeys.Enter) + + assertEquals(listOf(literal.reference), executedOn.map { it.reference }) + assertNull(editor.getActionMenu()) + } + } + + @Test + fun aFailingContextActionsProviderDoesNotHideTheOtherActions() = + runAttributeTest { + withContextActionsProvider({ error("provider failed") }) { + openContextActions(cellWithText("200")) + + assertEquals(listOf(ADD_BOOKMARK, ADD_TODO, ADD_OLD_NODE), contextActions()) + } + } + + private suspend fun withContextActionsProvider( + actions: (INode) -> List, + body: suspend () -> Unit, + ) { + val provider = + object : IContextActionsProvider { + override fun getContextActions( + node: INode, + parameters: CodeCompletionParameters, + ): List = actions(node) + } + ContextActionsAspect.providers.add(provider) + try { + body() + } finally { + ContextActionsAspect.providers.remove(provider) + } + } + + private class TestContextAction( + private val text: String, + private val group: String?, + private val onExecute: () -> Unit, + ) : ICodeCompletionAction { + override fun getMatchingText(): String = text + + override fun getDescription(): String = "" + + override fun getGroup(): String? = group + + override fun execute(editor: BackendEditorComponent): ICaretPositionPolicy? { + onExecute() + return null + } + } + private suspend fun selectText(cell: Cell) { editor.flushAndUpdateSelection { CaretSelection(editor, cell.layoutable()!!, 0) } editor.flush() @@ -391,6 +496,25 @@ class NodeAttributeTest { .getVisibleEntries() .map { it.matchingText } + private fun contextActionGroups(): List = + assertIs(editor.getActionMenu(), "The context actions menu is not open") + .getVisibleEntries() + .map { it.group } + + private fun contextActionIcons(): List = + assertIs(editor.getActionMenu(), "The context actions menu is not open") + .getVisibleEntries() + .map { it.icon } + + private fun renderedMenu(): String = + assertIs(editor.getActionMenu(), "The context actions menu is not open") + .toHtml(createHTML(prettyPrint = false)) + + private fun renderedGroupHeadings(): List { + val html = renderedMenu() + return Regex("""
([^<]*)
""").findAll(html).map { it.groupValues[1] }.toList() + } + private suspend fun addAttribute( concept: IConcept, init: (INode) -> Unit = {}, @@ -485,5 +609,6 @@ class NodeAttributeTest { const val ADD_BOOKMARK = "Add BookmarkAnnotation" const val ADD_TODO = "Add DotDotDot" const val ADD_OLD_NODE = "Add OldNodeAnnotation" + const val NODE_ATTRIBUTES = NodeContextActions.NODE_ATTRIBUTES_GROUP } } diff --git a/projectional-editor-ssr-client/src/jsMain/resources/editor.css b/projectional-editor-ssr-client/src/jsMain/resources/editor.css index a083f452..ea95df54 100644 --- a/projectional-editor-ssr-client/src/jsMain/resources/editor.css +++ b/projectional-editor-ssr-client/src/jsMain/resources/editor.css @@ -179,24 +179,54 @@ overflow-y: auto; } +.editor .context-actions-menu .context-actions-group { + padding: 4px 8px 2px; + font-size: 8pt; + font-weight: bold; + color: #808080; +} + +.editor .context-actions-menu .context-actions-group:not(:first-child) { + border-top: 1px solid #e0e0e0; +} + .editor .context-actions-menu .context-action { display: flex; - justify-content: space-between; - gap: 24px; + align-items: center; + gap: 6px; padding: 3px 8px; } -.editor .context-actions-menu .context-action.selected { - background-color: #1055d1; - color: white; +/* The icons of the IntelliJ Platform (new UI) that the intentions menu of MPS shows, Apache 2.0 licensed: + expui/codeInsight/intentionBulb.svg, expui/codeInsight/quickfixBulb.svg, expui/nodes/annotation.svg and the + expUi/actions/migrationBulb.svg of MPS. */ +.editor .context-actions-menu .context-action-icon { + flex: none; + width: 16px; + height: 16px; + background-repeat: no-repeat; + background-size: 16px 16px; } -.editor .context-actions-menu .context-action-description { - color: #808080; +.editor .context-actions-menu .context-action-icon.icon-intention { + background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='5.70142' y='12' width='4.6' height='1' fill='%236C707E'/%3E%3Cpath d='M6 14H10C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14Z' fill='%236C707E'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M10.8704 9.14748C12.0417 8.27221 12.8 6.87465 12.8 5.3C12.8 2.64903 10.6509 0.5 7.99995 0.5C5.34898 0.5 3.19995 2.64903 3.19995 5.3C3.19995 6.87464 3.95817 8.27218 5.12943 9.14746L5.49994 11H10.4999L10.8704 9.14748Z' fill='%23FFAF0F'/%3E%3C/svg%3E"); } -.editor .context-actions-menu .context-action.selected .context-action-description { - color: #d5e0f5; +.editor .context-actions-menu .context-action-icon.icon-error-intention { + background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='5.70142' y='12' width='4.6' height='1' fill='%236C707E'/%3E%3Cpath d='M6 14H10C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14Z' fill='%236C707E'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M10.8704 9.14748C12.0417 8.27221 12.8 6.87465 12.8 5.3C12.8 2.64903 10.6509 0.5 7.99995 0.5C5.34898 0.5 3.19995 2.64903 3.19995 5.3C3.19995 6.87464 3.95817 8.27218 5.12943 9.14746L5.49994 11H10.4999L10.8704 9.14748ZM8 2.00002C8.49706 2.00002 8.9 2.40297 8.9 2.90002V5.40002C8.9 5.89708 8.49706 6.30002 8 6.30002C7.50294 6.30002 7.1 5.89708 7.1 5.40002L7.1 2.90002C7.1 2.40297 7.50294 2.00002 8 2.00002ZM7.9999 9.2C8.60742 9.2 9.0999 8.70751 9.0999 8.1C9.0999 7.49249 8.60742 7 7.9999 7C7.39239 7 6.8999 7.49249 6.8999 8.1C6.8999 8.70751 7.39239 9.2 7.9999 9.2Z' fill='%23E55765'/%3E%3C/svg%3E"); +} + +.editor .context-actions-menu .context-action-icon.icon-migration { + background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M6 14H10C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14Z' fill='%236C707E'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M12.1464 8.14645C12.3417 7.95118 12.6583 7.95118 12.8536 8.14645L15.8536 11.1464C16.0488 11.3417 16.0488 11.6583 15.8536 11.8536C15.6583 12.0488 15.3417 12.0488 15.1464 11.8536L13 9.70711V15.5C13 15.7761 12.7761 16 12.5 16C12.2239 16 12 15.7761 12 15.5V9.70711L9.85355 11.8536C9.65829 12.0488 9.34171 12.0488 9.14645 11.8536C8.95118 11.6583 8.95118 11.3417 9.14645 11.1464L12.1464 8.14645Z' fill='%236C707E'/%3E%3Cpath d='M8.08542 12H5.70117V13H9.5C9.11612 13 8.73223 12.8536 8.43934 12.5607C8.27559 12.3969 8.15762 12.2047 8.08542 12Z' fill='%236C707E'/%3E%3Cpath d='M8.08542 11C8.15762 10.7953 8.2756 10.6031 8.43934 10.4393L11.4393 7.43934C11.7298 7.14888 12.1098 7.00244 12.4904 7.00003C12.6906 6.47159 12.8002 5.89859 12.8002 5.3C12.8002 2.64903 10.6512 0.5 8.0002 0.5C5.34923 0.5 3.2002 2.64903 3.2002 5.3C3.2002 6.87464 3.95842 8.27218 5.12968 9.14746L5.50018 11H8.08542Z' fill='%2355A76A'/%3E%3C/svg%3E"); +} + +.editor .context-actions-menu .context-action-icon.icon-node-attribute { + background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='8' cy='8' r='7' fill='%23F2FCF3'/%3E%3Cpath d='M9.72989 5.38506V6.35862H9.70012C9.35494 5.69 8.71609 5.3046 7.87126 5.3046C6.38276 5.3046 5.26437 6.47931 5.26437 8.04023C5.26437 9.60115 6.38276 10.7759 7.87126 10.7759C8.81103 10.7759 9.58828 10.339 10.0026 9.65425C10.442 10.3357 11.2602 10.7517 12.2885 10.7517C13.9218 10.7517 15 9.60115 15 7.91954C15 4.11379 11.854 1 8 1C4.14598 1 1 4.18621 1 8.08046C1 11.8862 4.14598 15 8 15C9.85057 15 11.5161 14.2356 12.4333 13.4069L11.7092 12.6103C10.8966 13.3345 9.5931 13.9943 8 13.9943C4.70115 13.9943 2.00575 11.331 2.00575 8.08046C2.00575 4.74138 4.70115 2.00575 8 2.00575C11.2989 2.00575 13.9943 4.66897 13.9943 7.91954C13.9943 9.02989 13.3264 9.78621 12.2885 9.78621C11.3471 9.78621 10.6552 9.1908 10.6552 8.32184V5.38506H9.72989ZM7.95977 9.8908C6.99425 9.8908 6.27011 9.09425 6.27011 8.04023C6.27011 6.98621 6.99425 6.18966 7.95977 6.18966C8.92529 6.18966 9.64943 6.98621 9.64943 8.04023C9.64943 9.09425 8.92529 9.8908 7.95977 9.8908Z' fill='%23208A3C'/%3E%3C/svg%3E"); +} + +.editor .context-actions-menu .context-action.selected { + background-color: #1055d1; + color: white; } .editor .context-actions-menu .context-actions-empty { diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index cd47fdaf..b3b6cf7c 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -1,5 +1,6 @@ package org.modelix.editor.ssr.mps +import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.debug import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -10,15 +11,20 @@ import org.modelix.editor.CaretSelection import org.modelix.editor.ChildNodeCellReference import org.modelix.editor.CodeCompletionParameters import org.modelix.editor.CommonCellProperties +import org.modelix.editor.ContextActionsAspect +import org.modelix.editor.ContextActionsMenu import org.modelix.editor.EditorEngine import org.modelix.editor.FrontendEditorComponent +import org.modelix.editor.IActionOrProvider import org.modelix.editor.ICodeCompletionAction import org.modelix.editor.ICodeCompletionActionProvider +import org.modelix.editor.IContextActionsProvider import org.modelix.editor.JSKeyboardEvent import org.modelix.editor.JSKeyboardEventType import org.modelix.editor.KnownKeys import org.modelix.editor.Modifiers import org.modelix.editor.NodeCellReference +import org.modelix.editor.NodeContextActions import org.modelix.editor.ReferencedNodeCellReference import org.modelix.editor.ancestors import org.modelix.editor.applyShadowing @@ -31,6 +37,8 @@ import org.modelix.editor.lastLeaf import org.modelix.editor.layoutable import org.modelix.editor.text.backend.TextEditorServiceImpl import org.modelix.editor.text.frontend.getVisibleText +import org.modelix.editor.text.shared.ActionIcon +import org.modelix.editor.text.shared.CompletionMenuEntryData import org.modelix.editor.text.shared.celltree.ICellTree import org.modelix.incremental.IncrementalEngine import org.modelix.model.api.ConceptReference @@ -982,6 +990,77 @@ class BaseLanguageTests : TestBase("SimpleProject") { """) } + private suspend fun openContextActions(cellText: String) { + placeCaretIntoCellWithText(cellText, 0) + editor.processKeyEvent( + JSKeyboardEvent(JSKeyboardEventType.KEYDOWN, null, KnownKeys.Enter, KnownKeys.Enter.name, Modifiers.ALT), + ) + editor.flush() + } + + private fun contextActions(): List = + assertInstanceOf(editor.getActionMenu(), ContextActionsMenu::class.java).getVisibleEntries() + + fun `test the context actions menu offers the intentions of the MPS languages`() = + kotlinx.coroutines.test.runTest { + openContextActions("method1") + val entries = contextActions() + + val makeFinal = entries.single { it.matchingText == "Make 'method1' Final" } + assertEquals(ActionIcon.INTENTION, makeFinal.icon) + // The intentions of baseLanguage have no section, so they are listed first, without a heading. + assertNull(makeFinal.group) + val firstAttributeAction = entries.indexOfFirst { it.group == NodeContextActions.NODE_ATTRIBUTES_GROUP } + assertTrue(entries.toString(), firstAttributeAction > entries.indexOf(makeFinal)) + assertTrue( + entries.toString(), + entries.drop(firstAttributeAction).all { it.group == NodeContextActions.NODE_ATTRIBUTES_GROUP }, + ) + assertTrue(entries.toString(), entries.drop(firstAttributeAction).any { it.matchingText.contains("Review") }) + } + + fun `test the context actions are collected on the UI thread where MPS editors can be created`() = + kotlinx.coroutines.test.runTest { + // MPS 2024.1 only allows creating an editor component on the UI thread. This platform doesn't check it. + val threads = mutableListOf() + val provider = + object : IContextActionsProvider { + override fun getContextActions( + node: INode, + parameters: CodeCompletionParameters, + ): List { + threads.add(ApplicationManager.getApplication().isDispatchThread) + return emptyList() + } + } + ContextActionsAspect.providers.add(provider) + try { + openContextActions("method1") + } finally { + ContextActionsAspect.providers.remove(provider) + } + + assertEquals(listOf(true), threads) + assertTrue(contextActions().toString(), contextActions().any { it.matchingText == "Make 'method1' Final" }) + } + + fun `test a context action executes an MPS intention`() = + kotlinx.coroutines.test.runTest { + openContextActions("method1") + typeText("final") + pressEnter() + editor.flush() + + assertNull(editor.getActionMenu()) + assertEquals("true", readAction { methodNode.getPropertyValue(IS_FINAL) }) + } + + fun `test the section of an intention is taken from its description like the menu of MPS-extensions does`() { + assertEquals("Refactoring" to "Extract Method", MPSIntentions.splitSection("Refactoring: Extract Method")) + assertEquals(null to "Make 'method1' Final", MPSIntentions.splitSection("Make 'method1' Final")) + assertEquals(null to "Without section", MPSIntentions.splitSection(": Without section")) + } + fun `test deleting the text of a node attribute removes it but keeps the node`() = kotlinx.coroutines.test.runTest { writeAction { methodNode.addNewChild(SMODEL_ATTRIBUTE, -1, REVIEW_MIGRATION) } @@ -1003,5 +1082,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { private val SMODEL_ATTRIBUTE = IChildLinkReference.fromName("smodelAttribute") private val REVIEW_MIGRATION = ConceptReference("mps:ceab5195-25ea-4f22-9b92-103b95ca8c0c/8703179436979359238") private val TRIM_KIND = IPropertyReference.fromName("trimKind") + private val IS_FINAL = IPropertyReference.fromName("isFinal") } } diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt index 79e42c5a..63da0026 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt @@ -3,12 +3,14 @@ package org.modelix.editor.ssr.mps import org.jetbrains.mps.openapi.module.SRepository import org.modelix.checks.ModelCheckAspect import org.modelix.constraints.ConstraintsAspect +import org.modelix.editor.ContextActionsAspect import org.modelix.editor.EditorEngine import org.modelix.model.api.ILanguageRepository import org.modelix.model.mpsadapters.MPSChangeTranslator import org.modelix.model.mpsadapters.MPSLanguageRepository import org.modelix.presentation.PropertyPresentationAspect import org.modelix.scopes.ScopeAspect +import kotlin.coroutines.EmptyCoroutineContext class EditorIntegrationForMPS( val editorEngine: EditorEngine, @@ -17,6 +19,7 @@ class EditorIntegrationForMPS( private var mpsChangeTranslator: MPSChangeTranslator? = null private var mpsLanguageRepository: MPSLanguageRepository? = null private var modelChecker: AsyncMPSModelChecker? = null + private var intentions: MPSIntentions? = null fun init(repository: SRepository) { mpsLanguageRepository = MPSLanguageRepository(repository) @@ -28,6 +31,8 @@ class EditorIntegrationForMPS( ConstraintsAspect.checkers.add(MPSConstraints) PropertyPresentationAspect.providers.add(MPSPropertyPresentation) modelChecker = AsyncMPSModelChecker(repository).also { ModelCheckAspect.checkers.add(it) } + intentions = MPSIntentions(repository).also { ContextActionsAspect.providers.add(it) } + ContextActionsAspect.loadingContext = EdtDispatcher editorEngine.addRegistry(aspectsFromMPS!!) } @@ -43,6 +48,9 @@ class EditorIntegrationForMPS( it.dispose() } modelChecker = null + intentions?.let { ContextActionsAspect.providers.remove(it) } + if (ContextActionsAspect.loadingContext == EdtDispatcher) ContextActionsAspect.loadingContext = EmptyCoroutineContext + intentions = null // The change translator and the aspects registry attach listeners to MPS. Leaving them registered would keep // this plugin's classes referenced from MPS and prevent the plugin from being unloaded. diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSIntentions.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSIntentions.kt new file mode 100644 index 00000000..a5ecc758 --- /dev/null +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSIntentions.kt @@ -0,0 +1,180 @@ +package org.modelix.editor.ssr.mps + +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.ModalityState +import jetbrains.mps.editor.runtime.HeadlessEditorComponent +import jetbrains.mps.ide.ThreadUtils +import jetbrains.mps.intentions.IntentionsManager +import jetbrains.mps.openapi.intentions.IntentionExecutable +import jetbrains.mps.openapi.intentions.Kind +import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory +import jetbrains.mps.smodel.language.LanguageRegistry +import kotlinx.coroutines.CoroutineDispatcher +import org.jetbrains.mps.openapi.model.SNode +import org.jetbrains.mps.openapi.module.SRepository +import org.modelix.editor.CaretPositionPolicy +import org.modelix.editor.CodeCompletionParameters +import org.modelix.editor.IActionOrProvider +import org.modelix.editor.ICaretPositionPolicy +import org.modelix.editor.ICodeCompletionAction +import org.modelix.editor.IContextActionsProvider +import org.modelix.editor.text.backend.BackendEditorComponent +import org.modelix.editor.text.shared.ActionIcon +import org.modelix.model.api.INode +import org.modelix.model.mpsadapters.MPSNode +import kotlin.coroutines.CoroutineContext + +/** + * Offers the intentions of the MPS languages as context actions, the same ones the intentions menu of MPS (Alt+Enter) + * shows for the node: the enabled intentions of the node and those of its ancestors that are available in child nodes. + * + * Intentions are written against an MPS editor, which they get as their [jetbrains.mps.openapi.editor.EditorContext] + * and may use to check the selection or to select what they created. They get a [HeadlessEditorComponent] on the root + * of the node with the node selected, and what an intention selects in it is selected in the web editor afterwards. + * + * The intentions are collected on the UI thread (see [EdtDispatcher]), like MPS does for its menu. + * + * Quick fixes of the checker messages aren't offered yet. MPS takes them from the messages its editor highlights, + * which a headless editor has none of. + */ +class MPSIntentions( + val repository: SRepository, +) : IContextActionsProvider { + override fun getContextActions( + node: INode, + parameters: CodeCompletionParameters, + ): List { + val mpsNode = node.toMPS() ?: return emptyList() + // MPS doesn't offer intentions in a model that can't be changed. + val model = mpsNode.model ?: return emptyList() + if (model.isReadOnly) return emptyList() + + val sectioned = isSectionedIntentionsMenuInstalled() + return withHeadlessEditor(mpsNode) { editor -> + val query = IntentionsManager.QueryDescriptor().also { it.setEnabledOnly(true) } + IntentionsManager + .getInstance() + .getAvailableIntentions(query, mpsNode, editor.editorContext) + .map { pair -> + val intention = pair.o1 + val intentionNode = pair.o2 + val description = intention.getDescription(intentionNode, editor.editorContext) + val (section, text) = if (sectioned) splitSection(description) else (null to description) + MPSIntentionAction(this, intention, intentionNode, text, section) + } + } + } + + /** + * The intentions menu of MPS-extensions (`com.mbeddr.mpsutil.intentions`) groups the intentions into sections. It + * replaces the menu of every editor when its language is loaded. + */ + private fun isSectionedIntentionsMenuInstalled(): Boolean = + LanguageRegistry.getInstance(repository).getLanguage(SECTIONS_LANGUAGE) != null + + internal fun withHeadlessEditor( + node: SNode, + body: (HeadlessEditorComponent) -> R, + ): R { + val editor = HeadlessEditorComponent(repository) + try { + editor.editNode(node.containingRoot) + editor.selectNode(node) + return body(editor) + } finally { + // An editor can only be disposed on the EDT and in a read action. Executing an intention is already there, + // because it runs in a command, but the intentions are collected in a read action of the web editor. + if (ThreadUtils.isInEDT()) { + editor.dispose() + } else { + repository.modelAccess.runReadInEDT { editor.dispose() } + } + } + } + + companion object { + private val SECTIONS_LANGUAGE = + MetaAdapterFactory.getLanguage( + 0xb92f861d0184446dUL.toLong(), + 0xb88b6dcf0e070241UL.toLong(), + "com.mbeddr.mpsutil.intentions", + ) + + /** + * Same as `com.mbeddr.mpsutil.intentions.runtime.ActionSection`: the text up to the first `:` names the section, + * and what follows it is the text of the intention. + */ + fun splitSection(description: String): Pair { + val separatorPosition = description.indexOf(':') + if (separatorPosition < 0) return null to description + val section = description.substring(0, separatorPosition).takeIf { it.isNotEmpty() } + return section to description.substring(separatorPosition + 1).trimStart() + } + } +} + +class MPSIntentionAction( + private val provider: MPSIntentions, + val intention: IntentionExecutable, + val node: SNode, + private val text: String, + private val section: String?, +) : ICodeCompletionAction { + override fun getMatchingText(): String = text + + override fun getDescription(): String { + val kind = + when (intention.descriptor.kind) { + Kind.ERROR -> "Error intention" + Kind.QUICKFIX -> "Quick fix" + Kind.MIGRATION -> "Migration" + Kind.NORMAL, null -> "Intention" + } + return "$kind of ${node.concept.name}" + } + + override fun getGroup(): String? = section + + /** + * Same as `jetbrains.mps.intentions.icons.IntentionIconProvider`, which shows a quick fix like a normal intention. + */ + override fun getIcon(): ActionIcon = + when (intention.descriptor.kind) { + Kind.ERROR -> ActionIcon.ERROR_INTENTION + Kind.MIGRATION -> ActionIcon.MIGRATION + Kind.QUICKFIX, Kind.NORMAL, null -> ActionIcon.INTENTION + } + + /** + * Runs in the command of the web editor, which an intention is executed in by MPS as well. + */ + override fun execute(editor: BackendEditorComponent): ICaretPositionPolicy? = + provider.withHeadlessEditor(node) { headless -> + val selectedBefore = headless.selectedNode + intention.execute(node, headless.editorContext) + // The selection of a node the intention created needs the cells for it. + headless.editorContext.flushEvents() + headless.selectedNode + ?.takeIf { it != selectedBefore && it.model != null } + ?.let { CaretPositionPolicy(MPSNode(it)) } + } +} + +/** + * Runs coroutines on the UI thread, where MPS also collects the intentions for its menu. A [HeadlessEditorComponent] + * can only be created there, because the editor asks the IntelliJ data context for its project. + * + * Holding a read action there is safe, unlike waiting for the UI thread while holding one, which deadlocks as soon as + * a write action is pending on the UI thread. + */ +object EdtDispatcher : CoroutineDispatcher() { + override fun isDispatchNeeded(context: CoroutineContext): Boolean = !ApplicationManager.getApplication().isDispatchThread + + override fun dispatch( + context: CoroutineContext, + block: Runnable, + ) { + // Also while a modal dialog is open, the actions are only read. + ApplicationManager.getApplication().invokeLater(block, ModalityState.any()) + } +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionActionWrapper.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionActionWrapper.kt index 260428b9..069e2ed3 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionActionWrapper.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionActionWrapper.kt @@ -1,6 +1,7 @@ package org.modelix.editor import org.modelix.editor.text.backend.BackendEditorComponent +import org.modelix.editor.text.shared.ActionIcon open class CodeCompletionActionWrapper( val wrappedAction: ICodeCompletionAction, @@ -60,6 +61,24 @@ class CodeCompletionActionWithDescription( override fun getDescription(): String = overridingDescription } +class CodeCompletionActionWithGroup( + action: ICodeCompletionAction, + val overridingGroup: String?, +) : CodeCompletionActionWrapper(action) { + override fun getGroup(): String? = overridingGroup +} + +fun ICodeCompletionAction.inGroup(group: String?): CodeCompletionActionWithGroup = CodeCompletionActionWithGroup(this, group) + +class CodeCompletionActionWithIcon( + action: ICodeCompletionAction, + val overridingIcon: ActionIcon?, +) : CodeCompletionActionWrapper(action) { + override fun getIcon(): ActionIcon? = overridingIcon +} + +fun ICodeCompletionAction.withIcon(icon: ActionIcon?): CodeCompletionActionWithIcon = CodeCompletionActionWithIcon(this, icon) + class CodeCompletionActionWithTokens( action: ICodeCompletionAction, val overrideTokens: (ICompletionTokenOrList) -> ICompletionTokenOrList, diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt index d7c524f4..00de0466 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt @@ -6,6 +6,7 @@ import kotlinx.html.table import kotlinx.html.td import kotlinx.html.tr import org.modelix.editor.text.backend.BackendEditorComponent +import org.modelix.editor.text.shared.ActionIcon import org.modelix.editor.text.shared.CompletionMenuEntryData class CodeCompletionMenu( @@ -173,6 +174,18 @@ interface ICodeCompletionAction : IActionOrProvider { fun getDescription(): String + /** + * The group a menu that groups its entries lists this action under, like the sections of the MPS intentions menu. + * Actions without a group come first, without a heading. The code completion menu doesn't group its entries. + */ + fun getGroup(): String? = null + + /** + * What a menu that shows icons shows in front of the action. The context actions menu does, the code completion + * menu doesn't. + */ + fun getIcon(): ActionIcon? = null + fun execute(editor: BackendEditorComponent): ICaretPositionPolicy? fun shadows(shadowed: ICodeCompletionAction) = false diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActions.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActions.kt index 61879ed8..567563e4 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActions.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActions.kt @@ -1,7 +1,13 @@ package org.modelix.editor +import io.github.oshai.kotlinlogging.KotlinLogging import org.modelix.editor.celltemplate.getAddAttributeContextAction +import org.modelix.editor.text.shared.ActionIcon import org.modelix.model.api.INode +import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.EmptyCoroutineContext + +private val LOG = KotlinLogging.logger { } /** * Context actions are what is offered in a menu for the selection instead of being reached by typing, like the @@ -10,11 +16,48 @@ import org.modelix.model.api.INode * The menu is opened with Alt+Enter and shows the context actions of the node the selected cell belongs to, so that * selecting a parent node (Cmd+Up) offers the actions of that one. A context action is an [ICodeCompletionAction] whose * [ICodeCompletionAction.getMatchingText] is what the menu shows, and a cell offers them through - * [CellActionProperties.contextActions]. + * [CellActionProperties.contextActions]. The menu lists them by their [ICodeCompletionAction.getGroup], each with its + * [ICodeCompletionAction.getIcon]. */ fun Cell.getContextActions(): ICodeCompletionActionProvider? = ancestors(true).firstNotNullOfOrNull { it.getProperty(CellActionProperties.contextActions) } +/** + * Extension point for context actions that don't come from the notations, like the intentions of MPS languages. + */ +object ContextActionsAspect { + val providers: MutableSet = LinkedHashSet() + + /** + * Where the context actions are collected, for providers that can only run on a particular thread. The MPS + * intentions need an MPS editor, which can only be created on the UI thread. + */ + var loadingContext: CoroutineContext = EmptyCoroutineContext + + fun getContextActions( + node: INode, + parameters: CodeCompletionParameters, + ): List = + providers.toList().flatMap { provider -> + // One failing provider shouldn't take the actions of the others with it. + runCatching { provider.getContextActions(node, parameters) } + .getOrElse { ex -> + LOG.error(ex) { "Context actions provider $provider failed for $node" } + emptyList() + } + } +} + +interface IContextActionsProvider { + /** + * The context actions for [node], the node the selection belongs to. + */ + fun getContextActions( + node: INode, + parameters: CodeCompletionParameters, + ): List +} + /** * The context actions of [node], which are set on its cell. */ @@ -22,7 +65,7 @@ class NodeContextActions( val node: INode, ) : ICodeCompletionActionProvider { override fun getApplicableActions(parameters: CodeCompletionParameters): List = - getAddAttributeActions(parameters.editor.engine) + getAddAttributeActions(parameters.editor.engine) + ContextActionsAspect.getContextActions(node, parameters) /** * Same placement as the side transforms: a new attribute goes directly outside of the selected attribute, and @@ -37,6 +80,23 @@ class NodeContextActions( } else { engine.getIndexInsideNodeAttributes(node) } - return engine.getNodeAttributeTemplates().mapNotNull { it.getAddAttributeContextAction(target, index) } + return engine + .getNodeAttributeTemplates() + .mapNotNull { + it + .getAddAttributeContextAction( + target, + index + )?.withIcon(ActionIcon.NODE_ATTRIBUTE) + ?.inGroup(NODE_ATTRIBUTES_GROUP) + } + } + + companion object { + /** + * The group of the actions that are generated for the notations of node attributes, which keeps them apart + * from the actions a language defines itself. + */ + const val NODE_ATTRIBUTES_GROUP = "Node Attributes" } } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt index a4517046..b2666cf8 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt @@ -11,6 +11,9 @@ import org.modelix.editor.text.shared.CompletionMenuEntryData * opens below the cell, and what is typed only searches the entries, anywhere in their text and ignoring the case. An * action is only executed once the user confirmed it. The entries don't depend on the pattern, so they are filtered * here instead of being loaded again from the backend. + * + * The entries are listed under a heading per group (see [org.modelix.editor.ICodeCompletionAction.getGroup]), like the + * sections of the MPS intentions menu, and with an icon instead of a description, like the intentions there. */ class ContextActionsMenu( editor: FrontendEditorComponent, @@ -41,13 +44,19 @@ class ContextActionsMenu( } div("context-actions-entries") { filteredEntries.forEachIndexed { index, entry -> + // The entries arrive ordered by their group, so a group starts where it differs from the previous. + val group = entry.group + if (group != null && group != filteredEntries.getOrNull(index - 1)?.group) { + div("context-actions-group") { + +group + } + } div(if (index == selectedIndex) "context-action $selectedEntryClass" else "context-action") { + // Also without an icon, so that the texts of all entries line up. + div(listOfNotNull("context-action-icon", entry.icon?.let { "icon-${it.cssClass}" }).joinToString(" ")) { } div("context-action-text") { +entry.matchingText } - div("context-action-description") { - +entry.description - } } } if (filteredEntries.isEmpty()) { diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/BackendEditorComponent.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/BackendEditorComponent.kt index 25ad81e7..7b400814 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/BackendEditorComponent.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/BackendEditorComponent.kt @@ -58,6 +58,16 @@ class BackendEditorComponent( fun runRead(body: () -> R): R = rootCall.node.getModel().executeRead(body) + private companion object { + /** + * The actions without a group first, then the groups by name, like the sections of the MPS intentions menu. + * Within a group by their text. + */ + val menuOrder: Comparator = + compareBy({ it.getGroup() != null }, { it.getGroup() }) + .thenBy { it.getCompletionPattern().lowercase() } + } + inner class CompletionMenuBackend( val providers: List, ) { @@ -77,7 +87,7 @@ class BackendEditorComponent( val matchingText = it.getCompletionPattern() matchingText.isNotEmpty() && matchingText.startsWith(parameters.pattern) }.applyShadowing() - .sortedBy { it.getCompletionPattern().lowercase() } + .sortedWith(menuOrder) } } } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt index 22142c2f..13e43383 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext import org.modelix.editor.CaretPositionPolicy import org.modelix.editor.CaretPositionPolicyWithIndex import org.modelix.editor.Cell @@ -14,6 +15,7 @@ import org.modelix.editor.CellActionProperties import org.modelix.editor.CodeCompletionParameters import org.modelix.editor.CommonCellProperties import org.modelix.editor.CompletionPosition +import org.modelix.editor.ContextActionsAspect import org.modelix.editor.ECellType import org.modelix.editor.EditorEngine import org.modelix.editor.ICaretPositionPolicy @@ -284,6 +286,15 @@ class TextEditorServiceImpl( editorId: Int, cellId: CellInstanceId, anchorCellId: CellInstanceId, + ): EditorUpdateData = + withContext(ContextActionsAspect.loadingContext) { + loadContextActions(editorId, cellId, anchorCellId) + } + + private suspend fun loadContextActions( + editorId: Int, + cellId: CellInstanceId, + anchorCellId: CellInstanceId, ): EditorUpdateData = runWithCell(editorId, cellId) { updateChannel, cell -> updateChannel.createUpdate().copy( @@ -416,7 +427,9 @@ class TextEditorServiceImpl( CompletionMenuEntryData( id = index, matchingText = entry.getMatchingText(), - description = entry.getDescription() + description = entry.getDescription(), + group = entry.getGroup(), + icon = entry.getIcon(), ) } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt index 1c6698a0..4333a79d 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt @@ -235,6 +235,10 @@ data class CompletionMenuEntryData( val id: Int, val matchingText: String, val description: String, + /** See [org.modelix.editor.ICodeCompletionAction.getGroup]. */ + val group: String? = null, + /** See [org.modelix.editor.ICodeCompletionAction.getIcon]. */ + val icon: ActionIcon? = null, ) { fun matches( pattern: String, @@ -246,3 +250,23 @@ data class CompletionMenuEntryData( fun matchesExactly(pattern: String): Boolean = matchingText == pattern } + +/** + * The icons a menu can show for an action, which are the ones of the MPS intentions menu. The client styles them, so an + * action can only use one of these. + */ +@Serializable +enum class ActionIcon( + val cssClass: String, +) { + /** A normal intention, and a quick fix, which MPS shows the same way. */ + INTENTION("intention"), + + /** An intention that fixes an error. */ + ERROR_INTENTION("error-intention"), + + MIGRATION("migration"), + + /** Adds a node attribute. */ + NODE_ATTRIBUTE("node-attribute"), +} diff --git a/react-ssr-client/src/components/ModelixTextEditor.css b/react-ssr-client/src/components/ModelixTextEditor.css index 03497927..265fd8cf 100644 --- a/react-ssr-client/src/components/ModelixTextEditor.css +++ b/react-ssr-client/src/components/ModelixTextEditor.css @@ -185,24 +185,54 @@ overflow-y: auto; } +.modelix-text-editor .context-actions-menu .context-actions-group { + padding: 4px 8px 2px; + font-size: 8pt; + font-weight: bold; + color: #808080; +} + +.modelix-text-editor .context-actions-menu .context-actions-group:not(:first-child) { + border-top: 1px solid #e0e0e0; +} + .modelix-text-editor .context-actions-menu .context-action { display: flex; - justify-content: space-between; - gap: 24px; + align-items: center; + gap: 6px; padding: 3px 8px; } -.modelix-text-editor .context-actions-menu .context-action.selected { - background-color: #1055d1; - color: white; +/* The icons of the IntelliJ Platform (new UI) that the intentions menu of MPS shows, Apache 2.0 licensed: + expui/codeInsight/intentionBulb.svg, expui/codeInsight/quickfixBulb.svg, expui/nodes/annotation.svg and the + expUi/actions/migrationBulb.svg of MPS. */ +.modelix-text-editor .context-actions-menu .context-action-icon { + flex: none; + width: 16px; + height: 16px; + background-repeat: no-repeat; + background-size: 16px 16px; } -.modelix-text-editor .context-actions-menu .context-action-description { - color: #808080; +.modelix-text-editor .context-actions-menu .context-action-icon.icon-intention { + background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='5.70142' y='12' width='4.6' height='1' fill='%236C707E'/%3E%3Cpath d='M6 14H10C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14Z' fill='%236C707E'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M10.8704 9.14748C12.0417 8.27221 12.8 6.87465 12.8 5.3C12.8 2.64903 10.6509 0.5 7.99995 0.5C5.34898 0.5 3.19995 2.64903 3.19995 5.3C3.19995 6.87464 3.95817 8.27218 5.12943 9.14746L5.49994 11H10.4999L10.8704 9.14748Z' fill='%23FFAF0F'/%3E%3C/svg%3E"); } -.modelix-text-editor .context-actions-menu .context-action.selected .context-action-description { - color: #d5e0f5; +.modelix-text-editor .context-actions-menu .context-action-icon.icon-error-intention { + background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='5.70142' y='12' width='4.6' height='1' fill='%236C707E'/%3E%3Cpath d='M6 14H10C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14Z' fill='%236C707E'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M10.8704 9.14748C12.0417 8.27221 12.8 6.87465 12.8 5.3C12.8 2.64903 10.6509 0.5 7.99995 0.5C5.34898 0.5 3.19995 2.64903 3.19995 5.3C3.19995 6.87464 3.95817 8.27218 5.12943 9.14746L5.49994 11H10.4999L10.8704 9.14748ZM8 2.00002C8.49706 2.00002 8.9 2.40297 8.9 2.90002V5.40002C8.9 5.89708 8.49706 6.30002 8 6.30002C7.50294 6.30002 7.1 5.89708 7.1 5.40002L7.1 2.90002C7.1 2.40297 7.50294 2.00002 8 2.00002ZM7.9999 9.2C8.60742 9.2 9.0999 8.70751 9.0999 8.1C9.0999 7.49249 8.60742 7 7.9999 7C7.39239 7 6.8999 7.49249 6.8999 8.1C6.8999 8.70751 7.39239 9.2 7.9999 9.2Z' fill='%23E55765'/%3E%3C/svg%3E"); +} + +.modelix-text-editor .context-actions-menu .context-action-icon.icon-migration { + background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M6 14H10C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14Z' fill='%236C707E'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M12.1464 8.14645C12.3417 7.95118 12.6583 7.95118 12.8536 8.14645L15.8536 11.1464C16.0488 11.3417 16.0488 11.6583 15.8536 11.8536C15.6583 12.0488 15.3417 12.0488 15.1464 11.8536L13 9.70711V15.5C13 15.7761 12.7761 16 12.5 16C12.2239 16 12 15.7761 12 15.5V9.70711L9.85355 11.8536C9.65829 12.0488 9.34171 12.0488 9.14645 11.8536C8.95118 11.6583 8.95118 11.3417 9.14645 11.1464L12.1464 8.14645Z' fill='%236C707E'/%3E%3Cpath d='M8.08542 12H5.70117V13H9.5C9.11612 13 8.73223 12.8536 8.43934 12.5607C8.27559 12.3969 8.15762 12.2047 8.08542 12Z' fill='%236C707E'/%3E%3Cpath d='M8.08542 11C8.15762 10.7953 8.2756 10.6031 8.43934 10.4393L11.4393 7.43934C11.7298 7.14888 12.1098 7.00244 12.4904 7.00003C12.6906 6.47159 12.8002 5.89859 12.8002 5.3C12.8002 2.64903 10.6512 0.5 8.0002 0.5C5.34923 0.5 3.2002 2.64903 3.2002 5.3C3.2002 6.87464 3.95842 8.27218 5.12968 9.14746L5.50018 11H8.08542Z' fill='%2355A76A'/%3E%3C/svg%3E"); +} + +.modelix-text-editor .context-actions-menu .context-action-icon.icon-node-attribute { + background-image: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='8' cy='8' r='7' fill='%23F2FCF3'/%3E%3Cpath d='M9.72989 5.38506V6.35862H9.70012C9.35494 5.69 8.71609 5.3046 7.87126 5.3046C6.38276 5.3046 5.26437 6.47931 5.26437 8.04023C5.26437 9.60115 6.38276 10.7759 7.87126 10.7759C8.81103 10.7759 9.58828 10.339 10.0026 9.65425C10.442 10.3357 11.2602 10.7517 12.2885 10.7517C13.9218 10.7517 15 9.60115 15 7.91954C15 4.11379 11.854 1 8 1C4.14598 1 1 4.18621 1 8.08046C1 11.8862 4.14598 15 8 15C9.85057 15 11.5161 14.2356 12.4333 13.4069L11.7092 12.6103C10.8966 13.3345 9.5931 13.9943 8 13.9943C4.70115 13.9943 2.00575 11.331 2.00575 8.08046C2.00575 4.74138 4.70115 2.00575 8 2.00575C11.2989 2.00575 13.9943 4.66897 13.9943 7.91954C13.9943 9.02989 13.3264 9.78621 12.2885 9.78621C11.3471 9.78621 10.6552 9.1908 10.6552 8.32184V5.38506H9.72989ZM7.95977 9.8908C6.99425 9.8908 6.27011 9.09425 6.27011 8.04023C6.27011 6.98621 6.99425 6.18966 7.95977 6.18966C8.92529 6.18966 9.64943 6.98621 9.64943 8.04023C9.64943 9.09425 8.92529 9.8908 7.95977 9.8908Z' fill='%23208A3C'/%3E%3C/svg%3E"); +} + +.modelix-text-editor .context-actions-menu .context-action.selected { + background-color: #1055d1; + color: white; } .modelix-text-editor .context-actions-menu .context-actions-empty { From 279065f75153e3644d75916d9de1cf48252383f3 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 13 Nov 2026 13:19:14 +0100 Subject: [PATCH 13/23] feat(projectional-editor): quick fixes of the model checker in the context actions menu The context actions menu now also offers the quick fixes of the messages the editor shows, like the intentions menu of MPS does. The background model checker keeps the MPS report items of its last completed check, and the headless editor the intentions are collected with highlights those of the node and its ancestors. MPS then decides which quick fixes apply. The checker checks wrappers of the nodes, so the quick fixes it reports hold these wrappers in their arguments. A quick fix like AddCast moves such an argument into the model, which would put a wrapper into the MPS model. The arguments are replaced by the MPS nodes they wrap before a quick fix is offered. Co-Authored-By: Claude Opus 5.5 --- .../editor/ssr/mps/BaseLanguageTests.kt | 44 ++++++++++++++++ .../editor/ssr/mps/AsyncMPSModelChecker.kt | 43 +++++++++++++--- .../editor/ssr/mps/EditorIntegrationForMPS.kt | 5 +- .../modelix/editor/ssr/mps/MPSIntentions.kt | 26 +++++++++- .../editor/ssr/mps/QuickFixArguments.kt | 51 +++++++++++++++++++ 5 files changed, 159 insertions(+), 10 deletions(-) create mode 100644 projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/QuickFixArguments.kt diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index b3b6cf7c..fae7394a 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -50,6 +50,7 @@ import org.modelix.model.api.IWritableNode import org.modelix.model.api.getDescendants import org.modelix.model.mpsadapters.MPSArea import org.modelix.model.mpsadapters.MPSWritableNode +import org.modelix.model.mpsadapters.tomps.ModelixNodeAsMPSNode import org.modelix.mps.editor.common.IncrementalModelChecker /** @@ -1055,6 +1056,49 @@ class BaseLanguageTests : TestBase("SimpleProject") { assertEquals("true", readAction { methodNode.getPropertyValue(IS_FINAL) }) } + fun `test the context actions menu offers the quick fixes of the checker messages`() = + kotlinx.coroutines.test.runTest { + // The initializer of an int variable can't be a boolean, which MPS can fix by adding a cast. + placeCaretIntoPlaceholderOf(methodBodyNode, "statement") + typeText("int ") + pressKey(KnownKeys.Tab) + typeText("abc") + typeText("=") + typeText("true") + assertNotEmpty(awaitErrorMessagesInEditor(present = true)) + + openContextActions("true") + // The quick fixes of an error are error intentions in MPS, which have the red bulb. + val quickFixes = contextActions().filter { it.icon == ActionIcon.ERROR_INTENTION }.map { it.matchingText } + assertEquals(listOf("Cast the initializer to int", "Change type of abc to boolean"), quickFixes) + + typeText("Cast the initializer") + pressEnter() + editor.flush() + + assertNull(editor.getActionMenu()) + // The quick fix moves the initializer into the cast. It must be the MPS node, not the wrapper the checker + // reported the error for. + readAction { + val variable = + checkNotNull( + methodBodyNode.asLegacyNode().getDescendants(false).firstOrNull { + it.concept?.getShortName() == + "LocalVariableDeclaration" + } + ) + val cast = checkNotNull(variable.toMPS()).getChildren().single { it.concept.name == "CastExpression" } + assertTrue(cast.getChildren().none { it is ModelixNodeAsMPSNode }) + } + assertFinalEditorText(""" + public class Class1 { + public void method1() { + int abc = (int) true; + } + } + """) + } + fun `test the section of an intention is taken from its description like the menu of MPS-extensions does`() { assertEquals("Refactoring" to "Extract Method", MPSIntentions.splitSection("Refactoring: Extract Method")) assertEquals(null to "Make 'method1' Final", MPSIntentions.splitSection("Make 'method1' Final")) diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/AsyncMPSModelChecker.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/AsyncMPSModelChecker.kt index 9ef03a91..abbedd98 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/AsyncMPSModelChecker.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/AsyncMPSModelChecker.kt @@ -3,11 +3,13 @@ package org.modelix.editor.ssr.mps import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager +import jetbrains.mps.errors.item.NodeReportItem import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay +import org.jetbrains.mps.openapi.model.SNodeReference import org.jetbrains.mps.openapi.module.SRepository import org.modelix.checks.CheckMessage import org.modelix.checks.IModelChecker @@ -61,6 +63,12 @@ class AsyncMPSModelChecker( private val publishedMessages = ConcurrentHashMap>() + /** + * The MPS messages of the last completed check, which the messages of the editor are made of, by root node. They + * carry the quick fixes. + */ + private val publishedReportItems = ConcurrentHashMap>>() + private val modelChangeListener = object : IDependencyListener { override fun accessed(key: IStateVariableReference<*>) {} @@ -90,12 +98,19 @@ class AsyncMPSModelChecker( return messages.read() } + /** + * The MPS messages of [node] from the last completed check, the ones the editor shows. Unlike [getMessages] this + * doesn't request a check. + */ + fun getReportItems(node: SNodeReference): List = publishedReportItems.values.flatMap { it[node].orEmpty() } + fun dispose() { DependencyTracking.removeListener(modelChangeListener) validator.stop() coroutineScope.cancel("disposed") checkEngine.dispose() publishedMessages.clear() + publishedReportItems.clear() } private suspend fun checkRequestedRoots() { @@ -131,17 +146,22 @@ class AsyncMPSModelChecker( return if (completed) result else null } + private class CheckResult( + val messages: Map>, + val reportItems: Map>, + ) + /** * The messages of the checked root nodes, grouped by root node and node. */ - private fun checkRoots(): Map>> { + private fun checkRoots(): Map { while (true) { val node = requestedNodes.poll() ?: break if (!node.isValid) continue val root = checker.getRootNodeOrNull(node) ?: continue checkedRoots[root.reference] = root } - val result = LinkedHashMap>>() + val result = LinkedHashMap() val iterator = checkedRoots.values.iterator() while (iterator.hasNext()) { val root = iterator.next() @@ -152,14 +172,25 @@ class AsyncMPSModelChecker( continue } result[root.reference] = - messages - .mapValues { (_, items) -> items.mapNotNull { it.toCheckMessage() } } - .filterValues { it.isNotEmpty() } + CheckResult( + messages = + messages + .mapValues { (_, items) -> + items.mapNotNull { it.toCheckMessage() } + }.filterValues { it.isNotEmpty() }, + reportItems = messages.values.flatten().groupBy { it.node }, + ) } return result } - private fun publish(messagesByRoot: Map>>) { + private fun publish(resultsByRoot: Map) { + publishedReportItems.keys.retainAll(resultsByRoot.keys) + for ((root, result) in resultsByRoot) { + publishedReportItems[root] = result.reportItems + } + + val messagesByRoot = resultsByRoot.mapValues { it.value.messages } for (root in publishedNodesByRoot.keys - messagesByRoot.keys) { publishedNodesByRoot.remove(root)?.forEach { publish(it, null) } } diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt index 63da0026..4200da2b 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/EditorIntegrationForMPS.kt @@ -30,8 +30,9 @@ class EditorIntegrationForMPS( ScopeAspect.registerScopeProvider(MPSScopeProvider) ConstraintsAspect.checkers.add(MPSConstraints) PropertyPresentationAspect.providers.add(MPSPropertyPresentation) - modelChecker = AsyncMPSModelChecker(repository).also { ModelCheckAspect.checkers.add(it) } - intentions = MPSIntentions(repository).also { ContextActionsAspect.providers.add(it) } + val modelChecker = AsyncMPSModelChecker(repository).also { ModelCheckAspect.checkers.add(it) } + this.modelChecker = modelChecker + intentions = MPSIntentions(repository, modelChecker::getReportItems).also { ContextActionsAspect.providers.add(it) } ContextActionsAspect.loadingContext = EdtDispatcher editorEngine.addRegistry(aspectsFromMPS!!) } diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSIntentions.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSIntentions.kt index a5ecc758..2e2f6302 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSIntentions.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/MPSIntentions.kt @@ -3,14 +3,18 @@ package org.modelix.editor.ssr.mps import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import jetbrains.mps.editor.runtime.HeadlessEditorComponent +import jetbrains.mps.errors.item.NodeReportItem import jetbrains.mps.ide.ThreadUtils import jetbrains.mps.intentions.IntentionsManager +import jetbrains.mps.nodeEditor.HighlighterMessage +import jetbrains.mps.openapi.editor.message.EditorMessageOwner import jetbrains.mps.openapi.intentions.IntentionExecutable import jetbrains.mps.openapi.intentions.Kind import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory import jetbrains.mps.smodel.language.LanguageRegistry import kotlinx.coroutines.CoroutineDispatcher import org.jetbrains.mps.openapi.model.SNode +import org.jetbrains.mps.openapi.model.SNodeReference import org.jetbrains.mps.openapi.module.SRepository import org.modelix.editor.CaretPositionPolicy import org.modelix.editor.CodeCompletionParameters @@ -34,11 +38,14 @@ import kotlin.coroutines.CoroutineContext * * The intentions are collected on the UI thread (see [EdtDispatcher]), like MPS does for its menu. * - * Quick fixes of the checker messages aren't offered yet. MPS takes them from the messages its editor highlights, - * which a headless editor has none of. + * The quick fixes of the messages the editor shows are offered as well. MPS takes them from the messages its editor + * highlights, so the headless editor highlights the [checkerMessages] of the node and its ancestors, and MPS decides + * which of their quick fixes apply, like in its own editor. */ class MPSIntentions( val repository: SRepository, + /** The messages the editor shows for a node, whose quick fixes are offered. */ + private val checkerMessages: (SNodeReference) -> List = { emptyList() }, ) : IContextActionsProvider { override fun getContextActions( node: INode, @@ -79,6 +86,7 @@ class MPSIntentions( val editor = HeadlessEditorComponent(repository) try { editor.editNode(node.containingRoot) + highlightCheckerMessages(editor, node) editor.selectNode(node) return body(editor) } finally { @@ -92,6 +100,20 @@ class MPSIntentions( } } + private fun highlightCheckerMessages( + editor: HeadlessEditorComponent, + node: SNode, + ) { + for (highlightedNode in generateSequence(node) { it.parent }) { + for (item in checkerMessages(highlightedNode.reference)) { + QuickFixArguments.unwrap(item) + editor.highlightManager.mark(HighlighterMessage(CheckerMessagesOwner, item, highlightedNode)) + } + } + } + + private object CheckerMessagesOwner : EditorMessageOwner + companion object { private val SECTIONS_LANGUAGE = MetaAdapterFactory.getLanguage( diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/QuickFixArguments.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/QuickFixArguments.kt new file mode 100644 index 00000000..222b22b1 --- /dev/null +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/QuickFixArguments.kt @@ -0,0 +1,51 @@ +package org.modelix.editor.ssr.mps + +import jetbrains.mps.errors.QuickFix_Runtime +import jetbrains.mps.errors.item.NodeReportItem +import jetbrains.mps.errors.item.QuickFixReportItem +import jetbrains.mps.errors.item.QuickFixRuntimeAdapter +import org.modelix.model.api.IWritableNode +import org.modelix.model.mpsadapters.tomps.ModelixNodeAsMPSNode +import java.lang.reflect.Field + +/** + * The model checker checks wrappers of the nodes ([ModelixNodeAsMPSNode]), which track what a check reads, so the quick + * fixes it reports hold these wrappers in their arguments. A quick fix that puts such an argument into the model, like + * `AddCast` does with the expression it casts, would put a wrapper into the MPS model. The arguments are replaced by the + * MPS nodes they wrap before a quick fix is offered. + * + * The node a quick fix is executed on is a reference, which already resolves to the MPS node. + */ +internal object QuickFixArguments { + /** + * [QuickFix_Runtime] has no API to list its arguments. Its subclasses read them by name from this map. + */ + private val argumentsField: Field? = + runCatching { QuickFix_Runtime::class.java.getDeclaredField("myMap").also { it.isAccessible = true } }.getOrNull() + + /** + * Has to run in a read action, and is a no-op for arguments that are no wrappers, so it can run again. + */ + fun unwrap(item: NodeReportItem) { + val field = argumentsField ?: return + for (quickFix in QuickFixReportItem.FLAVOUR_EDITOR_QUICKFIX.getCollection(item)) { + // The runtime is created once per quick fix provider of the item and then reused. + val runtime = (quickFix as? QuickFixRuntimeAdapter)?.fixRuntime ?: continue + + @Suppress("UNCHECKED_CAST") + val arguments = field.get(runtime) as? Map> ?: continue + for (values in arguments.values) { + for (i in values.indices) { + values[i] = unwrap(values[i]) + } + } + } + } + + private fun unwrap(value: Any?): Any? = + when (value) { + is ModelixNodeAsMPSNode -> (value.node as? IWritableNode).toMPS() ?: value + is List<*> -> if (value.any { it is ModelixNodeAsMPSNode }) value.map { unwrap(it) } else value + else -> value + } +} From 31eadb1643fc104a6b251261c5ff3c7220475b32 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 13 Nov 2026 13:37:35 +0100 Subject: [PATCH 14/23] feat(projectional-editor): fit the context actions menu into the visible part of the editor The entries of the context actions menu were limited to a height of 200px, which showed only about 9 of the many intentions the MPS languages offer. The menu now uses the space down to the end of the visible part of the editor, and opens above its anchor if the entries don't fit below it but there is more space above, like the popups of MPS. The JS editor measures the visible part as the window cut down by the scrolling elements around the editor. Where it can't be measured, the entries are limited to 60% of the window height. Co-Authored-By: Claude Opus 5.5 --- .../src/jsMain/resources/editor.css | 4 +- .../kotlin/org/modelix/editor/ActionMenu.kt | 19 +++++++-- .../org/modelix/editor/ContextActionsMenu.kt | 42 +++++++++++++++++++ .../modelix/editor/FrontendEditorComponent.kt | 6 +++ .../org/modelix/editor/JsEditorComponent.kt | 25 +++++++++++ .../src/components/ModelixTextEditor.css | 4 +- 6 files changed, 95 insertions(+), 5 deletions(-) diff --git a/projectional-editor-ssr-client/src/jsMain/resources/editor.css b/projectional-editor-ssr-client/src/jsMain/resources/editor.css index ea95df54..ac90bd6c 100644 --- a/projectional-editor-ssr-client/src/jsMain/resources/editor.css +++ b/projectional-editor-ssr-client/src/jsMain/resources/editor.css @@ -175,7 +175,9 @@ } .editor .context-actions-menu .context-actions-entries { - max-height: 200px; + /* As tall as the window allows, like the intentions popup of MPS. The languages offer many intentions, and only a + few of them would fit into a fixed height. */ + max-height: 60vh; overflow-y: auto; } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ActionMenu.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ActionMenu.kt index 6f796cf0..6ccfae55 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ActionMenu.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ActionMenu.kt @@ -82,6 +82,17 @@ abstract class ActionMenu( */ protected abstract fun getPosition(anchorBounds: Bounds): Position + /** + * Where the menu goes, given the bounds of the anchor and of the part of the editor that is visible, both relative + * to the main layer. A menu can also adapt its size to the visible part here. [visibleBounds] is null where it + * can't be measured. + */ + protected open fun place( + menuElement: IVirtualDom.HTMLElement, + anchorBounds: Bounds, + visibleBounds: Bounds?, + ): Position = getPosition(anchorBounds) + protected open suspend fun onPatternEdited() = updateEntries() protected open suspend fun onTextInserted( @@ -177,8 +188,10 @@ abstract class ActionMenu( LOG.trace { "ActionMenu.updateBounds()" } val containerElement = editor.getHtmlElement(this) ?: return val anchorElement = editor.getHtmlElement(getAnchor()) ?: return - val anchorBounds = anchorElement.getOuterBounds().relativeTo(editor.getMainLayer()?.getOuterBounds() ?: Bounds.ZERO) - val position = getPosition(anchorBounds) + val mainLayerBounds = editor.getMainLayer()?.getOuterBounds() ?: Bounds.ZERO + val anchorBounds = anchorElement.getOuterBounds().relativeTo(mainLayerBounds) + val visibleBounds = editor.getVisibleBounds()?.relativeTo(mainLayerBounds) + val position = place(containerElement, anchorBounds, visibleBounds) containerElement.style.left = "${position.left}px" containerElement.style.top = "${position.top}px" @@ -197,7 +210,7 @@ abstract class ActionMenu( protected fun getPatternElement(): IVirtualDom.HTMLElement? = editor.getHtmlElement(this)?.elementsWithClass(patternClass)?.firstOrNull() - private fun IVirtualDom.HTMLElement.elementsWithClass(cssClass: String): Sequence = + protected fun IVirtualDom.HTMLElement.elementsWithClass(cssClass: String): Sequence = descendants().filterIsInstance().filter { it.getClasses().contains(cssClass) } data class Position( diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt index b2666cf8..5ed66a47 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ContextActionsMenu.kt @@ -3,6 +3,8 @@ package org.modelix.editor import kotlinx.html.TagConsumer import kotlinx.html.div import org.modelix.editor.text.shared.CompletionMenuEntryData +import kotlin.math.max +import kotlin.math.min /** * The menu of the context actions of the selection (see [getContextActions]). @@ -32,6 +34,38 @@ class ContextActionsMenu( override fun getPosition(anchorBounds: Bounds): Position = Position(anchorBounds.x, anchorBounds.y + anchorBounds.height) + /** + * Below the anchor, as tall as the space down to the end of the visible part of the editor allows. If the entries + * don't fit there, but there is more space above the anchor, the menu opens above it instead, like the popups of + * MPS do. + */ + override fun place( + menuElement: IVirtualDom.HTMLElement, + anchorBounds: Bounds, + visibleBounds: Bounds?, + ): Position { + val below = getPosition(anchorBounds) + if (visibleBounds == null) return below + val entriesElement = menuElement.elementsWithClass("context-actions-entries").firstOrNull() ?: return below + + val entriesBounds = entriesElement.getOuterBounds() + // The title and the search pattern. + val headerHeight = menuElement.getOuterBounds().height - entriesBounds.height + // The entries element may be limited from the last time, but the entries in it still have their full height. + val entries = entriesElement.childNodes.filterIsInstance() + val contentHeight = + if (entries.isEmpty()) entriesBounds.height else entries.last().getOuterBounds().maxY() - entries.first().getOuterBounds().y + + val spaceBelow = visibleBounds.maxY() - anchorBounds.maxY() - MARGIN + val spaceAbove = anchorBounds.y - visibleBounds.y - MARGIN + val openAbove = headerHeight + contentHeight > spaceBelow && spaceAbove > spaceBelow + val maxEntriesHeight = max(MIN_ENTRIES_HEIGHT, (if (openAbove) spaceAbove else spaceBelow) - headerHeight) + entriesElement.style["max-height"] = "${maxEntriesHeight}px" + + if (!openAbove) return below + return Position(anchorBounds.x, anchorBounds.y - headerHeight - min(contentHeight, maxEntriesHeight)) + } + override fun produceHtml(consumer: TagConsumer) { consumer.div("context-actions-menu") { div("context-actions-title") { @@ -67,4 +101,12 @@ class ContextActionsMenu( } } } + + private companion object { + /** Between the menu and the end of the visible part of the editor. */ + const val MARGIN = 4.0 + + /** Below this the menu rather scrolls the editor than its entries. */ + const val MIN_ENTRIES_HEIGHT = 100.0 + } } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt index 24287cb9..e342855f 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt @@ -431,6 +431,12 @@ open class FrontendEditorComponent( open fun scrollIntoView(element: IVirtualDom.HTMLElement) {} + /** + * The part of the editor that can be seen, in the coordinates of [IVirtualDom.Element.getOuterBounds]: the window, + * cut down by the elements around the editor that scroll. Null where it can't be measured. + */ + open fun getVisibleBounds(): Bounds? = null + suspend fun serviceCall(call: suspend TextEditorService.() -> R): R { val result = call(service) when (result) { diff --git a/projectional-editor/src/jsMain/kotlin/org/modelix/editor/JsEditorComponent.kt b/projectional-editor/src/jsMain/kotlin/org/modelix/editor/JsEditorComponent.kt index d9f67def..d74b9c0d 100644 --- a/projectional-editor/src/jsMain/kotlin/org/modelix/editor/JsEditorComponent.kt +++ b/projectional-editor/src/jsMain/kotlin/org/modelix/editor/JsEditorComponent.kt @@ -5,10 +5,13 @@ import kotlinx.browser.window import kotlinx.html.div import kotlinx.html.tabIndex import org.modelix.editor.text.shared.TextEditorService +import org.w3c.dom.Element import org.w3c.dom.HTMLDivElement import org.w3c.dom.events.Event import org.w3c.dom.events.KeyboardEvent import org.w3c.dom.events.MouseEvent +import kotlin.math.max +import kotlin.math.min private val LOG = KotlinLogging.logger {} @@ -84,6 +87,28 @@ class JsEditorComponent( element.unwrap().scrollIntoView(js("""{block: "nearest"}""")) } + override fun getVisibleBounds(): Bounds { + val container = containerElement.unwrap() + var left = 0.0 + var top = 0.0 + var right = window.innerWidth.toDouble() + var bottom = window.innerHeight.toDouble() + var element: Element? = container + while (element != null) { + val style = window.getComputedStyle(element) + if (style.getPropertyValue("overflow-x") != "visible" || style.getPropertyValue("overflow-y") != "visible") { + val clip = element.getBoundingClientRect() + left = max(left, clip.left) + top = max(top, clip.top) + right = min(right, clip.right) + bottom = min(bottom, clip.bottom) + } + element = element.parentElement + } + val origin = container.getBoundingClientRect() + return Bounds(left - origin.left, top - origin.top, max(0.0, right - left), max(0.0, bottom - top)) + } + companion object { const val NAVIGATION_MODE_CLASS_NAME = "navigation-mode" } diff --git a/react-ssr-client/src/components/ModelixTextEditor.css b/react-ssr-client/src/components/ModelixTextEditor.css index 265fd8cf..e90e354f 100644 --- a/react-ssr-client/src/components/ModelixTextEditor.css +++ b/react-ssr-client/src/components/ModelixTextEditor.css @@ -181,7 +181,9 @@ } .modelix-text-editor .context-actions-menu .context-actions-entries { - max-height: 200px; + /* As tall as the window allows, like the intentions popup of MPS. The languages offer many intentions, and only a + few of them would fit into a fixed height. */ + max-height: 60vh; overflow-y: auto; } From 72d8a0c0c58d28748917d9da3023f663885de227 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 13 Nov 2026 16:10:04 +0100 Subject: [PATCH 15/23] fix(mps-plugin): offer only the concepts of the languages a model uses The constraint that hides the concepts of languages a model doesn't use never applied. It looked for the MPSModelAsNode of the model among the ancestors of the node, but the ancestors come as legacy nodes that wrap it. So the code completion offered the concepts of every language in the repository: the closures, collections and smodel concepts competed with baseLanguage in a plain Java model, and made typing `{` or `f` ambiguous. Co-Authored-By: Claude Opus 5.5 --- .../org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt index 026fc7ff..d2010557 100644 --- a/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt +++ b/projectional-editor-ssr-mps/src/main/kotlin/org/modelix/editor/ssr/mps/ModelixSSRServerForMPS.kt @@ -372,10 +372,11 @@ object MPSConstraints : IConstraintsChecker { fun checkLanguageImported(node: INonExistingNode): List { val concept = node.expectedConcept() as? MPSConcept ?: return emptyList() val language = concept.concept.language + // The ancestors come as legacy nodes, which wrap the MPSModelAsNode of the model. val model = node .ancestors() - .map { it.getNode() } + .map { it.getNode()?.asWritableNode() } .filterIsInstance() .map { it.model } .firstOrNull() ?: return emptyList() From 810bee8569324825bcf2fc086648c8293f752019 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 13 Nov 2026 16:10:08 +0100 Subject: [PATCH 16/23] feat(projectional-editor): type code the way it is written in a text editor Typing baseLanguage code key by key, as in a text editor, now ends up as the code that was typed. All of it is derived from the notations, none of it is declared for baseLanguage: - After a completion created nodes around what was typed, the caret goes to the first slot that still needs input: `int abc` is a declaration of abc, not an `int` cell with the text `intabc`. - A completion is applied automatically only if no longer one can still be typed: `do` isn't the do-while loop as long as it can become a `double`. - A key that starts a new token applies the only match of the text before it and is typed again behind it, as in `x=x+1`. If several match, the one whose next child can start with that key is applied: `(1` is a parenthesized expression, because a type can't start with `1`. - Typing a constant that is already there moves the caret over it, so `if (`, `x)`, `{` and the `:` of a ternary don't end up as text that means nothing. - Spaces where nothing can hold them are dropped. - Side transforms don't apply to text that is still being typed, or that is still the text of a substitution, like the `1.` of `1.5`. A side transform only wraps a node if everything in front of the typed text is there: `)` behind `a` doesn't make it `typeof(a)`. - The same action is offered once, without wrappers where none are needed, and a concept wins over its sub-concepts that are written the same way. - New nodes get their mandatory children that leave no choice, like the body of an `if`, as MPS does. - A side transform menu whose text is deleted again closes, and one that matches nothing anymore applies what was typed before a space: `else {`. - Deleting undoes typing: deleting in the empty operand of `a + <>` gives `a`, `!<>` and `return <>` are removed, an empty slot in an optional part of the notation removes that part, a node whose last character is deleted leaves its empty slot, and a property without text is unset. - Typing a different operator over the one of a node turns it into the concept whose notation only differs in that constant, keeping the operands: `a + b` becomes `a - b`. BaseLanguageTypingTest covers these gestures. The existing tests pressed TAB after typing a type to get to the name, where the caret now already is. Co-Authored-By: Claude Opus 5.5 --- .../editor/ssr/mps/BaseLanguageTestBase.kt | 197 ++++++++++ .../editor/ssr/mps/BaseLanguageTests.kt | 199 +--------- .../editor/ssr/mps/BaseLanguageTypingTest.kt | 259 +++++++++++++ .../org/modelix/editor/CaretPositionPolicy.kt | 30 ++ .../org/modelix/editor/CellProperties.kt | 6 + .../org/modelix/editor/CodeCompletionMenu.kt | 43 ++- .../modelix/editor/FrontendEditorComponent.kt | 6 + .../kotlin/org/modelix/editor/ICellAction.kt | 13 +- .../org/modelix/editor/INonExistingNode.kt | 5 + .../kotlin/org/modelix/editor/NodeCreation.kt | 54 +++ .../editor/celltemplate/CellTemplate.kt | 5 + .../editor/celltemplate/ChildCellTemplate.kt | 67 +++- .../celltemplate/ConstantCellTemplate.kt | 7 +- .../celltemplate/InstantiateNodeCellAction.kt | 3 +- .../InstantiateNodeCompletionAction.kt | 15 +- .../celltemplate/PropertyCellTemplate.kt | 18 +- .../celltemplate/ReferenceCellTemplate.kt | 30 +- .../celltemplate/ReplaceConstantActions.kt | 104 +++++ .../text/backend/TextEditorServiceImpl.kt | 361 ++++++++++++++++-- .../editor/text/shared/TextEditorService.kt | 5 + 20 files changed, 1180 insertions(+), 247 deletions(-) create mode 100644 projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTestBase.kt create mode 100644 projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTypingTest.kt create mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/NodeCreation.kt create mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ReplaceConstantActions.kt diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTestBase.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTestBase.kt new file mode 100644 index 00000000..1498439e --- /dev/null +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTestBase.kt @@ -0,0 +1,197 @@ +package org.modelix.editor.ssr.mps + +import com.intellij.openapi.diagnostic.debug +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import org.modelix.editor.CaretSelection +import org.modelix.editor.ChildNodeCellReference +import org.modelix.editor.CodeCompletionParameters +import org.modelix.editor.EditorEngine +import org.modelix.editor.FrontendEditorComponent +import org.modelix.editor.ICodeCompletionAction +import org.modelix.editor.ICodeCompletionActionProvider +import org.modelix.editor.JSKeyboardEvent +import org.modelix.editor.JSKeyboardEventType +import org.modelix.editor.KnownKeys +import org.modelix.editor.NodeCellReference +import org.modelix.editor.applyShadowing +import org.modelix.editor.descendantsAndSelf +import org.modelix.editor.flattenApplicableActions +import org.modelix.editor.getCompletionPattern +import org.modelix.editor.getMaxCaretPos +import org.modelix.editor.getSubstituteActions +import org.modelix.editor.lastLeaf +import org.modelix.editor.layoutable +import org.modelix.editor.text.backend.TextEditorServiceImpl +import org.modelix.editor.text.frontend.getVisibleText +import org.modelix.editor.text.shared.celltree.ICellTree +import org.modelix.incremental.IncrementalEngine +import org.modelix.model.api.INode +import org.modelix.model.api.IWritableNode +import org.modelix.model.mpsadapters.MPSArea +import org.modelix.model.mpsadapters.MPSWritableNode + +/** + * Opens the class of the test project in an editor that uses the notations of baseLanguage, and offers the gestures + * of a user typing into it. + */ +@Suppress("ktlint:standard:wrapping", "ktlint:standard:trailing-comma-on-call-site") +abstract class BaseLanguageTestBase : TestBase("SimpleProject") { + lateinit var editor: FrontendEditorComponent + lateinit var service: TextEditorServiceImpl + lateinit var mpsIntegration: EditorIntegrationForMPS + lateinit var editorEngine: EditorEngine + lateinit var incrementalEngine: IncrementalEngine + lateinit var classNode: MPSWritableNode + lateinit var coroutineScope: CoroutineScope + + protected fun getBackend() = service.getAllEditorBackends().single() + + override fun setUp() { + super.setUp() + println("Running test " + getTestName(false)) + + readAction { + val solution = mpsProject.projectModules.first { it.moduleName == "Solution1" } + val model = solution.models.first() + classNode = model.rootNodes.first().let { MPSWritableNode(it) } + } + + incrementalEngine = IncrementalEngine() + editorEngine = EditorEngine(incrementalEngine) + mpsIntegration = EditorIntegrationForMPS(editorEngine) + mpsIntegration.init(mpsProject.repository) + coroutineScope = CoroutineScope(Dispatchers.Default) + service = TextEditorServiceImpl(editorEngine, MPSArea(mpsProject.repository).asModel(), coroutineScope) + editor = FrontendEditorComponent(service) + runBlocking { + editor.openNode(classNode.getNodeReference()).await() + editor.flush() + println(editor.getRootCell().layout.toString()) + } + } + + override fun tearDown() { + editor.dispose() + mpsIntegration.dispose() + editorEngine.dispose() + incrementalEngine.dispose() + super.tearDown() + } + + protected fun ICellTree.Cell.backend() = service.getEditorBackend(editor.editorId).tree.getCell(getId()) + + suspend fun assertFinalEditorText(expected: String) { + assertEditorText(expected) + + // Reset all editor state to ensure the typed text triggered a model transformation. + editor.resetState() + assertEditorText(expected) + } + + fun assertCaretPosition(cellTextWithCaret: String) { + val selection = checkNotNull(editor.getSelection()) { "No active selection" } + if (selection !is CaretSelection) error("Not a caret selection: $selection") + assertEquals(cellTextWithCaret, selection.toString()) + } + + suspend fun assertEditorText(expected: String) { + editor.flush() + assertEquals( + expected.normalizedEditorText(), + editor + .getRootCell() + .layout + .toString() + .normalizedEditorText() + ) + } + + suspend fun placeCaretAtEnd(node: INode) { + val cell = editor.resolveCell(NodeCellReference(node.reference)).first() + val lastLeafCell = cell.lastLeaf() + editor.changeSelection(CaretSelection(lastLeafCell.layoutable()!!, lastLeafCell.getMaxCaretPos())) + } + + protected fun childOf( + node: IWritableNode, + role: String, + ) = readAction { node.getAllChildren().first { it.getContainmentLink().getSimpleName() == role } } + + protected val methodNode: IWritableNode get() = childOf(classNode, "member") + + protected val methodBodyNode: IWritableNode get() = childOf(methodNode, "body") + + /** + * Puts the caret into the placeholder of an empty child link. + * + * It used to be reachable through [placeCaretIntoCellWithText] by its `` text, but a notation can + * now say what an empty link renders as - the baseLanguage ones render nothing, like MPS - so the placeholder + * is resolved through the cell reference it carries instead of through what it shows. + */ + fun placeCaretIntoPlaceholderOf( + node: IWritableNode, + linkName: String, + ) { + val link = readAction { checkNotNull(node.tryGetConcept()).getAllChildLinks().first { it.getSimpleName() == linkName } } + val cell = + editor.resolveCell(ChildNodeCellReference(node.getNodeReference(), link.toReference())).firstOrNull() + ?: throw NoSuchElementException("No placeholder cell for the empty $linkName of $node") + editor.doChangeSelection(CaretSelection(cell.layoutable()!!, cell.getMaxCaretPos())) + } + + fun placeCaretIntoCellWithText( + text: String, + position: Int = -1, + ) { + val cell = editor.getRootCell().descendantsAndSelf().firstOrNull { it.getVisibleText() == text } + if (cell == null) { + editor.getRootCell().descendantsAndSelf().forEach { + println("$it: ${it.getVisibleText()}") + } + throw NoSuchElementException("Cell with text not found: $text") + } + editor.doChangeSelection(CaretSelection(cell.layoutable()!!, if (position == -1) cell.getMaxCaretPos() else position)) + } + + suspend fun pressEnter() = pressKey(KnownKeys.Enter) + + suspend fun pressKey(key: KnownKeys) { + editor.processKeyEvent(JSKeyboardEvent(JSKeyboardEventType.KEYDOWN, key)) + } + + suspend fun typeText(text: CharSequence) { + for (c in text) { + LOG.debug { "type: $c" } + editor + .enqueueUIEvent( + JSKeyboardEvent( + eventType = JSKeyboardEventType.KEYDOWN, + typedText = c.toString(), + knownKey = null, + rawKey = c.toString(), + ), + ).await() + editor.flushLocalLater().await() + } + } + + fun getCodeCompletionEntries(pattern: String): List = + readAction { + val selection = editor.getSelection() as CaretSelection + val actionProviders: Sequence = + selection.layoutable.cell + .backend() + .getSubstituteActions() + val actions = actionProviders.flatMap { it.flattenApplicableActions(CodeCompletionParameters(getBackend(), pattern)) }.toList() + val matchingActions = + actions.filter { + val matchingText = it.getCompletionPattern() + matchingText.isNotEmpty() && matchingText.startsWith(pattern) + } + val shadowedActions = matchingActions.applyShadowing() + val sortedActions = shadowedActions.sortedBy { it.getCompletionPattern().lowercase() } + sortedActions + } +} diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index fae7394a..4ab01693 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -1,23 +1,14 @@ package org.modelix.editor.ssr.mps import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.diagnostic.debug -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.runBlocking import org.modelix.checks.CheckMessage import org.modelix.checks.CheckSeverity import org.modelix.editor.CaretSelection -import org.modelix.editor.ChildNodeCellReference import org.modelix.editor.CodeCompletionParameters import org.modelix.editor.CommonCellProperties import org.modelix.editor.ContextActionsAspect import org.modelix.editor.ContextActionsMenu -import org.modelix.editor.EditorEngine -import org.modelix.editor.FrontendEditorComponent import org.modelix.editor.IActionOrProvider -import org.modelix.editor.ICodeCompletionAction -import org.modelix.editor.ICodeCompletionActionProvider import org.modelix.editor.IContextActionsProvider import org.modelix.editor.JSKeyboardEvent import org.modelix.editor.JSKeyboardEventType @@ -26,20 +17,12 @@ import org.modelix.editor.Modifiers import org.modelix.editor.NodeCellReference import org.modelix.editor.NodeContextActions import org.modelix.editor.ReferencedNodeCellReference -import org.modelix.editor.ancestors -import org.modelix.editor.applyShadowing import org.modelix.editor.descendantsAndSelf -import org.modelix.editor.flattenApplicableActions import org.modelix.editor.getCompletionPattern -import org.modelix.editor.getMaxCaretPos -import org.modelix.editor.getSubstituteActions -import org.modelix.editor.lastLeaf import org.modelix.editor.layoutable -import org.modelix.editor.text.backend.TextEditorServiceImpl import org.modelix.editor.text.frontend.getVisibleText import org.modelix.editor.text.shared.ActionIcon import org.modelix.editor.text.shared.CompletionMenuEntryData -import org.modelix.editor.text.shared.celltree.ICellTree import org.modelix.incremental.IncrementalEngine import org.modelix.model.api.ConceptReference import org.modelix.model.api.IChildLinkReference @@ -48,7 +31,6 @@ import org.modelix.model.api.IPropertyReference import org.modelix.model.api.IReferenceLinkReference import org.modelix.model.api.IWritableNode import org.modelix.model.api.getDescendants -import org.modelix.model.mpsadapters.MPSArea import org.modelix.model.mpsadapters.MPSWritableNode import org.modelix.model.mpsadapters.tomps.ModelixNodeAsMPSNode import org.modelix.mps.editor.common.IncrementalModelChecker @@ -57,164 +39,7 @@ import org.modelix.mps.editor.common.IncrementalModelChecker * Test editor for MPS baseLanguage ClassConcept */ @Suppress("ktlint:standard:wrapping", "ktlint:standard:trailing-comma-on-call-site", "ktlint:standard:function-naming") -class BaseLanguageTests : TestBase("SimpleProject") { - lateinit var editor: FrontendEditorComponent - lateinit var service: TextEditorServiceImpl - lateinit var mpsIntegration: EditorIntegrationForMPS - lateinit var editorEngine: EditorEngine - lateinit var incrementalEngine: IncrementalEngine - lateinit var classNode: MPSWritableNode - lateinit var coroutineScope: CoroutineScope - - private fun getBackend() = service.getAllEditorBackends().single() - - override fun setUp() { - super.setUp() - println("Running test " + getTestName(false)) - - readAction { - val solution = mpsProject.projectModules.first { it.moduleName == "Solution1" } - val model = solution.models.first() - classNode = model.rootNodes.first().let { MPSWritableNode(it) } - } - - incrementalEngine = IncrementalEngine() - editorEngine = EditorEngine(incrementalEngine) - mpsIntegration = EditorIntegrationForMPS(editorEngine) - mpsIntegration.init(mpsProject.repository) - coroutineScope = CoroutineScope(Dispatchers.Default) - service = TextEditorServiceImpl(editorEngine, MPSArea(mpsProject.repository).asModel(), coroutineScope) - editor = FrontendEditorComponent(service) - runBlocking { - editor.openNode(classNode.getNodeReference()).await() - editor.flush() - println(editor.getRootCell().layout.toString()) - } - } - - override fun tearDown() { - editor.dispose() - mpsIntegration.dispose() - editorEngine.dispose() - incrementalEngine.dispose() - super.tearDown() - } - - private fun ICellTree.Cell.backend() = service.getEditorBackend(editor.editorId).tree.getCell(getId()) - - suspend fun assertFinalEditorText(expected: String) { - assertEditorText(expected) - - // Reset all editor state to ensure the typed text triggered a model transformation. - editor.resetState() - assertEditorText(expected) - } - - fun assertCaretPosition(cellTextWithCaret: String) { - val selection = checkNotNull(editor.getSelection()) { "No active selection" } - if (selection !is CaretSelection) error("Not a caret selection: $selection") - assertEquals(cellTextWithCaret, selection.toString()) - } - - suspend fun assertEditorText(expected: String) { - editor.flush() - assertEquals( - expected.normalizedEditorText(), - editor - .getRootCell() - .layout - .toString() - .normalizedEditorText() - ) - } - - suspend fun placeCaretAtEnd(node: INode) { - val cell = editor.resolveCell(NodeCellReference(node.reference)).first() - val lastLeafCell = cell.lastLeaf() - editor.changeSelection(CaretSelection(lastLeafCell.layoutable()!!, lastLeafCell.getMaxCaretPos())) - } - - private fun childOf( - node: IWritableNode, - role: String, - ) = readAction { node.getAllChildren().first { it.getContainmentLink().getSimpleName() == role } } - - private val methodNode: IWritableNode get() = childOf(classNode, "member") - - private val methodBodyNode: IWritableNode get() = childOf(methodNode, "body") - - /** - * Puts the caret into the placeholder of an empty child link. - * - * It used to be reachable through [placeCaretIntoCellWithText] by its `` text, but a notation can - * now say what an empty link renders as - the baseLanguage ones render nothing, like MPS - so the placeholder - * is resolved through the cell reference it carries instead of through what it shows. - */ - fun placeCaretIntoPlaceholderOf( - node: IWritableNode, - linkName: String, - ) { - val link = readAction { checkNotNull(node.tryGetConcept()).getAllChildLinks().first { it.getSimpleName() == linkName } } - val cell = - editor.resolveCell(ChildNodeCellReference(node.getNodeReference(), link.toReference())).firstOrNull() - ?: throw NoSuchElementException("No placeholder cell for the empty $linkName of $node") - editor.doChangeSelection(CaretSelection(cell.layoutable()!!, cell.getMaxCaretPos())) - } - - fun placeCaretIntoCellWithText( - text: String, - position: Int = -1, - ) { - val cell = editor.getRootCell().descendantsAndSelf().firstOrNull { it.getVisibleText() == text } - if (cell == null) { - editor.getRootCell().descendantsAndSelf().forEach { - println("$it: ${it.getVisibleText()}") - } - throw NoSuchElementException("Cell with text not found: $text") - } - editor.doChangeSelection(CaretSelection(cell.layoutable()!!, if (position == -1) cell.getMaxCaretPos() else position)) - } - - suspend fun pressEnter() = pressKey(KnownKeys.Enter) - - suspend fun pressKey(key: KnownKeys) { - editor.processKeyEvent(JSKeyboardEvent(JSKeyboardEventType.KEYDOWN, key)) - } - - suspend fun typeText(text: CharSequence) { - for (c in text) { - LOG.debug { "type: $c" } - editor - .enqueueUIEvent( - JSKeyboardEvent( - eventType = JSKeyboardEventType.KEYDOWN, - typedText = c.toString(), - knownKey = null, - rawKey = c.toString(), - ), - ).await() - editor.flushLocalLater().await() - } - } - - fun getCodeCompletionEntries(pattern: String): List = - readAction { - val selection = editor.getSelection() as CaretSelection - val actionProviders: Sequence = - selection.layoutable.cell - .backend() - .getSubstituteActions() - val actions = actionProviders.flatMap { it.flattenApplicableActions(CodeCompletionParameters(getBackend(), pattern)) }.toList() - val matchingActions = - actions.filter { - val matchingText = it.getCompletionPattern() - matchingText.isNotEmpty() && matchingText.startsWith(pattern) - } - val shadowedActions = matchingActions.applyShadowing() - val sortedActions = shadowedActions.sortedBy { it.getCompletionPattern().lowercase() } - sortedActions - } - +class BaseLanguageTests : BaseLanguageTestBase() { fun `test initial editor`() = kotlinx.coroutines.test.runTest { assertFinalEditorText(""" @@ -254,6 +79,9 @@ class BaseLanguageTests : TestBase("SimpleProject") { actions.map { it.getCompletionPattern() + " | " + it.getDescription() }, ) typeText("int ") + editor.flush() + // Nothing is left to type in `int`, so typing goes on with the name. + assertCaretPosition("|") assertFinalEditorText(""" public class Class1 { public void method1() { @@ -267,7 +95,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodBodyNode, "statement") typeText("int ") - pressKey(KnownKeys.Tab) typeText("abc") assertFinalEditorText(""" public class Class1 { @@ -282,7 +109,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodBodyNode, "statement") typeText("int ") - pressKey(KnownKeys.Tab) typeText("abc") typeText("=") assertEditorText(""" @@ -299,7 +125,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodBodyNode, "statement") typeText("int ") - pressKey(KnownKeys.Tab) typeText("abc") pressKey(KnownKeys.Tab) assertEditorText(""" @@ -316,11 +141,9 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodBodyNode, "statement") typeText("int ") - pressKey(KnownKeys.Tab) typeText("abc") pressKey(KnownKeys.Enter) typeText("int ") - pressKey(KnownKeys.Tab) typeText("def") placeCaretIntoCellWithText("abc") @@ -362,7 +185,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodBodyNode, "statement") typeText("int ") - pressKey(KnownKeys.Tab) typeText("abc") typeText("=") typeText("10") @@ -379,7 +201,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodNode, "parameter") typeText("int") - pressKey(KnownKeys.Tab) typeText("p1") pressKey(KnownKeys.Enter) assertEditorText(""" @@ -390,7 +211,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { } """) typeText("int") - pressKey(KnownKeys.Tab) typeText("p2") assertFinalEditorText(""" public class Class1 { @@ -405,11 +225,9 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodNode, "parameter") typeText("int") - pressKey(KnownKeys.Tab) typeText("p1") typeText(",") typeText("int") - pressKey(KnownKeys.Tab) typeText("p2") assertFinalEditorText(""" public class Class1 { @@ -425,16 +243,13 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodNode, "parameter") typeText("int") - pressKey(KnownKeys.Tab) typeText("p1") typeText(",") typeText("int") - pressKey(KnownKeys.Tab) typeText("p2") placeCaretIntoCellWithText("p1") typeText(",") typeText("int") - pressKey(KnownKeys.Tab) typeText("p3") assertFinalEditorText(""" public class Class1 { @@ -473,7 +288,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodNode, "parameter") typeText("int") - pressKey(KnownKeys.Tab) typeText("p1") assertEditorText(""" public class Class1 { @@ -502,7 +316,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodNode, "parameter") typeText("int") - pressKey(KnownKeys.Tab) typeText("p1") assertEditorText(""" public class Class1 { @@ -526,7 +339,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { kotlinx.coroutines.test.runTest { placeCaretIntoPlaceholderOf(methodNode, "parameter") typeText("int") - pressKey(KnownKeys.Tab) typeText("p1") pressKey(KnownKeys.Enter) assertEditorText(""" @@ -558,7 +370,7 @@ class BaseLanguageTests : TestBase("SimpleProject") { } } """) - pressKey(KnownKeys.Tab) + assertCaretPosition("|") typeText("abc") assertEditorText(""" public class Class1 { @@ -1061,7 +873,6 @@ class BaseLanguageTests : TestBase("SimpleProject") { // The initializer of an int variable can't be a boolean, which MPS can fix by adding a cast. placeCaretIntoPlaceholderOf(methodBodyNode, "statement") typeText("int ") - pressKey(KnownKeys.Tab) typeText("abc") typeText("=") typeText("true") diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTypingTest.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTypingTest.kt new file mode 100644 index 00000000..6022919a --- /dev/null +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTypingTest.kt @@ -0,0 +1,259 @@ +package org.modelix.editor.ssr.mps + +import org.modelix.editor.CaretSelection +import org.modelix.editor.KnownKeys +import org.modelix.editor.descendantsAndSelf +import org.modelix.editor.layoutable +import org.modelix.editor.text.frontend.getVisibleText + +/** + * Typing baseLanguage code the way it's written in a text editor, key by key, and editing it again. + * + * None of this is declared in the notations of baseLanguage. All of it is derived from them: the caret goes where + * typing continues, constants that are already there are typed over, a side transform only applies to text that + * doesn't belong to the cell anymore, and deleting undoes what typing did. + */ +@Suppress("ktlint:standard:wrapping", "ktlint:standard:function-naming") +class BaseLanguageTypingTest : BaseLanguageTestBase() { + /** + * Types [text] into the empty body of `method1` and checks the statements that result. + */ + private suspend fun typeIntoBody( + text: String, + expectedStatements: String, + final: Boolean = true, + ) { + placeCaretIntoPlaceholderOf(methodBodyNode, "statement") + typeText(text) + assertBody(expectedStatements, final) + } + + /** + * The body of `method1` as it is shown, and with [final] also after resetting the state of the editor, which + * proves that the model holds it. That hides again the optional parts of the notation that are only shown + * because the user started to fill them in, like the `= ` that typing `=` shows. + */ + private suspend fun assertBody( + expectedStatements: String, + final: Boolean = true, + ) { + val indented = expectedStatements.trimIndent().lines().joinToString("\n") { " $it" } + val expected = "public class Class1 {\n public void method1() {\n$indented\n }\n}" + if (final) assertFinalEditorText(expected) else assertEditorText(expected) + } + + private fun selectTextOfCell(text: String) { + val cell = editor.getRootCell().descendantsAndSelf().first { it.getVisibleText() == text } + editor.doChangeSelection(CaretSelection(editor, cell.layoutable()!!, 0, text.length)) + } + + // Typing continues where the created nodes still need input. + + fun `test typing a declaration in one go`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int abc", "int abc;") + } + + fun `test typing a declaration with an initializer`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int abc = 10;", "int abc = 10;") + } + + fun `test typing a declaration of a class type`() = + kotlinx.coroutines.test.runTest { + // ClassifierType and InferredClassifierType write java.lang.String the same way. The general concept wins. + typeIntoBody("String s", "String s;") + } + + fun `test a keyword that is the start of another one is not applied too early`() = + kotlinx.coroutines.test.runTest { + // `do` is a complete do-while loop, but it may still become a `double`. + typeIntoBody("double d=1.5", "double d = 1.5;") + } + + fun `test spaces between tokens are ignored`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("return 1;", "return 1;") + } + + // A typed character that starts a new token completes what was typed before. + + fun `test typing an assignment to a variable`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x", "int x;") + pressEnter() + typeText("x=x+1;") + assertBody(""" + int x; + x = x + 1; + """) + } + + fun `test typing a reference to a variable`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int a=1;", "int a = 1;") + pressEnter() + typeText("int b=a+1;") + assertBody(""" + int a = 1; + int b = a + 1; + """) + } + + fun `test typing a boolean expression`() = + kotlinx.coroutines.test.runTest { + // The `f` of `false` must not be taken as the start of an operator behind it. + typeIntoBody("boolean b=true&&false||1<=2", "boolean b = true && false || 1 <= 2;") + } + + fun `test typing operators that share their first character`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("boolean b=1==2", "boolean b = 1 == 2;") + } + + fun `test typing a parenthesized expression`() = + kotlinx.coroutines.test.runTest { + // `(` can start a cast as well, but a type can't start with `1`. + typeIntoBody("int x=(1+2)*3;", "int x = (1 + 2) * 3;") + } + + fun `test typing a floating point number`() = + kotlinx.coroutines.test.runTest { + // `1.` is still a number, it's not the `.` of a method call on `1`. + typeIntoBody("double d=1.5;", "double d = 1.5;") + } + + // Constants that are already there are typed over. + + fun `test typing the brackets of an if statement`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("if(true){int a", """ + if (true) { + int a; + } + """) + } + + fun `test typing a while loop`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("while(true){break", """ + while (true) { + break; + } + """) + } + + fun `test typing a ternary operator`() = + kotlinx.coroutines.test.runTest { + // The `:` is the one of the ternary that is already there, not a new ternary around `1`. + typeIntoBody("int x=true?1:2;", "int x = true ? 1 : 2;") + } + + fun `test typing an else branch`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("if(true)", """ + if (true) { + + } + """) + placeCaretIntoCellWithText("}", 1) + typeText("else {int a") + assertBody(""" + if (true) { + + } else { + int a; + } + """) + } + + fun `test typing an else if branch`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("if(true)", """ + if (true) { + + } + """) + placeCaretIntoCellWithText("}", 1) + typeText("else if(false)") + assertBody(""" + if (true) { + + } else if (false) { + + } + """) + } + + // Deleting undoes what typing did. + + fun `test deleting the last digit of a number leaves the empty slot`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=1", "int x = 1;", final = false) + pressKey(KnownKeys.Backspace) + assertBody("int x = ;", final = false) + assertCaretPosition("|") + // Typing goes on in the slot. + typeText("5") + assertBody("int x = 5;") + } + + fun `test deleting in an empty initializer removes it`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=", "int x = ;", final = false) + pressKey(KnownKeys.Backspace) + assertBody("int x;", final = false) + assertCaretPosition("x|") + } + + fun `test deleting the name of a variable shows that it is missing`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x", "int x;") + pressKey(KnownKeys.Backspace) + assertBody("int ;") + } + + fun `test deleting in the empty operand of a binary operation removes the operation`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=1+2", "int x = 1 + 2;") + pressKey(KnownKeys.Backspace) + assertBody("int x = 1 + ;") + pressKey(KnownKeys.Backspace) + assertBody("int x = 1;") + assertCaretPosition("1|") + } + + fun `test deleting in the empty operand of a unary operation removes it`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("boolean b=!", "boolean b = !;", final = false) + pressKey(KnownKeys.Backspace) + assertBody("boolean b = ;", final = false) + } + + fun `test deleting a return statement`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("return 1", "return 1;") + pressKey(KnownKeys.Backspace) + pressKey(KnownKeys.Backspace) + assertBody("") + } + + // Typing a different operator over the one that is there keeps the operands. + + fun `test replacing an operator by typing over it`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=1+2", "int x = 1 + 2;") + selectTextOfCell("+") + typeText("*") + assertBody("int x = 1 * 2;") + } + + fun `test replacing an operator after deleting it`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=1+2", "int x = 1 + 2;") + placeCaretIntoCellWithText("+", 1) + pressKey(KnownKeys.Backspace) + typeText("-") + assertBody("int x = 1 - 2;") + } +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CaretPositionPolicy.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CaretPositionPolicy.kt index 074383c4..495fd5f2 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CaretPositionPolicy.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CaretPositionPolicy.kt @@ -73,6 +73,36 @@ data class CaretPositionPolicy( private fun isAvoided(cell: ICellTree.Cell) = cell.cellReferences.intersect(avoidedCellRefs).isNotEmpty() } +/** + * Where typing continues after the editor created nodes for text that was typed: the first cell from [start] on that + * is still waiting for input - an empty tab target - as long as it is inside [container]. + * + * Typing `int ` where a statement is expected creates a whole `int ;` declaration around the type. Nothing is + * left to type inside `int`, so the caret goes on to the name, where the next key belongs. Inside a node that has a + * slot of its own, like the `` of a `return`, the caret goes there. + * + * Without such a cell, the caret goes to the end of [start], as with a [CaretPositionPolicy] for it. + */ +@Serializable +data class ContinueTypingPolicy( + val start: CellReference, + val container: CellReference, +) : ICaretPositionPolicy { + override fun getBestSelection(editor: FrontendEditorComponent): CaretSelection? { + val startCell = editor.resolveCell(start).firstOrNull() + if (startCell != null) { + val containerCell = editor.resolveCell(container).firstOrNull { startCell.ancestors(true).contains(it) } + val after = if (containerCell == null) emptySequence() else startCell.nextCells().takeWhile { it != containerCell } + val target = + (startCell.descendantsAndSelf() + after) + .filter { it.isTabTarget() && it.getSelectableText().isNullOrEmpty() } + .firstNotNullOfOrNull { editor.resolveLayoutable(it) } + if (target != null) return CaretSelection(editor, target, 0) + } + return CaretPositionPolicy(start).getBestSelection(editor) + } +} + enum class CaretPositionType { START, END, diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellProperties.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellProperties.kt index 3b107b95..d489a4c4 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellProperties.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellProperties.kt @@ -200,6 +200,12 @@ object CommonCellProperties { val codeCompletionText = StringCellPropertyKey("code-completion-text", null) // empty string hides the entry val isForceShown = BooleanCellPropertyKey("force-shown", false) val node = BackendCellPropertyKey("node", null) // set on the root cell of a node + + /** + * Set on the cell of a constant of a notation, a keyword or a bracket. Typing its text right in front of it just + * moves the caret over it, the way it's typed in a text editor. + */ + val constant = BackendCellPropertyKey("constant", false) val cellCall = BackendCellPropertyKey("cell-call", null) // set on the root cell of a cell call val cellReferences = CellReferenceListPropertyKey diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt index 00de0466..94557d24 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CodeCompletionMenu.kt @@ -27,6 +27,11 @@ class CodeCompletionMenu( } override suspend fun onPatternEdited() { + // A menu that typing next to a cell opened shows what can follow the typed text. Without it, it's taken back. + if (completionPosition != CompletionPosition.CENTER && patternEditor.pattern.isEmpty()) { + editor.closeActionMenu() + return + } updateEntries() executeIfSingleAction() } @@ -50,6 +55,30 @@ class CodeCompletionMenu( } } else { onPatternEdited() + if (filteredEntries.isEmpty()) applyCompletedText(oldTextBeforeCaret) + } + } + + /** + * Nothing matches anymore after the user went on typing behind a space. What was typed before the space is + * complete if one entry is written exactly like it: `else` of `else {`, which can't be told apart from `else if` + * before the `{`. That entry is applied, and the rest is typed again behind it. + */ + private suspend fun applyCompletedText(oldTextBeforeCaret: String) { + val completedText = oldTextBeforeCaret.trimEnd() + if (completedText.isEmpty() || completedText == oldTextBeforeCaret) return + val remainingText = patternEditor.pattern.substring(completedText.length).trimStart() + editor.updateCodeCompletionActions(getAnchor().cell, completedText) + val entry = allEntries.singleOrNull { it.matchesExactly(completedText) } + if (entry == null) { + updateEntries() + return + } + execute(entry) + if (remainingText.isNotEmpty()) { + editor.enqueueUpdate { + (editor.getSelection() as? CaretSelection)?.processTypedText(remainingText) + } } } @@ -224,8 +253,16 @@ fun List.applyShadowing(): List = it.getCompletionPattern() }.flatMap { applyShadowingToGroup(it.value) } -private fun applyShadowingToGroup(actions: List): List = - actions.filter { a1 -> - val isShadowed = actions.any { a2 -> a2 !== a1 && (a2.shadows(a1) || a1.shadowedBy(a2)) } +/** + * Two actions that shadow each other do the same, so only the first one of them is kept. + */ +private fun applyShadowingToGroup(actions: List): List { + fun ICodeCompletionAction.isShadowedBy(other: ICodeCompletionAction) = other.shadows(this) || shadowedBy(other) + return actions.filterIndexed { index, a1 -> + val isShadowed = + actions.withIndex().any { (otherIndex, a2) -> + a2 !== a1 && a1.isShadowedBy(a2) && (otherIndex < index || !a2.isShadowedBy(a1)) + } !isShadowed } +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt index e342855f..e7132356 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/FrontendEditorComponent.kt @@ -162,6 +162,12 @@ open class FrontendEditorComponent( if (updateData.selectionChange != null) { state.setSelection(updateData.selectionChange) } + val textToRetype = updateData.textToRetype + if (!textToRetype.isNullOrEmpty()) { + eventQueue.enqueue(UIEventType.Generic) { + (state.getSelection() as? CaretSelection)?.processTypedText(textToRetype) + } + } return eventQueue.enqueue(UIEventType.Html) { state.updateHtml() } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt index fa038276..5227b223 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt @@ -1,11 +1,14 @@ package org.modelix.editor +import org.modelix.constraints.ConstraintsAspect import org.modelix.editor.celltemplate.NotationRootCellTemplate import org.modelix.editor.celltemplate.getAttributeSideTransformActions import org.modelix.editor.celltemplate.hasSymbolsBesideAttributedCell import org.modelix.editor.text.backend.BackendEditorComponent +import org.modelix.model.api.IChildLink import org.modelix.model.api.INode import org.modelix.model.api.getInstantiatableSubConcepts +import org.modelix.model.api.index interface ICellAction { fun isApplicable(): Boolean @@ -74,7 +77,15 @@ class SideTransformNode( fun getWrapperActions(engine: EditorEngine): List { val location = ExistingNode(node) val expectedConcept = location.expectedConcept() ?: return emptyList() - val allowedConcepts = expectedConcept.getInstantiatableSubConcepts() + // The wrapper takes the place of the node, so it has to be allowed there, as for a substitution. + val parent = node.parent + val link = node.asWritableNode().getContainmentLinkDefinition() as? IChildLink + val wrapperLocation = if (parent != null && link != null) NonExistingChild(ExistingNode(parent), link, node.index()) else null + val allowedConcepts = + expectedConcept.getInstantiatableSubConcepts().filter { concept -> + wrapperLocation == null || + runCatching { ConstraintsAspect.canCreate(wrapperLocation.replacement(concept)) }.getOrElse { true } + } val cellModels = allowedConcepts.map { concept -> engine.createCellModel(concept) diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/INonExistingNode.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/INonExistingNode.kt index a04ba641..e80f9ee4 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/INonExistingNode.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/INonExistingNode.kt @@ -78,6 +78,11 @@ data class NodeReplacement( fun INonExistingNode.replacement(newConcept: IConcept): INonExistingNode = NodeReplacement(this, newConcept) +/** + * The place this location is at, independent of the concept a [NodeReplacement] puts there. + */ +fun INonExistingNode.replacedLocation(): INonExistingNode = if (this is NodeReplacement) nodeToReplace.replacedLocation() else this + fun INonExistingNode.coerceOutputConcept(subConcept: IConcept?): IConcept? { val expectedConcept = expectedConcept() return if (subConcept != null) { diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/NodeCreation.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/NodeCreation.kt new file mode 100644 index 00000000..ae9bd973 --- /dev/null +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/NodeCreation.kt @@ -0,0 +1,54 @@ +package org.modelix.editor + +import org.modelix.model.api.INode + +/** + * How many of the ancestors of this location don't exist yet. A completion creates them together with the node: the + * wrappers it puts around what was typed, like the `int ;` declaration around a typed `int`. + */ +fun INonExistingNode.nonExistingAncestorCount(): Int = ancestors().takeWhile { it.getNode() == null }.count() + +/** + * Where the caret goes after [node] was created for what was typed, together with [createdAncestors] levels of + * wrappers around it. Without wrappers it stays in [startCell]. With them, typing continues where the wrappers still + * need input: see [ContinueTypingPolicy]. + */ +fun caretPolicyAfterCreating( + startCell: CellReference, + node: INode, + createdAncestors: Int, +): ICaretPositionPolicy { + if (createdAncestors <= 0) return CaretPositionPolicy(startCell) + val outermost = generateSequence(node) { it.parent }.elementAtOrNull(createdAncestors) ?: return CaretPositionPolicy(startCell) + return ContinueTypingPolicy(startCell, NodeCellReference(outermost.reference)) +} + +/** + * Adds the children that a new node can't do without and that leave no choice: a mandatory single child whose + * concept isn't abstract. That is the `{ }` of an `if` or a `while` - without it, the editor shows a placeholder in + * which the user can't type a statement, only the statement list around it. + * + * MPS initializes a new node the same way (`NodeFactoryManager.createNodeStructure`). Abstract concepts are left to + * the user, who has to choose one anyway. + */ +fun INode.addMissingMandatoryChildren() = addMissingMandatoryChildren(this, HashSet()) + +private fun addMissingMandatoryChildren( + node: INode, + conceptsBeingCreated: MutableSet, +) { + val concept = node.concept ?: return + for (link in concept.getAllChildLinks()) { + if (link.isOptional || link.isMultiple) continue + val targetConcept = link.targetConcept + if (targetConcept.isAbstract()) continue + if (node.getChildren(link).iterator().hasNext()) continue + // A concept that contains itself through mandatory links can't be completed. + if (!conceptsBeingCreated.add(targetConcept.getUID())) continue + try { + addMissingMandatoryChildren(node.addNewChild(link, -1, targetConcept), conceptsBeingCreated) + } finally { + conceptsBeingCreated.remove(targetConcept.getUID()) + } + } +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/CellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/CellTemplate.kt index 0b36a309..e78272a6 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/CellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/CellTemplate.kt @@ -116,6 +116,11 @@ abstract class CellTemplate( if (symbol is ChildCellTemplate && conceptToReplace.isSubConceptOf(symbol.link.targetConcept)) { val prevNextIndex = if (before) index - 1 else index + 1 val prevNextSymbol = symbols.getOrNull(prevNextIndex) ?: return@mapIndexedNotNull null + // Everything the wrapper writes in front of the typed text has to be there already. Typing `+` + // behind `a` makes `a + <>`, typing `!` in front of it makes `!a`. But typing `)` behind `a` is + // no reason to make it `typeof(a)`: nobody typed the `typeof(`. + val symbolsInFront = symbols.take(if (before) prevNextIndex else index) + if (symbolsInFront.any { it !is IOptionalSymbol }) return@mapIndexedNotNull null return@mapIndexedNotNull prevNextSymbol.createWrapperAction(nodeToReplace, symbol.link) } return@mapIndexedNotNull null diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ChildCellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ChildCellTemplate.kt index 108af0dd..bdb7f242 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ChildCellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ChildCellTemplate.kt @@ -30,12 +30,15 @@ import org.modelix.editor.TextCellSpec import org.modelix.editor.after import org.modelix.editor.ancestors import org.modelix.editor.asProvider +import org.modelix.editor.getContainmentLinkDefinition +import org.modelix.editor.isSmodelAttribute import org.modelix.editor.replacement import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.editor.toNonExisting import org.modelix.model.api.IChildLink import org.modelix.model.api.IConcept import org.modelix.model.api.INode +import org.modelix.model.api.index import org.modelix.model.api.remove import org.modelix.parser.AmbiguousNode import org.modelix.parser.ExactConceptSymbol @@ -163,13 +166,17 @@ class ChildCellTemplate( } placeholder.properties[CommonCellProperties.tabTarget] = true placeholder.properties[CellActionProperties.delete] = - object : ICellAction { - override fun execute(editor: BackendEditorComponent): ICaretPositionPolicy? { - context.cellTreeState.substitutionPlaceholderPositions.remove(createCellReference(node)) - return null // Position is updated by the frontend - } + if (isDefaultPlaceholder && !link.isMultiple) { + EmptySlotDeleteAction(node) + } else { + object : ICellAction { + override fun execute(editor: BackendEditorComponent): ICaretPositionPolicy? { + context.cellTreeState.substitutionPlaceholderPositions.remove(createCellReference(node)) + return null // Position is updated by the frontend + } - override fun isApplicable(): Boolean = true + override fun isApplicable(): Boolean = true + } } cell.addChild(placeholder) } @@ -284,6 +291,54 @@ class ChildCellTemplate( optionalCell: TemplateCellReference, ): IActionOrProvider? = ReplaceNodeActionProvider(NonExistingChild(node.toNonExisting(), link)) + /** + * Deleting where a single child is still missing takes back what made the slot appear. + * + * A node that holds just one other child that fits where the node is, was most likely made by wrapping that child, + * like `a + <>` by typing `+` behind `a`. It's replaced by that child again, as MPS does for an empty operand of a + * binary operation. A node that holds nothing else, like `return <>` or `!<>`, is deleted. + * + * Otherwise nothing is deleted here - a node with more content would lose it. The editor then clears the optional + * part of the notation around the slot, if there is one: the `= <>` of `int x = <>`. + */ + inner class EmptySlotDeleteAction( + val node: INode, + ) : ICellAction { + override fun isApplicable(): Boolean = true + + private fun otherContent(): List = node.allChildren.filterNot { it.getContainmentLink()?.isSmodelAttribute() == true } + + private fun childToKeep(): INode? { + val expectedConcept = node.asWritableNode().getContainmentLinkDefinition()?.targetConcept ?: return null + val child = otherContent().singleOrNull() ?: return null + return child.takeIf { child.concept?.isSubConceptOf(expectedConcept) == true } + } + + private fun isEmpty(): Boolean = + otherContent().isEmpty() && + node.getReferenceLinks().none { node.getReferenceTargetRef(it) != null } && + node.getPropertyLinks().none { node.getPropertyValue(it) != null } + + /** + * Whether deleting here changes anything. If not, the editor looks for something around it to delete. + */ + fun hasEffect(): Boolean = node.parent != null && (childToKeep() != null || isEmpty()) + + override fun execute(editor: BackendEditorComponent): ICaretPositionPolicy? { + editor.runWrite { + val parent = node.parent ?: return@runWrite + val childToKeep = childToKeep() + if (childToKeep != null) { + parent.moveChild(node.getContainmentLink()!!, node.index(), childToKeep) + node.remove() + } else if (isEmpty()) { + node.remove() + } + } + return null // The frontend updates the caret position using SavedCaretPosition + } + } + inner class InsertSubstitutionPlaceholderCompletionAction( val index: Int, val separatorText: String, diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ConstantCellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ConstantCellTemplate.kt index 6d2050ef..43a24aaa 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ConstantCellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ConstantCellTemplate.kt @@ -1,9 +1,11 @@ package org.modelix.editor.celltemplate import org.modelix.editor.CaretPositionPolicy +import org.modelix.editor.CellActionProperties import org.modelix.editor.CellCreationContext import org.modelix.editor.ChildNodeCellReference import org.modelix.editor.CodeCompletionParameters +import org.modelix.editor.CommonCellProperties import org.modelix.editor.ConstantCompletionToken import org.modelix.editor.IActionOrProvider import org.modelix.editor.ICodeCompletionAction @@ -43,7 +45,10 @@ class ConstantCellTemplate( override fun createCell( context: CellCreationContext, node: INode, - ) = TextCellSpec(text, "") + ) = TextCellSpec(text, "").also { + it.properties[CommonCellProperties.constant] = true + it.properties[CellActionProperties.substitute] = ReplaceConstantProvider(node, text) + } override fun getInstantiationActions( location: INonExistingNode, diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/InstantiateNodeCellAction.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/InstantiateNodeCellAction.kt index d45f18e1..90505daa 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/InstantiateNodeCellAction.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/InstantiateNodeCellAction.kt @@ -3,6 +3,7 @@ package org.modelix.editor.celltemplate import org.modelix.editor.CaretPositionPolicy import org.modelix.editor.ICellAction import org.modelix.editor.INonExistingNode +import org.modelix.editor.addMissingMandatoryChildren import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.model.api.IConcept @@ -15,7 +16,7 @@ class InstantiateNodeCellAction( override fun execute(editor: BackendEditorComponent): CaretPositionPolicy { val newNode = location.getExistingAncestor()!!.getArea().executeWrite { - location.replaceNode(concept) + location.replaceNode(concept).also { it.addMissingMandatoryChildren() } } return CaretPositionPolicy(newNode) } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/InstantiateNodeCompletionAction.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/InstantiateNodeCompletionAction.kt index 46ee7f55..06749238 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/InstantiateNodeCompletionAction.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/InstantiateNodeCompletionAction.kt @@ -1,8 +1,12 @@ package org.modelix.editor.celltemplate -import org.modelix.editor.CaretPositionPolicy +import org.modelix.editor.ICaretPositionPolicy import org.modelix.editor.ICodeCompletionAction import org.modelix.editor.INonExistingNode +import org.modelix.editor.NodeCellReference +import org.modelix.editor.addMissingMandatoryChildren +import org.modelix.editor.caretPolicyAfterCreating +import org.modelix.editor.nonExistingAncestorCount import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.model.api.IConcept @@ -29,12 +33,15 @@ class InstantiateNodeCompletionAction( override fun getDescription(): String = description - override fun execute(editor: BackendEditorComponent): CaretPositionPolicy? { + override fun execute(editor: BackendEditorComponent): ICaretPositionPolicy? { + val createdAncestors = location.nonExistingAncestorCount() val newNode = location.getExistingAncestor()!!.getArea().executeWrite { - location.replaceNode(concept) + location.replaceNode(concept).also { + generateSequence(it) { it.parent }.take(createdAncestors + 1).forEach { it.addMissingMandatoryChildren() } + } } - return CaretPositionPolicy(newNode) + return caretPolicyAfterCreating(NodeCellReference(newNode.reference), newNode, createdAncestors) } override fun shadowedBy(shadowing: ICodeCompletionAction): Boolean = diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/PropertyCellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/PropertyCellTemplate.kt index 903a352b..d8736f1c 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/PropertyCellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/PropertyCellTemplate.kt @@ -150,6 +150,17 @@ open class PropertyCellTemplate( override fun getDescription(): String = concept.getShortName() + fun getInstantiatedConcept(): IConcept = concept + + /** + * The same value is offered once, without wrappers where none are needed. + */ + override fun shadows(shadowed: ICodeCompletionAction): Boolean = + shadowed is PropertyCellTemplate.WrapPropertyValue && + shadowed.getInstantiatedConcept() == concept && + shadowed.value == value && + (location.nodeCreationDepth() < shadowed.location.nodeCreationDepth() || location == shadowed.location) + override fun execute(editor: BackendEditorComponent): CaretPositionPolicy? { val node = location.getOrCreateNode(concept) node.setPropertyValue(property, storedValue(value)) @@ -160,8 +171,11 @@ open class PropertyCellTemplate( inner class ChangePropertyAction( val node: INode, ) : ITextChangeAction { + /** + * Deleting all of the text unsets the property, so that the cell shows that it's missing again. + */ override fun isValid(value: String?): Boolean { - if (value == null) return true + if (value.isNullOrEmpty()) return true return validateValue(node.toNonExisting(), presentedValue(value)) } @@ -172,7 +186,7 @@ open class PropertyCellTemplate( newText: String, ): Boolean { node.getArea().executeWrite { - node.setPropertyValue(property, storedValue(newText)) + node.setPropertyValue(property, if (newText.isEmpty()) null else storedValue(newText)) } return true } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ReferenceCellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ReferenceCellTemplate.kt index b12aa932..8506d988 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ReferenceCellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ReferenceCellTemplate.kt @@ -2,7 +2,6 @@ package org.modelix.editor.celltemplate import org.modelix.checks.CheckMessageTarget import org.modelix.checks.addCheckMessages -import org.modelix.editor.CaretPositionPolicy import org.modelix.editor.CellActionProperties import org.modelix.editor.CellCreationContext import org.modelix.editor.CellSpecBase @@ -10,6 +9,7 @@ import org.modelix.editor.CodeCompletionParameters import org.modelix.editor.CommonCellProperties import org.modelix.editor.ExistingNode import org.modelix.editor.IActionOrProvider +import org.modelix.editor.ICaretPositionPolicy import org.modelix.editor.ICodeCompletionAction import org.modelix.editor.ICodeCompletionActionProvider import org.modelix.editor.ICompletionTokenOrList @@ -21,6 +21,9 @@ import org.modelix.editor.ReferencedNodeCellReference import org.modelix.editor.TemplateCellReference import org.modelix.editor.TextCellSpec import org.modelix.editor.after +import org.modelix.editor.caretPolicyAfterCreating +import org.modelix.editor.nonExistingAncestorCount +import org.modelix.editor.replacedLocation import org.modelix.editor.replacement import org.modelix.editor.text.backend.BackendEditorComponent import org.modelix.editor.toNonExisting @@ -131,10 +134,31 @@ class ReferenceCellTemplate( override fun getDescription(): String = concept.getShortName() - override fun execute(editor: BackendEditorComponent): CaretPositionPolicy? { + fun getInstantiatedConcept(): IConcept = concept + + /** + * The same target in the same place is written the same way by a concept and by its sub-concepts that don't + * have a notation of their own, so the user can't tell them apart. The more general concept is the one that is + * meant, the specialized one is for a special purpose, like `InferredClassifierType` of `ClassifierType`. + * The same reference in the same place is offered once, without wrappers where none are needed. + */ + override fun shadows(shadowed: ICodeCompletionAction): Boolean { + if (shadowed !is ReferenceCellTemplate.WrapReferenceTarget) return false + if (shadowed.target != target) return false + val otherConcept = shadowed.getInstantiatedConcept() + val samePlace = location.replacedLocation() == shadowed.location.replacedLocation() + return if (otherConcept == concept) { + location.nodeCreationDepth() < shadowed.location.nodeCreationDepth() || samePlace + } else { + samePlace && otherConcept.isSubConceptOf(concept) + } + } + + override fun execute(editor: BackendEditorComponent): ICaretPositionPolicy? { + val createdAncestors = location.nonExistingAncestorCount() val sourceNode = location.getOrCreateNode(concept) sourceNode.setReferenceTarget(link, target.getOrCreateNode()) - return CaretPositionPolicy(createCellReference(sourceNode)) + return caretPolicyAfterCreating(createCellReference(sourceNode), sourceNode, createdAncestors) } } } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ReplaceConstantActions.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ReplaceConstantActions.kt new file mode 100644 index 00000000..7ea3f2ee --- /dev/null +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ReplaceConstantActions.kt @@ -0,0 +1,104 @@ +package org.modelix.editor.celltemplate + +import org.modelix.constraints.ConstraintsAspect +import org.modelix.editor.CaretPositionPolicy +import org.modelix.editor.CodeCompletionParameters +import org.modelix.editor.EditorEngine +import org.modelix.editor.IActionOrProvider +import org.modelix.editor.ICodeCompletionAction +import org.modelix.editor.ICodeCompletionActionProvider +import org.modelix.editor.NonExistingChild +import org.modelix.editor.getContainmentLinkDefinition +import org.modelix.editor.replacement +import org.modelix.editor.text.backend.BackendEditorComponent +import org.modelix.editor.toNonExisting +import org.modelix.model.api.IChildLink +import org.modelix.model.api.IConcept +import org.modelix.model.api.INode +import org.modelix.model.api.getInstantiatableSubConcepts +import org.modelix.model.api.index +import org.modelix.model.api.remove + +/** + * Typing a different keyword or operator over the one of [node] turns it into the concept that writes that one + * instead, keeping everything else: `a + b` becomes `a - b`. + * + * A concept qualifies if its notation is written like the one of [node], with the same children, properties and + * references in the same order, and only the constant at the position of [constantText] differs. That is what all + * binary operations of baseLanguage share. Nothing has to be declared for it. + */ +class ReplaceConstantProvider( + val node: INode, + val constantText: String, +) : ICodeCompletionActionProvider { + override fun getApplicableActions(parameters: CodeCompletionParameters): List { + val engine = parameters.editor.engine + val concept = node.concept ?: return emptyList() + val link = node.asWritableNode().getContainmentLinkDefinition() ?: return emptyList() + val parent = node.parent ?: return emptyList() + val symbols = engine.grammarSymbols(concept) + val position = symbols.indexOfFirst { it is ConstantCellTemplate && it.text == constantText } + if (position == -1) return emptyList() + + val location = NonExistingChild(parent.toNonExisting(), link as? IChildLink ?: return emptyList(), node.index()) + return link.targetConcept + .getInstantiatableSubConcepts() + .asSequence() + .filter { it != concept } + .mapNotNull { candidate -> + val candidateSymbols = engine.grammarSymbols(candidate) + if (candidateSymbols.size != symbols.size) return@mapNotNull null + val candidateConstant = candidateSymbols[position] as? ConstantCellTemplate ?: return@mapNotNull null + if (candidateConstant.text == constantText) return@mapNotNull null + val sameOtherwise = symbols.indices.all { it == position || symbols[it].isWrittenLike(candidateSymbols[it]) } + if (!sameOtherwise) return@mapNotNull null + if (!runCatching { ConstraintsAspect.canCreate(location.replacement(candidate)) }.getOrElse { true }) { + return@mapNotNull null + } + ReplaceConstantAction(node, candidate, candidateConstant) + }.toList() + } + + private fun EditorEngine.grammarSymbols(concept: IConcept): List = + runCatching { createCellModelExcludingDefault(concept)?.getGrammarSymbols()?.toList() }.getOrNull() ?: emptyList() + + private fun IGrammarSymbol.isWrittenLike(other: IGrammarSymbol): Boolean = + when (this) { + is ConstantCellTemplate -> other is ConstantCellTemplate && other.text == text + is ChildCellTemplate -> other is ChildCellTemplate && other.link.toReference().matches(link.toReference()) + is PropertyCellTemplate -> other is PropertyCellTemplate && other.property.toReference().matches(property.toReference()) + is ReferenceCellTemplate -> other is ReferenceCellTemplate && other.link.toReference().matches(link.toReference()) + else -> false + } +} + +class ReplaceConstantAction( + val node: INode, + val newConcept: IConcept, + val newConstant: ConstantCellTemplate, +) : ICodeCompletionAction { + override fun getMatchingText(): String = newConstant.text + + override fun getDescription(): String = newConcept.getShortName() + + override fun execute(editor: BackendEditorComponent): CaretPositionPolicy { + val newNode = + editor.runWrite { + val parent = checkNotNull(node.parent) + val link = checkNotNull(node.getContainmentLink()) + val newNode = parent.addNewChild(link, node.index(), newConcept) + for (child in node.allChildren.toList()) { + newNode.moveChild(checkNotNull(child.getContainmentLink()), -1, child) + } + for (property in node.getPropertyLinks()) { + node.getPropertyValue(property)?.let { newNode.setPropertyValue(property, it) } + } + for (reference in node.getReferenceLinks()) { + node.getReferenceTarget(reference)?.let { newNode.setReferenceTarget(reference, it) } + } + node.remove() + newNode + } + return CaretPositionPolicy(newConstant.createCellReference(newNode)) + } +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt index 13e43383..7b90bc8c 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/backend/TextEditorServiceImpl.kt @@ -12,23 +12,44 @@ import org.modelix.editor.CaretPositionPolicy import org.modelix.editor.CaretPositionPolicyWithIndex import org.modelix.editor.Cell import org.modelix.editor.CellActionProperties +import org.modelix.editor.ChildCompletionToken +import org.modelix.editor.ChildNodeCellReference +import org.modelix.editor.CodeCompletionActionProviderWrapper import org.modelix.editor.CodeCompletionParameters import org.modelix.editor.CommonCellProperties import org.modelix.editor.CompletionPosition +import org.modelix.editor.CompletionToken import org.modelix.editor.ContextActionsAspect import org.modelix.editor.ECellType import org.modelix.editor.EditorEngine +import org.modelix.editor.IActionOrProvider import org.modelix.editor.ICaretPositionPolicy import org.modelix.editor.ICellAction import org.modelix.editor.ICodeCompletionAction +import org.modelix.editor.ICodeCompletionActionProvider +import org.modelix.editor.ICompletionTokenOrList +import org.modelix.editor.INonExistingNode +import org.modelix.editor.ITextChangeAction +import org.modelix.editor.NonExistingChild +import org.modelix.editor.NonExistingNode +import org.modelix.editor.PropertyCellReference +import org.modelix.editor.ReferencedNodeCellReference +import org.modelix.editor.ReplaceNodeActionProvider +import org.modelix.editor.RoleToken +import org.modelix.editor.SpaceCompletionToken import org.modelix.editor.ancestors import org.modelix.editor.applyShadowing +import org.modelix.editor.celltemplate.ChildCellTemplate +import org.modelix.editor.celltemplate.ClearOptionalCellAction +import org.modelix.editor.celltemplate.OverrideText import org.modelix.editor.centerAlignedHierarchy +import org.modelix.editor.descendantsAndSelf import org.modelix.editor.flattenApplicableActions import org.modelix.editor.getActionsAfter import org.modelix.editor.getActionsBefore import org.modelix.editor.getBordersBetween import org.modelix.editor.getCompletionPattern +import org.modelix.editor.getContainmentLinkDefinition import org.modelix.editor.getContextActions import org.modelix.editor.getSubstituteActions import org.modelix.editor.isTabTarget @@ -37,6 +58,8 @@ import org.modelix.editor.leftBorder import org.modelix.editor.nextCells import org.modelix.editor.nextLeaf import org.modelix.editor.previousCells +import org.modelix.editor.previousLeaf +import org.modelix.editor.replacement import org.modelix.editor.rightBorder import org.modelix.editor.text.frontend.getSelectableText import org.modelix.editor.text.frontend.type @@ -54,6 +77,7 @@ import org.modelix.model.api.BuiltinLanguages import org.modelix.model.api.IMutableModel import org.modelix.model.api.IReadableNode import org.modelix.model.api.NodeReference +import org.modelix.model.api.remove import org.modelix.model.api.runSynchronized import org.modelix.model.api.toSerialized @@ -168,11 +192,26 @@ class TextEditorServiceImpl( cellId: CellInstanceId, ): EditorUpdateData = runWithCell(editorId, cellId) { updateChannel, cell -> - val deleteAction = - cell - .ancestors(true) + val ancestors = cell.ancestors(true).toList() + val innermostAction = + ancestors .mapNotNull { it.getProperty(CellActionProperties.delete) } .firstOrNull { it.isApplicable() } + val deleteAction = + if (innermostAction is ChildCellTemplate.EmptySlotDeleteAction && + !updateChannel.editor.runRead { innermostAction.hasEffect() } + ) { + // An empty slot in an optional part of the notation, like the `<>` of `int x = <>`. Deleting in + // it deletes that part, as deleting the `=` would. + val nodeCellIndex = ancestors.indexOfFirst { it.getProperty(CommonCellProperties.node) != null } + ancestors + .take(if (nodeCellIndex == -1) ancestors.size else nodeCellIndex) + .mapNotNull { it.getProperty(CellActionProperties.delete) } + .firstOrNull { it is ClearOptionalCellAction } + ?: innermostAction + } else { + innermostAction + } if (deleteAction != null) { return@runWithCell updateChannel.createSelection(deleteAction.execute(updateChannel.editor)) } @@ -218,13 +257,18 @@ class TextEditorServiceImpl( val range = IntRange(rangeStart, rangeEnd) return runWithCell(editorId, cellId) { updateChannel, cell -> val oldText = cell.getSelectableText() ?: "" - val textLength = oldText.length + val newText = oldText.replaceRange(range, replacement) val leftTransform = range.isEmpty() && range.first == 0 - val rightTransform = range.isEmpty() && range.first == textLength - if (leftTransform || rightTransform) { - // if (replaceText(range, typedText, editor, false)) return - - val completionPosition = if (leftTransform) CompletionPosition.LEFT else CompletionPosition.RIGHT + val rightTransform = range.isEmpty() && range.first == oldText.length + // Text that is still being typed is not a node yet that could be transformed. It goes on in the cell. + val isPendingText = cell.getProperty(CommonCellProperties.textReplacement) != null + val completionPosition = + when { + leftTransform -> CompletionPosition.LEFT + rightTransform && !isPendingText -> CompletionPosition.RIGHT + else -> null + } + if (completionPosition != null) { val providers = ( if (completionPosition == CompletionPosition.LEFT) { @@ -241,26 +285,102 @@ class TextEditorServiceImpl( .filter { it.getCompletionPattern().startsWith(replacement) } .applyShadowing() } - if (matchingActions.isNotEmpty()) { - if (matchingActions.size == 1 && matchingActions.first().getCompletionPattern() == replacement) { - return@runWithCell matchingActions.first().executeAndUpdateSelection(updateChannel) - } - return@runWithCell updateChannel.createUpdate().copy( - menuTrigger = - CompletionMenuTrigger( - anchor = cell.getId(), - completionPosition = completionPosition, - pattern = replacement, - caretPosition = replacement.length - ), - completionEntries = updateChannel.editor.loadCompletionEntries(providers, replacement).toEntryData() - ) + // The text of the cell goes on as long as it is still the text of something, like `1.` of `1.5`. A + // side transform of the node behind the cell only applies to text that doesn't belong to it anymore. + if (matchingActions.isEmpty() || continuesSubstitution(cell, newText, updateChannel.editor)) { + return@runWithCell overtypeConstant(cell, range, replacement, oldText, updateChannel) + ?: replaceText(cell, range, replacement, updateChannel, true).updateData + ?: updateChannel.createUpdate() } + if (matchingActions.size == 1 && matchingActions.first().getCompletionPattern() == replacement) { + return@runWithCell matchingActions.first().executeAndUpdateSelection(updateChannel) + } + // A constant that is already there is what the user means, rather than a transformation that starts + // with the same text: `:` in `c ? a : b` is the colon behind `a`. + overtypeConstant(cell, range, replacement, oldText, updateChannel)?.let { return@runWithCell it } + return@runWithCell updateChannel.createUpdate().copy( + menuTrigger = + CompletionMenuTrigger( + anchor = cell.getId(), + completionPosition = completionPosition, + pattern = replacement, + caretPosition = replacement.length + ), + completionEntries = updateChannel.editor.loadCompletionEntries(providers, replacement).toEntryData() + ) } + overtypeConstant(cell, range, replacement, oldText, updateChannel)?.let { return@runWithCell it } replaceText(cell, range, replacement, updateChannel, true).updateData ?: updateChannel.createUpdate() } } + /** + * Whether [newText] is still, or can still become, what one of the substitutions of the cell writes. + */ + private fun continuesSubstitution( + cell: ICellTree.Cell, + newText: String, + editor: BackendEditorComponent, + ): Boolean { + if (newText.isBlank()) return false + val providers = cell.getSubstituteActions().toList() + if (providers.isEmpty()) return false + val actions = editor.runRead { providers.flatMap { it.flattenApplicableActions(CodeCompletionParameters(editor, newText)) } } + return actions.matchingCompletely(newText).isNotEmpty() || actions.any { it.isContinuedBy(newText) } + } + + /** + * Typing the text of a constant that is already there moves the caret over it, as in a text editor where the + * brackets were inserted automatically. The constants of a notation are there from the start, so writing `if (` + * or `x)` the way it's written in a text editor would otherwise end up as text that means nothing. + * + * The constant has to be right next to the caret: behind it, or in front of it in a cell that is still empty, which + * is where the caret is after `if` created the statement. + */ + private fun overtypeConstant( + cell: ICellTree.Cell, + range: IntRange, + replacement: String, + oldText: String, + updateChannel: EditorUpdateChannel, + ): EditorUpdateData? { + if (!range.isEmpty() || replacement.isBlank()) return null + + fun ICellTree.Cell.isConstant() = getProperty(CommonCellProperties.constant) + + // Behind the whole constant, the caret goes on into a slot that follows it and still is empty. + fun moveOver( + constant: ICellTree.Cell, + position: Int, + ): EditorUpdateData { + if (position == constant.getSelectableText().orEmpty().length) { + val next = constant.nextLeaf { it.isVisible() } + if (next != null && next.isTabTarget() && next.getSelectableText().isNullOrEmpty()) { + return updateChannel.createSelection(next, 0) + } + } + return updateChannel.createSelection(constant, position) + } + + val caretPos = range.first + if (cell.isConstant() && oldText.startsWith(replacement, caretPos)) { + return moveOver(cell, caretPos + replacement.length) + } + if (caretPos == oldText.length) { + val next = cell.nextLeaf { it.isVisible() } + if (next != null && next.isConstant() && next.getSelectableText().orEmpty().startsWith(replacement)) { + return moveOver(next, replacement.length) + } + } + if (oldText.isEmpty()) { + val previous = cell.previousLeaf { it.isVisible() } + if (previous != null && previous.isConstant() && previous.getSelectableText() == replacement) { + return updateChannel.createUpdate() + } + } + return null + } + override suspend fun triggerCodeCompletion( editorId: Int, cellId: CellInstanceId, @@ -360,25 +480,62 @@ class TextEditorServiceImpl( val newText = oldText.replaceRange(range, replacement) if (triggerCompletion) { - // complete immediately if there is a single matching action - val providers = cell.getSubstituteActions() - val params = CodeCompletionParameters(editor, newText) - val actions = editor.runRead { providers.flatMap { it.flattenApplicableActions(params) }.toList() } - val matchingActions = - actions - .filter { it.getTokens().consumeForAutoApply(newText)?.length == 0 } - .applyShadowing() + val providers = cell.getSubstituteActions().toList() + val actions = editor.runRead { providers.flatMap { it.flattenApplicableActions(CodeCompletionParameters(editor, newText)) } } + val matchingActions = actions.matchingCompletely(newText) + + // Complete immediately if there is a single matching action, unless the user may still be typing a + // longer one: `do` is not the `do`-`while` loop yet as long as it can become a `double`. val singleAction = matchingActions.singleOrNull() - if (singleAction != null) { + if (singleAction != null && actions.none { it.isContinuedBy(newText) }) { return editor .runWrite { editor.state.clearTextReplacement(cell) singleAction.executeAndUpdateSelection(updateChannel) }.let { ServiceCallResult(updateData = it, result = true) } } + + // Text that nothing can be made of anymore, because the last key started a new token. What was typed + // before is complete if exactly one action matches it, like the name of a variable before a `=`. That is + // applied, and the new key is typed again behind it. + val isAppended = range.isEmpty() && range.first == oldText.length + val isPendingText = cell.getProperty(CommonCellProperties.textReplacement) != null + if (isAppended && isPendingText && matchingActions.isEmpty() && actions.none { it.isContinuedBy(newText) } && + startsNewToken(oldText, replacement) + ) { + val previousActions = + editor.runRead { providers.flatMap { it.flattenApplicableActions(CodeCompletionParameters(editor, oldText)) } } + val previousMatches = previousActions.matchingCompletely(oldText) + val previousAction = + previousMatches.singleOrNull() + ?: editor + .runRead { + val location = providers.firstNotNullOfOrNull { it.replacedLocation() } + previousMatches.filter { it.acceptsNext(oldText, replacement, location, editor) } + }.singleOrNull() + if (previousAction != null) { + return editor + .runWrite { + editor.state.clearTextReplacement(cell) + previousAction.executeAndUpdateSelection(updateChannel).copy(textToRetype = replacement) + }.let { ServiceCallResult(updateData = it, result = true) } + } + } + } + + if (replacement.isEmpty() && newText.isEmpty()) { + deleteNodeWithoutText(cell, updateChannel)?.let { return ServiceCallResult(updateData = it, result = true) } } val replaceTextActions = cell.centerAlignedHierarchy().mapNotNull { it.getProperty(CellActionProperties.replaceText) } + + // Spaces separate tokens. Where the model can't hold one and no text is pending, there is nothing a space can + // separate, and it's dropped instead of being shown as text that means nothing - `return 1` is a return of 1. + if (replacement.isNotEmpty() && replacement.isBlank() && cell.getProperty(CommonCellProperties.textReplacement) == null && + replaceTextActions.none { it.acceptsAsModelText(newText) } + ) { + return ServiceCallResult(updateData = updateChannel.createUpdate(), result = true) + } for (action in replaceTextActions) { val newCaretPosition = CaretPositionPolicyWithIndex( @@ -441,6 +598,146 @@ class TextEditorServiceImpl( channel.createSelection(execute(channel.editor)) } + /** + * Deleting the last character of the only text a node has deletes the node, rather than leaving a node behind + * that shows nothing - like the `1` of `int x = 1`. The caret stays where the node was, in the then empty slot. + * + * Only applies to text that shows the node itself, its keyword or one of its properties or references, and to a + * node in a single child link, where an empty slot takes its place. + */ + private fun deleteNodeWithoutText( + cell: ICellTree.Cell, + updateChannel: EditorUpdateChannel, + ): EditorUpdateData? { + val nodeCell = cell.ancestors(true).firstOrNull { it.getProperty(CommonCellProperties.node) != null } ?: return null + val node = nodeCell.getProperty(CommonCellProperties.node)?.getNode() ?: return null + val otherText = nodeCell.descendantsAndSelf().filter { it != cell && it.type == ECellType.TEXT } + if (otherText.any { !it.getSelectableText().isNullOrEmpty() }) return null + val slot = + updateChannel.editor.runWrite { + val nodeRef = node.reference.serialize() + val showsTheNode = + cell.getProperty(CommonCellProperties.constant) || + cell.cellReferences.any { + (it is PropertyCellReference && it.nodeRef.serialize() == nodeRef) || + (it is ReferencedNodeCellReference && it.sourceNodeRef.serialize() == nodeRef) + } + val parent = node.parent + val link = node.asWritableNode().getContainmentLinkDefinition() + if (!showsTheNode || parent == null || link == null || link.isMultiple) return@runWrite null + updateChannel.editor.state.clearTextReplacement(cell) + node.remove() + ChildNodeCellReference(parent.reference, link.toReference(), 0) + } ?: return null + return updateChannel.createSelection(CaretPositionPolicy(slot)) + } + + /** + * The actions whose completion pattern consumes all of [text]. + */ + private fun List.matchingCompletely(text: String) = + filter { it.getTokens().consumeForAutoApply(text)?.length == 0 }.applyShadowing() + + /** + * Whether the user can still be typing this action after having typed [text]: its pattern goes on after it, but + * doesn't accept it yet. + */ + private fun ICodeCompletionAction.isContinuedBy(text: String): Boolean { + val pattern = getCompletionPattern() + return pattern.length > text.length && pattern.startsWith(text) && getTokens().consumeForAutoApply(text)?.length != 0 + } + + /** + * Whether what this action expects behind [typedBefore] can start with [typed]. That tells apart the actions + * that all match what was typed before: `(` can be a parenthesized expression or a cast, but only an expression + * can start with the `1` of `(1`. + * + * Only a child is checked, by the substitutions of its concept. Anything else is assumed to accept it. + */ + private fun ICodeCompletionAction.acceptsNext( + typedBefore: String, + typed: String, + replacedLocation: INonExistingNode?, + editor: BackendEditorComponent, + ): Boolean { + val next = getTokens().nextTokenAfter(typedBefore) ?: return false + if (next !is ChildCompletionToken) return next is RoleToken + // The child is somewhere below where the typed text is, which is what scopes are computed for. + val parent = + replacedLocation?.let { it.replacement(it.expectedConcept() ?: next.role.targetConcept) } + ?: NonExistingNode(next.role.targetConcept) + val parameters = CodeCompletionParameters(editor, typed) + val actions = ReplaceNodeActionProvider(NonExistingChild(parent, next.role)).flattenSafely(parameters).toList() + return actions.matchingCompletely(typed).isNotEmpty() || actions.any { it.isContinuedBy(typed) } + } + + /** + * The actions of a provider, leaving out those of nested providers that fail - which the scope of a reference + * may, where its node does not exist yet. + */ + private fun IActionOrProvider.flattenSafely(parameters: CodeCompletionParameters): Sequence = + when (this) { + is ICodeCompletionAction -> { + sequenceOf(this) + } + + is ICodeCompletionActionProvider -> { + runCatching { getApplicableActions(parameters) } + .getOrElse { emptyList() } + .asSequence() + .flatMap { it.flattenSafely(parameters) } + } + + else -> { + emptySequence() + } + } + + /** + * Where the node goes that a substitution of a cell creates. + */ + private fun ICodeCompletionActionProvider.replacedLocation(): INonExistingNode? = + when (this) { + is ReplaceNodeActionProvider -> location + is CodeCompletionActionProviderWrapper -> wrappedProvider.replacedLocation() + else -> null + } + + /** + * The token of a completion pattern that follows the part that [text] consumes, if [text] ends between tokens. + */ + private fun ICompletionTokenOrList.nextTokenAfter(text: String): CompletionToken? { + var remaining: CharSequence = text + for (token in flatten()) { + if (remaining.isEmpty()) { + if (token is SpaceCompletionToken) continue + return token + } + remaining = token.consumeForAutoApply(remaining) ?: return null + } + return null + } + + /** + * Whether [typed] starts a new token behind [before]. Letters and digits continue a name or a number. + */ + private fun startsNewToken( + before: String, + typed: String, + ): Boolean { + fun Char.isWordChar() = isLetterOrDigit() || this == '_' + val last = before.lastOrNull() ?: return false + val first = typed.firstOrNull() ?: return false + return !(last.isWordChar() && first.isWordChar()) + } + + /** + * Whether [text] is valid as what the cell shows of the model, not only as text that is shown instead of it. A + * cell can be wrapped in an [OverrideText] for each template it is part of. + */ + private fun ITextChangeAction.acceptsAsModelText(text: String): Boolean = + if (this is OverrideText) delegate?.acceptsAsModelText(text) == true else isValid(text) + fun triggerUpdates() { validator.invalidate() } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt index 4333a79d..97499441 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/text/shared/TextEditorService.kt @@ -207,6 +207,11 @@ data class EditorUpdateData( val selectionChange: ICaretPositionPolicy? = null, val menuTrigger: ActionMenuTrigger? = null, val completionEntries: List? = null, + /** + * Text the user typed that the update didn't consume. It completed what was typed before, so it's typed again at + * the new caret position: typing `=` behind a variable name first turns the name into a reference. + */ + val textToRetype: String? = null, ) /** From 2009dfd4f02245a31393d1e216f4349d9d93473b Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 13 Nov 2026 16:32:11 +0100 Subject: [PATCH 17/23] feat(projectional-editor): operator precedence declared in the notation Typing an operator behind a node that is the last operand of other operators can wrap each of them: `+` behind the `2` of `1 * 2` can make `1 * (2 + <>)` or `(1 * 2) + <>`. The innermost node was always wrapped, so `1*2+3` became `1 * (2 + 3)` while the editor showed `1 * 2 + 3`. A notation can now declare the precedence of an operator. The side transform that is typed takes the whole of each operator around the node that binds tighter, and operators of the same level are grouped from the left unless they are right associative. Without precedences, nothing changes. - The editor DSL has `precedence(level, rightAssociative)` on the root of a notation. - The notation language has an optional `precedence:` expression and a `right associative` flag on concept notations, in the inspector. Inside the expression, `concept` is the concept the notation is applied to, which a notation for all sub-concepts needs. - The baseLanguage notations of the operators declare it from baseLanguage's own `getPrecedenceLevel()`, so the precedences are the ones MPS uses. Assignments and the ternary operator are right associative. Co-Authored-By: Claude Opus 5.5 --- ...mps.notation.impl.baseLanguage.modelix.mps | 321 ++++++++++++++++++ ...notation.generator.templates@generator.mps | 136 +++++++- .../org.modelix.mps.notation.editor.mps | 25 ++ .../org.modelix.mps.notation.structure.mps | 18 + .../org.modelix.mps.notation.typesystem.mps | 59 ++++ .../editor/ssr/mps/BaseLanguageTypingTest.kt | 69 ++++ .../org/modelix/editor/CellTemplateBuilder.kt | 12 + .../kotlin/org/modelix/editor/EditorEngine.kt | 8 + .../kotlin/org/modelix/editor/ICellAction.kt | 2 +- .../kotlin/org/modelix/editor/Precedence.kt | 27 ++ .../editor/celltemplate/CellTemplate.kt | 5 +- .../celltemplate/ConstantCellTemplate.kt | 41 ++- .../editor/celltemplate/IGrammarSymbol.kt | 8 + .../celltemplate/NotationRootCellTemplate.kt | 6 + .../org/modelix/editor/PrecedenceTest.kt | 33 ++ 15 files changed, 765 insertions(+), 5 deletions(-) create mode 100644 projectional-editor/src/commonMain/kotlin/org/modelix/editor/Precedence.kt create mode 100644 projectional-editor/src/commonTest/kotlin/org/modelix/editor/PrecedenceTest.kt diff --git a/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps b/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps index 35b16e4c..47638d10 100644 --- a/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps +++ b/mps/modules/org.modelix.mps.notation.impl.baseLanguage/models/org.modelix.mps.notation.impl.baseLanguage.modelix.mps @@ -19,7 +19,9 @@ + + @@ -32,6 +34,10 @@
+ + + + @@ -42,6 +48,7 @@ + @@ -72,6 +79,7 @@ + @@ -139,7 +147,9 @@ + + @@ -158,6 +168,7 @@ + @@ -449,6 +460,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -489,6 +522,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -680,6 +735,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -1311,6 +1388,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -1376,6 +1475,7 @@ + @@ -1386,6 +1486,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -1434,6 +1556,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -1446,6 +1590,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -1467,6 +1633,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -1482,6 +1670,7 @@ + @@ -1500,6 +1689,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -2760,6 +2971,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -2827,6 +3060,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -2954,6 +3209,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -3106,6 +3383,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -3402,6 +3701,28 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps b/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps index 4467e642..7c1943a8 100644 --- a/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps +++ b/mps/modules/org.modelix.mps.notation/generator/templates/org.modelix.mps.notation.generator.templates@generator.mps @@ -31,9 +31,9 @@ + - @@ -83,6 +83,10 @@ + + + + @@ -140,6 +144,9 @@ + + + @@ -4630,6 +4637,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -6364,6 +6435,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps index 50ff3f76..6c2c1144 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.editor.mps @@ -295,6 +295,24 @@ + + + + + + + + + + + + + + + + + + @@ -1490,5 +1508,12 @@ + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps index cf720bf1..d40c3842 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.structure.mps @@ -116,6 +116,12 @@ + + + + + + @@ -128,6 +134,11 @@ + + + + + @@ -745,5 +756,12 @@ + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.typesystem.mps b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.typesystem.mps index 107ddf86..71f1a1dd 100644 --- a/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.typesystem.mps +++ b/mps/modules/org.modelix.mps.notation/models/org.modelix.mps.notation.typesystem.mps @@ -1523,5 +1523,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTypingTest.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTypingTest.kt index 6022919a..9e42cfd8 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTypingTest.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTypingTest.kt @@ -5,6 +5,9 @@ import org.modelix.editor.KnownKeys import org.modelix.editor.descendantsAndSelf import org.modelix.editor.layoutable import org.modelix.editor.text.frontend.getVisibleText +import org.modelix.model.api.INode +import org.modelix.model.api.IPropertyReference +import org.modelix.model.api.getDescendants /** * Typing baseLanguage code the way it's written in a text editor, key by key, and editing it again. @@ -256,4 +259,70 @@ class BaseLanguageTypingTest : BaseLanguageTestBase() { typeText("-") assertBody("int x = 1 - 2;") } + + // Operators wrap the nodes their precedence takes. The text looks the same either way, so the tree is checked. + + /** + * The tree of the initializer of the last variable declared in `method1`, like `Plus(Mul(1, 2), 3)`. + */ + private fun lastInitializer(): String = + readAction { + fun describe(node: INode): String { + val name = + node.concept + ?.getShortName() + ?.removeSuffix("Expression") + ?.removeSuffix("Constant") ?: "?" + val value = node.asWritableNode().getPropertyValue(IPropertyReference.fromName("value")) + val children = node.allChildren.toList() + return when { + children.isNotEmpty() -> name + children.joinToString(", ", "(", ")") { describe(it) } + name == "Boolean" -> value ?: "false" + value != null -> value + else -> name + } + } + val declaration = + methodBodyNode + .asLegacyNode() + .getDescendants(false) + .last { it.concept?.getShortName() == "LocalVariableDeclaration" } + describe(declaration.allChildren.last()) + } + + fun `test an operator that binds looser wraps the operator in front of it`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=1*2+3", "int x = 1 * 2 + 3;") + assertEquals("Plus(Mul(1, 2), 3)", lastInitializer()) + } + + fun `test an operator that binds tighter wraps only the last operand`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=1+2*3", "int x = 1 + 2 * 3;") + assertEquals("Plus(1, Mul(2, 3))", lastInitializer()) + } + + fun `test operators of the same precedence are grouped from the left`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=1-2+3", "int x = 1 - 2 + 3;") + assertEquals("Plus(Minus(1, 2), 3)", lastInitializer()) + } + + fun `test a chain of precedences`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("boolean b=1+2*3<4||!true&&false", "boolean b = 1 + 2 * 3 < 4 || !true && false;") + assertEquals("Or(LessThan(Plus(1, Mul(2, 3)), 4), And(Not(true), false))", lastInitializer()) + } + + fun `test the branches of a ternary operator`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=true?1+2:3*4", "int x = true ? 1 + 2 : 3 * 4;") + assertEquals("TernaryOperator(true, Plus(1, 2), Mul(3, 4))", lastInitializer()) + } + + fun `test parentheses keep what they contain together`() = + kotlinx.coroutines.test.runTest { + typeIntoBody("int x=(1+2)*3", "int x = (1 + 2) * 3;") + assertEquals("Mul(Parenthesized(Plus(1, 2)), 3)", lastInitializer()) + } } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellTemplateBuilder.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellTemplateBuilder.kt index 3035acd9..05b666df 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellTemplateBuilder.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/CellTemplateBuilder.kt @@ -33,6 +33,7 @@ import org.modelix.model.api.INode import org.modelix.model.api.IProperty import org.modelix.model.api.IReferenceLink import kotlin.jvm.JvmName +import kotlin.jvm.JvmOverloads import kotlin.reflect.KClass private val LOG = KotlinLogging.logger { } @@ -544,6 +545,17 @@ class NotationRootCellTemplateBuilder( (template as NotationRootCellTemplate).condition = condition } + /** + * Declares how tightly the notation of an operator binds its operands. See [Precedence]. + */ + @JvmOverloads + fun precedence( + level: Int, + rightAssociative: Boolean = false, + ) { + (template as NotationRootCellTemplate).precedence = Precedence(level, rightAssociative) + } + fun hideInCodeCompletion() = completionText("") fun completionText(text: String) { diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt index b2fe90ac..c33cc988 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/EditorEngine.kt @@ -191,6 +191,14 @@ class EditorEngine( return template } + /** + * The precedence the notation of [concept] declares, if it's the notation of an operator. + */ + fun getPrecedence(concept: IConcept?): Precedence? { + if (concept == null) return null + return runCatching { createCellModelExcludingDefault(concept) as? NotationRootCellTemplate }.getOrNull()?.precedence + } + fun createCellModelExcludingDefault(concept: IConcept): CellTemplate? = resolveConceptEditor(concept).minus(defaultConceptEditor).firstOrNull()?.apply(concept) diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt index 5227b223..4922cb7a 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/ICellAction.kt @@ -91,7 +91,7 @@ class SideTransformNode( engine.createCellModel(concept) } return cellModels.flatMap { - it.getSideTransformActions(before, node) ?: emptyList() + it.getSideTransformActions(before, node, engine) ?: emptyList() } } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/Precedence.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/Precedence.kt new file mode 100644 index 00000000..3eb00525 --- /dev/null +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/Precedence.kt @@ -0,0 +1,27 @@ +package org.modelix.editor + +/** + * How tightly a notation binds what is written next to it: `*` binds tighter than `+`. + * + * It decides which node an operator wraps that is typed behind (or in front of) a node that is itself the operand of + * other operators. Typing `+ 3` behind the `2` of `1 * 2` wraps all of `1 * 2`, because `*` binds tighter, while + * typing `* 3` behind the `2` of `1 + 2` wraps only the `2`. That is the tree that the text means, so the editor + * builds what it shows. + * + * A higher [level] binds tighter. Operators of the same level are grouped from the left - `1 - 2 - 3` is + * `(1 - 2) - 3` - unless they are [rightAssociative], like the assignments in `a = b = c`. + * + * A notation without a precedence doesn't take part. An operator without one wraps the innermost node it can, and + * one with a precedence doesn't wrap a node whose notation has none. + */ +data class Precedence( + val level: Int, + val rightAssociative: Boolean = false, +) { + /** + * Whether an operator with this precedence typed next to an operand of [operandsParent] takes [operandsParent] as + * its operand, instead of the operand of [operandsParent]. That's the case if [operandsParent] binds tighter. + */ + fun takesWhole(operandsParent: Precedence): Boolean = + operandsParent.level > level || (operandsParent.level == level && !rightAssociative) +} diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/CellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/CellTemplate.kt index e78272a6..b6f0d7bb 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/CellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/CellTemplate.kt @@ -9,6 +9,7 @@ import org.modelix.editor.ChildCellTemplateReference import org.modelix.editor.CodeCompletionParameters import org.modelix.editor.CommonCellProperties import org.modelix.editor.ECellLayout +import org.modelix.editor.EditorEngine import org.modelix.editor.IActionOrProvider import org.modelix.editor.ICellTemplateReference import org.modelix.editor.ICodeCompletionAction @@ -108,8 +109,10 @@ abstract class CellTemplate( fun getSideTransformActions( before: Boolean, nodeToReplace: INode, + engine: EditorEngine, ): List? { val symbols = getGrammarSymbols().toList() + val precedence = (this as? NotationRootCellTemplate)?.precedence val conceptToReplace = nodeToReplace.concept ?: return null return symbols .mapIndexedNotNull { index, symbol -> @@ -121,7 +124,7 @@ abstract class CellTemplate( // no reason to make it `typeof(a)`: nobody typed the `typeof(`. val symbolsInFront = symbols.take(if (before) prevNextIndex else index) if (symbolsInFront.any { it !is IOptionalSymbol }) return@mapIndexedNotNull null - return@mapIndexedNotNull prevNextSymbol.createWrapperAction(nodeToReplace, symbol.link) + return@mapIndexedNotNull prevNextSymbol.createWrapperAction(nodeToReplace, symbol.link, precedence, engine) } return@mapIndexedNotNull null }.flatten() diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ConstantCellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ConstantCellTemplate.kt index 43a24aaa..4996af53 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ConstantCellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/ConstantCellTemplate.kt @@ -7,11 +7,13 @@ import org.modelix.editor.ChildNodeCellReference import org.modelix.editor.CodeCompletionParameters import org.modelix.editor.CommonCellProperties import org.modelix.editor.ConstantCompletionToken +import org.modelix.editor.EditorEngine import org.modelix.editor.IActionOrProvider import org.modelix.editor.ICodeCompletionAction import org.modelix.editor.ICompletionTokenOrList import org.modelix.editor.INonExistingNode import org.modelix.editor.IParseTreeToAstBuilder +import org.modelix.editor.Precedence import org.modelix.editor.TemplateCellReference import org.modelix.editor.TextCellSpec import org.modelix.editor.ancestors @@ -58,7 +60,9 @@ class ConstantCellTemplate( override fun createWrapperAction( nodeToWrap: INode, wrappingLink: IChildLink, - ): List = listOf(SideTransformWrapper(nodeToWrap.toNonExisting(), wrappingLink)) + precedence: Precedence?, + engine: EditorEngine, + ): List = listOf(SideTransformWrapper(nodeToWrap.toNonExisting(), wrappingLink, precedence, engine)) override fun getSymbolTransformationAction( node: INode, @@ -72,9 +76,19 @@ class ConstantCellTemplate( } }.withMatchingText(text) + /** + * Wraps [nodeToWrap] into the concept of this notation, which writes [text] next to it. + * + * Typed behind a node that is the last operand of other nodes, the same text can wrap each of them: `+` behind the + * `2` of `1 * 2` can make `1 * (2 + <>)` or `(1 * 2) + <>`. The [precedence] of the wrapper decides, as in the + * text: it takes the whole of each operator around the node that binds tighter. Without precedences, the + * innermost node is wrapped. + */ inner class SideTransformWrapper( val nodeToWrap: INonExistingNode, val wrappingLink: IChildLink, + val precedence: Precedence?, + val engine: EditorEngine, ) : ICodeCompletionAction { override fun getMatchingText(): String = text @@ -103,7 +117,30 @@ class ConstantCellTemplate( .ancestors(true) .takeWhile { it != commonAncestor } .count() - if (ownDepth > otherDepth) return true + return when { + ownDepth > otherDepth -> !wrapsOuterNode(inner = nodeToWrap, outer = shadowed.nodeToWrap) + ownDepth < otherDepth -> wrapsOuterNode(inner = shadowed.nodeToWrap, outer = nodeToWrap) + else -> false + } + } + + /** + * Whether the text typed next to [inner] belongs around [outer], an ancestor of it: every node from the parent + * of [inner] up to [outer] binds tighter than the wrapper, so it's an operand of the wrapper as a whole. + */ + private fun wrapsOuterNode( + inner: INonExistingNode, + outer: INonExistingNode, + ): Boolean { + val precedence = precedence ?: return false + val outerNode = outer.getNode() ?: return false + var node = inner.getNode()?.parent + while (node != null) { + val operandsParent = engine.getPrecedence(node.concept) ?: return false + if (!precedence.takesWhole(operandsParent)) return false + if (node.reference.serialize() == outerNode.reference.serialize()) return true + node = node.parent + } return false } diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/IGrammarSymbol.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/IGrammarSymbol.kt index ef12567d..4b0b38ce 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/IGrammarSymbol.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/IGrammarSymbol.kt @@ -1,17 +1,25 @@ package org.modelix.editor.celltemplate +import org.modelix.editor.EditorEngine import org.modelix.editor.IActionOrProvider import org.modelix.editor.ICodeCompletionAction import org.modelix.editor.IParseTreeToAstBuilder +import org.modelix.editor.Precedence import org.modelix.editor.TemplateCellReference import org.modelix.model.api.IChildLink import org.modelix.model.api.INode import org.modelix.parser.ISymbol interface IGrammarSymbol { + /** + * The side transforms that wrap [nodeToWrap] into the concept of this notation when the text of this symbol is + * typed next to it. [precedence] is the one of the wrapping notation. + */ fun createWrapperAction( nodeToWrap: INode, wrappingLink: IChildLink, + precedence: Precedence?, + engine: EditorEngine, ): List = emptyList() fun getSymbolTransformationAction( diff --git a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/NotationRootCellTemplate.kt b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/NotationRootCellTemplate.kt index 3f832625..5742fbee 100644 --- a/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/NotationRootCellTemplate.kt +++ b/projectional-editor/src/commonMain/kotlin/org/modelix/editor/celltemplate/NotationRootCellTemplate.kt @@ -2,6 +2,7 @@ package org.modelix.editor.celltemplate import org.modelix.editor.CellCreationContext import org.modelix.editor.CellSpec +import org.modelix.editor.Precedence import org.modelix.model.api.IConcept import org.modelix.model.api.INode @@ -10,6 +11,11 @@ class NotationRootCellTemplate( ) : CellTemplate(concept) { var condition: ((INode) -> Boolean)? = null + /** + * How tightly the notation binds the nodes written next to it, if it is the notation of an operator. + */ + var precedence: Precedence? = null + override fun createCell( context: CellCreationContext, node: INode, diff --git a/projectional-editor/src/commonTest/kotlin/org/modelix/editor/PrecedenceTest.kt b/projectional-editor/src/commonTest/kotlin/org/modelix/editor/PrecedenceTest.kt new file mode 100644 index 00000000..bd4bd6a9 --- /dev/null +++ b/projectional-editor/src/commonTest/kotlin/org/modelix/editor/PrecedenceTest.kt @@ -0,0 +1,33 @@ +package org.modelix.editor + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class PrecedenceTest { + private val plus = Precedence(11) + private val times = Precedence(12) + private val assignment = Precedence(1, rightAssociative = true) + + @Test + fun anOperatorTakesTheWholeOfAnOperatorThatBindsTighter() { + // `1 * 2` + 3 + assertTrue(plus.takesWhole(times)) + // 1 + `2` * 3 + assertFalse(times.takesWhole(plus)) + } + + @Test + fun operatorsOfTheSameLevelAreGroupedFromTheLeft() { + // `1 - 2` - 3 + assertTrue(plus.takesWhole(plus)) + } + + @Test + fun rightAssociativeOperatorsAreGroupedFromTheRight() { + // a = `b` = c + assertFalse(assignment.takesWhole(assignment)) + // x = `1` + 2 + assertFalse(plus.takesWhole(assignment)) + } +} From 1acb465947b0b62f34e46829721b4cfbf8f9ee88 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 20 Nov 2026 11:46:41 +0100 Subject: [PATCH 18/23] fix(mps-plugin): every child of a wrapped node has a containment link ModelixNodeAsMPSNode.getContainmentLink() resolved the role against the concept of the parent and returned null unless that gave an MPSChildLink. Where the concept resolves to a generated modelix concept, the link is a generated one, so a node with a parent had no containment link. MPS code relies on the two being null together: - Scope.parent goes from a node into its last node attribute, and from an attribute up to the parent of the attributed node only if it sees the attribute in the smodelAttribute role. Without a role it went back to the attributed node and around again, so the background model checker looped forever in CheckVariableDoubling on a variable with a SuppressErrorsAnnotation or a doc comment, holding the read lock and freezing MPS. - SNodeOperations.getAllSiblings asserts the role, which failed in check_BaseDocCommentDuplication on a ClassifierDocComment. The role of an MPS node already is the id of its MPS link, so the link is now taken from it before anything is resolved. A role that can't be turned into an MPS link becomes an InvalidContainmentLink with its name, as MPS uses for a role the concept doesn't declare, which is enough for the code that only compares roles. The ConstraintsChecker of MPS only checks "can be child" when the link of a child is one of its parent concept's, so it now runs on wrapped nodes too. For the operations of a DotExpression it reports errors that MPS itself doesn't, which this doesn't fix. Co-Authored-By: Claude Opus 5.5 --- .../ssr/mps/ModelixNodeAsMPSNodeTest.kt | 76 ++++++++++++++++++- .../mpsadapters/tomps/ModelixNodeAsMPSNode.kt | 17 ++++- 2 files changed, 89 insertions(+), 4 deletions(-) diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt index ed10376c..7cd9c2f9 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt @@ -1,6 +1,10 @@ package org.modelix.editor.ssr.mps +import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations +import jetbrains.mps.scope.Scope import jetbrains.mps.smodel.SNodePointer +import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory +import jetbrains.mps.smodel.adapter.structure.link.InvalidContainmentLink import org.jetbrains.mps.openapi.language.SReferenceLink import org.jetbrains.mps.openapi.model.ResolveInfo import org.jetbrains.mps.openapi.model.SNode @@ -8,12 +12,15 @@ import org.jetbrains.mps.openapi.persistence.PersistenceFacade import org.modelix.model.api.ConceptReference import org.modelix.model.api.IChildLinkReference import org.modelix.model.api.IWritableNode +import org.modelix.model.data.NodeData +import org.modelix.model.data.NodeDataAsNode +import org.modelix.model.mpsadapters.MPSChildLink import org.modelix.model.mpsadapters.MPSWritableNode import org.modelix.model.mpsadapters.tomps.ModelixNodeAsMPSNode /** * The parts of [ModelixNodeAsMPSNode] that MPS code reaches beyond reading the model: user objects and the ways of - * setting a reference other than to a node, and references whose target cannot be resolved. + * setting a reference other than to a node, references whose target cannot be resolved, and the role of attributes. */ @Suppress("ktlint:standard:function-naming") class ModelixNodeAsMPSNodeTest : TestBase("SimpleProject") { @@ -127,7 +134,74 @@ class ModelixNodeAsMPSNodeTest : TestBase("SimpleProject") { } } + /** + * A statement in the body of the first method with a `SuppressErrorsAnnotation` attached to it. + */ + private fun newAttributedStatement(): Pair { + val method = classNode.getAllChildren().first { it.getContainmentLink().getSimpleName() == "member" } + val body = method.getAllChildren().first { it.getContainmentLink().getSimpleName() == "body" } + val statement = + body.addNewChild(IChildLinkReference.fromName("statement"), -1, ConceptReference(BL + "1068581242864")) as MPSWritableNode + val attribute = + statement.addNewChild( + MPSChildLink(SMODEL_ATTRIBUTE).toReference(), + -1, + ConceptReference(CORE + "4222318806802425298"), + ) as MPSWritableNode + return statement to attribute + } + + fun `test an attribute is in the attribute role`() { + writeAction { + val (_, attribute) = newAttributedStatement() + assertEquals(SMODEL_ATTRIBUTE, wrap(attribute).containmentLink) + assertTrue(SNodeOperations.isAttribute(wrap(attribute))) + } + } + + /** + * MPS walks up the ancestors of a node through its attributes. The walk only goes on from an attribute to the + * parent of the attributed node if it recognizes the attribute as one, and otherwise goes back and forth forever. + */ + fun `test the scope walk goes from an attribute to the parent of the attributed node`() { + writeAction { + val (statement, attribute) = newAttributedStatement() + assertEquals(wrap(attribute), Scope.parent(wrap(statement))) + assertEquals(wrap(statement).parent, Scope.parent(wrap(attribute))) + } + } + + fun `test the siblings of an attribute are the other children in its role`() { + writeAction { + val (_, attribute) = newAttributedStatement() + assertEquals(listOf(wrap(attribute)), SNodeOperations.getAllSiblings(wrap(attribute), true)) + } + } + + /** + * A child always has a containment link, even if its role can't be turned into an MPS link. + */ + fun `test a role that is no MPS link is an invalid link with its name`() { + val parent = + NodeDataAsNode( + NodeData(id = "parent", children = listOf(NodeData(id = "child", role = "notAnMPSLink"))), + null, + ) + val link = checkNotNull(wrap(parent.getAllChildren().single()).containmentLink) { "A child without a role" } + assertEquals(InvalidContainmentLink(null, "notAnMPSLink"), link) + assertEquals("notAnMPSLink", link.name) + } + companion object { private const val BL = "mps:f3061a53-9226-4cc5-a443-f952ceaf5816/" + private const val CORE = "mps:ceab5195-25ea-4f22-9b92-103b95ca8c0c/" + private val SMODEL_ATTRIBUTE = + MetaAdapterFactory.getContainmentLink( + 0xceab519525ea4f22uL.toLong(), + 0x9b92103b95ca8c0cuL.toLong(), + 0x10802efe25aL, + 0x47bf8397520e5942L, + "smodelAttribute", + ) } } diff --git a/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt b/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt index 645cc161..df2c35b8 100644 --- a/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt +++ b/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt @@ -1,6 +1,7 @@ package org.modelix.model.mpsadapters.tomps import jetbrains.mps.smodel.SNodeUtil +import jetbrains.mps.smodel.adapter.structure.link.InvalidContainmentLink import org.jetbrains.mps.openapi.language.SAbstractConcept import org.jetbrains.mps.openapi.language.SConcept import org.jetbrains.mps.openapi.language.SContainmentLink @@ -21,7 +22,7 @@ import org.modelix.model.api.IReferenceLinkReference import org.modelix.model.api.IWritableNode import org.modelix.model.api.NullChildLinkReference import org.modelix.model.api.remove -import org.modelix.model.api.resolve +import org.modelix.model.api.tryResolve import org.modelix.model.mpsadapters.MPSChildLink import org.modelix.model.mpsadapters.MPSConcept import org.modelix.model.mpsadapters.MPSNode @@ -202,9 +203,19 @@ data class ModelixNodeAsMPSNode( override fun getContainingRoot(): jetbrains.mps.smodel.SNode = treeParent()?.containingRoot ?: this + /** + * Null if and only if the node has no parent. MPS code relies on every child having a containment link. A role + * that can't be turned into an MPS link is an [InvalidContainmentLink] with its name, like MPS uses for a role + * that the concept doesn't declare, which is still good for the code that only compares roles. + */ override fun getContainmentLink(): SContainmentLink? { - val link = node.getContainmentLink().resolve(node.getParent()?.getConceptReference() ?: return null) - return (link as? MPSChildLink)?.link + val parent = node.getParent() ?: return null + val role = node.getContainmentLink() + MPSChildLink.tryFromReference(role)?.let { return it.link } + val parentConcept = parent.getConceptReference() + val link = role.tryResolve(parentConcept) + return ((link as? MPSChildLink) ?: link?.toReference()?.let { MPSChildLink.tryFromReference(it) })?.link + ?: InvalidContainmentLink(parentConcept.tryResolve()?.getLongName(), role.getNameOrId()) } override fun getFirstChild(): SNode? = node.getAllChildren().firstOrNull().wrap() From 50c46f952c11dbc25aa1c45f58b9cbb277812813 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 20 Nov 2026 11:47:04 +0100 Subject: [PATCH 19/23] chore(projectional-editor): sandbox with baseLanguage code for trying the editor A solution in the MPS project, outside every publication, whose classes exercise the recent editor changes in the web editor. Comments in the code say what to type or press and what to expect: - TypingPlayground: lines to type key by key, things to delete, and operators to type over. - OperatorPrecedence: operators to type behind the last operand of another one, and expressions that must show no parentheses the model doesn't have. - ContextActions: nodes with MPS intentions for Alt+Enter, in a class long enough for the menu to open above a node. - QuickFixes: type errors that MPS offers quick fixes for. - NodeAttributes: doc comments, an annotation and a SuppressErrorsAnnotation. The model uses only baseLanguage and javadoc (plus lang.text for the comments), so the completion offers nothing else. Co-Authored-By: Claude Opus 5.5 --- mps/.mps/modules.xml | 1 + ...mps.notation.impl.baseLanguage.sandbox.mps | 3642 +++++++++++++++++ ...mps.notation.impl.baseLanguage.sandbox.msd | 28 + 3 files changed, 3671 insertions(+) create mode 100644 mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/models/org.modelix.mps.notation.impl.baseLanguage.sandbox.mps create mode 100644 mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/org.modelix.mps.notation.impl.baseLanguage.sandbox.msd diff --git a/mps/.mps/modules.xml b/mps/.mps/modules.xml index 262af030..6319c321 100644 --- a/mps/.mps/modules.xml +++ b/mps/.mps/modules.xml @@ -2,6 +2,7 @@ + diff --git a/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/models/org.modelix.mps.notation.impl.baseLanguage.sandbox.mps b/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/models/org.modelix.mps.notation.impl.baseLanguage.sandbox.mps new file mode 100644 index 00000000..b01c0fb1 --- /dev/null +++ b/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/models/org.modelix.mps.notation.impl.baseLanguage.sandbox.mps @@ -0,0 +1,3642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/org.modelix.mps.notation.impl.baseLanguage.sandbox.msd b/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/org.modelix.mps.notation.impl.baseLanguage.sandbox.msd new file mode 100644 index 00000000..ca01d9ed --- /dev/null +++ b/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/org.modelix.mps.notation.impl.baseLanguage.sandbox.msd @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + 6354ebe7-c22a-4a0f-ac54-50b52ab9b065(JDK) + + + + + + + + + + + + + + From d3f59cb6a657f4acfa4f54d822fcfb09b931a0b2 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 20 Nov 2026 12:31:09 +0100 Subject: [PATCH 20/23] fix(mps-plugin): the containment link of a wrapped node is the one MPS uses MPS generates `link == link/DotExpression : operation/` in a constraint as a comparison with `==`, and keeps one instance per link in MetaAdapterFactory, which its nodes return. ModelixNodeAsMPSNode created a new link adapter on each call, equal but not the same, so the "can be child" rule of IOperation failed: the web editor reported "FieldReferenceOperation cannot be child of DotExpression" for every operation that has no rule of its own, which MPS doesn't. An MPS link is now the instance MetaAdapterFactory keeps for its id. Co-Authored-By: Claude Opus 5.5 --- .../ssr/mps/ModelixNodeAsMPSNodeTest.kt | 46 +++++++++++++++++-- .../mpsadapters/tomps/ModelixNodeAsMPSNode.kt | 13 +++++- 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt index 7cd9c2f9..697c04bf 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/ModelixNodeAsMPSNodeTest.kt @@ -1,6 +1,7 @@ package org.modelix.editor.ssr.mps import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations +import jetbrains.mps.nodeEditor.menus.CanBeChildPredicate import jetbrains.mps.scope.Scope import jetbrains.mps.smodel.SNodePointer import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory @@ -44,12 +45,16 @@ class ModelixNodeAsMPSNodeTest : TestBase("SimpleProject") { private val rawClass: SNode get() = classNode.node + private fun firstMethodBody(): IWritableNode { + val method = classNode.getAllChildren().first { it.getContainmentLink().getSimpleName() == "member" } + return method.getAllChildren().first { it.getContainmentLink().getSimpleName() == "body" } + } + /** * A `Class1 x;` in the body of the first method, whose `ClassifierType` has no target yet. */ private fun newClassifierType(): MPSWritableNode { - val method = classNode.getAllChildren().first { it.getContainmentLink().getSimpleName() == "member" } - val body = method.getAllChildren().first { it.getContainmentLink().getSimpleName() == "body" } + val body = firstMethodBody() return body .addNewChild(IChildLinkReference.fromName("statement"), -1, ConceptReference(BL + "1068581242864")) .addNewChild(IChildLinkReference.fromName("localVariableDeclaration"), -1, ConceptReference(BL + "1068581242863")) @@ -138,8 +143,7 @@ class ModelixNodeAsMPSNodeTest : TestBase("SimpleProject") { * A statement in the body of the first method with a `SuppressErrorsAnnotation` attached to it. */ private fun newAttributedStatement(): Pair { - val method = classNode.getAllChildren().first { it.getContainmentLink().getSimpleName() == "member" } - val body = method.getAllChildren().first { it.getContainmentLink().getSimpleName() == "body" } + val body = firstMethodBody() val statement = body.addNewChild(IChildLinkReference.fromName("statement"), -1, ConceptReference(BL + "1068581242864")) as MPSWritableNode val attribute = @@ -154,7 +158,7 @@ class ModelixNodeAsMPSNodeTest : TestBase("SimpleProject") { fun `test an attribute is in the attribute role`() { writeAction { val (_, attribute) = newAttributedStatement() - assertEquals(SMODEL_ATTRIBUTE, wrap(attribute).containmentLink) + assertSame(SMODEL_ATTRIBUTE, wrap(attribute).containmentLink) assertTrue(SNodeOperations.isAttribute(wrap(attribute))) } } @@ -178,6 +182,38 @@ class ModelixNodeAsMPSNodeTest : TestBase("SimpleProject") { } } + /** + * A `this.` in the body of the first method, whose `FieldReferenceOperation` has no target yet. + */ + private fun newFieldReferenceOperation(): MPSWritableNode { + val dot = + firstMethodBody() + .addNewChild(IChildLinkReference.fromName("statement"), -1, ConceptReference(BL + "1068580123155")) + .addNewChild(IChildLinkReference.fromName("expression"), -1, ConceptReference(BL + "1197027756228")) + dot.addNewChild(IChildLinkReference.fromName("operand"), -1, ConceptReference(BL + "1070475354124")) + return dot.addNewChild(IChildLinkReference.fromName("operation"), -1, ConceptReference(BL + "1197029447546")) as MPSWritableNode + } + + /** + * The code MPS generates for `link == link/DotExpression : operation/` compares the links with `==`. + */ + fun `test the containment link is the instance MPS uses for it`() { + writeAction { + val operation = newFieldReferenceOperation() + assertSame(operation.node.containmentLink, wrap(operation).containmentLink) + } + } + + /** + * The `can be child` rule of `IOperation` is one of those that compare links with `==`. + */ + fun `test an operation can be a child of a dot expression`() { + writeAction { + val operation = wrap(newFieldReferenceOperation()) + assertTrue(CanBeChildPredicate(checkNotNull(operation.parent), operation.containmentLink).test(operation.concept)) + } + } + /** * A child always has a containment link, even if its role can't be turned into an MPS link. */ diff --git a/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt b/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt index df2c35b8..0c69f7da 100644 --- a/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt +++ b/reverse-mpsadapters/src/main/kotlin/org/modelix/model/mpsadapters/tomps/ModelixNodeAsMPSNode.kt @@ -1,7 +1,10 @@ package org.modelix.model.mpsadapters.tomps import jetbrains.mps.smodel.SNodeUtil +import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory import jetbrains.mps.smodel.adapter.structure.link.InvalidContainmentLink +import jetbrains.mps.smodel.adapter.structure.link.SContainmentLinkAdapter +import jetbrains.mps.smodel.adapter.structure.link.SContainmentLinkAdapterById import org.jetbrains.mps.openapi.language.SAbstractConcept import org.jetbrains.mps.openapi.language.SConcept import org.jetbrains.mps.openapi.language.SContainmentLink @@ -207,17 +210,23 @@ data class ModelixNodeAsMPSNode( * Null if and only if the node has no parent. MPS code relies on every child having a containment link. A role * that can't be turned into an MPS link is an [InvalidContainmentLink] with its name, like MPS uses for a role * that the concept doesn't declare, which is still good for the code that only compares roles. + * + * An MPS link is the instance [MetaAdapterFactory] keeps for its id, as on the nodes of MPS, because the code that + * MPS generates for `link == link/C : role/` compares them with `==`. */ override fun getContainmentLink(): SContainmentLink? { val parent = node.getParent() ?: return null val role = node.getContainmentLink() - MPSChildLink.tryFromReference(role)?.let { return it.link } + MPSChildLink.tryFromReference(role)?.let { return it.link.cached() } val parentConcept = parent.getConceptReference() val link = role.tryResolve(parentConcept) - return ((link as? MPSChildLink) ?: link?.toReference()?.let { MPSChildLink.tryFromReference(it) })?.link + return ((link as? MPSChildLink) ?: link?.toReference()?.let { MPSChildLink.tryFromReference(it) })?.link?.cached() ?: InvalidContainmentLink(parentConcept.tryResolve()?.getLongName(), role.getNameOrId()) } + private fun SContainmentLinkAdapter.cached(): SContainmentLink = + if (this is SContainmentLinkAdapterById) MetaAdapterFactory.getContainmentLink(id, name) else this + override fun getFirstChild(): SNode? = node.getAllChildren().firstOrNull().wrap() override fun getLastChild(): SNode? = node.getAllChildren().lastOrNull().wrap() From a194e604672633c03acfabba4739061da7bfddab Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 20 Nov 2026 13:25:42 +0100 Subject: [PATCH 21/23] fix(mps-plugin): don't check a deleted node as a root node The editor asks for the messages of the nodes it shows, and they are checked a moment later. A node deleted in between, like a statement replaced while typing, was checked as a root node: getRootNode stops at a node without a parent, and an MPS node without a parent reports the role of a root node. MPS's ConstraintsChecker then checks it as a root of its model, which it doesn't have: IllegalArgumentException: Argument for @NotNull parameter 'model' of CanBeRootContext. must not be null The node also stayed among the checked roots for good, because MPSWritableNode.isValid() is always true (fixed in modelix.core#3105). A root node is now also required to have a parent, its model, so getRootNodeOrNull returns null for a node that isn't part of a model, as it says it does. Co-Authored-By: Claude Opus 5.5 --- .../editor/common/IncrementalModelChecker.kt | 7 ++++- .../editor/ssr/mps/BaseLanguageTests.kt | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/IncrementalModelChecker.kt b/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/IncrementalModelChecker.kt index c642d5cc..62995fb0 100644 --- a/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/IncrementalModelChecker.kt +++ b/editor-common-mps/src/main/kotlin/org/modelix/mps/editor/common/IncrementalModelChecker.kt @@ -179,8 +179,13 @@ class IncrementalModelChecker( private class CheckCancelledException : RuntimeException("Model check cancelled") + /** + * A root node is a child of its model. An MPS node that isn't part of a model, like one that was deleted, has the + * role of a root node too, but no parent. + */ private fun INode.isRootNode() = - getContainmentLink()?.getUID() == + parent != null && + getContainmentLink()?.getUID() == BuiltinLanguages.MPSRepositoryConcepts.Model.rootNodes .getUID() diff --git a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt index 4ab01693..5cf30bbb 100644 --- a/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt +++ b/projectional-editor-ssr-mps-languages/src/test/kotlin/org/modelix/editor/ssr/mps/BaseLanguageTests.kt @@ -31,6 +31,7 @@ import org.modelix.model.api.IPropertyReference import org.modelix.model.api.IReferenceLinkReference import org.modelix.model.api.IWritableNode import org.modelix.model.api.getDescendants +import org.modelix.model.api.remove import org.modelix.model.mpsadapters.MPSWritableNode import org.modelix.model.mpsadapters.tomps.ModelixNodeAsMPSNode import org.modelix.mps.editor.common.IncrementalModelChecker @@ -510,6 +511,33 @@ class BaseLanguageTests : BaseLanguageTestBase() { } } + /** + * The editor may ask for the messages of a node that is deleted before the check runs. MPS checks a node without + * a parent as a root node, which fails without a model. + */ + fun `test a node that was deleted from the model is not checked as a root node`() { + val engine = IncrementalEngine() + try { + val checker = IncrementalModelChecker(engine) + val statement = + writeAction { + methodBodyNode.addNewChild( + IChildLinkReference.fromName("statement"), + -1, + ConceptReference(BL + "1068580123157") + ) + } + writeAction { statement.remove() } + readAction { + assertNull(checker.getRootNodeOrNull(statement.asLegacyNode())) + assertNull(checker.getMessagesOfRoot(statement.asLegacyNode())) + assertNotNull(checker.getRootNodeOrNull(classNode.asLegacyNode())) + } + } finally { + engine.dispose() + } + } + /** * The model checker publishes its messages asynchronously, so they are only shown eventually. */ From cfc3d877d8119755bbcae185cd0c5b4e1b41e97e Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 20 Nov 2026 13:25:47 +0100 Subject: [PATCH 22/23] chore(projectional-editor): don't generate the sandbox The sandbox holds code with type errors on purpose, for the quick fixes in the context actions menu, and javac fails on them. Its model is now marked "do not generate", so a make of the project skips it. Co-Authored-By: Claude Opus 5.5 --- .../org.modelix.mps.notation.impl.baseLanguage.sandbox.mps | 1 + 1 file changed, 1 insertion(+) diff --git a/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/models/org.modelix.mps.notation.impl.baseLanguage.sandbox.mps b/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/models/org.modelix.mps.notation.impl.baseLanguage.sandbox.mps index b01c0fb1..39c0b97c 100644 --- a/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/models/org.modelix.mps.notation.impl.baseLanguage.sandbox.mps +++ b/mps/modules/org.modelix.mps.notation.impl.baseLanguage.sandbox/models/org.modelix.mps.notation.impl.baseLanguage.sandbox.mps @@ -1,6 +1,7 @@ + From 49acba936fbc724c388707dc687ca149d62f6bb5 Mon Sep 17 00:00:00 2001 From: Sascha Lisson Date: Fri, 20 Nov 2026 15:27:56 +0100 Subject: [PATCH 23/23] build: drop the kotlinx-html repository on JetBrains Space maven.pkg.jetbrains.space doesn't resolve anymore, and an unreachable repository fails a resolution instead of being skipped: the CI builds stopped at the local MPS of the IntelliJ Platform Gradle Plugin, which Gradle looks for in every repository. kotlinx-html is on Maven Central. Co-Authored-By: Claude Opus 5.5 --- build.gradle.kts | 1 - 1 file changed, 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index 43bcf609..3697431a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -64,7 +64,6 @@ subprojects { repositories { maven { url = uri("https://artifacts.itemis.cloud/repository/maven-mps/") } - maven { url = uri("https://maven.pkg.jetbrains.space/public/p/kotlinx-html/maven") } mavenCentral() mavenLocal() }