3 Commits
29 changed files with 908 additions and 26 deletions
+3 -3
View File
@@ -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.4
## 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.4`, 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:
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</dependency>
</dependencies>
```
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>core</artifactId>
+1 -1
View File
@@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.4</version></parent>
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.5</version></parent>
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
<dependencies><dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
+1 -1
View File
@@ -1,6 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.4</version></parent>
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.5</version></parent>
<artifactId>data-grid</artifactId>
<description>Toolkit-independent filter, query and grid setup contracts</description>
</project>
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>encryption</artifactId>
+2 -2
View File
@@ -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.4` 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.4.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.
+1 -1
View File
@@ -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.4.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.
+1 -1
View File
@@ -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.4.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
```
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>fx-example</artifactId>
+56 -1
View File
@@ -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.4` | 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 |
@@ -298,6 +298,61 @@ availability as the condition for disabling these controls. The managed View det
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<T>` when a Command starts a JavaFX `Task<T>`. 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<Void>`. 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<Boolean>();
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<Void>(valid, executor, createSaveTask)) {
saveButton.disableProperty().bind(Bindings.not(saving.getCommand().getCanExecute()));
EventHandler<ActionEvent> 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.
+21
View File
@@ -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<String> summaryProperty()` on the ViewModel and declare the label binding.
```xml
<DirectBinding control="summary" property="text" path="summary" direction="view"/>
```
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<Boolean>)` lets the application save/discard/block unfinished edits. `setAllConfirmation((query, count) -> CompletionStage<Boolean>)` 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.
+4 -4
View File
@@ -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.4. 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.4 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/
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@@ -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.4` 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. |
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>fx</artifactId>
@@ -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<T> 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 <T> result type
*/
public record State<T>(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 <T> State<T> 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<T>> state = new ReadOnlyObjectWrapper<>(State.of(Phase.IDLE));
private final Executor executor;
private final Supplier<? extends Task<T>> tasks;
private final boolean cancellable;
private Execution current;
/**
* Creates a command with no user cancellation.
*
* @param available the application's availability rule
* @param executor the executor that runs tasks outside the FX application thread
* @param tasks factory invoked on the FX application thread to supply a fresh, ready task
*/
public AsyncCommand(ObservableBooleanValue available, Executor executor, Supplier<? extends Task<T>> tasks) {
this(available, executor, tasks, false);
}
/**
* Creates a command with optional cancellation. A cancellable Task must cooperate with
* interruption and implement any application-specific rollback in its worker.
*
* @param available the application's availability rule
* @param executor the executor that runs tasks outside the FX application thread
* @param tasks factory invoked on the FX application thread to supply a fresh, ready task
* @param cancellable whether {@link #cancel()} may cancel a running execution
*/
public AsyncCommand(ObservableBooleanValue available, Executor executor, Supplier<? extends Task<T>> 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<T> getState() {
return state.get();
}
/** Returns a read-only property for observing progress and completion together. */
public ReadOnlyObjectProperty<State<T>> 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<T> 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<T> 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<Worker.State> 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<T> 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<T> 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);
}
}
}
}
@@ -94,6 +94,8 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
}
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this);
private final ReadOnlyObjectWrapper<GridSelection<K, T>> selection =
new ReadOnlyObjectWrapper<>(GridSelection.empty());
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ReadOnlyListWrapper<K> selectedKeys = new ReadOnlyListWrapper<>(
@@ -292,6 +294,7 @@ public final class DataGrid<K, T> 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<K, T> extends VBox implements AutoCloseable {
public ReadOnlyListProperty<T> 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<K, T> observeSelection() {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
return new DataGridSelection<>(this, selection.getReadOnlyProperty());
}
public void selectKeys(Collection<? extends K> keys) {
check();
renderer.selectKeys(keys);
@@ -1339,6 +1354,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
if (renderer != null) renderer.close();
selectedKey.unbind();
selectedElement.unbind();
selection.unbind();
selectedKeys.unbind();
selectedElements.unbind();
selectedKeys.set(FXCollections.emptyObservableList());
@@ -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 <K> row key type
* @param <T> row model type
*/
public final class DataGridSelection<K, T> implements AutoCloseable {
private final ReadOnlyObjectWrapper<GridSelection<K, T>> selection = new ReadOnlyObjectWrapper<>();
private DataGrid<K, T> grid;
DataGridSelection(DataGrid<K, T> grid, ReadOnlyObjectProperty<GridSelection<K, T>> source) {
this.grid = grid;
selection.bind(source);
}
/** Returns one read-only observable containing the selected keys and available elements. */
public ReadOnlyObjectProperty<GridSelection<K, T>> selectionProperty() {
return selection.getReadOnlyProperty();
}
/** Returns the current snapshot, or the last snapshot when the adapter is closed. */
public GridSelection<K, T> 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<? extends K> keys) {
requireOpen().selectKeys(keys);
}
private DataGrid<K, T> 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;
}
}
@@ -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 <K> row key type
* @param <T> row model type
*/
public record GridSelection<K, T>(
List<K> selectedKeys, List<T> 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 <K, T> GridSelection<K, T> 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<K, T> 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;
}
}
@@ -41,6 +41,8 @@ public final class TableResults<K, T> implements AutoCloseable {
private List<String> order;
private final Set<String> hiddenColumns = new HashSet<>();
private List<Entry<K, T>> entries = List.of();
private final ReadOnlyObjectWrapper<GridSelection<K, T>> selection =
new ReadOnlyObjectWrapper<>(GridSelection.empty());
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ObservableList<K> selectedKeys = FXCollections.observableArrayList();
@@ -131,6 +133,10 @@ public final class TableResults<K, T> implements AutoCloseable {
/** Only selected models currently visible and interactive are actionable. */
public ReadOnlyListProperty<T> selectedElementsProperty() { return elementsView.getReadOnlyProperty(); }
ReadOnlyObjectProperty<GridSelection<K, T>> selectionProperty() {
return selection.getReadOnlyProperty();
}
public RowSelectionMode getSelectionMode() { return selectionMode; }
public void setSelectionMode(RowSelectionMode mode) {
@@ -623,6 +629,10 @@ public final class TableResults<K, T> implements AutoCloseable {
}
selectedElement.set(rowsInteractive ? loaded : null);
selectedElements.setAll(actionable);
GridSelection<K, T> 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<K, T> 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();
@@ -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<AsyncCommand<String>>();
var states = new ArrayList<AsyncCommand.State<String>>();
var calls = new AtomicInteger();
FxThread.onFx(() -> {
var async = new AsyncCommand<>(available, action -> {
assertEquals(RUNNING, command.get().getState().phase());
queue.execute(action);
}, () -> new Task<String>() {
@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<AsyncCommand<String>>();
var starts = new AtomicInteger();
var failures = new ArrayList<Throwable>();
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<AsyncCommand<String>>();
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<AsyncCommand<String>>();
var calls = new AtomicInteger();
var phases = new ArrayList<AsyncCommand.Phase>();
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<Dialog<Boolean>>();
var saveButtonRef = new AtomicReference<Button>();
FxThread.onFx(() -> {
var dialog = new Dialog<Boolean>();
dialogRef.set(dialog);
var save = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().setAll(save, ButtonType.CANCEL);
dialog.setResultConverter(button -> false);
var async = new AsyncCommand<>(new SimpleBooleanProperty(true), queue, () -> task(() -> "saved"));
var button = (Button) dialog.getDialogPane().lookupButton(save);
saveButtonRef.set(button);
button.disableProperty().bind(Bindings.not(async.getCommand().getCanExecute()));
button.addEventFilter(ActionEvent.ACTION, event -> {
event.consume();
async.getCommand().execute();
});
dialog.setOnCloseRequest(event -> {
if (async.getState().running()) event.consume();
});
async.stateProperty().addListener((source, previous, state) -> {
if (state.phase() == SUCCEEDED) {
dialog.setResult(true);
dialog.close();
}
});
dialog.setOnHidden(event -> async.close());
dialog.show();
button.fire();
assertTrue(dialog.isShowing());
assertTrue(button.isDisable());
assertTrue(async.getState().running());
});
runWorker(queue.remove());
FxThread.onFx(() -> {
assertFalse(dialogRef.get().isShowing());
assertEquals(Boolean.TRUE, dialogRef.get().getResult());
assertTrue(saveButtonRef.get().isDisable());
});
}
private static Task<String> task(Callable<String> work) {
return new Task<>() {
@Override
protected String call() throws Exception {
return work.call();
}
};
}
private static void runWorker(Runnable job) throws InterruptedException {
var worker = Thread.ofVirtual().start(job);
worker.join(5000);
assertFalse(worker.isAlive());
}
private static final class QueueExecutor implements Executor {
private final ArrayDeque<Runnable> work = new ArrayDeque<>();
@Override
public void execute(Runnable action) {
work.addLast(action);
}
int size() {
return work.size();
}
Runnable remove() {
return work.removeFirst();
}
}
}
@@ -0,0 +1,144 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.DataGridTest.Item;
import de.neitzel.grid.TextFilter;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.Label;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ObserveGridSelectionTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
}
@Test
void publishesOneCoherentChangeToTheViewAndStopsAfterClose() throws Exception {
var first = new Item(1, "Alpha");
var second = new Item(2, "Beta");
var grid = new AtomicReference<DataGrid<Long, Item>>();
FxThread.onFx(() -> {
grid.set(DataGridTest.grid(List.of(first, second), new AtomicInteger()));
grid.get().refresh();
});
try {
DataGridTest.drain();
FxThread.onFx(() -> {
var control = grid.get();
control.select(1L);
var document = getClass().getResource("grid-selection-summary.fxml");
var context = new ApplicationContext("de.neitzel.fx.view.selection");
try (var selection = control.observeSelection();
var models = new ViewModelContext();
var view = ViewLoader.load(document, selection, context, models)) {
var initial = selection.getSelection();
var summary = (Label) view.getRoot().lookup("#summary");
assertEquals(List.of(1L), initial.selectedKeys());
assertEquals(List.of(first), initial.selectedElements());
assertEquals("[1] · 1 visible", summary.getText());
assertThrows(UnsupportedOperationException.class, () -> initial.selectedKeys().clear());
assertThrows(UnsupportedOperationException.class, () -> initial.selectedElements().clear());
var changes = new ArrayList<GridSelection<Long, Item>>();
selection.selectionProperty().addListener((observable, before, after) -> {
changes.add(after);
selection.selectKeys(after.selectedKeys());
});
var liveKeys = control.selectedKeysProperty().get();
selection.select(2L);
assertSame(liveKeys, control.selectedKeysProperty().get());
assertEquals(List.of(new GridSelection<>(List.of(2L), List.of(second), 2L, second)), changes);
assertEquals("[2] · 1 visible", summary.getText());
assertEquals(List.of(first), initial.selectedElements());
selection.close();
selection.close();
control.select(1L);
assertEquals("[2] · 1 visible", summary.getText());
assertEquals(1, changes.size());
assertEquals(List.of(1L), control.selectedKeysProperty());
assertThrows(IllegalStateException.class, () -> selection.select(2L));
}
});
} finally {
FxThread.onFx(() -> grid.get().close());
}
}
@Test
void keepsUnloadedKeysThroughPagingFiltersDeletionAndRestoration() throws Exception {
var first = new Item(1, "Alpha");
var second = new Item(2, "Beta");
var items = new ArrayList<>(List.of(first, second));
var grid = new AtomicReference<DataGrid<Long, Item>>();
var selected = new AtomicReference<DataGridSelection<Long, Item>>();
FxThread.onFx(() -> {
var control = DataGridTest.grid(items, new AtomicInteger());
grid.set(control);
control.setSelectionMode(RowSelectionMode.MULTIPLE);
selected.set(control.observeSelection());
assertEquals(GridSelection.empty(), selected.get().getSelection());
control.setPageSize(1);
});
try {
DataGridTest.drain();
FxThread.onFx(() -> {
var adapter = selected.get();
adapter.selectKeys(List.of(1L, 2L));
var current = adapter.getSelection();
assertEquals(List.of(1L, 2L), current.selectedKeys());
assertEquals(List.of(first), current.selectedElements());
assertEquals(2L, current.leadKey());
assertNull(current.leadElement());
grid.get().next();
assertEquals(List.of(), adapter.getSelection().selectedElements());
});
DataGridTest.drain();
FxThread.onFx(() -> {
var current = selected.get().getSelection();
assertEquals(List.of(1L, 2L), current.selectedKeys());
assertEquals(List.of(second), current.selectedElements());
assertSame(second, current.leadElement());
grid.get().setFilters(List.of(new TextFilter("text", TextFilter.Operator.EQUALS, "Alpha", false)));
});
DataGridTest.drain();
FxThread.onFx(() -> {
assertEquals(List.of(1L, 2L), selected.get().getSelection().selectedKeys());
assertEquals(List.of(first), selected.get().getSelection().selectedElements());
items.remove(first);
grid.get().confirmedDeleted(1L);
assertEquals(List.of(2L), selected.get().getSelection().selectedKeys());
grid.get().setFilters(List.of());
});
DataGridTest.drain();
FxThread.onFx(() -> {
var adapter = selected.get();
assertEquals(List.of(second), adapter.getSelection().selectedElements());
adapter.select(null);
assertEquals(GridSelection.empty(), adapter.getSelection());
adapter.selectKeys(List.of(2L));
assertSame(second, adapter.getSelection().leadElement());
grid.get().close();
assertEquals(GridSelection.empty(), adapter.getSelection());
});
} finally {
FxThread.onFx(() -> {
selected.get().close();
grid.get().close();
});
}
}
}
@@ -0,0 +1,25 @@
package de.neitzel.fx.view.selection;
import de.neitzel.fx.view.DataGridSelection;
import de.neitzel.fx.view.ViewModelClass;
import jakarta.inject.Singleton;
import javafx.beans.value.ObservableValue;
/** Supplies a read-only summary of the selected keys and available rows. */
@Singleton
@ViewModelClass(SelectionSummaryController.Summary.class)
public class SelectionSummaryController {
public static class Summary {
private final ObservableValue<String> summary;
public Summary(DataGridSelection<?, ?> selection) {
summary = selection.selectionProperty().map(state ->
state.selectedKeys() + " · " + state.selectedElements().size() + " visible");
}
public ObservableValue<String> summaryProperty() {
return summary;
}
}
}
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1"
fx:controller="de.neitzel.fx.view.selection.SelectionSummaryController">
<fx:define>
<BindingList>
<DirectBinding control="summary" property="text" path="summary" direction="view"/>
</BindingList>
</fx:define>
<Label fx:id="summary"/>
</VBox>
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>gson</artifactId>
+2 -2
View File
@@ -8,13 +8,13 @@ The worked example is the person desk in `fx-example`, package `de.neitzel.fx.ex
## Quick start
Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0.1 (plus shared logging dependencies). The parent artifact is `de.neitzel.lib:neitzellib:1.0.4`. Java 25.
Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0.1 (plus shared logging dependencies). The parent artifact is `de.neitzel.lib:neitzellib:1.0.5`. Java 25.
```xml
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>injection</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</dependency>
```
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>injection</artifactId>
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>log4j</artifactId>
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>net</artifactId>
+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
<packaging>pom</packaging>
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<artifactId>quarkus</artifactId>