Bind reusable commands to JavaFX action controls
This commit is contained in:
@@ -13,7 +13,7 @@ import java.util.Map;
|
||||
* The list of binding elements declared inside {@code fx:define}.
|
||||
* <p>
|
||||
* 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 {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<BindingList> lists, Map<String, Object> namespace) {
|
||||
var commands = new IdentityHashMap<Object, CommandBinding>();
|
||||
var propertyBindings = new ArrayList<Object>();
|
||||
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<Object> targets, Map<String, Object> namespace,
|
||||
String control, String property) {
|
||||
if ("disable".equals(property) || "onAction".equals(property)) {
|
||||
targets.add(namespace.get(control));
|
||||
}
|
||||
}
|
||||
|
||||
static void apply(Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Object, Object> properties, BooleanProperty disable,
|
||||
ObjectProperty<EventHandler<ActionEvent>> 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<Boolean> update = (observable, before, after) -> disable.set(!after);
|
||||
EventHandler<ActionEvent> 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);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user