diff --git a/README.md b/README.md index d59d71f..2ff419a 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ 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). +Open `ArchiveWindow.fxml` in **Neitzel Designer**, choose **Build and Refresh** and start **Interactive preview** with **Beispielarchiv**. Open the sample archive and select an entry in the example document. The entry, selected folder and scan state control the same 22 command permissions as the application. Opening read-only disables import and account management. The trash button opens the populated session-local trash, and closing the archive disables it. 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. @@ -95,6 +95,10 @@ Use `--import-form` with `scripts/check-ide-host.py --archiver ../Archiver` and Use `--management-readers` with the Archiver host check to exercise the two account states, the empty and populated trash, and all five reader toolbars. The check saves and reopens CommandBinding changes in both management forms and an icon and accessible text change in the picture toolbar. +Use `--row-menus` to qualify menu labels and Command assignments on the Archiver folder and trash rows and group captions for paths and file types containing spaces. The DataGrid inspector preserves literal keys using the qualified target runtime. + +Use `--folder-profiles` with the Archiver host check to rebind the profile buttons and edit mail and book columns against indexed EML and EPUB files. The editable attribute list offers the row attributes used by the current grid. + Use `--folder-actions` with the Archiver host check to edit a text field’s column count, accessible name and controller action, then exercise the folder toolbar’s dismiss handler, full-text search, multiple selection and saved display profiles. Use `--document-tabs` with the Archiver host check to open the production archive window and select **Archiver · HTML-Dokumenttabs**. The check also opens the production HTML and details FXML files directly, edits the assigned-tag Component and the input prompt through the visual inspector, and reopens the saved files. In the archive window it adds a second tag to the invoice, switches to the delivery note and back, removes the selected tag, and checks each WebView and suggestion popup. Direct examples cover read-only and busy states. @@ -107,6 +111,10 @@ Worker startup cancellation and ready-preview cleanup are covered by the [native These graphical checks require a macOS desktop session; other platforms are not qualified. See [workflow limits](docs/first-connected-workflow.md#limits-and-next-stage) before using arbitrary application documents. +In Archiver `HtmlDocument.fxml`, **Form controls** offers `HtmlMediaButton` in the palette. Select its **viewer** property, choose an earlier `HtmlViewer` with an `fx:id` and click **Set property**. **Reset property** clears the reference. **Bindings → Structure → Rename identifier** updates the reference when renaming the target. The `--viewer-import` IntelliJ qualification uses the local-image reference example and the real import dialog with a controlled file error and retry. + +Use `--reader-states` with the Archiver IntelliJ host check for the direct `DocumentTag.fxml` example, binary attachment export and HTML load error with recovery. The test saves a chip style in the disposable project and checks the styled chips in the archive window. + ## Implementation references - [Lombok adoption](docs/lombok-adoption.md): scope, API preservation and build/host validation. diff --git a/designer-core/src/main/java/de/neitzel/fxdesigner/build/SourceWatch.java b/designer-core/src/main/java/de/neitzel/fxdesigner/build/SourceWatch.java index 4cce2bb..bb65d16 100644 --- a/designer-core/src/main/java/de/neitzel/fxdesigner/build/SourceWatch.java +++ b/designer-core/src/main/java/de/neitzel/fxdesigner/build/SourceWatch.java @@ -2,6 +2,7 @@ package de.neitzel.fxdesigner.build; import java.io.*; import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; import java.util.*; /** Detects transient changes and overflow in addition to pre/post hashes and file attributes. */ @@ -13,18 +14,32 @@ final class SourceWatch implements AutoCloseable { SourceWatch(Path root) throws IOException { this.root = root; watch = root.getFileSystem().newWatchService(); - try (var dirs = Files.walk(root)) { - for (Path dir : - dirs.filter(Files::isDirectory) - .filter(p -> InputTree.included(root, root.relativize(p))) - .toList()) - keys.put( - dir.register( - watch, - StandardWatchEventKinds.ENTRY_CREATE, - StandardWatchEventKinds.ENTRY_DELETE, - StandardWatchEventKinds.ENTRY_MODIFY), - dir); + try { + Files.walkFileTree( + root, + new SimpleFileVisitor<>() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) + throws IOException { + if (!InputTree.included(root, root.relativize(dir))) + return FileVisitResult.SKIP_SUBTREE; + keys.put( + dir.register( + watch, + StandardWatchEventKinds.ENTRY_CREATE, + StandardWatchEventKinds.ENTRY_DELETE, + StandardWatchEventKinds.ENTRY_MODIFY), + dir); + return FileVisitResult.CONTINUE; + } + }); + } catch (IOException | RuntimeException failure) { + try { + watch.close(); + } catch (IOException cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; } } diff --git a/designer-core/src/test/java/de/neitzel/fxdesigner/build/SourceWatchTest.java b/designer-core/src/test/java/de/neitzel/fxdesigner/build/SourceWatchTest.java new file mode 100644 index 0000000..d39c83a --- /dev/null +++ b/designer-core/src/test/java/de/neitzel/fxdesigner/build/SourceWatchTest.java @@ -0,0 +1,29 @@ +package de.neitzel.fxdesigner.build; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermissions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class SourceWatchTest { + @Test + void registeringBuildInputsNeverTraversesSnapshotContents(@TempDir Path project) + throws Exception { + assumeTrue(project.getFileSystem().supportedFileAttributeViews().contains("posix")); + var snapshot = Files.createDirectories(project.resolve(".neitzel-fx-designer/snapshots")); + Files.createFile(snapshot.resolve("state.tmp")); + var permissions = Files.getPosixFilePermissions(snapshot); + try { + Files.setPosixFilePermissions(snapshot, PosixFilePermissions.fromString("---------")); + assumeTrue(!Files.isReadable(snapshot)); + try (var watch = new SourceWatch(project)) { + assertFalse(watch.changed()); + } + } finally { + Files.setPosixFilePermissions(snapshot, permissions); + } + } +} 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 b13e54e..a2bd38d 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 @@ -110,8 +110,12 @@ final class BindingDocument { } boolean named(Element e, String pkg, String type) { - if (e.getTagName().equals(pkg + type)) return true; - if (!e.getTagName().equals(type)) return false; + return resolves(e.getTagName(), pkg, type); + } + + boolean resolves(String tag, String pkg, String type) { + if (tag.equals(pkg + type)) return true; + if (!tag.equals(type)) return false; 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; 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 d59cb41..dd2f507 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 @@ -1,6 +1,7 @@ package de.neitzel.fxdesigner.kit; import com.oracle.javafx.scenebuilder.kit.editor.panel.content.ContentPanelController; +import com.oracle.javafx.scenebuilder.kit.editor.panel.content.driver.AbstractDriver; import com.oracle.javafx.scenebuilder.kit.editor.panel.hierarchy.HierarchyPanelController; import com.oracle.javafx.scenebuilder.kit.editor.panel.inspector.InspectorPanelController; import com.oracle.javafx.scenebuilder.kit.fxom.*; @@ -67,6 +68,22 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { .componentAttributes(id) .forEach( (name, value) -> { + if (name.equals("viewer") + && projection + .components() + .get(id) + .equals("de.neitzel.archiver.ui.HtmlMediaButton")) { + var edit = new Button("Choose HtmlViewer"); + edit.setOnAction( + e -> { + var panel = (TitledPane) lookup("#form-controls-inspector"); + panel.setExpanded(true); + formEditor.selectIndex(projection.sourceIndex(id)); + formEditor.selectViewerField(); + }); + componentInspector.getChildren().add(new HBox(4, new Label(name), edit)); + return; + } var field = new TextField(value); field.setId("component-property-" + name); field.setOnAction( @@ -172,7 +189,15 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { this.file = file; Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); kit = new KitView(host); - content = new ContentPanelController(kit.editor()); + content = + new ContentPanelController(kit.editor()) { + @Override + public AbstractDriver lookupDriver(FXOMObject object) { + // Popup menus have no editable Scene accessory or bounds on the form canvas. + if (object.getSceneGraphObject() instanceof ContextMenu) return null; + return super.lookupDriver(object); + } + }; design = new SplitPane( new HierarchyPanelController(kit.editor()).getPanelRoot(), @@ -472,6 +497,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable { bindingEditor.editProperty(values); }); var formPane = new TitledPane("Form controls", formEditor); + formPane.setId("form-controls-inspector"); formPane.setExpanded(false); formPane .expandedProperty() 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 index c322436..360bd66 100644 --- 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 @@ -9,19 +9,22 @@ import org.w3c.dom.*; * Visual form operations use ranges from the current source so bindings keep their original text. */ final class FormDocument { + static final String VIEWER_REFERENCE = "HtmlViewer reference"; + private static final String MEDIA_BUTTON = "HtmlMediaButton"; static final Map TYPES = new TreeMap<>(); static { register( "javafx.scene.control", "Label TextField TextArea PasswordField Button CheckBox ComboBox ToolBar Tab TabPane" - + " ScrollPane SplitPane"); + + " ScrollPane SplitPane MenuItem ContextMenu"); register( "javafx.scene.layout", "GridPane VBox HBox StackPane AnchorPane FlowPane TilePane Pane BorderPane"); register( "de.neitzel.fx.control", "StatusBar ToolBarPane AutoCompleteTextField TagChip NonNegativeIntegerSpinner HtmlViewer"); + register("de.neitzel.archiver.ui", MEDIA_BUTTON); register("de.neitzel.fx.view", "DataGrid Table"); register("de.neitzel.fx.docking", "DockPane"); } @@ -62,10 +65,14 @@ final class FormDocument { final List slots = new ArrayList<>(); private final Map imports = new HashMap<>(); private final Set packages = new HashSet<>(); - private final Set ids = new HashSet<>(); + private final Set ids = new HashSet<>(), duplicateIds = new HashSet<>(); FormDocument(String text) throws Exception { - xml = new BindingDocument(text); + this(new BindingDocument(text)); + } + + FormDocument(BindingDocument xml) { + this.xml = xml; 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(); @@ -76,7 +83,7 @@ final class FormDocument { 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); + if (!id.isEmpty() && !ids.add(id)) duplicateIds.add(id); String tag = e.getTagName(); if (BindingDocument.FX.equals(e.getNamespaceURI()) && e.getLocalName().equals("root")) tag = e.getAttribute("type"); @@ -88,6 +95,56 @@ final class FormDocument { } } + List palette() { + boolean mediaButtonInDocument = items.stream().anyMatch(i -> i.type().equals(MEDIA_BUTTON)); + return TYPES.keySet().stream() + .filter(type -> !type.equals("ContextMenu")) + .filter( + type -> + !type.equals(MEDIA_BUTTON) + || mediaButtonInDocument + || resolves(MEDIA_BUTTON, TYPES.get(MEDIA_BUTTON))) + .toList(); + } + + List viewerTargets(Item item) { + var owner = element(item); + return xml.elements.subList(0, item.index()).stream() + .filter( + e -> + isViewer(e) + && (e.compareDocumentPosition(owner) & Node.DOCUMENT_POSITION_CONTAINED_BY) + == 0) + .map(e -> e.getAttributeNS(BindingDocument.FX, "id")) + .filter(id -> !id.isEmpty() && !duplicateIds.contains(id)) + .map(id -> "$" + id) + .toList(); + } + + private boolean isViewer(Element e) { + String tag = + BindingDocument.FX.equals(e.getNamespaceURI()) && "root".equals(e.getLocalName()) + ? e.getAttribute("type") + : e.getTagName(); + return resolves(tag, TYPES.get("HtmlViewer")); + } + + List viewerReferenceErrors() { + var errors = new ArrayList(); + for (var item : items) { + if (!item.type().equals(MEDIA_BUTTON)) continue; + String value = element(item).getAttribute("viewer"); + if (!value.isEmpty() && !value.startsWith("${") && !viewerTargets(item).contains(value)) + errors.add(viewerReferenceError(value)); + } + return errors; + } + + private static String viewerReferenceError(String value) { + return "HtmlMediaButton.viewer requires a unique HtmlViewer fx:id declared before the button: " + + value; + } + private boolean resolves(String tag, String type) { if (tag.contains(".")) return tag.equals(type); if (imports.containsKey(tag)) return type.equals(imports.get(tag)); @@ -112,7 +169,7 @@ final class FormDocument { case "TabPane" -> List.of("tabs"); case "Tab", "ScrollPane" -> List.of("content"); case "BorderPane" -> List.of("center", "top", "bottom", "left", "right"); - case "SplitPane", "ToolBarPane", "ToolBar" -> List.of("items"); + case "ContextMenu", "SplitPane", "ToolBarPane", "ToolBar" -> List.of("items"); case "StatusBar" -> List.of("leftItems", "rightItems"); default -> List.of(); }; @@ -216,6 +273,11 @@ final class FormDocument { } private void accept(String type, Slot slot, Element moving) { + if (type.equals("ContextMenu")) + throw new IllegalArgumentException("A ContextMenu belongs to its owning control."); + if (type.equals("MenuItem") != slot.owner().type().equals("ContextMenu")) + throw new IllegalArgumentException( + "A ContextMenu accepts MenuItems. Other destinations accept controls."); if (type.equals("Tab") != slot.property().equals("tabs")) throw new IllegalArgumentException( slot.property().equals("tabs") @@ -249,6 +311,7 @@ final class FormDocument { if (container != null) return xml.append(container, snippet, ""); if ((single(slot) && members.isEmpty()) || slot.owner().type().equals("StatusBar") + || slot.owner().type().equals("ContextMenu") || (slot.owner().type().equals("ToolBarPane") && members.isEmpty())) snippet = "<" + slot.property() + ">" + snippet + ""; return xml.append(owner, snippet, ""); @@ -283,7 +346,7 @@ final class FormDocument { Edit add(String type, Slot slot, int at) { var host = owner(slot); - if (!TYPES.containsKey(type)) throw new IllegalArgumentException("Choose a palette control."); + if (!palette().contains(type)) throw new IllegalArgumentException("Choose a palette control."); accept(type, slot, null); String id = fresh(type), prefix = fxPrefix(host), qualified = TYPES.get(type); var edits = new ArrayList(); @@ -298,6 +361,7 @@ final class FormDocument { String extra = type.equals("Label") || type.equals("Button") + || type.equals("MenuItem") || type.equals("TagChip") || type.equals("Tab") ? " text=\"" + type + "\"" @@ -371,6 +435,14 @@ final class FormDocument { List fields(Item item) { var e = element(item); var fields = new LinkedHashMap(); + if (item.type().equals("ContextMenu")) return withSourceFields(e, fields); + if (item.type().equals("MenuItem")) { + field(fields, "text", "String", ""); + field(fields, "disable", "Boolean", "false"); + field(fields, "visible", "Boolean", "true"); + field(fields, "onAction", "Event handler", ""); + return withSourceFields(e, fields); + } if (item.type().equals("Tab")) { field(fields, "text", "String", ""); field(fields, "closable", "Boolean", "true"); @@ -430,6 +502,7 @@ final class FormDocument { .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(MEDIA_BUTTON)) field(fields, "viewer", VIEWER_REFERENCE, "none"); if (item.type().equals("HtmlViewer")) { field(fields, "html", "String", ""); field(fields, "mediaButtonVisible", "Boolean", "true"); @@ -561,6 +634,10 @@ final class FormDocument { } if (!reset) { switch (field.type()) { + case VIEWER_REFERENCE -> { + if (!viewerTargets(item).contains(input)) + throw new IllegalArgumentException(viewerReferenceError(input)); + } case "Boolean" -> { if (!Set.of("true", "false").contains(input)) throw new IllegalArgumentException("Choose true or false."); diff --git a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormEditor.java b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormEditor.java index 6c80258..1a820b7 100644 --- a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormEditor.java +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/FormEditor.java @@ -14,6 +14,7 @@ final class FormEditor extends VBox { private final Spinner position = new Spinner<>(0, 0, 0); private final ComboBox selected = combo("form-control"); private final ComboBox field = combo("form-property"); + private final ComboBox viewers = combo("form-viewer-reference"); private final ComboBox handlers = combo("form-event-handlers"); private Optional> verifiedHandlers = Optional.empty(); private final TextArea value = new TextArea(); @@ -29,8 +30,6 @@ final class FormEditor extends VBox { Consumer bind) { super(5); this.submit = submit; - palette.getItems().setAll(FormDocument.TYPES.keySet()); - palette.setValue("Label"); position.setId("form-position"); position.setPrefWidth(74); handlers.setPromptText("Choose controller method"); @@ -40,6 +39,9 @@ final class FormEditor extends VBox { e -> { if (handlers.getValue() != null) value.setText(handlers.getValue()); }); + viewers.setPromptText("Choose HtmlViewer"); + viewers.managedProperty().bind(viewers.visibleProperty()); + value.managedProperty().bind(value.visibleProperty()); value.setId("form-value"); value.setPrefRowCount(2); details.setId("form-field-type"); @@ -91,6 +93,7 @@ final class FormEditor extends VBox { position.getValue())))), row(new Label("Property"), field, details), handlers, + viewers, value, row( button( @@ -107,7 +110,12 @@ final class FormEditor extends VBox { + " for ActionEvent. Choose a listed method with no" + " argument or a compatible event argument."); return form.set( - selected.getValue(), field.getValue(), value.getText(), false); + selected.getValue(), + field.getValue(), + viewers.isVisible() + ? Objects.toString(viewers.getValue(), "") + : value.getText(), + false); })), button( "Reset property", @@ -160,6 +168,13 @@ final class FormEditor extends VBox { } } + void selectViewerField() { + field.getItems().stream() + .filter(property -> property.type().equals(FormDocument.VIEWER_REFERENCE)) + .findFirst() + .ifPresent(field::setValue); + } + void selectIndex(Integer index) { if (form == null || index == null || loading) return; form.items.stream() @@ -213,6 +228,11 @@ final class FormEditor extends VBox { handlers.getSelectionModel().clearSelection(); var f = field.getValue(); var item = selected.getValue(); + boolean viewerReference = f != null && f.type().equals(FormDocument.VIEWER_REFERENCE); + viewers.setVisible(viewerReference); + value.setVisible(!viewerReference); + viewers.getItems().clear(); + viewers.setValue(null); if (form == null || item == null || f == null) { details.setText(""); value.clear(); @@ -227,8 +247,17 @@ final class FormEditor extends VBox { ? "bind to a model list" : f.editable() ? "editable" : "read only")); if (eventSelected()) showHandlerStatus(); + String current = form.value(item, f); + if (viewerReference) { + viewers.getItems().setAll(form.viewerTargets(item)); + if (viewers.getItems().contains(current)) viewers.setValue(current); + else if (!current.isEmpty()) + details.setText("Unresolved or incompatible HtmlViewer target " + current); + else if (viewers.getItems().isEmpty()) + details.setText("No HtmlViewer with an earlier fx:id."); + } value.setEditable(f.editable()); - value.setText(form.value(item, f)); + value.setText(current); } String load(String source, boolean writable) { @@ -243,6 +272,9 @@ final class FormEditor extends VBox { loading = true; try { form = new FormDocument(source); + String paletteType = palette.getValue(); + palette.getItems().setAll(form.palette()); + palette.setValue(palette.getItems().contains(paletteType) ? paletteType : "Label"); selected.getItems().setAll(form.items); destination.getItems().setAll(form.slots); selected.setValue( diff --git a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/GridDockDocument.java b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/GridDockDocument.java index 5008e9f..9f7d63b 100644 --- a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/GridDockDocument.java +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/GridDockDocument.java @@ -104,7 +104,7 @@ final class GridDockDocument { return result; } - private Element property(Element e, String name) { + static Element property(Element e, String name) { var list = children(e).stream().filter(c -> c.getTagName().equals(name)).toList(); if (list.size() > 1) throw new IllegalArgumentException("Multiple declarations of " + name); return list.isEmpty() ? null : list.getFirst(); @@ -196,11 +196,44 @@ final class GridDockDocument { if (attr.getNamespaceURI() == null && literalKey(attr.getNodeName()) && !reference(attr.getNodeValue())) - names.put(attr.getNodeName(), attr.getNodeValue().replaceFirst("^\\\\", "")); + names.put(attr.getNodeName(), literal(attr.getNodeValue())); } + for (var pair : labelPairs(column)) { + if (pair.hasAttribute("key") + && pair.hasAttribute("value") + && !reference(pair.getAttribute("key")) + && !reference(pair.getAttribute("value"))) { + names.put(literal(pair.getAttribute("key")), literal(pair.getAttribute("value"))); + } + } return names; } + private List labelPairs(Element column) { + return children(column).stream() + .filter( + child -> { + String tag = child.getTagName(); + String suffix = ".groupLabel"; + return tag.endsWith(suffix) + && xml.resolves( + tag.substring(0, tag.length() - suffix.length()), + "de.neitzel.fx.view.", + "DataGridColumn"); + }) + .flatMap(child -> children(child).stream()) + .filter(child -> xml.named(child, "javafx.util.", "Pair")) + .toList(); + } + + private static String literal(String value) { + return value.startsWith("\\") ? value.substring(1) : value; + } + + private static String fxmlLiteral(String value) { + return reference(value) || value.startsWith("\\") ? "\\" + value : value; + } + private static boolean literalKey(String key) { // FXMLLoader reads an inline, read-only Map's ordinary property attributes as keys. return key.matches("[\\p{L}_][\\p{L}\\p{N}_-]*") @@ -213,17 +246,62 @@ final class GridDockDocument { } List groupLabel(Element column, String key, String label, boolean remove) { - if (!type(column).equals("DataGridColumn") || !literalKey(key)) - throw new IllegalArgumentException( - "Use a literal FXML map key (letters, digits, underscores or hyphens)."); + if (!type(column).equals("DataGridColumn") || key.isEmpty()) + throw new IllegalArgumentException("Enter a group key."); if (column.hasAttribute("groupLabels")) throw new IllegalArgumentException("This groupLabels map is supplied by an attribute."); var map = property(column, "groupLabels"); - if (map != null && (property(map, key) != null || reference(map.getAttribute(key)))) + if (map != null + && literalKey(key) + && (property(map, key) != null || reference(map.getAttribute(key)))) throw new IllegalArgumentException("This key is supplied by a nested value or reference."); - if (remove && (map == null || !map.hasAttribute(key))) return List.of(); if (!remove && label.isBlank()) throw new IllegalArgumentException("Enter a group label."); - String encoded = (reference(label) || label.startsWith("\\")) ? "\\" + label : label; + String encoded = fxmlLiteral(label); + var pairs = + labelPairs(column).stream() + .filter( + pair -> + pair.hasAttribute("key") + && !reference(pair.getAttribute("key")) + && literal(pair.getAttribute("key")).equals(key)) + .toList(); + if (pairs.size() > 1 + || !pairs.isEmpty() && literalKey(key) && map != null && map.hasAttribute(key)) + throw new IllegalArgumentException( + "Duplicate group key. Resolve the declarations in Source."); + if (!pairs.isEmpty()) { + var pair = pairs.getFirst(); + if (!pair.hasAttribute("value") + || reference(pair.getAttribute("value")) + || !children(pair).isEmpty()) + throw new IllegalArgumentException("This key is supplied by a nested value or reference."); + if (remove) { + var property = (Element) pair.getParentNode(); + if (children(property).size() > 1) return List.of(replace(pair, "")); + var wrapper = tag(property); + var entry = tag(pair); + String remaining = + xml.text.substring(wrapper.openEnd(), entry.start()) + + xml.text.substring(entry.end(), wrapper.closeStart()); + return List.of(replace(property, remaining.isBlank() ? "" : remaining)); + } + return xml.source.attributes(xml.elements.indexOf(pair), Map.of("value", encoded)); + } + if (remove && (map == null || !map.hasAttribute(key))) return List.of(); + if (!literalKey(key)) { + String property = column.getTagName() + ".groupLabel"; + String snippet = + "<" + + property + + ">"; + return List.of(xml.append(column, snippet, "")); + } if (map == null) return List.of( xml.append( @@ -232,6 +310,59 @@ final class GridDockDocument { xml.elements.indexOf(map), Collections.singletonMap(key, remove ? null : encoded)); } + // DataGridColumn defaults in the target library. The Kit does not load target classes. + static final Map COLUMN_WIDTHS = + Map.of("minimumWidth", "80", "width", "150", "maximumWidth", "1200"); + + private record ColumnWidth(String description, Double literal) { + static ColumnWidth read(Element column, String name, String edited, String proposed) { + String text = column.getAttribute(name); + if (name.equals(edited)) text = proposed; + else { + var nested = property(column, name); + if (nested != null) { + if (!children(nested).isEmpty()) return new ColumnWidth(name + "=", null); + text = nested.getTextContent().strip(); + } + } + boolean useDefault = text.isEmpty(); + if (useDefault) text = COLUMN_WIDTHS.get(name); + String label = name + "=" + text; + if (reference(text) || text.startsWith("#")) { + if (name.equals(edited)) + throw new IllegalArgumentException("Enter a literal pixel width for " + name); + return new ColumnWidth(label + " (resolved at runtime)", null); + } + double pixels; + try { + pixels = Double.parseDouble(text); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("Expected a pixel width for " + label); + } + if (!Double.isFinite(pixels) || pixels <= 0) + throw new IllegalArgumentException("Expected a finite, positive pixel width for " + label); + return new ColumnWidth(label + (useDefault ? " (default)" : ""), pixels); + } + + boolean exceeds(ColumnWidth other) { + return literal != null && other.literal != null && literal > other.literal; + } + } + + private static void validateColumnWidths(Element column, String edited, String proposed) { + var minimum = ColumnWidth.read(column, "minimumWidth", edited, proposed); + var width = ColumnWidth.read(column, "width", edited, proposed); + var maximum = ColumnWidth.read(column, "maximumWidth", edited, proposed); + if (minimum.exceeds(width) || width.exceeds(maximum) || minimum.exceeds(maximum)) + throw new IllegalArgumentException( + "Expected minimumWidth ≤ width ≤ maximumWidth: " + + minimum.description() + + ", " + + width.description() + + ", " + + maximum.description()); + } + List set(Element e, String field, String value) { if (!SETTINGS.getOrDefault(type(e), List.of()).contains(field) || Set.of("items", "source", "groupLabels").contains(field)) @@ -239,7 +370,7 @@ final class GridDockDocument { if (property(e, field) != null) throw new IllegalArgumentException( "The property has a nested declaration. Edit it in Source."); - if (e.getAttribute(field).matches("^[%$#].*")) + if (reference(e.getAttribute(field)) || e.getAttribute(field).startsWith("#")) throw new IllegalArgumentException("This property is a reference. Edit it in Source."); boolean required = field.equals("id") || field.equals("destinationId") || field.equals("header"); @@ -248,7 +379,9 @@ final class GridDockDocument { var opts = options(field); if (!value.isEmpty() && !opts.isEmpty() && !opts.contains(value)) throw new IllegalArgumentException("Choose one of " + opts); - if (!value.isEmpty() + if (type(e).equals("DataGridColumn") && COLUMN_WIDTHS.containsKey(field)) { + validateColumnWidths(e, field, value); + } else if (!value.isEmpty() && Set.of( "width", "minimumWidth", diff --git a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/GridDockEditor.java b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/GridDockEditor.java index 6cf953a..a162381 100644 --- a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/GridDockEditor.java +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/GridDockEditor.java @@ -250,8 +250,33 @@ final class GridDockEditor extends VBox { default -> ""; } : ""; + if (doc.type(e).equals("DataGridColumn") && GridDockDocument.COLUMN_WIDTHS.containsKey(field)) { + hint = + GridDockDocument.property(e, field) == null + ? "Default: " + GridDockDocument.COLUMN_WIDTHS.get(field) + " px" + : "Nested FXML value"; + value.setTooltip( + new Tooltip( + "minimumWidth ≤ width ≤ maximumWidth. FXML references are resolved at runtime.")); + } else value.setTooltip(null); value.setPromptText(hint); - value.getItems().setAll(GridDockDocument.options(field)); + if ("attribute".equals(field) || "groupAttribute".equals(field)) { + var columns = doc.branches(doc.parentOfType(e, "DataGrid")); + value + .getItems() + .setAll( + columns.stream() + .map( + column -> + column.getAttribute( + column.hasAttribute("attribute") ? "attribute" : "id")) + .filter(name -> !name.isBlank()) + .distinct() + .toList()); + value.setTooltip( + new Tooltip( + "Row attributes used by this grid. You can also enter another row attribute.")); + } else value.getItems().setAll(GridDockDocument.options(field)); value.setValue(e.getAttribute(field)); value.getEditor().setText(e.getAttribute(field)); } diff --git a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/ReferenceDocument.java b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/ReferenceDocument.java index 9879054..1ebf692 100644 --- a/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/ReferenceDocument.java +++ b/designer-kit-ui/src/main/java/de/neitzel/fxdesigner/kit/ReferenceDocument.java @@ -401,6 +401,7 @@ final class ReferenceDocument { && a.getNodeName().equals("source")) id = a.getNodeValue(); if (id != null && !available.contains(id)) result.add("Unresolved FXML reference: " + id); } + result.addAll(new FormDocument(xml).viewerReferenceErrors()); return List.copyOf(result); } diff --git a/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FormDocumentTest.java b/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FormDocumentTest.java index f768b39..82b4585 100644 --- a/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FormDocumentTest.java +++ b/designer-kit-ui/src/test/java/de/neitzel/fxdesigner/kit/FormDocumentTest.java @@ -70,7 +70,11 @@ class FormDocumentTest { @Test void emptyGridAndNamedListsKeepReferencesAndRejectCycles() throws Exception { assertEquals( - 9, FormDocument.TYPES.values().stream().filter(n -> n.startsWith("de.neitzel.")).count()); + 9, + doc().palette().stream() + .map(FormDocument.TYPES::get) + .filter(n -> n.startsWith("de.neitzel.")) + .count()); for (String type : List.of( "Label", @@ -168,4 +172,34 @@ class FormDocumentTest { assertEquals(2, doc().size(slot("", "items"))); assertFalse(source.contains("")); } + + @Test + void mediaReferenceChecksTypeAndDeclarationOrderAndPreservesHtmlBinding() throws Exception { + source = + """ + + + + + + + + + + """; + assertTrue(doc().palette().contains("HtmlMediaButton")); + assertEquals(List.of("$article"), doc().viewerTargets(item("media"))); + assertTrue(new ReferenceDocument(source).referenceErrors().getFirst().contains("$unrelated")); + assertThrows(IllegalArgumentException.class, () -> set("media", "viewer", "$later")); + assertThrows(IllegalArgumentException.class, () -> set("media", "viewer", "$missing")); + set("media", "viewer", "$article"); + assertTrue(new ReferenceDocument(source).referenceErrors().isEmpty()); + assertTrue( + source.contains( + "")); + } } 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 index 0ea792c..79b2ea7 100644 --- 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 @@ -5,6 +5,33 @@ import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class GridDockDocumentTest { + @Test + void columnBoundsIncludeDefaultsResetsAndKnownPartsOfDynamicWidths() throws Exception { + var doc = + new GridDockDocument( + ""); + var col = doc.xml.elements.getFirst(); + assertThrows(IllegalArgumentException.class, () -> doc.set(col, "width", "")); + assertThrows(IllegalArgumentException.class, () -> doc.set(col, "minimumWidth", "300")); + assertThrows(IllegalArgumentException.class, () -> doc.set(col, "maximumWidth", "100")); + assertThrows(IllegalArgumentException.class, () -> doc.set(col, "width", "%size")); + assertDoesNotThrow(() -> doc.set(col, "maximumWidth", "230")); + assertDoesNotThrow(() -> doc.set(col, "minimumWidth", "")); + var dynamic = + new GridDockDocument( + ""); + var bound = dynamic.xml.elements.getFirst(); + assertTrue( + assertThrows( + IllegalArgumentException.class, () -> dynamic.set(bound, "minimumWidth", "201")) + .getMessage() + .contains("%start (resolved at runtime)")); + assertEquals( + dynamic.xml.text.replace("200", "210"), + dynamic.xml.source.apply(dynamic.set(bound, "maximumWidth", "210"))); + assertThrows(IllegalArgumentException.class, () -> dynamic.set(bound, "width", "")); + } + @Test void dockMinimaAllowZeroWithoutChangingGridColumnRules() throws Exception { var source = @@ -49,6 +76,47 @@ class GridDockDocumentTest { assertThrows(IllegalArgumentException.class, () -> doc.set(col, "fixedPosition", "2")); } + @Test + void pathLabelsRoundTripWithoutChangingNeighbouringMapEntries() throws Exception { + String source = + """ + + + """; + for (String key : java.util.List.of("/", "Post/Eingang West", "Ohne Endung", "$path & more")) { + var doc = new GridDockDocument(source); + String edited = + doc.xml.source.apply(doc.groupLabel(doc.xml.elements.getFirst(), key, "%T & T", false)); + var changed = new GridDockDocument(edited); + var col = changed.xml.elements.getFirst(); + assertEquals("%T & T", changed.groupLabels(col).get(key)); + assertTrue(edited.contains("")); + String removed = changed.xml.source.apply(changed.groupLabel(col, key, "", true)); + var restored = new GridDockDocument(removed); + assertEquals( + java.util.Map.of("Post", "Alt"), restored.groupLabels(restored.xml.elements.getFirst())); + assertTrue(removed.contains("")); + } + } + + @Test + void deletingAPairPreservesSiblingsAndReferences() throws Exception { + String source = + """ + + + + + """; + var doc = new GridDockDocument(source); + var col = doc.xml.elements.getFirst(); + assertEquals( + source.replace("", ""), + doc.xml.source.apply(doc.groupLabel(col, "/", "", true))); + assertThrows( + IllegalArgumentException.class, () -> doc.groupLabel(col, "Post/Eingang", "", true)); + } + @Test void implicitRowAttributeAndGroupingSurviveRename() throws Exception { var source = diff --git a/docs/runtime/neitzellib-baseline.json b/docs/runtime/neitzellib-baseline.json index 5e575f6..a3a334f 100644 --- a/docs/runtime/neitzellib-baseline.json +++ b/docs/runtime/neitzellib-baseline.json @@ -2,9 +2,9 @@ "schemaVersion": 1, "status": "verified-local-development-snapshot", "sourceRepository": "ssh://git@gitea.neitzel.de:2222/konrad/NeitzelLib.git", - "sourceRevision": "e4f1fd3c96f79f22da8998f5a03d05363e30b1e2", + "sourceRevision": "2625616b2fa9f4bccb2f891b2b2ae60cafeccd3d", "minimumReleasedVersion": null, - "requiredCapability": "managed-views-command-bindings-and-document-inputs", + "requiredCapability": "managed-views-command-bindings-document-inputs-and-group-label-entries", "javaVersion": "25", "javafxVersion": "27.0.1", "testResults": { @@ -21,7 +21,7 @@ "skipped": 0 }, "fx": { - "tests": 408, + "tests": 409, "failures": 0, "errors": 0, "skipped": 12 @@ -110,7 +110,7 @@ "version": "1.0.6-SNAPSHOT", "extension": "jar", "repositoryPath": "de/neitzel/lib/fx/1.0.6-SNAPSHOT/fx-1.0.6-SNAPSHOT.jar", - "sha256": "6c1b95e963073ccca21bf2214ce33b9baf2fccae506b97e8215ef0130282b192" + "sha256": "626df132f37dcdc2da28ae0a2750ddf172a824c7b41058900cb1be18c0126a9a" } ], "generatedViewModelSupport": "stored-property-access-and-declarative-service-registry", diff --git a/docs/runtime/neitzellib-baseline.md b/docs/runtime/neitzellib-baseline.md index 05cfe8a..34fcf32 100644 --- a/docs/runtime/neitzellib-baseline.md +++ b/docs/runtime/neitzellib-baseline.md @@ -1,6 +1,6 @@ # NeitzelLib development runtime -The IntelliJ Archiver preview uses `de.neitzel.lib:fx:1.0.6-SNAPSHOT` on JDK 25 and JavaFX 27.0.1. The target uses managed Views, CommandBindings and the direct `ViewLoader.loadComponent` entry point for fx:root previews. The Archiver document example uses the one-way HTML and observable suggestion-source inputs. The host uses JavaFX 26. Source revision, build timestamp, test totals and the nine installed POM/JAR checksums are in the [active manifest](neitzellib-baseline.json). +The IntelliJ Archiver preview uses `de.neitzel.lib:fx:1.0.6-SNAPSHOT` on JDK 25 and JavaFX 27.0.1. The target uses managed Views, CommandBindings and the direct `ViewLoader.loadComponent` entry point for fx:root previews. The Archiver document example uses the one-way HTML and observable suggestion-source inputs. The target also accepts literal group keys in DataGridColumn.groupLabel entries. The host uses JavaFX 26. Source revision, build timestamp, test totals and the nine installed POM/JAR checksums are in the [active manifest](neitzellib-baseline.json). ## Rebuild and verify diff --git a/docs/user-guide/authoring.md b/docs/user-guide/authoring.md index a0cdfff..7b93e5c 100644 --- a/docs/user-guide/authoring.md +++ b/docs/user-guide/authoring.md @@ -54,6 +54,8 @@ In **Form controls**, choose **Tab** from the palette and **TabPane / tabs** as Under **Bindings → DataGrid / Docking**, select the grid to edit `setupId` or `setupVersion`. Clear the field and use **Apply setting** to restore the default. Persisted settings identify the grid by its setup ID. Restoring an older definition version requires a migration for that version. +Set the column widths so that `minimumWidth ≤ width ≤ maximumWidth`. Clearing a field restores its default (80, 150 and 1200 pixels respectively). The inspector checks the remaining literal bounds when a sibling value is supplied by an FXML reference. + Select a column and set `fixedPosition` to its current zero-based index. Clear the field or enter `-1` to make it movable. Under `groupLabels`, select or enter a literal FXML map key and its display text, then use **Set group label** or **Remove group label**. For the Archiver folder example, group by `folder` and label `Post` as **Posteingang**. Collapsing that heading still stores the key `Post`. Keys represented by resource references or nested declarations can be reviewed in **Source**. ### Dock group size, splitting and persistence diff --git a/integration-tests/idea/ArchiveTargetProbe.java b/integration-tests/idea/ArchiveTargetProbe.java index 2986dd7..43919ff 100644 --- a/integration-tests/idea/ArchiveTargetProbe.java +++ b/integration-tests/idea/ArchiveTargetProbe.java @@ -1,6 +1,7 @@ package qualification; import java.nio.file.*; +import java.util.*; import java.util.concurrent.*; import javafx.application.Platform; import javafx.scene.control.*; @@ -42,10 +43,32 @@ public final class ArchiveTargetProbe { } } + static void verify( + String state, + String expected, + Map commands, + Button trash, + StringBuilder evidence) { + var active = new TreeSet(); + commands.forEach( + (name, item) -> { + if (!item.isDisable()) active.add(name); + }); + if (!trash.isDisabled()) active.add("trash"); + if (commands.size() != 21 || !active.equals(Set.of(expected.trim().split(" +")))) + throw new AssertionError(state + " expected [" + expected + "] actual " + active); + evidence.append(state).append(" · enabled ").append(active).append("\n"); + } + static boolean inspect(Path directory) throws Exception { var stage = Window.getWindows().stream() - .filter(Window::isShowing) + .filter( + w -> + w.isShowing() + && w.getOpacity() > 0 + && w instanceof javafx.stage.Stage s + && Objects.toString(s.getTitle(), "").startsWith("Neitzel preview")) .filter(w -> w.getScene().lookup("#trash-button") instanceof Button) .findFirst(); if (stage.isEmpty()) return false; @@ -73,11 +96,23 @@ public final class ArchiveTargetProbe { trash.fire(); if (!status.getText().equals("Vorschau · Bereit")) throw new AssertionError("Disabled command ran"); - if (((TreeView) root.lookup("#folders")).getRoot() == null - || root.lookup("#dockPane").lookupAll(".label").stream() - .noneMatch( - n -> n instanceof Label l && l.getText().equals("Dokument im Beispielarchiv"))) + if (root.lookup("#dockPane").lookupAll(".label").stream() + .noneMatch(n -> n instanceof Label l && l.getText().equals("Dokument im Beispielarchiv"))) return false; + var commands = new LinkedHashMap(); + for (var group : ((MenuBar) root.lookup(".menu-bar")).getMenus()) { + for (var item : group.getItems()) { + if (!(item instanceof Menu) && item.getOnAction() != null) + commands.put(item == open ? "open" : item.getId(), item); + } + } + var evidence = new StringBuilder(); + String idle = "open openReadOnly overview preferences"; + String ready = idle + " closeArchive refresh rebuild trash find slideshow"; + String write = " importFile singleFile naming pending manageMail"; + String readEntry = " showFile showPlace openFile"; + String editEntry = " tags move duplicate"; + verify("closed", idle, commands, trash, evidence); open.fire(); String afterOpen = status.getText(); if (trash.isDisabled() || !afterOpen.endsWith(" · 1")) throw new AssertionError(afterOpen); @@ -85,6 +120,57 @@ public final class ArchiveTargetProbe { String afterTrash = status.getText(); if (!afterTrash.equals("Vorschau · Beispielpapierkorb geöffnet · 2")) throw new AssertionError(afterTrash); + var dialog = + Window.getWindows().stream() + .filter(w -> w.isShowing() && w.getScene().lookup("#archive-trash") != null) + .findFirst() + .orElseThrow(); + var content = dialog.getScene().getRoot(); + var items = (TableView) content.lookup("#trash-items"); + String summary = ((Label) content.lookup("#summary")).getText(); + boolean writable = afterOpen.equals("Vorschau · Beispielarchiv geöffnet · 1"); + if (items.getItems().size() != 2 + || !summary.contains("3 Dateien") + || ((Button) content.lookup("#trash-delete")).isDisabled() == writable) + throw new AssertionError(summary); + ((Button) ((DialogPane) content).lookupButton(ButtonType.CLOSE)).fire(); + if (dialog.isShowing()) throw new AssertionError("Trash dialog did not close"); + evidence.append(summary).append("\n"); + var folders = (TreeView) root.lookup("#folders"); + var entries = (ChoiceBox) root.lookup("#example-entry"); + var phase = (ChoiceBox) root.lookup("#example-activity"); + String mode = writable ? "writable" : "read-only"; + String opened = writable ? ready + write : ready; + verify(mode, opened, commands, trash, evidence); + folders.getSelectionModel().select(0); + entries.getSelectionModel().select(0); + String selected = opened + " rules" + readEntry + (writable ? editEntry : ""); + verify(mode + ", invoice selected", selected, commands, trash, evidence); + entries.getSelectionModel().select(1); + verify("server-bound mail", selected.replace(" move", ""), commands, trash, evidence); + entries.getSelectionModel().select(0); + phase.getSelectionModel().select(1); + verify("initial scan", "slideshow" + readEntry, commands, trash, evidence); + phase.getSelectionModel().select(2); + verify("background scan", "find slideshow" + readEntry, commands, trash, evidence); + phase.getSelectionModel().select(3); + verify("busy", "find", commands, trash, evidence); + commands.get("importFile").fire(); + if (!status.getText().equals(afterTrash)) throw new AssertionError("Blocked import executed"); + phase.getSelectionModel().select(4); + verify("foreground read", selected.replace(" closeArchive", ""), commands, trash, evidence); + phase.getSelectionModel().select(0); + entries.getSelectionModel().clearSelection(); + folders.getSelectionModel().clearSelection(); + verify("selection cleared", opened, commands, trash, evidence); + commands.get("closeArchive").fire(); + verify("archive closed", idle, commands, trash, evidence); + String closedStatus = status.getText(); + trash.fire(); + if (!status.getText().equals(closedStatus) || folders.getRoot() != null) + throw new AssertionError(closedStatus); + commands.get("openReadOnly").fire(); + verify("read-only reopened", ready, commands, trash, evidence); String run = Files.readString(directory.resolve("attempt")).trim(); var image = root.snapshot(null, null); int width = (int) image.getWidth(), height = (int) image.getHeight(); @@ -108,7 +194,7 @@ public final class ArchiveTargetProbe { screenshot, "png", directory.resolve("preview-" + run + ".png").toFile()); Files.writeString( directory.resolve("result-" + run), - afterOpen + "\n" + afterTrash + "\n" + ProcessHandle.current().pid()); + afterOpen + "\n" + afterTrash + "\n" + evidence + ProcessHandle.current().pid()); return true; } } diff --git a/integration-tests/idea/DocumentTabsTargetProbe.java b/integration-tests/idea/DocumentTabsTargetProbe.java index 1d0e295..74e42d8 100644 --- a/integration-tests/idea/DocumentTabsTargetProbe.java +++ b/integration-tests/idea/DocumentTabsTargetProbe.java @@ -22,7 +22,7 @@ public final class DocumentTabsTargetProbe { Thread.ofPlatform().daemon().start(() -> Probe.run(Path.of(dir))); } - private static final class Probe { + static final class Probe { private static T fx(Callable task) throws Exception { var future = new FutureTask<>(task); Platform.runLater(future); @@ -80,7 +80,8 @@ public final class DocumentTabsTargetProbe { } else { result = checkDetails(dir, root, id); } - Files.writeString(dir.resolve("result-" + id), result); + var completed = Files.writeString(dir.resolve("result-" + id + ".tmp"), result); + Files.move(completed, dir.resolve("result-" + id), StandardCopyOption.ATOMIC_MOVE); } catch (Throwable error) { var trace = new java.io.StringWriter(); error.printStackTrace(new java.io.PrintWriter(trace)); @@ -180,7 +181,7 @@ public final class DocumentTabsTargetProbe { popup(input, "Beleg geprüft", dir.resolve("rechnung-tab-tags.png")); } - private static Node select(TabPane group, String name) throws Exception { + static Node select(TabPane group, String name) throws Exception { var tab = fx( () -> { @@ -198,7 +199,7 @@ public final class DocumentTabsTargetProbe { return fx(tab::getContent); } - private static void checkHtml(Node root, String heading, String text) throws Exception { + static void checkHtml(Node root, String heading, String text) throws Exception { await( heading, () -> { @@ -242,13 +243,13 @@ public final class DocumentTabsTargetProbe { return named; } - private static void requireChips(Node root, String... expected) throws Exception { + static void requireChips(Node root, String... expected) throws Exception { var actual = chips(root).keySet(); if (!actual.equals(Set.of(expected))) throw new AssertionError("Assigned tags " + actual + " vs " + Arrays.toString(expected)); } - private static Button removeButton(Node root, String text) throws Exception { + static Button removeButton(Node root, String text) throws Exception { return (Button) Objects.requireNonNull(chips(root).get(text), text).lookup(".tag-chip-remove"); } @@ -260,29 +261,25 @@ public final class DocumentTabsTargetProbe { long activateAfter = 0; while (System.nanoTime() < deadline) { if (System.nanoTime() >= activateAfter - && !fx(field::isFocused) + && !fx(() -> field.isFocused() && field.getScene().getWindow().isFocused()) && System.getProperty("os.name").startsWith("Mac")) { - String activate = - "ObjC.import('AppKit');" - + " $.NSRunningApplication.runningApplicationWithProcessIdentifier(" - + ProcessHandle.current().pid() - + ").activateWithOptions(2)"; - new ProcessBuilder("/usr/bin/osascript", "-l", "JavaScript", "-e", activate) - .redirectErrorStream(true) - .start() - .waitFor(5, TimeUnit.SECONDS); + var desktop = java.awt.Desktop.getDesktop(); + if (desktop.isSupported(java.awt.Desktop.Action.APP_REQUEST_FOREGROUND)) { + // Request activation from the preview process itself, which owns the FX stage. + desktop.requestForeground(true); + } activateAfter = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); } boolean matched = fx( () -> { var stage = (Stage) field.getScene().getWindow(); - if (!field.isFocused()) { + if (!stage.isFocused() || !field.isFocused()) { stage.toFront(); stage.requestFocus(); field.requestFocus(); } - if (!field.isFocused()) return false; + if (!stage.isFocused() || !field.isFocused()) return false; if (!suggestions(field).contains(suggestion)) throw new AssertionError( "Missing " + suggestion + " in catalogue " + suggestions(field)); @@ -315,6 +312,10 @@ public final class DocumentTabsTargetProbe { + field.isFocused() + ", stage focused=" + field.getScene().getWindow().isFocused() + + ", focus owner=" + + field.getScene().getFocusOwner() + + ", field bounds=" + + field.localToScreen(field.getBoundsInLocal()) + ", catalogue=" + suggestions(field) + ", windows=" diff --git a/integration-tests/idea/DocumentTabsWorkflowProbe.java b/integration-tests/idea/DocumentTabsWorkflowProbe.java index 8ced1cd..1c1fa66 100644 --- a/integration-tests/idea/DocumentTabsWorkflowProbe.java +++ b/integration-tests/idea/DocumentTabsWorkflowProbe.java @@ -7,6 +7,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.LocalFileSystem; import de.neitzel.fxdesigner.workflow.DesignerWorkflow.Example; import java.nio.file.*; +import java.util.List; import java.util.concurrent.TimeUnit; import javafx.embed.swing.SwingFXUtils; import javafx.scene.control.*; @@ -24,17 +25,24 @@ public final class DocumentTabsWorkflowProbe extends FormWorkflowProbe { "AutoCompleteTextField #input", "promptText", "Belegtag wählen"); - build(4); - for (String id : - new String[] {"details-invoice", "details-delivery", "details-readonly", "details-busy"}) - preview(id); + qualify("details-invoice", "details-delivery", "details-readonly", "details-busy"); open(project, "HtmlDocument"); - build(2); - preview("html-invoice"); - preview("html-delivery"); + qualify("html-invoice", "html-delivery"); open(project, "ArchiveWindow"); - build(2); - preview("archive-window-documents"); + qualify("archive-window-documents"); + var ids = fx(this::available); + if (!ids.contains("archive-window-media")) + throw new AssertionError("Missing media example: " + ids); + try { + awaitExamples(List.of("missing-required-example")); + throw new AssertionError("Missing descriptor was accepted"); + } catch (IllegalStateException expected) { + String diagnostic = expected.getMessage(); + if (!diagnostic.contains( + "ArchiveWindow.fxml · required [missing-required-example] · available " + ids)) + throw expected; + step(diagnostic); + } Files.writeString(output.resolve("SUCCESS.txt"), Files.readString(output.resolve("steps.txt"))); } @@ -65,32 +73,84 @@ public final class DocumentTabsWorkflowProbe extends FormWorkflowProbe { step("Saved and reopened " + control + "." + property + " = " + value); } - private void build(int examples) throws Exception { + private List available() { + return ((ComboBox) pane.lookup("#preview-example")) + .getItems().stream().map(Example.class::cast).map(Example::id).toList(); + } + + private String state() { + return ((Label) pane.lookup("#preview-state")).getText(); + } + + private boolean failed() { + String state = state(); + return state.startsWith("Preview failed") + || state.startsWith("Preview blocked") + || state.startsWith("Preview unavailable") + || state.contains("correct the build"); + } + + private String diagnostic(List required) { + return file.getName() + + " · required " + + required + + " · available " + + available() + + " · " + + state(); + } + + private void awaitExamples(List required) throws Exception { + try { + // Discovery publishes the complete list at once. Additional providers may extend it. + await( + () -> + fx( + () -> + failed() + || state().contains("register an example") + || !state().startsWith("Building") && !available().isEmpty())); + } catch (AssertionError timeout) { + throw new AssertionError(fx(() -> diagnostic(required)), timeout); + } + if (!fx(() -> !failed() && available().containsAll(required))) + throw new IllegalStateException(fx(() -> diagnostic(required))); + } + + private void qualify(String... examples) throws Exception { + var required = List.of(examples); click(pane, "Form preview"); click(pane, "Build and Refresh"); - await( - () -> - fx( - () -> - ((ComboBox) pane.lookup("#preview-example")).getItems().size() == examples)); + awaitExamples(required); + step(file.getName() + " · available " + fx(this::available)); + for (String id : required) preview(id); } private void preview(String id) throws Exception { - choose("preview-example", id); String label = - fx(() -> ((Example) ((ComboBox) pane.lookup("#preview-example")).getValue()).label()); - await( - () -> - fx( - () -> { - String state = ((Label) pane.lookup("#preview-state")).getText(); - if (state.startsWith("Preview failed") - || state.startsWith("Preview blocked") - || state.startsWith("Preview unavailable")) - throw new AssertionError(id + ": " + state); - return ((ImageView) pane.lookup("#full-preview-image")).getImage() != null - && state.contains(label); - })); + fx( + () -> { + var choices = (ComboBox) pane.lookup("#preview-example"); + var selected = + choices.getItems().stream() + .filter(example -> example.id().equals(id)) + .findFirst() + .orElseThrow(() -> new IllegalStateException(diagnostic(List.of(id)))); + choices.getSelectionModel().select(selected); + return selected.label(); + }); + try { + await( + () -> + fx( + () -> + failed() + || ((ImageView) pane.lookup("#full-preview-image")).getImage() != null + && state().contains(label))); + } catch (AssertionError timeout) { + throw new AssertionError(fx(() -> diagnostic(List.of(id))), timeout); + } + if (fx(this::failed)) throw new AssertionError(fx(() -> diagnostic(List.of(id)))); fx( () -> { var frame = ((ImageView) pane.lookup("#full-preview-image")).getImage(); diff --git a/integration-tests/idea/FolderActionsTargetProbe.java b/integration-tests/idea/FolderActionsTargetProbe.java index f2d8865..f89247d 100644 --- a/integration-tests/idea/FolderActionsTargetProbe.java +++ b/integration-tests/idea/FolderActionsTargetProbe.java @@ -19,14 +19,14 @@ public final class FolderActionsTargetProbe { Thread.ofPlatform().daemon().start(() -> Worker.run(Path.of(dir))); } - private static final class Worker { - private static T fx(Callable action) throws Exception { + static final class Worker { + static T fx(Callable action) throws Exception { var task = new FutureTask<>(action); Platform.runLater(task); return task.get(10, TimeUnit.SECONDS); } - private static void await(String description, Callable test) throws Exception { + static void await(String description, Callable test) throws Exception { long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(22); while (System.nanoTime() < end) { if (fx(test)) return; @@ -35,34 +35,38 @@ public final class FolderActionsTargetProbe { throw new AssertionError(description); } - private static void require(boolean value, String message) { + static void require(boolean value, String message) { if (!value) throw new AssertionError(message); } + static Stage previewStage() throws Exception { + Stage stage = null; + while (stage == null) { + Thread.sleep(120); + try { + stage = + fx( + () -> + Window.getWindows().stream() + .filter( + w -> + w instanceof Stage s + && s.isShowing() + && s.getOpacity() > 0 + && s.getTitle() != null + && s.getTitle().startsWith("Neitzel preview")) + .map(Stage.class::cast) + .findFirst() + .orElse(null)); + } catch (IllegalStateException starting) { + } + } + return stage; + } + private static void run(Path dir) { try { - Stage stage = null; - while (stage == null) { - Thread.sleep(120); - try { - stage = - fx( - () -> - Window.getWindows().stream() - .filter( - w -> - w instanceof Stage s - && s.isShowing() - && s.getOpacity() > 0 - && s.getTitle() != null - && s.getTitle().startsWith("Neitzel preview")) - .map(Stage.class::cast) - .findFirst() - .orElse(null)); - } catch (IllegalStateException starting) { - } - } - Stage shown = stage; + Stage shown = previewStage(); var root = fx( () -> { @@ -106,19 +110,19 @@ public final class FolderActionsTargetProbe { } } - private static List rows(Node grid) throws Exception { + static List rows(Node grid) throws Exception { return (List) grid.getClass().getMethod("getItems").invoke(grid); } - private static String attr(Object row, String name) throws Exception { + static String attr(Object row, String name) throws Exception { return (String) row.getClass().getMethod(name).invoke(row); } - private static void select(Node grid, List keys) throws Exception { + static void select(Node grid, List keys) throws Exception { grid.getClass().getMethod("selectKeys", Collection.class).invoke(grid, keys); } - private static MenuItem move(Node grid, String file) { + static MenuItem move(Node grid, String file) { Node anchor = grid.lookupAll(".label").stream() .filter(n -> n instanceof Label l && l.getText().equals(file)) @@ -140,7 +144,7 @@ public final class FolderActionsTargetProbe { .orElseThrow(); } - private static boolean visible(Node grid, String column) throws Exception { + static boolean visible(Node grid, String column) throws Exception { return (boolean) grid.getClass().getMethod("isColumnVisible", String.class).invoke(grid, column); } @@ -283,7 +287,7 @@ public final class FolderActionsTargetProbe { + " Dateityp; Kurzansicht restored hidden Dateityp."); } - private static void image(Node node, Path path) throws Exception { + static void image(Node node, Path path) throws Exception { var img = node.snapshot(null, null); int w = (int) img.getWidth(), h = (int) img.getHeight(); var out = new java.awt.image.BufferedImage(w, h, java.awt.image.BufferedImage.TYPE_INT_ARGB); diff --git a/integration-tests/idea/FolderProfilesTargetProbe.java b/integration-tests/idea/FolderProfilesTargetProbe.java new file mode 100644 index 0000000..78ff3fc --- /dev/null +++ b/integration-tests/idea/FolderProfilesTargetProbe.java @@ -0,0 +1,328 @@ +package qualification; + +import static qualification.FolderActionsTargetProbe.Worker.*; + +import java.nio.file.*; +import java.time.*; +import java.time.format.*; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicInteger; +import javafx.application.Platform; +import javafx.collections.ListChangeListener; +import javafx.scene.*; +import javafx.scene.control.*; +import javafx.stage.Window; + +/** Checks rendered folder rows and the ordinary modal profile dialogs in the preview worker. */ +public final class FolderProfilesTargetProbe { + public static void premain(String directory) { + if (System.getProperty("sun.java.command", "") + .startsWith("de.neitzel.fxdesigner.target.WorkerMain ")) + Thread.ofPlatform().daemon().start(() -> Checks.run(Path.of(directory))); + } + + private static final class Checks { + private static void run(Path dir) { + try { + var stage = previewStage(); + var root = + fx( + () -> { + stage.setWidth(1360); + stage.setHeight(700); + var r = stage.getScene().getRoot(); + r.applyCss(); + r.layout(); + return r; + }); + var attempt = Files.readString(dir.resolve("layout-case")); + var result = + switch (attempt) { + case "profiles", "readonly", "rebound" -> profiles(root, attempt); + case "metadata", "renamed", "recovered" -> metadata(root, attempt, dir); + default -> throw new AssertionError(attempt); + }; + Files.writeString(dir.resolve("result-" + attempt), result); + } catch (Throwable failure) { + var trace = new java.io.StringWriter(); + failure.printStackTrace(new java.io.PrintWriter(trace)); + try { + Files.writeString(dir.resolve("target-error.txt"), trace.toString()); + } catch (Exception error) { + error.printStackTrace(); + } + } + } + + private static DialogPane dialog(String title) { + return Window.getWindows().stream() + .filter(javafx.stage.Stage.class::isInstance) + .map(javafx.stage.Stage.class::cast) + .filter(s -> s.isShowing() && title.equals(s.getTitle())) + .map(s -> (DialogPane) s.getScene().getRoot()) + .findFirst() + .orElse(null); + } + + private static Button change(DialogPane d) { + return (Button) + d.lookupButton( + d.getButtonTypes().stream() + .filter(t -> t.getButtonData() == ButtonBar.ButtonData.OTHER) + .findFirst() + .orElseThrow()); + } + + private static void toggle(Node grid, String header) { + var menu = (MenuButton) grid.lookup(".data-grid-column-menu"); + menu.show(); + var item = + (CheckMenuItem) + menu.getItems().stream() + .filter(i -> header.equals(i.getText())) + .findFirst() + .orElseThrow(); + item.setSelected(!item.isSelected()); + item.fire(); + menu.hide(); + } + + private static String profiles(Parent root, String attempt) throws Exception { + var grid = fx(() -> root.lookup("#grid")); + var profiles = fx(() -> (ComboBox) root.lookup("#folder-view-profile")); + var save = fx(() -> (Button) root.lookup("#save-folder-view-profile")); + var clear = fx(() -> (Button) root.lookup("#clear-folder-view-layout")); + var manage = fx(() -> (Button) root.lookup("#manage-folder-view-profiles")); + boolean readonly = attempt.equals("readonly"), rebound = attempt.equals("rebound"); + await( + "Initial profile", + () -> !manage.isDisabled() && profiles.isDisabled() == readonly && clear.isDisabled()); + String name = readonly ? "Metadaten" : "Prüfprofil"; + fx( + () -> { + require( + !profiles.getItems().contains("Prüfprofil"), + "New session inherited previous profile"); + if (!readonly) profiles.getEditor().setText(name); + require(readonly == save.isDisabled(), "Save availability"); + if (!readonly && !rebound) { + save.fire(); + require(profiles.getItems().contains(name), "Profile not saved"); + } + toggle(grid, "Dateityp"); + return null; + }); + await("Changed local layout", () -> !clear.isDisabled() && !visible(grid, "type")); + fx( + () -> { + clear.fire(); + return null; + }); + await("Restored local layout", () -> clear.isDisabled() && visible(grid, "type")); + var openings = new AtomicInteger(); + String title = "Anzeigeprofile verwalten"; + ListChangeListener shown = + changes -> { + while (changes.next()) + for (Window w : changes.getAddedSubList()) + if (w instanceof javafx.stage.Stage s && title.equals(s.getTitle())) + openings.incrementAndGet(); + }; + fx( + () -> { + Window.getWindows().addListener(shown); + Platform.runLater((rebound ? save : manage)::fire); + return null; + }); + await("Profile manager opened", () -> dialog(title) != null); + fx( + () -> { + var d = dialog(title); + var list = (ListView) d.lookup("#archive-display-profiles"); + if (rebound) require(!list.getItems().contains(name), "Old save handler also ran"); + else { + list.getSelectionModel().select(name); + var action = change(d); + require(action.isDisabled() == readonly, "Profile deletion availability"); + if (!readonly) Platform.runLater(action::fire); + } + return null; + }); + if (!readonly && !rebound) { + Callable confirm = + () -> + Window.getWindows().stream() + .filter(Window::isShowing) + .map(w -> w.getScene().getRoot()) + .filter(DialogPane.class::isInstance) + .map(DialogPane.class::cast) + .filter(d -> d.getButtonTypes().contains(ButtonType.OK)) + .findFirst() + .orElse(null); + await("Delete confirmation", () -> confirm.call() != null); + fx( + () -> { + ((Button) confirm.call().lookupButton(ButtonType.OK)).fire(); + return null; + }); + await("Deleted own profile", () -> !profiles.getItems().contains(name)); + } + fx( + () -> { + ((Button) dialog(title).lookupButton(ButtonType.CLOSE)).fire(); + return null; + }); + fx( + () -> { + Window.getWindows().removeListener(shown); + require( + openings.get() == 1 && dialog(title) == null, + "Expected exactly one profile dialog: " + openings); + return null; + }); + if (rebound) + return "Fresh session. Rebound Save opened exactly one management dialog, without saving a" + + " profile."; + if (readonly) + return "Read-only: archive save, selection and deletion disabled. Management and local" + + " layout change/reset succeeded."; + return "Saved Prüfprofil, hid and restored Dateityp, deleted own profile after confirmation."; + } + + private static Label cell(Node grid, String text) { + return grid.lookupAll(".label").stream() + .filter(Label.class::isInstance) + .map(Label.class::cast) + .filter(l -> text.equals(l.getText())) + .findFirst() + .orElseThrow(() -> new AssertionError(text)); + } + + private static List