diff --git a/README.md b/README.md index 5386524..d5115f8 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,31 @@ Qualify the registered editor and loaded JavaFX natives in real disposable IDE w python3 scripts/check-ide-host.py --java-home "$JAVA_HOME" --target-java-home "$TARGET_JAVA_HOME" --idea-home "$IDEA_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 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 \ + --idea-home "$IDEA_HOME" --java-home "$JAVA_HOME" --target-java-home "$JAVA_HOME" +``` + +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. + +Open **Bindings → DataGrid / Docking** in `FolderTab.fxml` to select the grid or one of its columns. **Apply setting** writes the selected property. Clear an optional value to restore its FXML default. **Edit data binding** opens the direct binding for `items` or `source`. The **Archivordner · Beispieldateien** example loads two local files using the grid's declared columns and grouping. + +In `ArchiveWindow.fxml`, select a layout branch to split it or an outer side area to move it. **Add area with group** creates a destination in an unused area. The **Beispielarchiv** example opens a document and its details in the declared destinations. Both the embedded image and the interactive window use this layout. To repeat both acceptance scenarios, add `--grid-docking ../NeitzelLib/fx-example/src/main/resources/de/neitzel/fx/example/docking/workspace/ReferenceWorkspace.fxml` to the Archiver host check. + +Add `--saved-document` to the Archiver launcher or host check to open the designer-profile view `SavedDocument.fxml`. Under **Form controls**, select **HtmlViewer #article** to edit the media button labels and tooltips. Select **AutoCompleteTextField #fixed** and edit **suggestions**, one tag per line. **Build and Refresh** discovers **HTML · Rechnung** and **HTML · Lieferschein**. **Form preview** shows the rendered HTML at the selected dimensions. In **Interactive preview**, use **Dokument wechseln**, edit **HTML-Quelle**, or type **Re** and **Li** into **Dokument-Tags** before and after switching. The form binds `article.html` to `html` and `dynamic.suggestionsSource` to `tags`, both toward the view. To create either binding, open **Bindings → Discover targets**, select **view** and the model path, select the compatible control property, then choose **Use selected target → Apply binding**. **Form controls → Bind property** opens the declaration for an existing target. + +Use `--document-tabs` with the Archiver host check to open the production archive window and select **Archiver · HTML-Dokumenttabs**. The check switches from the invoice to the delivery note and back, reads each WebView, and checks the actual suggestion popup for the same prefix in both tabs. + +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. Worker startup cancellation and ready-preview cleanup are covered by the [native lifecycle regression](docs/native-worker-lifecycle.md); host checks also reject new native JVM crash reports. diff --git a/designer-contracts/src/main/java/de/neitzel/fxdesigner/protocol/BindingMetadata.java b/designer-contracts/src/main/java/de/neitzel/fxdesigner/protocol/BindingMetadata.java index 8b8513a..76d95dc 100644 --- a/designer-contracts/src/main/java/de/neitzel/fxdesigner/protocol/BindingMetadata.java +++ b/designer-contracts/src/main/java/de/neitzel/fxdesigner/protocol/BindingMetadata.java @@ -20,7 +20,49 @@ public record BindingMetadata( List panes, List tableCollections, List tableRows, - List tableColumns) { + List tableColumns, + List commandPaths, + List commandTargets) { + public BindingMetadata( + String model, + String path, + String direction, + List attributes, + List targets, + List diagnostics, + List converters, + List problems, + String controller, + String viewModel, + List computed, + List collections, + List components, + List panes, + List tableCollections, + List tableRows, + List tableColumns) { + this( + model, + path, + direction, + attributes, + targets, + diagnostics, + converters, + problems, + controller, + viewModel, + computed, + collections, + components, + panes, + tableCollections, + tableRows, + tableColumns, + List.of(), + List.of()); + } + public BindingMetadata( String model, String path, @@ -160,6 +202,8 @@ public record BindingMetadata( tableCollections = List.copyOf(tableCollections); tableRows = List.copyOf(tableRows); tableColumns = List.copyOf(tableColumns); + commandPaths = List.copyOf(commandPaths); + commandTargets = List.copyOf(commandTargets); if (!Set.of("view", "model", "both").contains(direction)) throw new IllegalArgumentException("Invalid direction"); } @@ -167,6 +211,8 @@ public record BindingMetadata( public Map encode() { var m = new TreeMap(); m.put("format", "5"); + encodeStrings(m, "commands", commandPaths); + encodeStrings(m, "commandTargets", commandTargets); encodeOptions(m, "rc", collections); encodeOptions(m, "rt", components); encodeOptions(m, "rp", panes); @@ -228,6 +274,17 @@ public record BindingMetadata( return m; } + private static void encodeStrings(Map fields, String key, List values) { + fields.put(key, Integer.toString(values.size())); + for (int i = 0; i < values.size(); i++) fields.put(key + "." + i, values.get(i)); + } + + private static List decodeStrings(Map fields, String key) { + return java.util.stream.IntStream.range(0, count(fields, key)) + .mapToObj(i -> field(fields, key + "." + i)) + .toList(); + } + private static void encodeOptions( Map m, String prefix, List values) { m.put(prefix, "" + values.size()); @@ -266,6 +323,7 @@ public record BindingMetadata( } public static BindingMetadata decode(Map m) { + boolean commands = m.containsKey("commands"); if (!"5".equals(field(m, "format"))) throw new IllegalArgumentException("Unsupported binding metadata"); var a = new ArrayList(); @@ -333,6 +391,8 @@ public record BindingMetadata( decodeOptions(m, "rp"), decodeOptions(m, "tc"), decodeOptions(m, "tr"), - decodeOptions(m, "ta")); + decodeOptions(m, "ta"), + commands ? decodeStrings(m, "commands") : List.of(), + commands ? decodeStrings(m, "commandTargets") : List.of()); } } diff --git a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/BindingDocument.java b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/BindingDocument.java index b973728..b13e54e 100644 --- a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/BindingDocument.java +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/BindingDocument.java @@ -11,11 +11,13 @@ final class BindingDocument { enum Kind { DIRECT, COMPUTED, + COMMAND, REPEAT; String element() { return switch (this) { case DIRECT -> "DirectBinding"; + case COMMAND -> "CommandBinding"; case COMPUTED -> "ComputedBinding"; case REPEAT -> "Repeat"; }; @@ -54,8 +56,7 @@ final class BindingDocument { if (!values.pane().isEmpty()) return values.pane() + " ← " + values.collection() + " (" + values.component() + ")"; return values.control() - + "." - + values.property() + + (values.property().isEmpty() ? "" : "." + values.property()) + " ← " + (values.method().isEmpty() ? values.path() : values.method()); } @@ -105,11 +106,14 @@ final class BindingDocument { } boolean named(Element e, String type) { - if (e.getTagName().equals(PACKAGE + type)) return true; + return named(e, PACKAGE, type); + } + + boolean named(Element e, String pkg, String type) { + if (e.getTagName().equals(pkg + type)) return true; if (!e.getTagName().equals(type)) return false; - boolean own = imports.contains(PACKAGE + type) || imports.contains(PACKAGE + "*"); - boolean other = - imports.stream().anyMatch(i -> i.endsWith("." + type) && !i.equals(PACKAGE + type)); + boolean own = imports.contains(pkg + type) || imports.contains(pkg + "*"); + boolean other = imports.stream().anyMatch(i -> i.endsWith("." + type) && !i.equals(pkg + type)); return own && !other; } @@ -214,6 +218,14 @@ final class BindingDocument { private boolean conflicts(Element e, Values value) { if (kind == Kind.REPEAT) return binding(e, "Repeat") && e.getAttribute("pane").equals(value.pane()); + if (e.getAttribute("control").equals(value.control())) { + if (kind == Kind.COMMAND) + return binding(e, "CommandBinding") + || ((binding(e, "DirectBinding") || binding(e, "ComputedBinding")) + && Set.of("disable", "onAction").contains(e.getAttribute("property"))); + if (binding(e, "CommandBinding")) + return Set.of("disable", "onAction").contains(value.property()); + } return (binding(e, "DirectBinding") || binding(e, "ComputedBinding")) && e.getAttribute("control").equals(value.control()) && e.getAttribute("property").equals(value.property()); @@ -228,8 +240,11 @@ final class BindingDocument { List write(Integer index, Values value, boolean replaceConflicts) { if (kind == Kind.REPEAT && value.pane().isBlank()) throw new IllegalArgumentException("Choose a pane"); - if (kind != Kind.REPEAT && (value.control().isBlank() || value.property().isBlank())) + if (kind != Kind.REPEAT + && (value.control().isBlank() || (kind != Kind.COMMAND && value.property().isBlank()))) throw new IllegalArgumentException("Choose a control and property"); + if (kind == Kind.COMMAND && (!qualifiedName(value.path()) || value.path().contains("."))) + throw new IllegalArgumentException("Choose a simple Command path"); Element original = index == null ? null : entry(index); if (original != null && hasElementChildren(original)) throw new IllegalArgumentException( @@ -256,25 +271,27 @@ final class BindingDocument { value.component(), "collection", value.collection()) - : kind == Kind.COMPUTED - ? Map.of( - "control", - value.control(), - "property", - value.property(), - "method", - value.method()) - : Map.of( - "control", - value.control(), - "property", - value.property(), - "path", - value.path(), - "direction", - value.direction(), - "converter", - value.converter()); + : kind == Kind.COMMAND + ? Map.of("control", value.control(), "path", value.path()) + : kind == Kind.COMPUTED + ? Map.of( + "control", + value.control(), + "property", + value.property(), + "method", + value.method()) + : Map.of( + "control", + value.control(), + "property", + value.property(), + "path", + value.path(), + "direction", + value.direction(), + "converter", + value.converter()); for (var f : fields.entrySet()) if (!original.getAttribute(f.getKey()).equals(f.getValue())) changed.put( @@ -303,6 +320,15 @@ final class BindingDocument { + "\" collection=\"" + XmlSource.escape(value.collection(), '"') + "\""; + else if (kind == Kind.COMMAND) + node = + "<" + + PACKAGE + + "CommandBinding control=\"" + + XmlSource.escape(value.control(), '"') + + "\" path=\"" + + XmlSource.escape(value.path(), '"') + + "\""; else if (kind == Kind.COMPUTED) node += " method=\"" + XmlSource.escape(value.method(), '"') + "\""; else @@ -380,6 +406,13 @@ final class BindingDocument { t.insert(), t.openEnd(), attributes + ">" + eol + child + eol + ""); + int line = text.lastIndexOf('\n', t.closeStart() - 1) + 1; + String indent = text.substring(line, t.closeStart()); + if (indent.isBlank()) { + // Keep the closing tag on its indented line. Blank lines with spaces can trigger + // IntelliJ's strip-trailing-whitespace edit on the next automatic save. + return new Replacement(line, line, indent + " " + child + eol); + } return new Replacement(t.closeStart(), t.closeStart(), eol + child + eol); } } diff --git a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/BindingEditor.java b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/BindingEditor.java index fd235b0..1e7b97f 100644 --- a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/BindingEditor.java +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/BindingEditor.java @@ -31,6 +31,7 @@ final class BindingEditor extends VBox { private final BindingDocument.Kind kind; private final ComboBox converters = new ComboBox<>(); private final Button inspect = new Button("Find Converters / Validate"); + private final ComboBox commandPaths = new ComboBox<>(), commandTargets = new ComboBox<>(); private final ComboBox direction = new ComboBox<>(); private final CheckBox replace = new CheckBox("Replace conflicting bindings"); private final Label status = new Label("Open a valid FXML document to edit bindings."); @@ -50,7 +51,8 @@ final class BindingEditor extends VBox { this.kind = kind; boolean computed = kind == BindingDocument.Kind.COMPUTED; boolean repeat = kind == BindingDocument.Kind.REPEAT; - String prefix = repeat ? "repeat-" : computed ? "computed-" : "direct-"; + boolean command = kind == BindingDocument.Kind.COMMAND; + String prefix = command ? "command-" : repeat ? "repeat-" : computed ? "computed-" : "direct-"; this.navigate = navigate; for (var field : java.util.List.of(control, property, path, converter, method, pane, component, collection)) @@ -68,6 +70,20 @@ final class BindingEditor extends VBox { apply.setText("Apply Computed binding"); remove.setText("Remove Computed binding"); } + if (command) { + inspect.setText("Discover / Validate Commands"); + fresh.setText("New Command binding"); + apply.setText("Apply Command binding"); + remove.setText("Remove Command binding"); + commandPaths.setOnAction( + e -> { + if (commandPaths.getValue() != null) path.setText(commandPaths.getValue()); + }); + commandTargets.setOnAction( + e -> { + if (commandTargets.getValue() != null) control.setText(commandTargets.getValue()); + }); + } if (repeat) { inspect.setText("Discover / Validate Repeat"); fresh.setText("New Repeat binding"); @@ -126,7 +142,7 @@ final class BindingEditor extends VBox { var grid = new GridPane(); grid.setHgap(8); grid.setVgap(4); - if (!computed && !repeat) + if (kind == BindingDocument.Kind.DIRECT) grid.addRow( 0, new Label("Control (fx:id)"), @@ -135,7 +151,7 @@ final class BindingEditor extends VBox { property, new Label("Direction"), direction); - if (!computed && !repeat) + if (kind == BindingDocument.Kind.DIRECT) grid.addRow(1, new Label("Model path"), path, new Label("Converter (optional)"), converter); else if (computed) { grid.addRow(0, new Label("Control (fx:id)"), control, new Label("Property"), property); @@ -143,6 +159,10 @@ final class BindingEditor extends VBox { for (var field : java.util.List.of(control, property)) field.textProperty().addListener((o, a, b) -> methods.getItems().clear()); } + if (command) { + grid.addRow(0, new Label("Control (fx:id)"), control, commandTargets); + grid.addRow(1, new Label("Command path"), path, commandPaths); + } if (repeat) { repeatCollections.setId("repeat-collections"); repeatComponents.setId("repeat-components"); @@ -177,7 +197,9 @@ final class BindingEditor extends VBox { .addAll( bindings, grid, - repeat ? new HBox(8, inspect) : new HBox(8, inspect, computed ? methods : converters), + repeat || command + ? new HBox(8, inspect) + : new HBox(8, inspect, computed ? methods : converters), new HBox(8, fresh, apply, remove, replace), status); buttons(); @@ -209,7 +231,7 @@ final class BindingEditor extends VBox { control.setText(v.control()); property.setText(v.property()); path.setText(v.path()); - direction.setValue(v.direction()); + direction.setValue(kind == BindingDocument.Kind.COMMAND ? "view" : v.direction()); converter.setText(v.converter()); method.setText(v.method()); pane.setText(v.pane()); @@ -217,6 +239,18 @@ final class BindingEditor extends VBox { collection.setText(v.collection()); } + void editProperty(BindingDocument.Values v) { + var existing = + bindings.getItems().stream() + .filter( + e -> + e.values().control().equals(v.control()) + && e.values().property().equals(v.property())) + .findFirst(); + if (existing.isPresent()) bindings.getSelectionModel().select(existing.get()); + else newBinding(v); + } + void newBinding(BindingDocument.Values v) { loading = true; bindings.getSelectionModel().clearSelection(); @@ -329,6 +363,11 @@ final class BindingEditor extends VBox { } return; } + if (kind == BindingDocument.Kind.COMMAND) { + commandPaths.getItems().setAll(metadata.commandPaths()); + commandTargets.getItems().setAll(metadata.commandTargets()); + return; + } if (requested == null || !values().equals(requested)) return; if (kind == BindingDocument.Kind.COMPUTED) { methods.getItems().setAll(metadata.computed()); @@ -345,6 +384,8 @@ final class BindingEditor extends VBox { } void invalidateDiscovery() { + commandPaths.getItems().clear(); + commandTargets.getItems().clear(); updatingChoices = true; try { repeatCollections.getItems().clear(); 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 5091c32..c98e801 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,14 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { return content; } + private GridDockEditor gridDockEditor; + 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,9 +51,11 @@ 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); + if (commandEditor != null) commandEditor.selectControl(id); if (tableEditor != null) tableEditor.selectControl(id); if (referenceEditor != null) referenceEditor.selectIndex(projection.sourceIndex(id)); if (id == null || !projection.components().containsKey(id)) return; @@ -120,7 +130,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { private DesignerWorkflow bindingWorkflow; private ViewGenerationPane viewGeneration; private BindingBrowser bindingBrowser; - private BindingEditor bindingEditor, computedEditor, repeatEditor; + private BindingEditor bindingEditor, computedEditor, repeatEditor, commandEditor; private TableEditor tableEditor; private ReferenceEditor referenceEditor; private DiagnosticsPane diagnosticsPane; @@ -194,36 +204,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { launch.maven(), launch.tools(), this::log); - bindingEditor = - new BindingEditor( - BindingDocument.Kind.DIRECT, - this::editBinding, - id -> { - if (kit.editor().getFxomDocument() == null) return; - var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id); - if (target != null) kit.editor().getSelection().select(target); - }, - values -> validateBindings(values, false)); - computedEditor = - new BindingEditor( - BindingDocument.Kind.COMPUTED, - this::editBinding, - id -> { - if (kit.editor().getFxomDocument() == null) return; - var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id); - if (target != null) kit.editor().getSelection().select(target); - }, - values -> validateBindings(values, false)); - repeatEditor = - new BindingEditor( - BindingDocument.Kind.REPEAT, - this::editBinding, - id -> { - if (kit.editor().getFxomDocument() == null) return; - var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id); - if (target != null) kit.editor().getSelection().select(target); - }, - values -> validateBindings(values, false)); + bindingEditor = editor(BindingDocument.Kind.DIRECT); + computedEditor = editor(BindingDocument.Kind.COMPUTED); + repeatEditor = editor(BindingDocument.Kind.REPEAT); + commandEditor = editor(BindingDocument.Kind.COMMAND); tableEditor = new TableEditor( this::editTable, this::navigateComponent, values -> validateBindings(values, false)); @@ -258,7 +242,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"); @@ -277,7 +261,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(); @@ -355,13 +339,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", () -> { @@ -379,10 +418,21 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { directBindingTab.setClosable(false); var computedTab = new Tab("Computed bindings", computedEditor); computedTab.setClosable(false); + var commandTab = new Tab("Command bindings", commandEditor); + commandTab.setClosable(false); var repeatTab = new Tab("Repeat bindings", repeatEditor); repeatTab.setClosable(false); var tableTab = new Tab("Table / Columns", tableEditor); tableTab.setClosable(false); + gridDockEditor = + new GridDockEditor( + this::editForm, + values -> { + directBindingTab.getTabPane().getSelectionModel().select(directBindingTab); + bindingEditor.editProperty(values); + }); + var gridDockTab = new Tab("DataGrid / Docking", gridDockEditor); + gridDockTab.setClosable(false); var problemsTab = new Tab("Problems", diagnosticsPane); problemsTab.setClosable(false); var structureTab = new Tab("Structure", referenceEditor); @@ -396,14 +446,46 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { new TabPane( directBindingTab, computedTab, + commandTab, repeatTab, tableTab, + gridDockTab, structureTab, problemsTab, discoveryTab, generationTab)); bindings.setExpanded(false); - center.setBottom(new VBox(properties, bindings)); + formEditor = + new FormEditor( + this::editForm, + 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.editProperty(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"); @@ -443,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); })); })); @@ -502,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()); } @@ -542,11 +630,15 @@ 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()); repeatEditor.load(value.text(), value.writable()); + commandEditor.load(value.text(), value.writable()); tableEditor.load(value.text(), value.writable()); + gridDockEditor.load(value.text(), value.writable()); referenceEditor.load(value.text(), value.writable()); submittedSource = null; commitSource(); @@ -574,11 +666,16 @@ 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()); repeatEditor.load(value.text(), value.writable()); + commandEditor.load(value.text(), value.writable()); tableEditor.load(value.text(), value.writable()); + gridDockEditor.load(value.text(), value.writable()); referenceEditor.load(value.text(), value.writable()); if (!source.getText().equals(value.text())) { int anchor = source.getAnchor(), caret = source.getCaretPosition(); @@ -641,13 +738,14 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { } catch (Throwable error) { design.setDisable(true); componentInspector.setDisable(true); + gridDockEditor.setDisable(true); projection = null; report(error); } finally { 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; @@ -668,6 +766,36 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { : null; } + private void editForm(FormDocument.Edit edit) { + flush() + .whenComplete( + (ok, error) -> + fx( + () -> { + if (error != null) { + report(error); + return; + } + if (pending) { + status.setText("Finishing the previous edit; repeat the form action."); + return; + } + pending = true; + pendingBase = edit.source(); + pendingVisual = edit.changes(); + document + .snapshot() + .thenCompose( + latest -> + document.apply( + new EditBatch( + latest.revision(), + "Edit form", + FormDocument.forCurrentText(edit, latest.text())))) + .whenComplete(this::updated); + })); + } + private void replace(String text, String name) { if (draft == null || pending) return; submit(difference(draft.text(), text), name); @@ -750,6 +878,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { bindingWorkflow.cancel(); bindingBrowser.invalidate(message); repeatEditor.invalidateDiscovery(); + commandEditor.invalidateDiscovery(); tableEditor.invalidateDiscovery(); } @@ -846,6 +975,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { if (!draft.writable()) throw new IllegalStateException("Document is read-only"); if (!draft.text().equals(intent.source())) throw new IllegalStateException("Document changed; select the source object again"); + if (!intent.change().importedCommandTargets().isEmpty()) { + validateCommandPaste(intent); + return; + } if (intent.validate()) pendingReferenceValidation = apply(draft.text(), intent.change().edits()); submit(intent.change().edits(), intent.label()); @@ -855,6 +988,58 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { }); } + /** Validate imported Command paths against the destination snapshot before the first write. */ + private void validateCommandPaste(ReferenceEditor.Intent intent) { + var original = draft; + String proposed = apply(original.text(), intent.change().edits()); + var candidate = + new DocumentSnapshot( + original.document(), original.revision(), proposed, original.writable(), true); + bindingWorkflow + .bindingDetails(last, candidate, "", "view", "", "") + .whenComplete( + (metadata, error) -> + fx( + () -> { + if (closed) return; + if (error != null) { + referenceEditor.error( + "Cannot validate the destination Commands: " + error.getMessage()); + return; + } + if (draft.revision() != original.revision() + || !source.getText().equals(original.text())) { + referenceEditor.error( + "Destination changed. Select the destination and paste again."); + return; + } + if (!metadata + .commandTargets() + .containsAll(intent.change().importedCommandTargets())) { + referenceEditor.error( + "The destination build could not resolve the copied Command targets."); + return; + } + var conflicts = + metadata.problems().stream() + .filter( + p -> + p.severity().equals("ERROR") + && intent + .change() + .importedCommandTargets() + .contains(p.control())) + .map(p -> p.message()) + .toList(); + if (!conflicts.isEmpty()) { + referenceEditor.error(String.join("; ", conflicts)); + return; + } + pendingReferenceValidation = proposed; + submit(intent.change().edits(), intent.label()); + })); + } + private void editTable(TableEditor.Intent intent) { withDraft( () -> { @@ -869,6 +1054,19 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { }); } + private BindingEditor editor(BindingDocument.Kind kind) { + return new BindingEditor( + kind, + this::editBinding, + id -> { + var document = kit.editor().getFxomDocument(); + if (document == null) return; + var selection = new FXOMFxIdIndex(document).lookup(id); + if (selection != null) kit.editor().getSelection().select(selection); + }, + values -> validateBindings(kind == BindingDocument.Kind.COMMAND ? null : values, false)); + } + private void editBinding(BindingEditor.Intent intent) { withDraft( () -> { @@ -891,7 +1089,9 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { ? repeatEditor : intent.kind() == BindingDocument.Kind.COMPUTED ? computedEditor - : bindingEditor) + : intent.kind() == BindingDocument.Kind.COMMAND + ? commandEditor + : bindingEditor) .error(error.getMessage()); } }); @@ -904,6 +1104,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); @@ -954,6 +1155,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(); @@ -979,6 +1184,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { : "Current successful build") + " · draft revision " + captured.revision()); + commandEditor.metadata( + metadata, + values, + last ? "Retained build" : "Current successful build"); repeatEditor.metadata( metadata, values, @@ -1060,6 +1269,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 @@ -1095,6 +1305,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."); })); }); } @@ -1141,6 +1356,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( () -> { @@ -1156,10 +1392,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 || projection == null) return; + if (selected == null) { + 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 && !showWhole) return; long ticket = renderSequence.incrementAndGet(); host.documents() .snapshots() @@ -1191,7 +1435,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { new DocumentSnapshot( draft.document(), draft.revision(), - projection.previewText(), + projection == null ? draft.text() : projection.previewText(), draft.writable(), draft.dirty())); renderComponents(List.copyOf(drafts.values()), selected.id(), ticket); @@ -1202,7 +1446,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { private void renderComponents(List drafts, String example, long ticket) { if (ticket != renderSequence.get() || closed) return; var nodes = new LinkedHashMap(); - for (String id : projection.components().keySet()) { + for (String id : projection == null ? Set.of() : projection.components().keySet()) { var region = proxy(id); if (region == null) continue; int @@ -1245,8 +1489,13 @@ 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("No embedded Components; use Interactive preview for this View"); + status.setText( + projection == null + ? "Canvas projection unavailable; interactive preview uses the FXML draft" + : "No embedded Components; use Interactive preview for this View"); return; } workflow @@ -1257,14 +1506,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; } @@ -1291,6 +1545,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) { @@ -1302,14 +1571,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..924e575 --- /dev/null +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormDocument.java @@ -0,0 +1,533 @@ +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) { + boolean bindable() { + return type.equals("ObservableList") + || editable + && !name.equals("dismissText") + && Set.of("Integer", "String", "Boolean", "Number", "CSS", "Insets").contains(type); + } + + 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, ""); + } + + /** A native autosave can strip trailing whitespace between selection and apply. */ + static List forCurrentText(Edit edit, String current) { + if (edit.source().equals(current)) return edit.changes(); + var normalized = new StringBuilder(); + int[] offsets = new int[edit.source().length() + 1]; + var stripped = java.util.regex.Pattern.compile("(?m)[ \t]+$").matcher(edit.source()); + int start = 0; + while (stripped.find()) { + for (int i = start; i < stripped.start(); i++) { + offsets[i] = normalized.length(); + normalized.append(edit.source().charAt(i)); + } + Arrays.fill(offsets, stripped.start(), stripped.end(), normalized.length()); + start = stripped.end(); + } + for (int i = start; i < edit.source().length(); i++) { + offsets[i] = normalized.length(); + normalized.append(edit.source().charAt(i)); + } + offsets[edit.source().length()] = normalized.length(); + if (!current.contentEquals(normalized)) + throw new ConcurrentModificationException("Form changed; select the control again."); + return edit.changes().stream() + .map(r -> new Replacement(offsets[r.start()], offsets[r.end()], r.text())) + .toList(); + } + + 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", ""); + fields.put( + "suggestionsSource", + new Field("suggestionsSource", "ObservableList", "fixed suggestions", false)); + } + 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, "html", "String", ""); + 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 nativeSaveBetweenPaletteSelectionAndApply() throws Exception { + source = source.replace("", " \n"); + var edit = doc().add("Label", slot("", "children"), 0); + var saved = source.replace("> \n", ">\n"); + var changes = FormDocument.forCurrentText(edit, saved); + var result = + new EditBatch(2, "Insert Label", changes) + .applyTo(new DocumentSnapshot(URI.create("file:///test.fxml"), 2, saved, true, false)); + assertTrue(new FormDocument(result).items.stream().anyMatch(i -> i.id().equals("label"))); + assertThrows( + ConcurrentModificationException.class, + () -> FormDocument.forCurrentText(edit, saved.replace("GridPane", "VBox"))); + } + + @Test + void implicitToolbarChildrenStayInOneList() throws Exception { + source = + ""; + add("Label", "", "items"); + assertEquals(2, doc().size(slot("", "items"))); + assertFalse(source.contains("")); + } +} diff --git a/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FxmlProjectionTest.java b/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FxmlProjectionTest.java index 62164ab..ad71ee9 100644 --- a/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FxmlProjectionTest.java +++ b/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FxmlProjectionTest.java @@ -34,6 +34,26 @@ class FxmlProjectionTest { assertTrue(restored.contains("neitzel-model")); } + @Test + void editsTheStatusBarBesideAnAttachedMarginWithoutChangingItsXml() throws Exception { + String source = """ + + + + + + + + + + """; + var projection = new FxmlProjection(source); + String projected = projection.project(); + String edited = projection.restore(projected.replace("spacing=\"8\"", "spacing=\"10\"")); + assertEquals(source.replace("spacing='8'", "spacing='10'"), edited); + assertEquals(source, projection.restore(projected)); + } + @Test void rejectsExternalEntitiesAndExecutableFXML() throws Exception { assertThrows( diff --git a/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/GridDockDocumentTest.java b/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/GridDockDocumentTest.java new file mode 100644 index 0000000..f2aee43 --- /dev/null +++ b/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/GridDockDocumentTest.java @@ -0,0 +1,44 @@ +package de.neitzel.fxdesigner.kit; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class GridDockDocumentTest { + @Test + void implicitRowAttributeAndGroupingSurviveRename() throws Exception { + var source = + """ + + + + + + + """; + var doc = new GridDockDocument(source); + var grid = doc.roots().getFirst(); + var col = doc.branches(grid).getFirst(); + assertThrows(IllegalArgumentException.class, () -> doc.removeColumn(col)); + assertThrows(IllegalArgumentException.class, () -> doc.set(col, "id", "age")); + var renamed = doc.xml.source.apply(doc.set(col, "id", "title")); + assertTrue(renamed.contains("groupBy=\"title\"")); + assertTrue(renamed.contains("attribute=\"name\"")); + var removed = doc.xml.source.apply(doc.removeColumn(doc.branches(grid).getLast())); + assertEquals(source.replace(" \n", ""), removed); + } + + @Test + void rootDockProjectionAndAmbiguousImportPreserveOriginal() throws Exception { + String source = + """ + +
+ """; + var projection = new FxmlProjection(source); + assertEquals(source, projection.restore(projection.project())); + String conflict = source.replace("", "\n"); + var ex = assertThrows(java.io.IOException.class, () -> new FxmlProjection(conflict).project()); + assertTrue(ex.getMessage().contains(" at line 3, column 1"), ex::getMessage); + } +} diff --git a/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/ReferenceDocumentTest.java b/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/ReferenceDocumentTest.java index f9e1d15..beb90ba 100644 --- a/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/ReferenceDocumentTest.java +++ b/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/ReferenceDocumentTest.java @@ -96,6 +96,26 @@ class ReferenceDocumentTest { assertTrue(twice.contains("f:id='childCopy2'")); } + @Test + void copiesMenuCommandsWithFreshIdsAndTracksTargetsForDestinationValidation() throws Exception { + String text = + "" + + "" + + "" + + ""; + var menu = new ReferenceDocument(text); + var clip = menu.copy(index(menu, "open"), "source"); + var copied = menu.paste(clip, index(menu, "file"), "destination"); + assertEquals(Set.of("openCopy"), copied.importedCommandTargets()); + String result = apply(text, copied); + assertTrue(result.contains("fx:id='openCopy' accelerator='Shortcut+O'")); + assertTrue(result.contains("control='openCopy' path='open'")); + var layout = new ReferenceDocument(XML); + assertThrows( + IllegalArgumentException.class, + () -> layout.paste(clip, index(layout, "box"), "destination")); + } + @Test void carriesNamespacesImportsAndReportsDestinationContextDifferences() throws Exception { String source = 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 daf60f5..79a5087 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 @@ -1,7 +1,7 @@ package de.neitzel.fxdesigner.target; -import de.neitzel.fxdesigner.protocol.BindingMetadata.*; import de.neitzel.fxdesigner.protocol.BindingMetadata; +import de.neitzel.fxdesigner.protocol.BindingMetadata.*; import java.beans.*; import java.io.*; import java.lang.reflect.*; @@ -23,11 +23,38 @@ 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<>(); - private record TargetType(Class type, boolean writable) {} + private final Map> listElements = new HashMap<>(); + private record TargetType(Class type, boolean writable, Class listElement) {} + + // Invariant element signatures for explicit JavaFX list properties. Keep raw, wildcard + // and unresolvable generic declarations in the existing unverified collection path. + private static Class listElement(Method method) { + if (!(method.getGenericReturnType() instanceof ParameterizedType p) + || p.getActualTypeArguments().length != 1) return null; + Type value = p.getActualTypeArguments()[0]; + if (p.getRawType() == javafx.beans.property.ListProperty.class + || p.getRawType() == javafx.beans.property.ReadOnlyListProperty.class) + return value instanceof Class element ? element : null; + if ((p.getRawType() == javafx.beans.property.ObjectProperty.class + || p.getRawType() == javafx.beans.property.ReadOnlyObjectProperty.class) + && value instanceof ParameterizedType list + && list.getRawType() == javafx.collections.ObservableList.class + && list.getActualTypeArguments()[0] instanceof Class element) return element; + return null; + } + + private boolean knownListPair(String path, TargetType target, String direction) { + return direction.equals("view") + && listElements.containsKey(path) + && target.listElement() != null; + } + + private final Set actionHandlers = new HashSet<>(); private final Map> controlTypes = new HashMap<>(); private RepeatDiscovery repeats; private final Map targetTypes = new HashMap<>(); @@ -313,6 +340,10 @@ public final class BindingDiscovery { ? owner.controller : resolve(e, imports); controlTypes.put(id, control); + if (e.hasAttribute("onAction")) actionHandlers.add(id); + for (Node child = e.getFirstChild(); child != null; child = child.getNextSibling()) + if (child instanceof Element property && property.getTagName().equals("onAction")) + actionHandlers.add(id); String componentModel = ""; var componentResource = control.getResource(control.getSimpleName() + ".fxml"); if (componentResource != null) @@ -338,13 +369,17 @@ public final class BindingDiscovery { value = load(componentModel); constrained = true; } - targetTypes.put( - id + "." + property, - new TargetType(value, Property.class.isAssignableFrom(m.getReturnType()))); + var target = + new TargetType( + value, Property.class.isAssignableFrom(m.getReturnType()), listElement(m)); + targetTypes.put(id + "." + property, target); String status, reason; 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 @@ -352,6 +387,13 @@ public final class BindingDiscovery { status = "UNRESOLVED"; reason = "Declared types are insufficient; rebuild with specific signatures/Model metadata."; + } else if (knownListPair(selected, target, direction)) { + boolean matches = listElements.get(selected) == target.listElement(); + status = matches ? "COMPATIBLE" : "INCOMPATIBLE"; + reason = + matches + ? "Matching observable list element type: " + target.listElement().getName() + : "Observable list element types differ."; } else if (Collection.class.isAssignableFrom(source) || Collection.class.isAssignableFrom(value) || Map.class.isAssignableFrom(source) @@ -377,7 +419,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()); @@ -390,6 +431,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 = @@ -398,7 +448,8 @@ public final class BindingDiscovery { : converters.candidates(source, chosen == null ? null : chosen.type(), direction); repeats = new RepeatDiscovery(loader, attributes, owner, incompleteModel, controlTypes, ids); var tables = new TableDiscovery(loader, repeats, modelType, owner); - var problems = new ArrayList<>(validate(doc, imports, ids, converters)); + var commands = commandPaths(); + var problems = new ArrayList<>(validate(doc, imports, ids, converters, commands)); problems.addAll(tables.validate(doc)); var componentOptions = repeats.candidates(selected); for (var a : attributes) @@ -421,7 +472,35 @@ public final class BindingDiscovery { repeats.panes(), tables.collections(), tables.rows(selected), - tables.columns(selected)); + tables.columns(selected), + commands, + controlTypes.entrySet().stream() + .filter(e -> commandTarget(e.getValue())) + .map(Map.Entry::getKey) + .sorted() + .toList()); + } + + private List commandPaths() { + if (owner.viewModel == null) return List.of(); + return Arrays.stream(owner.viewModel.getMethods()) + .filter( + m -> + !Modifier.isStatic(m.getModifiers()) + && m.getParameterCount() == 0 + && m.getName().startsWith("get") + && m.getName().length() > 3 + && de.neitzel.fx.view.Command.class.isAssignableFrom(m.getReturnType())) + .map(m -> java.beans.Introspector.decapitalize(m.getName().substring(3))) + .distinct() + .sorted() + .toList(); + } + + private static boolean commandTarget(Class type) { + return type != null + && (javafx.scene.control.ButtonBase.class.isAssignableFrom(type) + || javafx.scene.control.MenuItem.class.isAssignableFrom(type)); } private void selectOwner(Document doc, List imports, String resource, Class model) @@ -466,22 +545,29 @@ 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); if (name.isEmpty() || paths.containsKey(name)) continue; + Class element = listElement(m); + if (element != null) listElements.put(name, element); Class value = propertyType(m.getGenericReturnType(), Map.of()); Class getter = valueType(vm, name); 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"); } @@ -492,17 +578,31 @@ public final class BindingDiscovery { .anyMatch(a -> a.path().equals(path) && Set.of("COMPLEX", "COLLECTION").contains(a.kind())); } + private static String propertyValue(Element declaration, String name) { + if (declaration.hasAttribute(name)) return declaration.getAttribute(name); + for (Node n = declaration.getFirstChild(); n != null; n = n.getNextSibling()) + if (n instanceof Element child && child.getTagName().equals(name)) + return child.getTextContent().trim(); + return ""; + } + private List validate( - Document doc, List imports, Set ids, ConverterDiscovery converters) + Document doc, + List imports, + Set ids, + ConverterDiscovery converters, + List commands) throws Exception { var problems = new ArrayList(selectionProblems); problems.addAll(owner.problems); var occupied = new HashSet(); + var commandControls = new TreeSet(); var nodes = doc.getElementsByTagName("*"); for (int i = 0; i < nodes.getLength(); i++) { var e = (Element) nodes.item(i); if (!library(e, "DirectBinding", imports) && !library(e, "ComputedBinding", imports) + && !library(e, "CommandBinding", imports) && !library(e, "Repeat", imports)) continue; Node parent = e.getParentNode(); if (parent instanceof Element p && p.getTagName().equals("elements")) @@ -529,9 +629,39 @@ public final class BindingDiscovery { } continue; } - String control = e.getAttribute("control"), - property = e.getAttribute("property"), + String control = propertyValue(e, "control"), + property = propertyValue(e, "property"), key = control + "." + property; + if (library(e, "CommandBinding", imports)) { + String path = propertyValue(e, "path"); + if (!ids.contains(control)) + problems.add( + new Problem(control, "command", "ERROR", "Unknown Command target fx:id: " + control)); + else if (!commandTarget(controlTypes.get(control))) + problems.add( + new Problem( + control, + "command", + "ERROR", + "Command target must be a ButtonBase or MenuItem: " + control)); + if (path.isBlank() || path.contains(".")) + problems.add( + new Problem(control, "command", "ERROR", "Expected a simple Command path: " + path)); + else if (!commands.contains(path)) + problems.add(new Problem(control, "command", "ERROR", "Unknown Command path: " + path)); + if (!commandControls.add(control)) + problems.add( + new Problem( + control, + "command", + "ERROR", + "Duplicate Command binding for disable and onAction")); + if (actionHandlers.contains(control)) + problems.add( + new Problem( + control, "command", "ERROR", "Command conflicts with existing onAction handler")); + continue; + } if (!occupied.add(key)) problems.add(new Problem(control, property, "ERROR", "Duplicate binding target")); @@ -591,6 +721,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; @@ -605,6 +738,11 @@ public final class BindingDiscovery { severity = c.status().equals("UNVERIFIED") ? "WARNING" : "ERROR"; message = converter + ": " + c.reason(); } + } else if (knownListPair(path, target, direction)) { + if (listElements.get(path) != target.listElement()) { + severity = "ERROR"; + message = "Observable list element types differ."; + } } else if (target.type() == null || source == Object.class || target.type() == Object.class @@ -624,6 +762,15 @@ public final class BindingDiscovery { } if (!severity.isEmpty()) problems.add(new Problem(control, property, severity, message)); } + for (String control : commandControls) + for (String endpoint : List.of("disable", "onAction")) + if (occupied.contains(control + "." + endpoint)) + problems.add( + new Problem( + control, + "command", + "ERROR", + "Command conflicts with another binding for " + endpoint)); return problems; } diff --git a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/TargetPreview.java b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/TargetPreview.java index 09aeae5..53e70a9 100644 --- a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/TargetPreview.java +++ b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/TargetPreview.java @@ -12,16 +12,19 @@ import javafx.scene.*; import javafx.scene.image.WritableImage; import javafx.scene.paint.Color; -/** - * One preview session per target JVM: the library retains process-wide Model/ViewModel identities. - */ +/** A worker owns one preview session and its managed Views. */ public final class TargetPreview implements AutoCloseable { private static final AtomicBoolean CONSUMED = new AtomicBoolean(); private PreviewSession session; private LoadedView view; + private final ViewModelContext models = new ViewModelContext(); private Scene scene; private final Occurrences occurrences = new Occurrences(); private javafx.stage.Stage interactive; + + private record WindowGeometry(double x, double y, double width, double height, double opacity) {} + + private WindowGeometry beforeWebSnapshot; private boolean closed; private final CompletableFuture ready = new CompletableFuture<>(); private final CompletableFuture cleanup = new CompletableFuture<>(); @@ -128,32 +131,12 @@ public final class TargetPreview implements AutoCloseable { if (component) { String name = d.viewResource().substring(0, d.viewResource().length() - 5).replace('/', '.'); - Class componentType = Class.forName(name, false, loader); - if (!Parent.class.isAssignableFrom(componentType)) - throw new IllegalArgumentException("Component root is not a Parent"); - byte[] wrapper = ("<" + name + "/>").getBytes(java.nio.charset.StandardCharsets.UTF_8); - var wrapped = - new java.net.URL( - null, - "memory:component", - new java.net.URLStreamHandler() { - protected java.net.URLConnection openConnection(java.net.URL url) { - return new java.net.URLConnection(url) { - public void connect() {} - - public java.io.InputStream getInputStream() { - return new java.io.ByteArrayInputStream(wrapper); - } - }; - } - }); - view = ViewLoader.load(wrapped, session.model(), context); - var model = componentType.getMethod("modelProperty").invoke(view.getRoot()); - if (!(model instanceof javafx.beans.property.Property property)) - throw new IllegalArgumentException("Component has no writable Model"); - property.setValue(session.model()); - } else view = ViewLoader.load(resource, session.model(), context); + var componentType = Class.forName(name, false, loader).asSubclass(Parent.class); + view = ViewLoader.loadComponent(componentType, session.model(), context, models); + } else view = ViewLoader.load(resource, session.model(), context, models); scene = new Scene(view.getRoot(), 420, 240); + interactive = new javafx.stage.Stage(); + interactive.setScene(scene); layout(420, 240); var wait = session.ready(); if (wait == null) @@ -216,6 +199,15 @@ public final class TargetPreview implements AutoCloseable { } public byte[] renderNode(String nodeId, int width, int height) { + return snapshotNode(nodeId, width, height, false).toCompletableFuture().join(); + } + + CompletionStage frame(String nodeId, int width, int height) { + return snapshotNode(nodeId, width, height, true); + } + + private CompletionStage snapshotNode( + String nodeId, int width, int height, boolean waitForWeb) { fx(); if (closed || !ready.isDone() || ready.isCompletedExceptionally()) throw new IllegalStateException("Preview not ready"); @@ -226,7 +218,31 @@ public final class TargetPreview implements AutoCloseable { || (long) width * height * 4 > 16 * 1024 * 1024) throw new IllegalArgumentException("Image exceeds protocol limits"); var node = occurrences.resolve(view.getRoot(), nodeId); - if (node == view.getRoot()) layout(width, height); + boolean web = waitForWeb && node != null && node.lookup("WebView") != null; + if (web && !interactive.isShowing()) { + beforeWebSnapshot = + new WindowGeometry( + interactive.getX(), + interactive.getY(), + interactive.getWidth(), + interactive.getHeight(), + interactive.getOpacity()); + double right = + javafx.stage.Screen.getScreens().stream() + .mapToDouble(s -> s.getBounds().getMaxX()) + .max() + .orElse(0); + interactive.setX(right + 1); + interactive.setOpacity(0); + interactive.show(); + } + if (node == view.getRoot()) { + if (web && beforeWebSnapshot != null) { + interactive.setWidth(width + Math.max(0, interactive.getWidth() - scene.getWidth())); + interactive.setHeight(height + Math.max(0, interactive.getHeight() - scene.getHeight())); + } + layout(width, height); + } if (node == null) throw new IllegalArgumentException("Unknown rendered node: " + nodeId); boolean isolate = node != view.getRoot() && node.isResizable(); boolean managed = node.isManaged(); @@ -243,23 +259,75 @@ public final class TargetPreview implements AutoCloseable { parameters.setFill(Color.TRANSPARENT); var bounds = node.getBoundsInParent(); parameters.setViewport(new Rectangle2D(bounds.getMinX(), bounds.getMinY(), width, height)); - var image = node.snapshot(parameters, new WritableImage(width, height)); - byte[] bytes = new byte[width * height * 4]; - var pixels = image.getPixelReader(); - for (int y = 0; y < height; y++) - for (int x = 0; x < width; x++) { - int argb = pixels.getArgb(x, y), i = (y * width + x) * 4; - bytes[i] = (byte) (argb >>> 16); - bytes[i + 1] = (byte) (argb >>> 8); - bytes[i + 2] = (byte) argb; - bytes[i + 3] = (byte) (argb >>> 24); - } - return bytes; - } finally { + var image = new WritableImage(width, height); + if (web) { + var frame = webFrame(node, parameters, image); + return frame.whenComplete( + (ignored, error) -> { + if (isolate) node.setManaged(managed); + }); + } + var bytes = pixels(node.snapshot(parameters, image)); if (isolate) node.setManaged(managed); + return CompletableFuture.completedFuture(bytes); + } catch (Throwable error) { + if (isolate) node.setManaged(managed); + throw error; } } + /** + * WebKit updates its render queue on a stage pulse, before scene layout. Give it a pulse at the + * new layout size before reading the next snapshot. + */ + private CompletionStage webFrame( + Node node, SnapshotParameters parameters, WritableImage image) { + var result = new CompletableFuture(); + Scene owner = scene; + owner.addPostLayoutPulseListener( + new Runnable() { + public void run() { + owner.removePostLayoutPulseListener(this); + Platform.runLater( + () -> { + try { + if (closed) throw new CancellationException("Preview closed"); + node.snapshot( + snapshot -> { + try { + result.complete(pixels(snapshot.getImage())); + } catch (Throwable error) { + result.completeExceptionally(error); + } + return null; + }, + parameters, + image); + } catch (Throwable error) { + result.completeExceptionally(error); + } + }); + } + }); + Platform.requestNextPulse(); + return result; + } + + private static byte[] pixels(javafx.scene.image.Image image) { + int width = (int) image.getWidth(), height = (int) image.getHeight(); + byte[] bytes = new byte[width * height * 4]; + var pixels = image.getPixelReader(); + for (int y = 0; y < height; y++) + for (int x = 0; x < width; x++) { + int argb = pixels.getArgb(x, y), i = (y * width + x) * 4; + bytes[i] = (byte) (argb >>> 16); + bytes[i + 1] = (byte) (argb >>> 8); + bytes[i + 2] = (byte) argb; + bytes[i + 3] = (byte) (argb >>> 24); + } + return bytes; + } + public de.neitzel.fxdesigner.protocol.LayoutMetrics measure(String key, int width, int height) { fx(); var node = occurrences.resolve(view.getRoot(), key); @@ -285,11 +353,19 @@ public final class TargetPreview implements AutoCloseable { public void showInteractive(String title, Runnable onClosed) { fx(); - if (interactive == null) { - interactive = new javafx.stage.Stage(); - interactive.setScene(scene); - interactive.setOnHidden(e -> onClosed.run()); + if (beforeWebSnapshot != null) { + var previous = beforeWebSnapshot; + beforeWebSnapshot = null; + interactive.hide(); + interactive.setOpacity(previous.opacity()); + if (Double.isFinite(previous.width())) interactive.setWidth(previous.width()); + if (Double.isFinite(previous.height())) interactive.setHeight(previous.height()); + if (Double.isFinite(previous.x()) && Double.isFinite(previous.y())) { + interactive.setX(previous.x()); + interactive.setY(previous.y()); + } else interactive.centerOnScreen(); } + interactive.setOnHidden(e -> onClosed.run()); interactive.setTitle(title); interactive.show(); interactive.toFront(); @@ -316,7 +392,9 @@ public final class TargetPreview implements AutoCloseable { closed = true; timer.shutdownNow(); try { - if (session != null) session.close(); + try (var ownedSession = session) { + models.close(); + } cleanup.complete(null); } catch (Throwable e) { if (failure != null) failure.addSuppressed(e); diff --git a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/WorkerMain.java b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/WorkerMain.java index 1f78ad6..8391796 100644 --- a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/WorkerMain.java +++ b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/WorkerMain.java @@ -205,13 +205,30 @@ public final class WorkerMain { () -> { if (stopping.get()) return; try { - send( - socket, - new Packet( - Kind.RESULT, - p.operation(), - p.identity(), - response(ready, p, data))); + var result = + p.operation() == Operation.RENDER + ? ready.frame( + data.get("node"), + p.identity().width(), + p.identity().height()) + : java.util.concurrent.CompletableFuture.completedFuture( + response(ready, p, data)); + result.whenComplete( + (payload, failure) -> { + if (stopping.get()) return; + if (failure != null) { + error(socket, p, failure); + return; + } + try { + send( + socket, + new Packet( + Kind.RESULT, p.operation(), p.identity(), payload)); + } catch (IOException e) { + error(socket, p, e); + } + }); } catch (Throwable e) { error(socket, p, e); } @@ -231,8 +248,6 @@ public final class WorkerMain { private static byte[] response(TargetPreview ready, Packet p, Map data) throws Exception { return switch (p.operation()) { - case RENDER -> - ready.renderNode(data.get("node"), p.identity().width(), p.identity().height()); case MEASURE -> PreviewMessages.encode( ready diff --git a/designer-target-tools/src/test/java/de/neitzel/fxdesigner/target/BindingDiscoveryTest.java b/designer-target-tools/src/test/java/de/neitzel/fxdesigner/target/BindingDiscoveryTest.java index 5bd2ba7..4b886fe 100644 --- a/designer-target-tools/src/test/java/de/neitzel/fxdesigner/target/BindingDiscoveryTest.java +++ b/designer-target-tools/src/test/java/de/neitzel/fxdesigner/target/BindingDiscoveryTest.java @@ -112,6 +112,67 @@ class BindingDiscoveryTest { () -> BindingDiscovery.inspect(fxml(), "", "wrong", getClass().getClassLoader())); } + @de.neitzel.fx.view.ViewModelClass(Commands.class) + public static class Controller {} + + public static class Commands { + public Commands(Model model) { + throw new AssertionError("Discovery constructed the ViewModel"); + } + + public de.neitzel.fx.view.Command getOpen() { + throw new AssertionError("Discovery executed the Command getter"); + } + } + + @Test + void commandDiscoveryResolvesTargetsAndLocatesConflictsInEitherOrder() throws Exception { + String command = ""; + String xml = + "" + + "" + + "" + + "" + + command + + "