Edit form controls and render localized application previews in the IntelliJ designer
This commit is contained in:
@@ -68,7 +68,7 @@ python3 scripts/check-ide-host.py --java-home "$JAVA_HOME" --target-java-home "$
|
||||
|
||||
### Archiver in IntelliJ
|
||||
|
||||
Build the [pinned NeitzelLib snapshot](docs/runtime/neitzellib-baseline.md), then build the Designer modules and plugin with the bootstrap command above. Archiver includes its example in the `designer-preview` Maven profile. To open an isolated IntelliJ instance with a project copy and the built plugin, run from this checkout with the same Maven environment:
|
||||
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 \
|
||||
@@ -77,6 +77,10 @@ python3 scripts/run-fixture-host.py intellij --archiver ../Archiver \
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -35,6 +35,13 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
return content;
|
||||
}
|
||||
|
||||
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,6 +50,7 @@ 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);
|
||||
@@ -233,7 +241,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");
|
||||
@@ -252,7 +260,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();
|
||||
@@ -330,13 +338,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",
|
||||
() -> {
|
||||
@@ -381,7 +444,48 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
discoveryTab,
|
||||
generationTab));
|
||||
bindings.setExpanded(false);
|
||||
center.setBottom(new VBox(properties, bindings));
|
||||
formEditor =
|
||||
new FormEditor(
|
||||
edit ->
|
||||
flush()
|
||||
.whenComplete(
|
||||
(ok, error) ->
|
||||
fx(
|
||||
() -> {
|
||||
if (error != null) report(error);
|
||||
else if (draft.writable() && draft.text().equals(edit.source()))
|
||||
submit(edit.changes(), "Edit form");
|
||||
else
|
||||
status.setText("Document changed; select the control again.");
|
||||
})),
|
||||
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.newBinding(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");
|
||||
@@ -421,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);
|
||||
}));
|
||||
}));
|
||||
@@ -480,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());
|
||||
}
|
||||
@@ -520,6 +630,8 @@ 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());
|
||||
@@ -553,6 +665,9 @@ 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());
|
||||
@@ -627,7 +742,7 @@ public final class DesignerPane extends BorderPane implements AutoCloseable {
|
||||
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;
|
||||
@@ -956,6 +1071,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);
|
||||
@@ -1006,6 +1122,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();
|
||||
@@ -1116,6 +1236,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
|
||||
@@ -1151,6 +1272,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.");
|
||||
}));
|
||||
});
|
||||
}
|
||||
@@ -1197,6 +1323,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(
|
||||
() -> {
|
||||
@@ -1212,14 +1359,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) {
|
||||
status.setText("Select a preview example after Build and Refresh.");
|
||||
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) return;
|
||||
if (projection == null && !interactiveRequested && !showWhole) return;
|
||||
long ticket = renderSequence.incrementAndGet();
|
||||
host.documents()
|
||||
.snapshots()
|
||||
@@ -1305,6 +1456,8 @@ 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(
|
||||
projection == null
|
||||
@@ -1320,14 +1473,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;
|
||||
}
|
||||
@@ -1354,6 +1512,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) {
|
||||
@@ -1365,14 +1538,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,494 @@
|
||||
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) {
|
||||
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, "");
|
||||
}
|
||||
|
||||
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", "");
|
||||
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, "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,238 @@
|
||||
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.editable()
|
||||
|| !(java.util.Set.of(
|
||||
"Integer", "String", "Boolean", "Number", "CSS", "Insets")
|
||||
.contains(property.type()))
|
||||
|| property.name().equals("dismissText")) {
|
||||
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.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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -193,6 +201,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) {
|
||||
@@ -221,7 +230,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);
|
||||
}
|
||||
@@ -357,7 +367,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,134 @@
|
||||
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 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>"));
|
||||
}
|
||||
}
|
||||
+23
-3
@@ -23,6 +23,7 @@ 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<>();
|
||||
|
||||
@@ -350,6 +351,9 @@ public final class BindingDiscovery {
|
||||
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
|
||||
@@ -382,7 +386,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());
|
||||
@@ -395,6 +398,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 =
|
||||
@@ -500,7 +512,8 @@ 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);
|
||||
@@ -510,12 +523,16 @@ public final class BindingDiscovery {
|
||||
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");
|
||||
}
|
||||
@@ -669,6 +686,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;
|
||||
|
||||
+15
-1
@@ -216,7 +216,21 @@ 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"))
|
||||
|
||||
+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>
|
||||
|
||||
+7
@@ -98,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");
|
||||
|
||||
+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>
|
||||
|
||||
+7
@@ -98,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");
|
||||
|
||||
@@ -45,25 +45,6 @@ public final class ArchiveWorkflowProbe implements StartupActivity.DumbAware {
|
||||
});
|
||||
}
|
||||
|
||||
private static void open(Project project, VirtualFile file) throws Exception {
|
||||
var editor =
|
||||
edt(
|
||||
() -> {
|
||||
var manager = FileEditorManager.getInstance(project);
|
||||
var all = manager.openFile(file, true);
|
||||
manager.setSelectedEditor(file, "neitzel-fx-designer");
|
||||
return java.util.Arrays.stream(all)
|
||||
.filter(e -> e.getName().equals("Neitzel Designer"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
});
|
||||
await(() -> edt(() -> bridge(editor.getComponent()) != null));
|
||||
var panel = edt(() -> bridge(editor.getComponent()));
|
||||
await(() -> fx(() -> panel.getScene() != null));
|
||||
pane = fx(() -> (DesignerPane) panel.getScene().getRoot());
|
||||
await(() -> fx(() -> pane.kit().editor().getFxomDocument() != null));
|
||||
}
|
||||
|
||||
private static void tab(String name) throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
@@ -131,7 +112,7 @@ public final class ArchiveWorkflowProbe implements StartupActivity.DumbAware {
|
||||
tab("Structure");
|
||||
select("structure-nodes", "openExample :");
|
||||
click(pane, "Copy subtree");
|
||||
open(project, destination);
|
||||
pane = openDesigner(project, destination);
|
||||
click(pane, "Preview last successful");
|
||||
await(
|
||||
() ->
|
||||
@@ -164,7 +145,7 @@ public final class ArchiveWorkflowProbe implements StartupActivity.DumbAware {
|
||||
FileEditorManager.getInstance(project).closeFile(destination);
|
||||
return null;
|
||||
});
|
||||
open(project, original);
|
||||
pane = openDesigner(project, original);
|
||||
step("Cross-View paste rejected at missing Command getter before writing");
|
||||
}
|
||||
|
||||
@@ -178,7 +159,7 @@ public final class ArchiveWorkflowProbe implements StartupActivity.DumbAware {
|
||||
+ "<BorderPane xmlns:fx='http://javafx.com/fxml/1'><top><MenuBar><menus>"
|
||||
+ "<Menu fx:id='recent'/></menus></MenuBar></top></BorderPane>");
|
||||
var file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
|
||||
open(project, file);
|
||||
pane = openDesigner(project, file);
|
||||
fx(
|
||||
() -> {
|
||||
var root =
|
||||
@@ -245,7 +226,7 @@ public final class ArchiveWorkflowProbe implements StartupActivity.DumbAware {
|
||||
FileEditorManager.getInstance(project).closeFile(file);
|
||||
return null;
|
||||
});
|
||||
open(project, file);
|
||||
pane = openDesigner(project, file);
|
||||
click(pane, "Build and Refresh");
|
||||
await(
|
||||
() ->
|
||||
@@ -302,7 +283,7 @@ public final class ArchiveWorkflowProbe implements StartupActivity.DumbAware {
|
||||
FileEditorManager.getInstance(project).closeFile(file);
|
||||
return null;
|
||||
});
|
||||
open(project, file);
|
||||
pane = openDesigner(project, file);
|
||||
click(pane, "Build and Refresh");
|
||||
await(
|
||||
() ->
|
||||
|
||||
@@ -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,348 @@
|
||||
package qualification;
|
||||
|
||||
import static qualification.WorkflowProbe.*;
|
||||
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.command.WriteCommandAction;
|
||||
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;
|
||||
|
||||
/** Drives the registered editor against a disposable copy of the real Archiver form. */
|
||||
public final class ConnectionWorkflowProbe implements StartupActivity.DumbAware {
|
||||
private DesignerPane pane;
|
||||
private 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();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void step(String message) throws Exception {
|
||||
Files.writeString(
|
||||
output.resolve("steps.txt"),
|
||||
message + "\n",
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.APPEND);
|
||||
}
|
||||
|
||||
private String source() throws Exception {
|
||||
return edt(() -> FileDocumentManager.getInstance().getDocument(file).getText());
|
||||
}
|
||||
|
||||
private 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;
|
||||
});
|
||||
}
|
||||
|
||||
private 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());
|
||||
});
|
||||
}
|
||||
|
||||
private 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);
|
||||
}
|
||||
|
||||
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();
|
||||
click(pane, "Insert control");
|
||||
edited(before, "fx:id=\"" + id + "\"");
|
||||
step("Inserted " + type + " into " + destination);
|
||||
}
|
||||
|
||||
private 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);
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
private 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));
|
||||
});
|
||||
}
|
||||
|
||||
private 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");
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -23,7 +23,10 @@ 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")
|
||||
p.add_argument("--connection-form", action="store_true", help="Qualify the Archiver connection form")
|
||||
args = p.parse_args()
|
||||
if args.connection_form and not args.archiver:
|
||||
p.error("--connection-form requires --archiver")
|
||||
if args.repeat < 1:
|
||||
p.error("--repeat must be positive")
|
||||
output = ROOT / "target/ide-workflow"
|
||||
@@ -34,9 +37,11 @@ modes = ("classpath",) if args.archiver else (("classpath", "modulepath") if arg
|
||||
for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode in modes):
|
||||
crashes = NativeCrashGuard(ROOT)
|
||||
launch = subprocess.run([sys.executable, ROOT / "scripts/run-fixture-host.py", "intellij",
|
||||
"--check", *(["--archiver", str(args.archiver.resolve())] if args.archiver else []), "--mode", mode, "--java-home", args.java_home,
|
||||
"--check", *(["--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)
|
||||
@@ -50,6 +55,8 @@ for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode i
|
||||
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))
|
||||
@@ -74,7 +81,7 @@ for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode i
|
||||
shutil.copyfile(base / "intellij.png", output / (mode + ".png"))
|
||||
(evidence / "proof.json").write_text(json.dumps(proof, indent=2) + "\n")
|
||||
finally:
|
||||
for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log", "steps.txt", "target-error.txt", "preview-restored.png"):
|
||||
for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log", "steps.txt", "target-error.txt", "preview-restored.png", "imap.png", "jmap.png", "intellij.png"):
|
||||
if (base / name).exists():
|
||||
shutil.copyfile(base / name, evidence / name)
|
||||
workers = descendant_workers(pid)
|
||||
|
||||
@@ -19,7 +19,10 @@ 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")
|
||||
p.add_argument("--connection-form", action="store_true", help="Open and qualify the Archiver connection form")
|
||||
args = p.parse_args()
|
||||
if args.connection_form and not args.archiver:
|
||||
p.error("--connection-form requires --archiver")
|
||||
base = Path(tempfile.mkdtemp(prefix="neitzel-designer-host-")).resolve()
|
||||
project = base / "project"
|
||||
if args.archiver:
|
||||
@@ -28,7 +31,8 @@ if args.archiver:
|
||||
shutil.copytree(args.archiver, project, ignore=shutil.ignore_patterns(".git", ".idea", "target", ".neitzel-fx-designer"))
|
||||
subprocess.run([sys.executable, ROOT / "scripts/configure-library-example.py", "--project", project,
|
||||
"--target-java-home", args.target_java_home], check=True)
|
||||
file = project / "src/main/resources/de/neitzel/archiver/ui/ArchiveWindow.fxml"
|
||||
view = "ConnectionForm" if args.connection_form else "ArchiveWindow"
|
||||
file = project / f"src/main/resources/de/neitzel/archiver/ui/{view}.fxml"
|
||||
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)
|
||||
@@ -55,16 +59,19 @@ else:
|
||||
jars = [*(args.idea_home / "lib").glob("*.jar"), *(base / "plugins").rglob("*.jar"), *(args.idea_home / "plugins/platform-problemView-plugin").rglob("*.jar")]
|
||||
sources = ROOT / "integration-tests/idea"
|
||||
probe = "ArchiveWorkflowProbe" if args.archiver else "WorkflowProbe"
|
||||
if args.connection_form:
|
||||
probe = "ConnectionWorkflowProbe"
|
||||
files = [sources / "WorkflowProbe.java"]
|
||||
if args.archiver:
|
||||
files.append(sources / "ArchiveWorkflowProbe.java")
|
||||
files.append(sources / f"{probe}.java")
|
||||
target_probe = "ConnectionTargetProbe" if args.connection_form else "ArchiveTargetProbe"
|
||||
agent_classes = base / "agent-classes"
|
||||
agent_classes.mkdir()
|
||||
subprocess.run([args.java_home / "bin/javac", "-cp", os.pathsep.join(map(str,jars)), "-d", agent_classes,
|
||||
sources / "ArchiveTargetProbe.java"], check=True)
|
||||
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", "Manifest-Version: 1.0\nPremain-Class: qualification.ArchiveTargetProbe\n\n")
|
||||
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}"'
|
||||
|
||||
Reference in New Issue
Block a user