Merge visual form editing, docking rules and Archiver preview qualification

This commit is contained in:
2026-11-25 10:21:57 +01:00
32 changed files with 3657 additions and 215 deletions
+11 -1
View File
@@ -81,13 +81,23 @@ Add `--connection-form` to open or qualify `ConnectionForm.fxml`. After **Build
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.
Use **TabPane / tabs** for a Tab, **SplitPane / items** for an ordered child, or select the named content slot on a Tab, ScrollPane or BorderPane. Add `--media-layout-grid` to the Archiver host check to exercise these destinations, the document media button and the folder grid. [Form and grid editing](docs/user-guide/authoring.md)
In `ArchiveWindow.fxml`, select a named DockGroupDefinition to edit minimum dimensions, allowed split directions and persistence. The Archiver host check accepts `--dock-rules` to exercise the document tab context menus at two window sizes and compare the destinations after closing the last tab. [Dock group settings and example](docs/user-guide/authoring.md#dock-group-size-splitting-and-persistence)
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.
Use `--import-form` with `scripts/check-ide-host.py --archiver ../Archiver` and the same JDK and IDEA options to verify seven generic binding targets. The check saves and reopens bindings on the folder grid and import selector, then exercises the free, conflicting and busy import examples in the registered editor.
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 `--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.
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.
@@ -22,7 +22,51 @@ public record BindingMetadata(
List<RepeatOption> tableRows,
List<RepeatOption> tableColumns,
List<String> commandPaths,
List<String> commandTargets) {
List<String> commandTargets,
Optional<List<String>> actionEventHandlers) {
public BindingMetadata(
String model,
String path,
String direction,
List<Attribute> attributes,
List<Target> targets,
List<String> diagnostics,
List<Converter> converters,
List<Problem> problems,
String controller,
String viewModel,
List<Computed> computed,
List<RepeatOption> collections,
List<RepeatOption> components,
List<RepeatOption> panes,
List<RepeatOption> tableCollections,
List<RepeatOption> tableRows,
List<RepeatOption> tableColumns,
List<String> commandPaths,
List<String> commandTargets) {
this(
model,
path,
direction,
attributes,
targets,
diagnostics,
converters,
problems,
controller,
viewModel,
computed,
collections,
components,
panes,
tableCollections,
tableRows,
tableColumns,
commandPaths,
commandTargets,
Optional.empty());
}
public BindingMetadata(
String model,
String path,
@@ -204,6 +248,7 @@ public record BindingMetadata(
tableColumns = List.copyOf(tableColumns);
commandPaths = List.copyOf(commandPaths);
commandTargets = List.copyOf(commandTargets);
actionEventHandlers = actionEventHandlers.map(List::copyOf);
if (!Set.of("view", "model", "both").contains(direction))
throw new IllegalArgumentException("Invalid direction");
}
@@ -211,6 +256,7 @@ public record BindingMetadata(
public Map<String, String> encode() {
var m = new TreeMap<String, String>();
m.put("format", "5");
actionEventHandlers.ifPresent(names -> encodeStrings(m, "actionEvents", names));
encodeStrings(m, "commands", commandPaths);
encodeStrings(m, "commandTargets", commandTargets);
encodeOptions(m, "rc", collections);
@@ -393,6 +439,9 @@ public record BindingMetadata(
decodeOptions(m, "tr"),
decodeOptions(m, "ta"),
commands ? decodeStrings(m, "commands") : List.of(),
commands ? decodeStrings(m, "commandTargets") : List.of());
commands ? decodeStrings(m, "commandTargets") : List.of(),
m.containsKey("actionEvents")
? Optional.of(decodeStrings(m, "actionEvents"))
: Optional.empty());
}
}
@@ -876,6 +876,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
validatingSource = null;
validationPreview = false;
bindingWorkflow.cancel();
formEditor.eventHandlers(Optional.empty());
bindingBrowser.invalidate(message);
repeatEditor.invalidateDiscovery();
commandEditor.invalidateDiscovery();
@@ -1163,6 +1164,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
}
validatedSource = captured.text();
bindingProblems = metadata.problems();
formEditor.eventHandlers(metadata.actionEventHandlers());
publishDiagnostics(
last
? "Explicit retained build (outdated)"
@@ -1243,6 +1245,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
}
validatedSource = captured.text();
bindingProblems = metadata.problems();
formEditor.eventHandlers(metadata.actionEventHandlers());
publishDiagnostics(
last
? "Explicit retained build (outdated)"
@@ -14,9 +14,11 @@ final class FormDocument {
static {
register(
"javafx.scene.control",
"Label TextField TextArea PasswordField Button CheckBox ComboBox ToolBar");
"Label TextField TextArea PasswordField Button CheckBox ComboBox ToolBar Tab TabPane"
+ " ScrollPane SplitPane");
register(
"javafx.scene.layout", "GridPane VBox HBox StackPane AnchorPane FlowPane TilePane Pane");
"javafx.scene.layout",
"GridPane VBox HBox StackPane AnchorPane FlowPane TilePane Pane BorderPane");
register(
"de.neitzel.fx.control",
"StatusBar ToolBarPane AutoCompleteTextField TagChip NonNegativeIntegerSpinner HtmlViewer");
@@ -107,7 +109,10 @@ final class FormDocument {
return switch (type) {
case "GridPane", "HBox", "VBox", "StackPane", "Pane", "AnchorPane", "FlowPane", "TilePane" ->
List.of("children");
case "ToolBarPane", "ToolBar" -> List.of("items");
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 "StatusBar" -> List.of("leftItems", "rightItems");
default -> List.of();
};
@@ -174,13 +179,57 @@ final class FormDocument {
private List<Element> 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();
if (list == null
&& (slot.owner().type().equals("StatusBar") || slot.owner().type().equals("BorderPane")))
return List.of();
return children(list == null ? host : list).stream().filter(FormDocument::instance).toList();
}
private static boolean instance(Element child) {
if (BindingDocument.FX.equals(child.getNamespaceURI()))
return Set.of("include", "reference", "copy").contains(child.getLocalName());
return Character.isUpperCase(simple(child.getTagName()).charAt(0));
}
private static boolean single(Slot slot) {
return slot.property().equals("content") || slot.owner().type().equals("BorderPane");
}
String destinationInfo(Slot slot) {
if (slot == null || !single(slot)) return "";
var host = owner(slot);
if (host.hasAttribute(slot.property())) return "Single place · supplied by an FXML attribute.";
var children = members(slot);
if (!children.isEmpty()) {
var child = children.getFirst();
boolean movable = items.stream().anyMatch(item -> element(item) == child);
return "Single place · occupied by "
+ child.getTagName()
+ (movable
? ". Move that child to a free destination first."
: ". Choose another destination or edit this place in Source.");
}
var wrapper = property(host, slot.property());
if (wrapper != null && (!children(wrapper).isEmpty() || !wrapper.getTextContent().isBlank()))
return "Single place · supplied by FXML content. Review this place in Source.";
return "Single place · empty";
}
private void accept(String type, Slot slot, Element moving) {
if (type.equals("Tab") != slot.property().equals("tabs"))
throw new IllegalArgumentException(
slot.property().equals("tabs")
? "TabPane.tabs accepts Tab only."
: "A Tab belongs in TabPane.tabs. This destination accepts Nodes.");
if (owner(slot).hasAttribute(slot.property()))
throw new IllegalArgumentException("This destination is supplied by an FXML attribute.");
var wrapper = property(owner(slot), slot.property());
if (single(slot)
&& (members(slot).stream().anyMatch(e -> e != moving)
|| wrapper != null
&& members(slot).isEmpty()
&& (!wrapper.getTextContent().isBlank() || !children(wrapper).isEmpty())))
throw new IllegalArgumentException("Occupied: " + slot + ". " + destinationInfo(slot));
}
int size(Slot slot) {
@@ -198,7 +247,8 @@ final class FormDocument {
}
var container = property(owner, slot.property());
if (container != null) return xml.append(container, snippet, "");
if (slot.owner().type().equals("StatusBar")
if ((single(slot) && members.isEmpty())
|| slot.owner().type().equals("StatusBar")
|| (slot.owner().type().equals("ToolBarPane") && members.isEmpty()))
snippet = "<" + slot.property() + ">" + snippet + "</" + slot.property() + ">";
return xml.append(owner, snippet, "");
@@ -234,6 +284,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.");
accept(type, slot, null);
String id = fresh(type), prefix = fxPrefix(host), qualified = TYPES.get(type);
var edits = new ArrayList<Replacement>();
String tagName = type;
@@ -245,7 +296,10 @@ final class FormDocument {
}
}
String extra =
type.equals("Label") || type.equals("Button") || type.equals("TagChip")
type.equals("Label")
|| type.equals("Button")
|| type.equals("TagChip")
|| type.equals("Tab")
? " text=\"" + type + "\""
: "";
if (slot.owner().type().equals("GridPane")) {
@@ -292,6 +346,7 @@ final class FormDocument {
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.");
accept(item.type(), slot, source);
var current = members(slot);
int old = current.indexOf(source);
if (old >= 0 && (at == old || at == old + 1)) return edit(List.of(), item.id());
@@ -316,6 +371,20 @@ final class FormDocument {
List<Field> fields(Item item) {
var e = element(item);
var fields = new LinkedHashMap<String, Field>();
if (item.type().equals("Tab")) {
field(fields, "text", "String", "");
field(fields, "closable", "Boolean", "true");
field(fields, "disable", "Boolean", "false");
field(fields, "style", "CSS", "");
field(fields, "styleClass", "CSS classes", "tab");
return withSourceFields(e, fields);
}
field(fields, "accessibleText", "String", "");
if (Set.of("TextField", "PasswordField", "AutoCompleteTextField").contains(item.type()))
field(fields, "prefColumnCount", "Integer", "12");
if (Set.of(
"TextField", "PasswordField", "AutoCompleteTextField", "Button", "CheckBox", "ComboBox")
.contains(item.type())) field(fields, "onAction", "Event handler", "");
field(fields, "styleClass", "CSS classes", "control default");
field(fields, "padding", "Insets", item.type().equals("StatusBar") ? "4 8 4 8" : "0");
field(fields, "style", "CSS", "");
@@ -388,6 +457,10 @@ final class FormDocument {
}
for (String name : List.of("width", "height"))
fields.put(name, new Field(name, "Number", "layout", false));
return withSourceFields(e, fields);
}
private static List<Field> withSourceFields(Element e, Map<String, Field> fields) {
for (int i = 0; i < e.getAttributes().getLength(); i++) {
var a = e.getAttributes().item(i);
if (a.getNamespaceURI() == null)
@@ -10,9 +10,12 @@ import javafx.scene.layout.*;
final class FormEditor extends VBox {
private final ComboBox<String> palette = combo("form-palette");
private final ComboBox<FormDocument.Slot> destination = combo("form-destination");
private final Label destinationInfo = new Label();
private final Spinner<Integer> position = new Spinner<>(0, 0, 0);
private final ComboBox<FormDocument.Item> selected = combo("form-control");
private final ComboBox<FormDocument.Field> field = combo("form-property");
private final ComboBox<String> handlers = combo("form-event-handlers");
private Optional<List<String>> verifiedHandlers = Optional.empty();
private final TextArea value = new TextArea();
private final Label details = new Label(), message = new Label();
private final Consumer<FormDocument.Edit> submit;
@@ -30,6 +33,13 @@ final class FormEditor extends VBox {
palette.setValue("Label");
position.setId("form-position");
position.setPrefWidth(74);
handlers.setPromptText("Choose controller method");
handlers.managedProperty().bind(handlers.visibleProperty());
handlers.setVisible(false);
handlers.setOnAction(
e -> {
if (handlers.getValue() != null) value.setText(handlers.getValue());
});
value.setId("form-value");
value.setPrefRowCount(2);
details.setId("form-field-type");
@@ -66,6 +76,7 @@ final class FormEditor extends VBox {
palette.getValue(),
destination.getValue(),
position.getValue())))),
destinationInfo,
row(
new Label("Selected control"),
selected,
@@ -79,18 +90,25 @@ final class FormEditor extends VBox {
destination.getValue(),
position.getValue())))),
row(new Label("Property"), field, details),
handlers,
value,
row(
button(
"Set property",
() ->
perform(
() ->
form.set(
selected.getValue(),
field.getValue(),
value.getText(),
false))),
() -> {
if (eventSelected()
&& verifiedHandlers.isPresent()
&& !verifiedHandlers.get().contains(value.getText()))
throw new IllegalArgumentException(
"No accessible controller method "
+ value.getText()
+ " for ActionEvent. Choose a listed method with no"
+ " argument or a compatible event argument.");
return form.set(
selected.getValue(), field.getValue(), value.getText(), false);
})),
button(
"Reset property",
() -> perform(() -> form.set(selected.getValue(), field.getValue(), "", true))),
@@ -155,6 +173,10 @@ final class FormEditor extends VBox {
private void setPosition() {
var slot = destination.getValue();
String hint = form == null ? "" : form.destinationInfo(slot);
destinationInfo.setText(hint);
destinationInfo.setVisible(!hint.isEmpty());
destinationInfo.setManaged(!hint.isEmpty());
int size = form == null || slot == null ? 0 : form.size(slot);
position.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, size, size));
}
@@ -168,7 +190,27 @@ final class FormEditor extends VBox {
showValue();
}
void eventHandlers(Optional<List<String>> names) {
verifiedHandlers = names;
handlers.getItems().setAll(names.orElse(List.of()));
handlers.setDisable(names.isEmpty());
if (eventSelected()) showHandlerStatus();
}
private boolean eventSelected() {
return field.getValue() != null && field.getValue().type().equals("Event handler");
}
private void showHandlerStatus() {
details.setText(
verifiedHandlers.isEmpty()
? "ActionEvent · Build and Refresh to check controller methods"
: "ActionEvent · methods from the compiled controller");
}
private void showValue() {
handlers.setVisible(eventSelected());
handlers.getSelectionModel().clearSelection();
var f = field.getValue();
var item = selected.getValue();
if (form == null || item == null || f == null) {
@@ -184,6 +226,7 @@ final class FormEditor extends VBox {
+ (f.type().equals("ObservableList<String>")
? "bind to a model list"
: f.editable() ? "editable" : "read only"));
if (eventSelected()) showHandlerStatus();
value.setEditable(f.editable());
value.setText(form.value(item, f));
}
@@ -13,6 +13,8 @@ final class GridDockDocument {
"DataGrid",
List.of(
"keyAttribute",
"setupId",
"setupVersion",
"pageSize",
"maximumPageSize",
"selectionMode",
@@ -33,7 +35,9 @@ final class GridDockDocument {
"maximumWidth",
"filterable",
"checklist",
"groupAttribute"),
"groupAttribute",
"fixedPosition",
"groupLabels"),
"DockGroupDefinition",
List.of(
"destinationId",
@@ -43,7 +47,11 @@ final class GridDockDocument {
"releaseSpaceWhenEmpty",
"collapsible",
"preferredWidth",
"preferredHeight"),
"preferredHeight",
"minimumWidth",
"minimumHeight",
"persistent",
"splitDirections"),
"DockSplitDefinition", List.of("destinationId", "orientation", "position"));
static List<String> options(String field) {
@@ -52,6 +60,7 @@ final class GridDockDocument {
"groupingEnabled",
"groupsCollapsed",
"visibleWhenEmpty",
"persistent",
"releaseSpaceWhenEmpty",
"collapsible" ->
List.of("true", "false");
@@ -59,6 +68,7 @@ final class GridDockDocument {
case "selectionMode" -> List.of("NONE", "SINGLE", "MULTIPLE");
case "tabSide" -> List.of("TOP", "RIGHT", "BOTTOM", "LEFT");
case "mode" -> List.of("DOCKED", "OVERLAY");
case "splitDirections" -> List.of("ALL", "NONE", "HORIZONTAL", "VERTICAL");
case "orientation" -> List.of("HORIZONTAL", "VERTICAL");
case "kind" -> List.of("TEXT", "INTEGER", "DECIMAL", "BOOLEAN");
default -> List.of();
@@ -177,9 +187,54 @@ final class GridDockDocument {
return id;
}
Map<String, String> groupLabels(Element column) {
var names = new TreeMap<String, String>();
var map = property(column, "groupLabels");
if (map != null)
for (int i = 0; i < map.getAttributes().getLength(); i++) {
var attr = map.getAttributes().item(i);
if (attr.getNamespaceURI() == null
&& literalKey(attr.getNodeName())
&& !reference(attr.getNodeValue()))
names.put(attr.getNodeName(), attr.getNodeValue().replaceFirst("^\\\\", ""));
}
return names;
}
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}_-]*")
&& !key.equals("xmlns")
&& !key.startsWith("on");
}
private static boolean reference(String text) {
return !text.isEmpty() && "%@$".indexOf(text.charAt(0)) >= 0;
}
List<Replacement> 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 (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))))
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;
if (map == null)
return List.of(
xml.append(
column, "<groupLabels " + key + "=\"" + XmlSource.escape(encoded, '"') + "\"/>", ""));
return xml.source.attributes(
xml.elements.indexOf(map), Collections.singletonMap(key, remove ? null : encoded));
}
List<Replacement> set(Element e, String field, String value) {
if (!SETTINGS.getOrDefault(type(e), List.of()).contains(field)
|| Set.of("items", "source").contains(field))
|| Set.of("items", "source", "groupLabels").contains(field))
throw new IllegalArgumentException("Use a model binding for the data input.");
if (property(e, field) != null)
throw new IllegalArgumentException(
@@ -197,19 +252,36 @@ final class GridDockDocument {
&& Set.of(
"width",
"minimumWidth",
"minimumHeight",
"maximumWidth",
"preferredWidth",
"preferredHeight",
"position")
.contains(field)) {
double n = Double.parseDouble(value);
if (!Double.isFinite(n) || n <= 0 || field.equals("position") && n >= 1)
boolean groupMinimum =
type(e).equals("DockGroupDefinition")
&& (field.equals("minimumWidth") || field.equals("minimumHeight"));
if (groupMinimum) {
if (!Double.isFinite(n) || n < 0)
throw new IllegalArgumentException("Enter a finite group minimum of 0 or more pixels.");
} else if (!Double.isFinite(n) || n <= 0 || field.equals("position") && n >= 1) {
throw new IllegalArgumentException("Invalid " + field);
}
}
if (!value.isEmpty()
&& Set.of("pageSize", "maximumPageSize").contains(field)
&& Integer.parseInt(value) < 1)
throw new IllegalArgumentException("Positive page size required");
if (field.equals("setupVersion") && !value.isEmpty() && Integer.parseInt(value) < 1)
throw new IllegalArgumentException("Setup version must be a positive integer.");
if (field.equals("fixedPosition") && !value.isEmpty()) {
int index = branches(parentOfType(e, "DataGrid")).indexOf(e);
int fixed = Integer.parseInt(value);
if (fixed != -1 && fixed != index)
throw new IllegalArgumentException(
"Use " + index + " for this column, or -1 to allow moving it.");
}
var edits = new ArrayList<Replacement>();
if (field.equals("destinationId")
&& destinations(e).stream().anyMatch(c -> c != e && c.getAttribute(field).equals(value)))
@@ -273,13 +345,24 @@ final class GridDockDocument {
if (index < 0) throw new IllegalArgumentException("Select a column.");
if (index + delta < 0 || index + delta >= columns.size()) return List.of();
var other = columns.get(index + delta);
if (fixed(col) || fixed(other))
throw new IllegalArgumentException("Clear the fixed position before moving these columns.");
return List.of(replace(other, fragment(col)), replace(col, fragment(other)));
}
private boolean fixed(Element col) {
return property(col, "fixedPosition") != null
|| col.hasAttribute("fixedPosition") && !col.getAttribute("fixedPosition").equals("-1");
}
List<Replacement> removeColumn(Element col) {
if (!type(col).equals("DataGridColumn")) throw new IllegalArgumentException("Select a column.");
if (grouped(parentOfType(col, "DataGrid")).contains(col.getAttribute("id")))
throw new IllegalArgumentException("Remove the column from groupBy first.");
var columns = branches(parentOfType(col, "DataGrid"));
if (columns.subList(columns.indexOf(col) + 1, columns.size()).stream().anyMatch(this::fixed))
throw new IllegalArgumentException(
"Removing this column shifts a fixed column. Clear its fixed position first.");
var span = tag(col);
int start = xml.text.lastIndexOf('\n', span.start() - 1) + 1;
int end = xml.text.indexOf('\n', span.end());
@@ -13,6 +13,13 @@ final class GridDockEditor extends VBox {
private final ComboBox<String> setting = new ComboBox<>(),
value = new ComboBox<>(),
area = new ComboBox<>();
private final ComboBox<String> groupKey = new ComboBox<>();
private final TextField groupText = new TextField();
private final FlowPane groupFields = new FlowPane(6, 4);
private final Label setupHint =
new Label(
"Saved setups use the setup ID and version. Restoring an older version requires a"
+ " migration.");
private final Label message = new Label(),
signals =
new Label(
@@ -55,6 +62,38 @@ final class GridDockEditor extends VBox {
() ->
doc.set(
selected(), setting.getValue(), value.getEditor().getText().trim())));
groupKey.setId("group-label-key");
groupKey.setEditable(true);
groupKey.setPromptText("Group key");
groupText.setId("group-label-text");
groupText.setPromptText("Displayed label");
groupKey.setOnAction(
event -> {
if (selected() != null && groupKey.getValue() != null)
groupText.setText(doc.groupLabels(selected()).getOrDefault(groupKey.getValue(), ""));
});
groupFields
.getChildren()
.addAll(
groupKey,
groupText,
button(
"Set group label",
() ->
edit(
() ->
doc.groupLabel(
selected(),
groupKey.getEditor().getText(),
groupText.getText(),
false))),
button(
"Remove group label",
() ->
edit(
() ->
doc.groupLabel(selected(), groupKey.getEditor().getText(), "", true))));
setupHint.setWrapText(true);
bind =
button(
"Edit data binding",
@@ -82,6 +121,8 @@ final class GridDockEditor extends VBox {
tree,
new FlowPane(6, 4, setting, value, apply, bind),
new FlowPane(6, 4, add, earlier, later, remove, area, addArea, moveArea, split),
groupFields,
setupHint,
signals,
message);
tree.getSelectionModel().selectedItemProperty().addListener((o, a, b) -> select());
@@ -185,11 +226,31 @@ final class GridDockEditor extends VBox {
String field = setting.getValue();
var e = selected();
boolean input = "items".equals(field) || "source".equals(field);
boolean editable = e != null && field != null && !input;
boolean labels = e != null && "groupLabels".equals(field);
visible(groupFields, labels);
visible(setupHint, "setupId".equals(field) || "setupVersion".equals(field));
if (labels) {
groupKey.getItems().setAll(doc.groupLabels(e).keySet());
groupKey.getSelectionModel().clearSelection();
groupKey.getEditor().clear();
groupText.clear();
groupKey.getSelectionModel().selectFirst();
}
boolean editable = e != null && field != null && !input && !labels;
visible(bind, input);
visible(apply, editable);
visible(value, editable);
if (!editable) return;
String hint =
doc.type(e).equals("DockGroupDefinition")
? switch (field) {
case "minimumWidth", "minimumHeight" -> "Default: 80 px";
case "persistent" -> "Default: true";
case "splitDirections" -> "Default: ALL";
default -> "";
}
: "";
value.setPromptText(hint);
value.getItems().setAll(GridDockDocument.options(field));
value.setValue(e.getAttribute(field));
value.getEditor().setText(e.getAttribute(field));
@@ -45,6 +45,28 @@ class FormDocumentTest {
apply(doc.set(item, field, value == null ? "" : value, value == null));
}
@Test
void singleSlotsRespectReferencesAndDefaultTabContent() throws Exception {
source =
"""
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1" bottom="$footer">
<center><TabPane fx:id="tabs"><Tab fx:id="first"><ScrollPane fx:id="scroll">
<content><fx:include source="Other.fxml"/></content>
</ScrollPane></Tab></TabPane></center>
</BorderPane>
""";
add("Tab", "tabs", "tabs");
assertThrows(IllegalArgumentException.class, () -> add("Label", "first", "content"));
assertThrows(IllegalArgumentException.class, () -> add("Label", "scroll", "content"));
assertThrows(IllegalArgumentException.class, () -> add("Label", "", "bottom"));
assertThrows(IllegalArgumentException.class, () -> add("Label", "tabs", "tabs"));
apply(doc().move(item("scroll"), slot("tab", "content"), 0));
assertTrue(source.contains("<content><fx:include source=\"Other.fxml\"/></content>"));
add("Label", "first", "content");
}
@Test
void emptyGridAndNamedListsKeepReferencesAndRejectCycles() throws Exception {
assertEquals(
@@ -5,6 +5,50 @@ import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class GridDockDocumentTest {
@Test
void dockMinimaAllowZeroWithoutChangingGridColumnRules() throws Exception {
var source =
"<?import de.neitzel.fx.docking.*?><DockGroupDefinition destinationId='messages'/>";
var doc = new GridDockDocument(source);
var group = doc.xml.elements.getFirst();
for (String field : java.util.List.of("minimumWidth", "minimumHeight")) {
for (String invalid : java.util.List.of("-1", "NaN", "Infinity", "wide"))
assertThrows(IllegalArgumentException.class, () -> doc.set(group, field, invalid));
var changed = new GridDockDocument(doc.xml.source.apply(doc.set(group, field, "0")));
var reset =
new GridDockDocument(
changed.xml.source.apply(changed.set(changed.xml.elements.getFirst(), field, "")));
var result = reset.xml.elements.getFirst();
assertFalse(result.hasAttribute(field));
assertEquals("messages", result.getAttribute("destinationId"));
}
assertThrows(IllegalArgumentException.class, () -> doc.set(group, "persistent", "yes"));
assertThrows(IllegalArgumentException.class, () -> doc.set(group, "splitDirections", "RIGHT"));
var grid = new GridDockDocument("<?import de.neitzel.fx.view.*?><DataGridColumn/>");
assertThrows(
IllegalArgumentException.class,
() -> grid.set(grid.xml.elements.getFirst(), "minimumWidth", "0"));
}
@Test
void updatingOneGroupLabelRetainsReferencesCommentsAndNestedEntries() throws Exception {
String source =
"""
<?import de.neitzel.fx.view.*?>
<DataGrid><DataGridColumn id="folder" header="Folder"><groupLabels other="%localized" Post='old'>
<!-- keep --><custom><Unknown/></custom></groupLabels></DataGridColumn></DataGrid>
""";
var doc = new GridDockDocument(source);
var col = doc.branches(doc.roots().getFirst()).getFirst();
assertEquals(
source.replace("Post='old'", "Post='Post &amp; Briefe'"),
doc.xml.source.apply(doc.groupLabel(col, "Post", "Post & Briefe", false)));
assertThrows(
IllegalArgumentException.class, () -> doc.groupLabel(col, "other", "changed", false));
assertThrows(IllegalArgumentException.class, () -> doc.groupLabel(col, "custom", "", true));
assertThrows(IllegalArgumentException.class, () -> doc.set(col, "fixedPosition", "2"));
}
@Test
void implicitRowAttributeAndGroupingSurviveRename() throws Exception {
var source =
@@ -31,27 +31,23 @@ public final class BindingDiscovery {
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;
&& target.listElement() != null
&& target.type() != null
&& target.type().isAssignableFrom(paths.get(path));
}
private static boolean disjointCollectionTypes(Class<?> source, Class<?> target) {
if (source == null || target == null || source == Object.class || target == Object.class)
return false;
return (Collection.class.isAssignableFrom(source)
|| Map.class.isAssignableFrom(source)
|| Collection.class.isAssignableFrom(target)
|| Map.class.isAssignableFrom(target))
&& !source.isAssignableFrom(target)
&& !target.isAssignableFrom(source);
}
private final Set<String> actionHandlers = new HashSet<>();
@@ -352,6 +348,7 @@ public final class BindingDiscovery {
if (b.length > 512 * 1024) throw new IOException("Component FXML exceeds limit");
componentModel = model(parse(new String(b, java.nio.charset.StandardCharsets.UTF_8)));
}
var fieldTypes = GenericPropertyType.controlBindings(owner.controller, id, control);
for (Method m : control.getMethods()) {
if (Modifier.isStatic(m.getModifiers())
|| m.getParameterCount() != 0
@@ -360,10 +357,12 @@ public final class BindingDiscovery {
String property = m.getName().substring(0, m.getName().length() - 8);
if (property.isEmpty()) continue;
Class<?> getter = valueType(control, property);
Class<?> value = propertyType(m.getGenericReturnType(), Map.of());
var signature = GenericPropertyType.of(control, m, fieldTypes);
Class<?> value = signature.value();
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;
else if (value != null && getter != null && !box(getter).isAssignableFrom(box(value)))
value = null;
boolean constrained = false;
if (property.equals("model") && !componentModel.isEmpty()) {
value = load(componentModel);
@@ -371,7 +370,9 @@ public final class BindingDiscovery {
}
var target =
new TargetType(
value, Property.class.isAssignableFrom(m.getReturnType()), listElement(m));
value,
Property.class.isAssignableFrom(m.getReturnType()),
signature.listElement());
targetTypes.put(id + "." + property, target);
String status, reason;
if (!Property.class.isAssignableFrom(m.getReturnType())) {
@@ -386,7 +387,8 @@ public final class BindingDiscovery {
|| value == Object.class) {
status = "UNRESOLVED";
reason =
"Declared types are insufficient; rebuild with specific signatures/Model metadata.";
"Declared types are insufficient. Declare the fx:id field with its concrete generic"
+ " type in the FXML controller and rebuild.";
} else if (knownListPair(selected, target, direction)) {
boolean matches = listElements.get(selected) == target.listElement();
status = matches ? "COMPATIBLE" : "INCOMPATIBLE";
@@ -394,14 +396,17 @@ public final class BindingDiscovery {
matches
? "Matching observable list element type: " + target.listElement().getName()
: "Observable list element types differ.";
} else if (disjointCollectionTypes(source, value)) {
status = "INCOMPATIBLE";
reason = "Collection and scalar types cannot be directly bound.";
} else if (Collection.class.isAssignableFrom(source)
|| Collection.class.isAssignableFrom(value)
|| Map.class.isAssignableFrom(source)
|| Map.class.isAssignableFrom(value)) {
status = "UNRESOLVED";
reason =
"Collection variance requires further metadata; use Repeat/Table for Model"
+ " collections.";
"Unresolved collection element types. Declare concrete element types on the model"
+ " and the fx:id controller field.";
} else {
Class<?> a = box(source), b = box(value);
boolean view = b.isAssignableFrom(a), back = a.isAssignableFrom(b);
@@ -478,7 +483,8 @@ public final class BindingDiscovery {
.filter(e -> commandTarget(e.getValue()))
.map(Map.Entry::getKey)
.sorted()
.toList());
.toList(),
owner.actionEventHandlers());
}
private List<String> commandPaths() {
@@ -551,13 +557,15 @@ public final class BindingDiscovery {
|| m.isSynthetic()) continue;
String name = m.getName().substring(0, m.getName().length() - 8);
if (name.isEmpty() || paths.containsKey(name)) continue;
Class<?> element = listElement(m);
var signature = GenericPropertyType.of(vm, m, Map.of());
Class<?> element = signature.listElement();
if (element != null) listElements.put(name, element);
Class<?> value = propertyType(m.getGenericReturnType(), Map.of());
Class<?> value = signature.value();
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;
else if (value != null && getter != null && !box(getter).isAssignableFrom(box(value)))
value = null;
boolean readOnly = !Property.class.isAssignableFrom(m.getReturnType());
if (readOnly) readOnlySources.add(name);
paths.put(name, value == null ? Object.class : value);
@@ -743,6 +751,9 @@ public final class BindingDiscovery {
severity = "ERROR";
message = "Observable list element types differ.";
}
} else if (disjointCollectionTypes(source, target.type())) {
severity = "ERROR";
message = "Collection and scalar types cannot be directly bound.";
} else if (target.type() == null
|| source == Object.class
|| target.type() == Object.class
@@ -751,7 +762,9 @@ public final class BindingDiscovery {
|| Map.class.isAssignableFrom(source)
|| Map.class.isAssignableFrom(target.type())) {
severity = "WARNING";
message = "Value types require additional metadata";
message =
"Value types require additional metadata. Declare concrete types on the model and the"
+ " fx:id controller field.";
} else {
Class<?> a = box(source), b = box(target.type());
if ((!direction.equals("model") && !b.isAssignableFrom(a))
@@ -808,33 +821,6 @@ public final class BindingDiscovery {
return candidates.iterator().next();
}
static Class<?> propertyType(Type type, Map<TypeVariable<?>, Type> inherited) {
Class<?> raw;
var bindings = new HashMap<>(inherited);
if (type instanceof ParameterizedType p && p.getRawType() instanceof Class<?> c) {
raw = c;
for (int i = 0; i < c.getTypeParameters().length; i++) {
Type argument = p.getActualTypeArguments()[i];
if (argument instanceof TypeVariable<?> v) argument = bindings.getOrDefault(v, v);
bindings.put(c.getTypeParameters()[i], argument);
}
} else if (type instanceof Class<?> c) raw = c;
else return null;
if (raw == ObservableValue.class) {
Type value = bindings.get(raw.getTypeParameters()[0]);
return value instanceof Class<?> c
? c
: value instanceof ParameterizedType p && p.getRawType() instanceof Class<?> c ? c : null;
}
for (Type parent : raw.getGenericInterfaces()) {
Class<?> value = propertyType(parent, bindings);
if (value != null) return value;
}
return raw.getGenericSuperclass() == null
? null
: propertyType(raw.getGenericSuperclass(), bindings);
}
private static Class<?> valueType(Class<?> control, String name) {
String suffix = Character.toUpperCase(name.charAt(0)) + name.substring(1);
for (String prefix : List.of("get", "is"))
@@ -117,6 +117,50 @@ final class ControllerMetadata {
}
}
/** FXMLLoader gives an event-taking overload precedence over a parameterless handler. */
Optional<List<String>> actionEventHandlers() {
if (unknownController && controller == null) return Optional.empty();
var names = new TreeSet<String>();
var effectiveEvents = new HashMap<String, Boolean>();
for (Class<?> type = controller;
type != null
&& !type.getPackageName().startsWith("java.")
&& !type.getPackageName().startsWith("javafx.");
type = type.getSuperclass()) {
var declaredEvents = new HashMap<String, Boolean>();
for (var method : type.getDeclaredMethods()) {
int modifiers = method.getModifiers();
boolean publicAccess =
Modifier.isPublic(modifiers) && Modifier.isPublic(type.getModifiers());
if (Modifier.isStatic(modifiers)
|| Modifier.isNative(modifiers)
|| method.isSynthetic()
|| method.isBridge()
|| (!publicAccess && !method.isAnnotationPresent(javafx.fxml.FXML.class))
|| method.getName().equals("initialize")) continue;
Module module = type.getModule(), fxml = javafx.fxml.FXMLLoader.class.getModule();
if (!module.isOpen(type.getPackageName(), fxml)
&& !(publicAccess && module.isExported(type.getPackageName(), fxml))) continue;
var parameters = method.getParameterTypes();
if (parameters.length == 0) names.add("#" + method.getName());
if (parameters.length == 1 && javafx.event.Event.class.isAssignableFrom(parameters[0])) {
declaredEvents.merge(
"#" + method.getName(),
parameters[0].isAssignableFrom(javafx.event.ActionEvent.class),
Boolean::logicalAnd);
}
}
// FXMLLoader indexes EVENT methods by name, with the subclass taking precedence.
declaredEvents.forEach(effectiveEvents::putIfAbsent);
}
effectiveEvents.forEach(
(name, acceptsAction) -> {
if (acceptsAction) names.add(name);
else names.remove(name);
});
return Optional.of(List.copyOf(names));
}
List<Computed> methods(Class<?> target) {
if (controller == null) return List.of();
var result = new TreeMap<String, Computed>();
@@ -0,0 +1,84 @@
package de.neitzel.fxdesigner.target;
import java.lang.reflect.*;
import java.util.*;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
/** Resolves JavaFX accessor signatures without constructing a controller or control. */
record GenericPropertyType(Class<?> value, Class<?> listElement) {
static Map<TypeVariable<?>, Type> controlBindings(
Class<?> controller, String id, Class<?> control) {
for (Class<?> declaring = controller;
declaring != null;
declaring = declaring.getSuperclass()) {
try {
Field field = declaring.getDeclaredField(id);
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)
|| Modifier.isFinal(modifiers)
|| !(Modifier.isPublic(modifiers) || field.isAnnotationPresent(FXML.class))
|| !field.getType().isAssignableFrom(control)) continue;
var inherited = bindings(controller, declaring, Map.of());
return bindArguments(field.getGenericType(), inherited);
} catch (NoSuchFieldException ignored) {
// FXMLLoader also looks for inherited controller fields.
}
}
return Map.of();
}
static GenericPropertyType of(
Class<?> receiver, Method accessor, Map<TypeVariable<?>, Type> fields) {
var scope = bindings(receiver, accessor.getDeclaringClass(), fields);
var valueScope = bindings(accessor.getGenericReturnType(), ObservableValue.class, scope);
Type type = resolve(ObservableValue.class.getTypeParameters()[0], valueScope);
Class<?> raw = raw(type);
Class<?> element = null;
if (raw != null && ObservableList.class.isAssignableFrom(raw)) {
var listScope = bindings(type, ObservableList.class, valueScope);
var item = resolve(ObservableList.class.getTypeParameters()[0], listScope);
if (item instanceof Class<?> exact) element = exact;
}
return new GenericPropertyType(raw, element);
}
private static Class<?> raw(Type type) {
if (type instanceof ParameterizedType p) return (Class<?>) p.getRawType();
return type instanceof Class<?> c ? c : null;
}
private static Type resolve(Type type, Map<TypeVariable<?>, Type> scope) {
while (type instanceof TypeVariable<?> v && scope.containsKey(v)) type = scope.get(v);
return type;
}
private static Map<TypeVariable<?>, Type> bindArguments(
Type type, Map<TypeVariable<?>, Type> scope) {
if (!(type instanceof ParameterizedType p)) return scope;
var result = new HashMap<>(scope);
var vars = raw(type).getTypeParameters();
var args = p.getActualTypeArguments();
for (int i = 0; i < vars.length; i++) {
Type argument = resolve(args[i], scope);
// A field can type an ancestor (ComboBoxBase<String>) while the FXML declares
// a raw subclass (ComboBox). An unbound subclass variable adds no information.
if (argument instanceof TypeVariable<?> && scope.containsKey(vars[i])) continue;
if (!vars[i].equals(argument)) result.put(vars[i], argument);
}
return result;
}
private static Map<TypeVariable<?>, Type> bindings(
Type type, Class<?> target, Map<TypeVariable<?>, Type> scope) {
var raw = raw(type);
if (raw == null || !target.isAssignableFrom(raw)) return scope;
var local = bindArguments(type, scope);
if (raw == target) return local;
for (Type parent : raw.getGenericInterfaces()) {
if (target.isAssignableFrom(raw(parent))) return bindings(parent, target, local);
}
return bindings(raw.getGenericSuperclass(), target, local);
}
}
@@ -222,7 +222,7 @@ final class RepeatDiscovery {
if (!Property.class.isAssignableFrom(accessor.getReturnType())
|| !ControllerMetadata.accessible(accessor.getDeclaringClass(), true))
throw new IllegalArgumentException("Component needs an accessible writable modelProperty");
Class<?> property = BindingDiscovery.propertyType(accessor.getGenericReturnType(), Map.of());
Class<?> property = GenericPropertyType.of(type, accessor, Map.of()).value();
Document doc = resource(type);
Element root = doc.getDocumentElement();
if (!"http://javafx.com/fxml/1".equals(root.getNamespaceURI())
@@ -0,0 +1,61 @@
package de.neitzel.fxdesigner.target;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fxdesigner.protocol.BindingMetadata;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.input.KeyEvent;
import org.junit.jupiter.api.Test;
class ActionEventHandlersTest {
public static class Parent {
@FXML
private void inherited(Event event) {}
public void replaced(KeyEvent event) {}
private void hidden() {}
}
public static class Controller extends Parent {
@FXML
private void submit(ActionEvent event) {}
public void replaced(ActionEvent event) {}
public void clear() {}
public void mixed() {}
public void mixed(KeyEvent event) {}
public void keys(KeyEvent event) {}
public static void helper() {}
public void initialize() {}
Controller() {
throw new AssertionError("Discovery constructed a controller");
}
}
@Test
void reportsOnlyAccessibleSignaturesCallableForActionEvents() throws Exception {
var xml =
"<?import javafx.scene.control.TextField?><TextField xmlns:fx=\"http://javafx.com/fxml/1\""
+ " fx:controller=\""
+ Controller.class.getName()
+ "\"/>";
var result = BindingDiscovery.inspect(xml, "", "view", getClass().getClassLoader());
var wire = result.encode();
assertEquals(
List.of("#clear", "#inherited", "#replaced", "#submit"),
BindingMetadata.decode(wire).actionEventHandlers().orElseThrow());
wire.remove("actionEvents");
assertTrue(BindingMetadata.decode(wire).actionEventHandlers().isEmpty());
}
}
@@ -0,0 +1,41 @@
package de.neitzel.fxdesigner.target;
import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ComboBoxBase;
import org.junit.jupiter.api.Test;
class GenericPropertyTypeTest {
static class Base<T> {
@FXML private ComboBox<T> inherited;
@FXML private ComboBoxBase<Long> baseControl;
@FXML private ComboBox<? extends Number> bounded;
@FXML private ComboBox<List<String>> nested;
private ComboBox<String> uninjected;
@FXML private List<String> wrongControl;
}
static class Controller extends Base<Integer> {}
private GenericPropertyType signature(String id, String property) throws Exception {
var field = GenericPropertyType.controlBindings(Controller.class, id, ComboBox.class);
return GenericPropertyType.of(
ComboBox.class, ComboBox.class.getMethod(property + "Property"), field);
}
@Test
void resolvesInheritedControllerAndControlArgumentsWithoutStartingJavaFx() throws Exception {
assertEquals(Integer.class, signature("inherited", "value").value());
assertEquals(Integer.class, signature("inherited", "items").listElement());
assertEquals(Long.class, signature("baseControl", "value").value());
}
@Test
void unknownOrIncompatibleFieldsDoNotCertifyListElementTypes() throws Exception {
for (String id : List.of("bounded", "nested", "uninjected", "missing", "wrongControl"))
assertNull(signature(id, "items").listElement(), id);
}
}
+2
View File
@@ -26,6 +26,8 @@ Discovery owns a separate workflow so it does not replace the canvas or interact
FXML parsing disables external entities and DOCTYPE. Inputs, scene-node counts, path expansion, target counts and protocol payloads are bounded. Ambiguous imports, duplicate IDs, missing classes, invalid XML and absent declarations produce diagnostics. Attached-property binding discovery, open child-draft metadata overlays, broader custom metadata and complete collection compatibility remain later extensions, not silently inferred support.
A field matching the FXML ID can supply generic arguments that are erased in the FXML element. For example, declaring `@FXML private ComboBox<String> security` on the controller types both `security.value` and the elements of `security.items`. The worker follows inherited controller fields, control superclasses and JavaFX property interfaces using compiled signatures. An invariant observable-list binding toward the view requires matching element types. Incompatible list elements and unrelated scalar destinations receive a diagnostic. Wildcards and raw selectors retain an unresolved result until the project provides a concrete type.
## Qualification
Tests cover non-initializing signature discovery, nested and collection metadata, direction-dependent assignability, read-only targets, incompatible targets, secure parsing, metadata codec bounds and capability negotiation. Real classpath/module-path Person fixtures check Component Model compatibility and absence of Model, Controller and provider construction/initialization. Connected contracts test the worker protocol in both document adapters; live shared Kit checks use the same browser in standalone and the registered IntelliJ editor and verify source preservation.
+28
View File
@@ -39,3 +39,31 @@ Paste targets supported standard Pane children (VBox, HBox, Pane, AnchorPane, St
Problems are scoped to open designer documents and current build/draft evidence. Selecting a problem navigates to the affected FXML location. Source underlines follow the same ranges. IntelliJ also exposes Problems entries, native XML annotations and **Alt+Enter** actions. This is not a whole-project background inspection or precise Java-source navigation service.
Errors block new previews; warnings remain visible and permit preview. Stale diagnostic actions are withdrawn after edits or build changes. Available fixes are deliberately narrow: explicit DirectBinding direction choices, removing a later duplicate Direct/Computed target, and removal of eligible simple invalid Direct/Computed/Repeat declarations. Tables, unknown/nested payloads, warnings and declarations with `fx:id` do not get speculative deletion fixes. No action is auto-selected. Fixes preserve unrelated source and use normal Undo/Redo; see [supported fixes](../source-highlighting-fixes.md).
### Form properties and controller events
In **Form controls**, select a control and property. **Set property** writes the FXML attribute. **Reset property** removes it and restores its JavaFX default. The accessible name is inherited from Node. Text fields including AutoCompleteTextField accept a non-negative integer for `prefColumnCount`. Layout results such as `width` are read-only.
After **Build and Refresh**, select `onAction` on a supported action control, `onDismiss` on ToolBarPane, or `onRemove` on TagChip. Choose a compiled controller method in the list, or enter its `#method` reference and select **Set property**. The target checks accessible no-argument methods and methods accepting ActionEvent or Event, including inherited and FXML-annotated handlers. Without current controller metadata the inspector indicates that a build is needed for method checking. Undo, Redo and Save use the same FXML document as the bindings editor.
### Tabs, split panes and border panes
In **Form controls**, choose **Tab** from the palette and **TabPane / tabs** as the destination. Set its text under **Selected control**. Select **Tab / content** to add a layout or a ScrollPane. Each Tab, ScrollPane and named BorderPane region has one content slot. The inspector shows its occupant. To reuse an occupied slot, move its existing control to a free destination first. **Move to destination** keeps the subtree, its identifiers, event handlers and bindings together. For **SplitPane / items**, **Position** is the zero-based insertion index.
### Grid setups and group headings
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.
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
Open `ArchiveWindow.fxml` and select **Bindings → DataGrid / Docking → DockGroupDefinition · messages**. Select a property and use **Apply setting**. Clearing the value restores its FXML default.
| Group property | Values and effect |
| --- | --- |
| `minimumWidth`, `minimumHeight` | Finite pixel values from 0 upwards, default 80 each. Both groups and their divider must fit before a split is available. |
| `splitDirections` | `HORIZONTAL` allows left and right, `VERTICAL` allows above and below, `NONE` disables splitting and `ALL` is the default. |
| `persistent` | The default `true` keeps an empty root group available as a destination. With `false`, closing its last tab removes the group. Inside a split, the surviving sibling fills the vacated branch. |
After saving, choose **Form preview → Build and Refresh → Archiver · HTML-Dokumenttabs → Interactive preview**. Open the context menu of **Lieferschein.html** and use **Split**. Unavailable directions show the reason in the menu. Resize the window to test the minimum dimensions. To inspect persistence, move the delivery tab to `details` and close the invoice. Open **Move to** on the remaining delivery tab to see whether `messages` is still available.
@@ -0,0 +1,155 @@
package qualification;
import static qualification.WorkflowProbe.*;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import de.neitzel.fxdesigner.workflow.DesignerWorkflow.Example;
import java.nio.file.*;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import org.w3c.dom.Element;
/** Shared actions for editing declarations and opening the resulting Archiver preview. */
abstract class DeclarationWorkflowProbe extends FormWorkflowProbe {
Project project;
void open(String name) throws Exception {
var path =
Path.of(project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui", name + ".fxml");
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
pane = openDesigner(project, file);
if (!source().contains("<?neitzel-model de.neitzel.archiver.ui."))
throw new AssertionError(name);
}
void build(String id) throws Exception {
click(pane, "Form preview");
click(pane, "Build and Refresh");
await(
() ->
fx(
() ->
((ComboBox<?>) pane.lookup("#preview-example"))
.getItems().stream().anyMatch(item -> item.toString().contains(id))));
}
void interactive(String id, String attempt) throws Exception {
choose("preview-example", id);
await(
() ->
fx(
() -> {
var 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);
var choice = (Example) ((ComboBox<?>) pane.lookup("#preview-example")).getValue();
return ((ImageView) pane.lookup("#full-preview-image")).getImage() != null
&& state.contains(choice.label());
}));
Files.writeString(output.resolve("layout-case"), attempt);
click(pane, "Interactive preview");
String name = "result-" + attempt;
awaitTarget(name);
step(id + " · " + Files.readString(output.resolve(name)));
click(pane, "Stop preview");
}
void reopen(String form, String saved) throws Exception {
click(pane, "Save");
await(() -> Files.readString(Path.of(file.getPath())).contains(saved));
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(file);
return null;
});
open(form);
if (!source().contains(saved)) throw new AssertionError("Reopened " + form);
}
void inspector(boolean expanded) throws Exception {
fx(
() -> {
var panel =
(TitledPane)
pane.lookupAll(".titled-pane").stream()
.filter(n -> n instanceof TitledPane t && t.getText().equals("Bindings"))
.findFirst()
.orElseThrow();
panel.setAnimated(false);
panel.setExpanded(expanded);
var tabs = (TabPane) panel.getContent();
tabs.getSelectionModel()
.select(
tabs.getTabs().stream()
.filter(t -> t.getText().equals("DataGrid / Docking"))
.findFirst()
.orElseThrow());
pane.applyCss();
pane.layout();
return null;
});
}
void select(String name, String id) throws Exception {
fx(
() -> {
var tree = (TreeView<Element>) pane.lookup("#declaration-tree");
for (int i = 0; i < tree.getExpandedItemCount(); i++) {
var item = tree.getTreeItem(i);
var e = item.getValue();
String tag = e.getTagName();
if ((tag.equals(name) || tag.endsWith("." + name))
&& (id.isEmpty()
|| e.getAttribute("fx:id").equals(id)
|| e.getAttribute("id").equals(id)
|| e.getAttribute("destinationId").equals(id))) {
tree.getSelectionModel().select(item);
return null;
}
}
throw new AssertionError("Missing " + name + " " + id);
});
}
void combo(String name, String text) throws Exception {
fx(
() -> {
var box = (ComboBox<String>) pane.lookup("#" + name);
box.setValue(text);
return null;
});
}
void edit(String button, String expected) throws Exception {
String before = source();
click(pane, button);
await(
() -> {
String now = source();
var msg = fx(() -> ((Label) pane.lookup("#declaration-message")).getText());
if (!msg.isEmpty()) throw new AssertionError(msg);
return !now.equals(before)
&& now.contains(expected)
&& fx(
() ->
((TextArea) pane.lookup("#fxml-source")) == null
|| ((TextArea) pane.lookup("#fxml-source")).getText().equals(now));
});
fx(pane::flush).toCompletableFuture().get();
step(button + " · " + expected);
}
void applySetting(String field, String value) throws Exception {
combo("declaration-property", field);
fx(
() -> {
((ComboBox<?>) pane.lookup("#declaration-value")).getEditor().setText(value);
return null;
});
edit("Apply setting", field + "=\"" + value + "\"");
}
}
@@ -0,0 +1,331 @@
package qualification;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import javafx.application.Platform;
import javafx.geometry.Side;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.stage.*;
/** Operates the document tabs' ordinary context menus in the interactive Archiver worker. */
public final class DockRulesTargetProbe {
public static void premain(String directory) {
if (System.getProperty("sun.java.command", "")
.startsWith("de.neitzel.fxdesigner.target.WorkerMain "))
Thread.ofPlatform().daemon().start(() -> Worker.run(Path.of(directory)));
}
private static final class Worker {
private static final String INVOICE = "Rechnung.html", DELIVERY = "Lieferschein.html";
static <T> T fx(Callable<T> action) throws Exception {
var task = new FutureTask<>(action);
Platform.runLater(task);
return task.get(10, TimeUnit.SECONDS);
}
static void run(Path dir) {
try {
Stage stage = null;
while (stage == null) {
Thread.sleep(100);
try {
stage =
fx(
() ->
Window.getWindows().stream()
.filter(Stage.class::isInstance)
.map(Stage.class::cast)
.filter(
s ->
s.isShowing()
&& s.getOpacity() > 0
&& Objects.toString(s.getTitle(), "")
.startsWith("Neitzel preview"))
.findFirst()
.orElse(null));
} catch (IllegalStateException starting) {
/* Await JavaFX startup. */
}
}
Stage preview = stage;
String attempt = Files.readString(dir.resolve("layout-case"));
Parent root = fx(() -> preview.getScene().getRoot());
String result;
if (attempt.equals("defaults")) {
result = fx(() -> defaults(root));
} else {
boolean horizontal = attempt.equals("horizontal");
require(horizontal || attempt.equals("vertical"), attempt);
resize(preview, 640, 440);
String small = fx(() -> checkRules(root, horizontal, false));
resize(preview, 1340, 760);
String large = fx(() -> checkRules(root, horizontal, true));
await(() -> tab(root, INVOICE).getTabPane() != tab(root, DELIVERY).getTabPane());
String split = fx(() -> inspectSplit(root, horizontal, dir));
fx(
() -> {
move(root, DELIVERY, "details");
return null;
});
await(() -> tab(root, INVOICE).getTabPane().getTabs().size() == 1);
fx(
() -> {
var invoice = tab(root, INVOICE);
var menu = menu(invoice);
item(menu.getItems(), "Close", "Schließen").fire();
return null;
});
await(() -> tabs(root).stream().noneMatch(t -> t.getText().equals(INVOICE)));
String empty = fx(() -> verifyEmpty(root, !horizontal, dir));
result = small + "\n" + large + "\n" + split + "\n" + empty;
}
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 ex) {
ex.printStackTrace();
}
}
}
static void await(Callable<Boolean> test) throws Exception {
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (System.nanoTime() < end) {
if (fx(test)) return;
Thread.sleep(50);
}
throw new AssertionError("Preview state did not settle");
}
static void resize(Stage stage, int width, int height) throws Exception {
fx(
() -> {
stage.setWidth(width);
stage.setHeight(height);
return null;
});
await(
() ->
Math.abs(stage.getScene().getWidth() - width) < 12
&& stage.getScene().getHeight() > height - 60
&& stage.getScene().getHeight() <= height);
fx(
() -> {
layout(stage.getScene().getRoot());
return null;
});
}
static void layout(Parent root) {
root.applyCss();
root.layout();
}
static void require(boolean ok, String reason) {
if (!ok) throw new AssertionError(reason);
}
static List<Tab> tabs(Parent root) {
return root.lookupAll(".dock-group").stream()
.map(TabPane.class::cast)
.flatMap(p -> p.getTabs().stream())
.toList();
}
static Tab tab(Parent root, String name) {
return tabs(root).stream().filter(t -> name.equals(t.getText())).findFirst().orElseThrow();
}
static ContextMenu menu(Tab tab) {
var m = tab.getContextMenu();
m.show(tab.getTabPane(), Side.TOP, 0, 0);
return m;
}
static MenuItem item(List<MenuItem> items, String... labels) {
return items.stream()
.filter(
i ->
Arrays.stream(labels)
.anyMatch(
l ->
l.equals(i.getText())
|| i.getText().startsWith(l + " (")
|| i.getText().startsWith(l + " —")))
.findFirst()
.orElseThrow(
() ->
new AssertionError(
"Missing "
+ Arrays.toString(labels)
+ " in "
+ items.stream().map(MenuItem::getText).toList()));
}
static String checkRules(Parent root, boolean horizontal, boolean large) {
var delivery = tab(root, DELIVERY);
var group = delivery.getTabPane();
require(tab(root, INVOICE).getTabPane() == group, "Initial document group");
require(group.minWidth(-1) == 300 && group.minHeight(-1) == 225, "Effective minima");
var m = menu(delivery);
var choices = ((Menu) item(m.getItems(), "Split", "Teilen")).getItems();
var right = item(choices, "Right", "Rechts");
var below = item(choices, "Below", "Unten");
var blocked = horizontal ? below : right;
var allowed = horizontal ? right : below;
require(
blocked.isDisable()
&& (blocked.getText().contains("direction")
|| blocked.getText().contains("Richtung")),
blocked.getText());
// Exercise the checked operation as well as its disabled presentation.
blocked.fire();
require(
tab(root, INVOICE).getTabPane() == tab(root, DELIVERY).getTabPane(),
"Forbidden split changed layout");
String size = Math.round(group.getWidth()) + " × " + Math.round(group.getHeight());
if (!large) {
require(
allowed.isDisable()
&& (horizontal
? group.getWidth() < 2 * group.minWidth(-1) + 8
: group.getHeight() < 2 * group.minHeight(-1) + 8)
&& !allowed.getText().equals(blocked.getText()),
size + " · " + allowed.getText());
allowed.fire();
require(
tab(root, INVOICE).getTabPane() == tab(root, DELIVERY).getTabPane(),
"Small split changed layout");
} else {
require(!allowed.isDisable(), size + " · " + allowed.getText());
allowed.fire();
}
m.hide();
return (large ? "1340 × 760" : "640 × 440")
+ " · Gruppe "
+ size
+ " · "
+ blocked.getText()
+ " · "
+ allowed.getText();
}
static String inspectSplit(Parent root, boolean horizontal, Path dir) throws Exception {
layout(root);
var first = tab(root, INVOICE).getTabPane();
var second = tab(root, DELIVERY).getTabPane();
for (var group : List.of(first, second)) {
require(group.getWidth() >= 300 && group.getHeight() >= 225, "Split child below minimum");
require(
group.minWidth(-1) == 300 && group.minHeight(-1) == 225,
"Split did not inherit minima");
}
var a = first.localToScene(first.getLayoutBounds());
var b = second.localToScene(second.getLayoutBounds());
require(
horizontal ? b.getMinX() >= a.getMaxX() - 1 : b.getMinY() >= a.getMaxY() - 1,
"Geometric split direction");
require(
first.lookup("#html-document") != null && second.lookup("#html-document") != null,
"Document viewers");
image(root, dir.resolve(horizontal ? "dock-horizontal.png" : "dock-vertical.png"));
return "Rechnung / Lieferschein · "
+ Math.round(a.getWidth())
+ " × "
+ Math.round(a.getHeight())
+ " und "
+ Math.round(b.getWidth())
+ " × "
+ Math.round(b.getHeight());
}
static void move(Parent root, String document, String destination) {
var m = menu(tab(root, document));
var targets = ((Menu) item(m.getItems(), "Move to", "Verschieben nach")).getItems();
var action = item(targets, destination);
require(!action.isDisable(), action.getText());
action.fire();
m.hide();
}
static String verifyEmpty(Parent root, boolean persistent, Path dir) throws Exception {
layout(root);
var m = menu(tab(root, DELIVERY));
var targets = ((Menu) item(m.getItems(), "Move to", "Verschieben nach")).getItems();
require(
targets.stream().anyMatch(i -> i.getText().startsWith("details")),
"details destination gone");
var messages = targets.stream().filter(i -> i.getText().equals("messages")).findFirst();
require(
messages.isPresent() == persistent,
"messages target after close: " + targets.stream().map(MenuItem::getText).toList());
m.hide();
var empty =
root.lookupAll(".dock-group").stream()
.map(TabPane.class::cast)
.filter(t -> t.getTabs().isEmpty() && t.isVisible() && t.isManaged())
.toList();
require(empty.size() == (persistent ? 1 : 0), "Empty groups: " + empty.size());
image(root, dir.resolve(persistent ? "dock-empty-kept.png" : "dock-empty-removed.png"));
if (persistent) {
move(root, DELIVERY, "messages");
require(tab(root, DELIVERY).getTabPane() == empty.getFirst(), "Return to persistent group");
}
return persistent
? "persistent=true · messages bleibt leer sichtbar und nimmt den Lieferschein wieder auf"
: "persistent=false · messages nach dem letzten Tab aus Layout und Zielmenü entfernt";
}
static String defaults(Parent root) throws Exception {
var pane = root.lookup("#dockPane");
var layout = pane.getClass().getMethod("getInitialLayout").invoke(pane);
var group = layout.getClass().getMethod("getCenter").invoke(layout);
var type = group.getClass();
require(
Objects.equals(type.getMethod("getMinimumWidth").invoke(group), 80.0)
&& Objects.equals(type.getMethod("getMinimumHeight").invoke(group), 80.0)
&& (boolean) type.getMethod("isPersistent").invoke(group)
&& type.getMethod("getSplitDirections").invoke(group).toString().equals("ALL"),
"Effective defaults");
var texts =
root.lookupAll(".label").stream()
.filter(Label.class::isInstance)
.map(Label.class::cast)
.map(Label::getText)
.toList();
require(
texts.contains("Rechnungen / Musterrechnung.pdf")
&& texts.contains("Belegnummer RE-2026-042"),
"Original sample content");
return "Defaults 80 × 80, true, ALL · Musterrechnung.pdf und Belegnummer RE-2026-042";
}
static void image(Parent root, Path file) throws Exception {
var image = root.snapshot(null, null);
var pixels =
new java.awt.image.BufferedImage(
(int) image.getWidth(),
(int) image.getHeight(),
java.awt.image.BufferedImage.TYPE_INT_ARGB);
var buffer = ((java.awt.image.DataBufferInt) pixels.getRaster().getDataBuffer()).getData();
image
.getPixelReader()
.getPixels(
0,
0,
pixels.getWidth(),
pixels.getHeight(),
javafx.scene.image.PixelFormat.getIntArgbInstance(),
buffer,
0,
pixels.getWidth());
javax.imageio.ImageIO.write(pixels, "png", file.toFile());
}
}
}
@@ -0,0 +1,104 @@
package qualification;
import static qualification.WorkflowProbe.*;
import com.intellij.openapi.project.Project;
import java.nio.file.Files;
import java.util.List;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.*;
import javax.imageio.ImageIO;
/** Configures the same central group in three independently loaded preview sessions. */
public final class DockRulesWorkflowProbe extends DeclarationWorkflowProbe {
private static final String FORM = "ArchiveWindow";
private static final String DOCUMENTS = "archive-window-documents";
private static final List<String> FIELDS =
List.of("minimumWidth", "minimumHeight", "persistent", "splitDirections");
@Override
void verify(Project project) throws Exception {
this.project = project;
open(FORM);
group();
reject("minimumWidth", "-0.5");
reject("minimumHeight", "Infinity");
reject("splitDirections", "RIGHT");
reject("persistent", "yes");
applySetting("minimumWidth", "300");
applySetting("minimumHeight", "225");
applySetting("persistent", "false");
applySetting("splitDirections", "HORIZONTAL");
savedGroup("HORIZONTAL");
fx(
() -> {
ImageIO.write(
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
"png",
output.resolve("intellij.png").toFile());
return null;
});
build(DOCUMENTS);
interactive(DOCUMENTS, "horizontal");
group();
applySetting("persistent", "true");
applySetting("splitDirections", "VERTICAL");
savedGroup("VERTICAL");
build(DOCUMENTS);
interactive(DOCUMENTS, "vertical");
group();
for (var field : FIELDS) {
enter(field, "");
click(pane, "Apply setting");
await(() -> !source().contains(field + "=\""));
fx(pane::flush).toCompletableFuture().get();
}
savedGroup("destinationId=\"messages\"");
for (var field : FIELDS) {
choose("declaration-property", field);
if (!fx(
() -> ((ComboBox<?>) pane.lookup("#declaration-value")).getEditor().getText().isEmpty()))
throw new AssertionError("Reset " + field);
}
build("archive-window");
interactive("archive-window", "defaults");
Files.writeString(output.resolve("SUCCESS.txt"), Files.readString(output.resolve("steps.txt")));
}
private void group() throws Exception {
inspector(true);
select("DockGroupDefinition", "messages");
}
private void savedGroup(String value) throws Exception {
String expected = source();
reopen(FORM, expected);
if (!source().equals(expected)) throw new AssertionError("Reopened FXML differs");
group();
select("DockGroupDefinition", "details");
select("DockGroupDefinition", "messages");
choose("declaration-property", "splitDirections");
step("Save / reopen · messages, details · " + value);
}
private void enter(String field, String value) throws Exception {
choose("declaration-property", field);
fx(
() -> {
((ComboBox<?>) pane.lookup("#declaration-value")).getEditor().setText(value);
return null;
});
}
private void reject(String field, String value) throws Exception {
String before = source();
enter(field, value);
click(pane, "Apply setting");
if (!before.equals(source())
|| fx(() -> ((Label) pane.lookup("#declaration-message")).getText().isBlank()))
throw new AssertionError("Accepted " + field + "=" + value);
step("Rejected · " + field + "=" + value);
}
}
@@ -62,48 +62,25 @@ public final class DocumentTabsTargetProbe {
}
}
final Stage window = stage;
TabPane group =
fx(
() ->
window.getScene().getRoot().lookupAll(".tab-pane").stream()
.map(TabPane.class::cast)
.filter(
p ->
p.getTabs().stream()
.anyMatch(t -> "Rechnung.html".equals(t.getText())))
.findFirst()
.orElseThrow());
check(
dir,
group,
"Rechnung.html",
"Rechnung RE-042",
"Büromaterial · 48,00 €",
"Beleg offen",
"Beleg geprüft",
"rechnung-tab");
check(
dir,
group,
"Lieferschein.html",
"Lieferschein LS-018",
"Wareneingang · 3 Archivkartons",
"Beleg geprüft",
"Beleg offen",
"lieferschein-tab");
check(
dir,
group,
"Rechnung.html",
"Rechnung RE-042",
"Büromaterial · 48,00 €",
"Beleg offen",
"Beleg geprüft",
"rechnung-tab");
Files.writeString(
dir.resolve("document-tabs-result"),
"PASS Rechnung → Lieferschein → Rechnung: HTML content, assigned tag and filtered"
+ " suggestion in each production tab.\n");
String id = Files.readString(dir.resolve("document-attempt"));
var root = fx(() -> window.getScene().getRoot());
String result;
if (id.equals("archive-window-documents")) {
checkWindow(dir, root);
result =
"Rechnung → Lieferschein → Rechnung: HTML, chips and popup matched each document."
+ " Adding Beleg geprüft affected only Rechnung; removing it restored its"
+ " suggestion.";
} else if (id.startsWith("html-")) {
boolean invoice = id.equals("html-invoice");
String heading = invoice ? "Rechnung RE-042" : "Lieferschein LS-018";
checkHtml(
root, heading, invoice ? "Büromaterial · 48,00 €" : "Wareneingang · 3 Archivkartons");
result = id + ": WebKit displayed " + heading;
} else {
result = checkDetails(dir, root, id);
}
Files.writeString(dir.resolve("result-" + id), result);
} catch (Throwable error) {
var trace = new java.io.StringWriter();
error.printStackTrace(new java.io.PrintWriter(trace));
@@ -115,16 +92,95 @@ public final class DocumentTabsTargetProbe {
}
}
private static void check(
Path dir,
TabPane group,
String name,
String heading,
String body,
String assigned,
String suggestion,
String image)
throws Exception {
private static String checkDetails(Path dir, Node root, String id) throws Exception {
String assigned = id.equals("details-delivery") ? "Beleg geprüft" : "Beleg offen";
String suggestion = id.equals("details-delivery") ? "Beleg offen" : "Beleg geprüft";
boolean readonly = id.equals("details-readonly"), busy = id.equals("details-busy");
var field = fx(() -> (TextField) root.lookup("#tag-input"));
fx(
() -> {
if (!field.getPromptText().equals("Belegtag wählen")
|| field.isDisabled() != (readonly || busy))
throw new AssertionError("Saved prompt or edit state: " + id);
var remove = removeButton(root, assigned);
if (remove.isVisible() == readonly || remove.isDisabled() != busy)
throw new AssertionError("Removal state: " + id);
if (readonly || busy) {
remove.fire();
requireChips(root, assigned);
}
return null;
});
if (!readonly && !busy) popup(field, suggestion, dir.resolve(id + "-tags.png"));
return id
+ ": "
+ assigned
+ (readonly ? ", removal hidden" : busy ? ", removal disabled" : ", Be → " + suggestion);
}
private static void checkWindow(Path dir, Node root) throws Exception {
var group =
fx(
() ->
root.lookupAll(".tab-pane").stream()
.map(TabPane.class::cast)
.filter(
p ->
p.getTabs().stream()
.anyMatch(t -> "Rechnung.html".equals(t.getText())))
.findFirst()
.orElseThrow());
var invoice = select(group, "Rechnung.html");
checkHtml(invoice, "Rechnung RE-042", "Büromaterial · 48,00 €");
var input = fx(() -> (TextField) invoice.lookup("#tag-input"));
fx(
() -> {
requireChips(invoice, "Beleg offen");
save(invoice, dir.resolve("rechnung-tab.png"));
return null;
});
popup(input, "Beleg geprüft", dir.resolve("rechnung-tab-tags.png"));
fx(
() -> {
input.setText("Beleg geprüft");
((Button) invoice.lookup("#add")).fire();
requireChips(invoice, "Beleg offen", "Beleg geprüft");
if (suggestions(input).contains("Beleg geprüft"))
throw new AssertionError("Assigned tag still suggested");
return null;
});
fx(
() -> {
invoice.applyCss();
((javafx.scene.Parent) invoice).layout();
save(invoice, dir.resolve("rechnung-zwei-tags.png"));
return null;
});
var delivery = select(group, "Lieferschein.html");
checkHtml(delivery, "Lieferschein LS-018", "Wareneingang · 3 Archivkartons");
fx(
() -> {
requireChips(delivery, "Beleg geprüft");
save(delivery, dir.resolve("lieferschein-tab.png"));
return null;
});
popup(
fx(() -> (TextField) delivery.lookup("#tag-input")),
"Beleg offen",
dir.resolve("lieferschein-tab-tags.png"));
select(group, "Rechnung.html");
checkHtml(invoice, "Rechnung RE-042", "Büromaterial · 48,00 €");
fx(
() -> {
requireChips(invoice, "Beleg offen", "Beleg geprüft");
removeButton(invoice, "Beleg geprüft").fire();
requireChips(invoice, "Beleg offen");
return null;
});
popup(input, "Beleg geprüft", dir.resolve("rechnung-tab-tags.png"));
}
private static Node select(TabPane group, String name) throws Exception {
var tab =
fx(
() -> {
@@ -137,67 +193,134 @@ public final class DocumentTabsTargetProbe {
return target;
});
await(
"HTML in " + name,
"Selected " + name,
() -> group.getSelectionModel().getSelectedItem() == tab && tab.getContent().isVisible());
return fx(tab::getContent);
}
private static void checkHtml(Node root, String heading, String text) throws Exception {
await(
heading,
() -> {
var content = tab.getContent();
var viewer = content.lookup("#html-document");
if (viewer == null
|| group.getSelectionModel().getSelectedItem() != tab
|| !content.isVisible()) return false;
var browser = viewer.lookup("WebView");
Object engine = browser.getClass().getMethod("getEngine").invoke(browser);
var browser = root.lookup("WebView");
if (browser == null) return false;
var engine = browser.getClass().getMethod("getEngine").invoke(browser);
var doc = (Document) engine.getClass().getMethod("getDocument").invoke(engine);
return doc != null
&& doc.getElementsByTagName("h1").getLength() == 1
&& heading.equals(doc.getElementsByTagName("h1").item(0).getTextContent())
&& doc.getDocumentElement().getTextContent().contains(body);
});
var field = fx(() -> (TextField) tab.getContent().lookup("#tag-input"));
await(
"Focus in " + name,
() -> {
var stage = (Stage) group.getScene().getWindow();
if (!field.isFocused()) {
stage.toFront();
stage.requestFocus();
field.requestFocus();
}
return field.isFocused();
});
fx(
() -> {
var chips = tab.getContent().lookupAll(".tag-chip");
if (chips.size() != 1) throw new AssertionError("Expected one assigned tag in " + name);
var chip = chips.iterator().next();
if (!assigned.equals(chip.getClass().getMethod("getText").invoke(chip)))
throw new AssertionError("Wrong assigned tag in " + name);
field.setText("");
field.setText("Be");
return null;
});
await(
"Popup with " + suggestion,
() -> {
for (var window : Window.getWindows()) {
if (window instanceof Popup popup
&& popup.isShowing()
&& popup.getOwnerNode() == field
&& popup.getScene().lookup(".list-view") instanceof ListView<?> list
&& list.getItems().equals(List.of(suggestion))) {
save(list, dir.resolve(image + "-tags.png"));
return true;
}
}
return false;
});
fx(
() -> {
save(tab.getContent(), dir.resolve(image + ".png"));
field.setText("");
return null;
&& doc.getElementsByTagName("h1").item(0).getTextContent().equals(heading)
&& doc.getDocumentElement().getTextContent().contains(text);
});
}
private static List<?> suggestions(TextField field) throws Exception {
return (List<?>) field.getClass().getMethod("getSuggestionsSource").invoke(field);
}
private static Map<String, Node> chips(Node root) throws Exception {
var named = new TreeMap<String, Node>();
var pane = (javafx.scene.layout.FlowPane) root.lookup("#tags");
for (var row : pane.getChildren()) {
var chip = (javafx.scene.layout.Region) row.lookup(".tag-chip");
String text = (String) chip.getClass().getMethod("getText").invoke(chip);
chip.applyCss();
var fills = chip.getBackground().getFills();
if (fills.stream()
.noneMatch(f -> javafx.scene.paint.Color.web("#f2d58a").equals(f.getFill())))
throw new AssertionError(
"Chip "
+ text
+ " style="
+ chip.getStyle()
+ ", background="
+ fills.stream().map(f -> f.getFill()).toList()
+ ", component="
+ row.getClass().getResource("DocumentTag.fxml"));
if (named.put(text, chip) != null)
throw new AssertionError("Duplicate assigned chip: " + text);
}
return named;
}
private 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 {
return (Button)
Objects.requireNonNull(chips(root).get(text), text).lookup(".tag-chip-remove");
}
private static void popup(TextField field, String suggestion, Path file) throws Exception {
// Each interactive target is a separate macOS app. Keep focus acquisition and typing in
// one FX event so an IDE activation between them cannot suppress the real popup.
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(45);
long activateAfter = 0;
while (System.nanoTime() < deadline) {
if (System.nanoTime() >= activateAfter
&& !fx(field::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);
activateAfter = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
}
boolean matched =
fx(
() -> {
var stage = (Stage) field.getScene().getWindow();
if (!field.isFocused()) {
stage.toFront();
stage.requestFocus();
field.requestFocus();
}
if (!field.isFocused()) return false;
if (!suggestions(field).contains(suggestion))
throw new AssertionError(
"Missing " + suggestion + " in catalogue " + suggestions(field));
field.setText("");
field.setText("Be");
for (var window : Window.getWindows()) {
if (window instanceof Popup popup
&& popup.isShowing()
&& popup.getOwnerNode() == field
&& popup.getScene().lookup(".list-view") instanceof ListView<?> list) {
if (!list.getItems().equals(List.of(suggestion)))
throw new AssertionError(
"Expected " + suggestion + " but saw " + list.getItems());
save(list, file);
field.setText("");
return true;
}
}
return false;
});
if (matched) return;
Thread.sleep(150);
}
throw new AssertionError(
fx(
() ->
"No popup for "
+ suggestion
+ ", field focused="
+ field.isFocused()
+ ", stage focused="
+ field.getScene().getWindow().isFocused()
+ ", catalogue="
+ suggestions(field)
+ ", windows="
+ Window.getWindows()));
}
private static void save(Node node, Path file) throws Exception {
var image = node.snapshot(null, null);
int width = (int) image.getWidth(), height = (int) image.getHeight();
@@ -2,59 +2,112 @@ package qualification;
import static qualification.WorkflowProbe.*;
import com.intellij.openapi.fileEditor.FileEditorManager;
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.concurrent.TimeUnit;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javax.imageio.ImageIO;
/**
* Opens the production ArchiveWindow in the registered editor and selects its real document tabs.
*/
/** Edits the real chip template and opens both child resources and the archive window. */
public final class DocumentTabsWorkflowProbe extends FormWorkflowProbe {
@Override
void verify(Project project) throws Exception {
edit(project, "DocumentTag", "TagChip #chip", "style", "-fx-background-color: #f2d58a;");
edit(
project,
"DocumentDetails",
"AutoCompleteTextField #input",
"promptText",
"Belegtag wählen");
build(4);
for (String id :
new String[] {"details-invoice", "details-delivery", "details-readonly", "details-busy"})
preview(id);
open(project, "HtmlDocument");
build(2);
preview("html-invoice");
preview("html-delivery");
open(project, "ArchiveWindow");
build(2);
preview("archive-window-documents");
Files.writeString(output.resolve("SUCCESS.txt"), Files.readString(output.resolve("steps.txt")));
}
private void open(Project project, String form) throws Exception {
var path =
Path.of(
project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui/ArchiveWindow.fxml");
Path.of(project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui", form + ".fxml");
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
pane = openDesigner(project, file);
fx(pane::flush).toCompletableFuture().get(10, TimeUnit.SECONDS);
step("Opened " + form + ".fxml in Neitzel Designer");
}
private void edit(Project project, String form, String control, String property, String value)
throws Exception {
open(project, form);
controls(true);
choose("form-control", control);
set(property, value, value);
click(pane, "Save");
await(() -> Files.readString(Path.of(file.getPath())).contains(value));
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(file);
return null;
});
open(project, form);
if (!source().contains(value)) throw new AssertionError(form + " lost " + property);
step("Saved and reopened " + control + "." + property + " = " + value);
}
private void build(int examples) throws Exception {
click(pane, "Form preview");
click(pane, "Build and Refresh");
await(
() ->
fx(
() ->
((ComboBox<?>) pane.lookup("#preview-example"))
.getItems().stream()
.anyMatch(
item -> item.toString().contains("archive-window-documents"))));
choose("preview-example", "archive-window-documents");
((ComboBox<?>) pane.lookup("#preview-example")).getItems().size() == examples));
}
private void preview(String id) throws Exception {
choose("preview-example", id);
String label =
fx(() -> ((Example) ((ComboBox<?>) pane.lookup("#preview-example")).getValue()).label());
await(
() ->
fx(
() -> {
var status = ((Label) pane.lookup("#preview-state")).getText();
if (status.startsWith("Preview failed") || status.startsWith("Preview blocked"))
throw new AssertionError(status);
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
&& status.contains("HTML-Dokumenttabs");
&& state.contains(label);
}));
step("Production ArchiveWindow rendered the document tabs");
fx(
() -> {
var frame = ((ImageView) pane.lookup("#full-preview-image")).getImage();
ImageIO.write(
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
"png",
output.resolve("intellij.png").toFile());
SwingFXUtils.fromFXImage(frame, null), "png", output.resolve(id + ".png").toFile());
if (id.equals("archive-window-documents"))
ImageIO.write(
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
"png",
output.resolve("intellij.png").toFile());
return null;
});
Files.writeString(output.resolve("document-attempt"), id);
click(pane, "Interactive preview");
awaitTarget("document-tabs-result");
var result = "result-" + id;
awaitTarget(result);
step(Files.readString(output.resolve(result)));
click(pane, "Stop preview");
Files.writeString(
output.resolve("SUCCESS.txt"), Files.readString(output.resolve("document-tabs-result")));
}
}
@@ -0,0 +1,297 @@
package qualification;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.ContextMenuEvent;
import javafx.stage.*;
import javax.imageio.ImageIO;
/** Acts on the actual controls in the interactive Archiver worker. */
public final class FolderActionsTargetProbe {
public static void premain(String dir) {
if (System.getProperty("sun.java.command", "")
.startsWith("de.neitzel.fxdesigner.target.WorkerMain "))
Thread.ofPlatform().daemon().start(() -> Worker.run(Path.of(dir)));
}
private static final class Worker {
private static <T> T fx(Callable<T> action) throws Exception {
var task = new FutureTask<>(action);
Platform.runLater(task);
return task.get(10, TimeUnit.SECONDS);
}
private static void await(String description, Callable<Boolean> test) throws Exception {
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(22);
while (System.nanoTime() < end) {
if (fx(test)) return;
Thread.sleep(90);
}
throw new AssertionError(description);
}
private static void require(boolean value, String message) {
if (!value) throw new AssertionError(message);
}
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;
var root =
fx(
() -> {
shown.setWidth(1250);
shown.setHeight(640);
var r = shown.getScene().getRoot();
r.applyCss();
r.layout();
return r;
});
if (fx(() -> root.lookup("#tag-input") != null)) {
fx(
() -> {
var input = (TextField) root.lookup("#tag-input");
require(
input.getPrefColumnCount() == 23
&& "Belege verschlagworten".equals(input.getAccessibleText()),
"Saved text field properties");
input.setText("Inspektorprobe");
input.fireEvent(new ActionEvent());
require(
root.lookupAll(".tag-chip").stream()
.anyMatch(
chip ->
chip.lookup(".label") instanceof Label l
&& l.getText().equals("Inspektorprobe")),
"onAction did not add tag");
return null;
});
Files.writeString(
dir.resolve("result-detail-action"),
"23 columns and accessible name restored; #addTag added Inspektorprobe");
} else checkFolder(dir, root);
} 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 ignored) {
}
}
}
private 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 {
return (String) row.getClass().getMethod(name).invoke(row);
}
private static void select(Node grid, List<String> keys) throws Exception {
grid.getClass().getMethod("selectKeys", Collection.class).invoke(grid, keys);
}
private static MenuItem move(Node grid, String file) {
Node anchor =
grid.lookupAll(".label").stream()
.filter(n -> n instanceof Label l && l.getText().equals(file))
.findFirst()
.orElseThrow();
while (anchor != null && anchor.getOnContextMenuRequested() == null)
anchor = anchor.getParent();
Objects.requireNonNull(anchor, "Product row context menu");
var p = anchor.localToScreen(0, 0);
anchor.fireEvent(
new ContextMenuEvent(
ContextMenuEvent.CONTEXT_MENU_REQUESTED, 0, 0, p.getX(), p.getY(), false, null));
return Window.getWindows().stream()
.filter(w -> w instanceof ContextMenu m && m.isShowing())
.map(ContextMenu.class::cast)
.flatMap(m -> m.getItems().stream())
.filter(i -> "Verschieben …".equals(i.getText()))
.findFirst()
.orElseThrow();
}
private static boolean visible(Node grid, String column) throws Exception {
return (boolean)
grid.getClass().getMethod("isColumnVisible", String.class).invoke(grid, column);
}
@SuppressWarnings("unchecked")
private static void checkFolder(Path dir, Parent root) throws Exception {
Node grid = fx(() -> root.lookup("#grid"));
var search = fx(() -> (TextField) root.lookup("#search"));
var feedback = fx(() -> (Label) root.lookup("#example-folder-result"));
var places = fx(() -> (Button) root.lookup("#places"));
var profiles = fx(() -> (ComboBox<String>) root.lookup("#folder-view-profile"));
var save = fx(() -> (Button) root.lookup("#save-folder-view-profile"));
fx(
() -> {
search.setText("Archivbeleg");
search.fireEvent(new ActionEvent());
return null;
});
await(
"Two distinguishable full-text hits for Archivbeleg",
() -> {
if (rows(grid).size() != 2) return false;
for (var row : rows(grid))
if (!attr(row, "snippet").toLowerCase(Locale.ROOT).contains("archivbeleg"))
return false;
return grid.lookupAll(".label").stream()
.anyMatch(n -> n instanceof Label l && l.getText().equals("Lieferbrief.md"));
});
var keys =
fx(
() -> {
var result = new TreeMap<String, String>();
for (var row : rows(grid)) result.put(attr(row, "path"), attr(row, "key"));
return result;
});
var invoice = keys.get("Musterrechnung.pdf");
var letter = keys.get("Lieferbrief.md");
require(
invoice != null && letter != null && !invoice.equals(letter),
"Distinct archive entry keys: " + keys);
fx(
() -> {
var action = move(grid, "Lieferbrief.md");
select(grid, List.of());
require(action.isDisable() && places.isDisabled(), "Empty selection enabled actions");
select(grid, List.of(letter));
require(!action.isDisable() && !places.isDisabled(), "Single selection blocked");
places.fire();
require(
feedback.getText().contains("Lieferbrief.md")
&& feedback.getText().contains("Wareneingang"),
"Wrong place: " + feedback.getText());
action.fire();
require(feedback.getText().equals("Verschieben · " + letter), "Wrong single key");
select(grid, List.of(invoice, letter));
require(!action.isDisable() && places.isDisabled(), "Multiple selection availability");
action.fire();
String message = feedback.getText();
require(
message.startsWith("Verschieben · ")
&& Set.copyOf(
Arrays.asList(message.substring("Verschieben · ".length()).split(", ")))
.equals(Set.of(invoice, letter)),
"Wrong affected keys: " + message);
image(root, dir.resolve("folder-search.png"));
search.setText("Wareneingang");
search.fireEvent(new ActionEvent());
String before = feedback.getText();
action.fire();
require(
places.isDisabled() && before.equals(feedback.getText()),
"Stale action during new search");
return null;
});
await(
"Only Lieferbrief matches Wareneingang",
() -> rows(grid).size() == 1 && attr(rows(grid).getFirst(), "key").equals(letter));
fx(
() -> {
((Button) root.lookup(".tool-bar-dismiss")).fire();
Node bar = root.lookup("#search-toolbar");
require(
!bar.isVisible() && !bar.isManaged() && search.getText().isEmpty(),
"onDismiss did not close/reset the search");
return null;
});
await(
"Normal folder rows and profiles ready",
() -> rows(grid).size() == 2 && !profiles.isDisabled());
fx(
() -> {
var menu = (MenuButton) grid.lookup(".data-grid-column-menu");
menu.show();
var type =
(CheckMenuItem)
menu.getItems().stream()
.filter(it -> "Dateityp".equals(it.getText()))
.findFirst()
.orElseThrow();
require(type.isSelected(), "Initially hidden type");
type.setSelected(false);
type.fire();
menu.hide();
profiles.getEditor().setText("Kurzansicht");
require(!save.isDisabled(), "Save unavailable");
save.fire();
require(profiles.getItems().contains("Kurzansicht"), "Profile not saved");
String standard =
profiles.getItems().stream()
.filter(it -> it.endsWith("STANDARD"))
.findFirst()
.orElseThrow();
profiles.getSelectionModel().select(standard);
return null;
});
await(
"Standard restores visible type", () -> visible(grid, "type") && !profiles.isDisabled());
fx(
() -> {
profiles.getSelectionModel().select("Kurzansicht");
return null;
});
await(
"Reapplied profile hides type",
() ->
!visible(grid, "type")
&& !profiles.isDisabled()
&& "Kurzansicht".equals(profiles.getEditor().getText()));
fx(
() -> {
image(root, dir.resolve("folder-profile.png"));
return null;
});
Files.writeString(
dir.resolve("result-folder-actions"),
"Archivbeleg → two hits; Wareneingang → Lieferbrief. Fundstelle and move verified for"
+ " zero, one, both keys "
+ keys
+ "; new search invalidated actions. Dismiss cleared search. Standard showed"
+ " Dateityp; Kurzansicht restored hidden Dateityp.");
}
private 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);
int[] pixels = new int[w * h];
img.getPixelReader()
.getPixels(0, 0, w, h, javafx.scene.image.PixelFormat.getIntArgbInstance(), pixels, 0, w);
out.setRGB(0, 0, w, h, pixels, 0, w);
ImageIO.write(out, "png", path.toFile());
}
}
}
@@ -0,0 +1,171 @@
package qualification;
import static qualification.WorkflowProbe.*;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import java.nio.file.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javax.imageio.ImageIO;
public final class FolderActionsWorkflowProbe extends FormWorkflowProbe {
@Override
void verify(Project project) throws Exception {
checkForm(project, true);
checkForm(project, false);
Files.writeString(output.resolve("SUCCESS.txt"), Files.readString(output.resolve("steps.txt")));
}
private void open(Project project, String name) throws Exception {
var path =
Path.of(project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui", name + ".fxml");
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
pane = openDesigner(project, file);
fx(pane::flush).toCompletableFuture().get(10, TimeUnit.SECONDS);
}
private void save() throws Exception {
var text = source();
click(pane, "Save");
await(
() ->
Files.readString(Path.of(file.getPath()))
.lines()
.map(String::stripTrailing)
.toList()
.equals(text.lines().map(String::stripTrailing).toList()));
}
private void build(String id, String label) throws Exception {
click(pane, "Form preview");
click(pane, "Build and Refresh");
await(
() ->
fx(
() ->
((ComboBox<?>) pane.lookup("#preview-example"))
.getItems().stream().anyMatch(e -> e.toString().contains(id))));
choose("preview-example", id);
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(state);
return ((ImageView) pane.lookup("#full-preview-image")).getImage() != null
&& state.contains(label);
}));
}
private void reset(String prop, String attribute) throws Exception {
choose("form-property", prop);
click(pane, "Reset property");
await(() -> !source().contains(attribute));
}
private void checkForm(Project project, boolean details) throws Exception {
String name = details ? "DocumentDetails" : "FolderTab";
String control = details ? "AutoCompleteTextField #input" : "ToolBarPane #find";
String prop = details ? "onAction" : "onDismiss";
String handler = details ? "#addTag" : "#closeFind";
String id = details ? "details-invoice" : "folder-actions";
String label = details ? "Dokumentdetails · Rechnung" : "Archivordner · Suche und Anzeigeprofile";
open(project, name);
List<String> bindings =
source()
.lines()
.filter(s -> s.contains("<DirectBinding ") || s.contains("<CommandBinding "))
.toList();
controls(true);
choose("form-control", control);
if (details) {
reset("accessibleText", "accessibleText=\"Neuen Tag eingeben\"");
reset("prefColumnCount", "prefColumnCount=\"12\"");
set("accessibleText", "Belege verschlagworten", "accessibleText=\"Belege verschlagworten\"");
set("prefColumnCount", "23", "prefColumnCount=\"23\"");
String edited = source();
click(pane, "Undo");
await(() -> !source().contains("prefColumnCount=\"23\""));
click(pane, "Redo");
await(() -> source().equals(edited));
choose("form-property", "width");
if (fx(() -> ((TextArea) pane.lookup("#form-value")).isEditable()))
throw new AssertionError("Writable width");
}
reset(prop, prop + "=\"" + handler + "\"");
save();
step(name + " · reset " + prop + " and saved");
build(id, label);
controls(true);
choose("form-control", control);
choose("form-property", prop);
await(
() ->
fx(
() ->
((ComboBox<?>) pane.lookup("#form-event-handlers"))
.getItems()
.contains(handler)));
String before = source();
fx(
() -> {
((TextArea) pane.lookup("#form-value")).setText("#falscherHandler");
return null;
});
click(pane, "Set property");
var msg = fx(() -> ((Label) pane.lookup("#form-message")).getText());
if (!msg.contains("#falscherHandler")
|| !msg.contains("ActionEvent")
|| !before.equals(source())) throw new AssertionError(msg);
if (!details) screenshot("folder-events.png");
choose("form-event-handlers", handler);
click(pane, "Set property");
edited(before, prop + "=\"" + handler + "\"");
save();
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(file);
return null;
});
open(project, name);
String saved = source();
if (!saved.contains(prop + "=\"" + handler + "\"")
|| !bindings.equals(
saved
.lines()
.filter(s -> s.contains("<DirectBinding ") || s.contains("<CommandBinding "))
.toList())) throw new AssertionError("Reopened declarations differ");
step(
name
+ " · rejected #falscherHandler, saved and reopened "
+ handler
+ " with "
+ bindings.size()
+ " unchanged bindings");
build(id, label);
if (!details) screenshot("intellij.png");
click(pane, "Interactive preview");
var result = details ? "result-detail-action" : "result-folder-actions";
awaitTarget(result);
step(Files.readString(output.resolve(result)));
click(pane, "Stop preview");
}
private void screenshot(String name) throws Exception {
fx(
() -> {
ImageIO.write(
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
"png",
output.resolve(name).toFile());
return null;
});
}
}
@@ -0,0 +1,160 @@
package qualification;
import java.awt.image.BufferedImage;
import java.nio.file.*;
import java.util.concurrent.*;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.stage.*;
import javax.imageio.ImageIO;
/** Reads the visible rows and drives the real import controls in the worker's interactive stage. */
public final class ImportTargetProbe {
public static void premain(String directory) {
if (System.getProperty("sun.java.command", "")
.startsWith("de.neitzel.fxdesigner.target.WorkerMain "))
Thread.ofPlatform().daemon().start(() -> Probe.run(Path.of(directory)));
}
private static final class Probe {
static void run(Path directory) {
try {
while (true) {
Thread.sleep(150);
var task = new FutureTask<>(() -> inspect(directory));
try {
Platform.runLater(task);
} catch (IllegalStateException booting) {
continue;
}
if (task.get(15, TimeUnit.SECONDS)) return;
}
} catch (Throwable failure) {
var trace = new java.io.StringWriter();
failure.printStackTrace(new java.io.PrintWriter(trace));
try {
Files.writeString(directory.resolve("target-error.txt"), trace.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
static boolean inspect(Path directory) throws Exception {
var stage =
Window.getWindows().stream()
.filter(Stage.class::isInstance)
.map(Stage.class::cast)
.filter(
w ->
w.isShowing()
&& w.getTitle() != null
&& w.getTitle().startsWith("Neitzel preview"))
.findFirst();
if (stage.isEmpty()) return false;
Node root = stage.get().getScene().getRoot();
String attempt = Files.readString(directory.resolve("import-attempt"));
String result;
if (attempt.equals("import-grid")) {
var cells =
root.lookupAll("*").stream()
.filter(Labeled.class::isInstance)
.map(n -> ((Labeled) n).getText())
.toList();
if (!cells.contains("Musterrechnung.pdf") || !cells.contains("Lieferbrief.txt"))
return false;
result = "Visible rows: Musterrechnung.pdf, Lieferbrief.txt";
} else {
var form = root.lookup("#form");
if (form == null) return false;
var name = (TextField) form.lookup("#name");
var folders = (ComboBox<?>) form.lookup("#folders");
var free = (Button) form.lookup("#useFreeName");
var target = (Label) form.lookup("#target");
var status = (Label) form.lookup("#status");
if (attempt.equals("import-free")) {
check(
target.getText().equals("Archivwurzel")
&& name.getText().equals("Rechnung.md")
&& !form.isDisabled(),
"Initial free name");
name.setText("Entwurf.md");
folders.getSelectionModel().select(1);
check(
target.getText().equals("Belege")
&& name.getText().equals("Entwurf.md")
&& !free.isVisible()
&& !free.isManaged(),
"Folder/name write-back");
folders.getSelectionModel().select(0);
check(
target.getText().equals("Archivwurzel") && name.getText().equals("Entwurf.md"),
"Return to root");
result = "Edited name Entwurf.md retained across Archivwurzel -> Belege -> Archivwurzel";
} else if (attempt.equals("import-busy")) {
check(
form.isDisabled()
&& name.isDisabled()
&& status.getText().contains("Datei wird abgelegt"),
"Busy draft must block input");
result = "Accepted draft entered busy state and disabled the form";
} else {
check(
attempt.equals("import-collision")
&& name.getText().equals("Rechnung.md")
&& target.getText().equals("Belege")
&& free.isVisible()
&& free.isManaged()
&& status.getText().contains("Dateiname belegt. Vorschlag: Rechnung (2).md"),
"Expected initial collision: "
+ name.getText()
+ " / "
+ target.getText()
+ " / "
+ status.getText());
picture(form, directory.resolve("import-collision.png"));
free.fire();
check(
name.getText().equals("Rechnung (2).md")
&& !free.isVisible()
&& !free.isManaged()
&& !status.getText().contains("belegt"),
"Accept free name");
picture(form, directory.resolve("import-accepted.png"));
result =
"Belege/Rechnung.md -> Rechnung (2).md; collision cleared, button invisible and"
+ " unmanaged";
}
}
Files.writeString(directory.resolve("result-" + attempt), result);
return true;
}
static void check(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
static void picture(Node node, Path file) throws Exception {
node.getScene().getRoot().applyCss();
node.getScene().getRoot().layout();
var image = node.snapshot(null, null);
int width = (int) image.getWidth(), height = (int) image.getHeight();
var buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int[] pixels = new int[width * height];
image
.getPixelReader()
.getPixels(
0,
0,
width,
height,
javafx.scene.image.PixelFormat.getIntArgbInstance(),
pixels,
0,
width);
buffer.setRGB(0, 0, width, height, pixels, 0, width);
ImageIO.write(buffer, "png", file.toFile());
}
}
}
@@ -0,0 +1,230 @@
package qualification;
import static qualification.WorkflowProbe.*;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import de.neitzel.fxdesigner.protocol.BindingMetadata.Target;
import java.nio.file.*;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javax.imageio.ImageIO;
/** Exercises generic discovery, persists two bindings, then drives the actual target views. */
public final class ImportWorkflowProbe extends FormWorkflowProbe {
@Override
void verify(Project project) throws Exception {
open(project, "ConnectionForm", 2);
discover();
target("securityChoices", "view", "security", "items", "COMPATIBLE");
target("protocol", "both", "protocol", "value", "COMPATIBLE");
target("security", "both", "security", "value", "COMPATIBLE");
open(project, "FolderTab", 2);
discover();
target("view", "both", "view", "value", "COMPATIBLE");
target("grouping", "both", "grouping", "value", "COMPATIBLE");
target("view", "both", "grouping", "value", "CONVERTER_REQUIRED");
target("rows", "view", "profiles", "items", "INCOMPATIBLE");
target("rows", "view", "clearLayout", "accessibleHelp", "INCOMPATIBLE");
target("view", "both", "untypedPick", "value", "UNRESOLVED");
target("rows", "view", "grid", "items", "COMPATIBLE");
applyAndReopen(project, "FolderTab", 2, "grid", "items", "rows", "view");
preview("archive-folder", "import-grid");
open(project, "ImportForm", 3);
discover();
target("folder", "both", "folders", "value", "COMPATIBLE");
applyAndReopen(project, "ImportForm", 3, "folders", "value", "folder", "both");
preview("import-free", "import-free");
preview("import-collision", "import-collision");
preview("import-busy", "import-busy");
Files.writeString(output.resolve("SUCCESS.txt"), Files.readString(output.resolve("steps.txt")));
}
private void open(Project project, String form, int count) throws Exception {
var path =
Path.of(project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui", form + ".fxml");
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
pane = openDesigner(project, file);
fx(pane::flush).toCompletableFuture().get(10, java.util.concurrent.TimeUnit.SECONDS);
click(pane, "Form preview");
click(pane, "Build and Refresh");
await(
() -> fx(() -> ((ComboBox<?>) pane.lookup("#preview-example")).getItems().size() == count));
// The initial native document sync invalidates discovery while the first preview is loading.
// Wait for the displayed revision before selecting a source in the inspector.
await(
() ->
fx(
() -> {
String state = ((Label) pane.lookup("#preview-state")).getText();
if (state.startsWith("Preview failed")
&& form.equals("FolderTab")
&& !((TextArea) pane.lookup("#fxml-source"))
.getText()
.contains("path=\"rows\"")) return true;
if (state.startsWith("Preview failed")
|| state.startsWith("Preview unavailable")
|| state.startsWith("Preview blocked"))
throw new AssertionError(form + " initial preview: " + state);
return ((ImageView) pane.lookup("#full-preview-image")).getImage() != null
&& state.contains("revision");
}));
step("Opened " + form + " with " + count + " examples");
}
private void discover() throws Exception {
fx(
() -> {
var group =
(TitledPane)
pane.lookupAll(".titled-pane").stream()
.filter(n -> n instanceof TitledPane t && t.getText().equals("Bindings"))
.findFirst()
.orElseThrow();
group.setAnimated(false);
group.setExpanded(true);
var tabs = (TabPane) group.getContent();
tabs.getSelectionModel()
.select(
tabs.getTabs().stream()
.filter(t -> t.getText().equals("Discover targets"))
.findFirst()
.orElseThrow());
pane.applyCss();
pane.layout();
return null;
});
click(pane, "Discover bindings");
await(
() ->
fx(
() -> {
if (!((ComboBox<?>) pane.lookup("#binding-path")).getItems().isEmpty())
return true;
var message = ((Label) pane.lookup("#binding-status")).getText();
if (message.startsWith("Document changed")
|| message.startsWith("Build changed")) {
((Button)
pane.lookupAll(".button").stream()
.filter(
n ->
n instanceof Button b
&& b.getText().equals("Discover bindings"))
.findFirst()
.orElseThrow())
.fire();
}
if (message.startsWith("Discovery unavailable"))
throw new AssertionError(message);
return false;
}));
}
@SuppressWarnings("unchecked")
private void target(String path, String dir, String id, String property, String status)
throws Exception {
var prefix = path + " : ";
choose("binding-direction", dir);
await(
() ->
fx(
() ->
((ComboBox<?>) pane.lookup("#binding-path"))
.getItems().stream().anyMatch(x -> x.toString().startsWith(prefix))));
choose("binding-path", prefix);
await(
() ->
fx(
() -> {
var paths = (ComboBox<?>) pane.lookup("#binding-path");
var direction = (ComboBox<?>) pane.lookup("#binding-direction");
if (paths.getValue() == null
|| !paths.getValue().toString().startsWith(prefix)
|| !dir.equals(direction.getValue())) return false;
var table = (TableView<Target>) pane.lookup("#binding-targets");
var found =
table.getItems().stream()
.filter(
t ->
t.control().equals(id)
&& t.property().equals(property)
&& t.status().equals(status))
.findFirst();
found.ifPresent(t -> table.getSelectionModel().select(t));
return found.isPresent();
}));
step(path + " -> " + id + "." + property + " (" + dir + ") " + status);
}
private void applyAndReopen(
Project project, String form, int count, String id, String prop, String path, String dir)
throws Exception {
click(pane, "Use selected target");
if (!fx(
() ->
((TextField) pane.lookup("#direct-path")).getText().equals(path)
&& ((ComboBox<?>) pane.lookup("#direct-direction")).getValue().equals(dir)))
throw new AssertionError("Wrong binding");
click(pane, "Apply binding");
String declaration =
"control=\""
+ id
+ "\" property=\""
+ prop
+ "\" path=\""
+ path
+ "\" direction=\""
+ dir
+ "\"";
await(() -> source().contains(declaration));
click(pane, "Save");
await(() -> Files.readString(Path.of(file.getPath())).contains(declaration));
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(file);
return null;
});
open(project, form, count);
if (!source().contains(declaration)) throw new AssertionError("Binding was lost on reopen");
step("Applied, saved and reopened " + declaration);
}
private void preview(String example, String attempt) throws Exception {
choose("preview-example", example);
String label =
fx(
() ->
((de.neitzel.fxdesigner.workflow.DesignerWorkflow.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(state);
return ((ImageView) pane.lookup("#full-preview-image")).getImage() != null
&& state.contains(label);
}));
if (attempt.equals("import-collision"))
fx(
() -> {
ImageIO.write(
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
"png",
output.resolve("intellij.png").toFile());
return null;
});
Files.writeString(output.resolve("import-attempt"), attempt);
click(pane, "Interactive preview");
awaitTarget("result-" + attempt);
step(Files.readString(output.resolve("result-" + attempt)));
click(pane, "Stop preview");
}
}
@@ -0,0 +1,388 @@
package qualification;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.shape.SVGPath;
import javafx.stage.*;
import javax.imageio.ImageIO;
/** Acts on the actual controls in the interactive Archiver worker. */
public final class ManagementReadersTargetProbe {
public static void premain(String dir) {
if (System.getProperty("sun.java.command", "")
.startsWith("de.neitzel.fxdesigner.target.WorkerMain "))
Thread.ofPlatform().daemon().start(() -> Worker.run(Path.of(dir)));
}
private static final class Worker {
private static <T> T fx(Callable<T> action) throws Exception {
var task = new FutureTask<>(action);
Platform.runLater(task);
return task.get(10, TimeUnit.SECONDS);
}
private static void require(boolean value, String message) {
if (!value) throw new AssertionError(message);
}
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;
var attempt = Files.readString(dir.resolve("management-case"));
boolean management = attempt.startsWith("accounts-") || attempt.startsWith("trash-");
var root =
fx(
() -> {
shown.setWidth(management ? 900 : 920);
shown.setHeight(management ? 600 : 135);
var r = shown.getScene().getRoot();
r.applyCss();
r.layout();
return r;
});
String result =
fx(
() ->
switch (attempt) {
case "accounts-idle", "accounts-busy", "accounts-idle-edited" ->
accounts(root, attempt, dir);
case "trash-full", "trash-empty", "trash-full-edited" ->
trash(root, attempt, dir);
default -> reader(root, attempt, dir);
});
if (attempt.equals("accounts-idle")) {
fx(
() -> {
root.applyCss();
root.layout();
var display = (javafx.scene.text.Text) root.lookup("#details").lookup(".text");
require(
display.getText().contains("mail.example.invalid"),
"Account endpoint clipped: " + display.getText());
image(root, dir.resolve("management-accounts.png"));
return null;
});
}
if (attempt.equals("slides")) {
verifyPlayback(root);
result += " · automatischer Bildwechsel und Stillstand nach Pause";
}
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 ignored) {
}
}
}
private static void verifyPlayback(Node root) throws Exception {
// Begin on the last slide so one advance also exercises automatic wraparound.
fx(
() -> {
button(root, "next").fire();
button(root, "next").fire();
button(root, "playback").fire();
return null;
});
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(12);
while (!fx(() -> label(root, "reader-sample").startsWith("1 / 3"))) {
if (System.nanoTime() > deadline) throw new AssertionError("No automatic advance");
Thread.sleep(80);
}
fx(
() -> {
button(root, "playback").fire();
return null;
});
Thread.sleep(4500);
require(
fx(
() ->
label(root, "reader-sample").startsWith("1 / 3")
&& button(root, "playback").getAccessibleText().equals("Abspielen")),
"Advanced during pause");
}
private static Button button(Node root, String id) {
return (Button) Objects.requireNonNull(root.lookup("#" + id), id);
}
private static String label(Node root, String id) {
return ((Label) root.lookup("#" + id)).getText();
}
private static void enabled(Node root, String id, boolean expected) {
require(!button(root, id).isDisabled() == expected, id + " enabled=" + expected);
}
private static String accounts(Node root, String attempt, Path dir) throws Exception {
var list = (ListView<?>) root.lookup("#accounts");
require(
list.getItems().stream().map(Object::toString).toList().equals(List.of("Privat", "Büro")),
"Accounts");
if (attempt.endsWith("busy")) {
require(list.isDisabled() && label(root, "status").contains("läuft"), "Busy list/status");
for (var id :
List.of(
"create",
"configure",
"activate",
"fetch",
"verify",
"release",
"revoke",
"expire",
"close")) {
enabled(root, id, false);
button(root, id).fire();
}
require(label(root, "status").contains("läuft"), "Busy action ran");
return "Abruf läuft · alle neun Commands und Kontenauswahl gesperrt";
}
require(label(root, "details").contains("kein Serverprofil"), "Local details");
enabled(root, "configure", true);
enabled(root, "fetch", false);
list.getSelectionModel().select(1);
require(
label(root, "details").contains("mail.example.invalid")
&& label(root, "details").contains("30 Tage"),
"Office details");
if (attempt.endsWith("edited")) {
button(root, "configure").fire();
require(
label(root, "status").equals("Beispielaktion · CREATE · Büro"), "Remapped configure");
return "configure → create nach Wiederöffnen am Konto Büro ausgelöst";
}
button(root, "configure").fire();
require(label(root, "status").contains("CONFIGURE · Büro"), "Configure office");
button(root, "fetch").fire();
require(label(root, "status").contains("CONFIGURE · Büro"), "Disabled fetch executed");
for (var action :
List.of(
"activate", "fetch", "verify", "release", "expire", "revoke", "create", "close")) {
enabled(root, action, true);
button(root, action).fire();
require(
label(root, "status").contains(action.toUpperCase(Locale.ROOT) + " · Büro"), action);
}
enabled(root, "expire", false);
return "Privat ohne Serverprofil, Büro mit IMAP · Aktivierung, Abruf, Prüflauf, Freigabe,"
+ " Löschlauf und Widerruf geprüft";
}
private static String trash(Node root, String attempt, Path dir) throws Exception {
var items = (TableView<?>) root.lookup("#trash-items");
var files = (TableView<?>) root.lookup("#trash-files");
if (attempt.endsWith("empty")) {
require(
items.getItems().isEmpty()
&& files.getItems().isEmpty()
&& label(root, "summary").equals("0 Einträge · 0 Dateien"),
"Empty trash");
enabled(root, "trash-delete", false);
enabled(root, "trash-empty", false);
return "Leerer Papierkorb · beide Commands gesperrt";
}
require(label(root, "summary").equals("2 Einträge · 3 Dateien"), "Initial summary");
items.getSelectionModel().clearSelection();
require(files.getItems().isEmpty(), "Files without selection");
enabled(root, "trash-delete", false);
enabled(root, "trash-empty", true);
items.getSelectionModel().select(0);
require(
files.getItems().size() == 2
&& files.getItems().getFirst().toString().contains("Rechnung.pdf")
&& files.getItems().getLast().toString().contains("Lieferschein.md"),
"Folder file list");
enabled(root, "trash-delete", true);
items.getSelectionModel().select(1);
require(
files.getItems().size() == 3
&& files.getItems().getLast().toString().contains("Notiz.txt"),
"Multiple file list");
if (attempt.endsWith("edited")) {
button(root, "trash-delete").fire();
require(
label(root, "example-trash-action").equals("Wiederherstellen · Belege, Notiz.txt"),
"Restore selection");
require(
items.getItems().isEmpty() && files.getItems().isEmpty(), "Restored items retained");
return "delete → restoreSelection nach Wiederöffnen · Belege und Notiz.txt"
+ " wiederhergestellt";
}
image(root, dir.resolve("management-trash.png"));
items.getSelectionModel().clearAndSelect(1);
button(root, "trash-delete").fire();
require(
label(root, "example-trash-action").equals("Löschen · Notiz.txt")
&& label(root, "summary").equals("1 Einträge · 2 Dateien"),
"Delete selection");
button(root, "trash-empty").fire();
require(
label(root, "example-trash-action").equals("Leeren · Belege")
&& items.getItems().isEmpty()
&& files.getItems().isEmpty()
&& label(root, "summary").equals("0 Einträge · 0 Dateien"),
"Empty action");
enabled(root, "trash-empty", false);
enabled(root, "trash-delete", false);
return "0/1/2 ausgewählte Einträge · Dateilisten und Summary geprüft · Notiz gelöscht und"
+ " Ordner geleert";
}
private static String reader(Node root, String attempt, Path dir) throws Exception {
if (attempt.equals("attachment")) {
var pick = (ComboBox<?>) root.lookup("#example-attachments");
for (var id : List.of("open-attachment", "save-attachment")) enabled(root, id, false);
pick.getSelectionModel().selectFirst();
for (var id : List.of("open-attachment", "save-attachment")) {
enabled(root, id, true);
button(root, id).fire();
String verb = id.startsWith("open") ? "Geöffnet" : "Gespeichert";
require(
label(root, "attachment-result")
.equals(verb + " · Lieferschein.txt · LS-018 · Drei Archivkartons"),
id);
}
image(root, dir.resolve("reader-attachment.png"));
pick.getSelectionModel().clearSelection();
for (var id : List.of("open-attachment", "save-attachment")) enabled(root, id, false);
return "Ohne Auswahl gesperrt · Lieferschein.txt geöffnet und Sitzungskopie mit gleichem"
+ " Inhalt gespeichert";
}
var suffix =
switch (attempt) {
case "pdf" -> "-page";
case "epub" -> "-chapter";
case "images" -> "-image";
default -> "";
};
var back = button(root, "previous" + suffix);
var next = button(root, "next" + suffix);
var state = attempt.equals("images") ? "image-position" : "reader-sample";
var names =
switch (attempt) {
case "pdf" -> List.of("Deckblatt", "Rechnungspositionen", "Zahlungsziel");
case "epub" -> List.of("Ankunft", "Im Archiv", "Heimweg");
default -> List.of("Eingang.jpg", "Regal.jpg", "Ausgang.jpg");
};
for (int i = 0; i < 3; i++) {
require(
back.isDisabled() == (i == 0) && next.isDisabled() == (i == 2), "Boundaries at " + i);
require(label(root, state).equals((i + 1) + " / 3 · " + names.get(i)), label(root, state));
if (i == 2) break;
next.fire();
}
next.fire();
for (int i = 2; i >= 0; i--) {
require(
label(root, state).startsWith((i + 1) + " / 3") && back.isDisabled() == (i == 0),
"Return " + i);
back.fire();
}
switch (attempt) {
case "images" -> {
var svg = (SVGPath) back.getGraphic().lookup("SVGPath");
require(
"Bild zurück".equals(back.getAccessibleText())
&& "Bild zurück".equals(back.getTooltip().getText())
&& svg.getContent().startsWith("M1 8 Q8"),
"Saved accessible text / VIEW graphic");
image(root, dir.resolve("reader-icon.png"));
}
case "pdf" -> {
var page = (TextField) root.lookup("#page-number");
page.setText("3");
page.fireEvent(new ActionEvent());
require(
next.isDisabled()
&& page.getText().equals("3")
&& label(root, state).contains("Zahlungsziel"),
"Page entry");
page.setText("99");
page.fireEvent(new ActionEvent());
require(page.getText().equals("3"), "Out-of-range page");
((ChoiceBox<?>) root.lookup("#page-zoom")).getSelectionModel().select(3);
require(
((Label) root.lookup("#reader-sample")).getFont().getSize() == 24, "150 % page zoom");
}
case "epub" -> {
((ChoiceBox<?>) root.lookup("#chapters")).getSelectionModel().select(1);
require(label(root, state).contains("Im Archiv"), "Chapter choice");
var sample = (Label) root.lookup("#reader-sample");
button(root, "larger").fire();
require(sample.getFont().getSize() == 20, "Larger font");
button(root, "smaller").fire();
require(sample.getFont().getSize() == 18, "Smaller font");
}
case "slides" -> {
var play = button(root, "playback");
var playPath = ((SVGPath) play.getGraphic().lookup("SVGPath")).getContent();
require("Abspielen".equals(play.getAccessibleText()), "Play action");
play.fire();
require(
"Pause".equals(play.getAccessibleText())
&& !playPath.equals(((SVGPath) play.getGraphic().lookup("SVGPath")).getContent()),
"Pause action");
play.fire();
require(
"Abspielen".equals(play.getAccessibleText())
&& playPath.equals(((SVGPath) play.getGraphic().lookup("SVGPath")).getContent()),
"Restored Play");
}
}
if (!attempt.equals("images")) image(root, dir.resolve("reader-" + attempt + ".png"));
return switch (attempt) {
case "images" ->
"1 → 2 → 3 → 2 → 1 · Bildnamen, Grenzsperren, gespeichertes VIEW-Symbol und"
+ " Beschreibung geprüft";
case "pdf" -> "Seitennavigation und Grenzsperren · Eingabe Seite 3 · Zoom 150 %";
case "epub" ->
"Kapitelnavigation und Grenzsperren · Kapitel Im Archiv · Schrift 18 → 20 → 18";
default ->
"Bildnavigation und Grenzsperren · Abspielen → Pause → Abspielen mit wechselnder"
+ " Grafik";
};
}
private 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);
int[] pixels = new int[w * h];
img.getPixelReader()
.getPixels(0, 0, w, h, javafx.scene.image.PixelFormat.getIntArgbInstance(), pixels, 0, w);
out.setRGB(0, 0, w, h, pixels, 0, w);
ImageIO.write(out, "png", path.toFile());
}
}
}
@@ -0,0 +1,196 @@
package qualification;
import static qualification.WorkflowProbe.*;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.oracle.javafx.scenebuilder.kit.fxom.FXOMFxIdIndex;
import de.neitzel.fxdesigner.workflow.DesignerWorkflow.Example;
import java.nio.file.*;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javax.imageio.ImageIO;
/** Changes the draft via the registered inspector, then exercises its managed worker. */
public final class ManagementReadersWorkflowProbe extends FormWorkflowProbe {
private Project project;
void verify(Project project) throws Exception {
this.project = project;
management(
"MailControls", "accounts-idle", "accounts-busy", "configure", "configure", "create", 9);
management(
"TrashPane",
"trash-full",
"trash-empty",
"delete",
"deleteSelection",
"restoreSelection",
2);
open("ReaderNavigation");
attribute("symbol", "VIEW");
attribute("accessibleText", "Bild zurück");
reopen("ReaderNavigation", "accessibleText=\"Bild zurück\"");
build("reader-images");
interactive("reader-images", "images");
for (String[] reader :
new String[][] {
{"PdfToolbar", "pdf"},
{"EpubToolbar", "epub"},
{"SlideshowToolbar", "slides"},
{"AttachmentToolbar", "attachment"}
}) {
open(reader[0]);
String id = "reader-" + reader[1];
build(id);
interactive(id, reader[1]);
}
Files.writeString(output.resolve("SUCCESS.txt"), Files.readString(output.resolve("steps.txt")));
}
private void open(String name) throws Exception {
var path =
Path.of(project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui", name + ".fxml");
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
pane = openDesigner(project, file);
if (!source().contains("<?neitzel-model de.neitzel.archiver.ui."))
throw new AssertionError(name);
}
private void build(String id) throws Exception {
click(pane, "Form preview");
click(pane, "Build and Refresh");
await(
() ->
fx(
() ->
((ComboBox<?>) pane.lookup("#preview-example"))
.getItems().stream().anyMatch(item -> item.toString().contains(id))));
}
private void interactive(String id, String attempt) throws Exception {
choose("preview-example", id);
await(
() ->
fx(
() -> {
var 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);
var choice = (Example) ((ComboBox<?>) pane.lookup("#preview-example")).getValue();
return ((ImageView) pane.lookup("#full-preview-image")).getImage() != null
&& state.contains(choice.label());
}));
Files.writeString(output.resolve("management-case"), attempt);
click(pane, "Interactive preview");
String name = "result-" + attempt;
awaitTarget(name);
step(id + " · " + Files.readString(output.resolve(name)));
click(pane, "Stop preview");
}
private void reopen(String form, String saved) throws Exception {
click(pane, "Save");
await(() -> Files.readString(Path.of(file.getPath())).contains(saved));
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(file);
return null;
});
open(form);
if (!source().contains(saved)) throw new AssertionError("Reopened " + form);
}
private void commands(String control, String path, int count) throws Exception {
fx(
() -> {
var group =
(TitledPane)
pane.lookupAll(".titled-pane").stream()
.filter(n -> n instanceof TitledPane t && "Bindings".equals(t.getText()))
.findFirst()
.orElseThrow();
group.setExpanded(true);
var tabs = (TabPane) group.getContent();
tabs.getSelectionModel()
.select(
tabs.getTabs().stream()
.filter(t -> t.getText().equals("Command bindings"))
.findFirst()
.orElseThrow());
pane.applyCss();
pane.layout();
var list = (ListView<?>) pane.lookup("#command-bindings");
if (list.getItems().size() != count) throw new AssertionError(list.getItems());
for (int i = 0; i < count; i++) {
if (list.getItems().get(i).toString().startsWith(control + " ←"))
list.getSelectionModel().select(i);
}
if (!control.equals(((TextField) pane.lookup("#command-control")).getText())
|| !path.equals(((TextField) pane.lookup("#command-path")).getText()))
throw new AssertionError(control + " → " + path);
return null;
});
}
private void management(
String form,
String data,
String other,
String control,
String path,
String replacement,
int count)
throws Exception {
open(form);
build(data);
interactive(data, data);
interactive(other, other);
commands(control, path, count);
fx(
() -> {
((TextField) pane.lookup("#command-path")).setText(replacement);
return null;
});
click(pane, "Apply Command binding");
String edited = "control=\"" + control + "\" path=\"" + replacement + "\"";
await(() -> source().contains(edited));
reopen(form, edited);
commands(control, replacement, count);
if (form.equals("MailControls")) {
fx(
() -> {
ImageIO.write(
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
"png",
output.resolve("intellij.png").toFile());
return null;
});
}
build(data);
interactive(data, data + "-edited");
}
private void attribute(String name, String value) throws Exception {
fx(
() -> {
var kit = pane.kit().editor();
kit.getSelection().select(new FXOMFxIdIndex(kit.getFxomDocument()).lookup("previous"));
return null;
});
await(() -> fx(() -> pane.lookup("#component-property-" + name) != null));
fx(
() -> {
var field = (TextField) pane.lookup("#component-property-" + name);
field.setText(value);
field.fireEvent(new ActionEvent());
return null;
});
await(() -> source().contains(name + "=\"" + value + "\""));
}
}
@@ -0,0 +1,362 @@
package qualification;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.application.Platform;
import javafx.beans.value.*;
import javafx.event.ActionEvent;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import javax.imageio.ImageIO;
/** Acts on the actual controls in the interactive Archiver worker. */
public final class MediaLayoutGridTargetProbe {
public static void premain(String dir) {
if (System.getProperty("sun.java.command", "")
.startsWith("de.neitzel.fxdesigner.target.WorkerMain "))
Thread.ofPlatform().daemon().start(() -> Worker.run(Path.of(dir)));
}
private static final class Worker {
private static <T> T fx(Callable<T> action) throws Exception {
var task = new FutureTask<>(action);
Platform.runLater(task);
return task.get(10, TimeUnit.SECONDS);
}
private static void require(boolean value, String message) {
if (!value) throw new AssertionError(message);
}
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;
var attempt = Files.readString(dir.resolve("layout-case"));
fx(
() -> {
shown.setWidth(1180);
shown.setHeight(660);
return null;
});
await(
"Resized interactive preview",
() -> shown.getScene().getWidth() >= 1100 && shown.getScene().getHeight() >= 550);
var root =
fx(
() -> {
var node = shown.getScene().getRoot();
node.applyCss();
node.layout();
return node;
});
String result =
switch (attempt) {
case "offline" -> fx(() -> offline(root));
case "details" -> fx(() -> details(root, dir));
case "trash" -> fx(() -> trash(root, dir));
case "media" -> media(root, dir);
case "grid" -> fx(() -> grid(root, dir));
default -> throw new IllegalArgumentException(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 ignored) {
}
}
}
private static String offline(Node root) {
var media = (Button) root.lookup("#external-media-load");
require(
media.isDisabled() && media.getAccessibleText().equals("Belegbilder laden"),
"Offline: " + media.getAccessibleText());
require(media.getTooltip().getText().contains("Keine auflösbaren"), "Offline tooltip");
return "Rechnung ohne Medien · gespeicherter Aktionsname, Tooltip und gesperrter Button";
}
private static String details(Parent root, Path dir) throws Exception {
var tabs = (TabPane) root;
require(
tabs.getTabs().stream()
.map(Tab::getText)
.toList()
.equals(List.of("Tags", "Datei", "Belegprüfung")),
"Tab order");
var moved = tabs.getTabs().getLast();
tabs.getSelectionModel().select(moved);
root.applyCss();
root.layout();
var scroll = (ScrollPane) moved.getContent();
var box = (HBox) scroll.getContent();
var input = (TextField) box.lookup("#tag-input");
require(input != null && tabs.getTabs().getFirst().getContent() == null, "Moved HBox");
require(
((List<?>) input.getClass().getMethod("getSuggestionsSource").invoke(input))
.contains("Beleg geprüft"),
"Bound suggestions");
input.setText("Beleg geprüft");
input.fireEvent(new ActionEvent());
require(box.lookupAll(".tag-chip").size() == 2, "Moved tag handler and Repeat");
image(root, dir.resolve("details-moved.png"));
return "Dritter Tab → ScrollPane → ursprüngliche HBox · Vorschlagsquelle, onAction und beide"
+ " TagChips wirksam";
}
private static String trash(Parent root, Path dir) throws Exception {
var split = (SplitPane) root.lookup(".split-pane");
require(
split.getItems().size() == 3
&& "trash-items".equals(split.getItems().getFirst().getId())
&& split.getItems().get(1) instanceof Label l
&& "Dateien der Auswahl".equals(l.getText())
&& "trash-files".equals(split.getItems().getLast().getId()),
"SplitPane order");
require(
((TableView<?>) split.getItems().getLast()).getItems().size() == 2,
"Selected folder files");
image(root, dir.resolve("trash-split.png"));
return "Beschriftung an Position 2 zwischen beiden Tabellen · zwei Dateien im markierten"
+ " Ordner";
}
private static void await(String name, Callable<Boolean> test) throws Exception {
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(14);
while (System.nanoTime() < end) {
if (fx(test)) return;
Thread.sleep(60);
}
throw new AssertionError(name);
}
private static Object get(Object target, String method) throws Exception {
return target.getClass().getMethod(method).invoke(target);
}
private static String media(Parent root, Path dir) throws Exception {
var group =
fx(
() ->
root.lookupAll(".tab-pane").stream()
.map(TabPane.class::cast)
.filter(
p ->
p.getTabs().stream()
.anyMatch(t -> t.getText().equals("Rechnung.html")))
.findFirst()
.orElseThrow());
fx(
() -> {
require(
root instanceof BorderPane p
&& p.getLeft() instanceof Label l
&& l.getText().equals("Medienprüfung")
&& p.getCenter().lookup("#dockPane") != null,
"BorderPane and docking");
return null;
});
var invoice = select(group, "Rechnung.html");
fx(() -> offline(invoice));
var delivery = select(group, "Lieferschein.html");
var viewer = fx(() -> delivery.lookup("#html-document"));
var button = fx(() -> (Button) delivery.lookup("#external-media-load"));
var blockedDuringLoad = new AtomicBoolean();
fx(
() -> {
require(
((Label) root.lookup("#status")).getText().equals("Lokale Bildanfragen · 0"),
"Request before grant");
require(
!button.isDisabled()
&& button.getAccessibleText().equals("Belegbilder laden")
&& button.getTooltip().getText().contains("Belegbilder laden")
&& button.getTooltip().getText().contains("Kontaktiert die Bildserver"),
"Delivery action");
var loading = (ObservableBooleanValue) get(viewer, "loadingProperty");
loading.addListener(
(obs, old, active) -> {
if (active && button.isDisabled()) blockedDuringLoad.set(true);
});
button.fire();
return null;
});
await(
"Granted image and request",
() -> {
var engine = get(viewer.lookup("WebView"), "getEngine");
var pixels =
engine
.getClass()
.getMethod("executeScript", String.class)
.invoke(engine, "document.images.length ? document.images[0].naturalWidth : 0");
return ((Label) root.lookup("#status")).getText().equals("Lokale Bildanfragen · 1")
&& !button.isDisabled()
&& ((Number) pixels).intValue() == 24;
});
fx(
() -> {
require(
blockedDuringLoad.get()
&& (boolean) get(viewer, "isExternalImagesAllowed")
&& button.getAccessibleText().equals("Externe Medien erneut laden"),
"Loading / reload states");
image(root, dir.resolve("media-granted.png"));
return null;
});
var other = select(group, "Rechnung.html");
fx(
() -> {
offline(other);
require(
!(boolean) get(other.lookup("#html-document"), "isExternalImagesAllowed"),
"Invoice inherited grant");
return null;
});
select(group, "Lieferschein.html");
fx(
() -> {
require(
!button.isDisabled() && button.getAccessibleText().contains("erneut"),
"Return to delivery");
button.fire();
return null;
});
await(
"Reload reached loopback",
() ->
((Label) root.lookup("#status")).getText().equals("Lokale Bildanfragen · 2")
&& !button.isDisabled());
return "BorderPane.left mit intaktem Docking · HTTP-Anfragen 0 → 1 → 2 · Bildbreite 24 px,"
+ " Ladesperre, erneutes Laden und tabbezogene Freigabe geprüft";
}
private static Node select(TabPane tabs, String title) throws Exception {
return fx(
() -> {
var tab =
tabs.getTabs().stream()
.filter(t -> title.equals(t.getText()))
.findFirst()
.orElseThrow();
tabs.getSelectionModel().select(tab);
tabs.applyCss();
tabs.layout();
return tab.getContent();
});
}
private static String grid(Parent root, Path dir) throws Exception {
Node grid = root.lookup("#grid");
var setup = get(grid, "snapshotSetup");
require(
get(setup, "definitionId").equals("archiver-pruefung")
&& get(setup, "definitionVersion").equals(2),
"Setup identity");
var cols = (List<?>) get(setup, "columns");
var order = new ArrayList<String>();
for (var col : cols) order.add((String) get(col, "id"));
require(order.get(1).equals("folder"), "Column position");
Collections.swap(order, 0, 1);
try {
grid.getClass().getMethod("setColumnOrder", List.class).invoke(grid, order);
throw new AssertionError("Fixed column displaced");
} catch (InvocationTargetException ex) {
require(
ex.getCause() instanceof IllegalArgumentException
&& ex.getCause().getMessage().contains("Fixed"),
"Fixed position check");
}
var heading =
grid.lookupAll(".group-heading").stream()
.map(Button.class::cast)
.filter(b -> b.getText().contains("Posteingang"))
.findFirst()
.orElseThrow();
require(
grid.lookupAll(".group-heading").stream()
.map(Button.class::cast)
.anyMatch(b -> b.getText().contains("Rechnungen")),
"Other group");
image(root, dir.resolve("grid-group.png"));
heading.fire();
var grouping = get(get(grid, "snapshotSetup"), "grouping");
var choice = ((List<?>) get(grouping, "choices")).getFirst();
var segment = ((List<?>) get(get(choice, "path"), "segments")).getFirst();
require(
get(segment, "columnId").equals("folder")
&& get(get(segment, "value"), "value").equals("Post"),
"Changed group key");
for (String id : List.of("archive-folder", "archiver-pruefung")) {
var fields = setup.getClass().getRecordComponents();
Object[] values = new Object[fields.length];
for (int i = 0; i < fields.length; i++)
values[i] =
switch (fields[i].getName()) {
case "definitionId" -> id;
case "definitionVersion" -> 1;
default -> fields[i].getAccessor().invoke(setup);
};
var old =
setup
.getClass()
.getConstructor(
Arrays.stream(fields).map(RecordComponent::getType).toArray(Class<?>[]::new))
.newInstance(values);
grid.getClass().getMethod("restoreSetup", setup.getClass()).invoke(grid, old);
var state = ((ObservableValue<?>) get(grid, "stateProperty")).getValue();
var error = (Throwable) get(state, "error");
require(
error != null
&& error
.getMessage()
.contains(
id.equals("archive-folder")
? "another grid definition"
: "Missing definition migration"),
"Wrong setup restore " + error);
}
return "Setup archiver-pruefung/2 · fremde ID und alte Version abgewiesen · folder fest an"
+ " Index 1 · Posteingang sichtbar, Gruppenschlüssel Post";
}
private 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);
int[] pixels = new int[w * h];
img.getPixelReader()
.getPixels(0, 0, w, h, javafx.scene.image.PixelFormat.getIntArgbInstance(), pixels, 0, w);
out.setRGB(0, 0, w, h, pixels, 0, w);
ImageIO.write(out, "png", path.toFile());
}
}
}
@@ -0,0 +1,192 @@
package qualification;
import static qualification.WorkflowProbe.*;
import com.intellij.openapi.project.Project;
import java.nio.file.*;
import java.util.*;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.*;
import javax.imageio.ImageIO;
/** Edits original Archiver forms in the registered IntelliJ designer. */
public final class MediaLayoutGridWorkflowProbe extends DeclarationWorkflowProbe {
void verify(Project project) throws Exception {
this.project = project;
open("HtmlDocument");
controls(true);
choose("form-control", "HtmlViewer #article");
set("mediaLoadText", "Belegbilder laden", "mediaLoadText=\"Belegbilder laden\"");
reopen("HtmlDocument", "Belegbilder laden");
build("html-invoice");
interactive("html-invoice", "offline");
details();
trash();
window();
folder();
Files.writeString(output.resolve("SUCCESS.txt"), Files.readString(output.resolve("steps.txt")));
}
private void insert(String type, String slot, int position, String id) throws Exception {
choose("form-palette", type);
choose("form-destination", slot);
if (position >= 0)
fx(
() -> {
((Spinner<Integer>) pane.lookup("#form-position")).getValueFactory().setValue(position);
return null;
});
String before = source();
click(pane, "Insert control");
edited(before, "fx:id=\"" + id + "\"");
}
private void reject(String type, String slot, String reason) throws Exception {
choose("form-palette", type);
choose("form-destination", slot);
String before = source();
click(pane, "Insert control");
if (!before.equals(source())
|| !fx(() -> ((Label) pane.lookup("#form-message")).getText()).contains(reason))
throw new AssertionError("Expected " + reason);
}
private void history(String before, String after) throws Exception {
click(pane, "Undo");
await(() -> source().equals(before));
click(pane, "Redo");
await(() -> source().equals(after));
fx(pane::flush).toCompletableFuture().get();
}
private List<String> declarations() throws Exception {
return source()
.lines()
.map(String::trim)
.filter(
l ->
l.startsWith("<DirectBinding ")
|| l.startsWith("<CommandBinding ")
|| l.startsWith("<Repeat "))
.toList();
}
private void details() throws Exception {
open("DocumentDetails");
controls(true);
var original = declarations();
reject("Label", "TabPane [", "TabPane.tabs accepts Tab");
reject("Label", "ScrollPane [", "Occupied");
insert("Tab", "TabPane [", -1, "tab");
choose("form-control", "Tab #tab");
set("text", "Belegprüfung", "text=\"Belegprüfung\"");
insert("ScrollPane", "Tab #tab / content", 0, "scrollPane");
choose("form-control", "HBox [");
choose("form-destination", "ScrollPane #scrollPane / content");
String before = source();
click(pane, "Move to destination");
edited(before, "onAction=\"#addTag\"");
history(before, source());
reopen("DocumentDetails", "Belegprüfung");
if (!original.equals(declarations())) throw new AssertionError("Moved bindings");
build("details-invoice");
interactive("details-invoice", "details");
}
private void trash() throws Exception {
open("TrashPane");
controls(true);
insert("Label", "SplitPane [", 1, "label");
choose("form-control", "Label #label");
set("text", "Dateien der Auswahl", "text=\"Dateien der Auswahl\"");
reopen("TrashPane", "Dateien der Auswahl");
build("trash-full");
interactive("trash-full", "trash");
}
private void window() throws Exception {
open("ArchiveWindow");
controls(true);
String left =
fx(
() ->
((ComboBox<?>) pane.lookup("#form-destination"))
.getItems().stream()
.map(Object::toString)
.filter(v -> v.startsWith("BorderPane [") && v.endsWith(" / left"))
.findFirst()
.orElseThrow());
String owner = left.substring(0, left.lastIndexOf(" / "));
for (String region : List.of("center", "top", "bottom", "left", "right")) {
choose("form-destination", owner + " / " + region);
}
reject("Label", owner + " / center", "Occupied");
insert("Label", left, 0, "label");
choose("form-control", "Label #label");
set("text", "Medienprüfung", "text=\"Medienprüfung\"");
reopen("ArchiveWindow", "Medienprüfung");
build("archive-window-media");
interactive("archive-window-media", "media");
}
private void folder() throws Exception {
open("FolderTab");
inspector(true);
var original = declarations();
select("DataGrid", "grid");
applySetting("setupId", "archiver-pruefung");
applySetting("setupVersion", "2");
for (var pair :
List.of(List.of("setupId", "archiver-pruefung"), List.of("setupVersion", "2"))) {
String before = source();
combo("declaration-property", pair.getFirst());
fx(
() -> {
((ComboBox<?>) pane.lookup("#declaration-value")).getEditor().clear();
return null;
});
click(pane, "Apply setting");
await(() -> !source().contains(pair.getFirst() + "=\""));
click(pane, "Undo");
await(() -> source().equals(before));
}
applySetting("groupBy", "folder");
select("DataGridColumn", "folder");
applySetting("fixedPosition", "1");
combo("declaration-property", "groupLabels");
fx(
() -> {
((ComboBox<?>) pane.lookup("#group-label-key")).getEditor().setText("Post");
((TextField) pane.lookup("#group-label-text")).setText("Posteingang");
return null;
});
String before = source();
edit("Set group label", "Post=\"Posteingang\"");
String grouped = source();
history(before, grouped);
combo("declaration-property", "groupLabels");
choose("group-label-key", "Post");
click(pane, "Remove group label");
await(() -> !source().contains("Post=\"Posteingang\""));
click(pane, "Undo");
await(() -> source().equals(grouped));
reopen("FolderTab", "Posteingang");
if (!original.equals(declarations())) throw new AssertionError("Grid bindings");
inspector(true);
select("DataGridColumn", "folder");
combo("declaration-property", "groupLabels");
if (!fx(() -> ((TextField) pane.lookup("#group-label-text")).getText().equals("Posteingang")))
throw new AssertionError("Reopened mapping");
fx(
() -> {
ImageIO.write(
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
"png",
output.resolve("intellij.png").toFile());
return null;
});
build("archive-folder");
interactive("archive-folder", "grid");
}
}
+8 -3
View File
@@ -26,10 +26,15 @@ p.add_argument("--archiver", type=Path, help="Qualify ArchiveWindow.fxml in a di
forms = p.add_mutually_exclusive_group()
forms.add_argument("--connection-form", action="store_true", help="Qualify the Archiver connection form")
forms.add_argument("--grid-docking", type=Path, metavar="REFERENCE_FXML", help="Qualify the Archiver grid, dock layout and the supplied reference workspace")
forms.add_argument("--dock-rules", action="store_true", help="Verify group minima, split directions and persistence in the Archiver")
forms.add_argument("--media-layout-grid", action="store_true", help="Verify media permissions, form destinations and grid setups in the Archiver")
forms.add_argument("--management-readers", action="store_true", help="Verify account and trash commands and the five reader toolbars")
forms.add_argument("--folder-actions", action="store_true", help="Check visual event references, folder search, selection and display profiles")
forms.add_argument("--import-form", action="store_true", help="Check generic binding types and the Archiver import collision")
forms.add_argument("--document-tabs", action="store_true", help="Qualify the production Archiver HTML document tabs")
forms.add_argument("--saved-document", action="store_true", help="Open the Archiver saved HTML and tag example")
args = p.parse_args()
if (args.connection_form or args.grid_docking or args.saved_document or args.document_tabs) and not args.archiver:
if (args.connection_form or args.grid_docking or args.saved_document or args.document_tabs or args.import_form or args.folder_actions or args.management_readers or args.media_layout_grid or args.dock_rules) and not args.archiver:
p.error("Selecting an Archiver view requires --archiver")
if args.repeat < 1:
p.error("--repeat must be positive")
@@ -41,7 +46,7 @@ modes = ("classpath",) if args.archiver else (("classpath", "modulepath") if arg
for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode in modes):
crashes = NativeCrashGuard(ROOT)
launch = subprocess.run([sys.executable, ROOT / "scripts/run-fixture-host.py", "intellij",
"--check", *(["--document-tabs"] if args.document_tabs else []), *(["--saved-document"] if args.saved_document else []), *(["--grid-docking", str(args.grid_docking.resolve())] if args.grid_docking else []), *(["--connection-form"] if args.connection_form else []), *(["--archiver", str(args.archiver.resolve())] if args.archiver else []), "--mode", mode, "--java-home", args.java_home,
"--check", *(["--dock-rules"] if args.dock_rules else []), *(["--media-layout-grid"] if args.media_layout_grid else []), *(["--management-readers"] if args.management_readers else []), *(["--folder-actions"] if args.folder_actions else []), *(["--import-form"] if args.import_form else []), *(["--document-tabs"] if args.document_tabs else []), *(["--saved-document"] if args.saved_document else []), *(["--grid-docking", str(args.grid_docking.resolve())] if args.grid_docking else []), *(["--connection-form"] if args.connection_form else []), *(["--archiver", str(args.archiver.resolve())] if args.archiver else []), "--mode", mode, "--java-home", args.java_home,
"--target-java-home", args.target_java_home, "--idea-home", args.idea_home],
cwd=ROOT, text=True, capture_output=True, timeout=60)
if launch.returncode:
@@ -85,7 +90,7 @@ for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode i
shutil.copyfile(base / "intellij.png", output / (mode + ".png"))
(evidence / "proof.json").write_text(json.dumps(proof, indent=2) + "\n")
finally:
for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log", "steps.txt", "target-error.txt", "preview-restored.png", "imap.png", "jmap.png", "invoice.png", "delivery.png", "saved-document-result", "saved-bindings.fxml", "binding-article.png", "binding-dynamic.png", "tags-Pr.png", "tags-Re.png", "tags-Li.png", "document-tabs-result", "rechnung-tab.png", "lieferschein-tab.png", "rechnung-tab-tags.png", "lieferschein-tab-tags.png", "folder.png", "right.png", "bottom.png", "result-folder", "result-right", "result-bottom", "intellij.png"):
for name in ("dock-horizontal.png", "dock-vertical.png", "dock-empty-kept.png", "dock-empty-removed.png", "media-granted.png", "details-moved.png", "trash-split.png", "grid-group.png", "reader-pdf.png", "reader-epub.png", "reader-slides.png", "reader-attachment.png", "management-accounts.png", "management-trash.png", "reader-icon.png", "folder-events.png", "folder-search.png", "folder-profile.png", "result-folder-actions", "result-detail-action", "details-invoice-tags.png", "details-delivery-tags.png", "details-invoice.png", "details-delivery.png", "details-readonly.png", "details-busy.png", "html-invoice.png", "html-delivery.png", "rechnung-zwei-tags.png", "import-collision.png", "import-accepted.png", "result-import-free", "result-import-busy", "result-import-collision", "result-import-grid", "SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log", "steps.txt", "target-error.txt", "preview-restored.png", "imap.png", "jmap.png", "invoice.png", "delivery.png", "saved-document-result", "saved-bindings.fxml", "binding-article.png", "binding-dynamic.png", "tags-Pr.png", "tags-Re.png", "tags-Li.png", "document-tabs-result", "rechnung-tab.png", "lieferschein-tab.png", "rechnung-tab-tags.png", "lieferschein-tab-tags.png", "folder.png", "right.png", "bottom.png", "result-folder", "result-right", "result-bottom", "intellij.png"):
if (base / name).exists():
shutil.copyfile(base / name, evidence / name)
workers = descendant_workers(pid)
+43 -2
View File
@@ -22,10 +22,15 @@ p.add_argument("--archiver", type=Path, help="Use a disposable copy of the Archi
forms = p.add_mutually_exclusive_group()
forms.add_argument("--connection-form", action="store_true", help="Open and qualify the Archiver connection form")
forms.add_argument("--grid-docking", type=Path, metavar="REFERENCE_FXML", help="Qualify the Archiver grid, dock layout and the supplied reference workspace")
forms.add_argument("--dock-rules", action="store_true", help="Verify group minima, split directions and persistence in the Archiver")
forms.add_argument("--media-layout-grid", action="store_true", help="Verify media permissions, form destinations and grid setups in the Archiver")
forms.add_argument("--management-readers", action="store_true", help="Verify account and trash commands and the five reader toolbars")
forms.add_argument("--folder-actions", action="store_true", help="Check visual event references, folder search, selection and display profiles")
forms.add_argument("--import-form", action="store_true", help="Check generic binding types and the Archiver import collision")
forms.add_argument("--document-tabs", action="store_true", help="Qualify the production Archiver HTML document tabs")
forms.add_argument("--saved-document", action="store_true", help="Open the Archiver saved HTML and tag example")
args = p.parse_args()
if (args.connection_form or args.grid_docking or args.saved_document or args.document_tabs) and not args.archiver:
if (args.connection_form or args.grid_docking or args.saved_document or args.document_tabs or args.import_form or args.folder_actions or args.management_readers or args.media_layout_grid or args.dock_rules) and not args.archiver:
p.error("Selecting an Archiver view requires --archiver")
base = Path(tempfile.mkdtemp(prefix="neitzel-designer-host-")).resolve()
project = base / "project"
@@ -36,10 +41,34 @@ if args.archiver:
subprocess.run([sys.executable, ROOT / "scripts/configure-library-example.py", "--project", project,
"--target-java-home", args.target_java_home], check=True)
view = "ConnectionForm" if args.connection_form else "ArchiveWindow"
if args.media_layout_grid:
view = "HtmlDocument"
if args.management_readers:
view = "MailControls"
if args.folder_actions:
view = "DocumentDetails" if args.check else "FolderTab"
if args.document_tabs and args.check:
view = "DocumentTag"
if args.grid_docking:
view = "FolderTab"
shutil.copyfile(args.grid_docking, project / "src/main/resources/ReferenceWorkspace.fxml")
file = project / f"src/main/resources/de/neitzel/archiver/ui/{view}.fxml"
if args.import_form:
file = file.with_name("ConnectionForm.fxml")
if args.check:
# Author two shipped bindings again in the disposable copy. One deliberately
# untyped selector exercises the diagnostic without changing the product form.
for form, declaration in [
(file.with_name("ImportForm.fxml"), '<DirectBinding control="folders" property="value" path="folder" direction="both"/>'),
(file.with_name("FolderTab.fxml"), '<DirectBinding control="grid" property="items" path="rows" direction="view"/>'),
]:
source = form.read_text()
if source.count(declaration) != 1:
raise ValueError(f"Expected the shipped binding in {form.name}")
source = "".join(line for line in source.splitlines(keepends=True) if line.strip() != declaration)
if form.name == "FolderTab.fxml":
source = source.replace("</VBox>", '<ComboBox fx:id="untypedPick" visible="false" managed="false"/></VBox>')
form.write_text(source)
if args.saved_document:
file = project / "src/designer/resources/de/neitzel/archiver/preview/SavedDocument.fxml"
if args.check:
@@ -81,14 +110,26 @@ else:
suite = "Connection"
elif args.grid_docking:
suite = "GridDock"
elif args.dock_rules:
suite = "DockRules"
elif args.media_layout_grid:
suite = "MediaLayoutGrid"
elif args.management_readers:
suite = "ManagementReaders"
elif args.folder_actions:
suite = "FolderActions"
elif args.import_form:
suite = "Import"
elif args.document_tabs:
suite = "DocumentTabs"
elif args.saved_document:
suite = "SavedDocument"
probe = f"{suite}WorkflowProbe" if args.archiver else "WorkflowProbe"
files = [sources / "WorkflowProbe.java"]
if args.connection_form or args.saved_document or args.document_tabs:
if args.connection_form or args.saved_document or args.document_tabs or args.import_form or args.folder_actions or args.management_readers or args.media_layout_grid or args.dock_rules:
files.append(sources / "FormWorkflowProbe.java")
if args.media_layout_grid or args.dock_rules:
files.append(sources / "DeclarationWorkflowProbe.java")
if args.archiver:
files.append(sources / f"{probe}.java")
target_probe = f"{suite}TargetProbe"