diff --git a/fx/README.md b/fx/README.md index 100f6dc..7fb191f 100644 --- a/fx/README.md +++ b/fx/README.md @@ -171,7 +171,7 @@ A direct binding names a control by `fx:id`, a JavaFX property of that control, For `both` and `model`, the write happens when the JavaFX property changes, including each change of a text property. There is no separate save. `view` does not write the attribute. -`BindingList` is the element that holds direct bindings, computed bindings, and repeats. Its default property is `elements`, so the children in FXML are the list. An unknown child fails the load with `Not a binding element:`. The children that apply are a direct binding, a computed binding, and a repeat. +`BindingList` is the element that holds direct bindings, computed bindings, command bindings, and repeats. Its default property is `elements`, so the children in FXML are the list. An unknown child fails the load with `Not a binding element:`. Command bindings require a managed View. When the attribute value is already an `ObservableList`, the control property is set to that same list. Direction and converter are not consulted. The tag binding names `direction="view"` and still shares the list. See [A list of simple values](#a-list-of-simple-values). @@ -266,6 +266,38 @@ A missing method fails the load with `No computed method "` and the method value An `onAction="#method"` handler is ordinary FXML. `addVisit`, `addTag`, `leaveNote`, `leaveWarning`, and `leaveFatal` are handlers. They are separate from the computed binding. +## Commands + +A `Command` combines an availability observable and an action. The ViewModel returns one +stable instance from a public getter. A keyboard shortcut can call `execute()` directly. +The command checks the current availability on every invocation. + +```java +private final Command clear = new Command(documentOpen, editor::clear); + +public Command getClear() { + return clear; +} + +void clearFromKeyboard() { + clear.execute(); +} +``` + +Load the FXML with a `ViewModelContext`. Inside its `BindingList`, add one declaration per +button or menu item. Here both controls use the same `getClear()` command. + +```xml + + +``` + +Import `de.neitzel.fx.view.CommandBinding` and give both controls the corresponding `fx:id`. +The binding owns the control's `disable` and `onAction` properties. Use the command's +availability as the condition for disabling these controls. The managed View detaches +both bindings on close. For dynamically created menu items, keep the registration from +`CommandBindings.bind(item, command)` and close it when discarding the item. + ## Controller Name the class on the root with `fx:controller`. The container creates it with `getComponent`, so it is the cached singleton. `@FXML` fields are filled during load, before the bindings run. diff --git a/fx/src/main/java/de/neitzel/fx/view/BindingList.java b/fx/src/main/java/de/neitzel/fx/view/BindingList.java index 51987a4..daf1e8d 100644 --- a/fx/src/main/java/de/neitzel/fx/view/BindingList.java +++ b/fx/src/main/java/de/neitzel/fx/view/BindingList.java @@ -13,7 +13,7 @@ import java.util.Map; * The list of binding elements declared inside {@code fx:define}. *

* The list is not a scene-graph child. FXML adds each {@link DirectBinding}, - * {@link ComputedBinding}, or {@link Repeat} child to {@link #getElements()}. + * {@link ComputedBinding}, {@link CommandBinding}, or {@link Repeat} child to {@link #getElements()}. */ @DefaultProperty("elements") public class BindingList { @@ -48,6 +48,8 @@ public class BindingList { DirectBindingApplier.apply(namespace, viewModel, directBinding, context, lifetime); } else if (element instanceof ComputedBinding computedBinding) { ComputedBindingApplier.apply(namespace, viewModel, controller, root, computedBinding, lifetime); + } else if (element instanceof CommandBinding commandBinding) { + CommandBindingApplier.apply(namespace, viewModel, commandBinding, lifetime); } else if (element instanceof Repeat repeat) { RepeatApplier.apply(namespace, viewModel, repeat, context, lifetime); } else { diff --git a/fx/src/main/java/de/neitzel/fx/view/Command.java b/fx/src/main/java/de/neitzel/fx/view/Command.java new file mode 100644 index 0000000..b3bf73d --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/Command.java @@ -0,0 +1,39 @@ +package de.neitzel.fx.view; + +import java.util.Objects; +import javafx.beans.value.ObservableBooleanValue; +import lombok.Getter; + +/** + * One action with a live availability rule. Use the command and its availability on the + * JavaFX application thread. + */ +public final class Command { + + /** The availability observed by each control displaying this command. */ + @Getter + private final ObservableBooleanValue canExecute; + + private final Runnable action; + + /** + * Creates a command for one action and execution context. + * + * @param canExecute live availability of the action + * @param action the work to start while the command is available + */ + public Command(ObservableBooleanValue canExecute, Runnable action) { + this.canExecute = Objects.requireNonNull(canExecute); + this.action = Objects.requireNonNull(action); + } + + /** + * Executes the action after checking the current availability, including for keyboard + * shortcuts or callers without an attached control. + */ + public void execute() { + if (canExecute.get()) { + action.run(); + } + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/CommandBinding.java b/fx/src/main/java/de/neitzel/fx/view/CommandBinding.java new file mode 100644 index 0000000..959f69a --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/CommandBinding.java @@ -0,0 +1,16 @@ +package de.neitzel.fx.view; + +import lombok.Getter; +import lombok.Setter; + +/** Connects an FXML button or menu item to a command supplied by its ViewModel. */ +@Getter +@Setter +public final class CommandBinding { + + /** The target control's {@code fx:id}. */ + private String control; + + /** The simple bean property name of the command on the ViewModel. */ + private String path; +} diff --git a/fx/src/main/java/de/neitzel/fx/view/CommandBindingApplier.java b/fx/src/main/java/de/neitzel/fx/view/CommandBindingApplier.java new file mode 100644 index 0000000..7e82347 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/CommandBindingApplier.java @@ -0,0 +1,102 @@ +package de.neitzel.fx.view; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import javafx.fxml.FXMLLoader; +import javafx.scene.control.ButtonBase; +import javafx.scene.control.MenuItem; + +final class CommandBindingApplier { + + private CommandBindingApplier() { + } + + static void validate(List lists, Map namespace) { + var commands = new IdentityHashMap(); + var propertyBindings = new ArrayList(); + for (BindingList list : lists) { + for (Object element : list.getElements()) { + if (element instanceof CommandBinding binding) { + Object control = target(namespace, binding); + if (commands.put(control, binding) != null) { + throw invalid(namespace, binding, "duplicate owner for disable and onAction"); + } + } else if (element instanceof DirectBinding binding) { + addConflict(propertyBindings, namespace, binding.getControl(), binding.getProperty()); + } else if (element instanceof ComputedBinding binding) { + addConflict(propertyBindings, namespace, binding.getControl(), binding.getProperty()); + } + } + } + for (Object control : propertyBindings) { + CommandBinding command = commands.get(control); + if (command != null) { + throw invalid(namespace, command, "another binding owns disable or onAction"); + } + } + } + + private static void addConflict(List targets, Map namespace, + String control, String property) { + if ("disable".equals(property) || "onAction".equals(property)) { + targets.add(namespace.get(control)); + } + } + + static void apply(Map namespace, Object viewModel, CommandBinding binding, + ViewLifetime lifetime) { + if (!lifetime.managed()) { + throw invalid(namespace, binding, "CommandBinding requires a ViewModelContext"); + } + var target = target(namespace, binding); + var command = command(namespace, binding, viewModel); + try { + var registration = target instanceof ButtonBase button + ? CommandBindings.bind(button, command) : CommandBindings.bind((MenuItem) target, command); + lifetime.own(registration::close); + } catch (IllegalArgumentException failure) { + throw invalid(namespace, binding, failure.getMessage()); + } + } + + private static Object target(Map namespace, CommandBinding binding) { + var target = namespace.get(binding.getControl()); + if (target == null) { + throw invalid(namespace, binding, "unknown target fx:id"); + } + if (!(target instanceof ButtonBase) && !(target instanceof MenuItem)) { + throw invalid(namespace, binding, "target must be a ButtonBase or MenuItem"); + } + return target; + } + + private static Command command(Map namespace, CommandBinding binding, Object viewModel) { + var path = binding.getPath(); + if (path == null || path.isBlank() || path.contains(".")) { + throw invalid(namespace, binding, "expected a simple command path"); + } + var getter = "get" + Character.toUpperCase(path.charAt(0)) + path.substring(1); + try { + var value = viewModel.getClass().getMethod(getter).invoke(viewModel); + if (value instanceof Command command) { + return command; + } + throw invalid(namespace, binding, getter + "() must return a Command instance"); + } catch (NoSuchMethodException | IllegalAccessException failure) { + throw invalid(namespace, binding, "missing accessible command getter " + getter + "()"); + } catch (InvocationTargetException failure) { + throw new IllegalArgumentException( + invalid(namespace, binding, "command getter " + getter + "() failed").getMessage(), + failure.getCause()); + } + } + + private static IllegalArgumentException invalid(Map namespace, CommandBinding binding, + String reason) { + return new IllegalArgumentException("Invalid CommandBinding in " + namespace.get(FXMLLoader.LOCATION_KEY) + + " for " + binding.getControl() + " (disable/onAction), path " + binding.getPath() + ": " + reason); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/CommandBindings.java b/fx/src/main/java/de/neitzel/fx/view/CommandBindings.java new file mode 100644 index 0000000..6dbf258 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/CommandBindings.java @@ -0,0 +1,76 @@ +package de.neitzel.fx.view; + +import java.util.Map; +import java.util.Objects; +import javafx.beans.property.BooleanProperty; +import javafx.beans.property.ObjectProperty; +import javafx.beans.value.ChangeListener; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.scene.control.ButtonBase; +import javafx.scene.control.MenuItem; + +/** Attaches reusable commands to JavaFX action controls. */ +public final class CommandBindings { + + private static final Object REGISTRATION_KEY = new Object(); + + private CommandBindings() { + } + + /** A single control's attachment to a command. Close on the JavaFX application thread. */ + @FunctionalInterface + public interface Registration extends AutoCloseable { + /** Removes this attachment. Subsequent calls have no effect. */ + @Override + void close(); + } + + /** + * Attaches the command to a button's action and disable properties. + * + * @param button the action control + * @param command the command to execute + * @return the attachment to close when the control is no longer in use + */ + public static Registration bind(ButtonBase button, Command command) { + return attach(button.getProperties(), button.disableProperty(), button.onActionProperty(), command); + } + + /** + * Attaches the command to a menu item's action and disable properties. + * + * @param item the menu action + * @param command the command to execute + * @return the attachment to close when the menu item is no longer in use + */ + public static Registration bind(MenuItem item, Command command) { + return attach(item.getProperties(), item.disableProperty(), item.onActionProperty(), command); + } + + private static Registration attach(Map properties, BooleanProperty disable, + ObjectProperty> onAction, Command command) { + Objects.requireNonNull(command); + if (properties.containsKey(REGISTRATION_KEY) || disable.isBound()) { + throw new IllegalArgumentException("disable is already bound"); + } + if (onAction.isBound() || onAction.get() != null) { + throw new IllegalArgumentException("onAction already has an owner"); + } + var available = command.getCanExecute(); + ChangeListener update = (observable, before, after) -> disable.set(!after); + EventHandler handler = event -> command.execute(); + disable.set(!available.get()); + onAction.set(handler); + available.addListener(update); + properties.put(REGISTRATION_KEY, handler); + return () -> { + if (properties.remove(REGISTRATION_KEY, handler)) { + available.removeListener(update); + if (onAction.get() == handler && !onAction.isBound()) { + onAction.set(null); + } + } + }; + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/Components.java b/fx/src/main/java/de/neitzel/fx/view/Components.java index 7202550..3366d50 100644 --- a/fx/src/main/java/de/neitzel/fx/view/Components.java +++ b/fx/src/main/java/de/neitzel/fx/view/Components.java @@ -235,6 +235,7 @@ final class Components { hasViewModel.setViewModel(bound); } Parent root = (Parent) component; + CommandBindingApplier.validate(lists, namespace); for (BindingList list : lists) { list.apply(namespace, viewModel, component, root, context, lifetime); } diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java b/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java index 8e2048e..6ada1fb 100644 --- a/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java +++ b/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java @@ -115,6 +115,7 @@ public final class ViewLoader { if (controller instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) { hasViewModel.setViewModel(bound); } + CommandBindingApplier.validate(session.bindingLists(), loader.getNamespace()); for (BindingList bindingList : session.bindingLists()) { bindingList.apply(loader.getNamespace(), viewModel, controller, root, context, lifetime); } diff --git a/fx/src/test/java/de/neitzel/fx/view/BindCommandTest.java b/fx/src/test/java/de/neitzel/fx/view/BindCommandTest.java new file mode 100644 index 0000000..d8cbd65 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/BindCommandTest.java @@ -0,0 +1,111 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.view.command.CommandController; +import de.neitzel.injection.ApplicationContext; +import java.nio.file.Files; +import java.nio.file.Path; +import javafx.scene.control.Button; +import javafx.scene.control.MenuBar; +import javafx.scene.control.MenuItem; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BindCommandTest { + + @TempDir + Path directory; + + @BeforeAll + static void start() throws InterruptedException { + FxThread.start(); + } + + @Test + void connectsOneCommandToButtonMenuAndKeyboardUntilClosed() throws Exception { + var url = view("commands.fxml", """ + + + """); + FxThread.onFx(() -> { + try (var models = new ViewModelContext()) { + var view = ViewLoader.load(url, new CommandController.Subject(), services(), models); + var model = (CommandController.Model) view.getViewModel(); + var button = (Button) view.getRoot().lookup("#button"); + var menu = ((MenuBar) view.getRoot().lookup("#menu")).getMenus().getFirst(); + var item = menu.getItems().getFirst(); + var dynamic = new MenuItem(); + try (var registration = CommandBindings.bind(dynamic, model.getClear())) { + assertTrue(button.isDisable()); + assertTrue(item.isDisable()); + item.fire(); + model.getClear().execute(); + assertEquals(0, model.getCalls()); + + model.getEnabled().set(true); + assertFalse(button.isDisable()); + assertFalse(item.isDisable()); + button.fire(); + item.fire(); + model.getClear().execute(); + dynamic.fire(); + assertEquals(4, model.getCalls()); + } + dynamic.fire(); + assertEquals(4, model.getCalls()); + + view.close(); + assertNull(button.getOnAction()); + assertNull(item.getOnAction()); + model.getEnabled().set(false); + assertFalse(button.isDisable()); + assertFalse(item.isDisable()); + } + }); + } + + @Test + void rejectsUnknownTargetsAndConflictingOwners() throws Exception { + var scenarios = new String[][] { + {"", "unknown"}, + {"", "unknown"}, + {"", "ButtonBase or MenuItem"}, + {"", "duplicate"}, + {"", "disable"} + }; + for (var scenario : scenarios) { + var url = view("invalid-command.fxml", scenario[0]); + FxThread.onFx(() -> { + try (var models = new ViewModelContext()) { + var failure = assertThrows(IllegalArgumentException.class, + () -> ViewLoader.load(url, new CommandController.Subject(), services(), models)); + assertTrue(failure.getMessage().contains("invalid-command.fxml")); + assertTrue(failure.getMessage().contains(scenario[1])); + } + }); + } + } + + private ApplicationContext services() { + return new ApplicationContext("de.neitzel.fx.view.command"); + } + + private java.net.URL view(String name, String bindings) throws Exception { + return Files.writeString(directory.resolve(name), """ + + + + + %s +