Edit and exercise Archiver CommandBindings in the IntelliJ designer

This commit is contained in:
2026-11-24 14:42:35 +01:00
parent 54e202014e
commit 98d37c6c3d
38 changed files with 1304 additions and 190 deletions
+13
View File
@@ -66,6 +66,19 @@ Qualify the registered editor and loaded JavaFX natives in real disposable IDE w
python3 scripts/check-ide-host.py --java-home "$JAVA_HOME" --target-java-home "$TARGET_JAVA_HOME" --idea-home "$IDEA_HOME" python3 scripts/check-ide-host.py --java-home "$JAVA_HOME" --target-java-home "$TARGET_JAVA_HOME" --idea-home "$IDEA_HOME"
``` ```
### Archiver in IntelliJ
Build the [pinned NeitzelLib snapshot](docs/runtime/neitzellib-baseline.md), then build the Designer modules and plugin with the bootstrap command above. Archiver includes its example in the `designer-preview` Maven profile. To open an isolated IntelliJ instance with a project copy and the built plugin, run from this checkout with the same Maven environment:
```sh
python3 scripts/run-fixture-host.py intellij --archiver ../Archiver \
--idea-home "$IDEA_HOME" --java-home "$JAVA_HOME" --target-java-home "$JAVA_HOME"
```
Open `ArchiveWindow.fxml` in **Neitzel Designer**, choose **Build and Refresh** and start **Interactive preview** with **Beispielarchiv**. The open menu command enables the trash button. Under **Bindings → Command bindings** select `open`, change its path to `openReadOnly`, apply and restart the preview. The status bar identifies the read-only example. **Discover / Validate Commands** lists public getters returning a NeitzelLib `Command`, including the Command exposed by an `AsyncCommand`. The Problems view navigates to an invalid declaration. To repeat the automated acceptance, use the same arguments with `python3 scripts/check-ide-host.py --archiver ../Archiver` (omit the `intellij` positional argument).
For an existing Archiver checkout, install the built plugin ZIP and create the ignored local JDK and worker mappings once with `python3 scripts/configure-library-example.py --project ../Archiver --target-java-home "$JAVA_HOME"`. Launch the IDE with access to the Maven repository containing the qualified snapshots.
The [save/startup reliability follow-up](docs/ide-host-reliability.md) covers queued IntelliJ VFS writes and host-revision/validation races, including repeated registered module-path qualification. Add `--mode modulepath --repeat 3` to the IDE runner to repeat that gate. The [save/startup reliability follow-up](docs/ide-host-reliability.md) covers queued IntelliJ VFS writes and host-revision/validation races, including repeated registered module-path qualification. Add `--mode modulepath --repeat 3` to the IDE runner to repeat that gate.
Worker startup cancellation and ready-preview cleanup are covered by the [native lifecycle regression](docs/native-worker-lifecycle.md); host checks also reject new native JVM crash reports. Worker startup cancellation and ready-preview cleanup are covered by the [native lifecycle regression](docs/native-worker-lifecycle.md); host checks also reject new native JVM crash reports.
@@ -4,6 +4,26 @@ import java.util.*;
/** Non-constructing target metadata; compatibility is computed by the target type system. */ /** Non-constructing target metadata; compatibility is computed by the target type system. */
public record BindingMetadata( public record 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) {
public BindingMetadata(
String model, String model,
String path, String path,
String direction, String direction,
@@ -21,6 +41,28 @@ public record BindingMetadata(
List<RepeatOption> tableCollections, List<RepeatOption> tableCollections,
List<RepeatOption> tableRows, List<RepeatOption> tableRows,
List<RepeatOption> tableColumns) { List<RepeatOption> tableColumns) {
this(
model,
path,
direction,
attributes,
targets,
diagnostics,
converters,
problems,
controller,
viewModel,
computed,
collections,
components,
panes,
tableCollections,
tableRows,
tableColumns,
List.of(),
List.of());
}
public BindingMetadata( public BindingMetadata(
String model, String model,
String path, String path,
@@ -160,6 +202,8 @@ public record BindingMetadata(
tableCollections = List.copyOf(tableCollections); tableCollections = List.copyOf(tableCollections);
tableRows = List.copyOf(tableRows); tableRows = List.copyOf(tableRows);
tableColumns = List.copyOf(tableColumns); tableColumns = List.copyOf(tableColumns);
commandPaths = List.copyOf(commandPaths);
commandTargets = List.copyOf(commandTargets);
if (!Set.of("view", "model", "both").contains(direction)) if (!Set.of("view", "model", "both").contains(direction))
throw new IllegalArgumentException("Invalid direction"); throw new IllegalArgumentException("Invalid direction");
} }
@@ -167,6 +211,8 @@ public record BindingMetadata(
public Map<String, String> encode() { public Map<String, String> encode() {
var m = new TreeMap<String, String>(); var m = new TreeMap<String, String>();
m.put("format", "5"); m.put("format", "5");
encodeStrings(m, "commands", commandPaths);
encodeStrings(m, "commandTargets", commandTargets);
encodeOptions(m, "rc", collections); encodeOptions(m, "rc", collections);
encodeOptions(m, "rt", components); encodeOptions(m, "rt", components);
encodeOptions(m, "rp", panes); encodeOptions(m, "rp", panes);
@@ -228,6 +274,17 @@ public record BindingMetadata(
return m; return m;
} }
private static void encodeStrings(Map<String, String> fields, String key, List<String> values) {
fields.put(key, Integer.toString(values.size()));
for (int i = 0; i < values.size(); i++) fields.put(key + "." + i, values.get(i));
}
private static List<String> decodeStrings(Map<String, String> fields, String key) {
return java.util.stream.IntStream.range(0, count(fields, key))
.mapToObj(i -> field(fields, key + "." + i))
.toList();
}
private static void encodeOptions( private static void encodeOptions(
Map<String, String> m, String prefix, List<RepeatOption> values) { Map<String, String> m, String prefix, List<RepeatOption> values) {
m.put(prefix, "" + values.size()); m.put(prefix, "" + values.size());
@@ -266,6 +323,7 @@ public record BindingMetadata(
} }
public static BindingMetadata decode(Map<String, String> m) { public static BindingMetadata decode(Map<String, String> m) {
boolean commands = m.containsKey("commands");
if (!"5".equals(field(m, "format"))) if (!"5".equals(field(m, "format")))
throw new IllegalArgumentException("Unsupported binding metadata"); throw new IllegalArgumentException("Unsupported binding metadata");
var a = new ArrayList<Attribute>(); var a = new ArrayList<Attribute>();
@@ -333,6 +391,8 @@ public record BindingMetadata(
decodeOptions(m, "rp"), decodeOptions(m, "rp"),
decodeOptions(m, "tc"), decodeOptions(m, "tc"),
decodeOptions(m, "tr"), decodeOptions(m, "tr"),
decodeOptions(m, "ta")); decodeOptions(m, "ta"),
commands ? decodeStrings(m, "commands") : List.of(),
commands ? decodeStrings(m, "commandTargets") : List.of());
} }
} }
@@ -11,11 +11,13 @@ final class BindingDocument {
enum Kind { enum Kind {
DIRECT, DIRECT,
COMPUTED, COMPUTED,
COMMAND,
REPEAT; REPEAT;
String element() { String element() {
return switch (this) { return switch (this) {
case DIRECT -> "DirectBinding"; case DIRECT -> "DirectBinding";
case COMMAND -> "CommandBinding";
case COMPUTED -> "ComputedBinding"; case COMPUTED -> "ComputedBinding";
case REPEAT -> "Repeat"; case REPEAT -> "Repeat";
}; };
@@ -54,8 +56,7 @@ final class BindingDocument {
if (!values.pane().isEmpty()) if (!values.pane().isEmpty())
return values.pane() + " ← " + values.collection() + " (" + values.component() + ")"; return values.pane() + " ← " + values.collection() + " (" + values.component() + ")";
return values.control() return values.control()
+ "." + (values.property().isEmpty() ? "" : "." + values.property())
+ values.property()
+ " ← " + " ← "
+ (values.method().isEmpty() ? values.path() : values.method()); + (values.method().isEmpty() ? values.path() : values.method());
} }
@@ -214,6 +215,14 @@ final class BindingDocument {
private boolean conflicts(Element e, Values value) { private boolean conflicts(Element e, Values value) {
if (kind == Kind.REPEAT) if (kind == Kind.REPEAT)
return binding(e, "Repeat") && e.getAttribute("pane").equals(value.pane()); return binding(e, "Repeat") && e.getAttribute("pane").equals(value.pane());
if (e.getAttribute("control").equals(value.control())) {
if (kind == Kind.COMMAND)
return binding(e, "CommandBinding")
|| ((binding(e, "DirectBinding") || binding(e, "ComputedBinding"))
&& Set.of("disable", "onAction").contains(e.getAttribute("property")));
if (binding(e, "CommandBinding"))
return Set.of("disable", "onAction").contains(value.property());
}
return (binding(e, "DirectBinding") || binding(e, "ComputedBinding")) return (binding(e, "DirectBinding") || binding(e, "ComputedBinding"))
&& e.getAttribute("control").equals(value.control()) && e.getAttribute("control").equals(value.control())
&& e.getAttribute("property").equals(value.property()); && e.getAttribute("property").equals(value.property());
@@ -228,8 +237,11 @@ final class BindingDocument {
List<Replacement> write(Integer index, Values value, boolean replaceConflicts) { List<Replacement> write(Integer index, Values value, boolean replaceConflicts) {
if (kind == Kind.REPEAT && value.pane().isBlank()) if (kind == Kind.REPEAT && value.pane().isBlank())
throw new IllegalArgumentException("Choose a pane"); throw new IllegalArgumentException("Choose a pane");
if (kind != Kind.REPEAT && (value.control().isBlank() || value.property().isBlank())) if (kind != Kind.REPEAT
&& (value.control().isBlank() || (kind != Kind.COMMAND && value.property().isBlank())))
throw new IllegalArgumentException("Choose a control and property"); throw new IllegalArgumentException("Choose a control and property");
if (kind == Kind.COMMAND && (!qualifiedName(value.path()) || value.path().contains(".")))
throw new IllegalArgumentException("Choose a simple Command path");
Element original = index == null ? null : entry(index); Element original = index == null ? null : entry(index);
if (original != null && hasElementChildren(original)) if (original != null && hasElementChildren(original))
throw new IllegalArgumentException( throw new IllegalArgumentException(
@@ -256,6 +268,8 @@ final class BindingDocument {
value.component(), value.component(),
"collection", "collection",
value.collection()) value.collection())
: kind == Kind.COMMAND
? Map.of("control", value.control(), "path", value.path())
: kind == Kind.COMPUTED : kind == Kind.COMPUTED
? Map.of( ? Map.of(
"control", "control",
@@ -303,6 +317,15 @@ final class BindingDocument {
+ "\" collection=\"" + "\" collection=\""
+ XmlSource.escape(value.collection(), '"') + XmlSource.escape(value.collection(), '"')
+ "\""; + "\"";
else if (kind == Kind.COMMAND)
node =
"<"
+ PACKAGE
+ "CommandBinding control=\""
+ XmlSource.escape(value.control(), '"')
+ "\" path=\""
+ XmlSource.escape(value.path(), '"')
+ "\"";
else if (kind == Kind.COMPUTED) else if (kind == Kind.COMPUTED)
node += " method=\"" + XmlSource.escape(value.method(), '"') + "\""; node += " method=\"" + XmlSource.escape(value.method(), '"') + "\"";
else else
@@ -31,6 +31,7 @@ final class BindingEditor extends VBox {
private final BindingDocument.Kind kind; private final BindingDocument.Kind kind;
private final ComboBox<BindingMetadata.Converter> converters = new ComboBox<>(); private final ComboBox<BindingMetadata.Converter> converters = new ComboBox<>();
private final Button inspect = new Button("Find Converters / Validate"); private final Button inspect = new Button("Find Converters / Validate");
private final ComboBox<String> commandPaths = new ComboBox<>(), commandTargets = new ComboBox<>();
private final ComboBox<String> direction = new ComboBox<>(); private final ComboBox<String> direction = new ComboBox<>();
private final CheckBox replace = new CheckBox("Replace conflicting bindings"); private final CheckBox replace = new CheckBox("Replace conflicting bindings");
private final Label status = new Label("Open a valid FXML document to edit bindings."); private final Label status = new Label("Open a valid FXML document to edit bindings.");
@@ -50,7 +51,8 @@ final class BindingEditor extends VBox {
this.kind = kind; this.kind = kind;
boolean computed = kind == BindingDocument.Kind.COMPUTED; boolean computed = kind == BindingDocument.Kind.COMPUTED;
boolean repeat = kind == BindingDocument.Kind.REPEAT; boolean repeat = kind == BindingDocument.Kind.REPEAT;
String prefix = repeat ? "repeat-" : computed ? "computed-" : "direct-"; boolean command = kind == BindingDocument.Kind.COMMAND;
String prefix = command ? "command-" : repeat ? "repeat-" : computed ? "computed-" : "direct-";
this.navigate = navigate; this.navigate = navigate;
for (var field : for (var field :
java.util.List.of(control, property, path, converter, method, pane, component, collection)) java.util.List.of(control, property, path, converter, method, pane, component, collection))
@@ -68,6 +70,20 @@ final class BindingEditor extends VBox {
apply.setText("Apply Computed binding"); apply.setText("Apply Computed binding");
remove.setText("Remove Computed binding"); remove.setText("Remove Computed binding");
} }
if (command) {
inspect.setText("Discover / Validate Commands");
fresh.setText("New Command binding");
apply.setText("Apply Command binding");
remove.setText("Remove Command binding");
commandPaths.setOnAction(
e -> {
if (commandPaths.getValue() != null) path.setText(commandPaths.getValue());
});
commandTargets.setOnAction(
e -> {
if (commandTargets.getValue() != null) control.setText(commandTargets.getValue());
});
}
if (repeat) { if (repeat) {
inspect.setText("Discover / Validate Repeat"); inspect.setText("Discover / Validate Repeat");
fresh.setText("New Repeat binding"); fresh.setText("New Repeat binding");
@@ -126,7 +142,7 @@ final class BindingEditor extends VBox {
var grid = new GridPane(); var grid = new GridPane();
grid.setHgap(8); grid.setHgap(8);
grid.setVgap(4); grid.setVgap(4);
if (!computed && !repeat) if (kind == BindingDocument.Kind.DIRECT)
grid.addRow( grid.addRow(
0, 0,
new Label("Control (fx:id)"), new Label("Control (fx:id)"),
@@ -135,7 +151,7 @@ final class BindingEditor extends VBox {
property, property,
new Label("Direction"), new Label("Direction"),
direction); direction);
if (!computed && !repeat) if (kind == BindingDocument.Kind.DIRECT)
grid.addRow(1, new Label("Model path"), path, new Label("Converter (optional)"), converter); grid.addRow(1, new Label("Model path"), path, new Label("Converter (optional)"), converter);
else if (computed) { else if (computed) {
grid.addRow(0, new Label("Control (fx:id)"), control, new Label("Property"), property); grid.addRow(0, new Label("Control (fx:id)"), control, new Label("Property"), property);
@@ -143,6 +159,10 @@ final class BindingEditor extends VBox {
for (var field : java.util.List.of(control, property)) for (var field : java.util.List.of(control, property))
field.textProperty().addListener((o, a, b) -> methods.getItems().clear()); field.textProperty().addListener((o, a, b) -> methods.getItems().clear());
} }
if (command) {
grid.addRow(0, new Label("Control (fx:id)"), control, commandTargets);
grid.addRow(1, new Label("Command path"), path, commandPaths);
}
if (repeat) { if (repeat) {
repeatCollections.setId("repeat-collections"); repeatCollections.setId("repeat-collections");
repeatComponents.setId("repeat-components"); repeatComponents.setId("repeat-components");
@@ -177,7 +197,9 @@ final class BindingEditor extends VBox {
.addAll( .addAll(
bindings, bindings,
grid, grid,
repeat ? new HBox(8, inspect) : new HBox(8, inspect, computed ? methods : converters), repeat || command
? new HBox(8, inspect)
: new HBox(8, inspect, computed ? methods : converters),
new HBox(8, fresh, apply, remove, replace), new HBox(8, fresh, apply, remove, replace),
status); status);
buttons(); buttons();
@@ -209,7 +231,7 @@ final class BindingEditor extends VBox {
control.setText(v.control()); control.setText(v.control());
property.setText(v.property()); property.setText(v.property());
path.setText(v.path()); path.setText(v.path());
direction.setValue(v.direction()); direction.setValue(kind == BindingDocument.Kind.COMMAND ? "view" : v.direction());
converter.setText(v.converter()); converter.setText(v.converter());
method.setText(v.method()); method.setText(v.method());
pane.setText(v.pane()); pane.setText(v.pane());
@@ -329,6 +351,11 @@ final class BindingEditor extends VBox {
} }
return; return;
} }
if (kind == BindingDocument.Kind.COMMAND) {
commandPaths.getItems().setAll(metadata.commandPaths());
commandTargets.getItems().setAll(metadata.commandTargets());
return;
}
if (requested == null || !values().equals(requested)) return; if (requested == null || !values().equals(requested)) return;
if (kind == BindingDocument.Kind.COMPUTED) { if (kind == BindingDocument.Kind.COMPUTED) {
methods.getItems().setAll(metadata.computed()); methods.getItems().setAll(metadata.computed());
@@ -345,6 +372,8 @@ final class BindingEditor extends VBox {
} }
void invalidateDiscovery() { void invalidateDiscovery() {
commandPaths.getItems().clear();
commandTargets.getItems().clear();
updatingChoices = true; updatingChoices = true;
try { try {
repeatCollections.getItems().clear(); repeatCollections.getItems().clear();
@@ -46,6 +46,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
if (bindingEditor != null) bindingEditor.selectControl(id); if (bindingEditor != null) bindingEditor.selectControl(id);
if (computedEditor != null) computedEditor.selectControl(id); if (computedEditor != null) computedEditor.selectControl(id);
if (repeatEditor != null) repeatEditor.selectControl(id); if (repeatEditor != null) repeatEditor.selectControl(id);
if (commandEditor != null) commandEditor.selectControl(id);
if (tableEditor != null) tableEditor.selectControl(id); if (tableEditor != null) tableEditor.selectControl(id);
if (referenceEditor != null) referenceEditor.selectIndex(projection.sourceIndex(id)); if (referenceEditor != null) referenceEditor.selectIndex(projection.sourceIndex(id));
if (id == null || !projection.components().containsKey(id)) return; if (id == null || !projection.components().containsKey(id)) return;
@@ -120,7 +121,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
private DesignerWorkflow bindingWorkflow; private DesignerWorkflow bindingWorkflow;
private ViewGenerationPane viewGeneration; private ViewGenerationPane viewGeneration;
private BindingBrowser bindingBrowser; private BindingBrowser bindingBrowser;
private BindingEditor bindingEditor, computedEditor, repeatEditor; private BindingEditor bindingEditor, computedEditor, repeatEditor, commandEditor;
private TableEditor tableEditor; private TableEditor tableEditor;
private ReferenceEditor referenceEditor; private ReferenceEditor referenceEditor;
private DiagnosticsPane diagnosticsPane; private DiagnosticsPane diagnosticsPane;
@@ -194,36 +195,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
launch.maven(), launch.maven(),
launch.tools(), launch.tools(),
this::log); this::log);
bindingEditor = bindingEditor = editor(BindingDocument.Kind.DIRECT);
new BindingEditor( computedEditor = editor(BindingDocument.Kind.COMPUTED);
BindingDocument.Kind.DIRECT, repeatEditor = editor(BindingDocument.Kind.REPEAT);
this::editBinding, commandEditor = editor(BindingDocument.Kind.COMMAND);
id -> {
if (kit.editor().getFxomDocument() == null) return;
var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id);
if (target != null) kit.editor().getSelection().select(target);
},
values -> validateBindings(values, false));
computedEditor =
new BindingEditor(
BindingDocument.Kind.COMPUTED,
this::editBinding,
id -> {
if (kit.editor().getFxomDocument() == null) return;
var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id);
if (target != null) kit.editor().getSelection().select(target);
},
values -> validateBindings(values, false));
repeatEditor =
new BindingEditor(
BindingDocument.Kind.REPEAT,
this::editBinding,
id -> {
if (kit.editor().getFxomDocument() == null) return;
var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id);
if (target != null) kit.editor().getSelection().select(target);
},
values -> validateBindings(values, false));
tableEditor = tableEditor =
new TableEditor( new TableEditor(
this::editTable, this::navigateComponent, values -> validateBindings(values, false)); this::editTable, this::navigateComponent, values -> validateBindings(values, false));
@@ -379,6 +354,8 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
directBindingTab.setClosable(false); directBindingTab.setClosable(false);
var computedTab = new Tab("Computed bindings", computedEditor); var computedTab = new Tab("Computed bindings", computedEditor);
computedTab.setClosable(false); computedTab.setClosable(false);
var commandTab = new Tab("Command bindings", commandEditor);
commandTab.setClosable(false);
var repeatTab = new Tab("Repeat bindings", repeatEditor); var repeatTab = new Tab("Repeat bindings", repeatEditor);
repeatTab.setClosable(false); repeatTab.setClosable(false);
var tableTab = new Tab("Table / Columns", tableEditor); var tableTab = new Tab("Table / Columns", tableEditor);
@@ -396,6 +373,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
new TabPane( new TabPane(
directBindingTab, directBindingTab,
computedTab, computedTab,
commandTab,
repeatTab, repeatTab,
tableTab, tableTab,
structureTab, structureTab,
@@ -546,6 +524,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
bindingEditor.load(value.text(), value.writable()); bindingEditor.load(value.text(), value.writable());
computedEditor.load(value.text(), value.writable()); computedEditor.load(value.text(), value.writable());
repeatEditor.load(value.text(), value.writable()); repeatEditor.load(value.text(), value.writable());
commandEditor.load(value.text(), value.writable());
tableEditor.load(value.text(), value.writable()); tableEditor.load(value.text(), value.writable());
referenceEditor.load(value.text(), value.writable()); referenceEditor.load(value.text(), value.writable());
submittedSource = null; submittedSource = null;
@@ -578,6 +557,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
bindingEditor.load(value.text(), value.writable()); bindingEditor.load(value.text(), value.writable());
computedEditor.load(value.text(), value.writable()); computedEditor.load(value.text(), value.writable());
repeatEditor.load(value.text(), value.writable()); repeatEditor.load(value.text(), value.writable());
commandEditor.load(value.text(), value.writable());
tableEditor.load(value.text(), value.writable()); tableEditor.load(value.text(), value.writable());
referenceEditor.load(value.text(), value.writable()); referenceEditor.load(value.text(), value.writable());
if (!source.getText().equals(value.text())) { if (!source.getText().equals(value.text())) {
@@ -750,6 +730,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
bindingWorkflow.cancel(); bindingWorkflow.cancel();
bindingBrowser.invalidate(message); bindingBrowser.invalidate(message);
repeatEditor.invalidateDiscovery(); repeatEditor.invalidateDiscovery();
commandEditor.invalidateDiscovery();
tableEditor.invalidateDiscovery(); tableEditor.invalidateDiscovery();
} }
@@ -846,6 +827,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
if (!draft.writable()) throw new IllegalStateException("Document is read-only"); if (!draft.writable()) throw new IllegalStateException("Document is read-only");
if (!draft.text().equals(intent.source())) if (!draft.text().equals(intent.source()))
throw new IllegalStateException("Document changed; select the source object again"); throw new IllegalStateException("Document changed; select the source object again");
if (!intent.change().importedCommandTargets().isEmpty()) {
validateCommandPaste(intent);
return;
}
if (intent.validate()) if (intent.validate())
pendingReferenceValidation = apply(draft.text(), intent.change().edits()); pendingReferenceValidation = apply(draft.text(), intent.change().edits());
submit(intent.change().edits(), intent.label()); submit(intent.change().edits(), intent.label());
@@ -855,6 +840,58 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
}); });
} }
/** Validate imported Command paths against the destination snapshot before the first write. */
private void validateCommandPaste(ReferenceEditor.Intent intent) {
var original = draft;
String proposed = apply(original.text(), intent.change().edits());
var candidate =
new DocumentSnapshot(
original.document(), original.revision(), proposed, original.writable(), true);
bindingWorkflow
.bindingDetails(last, candidate, "", "view", "", "")
.whenComplete(
(metadata, error) ->
fx(
() -> {
if (closed) return;
if (error != null) {
referenceEditor.error(
"Cannot validate the destination Commands: " + error.getMessage());
return;
}
if (draft.revision() != original.revision()
|| !source.getText().equals(original.text())) {
referenceEditor.error(
"Destination changed. Select the destination and paste again.");
return;
}
if (!metadata
.commandTargets()
.containsAll(intent.change().importedCommandTargets())) {
referenceEditor.error(
"The destination build could not resolve the copied Command targets.");
return;
}
var conflicts =
metadata.problems().stream()
.filter(
p ->
p.severity().equals("ERROR")
&& intent
.change()
.importedCommandTargets()
.contains(p.control()))
.map(p -> p.message())
.toList();
if (!conflicts.isEmpty()) {
referenceEditor.error(String.join("; ", conflicts));
return;
}
pendingReferenceValidation = proposed;
submit(intent.change().edits(), intent.label());
}));
}
private void editTable(TableEditor.Intent intent) { private void editTable(TableEditor.Intent intent) {
withDraft( withDraft(
() -> { () -> {
@@ -869,6 +906,19 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
}); });
} }
private BindingEditor editor(BindingDocument.Kind kind) {
return new BindingEditor(
kind,
this::editBinding,
id -> {
var document = kit.editor().getFxomDocument();
if (document == null) return;
var selection = new FXOMFxIdIndex(document).lookup(id);
if (selection != null) kit.editor().getSelection().select(selection);
},
values -> validateBindings(kind == BindingDocument.Kind.COMMAND ? null : values, false));
}
private void editBinding(BindingEditor.Intent intent) { private void editBinding(BindingEditor.Intent intent) {
withDraft( withDraft(
() -> { () -> {
@@ -891,6 +941,8 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
? repeatEditor ? repeatEditor
: intent.kind() == BindingDocument.Kind.COMPUTED : intent.kind() == BindingDocument.Kind.COMPUTED
? computedEditor ? computedEditor
: intent.kind() == BindingDocument.Kind.COMMAND
? commandEditor
: bindingEditor) : bindingEditor)
.error(error.getMessage()); .error(error.getMessage());
} }
@@ -979,6 +1031,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
: "Current successful build") : "Current successful build")
+ " · draft revision " + " · draft revision "
+ captured.revision()); + captured.revision());
commandEditor.metadata(
metadata,
values,
last ? "Retained build" : "Current successful build");
repeatEditor.metadata( repeatEditor.metadata(
metadata, metadata,
values, values,
@@ -1159,7 +1215,11 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
return; return;
} }
var selected = examples.getValue(); var selected = examples.getValue();
if (selected == null || projection == null) return; if (selected == null) {
status.setText("Select a preview example after Build and Refresh.");
return;
}
if (projection == null && !interactiveRequested) return;
long ticket = renderSequence.incrementAndGet(); long ticket = renderSequence.incrementAndGet();
host.documents() host.documents()
.snapshots() .snapshots()
@@ -1191,7 +1251,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
new DocumentSnapshot( new DocumentSnapshot(
draft.document(), draft.document(),
draft.revision(), draft.revision(),
projection.previewText(), projection == null ? draft.text() : projection.previewText(),
draft.writable(), draft.writable(),
draft.dirty())); draft.dirty()));
renderComponents(List.copyOf(drafts.values()), selected.id(), ticket); renderComponents(List.copyOf(drafts.values()), selected.id(), ticket);
@@ -1202,7 +1262,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
private void renderComponents(List<DocumentSnapshot> drafts, String example, long ticket) { private void renderComponents(List<DocumentSnapshot> drafts, String example, long ticket) {
if (ticket != renderSequence.get() || closed) return; if (ticket != renderSequence.get() || closed) return;
var nodes = new LinkedHashMap<String, DesignerWorkflow.Size>(); var nodes = new LinkedHashMap<String, DesignerWorkflow.Size>();
for (String id : projection.components().keySet()) { for (String id : projection == null ? Set.<String>of() : projection.components().keySet()) {
var region = proxy(id); var region = proxy(id);
if (region == null) continue; if (region == null) continue;
int int
@@ -1246,7 +1306,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
})); }));
} }
if (nodes.isEmpty()) { if (nodes.isEmpty()) {
status.setText("No embedded Components; use Interactive preview for this View"); status.setText(
projection == null
? "Canvas projection unavailable; interactive preview uses the FXML draft"
: "No embedded Components; use Interactive preview for this View");
return; return;
} }
workflow workflow
@@ -44,6 +44,9 @@ final class FxmlDiagnostics {
if ((xml.named(e, "DirectBinding") || xml.named(e, "ComputedBinding")) if ((xml.named(e, "DirectBinding") || xml.named(e, "ComputedBinding"))
&& property(e, "control").equals(p.control()) && property(e, "control").equals(p.control())
&& property(e, "property").equals(p.property())) matches.add(i); && property(e, "property").equals(p.property())) matches.add(i);
else if (xml.named(e, "CommandBinding")
&& p.property().equals("command")
&& property(e, "control").equals(p.control())) matches.add(i);
else if (xml.named(e, "Repeat") else if (xml.named(e, "Repeat")
&& p.property().equals("children") && p.property().equals("children")
&& property(e, "pane").equals(p.control())) matches.add(i); && property(e, "pane").equals(p.control())) matches.add(i);
@@ -212,7 +212,8 @@ public final class FxmlProjection {
|| attr.getName().equals("vgap")) || attr.getName().equals("vgap"))
&& !attr.getName().equals("fx:id")) e.removeAttributeNode(attr); && !attr.getName().equals("fx:id")) e.removeAttributeNode(attr);
} }
} else if (Character.isUpperCase(tag.charAt(0)) } else if (isObject(e)
&& Character.isUpperCase(tag.charAt(0))
&& tag.contains(".") && tag.contains(".")
&& !tag.startsWith("javafx.")) && !tag.startsWith("javafx."))
throw new IOException("Unsupported application element: " + tag); throw new IOException("Unsupported application element: " + tag);
@@ -17,7 +17,11 @@ final class ReferenceDocument {
record Clip(String source, int index, String origin) {} record Clip(String source, int index, String origin) {}
record Change(List<Replacement> edits, List<String> notes) {} record Change(List<Replacement> edits, List<String> notes, Set<String> importedCommandTargets) {
Change(List<Replacement> edits, List<String> notes) {
this(edits, notes, Set.of());
}
}
private record Target(Element binding, Element element, String attribute, String value) {} private record Target(Element binding, Element element, String attribute, String value) {}
@@ -54,6 +58,7 @@ final class ReferenceDocument {
private boolean binding(Element e) { private boolean binding(Element e) {
if (!(xml.named(e, "DirectBinding") if (!(xml.named(e, "DirectBinding")
|| xml.named(e, "CommandBinding")
|| xml.named(e, "ComputedBinding") || xml.named(e, "ComputedBinding")
|| xml.named(e, "Repeat"))) return false; || xml.named(e, "Repeat"))) return false;
Node parent = e.getParentNode(); Node parent = e.getParentNode();
@@ -211,9 +216,9 @@ final class ReferenceDocument {
Change paste(Clip clip, int destination, String origin) throws Exception { Change paste(Clip clip, int destination, String origin) throws Exception {
if (clip == null) throw new IllegalArgumentException("Copy a subtree first"); if (clip == null) throw new IllegalArgumentException("Copy a subtree first");
Element parent = entry(destination); Element parent = entry(destination);
requireContainer(parent);
var from = new ReferenceDocument(clip.source()); var from = new ReferenceDocument(clip.source());
Element selected = from.entry(clip.index()); Element selected = from.entry(clip.index());
String childProperty = childProperty(parent, selected);
if (!clip.origin().equals(origin)) if (!clip.origin().equals(origin))
for (var e : from.xml.elements) for (var e : from.xml.elements)
if (within(e, selected)) if (within(e, selected))
@@ -273,7 +278,7 @@ final class ReferenceDocument {
.collect(java.util.stream.Collectors.joining("\n")); .collect(java.util.stream.Collectors.joining("\n"));
Element container = Element container =
children(parent).stream() children(parent).stream()
.filter(c -> c.getTagName().equals("children")) .filter(c -> c.getTagName().equals(childProperty))
.findFirst() .findFirst()
.orElse(parent); .orElse(parent);
String result = xml.source.apply(List.of(xml.append(container, fragment, ""))); String result = xml.source.apply(List.of(xml.append(container, fragment, "")));
@@ -299,7 +304,16 @@ final class ReferenceDocument {
+ " validation."); + " validation.");
} }
notes.add("Assigned identifiers: " + mapping); notes.add("Assigned identifiers: " + mapping);
return new Change(difference(xml.text, result), List.copyOf(notes)); var importedCommands = new HashSet<String>();
if (!clip.origin().equals(origin)) {
for (var target : from.targets) {
if (from.xml.named(target.binding(), "CommandBinding")
&& mapping.containsKey(target.value()))
importedCommands.add(mapping.get(target.value()));
}
}
return new Change(
difference(xml.text, result), List.copyOf(notes), Set.copyOf(importedCommands));
} }
private String fragment(Element e, List<Replacement> edits) { private String fragment(Element e, List<Replacement> edits) {
@@ -407,7 +421,23 @@ final class ReferenceDocument {
return p; return p;
} }
private void requireContainer(Element e) { private String childProperty(Element e, Element child) {
String childName = child.getTagName();
String type = childName.substring(childName.lastIndexOf('.') + 1);
boolean menuItem =
Set.of(
"MenuItem",
"Menu",
"RadioMenuItem",
"CheckMenuItem",
"CustomMenuItem",
"SeparatorMenuItem")
.contains(type);
if (e.getTagName().equals("Menu") || e.getTagName().equals("javafx.scene.control.Menu")) {
if (!menuItem) throw new IllegalArgumentException("A Menu accepts MenuItem children");
return "items";
}
if (menuItem) throw new IllegalArgumentException("Paste a MenuItem into a Menu");
String name = e.getTagName(); String name = e.getTagName();
if (FX.equals(e.getNamespaceURI()) && "root".equals(e.getLocalName())) if (FX.equals(e.getNamespaceURI()) && "root".equals(e.getLocalName()))
name = e.getAttribute("type"); name = e.getAttribute("type");
@@ -427,6 +457,7 @@ final class ReferenceDocument {
"Paste into a standard Pane; other child properties require Source editing"); "Paste into a standard Pane; other child properties require Source editing");
if (children(e).stream().filter(c -> c.getTagName().equals("children")).count() > 1) if (children(e).stream().filter(c -> c.getTagName().equals("children")).count() > 1)
throw new IllegalArgumentException("Ambiguous children containers"); throw new IllegalArgumentException("Ambiguous children containers");
return "children";
} }
private String appendBindings(String body) throws Exception { private String appendBindings(String body) throws Exception {
@@ -39,7 +39,7 @@ final class ReferenceEditor extends VBox {
.addAll( .addAll(
new Label( new Label(
"Select a source object or its canvas item. Paste adds children to the selected" "Select a source object or its canvas item. Paste adds children to the selected"
+ " Pane."), + " Pane or Menu."),
nodes, nodes,
new HBox( new HBox(
6, 6,
@@ -59,7 +59,7 @@ final class ReferenceEditor extends VBox {
clipboard = document.copy(selected(), origin); clipboard = document.copy(selected(), origin);
actionStatus = actionStatus =
"Copied subtree and its associated bindings. Select a destination Pane" "Copied subtree and its associated bindings. Select a destination Pane"
+ " in this or another View."; + " or Menu in this or another View.";
status.setText(actionStatus); status.setText(actionStatus);
} catch (Exception e) { } catch (Exception e) {
error(e.getMessage()); error(e.getMessage());
@@ -34,6 +34,26 @@ class FxmlProjectionTest {
assertTrue(restored.contains("neitzel-model")); assertTrue(restored.contains("neitzel-model"));
} }
@Test
void editsTheStatusBarBesideAnAttachedMarginWithoutChangingItsXml() throws Exception {
String source = """
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import de.neitzel.fx.view.BindingList?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1">
<fx:define><BindingList/></fx:define>
<bottom><HBox spacing='8'>
<BorderPane.margin><Insets top='5' right='12' bottom='9' left='12'/></BorderPane.margin>
</HBox></bottom>
</BorderPane>
""";
var projection = new FxmlProjection(source);
String projected = projection.project();
String edited = projection.restore(projected.replace("spacing=\"8\"", "spacing=\"10\""));
assertEquals(source.replace("spacing='8'", "spacing='10'"), edited);
assertEquals(source, projection.restore(projected));
}
@Test @Test
void rejectsExternalEntitiesAndExecutableFXML() throws Exception { void rejectsExternalEntitiesAndExecutableFXML() throws Exception {
assertThrows( assertThrows(
@@ -96,6 +96,26 @@ class ReferenceDocumentTest {
assertTrue(twice.contains("f:id='childCopy2'")); assertTrue(twice.contains("f:id='childCopy2'"));
} }
@Test
void copiesMenuCommandsWithFreshIdsAndTracksTargetsForDestinationValidation() throws Exception {
String text =
"<?import de.neitzel.fx.view.*?><?import javafx.scene.control.*?>"
+ "<Menu xmlns:fx='http://javafx.com/fxml/1' fx:id='file'><fx:define><BindingList>"
+ "<CommandBinding control='open' path='open'/></BindingList></fx:define>"
+ "<items><MenuItem fx:id='open' accelerator='Shortcut+O'/></items></Menu>";
var menu = new ReferenceDocument(text);
var clip = menu.copy(index(menu, "open"), "source");
var copied = menu.paste(clip, index(menu, "file"), "destination");
assertEquals(Set.of("openCopy"), copied.importedCommandTargets());
String result = apply(text, copied);
assertTrue(result.contains("fx:id='openCopy' accelerator='Shortcut+O'"));
assertTrue(result.contains("control='openCopy' path='open'"));
var layout = new ReferenceDocument(XML);
assertThrows(
IllegalArgumentException.class,
() -> layout.paste(clip, index(layout, "box"), "destination"));
}
@Test @Test
void carriesNamespacesImportsAndReportsDestinationContextDifferences() throws Exception { void carriesNamespacesImportsAndReportsDestinationContextDifferences() throws Exception {
String source = String source =
@@ -1,7 +1,7 @@
package de.neitzel.fxdesigner.target; package de.neitzel.fxdesigner.target;
import de.neitzel.fxdesigner.protocol.BindingMetadata.*;
import de.neitzel.fxdesigner.protocol.BindingMetadata; import de.neitzel.fxdesigner.protocol.BindingMetadata;
import de.neitzel.fxdesigner.protocol.BindingMetadata.*;
import java.beans.*; import java.beans.*;
import java.io.*; import java.io.*;
import java.lang.reflect.*; import java.lang.reflect.*;
@@ -28,6 +28,7 @@ public final class BindingDiscovery {
private record TargetType(Class<?> type, boolean writable) {} private record TargetType(Class<?> type, boolean writable) {}
private final Set<String> actionHandlers = new HashSet<>();
private final Map<String, Class<?>> controlTypes = new HashMap<>(); private final Map<String, Class<?>> controlTypes = new HashMap<>();
private RepeatDiscovery repeats; private RepeatDiscovery repeats;
private final Map<String, TargetType> targetTypes = new HashMap<>(); private final Map<String, TargetType> targetTypes = new HashMap<>();
@@ -313,6 +314,10 @@ public final class BindingDiscovery {
? owner.controller ? owner.controller
: resolve(e, imports); : resolve(e, imports);
controlTypes.put(id, control); controlTypes.put(id, control);
if (e.hasAttribute("onAction")) actionHandlers.add(id);
for (Node child = e.getFirstChild(); child != null; child = child.getNextSibling())
if (child instanceof Element property && property.getTagName().equals("onAction"))
actionHandlers.add(id);
String componentModel = ""; String componentModel = "";
var componentResource = control.getResource(control.getSimpleName() + ".fxml"); var componentResource = control.getResource(control.getSimpleName() + ".fxml");
if (componentResource != null) if (componentResource != null)
@@ -398,7 +403,8 @@ public final class BindingDiscovery {
: converters.candidates(source, chosen == null ? null : chosen.type(), direction); : converters.candidates(source, chosen == null ? null : chosen.type(), direction);
repeats = new RepeatDiscovery(loader, attributes, owner, incompleteModel, controlTypes, ids); repeats = new RepeatDiscovery(loader, attributes, owner, incompleteModel, controlTypes, ids);
var tables = new TableDiscovery(loader, repeats, modelType, owner); var tables = new TableDiscovery(loader, repeats, modelType, owner);
var problems = new ArrayList<>(validate(doc, imports, ids, converters)); var commands = commandPaths();
var problems = new ArrayList<>(validate(doc, imports, ids, converters, commands));
problems.addAll(tables.validate(doc)); problems.addAll(tables.validate(doc));
var componentOptions = repeats.candidates(selected); var componentOptions = repeats.candidates(selected);
for (var a : attributes) for (var a : attributes)
@@ -421,7 +427,35 @@ public final class BindingDiscovery {
repeats.panes(), repeats.panes(),
tables.collections(), tables.collections(),
tables.rows(selected), tables.rows(selected),
tables.columns(selected)); tables.columns(selected),
commands,
controlTypes.entrySet().stream()
.filter(e -> commandTarget(e.getValue()))
.map(Map.Entry::getKey)
.sorted()
.toList());
}
private List<String> commandPaths() {
if (owner.viewModel == null) return List.of();
return Arrays.stream(owner.viewModel.getMethods())
.filter(
m ->
!Modifier.isStatic(m.getModifiers())
&& m.getParameterCount() == 0
&& m.getName().startsWith("get")
&& m.getName().length() > 3
&& de.neitzel.fx.view.Command.class.isAssignableFrom(m.getReturnType()))
.map(m -> java.beans.Introspector.decapitalize(m.getName().substring(3)))
.distinct()
.sorted()
.toList();
}
private static boolean commandTarget(Class<?> type) {
return type != null
&& (javafx.scene.control.ButtonBase.class.isAssignableFrom(type)
|| javafx.scene.control.MenuItem.class.isAssignableFrom(type));
} }
private void selectOwner(Document doc, List<String> imports, String resource, Class<?> model) private void selectOwner(Document doc, List<String> imports, String resource, Class<?> model)
@@ -492,17 +526,31 @@ public final class BindingDiscovery {
.anyMatch(a -> a.path().equals(path) && Set.of("COMPLEX", "COLLECTION").contains(a.kind())); .anyMatch(a -> a.path().equals(path) && Set.of("COMPLEX", "COLLECTION").contains(a.kind()));
} }
private static String propertyValue(Element declaration, String name) {
if (declaration.hasAttribute(name)) return declaration.getAttribute(name);
for (Node n = declaration.getFirstChild(); n != null; n = n.getNextSibling())
if (n instanceof Element child && child.getTagName().equals(name))
return child.getTextContent().trim();
return "";
}
private List<Problem> validate( private List<Problem> validate(
Document doc, List<String> imports, Set<String> ids, ConverterDiscovery converters) Document doc,
List<String> imports,
Set<String> ids,
ConverterDiscovery converters,
List<String> commands)
throws Exception { throws Exception {
var problems = new ArrayList<Problem>(selectionProblems); var problems = new ArrayList<Problem>(selectionProblems);
problems.addAll(owner.problems); problems.addAll(owner.problems);
var occupied = new HashSet<String>(); var occupied = new HashSet<String>();
var commandControls = new TreeSet<String>();
var nodes = doc.getElementsByTagName("*"); var nodes = doc.getElementsByTagName("*");
for (int i = 0; i < nodes.getLength(); i++) { for (int i = 0; i < nodes.getLength(); i++) {
var e = (Element) nodes.item(i); var e = (Element) nodes.item(i);
if (!library(e, "DirectBinding", imports) if (!library(e, "DirectBinding", imports)
&& !library(e, "ComputedBinding", imports) && !library(e, "ComputedBinding", imports)
&& !library(e, "CommandBinding", imports)
&& !library(e, "Repeat", imports)) continue; && !library(e, "Repeat", imports)) continue;
Node parent = e.getParentNode(); Node parent = e.getParentNode();
if (parent instanceof Element p && p.getTagName().equals("elements")) if (parent instanceof Element p && p.getTagName().equals("elements"))
@@ -529,9 +577,39 @@ public final class BindingDiscovery {
} }
continue; continue;
} }
String control = e.getAttribute("control"), String control = propertyValue(e, "control"),
property = e.getAttribute("property"), property = propertyValue(e, "property"),
key = control + "." + property; key = control + "." + property;
if (library(e, "CommandBinding", imports)) {
String path = propertyValue(e, "path");
if (!ids.contains(control))
problems.add(
new Problem(control, "command", "ERROR", "Unknown Command target fx:id: " + control));
else if (!commandTarget(controlTypes.get(control)))
problems.add(
new Problem(
control,
"command",
"ERROR",
"Command target must be a ButtonBase or MenuItem: " + control));
if (path.isBlank() || path.contains("."))
problems.add(
new Problem(control, "command", "ERROR", "Expected a simple Command path: " + path));
else if (!commands.contains(path))
problems.add(new Problem(control, "command", "ERROR", "Unknown Command path: " + path));
if (!commandControls.add(control))
problems.add(
new Problem(
control,
"command",
"ERROR",
"Duplicate Command binding for disable and onAction"));
if (actionHandlers.contains(control))
problems.add(
new Problem(
control, "command", "ERROR", "Command conflicts with existing onAction handler"));
continue;
}
if (!occupied.add(key)) if (!occupied.add(key))
problems.add(new Problem(control, property, "ERROR", "Duplicate binding target")); problems.add(new Problem(control, property, "ERROR", "Duplicate binding target"));
@@ -624,6 +702,15 @@ public final class BindingDiscovery {
} }
if (!severity.isEmpty()) problems.add(new Problem(control, property, severity, message)); if (!severity.isEmpty()) problems.add(new Problem(control, property, severity, message));
} }
for (String control : commandControls)
for (String endpoint : List.of("disable", "onAction"))
if (occupied.contains(control + "." + endpoint))
problems.add(
new Problem(
control,
"command",
"ERROR",
"Command conflicts with another binding for " + endpoint));
return problems; return problems;
} }
@@ -12,13 +12,12 @@ import javafx.scene.*;
import javafx.scene.image.WritableImage; import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color; import javafx.scene.paint.Color;
/** /** A worker owns one preview session and its managed Views. */
* One preview session per target JVM: the library retains process-wide Model/ViewModel identities.
*/
public final class TargetPreview implements AutoCloseable { public final class TargetPreview implements AutoCloseable {
private static final AtomicBoolean CONSUMED = new AtomicBoolean(); private static final AtomicBoolean CONSUMED = new AtomicBoolean();
private PreviewSession<?, ?> session; private PreviewSession<?, ?> session;
private LoadedView view; private LoadedView view;
private final ViewModelContext models = new ViewModelContext();
private Scene scene; private Scene scene;
private final Occurrences occurrences = new Occurrences(); private final Occurrences occurrences = new Occurrences();
private javafx.stage.Stage interactive; private javafx.stage.Stage interactive;
@@ -128,31 +127,9 @@ public final class TargetPreview implements AutoCloseable {
if (component) { if (component) {
String name = String name =
d.viewResource().substring(0, d.viewResource().length() - 5).replace('/', '.'); d.viewResource().substring(0, d.viewResource().length() - 5).replace('/', '.');
Class<?> componentType = Class.forName(name, false, loader); var componentType = Class.forName(name, false, loader).asSubclass(Parent.class);
if (!Parent.class.isAssignableFrom(componentType)) view = ViewLoader.loadComponent(componentType, session.model(), context, models);
throw new IllegalArgumentException("Component root is not a Parent"); } else view = ViewLoader.load(resource, session.model(), context, models);
byte[] wrapper = ("<" + name + "/>").getBytes(java.nio.charset.StandardCharsets.UTF_8);
var wrapped =
new java.net.URL(
null,
"memory:component",
new java.net.URLStreamHandler() {
protected java.net.URLConnection openConnection(java.net.URL url) {
return new java.net.URLConnection(url) {
public void connect() {}
public java.io.InputStream getInputStream() {
return new java.io.ByteArrayInputStream(wrapper);
}
};
}
});
view = ViewLoader.load(wrapped, session.model(), context);
var model = componentType.getMethod("modelProperty").invoke(view.getRoot());
if (!(model instanceof javafx.beans.property.Property property))
throw new IllegalArgumentException("Component has no writable Model");
property.setValue(session.model());
} else view = ViewLoader.load(resource, session.model(), context);
scene = new Scene(view.getRoot(), 420, 240); scene = new Scene(view.getRoot(), 420, 240);
layout(420, 240); layout(420, 240);
var wait = session.ready(); var wait = session.ready();
@@ -316,7 +293,9 @@ public final class TargetPreview implements AutoCloseable {
closed = true; closed = true;
timer.shutdownNow(); timer.shutdownNow();
try { try {
if (session != null) session.close(); try (var ownedSession = session) {
models.close();
}
cleanup.complete(null); cleanup.complete(null);
} catch (Throwable e) { } catch (Throwable e) {
if (failure != null) failure.addSuppressed(e); if (failure != null) failure.addSuppressed(e);
@@ -112,6 +112,67 @@ class BindingDiscoveryTest {
() -> BindingDiscovery.inspect(fxml(), "", "wrong", getClass().getClassLoader())); () -> BindingDiscovery.inspect(fxml(), "", "wrong", getClass().getClassLoader()));
} }
@de.neitzel.fx.view.ViewModelClass(Commands.class)
public static class Controller {}
public static class Commands {
public Commands(Model model) {
throw new AssertionError("Discovery constructed the ViewModel");
}
public de.neitzel.fx.view.Command getOpen() {
throw new AssertionError("Discovery executed the Command getter");
}
}
@Test
void commandDiscoveryResolvesTargetsAndLocatesConflictsInEitherOrder() throws Exception {
String command = "<CommandBinding control='menu' path='open'/>";
String xml =
"<?neitzel-model "
+ Model.class.getName()
+ "?><?import javafx.scene.layout.*?>"
+ "<?import javafx.scene.control.*?><?import de.neitzel.fx.view.*?>"
+ "<VBox xmlns:fx='http://javafx.com/fxml/1' fx:controller='"
+ Controller.class.getName()
+ "'>"
+ "<fx:define><BindingList>"
+ command
+ "<CommandBinding control='go'"
+ " path='open'/></BindingList></fx:define><MenuButton><items><MenuItem"
+ " fx:id='menu'/></items></MenuButton><Button fx:id='go'/><Label"
+ " fx:id='label'/></VBox>";
var valid = BindingDiscovery.inspect(xml, "", "view", getClass().getClassLoader());
assertEquals(List.of("open"), valid.commandPaths());
assertEquals(List.of("go", "menu"), valid.commandTargets());
assertTrue(
valid.problems().stream().noneMatch(p -> p.severity().equals("ERROR")),
valid.problems().toString());
for (var invalid :
List.of(
xml.replace(
command,
command
+ "<DirectBinding control='menu' property='disable' path='name'"
+ " direction='view'/>"),
xml.replace(
command,
"<ComputedBinding control='menu' property='onAction' method='#existing'/>"
+ command),
xml.replace(command, command + command),
xml.replace("fx:id='menu'", "fx:id='menu' onAction='#existing'"),
xml.replace("control='menu'", "control='missing'"),
xml.replace("control='menu'", "control='label'"),
xml.replace("path='open'", "path='sub.open'"),
xml.replace("path='open'", "path='missing'"))) {
var report = BindingDiscovery.inspect(invalid, "", "view", getClass().getClassLoader());
assertTrue(
report.problems().stream()
.anyMatch(p -> p.severity().equals("ERROR") && p.property().equals("command")),
report.problems().toString());
}
}
public static class NumberModel { public static class NumberModel {
public Number getAmount() { public Number getAmount() {
return null; return null;
+56 -27
View File
@@ -2,9 +2,9 @@
"schemaVersion": 1, "schemaVersion": 1,
"status": "verified-local-development-snapshot", "status": "verified-local-development-snapshot",
"sourceRepository": "ssh://git@gitea.neitzel.de:2222/konrad/NeitzelLib.git", "sourceRepository": "ssh://git@gitea.neitzel.de:2222/konrad/NeitzelLib.git",
"sourceRevision": "75b733abe300bea799a59664f0d5a9dbc21d315b", "sourceRevision": "514cc7fb8ec85824aa4f62adecd52585fe8a9093",
"minimumReleasedVersion": null, "minimumReleasedVersion": null,
"requiredCapability": "component-fxml-attributes-after-initialization", "requiredCapability": "managed-views-and-command-bindings",
"javaVersion": "25", "javaVersion": "25",
"javafxVersion": "27.0.1", "javafxVersion": "27.0.1",
"testResults": { "testResults": {
@@ -12,7 +12,7 @@
"tests": 9, "tests": 9,
"failures": 0, "failures": 0,
"errors": 0, "errors": 0,
"skipped": 0 "skipped": 1
}, },
"injection": { "injection": {
"tests": 10, "tests": 10,
@@ -21,7 +21,19 @@
"skipped": 0 "skipped": 0
}, },
"fx": { "fx": {
"tests": 105, "tests": 405,
"failures": 0,
"errors": 0,
"skipped": 12
},
"data-grid": {
"tests": 33,
"failures": 0,
"errors": 0,
"skipped": 0
},
"fx-test": {
"tests": 2,
"failures": 0, "failures": 0,
"errors": 0, "errors": 0,
"skipped": 0 "skipped": 0
@@ -31,59 +43,76 @@
{ {
"groupId": "de.neitzel.lib", "groupId": "de.neitzel.lib",
"artifactId": "neitzellib", "artifactId": "neitzellib",
"version": "1.0-SNAPSHOT", "version": "1.0.6-SNAPSHOT",
"extension": "pom", "extension": "pom",
"repositoryPath": "de/neitzel/lib/neitzellib/1.0-SNAPSHOT/neitzellib-1.0-SNAPSHOT.pom", "repositoryPath": "de/neitzel/lib/neitzellib/1.0.6-SNAPSHOT/neitzellib-1.0.6-SNAPSHOT.pom",
"sha256": "23f7507a215f42d1ace3a25586b16b154ff0810a381f508e4554b94f92e8e529" "sha256": "679b689ce3930c2e2a69c96d30357026f775141ec404e998533492b9fbda0202"
}, },
{ {
"groupId": "de.neitzel.lib", "groupId": "de.neitzel.lib",
"artifactId": "core", "artifactId": "core",
"version": "1.0-SNAPSHOT", "version": "1.0.6-SNAPSHOT",
"extension": "pom", "extension": "pom",
"repositoryPath": "de/neitzel/lib/core/1.0-SNAPSHOT/core-1.0-SNAPSHOT.pom", "repositoryPath": "de/neitzel/lib/core/1.0.6-SNAPSHOT/core-1.0.6-SNAPSHOT.pom",
"sha256": "bed4167d3bc74f3bccb3f1328eb796b735bd60ec35aa881219edcce2a562fbd2" "sha256": "91f8ed8976c058c7fcfb02a9d4fb9066d856e698c2d4fd3763fbf87992bdf646"
}, },
{ {
"groupId": "de.neitzel.lib", "groupId": "de.neitzel.lib",
"artifactId": "core", "artifactId": "core",
"version": "1.0-SNAPSHOT", "version": "1.0.6-SNAPSHOT",
"extension": "jar", "extension": "jar",
"repositoryPath": "de/neitzel/lib/core/1.0-SNAPSHOT/core-1.0-SNAPSHOT.jar", "repositoryPath": "de/neitzel/lib/core/1.0.6-SNAPSHOT/core-1.0.6-SNAPSHOT.jar",
"sha256": "a88374553bbb7c0dce9b1f5cc237601fa6d26db81b505f5e776ad13fa4db0db8" "sha256": "513c9ddbc3fe95ec2b6153e2e53f368b13ec4056beee2002f60fa0e1cc92bdb2"
}, },
{ {
"groupId": "de.neitzel.lib", "groupId": "de.neitzel.lib",
"artifactId": "injection", "artifactId": "injection",
"version": "1.0-SNAPSHOT", "version": "1.0.6-SNAPSHOT",
"extension": "pom", "extension": "pom",
"repositoryPath": "de/neitzel/lib/injection/1.0-SNAPSHOT/injection-1.0-SNAPSHOT.pom", "repositoryPath": "de/neitzel/lib/injection/1.0.6-SNAPSHOT/injection-1.0.6-SNAPSHOT.pom",
"sha256": "6060ccac3dd2eeb00342ab34028445649716e229e09bea9adbba56dda58d4780" "sha256": "25f02eb0f4c8fa7b60c2c106b0f8019f56b995c3891db34f875bc25d830fa36f"
}, },
{ {
"groupId": "de.neitzel.lib", "groupId": "de.neitzel.lib",
"artifactId": "injection", "artifactId": "injection",
"version": "1.0-SNAPSHOT", "version": "1.0.6-SNAPSHOT",
"extension": "jar", "extension": "jar",
"repositoryPath": "de/neitzel/lib/injection/1.0-SNAPSHOT/injection-1.0-SNAPSHOT.jar", "repositoryPath": "de/neitzel/lib/injection/1.0.6-SNAPSHOT/injection-1.0.6-SNAPSHOT.jar",
"sha256": "2d72111068cb8240b31e70c42c60687316dfbaf60d2fd965dcc833eeae17b084" "sha256": "c9b54bddc2eeff2cda7de51d8d55c20a16036a42a4cfd1cde864967c8e76b29a"
}, },
{ {
"groupId": "de.neitzel.lib", "groupId": "de.neitzel.lib",
"artifactId": "fx", "artifactId": "data-grid",
"version": "1.0-SNAPSHOT", "version": "1.0.6-SNAPSHOT",
"extension": "pom", "extension": "pom",
"repositoryPath": "de/neitzel/lib/fx/1.0-SNAPSHOT/fx-1.0-SNAPSHOT.pom", "repositoryPath": "de/neitzel/lib/data-grid/1.0.6-SNAPSHOT/data-grid-1.0.6-SNAPSHOT.pom",
"sha256": "4ccebda8f6cb8104aa272f3805263967530f8da259d2712b8ca0aa0c7d6fb356" "sha256": "565ce34c459282d519193c88f4d97dca0ca7c30ad395d3252918cf35aaa867e7"
},
{
"groupId": "de.neitzel.lib",
"artifactId": "data-grid",
"version": "1.0.6-SNAPSHOT",
"extension": "jar",
"repositoryPath": "de/neitzel/lib/data-grid/1.0.6-SNAPSHOT/data-grid-1.0.6-SNAPSHOT.jar",
"sha256": "5850b27705d5cbc493d6ff7f37a2803b4469aefad8273e9fd9e3350c53ca05c1"
}, },
{ {
"groupId": "de.neitzel.lib", "groupId": "de.neitzel.lib",
"artifactId": "fx", "artifactId": "fx",
"version": "1.0-SNAPSHOT", "version": "1.0.6-SNAPSHOT",
"extension": "pom",
"repositoryPath": "de/neitzel/lib/fx/1.0.6-SNAPSHOT/fx-1.0.6-SNAPSHOT.pom",
"sha256": "3d87b56f8c479396ad4b4cf5d6493a44621daed3991666cc98dbe9f112e05aea"
},
{
"groupId": "de.neitzel.lib",
"artifactId": "fx",
"version": "1.0.6-SNAPSHOT",
"extension": "jar", "extension": "jar",
"repositoryPath": "de/neitzel/lib/fx/1.0-SNAPSHOT/fx-1.0-SNAPSHOT.jar", "repositoryPath": "de/neitzel/lib/fx/1.0.6-SNAPSHOT/fx-1.0.6-SNAPSHOT.jar",
"sha256": "803b19f76039c8777809618f420f43d2ff46a9fe051e96317fb053f8afb49ef0" "sha256": "e2d5795d1c6e79d2ac47ef7944a14a8d4b847e78473012f3c63370ba7a04618f"
} }
], ],
"generatedViewModelSupport": "stored-property-access-and-declarative-service-registry" "generatedViewModelSupport": "stored-property-access-and-declarative-service-registry",
"buildOutputTimestamp": "2026-11-24T00:00:00Z"
} }
+12 -24
View File
@@ -1,18 +1,23 @@
# Corrected NeitzelLib development artifact # NeitzelLib development runtime
The Component builder fix is integrated in [NeitzelLib main at 2d83fb4](https://gitea.neitzel.de/konrad/NeitzelLib/src/commit/2d83fb467cc29b6e7c5aa92c86fc3fb49a504dc0). It collects FXML values, initializes the injected Component and installs its Model listener, then applies values using public FXMLLoader conversion. Both Components in the regression fixture retain the same Model reference; invalid properties and values fail. The IntelliJ Archiver preview uses `de.neitzel.lib:fx:1.0.6-SNAPSHOT` on JDK 25 and JavaFX 27.0.1. The target uses managed Views, CommandBindings and the direct `ViewLoader.loadComponent` entry point for fx:root previews. The host uses JavaFX 26. Source revision, build timestamp, test totals and the nine installed POM/JAR checksums are in the [active manifest](neitzellib-baseline.json).
## Artifact identity ## Rebuild and verify
Use `de.neitzel.lib:fx:1.0-SNAPSHOT` with its matching parent, core and injection artifacts. [The manifest](neitzellib-baseline.json) records the exact source commit and SHA-256 hashes of seven installed POM/JAR artifacts. These artifacts are installed in the developer's local Maven repository, not deployed to a remote artifact repository. No corrected released minimum is established and no release tag was created. A source commit on main is not a published release. Use the manifest's NeitzelLib commit with a clean source tree, JDK 25 and the Maven wrapper. Select an absolute repository path on the development machine. Both Maven and Gradle must resolve the same local snapshot during Designer builds.
```sh ```sh
export NEITZELLIB_MAVEN_REPOSITORY=/absolute/path/to/preview-repository
export MAVEN_OPTS="-Dmaven.repo.local=$NEITZELLIB_MAVEN_REPOSITORY"
export GRADLE_OPTS="$MAVEN_OPTS"
# In the NeitzelLib checkout
./mvnw -B -ntp -pl fx,fx-test -am -Dversions.skip=true \
-Dproject.build.outputTimestamp=2026-11-24T00:00:00Z clean install
# In the NeitzelFXDesigner checkout
python3 scripts/check-neitzellib-artifact.py python3 scripts/check-neitzellib-artifact.py
# For a non-default Maven repository:
python3 scripts/check-neitzellib-artifact.py --repository /path/to/repository
``` ```
This check detects an absent or overwritten snapshot. Maven coordinates alone are insufficient. Artifact bytes have also been compared against every tested compiled class in the isolated build. A fresh rebuild can change JAR timestamps, so it must be validated and its manifest deliberately refreshed; a checksum mismatch must not be automatically accepted. The verifier identifies missing files and changed bytes independently of the Maven coordinates. Inspect the module Surefire reports for platform skips. These artifacts are development snapshots installed locally.
## Original Java 21 qualification ## Original Java 21 qualification
@@ -21,25 +26,8 @@ This check detects an absent or overwritten snapshot. Maven coordinates alone ar
- Adapter-free Kit canvas/runtime smoke scenario: **38 passing checks**, including direct loading of the saved original FXML. It used JavaFX 21.0.7 in the target and the existing Kit 26 prototype host. - Adapter-free Kit canvas/runtime smoke scenario: **38 passing checks**, including direct loading of the saved original FXML. It used JavaFX 21.0.7 in the target and the existing Kit 26 prototype host.
- `clean install` completed using JDK 21 and the library's Maven 3.9.11 wrapper, including its configured report-generation/package phases. Test report totals, not the Maven exit status alone, are the test acceptance evidence. This does not claim new module-path, plugin or cross-platform qualification. - `clean install` completed using JDK 21 and the library's Maven 3.9.11 wrapper, including its configured report-generation/package phases. Test report totals, not the Maven exit status alone, are the test acceptance evidence. This does not claim new module-path, plugin or cross-platform qualification.
## Rebuild the active baseline
Use a clean checkout at the manifest's source revision; the canonical library checkout currently also contains unrelated native-desktop work. Keep that work separate. Run:
```sh
# In the clean NeitzelLib checkout, with JAVA_HOME pointing to JDK 25:
./mvnw -B -ntp -pl fx -am -Dversions.skip=true clean install
```
Surefire fails the current build on test failures. Inspect the XML reports under `core`, `injection` and `fx` and record any platform-specific skips. Re-run the direct adapter-free scenario before changing the recorded capability baseline. Record source revision and installed artifact hashes together after acceptance; do not silently reuse the old hashes for a new build.
The regression source covers custom/inherited properties, numeric/boolean/enum conversion, XML text escaping, attached layout constraints, post-initialization setters, shared Model identity/write-back and invalid values. The original canonical library branch and its working-tree changes were left untouched; only the isolated eight-file Component change was integrated into main.
## Generated ViewModel runtime extension — 2026-11-13 ## Generated ViewModel runtime extension — 2026-11-13
The Java 21 development snapshot included NeitzelLib `90e08b7`: [stored-property access and generated defaults](https://gitea.neitzel.de/konrad/NeitzelLib/src/commit/90e08b7/fx/docs/generated-viewmodels.md). The earlier Component baseline above remains historical qualification. The new isolated clean build passed core 1, injection 10 and fx 105 tests with no failures/errors/skips. Every installed class was compared with the tested class output before updating the manifest hashes. The canonical library checkout and its unrelated changes remain untouched. No released minimum or remote artifact publication is claimed. The Java 21 development snapshot included NeitzelLib `90e08b7`: [stored-property access and generated defaults](https://gitea.neitzel.de/konrad/NeitzelLib/src/commit/90e08b7/fx/docs/generated-viewmodels.md). The earlier Component baseline above remains historical qualification. The new isolated clean build passed core 1, injection 10 and fx 105 tests with no failures/errors/skips. Every installed class was compared with the tested class output before updating the manifest hashes. The canonical library checkout and its unrelated changes remain untouched. No released minimum or remote artifact publication is claimed.
Designer fixtures additionally verify generated runtime behavior in real classpath and module-path applications. The library build evidence is `/tmp/viewmodel-runtime-qualified.log`; generated fixture evidence is `/tmp/generated-vm-fixtures-final.log`. The prior 38 adapter-free checks remain historical; current whole-host qualification is recorded with the generated ViewModel slice. Designer fixtures additionally verify generated runtime behavior in real classpath and module-path applications. The library build evidence is `/tmp/viewmodel-runtime-qualified.log`; generated fixture evidence is `/tmp/generated-vm-fixtures-final.log`. The prior 38 adapter-free checks remain historical; current whole-host qualification is recorded with the generated ViewModel slice.
## Java 25 runtime baseline
The active manifest pins the Java 25 / JavaFX 27.0.1 NeitzelLib build. To qualify it in an isolated Maven repository, set `NEITZELLIB_MAVEN_REPOSITORY` to that repository and set `MAVEN_OPTS=-Dmaven.repo.local=$NEITZELLIB_MAVEN_REPOSITORY` for the build. The manifest records the exact source revision, Surefire totals and artifact hashes. The core totals include a separate run with `-Ddesktop.native.tests=true`.
@@ -0,0 +1,32 @@
package fixture.components;
@jakarta.inject.Singleton
@de.neitzel.fx.view.ViewModelClass(CommandCard.Model.class)
public class CommandCard extends javafx.scene.layout.VBox {
private final javafx.beans.property.ObjectProperty<fixture.model.Address> model =
new javafx.beans.property.SimpleObjectProperty<>();
public javafx.beans.property.ObjectProperty<fixture.model.Address> modelProperty() {
return model;
}
public static class Model extends de.neitzel.fx.view.ViewModel {
private final de.neitzel.fx.view.Command run;
public Model(fixture.model.Address model) {
super(model);
var enabled = new javafx.beans.property.SimpleBooleanProperty(true);
run =
new de.neitzel.fx.view.Command(
enabled,
() -> {
model.setStreet("Command executed");
enabled.set(false);
});
}
public de.neitzel.fx.view.Command getRun() {
return run;
}
}
}
@@ -15,6 +15,7 @@ public class PersonController implements de.neitzel.fx.view.HasViewModel {
return "Uncertain"; return "Uncertain";
} }
public static PersonController boundController;
public final Greeting greeting; public final Greeting greeting;
public de.neitzel.fx.view.ViewModel received; public de.neitzel.fx.view.ViewModel received;
@@ -25,6 +26,7 @@ public class PersonController implements de.neitzel.fx.view.HasViewModel {
public void setViewModel(de.neitzel.fx.view.ViewModel vm) { public void setViewModel(de.neitzel.fx.view.ViewModel vm) {
received = vm; received = vm;
boundController = this;
} }
public void action() { public void action() {
@@ -0,0 +1,8 @@
<?neitzel-model fixture.model.Address?>
<?import javafx.scene.control.Button?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.CommandBinding?>
<fx:root xmlns:fx="http://javafx.com/fxml/1" type="javafx.scene.layout.VBox">
<fx:define><BindingList><CommandBinding control="run" path="run"/></BindingList></fx:define>
<Button fx:id="run" text="Run"/>
</fx:root>
@@ -52,7 +52,8 @@ public final class PreviewChecks {
if (mode.equals("unstable") if (mode.equals("unstable")
|| mode.equals("full") || mode.equals("full")
|| mode.equals("full-empty") || mode.equals("full-empty")
|| mode.equals("card")) { || mode.equals("card")
|| mode.equals("command-card")) {
StageChecks.run(mode); StageChecks.run(mode);
return; return;
} }
@@ -345,7 +346,7 @@ public final class PreviewChecks {
() -> { () -> {
var view = ready.loadedView(); var view = ready.loadedView();
check(view.getViewModel() instanceof PersonViewModel, "Named ViewModel not selected"); check(view.getViewModel() instanceof PersonViewModel, "Named ViewModel not selected");
var controller = Examples.context.getComponent(PersonController.class); var controller = PersonController.boundController;
check(controller.received == view.getViewModel(), "Controller ViewModel handoff"); check(controller.received == view.getViewModel(), "Controller ViewModel handoff");
check(controller.greeting == Examples.service, "Configured service not injected"); check(controller.greeting == Examples.service, "Configured service not injected");
var card = (Card) view.getRoot().lookup("#card"); var card = (Card) view.getRoot().lookup("#card");
@@ -20,17 +20,25 @@ public final class StageChecks {
if (!started.await(10, TimeUnit.SECONDS)) throw new AssertionError("FX startup"); if (!started.await(10, TimeUnit.SECONDS)) throw new AssertionError("FX startup");
var descriptor = var descriptor =
ExampleCatalog.discover(StageChecks.class.getClassLoader()).stream() ExampleCatalog.discover(StageChecks.class.getClassLoader()).stream()
.filter(e -> e.id().equals(mode.equals("unstable") ? "full" : mode)) .filter(
e ->
e.id()
.equals(
mode.equals("unstable")
? "full"
: mode.equals("command-card") ? "card" : mode))
.findFirst() .findFirst()
.orElseThrow(); .orElseThrow();
if (mode.equals("unstable")) if (mode.equals("unstable") || mode.equals("command-card"))
descriptor = descriptor =
new de.neitzel.fxdesigner.preview.ExampleDescriptor( new de.neitzel.fxdesigner.preview.ExampleDescriptor(
descriptor.id(), descriptor.id(),
descriptor.label(), descriptor.label(),
descriptor.modelType(), descriptor.modelType(),
descriptor.providerClass(), descriptor.providerClass(),
"fixture/components/Unstable.fxml", mode.equals("unstable")
? "fixture/components/Unstable.fxml"
: "fixture/components/CommandCard.fxml",
descriptor.componentPackage()); descriptor.componentPackage());
var preview = var preview =
TargetPreview.open(descriptor, StageChecks.class.getClassLoader(), Duration.ofSeconds(15)); TargetPreview.open(descriptor, StageChecks.class.getClassLoader(), Duration.ofSeconds(15));
@@ -55,7 +63,15 @@ public final class StageChecks {
PreviewChecks.fx( PreviewChecks.fx(
() -> { () -> {
var root = ready.loadedView().getRoot(); var root = ready.loadedView().getRoot();
if (mode.equals("card")) { if (mode.equals("command-card")) {
var button = (Button) root.lookup("#run");
var model = (fixture.model.Address) ((CommandCard) root).modelProperty().get();
button.fire();
PreviewChecks.check(
model.getStreet().equals("Command executed"), "Component command");
PreviewChecks.check(
button.isDisabled(), "Component command disabled after execution");
} else if (mode.equals("card")) {
var card = (Card) root; var card = (Card) root;
PreviewChecks.check( PreviewChecks.check(
card.street().getText().equals("Independent Card sample"), card.street().getText().equals("Independent Card sample"),
@@ -14,7 +14,7 @@
<!-- Dependency versions --> <!-- Dependency versions -->
<designer.version>0.1.0-SNAPSHOT</designer.version> <designer.version>0.1.0-SNAPSHOT</designer.version>
<neitzellib.version>1.0-SNAPSHOT</neitzellib.version> <neitzellib.version>1.0.6-SNAPSHOT</neitzellib.version>
<!-- Plugin versions --> <!-- Plugin versions -->
<maven.compiler.plugin>3.16.0</maven.compiler.plugin> <maven.compiler.plugin>3.16.0</maven.compiler.plugin>
@@ -0,0 +1,32 @@
package fixture.components;
@jakarta.inject.Singleton
@de.neitzel.fx.view.ViewModelClass(CommandCard.Model.class)
public class CommandCard extends javafx.scene.layout.VBox {
private final javafx.beans.property.ObjectProperty<fixture.model.Address> model =
new javafx.beans.property.SimpleObjectProperty<>();
public javafx.beans.property.ObjectProperty<fixture.model.Address> modelProperty() {
return model;
}
public static class Model extends de.neitzel.fx.view.ViewModel {
private final de.neitzel.fx.view.Command run;
public Model(fixture.model.Address model) {
super(model);
var enabled = new javafx.beans.property.SimpleBooleanProperty(true);
run =
new de.neitzel.fx.view.Command(
enabled,
() -> {
model.setStreet("Command executed");
enabled.set(false);
});
}
public de.neitzel.fx.view.Command getRun() {
return run;
}
}
}
@@ -15,6 +15,7 @@ public class PersonController implements de.neitzel.fx.view.HasViewModel {
return "Uncertain"; return "Uncertain";
} }
public static PersonController boundController;
public final Greeting greeting; public final Greeting greeting;
public de.neitzel.fx.view.ViewModel received; public de.neitzel.fx.view.ViewModel received;
@@ -25,6 +26,7 @@ public class PersonController implements de.neitzel.fx.view.HasViewModel {
public void setViewModel(de.neitzel.fx.view.ViewModel vm) { public void setViewModel(de.neitzel.fx.view.ViewModel vm) {
received = vm; received = vm;
boundController = this;
} }
public void action() { public void action() {
@@ -0,0 +1,8 @@
<?neitzel-model fixture.model.Address?>
<?import javafx.scene.control.Button?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.CommandBinding?>
<fx:root xmlns:fx="http://javafx.com/fxml/1" type="javafx.scene.layout.VBox">
<fx:define><BindingList><CommandBinding control="run" path="run"/></BindingList></fx:define>
<Button fx:id="run" text="Run"/>
</fx:root>
@@ -52,7 +52,8 @@ public final class PreviewChecks {
if (mode.equals("unstable") if (mode.equals("unstable")
|| mode.equals("full") || mode.equals("full")
|| mode.equals("full-empty") || mode.equals("full-empty")
|| mode.equals("card")) { || mode.equals("card")
|| mode.equals("command-card")) {
StageChecks.run(mode); StageChecks.run(mode);
return; return;
} }
@@ -345,7 +346,7 @@ public final class PreviewChecks {
() -> { () -> {
var view = ready.loadedView(); var view = ready.loadedView();
check(view.getViewModel() instanceof PersonViewModel, "Named ViewModel not selected"); check(view.getViewModel() instanceof PersonViewModel, "Named ViewModel not selected");
var controller = Examples.context.getComponent(PersonController.class); var controller = PersonController.boundController;
check(controller.received == view.getViewModel(), "Controller ViewModel handoff"); check(controller.received == view.getViewModel(), "Controller ViewModel handoff");
check(controller.greeting == Examples.service, "Configured service not injected"); check(controller.greeting == Examples.service, "Configured service not injected");
var card = (Card) view.getRoot().lookup("#card"); var card = (Card) view.getRoot().lookup("#card");
@@ -20,17 +20,25 @@ public final class StageChecks {
if (!started.await(10, TimeUnit.SECONDS)) throw new AssertionError("FX startup"); if (!started.await(10, TimeUnit.SECONDS)) throw new AssertionError("FX startup");
var descriptor = var descriptor =
ExampleCatalog.discover(StageChecks.class.getClassLoader()).stream() ExampleCatalog.discover(StageChecks.class.getClassLoader()).stream()
.filter(e -> e.id().equals(mode.equals("unstable") ? "full" : mode)) .filter(
e ->
e.id()
.equals(
mode.equals("unstable")
? "full"
: mode.equals("command-card") ? "card" : mode))
.findFirst() .findFirst()
.orElseThrow(); .orElseThrow();
if (mode.equals("unstable")) if (mode.equals("unstable") || mode.equals("command-card"))
descriptor = descriptor =
new de.neitzel.fxdesigner.preview.ExampleDescriptor( new de.neitzel.fxdesigner.preview.ExampleDescriptor(
descriptor.id(), descriptor.id(),
descriptor.label(), descriptor.label(),
descriptor.modelType(), descriptor.modelType(),
descriptor.providerClass(), descriptor.providerClass(),
"fixture/components/Unstable.fxml", mode.equals("unstable")
? "fixture/components/Unstable.fxml"
: "fixture/components/CommandCard.fxml",
descriptor.componentPackage()); descriptor.componentPackage());
var preview = var preview =
TargetPreview.open(descriptor, StageChecks.class.getClassLoader(), Duration.ofSeconds(15)); TargetPreview.open(descriptor, StageChecks.class.getClassLoader(), Duration.ofSeconds(15));
@@ -55,7 +63,15 @@ public final class StageChecks {
PreviewChecks.fx( PreviewChecks.fx(
() -> { () -> {
var root = ready.loadedView().getRoot(); var root = ready.loadedView().getRoot();
if (mode.equals("card")) { if (mode.equals("command-card")) {
var button = (Button) root.lookup("#run");
var model = (fixture.model.Address) ((CommandCard) root).modelProperty().get();
button.fire();
PreviewChecks.check(
model.getStreet().equals("Command executed"), "Component command");
PreviewChecks.check(
button.isDisabled(), "Component command disabled after execution");
} else if (mode.equals("card")) {
var card = (Card) root; var card = (Card) root;
PreviewChecks.check( PreviewChecks.check(
card.street().getText().equals("Independent Card sample"), card.street().getText().equals("Independent Card sample"),
@@ -16,7 +16,7 @@
<!-- Dependency versions --> <!-- Dependency versions -->
<designer.version>0.1.0-SNAPSHOT</designer.version> <designer.version>0.1.0-SNAPSHOT</designer.version>
<neitzellib.version>1.0-SNAPSHOT</neitzellib.version> <neitzellib.version>1.0.6-SNAPSHOT</neitzellib.version>
<!-- Plugin versions --> <!-- Plugin versions -->
<maven.compiler.plugin>3.16.0</maven.compiler.plugin> <maven.compiler.plugin>3.16.0</maven.compiler.plugin>
@@ -0,0 +1,37 @@
package qualification;
import de.neitzel.fxdesigner.target.ExampleCatalog;
import de.neitzel.fxdesigner.target.TargetPreview;
import java.time.Duration;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
/** Run once per example in a fresh target JVM with fx-example's designer test classpath. */
public final class PersonDeskRender {
public static void main(String[] args) throws Exception {
var loader = PersonDeskRender.class.getClassLoader();
var example =
ExampleCatalog.discover(loader).stream()
.filter(entry -> entry.id().equals(args[0]))
.findFirst()
.orElseThrow();
Platform.startup(() -> Platform.setImplicitExit(false));
try (var preview = TargetPreview.open(example, loader, Duration.ofSeconds(15))) {
preview.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
var render = new FutureTask<>(() -> preview.render(480, 320));
Platform.runLater(render);
byte[] rgba = render.get(10, TimeUnit.SECONDS);
int distinct = 0;
for (int p = 4; p < rgba.length; p += 4) {
if (rgba[p] != rgba[0] || rgba[p + 1] != rgba[1] || rgba[p + 2] != rgba[2]) distinct++;
}
if (rgba.length != 480 * 320 * 4 || distinct < 100)
throw new AssertionError("Incomplete or blank frame for " + example.id());
System.out.printf(
"PASS %s 480x320, %d pixels differ from background%n", example.id(), distinct);
} finally {
Platform.exit();
}
}
}
@@ -0,0 +1,115 @@
package qualification;
import java.nio.file.*;
import java.util.concurrent.*;
import javafx.application.Platform;
import javafx.scene.control.*;
import javafx.stage.Window;
/**
* Test-only agent. Exercise the actual scene when the plugin opens its interactive target window.
*/
public final class ArchiveTargetProbe {
public static void premain(String directory) {
if (System.getProperty("sun.java.command", "")
.startsWith("de.neitzel.fxdesigner.target.WorkerMain ")) {
Thread.ofPlatform()
.daemon()
.name("archiver-preview-probe")
.start(() -> Probe.observe(Path.of(directory)));
}
}
private static class Probe {
static void observe(Path directory) {
try {
while (true) {
Thread.sleep(150);
var check = new FutureTask<>(() -> inspect(directory));
try {
Platform.runLater(check);
} catch (IllegalStateException toolkitStarting) {
continue;
}
if (check.get(10, TimeUnit.SECONDS)) return;
}
} catch (Throwable error) {
try {
Files.writeString(directory.resolve("target-error.txt"), error.toString());
} catch (java.io.IOException writeError) {
error.printStackTrace();
}
}
}
static boolean inspect(Path directory) throws Exception {
var stage =
Window.getWindows().stream()
.filter(Window::isShowing)
.filter(w -> w.getScene().lookup("#trash-button") instanceof Button)
.findFirst();
if (stage.isEmpty()) return false;
var root = stage.get().getScene().getRoot();
var status = (Label) root.lookup("#status");
var trash = (Button) root.lookup("#trash-button");
var menu = ((MenuBar) root.lookup(".menu-bar")).getMenus().getFirst();
var menuCommands =
((MenuBar) root.lookup(".menu-bar"))
.getMenus().stream()
.flatMap(group -> group.getItems().stream())
.filter(item -> !(item instanceof Menu))
.filter(item -> item.getOnAction() != null)
.count();
if (menuCommands != 21 || trash.getOnAction() == null)
throw new AssertionError(
"Expected 21 menu commands and the trash button, got " + menuCommands);
var open =
menu.getItems().stream()
.filter(m -> "Archiv öffnen …".equals(m.getText()))
.findFirst()
.orElseThrow();
if (!trash.isDisabled() || !status.getText().equals("Vorschau · Bereit"))
throw new AssertionError("Expected a fresh, closed example");
trash.fire();
if (!status.getText().equals("Vorschau · Bereit"))
throw new AssertionError("Disabled command ran");
if (((TreeView<?>) root.lookup("#folders")).getRoot() == null
|| root.lookup("#dockPane").lookupAll(".label").stream()
.noneMatch(
n -> n instanceof Label l && l.getText().equals("Dokument im Beispielarchiv")))
return false;
open.fire();
String afterOpen = status.getText();
if (trash.isDisabled() || !afterOpen.endsWith(" · 1")) throw new AssertionError(afterOpen);
trash.fire();
String afterTrash = status.getText();
if (!afterTrash.equals("Vorschau · Beispielpapierkorb geöffnet · 2"))
throw new AssertionError(afterTrash);
String run = Files.readString(directory.resolve("attempt")).trim();
var image = root.snapshot(null, null);
int width = (int) image.getWidth(), height = (int) image.getHeight();
int[] argb = new int[width * height];
image
.getPixelReader()
.getPixels(
0,
0,
width,
height,
javafx.scene.image.PixelFormat.getIntArgbInstance(),
argb,
0,
width);
var screenshot =
new java.awt.image.BufferedImage(
width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB);
screenshot.setRGB(0, 0, width, height, argb, 0, width);
javax.imageio.ImageIO.write(
screenshot, "png", directory.resolve("preview-" + run + ".png").toFile());
Files.writeString(
directory.resolve("result-" + run),
afterOpen + "\n" + afterTrash + "\n" + ProcessHandle.current().pid());
return true;
}
}
}
@@ -0,0 +1,408 @@
package qualification;
import static qualification.WorkflowProbe.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.vfs.*;
import de.neitzel.fxdesigner.kit.DesignerPane;
import java.nio.file.*;
import java.util.concurrent.Callable;
import javafx.scene.control.*;
public final class ArchiveWorkflowProbe implements StartupActivity.DumbAware {
private static final String RESOURCE =
"src/main/resources/de/neitzel/archiver/ui/ArchiveWindow.fxml";
private static DesignerPane pane;
public void runActivity(Project project) {
if (!started.compareAndSet(false, true)) return;
ApplicationManager.getApplication()
.executeOnPooledThread(
() -> {
try {
verify(project);
} catch (Throwable error) {
try {
var trace = new java.io.StringWriter();
error.printStackTrace(new java.io.PrintWriter(trace));
if (pane != null)
trace.append(
fx(
() ->
pane.lookupAll(".label").stream()
.filter(Label.class::isInstance)
.map(n -> ((Label) n).getText())
.toList()
.toString()));
Files.writeString(output.resolve("FAILURE.txt"), trace.toString());
} catch (Exception writeError) {
error.printStackTrace();
}
}
});
}
private static void open(Project project, VirtualFile file) throws Exception {
var editor =
edt(
() -> {
var manager = FileEditorManager.getInstance(project);
var all = manager.openFile(file, true);
manager.setSelectedEditor(file, "neitzel-fx-designer");
return java.util.Arrays.stream(all)
.filter(e -> e.getName().equals("Neitzel Designer"))
.findFirst()
.orElseThrow();
});
await(() -> edt(() -> bridge(editor.getComponent()) != null));
var panel = edt(() -> bridge(editor.getComponent()));
await(() -> fx(() -> panel.getScene() != null));
pane = fx(() -> (DesignerPane) panel.getScene().getRoot());
await(() -> fx(() -> pane.kit().editor().getFxomDocument() != null));
}
private static void tab(String name) 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 -> name.equals(t.getText()))
.findFirst()
.orElseThrow());
pane.applyCss();
pane.layout();
return null;
});
}
private static void select(String id, String prefix) throws Exception {
fx(
() -> {
var list = (ListView<?>) pane.lookup("#" + id);
for (int i = 0; i < list.getItems().size(); i++) {
if (list.getItems().get(i).toString().startsWith(prefix)) {
list.getSelectionModel().select(i);
return null;
}
}
throw new AssertionError("Missing " + prefix + " in " + list.getItems());
});
}
private static void step(String message) throws Exception {
Files.writeString(
output.resolve("steps.txt"),
message + "\n",
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
}
private static void interactive(String run, String expected) throws Exception {
Files.writeString(output.resolve("attempt"), run);
click(pane, "Interactive preview");
var result = output.resolve("result-" + run);
await(
() -> {
if (Files.exists(output.resolve("target-error.txt")))
throw new AssertionError(Files.readString(output.resolve("target-error.txt")));
return Files.exists(result);
});
if (!Files.readString(result).contains(expected + " · 1"))
throw new AssertionError(Files.readString(result));
step("Interactive " + run + ": " + Files.readString(result));
}
private static void verifyCrossViewPaste(Project project, VirtualFile original, Path other)
throws Exception {
var destination = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(other));
String expected = Files.readString(other);
tab("Structure");
select("structure-nodes", "openExample :");
click(pane, "Copy subtree");
open(project, destination);
click(pane, "Preview last successful");
await(
() ->
fx(
() ->
pane.lookupAll(".label").stream()
.anyMatch(
n ->
n instanceof Label label
&& label.getText() != null
&& label
.getText()
.contains(
"Select a preview example after Build and Refresh"))));
tab("Structure");
select("structure-nodes", "recent :");
click(pane, "Paste subtree");
await(
() ->
fx(
() ->
((Label) pane.lookup("#structure-status"))
.getText()
.contains("Unknown Command path: openReadOnly")));
if (!edt(() -> FileDocumentManager.getInstance().getDocument(destination).getText())
.equals(expected))
throw new AssertionError("Incompatible paste changed the destination document");
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(destination);
return null;
});
open(project, original);
step("Cross-View paste rejected at missing Command getter before writing");
}
private static void verify(Project project) throws Exception {
var path = Path.of(project.getBasePath(), RESOURCE);
var other = path.resolveSibling("ArchivePasteDestination.fxml");
String originalSource = Files.readString(path);
Files.writeString(
other,
originalSource.substring(0, originalSource.indexOf("<BorderPane"))
+ "<BorderPane xmlns:fx='http://javafx.com/fxml/1'><top><MenuBar><menus>"
+ "<Menu fx:id='recent'/></menus></MenuBar></top></BorderPane>");
var file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
open(project, file);
fx(
() -> {
var root =
(javafx.scene.layout.BorderPane)
pane.kit().editor().getFxomDocument().getSceneGraphRoot();
if (!(root.getTop() instanceof MenuBar)
|| !(root.getCenter() instanceof SplitPane)
|| !new javafx.geometry.Insets(5, 12, 9, 12)
.equals(javafx.scene.layout.BorderPane.getMargin(root.getBottom())))
throw new AssertionError("Incomplete Kit layout or incorrect status bar margin");
return null;
});
step("Registered editor opened ArchiveWindow.fxml");
click(pane, "Build and Refresh");
await(
() ->
fx(
() ->
pane.lookupAll(".combo-box").stream()
.anyMatch(
n ->
n instanceof ComboBox<?> c
&& c.getValue() != null
&& c.getValue().toString().contains("Beispielarchiv"))));
step("Build and Refresh discovered Archiver example");
tab("Command bindings");
await(() -> fx(() -> ((ListView<?>) pane.lookup("#command-bindings")).getItems().size() == 22));
interactive("initial", "Beispielarchiv geöffnet");
click(pane, "Stop preview");
select("command-bindings", "open ←");
fx(
() -> {
((TextField) pane.lookup("#command-path")).setText("openReadOnly");
return null;
});
click(pane, "Apply Command binding");
Callable<String> source =
() -> edt(() -> FileDocumentManager.getInstance().getDocument(file).getText());
await(() -> source.call().contains("control=\"open\" path=\"openReadOnly\""));
click(pane, "Save");
await(() -> Files.readString(path).contains("control=\"open\" path=\"openReadOnly\""));
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(file);
return null;
});
open(project, file);
click(pane, "Build and Refresh");
await(
() ->
fx(
() ->
pane.lookupAll(".combo-box").stream()
.anyMatch(
n ->
n instanceof ComboBox<?> c
&& c.getValue() != null
&& c.getValue().toString().contains("Beispielarchiv"))));
interactive("edited", "Beispielarchiv schreibgeschützt geöffnet");
click(pane, "Stop preview");
tab("Structure");
select("structure-nodes", "open :");
fx(
() -> {
((TextField) pane.lookup("#structure-name")).setText("openExample");
return null;
});
click(pane, "Rename identifier");
String renamed = "control=\"openExample\" path=\"openReadOnly\"";
await(() -> source.call().contains(renamed));
String afterRename = source.call();
if (!afterRename.contains(
"fx:id=\"openExample\" text=\"Archiv öffnen …\" accelerator=\"Shortcut+O\""))
throw new AssertionError("Rename lost the menu accelerator");
click(pane, "Undo");
await(() -> !source.call().contains(renamed));
click(pane, "Redo");
await(() -> source.call().contains(renamed));
select("structure-nodes", "openExample :");
click(pane, "Copy subtree");
select("structure-nodes", "recent :");
click(pane, "Paste subtree");
String duplicate = "control=\"openExampleCopy\" path=\"openReadOnly\"";
await(() -> source.call().contains(duplicate));
String afterPaste = source.call();
click(pane, "Undo");
await(() -> source.call().equals(afterRename));
click(pane, "Redo");
await(() -> source.call().equals(afterPaste));
click(pane, "Undo");
await(() -> source.call().equals(afterRename));
select("structure-nodes", "openExample :");
click(pane, "Delete subtree");
await(() -> !source.call().contains("openExample"));
click(pane, "Undo");
await(() -> source.call().contains(renamed));
click(pane, "Save");
await(() -> Files.readString(path).contains(renamed));
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(file);
return null;
});
open(project, file);
click(pane, "Build and Refresh");
await(
() ->
fx(
() ->
pane.lookupAll(".combo-box").stream()
.anyMatch(
n ->
n instanceof ComboBox<?> c
&& c.getValue() != null
&& c.getValue().toString().contains("Beispielarchiv"))));
tab("Command bindings");
select("command-bindings", "openExample ←");
click(pane, "Remove Command binding");
await(() -> !source.call().contains(renamed));
click(pane, "New Command binding");
fx(
() -> {
((TextField) pane.lookup("#command-control")).setText("openExample");
((TextField) pane.lookup("#command-path")).setText("openReadOnly");
return null;
});
click(pane, "Apply Command binding");
await(() -> source.call().contains(renamed));
click(pane, "Undo");
await(() -> !source.call().contains(renamed));
click(pane, "Undo");
await(() -> source.call().equals(afterRename));
select("command-bindings", "openExample ←");
fx(
() -> {
((TextField) pane.lookup("#command-path")).setText("missingCommand");
return null;
});
click(pane, "Apply Command binding");
await(() -> source.call().contains("missingCommand"));
click(pane, "Discover / Validate Commands");
await(
() ->
fx(
() ->
((Label) pane.lookup("#command-status"))
.getText()
.contains("Unknown Command path: missingCommand")));
var collector = com.intellij.analysis.problemsView.ProblemsCollector.getInstance(project);
await(
() ->
edt(
() ->
collector.getFileProblems(file).stream()
.anyMatch(p -> p.getText().contains("missingCommand"))));
edt(
() -> {
var problem =
(com.intellij.analysis.problemsView.FileProblem)
collector.getFileProblems(file).stream()
.filter(p -> p.getText().contains("missingCommand"))
.findFirst()
.orElseThrow();
var doc = FileDocumentManager.getInstance().getDocument(file);
int offset = doc.getLineStartOffset(problem.getLine()) + problem.getColumn();
if (!doc.getText()
.startsWith(
"<CommandBinding control=\"openExample\" path=\"missingCommand\"", offset))
throw new AssertionError("IntelliJ problem points outside the CommandBinding");
new com.intellij.openapi.fileEditor.OpenFileDescriptor(project, file, offset)
.navigate(true);
if (FileEditorManager.getInstance(project)
.getSelectedTextEditor()
.getCaretModel()
.getOffset()
!= offset) throw new AssertionError("Navigation did not reach the CommandBinding");
FileEditorManager.getInstance(project).setSelectedEditor(file, "neitzel-fx-designer");
return null;
});
click(pane, "Undo");
await(() -> source.call().equals(afterRename));
click(pane, "Discover / Validate Commands");
await(
() ->
edt(
() ->
collector.getFileProblems(file).stream()
.noneMatch(p -> p.getText().contains("missingCommand"))));
verifyCrossViewPaste(project, file, other);
tab("Command bindings");
interactive("restored", "Beispielarchiv schreibgeschützt geöffnet");
fx(
() -> {
javax.imageio.ImageIO.write(
javafx.embed.swing.SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
"png",
output.resolve("intellij.png").toFile());
return null;
});
click(pane, "Stop preview");
// A valid application wildcard exceeds the canvas projection's import support.
String fallback =
afterRename.replace(
"<?import de.neitzel.fx.view.BindingList?>", "<?import de.neitzel.fx.view.*?>");
edt(
() -> {
var document = FileDocumentManager.getInstance().getDocument(file);
com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction(
project, () -> document.setText(fallback));
return null;
});
await(() -> fx(() -> ((TextArea) pane.lookup("#fxml-source")).getText().equals(fallback)));
interactive("unprojected", "Beispielarchiv schreibgeschützt geöffnet");
long pid = Long.parseLong(Files.readAllLines(output.resolve("result-unprojected")).getLast());
edt(
() -> {
FileEditorManager.getInstance(project).closeFile(file);
return null;
});
await(() -> ProcessHandle.of(pid).map(p -> !p.isAlive()).orElse(true));
Files.writeString(
output.resolve("SUCCESS.txt"),
"PASS Archiver A1–A5, 22 Command bindings, edited and reopened FXML, menu and button"
+ " actions, reference edits, diagnostic recovery, worker exit\n");
}
}
+1 -1
View File
@@ -22,7 +22,7 @@
<!-- Dependency versions --> <!-- Dependency versions -->
<junit.version>6.1.3</junit.version> <junit.version>6.1.3</junit.version>
<lombok.version>1.18.48</lombok.version> <lombok.version>1.18.48</lombok.version>
<neitzellib.version>1.0-SNAPSHOT</neitzellib.version> <neitzellib.version>1.0.6-SNAPSHOT</neitzellib.version>
<!-- Plugin versions --> <!-- Plugin versions -->
<maven.clean.plugin>3.5.0</maven.clean.plugin> <maven.clean.plugin>3.5.0</maven.clean.plugin>
+1 -1
View File
@@ -34,7 +34,7 @@ def run(name, command):
with tempfile.TemporaryDirectory(prefix="designer-connected-") as temporary: with tempfile.TemporaryDirectory(prefix="designer-connected-") as temporary:
for host in ("standalone", "intellij"): for host in ("standalone", "intellij"):
base = Path(temporary) / host base = (Path(temporary) / host).resolve()
for mode in ("classpath", "modulepath"): for mode in ("classpath", "modulepath"):
fixture = base / mode fixture = base / mode
shutil.copytree(ROOT / "integration-fixtures/preview" / mode, fixture, shutil.copytree(ROOT / "integration-fixtures/preview" / mode, fixture,
+5 -4
View File
@@ -22,6 +22,7 @@ p.add_argument("--target-java-home", type=Path, required=True)
p.add_argument("--idea-home", type=Path, required=True) p.add_argument("--idea-home", type=Path, required=True)
p.add_argument("--mode", choices=["all", "classpath", "modulepath"], default="all") p.add_argument("--mode", choices=["all", "classpath", "modulepath"], default="all")
p.add_argument("--repeat", type=int, default=1, help="Consecutive independent runs per mode") p.add_argument("--repeat", type=int, default=1, help="Consecutive independent runs per mode")
p.add_argument("--archiver", type=Path, help="Qualify ArchiveWindow.fxml in a disposable project copy")
args = p.parse_args() args = p.parse_args()
if args.repeat < 1: if args.repeat < 1:
p.error("--repeat must be positive") p.error("--repeat must be positive")
@@ -29,11 +30,11 @@ output = ROOT / "target/ide-workflow"
output.mkdir(parents=True, exist_ok=True) output.mkdir(parents=True, exist_ok=True)
batch = Path(tempfile.mkdtemp(prefix="runs-", dir=output)) batch = Path(tempfile.mkdtemp(prefix="runs-", dir=output))
print("Host evidence: " + str(batch), flush=True) print("Host evidence: " + str(batch), flush=True)
modes = ("classpath", "modulepath") if args.mode == "all" else (args.mode,) modes = ("classpath",) if args.archiver else (("classpath", "modulepath") if args.mode == "all" else (args.mode,))
for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode in modes): for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode in modes):
crashes = NativeCrashGuard(ROOT) crashes = NativeCrashGuard(ROOT)
launch = subprocess.run([sys.executable, ROOT / "scripts/run-fixture-host.py", "intellij", launch = subprocess.run([sys.executable, ROOT / "scripts/run-fixture-host.py", "intellij",
"--check", "--mode", mode, "--java-home", args.java_home, "--check", *(["--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], "--target-java-home", args.target_java_home, "--idea-home", args.idea_home],
cwd=ROOT, text=True, capture_output=True, check=True, timeout=60) cwd=ROOT, text=True, capture_output=True, check=True, timeout=60)
evidence = batch / f"{mode}-run-{run_number}" evidence = batch / f"{mode}-run-{run_number}"
@@ -43,7 +44,7 @@ for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode i
base = Path(re.search(r"Disposable host: (.+)", launch.stdout)[1]) base = Path(re.search(r"Disposable host: (.+)", launch.stdout)[1])
pid = int(re.search(r"Host PID: (\d+)", launch.stdout)[1]) pid = int(re.search(r"Host PID: (\d+)", launch.stdout)[1])
try: try:
until = time.monotonic() + 240 until = time.monotonic() + (480 if args.archiver else 240)
while time.monotonic() < until: while time.monotonic() < until:
if (base / "FAILURE.txt").exists(): if (base / "FAILURE.txt").exists():
raise RuntimeError((base / "FAILURE.txt").read_text()) raise RuntimeError((base / "FAILURE.txt").read_text())
@@ -73,7 +74,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")) shutil.copyfile(base / "intellij.png", output / (mode + ".png"))
(evidence / "proof.json").write_text(json.dumps(proof, indent=2) + "\n") (evidence / "proof.json").write_text(json.dumps(proof, indent=2) + "\n")
finally: finally:
for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log"): for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log", "steps.txt", "target-error.txt", "preview-restored.png"):
if (base / name).exists(): if (base / name).exists():
shutil.copyfile(base / name, evidence / name) shutil.copyfile(base / name, evidence / name)
workers = descendant_workers(pid) workers = descendant_workers(pid)
+1 -1
View File
@@ -21,5 +21,5 @@ for artifact in manifest["artifacts"]:
errors.append(f"Different build: {path}") errors.append(f"Different build: {path}")
if errors: if errors:
print("\n".join(errors), file=sys.stderr) print("\n".join(errors), file=sys.stderr)
sys.exit("Runtime identity mismatch. See docs/runtime/neitzellib-baseline.md; do not bypass this check merely because the version is 1.0-SNAPSHOT.") sys.exit("Runtime identity mismatch. See docs/runtime/neitzellib-baseline.md.")
print(f"PASS {len(manifest['artifacts'])} runtime artifacts match tested source {manifest['sourceRevision']}; no corrected release version is claimed") print(f"PASS {len(manifest['artifacts'])} runtime artifacts match tested source {manifest['sourceRevision']}; no corrected release version is claimed")
+1 -1
View File
@@ -64,7 +64,7 @@ with tempfile.TemporaryDirectory(prefix="designer-preview-") as temp:
first = None first = None
for mode in ("discovery", "bindings", "standard", "async", "timeout", "cancel", for mode in ("discovery", "bindings", "standard", "async", "timeout", "cancel",
"readiness-failure", "wrong-model", "invalid-attribute", "readiness-failure", "wrong-model", "invalid-attribute",
"cleanup-failure", "factory-failure", "viewmodels", "generated", "full", "full-empty", "card", "unstable"): "cleanup-failure", "factory-failure", "viewmodels", "generated", "full", "full-empty", "card", "command-card", "unstable"):
log = launch(path, arrangement, mode, arrangement + "-" + mode) log = launch(path, arrangement, mode, arrangement + "-" + mode)
if mode == "standard": if mode == "standard":
first = re.search(r"SESSION (\S+) models=1", log)[1] first = re.search(r"SESSION (\S+) models=1", log)[1]
+8 -4
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Create ignored local launch settings for NeitzelLib's checked-in fx-example context.""" """Create ignored local launch settings for a project with a checked-in Designer context."""
import argparse import argparse
import json import json
import os import os
@@ -7,7 +7,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent ROOT = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--library", type=Path, required=True) parser.add_argument("--library", "--project", type=Path, required=True)
parser.add_argument("--target-java-home", type=Path, required=True) parser.add_argument("--target-java-home", type=Path, required=True)
parser.add_argument("--maven", type=Path, default=ROOT / "mvnw") parser.add_argument("--maven", type=Path, default=ROOT / "mvnw")
args = parser.parse_args() args = parser.parse_args()
@@ -15,7 +15,11 @@ library = args.library.resolve()
java = args.target_java_home.resolve() java = args.target_java_home.resolve()
maven = args.maven.resolve() maven = args.maven.resolve()
if not (library / "neitzel-fx-designer.json").is_file(): if not (library / "neitzel-fx-designer.json").is_file():
parser.error("Library checkout has no designer configuration") parser.error("Project has no designer configuration")
contexts = json.loads((library / "neitzel-fx-designer.json").read_text())["contexts"]
if len(contexts) != 1:
parser.error("Expected a single example context")
context = next(iter(contexts))
if not all((java / "bin" / name).is_file() for name in ("java", "javac")): if not all((java / "bin" / name).is_file() for name in ("java", "javac")):
parser.error("Supply a full application JDK installation") parser.error("Supply a full application JDK installation")
if not maven.is_file() or not os.access(maven, os.X_OK): if not maven.is_file() or not os.access(maven, os.X_OK):
@@ -50,7 +54,7 @@ def prop(value):
with launch.open("x", encoding="ascii") as file: with launch.open("x", encoding="ascii") as file:
file.write("configuration=../neitzel-fx-designer.json\ncontext=person-desk\n" file.write(f"configuration=../neitzel-fx-designer.json\ncontext={context}\n"
"settings=runtimes.json\nmaven=" + prop(maven) + "\ntools=" "settings=runtimes.json\nmaven=" + prop(maven) + "\ntools="
+ os.pathsep.join(map(prop, tools)) + "\n") + os.pathsep.join(map(prop, tools)) + "\n")
print(settings) print(settings)
+27 -3
View File
@@ -18,13 +18,22 @@ p.add_argument("--target-java-home", type=Path, required=True)
p.add_argument("--idea-home", type=Path) p.add_argument("--idea-home", type=Path)
p.add_argument("--check", action="store_true", help="Install the disposable IDE qualification companion") p.add_argument("--check", action="store_true", help="Install the disposable IDE qualification companion")
p.add_argument("--mode", choices=["classpath","modulepath"], default="classpath") p.add_argument("--mode", choices=["classpath","modulepath"], default="classpath")
p.add_argument("--archiver", type=Path, help="Use a disposable copy of the Archiver project")
args = p.parse_args() args = p.parse_args()
base = Path(tempfile.mkdtemp(prefix="neitzel-designer-host-")).resolve() base = Path(tempfile.mkdtemp(prefix="neitzel-designer-host-")).resolve()
project = base / "project" project = base / "project"
if args.archiver:
if args.host != "intellij" or args.mode != "classpath":
p.error("Archiver requires the IntelliJ classpath configuration")
shutil.copytree(args.archiver, project, ignore=shutil.ignore_patterns(".git", ".idea", "target", ".neitzel-fx-designer"))
subprocess.run([sys.executable, ROOT / "scripts/configure-library-example.py", "--project", project,
"--target-java-home", args.target_java_home], check=True)
file = project / "src/main/resources/de/neitzel/archiver/ui/ArchiveWindow.fxml"
else:
subprocess.run([sys.executable, ROOT / "scripts/prepare-fixture-host.py", "--destination", project, subprocess.run([sys.executable, ROOT / "scripts/prepare-fixture-host.py", "--destination", project,
"--target-java-home", args.target_java_home, "--mode", args.mode], check=True) "--target-java-home", args.target_java_home, "--mode", args.mode], check=True)
settings = project / ".neitzel-fx-designer/host.properties"
file = project / "app/src/main/resources/fixture/components/Person.fxml" file = project / "app/src/main/resources/fixture/components/Person.fxml"
settings = project / ".neitzel-fx-designer/host.properties"
env = dict(os.environ) env = dict(os.environ)
if args.host == "standalone": if args.host == "standalone":
cp = os.pathsep.join([str(ROOT / "designer-standalone/target/classes"), cp = os.pathsep.join([str(ROOT / "designer-standalone/target/classes"),
@@ -44,11 +53,26 @@ else:
checks.parent.mkdir(parents=True) checks.parent.mkdir(parents=True)
shutil.copyfile(ROOT / "designer-kit-ui/target/designer-kit-ui-0.1.0-SNAPSHOT-tests.jar", checks) shutil.copyfile(ROOT / "designer-kit-ui/target/designer-kit-ui-0.1.0-SNAPSHOT-tests.jar", checks)
jars = [*(args.idea_home / "lib").glob("*.jar"), *(base / "plugins").rglob("*.jar"), *(args.idea_home / "plugins/platform-problemView-plugin").rglob("*.jar")] jars = [*(args.idea_home / "lib").glob("*.jar"), *(base / "plugins").rglob("*.jar"), *(args.idea_home / "plugins/platform-problemView-plugin").rglob("*.jar")]
sources = ROOT / "integration-tests/idea"
probe = "ArchiveWorkflowProbe" if args.archiver else "WorkflowProbe"
files = [sources / "WorkflowProbe.java"]
if args.archiver:
files.append(sources / "ArchiveWorkflowProbe.java")
agent_classes = base / "agent-classes"
agent_classes.mkdir()
subprocess.run([args.java_home / "bin/javac", "-cp", os.pathsep.join(map(str,jars)), "-d", agent_classes,
sources / "ArchiveTargetProbe.java"], check=True)
agent = base / "archiver-ui-check.jar"
with zipfile.ZipFile(agent, "w") as archive:
archive.writestr("META-INF/MANIFEST.MF", "Manifest-Version: 1.0\nPremain-Class: qualification.ArchiveTargetProbe\n\n")
for item in agent_classes.rglob("*.class"):
archive.write(item, item.relative_to(agent_classes))
env["JAVA_TOOL_OPTIONS"] = env.get("JAVA_TOOL_OPTIONS", "") + f' "-javaagent:{agent}={base}"'
subprocess.run([str(args.java_home / "bin/javac"), "-cp", os.pathsep.join(map(str,jars)), "-d", str(classes), subprocess.run([str(args.java_home / "bin/javac"), "-cp", os.pathsep.join(map(str,jars)), "-d", str(classes),
str(ROOT / "integration-tests/idea/WorkflowProbe.java")], check=True) *files], check=True)
meta = classes / "META-INF" meta = classes / "META-INF"
meta.mkdir() meta.mkdir()
(meta / "plugin.xml").write_text('<idea-plugin><id>de.neitzel.fxdesigner.qualification</id><name>Designer workflow qualification</name><version>1</version><vendor>Local tests</vendor><idea-version since-build="263" until-build="263.*"/><depends>com.intellij.modules.platform</depends><depends>de.neitzel.fxdesigner</depends><depends>com.intellij.problemsView</depends><extensions defaultExtensionNs="com.intellij"><postStartupActivity implementation="qualification.WorkflowProbe"/></extensions></idea-plugin>') (meta / "plugin.xml").write_text('<idea-plugin><id>de.neitzel.fxdesigner.qualification</id><name>Designer workflow qualification</name><version>1</version><vendor>Local tests</vendor><idea-version since-build="263" until-build="263.*"/><depends>com.intellij.modules.platform</depends><depends>de.neitzel.fxdesigner</depends><depends>com.intellij.problemsView</depends><extensions defaultExtensionNs="com.intellij"><postStartupActivity implementation="qualification.'+probe+'"/></extensions></idea-plugin>')
jar = base / "plugins/qualification/lib/qualification.jar" jar = base / "plugins/qualification/lib/qualification.jar"
jar.parent.mkdir(parents=True, exist_ok=True) jar.parent.mkdir(parents=True, exist_ok=True)
subprocess.run([str(args.java_home / "bin/jar"), "cf", str(jar), "-C", str(classes), "."], check=True) subprocess.run([str(args.java_home / "bin/jar"), "cf", str(jar), "-C", str(classes), "."], check=True)