Edit and exercise Archiver CommandBindings in the IntelliJ designer

This commit is contained in:
2026-11-24 14:42:35 +01:00
parent 54e202014e
commit 98d37c6c3d
38 changed files with 1304 additions and 190 deletions
@@ -1,7 +1,7 @@
package de.neitzel.fxdesigner.target;
import de.neitzel.fxdesigner.protocol.BindingMetadata.*;
import de.neitzel.fxdesigner.protocol.BindingMetadata;
import de.neitzel.fxdesigner.protocol.BindingMetadata.*;
import java.beans.*;
import java.io.*;
import java.lang.reflect.*;
@@ -28,6 +28,7 @@ public final class BindingDiscovery {
private record TargetType(Class<?> type, boolean writable) {}
private final Set<String> actionHandlers = new HashSet<>();
private final Map<String, Class<?>> controlTypes = new HashMap<>();
private RepeatDiscovery repeats;
private final Map<String, TargetType> targetTypes = new HashMap<>();
@@ -313,6 +314,10 @@ public final class BindingDiscovery {
? owner.controller
: resolve(e, imports);
controlTypes.put(id, control);
if (e.hasAttribute("onAction")) actionHandlers.add(id);
for (Node child = e.getFirstChild(); child != null; child = child.getNextSibling())
if (child instanceof Element property && property.getTagName().equals("onAction"))
actionHandlers.add(id);
String componentModel = "";
var componentResource = control.getResource(control.getSimpleName() + ".fxml");
if (componentResource != null)
@@ -398,7 +403,8 @@ public final class BindingDiscovery {
: converters.candidates(source, chosen == null ? null : chosen.type(), direction);
repeats = new RepeatDiscovery(loader, attributes, owner, incompleteModel, controlTypes, ids);
var tables = new TableDiscovery(loader, repeats, modelType, owner);
var problems = new ArrayList<>(validate(doc, imports, ids, converters));
var commands = commandPaths();
var problems = new ArrayList<>(validate(doc, imports, ids, converters, commands));
problems.addAll(tables.validate(doc));
var componentOptions = repeats.candidates(selected);
for (var a : attributes)
@@ -421,7 +427,35 @@ public final class BindingDiscovery {
repeats.panes(),
tables.collections(),
tables.rows(selected),
tables.columns(selected));
tables.columns(selected),
commands,
controlTypes.entrySet().stream()
.filter(e -> commandTarget(e.getValue()))
.map(Map.Entry::getKey)
.sorted()
.toList());
}
private List<String> commandPaths() {
if (owner.viewModel == null) return List.of();
return Arrays.stream(owner.viewModel.getMethods())
.filter(
m ->
!Modifier.isStatic(m.getModifiers())
&& m.getParameterCount() == 0
&& m.getName().startsWith("get")
&& m.getName().length() > 3
&& de.neitzel.fx.view.Command.class.isAssignableFrom(m.getReturnType()))
.map(m -> java.beans.Introspector.decapitalize(m.getName().substring(3)))
.distinct()
.sorted()
.toList();
}
private static boolean commandTarget(Class<?> type) {
return type != null
&& (javafx.scene.control.ButtonBase.class.isAssignableFrom(type)
|| javafx.scene.control.MenuItem.class.isAssignableFrom(type));
}
private void selectOwner(Document doc, List<String> imports, String resource, Class<?> model)
@@ -492,17 +526,31 @@ public final class BindingDiscovery {
.anyMatch(a -> a.path().equals(path) && Set.of("COMPLEX", "COLLECTION").contains(a.kind()));
}
private static String propertyValue(Element declaration, String name) {
if (declaration.hasAttribute(name)) return declaration.getAttribute(name);
for (Node n = declaration.getFirstChild(); n != null; n = n.getNextSibling())
if (n instanceof Element child && child.getTagName().equals(name))
return child.getTextContent().trim();
return "";
}
private List<Problem> validate(
Document doc, List<String> imports, Set<String> ids, ConverterDiscovery converters)
Document doc,
List<String> imports,
Set<String> ids,
ConverterDiscovery converters,
List<String> commands)
throws Exception {
var problems = new ArrayList<Problem>(selectionProblems);
problems.addAll(owner.problems);
var occupied = new HashSet<String>();
var commandControls = new TreeSet<String>();
var nodes = doc.getElementsByTagName("*");
for (int i = 0; i < nodes.getLength(); i++) {
var e = (Element) nodes.item(i);
if (!library(e, "DirectBinding", imports)
&& !library(e, "ComputedBinding", imports)
&& !library(e, "CommandBinding", imports)
&& !library(e, "Repeat", imports)) continue;
Node parent = e.getParentNode();
if (parent instanceof Element p && p.getTagName().equals("elements"))
@@ -529,9 +577,39 @@ public final class BindingDiscovery {
}
continue;
}
String control = e.getAttribute("control"),
property = e.getAttribute("property"),
String control = propertyValue(e, "control"),
property = propertyValue(e, "property"),
key = control + "." + property;
if (library(e, "CommandBinding", imports)) {
String path = propertyValue(e, "path");
if (!ids.contains(control))
problems.add(
new Problem(control, "command", "ERROR", "Unknown Command target fx:id: " + control));
else if (!commandTarget(controlTypes.get(control)))
problems.add(
new Problem(
control,
"command",
"ERROR",
"Command target must be a ButtonBase or MenuItem: " + control));
if (path.isBlank() || path.contains("."))
problems.add(
new Problem(control, "command", "ERROR", "Expected a simple Command path: " + path));
else if (!commands.contains(path))
problems.add(new Problem(control, "command", "ERROR", "Unknown Command path: " + path));
if (!commandControls.add(control))
problems.add(
new Problem(
control,
"command",
"ERROR",
"Duplicate Command binding for disable and onAction"));
if (actionHandlers.contains(control))
problems.add(
new Problem(
control, "command", "ERROR", "Command conflicts with existing onAction handler"));
continue;
}
if (!occupied.add(key))
problems.add(new Problem(control, property, "ERROR", "Duplicate binding target"));
@@ -624,6 +702,15 @@ public final class BindingDiscovery {
}
if (!severity.isEmpty()) problems.add(new Problem(control, property, severity, message));
}
for (String control : commandControls)
for (String endpoint : List.of("disable", "onAction"))
if (occupied.contains(control + "." + endpoint))
problems.add(
new Problem(
control,
"command",
"ERROR",
"Command conflicts with another binding for " + endpoint));
return problems;
}
@@ -12,13 +12,12 @@ import javafx.scene.*;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
/**
* One preview session per target JVM: the library retains process-wide Model/ViewModel identities.
*/
/** A worker owns one preview session and its managed Views. */
public final class TargetPreview implements AutoCloseable {
private static final AtomicBoolean CONSUMED = new AtomicBoolean();
private PreviewSession<?, ?> session;
private LoadedView view;
private final ViewModelContext models = new ViewModelContext();
private Scene scene;
private final Occurrences occurrences = new Occurrences();
private javafx.stage.Stage interactive;
@@ -128,31 +127,9 @@ public final class TargetPreview implements AutoCloseable {
if (component) {
String name =
d.viewResource().substring(0, d.viewResource().length() - 5).replace('/', '.');
Class<?> componentType = Class.forName(name, false, loader);
if (!Parent.class.isAssignableFrom(componentType))
throw new IllegalArgumentException("Component root is not a Parent");
byte[] wrapper = ("<" + name + "/>").getBytes(java.nio.charset.StandardCharsets.UTF_8);
var wrapped =
new java.net.URL(
null,
"memory:component",
new java.net.URLStreamHandler() {
protected java.net.URLConnection openConnection(java.net.URL url) {
return new java.net.URLConnection(url) {
public void connect() {}
public java.io.InputStream getInputStream() {
return new java.io.ByteArrayInputStream(wrapper);
}
};
}
});
view = ViewLoader.load(wrapped, session.model(), context);
var model = componentType.getMethod("modelProperty").invoke(view.getRoot());
if (!(model instanceof javafx.beans.property.Property property))
throw new IllegalArgumentException("Component has no writable Model");
property.setValue(session.model());
} else view = ViewLoader.load(resource, session.model(), context);
var componentType = Class.forName(name, false, loader).asSubclass(Parent.class);
view = ViewLoader.loadComponent(componentType, session.model(), context, models);
} else view = ViewLoader.load(resource, session.model(), context, models);
scene = new Scene(view.getRoot(), 420, 240);
layout(420, 240);
var wait = session.ready();
@@ -316,7 +293,9 @@ public final class TargetPreview implements AutoCloseable {
closed = true;
timer.shutdownNow();
try {
if (session != null) session.close();
try (var ownedSession = session) {
models.close();
}
cleanup.complete(null);
} catch (Throwable e) {
if (failure != null) failure.addSuppressed(e);
@@ -112,6 +112,67 @@ class BindingDiscoveryTest {
() -> BindingDiscovery.inspect(fxml(), "", "wrong", getClass().getClassLoader()));
}
@de.neitzel.fx.view.ViewModelClass(Commands.class)
public static class Controller {}
public static class Commands {
public Commands(Model model) {
throw new AssertionError("Discovery constructed the ViewModel");
}
public de.neitzel.fx.view.Command getOpen() {
throw new AssertionError("Discovery executed the Command getter");
}
}
@Test
void commandDiscoveryResolvesTargetsAndLocatesConflictsInEitherOrder() throws Exception {
String command = "<CommandBinding control='menu' path='open'/>";
String xml =
"<?neitzel-model "
+ Model.class.getName()
+ "?><?import javafx.scene.layout.*?>"
+ "<?import javafx.scene.control.*?><?import de.neitzel.fx.view.*?>"
+ "<VBox xmlns:fx='http://javafx.com/fxml/1' fx:controller='"
+ Controller.class.getName()
+ "'>"
+ "<fx:define><BindingList>"
+ command
+ "<CommandBinding control='go'"
+ " path='open'/></BindingList></fx:define><MenuButton><items><MenuItem"
+ " fx:id='menu'/></items></MenuButton><Button fx:id='go'/><Label"
+ " fx:id='label'/></VBox>";
var valid = BindingDiscovery.inspect(xml, "", "view", getClass().getClassLoader());
assertEquals(List.of("open"), valid.commandPaths());
assertEquals(List.of("go", "menu"), valid.commandTargets());
assertTrue(
valid.problems().stream().noneMatch(p -> p.severity().equals("ERROR")),
valid.problems().toString());
for (var invalid :
List.of(
xml.replace(
command,
command
+ "<DirectBinding control='menu' property='disable' path='name'"
+ " direction='view'/>"),
xml.replace(
command,
"<ComputedBinding control='menu' property='onAction' method='#existing'/>"
+ command),
xml.replace(command, command + command),
xml.replace("fx:id='menu'", "fx:id='menu' onAction='#existing'"),
xml.replace("control='menu'", "control='missing'"),
xml.replace("control='menu'", "control='label'"),
xml.replace("path='open'", "path='sub.open'"),
xml.replace("path='open'", "path='missing'"))) {
var report = BindingDiscovery.inspect(invalid, "", "view", getClass().getClassLoader());
assertTrue(
report.problems().stream()
.anyMatch(p -> p.severity().equals("ERROR") && p.property().equals("command")),
report.problems().toString());
}
}
public static class NumberModel {
public Number getAmount() {
return null;