Merge IntelliJ visual editing and Archiver preview verification
This commit is contained in:
@@ -66,6 +66,31 @@ Qualify the registered editor and loaded JavaFX natives in real disposable IDE w
|
||||
python3 scripts/check-ide-host.py --java-home "$JAVA_HOME" --target-java-home "$TARGET_JAVA_HOME" --idea-home "$IDEA_HOME"
|
||||
```
|
||||
|
||||
### Archiver in IntelliJ
|
||||
|
||||
Build the [pinned NeitzelLib snapshot](docs/runtime/neitzellib-baseline.md), then build the Designer modules and plugin with the bootstrap command above. Archiver includes its preview examples in the `designer-preview` Maven profile. To open an isolated IntelliJ instance with a project copy and the built plugin, run from this checkout with the same Maven environment:
|
||||
|
||||
```sh
|
||||
python3 scripts/run-fixture-host.py intellij --archiver ../Archiver \
|
||||
--idea-home "$IDEA_HOME" --java-home "$JAVA_HOME" --target-java-home "$JAVA_HOME"
|
||||
```
|
||||
|
||||
Open `ArchiveWindow.fxml` in **Neitzel Designer**, choose **Build and Refresh** and start **Interactive preview** with **Beispielarchiv**. The open menu command enables the trash button. Under **Bindings → Command bindings** select `open`, change its path to `openReadOnly`, apply and restart the preview. The status bar identifies the read-only example. **Discover / Validate Commands** lists public getters returning a NeitzelLib `Command`, including the Command exposed by an `AsyncCommand`. The Problems view navigates to an invalid declaration. To repeat the automated acceptance, use the same arguments with `python3 scripts/check-ide-host.py --archiver ../Archiver` (omit the `intellij` positional argument).
|
||||
|
||||
Add `--connection-form` to open or qualify `ConnectionForm.fxml`. After **Build and Refresh**, choose **Form preview** and select **IMAP · Beispielkonto** or **JMAP · Beispielkonto**. The full image comes from the target application at the selected width and height. **Interactive preview** opens a separate, editable instance of the selected example.
|
||||
|
||||
In **Form controls**, select the palette type, destination child list and insertion position, then **Insert control**. Select a control on the canvas or in **Selected control**. **Set property** and **Reset property** edit its FXML, and **Bind property** opens the direct-binding form. For **suggestions**, enter one string per line. To reorder or move a child, choose its destination and position, then **Move to destination**. Each change participates in IntelliJ Undo and Redo.
|
||||
|
||||
Open **Bindings → DataGrid / Docking** in `FolderTab.fxml` to select the grid or one of its columns. **Apply setting** writes the selected property. Clear an optional value to restore its FXML default. **Edit data binding** opens the direct binding for `items` or `source`. The **Archivordner · Beispieldateien** example loads two local files using the grid's declared columns and grouping.
|
||||
|
||||
In `ArchiveWindow.fxml`, select a layout branch to split it or an outer side area to move it. **Add area with group** creates a destination in an unused area. The **Beispielarchiv** example opens a document and its details in the declared destinations. Both the embedded image and the interactive window use this layout. To repeat both acceptance scenarios, add `--grid-docking ../NeitzelLib/fx-example/src/main/resources/de/neitzel/fx/example/docking/workspace/ReferenceWorkspace.fxml` to the Archiver host check.
|
||||
|
||||
Add `--saved-document` to the Archiver launcher or host check to open the designer-profile view `SavedDocument.fxml`. Under **Form controls**, select **HtmlViewer #article** to edit the media button labels and tooltips. Select **AutoCompleteTextField #fixed** and edit **suggestions**, one tag per line. **Build and Refresh** discovers **HTML · Rechnung** and **HTML · Lieferschein**. **Form preview** shows the rendered HTML at the selected dimensions. In **Interactive preview**, use **Dokument wechseln**, edit **HTML-Quelle**, or type **Re** and **Li** into **Dokument-Tags** before and after switching. The form binds `article.html` to `html` and `dynamic.suggestionsSource` to `tags`, both toward the view. To create either binding, open **Bindings → Discover targets**, select **view** and the model path, select the compatible control property, then choose **Use selected target → Apply binding**. **Form controls → Bind property** opens the declaration for an existing target.
|
||||
|
||||
Use `--document-tabs` with the Archiver host check to open the production archive window and select **Archiver · HTML-Dokumenttabs**. The check switches from the invoice to the delivery note and back, reads each WebView, and checks the actual suggestion popup for the same prefix in both tabs.
|
||||
|
||||
For an existing Archiver checkout, install the built plugin ZIP and create the ignored local JDK and worker mappings once with `python3 scripts/configure-library-example.py --project ../Archiver --target-java-home "$JAVA_HOME"`. Launch the IDE with access to the Maven repository containing the qualified snapshots.
|
||||
|
||||
The [save/startup reliability follow-up](docs/ide-host-reliability.md) covers queued IntelliJ VFS writes and host-revision/validation races, including repeated registered module-path qualification. Add `--mode modulepath --repeat 3` to the IDE runner to repeat that gate.
|
||||
|
||||
Worker startup cancellation and ready-preview cleanup are covered by the [native lifecycle regression](docs/native-worker-lifecycle.md); host checks also reject new native JVM crash reports.
|
||||
|
||||
+62
-2
@@ -20,7 +20,49 @@ public record BindingMetadata(
|
||||
List<RepeatOption> panes,
|
||||
List<RepeatOption> tableCollections,
|
||||
List<RepeatOption> tableRows,
|
||||
List<RepeatOption> tableColumns) {
|
||||
List<RepeatOption> tableColumns,
|
||||
List<String> commandPaths,
|
||||
List<String> commandTargets) {
|
||||
public BindingMetadata(
|
||||
String model,
|
||||
String path,
|
||||
String direction,
|
||||
List<Attribute> attributes,
|
||||
List<Target> targets,
|
||||
List<String> diagnostics,
|
||||
List<Converter> converters,
|
||||
List<Problem> problems,
|
||||
String controller,
|
||||
String viewModel,
|
||||
List<Computed> computed,
|
||||
List<RepeatOption> collections,
|
||||
List<RepeatOption> components,
|
||||
List<RepeatOption> panes,
|
||||
List<RepeatOption> tableCollections,
|
||||
List<RepeatOption> tableRows,
|
||||
List<RepeatOption> tableColumns) {
|
||||
this(
|
||||
model,
|
||||
path,
|
||||
direction,
|
||||
attributes,
|
||||
targets,
|
||||
diagnostics,
|
||||
converters,
|
||||
problems,
|
||||
controller,
|
||||
viewModel,
|
||||
computed,
|
||||
collections,
|
||||
components,
|
||||
panes,
|
||||
tableCollections,
|
||||
tableRows,
|
||||
tableColumns,
|
||||
List.of(),
|
||||
List.of());
|
||||
}
|
||||
|
||||
public BindingMetadata(
|
||||
String model,
|
||||
String path,
|
||||
@@ -160,6 +202,8 @@ public record BindingMetadata(
|
||||
tableCollections = List.copyOf(tableCollections);
|
||||
tableRows = List.copyOf(tableRows);
|
||||
tableColumns = List.copyOf(tableColumns);
|
||||
commandPaths = List.copyOf(commandPaths);
|
||||
commandTargets = List.copyOf(commandTargets);
|
||||
if (!Set.of("view", "model", "both").contains(direction))
|
||||
throw new IllegalArgumentException("Invalid direction");
|
||||
}
|
||||
@@ -167,6 +211,8 @@ public record BindingMetadata(
|
||||
public Map<String, String> encode() {
|
||||
var m = new TreeMap<String, String>();
|
||||
m.put("format", "5");
|
||||
encodeStrings(m, "commands", commandPaths);
|
||||
encodeStrings(m, "commandTargets", commandTargets);
|
||||
encodeOptions(m, "rc", collections);
|
||||
encodeOptions(m, "rt", components);
|
||||
encodeOptions(m, "rp", panes);
|
||||
@@ -228,6 +274,17 @@ public record BindingMetadata(
|
||||
return m;
|
||||
}
|
||||
|
||||
private static void encodeStrings(Map<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(
|
||||
Map<String, String> m, String prefix, List<RepeatOption> values) {
|
||||
m.put(prefix, "" + values.size());
|
||||
@@ -266,6 +323,7 @@ public record BindingMetadata(
|
||||
}
|
||||
|
||||
public static BindingMetadata decode(Map<String, String> m) {
|
||||
boolean commands = m.containsKey("commands");
|
||||
if (!"5".equals(field(m, "format")))
|
||||
throw new IllegalArgumentException("Unsupported binding metadata");
|
||||
var a = new ArrayList<Attribute>();
|
||||
@@ -333,6 +391,8 @@ public record BindingMetadata(
|
||||
decodeOptions(m, "rp"),
|
||||
decodeOptions(m, "tc"),
|
||||
decodeOptions(m, "tr"),
|
||||
decodeOptions(m, "ta"));
|
||||
decodeOptions(m, "ta"),
|
||||
commands ? decodeStrings(m, "commands") : List.of(),
|
||||
commands ? decodeStrings(m, "commandTargets") : List.of());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,13 @@ final class BindingDocument {
|
||||
enum Kind {
|
||||
DIRECT,
|
||||
COMPUTED,
|
||||
COMMAND,
|
||||
REPEAT;
|
||||
|
||||
String element() {
|
||||
return switch (this) {
|
||||
case DIRECT -> "DirectBinding";
|
||||
case COMMAND -> "CommandBinding";
|
||||
case COMPUTED -> "ComputedBinding";
|
||||
case REPEAT -> "Repeat";
|
||||
};
|
||||
@@ -54,8 +56,7 @@ final class BindingDocument {
|
||||
if (!values.pane().isEmpty())
|
||||
return values.pane() + " ← " + values.collection() + " (" + values.component() + ")";
|
||||
return values.control()
|
||||
+ "."
|
||||
+ values.property()
|
||||
+ (values.property().isEmpty() ? "" : "." + values.property())
|
||||
+ " ← "
|
||||
+ (values.method().isEmpty() ? values.path() : values.method());
|
||||
}
|
||||
@@ -105,11 +106,14 @@ final class BindingDocument {
|
||||
}
|
||||
|
||||
boolean named(Element e, String type) {
|
||||
if (e.getTagName().equals(PACKAGE + type)) return true;
|
||||
return named(e, PACKAGE, type);
|
||||
}
|
||||
|
||||
boolean named(Element e, String pkg, String type) {
|
||||
if (e.getTagName().equals(pkg + type)) return true;
|
||||
if (!e.getTagName().equals(type)) return false;
|
||||
boolean own = imports.contains(PACKAGE + type) || imports.contains(PACKAGE + "*");
|
||||
boolean other =
|
||||
imports.stream().anyMatch(i -> i.endsWith("." + type) && !i.equals(PACKAGE + type));
|
||||
boolean own = imports.contains(pkg + type) || imports.contains(pkg + "*");
|
||||
boolean other = imports.stream().anyMatch(i -> i.endsWith("." + type) && !i.equals(pkg + type));
|
||||
return own && !other;
|
||||
}
|
||||
|
||||
@@ -214,6 +218,14 @@ final class BindingDocument {
|
||||
private boolean conflicts(Element e, Values value) {
|
||||
if (kind == Kind.REPEAT)
|
||||
return binding(e, "Repeat") && e.getAttribute("pane").equals(value.pane());
|
||||
if (e.getAttribute("control").equals(value.control())) {
|
||||
if (kind == Kind.COMMAND)
|
||||
return binding(e, "CommandBinding")
|
||||
|| ((binding(e, "DirectBinding") || binding(e, "ComputedBinding"))
|
||||
&& Set.of("disable", "onAction").contains(e.getAttribute("property")));
|
||||
if (binding(e, "CommandBinding"))
|
||||
return Set.of("disable", "onAction").contains(value.property());
|
||||
}
|
||||
return (binding(e, "DirectBinding") || binding(e, "ComputedBinding"))
|
||||
&& e.getAttribute("control").equals(value.control())
|
||||
&& e.getAttribute("property").equals(value.property());
|
||||
@@ -228,8 +240,11 @@ final class BindingDocument {
|
||||
List<Replacement> write(Integer index, Values value, boolean replaceConflicts) {
|
||||
if (kind == Kind.REPEAT && value.pane().isBlank())
|
||||
throw new IllegalArgumentException("Choose a pane");
|
||||
if (kind != Kind.REPEAT && (value.control().isBlank() || value.property().isBlank()))
|
||||
if (kind != Kind.REPEAT
|
||||
&& (value.control().isBlank() || (kind != Kind.COMMAND && value.property().isBlank())))
|
||||
throw new IllegalArgumentException("Choose a control and property");
|
||||
if (kind == Kind.COMMAND && (!qualifiedName(value.path()) || value.path().contains(".")))
|
||||
throw new IllegalArgumentException("Choose a simple Command path");
|
||||
Element original = index == null ? null : entry(index);
|
||||
if (original != null && hasElementChildren(original))
|
||||
throw new IllegalArgumentException(
|
||||
@@ -256,25 +271,27 @@ final class BindingDocument {
|
||||
value.component(),
|
||||
"collection",
|
||||
value.collection())
|
||||
: kind == Kind.COMPUTED
|
||||
? Map.of(
|
||||
"control",
|
||||
value.control(),
|
||||
"property",
|
||||
value.property(),
|
||||
"method",
|
||||
value.method())
|
||||
: Map.of(
|
||||
"control",
|
||||
value.control(),
|
||||
"property",
|
||||
value.property(),
|
||||
"path",
|
||||
value.path(),
|
||||
"direction",
|
||||
value.direction(),
|
||||
"converter",
|
||||
value.converter());
|
||||
: kind == Kind.COMMAND
|
||||
? Map.of("control", value.control(), "path", value.path())
|
||||
: kind == Kind.COMPUTED
|
||||
? Map.of(
|
||||
"control",
|
||||
value.control(),
|
||||
"property",
|
||||
value.property(),
|
||||
"method",
|
||||
value.method())
|
||||
: Map.of(
|
||||
"control",
|
||||
value.control(),
|
||||
"property",
|
||||
value.property(),
|
||||
"path",
|
||||
value.path(),
|
||||
"direction",
|
||||
value.direction(),
|
||||
"converter",
|
||||
value.converter());
|
||||
for (var f : fields.entrySet())
|
||||
if (!original.getAttribute(f.getKey()).equals(f.getValue()))
|
||||
changed.put(
|
||||
@@ -303,6 +320,15 @@ final class BindingDocument {
|
||||
+ "\" collection=\""
|
||||
+ XmlSource.escape(value.collection(), '"')
|
||||
+ "\"";
|
||||
else if (kind == Kind.COMMAND)
|
||||
node =
|
||||
"<"
|
||||
+ PACKAGE
|
||||
+ "CommandBinding control=\""
|
||||
+ XmlSource.escape(value.control(), '"')
|
||||
+ "\" path=\""
|
||||
+ XmlSource.escape(value.path(), '"')
|
||||
+ "\"";
|
||||
else if (kind == Kind.COMPUTED)
|
||||
node += " method=\"" + XmlSource.escape(value.method(), '"') + "\"";
|
||||
else
|
||||
@@ -380,6 +406,13 @@ final class BindingDocument {
|
||||
t.insert(),
|
||||
t.openEnd(),
|
||||
attributes + ">" + eol + child + eol + "</" + container.getTagName() + ">");
|
||||
int line = text.lastIndexOf('\n', t.closeStart() - 1) + 1;
|
||||
String indent = text.substring(line, t.closeStart());
|
||||
if (indent.isBlank()) {
|
||||
// Keep the closing tag on its indented line. Blank lines with spaces can trigger
|
||||
// IntelliJ's strip-trailing-whitespace edit on the next automatic save.
|
||||
return new Replacement(line, line, indent + " " + child + eol);
|
||||
}
|
||||
return new Replacement(t.closeStart(), t.closeStart(), eol + child + eol);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ final class BindingEditor extends VBox {
|
||||
private final BindingDocument.Kind kind;
|
||||
private final ComboBox<BindingMetadata.Converter> converters = new ComboBox<>();
|
||||
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 CheckBox replace = new CheckBox("Replace conflicting bindings");
|
||||
private final Label status = new Label("Open a valid FXML document to edit bindings.");
|
||||
@@ -50,7 +51,8 @@ final class BindingEditor extends VBox {
|
||||
this.kind = kind;
|
||||
boolean computed = kind == BindingDocument.Kind.COMPUTED;
|
||||
boolean repeat = kind == BindingDocument.Kind.REPEAT;
|
||||
String prefix = repeat ? "repeat-" : computed ? "computed-" : "direct-";
|
||||
boolean command = kind == BindingDocument.Kind.COMMAND;
|
||||
String prefix = command ? "command-" : repeat ? "repeat-" : computed ? "computed-" : "direct-";
|
||||
this.navigate = navigate;
|
||||
for (var field :
|
||||
java.util.List.of(control, property, path, converter, method, pane, component, collection))
|
||||
@@ -68,6 +70,20 @@ final class BindingEditor extends VBox {
|
||||
apply.setText("Apply Computed binding");
|
||||
remove.setText("Remove Computed binding");
|
||||
}
|
||||
if (command) {
|
||||
inspect.setText("Discover / Validate Commands");
|
||||
fresh.setText("New Command binding");
|
||||
apply.setText("Apply Command binding");
|
||||
remove.setText("Remove Command binding");
|
||||
commandPaths.setOnAction(
|
||||
e -> {
|
||||
if (commandPaths.getValue() != null) path.setText(commandPaths.getValue());
|
||||
});
|
||||
commandTargets.setOnAction(
|
||||
e -> {
|
||||
if (commandTargets.getValue() != null) control.setText(commandTargets.getValue());
|
||||
});
|
||||
}
|
||||
if (repeat) {
|
||||
inspect.setText("Discover / Validate Repeat");
|
||||
fresh.setText("New Repeat binding");
|
||||
@@ -126,7 +142,7 @@ final class BindingEditor extends VBox {
|
||||
var grid = new GridPane();
|
||||
grid.setHgap(8);
|
||||
grid.setVgap(4);
|
||||
if (!computed && !repeat)
|
||||
if (kind == BindingDocument.Kind.DIRECT)
|
||||
grid.addRow(
|
||||
0,
|
||||
new Label("Control (fx:id)"),
|
||||
@@ -135,7 +151,7 @@ final class BindingEditor extends VBox {
|
||||
property,
|
||||
new Label("Direction"),
|
||||
direction);
|
||||
if (!computed && !repeat)
|
||||
if (kind == BindingDocument.Kind.DIRECT)
|
||||
grid.addRow(1, new Label("Model path"), path, new Label("Converter (optional)"), converter);
|
||||
else if (computed) {
|
||||
grid.addRow(0, new Label("Control (fx:id)"), control, new Label("Property"), property);
|
||||
@@ -143,6 +159,10 @@ final class BindingEditor extends VBox {
|
||||
for (var field : java.util.List.of(control, property))
|
||||
field.textProperty().addListener((o, a, b) -> methods.getItems().clear());
|
||||
}
|
||||
if (command) {
|
||||
grid.addRow(0, new Label("Control (fx:id)"), control, commandTargets);
|
||||
grid.addRow(1, new Label("Command path"), path, commandPaths);
|
||||
}
|
||||
if (repeat) {
|
||||
repeatCollections.setId("repeat-collections");
|
||||
repeatComponents.setId("repeat-components");
|
||||
@@ -177,7 +197,9 @@ final class BindingEditor extends VBox {
|
||||
.addAll(
|
||||
bindings,
|
||||
grid,
|
||||
repeat ? new HBox(8, inspect) : new HBox(8, inspect, computed ? methods : converters),
|
||||
repeat || command
|
||||
? new HBox(8, inspect)
|
||||
: new HBox(8, inspect, computed ? methods : converters),
|
||||
new HBox(8, fresh, apply, remove, replace),
|
||||
status);
|
||||
buttons();
|
||||
@@ -209,7 +231,7 @@ final class BindingEditor extends VBox {
|
||||
control.setText(v.control());
|
||||
property.setText(v.property());
|
||||
path.setText(v.path());
|
||||
direction.setValue(v.direction());
|
||||
direction.setValue(kind == BindingDocument.Kind.COMMAND ? "view" : v.direction());
|
||||
converter.setText(v.converter());
|
||||
method.setText(v.method());
|
||||
pane.setText(v.pane());
|
||||
@@ -217,6 +239,18 @@ final class BindingEditor extends VBox {
|
||||
collection.setText(v.collection());
|
||||
}
|
||||
|
||||
void editProperty(BindingDocument.Values v) {
|
||||
var existing =
|
||||
bindings.getItems().stream()
|
||||
.filter(
|
||||
e ->
|
||||
e.values().control().equals(v.control())
|
||||
&& e.values().property().equals(v.property()))
|
||||
.findFirst();
|
||||
if (existing.isPresent()) bindings.getSelectionModel().select(existing.get());
|
||||
else newBinding(v);
|
||||
}
|
||||
|
||||
void newBinding(BindingDocument.Values v) {
|
||||
loading = true;
|
||||
bindings.getSelectionModel().clearSelection();
|
||||
@@ -329,6 +363,11 @@ final class BindingEditor extends VBox {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (kind == BindingDocument.Kind.COMMAND) {
|
||||
commandPaths.getItems().setAll(metadata.commandPaths());
|
||||
commandTargets.getItems().setAll(metadata.commandTargets());
|
||||
return;
|
||||
}
|
||||
if (requested == null || !values().equals(requested)) return;
|
||||
if (kind == BindingDocument.Kind.COMPUTED) {
|
||||
methods.getItems().setAll(metadata.computed());
|
||||
@@ -345,6 +384,8 @@ final class BindingEditor extends VBox {
|
||||
}
|
||||
|
||||
void invalidateDiscovery() {
|
||||
commandPaths.getItems().clear();
|
||||
commandTargets.getItems().clear();
|
||||
updatingChoices = true;
|
||||
try {
|
||||
repeatCollections.getItems().clear();
|
||||
|
||||
@@ -35,6 +35,14 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
return content;
|
||||
}
|
||||
|
||||
private GridDockEditor gridDockEditor;
|
||||
private FormEditor formEditor;
|
||||
private final ImageView wholeImage = new ImageView();
|
||||
private final Spinner<Integer> previewWidth = new Spinner<>(120, 1600, 760, 40);
|
||||
private final Spinner<Integer> previewHeight = new Spinner<>(100, 1200, 520, 40);
|
||||
private final Label previewState = new Label("Build and Refresh, then select an example.");
|
||||
private boolean showWhole;
|
||||
|
||||
private final VBox componentInspector = new VBox(4);
|
||||
|
||||
private void componentSelection() {
|
||||
@@ -43,9 +51,11 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
var hit = kit.editor().getSelection().getHitItem();
|
||||
if (hit == null) return;
|
||||
String id = hit.getFxId();
|
||||
if (formEditor != null) formEditor.selectIndex(projection.sourceIndex(id));
|
||||
if (bindingEditor != null) bindingEditor.selectControl(id);
|
||||
if (computedEditor != null) computedEditor.selectControl(id);
|
||||
if (repeatEditor != null) repeatEditor.selectControl(id);
|
||||
if (commandEditor != null) commandEditor.selectControl(id);
|
||||
if (tableEditor != null) tableEditor.selectControl(id);
|
||||
if (referenceEditor != null) referenceEditor.selectIndex(projection.sourceIndex(id));
|
||||
if (id == null || !projection.components().containsKey(id)) return;
|
||||
@@ -120,7 +130,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
private DesignerWorkflow bindingWorkflow;
|
||||
private ViewGenerationPane viewGeneration;
|
||||
private BindingBrowser bindingBrowser;
|
||||
private BindingEditor bindingEditor, computedEditor, repeatEditor;
|
||||
private BindingEditor bindingEditor, computedEditor, repeatEditor, commandEditor;
|
||||
private TableEditor tableEditor;
|
||||
private ReferenceEditor referenceEditor;
|
||||
private DiagnosticsPane diagnosticsPane;
|
||||
@@ -194,36 +204,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
launch.maven(),
|
||||
launch.tools(),
|
||||
this::log);
|
||||
bindingEditor =
|
||||
new BindingEditor(
|
||||
BindingDocument.Kind.DIRECT,
|
||||
this::editBinding,
|
||||
id -> {
|
||||
if (kit.editor().getFxomDocument() == null) return;
|
||||
var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id);
|
||||
if (target != null) kit.editor().getSelection().select(target);
|
||||
},
|
||||
values -> validateBindings(values, false));
|
||||
computedEditor =
|
||||
new BindingEditor(
|
||||
BindingDocument.Kind.COMPUTED,
|
||||
this::editBinding,
|
||||
id -> {
|
||||
if (kit.editor().getFxomDocument() == null) return;
|
||||
var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id);
|
||||
if (target != null) kit.editor().getSelection().select(target);
|
||||
},
|
||||
values -> validateBindings(values, false));
|
||||
repeatEditor =
|
||||
new BindingEditor(
|
||||
BindingDocument.Kind.REPEAT,
|
||||
this::editBinding,
|
||||
id -> {
|
||||
if (kit.editor().getFxomDocument() == null) return;
|
||||
var target = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id);
|
||||
if (target != null) kit.editor().getSelection().select(target);
|
||||
},
|
||||
values -> validateBindings(values, false));
|
||||
bindingEditor = editor(BindingDocument.Kind.DIRECT);
|
||||
computedEditor = editor(BindingDocument.Kind.COMPUTED);
|
||||
repeatEditor = editor(BindingDocument.Kind.REPEAT);
|
||||
commandEditor = editor(BindingDocument.Kind.COMMAND);
|
||||
tableEditor =
|
||||
new TableEditor(
|
||||
this::editTable, this::navigateComponent, values -> validateBindings(values, false));
|
||||
@@ -258,7 +242,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
fx(
|
||||
() -> {
|
||||
invalidateBindings("Document changed; discover bindings again.");
|
||||
if (interactiveRequested)
|
||||
if (interactiveRequested && affectsInteractive(uri))
|
||||
interactiveStatus.setText(
|
||||
"Interactive preview uses earlier drafts; rerun or save to"
|
||||
+ " restart");
|
||||
@@ -277,7 +261,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
if (Path.of(uri).startsWith(reactorRoot))
|
||||
fx(
|
||||
() -> {
|
||||
if (interactiveRequested) {
|
||||
if (interactiveRequested && affectsInteractive(uri)) {
|
||||
interactiveRestart = true;
|
||||
interactiveRequest++;
|
||||
interactiveWorkflow.cancel();
|
||||
@@ -355,13 +339,68 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
examples.setId("preview-example");
|
||||
examples
|
||||
.valueProperty()
|
||||
.addListener(
|
||||
(o, before, after) -> {
|
||||
renderSequence.incrementAndGet();
|
||||
clearFormPreview(
|
||||
after == null
|
||||
? "Build and Refresh, then select an example."
|
||||
: "Rendering " + after.label() + "…");
|
||||
if (interactiveRequested) {
|
||||
interactiveRequest++;
|
||||
interactiveWorkflow.cancel();
|
||||
interactiveRestart = true;
|
||||
}
|
||||
resize.playFromStart();
|
||||
});
|
||||
previewWidth.setId("preview-width");
|
||||
previewHeight.setId("preview-height");
|
||||
previewState.setId("preview-state");
|
||||
wholeImage.setId("full-preview-image");
|
||||
wholeImage.setPreserveRatio(true);
|
||||
var picture = new ScrollPane(wholeImage);
|
||||
picture.setMinSize(0, 0);
|
||||
picture
|
||||
.viewportBoundsProperty()
|
||||
.addListener(
|
||||
(o, a, bounds) -> {
|
||||
wholeImage.setFitWidth(Math.max(1, bounds.getWidth()));
|
||||
wholeImage.setFitHeight(Math.max(1, bounds.getHeight()));
|
||||
});
|
||||
VBox.setVgrow(picture, Priority.ALWAYS);
|
||||
var fullPreview =
|
||||
new VBox(
|
||||
4,
|
||||
new FlowPane(
|
||||
5, 4, new Label("Width"), previewWidth, new Label("Height"), previewHeight),
|
||||
previewState,
|
||||
picture);
|
||||
previewWidth.valueProperty().addListener((o, a, b) -> previewSizeChanged());
|
||||
previewHeight.valueProperty().addListener((o, a, b) -> previewSizeChanged());
|
||||
var split = new SplitPane(source, design);
|
||||
split
|
||||
.getItems()
|
||||
.addListener(
|
||||
(javafx.collections.ListChangeListener<javafx.scene.Node>)
|
||||
change -> {
|
||||
showWhole = split.getItems().contains(fullPreview);
|
||||
});
|
||||
sourceSplit = split;
|
||||
split.setDividerPositions(.3);
|
||||
var modes =
|
||||
new ToolBar(
|
||||
button("Source", () -> split.getItems().setAll(source)),
|
||||
button("Design", () -> split.getItems().setAll(design)),
|
||||
button(
|
||||
"Form preview",
|
||||
() -> {
|
||||
split.getItems().setAll(design, fullPreview);
|
||||
split.setDividerPositions(.48);
|
||||
render();
|
||||
}),
|
||||
button(
|
||||
"Split",
|
||||
() -> {
|
||||
@@ -379,10 +418,21 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
directBindingTab.setClosable(false);
|
||||
var computedTab = new Tab("Computed bindings", computedEditor);
|
||||
computedTab.setClosable(false);
|
||||
var commandTab = new Tab("Command bindings", commandEditor);
|
||||
commandTab.setClosable(false);
|
||||
var repeatTab = new Tab("Repeat bindings", repeatEditor);
|
||||
repeatTab.setClosable(false);
|
||||
var tableTab = new Tab("Table / Columns", tableEditor);
|
||||
tableTab.setClosable(false);
|
||||
gridDockEditor =
|
||||
new GridDockEditor(
|
||||
this::editForm,
|
||||
values -> {
|
||||
directBindingTab.getTabPane().getSelectionModel().select(directBindingTab);
|
||||
bindingEditor.editProperty(values);
|
||||
});
|
||||
var gridDockTab = new Tab("DataGrid / Docking", gridDockEditor);
|
||||
gridDockTab.setClosable(false);
|
||||
var problemsTab = new Tab("Problems", diagnosticsPane);
|
||||
problemsTab.setClosable(false);
|
||||
var structureTab = new Tab("Structure", referenceEditor);
|
||||
@@ -396,14 +446,46 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
new TabPane(
|
||||
directBindingTab,
|
||||
computedTab,
|
||||
commandTab,
|
||||
repeatTab,
|
||||
tableTab,
|
||||
gridDockTab,
|
||||
structureTab,
|
||||
problemsTab,
|
||||
discoveryTab,
|
||||
generationTab));
|
||||
bindings.setExpanded(false);
|
||||
center.setBottom(new VBox(properties, bindings));
|
||||
formEditor =
|
||||
new FormEditor(
|
||||
this::editForm,
|
||||
index -> {
|
||||
if (loading || projection == null || kit.editor().getFxomDocument() == null) return;
|
||||
String id = projection.canvasId(index);
|
||||
if (id == null) return;
|
||||
var object = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id);
|
||||
if (object != null && kit.editor().getSelection().getHitItem() != object)
|
||||
kit.editor().getSelection().select(object);
|
||||
},
|
||||
values -> {
|
||||
bindings.setExpanded(true);
|
||||
directBindingTab.getTabPane().getSelectionModel().select(directBindingTab);
|
||||
bindingEditor.editProperty(values);
|
||||
});
|
||||
var formPane = new TitledPane("Form controls", formEditor);
|
||||
formPane.setExpanded(false);
|
||||
formPane
|
||||
.expandedProperty()
|
||||
.addListener(
|
||||
(o, a, b) -> {
|
||||
if (b) bindings.setExpanded(false);
|
||||
});
|
||||
bindings
|
||||
.expandedProperty()
|
||||
.addListener(
|
||||
(o, a, b) -> {
|
||||
if (b) formPane.setExpanded(false);
|
||||
});
|
||||
center.setBottom(new VBox(properties, formPane, bindings));
|
||||
output.setEditable(false);
|
||||
output.setPrefRowCount(5);
|
||||
Path origin = file.resolveSibling(file.getFileName() + ".origin");
|
||||
@@ -443,7 +525,8 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
fx(
|
||||
() -> {
|
||||
if (error != null) report(error);
|
||||
else if (draft == null || d.revision() != draft.revision())
|
||||
else if (!pending
|
||||
&& (draft == null || d.revision() > draft.revision()))
|
||||
load(d);
|
||||
}));
|
||||
}));
|
||||
@@ -502,6 +585,11 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
new HostServices.Diagnostic(
|
||||
"Designer", HostServices.Severity.ERROR, String.valueOf(error), Optional.empty()));
|
||||
if (draft != null && diagnosticsPane != null) validationUnavailable(error);
|
||||
if (showWhole)
|
||||
clearFormPreview(
|
||||
"Preview unavailable · "
|
||||
+ error.getMessage()
|
||||
+ " · use Build and Refresh after correcting the problem.");
|
||||
status.setText("Designer: " + error.getMessage());
|
||||
log(error.toString());
|
||||
}
|
||||
@@ -542,11 +630,15 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
draft = value;
|
||||
formEditor.load(value.text(), value.writable());
|
||||
clearFormPreview("Draft changed · select an example to render the current revision.");
|
||||
publishDiagnostics("Source checked; target validation outdated", java.util.List.of());
|
||||
bindingEditor.load(value.text(), value.writable());
|
||||
computedEditor.load(value.text(), value.writable());
|
||||
repeatEditor.load(value.text(), value.writable());
|
||||
commandEditor.load(value.text(), value.writable());
|
||||
tableEditor.load(value.text(), value.writable());
|
||||
gridDockEditor.load(value.text(), value.writable());
|
||||
referenceEditor.load(value.text(), value.writable());
|
||||
submittedSource = null;
|
||||
commitSource();
|
||||
@@ -574,11 +666,16 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
var hit = kit.editor().getSelection().getHitItem();
|
||||
String selectedId = hit == null ? null : hit.getFxId();
|
||||
draft = value;
|
||||
String requestedSelection = formEditor.load(value.text(), value.writable());
|
||||
if (!requestedSelection.isEmpty()) selectedId = requestedSelection;
|
||||
clearFormPreview("Draft changed · select an example to render the current revision.");
|
||||
publishDiagnostics("Source checked; target validation outdated", java.util.List.of());
|
||||
bindingEditor.load(value.text(), value.writable());
|
||||
computedEditor.load(value.text(), value.writable());
|
||||
repeatEditor.load(value.text(), value.writable());
|
||||
commandEditor.load(value.text(), value.writable());
|
||||
tableEditor.load(value.text(), value.writable());
|
||||
gridDockEditor.load(value.text(), value.writable());
|
||||
referenceEditor.load(value.text(), value.writable());
|
||||
if (!source.getText().equals(value.text())) {
|
||||
int anchor = source.getAnchor(), caret = source.getCaretPosition();
|
||||
@@ -641,13 +738,14 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
} catch (Throwable error) {
|
||||
design.setDisable(true);
|
||||
componentInspector.setDisable(true);
|
||||
gridDockEditor.setDisable(true);
|
||||
projection = null;
|
||||
report(error);
|
||||
} finally {
|
||||
loading = false;
|
||||
// The change debounce may already have fired against the previous draft.
|
||||
// Render only after the authoritative revision and its projection agree.
|
||||
if (projection != null && examples.getValue() != null) resize.playFromStart();
|
||||
if ((projection != null || showWhole) && examples.getValue() != null) resize.playFromStart();
|
||||
if (pendingSourceOffset != null) {
|
||||
int offset = pendingSourceOffset;
|
||||
pendingSourceOffset = null;
|
||||
@@ -668,6 +766,36 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
: null;
|
||||
}
|
||||
|
||||
private void editForm(FormDocument.Edit edit) {
|
||||
flush()
|
||||
.whenComplete(
|
||||
(ok, error) ->
|
||||
fx(
|
||||
() -> {
|
||||
if (error != null) {
|
||||
report(error);
|
||||
return;
|
||||
}
|
||||
if (pending) {
|
||||
status.setText("Finishing the previous edit; repeat the form action.");
|
||||
return;
|
||||
}
|
||||
pending = true;
|
||||
pendingBase = edit.source();
|
||||
pendingVisual = edit.changes();
|
||||
document
|
||||
.snapshot()
|
||||
.thenCompose(
|
||||
latest ->
|
||||
document.apply(
|
||||
new EditBatch(
|
||||
latest.revision(),
|
||||
"Edit form",
|
||||
FormDocument.forCurrentText(edit, latest.text()))))
|
||||
.whenComplete(this::updated);
|
||||
}));
|
||||
}
|
||||
|
||||
private void replace(String text, String name) {
|
||||
if (draft == null || pending) return;
|
||||
submit(difference(draft.text(), text), name);
|
||||
@@ -750,6 +878,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
bindingWorkflow.cancel();
|
||||
bindingBrowser.invalidate(message);
|
||||
repeatEditor.invalidateDiscovery();
|
||||
commandEditor.invalidateDiscovery();
|
||||
tableEditor.invalidateDiscovery();
|
||||
}
|
||||
|
||||
@@ -846,6 +975,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
if (!draft.writable()) throw new IllegalStateException("Document is read-only");
|
||||
if (!draft.text().equals(intent.source()))
|
||||
throw new IllegalStateException("Document changed; select the source object again");
|
||||
if (!intent.change().importedCommandTargets().isEmpty()) {
|
||||
validateCommandPaste(intent);
|
||||
return;
|
||||
}
|
||||
if (intent.validate())
|
||||
pendingReferenceValidation = apply(draft.text(), intent.change().edits());
|
||||
submit(intent.change().edits(), intent.label());
|
||||
@@ -855,6 +988,58 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
});
|
||||
}
|
||||
|
||||
/** Validate imported Command paths against the destination snapshot before the first write. */
|
||||
private void validateCommandPaste(ReferenceEditor.Intent intent) {
|
||||
var original = draft;
|
||||
String proposed = apply(original.text(), intent.change().edits());
|
||||
var candidate =
|
||||
new DocumentSnapshot(
|
||||
original.document(), original.revision(), proposed, original.writable(), true);
|
||||
bindingWorkflow
|
||||
.bindingDetails(last, candidate, "", "view", "", "")
|
||||
.whenComplete(
|
||||
(metadata, error) ->
|
||||
fx(
|
||||
() -> {
|
||||
if (closed) return;
|
||||
if (error != null) {
|
||||
referenceEditor.error(
|
||||
"Cannot validate the destination Commands: " + error.getMessage());
|
||||
return;
|
||||
}
|
||||
if (draft.revision() != original.revision()
|
||||
|| !source.getText().equals(original.text())) {
|
||||
referenceEditor.error(
|
||||
"Destination changed. Select the destination and paste again.");
|
||||
return;
|
||||
}
|
||||
if (!metadata
|
||||
.commandTargets()
|
||||
.containsAll(intent.change().importedCommandTargets())) {
|
||||
referenceEditor.error(
|
||||
"The destination build could not resolve the copied Command targets.");
|
||||
return;
|
||||
}
|
||||
var conflicts =
|
||||
metadata.problems().stream()
|
||||
.filter(
|
||||
p ->
|
||||
p.severity().equals("ERROR")
|
||||
&& intent
|
||||
.change()
|
||||
.importedCommandTargets()
|
||||
.contains(p.control()))
|
||||
.map(p -> p.message())
|
||||
.toList();
|
||||
if (!conflicts.isEmpty()) {
|
||||
referenceEditor.error(String.join("; ", conflicts));
|
||||
return;
|
||||
}
|
||||
pendingReferenceValidation = proposed;
|
||||
submit(intent.change().edits(), intent.label());
|
||||
}));
|
||||
}
|
||||
|
||||
private void editTable(TableEditor.Intent intent) {
|
||||
withDraft(
|
||||
() -> {
|
||||
@@ -869,6 +1054,19 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
});
|
||||
}
|
||||
|
||||
private BindingEditor editor(BindingDocument.Kind kind) {
|
||||
return new BindingEditor(
|
||||
kind,
|
||||
this::editBinding,
|
||||
id -> {
|
||||
var document = kit.editor().getFxomDocument();
|
||||
if (document == null) return;
|
||||
var selection = new FXOMFxIdIndex(document).lookup(id);
|
||||
if (selection != null) kit.editor().getSelection().select(selection);
|
||||
},
|
||||
values -> validateBindings(kind == BindingDocument.Kind.COMMAND ? null : values, false));
|
||||
}
|
||||
|
||||
private void editBinding(BindingEditor.Intent intent) {
|
||||
withDraft(
|
||||
() -> {
|
||||
@@ -891,7 +1089,9 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
? repeatEditor
|
||||
: intent.kind() == BindingDocument.Kind.COMPUTED
|
||||
? computedEditor
|
||||
: bindingEditor)
|
||||
: intent.kind() == BindingDocument.Kind.COMMAND
|
||||
? commandEditor
|
||||
: bindingEditor)
|
||||
.error(error.getMessage());
|
||||
}
|
||||
});
|
||||
@@ -904,6 +1104,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
errors.addAll(new ReferenceDocument(draft.text()).referenceErrors());
|
||||
if (errors.isEmpty()) return true;
|
||||
status.setText("Preview blocked: " + String.join("; ", errors));
|
||||
clearFormPreview(status.getText());
|
||||
if (projection != null)
|
||||
for (String id : projection.components().keySet()) {
|
||||
var region = proxy(id);
|
||||
@@ -954,6 +1155,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
validationUnavailable(error);
|
||||
status.setText(
|
||||
"Binding validation unavailable: " + error.getMessage());
|
||||
clearFormPreview(
|
||||
status.getText()
|
||||
+ " · use Build and Refresh, or choose Preview last"
|
||||
+ " successful.");
|
||||
return;
|
||||
}
|
||||
validatedSource = captured.text();
|
||||
@@ -979,6 +1184,10 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
: "Current successful build")
|
||||
+ " · draft revision "
|
||||
+ captured.revision());
|
||||
commandEditor.metadata(
|
||||
metadata,
|
||||
values,
|
||||
last ? "Retained build" : "Current successful build");
|
||||
repeatEditor.metadata(
|
||||
metadata,
|
||||
values,
|
||||
@@ -1060,6 +1269,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
withDraft(
|
||||
() -> {
|
||||
renderSequence.incrementAndGet();
|
||||
clearFormPreview("Building selected context…");
|
||||
status.setText("Building selected context…");
|
||||
buildRun = workflow.build(approvals);
|
||||
buildRun
|
||||
@@ -1095,6 +1305,11 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
}
|
||||
} else if (result.status() == BuildRefresh.Status.READY)
|
||||
discover(false);
|
||||
else
|
||||
clearFormPreview(
|
||||
result.message()
|
||||
+ " · correct the build and use Build and Refresh, or choose"
|
||||
+ " Preview last successful.");
|
||||
}));
|
||||
});
|
||||
}
|
||||
@@ -1141,6 +1356,27 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
});
|
||||
}
|
||||
|
||||
private void clearFormPreview(String message) {
|
||||
wholeImage.setImage(null);
|
||||
previewState.setText(message);
|
||||
}
|
||||
|
||||
private void previewSizeChanged() {
|
||||
renderSequence.incrementAndGet();
|
||||
wholeImage.setImage(null);
|
||||
previewState.setText("Rendering selected size…");
|
||||
resize.playFromStart();
|
||||
}
|
||||
|
||||
private boolean affectsInteractive(java.net.URI uri) {
|
||||
if (file.toUri().equals(uri) || Path.of(uri).equals(file)) return true;
|
||||
if (projection == null) return false;
|
||||
String path = Path.of(uri).toString().replace(java.io.File.separatorChar, '/');
|
||||
return java.util.stream.Stream.concat(
|
||||
projection.navigationTypes().values().stream(), projection.rowComponents().stream())
|
||||
.anyMatch(type -> path.endsWith("/" + type.replace('.', '/') + ".fxml"));
|
||||
}
|
||||
|
||||
public void render() {
|
||||
withDraft(
|
||||
() -> {
|
||||
@@ -1156,10 +1392,18 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
.filter(p -> p.severity().equals("ERROR"))
|
||||
.map(p -> p.message())
|
||||
.collect(java.util.stream.Collectors.joining("; ")));
|
||||
clearFormPreview(status.getText());
|
||||
return;
|
||||
}
|
||||
var selected = examples.getValue();
|
||||
if (selected == null || projection == null) return;
|
||||
if (selected == null) {
|
||||
previewState.setText(
|
||||
"Select a preview example after Build and Refresh. If none is listed, register an"
|
||||
+ " example for this FXML.");
|
||||
status.setText(previewState.getText());
|
||||
return;
|
||||
}
|
||||
if (projection == null && !interactiveRequested && !showWhole) return;
|
||||
long ticket = renderSequence.incrementAndGet();
|
||||
host.documents()
|
||||
.snapshots()
|
||||
@@ -1191,7 +1435,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
new DocumentSnapshot(
|
||||
draft.document(),
|
||||
draft.revision(),
|
||||
projection.previewText(),
|
||||
projection == null ? draft.text() : projection.previewText(),
|
||||
draft.writable(),
|
||||
draft.dirty()));
|
||||
renderComponents(List.copyOf(drafts.values()), selected.id(), ticket);
|
||||
@@ -1202,7 +1446,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
private void renderComponents(List<DocumentSnapshot> drafts, String example, long ticket) {
|
||||
if (ticket != renderSequence.get() || closed) return;
|
||||
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);
|
||||
if (region == null) continue;
|
||||
int
|
||||
@@ -1245,8 +1489,13 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
+ " restart");
|
||||
}));
|
||||
}
|
||||
if (showWhole)
|
||||
nodes.put("", new DesignerWorkflow.Size(previewWidth.getValue(), previewHeight.getValue()));
|
||||
if (nodes.isEmpty()) {
|
||||
status.setText("No embedded Components; use Interactive preview for this View");
|
||||
status.setText(
|
||||
projection == null
|
||||
? "Canvas projection unavailable; interactive preview uses the FXML draft"
|
||||
: "No embedded Components; use Interactive preview for this View");
|
||||
return;
|
||||
}
|
||||
workflow
|
||||
@@ -1257,14 +1506,19 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
() -> {
|
||||
if (ticket != renderSequence.get()) return;
|
||||
if (error != null) {
|
||||
projection
|
||||
.components()
|
||||
.keySet()
|
||||
.forEach(
|
||||
id -> {
|
||||
var region = proxy(id);
|
||||
if (region != null) region.failed();
|
||||
});
|
||||
if (showWhole) {
|
||||
wholeImage.setImage(null);
|
||||
previewState.setText("Preview failed: " + error.getMessage());
|
||||
}
|
||||
if (projection != null)
|
||||
projection
|
||||
.components()
|
||||
.keySet()
|
||||
.forEach(
|
||||
id -> {
|
||||
var region = proxy(id);
|
||||
if (region != null) region.failed();
|
||||
});
|
||||
report(error);
|
||||
return;
|
||||
}
|
||||
@@ -1291,6 +1545,21 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
argb,
|
||||
0,
|
||||
width);
|
||||
if (frame.node().isEmpty()) {
|
||||
wholeImage.setImage(image);
|
||||
previewState.setText(
|
||||
(last
|
||||
? "Retained build · Build and Refresh for current sources · "
|
||||
: "")
|
||||
+ examples.getValue().label()
|
||||
+ " · "
|
||||
+ width
|
||||
+ " × "
|
||||
+ height
|
||||
+ " · revision "
|
||||
+ draft.revision());
|
||||
continue;
|
||||
}
|
||||
images.put(frame.node(), image);
|
||||
var region = proxy(frame.node());
|
||||
if (region != null) {
|
||||
@@ -1302,14 +1571,15 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
layoutPasses = measurementsChanged ? layoutPasses + 1 : 0;
|
||||
if (layoutPasses >= 8) {
|
||||
resize.stop();
|
||||
projection
|
||||
.components()
|
||||
.keySet()
|
||||
.forEach(
|
||||
id -> {
|
||||
var region = proxy(id);
|
||||
if (region != null) region.failed();
|
||||
});
|
||||
if (projection != null)
|
||||
projection
|
||||
.components()
|
||||
.keySet()
|
||||
.forEach(
|
||||
id -> {
|
||||
var region = proxy(id);
|
||||
if (region != null) region.failed();
|
||||
});
|
||||
status.setText("Target layout did not stabilize; retaining last layout");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,533 @@
|
||||
package de.neitzel.fxdesigner.kit;
|
||||
|
||||
import de.neitzel.fxdesigner.contracts.EditBatch.Replacement;
|
||||
import java.util.*;
|
||||
import javafx.scene.layout.*;
|
||||
import org.w3c.dom.*;
|
||||
|
||||
/**
|
||||
* Visual form operations use ranges from the current source so bindings keep their original text.
|
||||
*/
|
||||
final class FormDocument {
|
||||
static final Map<String, String> TYPES = new TreeMap<>();
|
||||
|
||||
static {
|
||||
register(
|
||||
"javafx.scene.control",
|
||||
"Label TextField TextArea PasswordField Button CheckBox ComboBox ToolBar");
|
||||
register(
|
||||
"javafx.scene.layout", "GridPane VBox HBox StackPane AnchorPane FlowPane TilePane Pane");
|
||||
register(
|
||||
"de.neitzel.fx.control",
|
||||
"StatusBar ToolBarPane AutoCompleteTextField TagChip NonNegativeIntegerSpinner HtmlViewer");
|
||||
register("de.neitzel.fx.view", "DataGrid Table");
|
||||
register("de.neitzel.fx.docking", "DockPane");
|
||||
}
|
||||
|
||||
private static void register(String pkg, String names) {
|
||||
for (String name : names.split(" ")) TYPES.put(name, pkg + "." + name);
|
||||
}
|
||||
|
||||
record Item(int index, String type, String id) {
|
||||
public String toString() {
|
||||
return type + (id.isEmpty() ? " [" + index + "]" : " #" + id);
|
||||
}
|
||||
}
|
||||
|
||||
record Slot(Item owner, String property) {
|
||||
public String toString() {
|
||||
return owner + " / " + property;
|
||||
}
|
||||
}
|
||||
|
||||
record Edit(String source, List<Replacement> changes, String selectId) {}
|
||||
|
||||
record Field(String name, String type, String fallback, boolean editable) {
|
||||
boolean bindable() {
|
||||
return type.equals("ObservableList<String>")
|
||||
|| editable
|
||||
&& !name.equals("dismissText")
|
||||
&& Set.of("Integer", "String", "Boolean", "Number", "CSS", "Insets").contains(type);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
private final BindingDocument xml;
|
||||
final List<Item> items = new ArrayList<>();
|
||||
final List<Slot> slots = new ArrayList<>();
|
||||
private final Map<String, String> imports = new HashMap<>();
|
||||
private final Set<String> packages = new HashSet<>();
|
||||
private final Set<String> ids = new HashSet<>();
|
||||
|
||||
FormDocument(String text) throws Exception {
|
||||
xml = new BindingDocument(text);
|
||||
for (Node n = xml.document.getFirstChild(); n != null; n = n.getNextSibling()) {
|
||||
if (n instanceof ProcessingInstruction pi && pi.getTarget().equals("import")) {
|
||||
String type = pi.getData().trim();
|
||||
if (type.endsWith(".*")) packages.add(type.substring(0, type.length() - 2));
|
||||
else imports.put(simple(type), type);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < xml.elements.size(); i++) {
|
||||
var e = xml.elements.get(i);
|
||||
String id = e.getAttributeNS(BindingDocument.FX, "id");
|
||||
if (!id.isEmpty()) ids.add(id);
|
||||
String tag = e.getTagName();
|
||||
if (BindingDocument.FX.equals(e.getNamespaceURI()) && e.getLocalName().equals("root"))
|
||||
tag = e.getAttribute("type");
|
||||
String type = simple(tag);
|
||||
if (!TYPES.containsKey(type) || !resolves(tag, TYPES.get(type)) || inDefinition(e)) continue;
|
||||
var item = new Item(i, type, id);
|
||||
items.add(item);
|
||||
for (String property : childLists(type)) slots.add(new Slot(item, property));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean resolves(String tag, String type) {
|
||||
if (tag.contains(".")) return tag.equals(type);
|
||||
if (imports.containsKey(tag)) return type.equals(imports.get(tag));
|
||||
return packages.contains(type.substring(0, type.lastIndexOf('.')));
|
||||
}
|
||||
|
||||
private static String simple(String type) {
|
||||
return type.substring(type.lastIndexOf('.') + 1);
|
||||
}
|
||||
|
||||
private static boolean inDefinition(Element e) {
|
||||
for (Node n = e; n instanceof Element parent; n = n.getParentNode())
|
||||
if (BindingDocument.FX.equals(parent.getNamespaceURI())
|
||||
&& parent.getLocalName().equals("define")) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static List<String> childLists(String type) {
|
||||
return switch (type) {
|
||||
case "GridPane", "HBox", "VBox", "StackPane", "Pane", "AnchorPane", "FlowPane", "TilePane" ->
|
||||
List.of("children");
|
||||
case "ToolBarPane", "ToolBar" -> List.of("items");
|
||||
case "StatusBar" -> List.of("leftItems", "rightItems");
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
|
||||
private static List<Element> children(Element parent) {
|
||||
var result = new ArrayList<Element>();
|
||||
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling())
|
||||
if (n instanceof Element e) result.add(e);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Element property(Element owner, String name) {
|
||||
var matches = children(owner).stream().filter(e -> e.getTagName().equals(name)).toList();
|
||||
if (matches.size() > 1)
|
||||
throw new IllegalArgumentException("Multiple " + name + " properties; edit in Source.");
|
||||
return matches.isEmpty() ? null : matches.getFirst();
|
||||
}
|
||||
|
||||
private Element owner(Slot slot) {
|
||||
if (slot == null || !slots.contains(slot))
|
||||
throw new IllegalArgumentException("Choose a destination child list.");
|
||||
return element(slot.owner());
|
||||
}
|
||||
|
||||
private Element element(Item item) {
|
||||
if (item == null || !items.contains(item))
|
||||
throw new IllegalArgumentException("Select a control in the form.");
|
||||
return xml.elements.get(item.index());
|
||||
}
|
||||
|
||||
private XmlSource.Tag tag(Element e) {
|
||||
return xml.source.tags.get(xml.elements.indexOf(e));
|
||||
}
|
||||
|
||||
private String fragment(Element e) {
|
||||
var t = tag(e);
|
||||
return xml.text.substring(t.start(), t.end());
|
||||
}
|
||||
|
||||
private Edit edit(List<Replacement> edits, String id) {
|
||||
return new Edit(xml.text, List.copyOf(edits), id);
|
||||
}
|
||||
|
||||
private String fresh(String type) {
|
||||
String base = java.beans.Introspector.decapitalize(type), id = base;
|
||||
for (int suffix = 2; ids.contains(id); suffix++) id = base + suffix;
|
||||
return id;
|
||||
}
|
||||
|
||||
private String fxPrefix(Element e) {
|
||||
String prefix = e.lookupPrefix(BindingDocument.FX);
|
||||
if (prefix != null) return prefix;
|
||||
prefix = "fx";
|
||||
for (int i = 2; e.lookupNamespaceURI(prefix) != null; i++) prefix = "fx" + i;
|
||||
return prefix;
|
||||
}
|
||||
|
||||
private String namespace(Element e, String prefix) {
|
||||
return e.lookupNamespaceURI(prefix) == null
|
||||
? " xmlns:" + prefix + "=\"" + BindingDocument.FX + "\""
|
||||
: "";
|
||||
}
|
||||
|
||||
private List<Element> members(Slot slot) {
|
||||
Element host = owner(slot), list = property(host, slot.property());
|
||||
if (list == null && slot.owner().type().equals("StatusBar")) return List.of();
|
||||
return children(list == null ? host : list).stream()
|
||||
.filter(
|
||||
e ->
|
||||
!BindingDocument.FX.equals(e.getNamespaceURI())
|
||||
&& Character.isUpperCase(simple(e.getTagName()).charAt(0)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
int size(Slot slot) {
|
||||
return members(slot).size();
|
||||
}
|
||||
|
||||
private Replacement insert(Slot slot, int position, String snippet) {
|
||||
var owner = owner(slot);
|
||||
var members = members(slot);
|
||||
if (position < 0 || position > members.size())
|
||||
throw new IllegalArgumentException("Position must be between 0 and " + members.size());
|
||||
if (position < members.size()) {
|
||||
int start = tag(members.get(position)).start();
|
||||
return new Replacement(start, start, snippet + "\n");
|
||||
}
|
||||
var container = property(owner, slot.property());
|
||||
if (container != null) return xml.append(container, snippet, "");
|
||||
if (slot.owner().type().equals("StatusBar")
|
||||
|| (slot.owner().type().equals("ToolBarPane") && members.isEmpty()))
|
||||
snippet = "<" + slot.property() + ">" + snippet + "</" + slot.property() + ">";
|
||||
return xml.append(owner, snippet, "");
|
||||
}
|
||||
|
||||
/** A native autosave can strip trailing whitespace between selection and apply. */
|
||||
static List<Replacement> forCurrentText(Edit edit, String current) {
|
||||
if (edit.source().equals(current)) return edit.changes();
|
||||
var normalized = new StringBuilder();
|
||||
int[] offsets = new int[edit.source().length() + 1];
|
||||
var stripped = java.util.regex.Pattern.compile("(?m)[ \t]+$").matcher(edit.source());
|
||||
int start = 0;
|
||||
while (stripped.find()) {
|
||||
for (int i = start; i < stripped.start(); i++) {
|
||||
offsets[i] = normalized.length();
|
||||
normalized.append(edit.source().charAt(i));
|
||||
}
|
||||
Arrays.fill(offsets, stripped.start(), stripped.end(), normalized.length());
|
||||
start = stripped.end();
|
||||
}
|
||||
for (int i = start; i < edit.source().length(); i++) {
|
||||
offsets[i] = normalized.length();
|
||||
normalized.append(edit.source().charAt(i));
|
||||
}
|
||||
offsets[edit.source().length()] = normalized.length();
|
||||
if (!current.contentEquals(normalized))
|
||||
throw new ConcurrentModificationException("Form changed; select the control again.");
|
||||
return edit.changes().stream()
|
||||
.map(r -> new Replacement(offsets[r.start()], offsets[r.end()], r.text()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Edit add(String type, Slot slot, int at) {
|
||||
var host = owner(slot);
|
||||
if (!TYPES.containsKey(type)) throw new IllegalArgumentException("Choose a palette control.");
|
||||
String id = fresh(type), prefix = fxPrefix(host), qualified = TYPES.get(type);
|
||||
var edits = new ArrayList<Replacement>();
|
||||
String tagName = type;
|
||||
if (!resolves(type, qualified)) {
|
||||
if (imports.containsKey(type)) tagName = qualified;
|
||||
else {
|
||||
int start = tag(xml.document.getDocumentElement()).start();
|
||||
edits.add(new Replacement(start, start, "<?import " + qualified + "?>\n"));
|
||||
}
|
||||
}
|
||||
String extra =
|
||||
type.equals("Label") || type.equals("Button") || type.equals("TagChip")
|
||||
? " text=\"" + type + "\""
|
||||
: "";
|
||||
if (slot.owner().type().equals("GridPane")) {
|
||||
int row = 0;
|
||||
for (var sibling : members(slot)) {
|
||||
try {
|
||||
row =
|
||||
Math.max(
|
||||
row,
|
||||
Math.addExact(
|
||||
Integer.parseInt(
|
||||
sibling.getAttribute("GridPane.rowIndex").isEmpty()
|
||||
? "0"
|
||||
: sibling.getAttribute("GridPane.rowIndex")),
|
||||
1));
|
||||
} catch (NumberFormatException ignored) {
|
||||
/* Dynamic constraints remain verbatim. */
|
||||
}
|
||||
}
|
||||
String grid =
|
||||
resolves("GridPane", TYPES.get("GridPane")) ? "GridPane" : TYPES.get("GridPane");
|
||||
extra += " " + grid + ".rowIndex=\"" + row + "\"";
|
||||
}
|
||||
edits.add(
|
||||
insert(
|
||||
slot,
|
||||
at,
|
||||
"<"
|
||||
+ tagName
|
||||
+ namespace(host, prefix)
|
||||
+ " "
|
||||
+ prefix
|
||||
+ ":id=\""
|
||||
+ id
|
||||
+ "\""
|
||||
+ extra
|
||||
+ "/>"));
|
||||
return edit(edits, id);
|
||||
}
|
||||
|
||||
Edit move(Item item, Slot slot, int at) {
|
||||
Element source = element(item), host = owner(slot);
|
||||
if (slots.stream().noneMatch(s -> members(s).contains(source)))
|
||||
throw new IllegalArgumentException("Only a child in a supported list can be moved.");
|
||||
for (Node n = host; n != null; n = n.getParentNode())
|
||||
if (n == source) throw new IllegalArgumentException("Cannot move a control into itself.");
|
||||
var current = members(slot);
|
||||
int old = current.indexOf(source);
|
||||
if (old >= 0 && (at == old || at == old + 1)) return edit(List.of(), item.id());
|
||||
var removed = tag(source);
|
||||
String body = fragment(source);
|
||||
// Moving across a locally declared namespace must preserve its interpretation.
|
||||
for (Node n = source.getParentNode(); n instanceof Element ancestor; n = n.getParentNode())
|
||||
for (int i = 0; i < ancestor.getAttributes().getLength(); i++) {
|
||||
var attr = ancestor.getAttributes().item(i);
|
||||
if (javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attr.getNamespaceURI())) {
|
||||
String prefix = attr.getNodeName().equals("xmlns") ? null : attr.getLocalName();
|
||||
if (!Objects.equals(host.lookupNamespaceURI(prefix), source.lookupNamespaceURI(prefix)))
|
||||
throw new IllegalArgumentException(
|
||||
"Destination namespace differs; move this control in Source.");
|
||||
}
|
||||
}
|
||||
return edit(
|
||||
List.of(new Replacement(removed.start(), removed.end(), ""), insert(slot, at, body)),
|
||||
item.id());
|
||||
}
|
||||
|
||||
List<Field> fields(Item item) {
|
||||
var e = element(item);
|
||||
var fields = new LinkedHashMap<String, Field>();
|
||||
field(fields, "styleClass", "CSS classes", "control default");
|
||||
field(fields, "padding", "Insets", item.type().equals("StatusBar") ? "4 8 4 8" : "0");
|
||||
field(fields, "style", "CSS", "");
|
||||
for (String dimension :
|
||||
List.of("minWidth", "maxWidth", "minHeight", "maxHeight", "prefWidth", "prefHeight"))
|
||||
field(fields, dimension, "Number", "-1");
|
||||
field(fields, "disable", "Boolean", "false");
|
||||
field(fields, "visible", "Boolean", "true");
|
||||
if (Set.of(
|
||||
"Label",
|
||||
"Button",
|
||||
"CheckBox",
|
||||
"TagChip",
|
||||
"TextField",
|
||||
"TextArea",
|
||||
"PasswordField",
|
||||
"AutoCompleteTextField")
|
||||
.contains(item.type())) field(fields, "text", "String", "");
|
||||
if (Set.of("TextField", "TextArea", "PasswordField", "AutoCompleteTextField", "ComboBox")
|
||||
.contains(item.type())) field(fields, "promptText", "String", "");
|
||||
if (item.type().equals("NonNegativeIntegerSpinner")) {
|
||||
field(fields, "minimum", "Constructor integer", "0");
|
||||
field(fields, "maximum", "Constructor integer", Integer.toString(Integer.MAX_VALUE));
|
||||
field(fields, "initialValue", "Constructor integer", "0");
|
||||
field(fields, "number", "Integer", "initialValue");
|
||||
}
|
||||
if (item.type().equals("AutoCompleteTextField")) {
|
||||
field(fields, "suggestions", "String list", "");
|
||||
fields.put(
|
||||
"suggestionsSource",
|
||||
new Field("suggestionsSource", "ObservableList<String>", "fixed suggestions", false));
|
||||
}
|
||||
if (item.type().equals("TagChip")) {
|
||||
field(fields, "removable", "Boolean", "false");
|
||||
field(fields, "onRemove", "Event handler", "");
|
||||
}
|
||||
if (item.type().equals("ToolBarPane")) {
|
||||
field(fields, "dismissible", "Boolean", "false");
|
||||
field(fields, "dismissText", "String", "Close toolbar");
|
||||
field(fields, "onDismiss", "Event handler", "");
|
||||
}
|
||||
if (Set.of("TextField", "TextArea", "AutoCompleteTextField", "PasswordField")
|
||||
.contains(item.type())) field(fields, "editable", "Boolean", "true");
|
||||
if (Set.of("Label", "Button", "CheckBox", "TextArea").contains(item.type()))
|
||||
field(fields, "wrapText", "Boolean", "false");
|
||||
if (item.type().equals("HtmlViewer")) {
|
||||
field(fields, "html", "String", "");
|
||||
field(fields, "mediaButtonVisible", "Boolean", "true");
|
||||
field(fields, "mediaLoadText", "String", "Load external media");
|
||||
field(fields, "mediaReloadText", "String", "Reload external media");
|
||||
field(
|
||||
fields,
|
||||
"mediaTooltipText",
|
||||
"String",
|
||||
"Loads external images for this viewer only and contacts their servers.");
|
||||
field(
|
||||
fields, "noExternalMediaText", "String", "No resolvable external image addresses found.");
|
||||
}
|
||||
if (item.type().equals("GridPane")) {
|
||||
field(fields, "hgap", "Number", "0");
|
||||
field(fields, "vgap", "Number", "0");
|
||||
}
|
||||
if (item.type().equals("HBox") || item.type().equals("VBox"))
|
||||
field(fields, "spacing", "Number", "0");
|
||||
if (slots.stream().anyMatch(s -> s.owner.type.equals("GridPane") && members(s).contains(e))) {
|
||||
for (String name : List.of("rowIndex", "columnIndex", "rowSpan", "columnSpan"))
|
||||
field(fields, "GridPane." + name, "Layout integer", name.endsWith("Span") ? "1" : "0");
|
||||
for (String name : List.of("hgrow", "vgrow"))
|
||||
field(fields, "GridPane." + name, "Priority", "unset");
|
||||
}
|
||||
for (String name : List.of("width", "height"))
|
||||
fields.put(name, new Field(name, "Number", "layout", false));
|
||||
for (int i = 0; i < e.getAttributes().getLength(); i++) {
|
||||
var a = e.getAttributes().item(i);
|
||||
if (a.getNamespaceURI() == null)
|
||||
fields.putIfAbsent(a.getNodeName(), new Field(a.getNodeName(), "FXML", "source", false));
|
||||
}
|
||||
return List.copyOf(fields.values());
|
||||
}
|
||||
|
||||
private static void field(Map<String, Field> fields, String name, String type, String fallback) {
|
||||
fields.put(name, new Field(name, type, fallback, true));
|
||||
}
|
||||
|
||||
String value(Item item, Field field) {
|
||||
var e = element(item);
|
||||
if (e.hasAttribute(field.name())) return e.getAttribute(field.name());
|
||||
var nested = property(e, field.name());
|
||||
if (nested == null) return "";
|
||||
var values = children(nested);
|
||||
if (field.name().equals("suggestions"))
|
||||
return String.join(
|
||||
"\n", values.stream().map(v -> v.getAttributeNS(BindingDocument.FX, "value")).toList());
|
||||
if (field.name().equals("padding") && values.size() == 1) {
|
||||
var insets = values.getFirst();
|
||||
return String.join(
|
||||
" ",
|
||||
List.of("top", "right", "bottom", "left").stream()
|
||||
.map(p -> insets.hasAttribute(p) ? insets.getAttribute(p) : "0")
|
||||
.toList());
|
||||
}
|
||||
return nested.getTextContent();
|
||||
}
|
||||
|
||||
Edit set(Item item, Field field, String input, boolean reset) {
|
||||
Element e = element(item);
|
||||
if (field == null || !fields(item).contains(field) || !field.editable())
|
||||
throw new IllegalArgumentException("Choose a writable property.");
|
||||
String name = field.name();
|
||||
var nested = property(e, name);
|
||||
if (nested != null && !Set.of("padding", "suggestions").contains(name))
|
||||
throw new IllegalArgumentException("This property contains nested FXML. Edit it in Source.");
|
||||
if (name.equals("padding") || name.equals("suggestions")) {
|
||||
if (nested != null) {
|
||||
for (var child : children(nested)) {
|
||||
String expected = name.equals("padding") ? "javafx.geometry.Insets" : "java.lang.String";
|
||||
if (!(resolves(child.getTagName(), expected)
|
||||
|| child.getTagName().equals("String")
|
||||
&& expected.equals("java.lang.String")
|
||||
&& !imports.containsKey("String"))
|
||||
|| !children(child).isEmpty())
|
||||
throw new IllegalArgumentException("Complex property value; edit it in Source.");
|
||||
for (int i = 0; i < child.getAttributes().getLength(); i++) {
|
||||
Node a = child.getAttributes().item(i);
|
||||
if (!(name.equals("padding")
|
||||
&& Set.of("top", "left", "right", "bottom").contains(a.getNodeName())
|
||||
|| name.equals("suggestions")
|
||||
&& BindingDocument.FX.equals(a.getNamespaceURI())
|
||||
&& "value".equals(a.getLocalName())))
|
||||
throw new IllegalArgumentException("Annotated property value; edit it in Source.");
|
||||
}
|
||||
}
|
||||
if (fragment(nested).contains("<!--"))
|
||||
throw new IllegalArgumentException("Property contains a comment; edit it in Source.");
|
||||
}
|
||||
var edits = new ArrayList<Replacement>();
|
||||
if (e.hasAttribute(name))
|
||||
edits.addAll(xml.source.attributes(item.index(), Collections.singletonMap(name, null)));
|
||||
String snippet = "";
|
||||
if (!reset) {
|
||||
if (name.equals("padding")) {
|
||||
var parts = input.strip().split("[,\\s]+");
|
||||
if (parts.length != 1 && parts.length != 4)
|
||||
throw new IllegalArgumentException("Enter one inset or top right bottom left.");
|
||||
var attrs = new StringBuilder();
|
||||
int i = 0;
|
||||
for (String side : List.of("top", "right", "bottom", "left")) {
|
||||
double v = Double.parseDouble(parts.length == 1 ? parts[0] : parts[i++]);
|
||||
if (!Double.isFinite(v)) throw new IllegalArgumentException("Insets must be finite.");
|
||||
attrs.append(" ").append(side).append("=\"").append(v).append("\"");
|
||||
}
|
||||
snippet = "<padding><javafx.geometry.Insets" + attrs + "/></padding>";
|
||||
} else {
|
||||
String prefix = fxPrefix(e);
|
||||
var values = new StringBuilder("<suggestions" + namespace(e, prefix) + ">");
|
||||
for (String suggestion : input.lines().toList())
|
||||
values
|
||||
.append("<java.lang.String ")
|
||||
.append(prefix)
|
||||
.append(":value=\"")
|
||||
.append(XmlSource.escape(suggestion, '"'))
|
||||
.append("\"/>");
|
||||
snippet = values.append("</suggestions>").toString();
|
||||
}
|
||||
}
|
||||
if (nested != null)
|
||||
edits.add(new Replacement(tag(nested).start(), tag(nested).end(), snippet));
|
||||
else if (!reset) edits.add(xml.append(e, snippet, ""));
|
||||
return edit(edits, item.id());
|
||||
}
|
||||
if (!reset) {
|
||||
switch (field.type()) {
|
||||
case "Boolean" -> {
|
||||
if (!Set.of("true", "false").contains(input))
|
||||
throw new IllegalArgumentException("Choose true or false.");
|
||||
}
|
||||
case "Number" -> {
|
||||
if (!Double.isFinite(Double.parseDouble(input)))
|
||||
throw new IllegalArgumentException("Enter a finite number.");
|
||||
}
|
||||
case "Integer", "Constructor integer", "Layout integer" -> {
|
||||
if (Integer.parseInt(input) < (name.endsWith("Span") ? 1 : 0))
|
||||
throw new IllegalArgumentException("Value outside the supported range.");
|
||||
}
|
||||
case "Priority" -> Priority.valueOf(input);
|
||||
case "Event handler" -> {
|
||||
if (!input.matches("#[\\p{javaJavaIdentifierStart}][\\p{javaJavaIdentifierPart}]*"))
|
||||
throw new IllegalArgumentException("Use #controllerMethod.");
|
||||
}
|
||||
default -> {}
|
||||
}
|
||||
}
|
||||
if (item.type().equals("NonNegativeIntegerSpinner")
|
||||
&& Set.of("minimum", "maximum", "initialValue", "number").contains(name)) {
|
||||
var limits = new HashMap<String, Integer>();
|
||||
for (var f : fields(item))
|
||||
if (f.type().equals("Constructor integer")) {
|
||||
String current = value(item, f);
|
||||
if (name.equals(f.name())) current = reset ? "" : input;
|
||||
limits.put(f.name(), Integer.parseInt(current.isEmpty() ? f.fallback() : current));
|
||||
}
|
||||
int min = limits.get("minimum"),
|
||||
max = limits.get("maximum"),
|
||||
initial = limits.get("initialValue");
|
||||
if (min < 0 || initial < min || initial > max)
|
||||
throw new IllegalArgumentException("Require 0 ≤ minimum ≤ initialValue ≤ maximum.");
|
||||
String number = name.equals("number") ? (reset ? "" : input) : e.getAttribute("number");
|
||||
if (!number.isEmpty() && (Integer.parseInt(number) < min || Integer.parseInt(number) > max))
|
||||
throw new IllegalArgumentException("Number outside spinner bounds.");
|
||||
}
|
||||
return edit(
|
||||
xml.source.attributes(item.index(), Collections.singletonMap(name, reset ? null : input)),
|
||||
item.id());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package de.neitzel.fxdesigner.kit;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
|
||||
/** Source-backed palette and inspector, also addresses items inside target-only controls. */
|
||||
final class FormEditor extends VBox {
|
||||
private final ComboBox<String> palette = combo("form-palette");
|
||||
private final ComboBox<FormDocument.Slot> destination = combo("form-destination");
|
||||
private final Spinner<Integer> position = new Spinner<>(0, 0, 0);
|
||||
private final ComboBox<FormDocument.Item> selected = combo("form-control");
|
||||
private final ComboBox<FormDocument.Field> field = combo("form-property");
|
||||
private final TextArea value = new TextArea();
|
||||
private final Label details = new Label(), message = new Label();
|
||||
private final Consumer<FormDocument.Edit> submit;
|
||||
private FormDocument form;
|
||||
private String text = "", pendingId = "";
|
||||
private boolean loading;
|
||||
|
||||
FormEditor(
|
||||
Consumer<FormDocument.Edit> submit,
|
||||
Consumer<Integer> selectCanvas,
|
||||
Consumer<BindingDocument.Values> bind) {
|
||||
super(5);
|
||||
this.submit = submit;
|
||||
palette.getItems().setAll(FormDocument.TYPES.keySet());
|
||||
palette.setValue("Label");
|
||||
position.setId("form-position");
|
||||
position.setPrefWidth(74);
|
||||
value.setId("form-value");
|
||||
value.setPrefRowCount(2);
|
||||
details.setId("form-field-type");
|
||||
message.setId("form-message");
|
||||
message.setWrapText(true);
|
||||
selected.setOnAction(
|
||||
e -> {
|
||||
if (loading || selected.getValue() == null) return;
|
||||
updateFields();
|
||||
var item = selected.getValue();
|
||||
destination.getItems().stream()
|
||||
.filter(s -> s.owner().equals(item))
|
||||
.findFirst()
|
||||
.ifPresent(destination::setValue);
|
||||
selectCanvas.accept(item.index());
|
||||
});
|
||||
destination.setOnAction(e -> setPosition());
|
||||
field.setOnAction(e -> showValue());
|
||||
getChildren()
|
||||
.addAll(
|
||||
row(
|
||||
new Label("Palette"),
|
||||
palette,
|
||||
new Label("Destination"),
|
||||
destination,
|
||||
new Label("Position"),
|
||||
position,
|
||||
button(
|
||||
"Insert control",
|
||||
() ->
|
||||
perform(
|
||||
() ->
|
||||
form.add(
|
||||
palette.getValue(),
|
||||
destination.getValue(),
|
||||
position.getValue())))),
|
||||
row(
|
||||
new Label("Selected control"),
|
||||
selected,
|
||||
button(
|
||||
"Move to destination",
|
||||
() ->
|
||||
perform(
|
||||
() ->
|
||||
form.move(
|
||||
selected.getValue(),
|
||||
destination.getValue(),
|
||||
position.getValue())))),
|
||||
row(new Label("Property"), field, details),
|
||||
value,
|
||||
row(
|
||||
button(
|
||||
"Set property",
|
||||
() ->
|
||||
perform(
|
||||
() ->
|
||||
form.set(
|
||||
selected.getValue(),
|
||||
field.getValue(),
|
||||
value.getText(),
|
||||
false))),
|
||||
button(
|
||||
"Reset property",
|
||||
() -> perform(() -> form.set(selected.getValue(), field.getValue(), "", true))),
|
||||
button(
|
||||
"Bind property",
|
||||
() -> {
|
||||
var item = selected.getValue();
|
||||
var property = field.getValue();
|
||||
if (item == null || item.id().isEmpty() || property == null) {
|
||||
message.setText("Select a control with an fx:id and a property.");
|
||||
return;
|
||||
}
|
||||
if (!property.bindable()) {
|
||||
message.setText(
|
||||
"This setting has no writable JavaFX property for DirectBinding.");
|
||||
return;
|
||||
}
|
||||
bind.accept(
|
||||
new BindingDocument.Values(item.id(), property.name(), "", "view", ""));
|
||||
})),
|
||||
message);
|
||||
}
|
||||
|
||||
private static FlowPane row(Node... nodes) {
|
||||
return new FlowPane(6, 4, nodes);
|
||||
}
|
||||
|
||||
private static <T> ComboBox<T> combo(String id) {
|
||||
var c = new ComboBox<T>();
|
||||
c.setId(id);
|
||||
return c;
|
||||
}
|
||||
|
||||
private static Button button(String label, Runnable action) {
|
||||
var b = new Button(label);
|
||||
b.setOnAction(e -> action.run());
|
||||
return b;
|
||||
}
|
||||
|
||||
private void perform(Supplier<FormDocument.Edit> change) {
|
||||
try {
|
||||
var edit = change.get();
|
||||
if (edit.changes().isEmpty()) return;
|
||||
pendingId = edit.selectId();
|
||||
message.setText("");
|
||||
submit.accept(edit);
|
||||
} catch (RuntimeException ex) {
|
||||
message.setText(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
void selectIndex(Integer index) {
|
||||
if (form == null || index == null || loading) return;
|
||||
form.items.stream()
|
||||
.filter(i -> i.index() == index)
|
||||
.findFirst()
|
||||
.ifPresent(
|
||||
i -> {
|
||||
if (!i.equals(selected.getValue())) selected.setValue(i);
|
||||
});
|
||||
}
|
||||
|
||||
private void setPosition() {
|
||||
var slot = destination.getValue();
|
||||
int size = form == null || slot == null ? 0 : form.size(slot);
|
||||
position.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, size, size));
|
||||
}
|
||||
|
||||
private void updateFields() {
|
||||
var item = selected.getValue();
|
||||
var previous = field.getValue();
|
||||
field.getItems().setAll(item == null ? List.of() : form.fields(item));
|
||||
if (previous != null && field.getItems().contains(previous)) field.setValue(previous);
|
||||
else field.getSelectionModel().selectFirst();
|
||||
showValue();
|
||||
}
|
||||
|
||||
private void showValue() {
|
||||
var f = field.getValue();
|
||||
var item = selected.getValue();
|
||||
if (form == null || item == null || f == null) {
|
||||
details.setText("");
|
||||
value.clear();
|
||||
return;
|
||||
}
|
||||
details.setText(
|
||||
f.type()
|
||||
+ " · default "
|
||||
+ (f.fallback().isEmpty() ? "(empty)" : f.fallback())
|
||||
+ " · "
|
||||
+ (f.type().equals("ObservableList<String>")
|
||||
? "bind to a model list"
|
||||
: f.editable() ? "editable" : "read only"));
|
||||
value.setEditable(f.editable());
|
||||
value.setText(form.value(item, f));
|
||||
}
|
||||
|
||||
String load(String source, boolean writable) {
|
||||
setDisable(!writable);
|
||||
if (source.equals(text)) return "";
|
||||
var old = selected.getValue();
|
||||
var slot = destination.getValue();
|
||||
String id = pendingId.isEmpty() ? (old == null ? "" : old.id()) : pendingId;
|
||||
String requested = pendingId;
|
||||
pendingId = "";
|
||||
text = source;
|
||||
loading = true;
|
||||
try {
|
||||
form = new FormDocument(source);
|
||||
selected.getItems().setAll(form.items);
|
||||
destination.getItems().setAll(form.slots);
|
||||
selected.setValue(
|
||||
form.items.stream()
|
||||
.filter(i -> !id.isEmpty() ? i.id().equals(id) : i.equals(old))
|
||||
.findFirst()
|
||||
.orElse(form.items.isEmpty() ? null : form.items.getFirst()));
|
||||
destination.setValue(
|
||||
form.slots.stream()
|
||||
.filter(
|
||||
s ->
|
||||
s.equals(slot)
|
||||
|| slot != null
|
||||
&& !slot.owner().id().isEmpty()
|
||||
&& s.owner().id().equals(slot.owner().id())
|
||||
&& s.property().equals(slot.property()))
|
||||
.findFirst()
|
||||
.orElse(form.slots.isEmpty() ? null : form.slots.getFirst()));
|
||||
updateFields();
|
||||
setPosition();
|
||||
message.setText("");
|
||||
} catch (Exception ex) {
|
||||
form = null;
|
||||
selected.getItems().clear();
|
||||
destination.getItems().clear();
|
||||
field.getItems().clear();
|
||||
setDisable(true);
|
||||
message.setText(ex.getMessage());
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,9 @@ final class FxmlDiagnostics {
|
||||
if ((xml.named(e, "DirectBinding") || xml.named(e, "ComputedBinding"))
|
||||
&& property(e, "control").equals(p.control())
|
||||
&& 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")
|
||||
&& p.property().equals("children")
|
||||
&& property(e, "pane").equals(p.control())) matches.add(i);
|
||||
|
||||
@@ -96,6 +96,14 @@ public final class FxmlProjection {
|
||||
return sourceNodes.get(id);
|
||||
}
|
||||
|
||||
String canvasId(int index) {
|
||||
return sourceNodes.entrySet().stream()
|
||||
.filter(e -> e.getValue() == index)
|
||||
.map(Map.Entry::getKey)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public Map<String, String> components() {
|
||||
return Map.copyOf(components);
|
||||
}
|
||||
@@ -163,16 +171,38 @@ public final class FxmlProjection {
|
||||
}
|
||||
var imports = new HashMap<String, String>();
|
||||
var remove = new ArrayList<Node>();
|
||||
var explicit = new HashMap<String, String>();
|
||||
var conflicts = new HashSet<String>();
|
||||
var unknownPackages = new ArrayList<String>();
|
||||
boolean docking = false;
|
||||
for (Node n = d.getFirstChild(); n != null; n = n.getNextSibling())
|
||||
if (n instanceof ProcessingInstruction pi && pi.getTarget().equals("import")) {
|
||||
String type = pi.getData().trim();
|
||||
if (!type.startsWith("javafx.")) {
|
||||
if (type.endsWith(".*"))
|
||||
throw new IOException("Application wildcard imports need an explicit Component import");
|
||||
imports.put(type.substring(type.lastIndexOf('.') + 1), type);
|
||||
remove.add(n);
|
||||
String simple = type.substring(type.lastIndexOf('.') + 1);
|
||||
if (!simple.equals("*")) {
|
||||
var previous = explicit.putIfAbsent(simple, type);
|
||||
if (previous != null && !previous.equals(type)) conflicts.add(simple);
|
||||
}
|
||||
if (type.startsWith("javafx.")) continue;
|
||||
if (type.equals("de.neitzel.fx.docking.*")) docking = true;
|
||||
else if (simple.equals("*")) unknownPackages.add(type);
|
||||
else imports.put(simple, type);
|
||||
remove.add(n);
|
||||
}
|
||||
for (int i = 0; i < originals.getLength(); i++) {
|
||||
var element = (Element) originals.item(i);
|
||||
String tag = element.getTagName();
|
||||
if (!isObject(element) || tag.contains(".")) continue;
|
||||
if (conflicts.contains(tag)) throw importError(i, tag, "Conflicting explicit imports");
|
||||
if (explicit.containsKey(tag)) continue;
|
||||
if (!unknownPackages.isEmpty()) {
|
||||
throw importError(
|
||||
i, tag, "Unresolved wildcard import (" + String.join(", ", unknownPackages) + ")");
|
||||
}
|
||||
if (docking
|
||||
&& Set.of("DockPane", "DockLayout", "DockGroupDefinition", "DockSplitDefinition")
|
||||
.contains(tag)) imports.put(tag, "de.neitzel.fx.docking." + tag);
|
||||
}
|
||||
remove.forEach(d::removeChild);
|
||||
d.insertBefore(
|
||||
d.createProcessingInstruction("import", SnapshotRegion.class.getName()),
|
||||
@@ -193,6 +223,7 @@ public final class FxmlProjection {
|
||||
&& tag.contains(".")
|
||||
&& Character.isUpperCase(tag.charAt(tag.lastIndexOf('.') + 1))
|
||||
&& !tag.startsWith("javafx.")) componentType = tag;
|
||||
if (componentType != null && componentType.startsWith("java.lang.")) componentType = null;
|
||||
if (componentType == null && repeated.containsKey(e.getAttributeNS(FX, "id")))
|
||||
componentType = tag.contains(".") ? tag : "javafx.scene.layout." + tag;
|
||||
if (componentType != null) {
|
||||
@@ -212,7 +243,8 @@ public final class FxmlProjection {
|
||||
|| attr.getName().equals("vgap"))
|
||||
&& !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.startsWith("javafx."))
|
||||
throw new IOException("Unsupported application element: " + tag);
|
||||
@@ -220,7 +252,8 @@ public final class FxmlProjection {
|
||||
var attrs = e.getAttributes();
|
||||
for (int a = attrs.getLength() - 1; a >= 0; a--) {
|
||||
var attr = (Attr) attrs.item(a);
|
||||
if (attr.getValue().startsWith("#")
|
||||
if (attr.getValue().startsWith("%")) attr.setValue(attr.getValue().substring(1));
|
||||
else if (attr.getValue().startsWith("#")
|
||||
|| attr.getValue().startsWith("$")
|
||||
|| attr.getName().startsWith("on")) e.removeAttributeNode(attr);
|
||||
}
|
||||
@@ -229,6 +262,21 @@ public final class FxmlProjection {
|
||||
return xml(d);
|
||||
}
|
||||
|
||||
private IOException importError(int index, String tag, String message) {
|
||||
int offset = source.tags.get(index).start();
|
||||
int line = 1 + (int) source.text.substring(0, offset).chars().filter(c -> c == '\n').count();
|
||||
int column = offset - source.text.lastIndexOf('\n', offset);
|
||||
return new IOException(
|
||||
message
|
||||
+ " for <"
|
||||
+ tag
|
||||
+ "> at line "
|
||||
+ line
|
||||
+ ", column "
|
||||
+ column
|
||||
+ ". Use one explicit import for this type.");
|
||||
}
|
||||
|
||||
private static Map<String, Element> indexed(Document d) throws IOException {
|
||||
var result = new LinkedHashMap<String, Element>();
|
||||
|
||||
@@ -356,7 +404,9 @@ public final class FxmlProjection {
|
||||
|| before.get(id).hasAttribute(attr) != after.get(id).hasAttribute(attr)) {
|
||||
var target = sourceElements.get(id);
|
||||
String originalValue = target.getAttribute(attr);
|
||||
if (originalValue.startsWith("$") || originalValue.startsWith("#"))
|
||||
if (originalValue.startsWith("$")
|
||||
|| originalValue.startsWith("#")
|
||||
|| originalValue.startsWith("%"))
|
||||
throw new IOException("Bound attributes must be edited in source");
|
||||
values.put(attr, after.get(id).hasAttribute(attr) ? value : null);
|
||||
if (after.get(id).hasAttribute(attr) && attr.contains(".")) {
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
package de.neitzel.fxdesigner.kit;
|
||||
|
||||
import de.neitzel.fxdesigner.contracts.EditBatch.Replacement;
|
||||
import java.util.*;
|
||||
import org.w3c.dom.*;
|
||||
|
||||
/** Address declarations by their source elements. Replacing a branch retains its complete XML. */
|
||||
final class GridDockDocument {
|
||||
static final String DOCK = "de.neitzel.fx.docking.";
|
||||
static final List<String> AREAS = List.of("center", "left", "right", "top", "bottom");
|
||||
static final Map<String, List<String>> SETTINGS =
|
||||
Map.of(
|
||||
"DataGrid",
|
||||
List.of(
|
||||
"keyAttribute",
|
||||
"pageSize",
|
||||
"maximumPageSize",
|
||||
"selectionMode",
|
||||
"groupingEnabled",
|
||||
"groupBy",
|
||||
"groupsCollapsed",
|
||||
"items",
|
||||
"source"),
|
||||
"DataGridColumn",
|
||||
List.of(
|
||||
"id",
|
||||
"attribute",
|
||||
"header",
|
||||
"type",
|
||||
"kind",
|
||||
"width",
|
||||
"minimumWidth",
|
||||
"maximumWidth",
|
||||
"filterable",
|
||||
"checklist",
|
||||
"groupAttribute"),
|
||||
"DockGroupDefinition",
|
||||
List.of(
|
||||
"destinationId",
|
||||
"tabSide",
|
||||
"mode",
|
||||
"visibleWhenEmpty",
|
||||
"releaseSpaceWhenEmpty",
|
||||
"collapsible",
|
||||
"preferredWidth",
|
||||
"preferredHeight"),
|
||||
"DockSplitDefinition", List.of("destinationId", "orientation", "position"));
|
||||
|
||||
static List<String> options(String field) {
|
||||
return switch (field) {
|
||||
case "filterable",
|
||||
"groupingEnabled",
|
||||
"groupsCollapsed",
|
||||
"visibleWhenEmpty",
|
||||
"releaseSpaceWhenEmpty",
|
||||
"collapsible" ->
|
||||
List.of("true", "false");
|
||||
case "checklist" -> List.of("DISABLED", "INHERIT", "CURRENT_PAGE", "SOURCE_WIDE");
|
||||
case "selectionMode" -> List.of("NONE", "SINGLE", "MULTIPLE");
|
||||
case "tabSide" -> List.of("TOP", "RIGHT", "BOTTOM", "LEFT");
|
||||
case "mode" -> List.of("DOCKED", "OVERLAY");
|
||||
case "orientation" -> List.of("HORIZONTAL", "VERTICAL");
|
||||
case "kind" -> List.of("TEXT", "INTEGER", "DECIMAL", "BOOLEAN");
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
|
||||
final BindingDocument xml;
|
||||
|
||||
GridDockDocument(String text) throws Exception {
|
||||
xml = new BindingDocument(text);
|
||||
}
|
||||
|
||||
String type(Element e) {
|
||||
String tag = e.getTagName(), name = tag.substring(tag.lastIndexOf('.') + 1);
|
||||
if ((name.equals("DataGrid") || name.equals("DataGridColumn")) && xml.named(e, name))
|
||||
return name;
|
||||
if (Set.of("DockPane", "DockLayout", "DockGroupDefinition", "DockSplitDefinition")
|
||||
.contains(name)
|
||||
&& xml.named(e, DOCK, name)) return name;
|
||||
return "";
|
||||
}
|
||||
|
||||
List<Element> roots() {
|
||||
return xml.elements.stream()
|
||||
.filter(e -> Set.of("DataGrid", "DockPane").contains(type(e)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
static List<Element> children(Element e) {
|
||||
var result = new ArrayList<Element>();
|
||||
for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling())
|
||||
if (n instanceof Element c) result.add(c);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Element property(Element e, String name) {
|
||||
var list = children(e).stream().filter(c -> c.getTagName().equals(name)).toList();
|
||||
if (list.size() > 1) throw new IllegalArgumentException("Multiple declarations of " + name);
|
||||
return list.isEmpty() ? null : list.getFirst();
|
||||
}
|
||||
|
||||
Element parentOfType(Element e, String type) {
|
||||
for (Node n = e; n instanceof Element p; n = n.getParentNode())
|
||||
if (type(p).equals(type)) return p;
|
||||
throw new IllegalArgumentException("Missing " + type);
|
||||
}
|
||||
|
||||
private Element columnsOwner(Element grid) {
|
||||
var wrapper = property(grid, "columns");
|
||||
if (wrapper != null && children(grid).stream().anyMatch(c -> type(c).equals("DataGridColumn")))
|
||||
throw new IllegalArgumentException(
|
||||
"Mixed column containers. Edit the declaration in Source.");
|
||||
return wrapper == null ? grid : wrapper;
|
||||
}
|
||||
|
||||
List<Element> branches(Element e) {
|
||||
if (type(e).equals("DataGrid"))
|
||||
return children(columnsOwner(e)).stream()
|
||||
.filter(c -> type(c).equals("DataGridColumn"))
|
||||
.toList();
|
||||
if (type(e).equals("DataGridColumn") || type(e).equals("DockGroupDefinition")) return List.of();
|
||||
return children(e).stream()
|
||||
.filter(
|
||||
c ->
|
||||
!type(c).isEmpty()
|
||||
|| AREAS.contains(c.getTagName())
|
||||
|| Set.of("initialLayout", "first", "second").contains(c.getTagName()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
String label(Element e) {
|
||||
String label = type(e);
|
||||
if (label.isEmpty()) return e.getTagName();
|
||||
String id =
|
||||
e.hasAttribute("destinationId") ? e.getAttribute("destinationId") : e.getAttribute("id");
|
||||
if (id.isEmpty()) id = e.getAttributeNS(BindingDocument.FX, "id");
|
||||
return id.isEmpty() ? label : label + " · " + id;
|
||||
}
|
||||
|
||||
private XmlSource.Tag tag(Element e) {
|
||||
return xml.source.tags.get(xml.elements.indexOf(e));
|
||||
}
|
||||
|
||||
private String fragment(Element e) {
|
||||
var t = tag(e);
|
||||
return xml.text.substring(t.start(), t.end());
|
||||
}
|
||||
|
||||
private Replacement replace(Element e, String snippet) {
|
||||
var t = tag(e);
|
||||
return new Replacement(t.start(), t.end(), snippet);
|
||||
}
|
||||
|
||||
private List<String> grouped(Element grid) {
|
||||
return Arrays.stream(grid.getAttribute("groupBy").split(","))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.toList();
|
||||
}
|
||||
|
||||
private List<Element> destinations(Element e) {
|
||||
var pane = parentOfType(e, "DockPane");
|
||||
return xml.elements.stream()
|
||||
.filter(
|
||||
c ->
|
||||
(pane.compareDocumentPosition(c) & Node.DOCUMENT_POSITION_CONTAINED_BY) != 0
|
||||
&& Set.of("DockGroupDefinition", "DockSplitDefinition").contains(type(c)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private String fresh(List<Element> elements, String attr, String base) {
|
||||
var used = new HashSet<String>();
|
||||
elements.forEach(e -> used.add(e.getAttribute(attr)));
|
||||
String id = base;
|
||||
for (int i = 2; used.contains(id); i++) id = base + i;
|
||||
return id;
|
||||
}
|
||||
|
||||
List<Replacement> set(Element e, String field, String value) {
|
||||
if (!SETTINGS.getOrDefault(type(e), List.of()).contains(field)
|
||||
|| Set.of("items", "source").contains(field))
|
||||
throw new IllegalArgumentException("Use a model binding for the data input.");
|
||||
if (property(e, field) != null)
|
||||
throw new IllegalArgumentException(
|
||||
"The property has a nested declaration. Edit it in Source.");
|
||||
if (e.getAttribute(field).matches("^[%$#].*"))
|
||||
throw new IllegalArgumentException("This property is a reference. Edit it in Source.");
|
||||
boolean required =
|
||||
field.equals("id") || field.equals("destinationId") || field.equals("header");
|
||||
if (required && value.isBlank())
|
||||
throw new IllegalArgumentException("A value is required for " + field);
|
||||
var opts = options(field);
|
||||
if (!value.isEmpty() && !opts.isEmpty() && !opts.contains(value))
|
||||
throw new IllegalArgumentException("Choose one of " + opts);
|
||||
if (!value.isEmpty()
|
||||
&& Set.of(
|
||||
"width",
|
||||
"minimumWidth",
|
||||
"maximumWidth",
|
||||
"preferredWidth",
|
||||
"preferredHeight",
|
||||
"position")
|
||||
.contains(field)) {
|
||||
double n = Double.parseDouble(value);
|
||||
if (!Double.isFinite(n) || n <= 0 || field.equals("position") && n >= 1)
|
||||
throw new IllegalArgumentException("Invalid " + field);
|
||||
}
|
||||
if (!value.isEmpty()
|
||||
&& Set.of("pageSize", "maximumPageSize").contains(field)
|
||||
&& Integer.parseInt(value) < 1)
|
||||
throw new IllegalArgumentException("Positive page size required");
|
||||
var edits = new ArrayList<Replacement>();
|
||||
if (field.equals("destinationId")
|
||||
&& destinations(e).stream().anyMatch(c -> c != e && c.getAttribute(field).equals(value)))
|
||||
throw new IllegalArgumentException("Destination already exists: " + value);
|
||||
if (field.equals("id")) {
|
||||
var grid = parentOfType(e, "DataGrid");
|
||||
if (branches(grid).stream().anyMatch(c -> c != e && c.getAttribute("id").equals(value)))
|
||||
throw new IllegalArgumentException("Column already exists: " + value);
|
||||
var groups = new ArrayList<>(grouped(grid));
|
||||
if (Collections.replaceAll(groups, e.getAttribute("id"), value))
|
||||
edits.addAll(
|
||||
xml.source.attributes(
|
||||
xml.elements.indexOf(grid), Map.of("groupBy", String.join(", ", groups))));
|
||||
// The library defaults the row attribute to the column id.
|
||||
if (!e.hasAttribute("attribute")
|
||||
&& !e.getAttribute("id").equals(value)
|
||||
&& !e.getAttribute("id").isEmpty()) {
|
||||
edits.addAll(
|
||||
xml.source.attributes(
|
||||
xml.elements.indexOf(e), Map.of("id", value, "attribute", e.getAttribute("id"))));
|
||||
return edits;
|
||||
}
|
||||
}
|
||||
if (field.equals("groupBy") && !value.isBlank()) {
|
||||
var ids = branches(e).stream().map(c -> c.getAttribute("id")).toList();
|
||||
var seen = new HashSet<String>();
|
||||
for (String token : value.split(",", -1))
|
||||
if (!ids.contains(token.trim()) || !seen.add(token.trim()))
|
||||
throw new IllegalArgumentException("Unknown or repeated grouping column: " + token);
|
||||
}
|
||||
edits.addAll(
|
||||
xml.source.attributes(
|
||||
xml.elements.indexOf(e),
|
||||
Collections.singletonMap(field, value.isEmpty() ? null : value)));
|
||||
return edits;
|
||||
}
|
||||
|
||||
List<Replacement> addColumn(Element e) {
|
||||
var grid = parentOfType(e, "DataGrid");
|
||||
var cols = branches(grid);
|
||||
String id = fresh(cols, "id", "column");
|
||||
// Start with an existing row attribute so the new column can render immediately.
|
||||
String attribute = cols.isEmpty() ? "value" : cols.getFirst().getAttribute("attribute");
|
||||
if (attribute.isEmpty() && !cols.isEmpty()) attribute = cols.getFirst().getAttribute("id");
|
||||
return List.of(
|
||||
xml.append(
|
||||
columnsOwner(grid),
|
||||
"<de.neitzel.fx.view.DataGridColumn id=\""
|
||||
+ id
|
||||
+ "\" attribute=\""
|
||||
+ XmlSource.escape(attribute, '"')
|
||||
+ "\" header=\""
|
||||
+ id
|
||||
+ "\"/>",
|
||||
""));
|
||||
}
|
||||
|
||||
List<Replacement> move(Element col, int delta) {
|
||||
var columns = branches(parentOfType(col, "DataGrid"));
|
||||
int index = columns.indexOf(col);
|
||||
if (index < 0) throw new IllegalArgumentException("Select a column.");
|
||||
if (index + delta < 0 || index + delta >= columns.size()) return List.of();
|
||||
var other = columns.get(index + delta);
|
||||
return List.of(replace(other, fragment(col)), replace(col, fragment(other)));
|
||||
}
|
||||
|
||||
List<Replacement> removeColumn(Element col) {
|
||||
if (!type(col).equals("DataGridColumn")) throw new IllegalArgumentException("Select a column.");
|
||||
if (grouped(parentOfType(col, "DataGrid")).contains(col.getAttribute("id")))
|
||||
throw new IllegalArgumentException("Remove the column from groupBy first.");
|
||||
var span = tag(col);
|
||||
int start = xml.text.lastIndexOf('\n', span.start() - 1) + 1;
|
||||
int end = xml.text.indexOf('\n', span.end());
|
||||
if (end >= 0
|
||||
&& xml.text.substring(start, span.start()).isBlank()
|
||||
&& xml.text.substring(span.end(), end).isBlank())
|
||||
return List.of(new Replacement(start, end + 1, ""));
|
||||
return List.of(replace(col, ""));
|
||||
}
|
||||
|
||||
private String group(String id) {
|
||||
return "<" + DOCK + "DockGroupDefinition destinationId=\"" + id + "\"/>";
|
||||
}
|
||||
|
||||
List<Replacement> addArea(Element e, String area) {
|
||||
if (!AREAS.contains(area)) throw new IllegalArgumentException("Choose a dock area.");
|
||||
var pane = parentOfType(e, "DockPane");
|
||||
var initial = property(pane, "initialLayout");
|
||||
var child =
|
||||
"<"
|
||||
+ area
|
||||
+ ">"
|
||||
+ group(fresh(destinations(pane), "destinationId", area))
|
||||
+ "</"
|
||||
+ area
|
||||
+ ">";
|
||||
if (initial == null) {
|
||||
if (pane.hasAttribute("initialLayout"))
|
||||
throw new IllegalArgumentException("The layout is supplied by reference.");
|
||||
if (!area.equals("center"))
|
||||
throw new IllegalArgumentException("Create the center area first.");
|
||||
return List.of(
|
||||
xml.append(
|
||||
pane,
|
||||
"<initialLayout><"
|
||||
+ DOCK
|
||||
+ "DockLayout>"
|
||||
+ child
|
||||
+ "</"
|
||||
+ DOCK
|
||||
+ "DockLayout></initialLayout>",
|
||||
""));
|
||||
}
|
||||
var layout =
|
||||
children(initial).stream()
|
||||
.filter(c -> type(c).equals("DockLayout"))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("An inline DockLayout is required."));
|
||||
if (property(layout, area) != null || layout.hasAttribute(area))
|
||||
throw new IllegalArgumentException("Area already exists: " + area);
|
||||
return List.of(xml.append(layout, child, ""));
|
||||
}
|
||||
|
||||
List<Replacement> moveArea(Element origin, String target) {
|
||||
if (!AREAS.contains(origin.getTagName())
|
||||
|| !AREAS.contains(target)
|
||||
|| origin.getTagName().equals("center"))
|
||||
throw new IllegalArgumentException("Select a side area to move.");
|
||||
var layout = parentOfType(origin, "DockLayout");
|
||||
if (property(layout, target) != null || layout.hasAttribute(target))
|
||||
throw new IllegalArgumentException("Area already exists: " + target);
|
||||
var t = tag(origin);
|
||||
String name = origin.getTagName();
|
||||
if (t.selfClosing())
|
||||
return List.of(new Replacement(t.start() + 1, t.start() + 1 + name.length(), target));
|
||||
return List.of(
|
||||
new Replacement(t.start() + 1, t.start() + 1 + name.length(), target),
|
||||
new Replacement(t.closeStart() + 2, t.closeStart() + 2 + name.length(), target));
|
||||
}
|
||||
|
||||
List<Replacement> split(Element e) {
|
||||
if (!Set.of("DockGroupDefinition", "DockSplitDefinition").contains(type(e)))
|
||||
throw new IllegalArgumentException("Select a dock group or split.");
|
||||
var destinations = destinations(e);
|
||||
String id = fresh(destinations, "destinationId", "split");
|
||||
return List.of(
|
||||
replace(
|
||||
e,
|
||||
"<"
|
||||
+ DOCK
|
||||
+ "DockSplitDefinition destinationId=\""
|
||||
+ id
|
||||
+ "\" orientation=\"HORIZONTAL\"><first>"
|
||||
+ fragment(e)
|
||||
+ "</first><second>"
|
||||
+ group(fresh(destinations, "destinationId", "group"))
|
||||
+ "</second></"
|
||||
+ DOCK
|
||||
+ "DockSplitDefinition>"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package de.neitzel.fxdesigner.kit;
|
||||
|
||||
import de.neitzel.fxdesigner.contracts.EditBatch.Replacement;
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/** Source-backed inspector for the two declarative structures hidden inside Kit proxies. */
|
||||
final class GridDockEditor extends VBox {
|
||||
private final TreeView<Element> tree = new TreeView<>();
|
||||
private final ComboBox<String> setting = new ComboBox<>(),
|
||||
value = new ComboBox<>(),
|
||||
area = new ComboBox<>();
|
||||
private final Label message = new Label(),
|
||||
signals =
|
||||
new Label(
|
||||
"Selection outputs (read-only): selectedKey, selectedKeys, selectedElement,"
|
||||
+ " selectedElements");
|
||||
private GridDockDocument doc;
|
||||
private final Consumer<FormDocument.Edit> submit;
|
||||
private final Consumer<BindingDocument.Values> binding;
|
||||
private final Button apply, bind, add, remove, earlier, later, addArea, moveArea, split;
|
||||
|
||||
GridDockEditor(Consumer<FormDocument.Edit> submit, Consumer<BindingDocument.Values> binding) {
|
||||
super(4);
|
||||
this.submit = submit;
|
||||
this.binding = binding;
|
||||
tree.setId("declaration-tree");
|
||||
tree.setShowRoot(false);
|
||||
tree.setPrefHeight(155);
|
||||
tree.setMinHeight(88);
|
||||
tree.setCellFactory(
|
||||
v ->
|
||||
new TreeCell<>() {
|
||||
protected void updateItem(Element e, boolean empty) {
|
||||
super.updateItem(e, empty);
|
||||
setText(empty || e == null ? null : doc.label(e));
|
||||
}
|
||||
});
|
||||
setting.setId("declaration-property");
|
||||
value.setId("declaration-value");
|
||||
message.setId("declaration-message");
|
||||
value.setEditable(true);
|
||||
value.setPrefWidth(180);
|
||||
area.setId("dock-area");
|
||||
area.getItems().addAll(GridDockDocument.AREAS);
|
||||
area.setValue("center");
|
||||
apply =
|
||||
button(
|
||||
"Apply setting",
|
||||
() ->
|
||||
edit(
|
||||
() ->
|
||||
doc.set(
|
||||
selected(), setting.getValue(), value.getEditor().getText().trim())));
|
||||
bind =
|
||||
button(
|
||||
"Edit data binding",
|
||||
() -> {
|
||||
String id = selected().getAttributeNS(BindingDocument.FX, "id");
|
||||
if (id.isEmpty()) {
|
||||
message.setText("Give the grid an fx:id under Structure first.");
|
||||
return;
|
||||
}
|
||||
String field = setting.getValue();
|
||||
binding.accept(new BindingDocument.Values(id, field, "", "view", ""));
|
||||
});
|
||||
add = button("Add column", () -> edit(() -> doc.addColumn(selected())));
|
||||
remove = button("Delete column", () -> edit(() -> doc.removeColumn(selected())));
|
||||
earlier = button("Earlier", () -> edit(() -> doc.move(selected(), -1)));
|
||||
later = button("Later", () -> edit(() -> doc.move(selected(), 1)));
|
||||
addArea =
|
||||
button("Add area with group", () -> edit(() -> doc.addArea(selected(), area.getValue())));
|
||||
moveArea = button("Move area", () -> edit(() -> doc.moveArea(selected(), area.getValue())));
|
||||
split = button("Split branch", () -> edit(() -> doc.split(selected())));
|
||||
signals.setWrapText(true);
|
||||
message.setWrapText(true);
|
||||
getChildren()
|
||||
.addAll(
|
||||
tree,
|
||||
new FlowPane(6, 4, setting, value, apply, bind),
|
||||
new FlowPane(6, 4, add, earlier, later, remove, area, addArea, moveArea, split),
|
||||
signals,
|
||||
message);
|
||||
tree.getSelectionModel().selectedItemProperty().addListener((o, a, b) -> select());
|
||||
setting.valueProperty().addListener((o, a, b) -> showValue());
|
||||
}
|
||||
|
||||
private static Button button(String text, Runnable action) {
|
||||
var button = new Button(text);
|
||||
button.setOnAction(e -> action.run());
|
||||
return button;
|
||||
}
|
||||
|
||||
private Element selected() {
|
||||
var item = tree.getSelectionModel().getSelectedItem();
|
||||
return item == null ? null : item.getValue();
|
||||
}
|
||||
|
||||
private void edit(Supplier<List<Replacement>> action) {
|
||||
try {
|
||||
var edits = action.get();
|
||||
message.setText("");
|
||||
if (!edits.isEmpty()) submit.accept(new FormDocument.Edit(doc.xml.text, edits, ""));
|
||||
} catch (RuntimeException ex) {
|
||||
message.setText(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private TreeItem<Element> item(Element e) {
|
||||
var node = new TreeItem<>(e);
|
||||
node.setExpanded(true);
|
||||
for (var c : doc.branches(e)) node.getChildren().add(item(c));
|
||||
return node;
|
||||
}
|
||||
|
||||
void load(String text, boolean writable) {
|
||||
var previous = selected();
|
||||
String label = previous == null ? "" : doc.label(previous);
|
||||
var oldItem = tree.getSelectionModel().getSelectedItem();
|
||||
var path = new LinkedList<Integer>();
|
||||
for (var n = oldItem; n != null && n.getParent() != null; n = n.getParent())
|
||||
path.addFirst(n.getParent().getChildren().indexOf(n));
|
||||
String field = setting.getValue();
|
||||
try {
|
||||
doc = new GridDockDocument(text);
|
||||
var root = new TreeItem<Element>();
|
||||
root.setExpanded(true);
|
||||
for (var e : doc.roots()) root.getChildren().add(item(e));
|
||||
tree.setRoot(root);
|
||||
setDisable(!writable);
|
||||
var match = root;
|
||||
for (int i : path) {
|
||||
if (i >= match.getChildren().size()) break;
|
||||
match = match.getChildren().get(i);
|
||||
}
|
||||
if (match == root && !root.getChildren().isEmpty()) match = root.getChildren().getFirst();
|
||||
if (match.getValue() != null
|
||||
&& !doc.label(match.getValue()).equals(label)
|
||||
&& match.getParent() != null)
|
||||
match =
|
||||
match.getParent().getChildren().stream()
|
||||
.filter(n -> doc.label(n.getValue()).equals(label))
|
||||
.findFirst()
|
||||
.orElse(match);
|
||||
tree.getSelectionModel().select(match);
|
||||
select();
|
||||
if (setting.getItems().contains(field)) setting.setValue(field);
|
||||
message.setText(root.getChildren().isEmpty() ? "No DataGrid or DockPane in this view." : "");
|
||||
} catch (Exception ex) {
|
||||
tree.setRoot(null);
|
||||
setDisable(true);
|
||||
message.setText(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void visible(javafx.scene.Node node, boolean flag) {
|
||||
node.setVisible(flag);
|
||||
node.setManaged(flag);
|
||||
}
|
||||
|
||||
private void select() {
|
||||
var e = selected();
|
||||
String type = e == null ? "" : doc.type(e);
|
||||
boolean grid = type.equals("DataGrid"), column = type.equals("DataGridColumn");
|
||||
setting.getItems().setAll(GridDockDocument.SETTINGS.getOrDefault(type, List.of()));
|
||||
setting.getSelectionModel().selectFirst();
|
||||
for (var node : List.of(add, signals)) visible(node, grid || column);
|
||||
for (var node : List.of(earlier, later, remove)) visible(node, column);
|
||||
for (var node : List.of(area, addArea)) visible(node, e != null && !grid && !column);
|
||||
visible(
|
||||
moveArea,
|
||||
e != null
|
||||
&& GridDockDocument.AREAS.contains(e.getTagName())
|
||||
&& !e.getTagName().equals("center"));
|
||||
visible(split, type.equals("DockGroupDefinition") || type.equals("DockSplitDefinition"));
|
||||
visible(setting, !setting.getItems().isEmpty());
|
||||
message.setText("");
|
||||
showValue();
|
||||
}
|
||||
|
||||
private void showValue() {
|
||||
String field = setting.getValue();
|
||||
var e = selected();
|
||||
boolean input = "items".equals(field) || "source".equals(field);
|
||||
boolean editable = e != null && field != null && !input;
|
||||
visible(bind, input);
|
||||
visible(apply, editable);
|
||||
visible(value, editable);
|
||||
if (!editable) return;
|
||||
value.getItems().setAll(GridDockDocument.options(field));
|
||||
value.setValue(e.getAttribute(field));
|
||||
value.getEditor().setText(e.getAttribute(field));
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,11 @@ final class ReferenceDocument {
|
||||
|
||||
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) {}
|
||||
|
||||
@@ -54,6 +58,7 @@ final class ReferenceDocument {
|
||||
|
||||
private boolean binding(Element e) {
|
||||
if (!(xml.named(e, "DirectBinding")
|
||||
|| xml.named(e, "CommandBinding")
|
||||
|| xml.named(e, "ComputedBinding")
|
||||
|| xml.named(e, "Repeat"))) return false;
|
||||
Node parent = e.getParentNode();
|
||||
@@ -211,9 +216,9 @@ final class ReferenceDocument {
|
||||
Change paste(Clip clip, int destination, String origin) throws Exception {
|
||||
if (clip == null) throw new IllegalArgumentException("Copy a subtree first");
|
||||
Element parent = entry(destination);
|
||||
requireContainer(parent);
|
||||
var from = new ReferenceDocument(clip.source());
|
||||
Element selected = from.entry(clip.index());
|
||||
String childProperty = childProperty(parent, selected);
|
||||
if (!clip.origin().equals(origin))
|
||||
for (var e : from.xml.elements)
|
||||
if (within(e, selected))
|
||||
@@ -273,7 +278,7 @@ final class ReferenceDocument {
|
||||
.collect(java.util.stream.Collectors.joining("\n"));
|
||||
Element container =
|
||||
children(parent).stream()
|
||||
.filter(c -> c.getTagName().equals("children"))
|
||||
.filter(c -> c.getTagName().equals(childProperty))
|
||||
.findFirst()
|
||||
.orElse(parent);
|
||||
String result = xml.source.apply(List.of(xml.append(container, fragment, "")));
|
||||
@@ -299,7 +304,16 @@ final class ReferenceDocument {
|
||||
+ " validation.");
|
||||
}
|
||||
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) {
|
||||
@@ -407,7 +421,23 @@ final class ReferenceDocument {
|
||||
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();
|
||||
if (FX.equals(e.getNamespaceURI()) && "root".equals(e.getLocalName()))
|
||||
name = e.getAttribute("type");
|
||||
@@ -427,6 +457,7 @@ final class ReferenceDocument {
|
||||
"Paste into a standard Pane; other child properties require Source editing");
|
||||
if (children(e).stream().filter(c -> c.getTagName().equals("children")).count() > 1)
|
||||
throw new IllegalArgumentException("Ambiguous children containers");
|
||||
return "children";
|
||||
}
|
||||
|
||||
private String appendBindings(String body) throws Exception {
|
||||
|
||||
@@ -39,7 +39,7 @@ final class ReferenceEditor extends VBox {
|
||||
.addAll(
|
||||
new Label(
|
||||
"Select a source object or its canvas item. Paste adds children to the selected"
|
||||
+ " Pane."),
|
||||
+ " Pane or Menu."),
|
||||
nodes,
|
||||
new HBox(
|
||||
6,
|
||||
@@ -59,7 +59,7 @@ final class ReferenceEditor extends VBox {
|
||||
clipboard = document.copy(selected(), origin);
|
||||
actionStatus =
|
||||
"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);
|
||||
} catch (Exception e) {
|
||||
error(e.getMessage());
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package de.neitzel.fxdesigner.kit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import de.neitzel.fxdesigner.contracts.*;
|
||||
import java.net.URI;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FormDocumentTest {
|
||||
private String source = "<?import javafx.scene.layout.GridPane?>\n<GridPane/>";
|
||||
|
||||
private FormDocument doc() throws Exception {
|
||||
return new FormDocument(source);
|
||||
}
|
||||
|
||||
private FormDocument.Item item(String id) throws Exception {
|
||||
return doc().items.stream().filter(i -> i.id().equals(id)).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
private FormDocument.Slot slot(String owner, String property) throws Exception {
|
||||
return doc().slots.stream()
|
||||
.filter(s -> s.owner().id().equals(owner) && s.property().equals(property))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
private void apply(FormDocument.Edit edit) throws Exception {
|
||||
source =
|
||||
new EditBatch(1, "form", edit.changes())
|
||||
.applyTo(new DocumentSnapshot(URI.create("file:///test.fxml"), 1, source, true, false));
|
||||
doc();
|
||||
}
|
||||
|
||||
private void add(String type, String owner, String property) throws Exception {
|
||||
var target = slot(owner, property);
|
||||
apply(doc().add(type, target, doc().size(target)));
|
||||
}
|
||||
|
||||
private void set(String id, String name, String value) throws Exception {
|
||||
var doc = doc();
|
||||
var item = item(id);
|
||||
var field =
|
||||
doc.fields(item).stream().filter(f -> f.name().equals(name)).findFirst().orElseThrow();
|
||||
apply(doc.set(item, field, value == null ? "" : value, value == null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyGridAndNamedListsKeepReferencesAndRejectCycles() throws Exception {
|
||||
assertEquals(
|
||||
9, FormDocument.TYPES.values().stream().filter(n -> n.startsWith("de.neitzel.")).count());
|
||||
for (String type :
|
||||
List.of(
|
||||
"Label",
|
||||
"TextField",
|
||||
"NonNegativeIntegerSpinner",
|
||||
"StatusBar",
|
||||
"ToolBarPane",
|
||||
"ToolBar")) add(type, "", "children");
|
||||
add("Label", "statusBar", "leftItems");
|
||||
add("Label", "statusBar", "rightItems");
|
||||
source = source.replace("</GridPane>", "<!--preserve--></GridPane>");
|
||||
apply(doc().move(item("label2"), slot("statusBar", "rightItems"), 0));
|
||||
assertTrue(source.indexOf("id=\"label2\"") < source.indexOf("id=\"label3\""));
|
||||
add("TagChip", "toolBarPane", "items");
|
||||
set("tagChip", "removable", "true");
|
||||
set("tagChip", "onRemove", "#removeTag");
|
||||
set("toolBarPane", "dismissible", "true");
|
||||
set("toolBarPane", "dismissText", "Schließen");
|
||||
set("toolBarPane", "onDismiss", "#dismiss");
|
||||
apply(doc().move(item("tagChip"), slot("toolBar", "items"), 0));
|
||||
var toolbar = source.substring(source.indexOf("<ToolBar "), source.indexOf("</ToolBar>"));
|
||||
assertTrue(
|
||||
toolbar.contains("onRemove=\"#removeTag\"") && toolbar.contains("removable=\"true\""));
|
||||
assertTrue(source.contains("onDismiss=\"#dismiss\"") && source.contains("<!--preserve-->"));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> doc().move(item("toolBar"), slot("toolBar", "items"), 0));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> doc().add("Label", new FormDocument.Slot(item("textField"), "children"), 0));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class, () -> doc().add("Label", slot("", "children"), 999));
|
||||
}
|
||||
|
||||
@Test
|
||||
void propertiesValidateResetAndRoundTrip() throws Exception {
|
||||
add("NonNegativeIntegerSpinner", "", "children");
|
||||
for (var p : List.of("maximum", "initialValue", "minimum"))
|
||||
set(
|
||||
"nonNegativeIntegerSpinner",
|
||||
p,
|
||||
switch (p) {
|
||||
case "maximum" -> "42";
|
||||
case "minimum" -> "2";
|
||||
default -> "8";
|
||||
});
|
||||
assertThrows(
|
||||
IllegalArgumentException.class, () -> set("nonNegativeIntegerSpinner", "maximum", "6"));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class, () -> set("nonNegativeIntegerSpinner", "minimum", "-1"));
|
||||
set("nonNegativeIntegerSpinner", "number", "10");
|
||||
add("AutoCompleteTextField", "", "children");
|
||||
for (var name :
|
||||
List.of("promptText", "styleClass", "padding", "GridPane.columnIndex", "suggestions")) {
|
||||
String value =
|
||||
switch (name) {
|
||||
case "padding" -> "1 2 3 4";
|
||||
case "GridPane.columnIndex" -> "1";
|
||||
case "suggestions" -> "A & B\nPosteingang";
|
||||
default -> "Eingabe";
|
||||
};
|
||||
set("autoCompleteTextField", name, value);
|
||||
var d = doc();
|
||||
var item = item("autoCompleteTextField");
|
||||
var f = d.fields(item).stream().filter(x -> name.equals(x.name())).findFirst().orElseThrow();
|
||||
assertEquals(name.equals("padding") ? "1.0 2.0 3.0 4.0" : value, d.value(item, f));
|
||||
set("autoCompleteTextField", name, null);
|
||||
assertFalse(source.contains("<" + name + ">"));
|
||||
assertEquals("", doc().value(item("autoCompleteTextField"), f));
|
||||
}
|
||||
assertThrows(IllegalArgumentException.class, () -> set("autoCompleteTextField", "width", "20"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nativeSaveBetweenPaletteSelectionAndApply() throws Exception {
|
||||
source = source.replace("<GridPane/>", "<GridPane> \n</GridPane>");
|
||||
var edit = doc().add("Label", slot("", "children"), 0);
|
||||
var saved = source.replace("> \n", ">\n");
|
||||
var changes = FormDocument.forCurrentText(edit, saved);
|
||||
var result =
|
||||
new EditBatch(2, "Insert Label", changes)
|
||||
.applyTo(new DocumentSnapshot(URI.create("file:///test.fxml"), 2, saved, true, false));
|
||||
assertTrue(new FormDocument(result).items.stream().anyMatch(i -> i.id().equals("label")));
|
||||
assertThrows(
|
||||
ConcurrentModificationException.class,
|
||||
() -> FormDocument.forCurrentText(edit, saved.replace("GridPane", "VBox")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void implicitToolbarChildrenStayInOneList() throws Exception {
|
||||
source =
|
||||
"<?import de.neitzel.fx.control.ToolBarPane?><?import"
|
||||
+ " javafx.scene.control.Label?><ToolBarPane><Label/></ToolBarPane>";
|
||||
add("Label", "", "items");
|
||||
assertEquals(2, doc().size(slot("", "items")));
|
||||
assertFalse(source.contains("<items>"));
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,26 @@ class FxmlProjectionTest {
|
||||
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
|
||||
void rejectsExternalEntitiesAndExecutableFXML() throws Exception {
|
||||
assertThrows(
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package de.neitzel.fxdesigner.kit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class GridDockDocumentTest {
|
||||
@Test
|
||||
void implicitRowAttributeAndGroupingSurviveRename() throws Exception {
|
||||
var source =
|
||||
"""
|
||||
<?import de.neitzel.fx.view.DataGrid?>
|
||||
<?import de.neitzel.fx.view.DataGridColumn?>
|
||||
<DataGrid groupBy="name"><columns>
|
||||
<DataGridColumn id="name" header="Name"/>
|
||||
<DataGridColumn id="age"/>
|
||||
</columns></DataGrid>
|
||||
""";
|
||||
var doc = new GridDockDocument(source);
|
||||
var grid = doc.roots().getFirst();
|
||||
var col = doc.branches(grid).getFirst();
|
||||
assertThrows(IllegalArgumentException.class, () -> doc.removeColumn(col));
|
||||
assertThrows(IllegalArgumentException.class, () -> doc.set(col, "id", "age"));
|
||||
var renamed = doc.xml.source.apply(doc.set(col, "id", "title"));
|
||||
assertTrue(renamed.contains("groupBy=\"title\""));
|
||||
assertTrue(renamed.contains("attribute=\"name\""));
|
||||
var removed = doc.xml.source.apply(doc.removeColumn(doc.branches(grid).getLast()));
|
||||
assertEquals(source.replace(" <DataGridColumn id=\"age\"/>\n", ""), removed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rootDockProjectionAndAmbiguousImportPreserveOriginal() throws Exception {
|
||||
String source =
|
||||
"""
|
||||
<?import de.neitzel.fx.docking.*?>
|
||||
<DockPane><initialLayout><DockLayout><center><DockGroupDefinition destinationId='main'/></center></DockLayout></initialLayout></DockPane>
|
||||
""";
|
||||
var projection = new FxmlProjection(source);
|
||||
assertEquals(source, projection.restore(projection.project()));
|
||||
String conflict = source.replace("<DockPane>", "<?import my.docks.*?>\n<DockPane>");
|
||||
var ex = assertThrows(java.io.IOException.class, () -> new FxmlProjection(conflict).project());
|
||||
assertTrue(ex.getMessage().contains("<DockPane> at line 3, column 1"), ex::getMessage);
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,26 @@ class ReferenceDocumentTest {
|
||||
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
|
||||
void carriesNamespacesImportsAndReportsDestinationContextDifferences() throws Exception {
|
||||
String source =
|
||||
|
||||
+160
-13
@@ -1,7 +1,7 @@
|
||||
package de.neitzel.fxdesigner.target;
|
||||
|
||||
import de.neitzel.fxdesigner.protocol.BindingMetadata.*;
|
||||
import de.neitzel.fxdesigner.protocol.BindingMetadata;
|
||||
import de.neitzel.fxdesigner.protocol.BindingMetadata.*;
|
||||
import java.beans.*;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
@@ -23,11 +23,38 @@ public final class BindingDiscovery {
|
||||
private final Map<String, String> generatedElements = new HashMap<>();
|
||||
private ControllerMetadata owner;
|
||||
private final List<Problem> selectionProblems = new ArrayList<>();
|
||||
private final Set<String> readOnlySources = new HashSet<>();
|
||||
private final Map<String, Class<?>> paths = new TreeMap<>();
|
||||
private final List<Attribute> attributes = new ArrayList<>();
|
||||
|
||||
private record TargetType(Class<?> type, boolean writable) {}
|
||||
private final Map<String, Class<?>> listElements = new HashMap<>();
|
||||
|
||||
private record TargetType(Class<?> type, boolean writable, Class<?> listElement) {}
|
||||
|
||||
// Invariant element signatures for explicit JavaFX list properties. Keep raw, wildcard
|
||||
// and unresolvable generic declarations in the existing unverified collection path.
|
||||
private static Class<?> listElement(Method method) {
|
||||
if (!(method.getGenericReturnType() instanceof ParameterizedType p)
|
||||
|| p.getActualTypeArguments().length != 1) return null;
|
||||
Type value = p.getActualTypeArguments()[0];
|
||||
if (p.getRawType() == javafx.beans.property.ListProperty.class
|
||||
|| p.getRawType() == javafx.beans.property.ReadOnlyListProperty.class)
|
||||
return value instanceof Class<?> element ? element : null;
|
||||
if ((p.getRawType() == javafx.beans.property.ObjectProperty.class
|
||||
|| p.getRawType() == javafx.beans.property.ReadOnlyObjectProperty.class)
|
||||
&& value instanceof ParameterizedType list
|
||||
&& list.getRawType() == javafx.collections.ObservableList.class
|
||||
&& list.getActualTypeArguments()[0] instanceof Class<?> element) return element;
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean knownListPair(String path, TargetType target, String direction) {
|
||||
return direction.equals("view")
|
||||
&& listElements.containsKey(path)
|
||||
&& target.listElement() != null;
|
||||
}
|
||||
|
||||
private final Set<String> actionHandlers = new HashSet<>();
|
||||
private final Map<String, Class<?>> controlTypes = new HashMap<>();
|
||||
private RepeatDiscovery repeats;
|
||||
private final Map<String, TargetType> targetTypes = new HashMap<>();
|
||||
@@ -313,6 +340,10 @@ public final class BindingDiscovery {
|
||||
? owner.controller
|
||||
: resolve(e, imports);
|
||||
controlTypes.put(id, control);
|
||||
if (e.hasAttribute("onAction")) actionHandlers.add(id);
|
||||
for (Node child = e.getFirstChild(); child != null; child = child.getNextSibling())
|
||||
if (child instanceof Element property && property.getTagName().equals("onAction"))
|
||||
actionHandlers.add(id);
|
||||
String componentModel = "";
|
||||
var componentResource = control.getResource(control.getSimpleName() + ".fxml");
|
||||
if (componentResource != null)
|
||||
@@ -338,13 +369,17 @@ public final class BindingDiscovery {
|
||||
value = load(componentModel);
|
||||
constrained = true;
|
||||
}
|
||||
targetTypes.put(
|
||||
id + "." + property,
|
||||
new TargetType(value, Property.class.isAssignableFrom(m.getReturnType())));
|
||||
var target =
|
||||
new TargetType(
|
||||
value, Property.class.isAssignableFrom(m.getReturnType()), listElement(m));
|
||||
targetTypes.put(id + "." + property, target);
|
||||
String status, reason;
|
||||
if (!Property.class.isAssignableFrom(m.getReturnType())) {
|
||||
status = "INCOMPATIBLE";
|
||||
reason = "Runtime bindings require a writable JavaFX Property accessor.";
|
||||
} else if (readOnlySources.contains(selected) && !direction.equals("view")) {
|
||||
status = "INCOMPATIBLE";
|
||||
reason = "Read-only source requires direction=view.";
|
||||
} else if (source == null
|
||||
|| source == Object.class
|
||||
|| value == null
|
||||
@@ -352,6 +387,13 @@ public final class BindingDiscovery {
|
||||
status = "UNRESOLVED";
|
||||
reason =
|
||||
"Declared types are insufficient; rebuild with specific signatures/Model metadata.";
|
||||
} else if (knownListPair(selected, target, direction)) {
|
||||
boolean matches = listElements.get(selected) == target.listElement();
|
||||
status = matches ? "COMPATIBLE" : "INCOMPATIBLE";
|
||||
reason =
|
||||
matches
|
||||
? "Matching observable list element type: " + target.listElement().getName()
|
||||
: "Observable list element types differ.";
|
||||
} else if (Collection.class.isAssignableFrom(source)
|
||||
|| Collection.class.isAssignableFrom(value)
|
||||
|| Map.class.isAssignableFrom(source)
|
||||
@@ -377,7 +419,6 @@ public final class BindingDiscovery {
|
||||
}
|
||||
targets.add(
|
||||
new Target(id, property, value == null ? "?" : value.getName(), status, reason));
|
||||
if (targets.size() > 2048) throw new IOException("Too many binding targets");
|
||||
}
|
||||
} catch (ClassNotFoundException | LinkageError ex) {
|
||||
diagnostics.add(id + ": unavailable target type: " + ex.getMessage());
|
||||
@@ -390,6 +431,15 @@ public final class BindingDiscovery {
|
||||
.indexOf(t.status()))
|
||||
.thenComparing(Target::control)
|
||||
.thenComparing(Target::property));
|
||||
// Validate every declaration. Bound only the suggestions sent to the editor.
|
||||
if (targets.size() > 2048) {
|
||||
targets.sort(Comparator.comparing(t -> !t.control().equals(selectedControl)));
|
||||
diagnostics.add(
|
||||
"Showing 2048 of "
|
||||
+ targets.size()
|
||||
+ " target properties. Select a control in the form inspector to edit its bindings.");
|
||||
targets.subList(2048, targets.size()).clear();
|
||||
}
|
||||
var converters = new ConverterDiscovery(loader);
|
||||
var chosen = targetTypes.get(selectedControl + "." + selectedProperty);
|
||||
var candidates =
|
||||
@@ -398,7 +448,8 @@ public final class BindingDiscovery {
|
||||
: converters.candidates(source, chosen == null ? null : chosen.type(), direction);
|
||||
repeats = new RepeatDiscovery(loader, attributes, owner, incompleteModel, controlTypes, ids);
|
||||
var tables = new TableDiscovery(loader, repeats, modelType, owner);
|
||||
var problems = new ArrayList<>(validate(doc, imports, ids, converters));
|
||||
var commands = commandPaths();
|
||||
var problems = new ArrayList<>(validate(doc, imports, ids, converters, commands));
|
||||
problems.addAll(tables.validate(doc));
|
||||
var componentOptions = repeats.candidates(selected);
|
||||
for (var a : attributes)
|
||||
@@ -421,7 +472,35 @@ public final class BindingDiscovery {
|
||||
repeats.panes(),
|
||||
tables.collections(),
|
||||
tables.rows(selected),
|
||||
tables.columns(selected));
|
||||
tables.columns(selected),
|
||||
commands,
|
||||
controlTypes.entrySet().stream()
|
||||
.filter(e -> commandTarget(e.getValue()))
|
||||
.map(Map.Entry::getKey)
|
||||
.sorted()
|
||||
.toList());
|
||||
}
|
||||
|
||||
private List<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)
|
||||
@@ -466,22 +545,29 @@ public final class BindingDiscovery {
|
||||
for (Method m : vm.getMethods()) {
|
||||
if (m.getParameterCount() != 0
|
||||
|| !m.getName().endsWith("Property")
|
||||
|| !Property.class.isAssignableFrom(m.getReturnType())
|
||||
|| !ObservableValue.class.isAssignableFrom(m.getReturnType())
|
||||
|| Modifier.isStatic(m.getModifiers())
|
||||
|| m.isBridge()
|
||||
|| m.isSynthetic()) continue;
|
||||
String name = m.getName().substring(0, m.getName().length() - 8);
|
||||
if (name.isEmpty() || paths.containsKey(name)) continue;
|
||||
Class<?> element = listElement(m);
|
||||
if (element != null) listElements.put(name, element);
|
||||
Class<?> value = propertyType(m.getGenericReturnType(), Map.of());
|
||||
Class<?> getter = valueType(vm, name);
|
||||
if (value == Number.class && getter != null && Number.class.isAssignableFrom(box(getter)))
|
||||
value = getter;
|
||||
else if (value != null && getter != null && box(value) != box(getter)) value = null;
|
||||
boolean readOnly = !Property.class.isAssignableFrom(m.getReturnType());
|
||||
if (readOnly) readOnlySources.add(name);
|
||||
paths.put(name, value == null ? Object.class : value);
|
||||
attributes.add(
|
||||
new Attribute(
|
||||
name,
|
||||
value == null ? "?" : value.getName(),
|
||||
value == null || value == Object.class ? "UNRESOLVED" : "VIEWMODEL",
|
||||
readOnly
|
||||
? "READ_ONLY"
|
||||
: value == null || value == Object.class ? "UNRESOLVED" : "VIEWMODEL",
|
||||
""));
|
||||
if (attributes.size() > 256) throw new IOException("Too many ViewModel properties");
|
||||
}
|
||||
@@ -492,17 +578,31 @@ public final class BindingDiscovery {
|
||||
.anyMatch(a -> a.path().equals(path) && Set.of("COMPLEX", "COLLECTION").contains(a.kind()));
|
||||
}
|
||||
|
||||
private static String propertyValue(Element declaration, String name) {
|
||||
if (declaration.hasAttribute(name)) return declaration.getAttribute(name);
|
||||
for (Node n = declaration.getFirstChild(); n != null; n = n.getNextSibling())
|
||||
if (n instanceof Element child && child.getTagName().equals(name))
|
||||
return child.getTextContent().trim();
|
||||
return "";
|
||||
}
|
||||
|
||||
private List<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 {
|
||||
var problems = new ArrayList<Problem>(selectionProblems);
|
||||
problems.addAll(owner.problems);
|
||||
var occupied = new HashSet<String>();
|
||||
var commandControls = new TreeSet<String>();
|
||||
var nodes = doc.getElementsByTagName("*");
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
var e = (Element) nodes.item(i);
|
||||
if (!library(e, "DirectBinding", imports)
|
||||
&& !library(e, "ComputedBinding", imports)
|
||||
&& !library(e, "CommandBinding", imports)
|
||||
&& !library(e, "Repeat", imports)) continue;
|
||||
Node parent = e.getParentNode();
|
||||
if (parent instanceof Element p && p.getTagName().equals("elements"))
|
||||
@@ -529,9 +629,39 @@ public final class BindingDiscovery {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
String control = e.getAttribute("control"),
|
||||
property = e.getAttribute("property"),
|
||||
String control = propertyValue(e, "control"),
|
||||
property = propertyValue(e, "property"),
|
||||
key = control + "." + property;
|
||||
if (library(e, "CommandBinding", imports)) {
|
||||
String path = propertyValue(e, "path");
|
||||
if (!ids.contains(control))
|
||||
problems.add(
|
||||
new Problem(control, "command", "ERROR", "Unknown Command target fx:id: " + control));
|
||||
else if (!commandTarget(controlTypes.get(control)))
|
||||
problems.add(
|
||||
new Problem(
|
||||
control,
|
||||
"command",
|
||||
"ERROR",
|
||||
"Command target must be a ButtonBase or MenuItem: " + control));
|
||||
if (path.isBlank() || path.contains("."))
|
||||
problems.add(
|
||||
new Problem(control, "command", "ERROR", "Expected a simple Command path: " + path));
|
||||
else if (!commands.contains(path))
|
||||
problems.add(new Problem(control, "command", "ERROR", "Unknown Command path: " + path));
|
||||
if (!commandControls.add(control))
|
||||
problems.add(
|
||||
new Problem(
|
||||
control,
|
||||
"command",
|
||||
"ERROR",
|
||||
"Duplicate Command binding for disable and onAction"));
|
||||
if (actionHandlers.contains(control))
|
||||
problems.add(
|
||||
new Problem(
|
||||
control, "command", "ERROR", "Command conflicts with existing onAction handler"));
|
||||
continue;
|
||||
}
|
||||
if (!occupied.add(key))
|
||||
problems.add(new Problem(control, property, "ERROR", "Duplicate binding target"));
|
||||
|
||||
@@ -591,6 +721,9 @@ public final class BindingDiscovery {
|
||||
} else if (!target.writable()) {
|
||||
severity = "ERROR";
|
||||
message = "Runtime requires a writable JavaFX Property";
|
||||
} else if (readOnlySources.contains(path) && !direction.equals("view")) {
|
||||
severity = "ERROR";
|
||||
message = "Read-only source " + path + " requires direction=view";
|
||||
} else if (source == null) {
|
||||
severity = incompleteModel ? "WARNING" : "ERROR";
|
||||
message = "Unknown or unresolved Model path: " + path;
|
||||
@@ -605,6 +738,11 @@ public final class BindingDiscovery {
|
||||
severity = c.status().equals("UNVERIFIED") ? "WARNING" : "ERROR";
|
||||
message = converter + ": " + c.reason();
|
||||
}
|
||||
} else if (knownListPair(path, target, direction)) {
|
||||
if (listElements.get(path) != target.listElement()) {
|
||||
severity = "ERROR";
|
||||
message = "Observable list element types differ.";
|
||||
}
|
||||
} else if (target.type() == null
|
||||
|| source == Object.class
|
||||
|| target.type() == Object.class
|
||||
@@ -624,6 +762,15 @@ public final class BindingDiscovery {
|
||||
}
|
||||
if (!severity.isEmpty()) problems.add(new Problem(control, property, severity, message));
|
||||
}
|
||||
for (String control : commandControls)
|
||||
for (String endpoint : List.of("disable", "onAction"))
|
||||
if (occupied.contains(control + "." + endpoint))
|
||||
problems.add(
|
||||
new Problem(
|
||||
control,
|
||||
"command",
|
||||
"ERROR",
|
||||
"Command conflicts with another binding for " + endpoint));
|
||||
return problems;
|
||||
}
|
||||
|
||||
|
||||
+125
-47
@@ -12,16 +12,19 @@ import javafx.scene.*;
|
||||
import javafx.scene.image.WritableImage;
|
||||
import javafx.scene.paint.Color;
|
||||
|
||||
/**
|
||||
* One preview session per target JVM: the library retains process-wide Model/ViewModel identities.
|
||||
*/
|
||||
/** A worker owns one preview session and its managed Views. */
|
||||
public final class TargetPreview implements AutoCloseable {
|
||||
private static final AtomicBoolean CONSUMED = new AtomicBoolean();
|
||||
private PreviewSession<?, ?> session;
|
||||
private LoadedView view;
|
||||
private final ViewModelContext models = new ViewModelContext();
|
||||
private Scene scene;
|
||||
private final Occurrences occurrences = new Occurrences();
|
||||
private javafx.stage.Stage interactive;
|
||||
|
||||
private record WindowGeometry(double x, double y, double width, double height, double opacity) {}
|
||||
|
||||
private WindowGeometry beforeWebSnapshot;
|
||||
private boolean closed;
|
||||
private final CompletableFuture<TargetPreview> ready = new CompletableFuture<>();
|
||||
private final CompletableFuture<Void> cleanup = new CompletableFuture<>();
|
||||
@@ -128,32 +131,12 @@ public final class TargetPreview implements AutoCloseable {
|
||||
if (component) {
|
||||
String name =
|
||||
d.viewResource().substring(0, d.viewResource().length() - 5).replace('/', '.');
|
||||
Class<?> componentType = Class.forName(name, false, loader);
|
||||
if (!Parent.class.isAssignableFrom(componentType))
|
||||
throw new IllegalArgumentException("Component root is not a Parent");
|
||||
byte[] wrapper = ("<" + name + "/>").getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
var wrapped =
|
||||
new java.net.URL(
|
||||
null,
|
||||
"memory:component",
|
||||
new java.net.URLStreamHandler() {
|
||||
protected java.net.URLConnection openConnection(java.net.URL url) {
|
||||
return new java.net.URLConnection(url) {
|
||||
public void connect() {}
|
||||
|
||||
public java.io.InputStream getInputStream() {
|
||||
return new java.io.ByteArrayInputStream(wrapper);
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
view = ViewLoader.load(wrapped, session.model(), context);
|
||||
var model = componentType.getMethod("modelProperty").invoke(view.getRoot());
|
||||
if (!(model instanceof javafx.beans.property.Property property))
|
||||
throw new IllegalArgumentException("Component has no writable Model");
|
||||
property.setValue(session.model());
|
||||
} else view = ViewLoader.load(resource, session.model(), context);
|
||||
var componentType = Class.forName(name, false, loader).asSubclass(Parent.class);
|
||||
view = ViewLoader.loadComponent(componentType, session.model(), context, models);
|
||||
} else view = ViewLoader.load(resource, session.model(), context, models);
|
||||
scene = new Scene(view.getRoot(), 420, 240);
|
||||
interactive = new javafx.stage.Stage();
|
||||
interactive.setScene(scene);
|
||||
layout(420, 240);
|
||||
var wait = session.ready();
|
||||
if (wait == null)
|
||||
@@ -216,6 +199,15 @@ public final class TargetPreview implements AutoCloseable {
|
||||
}
|
||||
|
||||
public byte[] renderNode(String nodeId, int width, int height) {
|
||||
return snapshotNode(nodeId, width, height, false).toCompletableFuture().join();
|
||||
}
|
||||
|
||||
CompletionStage<byte[]> frame(String nodeId, int width, int height) {
|
||||
return snapshotNode(nodeId, width, height, true);
|
||||
}
|
||||
|
||||
private CompletionStage<byte[]> snapshotNode(
|
||||
String nodeId, int width, int height, boolean waitForWeb) {
|
||||
fx();
|
||||
if (closed || !ready.isDone() || ready.isCompletedExceptionally())
|
||||
throw new IllegalStateException("Preview not ready");
|
||||
@@ -226,7 +218,31 @@ public final class TargetPreview implements AutoCloseable {
|
||||
|| (long) width * height * 4 > 16 * 1024 * 1024)
|
||||
throw new IllegalArgumentException("Image exceeds protocol limits");
|
||||
var node = occurrences.resolve(view.getRoot(), nodeId);
|
||||
if (node == view.getRoot()) layout(width, height);
|
||||
boolean web = waitForWeb && node != null && node.lookup("WebView") != null;
|
||||
if (web && !interactive.isShowing()) {
|
||||
beforeWebSnapshot =
|
||||
new WindowGeometry(
|
||||
interactive.getX(),
|
||||
interactive.getY(),
|
||||
interactive.getWidth(),
|
||||
interactive.getHeight(),
|
||||
interactive.getOpacity());
|
||||
double right =
|
||||
javafx.stage.Screen.getScreens().stream()
|
||||
.mapToDouble(s -> s.getBounds().getMaxX())
|
||||
.max()
|
||||
.orElse(0);
|
||||
interactive.setX(right + 1);
|
||||
interactive.setOpacity(0);
|
||||
interactive.show();
|
||||
}
|
||||
if (node == view.getRoot()) {
|
||||
if (web && beforeWebSnapshot != null) {
|
||||
interactive.setWidth(width + Math.max(0, interactive.getWidth() - scene.getWidth()));
|
||||
interactive.setHeight(height + Math.max(0, interactive.getHeight() - scene.getHeight()));
|
||||
}
|
||||
layout(width, height);
|
||||
}
|
||||
if (node == null) throw new IllegalArgumentException("Unknown rendered node: " + nodeId);
|
||||
boolean isolate = node != view.getRoot() && node.isResizable();
|
||||
boolean managed = node.isManaged();
|
||||
@@ -243,23 +259,75 @@ public final class TargetPreview implements AutoCloseable {
|
||||
parameters.setFill(Color.TRANSPARENT);
|
||||
var bounds = node.getBoundsInParent();
|
||||
parameters.setViewport(new Rectangle2D(bounds.getMinX(), bounds.getMinY(), width, height));
|
||||
var image = node.snapshot(parameters, new WritableImage(width, height));
|
||||
byte[] bytes = new byte[width * height * 4];
|
||||
var pixels = image.getPixelReader();
|
||||
for (int y = 0; y < height; y++)
|
||||
for (int x = 0; x < width; x++) {
|
||||
int argb = pixels.getArgb(x, y), i = (y * width + x) * 4;
|
||||
bytes[i] = (byte) (argb >>> 16);
|
||||
bytes[i + 1] = (byte) (argb >>> 8);
|
||||
bytes[i + 2] = (byte) argb;
|
||||
bytes[i + 3] = (byte) (argb >>> 24);
|
||||
}
|
||||
return bytes;
|
||||
} finally {
|
||||
var image = new WritableImage(width, height);
|
||||
if (web) {
|
||||
var frame = webFrame(node, parameters, image);
|
||||
return frame.whenComplete(
|
||||
(ignored, error) -> {
|
||||
if (isolate) node.setManaged(managed);
|
||||
});
|
||||
}
|
||||
var bytes = pixels(node.snapshot(parameters, image));
|
||||
if (isolate) node.setManaged(managed);
|
||||
return CompletableFuture.completedFuture(bytes);
|
||||
} catch (Throwable error) {
|
||||
if (isolate) node.setManaged(managed);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WebKit updates its render queue on a stage pulse, before scene layout. Give it a pulse at the
|
||||
* new layout size before reading the next snapshot.
|
||||
*/
|
||||
private CompletionStage<byte[]> webFrame(
|
||||
Node node, SnapshotParameters parameters, WritableImage image) {
|
||||
var result = new CompletableFuture<byte[]>();
|
||||
Scene owner = scene;
|
||||
owner.addPostLayoutPulseListener(
|
||||
new Runnable() {
|
||||
public void run() {
|
||||
owner.removePostLayoutPulseListener(this);
|
||||
Platform.runLater(
|
||||
() -> {
|
||||
try {
|
||||
if (closed) throw new CancellationException("Preview closed");
|
||||
node.snapshot(
|
||||
snapshot -> {
|
||||
try {
|
||||
result.complete(pixels(snapshot.getImage()));
|
||||
} catch (Throwable error) {
|
||||
result.completeExceptionally(error);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
parameters,
|
||||
image);
|
||||
} catch (Throwable error) {
|
||||
result.completeExceptionally(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Platform.requestNextPulse();
|
||||
return result;
|
||||
}
|
||||
|
||||
private static byte[] pixels(javafx.scene.image.Image image) {
|
||||
int width = (int) image.getWidth(), height = (int) image.getHeight();
|
||||
byte[] bytes = new byte[width * height * 4];
|
||||
var pixels = image.getPixelReader();
|
||||
for (int y = 0; y < height; y++)
|
||||
for (int x = 0; x < width; x++) {
|
||||
int argb = pixels.getArgb(x, y), i = (y * width + x) * 4;
|
||||
bytes[i] = (byte) (argb >>> 16);
|
||||
bytes[i + 1] = (byte) (argb >>> 8);
|
||||
bytes[i + 2] = (byte) argb;
|
||||
bytes[i + 3] = (byte) (argb >>> 24);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public de.neitzel.fxdesigner.protocol.LayoutMetrics measure(String key, int width, int height) {
|
||||
fx();
|
||||
var node = occurrences.resolve(view.getRoot(), key);
|
||||
@@ -285,11 +353,19 @@ public final class TargetPreview implements AutoCloseable {
|
||||
|
||||
public void showInteractive(String title, Runnable onClosed) {
|
||||
fx();
|
||||
if (interactive == null) {
|
||||
interactive = new javafx.stage.Stage();
|
||||
interactive.setScene(scene);
|
||||
interactive.setOnHidden(e -> onClosed.run());
|
||||
if (beforeWebSnapshot != null) {
|
||||
var previous = beforeWebSnapshot;
|
||||
beforeWebSnapshot = null;
|
||||
interactive.hide();
|
||||
interactive.setOpacity(previous.opacity());
|
||||
if (Double.isFinite(previous.width())) interactive.setWidth(previous.width());
|
||||
if (Double.isFinite(previous.height())) interactive.setHeight(previous.height());
|
||||
if (Double.isFinite(previous.x()) && Double.isFinite(previous.y())) {
|
||||
interactive.setX(previous.x());
|
||||
interactive.setY(previous.y());
|
||||
} else interactive.centerOnScreen();
|
||||
}
|
||||
interactive.setOnHidden(e -> onClosed.run());
|
||||
interactive.setTitle(title);
|
||||
interactive.show();
|
||||
interactive.toFront();
|
||||
@@ -316,7 +392,9 @@ public final class TargetPreview implements AutoCloseable {
|
||||
closed = true;
|
||||
timer.shutdownNow();
|
||||
try {
|
||||
if (session != null) session.close();
|
||||
try (var ownedSession = session) {
|
||||
models.close();
|
||||
}
|
||||
cleanup.complete(null);
|
||||
} catch (Throwable e) {
|
||||
if (failure != null) failure.addSuppressed(e);
|
||||
|
||||
@@ -205,13 +205,30 @@ public final class WorkerMain {
|
||||
() -> {
|
||||
if (stopping.get()) return;
|
||||
try {
|
||||
send(
|
||||
socket,
|
||||
new Packet(
|
||||
Kind.RESULT,
|
||||
p.operation(),
|
||||
p.identity(),
|
||||
response(ready, p, data)));
|
||||
var result =
|
||||
p.operation() == Operation.RENDER
|
||||
? ready.frame(
|
||||
data.get("node"),
|
||||
p.identity().width(),
|
||||
p.identity().height())
|
||||
: java.util.concurrent.CompletableFuture.completedFuture(
|
||||
response(ready, p, data));
|
||||
result.whenComplete(
|
||||
(payload, failure) -> {
|
||||
if (stopping.get()) return;
|
||||
if (failure != null) {
|
||||
error(socket, p, failure);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
send(
|
||||
socket,
|
||||
new Packet(
|
||||
Kind.RESULT, p.operation(), p.identity(), payload));
|
||||
} catch (IOException e) {
|
||||
error(socket, p, e);
|
||||
}
|
||||
});
|
||||
} catch (Throwable e) {
|
||||
error(socket, p, e);
|
||||
}
|
||||
@@ -231,8 +248,6 @@ public final class WorkerMain {
|
||||
private static byte[] response(TargetPreview ready, Packet p, Map<String, String> data)
|
||||
throws Exception {
|
||||
return switch (p.operation()) {
|
||||
case RENDER ->
|
||||
ready.renderNode(data.get("node"), p.identity().width(), p.identity().height());
|
||||
case MEASURE ->
|
||||
PreviewMessages.encode(
|
||||
ready
|
||||
|
||||
+61
@@ -112,6 +112,67 @@ class BindingDiscoveryTest {
|
||||
() -> BindingDiscovery.inspect(fxml(), "", "wrong", getClass().getClassLoader()));
|
||||
}
|
||||
|
||||
@de.neitzel.fx.view.ViewModelClass(Commands.class)
|
||||
public static class Controller {}
|
||||
|
||||
public static class Commands {
|
||||
public Commands(Model model) {
|
||||
throw new AssertionError("Discovery constructed the ViewModel");
|
||||
}
|
||||
|
||||
public de.neitzel.fx.view.Command getOpen() {
|
||||
throw new AssertionError("Discovery executed the Command getter");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void commandDiscoveryResolvesTargetsAndLocatesConflictsInEitherOrder() throws Exception {
|
||||
String command = "<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 Number getAmount() {
|
||||
return null;
|
||||
|
||||
+47
-1
@@ -49,6 +49,14 @@ class ViewModelComputedTest {
|
||||
throw new AssertionError("reserved invoked");
|
||||
}
|
||||
|
||||
public ReadOnlyListProperty<String> tagsProperty() {
|
||||
throw new AssertionError("property invoked");
|
||||
}
|
||||
|
||||
public ObjectProperty<javafx.collections.ObservableList<Integer>> numbersProperty() {
|
||||
throw new AssertionError("property invoked");
|
||||
}
|
||||
|
||||
public ReadOnlyStringProperty readOnlyProperty() {
|
||||
throw new AssertionError("readonly invoked");
|
||||
}
|
||||
@@ -216,13 +224,51 @@ class ViewModelComputedTest {
|
||||
assertEquals(String.class.getName(), types.get("badge"));
|
||||
assertEquals(String.class.getName(), types.get("name"));
|
||||
assertEquals(String.class.getName(), types.get("latestMessage"));
|
||||
assertFalse(types.containsKey("readOnly"));
|
||||
assertEquals(String.class.getName(), types.get("readOnly"));
|
||||
assertTrue(
|
||||
result.attributes().stream()
|
||||
.anyMatch(a -> a.path().equals("readOnly") && a.kind().equals("READ_ONLY")));
|
||||
for (String direction : List.of("view", "model", "both")) {
|
||||
var validation =
|
||||
inspect(
|
||||
xml(
|
||||
Controller.class,
|
||||
direct("readOnly").replace("direction='view'", "direction='" + direction + "'")));
|
||||
assertEquals(
|
||||
!direction.equals("view"),
|
||||
validation.problems().stream()
|
||||
.anyMatch(p -> p.message().contains("requires direction=view")));
|
||||
}
|
||||
assertEquals(Custom.class.getName(), result.viewModel());
|
||||
assertTrue(result.problems().isEmpty(), result.problems().toString());
|
||||
for (String key : List.of("vm.metadata.initialized", "controller.metadata.initialized"))
|
||||
assertNull(System.getProperty(key));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listTargetsCheckTheDeclaredElementTypeForDiscoveryAndValidation() throws Exception {
|
||||
for (String path : List.of("tags", "numbers")) {
|
||||
String document =
|
||||
xml(
|
||||
Controller.class,
|
||||
direct(path).replace("property='text'", "property='suggestionsSource'"))
|
||||
.replace(
|
||||
"javafx.scene.control.TextField", "de.neitzel.fx.control.AutoCompleteTextField")
|
||||
.replace("<TextField", "<AutoCompleteTextField")
|
||||
.replace("</TextField>", "</AutoCompleteTextField>");
|
||||
var result = BindingDiscovery.inspect(document, path, "view", getClass().getClassLoader());
|
||||
var target =
|
||||
result.targets().stream()
|
||||
.filter(t -> t.property().equals("suggestionsSource"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
boolean matching = path.equals("tags");
|
||||
assertEquals(matching ? "COMPATIBLE" : "INCOMPATIBLE", target.status());
|
||||
assertEquals(
|
||||
!matching, result.problems().stream().anyMatch(p -> p.severity().equals("ERROR")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementDoesNotInheritModelAttributesOrDottedTraversal() throws Exception {
|
||||
var result = inspect(xml(ReplacementController.class, direct("home.name")));
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
"schemaVersion": 1,
|
||||
"status": "verified-local-development-snapshot",
|
||||
"sourceRepository": "ssh://git@gitea.neitzel.de:2222/konrad/NeitzelLib.git",
|
||||
"sourceRevision": "75b733abe300bea799a59664f0d5a9dbc21d315b",
|
||||
"sourceRevision": "e4f1fd3c96f79f22da8998f5a03d05363e30b1e2",
|
||||
"minimumReleasedVersion": null,
|
||||
"requiredCapability": "component-fxml-attributes-after-initialization",
|
||||
"requiredCapability": "managed-views-command-bindings-and-document-inputs",
|
||||
"javaVersion": "25",
|
||||
"javafxVersion": "27.0.1",
|
||||
"testResults": {
|
||||
@@ -12,7 +12,7 @@
|
||||
"tests": 9,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
"skipped": 1
|
||||
},
|
||||
"injection": {
|
||||
"tests": 10,
|
||||
@@ -21,7 +21,19 @@
|
||||
"skipped": 0
|
||||
},
|
||||
"fx": {
|
||||
"tests": 105,
|
||||
"tests": 408,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 12
|
||||
},
|
||||
"data-grid": {
|
||||
"tests": 33,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
"fx-test": {
|
||||
"tests": 2,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
@@ -31,59 +43,76 @@
|
||||
{
|
||||
"groupId": "de.neitzel.lib",
|
||||
"artifactId": "neitzellib",
|
||||
"version": "1.0-SNAPSHOT",
|
||||
"version": "1.0.6-SNAPSHOT",
|
||||
"extension": "pom",
|
||||
"repositoryPath": "de/neitzel/lib/neitzellib/1.0-SNAPSHOT/neitzellib-1.0-SNAPSHOT.pom",
|
||||
"sha256": "23f7507a215f42d1ace3a25586b16b154ff0810a381f508e4554b94f92e8e529"
|
||||
"repositoryPath": "de/neitzel/lib/neitzellib/1.0.6-SNAPSHOT/neitzellib-1.0.6-SNAPSHOT.pom",
|
||||
"sha256": "679b689ce3930c2e2a69c96d30357026f775141ec404e998533492b9fbda0202"
|
||||
},
|
||||
{
|
||||
"groupId": "de.neitzel.lib",
|
||||
"artifactId": "core",
|
||||
"version": "1.0-SNAPSHOT",
|
||||
"version": "1.0.6-SNAPSHOT",
|
||||
"extension": "pom",
|
||||
"repositoryPath": "de/neitzel/lib/core/1.0-SNAPSHOT/core-1.0-SNAPSHOT.pom",
|
||||
"sha256": "bed4167d3bc74f3bccb3f1328eb796b735bd60ec35aa881219edcce2a562fbd2"
|
||||
"repositoryPath": "de/neitzel/lib/core/1.0.6-SNAPSHOT/core-1.0.6-SNAPSHOT.pom",
|
||||
"sha256": "91f8ed8976c058c7fcfb02a9d4fb9066d856e698c2d4fd3763fbf87992bdf646"
|
||||
},
|
||||
{
|
||||
"groupId": "de.neitzel.lib",
|
||||
"artifactId": "core",
|
||||
"version": "1.0-SNAPSHOT",
|
||||
"version": "1.0.6-SNAPSHOT",
|
||||
"extension": "jar",
|
||||
"repositoryPath": "de/neitzel/lib/core/1.0-SNAPSHOT/core-1.0-SNAPSHOT.jar",
|
||||
"sha256": "a88374553bbb7c0dce9b1f5cc237601fa6d26db81b505f5e776ad13fa4db0db8"
|
||||
"repositoryPath": "de/neitzel/lib/core/1.0.6-SNAPSHOT/core-1.0.6-SNAPSHOT.jar",
|
||||
"sha256": "513c9ddbc3fe95ec2b6153e2e53f368b13ec4056beee2002f60fa0e1cc92bdb2"
|
||||
},
|
||||
{
|
||||
"groupId": "de.neitzel.lib",
|
||||
"artifactId": "injection",
|
||||
"version": "1.0-SNAPSHOT",
|
||||
"version": "1.0.6-SNAPSHOT",
|
||||
"extension": "pom",
|
||||
"repositoryPath": "de/neitzel/lib/injection/1.0-SNAPSHOT/injection-1.0-SNAPSHOT.pom",
|
||||
"sha256": "6060ccac3dd2eeb00342ab34028445649716e229e09bea9adbba56dda58d4780"
|
||||
"repositoryPath": "de/neitzel/lib/injection/1.0.6-SNAPSHOT/injection-1.0.6-SNAPSHOT.pom",
|
||||
"sha256": "25f02eb0f4c8fa7b60c2c106b0f8019f56b995c3891db34f875bc25d830fa36f"
|
||||
},
|
||||
{
|
||||
"groupId": "de.neitzel.lib",
|
||||
"artifactId": "injection",
|
||||
"version": "1.0-SNAPSHOT",
|
||||
"version": "1.0.6-SNAPSHOT",
|
||||
"extension": "jar",
|
||||
"repositoryPath": "de/neitzel/lib/injection/1.0-SNAPSHOT/injection-1.0-SNAPSHOT.jar",
|
||||
"sha256": "2d72111068cb8240b31e70c42c60687316dfbaf60d2fd965dcc833eeae17b084"
|
||||
"repositoryPath": "de/neitzel/lib/injection/1.0.6-SNAPSHOT/injection-1.0.6-SNAPSHOT.jar",
|
||||
"sha256": "c9b54bddc2eeff2cda7de51d8d55c20a16036a42a4cfd1cde864967c8e76b29a"
|
||||
},
|
||||
{
|
||||
"groupId": "de.neitzel.lib",
|
||||
"artifactId": "fx",
|
||||
"version": "1.0-SNAPSHOT",
|
||||
"artifactId": "data-grid",
|
||||
"version": "1.0.6-SNAPSHOT",
|
||||
"extension": "pom",
|
||||
"repositoryPath": "de/neitzel/lib/fx/1.0-SNAPSHOT/fx-1.0-SNAPSHOT.pom",
|
||||
"sha256": "4ccebda8f6cb8104aa272f3805263967530f8da259d2712b8ca0aa0c7d6fb356"
|
||||
"repositoryPath": "de/neitzel/lib/data-grid/1.0.6-SNAPSHOT/data-grid-1.0.6-SNAPSHOT.pom",
|
||||
"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",
|
||||
"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",
|
||||
"repositoryPath": "de/neitzel/lib/fx/1.0-SNAPSHOT/fx-1.0-SNAPSHOT.jar",
|
||||
"sha256": "803b19f76039c8777809618f420f43d2ff46a9fe051e96317fb053f8afb49ef0"
|
||||
"repositoryPath": "de/neitzel/lib/fx/1.0.6-SNAPSHOT/fx-1.0.6-SNAPSHOT.jar",
|
||||
"sha256": "6c1b95e963073ccca21bf2214ce33b9baf2fccae506b97e8215ef0130282b192"
|
||||
}
|
||||
],
|
||||
"generatedViewModelSupport": "stored-property-access-and-declarative-service-registry"
|
||||
"generatedViewModelSupport": "stored-property-access-and-declarative-service-registry",
|
||||
"buildOutputTimestamp": "2026-11-24T00:00:00Z"
|
||||
}
|
||||
|
||||
@@ -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 Archiver document example uses the one-way HTML and observable suggestion-source inputs. The host uses JavaFX 26. Source revision, build timestamp, test totals and the nine installed POM/JAR checksums are in the [active manifest](neitzellib-baseline.json).
|
||||
|
||||
## 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
|
||||
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
|
||||
# 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
|
||||
|
||||
@@ -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.
|
||||
- `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
|
||||
|
||||
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.
|
||||
|
||||
## 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`.
|
||||
|
||||
@@ -67,7 +67,7 @@ The user subsequently passed the physical corner retest for both Components in b
|
||||
|
||||
## Remaining boundaries
|
||||
|
||||
This stage preserves arbitrary source, but does not make arbitrary structure visually editable. Binding-aware renames and subtree copy/paste/delete are now available through the [Structure editor](reference-safe-structure.md). Arbitrary insertion/reparenting still requires Source editing. Application wildcard imports, `fx:include`, scripts and unrepresentable roots retain source fallback. Arbitrary target properties use declared FXML text editing until shared discovery supplies typed metadata. Anonymous identities are local to a projection revision, not the persistent occurrence identities needed for repeated/Table Components. Target node lookup still uses the initial CSS-ID route; separate CSS IDs and repeated/internal scopes need stage 3's occurrence identity work.
|
||||
This stage preserves arbitrary source, but does not make arbitrary structure visually editable. Binding-aware renames and subtree copy/paste/delete are now available through the [Structure editor](reference-safe-structure.md). Arbitrary insertion/reparenting still requires Source editing. Unresolved application wildcard imports, `fx:include`, scripts and unrepresentable roots retain source fallback. The four declarative docking types in `de.neitzel.fx.docking.*` are recognized by the projection and editable in the DataGrid / Docking inspector. Arbitrary target properties use declared FXML text editing until shared discovery supplies typed metadata. Anonymous identities are local to a projection revision, not the persistent occurrence identities needed for repeated/Table Components. Target node lookup still uses the initial CSS-ID route; separate CSS IDs and repeated/internal scopes need stage 3's occurrence identity work.
|
||||
|
||||
Qualification remains scoped to the recorded macOS arm64 / IntelliJ 263.7307.200 / JavaFX and Kit 26 host baseline and Java 21 / JavaFX 21.0.7 application fixtures. Product packaging, a broader platform matrix, lossless structural editing and wider input qualification are not implied. The stage-2 physical input gate is closed on the tested baseline. The following [target-runtime stage](target-runtime-sessions.md) implements retained sessions, sizing and navigation; its new actions have a separate human review.
|
||||
|
||||
|
||||
+32
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -15,6 +15,7 @@ public class PersonController implements de.neitzel.fx.view.HasViewModel {
|
||||
return "Uncertain";
|
||||
}
|
||||
|
||||
public static PersonController boundController;
|
||||
public final Greeting greeting;
|
||||
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) {
|
||||
received = vm;
|
||||
boundController = this;
|
||||
}
|
||||
|
||||
public void action() {
|
||||
|
||||
+8
@@ -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>
|
||||
+3
-1
@@ -1,8 +1,10 @@
|
||||
<?neitzel-model fixture.model.Person?>
|
||||
<?import de.neitzel.fx.control.NonNegativeIntegerSpinner?>
|
||||
<?import javafx.scene.layout.VBox?><?import javafx.scene.control.TextField?><?import javafx.scene.control.Button?><?import fixture.components.AddressForm?><?import de.neitzel.fx.view.BindingList?><?import de.neitzel.fx.view.DirectBinding?><?import de.neitzel.fx.view.Repeat?><?import de.neitzel.fx.view.Table?><?import de.neitzel.fx.view.Column?>
|
||||
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="fixture.components.PersonController" prefWidth="640" prefHeight="700">
|
||||
<fx:define><BindingList><DirectBinding control="rankInput" property="text" path="rank" direction="both" converter="fixture.components.RankConverter"/><DirectBinding control="home" property="model" path="home" direction="both"/><Repeat pane="visits" component="fixture.components.AddressForm" collection="visits"/></BindingList></fx:define>
|
||||
<fx:define><BindingList><DirectBinding control="rankSpinner" property="number" path="rank" direction="both"/><DirectBinding control="rankInput" property="text" path="rank" direction="both" converter="fixture.components.RankConverter"/><DirectBinding control="home" property="model" path="home" direction="both"/><Repeat pane="visits" component="fixture.components.AddressForm" collection="visits"/></BindingList></fx:define>
|
||||
<AddressForm fx:id="home" id="different-css-id"/>
|
||||
<VBox fx:id="visits"/>
|
||||
<Table fx:id="table" collection="visits" row="fixture.components.VisitRow" prefHeight="250"><Column header="Street" attribute="street"/></Table>
|
||||
<NonNegativeIntegerSpinner fx:id="rankSpinner" minimum="0" maximum="100" initialValue="1"/>
|
||||
<TextField fx:id="rankInput"/><Button fx:id="action" text="Run action" onAction="#action"/></VBox>
|
||||
|
||||
+3
-2
@@ -52,7 +52,8 @@ public final class PreviewChecks {
|
||||
if (mode.equals("unstable")
|
||||
|| mode.equals("full")
|
||||
|| mode.equals("full-empty")
|
||||
|| mode.equals("card")) {
|
||||
|| mode.equals("card")
|
||||
|| mode.equals("command-card")) {
|
||||
StageChecks.run(mode);
|
||||
return;
|
||||
}
|
||||
@@ -345,7 +346,7 @@ public final class PreviewChecks {
|
||||
() -> {
|
||||
var view = ready.loadedView();
|
||||
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.greeting == Examples.service, "Configured service not injected");
|
||||
var card = (Card) view.getRoot().lookup("#card");
|
||||
|
||||
+27
-4
@@ -20,17 +20,25 @@ public final class StageChecks {
|
||||
if (!started.await(10, TimeUnit.SECONDS)) throw new AssertionError("FX startup");
|
||||
var descriptor =
|
||||
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()
|
||||
.orElseThrow();
|
||||
if (mode.equals("unstable"))
|
||||
if (mode.equals("unstable") || mode.equals("command-card"))
|
||||
descriptor =
|
||||
new de.neitzel.fxdesigner.preview.ExampleDescriptor(
|
||||
descriptor.id(),
|
||||
descriptor.label(),
|
||||
descriptor.modelType(),
|
||||
descriptor.providerClass(),
|
||||
"fixture/components/Unstable.fxml",
|
||||
mode.equals("unstable")
|
||||
? "fixture/components/Unstable.fxml"
|
||||
: "fixture/components/CommandCard.fxml",
|
||||
descriptor.componentPackage());
|
||||
var preview =
|
||||
TargetPreview.open(descriptor, StageChecks.class.getClassLoader(), Duration.ofSeconds(15));
|
||||
@@ -55,7 +63,15 @@ public final class StageChecks {
|
||||
PreviewChecks.fx(
|
||||
() -> {
|
||||
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;
|
||||
PreviewChecks.check(
|
||||
card.street().getText().equals("Independent Card sample"),
|
||||
@@ -82,6 +98,13 @@ public final class StageChecks {
|
||||
Examples.person.getRank() == 7, "Conversion failure changed Model");
|
||||
rank.setText("42");
|
||||
PreviewChecks.check(Examples.person.getRank() == 42, "Conversion recovery");
|
||||
var spinner =
|
||||
(de.neitzel.fx.control.NonNegativeIntegerSpinner) root.lookup("#rankSpinner");
|
||||
PreviewChecks.check(spinner.getNumber() == 42, "Bound spinner received changed rank");
|
||||
spinner.increment();
|
||||
PreviewChecks.check(
|
||||
Examples.person.getRank() == 43 && rank.getText().contains("43"),
|
||||
"Spinner writes through the numeric binding");
|
||||
((Button) root.lookup("#action")).fire();
|
||||
PreviewChecks.check(
|
||||
Examples.person.getName().equals("Controller action"), "Controller action");
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
<!-- Dependency versions -->
|
||||
<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 -->
|
||||
<maven.compiler.plugin>3.16.0</maven.compiler.plugin>
|
||||
|
||||
+32
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -15,6 +15,7 @@ public class PersonController implements de.neitzel.fx.view.HasViewModel {
|
||||
return "Uncertain";
|
||||
}
|
||||
|
||||
public static PersonController boundController;
|
||||
public final Greeting greeting;
|
||||
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) {
|
||||
received = vm;
|
||||
boundController = this;
|
||||
}
|
||||
|
||||
public void action() {
|
||||
|
||||
+8
@@ -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>
|
||||
+3
-1
@@ -1,8 +1,10 @@
|
||||
<?neitzel-model fixture.model.Person?>
|
||||
<?import de.neitzel.fx.control.NonNegativeIntegerSpinner?>
|
||||
<?import javafx.scene.layout.VBox?><?import javafx.scene.control.TextField?><?import javafx.scene.control.Button?><?import fixture.components.AddressForm?><?import de.neitzel.fx.view.BindingList?><?import de.neitzel.fx.view.DirectBinding?><?import de.neitzel.fx.view.Repeat?><?import de.neitzel.fx.view.Table?><?import de.neitzel.fx.view.Column?>
|
||||
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="fixture.components.PersonController" prefWidth="640" prefHeight="700">
|
||||
<fx:define><BindingList><DirectBinding control="rankInput" property="text" path="rank" direction="both" converter="fixture.components.RankConverter"/><DirectBinding control="home" property="model" path="home" direction="both"/><Repeat pane="visits" component="fixture.components.AddressForm" collection="visits"/></BindingList></fx:define>
|
||||
<fx:define><BindingList><DirectBinding control="rankSpinner" property="number" path="rank" direction="both"/><DirectBinding control="rankInput" property="text" path="rank" direction="both" converter="fixture.components.RankConverter"/><DirectBinding control="home" property="model" path="home" direction="both"/><Repeat pane="visits" component="fixture.components.AddressForm" collection="visits"/></BindingList></fx:define>
|
||||
<AddressForm fx:id="home" id="different-css-id"/>
|
||||
<VBox fx:id="visits"/>
|
||||
<Table fx:id="table" collection="visits" row="fixture.components.VisitRow" prefHeight="250"><Column header="Street" attribute="street"/></Table>
|
||||
<NonNegativeIntegerSpinner fx:id="rankSpinner" minimum="0" maximum="100" initialValue="1"/>
|
||||
<TextField fx:id="rankInput"/><Button fx:id="action" text="Run action" onAction="#action"/></VBox>
|
||||
|
||||
+3
-2
@@ -52,7 +52,8 @@ public final class PreviewChecks {
|
||||
if (mode.equals("unstable")
|
||||
|| mode.equals("full")
|
||||
|| mode.equals("full-empty")
|
||||
|| mode.equals("card")) {
|
||||
|| mode.equals("card")
|
||||
|| mode.equals("command-card")) {
|
||||
StageChecks.run(mode);
|
||||
return;
|
||||
}
|
||||
@@ -345,7 +346,7 @@ public final class PreviewChecks {
|
||||
() -> {
|
||||
var view = ready.loadedView();
|
||||
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.greeting == Examples.service, "Configured service not injected");
|
||||
var card = (Card) view.getRoot().lookup("#card");
|
||||
|
||||
+27
-4
@@ -20,17 +20,25 @@ public final class StageChecks {
|
||||
if (!started.await(10, TimeUnit.SECONDS)) throw new AssertionError("FX startup");
|
||||
var descriptor =
|
||||
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()
|
||||
.orElseThrow();
|
||||
if (mode.equals("unstable"))
|
||||
if (mode.equals("unstable") || mode.equals("command-card"))
|
||||
descriptor =
|
||||
new de.neitzel.fxdesigner.preview.ExampleDescriptor(
|
||||
descriptor.id(),
|
||||
descriptor.label(),
|
||||
descriptor.modelType(),
|
||||
descriptor.providerClass(),
|
||||
"fixture/components/Unstable.fxml",
|
||||
mode.equals("unstable")
|
||||
? "fixture/components/Unstable.fxml"
|
||||
: "fixture/components/CommandCard.fxml",
|
||||
descriptor.componentPackage());
|
||||
var preview =
|
||||
TargetPreview.open(descriptor, StageChecks.class.getClassLoader(), Duration.ofSeconds(15));
|
||||
@@ -55,7 +63,15 @@ public final class StageChecks {
|
||||
PreviewChecks.fx(
|
||||
() -> {
|
||||
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;
|
||||
PreviewChecks.check(
|
||||
card.street().getText().equals("Independent Card sample"),
|
||||
@@ -82,6 +98,13 @@ public final class StageChecks {
|
||||
Examples.person.getRank() == 7, "Conversion failure changed Model");
|
||||
rank.setText("42");
|
||||
PreviewChecks.check(Examples.person.getRank() == 42, "Conversion recovery");
|
||||
var spinner =
|
||||
(de.neitzel.fx.control.NonNegativeIntegerSpinner) root.lookup("#rankSpinner");
|
||||
PreviewChecks.check(spinner.getNumber() == 42, "Bound spinner received changed rank");
|
||||
spinner.increment();
|
||||
PreviewChecks.check(
|
||||
Examples.person.getRank() == 43 && rank.getText().contains("43"),
|
||||
"Spinner writes through the numeric binding");
|
||||
((Button) root.lookup("#action")).fire();
|
||||
PreviewChecks.check(
|
||||
Examples.person.getName().equals("Controller action"), "Controller action");
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
<!-- Dependency versions -->
|
||||
<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 -->
|
||||
<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,409 @@
|
||||
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 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");
|
||||
pane = openDesigner(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;
|
||||
});
|
||||
pane = openDesigner(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));
|
||||
pane = openDesigner(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));
|
||||
click(pane, "Discover / Validate Commands");
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() ->
|
||||
((Label) pane.lookup("#command-status"))
|
||||
.getText()
|
||||
.contains("No detected binding errors.")));
|
||||
if (!fx(
|
||||
() ->
|
||||
pane.lookupAll(".combo-box").stream()
|
||||
.anyMatch(
|
||||
n ->
|
||||
n instanceof ComboBox<?> choices
|
||||
&& choices.getItems().size() == 22
|
||||
&& choices
|
||||
.getItems()
|
||||
.containsAll(java.util.List.of("open", "openReadOnly", "trash")))))
|
||||
throw new AssertionError("Incomplete Command getter suggestions");
|
||||
step("22 Command getters discovered; initial binding validation clean");
|
||||
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;
|
||||
});
|
||||
pane = openDesigner(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;
|
||||
});
|
||||
pane = openDesigner(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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package qualification;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.concurrent.*;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.stage.Window;
|
||||
|
||||
/** In the disposable target JVM, inspect the controls that the IDE actually launched. */
|
||||
public final class ConnectionTargetProbe {
|
||||
public static void premain(String directory) {
|
||||
if (!System.getProperty("sun.java.command", "")
|
||||
.startsWith("de.neitzel.fxdesigner.target.WorkerMain ")) return;
|
||||
Thread.ofPlatform().daemon().start(() -> Probe.observe(Path.of(directory)));
|
||||
}
|
||||
|
||||
private static final class Probe {
|
||||
private static void observe(Path directory) {
|
||||
try {
|
||||
while (true) {
|
||||
Thread.sleep(200);
|
||||
var result = new FutureTask<>(() -> inspect(directory));
|
||||
try {
|
||||
Platform.runLater(result);
|
||||
} catch (IllegalStateException starting) {
|
||||
continue;
|
||||
}
|
||||
if (result.get(10, TimeUnit.SECONDS)) return;
|
||||
}
|
||||
} catch (Throwable ex) {
|
||||
try {
|
||||
Files.writeString(directory.resolve("target-error.txt"), ex + " " + ex.getCause());
|
||||
} catch (Exception writeError) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean changed;
|
||||
|
||||
private static boolean inspect(Path directory) throws Exception {
|
||||
var window =
|
||||
Window.getWindows().stream()
|
||||
.filter(Window::isShowing)
|
||||
.filter(w -> w.getScene().lookup("#protocol") instanceof ComboBox)
|
||||
.findFirst();
|
||||
if (window.isEmpty()) return false;
|
||||
var root = window.get().getScene().getRoot();
|
||||
var user = (TextField) root.lookup("#user");
|
||||
var mirror = (Label) root.lookup("#label");
|
||||
var auto = (TextField) root.lookup("#autoCompleteTextField");
|
||||
if (changed) {
|
||||
if (!Files.exists(directory.resolve("unrelated-saved"))) return false;
|
||||
if (!"changed@example.org".equals(user.getText())
|
||||
|| !user.getText().equals(mirror.getText()))
|
||||
throw new AssertionError("Unrelated save reset interactive state");
|
||||
Files.writeString(directory.resolve("retained-imap"), "" + ProcessHandle.current().pid());
|
||||
return true;
|
||||
}
|
||||
var protocol = ((ComboBox<?>) root.lookup("#protocol")).getValue().toString();
|
||||
boolean imap = protocol.equals("IMAP");
|
||||
String id = imap ? "imap" : "jmap";
|
||||
if (!Files.readString(directory.resolve("attempt")).equals(id))
|
||||
throw new AssertionError("Wrong example " + id);
|
||||
if (!root.lookupAll(".label").stream()
|
||||
.anyMatch(n -> n instanceof Label l && l.getText().equals("Protokoll")))
|
||||
throw new AssertionError("Missing localized protocol label");
|
||||
if (!((Label) root.lookup("#label2")).getText().equals("Kontoprüfung")
|
||||
|| !((TextField) root.lookup("#endpoint"))
|
||||
.getText()
|
||||
.equals(imap ? "imap.example.org" : "https://mail.example.org/.well-known/jmap")
|
||||
|| !user.getText().equals(imap ? "anna@example.org" : "ben@example.org")
|
||||
|| !user.getText().equals(mirror.getText())
|
||||
|| !user.getText().equals(auto.getText())
|
||||
|| root.lookup("#port").isDisabled() == imap
|
||||
|| root.lookup("#account").isDisabled() != imap
|
||||
|| !((Spinner<?>) root.lookup("#nonNegativeIntegerSpinner")).getValue().equals(14))
|
||||
throw new AssertionError("Unexpected rendered data or field enablement in " + protocol);
|
||||
user.setText("changed@example.org");
|
||||
if (!user.getText().equals(mirror.getText()) || !user.getText().equals(auto.getText()))
|
||||
throw new AssertionError("Missing model write-back");
|
||||
changed = true;
|
||||
Files.writeString(
|
||||
directory.resolve("result-" + id),
|
||||
protocol + " · Protokoll · " + ProcessHandle.current().pid());
|
||||
return !imap;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package qualification;
|
||||
|
||||
import static qualification.WorkflowProbe.*;
|
||||
|
||||
import com.intellij.openapi.command.WriteCommandAction;
|
||||
import com.intellij.openapi.fileEditor.*;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.vfs.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import javafx.embed.swing.SwingFXUtils;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.*;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
/** Drives the registered editor against a disposable copy of the real Archiver connection form. */
|
||||
public final class ConnectionWorkflowProbe extends FormWorkflowProbe {
|
||||
private void add(String type, String destination, String id) throws Exception {
|
||||
step("Inserting " + type + " as " + id);
|
||||
choose("form-palette", type);
|
||||
choose("form-destination", destination);
|
||||
String before = source();
|
||||
fx(
|
||||
() -> {
|
||||
var b =
|
||||
(Button)
|
||||
pane.lookupAll(".button").stream()
|
||||
.filter(n -> n instanceof Button bt && bt.getText().equals("Insert control"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
if (b.isDisabled())
|
||||
throw new AssertionError("Insert control disabled for " + destination);
|
||||
step(
|
||||
"Selected insert "
|
||||
+ ((ComboBox<?>) pane.lookup("#form-palette")).getValue()
|
||||
+ " / "
|
||||
+ ((ComboBox<?>) pane.lookup("#form-destination")).getValue()
|
||||
+ " at "
|
||||
+ ((Spinner<?>) pane.lookup("#form-position")).getValue());
|
||||
return null;
|
||||
});
|
||||
click(pane, "Insert control");
|
||||
edited(before, "fx:id=\"" + id + "\"");
|
||||
step("Inserted " + type + " into " + destination);
|
||||
}
|
||||
|
||||
private void bind(String name, String path) throws Exception {
|
||||
choose("form-property", name);
|
||||
click(pane, "Bind property");
|
||||
fx(
|
||||
() -> {
|
||||
pane.applyCss();
|
||||
pane.layout();
|
||||
return null;
|
||||
});
|
||||
fx(
|
||||
() -> {
|
||||
((TextField) pane.lookup("#direct-path")).setText(path);
|
||||
return null;
|
||||
});
|
||||
String before = source();
|
||||
click(pane, "Apply binding");
|
||||
edited(before, "path=\"" + path + "\"");
|
||||
controls(true);
|
||||
}
|
||||
|
||||
private void example(String id) throws Exception {
|
||||
choose("preview-example", "connection-" + id);
|
||||
}
|
||||
|
||||
private void frame(String id, int width) throws Exception {
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() -> {
|
||||
var image = (ImageView) pane.lookup("#full-preview-image");
|
||||
var status = ((Label) pane.lookup("#preview-state")).getText();
|
||||
return image.getImage() != null
|
||||
&& image.getImage().getWidth() == width
|
||||
&& image.getImage().getHeight() == 720
|
||||
&& status.contains(id.toUpperCase(Locale.ROOT));
|
||||
}));
|
||||
fx(
|
||||
() -> {
|
||||
ImageIO.write(
|
||||
SwingFXUtils.fromFXImage(
|
||||
((ImageView) pane.lookup("#full-preview-image")).getImage(), null),
|
||||
"png",
|
||||
output.resolve(id + ".png").toFile());
|
||||
return null;
|
||||
});
|
||||
step("In-editor " + id + " target frame " + width + " × 720");
|
||||
}
|
||||
|
||||
@Override
|
||||
void verify(Project project) throws Exception {
|
||||
var path =
|
||||
Path.of(
|
||||
project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui/ConnectionForm.fxml");
|
||||
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
|
||||
pane = openDesigner(project, file);
|
||||
step("Opened registered Neitzel Designer");
|
||||
fx(
|
||||
() -> {
|
||||
for (var n : pane.lookupAll(".label"))
|
||||
if (n instanceof Label label
|
||||
&& (label.getText() != null && label.getText().startsWith("Context ")
|
||||
|| "form-message".equals(label.getId()))) {
|
||||
label
|
||||
.textProperty()
|
||||
.addListener(
|
||||
(o, a, b) -> {
|
||||
try {
|
||||
step("Editor: " + b);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
return null;
|
||||
});
|
||||
controls(true);
|
||||
String grid = "GridPane [0] / children";
|
||||
add("StatusBar", grid, "statusBar");
|
||||
add("Label", "StatusBar #statusBar / leftItems", "label");
|
||||
bind("text", "user");
|
||||
add("Label", "StatusBar #statusBar / rightItems", "label2");
|
||||
set("text", "Kontostatus", "Kontostatus");
|
||||
choose("form-destination", "StatusBar #statusBar / leftItems");
|
||||
String before = source();
|
||||
click(pane, "Move to destination");
|
||||
edited(before, "Kontostatus");
|
||||
String moved = source();
|
||||
click(pane, "Undo");
|
||||
await(() -> source().equals(before));
|
||||
click(pane, "Redo");
|
||||
await(() -> source().equals(moved));
|
||||
add("TextField", grid, "textField");
|
||||
fx(
|
||||
() -> {
|
||||
var index =
|
||||
new com.oracle.javafx.scenebuilder.kit.fxom.FXOMFxIdIndex(
|
||||
pane.kit().editor().getFxomDocument());
|
||||
pane.kit().editor().getSelection().select(index.lookup("endpoint"));
|
||||
pane.kit().editor().getSelection().select(index.lookup("textField"));
|
||||
if (!((ComboBox<?>) pane.lookup("#form-control"))
|
||||
.getValue()
|
||||
.toString()
|
||||
.equals("TextField #textField"))
|
||||
throw new AssertionError("Canvas selection did not reach the form inspector");
|
||||
return null;
|
||||
});
|
||||
set("promptText", "Verbindung prüfen", "Verbindung prüfen");
|
||||
set("styleClass", "connection-input", "connection-input");
|
||||
set("padding", "2 3 4 5", "right=\"3.0\"");
|
||||
set("GridPane.columnIndex", "1", "GridPane.columnIndex=\"1\"");
|
||||
add("NonNegativeIntegerSpinner", grid, "nonNegativeIntegerSpinner");
|
||||
set("maximum", "365", "maximum=\"365\"");
|
||||
set("initialValue", "14", "initialValue=\"14\"");
|
||||
set("minimum", "1", "minimum=\"1\"");
|
||||
add("TagChip", grid, "tagChip");
|
||||
set("removable", "true", "removable=\"true\"");
|
||||
set("onRemove", "#removeTag", "onRemove=\"#removeTag\"");
|
||||
click(pane, "Reset property");
|
||||
await(() -> !source().contains("onRemove="));
|
||||
add("ToolBarPane", grid, "toolBarPane");
|
||||
set("dismissible", "true", "dismissible=\"true\"");
|
||||
set("dismissText", "Schließen", "dismissText=\"Schließen\"");
|
||||
set("onDismiss", "#dismiss", "onDismiss=\"#dismiss\"");
|
||||
click(pane, "Reset property");
|
||||
await(() -> !source().contains("onDismiss="));
|
||||
add("ToolBar", grid, "toolBar");
|
||||
add("Button", "ToolBarPane #toolBarPane / items", "button");
|
||||
choose("form-destination", "ToolBar #toolBar / items");
|
||||
String toolbar = source();
|
||||
click(pane, "Move to destination");
|
||||
edited(toolbar, "fx:id=\"button\"");
|
||||
add("AutoCompleteTextField", grid, "autoCompleteTextField");
|
||||
set("suggestions", "INBOX\nRechnungen", "fx:value=\"Rechnungen\"");
|
||||
bind("text", "user");
|
||||
String edited = source();
|
||||
click(pane, "Save");
|
||||
await(() -> Files.readString(path).equals(edited));
|
||||
if (!edited.contains("%server.protocol"))
|
||||
throw new AssertionError("Resource key was overwritten");
|
||||
edt(
|
||||
() -> {
|
||||
FileEditorManager.getInstance(project).closeFile(file);
|
||||
return null;
|
||||
});
|
||||
pane = openDesigner(project, file);
|
||||
if (!source().equals(edited)) throw new AssertionError("Reopen changed source");
|
||||
step("Native undo, redo, save and reopen preserved form, lists and bindings");
|
||||
click(pane, "Form preview");
|
||||
click(pane, "Build and Refresh");
|
||||
await(() -> fx(() -> ((ComboBox<?>) pane.lookup("#preview-example")).getItems().size() == 2));
|
||||
step("Built and discovered both connection examples");
|
||||
example("imap");
|
||||
fx(
|
||||
() -> {
|
||||
((Spinner<?>) pane.lookup("#preview-height")).increment(5);
|
||||
return null;
|
||||
});
|
||||
frame("imap", 760);
|
||||
byte[] initialImage = Files.readAllBytes(output.resolve("imap.png"));
|
||||
controls(true);
|
||||
choose("form-control", "Label #label2");
|
||||
set("text", "Kontoprüfung", "Kontoprüfung");
|
||||
controls(false);
|
||||
frame("imap", 760);
|
||||
if (java.util.Arrays.equals(initialImage, Files.readAllBytes(output.resolve("imap.png"))))
|
||||
throw new AssertionError("Visual label edit produced the previous frame");
|
||||
step("Current draft rendered a changed status label without a Save action");
|
||||
Files.writeString(output.resolve("attempt"), "imap");
|
||||
click(pane, "Interactive preview");
|
||||
awaitTarget("result-imap");
|
||||
var otherPath = path.resolveSibling("ArchiveWindow.fxml");
|
||||
var other = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(otherPath));
|
||||
edt(
|
||||
() -> {
|
||||
FileEditorManager.getInstance(project).openFile(other, false);
|
||||
var doc = FileDocumentManager.getInstance().getDocument(other);
|
||||
WriteCommandAction.runWriteCommandAction(
|
||||
project, () -> doc.insertString(doc.getTextLength(), "\n"));
|
||||
FileDocumentManager.getInstance().saveDocument(doc);
|
||||
return null;
|
||||
});
|
||||
Files.writeString(output.resolve("unrelated-saved"), "yes");
|
||||
awaitTarget("retained-imap");
|
||||
long originalPid = Long.parseLong(Files.readString(output.resolve("retained-imap")));
|
||||
if (!ProcessHandle.of(originalPid).map(ProcessHandle::isAlive).orElse(false))
|
||||
throw new AssertionError("Saving a different view stopped the IMAP worker");
|
||||
step("Interactive IMAP input reached bound Label and survived unrelated save");
|
||||
Files.writeString(output.resolve("attempt"), "jmap");
|
||||
example("jmap");
|
||||
fx(
|
||||
() -> {
|
||||
((Spinner<?>) pane.lookup("#preview-width")).increment();
|
||||
return null;
|
||||
});
|
||||
frame("jmap", 800);
|
||||
awaitTarget("result-jmap");
|
||||
step("Interactive JMAP started with fresh sample data and reversed account/port enablement");
|
||||
fx(
|
||||
() -> {
|
||||
ImageIO.write(
|
||||
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
|
||||
"png",
|
||||
output.resolve("intellij.png").toFile());
|
||||
return null;
|
||||
});
|
||||
click(pane, "Stop preview");
|
||||
Files.writeString(
|
||||
output.resolve("SUCCESS.txt"),
|
||||
"PASS registered IntelliJ connection form, palette and inspector edits, named lists,"
|
||||
+ " bindings, native undo/redo/reopen, localized IMAP/JMAP frames and interactive"
|
||||
+ " write-back\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package qualification;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.PixelFormat;
|
||||
import javafx.stage.*;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
/**
|
||||
* Checks the selected product tab, WebKit DOM and actual popup, including a return to the first
|
||||
* tab.
|
||||
*/
|
||||
public final class DocumentTabsTargetProbe {
|
||||
public static void premain(String dir) {
|
||||
if (System.getProperty("sun.java.command", "")
|
||||
.startsWith("de.neitzel.fxdesigner.target.WorkerMain "))
|
||||
Thread.ofPlatform().daemon().start(() -> Probe.run(Path.of(dir)));
|
||||
}
|
||||
|
||||
private static final class Probe {
|
||||
private static <T> T fx(Callable<T> task) throws Exception {
|
||||
var future = new FutureTask<>(task);
|
||||
Platform.runLater(future);
|
||||
return future.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static void await(String description, Callable<Boolean> check) throws Exception {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(45);
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (fx(check)) return;
|
||||
Thread.sleep(100);
|
||||
}
|
||||
throw new AssertionError(description);
|
||||
}
|
||||
|
||||
private static void run(Path dir) {
|
||||
try {
|
||||
Stage stage = null;
|
||||
while (stage == null) {
|
||||
Thread.sleep(120);
|
||||
try {
|
||||
stage =
|
||||
fx(
|
||||
() ->
|
||||
Window.getWindows().stream()
|
||||
.filter(Stage.class::isInstance)
|
||||
.map(Stage.class::cast)
|
||||
.filter(
|
||||
s ->
|
||||
s.getOpacity() > 0
|
||||
&& s.getTitle() != null
|
||||
&& s.getTitle().startsWith("Neitzel preview"))
|
||||
.findFirst()
|
||||
.orElse(null));
|
||||
} catch (IllegalStateException starting) {
|
||||
/* Waiting for FX startup. */
|
||||
}
|
||||
}
|
||||
final Stage window = stage;
|
||||
TabPane group =
|
||||
fx(
|
||||
() ->
|
||||
window.getScene().getRoot().lookupAll(".tab-pane").stream()
|
||||
.map(TabPane.class::cast)
|
||||
.filter(
|
||||
p ->
|
||||
p.getTabs().stream()
|
||||
.anyMatch(t -> "Rechnung.html".equals(t.getText())))
|
||||
.findFirst()
|
||||
.orElseThrow());
|
||||
check(
|
||||
dir,
|
||||
group,
|
||||
"Rechnung.html",
|
||||
"Rechnung RE-042",
|
||||
"Büromaterial · 48,00 €",
|
||||
"Beleg offen",
|
||||
"Beleg geprüft",
|
||||
"rechnung-tab");
|
||||
check(
|
||||
dir,
|
||||
group,
|
||||
"Lieferschein.html",
|
||||
"Lieferschein LS-018",
|
||||
"Wareneingang · 3 Archivkartons",
|
||||
"Beleg geprüft",
|
||||
"Beleg offen",
|
||||
"lieferschein-tab");
|
||||
check(
|
||||
dir,
|
||||
group,
|
||||
"Rechnung.html",
|
||||
"Rechnung RE-042",
|
||||
"Büromaterial · 48,00 €",
|
||||
"Beleg offen",
|
||||
"Beleg geprüft",
|
||||
"rechnung-tab");
|
||||
Files.writeString(
|
||||
dir.resolve("document-tabs-result"),
|
||||
"PASS Rechnung → Lieferschein → Rechnung: HTML content, assigned tag and filtered"
|
||||
+ " suggestion in each production tab.\n");
|
||||
} catch (Throwable error) {
|
||||
var trace = new java.io.StringWriter();
|
||||
error.printStackTrace(new java.io.PrintWriter(trace));
|
||||
try {
|
||||
Files.writeString(dir.resolve("target-error.txt"), trace.toString());
|
||||
} catch (Exception ignored) {
|
||||
error.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void check(
|
||||
Path dir,
|
||||
TabPane group,
|
||||
String name,
|
||||
String heading,
|
||||
String body,
|
||||
String assigned,
|
||||
String suggestion,
|
||||
String image)
|
||||
throws Exception {
|
||||
var tab =
|
||||
fx(
|
||||
() -> {
|
||||
var target =
|
||||
group.getTabs().stream()
|
||||
.filter(t -> name.equals(t.getText()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
group.getSelectionModel().select(target);
|
||||
return target;
|
||||
});
|
||||
await(
|
||||
"HTML in " + name,
|
||||
() -> {
|
||||
var content = tab.getContent();
|
||||
var viewer = content.lookup("#html-document");
|
||||
if (viewer == null
|
||||
|| group.getSelectionModel().getSelectedItem() != tab
|
||||
|| !content.isVisible()) return false;
|
||||
var browser = viewer.lookup("WebView");
|
||||
Object engine = browser.getClass().getMethod("getEngine").invoke(browser);
|
||||
var doc = (Document) engine.getClass().getMethod("getDocument").invoke(engine);
|
||||
return doc != null
|
||||
&& doc.getElementsByTagName("h1").getLength() == 1
|
||||
&& heading.equals(doc.getElementsByTagName("h1").item(0).getTextContent())
|
||||
&& doc.getDocumentElement().getTextContent().contains(body);
|
||||
});
|
||||
var field = fx(() -> (TextField) tab.getContent().lookup("#tag-input"));
|
||||
await(
|
||||
"Focus in " + name,
|
||||
() -> {
|
||||
var stage = (Stage) group.getScene().getWindow();
|
||||
if (!field.isFocused()) {
|
||||
stage.toFront();
|
||||
stage.requestFocus();
|
||||
field.requestFocus();
|
||||
}
|
||||
return field.isFocused();
|
||||
});
|
||||
fx(
|
||||
() -> {
|
||||
var chips = tab.getContent().lookupAll(".tag-chip");
|
||||
if (chips.size() != 1) throw new AssertionError("Expected one assigned tag in " + name);
|
||||
var chip = chips.iterator().next();
|
||||
if (!assigned.equals(chip.getClass().getMethod("getText").invoke(chip)))
|
||||
throw new AssertionError("Wrong assigned tag in " + name);
|
||||
field.setText("");
|
||||
field.setText("Be");
|
||||
return null;
|
||||
});
|
||||
await(
|
||||
"Popup with " + suggestion,
|
||||
() -> {
|
||||
for (var window : Window.getWindows()) {
|
||||
if (window instanceof Popup popup
|
||||
&& popup.isShowing()
|
||||
&& popup.getOwnerNode() == field
|
||||
&& popup.getScene().lookup(".list-view") instanceof ListView<?> list
|
||||
&& list.getItems().equals(List.of(suggestion))) {
|
||||
save(list, dir.resolve(image + "-tags.png"));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
fx(
|
||||
() -> {
|
||||
save(tab.getContent(), dir.resolve(image + ".png"));
|
||||
field.setText("");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private static void save(Node node, Path file) throws Exception {
|
||||
var image = node.snapshot(null, null);
|
||||
int width = (int) image.getWidth(), height = (int) image.getHeight();
|
||||
var pixels = new int[width * height];
|
||||
image
|
||||
.getPixelReader()
|
||||
.getPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
|
||||
var png =
|
||||
new java.awt.image.BufferedImage(
|
||||
width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB);
|
||||
png.setRGB(0, 0, width, height, pixels, 0, width);
|
||||
ImageIO.write(png, "png", file.toFile());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package qualification;
|
||||
|
||||
import static qualification.WorkflowProbe.*;
|
||||
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.vfs.LocalFileSystem;
|
||||
import java.nio.file.*;
|
||||
import javafx.embed.swing.SwingFXUtils;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.ImageView;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
/**
|
||||
* Opens the production ArchiveWindow in the registered editor and selects its real document tabs.
|
||||
*/
|
||||
public final class DocumentTabsWorkflowProbe extends FormWorkflowProbe {
|
||||
@Override
|
||||
void verify(Project project) throws Exception {
|
||||
var path =
|
||||
Path.of(
|
||||
project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui/ArchiveWindow.fxml");
|
||||
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
|
||||
pane = openDesigner(project, file);
|
||||
click(pane, "Form preview");
|
||||
click(pane, "Build and Refresh");
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() ->
|
||||
((ComboBox<?>) pane.lookup("#preview-example"))
|
||||
.getItems().stream()
|
||||
.anyMatch(
|
||||
item -> item.toString().contains("archive-window-documents"))));
|
||||
choose("preview-example", "archive-window-documents");
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() -> {
|
||||
var status = ((Label) pane.lookup("#preview-state")).getText();
|
||||
if (status.startsWith("Preview failed") || status.startsWith("Preview blocked"))
|
||||
throw new AssertionError(status);
|
||||
return ((ImageView) pane.lookup("#full-preview-image")).getImage() != null
|
||||
&& status.contains("HTML-Dokumenttabs");
|
||||
}));
|
||||
step("Production ArchiveWindow rendered the document tabs");
|
||||
fx(
|
||||
() -> {
|
||||
ImageIO.write(
|
||||
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
|
||||
"png",
|
||||
output.resolve("intellij.png").toFile());
|
||||
return null;
|
||||
});
|
||||
click(pane, "Interactive preview");
|
||||
awaitTarget("document-tabs-result");
|
||||
click(pane, "Stop preview");
|
||||
Files.writeString(
|
||||
output.resolve("SUCCESS.txt"), Files.readString(output.resolve("document-tabs-result")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
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.*;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.*;
|
||||
|
||||
/** Shared actions on the real form inspector in the registered editor. */
|
||||
abstract class FormWorkflowProbe implements StartupActivity.DumbAware {
|
||||
DesignerPane pane;
|
||||
VirtualFile file;
|
||||
|
||||
public void runActivity(Project project) {
|
||||
if (!started.compareAndSet(false, true)) return;
|
||||
ApplicationManager.getApplication()
|
||||
.executeOnPooledThread(
|
||||
() -> {
|
||||
try {
|
||||
verify(project);
|
||||
} catch (Throwable ex) {
|
||||
try {
|
||||
var trace = new java.io.StringWriter();
|
||||
ex.printStackTrace(new java.io.PrintWriter(trace));
|
||||
if (pane != null)
|
||||
trace.append(
|
||||
fx(
|
||||
() ->
|
||||
pane.lookupAll(".label").stream()
|
||||
.filter(Label.class::isInstance)
|
||||
.map(n -> Objects.toString(((Label) n).getText(), ""))
|
||||
.filter(s -> !s.isEmpty())
|
||||
.toList()
|
||||
.toString()));
|
||||
Files.writeString(output.resolve("FAILURE.txt"), trace.toString());
|
||||
} catch (Exception failure) {
|
||||
failure.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void step(String message) throws Exception {
|
||||
Files.writeString(
|
||||
output.resolve("steps.txt"),
|
||||
message + "\n",
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.APPEND);
|
||||
}
|
||||
|
||||
String source() throws Exception {
|
||||
return edt(() -> FileDocumentManager.getInstance().getDocument(file).getText());
|
||||
}
|
||||
|
||||
void controls(boolean expanded) throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
var panel =
|
||||
(TitledPane)
|
||||
pane.lookupAll(".titled-pane").stream()
|
||||
.filter(n -> n instanceof TitledPane t && t.getText().equals("Form controls"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
panel.setAnimated(false);
|
||||
panel.setExpanded(expanded);
|
||||
pane.applyCss();
|
||||
pane.layout();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
void choose(String selector, String text) throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
var combo = (ComboBox<?>) pane.lookup("#" + selector);
|
||||
for (int i = 0; i < combo.getItems().size(); i++) {
|
||||
if (combo.getItems().get(i).toString().equals(text)) {
|
||||
combo.getSelectionModel().select(i);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < combo.getItems().size(); i++) {
|
||||
String label = combo.getItems().get(i).toString();
|
||||
if (label.equals(text) || label.contains(text)) {
|
||||
combo.getSelectionModel().select(i);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
throw new AssertionError(selector + " missing " + text + " in " + combo.getItems());
|
||||
});
|
||||
}
|
||||
|
||||
void edited(String before, String expected) throws Exception {
|
||||
await(
|
||||
() -> {
|
||||
String now = source();
|
||||
String error =
|
||||
fx(
|
||||
() -> {
|
||||
var label = (Label) pane.lookup("#form-message");
|
||||
return label == null ? "" : label.getText();
|
||||
});
|
||||
if (!error.isEmpty()) throw new AssertionError(error);
|
||||
return !before.equals(now)
|
||||
&& now.contains(expected)
|
||||
&& fx(
|
||||
() ->
|
||||
((TextArea) pane.lookup("#fxml-source")) == null
|
||||
|| ((TextArea) pane.lookup("#fxml-source")).getText().equals(now));
|
||||
});
|
||||
// Both the native document and visual selection are refreshed asynchronously.
|
||||
fx(pane::flush).toCompletableFuture().get(10, java.util.concurrent.TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
void set(String name, String value, String expected) throws Exception {
|
||||
choose("form-property", name);
|
||||
fx(
|
||||
() -> {
|
||||
((TextArea) pane.lookup("#form-value")).setText(value);
|
||||
return null;
|
||||
});
|
||||
String before = source();
|
||||
click(pane, "Set property");
|
||||
edited(before, expected);
|
||||
}
|
||||
|
||||
void awaitTarget(String name) throws Exception {
|
||||
await(
|
||||
() -> {
|
||||
var error = output.resolve("target-error.txt");
|
||||
if (Files.exists(error)) throw new AssertionError(Files.readString(error));
|
||||
return Files.exists(output.resolve(name));
|
||||
});
|
||||
}
|
||||
|
||||
abstract void verify(Project project) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package qualification;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import javafx.application.Platform;
|
||||
import javafx.beans.value.ObservableValue;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.stage.Window;
|
||||
|
||||
/**
|
||||
* Measures the real Archiver controls in the interactive worker launched by the registered editor.
|
||||
*/
|
||||
public final class GridDockTargetProbe {
|
||||
public static void premain(String dir) {
|
||||
if (!System.getProperty("sun.java.command", "")
|
||||
.startsWith("de.neitzel.fxdesigner.target.WorkerMain ")) return;
|
||||
Thread.ofPlatform().daemon().start(() -> Probe.observe(Path.of(dir)));
|
||||
}
|
||||
|
||||
private static final class Probe {
|
||||
private static void observe(Path dir) {
|
||||
try {
|
||||
while (true) {
|
||||
Thread.sleep(200);
|
||||
var check = new FutureTask<>(() -> inspect(dir));
|
||||
try {
|
||||
Platform.runLater(check);
|
||||
} catch (IllegalStateException starting) {
|
||||
continue;
|
||||
}
|
||||
if (check.get(10, TimeUnit.SECONDS)) return;
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
try {
|
||||
Files.writeString(dir.resolve("target-error.txt"), e + " " + e.getCause());
|
||||
} catch (Exception ignored) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean inspect(Path dir) throws Exception {
|
||||
var windows = Window.getWindows().stream().filter(Window::isShowing).toList();
|
||||
if (windows.isEmpty() || !Files.exists(dir.resolve("attempt"))) return false;
|
||||
var root = windows.getFirst().getScene().getRoot();
|
||||
String attempt = Files.readString(dir.resolve("attempt"));
|
||||
if (attempt.equals("folder")) {
|
||||
var grid = root.lookup("#grid");
|
||||
if (grid == null) return false;
|
||||
var grouping = (ChoiceBox<?>) root.lookup("#grouping");
|
||||
if (!"Nach Ordner".equals(String.valueOf(grouping.getValue())))
|
||||
throw new AssertionError("Wrong grouping choice: " + grouping.getValue());
|
||||
var type = grid.getClass();
|
||||
var cols = (List<?>) type.getMethod("getColumns").invoke(grid);
|
||||
var first = cols.getFirst();
|
||||
if (!"Archivdatei".equals(first.getClass().getMethod("getHeader").invoke(first)))
|
||||
throw new AssertionError("Unexpected first column");
|
||||
var texts =
|
||||
root.lookupAll("*").stream()
|
||||
.filter(Labeled.class::isInstance)
|
||||
.map(n -> ((Labeled) n).getText())
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
for (String expected : List.of("Archivdatei", "Musterrechnung.pdf", "Lieferbrief.txt"))
|
||||
if (!texts.contains(expected))
|
||||
throw new AssertionError("Missing " + expected + " in " + texts);
|
||||
type.getMethod("select", Object.class).invoke(grid, "Musterrechnung.pdf");
|
||||
Object key =
|
||||
((ObservableValue<?>) type.getMethod("selectedKeyProperty").invoke(grid)).getValue();
|
||||
Object row =
|
||||
((ObservableValue<?>) type.getMethod("selectedElementProperty").invoke(grid))
|
||||
.getValue();
|
||||
if (!"Musterrechnung.pdf".equals(key)
|
||||
|| !key.equals(row.getClass().getMethod("path").invoke(row)))
|
||||
throw new AssertionError("Unstable selection " + key);
|
||||
Files.writeString(
|
||||
dir.resolve("result-folder"),
|
||||
"Archivdatei · Musterrechnung.pdf · Lieferbrief.txt · selectedKey=" + key);
|
||||
} else {
|
||||
Node doc = null, details = null;
|
||||
for (var n : root.lookupAll(".label"))
|
||||
if (n instanceof Label label) {
|
||||
if ("Dokument im Beispielarchiv".equals(label.getText())) doc = n;
|
||||
if ("Belegnummer RE-2026-042".equals(label.getText())) details = n;
|
||||
}
|
||||
if (doc == null || details == null)
|
||||
throw new AssertionError("Missing visible example content");
|
||||
if (attempt.equals("bottom")) {
|
||||
var pane = root.lookup("#dockPane");
|
||||
var layout = pane.getClass().getMethod("getInitialLayout").invoke(pane);
|
||||
var center = layout.getClass().getMethod("getCenter").invoke(layout);
|
||||
var bottom = layout.getClass().getMethod("getBottom").invoke(layout);
|
||||
if (!"VERTICAL"
|
||||
.equals(center.getClass().getMethod("getOrientation").invoke(center).toString())
|
||||
|| !"beleg".equals(bottom.getClass().getMethod("getDestinationId").invoke(bottom)))
|
||||
throw new AssertionError("Target did not load the edited split and destination");
|
||||
}
|
||||
var a = doc.localToScene(doc.getBoundsInLocal());
|
||||
var b = details.localToScene(details.getBoundsInLocal());
|
||||
if (attempt.equals("right") ? b.getMinX() <= a.getMaxX() : b.getMinY() <= a.getMaxY())
|
||||
throw new AssertionError("Wrong " + attempt + " arrangement: " + a + " / " + b);
|
||||
Files.writeString(
|
||||
dir.resolve("result-" + attempt),
|
||||
"Dokument ("
|
||||
+ (int) a.getMinX()
|
||||
+ ","
|
||||
+ (int) a.getMinY()
|
||||
+ "), Belegnummer ("
|
||||
+ (int) b.getMinX()
|
||||
+ ","
|
||||
+ (int) b.getMinY()
|
||||
+ ")");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
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.*;
|
||||
import javafx.embed.swing.SwingFXUtils;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.*;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/** Drives the inspector, native document and target preview in a disposable Archiver checkout. */
|
||||
public final class GridDockWorkflowProbe implements StartupActivity.DumbAware {
|
||||
private DesignerPane pane;
|
||||
private VirtualFile file;
|
||||
private Project project;
|
||||
|
||||
public void runActivity(Project project) {
|
||||
if (!started.compareAndSet(false, true)) return;
|
||||
this.project = project;
|
||||
ApplicationManager.getApplication()
|
||||
.executeOnPooledThread(
|
||||
() -> {
|
||||
try {
|
||||
verify();
|
||||
} catch (Throwable ex) {
|
||||
try {
|
||||
var trace = new java.io.StringWriter();
|
||||
ex.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())
|
||||
.filter(Objects::nonNull)
|
||||
.toList()
|
||||
.toString()));
|
||||
Files.writeString(output.resolve("FAILURE.txt"), trace.toString());
|
||||
} catch (Exception e) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void step(String text) throws Exception {
|
||||
Files.writeString(
|
||||
output.resolve("steps.txt"),
|
||||
text + "\n",
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.APPEND);
|
||||
}
|
||||
|
||||
private String source() throws Exception {
|
||||
return edt(() -> FileDocumentManager.getInstance().getDocument(file).getText());
|
||||
}
|
||||
|
||||
private void open(Path path) throws Exception {
|
||||
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
|
||||
pane = openDesigner(project, file);
|
||||
step("Opened " + file.getName());
|
||||
}
|
||||
|
||||
private void inspector(boolean expanded) throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
var panel =
|
||||
(TitledPane)
|
||||
pane.lookupAll(".titled-pane").stream()
|
||||
.filter(n -> n instanceof TitledPane t && t.getText().equals("Bindings"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
panel.setAnimated(false);
|
||||
panel.setExpanded(expanded);
|
||||
var tabs = (TabPane) panel.getContent();
|
||||
tabs.getSelectionModel()
|
||||
.select(
|
||||
tabs.getTabs().stream()
|
||||
.filter(t -> t.getText().equals("DataGrid / Docking"))
|
||||
.findFirst()
|
||||
.orElseThrow());
|
||||
pane.applyCss();
|
||||
pane.layout();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void select(String name, String id) throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
var tree = (TreeView<Element>) pane.lookup("#declaration-tree");
|
||||
for (int i = 0; i < tree.getExpandedItemCount(); i++) {
|
||||
var item = tree.getTreeItem(i);
|
||||
var e = item.getValue();
|
||||
String tag = e.getTagName();
|
||||
if ((tag.equals(name) || tag.endsWith("." + name))
|
||||
&& (id.isEmpty()
|
||||
|| e.getAttribute("id").equals(id)
|
||||
|| e.getAttribute("destinationId").equals(id))) {
|
||||
tree.getSelectionModel().select(item);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
throw new AssertionError("Missing " + name + " " + id);
|
||||
});
|
||||
}
|
||||
|
||||
private void combo(String name, String text) throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
var box = (ComboBox<String>) pane.lookup("#" + name);
|
||||
box.setValue(text);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void edit(String button, String expected) throws Exception {
|
||||
String before = source();
|
||||
click(pane, button);
|
||||
await(
|
||||
() -> {
|
||||
String now = source();
|
||||
var msg = fx(() -> ((Label) pane.lookup("#declaration-message")).getText());
|
||||
if (!msg.isEmpty()) throw new AssertionError(msg);
|
||||
return !now.equals(before)
|
||||
&& now.contains(expected)
|
||||
&& fx(
|
||||
() ->
|
||||
((TextArea) pane.lookup("#fxml-source")) == null
|
||||
|| ((TextArea) pane.lookup("#fxml-source")).getText().equals(now));
|
||||
});
|
||||
fx(pane::flush).toCompletableFuture().get();
|
||||
step(button + " · " + expected);
|
||||
}
|
||||
|
||||
private void set(String field, String value) throws Exception {
|
||||
combo("declaration-property", field);
|
||||
fx(
|
||||
() -> {
|
||||
((ComboBox<?>) pane.lookup("#declaration-value")).getEditor().setText(value);
|
||||
return null;
|
||||
});
|
||||
edit("Apply setting", field + "=\"" + value + "\"");
|
||||
}
|
||||
|
||||
private void roundtrip(String previous) throws Exception {
|
||||
String now = source();
|
||||
click(pane, "Undo");
|
||||
await(() -> source().equals(previous));
|
||||
click(pane, "Redo");
|
||||
await(() -> source().equals(now));
|
||||
Path path = Path.of(file.getPath());
|
||||
click(pane, "Save");
|
||||
await(() -> Files.readString(path).equals(now));
|
||||
edt(
|
||||
() -> {
|
||||
FileEditorManager.getInstance(project).closeFile(file);
|
||||
return null;
|
||||
});
|
||||
open(path);
|
||||
if (!source().equals(now)) throw new AssertionError("Reopened source differs");
|
||||
}
|
||||
|
||||
private void checkPreviewState() {
|
||||
var state = (Label) pane.lookup("#preview-state");
|
||||
if (state != null
|
||||
&& (state.getText().startsWith("Preview failed")
|
||||
|| state.getText().startsWith("Preview unavailable")
|
||||
|| state.getText().startsWith("Preview blocked")))
|
||||
throw new AssertionError(state.getText());
|
||||
}
|
||||
|
||||
private void preview(String id, boolean build) throws Exception {
|
||||
step("Preview " + id);
|
||||
click(pane, "Form preview");
|
||||
click(pane, build ? "Build and Refresh" : "Preview last successful");
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() -> {
|
||||
checkPreviewState();
|
||||
return !((ComboBox<?>) pane.lookup("#preview-example")).getItems().isEmpty();
|
||||
}));
|
||||
fx(
|
||||
() -> {
|
||||
((ComboBox<?>) pane.lookup("#preview-example")).getSelectionModel().selectFirst();
|
||||
((Spinner<?>) pane.lookup("#preview-height")).increment(5);
|
||||
return null;
|
||||
});
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() -> {
|
||||
checkPreviewState();
|
||||
var image = (ImageView) pane.lookup("#full-preview-image");
|
||||
return image != null
|
||||
&& image.getImage() != null
|
||||
&& image.getImage().getHeight() == 720;
|
||||
}));
|
||||
fx(
|
||||
() -> {
|
||||
var image = ((ImageView) pane.lookup("#full-preview-image")).getImage();
|
||||
ImageIO.write(
|
||||
SwingFXUtils.fromFXImage(image, null), "png", output.resolve(id + ".png").toFile());
|
||||
return null;
|
||||
});
|
||||
Files.writeString(output.resolve("attempt"), id);
|
||||
click(pane, "Interactive preview");
|
||||
await(
|
||||
() -> {
|
||||
if (Files.exists(output.resolve("target-error.txt")))
|
||||
throw new AssertionError(Files.readString(output.resolve("target-error.txt")));
|
||||
return Files.exists(output.resolve("result-" + id));
|
||||
});
|
||||
click(pane, "Stop preview");
|
||||
step(Files.readString(output.resolve("result-" + id)));
|
||||
}
|
||||
|
||||
private void verify() throws Exception {
|
||||
Path root = Path.of(project.getBasePath()),
|
||||
views = root.resolve("src/main/resources/de/neitzel/archiver/ui");
|
||||
open(root.resolve("src/main/resources/ReferenceWorkspace.fxml"));
|
||||
inspector(true);
|
||||
select("DockGroupDefinition", "editors");
|
||||
select("DockGroupDefinition", "changes");
|
||||
open(views.resolve("FolderTab.fxml"));
|
||||
inspector(true);
|
||||
select("DataGrid", "");
|
||||
combo("declaration-property", "items");
|
||||
click(pane, "Edit data binding");
|
||||
fx(
|
||||
() -> {
|
||||
if (!((TextField) pane.lookup("#direct-path")).getText().equals("rows"))
|
||||
throw new AssertionError("Missing grid.items binding");
|
||||
return null;
|
||||
});
|
||||
inspector(true);
|
||||
select("DataGrid", "");
|
||||
combo("declaration-property", "source");
|
||||
click(pane, "Edit data binding");
|
||||
fx(
|
||||
() -> {
|
||||
if (!((TextField) pane.lookup("#direct-property")).getText().equals("source"))
|
||||
throw new AssertionError("Missing source binding input");
|
||||
return null;
|
||||
});
|
||||
inspector(true);
|
||||
select("DataGrid", "");
|
||||
set("keyAttribute", "path");
|
||||
set("selectionMode", "SINGLE");
|
||||
set("pageSize", "25");
|
||||
set("groupBy", "folder");
|
||||
select("DataGridColumn", "path");
|
||||
set("id", "document");
|
||||
set("header", "Archivdatei");
|
||||
set("width", "245");
|
||||
set("kind", "TEXT");
|
||||
set("filterable", "false");
|
||||
edit("Later", "Archivdatei");
|
||||
select("DataGridColumn", "document");
|
||||
edit("Earlier", "Archivdatei");
|
||||
edit("Add column", "id=\"column\"");
|
||||
select("DataGridColumn", "column");
|
||||
set("attribute", "folder");
|
||||
set("checklist", "CURRENT_PAGE");
|
||||
String before = source();
|
||||
edit("Delete column", "Archivdatei");
|
||||
roundtrip(before);
|
||||
preview("folder", true);
|
||||
open(views.resolve("ArchiveWindow.fxml"));
|
||||
preview("right", false);
|
||||
inspector(true);
|
||||
select("right", "");
|
||||
combo("dock-area", "bottom");
|
||||
edit("Move area", "<bottom><DockGroupDefinition");
|
||||
select("DockGroupDefinition", "details");
|
||||
set("destinationId", "beleg");
|
||||
set("visibleWhenEmpty", "true");
|
||||
select("DockPane", "");
|
||||
combo("dock-area", "left");
|
||||
edit("Add area with group", "destinationId=\"left\"");
|
||||
select("DockGroupDefinition", "messages");
|
||||
edit("Split branch", "destinationId=\"split\"");
|
||||
select("DockSplitDefinition", "split");
|
||||
String horizontal = source();
|
||||
set("orientation", "VERTICAL");
|
||||
roundtrip(horizontal);
|
||||
inspector(true);
|
||||
select("DockSplitDefinition", "split");
|
||||
select("DockGroupDefinition", "messages");
|
||||
select("DockGroupDefinition", "beleg");
|
||||
inspector(false);
|
||||
preview("bottom", false);
|
||||
fx(
|
||||
() -> {
|
||||
ImageIO.write(
|
||||
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
|
||||
"png",
|
||||
output.resolve("intellij.png").toFile());
|
||||
return null;
|
||||
});
|
||||
Files.writeString(
|
||||
output.resolve("SUCCESS.txt"),
|
||||
"PASS registered IntelliJ DataGrid and Docking inspectors, reference workspace, native"
|
||||
+ " edits/undo/redo/save/reopen, loaded Archiver rows and stable selection, two sample"
|
||||
+ " contents moved from right to bottom.\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package qualification;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.Parent;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.input.*;
|
||||
import javafx.stage.*;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
/** Observes the target JVM launched by the IDE. No application or WebKit classes enter the IDE. */
|
||||
public final class SavedDocumentTargetProbe {
|
||||
public static void premain(String directory) {
|
||||
if (System.getProperty("sun.java.command", "")
|
||||
.startsWith("de.neitzel.fxdesigner.target.WorkerMain "))
|
||||
Thread.ofPlatform().daemon().start(() -> new Probe().run(Path.of(directory)));
|
||||
}
|
||||
|
||||
private static final class Probe {
|
||||
private Path evidence;
|
||||
private Parent root;
|
||||
private Object viewer, engine;
|
||||
private TextField fixed, dynamic;
|
||||
|
||||
private <T> T fx(Callable<T> action) throws Exception {
|
||||
var task = new FutureTask<>(action);
|
||||
Platform.runLater(task);
|
||||
return task.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private void await(Callable<Boolean> check) throws Exception {
|
||||
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
while (System.nanoTime() < end) {
|
||||
if (fx(check)) return;
|
||||
Thread.sleep(80);
|
||||
}
|
||||
throw new AssertionError("Timed out waiting for " + check);
|
||||
}
|
||||
|
||||
private void run(Path directory) {
|
||||
evidence = directory;
|
||||
try {
|
||||
// The same agent is present in discovery and off-screen render workers.
|
||||
while (true) {
|
||||
try {
|
||||
if (fx(
|
||||
() -> {
|
||||
var stage =
|
||||
Window.getWindows().stream()
|
||||
.filter(Stage.class::isInstance)
|
||||
.map(Stage.class::cast)
|
||||
.filter(
|
||||
w ->
|
||||
w.isShowing()
|
||||
&& w.getOpacity() > 0
|
||||
&& w.getTitle() != null
|
||||
&& w.getTitle().startsWith("Neitzel preview"))
|
||||
.findFirst();
|
||||
if (stage.isEmpty()) return false;
|
||||
stage.get().setWidth(800);
|
||||
stage.get().setHeight(580);
|
||||
stage.get().requestFocus();
|
||||
root = stage.get().getScene().getRoot();
|
||||
viewer = root.lookup("#article");
|
||||
return viewer != null;
|
||||
})) break;
|
||||
} catch (IllegalStateException starting) {
|
||||
}
|
||||
Thread.sleep(120);
|
||||
}
|
||||
fx(
|
||||
() -> {
|
||||
var browser = root.lookup("WebView");
|
||||
engine = browser.getClass().getMethod("getEngine").invoke(browser);
|
||||
fixed = (TextField) root.lookup("#fixed");
|
||||
dynamic = (TextField) root.lookup("#dynamic");
|
||||
var media = (Button) root.lookup(".html-viewer-media-load");
|
||||
require(
|
||||
media.getText().equals("Belegbilder laden")
|
||||
&& media.getTooltip().getText().equals("Keine externen Belegbilder")
|
||||
&& media.isDisabled(),
|
||||
"edited offline media labels");
|
||||
require(
|
||||
"Belegbilder erneut laden".equals(call("getMediaReloadText"))
|
||||
&& "Bilder dieses Belegs laden".equals(call("getMediaTooltipText")),
|
||||
"remaining media labels");
|
||||
require(!Boolean.TRUE.equals(call("isExternalImagesAllowed")), "offline viewer");
|
||||
return null;
|
||||
});
|
||||
body("Rechnung RE-042");
|
||||
popup(fixed, "Pr", List.of("Prüfung", "Privat"));
|
||||
popup(dynamic, "Re", List.of("Rechnung", "Reise"));
|
||||
fx(
|
||||
() -> {
|
||||
var tags = tagSource();
|
||||
dynamic.setText("R");
|
||||
tags.add("Register");
|
||||
var choices =
|
||||
Window.getWindows().stream()
|
||||
.filter(w -> w instanceof Popup && w.isShowing())
|
||||
.map(w -> (ListView<?>) w.getScene().lookup(".list-view"))
|
||||
.filter(Objects::nonNull)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
require(
|
||||
choices.getItems().equals(List.of("Rechnung", "Reise", "Register")),
|
||||
"addition in open popup");
|
||||
tags.remove("Reise");
|
||||
require(
|
||||
choices.getItems().equals(List.of("Rechnung", "Register")),
|
||||
"removal in open popup");
|
||||
dynamic.fireEvent(
|
||||
new KeyEvent(
|
||||
KeyEvent.KEY_PRESSED, "", "", KeyCode.DOWN, false, false, false, false));
|
||||
dynamic.fireEvent(
|
||||
new KeyEvent(
|
||||
KeyEvent.KEY_PRESSED, "", "", KeyCode.ENTER, false, false, false, false));
|
||||
require(
|
||||
dynamic.getText().equals("Rechnung")
|
||||
&& tags.equals(List.of("Rechnung", "Register")),
|
||||
"pick leaves catalogue intact");
|
||||
dynamic.setText("Re");
|
||||
((Button) root.lookup("#next")).fire();
|
||||
require(
|
||||
Window.getWindows().stream().noneMatch(w -> w instanceof Popup && w.isShowing()),
|
||||
"old matches dismissed on replacement");
|
||||
return null;
|
||||
});
|
||||
body("Lieferschein LS-018");
|
||||
require(
|
||||
fx(() -> tagSource().equals(List.of("Lieferung", "Lieferschein"))),
|
||||
"replacement removes old document tags");
|
||||
popup(dynamic, "Li", List.of("Lieferung", "Lieferschein"));
|
||||
popup(fixed, "Pr", List.of("Prüfung", "Privat"));
|
||||
fx(
|
||||
() -> {
|
||||
((TextArea) root.lookup("#source"))
|
||||
.setText("<html><body><h1>Geänderter Beleg</h1></body></html>");
|
||||
return null;
|
||||
});
|
||||
body("Geänderter Beleg");
|
||||
fx(
|
||||
() -> {
|
||||
viewer
|
||||
.getClass()
|
||||
.getMethod("load", Path.class)
|
||||
.invoke(viewer, directory.resolve("missing-preview.html"));
|
||||
return null;
|
||||
});
|
||||
await(() -> !Boolean.TRUE.equals(call("isLoading")) && call("getError") != null);
|
||||
fx(
|
||||
() -> {
|
||||
((Button) root.lookup("#next")).fire();
|
||||
return null;
|
||||
});
|
||||
body("Rechnung RE-042");
|
||||
Files.writeString(
|
||||
directory.resolve("saved-document-result"),
|
||||
"Rechnung RE-042 → Lieferschein LS-018 → Geänderter Beleg; load error and recovery;"
|
||||
+ " popup Pr: Prüfung, Privat; Re: Rechnung, Reise; Li: Lieferung, Lieferschein."
|
||||
+ " PID "
|
||||
+ ProcessHandle.current().pid());
|
||||
} catch (Throwable ex) {
|
||||
try {
|
||||
var trace = new java.io.StringWriter();
|
||||
ex.printStackTrace(new java.io.PrintWriter(trace));
|
||||
Files.writeString(directory.resolve("target-error.txt"), trace.toString());
|
||||
} catch (Exception ignored) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Object call(String method) throws Exception {
|
||||
return viewer.getClass().getMethod(method).invoke(viewer);
|
||||
}
|
||||
|
||||
private void body(String text) throws Exception {
|
||||
await(
|
||||
() -> {
|
||||
if (call("getError") != null) throw new AssertionError(call("getError"));
|
||||
var doc = (Document) engine.getClass().getMethod("getDocument").invoke(engine);
|
||||
return !Boolean.TRUE.equals(call("isLoading"))
|
||||
&& doc != null
|
||||
&& doc.getDocumentElement().getTextContent().contains(text);
|
||||
});
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<String> tagSource() throws Exception {
|
||||
return (List<String>) dynamic.getClass().getMethod("getSuggestionsSource").invoke(dynamic);
|
||||
}
|
||||
|
||||
private void popup(TextField field, String prefix, List<String> expected) throws Exception {
|
||||
await(
|
||||
() -> {
|
||||
if (field.isFocused()) return true;
|
||||
var stage = (Stage) root.getScene().getWindow();
|
||||
stage.toFront();
|
||||
stage.requestFocus();
|
||||
field.requestFocus();
|
||||
return field.isFocused();
|
||||
});
|
||||
fx(
|
||||
() -> {
|
||||
field.setText("");
|
||||
field.setText(prefix);
|
||||
return null;
|
||||
});
|
||||
await(
|
||||
() -> {
|
||||
for (var window : Window.getWindows()) {
|
||||
if (!(window instanceof Popup)
|
||||
|| !window.isShowing()
|
||||
|| !(window.getScene().lookup(".list-view") instanceof ListView<?> list)
|
||||
|| !list.getItems().equals(expected)) continue;
|
||||
var image = window.getScene().snapshot(null);
|
||||
int w = (int) image.getWidth(), h = (int) image.getHeight();
|
||||
var png =
|
||||
new java.awt.image.BufferedImage(
|
||||
w, h, java.awt.image.BufferedImage.TYPE_INT_ARGB);
|
||||
var pixels = new int[w * h];
|
||||
image
|
||||
.getPixelReader()
|
||||
.getPixels(
|
||||
0,
|
||||
0,
|
||||
w,
|
||||
h,
|
||||
javafx.scene.image.PixelFormat.getIntArgbInstance(),
|
||||
pixels,
|
||||
0,
|
||||
w);
|
||||
png.setRGB(0, 0, w, h, pixels, 0, w);
|
||||
javax.imageio.ImageIO.write(
|
||||
png, "png", evidence.resolve("tags-" + prefix + ".png").toFile());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
fx(
|
||||
() -> {
|
||||
field.fireEvent(
|
||||
new KeyEvent(
|
||||
KeyEvent.KEY_PRESSED, "", "", KeyCode.ESCAPE, false, false, false, false));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private static void require(boolean condition, String label) {
|
||||
if (!condition) throw new AssertionError(label);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package qualification;
|
||||
|
||||
import static qualification.WorkflowProbe.*;
|
||||
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.vfs.LocalFileSystem;
|
||||
import de.neitzel.fxdesigner.protocol.BindingMetadata.Target;
|
||||
import java.nio.file.*;
|
||||
import javafx.embed.swing.SwingFXUtils;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.ImageView;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
/** Configures the Archiver HTML viewer and both tag fields in the registered form inspector. */
|
||||
public final class SavedDocumentWorkflowProbe extends FormWorkflowProbe {
|
||||
@Override
|
||||
void verify(Project project) throws Exception {
|
||||
var path =
|
||||
Path.of(
|
||||
project.getBasePath(),
|
||||
"src/designer/resources/de/neitzel/archiver/preview/SavedDocument.fxml");
|
||||
file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
|
||||
pane = openDesigner(project, file);
|
||||
controls(true);
|
||||
choose("form-control", "HtmlViewer #article");
|
||||
set("mediaLoadText", "Belegbilder laden", "mediaLoadText=\"Belegbilder laden\"");
|
||||
set(
|
||||
"mediaReloadText",
|
||||
"Belegbilder erneut laden",
|
||||
"mediaReloadText=\"Belegbilder erneut laden\"");
|
||||
set(
|
||||
"mediaTooltipText",
|
||||
"Bilder dieses Belegs laden",
|
||||
"mediaTooltipText=\"Bilder dieses Belegs laden\"");
|
||||
set(
|
||||
"noExternalMediaText",
|
||||
"Keine externen Belegbilder",
|
||||
"noExternalMediaText=\"Keine externen Belegbilder\"");
|
||||
set("mediaButtonVisible", "false", "mediaButtonVisible=\"false\"");
|
||||
click(pane, "Undo");
|
||||
await(() -> source().contains("mediaButtonVisible=\"true\""));
|
||||
choose("form-control", "AutoCompleteTextField #fixed");
|
||||
set("suggestions", "Prüfung\nPrivat", "fx:value=\"Prüfung\"");
|
||||
click(pane, "Bind property");
|
||||
if (!fx(
|
||||
() ->
|
||||
((Label) pane.lookup("#form-message"))
|
||||
.getText()
|
||||
.contains("no writable JavaFX property")))
|
||||
throw new AssertionError("Static collection was offered as a direct binding target");
|
||||
if (source().contains("property=\"suggestionsSource\"")
|
||||
|| source().contains("property=\"html\""))
|
||||
throw new AssertionError("Expected two unbound targets before visual authoring");
|
||||
String current = normalized(source());
|
||||
click(pane, "Save");
|
||||
await(() -> normalized(Files.readString(path)).equals(current));
|
||||
edt(
|
||||
() -> {
|
||||
FileEditorManager.getInstance(project).closeFile(file);
|
||||
return null;
|
||||
});
|
||||
pane = openDesigner(project, file);
|
||||
if (!normalized(source()).equals(current))
|
||||
throw new AssertionError("Reopen lost document settings");
|
||||
step("Edited four media labels, visibility and fixed suggestions; saved and reopened");
|
||||
click(pane, "Form preview");
|
||||
click(pane, "Build and Refresh");
|
||||
await(() -> fx(() -> ((ComboBox<?>) pane.lookup("#preview-example")).getItems().size() == 2));
|
||||
bindFromModel("html", "article", "html");
|
||||
bindFromModel("tags", "dynamic", "suggestionsSource");
|
||||
String bound = normalized(source());
|
||||
click(pane, "Save");
|
||||
await(() -> normalized(Files.readString(path)).equals(bound));
|
||||
edt(
|
||||
() -> {
|
||||
FileEditorManager.getInstance(project).closeFile(file);
|
||||
return null;
|
||||
});
|
||||
pane = openDesigner(project, file);
|
||||
if (!normalized(source()).equals(bound))
|
||||
throw new AssertionError("Reopen lost direct bindings");
|
||||
Files.copy(path, output.resolve("saved-bindings.fxml"));
|
||||
checkSavedBinding("HtmlViewer #article", "html", "html");
|
||||
checkSavedBinding("AutoCompleteTextField #dynamic", "suggestionsSource", "tags");
|
||||
click(pane, "Form preview");
|
||||
click(pane, "Build and Refresh");
|
||||
await(() -> fx(() -> ((ComboBox<?>) pane.lookup("#preview-example")).getItems().size() == 2));
|
||||
choose("preview-example", "saved-invoice");
|
||||
frame("invoice", "Rechnung", 0xff294973);
|
||||
click(pane, "Interactive preview");
|
||||
awaitTarget("saved-document-result");
|
||||
click(pane, "Stop preview");
|
||||
choose("preview-example", "saved-delivery");
|
||||
frame("delivery", "Lieferschein", 0xff38643e);
|
||||
fx(
|
||||
() -> {
|
||||
ImageIO.write(
|
||||
SwingFXUtils.fromFXImage(pane.snapshot(null, null), null),
|
||||
"png",
|
||||
output.resolve("intellij.png").toFile());
|
||||
return null;
|
||||
});
|
||||
Files.writeString(
|
||||
output.resolve("SUCCESS.txt"),
|
||||
"PASS registered IntelliJ Archiver saved documents: inspector configuration, two WebView"
|
||||
+ " frames, document replacement, error recovery and live suggestion popups.\n");
|
||||
}
|
||||
|
||||
// IntelliJ can strip indentation from empty lines left by element removal on save.
|
||||
private static String normalized(String source) {
|
||||
return source.replaceAll("(?m)^[ \t]+$", "");
|
||||
}
|
||||
|
||||
private void checkSavedBinding(String control, String property, String path) throws Exception {
|
||||
controls(true);
|
||||
choose("form-control", control);
|
||||
choose("form-property", property);
|
||||
click(pane, "Bind property");
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() ->
|
||||
((TextField) pane.lookup("#direct-property")).getText().equals(property)
|
||||
&& ((TextField) pane.lookup("#direct-path")).getText().equals(path)
|
||||
&& ((ComboBox<?>) pane.lookup("#direct-direction"))
|
||||
.getValue()
|
||||
.equals("view")));
|
||||
}
|
||||
|
||||
private void bindFromModel(String path, String control, String property) throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
var group =
|
||||
(TitledPane)
|
||||
pane.lookupAll(".titled-pane").stream()
|
||||
.filter(n -> n instanceof TitledPane t && t.getText().equals("Bindings"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
group.setAnimated(false);
|
||||
group.setExpanded(true);
|
||||
var tabs = (TabPane) group.getContent();
|
||||
tabs.getSelectionModel()
|
||||
.select(
|
||||
tabs.getTabs().stream()
|
||||
.filter(t -> t.getText().equals("Discover targets"))
|
||||
.findFirst()
|
||||
.orElseThrow());
|
||||
pane.applyCss();
|
||||
pane.layout();
|
||||
return null;
|
||||
});
|
||||
click(pane, "Discover bindings");
|
||||
await(() -> fx(() -> !((ComboBox<?>) pane.lookup("#binding-path")).getItems().isEmpty()));
|
||||
choose("binding-direction", "view");
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() ->
|
||||
((ComboBox<?>) pane.lookup("#binding-path"))
|
||||
.getItems().stream().anyMatch(a -> a.toString().startsWith(path + " : "))));
|
||||
choose("binding-path", path + " : ");
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
var targets = (TableView<Target>) pane.lookup("#binding-targets");
|
||||
var target =
|
||||
targets.getItems().stream()
|
||||
.filter(
|
||||
t ->
|
||||
t.control().equals(control)
|
||||
&& t.property().equals(property)
|
||||
&& t.status().equals("COMPATIBLE"))
|
||||
.findFirst();
|
||||
if (target.isEmpty()) return false;
|
||||
targets.getSelectionModel().select(target.get());
|
||||
return true;
|
||||
}));
|
||||
click(pane, "Use selected target");
|
||||
if (!fx(
|
||||
() ->
|
||||
((TextField) pane.lookup("#direct-path")).getText().equals(path)
|
||||
&& ((ComboBox<?>) pane.lookup("#direct-direction")).getValue().equals("view")))
|
||||
throw new AssertionError("Wrong source or direction for " + property);
|
||||
fx(
|
||||
() -> {
|
||||
var editor = pane.lookup("#direct-bindings").getParent();
|
||||
ImageIO.write(
|
||||
SwingFXUtils.fromFXImage(editor.snapshot(null, null), null),
|
||||
"png",
|
||||
output.resolve("binding-" + control + ".png").toFile());
|
||||
return null;
|
||||
});
|
||||
click(pane, "Apply binding");
|
||||
await(() -> source().contains("property=\"" + property + "\""));
|
||||
step(
|
||||
"Created " + control + "." + property + " from compatible source " + path + " toward view");
|
||||
}
|
||||
|
||||
private void frame(String id, String title, int accent) throws Exception {
|
||||
await(
|
||||
() ->
|
||||
fx(
|
||||
() -> {
|
||||
var image = ((ImageView) pane.lookup("#full-preview-image")).getImage();
|
||||
var state = ((Label) pane.lookup("#preview-state")).getText();
|
||||
if (state.startsWith("Preview failed")
|
||||
|| state.startsWith("Preview unavailable")
|
||||
|| state.startsWith("Preview blocked")) throw new AssertionError(state);
|
||||
if (image == null || !state.contains(title)) return false;
|
||||
ImageIO.write(
|
||||
SwingFXUtils.fromFXImage(image, null),
|
||||
"png",
|
||||
output.resolve(id + ".png").toFile());
|
||||
int ink = 0;
|
||||
for (int y = 0; y < (int) image.getHeight(); y++)
|
||||
for (int x = 0; x < (int) image.getWidth(); x++)
|
||||
if (image.getPixelReader().getArgb(x, y) == accent) ink++;
|
||||
if (ink < 1800
|
||||
|| image.getPixelReader().getArgb((int) image.getWidth() - 32, 104)
|
||||
!= 0xffffffff)
|
||||
throw new AssertionError(
|
||||
title + " missing HTML accent in the embedded frame: " + ink);
|
||||
return true;
|
||||
}));
|
||||
step("Embedded " + title + " rendered its document-specific HTML colour");
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,26 @@ public final class WorkflowProbe implements StartupActivity.DumbAware {
|
||||
return null;
|
||||
}
|
||||
|
||||
static DesignerPane openDesigner(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));
|
||||
var pane = fx(() -> (DesignerPane) panel.getScene().getRoot());
|
||||
await(() -> fx(() -> pane.kit().editor().getFxomDocument() != null));
|
||||
return pane;
|
||||
}
|
||||
|
||||
static void await(Callable<Boolean> condition) throws Exception {
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(120);
|
||||
while (System.nanoTime() < until) {
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
<!-- Dependency versions -->
|
||||
<junit.version>6.1.3</junit.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 -->
|
||||
<maven.clean.plugin>3.5.0</maven.clean.plugin>
|
||||
|
||||
@@ -34,7 +34,7 @@ def run(name, command):
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="designer-connected-") as temporary:
|
||||
for host in ("standalone", "intellij"):
|
||||
base = Path(temporary) / host
|
||||
base = (Path(temporary) / host).resolve()
|
||||
for mode in ("classpath", "modulepath"):
|
||||
fixture = base / mode
|
||||
shutil.copytree(ROOT / "integration-fixtures/preview" / mode, fixture,
|
||||
|
||||
@@ -22,20 +22,30 @@ p.add_argument("--target-java-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("--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")
|
||||
forms = p.add_mutually_exclusive_group()
|
||||
forms.add_argument("--connection-form", action="store_true", help="Qualify the Archiver connection form")
|
||||
forms.add_argument("--grid-docking", type=Path, metavar="REFERENCE_FXML", help="Qualify the Archiver grid, dock layout and the supplied reference workspace")
|
||||
forms.add_argument("--document-tabs", action="store_true", help="Qualify the production Archiver HTML document tabs")
|
||||
forms.add_argument("--saved-document", action="store_true", help="Open the Archiver saved HTML and tag example")
|
||||
args = p.parse_args()
|
||||
if (args.connection_form or args.grid_docking or args.saved_document or args.document_tabs) and not args.archiver:
|
||||
p.error("Selecting an Archiver view requires --archiver")
|
||||
if args.repeat < 1:
|
||||
p.error("--repeat must be positive")
|
||||
output = ROOT / "target/ide-workflow"
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
batch = Path(tempfile.mkdtemp(prefix="runs-", dir=output))
|
||||
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):
|
||||
crashes = NativeCrashGuard(ROOT)
|
||||
launch = subprocess.run([sys.executable, ROOT / "scripts/run-fixture-host.py", "intellij",
|
||||
"--check", "--mode", mode, "--java-home", args.java_home,
|
||||
"--check", *(["--document-tabs"] if args.document_tabs else []), *(["--saved-document"] if args.saved_document else []), *(["--grid-docking", str(args.grid_docking.resolve())] if args.grid_docking else []), *(["--connection-form"] if args.connection_form else []), *(["--archiver", str(args.archiver.resolve())] if args.archiver else []), "--mode", mode, "--java-home", args.java_home,
|
||||
"--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, timeout=60)
|
||||
if launch.returncode:
|
||||
raise RuntimeError(launch.stdout + launch.stderr)
|
||||
evidence = batch / f"{mode}-run-{run_number}"
|
||||
evidence.mkdir(exist_ok=True)
|
||||
(output / (mode + "-launch.log")).write_text(launch.stdout + launch.stderr)
|
||||
@@ -43,12 +53,14 @@ 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])
|
||||
pid = int(re.search(r"Host PID: (\d+)", launch.stdout)[1])
|
||||
try:
|
||||
until = time.monotonic() + 240
|
||||
until = time.monotonic() + (480 if args.archiver else 240)
|
||||
while time.monotonic() < until:
|
||||
if (base / "FAILURE.txt").exists():
|
||||
raise RuntimeError((base / "FAILURE.txt").read_text())
|
||||
if (base / "SUCCESS.txt").exists():
|
||||
break
|
||||
if not subprocess.run(["ps", "-p", str(pid), "-o", "pid="], capture_output=True).stdout.strip():
|
||||
raise RuntimeError("IDE exited during qualification. See " + str(base / "launcher.log"))
|
||||
time.sleep(.25)
|
||||
else:
|
||||
raise RuntimeError("IDE qualification timed out: " + str(base))
|
||||
@@ -73,7 +85,7 @@ for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode i
|
||||
shutil.copyfile(base / "intellij.png", output / (mode + ".png"))
|
||||
(evidence / "proof.json").write_text(json.dumps(proof, indent=2) + "\n")
|
||||
finally:
|
||||
for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log"):
|
||||
for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log", "steps.txt", "target-error.txt", "preview-restored.png", "imap.png", "jmap.png", "invoice.png", "delivery.png", "saved-document-result", "saved-bindings.fxml", "binding-article.png", "binding-dynamic.png", "tags-Pr.png", "tags-Re.png", "tags-Li.png", "document-tabs-result", "rechnung-tab.png", "lieferschein-tab.png", "rechnung-tab-tags.png", "lieferschein-tab-tags.png", "folder.png", "right.png", "bottom.png", "result-folder", "result-right", "result-bottom", "intellij.png"):
|
||||
if (base / name).exists():
|
||||
shutil.copyfile(base / name, evidence / name)
|
||||
workers = descendant_workers(pid)
|
||||
|
||||
@@ -21,5 +21,5 @@ for artifact in manifest["artifacts"]:
|
||||
errors.append(f"Different build: {path}")
|
||||
if errors:
|
||||
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")
|
||||
|
||||
@@ -64,7 +64,7 @@ with tempfile.TemporaryDirectory(prefix="designer-preview-") as temp:
|
||||
first = None
|
||||
for mode in ("discovery", "bindings", "standard", "async", "timeout", "cancel",
|
||||
"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)
|
||||
if mode == "standard":
|
||||
first = re.search(r"SESSION (\S+) models=1", log)[1]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/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 json
|
||||
import os
|
||||
@@ -7,7 +7,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
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("--maven", type=Path, default=ROOT / "mvnw")
|
||||
args = parser.parse_args()
|
||||
@@ -15,7 +15,11 @@ library = args.library.resolve()
|
||||
java = args.target_java_home.resolve()
|
||||
maven = args.maven.resolve()
|
||||
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")):
|
||||
parser.error("Supply a full application JDK installation")
|
||||
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:
|
||||
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="
|
||||
+ os.pathsep.join(map(prop, tools)) + "\n")
|
||||
print(settings)
|
||||
|
||||
@@ -18,13 +18,44 @@ p.add_argument("--target-java-home", type=Path, required=True)
|
||||
p.add_argument("--idea-home", type=Path)
|
||||
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("--archiver", type=Path, help="Use a disposable copy of the Archiver project")
|
||||
forms = p.add_mutually_exclusive_group()
|
||||
forms.add_argument("--connection-form", action="store_true", help="Open and qualify the Archiver connection form")
|
||||
forms.add_argument("--grid-docking", type=Path, metavar="REFERENCE_FXML", help="Qualify the Archiver grid, dock layout and the supplied reference workspace")
|
||||
forms.add_argument("--document-tabs", action="store_true", help="Qualify the production Archiver HTML document tabs")
|
||||
forms.add_argument("--saved-document", action="store_true", help="Open the Archiver saved HTML and tag example")
|
||||
args = p.parse_args()
|
||||
if (args.connection_form or args.grid_docking or args.saved_document or args.document_tabs) and not args.archiver:
|
||||
p.error("Selecting an Archiver view requires --archiver")
|
||||
base = Path(tempfile.mkdtemp(prefix="neitzel-designer-host-")).resolve()
|
||||
project = base / "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)
|
||||
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)
|
||||
view = "ConnectionForm" if args.connection_form else "ArchiveWindow"
|
||||
if args.grid_docking:
|
||||
view = "FolderTab"
|
||||
shutil.copyfile(args.grid_docking, project / "src/main/resources/ReferenceWorkspace.fxml")
|
||||
file = project / f"src/main/resources/de/neitzel/archiver/ui/{view}.fxml"
|
||||
if args.saved_document:
|
||||
file = project / "src/designer/resources/de/neitzel/archiver/preview/SavedDocument.fxml"
|
||||
if args.check:
|
||||
# Start the authoring test with both destinations unbound in the disposable copy.
|
||||
source = file.read_text()
|
||||
for control, prop, path in (("article", "html", "html"), ("dynamic", "suggestionsSource", "tags")):
|
||||
declaration = f'<DirectBinding control="{control}" property="{prop}" path="{path}" direction="view"/>'
|
||||
if source.count(declaration) != 1:
|
||||
raise ValueError(f"Expected the shipped sample binding for {control}.{prop}")
|
||||
source = source.replace(declaration, "")
|
||||
file.write_text(source)
|
||||
else:
|
||||
subprocess.run([sys.executable, ROOT / "scripts/prepare-fixture-host.py", "--destination", project,
|
||||
"--target-java-home", args.target_java_home, "--mode", args.mode], check=True)
|
||||
file = project / "app/src/main/resources/fixture/components/Person.fxml"
|
||||
settings = project / ".neitzel-fx-designer/host.properties"
|
||||
file = project / "app/src/main/resources/fixture/components/Person.fxml"
|
||||
env = dict(os.environ)
|
||||
if args.host == "standalone":
|
||||
cp = os.pathsep.join([str(ROOT / "designer-standalone/target/classes"),
|
||||
@@ -44,11 +75,38 @@ else:
|
||||
checks.parent.mkdir(parents=True)
|
||||
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")]
|
||||
sources = ROOT / "integration-tests/idea"
|
||||
suite = "Archive"
|
||||
if args.connection_form:
|
||||
suite = "Connection"
|
||||
elif args.grid_docking:
|
||||
suite = "GridDock"
|
||||
elif args.document_tabs:
|
||||
suite = "DocumentTabs"
|
||||
elif args.saved_document:
|
||||
suite = "SavedDocument"
|
||||
probe = f"{suite}WorkflowProbe" if args.archiver else "WorkflowProbe"
|
||||
files = [sources / "WorkflowProbe.java"]
|
||||
if args.connection_form or args.saved_document or args.document_tabs:
|
||||
files.append(sources / "FormWorkflowProbe.java")
|
||||
if args.archiver:
|
||||
files.append(sources / f"{probe}.java")
|
||||
target_probe = f"{suite}TargetProbe"
|
||||
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 / f"{target_probe}.java"], check=True)
|
||||
agent = base / "archiver-ui-check.jar"
|
||||
with zipfile.ZipFile(agent, "w") as archive:
|
||||
archive.writestr("META-INF/MANIFEST.MF", f"Manifest-Version: 1.0\nPremain-Class: qualification.{target_probe}\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),
|
||||
str(ROOT / "integration-tests/idea/WorkflowProbe.java")], check=True)
|
||||
*files], check=True)
|
||||
meta = classes / "META-INF"
|
||||
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.parent.mkdir(parents=True, exist_ok=True)
|
||||
subprocess.run([str(args.java_home / "bin/jar"), "cf", str(jar), "-C", str(classes), "."], check=True)
|
||||
|
||||
Reference in New Issue
Block a user