diff --git a/README.md b/README.md
index 959972b..ec5a637 100644
--- a/README.md
+++ b/README.md
@@ -84,7 +84,7 @@ The [complete quick start](fx/docs/quick-start.md) includes local installation,
Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven 3.9.11 or later. Surefire fails the build if tests fail.
-## Changes in 1.0.3
+## Changes in 1.0.5
- Show or hide DataGrid columns from the header checklist or context menu while retaining column order and widths.
- Observe column visibility changes from applications that store their own view preferences.
@@ -99,7 +99,7 @@ Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven
## Use a release from Maven
-To use release `1.0.3`, add the Gitea registry to the consuming project's POM and use the release
+To use release `1.0.5`, add the Gitea registry to the consuming project's POM and use the release
version for the module you need:
```xml
@@ -114,7 +114,7 @@ version for the module you need:
de.neitzel.libfx
- 1.0.3
+ 1.0.5
```
diff --git a/core/pom.xml b/core/pom.xml
index 5b1d9ca..307056d 100644
--- a/core/pom.xml
+++ b/core/pom.xml
@@ -7,7 +7,7 @@
de.neitzel.libneitzellib
- 1.0.3
+ 1.0.5core
diff --git a/data-grid-jdbc/pom.xml b/data-grid-jdbc/pom.xml
index 32eb9fd..4dbba00 100644
--- a/data-grid-jdbc/pom.xml
+++ b/data-grid-jdbc/pom.xml
@@ -1,5 +1,5 @@
-4.0.0de.neitzel.libneitzellib1.0.3
+4.0.0de.neitzel.libneitzellib1.0.5data-grid-jdbcOptional mapped JDBC grid sourcede.neitzel.libdata-grid${project.version}com.h2databaseh22.5.252test
diff --git a/data-grid/pom.xml b/data-grid/pom.xml
index a775e80..3a5d9ba 100644
--- a/data-grid/pom.xml
+++ b/data-grid/pom.xml
@@ -1,6 +1,6 @@
4.0.0
- de.neitzel.libneitzellib1.0.3
+ de.neitzel.libneitzellib1.0.5data-gridToolkit-independent filter, query and grid setup contracts
diff --git a/encryption/pom.xml b/encryption/pom.xml
index 38e73df..f60cdab 100644
--- a/encryption/pom.xml
+++ b/encryption/pom.xml
@@ -7,7 +7,7 @@
de.neitzel.libneitzellib
- 1.0.3
+ 1.0.5encryption
diff --git a/fx-example/README.md b/fx-example/README.md
index 334c045..51d02fd 100644
--- a/fx-example/README.md
+++ b/fx-example/README.md
@@ -30,12 +30,12 @@ From the NeitzelLib root with JDK 25:
./mvnw -f fx-example/pom.xml javafx:run
```
-The first command installs local `1.0.3` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
+The first command installs local `1.0.5` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
The packaged alternative, after `package` or `install`, is:
```bash
-java -jar fx-example/target/fx-example-1.0.3.jar
+java -jar fx-example/target/fx-example-1.0.5.jar
```
Keep the adjacent `target/libs` directory with the JAR: the manifest refers to those copied runtime dependencies. A desktop session is required. This example has no `module-info.java`; it is a classpath application.
diff --git a/fx-example/docs/product-grid.md b/fx-example/docs/product-grid.md
index 313a388..96bd5d4 100644
--- a/fx-example/docs/product-grid.md
+++ b/fx-example/docs/product-grid.md
@@ -6,7 +6,7 @@ From the repository root with JDK 25, build without installing runtime artifacts
```sh
./mvnw -pl fx-example -am package -DskipTests
-java -cp 'fx-example/target/fx-example-1.0.3.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
+java -cp 'fx-example/target/fx-example-1.0.5.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
```
The default catalog has 10,000 products. Both backends use identical stable IDs, names, categories, quantities and DECIMAL(12,2) prices. Fixtures include duplicate sort values, nulls, empty text, mixed case, Unicode, apostrophes and literal SQL wildcard characters. One `ProductCatalog` service maintains original text and Locale.ROOT comparison keys together on insertion/reset. Mutations run on application workers and explicitly refresh the grid; browsing is read-only.
diff --git a/fx-example/docs/theme-gallery.md b/fx-example/docs/theme-gallery.md
index d309220..a12a31b 100644
--- a/fx-example/docs/theme-gallery.md
+++ b/fx-example/docs/theme-gallery.md
@@ -5,7 +5,7 @@
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
```sh
-java -cp 'fx-example/target/fx-example-1.0.3.jar:fx-example/target/libs/*' \
+java -cp 'fx-example/target/fx-example-1.0.5.jar:fx-example/target/libs/*' \
de.neitzel.fx.example.theme.ThemeGalleryMain
```
diff --git a/fx-example/pom.xml b/fx-example/pom.xml
index 38f5e35..709eea5 100644
--- a/fx-example/pom.xml
+++ b/fx-example/pom.xml
@@ -7,7 +7,7 @@
de.neitzel.libneitzellib
- 1.0.3
+ 1.0.5fx-example
diff --git a/fx/README.md b/fx/README.md
index f5597db..acf22ce 100644
--- a/fx/README.md
+++ b/fx/README.md
@@ -56,7 +56,7 @@ These are the versions configured by this source snapshot, not a promise of comp
| --- | --- | --- |
| JDK | Java 25 | Select a matching JDK for compilation and launch |
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
-| Library | `de.neitzel.lib:fx:1.0.3` | Use the Gitea Maven registry or install the local reactor |
+| Library | `de.neitzel.lib:fx:1.0.5` | Use the Gitea Maven registry or install the local reactor |
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
| JavaFX | 27.0.1: base, graphics, controls, FXML and web | Resolved transitively; deployment still needs platform-native artifacts |
| Saved HTML | jsoup 1.23.2, ph-css 8.2.3, TwelveMonkeys WebP 3.15.3 | Resolved transitively by `fx`; no separate application setup |
@@ -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).
@@ -185,6 +185,21 @@ A binding that names no such control fails with `No control "` and the id. A mis
| `view` | Shows the attribute and follows later changes of the JavaFX property. Edits to the control stay on the control. |
| `model` | Shows the current value, writes the attribute when the control changes, and leaves the control where it is when the attribute changes later. |
+For `view`, a public `xxxProperty()` accessor on the ViewModel or its replacement can
+return an `ObservableValue`, such as a `ReadOnlyStringProperty` or a `BooleanBinding`.
+The value is read once at load and then followed as the observable changes. For a computed
+value, declare its dependencies in JavaFX. The example connects the derived
+`saveDisabledProperty()` to a button.
+
+```xml
+
+```
+
+`both` and `model` require an accessor that exposes a writable `Property`. The error for
+a read-only source gives the path, target control and property, and FXML resource.
+`ViewModel.property(name)` and `LoadedView.property(name)` continue to look up writable
+properties.
+
The desk puts all three on `name`. The name field is `both`. Shown name (`nameEcho`) is `view`: typing there leaves `Person.name` and the name field unchanged, and typing in the name field updates the echo. Name draft (`nameDraft`) is `model`: it opens as `Ada Lovelace`, stays there while the name field changes, and typing in the draft writes `Person.name` and updates the name field and the echo.
Always specify `direction`: it has no default. A non-null value other than `view`, `model`, or `both` fails the load with `Not a direction:`. Omitting it can currently fail with a `NullPointerException` during binding application. The ObservableList shortcut described above bypasses direction handling; do not rely on that shortcut to omit the declaration.
@@ -193,7 +208,7 @@ For a complex last segment the control receives the model instance behind the vi
## Paths
-A path is attribute names separated by `.`. One name is an attribute of this view's view model, or `latestMessage`, or a `nameProperty()` on the view model. Earlier names must be complex attributes. The direction applies to the last name.
+A path is attribute names separated by `.`. The last name resolves to an attribute, `latestMessage`, or a `nameProperty()` accessor. Earlier names must be complex attributes. The direction applies to the last name.
`home.street` on the home street label steps through the home view model, and `view` applies to `street`. When a complex attribute along the path is null, that binding is left unapplied and both sides keep their current values. The load still succeeds.
@@ -201,7 +216,7 @@ The path is resolved when the binding is applied. A binding whose last segment i
A list is not indexed in a path. Repeat a component, place a table, or hand a list of simple values to a control.
-A path that is not a read-write attribute fails the load with `No read-write attribute for path "` and the path. `Object.getClass` is not an attribute, and a getter without a setter is not one either.
+An unresolved path fails the load with `No read-write attribute for path "` and the path. `Object.getClass` is not an attribute, and a getter without a setter is not one either.
## Converter
@@ -251,6 +266,93 @@ 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.
+
+### Asynchronous Commands
+
+Use `AsyncCommand` when a Command starts a JavaFX `Task`. The application supplies
+an executor and a factory for a fresh Task on each execution. Use `getCommand()` from the
+ViewModel's public getter, or from a keyboard handler or a dynamic menu. Availability combines
+the application rule with the state of the current execution. The worker slot is occupied before
+the executor receives the Task. Failures from the factory, executor, and worker appear in
+`stateProperty()` alongside progress and the Task message. A terminal observation has
+`running() == false`, so a completion listener can retry or close the host.
+
+Pass `true` as the last constructor argument for a Task that supports cancellation. Call
+`cancel()` to cancel it and let the worker finish any cooperative cleanup. The worker slot
+becomes available again when the worker exits. Closing an `AsyncCommand` detaches its Task
+listeners and disables future invocations. Call `cancel()` before closing if the View explicitly
+owns the work and should cancel it.
+
+A dialog's generated button has its own standard close handler. In the following example,
+`valid` is the form's observable validity, `executor` runs background tasks, and
+`createSaveTask` supplies a fresh `Task`. Filter the action, and close the dialog only
+after success. In the failure branch, the user can correct the form and retry.
+
+```java
+var dialog = new Dialog();
+var save = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE);
+dialog.getDialogPane().getButtonTypes().setAll(save, ButtonType.CANCEL);
+dialog.setResultConverter(button -> false);
+var saveButton = dialog.getDialogPane().lookupButton(save);
+try (var saving = new AsyncCommand(valid, executor, createSaveTask)) {
+ saveButton.disableProperty().bind(Bindings.not(saving.getCommand().getCanExecute()));
+ EventHandler saveAction = event -> {
+ event.consume();
+ saving.getCommand().execute();
+ };
+ saveButton.addEventFilter(ActionEvent.ACTION, saveAction);
+ dialog.setOnCloseRequest(event -> {
+ if (saving.getState().running()) event.consume();
+ });
+ try {
+ saving.stateProperty().addListener((source, previous, state) -> {
+ if (state.phase() == AsyncCommand.Phase.SUCCEEDED) {
+ dialog.setResult(true);
+ dialog.close();
+ } else if (state.phase() == AsyncCommand.Phase.FAILED) {
+ dialog.getDialogPane().setHeaderText(state.error().getMessage());
+ }
+ });
+ dialog.showAndWait();
+ } finally {
+ saveButton.removeEventFilter(ActionEvent.ACTION, saveAction);
+ saveButton.disableProperty().unbind();
+ dialog.setOnCloseRequest(null);
+ }
+}
+```
+
## 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.
@@ -433,6 +535,32 @@ Other load failures, all `IllegalArgumentException`:
These style classes are on the nodes: `table`, `column-header-row`, `table-scroll`, `table-header-scroll`, `column-header`, `column-cell`, `column-resize`, `column-opener`, `sort-mark`, `selected`, `column-popup`, `column-search`, `column-select-all`, `column-comparison-operator`, `column-comparison-value`, and `filtered` on an opener whose column has an active filter.
+### Managed Views and Model contexts
+
+Use the four-argument loader when a window, dialog or dockable owns a View:
+
+```java
+try (var models = new ViewModelContext();
+ var loaded = ViewLoader.load(fxml, model, application, models)) {
+ // Use loaded.getRoot() while this View is open.
+}
+```
+
+In a GUI host, retain the handles until the real close event. A drag between docking groups
+keeps the same View open. Close an individual `LoadedView` to remove its bindings, including
+those on components and collection rows. Close its `ViewModelContext` once the owning
+window or archive ends. The context closes remaining Views and releases the Model-to-ViewModel
+registrations. Views of the same model instance in one context share a ViewModel.
+
+The managed loader creates a fresh injected Controller or Component for each instance.
+Dependencies still come from the application context. Controllers and Components can
+implement `AutoCloseable` to release additional resources such as programmatic event handlers
+or subscriptions to application services. The library also closes these resources if FXML or
+binding setup throws. Use these handles on the FX application thread.
+
+The three-argument loader keeps its existing shared cache and Controller behavior. Manage a
+View with the four-argument loader if it needs deterministic cleanup.
+
### Column width
A column with no `width` shares the table width with the other open columns. A `width` is the starting width, and not below the header text. The text minimum is the header text's layout width, rounded up, plus 8. The desk's Street column opens at 300 and Visited at 120. City names no width, so it receives what remains of the table's 496, which is 76.
@@ -541,7 +669,8 @@ These are the `IllegalArgumentException` messages a document can produce. The vi
| `No control "` | `fx:id` is missing |
| `No property ` | the control has no such JavaFX property |
| `Not a direction:` | an explicitly supplied direction is not `view`, `model`, or `both`; an omitted direction can instead cause `NullPointerException` |
-| `No read-write attribute for path "` | the path is not an attribute |
+| `No read-write attribute for path "` | the path did not resolve to an attribute or a named observable |
+| `Read-only source for path` | use `view` to read an observable source |
| `Not a binding element:` | a child of `BindingList` is not a direct binding, a computed binding, or a repeat |
| `No converter ` / `Not a converter:` | the converter class is missing or does not implement `Converter` |
| `No controller for ` / `No computed method "` | a computed binding has no controller or no such method |
diff --git a/fx/docs/data-grid.md b/fx/docs/data-grid.md
index 46fac83..2dd89c9 100644
--- a/fx/docs/data-grid.md
+++ b/fx/docs/data-grid.md
@@ -36,6 +36,27 @@ Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` fo
- A successfully replaced source clears all selection. `confirmedDeleted(key)` removes only that key and refreshes; absence from a page alone does not imply deletion. Collapsed groups retain their keys but expose no actionable elements for hidden rows.
- Empty results disable navigation. Unknown totals are displayed as unknown and disable Last. A disappeared page receives one bounded correction; subsequent invalidation becomes an error with Retry.
+## Selection in a ViewModel
+
+Use `grid.observeSelection()` for a single read-only property containing both selected keys and available elements. The initial snapshot reflects the current grid. Each subsequent snapshot captures both lists after selection or row availability changes. Keys follow selection order and elements follow display order. A selected key can remain present while its row is unavailable. An action that needs every selected row can compare the two list sizes in one snapshot before capturing that snapshot for confirmation.
+
+For example, a ViewModel can derive a label from the adapter.
+
+```java
+var selection = grid.observeSelection();
+var summary = selection.selectionProperty().map(state ->
+ state.selectedKeys().size() + " selected, "
+ + state.selectedElements().size() + " visible");
+```
+
+Expose the result through a public `ObservableValue summaryProperty()` on the ViewModel and declare the label binding.
+
+```xml
+
+```
+
+Restore keys explicitly with `selection.selectKeys(savedKeys)` or restore one with `selection.select(key)`. The adapter delegates to the grid and respects its selection mode. The owner closes the adapter on the JavaFX thread when the ViewModel stops observing. Closing detaches the adapter and freezes its last snapshot while the grid and other observers continue to work independently. See the [FXML integration test](../src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java).
+
## Guards, warnings and supersession
`setEditGuard(query -> CompletionStage)` lets the application save/discard/block unfinished edits. `setAllConfirmation((query, count) -> CompletionStage)` can replace the default nonblocking Continue/Cancel alert. Neither dialog handling nor guard completion runs inside a source transaction. Superseded answers cannot publish or restart old requests.
diff --git a/fx/docs/quick-start.md b/fx/docs/quick-start.md
index ce1ac65..bae97a4 100644
--- a/fx/docs/quick-start.md
+++ b/fx/docs/quick-start.md
@@ -1,13 +1,13 @@
# Your first JavaFX application
-This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.3. The source build below uses the matching release tag.
+This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.5. The source build below uses the matching release tag.
## Prepare the library
Install a JDK 25. Use the library's Maven wrapper (3.9.11), or a separate Maven installation version 3.9.11 or newer. Check `java -version` and `./mvnw -version` before building; on macOS, select the JDK with `export JAVA_HOME=$(/usr/libexec/java_home -v 25)` if necessary.
```bash
-git clone --branch v1.0.3 https://gitea.neitzel.de/konrad/NeitzelLib.git
+git clone --branch v1.0.5 https://gitea.neitzel.de/konrad/NeitzelLib.git
cd NeitzelLib
./mvnw -pl fx-example -am install
./mvnw -f fx-example/pom.xml javafx:run
@@ -66,7 +66,7 @@ hello-fx/
de.neitzel.libfx
- 1.0.3
+ 1.0.5org.slf4j
@@ -190,7 +190,7 @@ For a named-module application, see the [module and lifecycle notes](architectur
| Symptom | Check |
| --- | --- |
-| Maven cannot resolve `de.neitzel.lib:fx:1.0.3` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
+| Maven cannot resolve `de.neitzel.lib:fx:1.0.5` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
| `No plugin found for prefix 'javafx'` | Invoke the example POM directly, or use the complete application POM above. Do not invoke the goal on the library reactor parent. |
| JavaFX runtime/native library failure | Check the JDK version, architecture and JavaFX dependencies actually resolved; avoid mixing native artifacts from different platforms or JavaFX versions. |
| `getResource(...)` returns null | The FXML belongs under `src/main/resources` in the matching package; verify it was copied to `target/classes`. Resource names are case-sensitive. |
diff --git a/fx/pom.xml b/fx/pom.xml
index aad068a..a1d582e 100644
--- a/fx/pom.xml
+++ b/fx/pom.xml
@@ -7,7 +7,7 @@
de.neitzel.libneitzellib
- 1.0.3
+ 1.0.5fx
diff --git a/fx/src/main/java/de/neitzel/fx/view/AsyncCommand.java b/fx/src/main/java/de/neitzel/fx/view/AsyncCommand.java
new file mode 100644
index 0000000..f169c58
--- /dev/null
+++ b/fx/src/main/java/de/neitzel/fx/view/AsyncCommand.java
@@ -0,0 +1,205 @@
+package de.neitzel.fx.view;
+
+import java.util.Objects;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Supplier;
+import javafx.application.Platform;
+import javafx.beans.InvalidationListener;
+import javafx.beans.binding.Bindings;
+import javafx.beans.property.ReadOnlyObjectProperty;
+import javafx.beans.property.ReadOnlyObjectWrapper;
+import javafx.beans.value.ChangeListener;
+import javafx.beans.value.ObservableBooleanValue;
+import javafx.concurrent.Task;
+import javafx.concurrent.Worker;
+import lombok.Getter;
+
+/**
+ * A Command that runs one JavaFX Task at a time on a caller-provided executor.
+ * Create and use it, including its Command and state, on the JavaFX application thread.
+ */
+public final class AsyncCommand implements AutoCloseable {
+
+ /** The execution phase reported to the View. */
+ public enum Phase { IDLE, RUNNING, SUCCEEDED, FAILED, CANCELLED, CLOSED }
+
+ /**
+ * One observation of an execution, published on the FX application thread.
+ *
+ * @param phase execution phase
+ * @param result value from a successful execution
+ * @param error failure from task creation, scheduling or execution
+ * @param progress progress in the range 0 to 1, or -1 for indeterminate work
+ * @param message current task message
+ * @param result type
+ */
+ public record State(Phase phase, T result, Throwable error, double progress, String message) {
+
+ /** Returns whether an execution occupies this Command's worker slot. */
+ public boolean running() {
+ return phase == Phase.RUNNING;
+ }
+
+ private static State of(Phase phase) {
+ return new State<>(phase, null, null, -1, "");
+ }
+ }
+
+ /** The Command shared by controls, FXML bindings and keyboard actions. */
+ @Getter
+ private final Command command;
+ private final ReadOnlyObjectWrapper> state = new ReadOnlyObjectWrapper<>(State.of(Phase.IDLE));
+ private final Executor executor;
+ private final Supplier extends Task> tasks;
+ private final boolean cancellable;
+ private Execution current;
+
+ /**
+ * Creates a command with no user cancellation.
+ *
+ * @param available the application's availability rule
+ * @param executor the executor that runs tasks outside the FX application thread
+ * @param tasks factory invoked on the FX application thread to supply a fresh, ready task
+ */
+ public AsyncCommand(ObservableBooleanValue available, Executor executor, Supplier extends Task> tasks) {
+ this(available, executor, tasks, false);
+ }
+
+ /**
+ * Creates a command with optional cancellation. A cancellable Task must cooperate with
+ * interruption and implement any application-specific rollback in its worker.
+ *
+ * @param available the application's availability rule
+ * @param executor the executor that runs tasks outside the FX application thread
+ * @param tasks factory invoked on the FX application thread to supply a fresh, ready task
+ * @param cancellable whether {@link #cancel()} may cancel a running execution
+ */
+ public AsyncCommand(ObservableBooleanValue available, Executor executor, Supplier extends Task> tasks,
+ boolean cancellable) {
+ Objects.requireNonNull(available);
+ this.executor = Objects.requireNonNull(executor);
+ this.tasks = Objects.requireNonNull(tasks);
+ this.cancellable = cancellable;
+ var canStart = Bindings.createBooleanBinding(() -> available.get() && !state.get().running()
+ && state.get().phase() != Phase.CLOSED, available, state);
+ command = new Command(canStart, this::start);
+ }
+
+ /** Returns the current observation of the command. */
+ public State getState() {
+ return state.get();
+ }
+
+ /** Returns a read-only property for observing progress and completion together. */
+ public ReadOnlyObjectProperty> stateProperty() {
+ return state.getReadOnlyProperty();
+ }
+
+ /**
+ * Requests cancellation if this Command allows it. The worker slot stays occupied until
+ * the Task's worker has left, including when it needs time to handle interruption.
+ *
+ * @return whether a cancellation request was accepted
+ */
+ public boolean cancel() {
+ var execution = current;
+ if (!cancellable || execution == null) return false;
+ if (execution.task != null) return execution.task.cancel();
+ finish(execution, State.of(Phase.CANCELLED));
+ return true;
+ }
+
+ /**
+ * Ends observation and disables the Command. A running task retains its own lifetime.
+ * If a View owns cancellable work, call {@link #cancel()} explicitly before closing.
+ */
+ @Override
+ public void close() {
+ if (getState().phase() == Phase.CLOSED) return;
+ var execution = current;
+ current = null;
+ if (execution != null) execution.detach();
+ state.set(State.of(Phase.CLOSED));
+ }
+
+ private void start() {
+ if (current != null || getState().phase() == Phase.CLOSED) return;
+ var execution = new Execution();
+ current = execution;
+ state.set(State.of(Phase.RUNNING));
+ if (current != execution) return;
+ try {
+ var task = Objects.requireNonNull(tasks.get(), "Task factory returned null");
+ if (current != execution) return;
+ if (task.getState() != Worker.State.READY) {
+ throw new IllegalArgumentException("Task factory must return a fresh Task");
+ }
+ execution.attach(task);
+ executor.execute(execution::run);
+ } catch (RuntimeException failure) {
+ finish(execution, new State<>(Phase.FAILED, null, failure, -1, ""));
+ }
+ }
+
+ private void finish(Execution execution, State terminal) {
+ if (current != execution) return;
+ current = null;
+ execution.detach();
+ state.set(terminal);
+ }
+
+ /** Identifies one execution, with FX-thread observations and a worker-thread completion flag. */
+ private final class Execution {
+
+ private Task task;
+ private final AtomicBoolean working = new AtomicBoolean();
+ private final InvalidationListener progress = ignored -> {
+ if (current == this) state.set(observation(Phase.RUNNING, null, null));
+ };
+ private final ChangeListener phase = (observable, before, after) -> {
+ if (current != this) return;
+ switch (after) {
+ case SUCCEEDED -> finish(this, observation(Phase.SUCCEEDED, task.getValue(), null));
+ case FAILED -> finish(this, observation(Phase.FAILED, null, task.getException()));
+ case CANCELLED -> finishCancellation();
+ default -> { }
+ }
+ };
+
+ private void attach(Task started) {
+ task = started;
+ started.progressProperty().addListener(progress);
+ started.messageProperty().addListener(progress);
+ started.stateProperty().addListener(phase);
+ }
+
+ private void run() {
+ working.set(true);
+ try {
+ task.run();
+ } finally {
+ working.set(false);
+ if (task.isCancelled()) Platform.runLater(this::finishCancellation);
+ }
+ }
+
+ private void finishCancellation() {
+ if (current == this && !working.get()) {
+ finish(this, observation(Phase.CANCELLED, null, null));
+ }
+ }
+
+ private State observation(Phase phase, T result, Throwable error) {
+ return new State<>(phase, result, error, task.getProgress(), task.getMessage());
+ }
+
+ private void detach() {
+ if (task != null) {
+ task.progressProperty().removeListener(progress);
+ task.messageProperty().removeListener(progress);
+ task.stateProperty().removeListener(phase);
+ }
+ }
+ }
+}
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 ca48ac5..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 {
@@ -42,14 +42,16 @@ public class BindingList {
* @param context the container that creates a named Converter
*/
void apply(Map namespace, Object viewModel, Object controller, Parent root,
- ApplicationContext context) {
+ ApplicationContext context, ViewLifetime lifetime) {
for (Object element : elements) {
if (element instanceof DirectBinding directBinding) {
- DirectBindingApplier.apply(namespace, viewModel, directBinding, context);
+ DirectBindingApplier.apply(namespace, viewModel, directBinding, context, lifetime);
} else if (element instanceof ComputedBinding computedBinding) {
- ComputedBindingApplier.apply(namespace, viewModel, controller, root, 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);
+ RepeatApplier.apply(namespace, viewModel, repeat, context, lifetime);
} else {
throw new IllegalArgumentException("Not a binding element: " + element);
}
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