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.lib fx - 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.lib neitzellib - 1.0.3 + 1.0.5 core 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.5 data-grid-jdbcOptional mapped JDBC grid source de.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.5 data-grid Toolkit-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.lib neitzellib - 1.0.3 + 1.0.5 encryption 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.lib neitzellib - 1.0.3 + 1.0.5 fx-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.lib fx - 1.0.3 + 1.0.5 org.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.lib neitzellib - 1.0.3 + 1.0.5 fx 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> 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> 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> 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(); + 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 3ccba3b..3366d50 100644 --- a/fx/src/main/java/de/neitzel/fx/view/Components.java +++ b/fx/src/main/java/de/neitzel/fx/view/Components.java @@ -14,6 +14,7 @@ import java.util.Map; import java.util.Set; import javafx.beans.property.Property; import javafx.fxml.FXMLLoader; +import javafx.scene.Node; import javafx.scene.Parent; import javafx.util.Builder; import lombok.AccessLevel; @@ -51,20 +52,20 @@ final class Components { * @param context the container that creates Components * @return a builder for a Component, or {@code null} when the type is not a Component */ - static Builder builder(Class type, ApplicationContext context) { + static Builder builder(Class type, ApplicationContext context, ViewLifetime owner) { Object component; try { - component = context.getComponent(type.asSubclass(Object.class)); + component = owner.managed() ? context.createComponent(type) : context.getComponent(type); } catch (IllegalArgumentException notAComponent) { return null; } if (component.getClass() != type) { return null; } - if (!LoadSession.claimFirst(type)) { + if (!owner.managed() && !LoadSession.claimFirst(type)) { component = context.createComponent(type.asSubclass(Object.class)); } - return new ComponentBuilder(component, context); + return new ComponentBuilder(component, context, owner.child()); } /** @@ -77,6 +78,7 @@ final class Components { private final Object component; /** The context used to load its document. */ private final ApplicationContext context; + private final ViewLifetime lifetime; /** Values already resolved by the containing FXMLLoader. */ private final Map values = new LinkedHashMap<>(); @@ -106,7 +108,7 @@ final class Components { */ @Override public Object build() { - Object result = load(component, context); + Object result = load(component, context, lifetime); if (!values.isEmpty()) { // A second fx:root load uses the public FXMLLoader API for bean setters, // enum/numeric coercion and diagnostics, without depending on BeanAdapter @@ -145,9 +147,9 @@ final class Components { * @param context the container that creates the instance and its dependencies * @return the loaded Component */ - static Object fresh(Class type, ApplicationContext context) { + static Object fresh(Class type, ApplicationContext context, ViewLifetime lifetime) { Object component = context.createComponent(type.asSubclass(Object.class)); - return load(component, context); + return load(component, context, lifetime); } /** @@ -158,8 +160,18 @@ final class Components { * @param component the Component * @param model the Model instance */ - static void setModel(Object component, Object model) { - modelProperty(component).setValue(model); + static void setModel(Object component, Object model, ViewLifetime lifetime) { + if (!lifetime.managed()) { + modelProperty(component).setValue(model); + return; + } + LoadSession session = LoadSession.nest(); + try { + modelProperty(component).setValue(model); + session.checkFailure(); + } finally { + LoadSession.unnest(); + } } /** @@ -169,7 +181,8 @@ final class Components { * @param context the container that creates nested Components * @return the loaded Component */ - private static Object load(Object component, ApplicationContext context) { + private static Object load(Object component, ApplicationContext context, ViewLifetime lifetime) { + lifetime.ownController(component); Class type = component.getClass(); String document = type.getSimpleName() + ".fxml"; URL fxml = type.getResource(document); @@ -179,11 +192,18 @@ final class Components { LoadSession nested = LoadSession.nest(); try { FXMLLoader loader = new FXMLLoader(fxml, ViewLoader.resources(context, fxml, type)); + FxmlHandlers.observe(loader, lifetime); loader.setRoot(component); loader.setController(component); - loader.setBuilderFactory(nestedType -> builder(nestedType, context)); + loader.setControllerFactory(nestedType -> ViewLoader.createController(context, nestedType, lifetime)); + loader.setBuilderFactory(nestedType -> builder(nestedType, context, lifetime)); loader.load(); - watchModel(component, List.copyOf(nested.bindingLists()), loader.getNamespace(), context); + nested.checkFailure(); + if (lifetime.managed() && component instanceof Node node) { + node.getProperties().put(Components.class, Boolean.TRUE); + lifetime.own(() -> node.getProperties().remove(Components.class)); + } + watchModel(component, List.copyOf(nested.bindingLists()), loader.getNamespace(), context, lifetime); return component; } catch (IOException failure) { throw new IllegalStateException("Could not load component " + fxml, failure); @@ -201,25 +221,38 @@ final class Components { * @param context the container that creates a named Converter */ private static void watchModel(Object component, List lists, Map namespace, - ApplicationContext context) { + ApplicationContext context, ViewLifetime lifetime) { Property model = modelProperty(component); boolean[] applied = {false}; - model.addListener((observable, oldValue, newValue) -> { + lifetime.listen(model, (observable, oldValue, newValue) -> { if (newValue == null || applied[0]) { return; } applied[0] = true; - Object viewModel = ViewModels.of(newValue, ViewModels.namedOn(component.getClass())); - if (component instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) { - hasViewModel.setViewModel(bound); - } - Parent root = (Parent) component; - for (BindingList list : lists) { - list.apply(namespace, viewModel, component, root, context); + try { + Object viewModel = ViewModels.of(lifetime.models(), newValue, ViewModels.namedOn(component.getClass())); + if (component instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) { + hasViewModel.setViewModel(bound); + } + Parent root = (Parent) component; + CommandBindingApplier.validate(lists, namespace); + for (BindingList list : lists) { + list.apply(namespace, viewModel, component, root, context, lifetime); + } + if (lifetime.managed()) Table.openAll(root, viewModel, context, lifetime); + } catch (RuntimeException | Error failure) { + lifetime.rollback(failure); + if (!lifetime.managed() || !LoadSession.recordFailure(failure)) { + throw failure; + } } }); } + static boolean ownsBindings(Node node) { + return node.hasProperties() && node.getProperties().containsKey(Components.class); + } + /** * Returns the Component's {@code model} property. * diff --git a/fx/src/main/java/de/neitzel/fx/view/ComputedBindingApplier.java b/fx/src/main/java/de/neitzel/fx/view/ComputedBindingApplier.java index 2b1f4f2..034a232 100644 --- a/fx/src/main/java/de/neitzel/fx/view/ComputedBindingApplier.java +++ b/fx/src/main/java/de/neitzel/fx/view/ComputedBindingApplier.java @@ -41,7 +41,7 @@ final class ComputedBindingApplier { Object viewModel, Object controller, Parent root, - ComputedBinding binding) { + ComputedBinding binding, ViewLifetime lifetime) { Object control = namespace.get(binding.getControl()); if (control == null) { throw new IllegalArgumentException("No control \"" + binding.getControl() + "\""); @@ -49,9 +49,9 @@ final class ComputedBindingApplier { Property target = controlProperty(control, binding.getProperty()); Runnable refresh = refresh(controller, binding.getMethod(), target); refresh.run(); - watchControls(root, target, refresh); + watchNode(root, target, refresh, lifetime); if (viewModel instanceof ViewModel model) { - model.addAttributeListener((observable, oldValue, newValue) -> refresh.run()); + model.addAttributeListener(lifetime, (observable, oldValue, newValue) -> refresh.run()); } } @@ -80,17 +80,6 @@ final class ComputedBindingApplier { }; } - /** - * Watches JavaFX properties on controls under {@code root}, other than {@code target}. - * - * @param root the scene-graph root - * @param target the property the method writes, which is not watched - * @param refresh the refresh to run when a watched property changes - */ - private static void watchControls(Parent root, Property target, Runnable refresh) { - watchNode(root, target, refresh); - } - /** * Watches one control and walks its children. * @@ -98,13 +87,13 @@ final class ComputedBindingApplier { * @param target the property the method writes, which is not watched * @param refresh the refresh to run when a watched property changes */ - private static void watchNode(Node node, Property target, Runnable refresh) { + private static void watchNode(Node node, Property target, Runnable refresh, ViewLifetime lifetime) { if (node instanceof Control control) { - watchProperties(control, target, refresh); + watchProperties(control, target, refresh, lifetime); } if (node instanceof Parent parent) { for (Node child : parent.getChildrenUnmodifiable()) { - watchNode(child, target, refresh); + watchNode(child, target, refresh, lifetime); } } } @@ -117,7 +106,7 @@ final class ComputedBindingApplier { * @param refresh the refresh to run when a watched property changes */ @SuppressWarnings("unchecked") - private static void watchProperties(Object bean, Property target, Runnable refresh) { + private static void watchProperties(Object bean, Property target, Runnable refresh, ViewLifetime lifetime) { ChangeListener listener = (observable, oldValue, newValue) -> refresh.run(); for (Method method : bean.getClass().getMethods()) { if (method.getParameterCount() != 0 || !method.getName().endsWith("Property")) { @@ -128,7 +117,7 @@ final class ComputedBindingApplier { } Object value = readProperty(bean, method); if (value instanceof ObservableValue observable && observable != target) { - ((ObservableValue) observable).addListener(listener); + lifetime.listen((ObservableValue) observable, listener); } } } diff --git a/fx/src/main/java/de/neitzel/fx/view/DataGrid.java b/fx/src/main/java/de/neitzel/fx/view/DataGrid.java index c9ac51c..38aa664 100644 --- a/fx/src/main/java/de/neitzel/fx/view/DataGrid.java +++ b/fx/src/main/java/de/neitzel/fx/view/DataGrid.java @@ -94,6 +94,8 @@ public final class DataGrid extends VBox implements AutoCloseable { } private final DataGridDeclaration declaration = new DataGridDeclaration<>(this); + private final ReadOnlyObjectWrapper> selection = + new ReadOnlyObjectWrapper<>(GridSelection.empty()); private final ReadOnlyObjectWrapper selectedKey = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper selectedElement = new ReadOnlyObjectWrapper<>(); private final ReadOnlyListWrapper selectedKeys = new ReadOnlyListWrapper<>( @@ -292,6 +294,7 @@ public final class DataGrid extends VBox implements AutoCloseable { renderer.enableColumnSeparators(); selectedKey.bind(renderer.selectedKeyProperty()); selectedElement.bind(renderer.selectedElementProperty()); + selection.bind(renderer.selectionProperty()); coordinator = new GridCoordinator<>( source, Platform::runLater, this::changed, result -> publishRows(result)); @@ -395,6 +398,18 @@ public final class DataGrid extends VBox implements AutoCloseable { public ReadOnlyListProperty selectedElementsProperty() { return selectedElements.getReadOnlyProperty(); } + /** + * Observes selection as one snapshot from the current state, including before the first load. + * The caller owns the adapter and closes it when the observing ViewModel stops using it. + * + * @return an independently closeable selection adapter for this grid + */ + public DataGridSelection observeSelection() { + requireFx(); + if (closed) throw new IllegalStateException("Grid is closed"); + return new DataGridSelection<>(this, selection.getReadOnlyProperty()); + } + public void selectKeys(Collection keys) { check(); renderer.selectKeys(keys); @@ -1339,6 +1354,7 @@ public final class DataGrid extends VBox implements AutoCloseable { if (renderer != null) renderer.close(); selectedKey.unbind(); selectedElement.unbind(); + selection.unbind(); selectedKeys.unbind(); selectedElements.unbind(); selectedKeys.set(FXCollections.emptyObservableList()); diff --git a/fx/src/main/java/de/neitzel/fx/view/DataGridSelection.java b/fx/src/main/java/de/neitzel/fx/view/DataGridSelection.java new file mode 100644 index 0000000..c1ce825 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/DataGridSelection.java @@ -0,0 +1,58 @@ +package de.neitzel.fx.view; + +import java.util.Collection; +import javafx.application.Platform; +import javafx.beans.property.ReadOnlyObjectProperty; +import javafx.beans.property.ReadOnlyObjectWrapper; + +/** + * An observable selection for a ViewModel to read, with explicit methods for selection changes. + * Create it through {@link DataGrid#observeSelection()} and use it on the JavaFX application thread. + * Closing the adapter detaches it without changing the grid's selection or closing the grid. + * + * @param row key type + * @param row model type + */ +public final class DataGridSelection implements AutoCloseable { + private final ReadOnlyObjectWrapper> selection = new ReadOnlyObjectWrapper<>(); + private DataGrid grid; + + DataGridSelection(DataGrid grid, ReadOnlyObjectProperty> source) { + this.grid = grid; + selection.bind(source); + } + + /** Returns one read-only observable containing the selected keys and available elements. */ + public ReadOnlyObjectProperty> selectionProperty() { + return selection.getReadOnlyProperty(); + } + + /** Returns the current snapshot, or the last snapshot when the adapter is closed. */ + public GridSelection getSelection() { + return selection.get(); + } + + /** Replaces the selection with one key, or clears it for a null key. */ + public void select(K key) { + requireOpen().select(key); + } + + /** Restores the selection by key, respecting the grid's current selection mode. */ + public void selectKeys(Collection keys) { + requireOpen().selectKeys(keys); + } + + private DataGrid requireOpen() { + if (grid == null) throw new IllegalStateException("Selection adapter is closed"); + return grid; + } + + /** Detaches the adapter and preserves its last published snapshot. */ + @Override + public void close() { + if (!Platform.isFxApplicationThread()) + throw new IllegalStateException("Use the JavaFX application thread"); + selection.unbind(); + grid = null; + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/DirectBinding.java b/fx/src/main/java/de/neitzel/fx/view/DirectBinding.java index c8fc994..d1eff69 100644 --- a/fx/src/main/java/de/neitzel/fx/view/DirectBinding.java +++ b/fx/src/main/java/de/neitzel/fx/view/DirectBinding.java @@ -11,7 +11,9 @@ import lombok.Setter; * View's ViewModel. Further names step into the ViewModel of a Complex attribute, and the * direction applies to the last name. When that last name is complex, the control receives the * Model instance behind the ViewModel. Direction values are {@code view}, {@code model}, and - * {@code both}. The Converter value is the class name. The container creates that class. + * {@code both}. The last segment of a {@code view} binding may also name a public + * {@code xxxProperty()} accessor returning a read-only observable. The Converter value is the + * class name. The container creates that class. */ @Getter @Setter diff --git a/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java b/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java index 8662e85..0f6fa6a 100644 --- a/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java +++ b/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java @@ -6,7 +6,9 @@ import java.lang.reflect.Method; import java.util.List; import java.util.Map; import javafx.beans.property.Property; +import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; +import javafx.fxml.FXMLLoader; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; @@ -30,48 +32,69 @@ final class DirectBindingApplier { * @param context the container that creates a named Converter */ static void apply(Map namespace, Object viewModel, DirectBinding binding, - ApplicationContext context) { + ApplicationContext context, ViewLifetime lifetime) { Object control = namespace.get(binding.getControl()); if (control == null) { throw new IllegalArgumentException("No control \"" + binding.getControl() + "\""); } - selectComponentViewModel(control, viewModel, binding); + selectComponentViewModel(control, viewModel, binding, lifetime); Resolved resolved = resolve(viewModel, binding.getPath()); if (resolved == null) { return; } Property controlProperty = controlProperty(control, binding.getProperty()); - Property attribute = resolved.attribute; + if (!resolved.writable) { + alignReadOnly(namespace, controlProperty, resolved, binding, context, lifetime); + return; + } + Property attribute = (Property) resolved.attribute; if (resolved.complex) { switch (binding.getDirection()) { - case "both" -> alignBothComplex(controlProperty, attribute); - case "view" -> alignTowardViewComplex(controlProperty, attribute); - case "model" -> alignTowardModelComplex(controlProperty, attribute); + case "both" -> alignBothComplex(controlProperty, attribute, lifetime); + case "view" -> alignTowardViewComplex(controlProperty, attribute, lifetime); + case "model" -> alignTowardModelComplex(controlProperty, attribute, lifetime); default -> throw new IllegalArgumentException("Not a direction: " + binding.getDirection()); } return; } if (attribute.getValue() instanceof ObservableList values) { - assignList(controlProperty, values); + assignList(controlProperty, values, lifetime); return; } String converterName = binding.getConverter(); if (converterName == null || converterName.isEmpty()) { - alignPlain(controlProperty, attribute, binding.getDirection()); + alignPlain(controlProperty, attribute, binding.getDirection(), lifetime); return; } Converter converter = converter(context, converterName); switch (binding.getDirection()) { case "both" -> alignConverted( - controlProperty, attribute, converter, resolved.owner, resolved.name, true, true); + controlProperty, attribute, converter, resolved.owner, resolved.name, true, true, lifetime); case "view" -> alignConverted( - controlProperty, attribute, converter, resolved.owner, resolved.name, true, false); + controlProperty, attribute, converter, resolved.owner, resolved.name, true, false, lifetime); case "model" -> alignConverted( - controlProperty, attribute, converter, resolved.owner, resolved.name, false, true); + controlProperty, attribute, converter, resolved.owner, resolved.name, false, true, lifetime); default -> throw new IllegalArgumentException("Not a direction: " + binding.getDirection()); } } + /** Connects a named observable to the View when its accessor exposes no writable property. */ + private static void alignReadOnly(Map namespace, Property control, Resolved resolved, + DirectBinding binding, ApplicationContext context, ViewLifetime lifetime) { + if (!"view".equals(binding.getDirection())) { + throw new IllegalArgumentException("Read-only source for path \"" + binding.getPath() + + "\" requires direction=\"view\" on " + binding.getControl() + "." + binding.getProperty() + + " in " + namespace.get(FXMLLoader.LOCATION_KEY)); + } + String converterName = binding.getConverter(); + if (converterName == null || converterName.isEmpty()) { + alignTowardView(control, resolved.attribute, lifetime); + } else { + alignConverted(control, resolved.attribute, converter(context, converterName), + resolved.owner, resolved.name, true, false, lifetime); + } + } + /** * Aligns a plain Attribute in the named direction. * @@ -79,11 +102,11 @@ final class DirectBindingApplier { * @param attribute the Attribute * @param direction {@code view}, {@code model}, or {@code both} */ - private static void alignPlain(Property controlProperty, Property attribute, String direction) { + private static void alignPlain(Property controlProperty, Property attribute, String direction, ViewLifetime lifetime) { switch (direction) { - case "both" -> alignBoth(controlProperty, attribute); - case "view" -> alignTowardView(controlProperty, attribute); - case "model" -> alignTowardModel(controlProperty, attribute); + case "both" -> alignBoth(controlProperty, attribute, lifetime); + case "view" -> alignTowardView(controlProperty, attribute, lifetime); + case "model" -> alignTowardModel(controlProperty, attribute, lifetime); default -> throw new IllegalArgumentException("Not a direction: " + direction); } } @@ -100,7 +123,10 @@ final class DirectBindingApplier { /** * The Attribute the Path names. */ - private final Property attribute; + private final ObservableValue attribute; + + /** Whether the Attribute resolves to a writable endpoint. */ + private final boolean writable; /** * Whether that Attribute is complex. @@ -153,13 +179,16 @@ final class DirectBindingApplier { current = child; } String last = names[names.length - 1]; - Property attribute = propertyOf(current, last); - if (attribute == null) { + Property property = propertyOf(current, last); + ViewModel owner = current instanceof ViewModel model ? model : null; + if (property != null) { + return new Resolved(property, true, owner != null && owner.isComplex(last), owner, last); + } + ObservableValue source = NamedProperties.getReadOnly(current, last); + if (source == null) { throw missing(path); } - boolean complex = current instanceof ViewModel stepped && stepped.isComplex(last); - ViewModel owner = current instanceof ViewModel model ? model : null; - return new Resolved(attribute, complex, owner, last); + return new Resolved(source, false, false, owner, last); } /** @@ -172,7 +201,7 @@ final class DirectBindingApplier { * @param viewModel the ViewModel for this View * @param binding the declaration */ - private static void selectComponentViewModel(Object control, Object viewModel, DirectBinding binding) { + private static void selectComponentViewModel(Object control, Object viewModel, DirectBinding binding, ViewLifetime lifetime) { if (!"model".equals(binding.getProperty())) { return; } @@ -184,7 +213,7 @@ final class DirectBindingApplier { if (instance == null) { return; } - ViewModels.of(instance, requested); + ViewModels.of(lifetime.models(), instance, requested); } /** @@ -279,23 +308,24 @@ final class DirectBindingApplier { * which is the last name of the Path. */ @SuppressWarnings("unchecked") - private static void alignConverted(Property controlProperty, Property attribute, Converter converter, - ViewModel owner, String sourceName, boolean towardView, boolean towardModel) { + private static void alignConverted(Property controlProperty, ObservableValue source, Converter converter, + ViewModel owner, String sourceName, boolean towardView, boolean towardModel, + ViewLifetime lifetime) { Property control = (Property) controlProperty; - Property source = (Property) attribute; Link link = new Link(); pushControl(control, source, converter, owner, sourceName, link); if (towardView) { - source.addListener((observable, oldValue, newValue) -> { + lifetime.listen(source, (observable, oldValue, newValue) -> { if (!link.applying) { pushControl(control, source, converter, owner, sourceName, link); } }); } if (towardModel) { - control.addListener((observable, oldValue, newValue) -> { + Property target = (Property) source; + lifetime.listen(control, (observable, oldValue, newValue) -> { if (!link.applying) { - pushAttribute(control, source, converter, owner, sourceName, link); + pushAttribute(control, target, converter, owner, sourceName, link); } }); } @@ -311,7 +341,7 @@ final class DirectBindingApplier { * @param source the Attribute name used as the failure source * @param link the guard against hearing this write */ - private static void pushControl(Property control, Property attribute, Converter converter, + private static void pushControl(Property control, ObservableValue attribute, Converter converter, ViewModel owner, String source, Link link) { try { Object shown = converter.toControlValue(attribute.getValue()); @@ -321,8 +351,13 @@ final class DirectBindingApplier { } finally { link.applying = false; } - owner.clearBindingFailure(source); + if (owner != null) { + owner.clearBindingFailure(source); + } } catch (RuntimeException failure) { + if (owner == null) { + throw failure; + } owner.reportBindingFailure(source, failureText(failure)); } } @@ -412,21 +447,21 @@ final class DirectBindingApplier { * @param attribute the complex Attribute */ @SuppressWarnings("unchecked") - private static void alignBothComplex(Property controlProperty, Property attribute) { + private static void alignBothComplex(Property controlProperty, Property attribute, ViewLifetime lifetime) { Property control = (Property) controlProperty; Property source = (Property) attribute; control.setValue(modelBehind(source.getValue())); - source.addListener((observable, oldValue, newValue) -> { + lifetime.listen(source, (observable, oldValue, newValue) -> { Object model = modelBehind(newValue); if (control.getValue() != model) { control.setValue(model); } }); - control.addListener((observable, oldValue, newValue) -> { + lifetime.listen(control, (observable, oldValue, newValue) -> { if (modelBehind(source.getValue()) == newValue) { return; } - source.setValue(newValue == null ? null : ViewModels.of(newValue)); + source.setValue(newValue == null ? null : ViewModels.of(lifetime.models(), newValue, null)); }); } @@ -437,11 +472,11 @@ final class DirectBindingApplier { * @param attribute the complex Attribute */ @SuppressWarnings("unchecked") - private static void alignTowardViewComplex(Property controlProperty, Property attribute) { + private static void alignTowardViewComplex(Property controlProperty, Property attribute, ViewLifetime lifetime) { Property control = (Property) controlProperty; Property source = (Property) attribute; control.setValue(modelBehind(source.getValue())); - source.addListener((observable, oldValue, newValue) -> control.setValue(modelBehind(newValue))); + lifetime.listen(source, (observable, oldValue, newValue) -> control.setValue(modelBehind(newValue))); } /** @@ -451,15 +486,15 @@ final class DirectBindingApplier { * @param attribute the complex Attribute */ @SuppressWarnings("unchecked") - private static void alignTowardModelComplex(Property controlProperty, Property attribute) { + private static void alignTowardModelComplex(Property controlProperty, Property attribute, ViewLifetime lifetime) { Property control = (Property) controlProperty; Property source = (Property) attribute; control.setValue(modelBehind(source.getValue())); - control.addListener((observable, oldValue, newValue) -> { + lifetime.listen(control, (observable, oldValue, newValue) -> { if (modelBehind(source.getValue()) == newValue) { return; } - source.setValue(newValue == null ? null : ViewModels.of(newValue)); + source.setValue(newValue == null ? null : ViewModels.of(lifetime.models(), newValue, null)); }); } @@ -483,8 +518,13 @@ final class DirectBindingApplier { * @param values the list the ViewModel and the Model share */ @SuppressWarnings("unchecked") - private static void assignList(Property controlProperty, ObservableList values) { - ((Property) controlProperty).setValue(values); + private static void assignList(Property controlProperty, ObservableList values, ViewLifetime lifetime) { + Property target = (Property) controlProperty; + Object previous = target.getValue(); + target.setValue(values); + lifetime.own(() -> { + if (target.getValue() == values) target.setValue(previous); + }); } /** @@ -494,8 +534,11 @@ final class DirectBindingApplier { * @param attribute the Attribute */ @SuppressWarnings("unchecked") - private static void alignBoth(Property controlProperty, Property attribute) { - ((Property) controlProperty).bindBidirectional((Property) attribute); + private static void alignBoth(Property controlProperty, Property attribute, ViewLifetime lifetime) { + Property control = (Property) controlProperty; + Property source = (Property) attribute; + control.bindBidirectional(source); + lifetime.own(() -> control.unbindBidirectional(source)); } /** @@ -505,11 +548,11 @@ final class DirectBindingApplier { * @param attribute the Attribute */ @SuppressWarnings("unchecked") - private static void alignTowardView(Property controlProperty, Property attribute) { + private static void alignTowardView(Property controlProperty, ObservableValue attribute, + ViewLifetime lifetime) { Property control = (Property) controlProperty; - Property source = (Property) attribute; - control.setValue(source.getValue()); - source.addListener((observable, oldValue, newValue) -> control.setValue(newValue)); + control.setValue(attribute.getValue()); + lifetime.listen(attribute, (observable, oldValue, newValue) -> control.setValue(newValue)); } /** @@ -519,10 +562,10 @@ final class DirectBindingApplier { * @param attribute the Attribute */ @SuppressWarnings("unchecked") - private static void alignTowardModel(Property controlProperty, Property attribute) { + private static void alignTowardModel(Property controlProperty, Property attribute, ViewLifetime lifetime) { Property control = (Property) controlProperty; Property target = (Property) attribute; control.setValue(target.getValue()); - control.addListener((observable, oldValue, newValue) -> target.setValue(newValue)); + lifetime.listen(control, (observable, oldValue, newValue) -> target.setValue(newValue)); } } diff --git a/fx/src/main/java/de/neitzel/fx/view/FxmlHandlers.java b/fx/src/main/java/de/neitzel/fx/view/FxmlHandlers.java new file mode 100644 index 0000000..b8f5332 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/FxmlHandlers.java @@ -0,0 +1,66 @@ +package de.neitzel.fx.view; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import javafx.beans.property.Property; +import javafx.event.EventHandler; +import javafx.fxml.FXMLLoader; +import javafx.fxml.LoadListener; + +/** Removes handler properties assigned by the managed FXML document when its View closes. */ +final class FxmlHandlers implements LoadListener { + + private final ViewLifetime lifetime; + private final Deque> handlers = new ArrayDeque<>(); + + private FxmlHandlers(ViewLifetime lifetime) { + this.lifetime = lifetime; + } + + static void observe(FXMLLoader loader, ViewLifetime lifetime) { + if (lifetime.managed()) loader.setLoadListener(new FxmlHandlers(lifetime)); + } + + @Override + public void readEventHandlerAttribute(String name, String value) { + handlers.getLast().add(name); + } + + @Override + public void endElement(Object value) { + List attributes = handlers.removeLast(); + if (value == null) return; + for (String attribute : attributes) { + Property property = NamedProperties.get(value, attribute); + if (property != null && property.getValue() instanceof EventHandler handler) { + lifetime.own(() -> { + if (property.getValue() == handler) property.setValue(null); + }); + } + } + } + + private void beginElement() { + handlers.addLast(new ArrayList<>()); + } + + @Override public void beginInstanceDeclarationElement(Class type) { beginElement(); } + @Override public void beginUnknownTypeElement(String name) { beginElement(); } + @Override public void beginIncludeElement() { beginElement(); } + @Override public void beginReferenceElement() { beginElement(); } + @Override public void beginCopyElement() { beginElement(); } + @Override public void beginRootElement() { beginElement(); } + @Override public void beginPropertyElement(String name, Class sourceType) { beginElement(); } + @Override public void beginUnknownStaticPropertyElement(String name) { beginElement(); } + @Override public void beginScriptElement() { beginElement(); } + @Override public void beginDefineElement() { beginElement(); } + + @Override public void readImportProcessingInstruction(String target) { } + @Override public void readLanguageProcessingInstruction(String language) { } + @Override public void readComment(String comment) { } + @Override public void readInternalAttribute(String name, String value) { } + @Override public void readPropertyAttribute(String name, Class sourceType, String value) { } + @Override public void readUnknownStaticPropertyAttribute(String name, String value) { } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/GridSelection.java b/fx/src/main/java/de/neitzel/fx/view/GridSelection.java new file mode 100644 index 0000000..8934556 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/GridSelection.java @@ -0,0 +1,45 @@ +package de.neitzel.fx.view; + +import java.util.List; +import java.util.Objects; + +/** + * One published selection of a grid. Keys retain their selection order and can include keys outside + * the current page. Elements follow the grid's display order and contain only available selected + * rows. The lead element is null when the lead key has no available row. + * + * @param selectedKeys selected keys, including retained off-page keys + * @param selectedElements selected models of visible and interactive rows + * @param leadKey lead key, or null for an empty selection + * @param leadElement lead model, or null when unavailable + * @param row key type + * @param row model type + */ +public record GridSelection( + List selectedKeys, List selectedElements, K leadKey, T leadElement) { + + /** Copies both lists so a published selection remains stable as the grid changes. */ + public GridSelection { + selectedKeys = List.copyOf(selectedKeys); + selectedElements = List.copyOf(selectedElements); + } + + static GridSelection empty() { + return new GridSelection<>(List.of(), List.of(), null, null); + } + + /** A refreshed row can replace an equal model with a different instance. */ + boolean sameSelection(GridSelection previous) { + if (!selectedKeys.equals(previous.selectedKeys) || !Objects.equals(leadKey, previous.leadKey) + || leadElement != previous.leadElement + || selectedElements.size() != previous.selectedElements.size()) { + return false; + } + for (int index = 0; index < selectedElements.size(); index++) { + if (selectedElements.get(index) != previous.selectedElements.get(index)) { + return false; + } + } + return true; + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/LoadSession.java b/fx/src/main/java/de/neitzel/fx/view/LoadSession.java index 0c40ff0..4f6dd5c 100644 --- a/fx/src/main/java/de/neitzel/fx/view/LoadSession.java +++ b/fx/src/main/java/de/neitzel/fx/view/LoadSession.java @@ -18,7 +18,7 @@ import java.util.Set; final class LoadSession { /** - * The sessions open on this thread. The last one is the outermost load. + * The sessions open on this thread, with the current session first. */ private static final ThreadLocal> STACK = new ThreadLocal<>(); @@ -32,25 +32,33 @@ final class LoadSession { */ private final Set> built = new HashSet<>(); + private Throwable bindingFailure; + + // JavaFX reports exceptions from a property listener to the thread's uncaught handler. + // Keep a synchronous Component failure with the load that triggered that property change. + static boolean recordFailure(Throwable failure) { + Deque stack = STACK.get(); + if (stack == null) return false; + LoadSession session = stack.peek(); + if (session.bindingFailure == null) { + session.bindingFailure = failure; + } else if (session.bindingFailure != failure) { + session.bindingFailure.addSuppressed(failure); + } + return true; + } + + void checkFailure() { + if (bindingFailure instanceof RuntimeException runtime) throw runtime; + if (bindingFailure instanceof Error error) throw error; + } + /** * Prevents instantiation from outside this class. */ private LoadSession() { } - /** - * Starts a session on this thread. - * - * @return the open session - */ - static LoadSession open() { - Deque stack = new ArrayDeque<>(); - LoadSession session = new LoadSession(); - stack.push(session); - STACK.set(stack); - return session; - } - /** * Opens a nested session for a Component document. *

@@ -84,13 +92,6 @@ final class LoadSession { } } - /** - * Drops the session for this thread. - */ - static void close() { - STACK.remove(); - } - /** * Registers a binding list created while a session is open. * diff --git a/fx/src/main/java/de/neitzel/fx/view/LoadedView.java b/fx/src/main/java/de/neitzel/fx/view/LoadedView.java index 84905bb..02150f4 100644 --- a/fx/src/main/java/de/neitzel/fx/view/LoadedView.java +++ b/fx/src/main/java/de/neitzel/fx/view/LoadedView.java @@ -10,7 +10,7 @@ import lombok.RequiredArgsConstructor; * The scene-graph root and ViewModel produced by loading a View for a Model instance. */ @RequiredArgsConstructor(access = AccessLevel.PACKAGE) -public final class LoadedView { +public final class LoadedView implements AutoCloseable { /** * The scene-graph root of the loaded View. @@ -23,6 +23,17 @@ public final class LoadedView { */ private final Object viewModel; + private final ViewLifetime lifetime; + + /** + * Releases the resources owned by a managed View. Calling this twice is harmless. + * Use the ViewLoader overload taking a ViewModelContext to opt into managed lifetimes. + */ + @Override + public void close() { + lifetime.close(); + } + /** * Returns the ViewModel the View is bound to. *

diff --git a/fx/src/main/java/de/neitzel/fx/view/NamedProperties.java b/fx/src/main/java/de/neitzel/fx/view/NamedProperties.java index 5fd625a..04366a4 100644 --- a/fx/src/main/java/de/neitzel/fx/view/NamedProperties.java +++ b/fx/src/main/java/de/neitzel/fx/view/NamedProperties.java @@ -1,6 +1,7 @@ package de.neitzel.fx.view; import javafx.beans.property.Property; +import javafx.beans.value.ObservableValue; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -26,17 +27,31 @@ final class NamedProperties { * @return the property, or {@code null} when {@code bean} declares none of that name */ static Property get(Object bean, String name) { + Object value = read(bean, name, true); + return value instanceof Property property ? property : null; + } + + /** + * Returns a named observable whose accessor exposes a read-only source. + * + * @param bean the object that declares the source + * @param name the source name + * @return the source or {@code null} when there is no such accessor or it returns {@code null} + */ + static ObservableValue getReadOnly(Object bean, String name) { + Object value = read(bean, name, false); + return value instanceof ObservableValue source ? source : null; + } + + private static Object read(Object bean, String name, boolean writable) { String methodName = name + "Property"; try { Method method = bean.getClass().getMethod(methodName); - if (!Property.class.isAssignableFrom(method.getReturnType())) { + Class type = method.getReturnType(); + if (!ObservableValue.class.isAssignableFrom(type) || writable != Property.class.isAssignableFrom(type)) { return null; } - Object value = method.invoke(bean); - if (value instanceof Property property) { - return property; - } - return null; + return method.invoke(bean); } catch (NoSuchMethodException notDeclared) { return null; } catch (IllegalAccessException | InvocationTargetException failure) { diff --git a/fx/src/main/java/de/neitzel/fx/view/RepeatApplier.java b/fx/src/main/java/de/neitzel/fx/view/RepeatApplier.java index 4aec836..4a0219a 100644 --- a/fx/src/main/java/de/neitzel/fx/view/RepeatApplier.java +++ b/fx/src/main/java/de/neitzel/fx/view/RepeatApplier.java @@ -2,11 +2,12 @@ package de.neitzel.fx.view; import de.neitzel.injection.ApplicationContext; import javafx.beans.property.Property; -import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.layout.Pane; +import java.util.ArrayList; +import java.util.List; import java.util.Map; /** @@ -34,7 +35,7 @@ final class RepeatApplier { * @param context the container that creates each Component */ static void apply(Map namespace, Object viewModel, Repeat repeat, - ApplicationContext context) { + ApplicationContext context, ViewLifetime lifetime) { Object named = namespace.get(repeat.getPane()); if (!(named instanceof Pane pane)) { throw new IllegalArgumentException("No pane \"" + repeat.getPane() + "\""); @@ -44,10 +45,15 @@ final class RepeatApplier { throw new IllegalArgumentException("No collection \"" + repeat.getCollection() + "\""); } Class type = componentType(repeat.getComponent()); + int offset = pane.getChildren().size(); + List children = new ArrayList<>(); + lifetime.own(() -> pane.getChildren().removeAll(children.stream().map(RepeatedChild::node).toList())); for (Object element : values) { - pane.getChildren().add(child(type, context, element)); + RepeatedChild child = child(type, context, element, lifetime); + children.add(child); + pane.getChildren().add(child.node()); } - listen(pane, type, context, values); + listen(pane, type, context, values, lifetime, offset, children); } /** @@ -76,20 +82,24 @@ final class RepeatApplier { * @param values the collection */ @SuppressWarnings("unchecked") - private static void listen(Pane pane, Class type, ApplicationContext context, ObservableList values) { + private static void listen(Pane pane, Class type, ApplicationContext context, ObservableList values, + ViewLifetime lifetime, int offset, List children) { ObservableList elements = (ObservableList) values; - elements.addListener((ListChangeListener) change -> { + lifetime.listen(elements, change -> { while (change.next()) { if (change.wasPermutated() || change.wasUpdated()) { continue; } - if (change.getRemovedSize() > 0) { - pane.getChildren().remove(change.getFrom(), change.getFrom() + change.getRemovedSize()); + for (int removed = 0; removed < change.getRemovedSize(); removed++) { + RepeatedChild child = children.remove(change.getFrom()); + pane.getChildren().remove(child.node()); + child.lifetime().close(); } for (int index = 0; index < change.getAddedSize(); index++) { - pane.getChildren().add( - change.getFrom() + index, - child(type, context, change.getAddedSubList().get(index))); + RepeatedChild child = child(type, context, change.getAddedSubList().get(index), lifetime); + int position = change.getFrom() + index; + children.add(position, child); + pane.getChildren().add(offset + position, child.node()); } } }); @@ -103,12 +113,21 @@ final class RepeatApplier { * @param element the Model instance * @return the loaded Component */ - private static Node child(Class type, ApplicationContext context, Object element) { - Object component = Components.fresh(type, context); - Components.setModel(component, element); - return (Node) component; + private static RepeatedChild child(Class type, ApplicationContext context, Object element, + ViewLifetime owner) { + ViewLifetime lifetime = owner.child(); + try { + Object component = Components.fresh(type, context, lifetime); + Components.setModel(component, element, lifetime); + return new RepeatedChild((Node) component, lifetime); + } catch (RuntimeException | Error failure) { + lifetime.rollback(failure); + throw failure; + } } + private record RepeatedChild(Node node, ViewLifetime lifetime) {} + /** * Returns the Component class named by the repeat. * diff --git a/fx/src/main/java/de/neitzel/fx/view/Table.java b/fx/src/main/java/de/neitzel/fx/view/Table.java index f425270..5c1dca0 100644 --- a/fx/src/main/java/de/neitzel/fx/view/Table.java +++ b/fx/src/main/java/de/neitzel/fx/view/Table.java @@ -25,6 +25,7 @@ import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; +import javafx.event.EventHandler; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.Parent; @@ -156,6 +157,8 @@ public class Table extends VBox { * One Row per element that has been shown. A hidden element keeps its Row. */ private final Map rows = new IdentityHashMap<>(); + private final Map rowLifetimes = new IdentityHashMap<>(); + private ViewLifetime lifetime; /** * The collection this Table shows. @@ -360,8 +363,8 @@ public class Table extends VBox { * @param viewModel the ViewModel for this View * @param context the container that creates each Row */ - static void openAll(Parent root, Object viewModel, ApplicationContext context) { - walk(root, viewModel, context); + static void openAll(Parent root, Object viewModel, ApplicationContext context, ViewLifetime lifetime) { + walk(root, root, viewModel, context, lifetime); } /** @@ -370,7 +373,7 @@ public class Table extends VBox { * @param viewModel the ViewModel for this View * @param context the container that creates each Row */ - void open(Object viewModel, ApplicationContext context) { + void open(Object viewModel, ApplicationContext context, ViewLifetime owner) { if (resultMode) { return; } @@ -379,6 +382,15 @@ public class Table extends VBox { } opened = true; this.context = context; + lifetime = owner.child(); + lifetime.own(() -> { + rowLifetimes.clear(); + rows.clear(); + body.getChildren().clear(); + elements = FXCollections.observableArrayList(); + selection.set(null); + this.context = null; + }); if (columns.isEmpty()) { throw new IllegalArgumentException("A table needs a column"); } @@ -393,7 +405,7 @@ public class Table extends VBox { } buildHeader(); ensureWidths(); - elements.addListener((ListChangeListener) this::onCollectionChange); + lifetime.listen(elements, this::onCollectionChange); refresh(); } @@ -1182,6 +1194,8 @@ public class Table extends VBox { } for (Object removed : change.getRemoved()) { rows.remove(removed); + ViewLifetime removedRow = rowLifetimes.remove(removed); + if (removedRow != null) removedRow.close(); if (selection.get() == removed) { selection.set(null); } @@ -1310,18 +1324,27 @@ public class Table extends VBox { * @return the Row */ private Node createRow(Object element) { - Object component = Components.fresh(rowType, context); - Components.setModel(component, element); - if (!(component instanceof Node node)) { - throw new IllegalArgumentException("Row is not a node: " + rowType.getName()); - } - node.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> { - if (event.getButton() == MouseButton.PRIMARY) { - selection.set(element); + ViewLifetime rowLifetime = lifetime.child(); + try { + Object component = Components.fresh(rowType, context, rowLifetime); + Components.setModel(component, element, rowLifetime); + if (!(component instanceof Node node)) { + throw new IllegalArgumentException("Row is not a node: " + rowType.getName()); } - }); - watchEdits(node); - return node; + EventHandler select = event -> { + if (event.getButton() == MouseButton.PRIMARY) { + selection.set(element); + } + }; + node.addEventFilter(MouseEvent.MOUSE_CLICKED, select); + rowLifetime.own(() -> node.removeEventFilter(MouseEvent.MOUSE_CLICKED, select)); + watchEdits(node, rowLifetime); + if (rowLifetime.managed()) rowLifetimes.put(element, rowLifetime); + return node; + } catch (RuntimeException | Error failure) { + rowLifetime.rollback(failure); + throw failure; + } } /** @@ -1329,13 +1352,13 @@ public class Table extends VBox { * * @param node the Row or one of its fields */ - private void watchEdits(Node node) { + private void watchEdits(Node node, ViewLifetime rowLifetime) { if (node instanceof javafx.scene.control.TextInputControl input) { - input.textProperty().addListener((observable, previous, current) -> refresh()); + rowLifetime.listen(input.textProperty(), (observable, previous, current) -> refresh()); } if (node instanceof Parent parent) { for (Node child : parent.getChildrenUnmodifiable()) { - watchEdits(child); + watchEdits(child, rowLifetime); } } } @@ -1543,18 +1566,20 @@ public class Table extends VBox { * @param viewModel the ViewModel for this View * @param context the container that creates each Row */ - private static void walk(Node node, Object viewModel, ApplicationContext context) { + private static void walk(Node node, Parent root, Object viewModel, ApplicationContext context, + ViewLifetime lifetime) { + if (node != root && Components.ownsBindings(node)) return; if (node instanceof Table table) { - table.open(viewModel, context); + table.open(viewModel, context, lifetime); } if (!(node instanceof Parent parent)) { return; } for (Node child : parent.getChildrenUnmodifiable()) { - walk(child, viewModel, context); + walk(child, root, viewModel, context, lifetime); } if (parent instanceof ScrollPane pane && pane.getContent() != null) { - walk(pane.getContent(), viewModel, context); + walk(pane.getContent(), root, viewModel, context, lifetime); } } diff --git a/fx/src/main/java/de/neitzel/fx/view/TableResults.java b/fx/src/main/java/de/neitzel/fx/view/TableResults.java index ff8646f..50b5853 100644 --- a/fx/src/main/java/de/neitzel/fx/view/TableResults.java +++ b/fx/src/main/java/de/neitzel/fx/view/TableResults.java @@ -41,6 +41,8 @@ public final class TableResults implements AutoCloseable { private List order; private final Set hiddenColumns = new HashSet<>(); private List> entries = List.of(); + private final ReadOnlyObjectWrapper> selection = + new ReadOnlyObjectWrapper<>(GridSelection.empty()); private final ReadOnlyObjectWrapper selectedKey = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper selectedElement = new ReadOnlyObjectWrapper<>(); private final ObservableList selectedKeys = FXCollections.observableArrayList(); @@ -131,6 +133,10 @@ public final class TableResults implements AutoCloseable { /** Only selected models currently visible and interactive are actionable. */ public ReadOnlyListProperty selectedElementsProperty() { return elementsView.getReadOnlyProperty(); } + ReadOnlyObjectProperty> selectionProperty() { + return selection.getReadOnlyProperty(); + } + public RowSelectionMode getSelectionMode() { return selectionMode; } public void setSelectionMode(RowSelectionMode mode) { @@ -623,6 +629,10 @@ public final class TableResults implements AutoCloseable { } selectedElement.set(rowsInteractive ? loaded : null); selectedElements.setAll(actionable); + + GridSelection snapshot = new GridSelection<>( + selectedKeys, selectedElements, selectedKey.get(), selectedElement.get()); + if (!snapshot.sameSelection(selection.get())) selection.set(snapshot); } public void setOnLayoutCommitted(Runnable handler) { @@ -980,6 +990,7 @@ public final class TableResults implements AutoCloseable { selectedElement.set(null); selectedKeys.clear(); selectedElements.clear(); + selection.set(GridSelection.empty()); anchor = null; captured = GroupProjection.capture(List.of(), List.of()); groupTree = List.of(); diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewLifetime.java b/fx/src/main/java/de/neitzel/fx/view/ViewLifetime.java new file mode 100644 index 0000000..07db531 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/ViewLifetime.java @@ -0,0 +1,99 @@ +package de.neitzel.fx.view; + +import java.util.LinkedHashSet; +import java.util.SequencedSet; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.collections.ListChangeListener; +import javafx.collections.ObservableList; + +/** Tracks the resources installed by one View or one of its dynamic children. */ +final class ViewLifetime implements AutoCloseable { + + private final ViewModelContext models; + private final SequencedSet cleanup = new LinkedHashSet<>(); + private boolean closed; + + ViewLifetime(ViewModelContext models) { + this.models = models; + } + + ViewModelContext models() { + return models; + } + + boolean managed() { + return models != ViewModels.LEGACY; + } + + void own(Runnable removal) { + if (managed()) { + if (closed) { + removal.run(); + } else { + cleanup.addLast(removal); + } + } + } + + void ownController(Object controller) { + if (controller instanceof AutoCloseable closeable) { + own(() -> { + try { + closeable.close(); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Could not close " + controller.getClass().getName(), failure); + } + }); + } + } + + void listen(ObservableValue observable, ChangeListener listener) { + observable.addListener(listener); + own(() -> observable.removeListener(listener)); + } + + void listen(ObservableList observable, ListChangeListener listener) { + observable.addListener(listener); + own(() -> observable.removeListener(listener)); + } + + ViewLifetime child() { + ViewLifetime child = new ViewLifetime(models); + Runnable closeChild = child::close; + own(closeChild); + child.own(() -> cleanup.remove(closeChild)); + return child; + } + + @Override + public void close() { + if (closed) return; + closed = true; + Throwable failure = null; + while (!cleanup.isEmpty()) { + try { + cleanup.removeLast().run(); + } catch (RuntimeException | Error next) { + if (failure == null) { + failure = next; + } else if (failure != next) { + failure.addSuppressed(next); + } + } + } + if (failure instanceof RuntimeException runtime) throw runtime; + if (failure instanceof Error error) throw error; + } + + /** Cleans up an incomplete load while preserving its original failure. */ + void rollback(Throwable failure) { + try { + close(); + } catch (RuntimeException | Error cleanupFailure) { + if (failure != cleanupFailure) failure.addSuppressed(cleanupFailure); + } + } +} 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 92310b3..6ada1fb 100644 --- a/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java +++ b/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java @@ -77,14 +77,33 @@ public final class ViewLoader { * @throws IllegalArgumentException when a Direct binding names a path that is not a read-write Attribute */ public static LoadedView load(URL fxml, Object model, ApplicationContext context) { - Class controllerType = FxmlControllers.controllerClass(fxml); - Class viewModelClass = ViewModels.namedOn(controllerType); - Object viewModel = ViewModels.of(model, viewModelClass); - LoadSession session = LoadSession.open(); + return load(fxml, model, context, new ViewLifetime(ViewModels.LEGACY)); + } + + /** + * Loads a View with a fresh Controller and Components in an explicitly owned Model context. + * Close the result when its UI is removed, or close the Model context to close all its Views. + * + * @param fxml the FXML document + * @param model the Model instance + * @param context the container for Controllers and services + * @param models the Model context shared by this View and related Views + * @return the loaded View + */ + public static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewModelContext models) { + return load(fxml, model, context, models.openView()); + } + + private static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewLifetime lifetime) { + LoadSession session = LoadSession.nest(); try { + Class controllerType = FxmlControllers.controllerClass(fxml); + Class viewModelClass = ViewModels.namedOn(controllerType); + Object viewModel = ViewModels.of(lifetime.models(), model, viewModelClass); FXMLLoader loader = new FXMLLoader(fxml, resources(context, fxml, controllerType)); - loader.setControllerFactory(type -> controller(context, type)); - loader.setBuilderFactory(type -> Components.builder(type, context)); + FxmlHandlers.observe(loader, lifetime); + loader.setControllerFactory(type -> createController(context, type, lifetime)); + loader.setBuilderFactory(type -> Components.builder(type, context, lifetime)); Object loaded = loader.load(); if (!(loaded instanceof Parent root)) { throw new IllegalArgumentException("View root must be a parent"); @@ -96,18 +115,31 @@ 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); + bindingList.apply(loader.getNamespace(), viewModel, controller, root, context, lifetime); } - Table.openAll(root, viewModel, context); - return new LoadedView(root, viewModel); + Table.openAll(root, viewModel, context, lifetime); + session.checkFailure(); + return new LoadedView(root, viewModel, lifetime); } catch (IOException failure) { + lifetime.rollback(failure); throw new IllegalStateException("Could not load view " + fxml, failure); + } catch (RuntimeException | Error failure) { + lifetime.rollback(failure); + throw failure; } finally { - LoadSession.close(); + LoadSession.unnest(); } } + static Object createController(ApplicationContext context, Class type, ViewLifetime lifetime) { + if (!lifetime.managed()) return context.getComponent(type); + Object controller = context.createComponent(type); + lifetime.ownController(controller); + return controller; + } + static Messages resources(ApplicationContext context, URL fxml, Class type) { Localizer languages; try { @@ -118,14 +150,4 @@ public final class ViewLoader { return languages.forView(fxml, type); } - /** - * Asks the container for the Controller class named by the document. - * - * @param context the container - * @param type the Controller class - * @return the Controller - */ - private static Object controller(ApplicationContext context, Class type) { - return context.getComponent(type.asSubclass(Object.class)); - } } diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewModel.java b/fx/src/main/java/de/neitzel/fx/view/ViewModel.java index 29ed0b8..0a7a648 100644 --- a/fx/src/main/java/de/neitzel/fx/view/ViewModel.java +++ b/fx/src/main/java/de/neitzel/fx/view/ViewModel.java @@ -80,6 +80,7 @@ public class ViewModel { * The Model instance this ViewModel was built for. */ private final Object model; + private final ViewModelContext models; /** * JavaFX properties keyed by Attribute name. @@ -136,7 +137,8 @@ public class ViewModel { */ protected ViewModel(Object model) { this.model = model; - ViewModels.register(model, this); + models = ViewModels.constructingContext(); + models.viewModels().put(model, this); for (PropertyDescriptor descriptor : descriptors(model.getClass())) { Method getter = descriptor.getReadMethod(); Method setter = descriptor.getWriteMethod(); @@ -218,9 +220,9 @@ public class ViewModel { * @param listener the listener */ @SuppressWarnings("unchecked") - void addAttributeListener(ChangeListener listener) { + void addAttributeListener(ViewLifetime lifetime, ChangeListener listener) { for (Property property : properties.values()) { - ((Property) property).addListener(listener); + lifetime.listen((Property) property, listener); } } @@ -429,7 +431,7 @@ public class ViewModel { * Attaching the change listener reads the value. That read is ignored until * {@link #attached()} so a Component annotation can name the class first. */ - private static final class LazyComplex extends SimpleObjectProperty { + private final class LazyComplex extends SimpleObjectProperty { /** * The Model instance, kept until the nested ViewModel is built. @@ -464,7 +466,7 @@ public class ViewModel { public Object get() { if (!attaching && !realized) { realized = true; - super.set(current == null ? null : ViewModels.of(current)); + super.set(current == null ? null : ViewModels.of(models, current, null)); } return super.get(); } diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewModelContext.java b/fx/src/main/java/de/neitzel/fx/view/ViewModelContext.java new file mode 100644 index 0000000..3ba7522 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/ViewModelContext.java @@ -0,0 +1,42 @@ +package de.neitzel.fx.view; + +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * Owns the ViewModel identity and loaded Views for a window, document or archive session. + * Use this context on the JavaFX application thread. Closing it closes its remaining Views and + * releases its Model registrations. Close an individual {@link LoadedView} earlier to detach it + * while its Model remains available to other Views in this context. + */ +public final class ViewModelContext implements AutoCloseable { + + private final Map viewModels = new IdentityHashMap<>(); + private final ViewLifetime views = new ViewLifetime(this); + private boolean closed; + + ViewLifetime openView() { + checkOpen(); + return views.child(); + } + + Map viewModels() { + checkOpen(); + return viewModels; + } + + private void checkOpen() { + if (closed) throw new IllegalStateException("ViewModelContext is closed"); + } + + @Override + public void close() { + if (closed) return; + closed = true; + try { + views.close(); + } finally { + viewModels.clear(); + } + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewModels.java b/fx/src/main/java/de/neitzel/fx/view/ViewModels.java index d9e6219..31256bb 100644 --- a/fx/src/main/java/de/neitzel/fx/view/ViewModels.java +++ b/fx/src/main/java/de/neitzel/fx/view/ViewModels.java @@ -2,7 +2,6 @@ package de.neitzel.fx.view; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.IdentityHashMap; import java.util.Map; /** @@ -15,7 +14,10 @@ final class ViewModels { /** * ViewModels already built, keyed by Model identity. */ - private static final Map BY_INSTANCE = new IdentityHashMap<>(); + static final ViewModelContext LEGACY = new ViewModelContext(); + + // Preserve the single-argument constructor used by custom and generated ViewModels. + private static final ThreadLocal CONSTRUCTING = new ThreadLocal<>(); /** * Prevents instantiation. @@ -23,32 +25,26 @@ final class ViewModels { private ViewModels() { } - /** - * Returns the ViewModel for a Model instance, building the generic one when none exists yet. - * - * @param model the Model instance - * @return the ViewModel for that instance, or a replacement that exposes JavaFX properties by name - */ static Object of(Object model) { return of(model, null); } - /** - * Returns the ViewModel for a Model instance. - *

- * Selects a registered default or compatible explicit class before construction. Without - * a registered default, a null class or {@link ViewModel} itself uses the generic ViewModel. - * An unregistered replacement may expose JavaFX properties by name. The container does not - * create it. The first View fixes the instance; later compatible superclass/interface requests - * reuse it, while incompatible requests fail. A View naming no class reuses the instance. - * - * @param model the Model instance - * @param viewModelClass the class named by {@link ViewModelClass}, or {@code null} - * @return the ViewModel for that instance, or the replacement - */ static Object of(Object model, Class viewModelClass) { + return of(LEGACY, model, viewModelClass); + } + + static ViewModelContext constructingContext() { + ViewModelContext context = CONSTRUCTING.get(); + return context == null ? LEGACY : context; + } + + /** + * Gets or builds the ViewModel for this Model identity in the caller's context. + */ + static Object of(ViewModelContext context, Object model, Class viewModelClass) { + Map instances = context.viewModels(); Class selected = ViewModelDefaults.select(model.getClass(), viewModelClass, model.getClass().getClassLoader()); - Object existing = BY_INSTANCE.get(model); + Object existing = instances.get(model); if (existing != null) { if (viewModelClass != null && viewModelClass != ViewModel.class && !selected.isInstance(existing)) { @@ -58,8 +54,22 @@ final class ViewModels { } return existing; } - if (selected == ViewModel.class) return new ViewModel(model); - return construct(model, selected); + ViewModelContext previous = CONSTRUCTING.get(); + CONSTRUCTING.set(context); + try { + Object created = selected == ViewModel.class ? new ViewModel(model) : construct(model, selected); + instances.put(model, created); + return created; + } catch (RuntimeException | Error failure) { + instances.remove(model); + throw failure; + } finally { + if (previous == null) { + CONSTRUCTING.remove(); + } else { + CONSTRUCTING.set(previous); + } + } } /** @@ -83,8 +93,7 @@ final class ViewModels { /** * Constructs a ViewModel or a replacement with the Model instance. *

- * A result that is not a {@link ViewModel} is registered here. A {@link ViewModel} registers - * itself from its constructor, before its Attributes are walked. + * A {@link ViewModel} registers itself from its constructor, before its Attributes are walked. * * @param model the Model instance * @param viewModelClass the class to construct @@ -94,13 +103,8 @@ final class ViewModels { Constructor constructor = constructor(model, viewModelClass); constructor.setAccessible(true); try { - Object created = constructor.newInstance(model); - if (!(created instanceof ViewModel)) { - register(model, created); - } - return created; + return constructor.newInstance(model); } catch (InvocationTargetException failure) { - BY_INSTANCE.remove(model); if (failure.getCause() instanceof RuntimeException runtime) { throw runtime; } @@ -138,13 +142,4 @@ final class ViewModels { return chosen; } - /** - * Records a ViewModel before its Attributes are walked, so a cycle reuses it. - * - * @param model the Model instance - * @param viewModel the ViewModel under construction - */ - static void register(Object model, Object viewModel) { - BY_INSTANCE.put(model, viewModel); - } } diff --git a/fx/src/test/java/de/neitzel/fx/view/AsyncCommandTest.java b/fx/src/test/java/de/neitzel/fx/view/AsyncCommandTest.java new file mode 100644 index 0000000..b1afec0 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/AsyncCommandTest.java @@ -0,0 +1,287 @@ +package de.neitzel.fx.view; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javafx.application.Platform; +import javafx.beans.binding.Bindings; +import javafx.beans.property.SimpleBooleanProperty; +import javafx.concurrent.Task; +import javafx.event.ActionEvent; +import javafx.scene.control.Button; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static de.neitzel.fx.view.AsyncCommand.Phase.*; +import static org.junit.jupiter.api.Assertions.*; + +class AsyncCommandTest { + + @BeforeAll + static void start() throws Exception { + FxThread.start(); + FxThread.onFx(() -> Platform.setImplicitExit(false)); + } + + @Test + void publishesRunningBeforeSchedulingAndReportsProgressAndOneResult() throws Exception { + var available = new SimpleBooleanProperty(false); + var queue = new QueueExecutor(); + var command = new AtomicReference>(); + var states = new ArrayList>(); + var calls = new AtomicInteger(); + + FxThread.onFx(() -> { + var async = new AsyncCommand<>(available, action -> { + assertEquals(RUNNING, command.get().getState().phase()); + queue.execute(action); + }, () -> new Task() { + @Override + protected String call() { + calls.incrementAndGet(); + updateMessage("Saving"); + updateProgress(1, 2); + return "saved"; + } + }); + command.set(async); + async.stateProperty().addListener((source, previous, next) -> { + assertTrue(Platform.isFxApplicationThread()); + states.add(next); + }); + async.getCommand().execute(); + assertEquals(IDLE, async.getState().phase()); + + available.set(true); + async.getCommand().execute(); + async.getCommand().execute(); + assertFalse(async.cancel()); + assertFalse(async.getCommand().getCanExecute().get()); + assertEquals(1, queue.size()); + }); + + runWorker(queue.remove()); + FxThread.onFx(() -> { + var async = command.get(); + assertEquals(1, calls.get()); + assertTrue(states.stream().anyMatch(state -> state.running() && state.message().equals("Saving"))); + assertEquals(1, states.stream().filter(state -> state.phase() == SUCCEEDED).count()); + assertEquals(new AsyncCommand.State<>(SUCCEEDED, "saved", null, 0.5, "Saving"), async.getState()); + assertTrue(async.getCommand().getCanExecute().get()); + async.close(); + }); + } + + @Test + void reportsSynchronousAndWorkerFailuresAndAllowsRetry() throws Exception { + var queue = new QueueExecutor(); + var command = new AtomicReference>(); + var starts = new AtomicInteger(); + var failures = new ArrayList(); + var factoryFailure = new IllegalArgumentException("factory"); + var schedulingFailure = new RejectedExecutionException("executor"); + var operationFailure = new IllegalStateException("worker"); + FxThread.onFx(() -> { + var async = new AsyncCommand<>(new SimpleBooleanProperty(true), work -> { + if (starts.get() == 2) throw schedulingFailure; + queue.execute(work); + }, () -> switch (starts.incrementAndGet()) { + case 1 -> throw factoryFailure; + case 2 -> task(() -> "not scheduled"); + case 3 -> task(() -> { throw operationFailure; }); + default -> task(() -> "retry"); + }); + command.set(async); + async.stateProperty().addListener((source, previous, next) -> { + if (next.phase() == FAILED) failures.add(next.error()); + }); + async.getCommand().execute(); + assertSame(factoryFailure, async.getState().error()); + async.getCommand().execute(); + assertSame(schedulingFailure, async.getState().error()); + async.getCommand().execute(); + }); + runWorker(queue.remove()); + FxThread.onFx(() -> { + assertEquals(List.of(factoryFailure, schedulingFailure, operationFailure), failures); + assertSame(operationFailure, command.get().getState().error()); + command.get().getCommand().execute(); + }); + runWorker(queue.remove()); + FxThread.onFx(() -> { + assertEquals("retry", command.get().getState().result()); + command.get().close(); + }); + } + + @Test + void cancellationKeepsSlotUntilTheWorkerLeavesAndPublishesOneCompletion() throws Exception { + var queue = new QueueExecutor(); + var command = new AtomicReference>(); + var entered = new CountDownLatch(1); + var interrupted = new CountDownLatch(1); + var release = new CountDownLatch(1); + var cancellations = new AtomicInteger(); + FxThread.onFx(() -> { + var async = new AsyncCommand<>(new SimpleBooleanProperty(true), queue, () -> task(() -> { + entered.countDown(); + try { + new CountDownLatch(1).await(); + } catch (InterruptedException cancellation) { + interrupted.countDown(); + assertTrue(release.await(5, TimeUnit.SECONDS), "waiting to clean up after interrupt"); + } + return "ignored"; + }), true); + command.set(async); + async.stateProperty().addListener((source, previous, next) -> { + if (next.phase() == CANCELLED) cancellations.incrementAndGet(); + }); + async.getCommand().execute(); + }); + var worker = Thread.ofVirtual().start(queue.remove()); + try { + assertTrue(entered.await(5, TimeUnit.SECONDS)); + FxThread.onFx(() -> assertTrue(command.get().cancel())); + assertTrue(interrupted.await(5, TimeUnit.SECONDS)); + FxThread.onFx(() -> { + var async = command.get(); + assertTrue(async.getState().running()); + async.getCommand().execute(); + assertEquals(0, queue.size()); + }); + } finally { + release.countDown(); + worker.join(5000); + } + FxThread.onFx(() -> { + var async = command.get(); + assertEquals(CANCELLED, async.getState().phase()); + assertEquals(1, cancellations.get()); + assertTrue(async.getCommand().getCanExecute().get()); + async.close(); + }); + } + + @Test + void oldCancellationCannotOverwriteANewerRunAndCloseDoesNotStopItsWorker() throws Exception { + var queue = new QueueExecutor(); + var command = new AtomicReference>(); + var calls = new AtomicInteger(); + var phases = new ArrayList(); + FxThread.onFx(() -> { + var async = new AsyncCommand<>(new SimpleBooleanProperty(true), queue, + () -> task(() -> "run " + calls.incrementAndGet()), true); + command.set(async); + async.stateProperty().addListener((source, previous, next) -> phases.add(next.phase())); + async.getCommand().execute(); + assertTrue(async.cancel()); + assertEquals(CANCELLED, async.getState().phase()); + async.getCommand().execute(); + }); + runWorker(queue.remove()); + FxThread.onFx(() -> { + var async = command.get(); + assertEquals(RUNNING, async.getState().phase()); + assertEquals(0, calls.get()); + async.close(); + async.close(); + async.getCommand().execute(); + assertFalse(async.cancel()); + assertFalse(async.getCommand().getCanExecute().get()); + }); + runWorker(queue.remove()); + FxThread.onFx(() -> { + assertEquals(1, calls.get()); + assertEquals(List.of(RUNNING, CANCELLED, RUNNING, CLOSED), phases); + assertEquals(CLOSED, command.get().getState().phase()); + }); + } + + @Test + void aGeneratedDialogButtonClosesOnlyAfterASuccessfulTask() throws Exception { + var queue = new QueueExecutor(); + var dialogRef = new AtomicReference>(); + var saveButtonRef = new AtomicReference