Edit form controls and render localized application previews in the IntelliJ designer
This commit is contained in:
@@ -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>"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user