From 93a9f04b11bbdb51deafe64e439829e78ae24ab9 Mon Sep 17 00:00:00 2001 From: Konrad Neitzel Date: Tue, 24 Nov 2026 15:13:31 +0100 Subject: [PATCH] Edit form controls and render localized application previews in the IntelliJ designer --- README.md | 6 +- .../neitzel/fxdesigner/kit/DesignerPane.java | 220 +++++++- .../neitzel/fxdesigner/kit/FormDocument.java | 494 ++++++++++++++++++ .../de/neitzel/fxdesigner/kit/FormEditor.java | 238 +++++++++ .../fxdesigner/kit/FxmlProjection.java | 16 +- .../fxdesigner/kit/FormDocumentTest.java | 134 +++++ .../fxdesigner/target/BindingDiscovery.java | 26 +- .../target/ViewModelComputedTest.java | 16 +- .../resources/fixture/components/Full.fxml | 4 +- .../test/java/fixture/checks/StageChecks.java | 7 + .../resources/fixture/components/Full.fxml | 4 +- .../main/java/fixture/checks/StageChecks.java | 7 + .../idea/ArchiveWorkflowProbe.java | 29 +- .../idea/ConnectionTargetProbe.java | 89 ++++ .../idea/ConnectionWorkflowProbe.java | 348 ++++++++++++ integration-tests/idea/WorkflowProbe.java | 20 + scripts/check-ide-host.py | 13 +- scripts/run-fixture-host.py | 15 +- 18 files changed, 1623 insertions(+), 63 deletions(-) create mode 100644 designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormDocument.java create mode 100644 designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormEditor.java create mode 100644 designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FormDocumentTest.java create mode 100644 integration-tests/idea/ConnectionTargetProbe.java create mode 100644 integration-tests/idea/ConnectionWorkflowProbe.java diff --git a/README.md b/README.md index 447c4fb..99f4f3a 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ python3 scripts/check-ide-host.py --java-home "$JAVA_HOME" --target-java-home "$ ### Archiver in IntelliJ -Build the [pinned NeitzelLib snapshot](docs/runtime/neitzellib-baseline.md), then build the Designer modules and plugin with the bootstrap command above. Archiver includes its example in the `designer-preview` Maven profile. To open an isolated IntelliJ instance with a project copy and the built plugin, run from this checkout with the same Maven environment: +Build the [pinned NeitzelLib snapshot](docs/runtime/neitzellib-baseline.md), then build the Designer modules and plugin with the bootstrap command above. Archiver includes its preview examples in the `designer-preview` Maven profile. To open an isolated IntelliJ instance with a project copy and the built plugin, run from this checkout with the same Maven environment: ```sh python3 scripts/run-fixture-host.py intellij --archiver ../Archiver \ @@ -77,6 +77,10 @@ python3 scripts/run-fixture-host.py intellij --archiver ../Archiver \ Open `ArchiveWindow.fxml` in **Neitzel Designer**, choose **Build and Refresh** and start **Interactive preview** with **Beispielarchiv**. The open menu command enables the trash button. Under **Bindings → Command bindings** select `open`, change its path to `openReadOnly`, apply and restart the preview. The status bar identifies the read-only example. **Discover / Validate Commands** lists public getters returning a NeitzelLib `Command`, including the Command exposed by an `AsyncCommand`. The Problems view navigates to an invalid declaration. To repeat the automated acceptance, use the same arguments with `python3 scripts/check-ide-host.py --archiver ../Archiver` (omit the `intellij` positional argument). +Add `--connection-form` to open or qualify `ConnectionForm.fxml`. After **Build and Refresh**, choose **Form preview** and select **IMAP · Beispielkonto** or **JMAP · Beispielkonto**. The full image comes from the target application at the selected width and height. **Interactive preview** opens a separate, editable instance of the selected example. + +In **Form controls**, select the palette type, destination child list and insertion position, then **Insert control**. Select a control on the canvas or in **Selected control**. **Set property** and **Reset property** edit its FXML, and **Bind property** opens the direct-binding form. For **suggestions**, enter one string per line. To reorder or move a child, choose its destination and position, then **Move to destination**. Each change participates in IntelliJ Undo and Redo. + For an existing Archiver checkout, install the built plugin ZIP and create the ignored local JDK and worker mappings once with `python3 scripts/configure-library-example.py --project ../Archiver --target-java-home "$JAVA_HOME"`. Launch the IDE with access to the Maven repository containing the qualified snapshots. The [save/startup reliability follow-up](docs/ide-host-reliability.md) covers queued IntelliJ VFS writes and host-revision/validation races, including repeated registered module-path qualification. Add `--mode modulepath --repeat 3` to the IDE runner to repeat that gate. diff --git a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/DesignerPane.java b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/DesignerPane.java index 6daa4e4..806b82d 100644 --- a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/DesignerPane.java +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/DesignerPane.java @@ -35,6 +35,13 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { return content; } + private FormEditor formEditor; + private final ImageView wholeImage = new ImageView(); + private final Spinner previewWidth = new Spinner<>(120, 1600, 760, 40); + private final Spinner previewHeight = new Spinner<>(100, 1200, 520, 40); + private final Label previewState = new Label("Build and Refresh, then select an example."); + private boolean showWhole; + private final VBox componentInspector = new VBox(4); private void componentSelection() { @@ -43,6 +50,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { var hit = kit.editor().getSelection().getHitItem(); if (hit == null) return; String id = hit.getFxId(); + if (formEditor != null) formEditor.selectIndex(projection.sourceIndex(id)); if (bindingEditor != null) bindingEditor.selectControl(id); if (computedEditor != null) computedEditor.selectControl(id); if (repeatEditor != null) repeatEditor.selectControl(id); @@ -233,7 +241,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { fx( () -> { invalidateBindings("Document changed; discover bindings again."); - if (interactiveRequested) + if (interactiveRequested && affectsInteractive(uri)) interactiveStatus.setText( "Interactive preview uses earlier drafts; rerun or save to" + " restart"); @@ -252,7 +260,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { if (Path.of(uri).startsWith(reactorRoot)) fx( () -> { - if (interactiveRequested) { + if (interactiveRequested && affectsInteractive(uri)) { interactiveRestart = true; interactiveRequest++; interactiveWorkflow.cancel(); @@ -330,13 +338,68 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { return null; } }); + examples.setId("preview-example"); + examples + .valueProperty() + .addListener( + (o, before, after) -> { + renderSequence.incrementAndGet(); + clearFormPreview( + after == null + ? "Build and Refresh, then select an example." + : "Rendering " + after.label() + "…"); + if (interactiveRequested) { + interactiveRequest++; + interactiveWorkflow.cancel(); + interactiveRestart = true; + } + resize.playFromStart(); + }); + previewWidth.setId("preview-width"); + previewHeight.setId("preview-height"); + previewState.setId("preview-state"); + wholeImage.setId("full-preview-image"); + wholeImage.setPreserveRatio(true); + var picture = new ScrollPane(wholeImage); + picture.setMinSize(0, 0); + picture + .viewportBoundsProperty() + .addListener( + (o, a, bounds) -> { + wholeImage.setFitWidth(Math.max(1, bounds.getWidth())); + wholeImage.setFitHeight(Math.max(1, bounds.getHeight())); + }); + VBox.setVgrow(picture, Priority.ALWAYS); + var fullPreview = + new VBox( + 4, + new FlowPane( + 5, 4, new Label("Width"), previewWidth, new Label("Height"), previewHeight), + previewState, + picture); + previewWidth.valueProperty().addListener((o, a, b) -> previewSizeChanged()); + previewHeight.valueProperty().addListener((o, a, b) -> previewSizeChanged()); var split = new SplitPane(source, design); + split + .getItems() + .addListener( + (javafx.collections.ListChangeListener) + change -> { + showWhole = split.getItems().contains(fullPreview); + }); sourceSplit = split; split.setDividerPositions(.3); var modes = new ToolBar( button("Source", () -> split.getItems().setAll(source)), button("Design", () -> split.getItems().setAll(design)), + button( + "Form preview", + () -> { + split.getItems().setAll(design, fullPreview); + split.setDividerPositions(.48); + render(); + }), button( "Split", () -> { @@ -381,7 +444,48 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { discoveryTab, generationTab)); bindings.setExpanded(false); - center.setBottom(new VBox(properties, bindings)); + formEditor = + new FormEditor( + edit -> + flush() + .whenComplete( + (ok, error) -> + fx( + () -> { + if (error != null) report(error); + else if (draft.writable() && draft.text().equals(edit.source())) + submit(edit.changes(), "Edit form"); + else + status.setText("Document changed; select the control again."); + })), + index -> { + if (loading || projection == null || kit.editor().getFxomDocument() == null) return; + String id = projection.canvasId(index); + if (id == null) return; + var object = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id); + if (object != null && kit.editor().getSelection().getHitItem() != object) + kit.editor().getSelection().select(object); + }, + values -> { + bindings.setExpanded(true); + directBindingTab.getTabPane().getSelectionModel().select(directBindingTab); + bindingEditor.newBinding(values); + }); + var formPane = new TitledPane("Form controls", formEditor); + formPane.setExpanded(false); + formPane + .expandedProperty() + .addListener( + (o, a, b) -> { + if (b) bindings.setExpanded(false); + }); + bindings + .expandedProperty() + .addListener( + (o, a, b) -> { + if (b) formPane.setExpanded(false); + }); + center.setBottom(new VBox(properties, formPane, bindings)); output.setEditable(false); output.setPrefRowCount(5); Path origin = file.resolveSibling(file.getFileName() + ".origin"); @@ -421,7 +525,8 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { fx( () -> { if (error != null) report(error); - else if (draft == null || d.revision() != draft.revision()) + else if (!pending + && (draft == null || d.revision() > draft.revision())) load(d); })); })); @@ -480,6 +585,11 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { new HostServices.Diagnostic( "Designer", HostServices.Severity.ERROR, String.valueOf(error), Optional.empty())); if (draft != null && diagnosticsPane != null) validationUnavailable(error); + if (showWhole) + clearFormPreview( + "Preview unavailable · " + + error.getMessage() + + " · use Build and Refresh after correcting the problem."); status.setText("Designer: " + error.getMessage()); log(error.toString()); } @@ -520,6 +630,8 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { } } draft = value; + formEditor.load(value.text(), value.writable()); + clearFormPreview("Draft changed · select an example to render the current revision."); publishDiagnostics("Source checked; target validation outdated", java.util.List.of()); bindingEditor.load(value.text(), value.writable()); computedEditor.load(value.text(), value.writable()); @@ -553,6 +665,9 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { var hit = kit.editor().getSelection().getHitItem(); String selectedId = hit == null ? null : hit.getFxId(); draft = value; + String requestedSelection = formEditor.load(value.text(), value.writable()); + if (!requestedSelection.isEmpty()) selectedId = requestedSelection; + clearFormPreview("Draft changed · select an example to render the current revision."); publishDiagnostics("Source checked; target validation outdated", java.util.List.of()); bindingEditor.load(value.text(), value.writable()); computedEditor.load(value.text(), value.writable()); @@ -627,7 +742,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { loading = false; // The change debounce may already have fired against the previous draft. // Render only after the authoritative revision and its projection agree. - if (projection != null && examples.getValue() != null) resize.playFromStart(); + if ((projection != null || showWhole) && examples.getValue() != null) resize.playFromStart(); if (pendingSourceOffset != null) { int offset = pendingSourceOffset; pendingSourceOffset = null; @@ -956,6 +1071,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { errors.addAll(new ReferenceDocument(draft.text()).referenceErrors()); if (errors.isEmpty()) return true; status.setText("Preview blocked: " + String.join("; ", errors)); + clearFormPreview(status.getText()); if (projection != null) for (String id : projection.components().keySet()) { var region = proxy(id); @@ -1006,6 +1122,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { validationUnavailable(error); status.setText( "Binding validation unavailable: " + error.getMessage()); + clearFormPreview( + status.getText() + + " · use Build and Refresh, or choose Preview last" + + " successful."); return; } validatedSource = captured.text(); @@ -1116,6 +1236,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { withDraft( () -> { renderSequence.incrementAndGet(); + clearFormPreview("Building selected context…"); status.setText("Building selected context…"); buildRun = workflow.build(approvals); buildRun @@ -1151,6 +1272,11 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { } } else if (result.status() == BuildRefresh.Status.READY) discover(false); + else + clearFormPreview( + result.message() + + " · correct the build and use Build and Refresh, or choose" + + " Preview last successful."); })); }); } @@ -1197,6 +1323,27 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { }); } + private void clearFormPreview(String message) { + wholeImage.setImage(null); + previewState.setText(message); + } + + private void previewSizeChanged() { + renderSequence.incrementAndGet(); + wholeImage.setImage(null); + previewState.setText("Rendering selected size…"); + resize.playFromStart(); + } + + private boolean affectsInteractive(java.net.URI uri) { + if (file.toUri().equals(uri) || Path.of(uri).equals(file)) return true; + if (projection == null) return false; + String path = Path.of(uri).toString().replace(java.io.File.separatorChar, '/'); + return java.util.stream.Stream.concat( + projection.navigationTypes().values().stream(), projection.rowComponents().stream()) + .anyMatch(type -> path.endsWith("/" + type.replace('.', '/') + ".fxml")); + } + public void render() { withDraft( () -> { @@ -1212,14 +1359,18 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { .filter(p -> p.severity().equals("ERROR")) .map(p -> p.message()) .collect(java.util.stream.Collectors.joining("; "))); + clearFormPreview(status.getText()); return; } var selected = examples.getValue(); if (selected == null) { - status.setText("Select a preview example after Build and Refresh."); + previewState.setText( + "Select a preview example after Build and Refresh. If none is listed, register an" + + " example for this FXML."); + status.setText(previewState.getText()); return; } - if (projection == null && !interactiveRequested) return; + if (projection == null && !interactiveRequested && !showWhole) return; long ticket = renderSequence.incrementAndGet(); host.documents() .snapshots() @@ -1305,6 +1456,8 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { + " restart"); })); } + if (showWhole) + nodes.put("", new DesignerWorkflow.Size(previewWidth.getValue(), previewHeight.getValue())); if (nodes.isEmpty()) { status.setText( projection == null @@ -1320,14 +1473,19 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { () -> { if (ticket != renderSequence.get()) return; if (error != null) { - projection - .components() - .keySet() - .forEach( - id -> { - var region = proxy(id); - if (region != null) region.failed(); - }); + if (showWhole) { + wholeImage.setImage(null); + previewState.setText("Preview failed: " + error.getMessage()); + } + if (projection != null) + projection + .components() + .keySet() + .forEach( + id -> { + var region = proxy(id); + if (region != null) region.failed(); + }); report(error); return; } @@ -1354,6 +1512,21 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { argb, 0, width); + if (frame.node().isEmpty()) { + wholeImage.setImage(image); + previewState.setText( + (last + ? "Retained build · Build and Refresh for current sources · " + : "") + + examples.getValue().label() + + " · " + + width + + " × " + + height + + " · revision " + + draft.revision()); + continue; + } images.put(frame.node(), image); var region = proxy(frame.node()); if (region != null) { @@ -1365,14 +1538,15 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { layoutPasses = measurementsChanged ? layoutPasses + 1 : 0; if (layoutPasses >= 8) { resize.stop(); - projection - .components() - .keySet() - .forEach( - id -> { - var region = proxy(id); - if (region != null) region.failed(); - }); + if (projection != null) + projection + .components() + .keySet() + .forEach( + id -> { + var region = proxy(id); + if (region != null) region.failed(); + }); status.setText("Target layout did not stabilize; retaining last layout"); return; } diff --git a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormDocument.java b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormDocument.java new file mode 100644 index 0000000..65b219a --- /dev/null +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormDocument.java @@ -0,0 +1,494 @@ +package de.neitzel.fxdesigner.kit; + +import de.neitzel.fxdesigner.contracts.EditBatch.Replacement; +import java.util.*; +import javafx.scene.layout.*; +import org.w3c.dom.*; + +/** + * Visual form operations use ranges from the current source so bindings keep their original text. + */ +final class FormDocument { + static final Map TYPES = new TreeMap<>(); + + static { + register( + "javafx.scene.control", + "Label TextField TextArea PasswordField Button CheckBox ComboBox ToolBar"); + register( + "javafx.scene.layout", "GridPane VBox HBox StackPane AnchorPane FlowPane TilePane Pane"); + register( + "de.neitzel.fx.control", + "StatusBar ToolBarPane AutoCompleteTextField TagChip NonNegativeIntegerSpinner HtmlViewer"); + register("de.neitzel.fx.view", "DataGrid Table"); + register("de.neitzel.fx.docking", "DockPane"); + } + + private static void register(String pkg, String names) { + for (String name : names.split(" ")) TYPES.put(name, pkg + "." + name); + } + + record Item(int index, String type, String id) { + public String toString() { + return type + (id.isEmpty() ? " [" + index + "]" : " #" + id); + } + } + + record Slot(Item owner, String property) { + public String toString() { + return owner + " / " + property; + } + } + + record Edit(String source, List changes, String selectId) {} + + record Field(String name, String type, String fallback, boolean editable) { + public String toString() { + return name; + } + } + + private final BindingDocument xml; + final List items = new ArrayList<>(); + final List slots = new ArrayList<>(); + private final Map imports = new HashMap<>(); + private final Set packages = new HashSet<>(); + private final Set ids = new HashSet<>(); + + FormDocument(String text) throws Exception { + xml = new BindingDocument(text); + for (Node n = xml.document.getFirstChild(); n != null; n = n.getNextSibling()) { + if (n instanceof ProcessingInstruction pi && pi.getTarget().equals("import")) { + String type = pi.getData().trim(); + if (type.endsWith(".*")) packages.add(type.substring(0, type.length() - 2)); + else imports.put(simple(type), type); + } + } + for (int i = 0; i < xml.elements.size(); i++) { + var e = xml.elements.get(i); + String id = e.getAttributeNS(BindingDocument.FX, "id"); + if (!id.isEmpty()) ids.add(id); + String tag = e.getTagName(); + if (BindingDocument.FX.equals(e.getNamespaceURI()) && e.getLocalName().equals("root")) + tag = e.getAttribute("type"); + String type = simple(tag); + if (!TYPES.containsKey(type) || !resolves(tag, TYPES.get(type)) || inDefinition(e)) continue; + var item = new Item(i, type, id); + items.add(item); + for (String property : childLists(type)) slots.add(new Slot(item, property)); + } + } + + private boolean resolves(String tag, String type) { + if (tag.contains(".")) return tag.equals(type); + if (imports.containsKey(tag)) return type.equals(imports.get(tag)); + return packages.contains(type.substring(0, type.lastIndexOf('.'))); + } + + private static String simple(String type) { + return type.substring(type.lastIndexOf('.') + 1); + } + + private static boolean inDefinition(Element e) { + for (Node n = e; n instanceof Element parent; n = n.getParentNode()) + if (BindingDocument.FX.equals(parent.getNamespaceURI()) + && parent.getLocalName().equals("define")) return true; + return false; + } + + private static List childLists(String type) { + return switch (type) { + case "GridPane", "HBox", "VBox", "StackPane", "Pane", "AnchorPane", "FlowPane", "TilePane" -> + List.of("children"); + case "ToolBarPane", "ToolBar" -> List.of("items"); + case "StatusBar" -> List.of("leftItems", "rightItems"); + default -> List.of(); + }; + } + + private static List children(Element parent) { + var result = new ArrayList(); + for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) + if (n instanceof Element e) result.add(e); + return result; + } + + private static Element property(Element owner, String name) { + var matches = children(owner).stream().filter(e -> e.getTagName().equals(name)).toList(); + if (matches.size() > 1) + throw new IllegalArgumentException("Multiple " + name + " properties; edit in Source."); + return matches.isEmpty() ? null : matches.getFirst(); + } + + private Element owner(Slot slot) { + if (slot == null || !slots.contains(slot)) + throw new IllegalArgumentException("Choose a destination child list."); + return element(slot.owner()); + } + + private Element element(Item item) { + if (item == null || !items.contains(item)) + throw new IllegalArgumentException("Select a control in the form."); + return xml.elements.get(item.index()); + } + + private XmlSource.Tag tag(Element e) { + return xml.source.tags.get(xml.elements.indexOf(e)); + } + + private String fragment(Element e) { + var t = tag(e); + return xml.text.substring(t.start(), t.end()); + } + + private Edit edit(List edits, String id) { + return new Edit(xml.text, List.copyOf(edits), id); + } + + private String fresh(String type) { + String base = java.beans.Introspector.decapitalize(type), id = base; + for (int suffix = 2; ids.contains(id); suffix++) id = base + suffix; + return id; + } + + private String fxPrefix(Element e) { + String prefix = e.lookupPrefix(BindingDocument.FX); + if (prefix != null) return prefix; + prefix = "fx"; + for (int i = 2; e.lookupNamespaceURI(prefix) != null; i++) prefix = "fx" + i; + return prefix; + } + + private String namespace(Element e, String prefix) { + return e.lookupNamespaceURI(prefix) == null + ? " xmlns:" + prefix + "=\"" + BindingDocument.FX + "\"" + : ""; + } + + private List members(Slot slot) { + Element host = owner(slot), list = property(host, slot.property()); + if (list == null && slot.owner().type().equals("StatusBar")) return List.of(); + return children(list == null ? host : list).stream() + .filter( + e -> + !BindingDocument.FX.equals(e.getNamespaceURI()) + && Character.isUpperCase(simple(e.getTagName()).charAt(0))) + .toList(); + } + + int size(Slot slot) { + return members(slot).size(); + } + + private Replacement insert(Slot slot, int position, String snippet) { + var owner = owner(slot); + var members = members(slot); + if (position < 0 || position > members.size()) + throw new IllegalArgumentException("Position must be between 0 and " + members.size()); + if (position < members.size()) { + int start = tag(members.get(position)).start(); + return new Replacement(start, start, snippet + "\n"); + } + var container = property(owner, slot.property()); + if (container != null) return xml.append(container, snippet, ""); + if (slot.owner().type().equals("StatusBar") + || (slot.owner().type().equals("ToolBarPane") && members.isEmpty())) + snippet = "<" + slot.property() + ">" + snippet + ""; + return xml.append(owner, snippet, ""); + } + + Edit add(String type, Slot slot, int at) { + var host = owner(slot); + if (!TYPES.containsKey(type)) throw new IllegalArgumentException("Choose a palette control."); + String id = fresh(type), prefix = fxPrefix(host), qualified = TYPES.get(type); + var edits = new ArrayList(); + String tagName = type; + if (!resolves(type, qualified)) { + if (imports.containsKey(type)) tagName = qualified; + else { + int start = tag(xml.document.getDocumentElement()).start(); + edits.add(new Replacement(start, start, "\n")); + } + } + String extra = + type.equals("Label") || type.equals("Button") || type.equals("TagChip") + ? " text=\"" + type + "\"" + : ""; + if (slot.owner().type().equals("GridPane")) { + int row = 0; + for (var sibling : members(slot)) { + try { + row = + Math.max( + row, + Math.addExact( + Integer.parseInt( + sibling.getAttribute("GridPane.rowIndex").isEmpty() + ? "0" + : sibling.getAttribute("GridPane.rowIndex")), + 1)); + } catch (NumberFormatException ignored) { + /* Dynamic constraints remain verbatim. */ + } + } + String grid = + resolves("GridPane", TYPES.get("GridPane")) ? "GridPane" : TYPES.get("GridPane"); + extra += " " + grid + ".rowIndex=\"" + row + "\""; + } + edits.add( + insert( + slot, + at, + "<" + + tagName + + namespace(host, prefix) + + " " + + prefix + + ":id=\"" + + id + + "\"" + + extra + + "/>")); + return edit(edits, id); + } + + Edit move(Item item, Slot slot, int at) { + Element source = element(item), host = owner(slot); + if (slots.stream().noneMatch(s -> members(s).contains(source))) + throw new IllegalArgumentException("Only a child in a supported list can be moved."); + for (Node n = host; n != null; n = n.getParentNode()) + if (n == source) throw new IllegalArgumentException("Cannot move a control into itself."); + var current = members(slot); + int old = current.indexOf(source); + if (old >= 0 && (at == old || at == old + 1)) return edit(List.of(), item.id()); + var removed = tag(source); + String body = fragment(source); + // Moving across a locally declared namespace must preserve its interpretation. + for (Node n = source.getParentNode(); n instanceof Element ancestor; n = n.getParentNode()) + for (int i = 0; i < ancestor.getAttributes().getLength(); i++) { + var attr = ancestor.getAttributes().item(i); + if (javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attr.getNamespaceURI())) { + String prefix = attr.getNodeName().equals("xmlns") ? null : attr.getLocalName(); + if (!Objects.equals(host.lookupNamespaceURI(prefix), source.lookupNamespaceURI(prefix))) + throw new IllegalArgumentException( + "Destination namespace differs; move this control in Source."); + } + } + return edit( + List.of(new Replacement(removed.start(), removed.end(), ""), insert(slot, at, body)), + item.id()); + } + + List fields(Item item) { + var e = element(item); + var fields = new LinkedHashMap(); + field(fields, "styleClass", "CSS classes", "control default"); + field(fields, "padding", "Insets", item.type().equals("StatusBar") ? "4 8 4 8" : "0"); + field(fields, "style", "CSS", ""); + for (String dimension : + List.of("minWidth", "maxWidth", "minHeight", "maxHeight", "prefWidth", "prefHeight")) + field(fields, dimension, "Number", "-1"); + field(fields, "disable", "Boolean", "false"); + field(fields, "visible", "Boolean", "true"); + if (Set.of( + "Label", + "Button", + "CheckBox", + "TagChip", + "TextField", + "TextArea", + "PasswordField", + "AutoCompleteTextField") + .contains(item.type())) field(fields, "text", "String", ""); + if (Set.of("TextField", "TextArea", "PasswordField", "AutoCompleteTextField", "ComboBox") + .contains(item.type())) field(fields, "promptText", "String", ""); + if (item.type().equals("NonNegativeIntegerSpinner")) { + field(fields, "minimum", "Constructor integer", "0"); + field(fields, "maximum", "Constructor integer", Integer.toString(Integer.MAX_VALUE)); + field(fields, "initialValue", "Constructor integer", "0"); + field(fields, "number", "Integer", "initialValue"); + } + if (item.type().equals("AutoCompleteTextField")) + field(fields, "suggestions", "String list", ""); + if (item.type().equals("TagChip")) { + field(fields, "removable", "Boolean", "false"); + field(fields, "onRemove", "Event handler", ""); + } + if (item.type().equals("ToolBarPane")) { + field(fields, "dismissible", "Boolean", "false"); + field(fields, "dismissText", "String", "Close toolbar"); + field(fields, "onDismiss", "Event handler", ""); + } + if (Set.of("TextField", "TextArea", "AutoCompleteTextField", "PasswordField") + .contains(item.type())) field(fields, "editable", "Boolean", "true"); + if (Set.of("Label", "Button", "CheckBox", "TextArea").contains(item.type())) + field(fields, "wrapText", "Boolean", "false"); + if (item.type().equals("HtmlViewer")) { + field(fields, "mediaButtonVisible", "Boolean", "true"); + field(fields, "mediaLoadText", "String", "Load external media"); + field(fields, "mediaReloadText", "String", "Reload external media"); + field( + fields, + "mediaTooltipText", + "String", + "Loads external images for this viewer only and contacts their servers."); + field( + fields, "noExternalMediaText", "String", "No resolvable external image addresses found."); + } + if (item.type().equals("GridPane")) { + field(fields, "hgap", "Number", "0"); + field(fields, "vgap", "Number", "0"); + } + if (item.type().equals("HBox") || item.type().equals("VBox")) + field(fields, "spacing", "Number", "0"); + if (slots.stream().anyMatch(s -> s.owner.type.equals("GridPane") && members(s).contains(e))) { + for (String name : List.of("rowIndex", "columnIndex", "rowSpan", "columnSpan")) + field(fields, "GridPane." + name, "Layout integer", name.endsWith("Span") ? "1" : "0"); + for (String name : List.of("hgrow", "vgrow")) + field(fields, "GridPane." + name, "Priority", "unset"); + } + for (String name : List.of("width", "height")) + fields.put(name, new Field(name, "Number", "layout", false)); + for (int i = 0; i < e.getAttributes().getLength(); i++) { + var a = e.getAttributes().item(i); + if (a.getNamespaceURI() == null) + fields.putIfAbsent(a.getNodeName(), new Field(a.getNodeName(), "FXML", "source", false)); + } + return List.copyOf(fields.values()); + } + + private static void field(Map fields, String name, String type, String fallback) { + fields.put(name, new Field(name, type, fallback, true)); + } + + String value(Item item, Field field) { + var e = element(item); + if (e.hasAttribute(field.name())) return e.getAttribute(field.name()); + var nested = property(e, field.name()); + if (nested == null) return ""; + var values = children(nested); + if (field.name().equals("suggestions")) + return String.join( + "\n", values.stream().map(v -> v.getAttributeNS(BindingDocument.FX, "value")).toList()); + if (field.name().equals("padding") && values.size() == 1) { + var insets = values.getFirst(); + return String.join( + " ", + List.of("top", "right", "bottom", "left").stream() + .map(p -> insets.hasAttribute(p) ? insets.getAttribute(p) : "0") + .toList()); + } + return nested.getTextContent(); + } + + Edit set(Item item, Field field, String input, boolean reset) { + Element e = element(item); + if (field == null || !fields(item).contains(field) || !field.editable()) + throw new IllegalArgumentException("Choose a writable property."); + String name = field.name(); + var nested = property(e, name); + if (nested != null && !Set.of("padding", "suggestions").contains(name)) + throw new IllegalArgumentException("This property contains nested FXML. Edit it in Source."); + if (name.equals("padding") || name.equals("suggestions")) { + if (nested != null) { + for (var child : children(nested)) { + String expected = name.equals("padding") ? "javafx.geometry.Insets" : "java.lang.String"; + if (!(resolves(child.getTagName(), expected) + || child.getTagName().equals("String") + && expected.equals("java.lang.String") + && !imports.containsKey("String")) + || !children(child).isEmpty()) + throw new IllegalArgumentException("Complex property value; edit it in Source."); + for (int i = 0; i < child.getAttributes().getLength(); i++) { + Node a = child.getAttributes().item(i); + if (!(name.equals("padding") + && Set.of("top", "left", "right", "bottom").contains(a.getNodeName()) + || name.equals("suggestions") + && BindingDocument.FX.equals(a.getNamespaceURI()) + && "value".equals(a.getLocalName()))) + throw new IllegalArgumentException("Annotated property value; edit it in Source."); + } + } + if (fragment(nested).contains(""); + apply(doc().move(item("label2"), slot("statusBar", "rightItems"), 0)); + assertTrue(source.indexOf("id=\"label2\"") < source.indexOf("id=\"label3\"")); + add("TagChip", "toolBarPane", "items"); + set("tagChip", "removable", "true"); + set("tagChip", "onRemove", "#removeTag"); + set("toolBarPane", "dismissible", "true"); + set("toolBarPane", "dismissText", "Schließen"); + set("toolBarPane", "onDismiss", "#dismiss"); + apply(doc().move(item("tagChip"), slot("toolBar", "items"), 0)); + var toolbar = source.substring(source.indexOf("")); + assertTrue( + toolbar.contains("onRemove=\"#removeTag\"") && toolbar.contains("removable=\"true\"")); + assertTrue(source.contains("onDismiss=\"#dismiss\"") && source.contains("")); + assertThrows( + IllegalArgumentException.class, + () -> doc().move(item("toolBar"), slot("toolBar", "items"), 0)); + assertThrows( + IllegalArgumentException.class, + () -> doc().add("Label", new FormDocument.Slot(item("textField"), "children"), 0)); + assertThrows( + IllegalArgumentException.class, () -> doc().add("Label", slot("", "children"), 999)); + } + + @Test + void propertiesValidateResetAndRoundTrip() throws Exception { + add("NonNegativeIntegerSpinner", "", "children"); + for (var p : List.of("maximum", "initialValue", "minimum")) + set( + "nonNegativeIntegerSpinner", + p, + switch (p) { + case "maximum" -> "42"; + case "minimum" -> "2"; + default -> "8"; + }); + assertThrows( + IllegalArgumentException.class, () -> set("nonNegativeIntegerSpinner", "maximum", "6")); + assertThrows( + IllegalArgumentException.class, () -> set("nonNegativeIntegerSpinner", "minimum", "-1")); + set("nonNegativeIntegerSpinner", "number", "10"); + add("AutoCompleteTextField", "", "children"); + for (var name : + List.of("promptText", "styleClass", "padding", "GridPane.columnIndex", "suggestions")) { + String value = + switch (name) { + case "padding" -> "1 2 3 4"; + case "GridPane.columnIndex" -> "1"; + case "suggestions" -> "A & B\nPosteingang"; + default -> "Eingabe"; + }; + set("autoCompleteTextField", name, value); + var d = doc(); + var item = item("autoCompleteTextField"); + var f = d.fields(item).stream().filter(x -> name.equals(x.name())).findFirst().orElseThrow(); + assertEquals(name.equals("padding") ? "1.0 2.0 3.0 4.0" : value, d.value(item, f)); + set("autoCompleteTextField", name, null); + assertFalse(source.contains("<" + name + ">")); + assertEquals("", doc().value(item("autoCompleteTextField"), f)); + } + assertThrows(IllegalArgumentException.class, () -> set("autoCompleteTextField", "width", "20")); + } + + @Test + void implicitToolbarChildrenStayInOneList() throws Exception { + source = + ""; + add("Label", "", "items"); + assertEquals(2, doc().size(slot("", "items"))); + assertFalse(source.contains("")); + } +} diff --git a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/BindingDiscovery.java b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/BindingDiscovery.java index 9fe1825..4037024 100644 --- a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/BindingDiscovery.java +++ b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/BindingDiscovery.java @@ -23,6 +23,7 @@ public final class BindingDiscovery { private final Map generatedElements = new HashMap<>(); private ControllerMetadata owner; private final List selectionProblems = new ArrayList<>(); + private final Set readOnlySources = new HashSet<>(); private final Map> paths = new TreeMap<>(); private final List attributes = new ArrayList<>(); @@ -350,6 +351,9 @@ public final class BindingDiscovery { if (!Property.class.isAssignableFrom(m.getReturnType())) { status = "INCOMPATIBLE"; reason = "Runtime bindings require a writable JavaFX Property accessor."; + } else if (readOnlySources.contains(selected) && !direction.equals("view")) { + status = "INCOMPATIBLE"; + reason = "Read-only source requires direction=view."; } else if (source == null || source == Object.class || value == null @@ -382,7 +386,6 @@ public final class BindingDiscovery { } targets.add( new Target(id, property, value == null ? "?" : value.getName(), status, reason)); - if (targets.size() > 2048) throw new IOException("Too many binding targets"); } } catch (ClassNotFoundException | LinkageError ex) { diagnostics.add(id + ": unavailable target type: " + ex.getMessage()); @@ -395,6 +398,15 @@ public final class BindingDiscovery { .indexOf(t.status())) .thenComparing(Target::control) .thenComparing(Target::property)); + // Validate every declaration. Bound only the suggestions sent to the editor. + if (targets.size() > 2048) { + targets.sort(Comparator.comparing(t -> !t.control().equals(selectedControl))); + diagnostics.add( + "Showing 2048 of " + + targets.size() + + " target properties. Select a control in the form inspector to edit its bindings."); + targets.subList(2048, targets.size()).clear(); + } var converters = new ConverterDiscovery(loader); var chosen = targetTypes.get(selectedControl + "." + selectedProperty); var candidates = @@ -500,7 +512,8 @@ public final class BindingDiscovery { for (Method m : vm.getMethods()) { if (m.getParameterCount() != 0 || !m.getName().endsWith("Property") - || !Property.class.isAssignableFrom(m.getReturnType()) + || !ObservableValue.class.isAssignableFrom(m.getReturnType()) + || Modifier.isStatic(m.getModifiers()) || m.isBridge() || m.isSynthetic()) continue; String name = m.getName().substring(0, m.getName().length() - 8); @@ -510,12 +523,16 @@ public final class BindingDiscovery { if (value == Number.class && getter != null && Number.class.isAssignableFrom(box(getter))) value = getter; else if (value != null && getter != null && box(value) != box(getter)) value = null; + boolean readOnly = !Property.class.isAssignableFrom(m.getReturnType()); + if (readOnly) readOnlySources.add(name); paths.put(name, value == null ? Object.class : value); attributes.add( new Attribute( name, value == null ? "?" : value.getName(), - value == null || value == Object.class ? "UNRESOLVED" : "VIEWMODEL", + readOnly + ? "READ_ONLY" + : value == null || value == Object.class ? "UNRESOLVED" : "VIEWMODEL", "")); if (attributes.size() > 256) throw new IOException("Too many ViewModel properties"); } @@ -669,6 +686,9 @@ public final class BindingDiscovery { } else if (!target.writable()) { severity = "ERROR"; message = "Runtime requires a writable JavaFX Property"; + } else if (readOnlySources.contains(path) && !direction.equals("view")) { + severity = "ERROR"; + message = "Read-only source " + path + " requires direction=view"; } else if (source == null) { severity = incompleteModel ? "WARNING" : "ERROR"; message = "Unknown or unresolved Model path: " + path; diff --git a/designer-target-tools/src/test/java/de/neitzel/fxdesigner/target/ViewModelComputedTest.java b/designer-target-tools/src/test/java/de/neitzel/fxdesigner/target/ViewModelComputedTest.java index 723dd84..53b9677 100644 --- a/designer-target-tools/src/test/java/de/neitzel/fxdesigner/target/ViewModelComputedTest.java +++ b/designer-target-tools/src/test/java/de/neitzel/fxdesigner/target/ViewModelComputedTest.java @@ -216,7 +216,21 @@ class ViewModelComputedTest { assertEquals(String.class.getName(), types.get("badge")); assertEquals(String.class.getName(), types.get("name")); assertEquals(String.class.getName(), types.get("latestMessage")); - assertFalse(types.containsKey("readOnly")); + assertEquals(String.class.getName(), types.get("readOnly")); + assertTrue( + result.attributes().stream() + .anyMatch(a -> a.path().equals("readOnly") && a.kind().equals("READ_ONLY"))); + for (String direction : List.of("view", "model", "both")) { + var validation = + inspect( + xml( + Controller.class, + direct("readOnly").replace("direction='view'", "direction='" + direction + "'"))); + assertEquals( + !direction.equals("view"), + validation.problems().stream() + .anyMatch(p -> p.message().contains("requires direction=view"))); + } assertEquals(Custom.class.getName(), result.viewModel()); assertTrue(result.problems().isEmpty(), result.problems().toString()); for (String key : List.of("vm.metadata.initialized", "controller.metadata.initialized")) diff --git a/integration-fixtures/preview/classpath/app/src/main/resources/fixture/components/Full.fxml b/integration-fixtures/preview/classpath/app/src/main/resources/fixture/components/Full.fxml index 159a79c..0b1e1fb 100644 --- a/integration-fixtures/preview/classpath/app/src/main/resources/fixture/components/Full.fxml +++ b/integration-fixtures/preview/classpath/app/src/main/resources/fixture/components/Full.fxml @@ -1,8 +1,10 @@ + - +
+