Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f585ab9cd9 | ||
|
|
82067cfc1a | ||
|
|
407ecc28c7 | ||
|
|
0037f089b9 | ||
|
|
83e0bdf8d4 | ||
|
|
2625616b2f | ||
|
|
9522ed90ce | ||
|
|
4a455e63ab | ||
|
|
e4f1fd3c96 | ||
|
|
514cc7fb8e | ||
|
|
ac992167bc | ||
|
|
50046be154 | ||
|
|
597252f676 | ||
|
|
073b4a65dc | ||
|
|
f1b2fd24d4 | ||
|
|
d8b2871f24 | ||
|
|
7b3f98f489 | ||
|
|
e37a66dfa8 | ||
|
|
081d94e373 | ||
|
|
13cd3c8c7f | ||
|
|
2553d04e82 | ||
|
|
ad5b901bbe | ||
|
|
1ff9753de8 | ||
|
|
a3f7d2423f | ||
|
|
981cd68f49 | ||
|
|
e915ed392f | ||
|
|
2d12a7d393 | ||
|
|
8aefe53ad1 | ||
|
|
12aad4d3a1 | ||
|
|
fba2735e1e | ||
|
|
17c36ccae7 | ||
|
|
42c1ee19a1 | ||
|
|
dcd26a088f | ||
|
|
f7ae3c4688 | ||
|
|
b2e0724611 | ||
|
|
32f8d28159 | ||
|
|
f8ab7fc1d7 | ||
|
|
944227d0bd | ||
|
|
e978ee7ca8 | ||
|
|
a14d1d7e48 | ||
|
|
257e0edb28 | ||
|
|
91d9cdccaa | ||
|
|
7f2a62777d |
@@ -34,7 +34,7 @@ domain or usable under a license compatible with this project's license.
|
|||||||
### core
|
### core
|
||||||
|
|
||||||
Core utilities, including [foreground desktop observations](core/docs/foreground-detection.md)
|
Core utilities, including [foreground desktop observations](core/docs/foreground-detection.md)
|
||||||
using JNA for optional native desktop integration, and [native application configuration folders](core/docs/application-directories.md).
|
using JNA for optional native desktop integration, and [native application configuration folders](core/docs/application-directories.md). Use [ImageScaler.fitOpaque](core/docs/image-fitting.md) to fit images within bounds and composite transparent pixels onto a background.
|
||||||
|
|
||||||
### encryption
|
### encryption
|
||||||
|
|
||||||
@@ -52,7 +52,13 @@ Optional mapped JDBC DataGrid source, initially qualified with H2. See [data-gri
|
|||||||
|
|
||||||
### fx
|
### fx
|
||||||
|
|
||||||
JavaFX docking, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md).
|
JavaFX docking, saved HTML/SingleFile viewing, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md).
|
||||||
|
|
||||||
|
### fx-test
|
||||||
|
|
||||||
|
JavaFX fixtures for JUnit Jupiter. Add `de.neitzel.lib:fx-test` at the same version as `fx` with Maven scope `test`. Annotate the class with `@FxTest` and accept an `FxFixture` parameter in each test. Use `fx.run` for actions, `fx.call` for values and `fx.await("dialog closed", () -> !dialog.isShowing())` to wait from the test thread. `fx.load(fxml, model, services)` uses the production ViewLoader and a fresh ViewModelContext per test.
|
||||||
|
|
||||||
|
The extension keeps JavaFX running between tests, isolates the class with JUnit's `@Isolated`, hides windows opened by each test, closes its view context and reports unhandled FX callbacks at teardown. Complete background work before the test ends. Select the backend in the test JVM before toolkit startup, for example `-Dglass.platform=Headless`.
|
||||||
|
|
||||||
### injection
|
### injection
|
||||||
|
|
||||||
@@ -64,20 +70,19 @@ Person desk that shows how to use `fx` and `injection`. Build with `./mvnw -pl f
|
|||||||
|
|
||||||
### gson
|
### gson
|
||||||
|
|
||||||
TypeAdapter for gson.
|
Gson configuration and type adapters, plus JSON storage for versioned DataGrid setups. See the [Gson guide](gson/README.md).
|
||||||
|
|
||||||
### log4j
|
### log4j
|
||||||
|
|
||||||
Stuff for log4j (Version 1). Please use log4j2 if you want to use log4j! (Or log with slf4j as I do in all other
|
Configuration helpers for legacy Log4j 1 applications.
|
||||||
modules!)
|
|
||||||
|
|
||||||
### net
|
### net
|
||||||
|
|
||||||
Some network stuff using javax.mail as dependency.
|
IMAP account monitoring, new-message events and message utilities built on JavaMail.
|
||||||
|
|
||||||
### quarkus
|
### quarkus
|
||||||
|
|
||||||
Some additions for quarkus that might be useful.
|
Request filters and route logging for Quarkus applications.
|
||||||
|
|
||||||
## Start a JavaFX project
|
## Start a JavaFX project
|
||||||
|
|
||||||
@@ -85,9 +90,28 @@ 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.
|
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.6
|
||||||
|
|
||||||
|
- Load managed FXML Components independently and bind read-only observables, HTML and replaceable suggestion lists toward the view.
|
||||||
|
- Use the new `fx-test` module for JavaFX and managed FXML tests with JUnit Jupiter.
|
||||||
|
- Use literal DataGrid group-label keys in FXML, including file types and paths with spaces.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
- Use reusable action icons with tooltips and accessible names in JavaFX controls.
|
||||||
|
|
||||||
|
## Changes in 1.0.2
|
||||||
|
|
||||||
|
- Display saved HTML and SingleFile archives offline with [HtmlViewer](fx/docs/html-viewer.md). Each viewer can grant external image access for its current document.
|
||||||
|
- Configure single, multiple or disabled [DataGrid row selection](fx/docs/data-grid.md). Applications can track selected keys across pages and access the selected rows on the current page.
|
||||||
|
- Offer prefix suggestions with `AutoCompleteTextField`, removable tags with `TagChip`, and dismissible toolbars with `ToolBarPane`. See the [FXML control reference](fx/docs/fxml-controls.md).
|
||||||
|
- Give each window a [platform menu bar](fx/docs/bars.md#window-menus), including floating docking windows. Use [message catalogs](fx/docs/i18n.md) to translate FXML and Java controls and offer a language menu.
|
||||||
|
|
||||||
## Use a release from Maven
|
## Use a release from Maven
|
||||||
|
|
||||||
Add the Gitea registry to the consuming project's POM and use the release
|
To use release `1.0.6`, add the Gitea registry to the consuming project's POM and use the release
|
||||||
version for the module you need:
|
version for the module you need:
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
@@ -102,7 +126,7 @@ version for the module you need:
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.6</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -71,9 +71,7 @@ detection is working. No compositor extensions or bridges are installed.
|
|||||||
## Tests and observed evidence
|
## Tests and observed evidence
|
||||||
|
|
||||||
Public capability/lifecycle tests run with `mvn -pl core
|
Public capability/lifecycle tests run with `mvn -pl core
|
||||||
-Dtest=ForegroundDetectorTest -Dmaven.test.failure.ignore=false test`. The parent
|
-Dtest=ForegroundDetectorTest test`. Surefire fails the build when a test fails.
|
||||||
project otherwise permits ignored test failures, so use that override when
|
|
||||||
verifying acceptance.
|
|
||||||
|
|
||||||
Native opt-in smoke check: add `-Ddesktop.native.tests=true` in a graphical
|
Native opt-in smoke check: add `-Ddesktop.native.tests=true` in a graphical
|
||||||
session with an identifiable external application foreground. It validates focus
|
session with an identifiable external application foreground. It validates focus
|
||||||
|
|||||||
+5
-2
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.6</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>core</artifactId>
|
<artifactId>core</artifactId>
|
||||||
@@ -18,13 +18,16 @@
|
|||||||
<launcher>${project.artifactId}</launcher>
|
<launcher>${project.artifactId}</launcher>
|
||||||
<appName>${project.artifactId}</appName>
|
<appName>${project.artifactId}</appName>
|
||||||
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
|
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
|
||||||
|
|
||||||
|
<!-- Dependency versions -->
|
||||||
|
<jna.version>5.19.1</jna.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.java.dev.jna</groupId>
|
<groupId>net.java.dev.jna</groupId>
|
||||||
<artifactId>jna</artifactId>
|
<artifactId>jna</artifactId>
|
||||||
<version>5.19.1</version>
|
<version>${jna.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.reflections</groupId>
|
<groupId>org.reflections</groupId>
|
||||||
|
|||||||
@@ -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">
|
<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</version></parent>
|
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.6</version></parent>
|
||||||
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
|
<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>
|
<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>
|
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>${h2.version}</version><scope>test</scope></dependency></dependencies></project>
|
||||||
|
|||||||
@@ -37,3 +37,16 @@ Collection changes do not automatically trigger requests in this slice. Call ref
|
|||||||
## Saved setups
|
## Saved setups
|
||||||
|
|
||||||
`GridDefinition.prepare` applies explicit definition migrations and validates column types/order, widths and source support. `GridSetup.ColumnState` carries stable type IDs. JSON is provided separately by `de.neitzel.lib:gson`; `data-grid` does not depend on JavaFX or Gson. See the [saved setup guide](../fx/docs/saved-setups.md).
|
`GridDefinition.prepare` applies explicit definition migrations and validates column types/order, widths and source support. `GridSetup.ColumnState` carries stable type IDs. JSON is provided separately by `de.neitzel.lib:gson`; `data-grid` does not depend on JavaFX or Gson. See the [saved setup guide](../fx/docs/saved-setups.md).
|
||||||
|
|
||||||
|
## Page-local grouping and application configuration
|
||||||
|
|
||||||
|
`GroupColumn`, `GroupProjection`, `GroupPath` and `GroupExpansion` capture typed
|
||||||
|
values and project a returned page without fetching or mutating source order.
|
||||||
|
GroupingSetup extends GridSetup v2 with ordered columns and explicit path choices;
|
||||||
|
old constructors/version-one documents remain supported. Group expansion retains
|
||||||
|
current choices plus a configurable inactive LRU history, never historical rows.
|
||||||
|
|
||||||
|
`GridApplicationConfiguration` owns debounced immutable setup snapshots and queued
|
||||||
|
saves after views detach. `GridSetupStore` requires revision-aware conditional
|
||||||
|
writes. The default optional JSON/file implementation is in Gson; no toolkit or
|
||||||
|
JSON dependency is introduced here. See the [integration guide](../fx/docs/data-grid-layout.md).
|
||||||
|
|||||||
+1
-1
@@ -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">
|
<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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0</version></parent>
|
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.6</version></parent>
|
||||||
<artifactId>data-grid</artifactId>
|
<artifactId>data-grid</artifactId>
|
||||||
<description>Toolkit-independent filter, query and grid setup contracts</description>
|
<description>Toolkit-independent filter, query and grid setup contracts</description>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -0,0 +1,378 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Application-owned, toolkit-independent save coordination. Accept immutable snapshots on the owner
|
||||||
|
* thread; this service serializes blocking store work on its scheduled worker. No I/O runs in
|
||||||
|
* construction. A detached view does not own or discard already accepted saves.
|
||||||
|
*/
|
||||||
|
public final class GridApplicationConfiguration {
|
||||||
|
public enum Phase {
|
||||||
|
IDLE,
|
||||||
|
LOADING,
|
||||||
|
PENDING,
|
||||||
|
SAVING,
|
||||||
|
SAVED,
|
||||||
|
ERROR,
|
||||||
|
CONFLICT,
|
||||||
|
CLOSED
|
||||||
|
}
|
||||||
|
|
||||||
|
public record State(Phase phase, long generation, boolean dirty, Throwable error) {}
|
||||||
|
|
||||||
|
public record Loaded(
|
||||||
|
GridSetupStore.Key key, GridSetupStore.Stored stored, long storageVersion) {}
|
||||||
|
|
||||||
|
private record Pending(long generation, GridSetup setup, boolean overwrite) {}
|
||||||
|
|
||||||
|
private static final class Slot {
|
||||||
|
final java.util.concurrent.locks.ReentrantLock io =
|
||||||
|
new java.util.concurrent.locks.ReentrantLock();
|
||||||
|
String revision;
|
||||||
|
long generation, storageVersion;
|
||||||
|
Pending pending;
|
||||||
|
ScheduledFuture<?> delay;
|
||||||
|
State state = new State(Phase.IDLE, 0, false, null);
|
||||||
|
final List<Consumer<State>> listeners = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
@lombok.Getter
|
||||||
|
@lombok.experimental.Accessors(fluent = true)
|
||||||
|
private final String applicationName;
|
||||||
|
|
||||||
|
private final GridSetupStore store;
|
||||||
|
private final ScheduledExecutorService worker;
|
||||||
|
private final boolean ownsWorker;
|
||||||
|
private final long debounceMillis;
|
||||||
|
private final Map<GridSetupStore.Key, Slot> slots = new LinkedHashMap<>();
|
||||||
|
private boolean closing, closed;
|
||||||
|
|
||||||
|
public GridApplicationConfiguration(String applicationName, GridSetupStore store) {
|
||||||
|
this(
|
||||||
|
applicationName,
|
||||||
|
store,
|
||||||
|
Duration.ofMillis(500),
|
||||||
|
Executors.newSingleThreadScheduledExecutor(r -> {
|
||||||
|
Thread thread = new Thread(r, "grid-setup-storage");
|
||||||
|
thread.setDaemon(true);
|
||||||
|
return thread;
|
||||||
|
}),
|
||||||
|
true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridApplicationConfiguration(
|
||||||
|
String applicationName,
|
||||||
|
GridSetupStore store,
|
||||||
|
Duration debounce,
|
||||||
|
ScheduledExecutorService worker,
|
||||||
|
boolean ownsWorker) {
|
||||||
|
if (applicationName == null
|
||||||
|
|| applicationName.isBlank()
|
||||||
|
|| applicationName.equals(".")
|
||||||
|
|| applicationName.equals("..")
|
||||||
|
|| applicationName.contains("/")
|
||||||
|
|| applicationName.contains("\\")
|
||||||
|
|| applicationName.indexOf(0) >= 0)
|
||||||
|
throw new IllegalArgumentException("Application name must be a directory name");
|
||||||
|
this.applicationName = applicationName;
|
||||||
|
this.store = Objects.requireNonNull(store);
|
||||||
|
debounceMillis = Objects.requireNonNull(debounce).toMillis();
|
||||||
|
if (debounceMillis < 0) throw new IllegalArgumentException("Negative debounce");
|
||||||
|
this.worker = Objects.requireNonNull(worker);
|
||||||
|
this.ownsWorker = ownsWorker;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Slot slot(GridSetupStore.Key key) {
|
||||||
|
return slots.computeIfAbsent(key, k -> new Slot());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireOpen() {
|
||||||
|
if (closed || closing) throw new IllegalStateException("Configuration is closing/closed");
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized State state(GridSetupStore.Key key) {
|
||||||
|
return slot(key).state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Listener callbacks may run on the storage thread; an FX adapter must dispatch them. */
|
||||||
|
public synchronized AutoCloseable observe(GridSetupStore.Key key, Consumer<State> listener) {
|
||||||
|
requireOpen();
|
||||||
|
var s = slot(key);
|
||||||
|
s.listeners.add(listener);
|
||||||
|
listener.accept(s.state);
|
||||||
|
return () -> {
|
||||||
|
synchronized (this) {
|
||||||
|
s.listeners.remove(listener);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private void emit(Slot slot, Phase phase, Throwable error) {
|
||||||
|
slot.state = new State(phase, slot.generation, slot.pending != null, error);
|
||||||
|
for (var listener : List.copyOf(slot.listeners)) listener.accept(slot.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Loaded> loadAsync(GridSetupStore.Key key) {
|
||||||
|
synchronized (this) {
|
||||||
|
requireOpen();
|
||||||
|
emit(slot(key), Phase.LOADING, null);
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
Slot target;
|
||||||
|
synchronized (this) {
|
||||||
|
target = slot(key);
|
||||||
|
}
|
||||||
|
target.io.lock();
|
||||||
|
try {
|
||||||
|
GridSetupStore.Stored loaded = store.load(key);
|
||||||
|
synchronized (this) {
|
||||||
|
return new Loaded(key, loaded, target.storageVersion);
|
||||||
|
}
|
||||||
|
} catch (Exception failure) {
|
||||||
|
synchronized (this) {
|
||||||
|
emit(target, Phase.ERROR, failure);
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
} finally {
|
||||||
|
target.io.unlock();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Called only after the grid has successfully validated/published this loaded setup. */
|
||||||
|
public synchronized void adopt(Loaded loaded, long discardedOwnGeneration) {
|
||||||
|
requireOpen();
|
||||||
|
Slot s = slot(loaded.key());
|
||||||
|
if (s.storageVersion == loaded.storageVersion()) s.revision = loaded.stored().revision();
|
||||||
|
if (s.pending != null && s.pending.generation() == discardedOwnGeneration) {
|
||||||
|
s.pending = null;
|
||||||
|
if (s.delay != null) s.delay.cancel(false);
|
||||||
|
}
|
||||||
|
emit(s, s.pending == null ? Phase.SAVED : Phase.PENDING, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized long accept(GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||||
|
return accept(key, setup, owner, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized long acceptOverwrite(
|
||||||
|
GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||||
|
return accept(key, setup, owner, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long accept(GridSetupStore.Key key, GridSetup setup, Object owner, boolean overwrite) {
|
||||||
|
requireOpen();
|
||||||
|
Slot s = slot(key);
|
||||||
|
// Owner is an attribution token, never retained: it may be a closed UI view.
|
||||||
|
Objects.requireNonNull(owner);
|
||||||
|
s.pending = new Pending(++s.generation, Objects.requireNonNull(setup), overwrite);
|
||||||
|
if (s.delay != null) s.delay.cancel(false);
|
||||||
|
emit(s, Phase.PENDING, null);
|
||||||
|
long acceptedGeneration = s.generation;
|
||||||
|
s.delay =
|
||||||
|
worker.schedule(
|
||||||
|
() -> {
|
||||||
|
try {
|
||||||
|
write(key, acceptedGeneration);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
/* retained and exposed through state */
|
||||||
|
}
|
||||||
|
},
|
||||||
|
debounceMillis,
|
||||||
|
TimeUnit.MILLISECONDS);
|
||||||
|
return s.generation;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicit user recovery: still performs a conditional write against a fresh revision. */
|
||||||
|
public CompletionStage<Void> overwriteAsync(
|
||||||
|
GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||||
|
synchronized (this) {
|
||||||
|
accept(key, setup, owner, true);
|
||||||
|
}
|
||||||
|
return retryAsync(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> retryAsync(GridSetupStore.Key key) {
|
||||||
|
synchronized (this) {
|
||||||
|
requireOpen();
|
||||||
|
Slot s = slot(key);
|
||||||
|
if (s.delay != null) s.delay.cancel(false);
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
write(key);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void write(GridSetupStore.Key key) throws Exception {
|
||||||
|
write(key, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void write(GridSetupStore.Key key, long scheduledGeneration) throws Exception {
|
||||||
|
Slot target;
|
||||||
|
synchronized (this) {
|
||||||
|
target = slot(key);
|
||||||
|
}
|
||||||
|
target.io.lock();
|
||||||
|
try {
|
||||||
|
writeLocked(key, scheduledGeneration);
|
||||||
|
} finally {
|
||||||
|
target.io.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeLocked(GridSetupStore.Key key, long scheduledGeneration) throws Exception {
|
||||||
|
Pending pending;
|
||||||
|
String expected;
|
||||||
|
synchronized (this) {
|
||||||
|
Slot s = slot(key);
|
||||||
|
pending = s.pending;
|
||||||
|
if (pending == null
|
||||||
|
|| closed
|
||||||
|
|| (scheduledGeneration >= 0 && pending.generation() != scheduledGeneration))
|
||||||
|
return;
|
||||||
|
expected = s.revision;
|
||||||
|
emit(s, Phase.SAVING, null);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (pending.overwrite()) expected = store.revision(key);
|
||||||
|
if (expected == null)
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"Load or explicitly reset the saved setup before writing");
|
||||||
|
String revision = store.save(key, expected, pending.setup());
|
||||||
|
synchronized (this) {
|
||||||
|
Slot s = slot(key);
|
||||||
|
s.revision = revision;
|
||||||
|
s.storageVersion++;
|
||||||
|
if (s.pending != null && s.pending.generation() == pending.generation())
|
||||||
|
s.pending = null;
|
||||||
|
emit(s, s.pending == null ? Phase.SAVED : Phase.PENDING, null);
|
||||||
|
}
|
||||||
|
} catch (Exception failure) {
|
||||||
|
synchronized (this) {
|
||||||
|
emit(
|
||||||
|
slot(key),
|
||||||
|
failure instanceof GridSetupStore.Conflict ? Phase.CONFLICT : Phase.ERROR,
|
||||||
|
failure);
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> flushAsync() {
|
||||||
|
synchronized (this) {
|
||||||
|
if (closed) return CompletableFuture.completedFuture(null);
|
||||||
|
cancelDelays();
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
flush();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cancelDelays() {
|
||||||
|
slots.values()
|
||||||
|
.forEach(s -> {
|
||||||
|
if (s.delay != null) s.delay.cancel(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void flush() throws Exception {
|
||||||
|
while (true) {
|
||||||
|
List<GridSetupStore.Key> pending;
|
||||||
|
synchronized (this) {
|
||||||
|
pending =
|
||||||
|
slots.entrySet().stream()
|
||||||
|
.filter(e -> e.getValue().pending != null)
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
if (pending.isEmpty()) return;
|
||||||
|
for (var key : pending) write(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> closeAsync() {
|
||||||
|
synchronized (this) {
|
||||||
|
if (closed) return CompletableFuture.completedFuture(null);
|
||||||
|
if (closing) throw new IllegalStateException("Close already pending");
|
||||||
|
closing = true;
|
||||||
|
cancelDelays();
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
try {
|
||||||
|
flush();
|
||||||
|
finishClose();
|
||||||
|
return null;
|
||||||
|
} catch (Exception failure) {
|
||||||
|
synchronized (this) {
|
||||||
|
closing = false;
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicit quit-without-saving path. It cannot undo a write already committed. */
|
||||||
|
public CompletionStage<Void> discardAndCloseAsync() {
|
||||||
|
synchronized (this) {
|
||||||
|
if (closed) return CompletableFuture.completedFuture(null);
|
||||||
|
closing = true;
|
||||||
|
cancelDelays();
|
||||||
|
slots.values().forEach(s -> s.pending = null);
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
finishClose();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishClose() {
|
||||||
|
// A supplied scheduler may have multiple workers. Drain all in-flight slot I/O
|
||||||
|
// before publishing CLOSED, including an already-committing discarded write.
|
||||||
|
List<Slot> targets;
|
||||||
|
synchronized (this) {
|
||||||
|
targets = List.copyOf(slots.values());
|
||||||
|
}
|
||||||
|
targets.forEach(s -> s.io.lock());
|
||||||
|
try {
|
||||||
|
finishCloseLocked();
|
||||||
|
} finally {
|
||||||
|
for (int index = targets.size() - 1; index >= 0; index--)
|
||||||
|
targets.get(index).io.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishCloseLocked() {
|
||||||
|
synchronized (this) {
|
||||||
|
closed = true;
|
||||||
|
closing = false;
|
||||||
|
slots.values()
|
||||||
|
.forEach(s -> {
|
||||||
|
emit(s, Phase.CLOSED, null);
|
||||||
|
s.listeners.clear();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (ownsWorker) worker.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
private <V> CompletionStage<V> submit(Callable<V> action) {
|
||||||
|
CompletableFuture<V> future = new CompletableFuture<>();
|
||||||
|
try {
|
||||||
|
worker.execute(() -> {
|
||||||
|
try {
|
||||||
|
future.complete(action.call());
|
||||||
|
} catch (Exception failure) {
|
||||||
|
future.completeExceptionally(failure);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (RejectedExecutionException failure) {
|
||||||
|
future.completeExceptionally(failure);
|
||||||
|
}
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -57,7 +57,7 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
|||||||
Consumer<FilterCondition> validateFilter) {
|
Consumer<FilterCondition> validateFilter) {
|
||||||
Objects.requireNonNull(input);
|
Objects.requireNonNull(input);
|
||||||
Objects.requireNonNull(migrations);
|
Objects.requireNonNull(migrations);
|
||||||
if (input.formatVersion() != 1)
|
if (input.formatVersion() != 1 && input.formatVersion() != 2)
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"Unsupported setup format version: " + input.formatVersion());
|
"Unsupported setup format version: " + input.formatVersion());
|
||||||
if (!id.equals(input.definitionId()))
|
if (!id.equals(input.definitionId()))
|
||||||
@@ -75,7 +75,7 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
|||||||
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
|
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
|
||||||
if (!id.equals(setup.definitionId())
|
if (!id.equals(setup.definitionId())
|
||||||
|| setup.definitionVersion() != old + 1
|
|| setup.definitionVersion() != old + 1
|
||||||
|| setup.formatVersion() != 1)
|
|| setup.formatVersion() != input.formatVersion())
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"Migration must preserve identity/format and advance one definition"
|
"Migration must preserve identity/format and advance one definition"
|
||||||
+ " version");
|
+ " version");
|
||||||
@@ -123,7 +123,15 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
|||||||
source.validate(setup.page());
|
source.validate(setup.page());
|
||||||
setup.filters().forEach(validateFilter);
|
setup.filters().forEach(validateFilter);
|
||||||
return new Prepared(
|
return new Prepared(
|
||||||
new GridSetup(1, id, version, next, setup.sort(), setup.filters(), setup.page()),
|
new GridSetup(
|
||||||
|
setup.formatVersion(),
|
||||||
|
id,
|
||||||
|
version,
|
||||||
|
next,
|
||||||
|
setup.sort(),
|
||||||
|
setup.filters(),
|
||||||
|
setup.page(),
|
||||||
|
setup.grouping()),
|
||||||
adjustments);
|
adjustments);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,16 @@ import java.util.*;
|
|||||||
|
|
||||||
/** Plain versioned setup. No selection, credentials, page index, drafts, or approval tokens. */
|
/** Plain versioned setup. No selection, credentials, page index, drafts, or approval tokens. */
|
||||||
public record GridSetup(
|
public record GridSetup(
|
||||||
|
int formatVersion,
|
||||||
|
String definitionId,
|
||||||
|
int definitionVersion,
|
||||||
|
List<ColumnState> columns,
|
||||||
|
List<SortKey> sort,
|
||||||
|
List<FilterCondition> filters,
|
||||||
|
PageRequest page,
|
||||||
|
GroupingSetup grouping) {
|
||||||
|
/** Source/binary-compatible constructor for version-one clients. */
|
||||||
|
public GridSetup(
|
||||||
int formatVersion,
|
int formatVersion,
|
||||||
String definitionId,
|
String definitionId,
|
||||||
int definitionVersion,
|
int definitionVersion,
|
||||||
@@ -11,6 +21,9 @@ public record GridSetup(
|
|||||||
List<SortKey> sort,
|
List<SortKey> sort,
|
||||||
List<FilterCondition> filters,
|
List<FilterCondition> filters,
|
||||||
PageRequest page) {
|
PageRequest page) {
|
||||||
|
this(formatVersion, definitionId, definitionVersion, columns, sort, filters, page, null);
|
||||||
|
}
|
||||||
|
|
||||||
public record ColumnState(String id, String type, ColumnWidth width) {
|
public record ColumnState(String id, String type, ColumnWidth width) {
|
||||||
/** Older callers must supply a definition type before persistence/restoration. */
|
/** Older callers must supply a definition type before persistence/restoration. */
|
||||||
public ColumnState(String id, ColumnWidth width) {
|
public ColumnState(String id, ColumnWidth width) {
|
||||||
@@ -43,6 +56,17 @@ public record GridSetup(
|
|||||||
for (var f : filters)
|
for (var f : filters)
|
||||||
if (!ids.contains(f.columnId()))
|
if (!ids.contains(f.columnId()))
|
||||||
throw new IllegalArgumentException("Unknown filter column");
|
throw new IllegalArgumentException("Unknown filter column");
|
||||||
|
if (formatVersion == 2 && grouping == null)
|
||||||
|
throw new IllegalArgumentException("Version two requires grouping preferences");
|
||||||
|
if (grouping != null) {
|
||||||
|
for (String id : grouping.columns())
|
||||||
|
if (!ids.contains(id))
|
||||||
|
throw new IllegalArgumentException("Unknown grouping column");
|
||||||
|
for (var choice : grouping.choices())
|
||||||
|
for (var segment : choice.path().segments())
|
||||||
|
if (!ids.contains(segment.columnId()))
|
||||||
|
throw new IllegalArgumentException("Unknown group path column");
|
||||||
|
}
|
||||||
new GridQuery(filters, sort, page);
|
new GridQuery(filters, sort, page);
|
||||||
if (page instanceof PageRequest.Paged p && p.pageIndex() != 0)
|
if (page instanceof PageRequest.Paged p && p.pageIndex() != 0)
|
||||||
throw new IllegalArgumentException("Setups must start on the first page");
|
throw new IllegalArgumentException("Setups must start on the first page");
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/** Blocking store port. The configuration service calls it off the UI thread. */
|
||||||
|
public interface GridSetupStore {
|
||||||
|
record Key(String gridId, String context) {
|
||||||
|
public Key {
|
||||||
|
Checks.id(gridId);
|
||||||
|
if (context != null) Checks.id(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
record Stored(GridSetup setup, String revision) {
|
||||||
|
public Stored {
|
||||||
|
Objects.requireNonNull(revision);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Stored load(Key key) throws IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Revision alone must remain readable even when setup decoding fails, for explicit recovery.
|
||||||
|
*/
|
||||||
|
String revision(Key key) throws IOException;
|
||||||
|
|
||||||
|
/** Atomically compare revision and replace the entire setup; never a blind overwrite. */
|
||||||
|
String save(Key key, String expectedRevision, GridSetup setup) throws IOException;
|
||||||
|
|
||||||
|
final class Conflict extends IOException {
|
||||||
|
public Conflict() {
|
||||||
|
super(
|
||||||
|
"Saved grid setup changed in another application instance. Reload or explicitly"
|
||||||
|
+ " overwrite.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
/** Explicit owner-thread mapping. Labels never determine identity or ordering. */
|
||||||
|
public record GroupColumn<T>(
|
||||||
|
String id,
|
||||||
|
MemoryColumn.Kind kind,
|
||||||
|
Function<T, FilterValue> read,
|
||||||
|
Function<FilterValue, String> label) {
|
||||||
|
public GroupColumn {
|
||||||
|
Checks.id(id);
|
||||||
|
Objects.requireNonNull(kind);
|
||||||
|
Objects.requireNonNull(read);
|
||||||
|
Objects.requireNonNull(label);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> GroupColumn<T> text(String id, Function<T, String> reader) {
|
||||||
|
return new GroupColumn<>(
|
||||||
|
id,
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
row -> {
|
||||||
|
String value = reader.apply(row);
|
||||||
|
return value == null ? null : new FilterValue.Text(value);
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> GroupColumn<T> integer(String id, Function<T, Long> reader) {
|
||||||
|
return new GroupColumn<>(
|
||||||
|
id,
|
||||||
|
MemoryColumn.Kind.INTEGER,
|
||||||
|
row -> {
|
||||||
|
Long value = reader.apply(row);
|
||||||
|
return value == null ? null : new FilterValue.IntegerValue(value);
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> GroupColumn<T> decimal(String id, Function<T, java.math.BigDecimal> reader) {
|
||||||
|
return new GroupColumn<>(
|
||||||
|
id,
|
||||||
|
MemoryColumn.Kind.DECIMAL,
|
||||||
|
row -> {
|
||||||
|
var value = reader.apply(row);
|
||||||
|
return value == null ? null : new FilterValue.Decimal(value);
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> GroupColumn<T> bool(String id, Function<T, Boolean> reader) {
|
||||||
|
return new GroupColumn<>(
|
||||||
|
id,
|
||||||
|
MemoryColumn.Kind.BOOLEAN,
|
||||||
|
row -> {
|
||||||
|
Boolean value = reader.apply(row);
|
||||||
|
return value == null ? null : new FilterValue.BooleanValue(value);
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validate(FilterValue value) {
|
||||||
|
if (value == null) return;
|
||||||
|
boolean valid =
|
||||||
|
switch (kind) {
|
||||||
|
case TEXT -> value instanceof FilterValue.Text;
|
||||||
|
case INTEGER -> value instanceof FilterValue.IntegerValue;
|
||||||
|
case DECIMAL -> value instanceof FilterValue.Decimal;
|
||||||
|
case BOOLEAN -> value instanceof FilterValue.BooleanValue;
|
||||||
|
};
|
||||||
|
if (!valid) throw new IllegalArgumentException("Grouping value type changed: " + id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String display(FilterValue value) {
|
||||||
|
return switch (value) {
|
||||||
|
case null -> "(Missing)";
|
||||||
|
case FilterValue.Text t -> t.value().isEmpty() ? "(Empty)" : t.value();
|
||||||
|
case FilterValue.IntegerValue i -> Long.toString(i.value());
|
||||||
|
case FilterValue.Decimal d -> d.value().toPlainString();
|
||||||
|
case FilterValue.BooleanValue b -> Boolean.toString(b.value());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int compare(FilterValue a, FilterValue b) {
|
||||||
|
if (a == null) return b == null ? 0 : 1;
|
||||||
|
if (b == null) return -1;
|
||||||
|
return switch (a) {
|
||||||
|
case FilterValue.Text t -> {
|
||||||
|
String right = ((FilterValue.Text) b).value();
|
||||||
|
int order =
|
||||||
|
t.value()
|
||||||
|
.toLowerCase(Locale.ROOT)
|
||||||
|
.compareTo(right.toLowerCase(Locale.ROOT));
|
||||||
|
yield order == 0 ? t.value().compareTo(right) : order;
|
||||||
|
}
|
||||||
|
case FilterValue.IntegerValue i ->
|
||||||
|
Long.compare(i.value(), ((FilterValue.IntegerValue) b).value());
|
||||||
|
case FilterValue.Decimal d -> d.value().compareTo(((FilterValue.Decimal) b).value());
|
||||||
|
case FilterValue.BooleanValue v ->
|
||||||
|
Boolean.compare(v.value(), ((FilterValue.BooleanValue) b).value());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Owner-thread expansion history retaining scalar paths, never rows/models. */
|
||||||
|
public final class GroupExpansion {
|
||||||
|
private final LinkedHashMap<GroupPath, Boolean> choices = new LinkedHashMap<>();
|
||||||
|
private Set<GroupPath> current = Set.of();
|
||||||
|
private boolean defaultCollapsed;
|
||||||
|
private int inactiveLimit;
|
||||||
|
|
||||||
|
public GroupExpansion(boolean defaultCollapsed, int inactiveLimit) {
|
||||||
|
configure(defaultCollapsed, inactiveLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void configure(boolean collapsed, int limit) {
|
||||||
|
if (limit < 0) throw new IllegalArgumentException("Negative expansion history capacity");
|
||||||
|
defaultCollapsed = collapsed;
|
||||||
|
inactiveLimit = limit;
|
||||||
|
trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean expanded(GroupPath path) {
|
||||||
|
return choices.getOrDefault(path, !defaultCollapsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void set(GroupPath path, boolean expanded) {
|
||||||
|
choices.remove(path);
|
||||||
|
choices.put(path, expanded);
|
||||||
|
trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void current(Collection<GroupPath> paths) {
|
||||||
|
current = Set.copyOf(paths);
|
||||||
|
for (var path : paths)
|
||||||
|
if (choices.containsKey(path)) {
|
||||||
|
boolean choice = choices.remove(path);
|
||||||
|
choices.put(path, choice);
|
||||||
|
}
|
||||||
|
trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<GroupingSetup.Choice> snapshot() {
|
||||||
|
return choices.entrySet().stream()
|
||||||
|
.map(e -> new GroupingSetup.Choice(e.getKey(), e.getValue()))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void restore(List<GroupingSetup.Choice> saved) {
|
||||||
|
choices.clear();
|
||||||
|
saved.forEach(c -> choices.put(c.path(), c.expanded()));
|
||||||
|
trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reset() {
|
||||||
|
choices.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void trim() {
|
||||||
|
int inactive = (int) choices.keySet().stream().filter(p -> !current.contains(p)).count();
|
||||||
|
for (var iterator = choices.keySet().iterator();
|
||||||
|
inactive > inactiveLimit && iterator.hasNext(); ) {
|
||||||
|
if (!current.contains(iterator.next())) {
|
||||||
|
iterator.remove();
|
||||||
|
inactive--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Stable typed identity, independent of labels, page position and row identity. */
|
||||||
|
public record GroupPath(List<Segment> segments) {
|
||||||
|
public record Segment(String columnId, FilterValue value) {
|
||||||
|
public Segment {
|
||||||
|
Checks.id(columnId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupPath {
|
||||||
|
segments = List.copyOf(segments);
|
||||||
|
if (segments.isEmpty()) throw new IllegalArgumentException("Empty group path");
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (var segment : segments)
|
||||||
|
if (!seen.add(segment.columnId()))
|
||||||
|
throw new IllegalArgumentException("Repeated group column");
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupPath child(String column, FilterValue value) {
|
||||||
|
var next = new ArrayList<>(segments);
|
||||||
|
next.add(new Segment(column, value));
|
||||||
|
return new GroupPath(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Pure current-page projection. Capture all eligible scalar values before publishing a page. */
|
||||||
|
public final class GroupProjection {
|
||||||
|
private GroupProjection() {}
|
||||||
|
|
||||||
|
public record Value(FilterValue key, String label) {
|
||||||
|
public Value {
|
||||||
|
Objects.requireNonNull(label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Captured<K, T>(GridRow<K, T> row, Map<String, Value> values) {
|
||||||
|
public Captured {
|
||||||
|
Objects.requireNonNull(row);
|
||||||
|
values = Map.copyOf(values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Snapshot<K, T>(List<Captured<K, T>> rows, Map<String, GroupColumn<T>> columns) {
|
||||||
|
public Snapshot {
|
||||||
|
rows = List.copyOf(rows);
|
||||||
|
columns = Map.copyOf(columns);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Node<K, T>(
|
||||||
|
GroupPath path, String label, List<Node<K, T>> children, List<GridRow<K, T>> rows) {
|
||||||
|
public Node {
|
||||||
|
children = List.copyOf(children);
|
||||||
|
rows = List.copyOf(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int count() {
|
||||||
|
return rows.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <K, T> Snapshot<K, T> capture(
|
||||||
|
List<GridRow<K, T>> rows, Collection<GroupColumn<T>> columns) {
|
||||||
|
Map<String, GroupColumn<T>> mappings = new LinkedHashMap<>();
|
||||||
|
for (var c : columns)
|
||||||
|
if (mappings.putIfAbsent(c.id(), c) != null)
|
||||||
|
throw new IllegalArgumentException("Duplicate group mapping");
|
||||||
|
List<Captured<K, T>> captured = new ArrayList<>();
|
||||||
|
for (var row : rows) {
|
||||||
|
Map<String, Value> values = new LinkedHashMap<>();
|
||||||
|
for (var c : columns) {
|
||||||
|
FilterValue key = c.read().apply(row.model());
|
||||||
|
c.validate(key);
|
||||||
|
values.put(c.id(), new Value(key, c.label().apply(key)));
|
||||||
|
}
|
||||||
|
captured.add(new Captured<>(row, values));
|
||||||
|
}
|
||||||
|
return new Snapshot<>(captured, mappings);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <K, T> List<Node<K, T>> project(Snapshot<K, T> snapshot, List<String> order) {
|
||||||
|
if (new HashSet<>(order).size() != order.size()
|
||||||
|
|| !snapshot.columns().keySet().containsAll(order))
|
||||||
|
throw new IllegalArgumentException("Unknown/repeated grouping column");
|
||||||
|
return build(snapshot.rows(), order, 0, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <K, T> List<Node<K, T>> build(
|
||||||
|
List<Captured<K, T>> rows, List<String> order, int depth, GroupPath parent) {
|
||||||
|
if (depth == order.size()) return List.of();
|
||||||
|
String id = order.get(depth);
|
||||||
|
Map<FilterValue, List<Captured<K, T>>> buckets = new LinkedHashMap<>();
|
||||||
|
for (var row : rows)
|
||||||
|
buckets.computeIfAbsent(row.values().get(id).key(), ignored -> new ArrayList<>())
|
||||||
|
.add(row);
|
||||||
|
List<FilterValue> keys = new ArrayList<>(buckets.keySet());
|
||||||
|
keys.sort(GroupColumn::compare);
|
||||||
|
List<Node<K, T>> nodes = new ArrayList<>();
|
||||||
|
for (var key : keys) {
|
||||||
|
var bucket = buckets.get(key);
|
||||||
|
String label = bucket.getFirst().values().get(id).label();
|
||||||
|
if (bucket.stream().anyMatch(r -> !r.values().get(id).label().equals(label)))
|
||||||
|
throw new IllegalArgumentException("Inconsistent label for group value in " + id);
|
||||||
|
GroupPath path =
|
||||||
|
parent == null
|
||||||
|
? new GroupPath(List.of(new GroupPath.Segment(id, key)))
|
||||||
|
: parent.child(id, key);
|
||||||
|
nodes.add(
|
||||||
|
new Node<>(
|
||||||
|
path,
|
||||||
|
label,
|
||||||
|
build(bucket, order, depth + 1, path),
|
||||||
|
bucket.stream().map(Captured::row).toList()));
|
||||||
|
}
|
||||||
|
return List.copyOf(nodes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <K, T> List<GroupPath> paths(List<Node<K, T>> nodes) {
|
||||||
|
List<GroupPath> paths = new ArrayList<>();
|
||||||
|
for (var node : nodes) {
|
||||||
|
paths.add(node.path());
|
||||||
|
paths.addAll(paths(node.children()));
|
||||||
|
}
|
||||||
|
return paths;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Committed grouping preferences. Choices are ordered least-recently to most-recently used. */
|
||||||
|
public record GroupingSetup(List<String> columns, List<Choice> choices) {
|
||||||
|
public record Choice(GroupPath path, boolean expanded) {
|
||||||
|
public Choice {
|
||||||
|
Objects.requireNonNull(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupingSetup {
|
||||||
|
columns = List.copyOf(columns);
|
||||||
|
choices = List.copyOf(choices);
|
||||||
|
Set<String> ids = new HashSet<>();
|
||||||
|
for (String id : columns) {
|
||||||
|
Checks.id(id);
|
||||||
|
if (!ids.add(id)) throw new IllegalArgumentException("Repeated grouping column");
|
||||||
|
}
|
||||||
|
Set<GroupPath> paths = new HashSet<>();
|
||||||
|
for (var choice : choices)
|
||||||
|
if (!paths.add(choice.path()))
|
||||||
|
throw new IllegalArgumentException("Repeated expansion choice");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static GroupingSetup empty() {
|
||||||
|
return new GroupingSetup(List.of(), List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
class GridConfigurationTest {
|
||||||
|
static GridSetup setup(double width) {
|
||||||
|
return new GridSetup(
|
||||||
|
2,
|
||||||
|
"records",
|
||||||
|
1,
|
||||||
|
List.of(new GridSetup.ColumnState("type", "text", new ColumnWidth.Explicit(width))),
|
||||||
|
List.of(),
|
||||||
|
List.of(),
|
||||||
|
new PageRequest.Paged(0, 50),
|
||||||
|
new GroupingSetup(List.of("type"), List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
static final GridSetupStore.Key KEY = new GridSetupStore.Key("records", null);
|
||||||
|
|
||||||
|
static final class MemoryStore implements GridSetupStore {
|
||||||
|
GridSetup value;
|
||||||
|
int revision, writes;
|
||||||
|
boolean fail;
|
||||||
|
|
||||||
|
public synchronized Stored load(Key key) {
|
||||||
|
return new Stored(value, Integer.toString(revision));
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized String revision(Key key) {
|
||||||
|
return Integer.toString(revision);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized String save(Key key, String expected, GridSetup setup)
|
||||||
|
throws IOException {
|
||||||
|
if (fail) throw new IOException("disk unavailable");
|
||||||
|
if (!expected.equals(Integer.toString(revision))) throw new Conflict();
|
||||||
|
value = setup;
|
||||||
|
writes++;
|
||||||
|
return Integer.toString(++revision);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static GridApplicationConfiguration config(MemoryStore store) {
|
||||||
|
return new GridApplicationConfiguration(
|
||||||
|
"Example",
|
||||||
|
store,
|
||||||
|
Duration.ofHours(1),
|
||||||
|
Executors.newSingleThreadScheduledExecutor(),
|
||||||
|
true);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void load(GridApplicationConfiguration config) throws Exception {
|
||||||
|
config.adopt(config.loadAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS), -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void coalescesWholeSnapshotsAndDoesNotSaveUnchangedLoadsOrClose() throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var config = config(store);
|
||||||
|
load(config);
|
||||||
|
assertEquals(0, store.writes);
|
||||||
|
config.accept(KEY, setup(100), new Object());
|
||||||
|
config.accept(KEY, setup(200), new Object());
|
||||||
|
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failedCloseRetainsLatestUnsavedStateAndCanRetry() throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var config = config(store);
|
||||||
|
load(config);
|
||||||
|
config.accept(KEY, setup(100), this);
|
||||||
|
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
store.fail = true;
|
||||||
|
config.accept(KEY, setup(200), this);
|
||||||
|
assertThrows(
|
||||||
|
ExecutionException.class,
|
||||||
|
() -> config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||||
|
assertEquals(setup(100), store.value);
|
||||||
|
assertTrue(config.state(KEY).dirty());
|
||||||
|
store.fail = false;
|
||||||
|
config.retryAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reloadCannotDiscardAnotherViewsNewerGeneration() throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var config = config(store);
|
||||||
|
load(config);
|
||||||
|
long old = config.accept(KEY, setup(100), this);
|
||||||
|
var read = config.loadAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
config.accept(KEY, setup(200), new Object());
|
||||||
|
config.adopt(read, old);
|
||||||
|
assertTrue(config.state(KEY).dirty());
|
||||||
|
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void crossInstanceConflictRequiresExplicitOverwriteAndDiscardCloseDoesNotWrite()
|
||||||
|
throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var first = config(store);
|
||||||
|
var second = config(store);
|
||||||
|
load(first);
|
||||||
|
load(second);
|
||||||
|
first.accept(KEY, setup(100), first);
|
||||||
|
first.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
second.accept(KEY, setup(200), second);
|
||||||
|
assertThrows(
|
||||||
|
ExecutionException.class,
|
||||||
|
() -> second.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||||
|
assertEquals(GridApplicationConfiguration.Phase.CONFLICT, second.state(KEY).phase());
|
||||||
|
second.overwriteAsync(KEY, setup(200), second)
|
||||||
|
.toCompletableFuture()
|
||||||
|
.get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
second.accept(KEY, setup(300), second);
|
||||||
|
second.discardAndCloseAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
first.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void debounceWaitsForQuietPeriodRatherThanSavingEveryChange() throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var clock = new Clock();
|
||||||
|
var config =
|
||||||
|
new GridApplicationConfiguration(
|
||||||
|
"Example", store, Duration.ofMillis(500), clock, false);
|
||||||
|
load(config);
|
||||||
|
config.accept(KEY, setup(100), this);
|
||||||
|
clock.advance(499);
|
||||||
|
assertEquals(0, store.writes);
|
||||||
|
config.accept(KEY, setup(200), this);
|
||||||
|
clock.advance(1);
|
||||||
|
assertEquals(0, store.writes);
|
||||||
|
clock.advance(499);
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
config.closeAsync().toCompletableFuture().get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void discardCloseWaitsForAnAlreadyCommittingWriteOnAParallelScheduler() throws Exception {
|
||||||
|
var entered = new CountDownLatch(1);
|
||||||
|
var release = new CountDownLatch(1);
|
||||||
|
var closed = new CountDownLatch(1);
|
||||||
|
var backing = new MemoryStore();
|
||||||
|
GridSetupStore store =
|
||||||
|
new GridSetupStore() {
|
||||||
|
public Stored load(Key key) {
|
||||||
|
return backing.load(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String revision(Key key) {
|
||||||
|
return backing.revision(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String save(Key key, String revision, GridSetup setup)
|
||||||
|
throws IOException {
|
||||||
|
entered.countDown();
|
||||||
|
try {
|
||||||
|
if (!release.await(5, TimeUnit.SECONDS))
|
||||||
|
throw new IOException("Timed out");
|
||||||
|
} catch (InterruptedException failure) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new IOException(failure);
|
||||||
|
}
|
||||||
|
return backing.save(key, revision, setup);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var worker = Executors.newScheduledThreadPool(2);
|
||||||
|
var config =
|
||||||
|
new GridApplicationConfiguration(
|
||||||
|
"Example", store, Duration.ofHours(1), worker, true);
|
||||||
|
load(config);
|
||||||
|
config.observe(
|
||||||
|
KEY,
|
||||||
|
state -> {
|
||||||
|
if (state.phase() == GridApplicationConfiguration.Phase.CLOSED)
|
||||||
|
closed.countDown();
|
||||||
|
});
|
||||||
|
config.accept(KEY, setup(100), this);
|
||||||
|
var write = config.retryAsync(KEY);
|
||||||
|
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||||
|
var close = config.discardAndCloseAsync();
|
||||||
|
try {
|
||||||
|
assertFalse(closed.await(100, TimeUnit.MILLISECONDS));
|
||||||
|
} finally {
|
||||||
|
release.countDown();
|
||||||
|
}
|
||||||
|
close.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
write.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(GridApplicationConfiguration.Phase.CLOSED, config.state(KEY).phase());
|
||||||
|
assertFalse(config.state(KEY).dirty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deterministic scheduled worker: no wall-clock sleeps in debounce assertions. */
|
||||||
|
static final class Clock extends java.util.concurrent.AbstractExecutorService
|
||||||
|
implements java.util.concurrent.ScheduledExecutorService {
|
||||||
|
long now;
|
||||||
|
boolean shutdown;
|
||||||
|
final List<Job> jobs = new ArrayList<>();
|
||||||
|
|
||||||
|
static final class Job extends java.util.concurrent.FutureTask<Void>
|
||||||
|
implements java.util.concurrent.ScheduledFuture<Void> {
|
||||||
|
final long due;
|
||||||
|
|
||||||
|
Job(Runnable action, long due) {
|
||||||
|
super(action, null);
|
||||||
|
this.due = due;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getDelay(java.util.concurrent.TimeUnit unit) {
|
||||||
|
return unit.convert(due, java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int compareTo(java.util.concurrent.Delayed other) {
|
||||||
|
return Long.compare(due, ((Job) other).due);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void advance(long millis) {
|
||||||
|
now += millis;
|
||||||
|
var ready = jobs.stream().filter(job -> job.due <= now).toList();
|
||||||
|
jobs.removeAll(ready);
|
||||||
|
ready.forEach(Job::run);
|
||||||
|
}
|
||||||
|
|
||||||
|
public java.util.concurrent.ScheduledFuture<?> schedule(
|
||||||
|
Runnable action, long delay, java.util.concurrent.TimeUnit unit) {
|
||||||
|
var job = new Job(action, now + unit.toMillis(delay));
|
||||||
|
jobs.add(job);
|
||||||
|
return job;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <V> java.util.concurrent.ScheduledFuture<V> schedule(
|
||||||
|
java.util.concurrent.Callable<V> action,
|
||||||
|
long delay,
|
||||||
|
java.util.concurrent.TimeUnit unit) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public java.util.concurrent.ScheduledFuture<?> scheduleAtFixedRate(
|
||||||
|
Runnable r, long a, long b, java.util.concurrent.TimeUnit u) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public java.util.concurrent.ScheduledFuture<?> scheduleWithFixedDelay(
|
||||||
|
Runnable r, long a, long b, java.util.concurrent.TimeUnit u) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void execute(Runnable command) {
|
||||||
|
command.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void shutdown() {
|
||||||
|
shutdown = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Runnable> shutdownNow() {
|
||||||
|
shutdown = true;
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isShutdown() {
|
||||||
|
return shutdown;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isTerminated() {
|
||||||
|
return shutdown;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) {
|
||||||
|
return shutdown;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
class GroupingTest {
|
||||||
|
record Item(String type, String status) {}
|
||||||
|
|
||||||
|
static GroupPath path(String value) {
|
||||||
|
return new GroupPath(List.of(new GroupPath.Segment("type", new FilterValue.Text(value))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void snapshotSeparatesExactIdentityAndLabelsFromOrderingAndRetainsLeafSourceOrder() {
|
||||||
|
AtomicInteger calls = new AtomicInteger();
|
||||||
|
var mapping =
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> {
|
||||||
|
calls.incrementAndGet();
|
||||||
|
return i.type() == null ? null : new FilterValue.Text(i.type());
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
var rows =
|
||||||
|
List.of(
|
||||||
|
new GridRow<>(1, new Item("a", "one")),
|
||||||
|
new GridRow<>(2, new Item(null, "two")),
|
||||||
|
new GridRow<>(3, new Item("A", "three")),
|
||||||
|
new GridRow<>(4, new Item("a", "four")),
|
||||||
|
new GridRow<>(5, new Item("", "five")));
|
||||||
|
var snapshot = GroupProjection.capture(rows, List.of(mapping));
|
||||||
|
var groups = GroupProjection.project(snapshot, List.of("type"));
|
||||||
|
assertEquals(
|
||||||
|
List.of("(Empty)", "A", "a", "(Missing)"),
|
||||||
|
groups.stream().map(GroupProjection.Node::label).toList());
|
||||||
|
assertEquals(List.of(1, 4), groups.get(2).rows().stream().map(GridRow::key).toList());
|
||||||
|
assertEquals(5, calls.get());
|
||||||
|
GroupProjection.project(snapshot, List.of("type"));
|
||||||
|
assertEquals(5, calls.get(), "Regroup must use captured scalars, not reread models");
|
||||||
|
assertEquals(List.of(1, 2, 3, 4, 5), rows.stream().map(GridRow::key).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void decimalScaleDoesNotCreateDifferentGroupsAndWrongTypesFailBeforePublication() {
|
||||||
|
var mapping =
|
||||||
|
new GroupColumn<BigDecimal>(
|
||||||
|
"amount",
|
||||||
|
MemoryColumn.Kind.DECIMAL,
|
||||||
|
FilterValue.Decimal::new,
|
||||||
|
GroupColumn::display);
|
||||||
|
var groups =
|
||||||
|
GroupProjection.project(
|
||||||
|
GroupProjection.capture(
|
||||||
|
List.of(
|
||||||
|
new GridRow<>(1, new BigDecimal("1.0")),
|
||||||
|
new GridRow<>(2, new BigDecimal("1.00"))),
|
||||||
|
List.of(mapping)),
|
||||||
|
List.of("amount"));
|
||||||
|
assertEquals(1, groups.size());
|
||||||
|
assertEquals(2, groups.getFirst().count());
|
||||||
|
var invalid =
|
||||||
|
new GroupColumn<String>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
s -> new FilterValue.BooleanValue(true),
|
||||||
|
GroupColumn::display);
|
||||||
|
assertThrows(
|
||||||
|
IllegalArgumentException.class,
|
||||||
|
() -> GroupProjection.capture(List.of(new GridRow<>(1, "x")), List.of(invalid)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void expansionPreservesCurrentChoicesAndBoundsOnlyInactiveHistory() {
|
||||||
|
var expansion = new GroupExpansion(true, 1);
|
||||||
|
expansion.current(List.of(path("A"), path("B")));
|
||||||
|
expansion.set(path("A"), true);
|
||||||
|
expansion.set(path("B"), false);
|
||||||
|
expansion.set(path("C"), true);
|
||||||
|
expansion.set(path("D"), true);
|
||||||
|
assertEquals(3, expansion.snapshot().size());
|
||||||
|
assertTrue(expansion.expanded(path("A")));
|
||||||
|
assertFalse(expansion.expanded(path("C")));
|
||||||
|
expansion.configure(false, 1);
|
||||||
|
assertFalse(
|
||||||
|
expansion.expanded(path("B")),
|
||||||
|
"Explicit choice equal to old default must survive default change");
|
||||||
|
expansion.reset();
|
||||||
|
assertTrue(expansion.expanded(path("B")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nestedCountsAndPathsDoNotConflateEqualLabelsOrParentCollapse() {
|
||||||
|
var cols =
|
||||||
|
List.of(
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.type()),
|
||||||
|
v -> "same"),
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"status",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.status()),
|
||||||
|
GroupColumn::display));
|
||||||
|
var tree =
|
||||||
|
GroupProjection.project(
|
||||||
|
GroupProjection.capture(
|
||||||
|
List.of(
|
||||||
|
new GridRow<>(1, new Item("A", "live")),
|
||||||
|
new GridRow<>(2, new Item("B", "live"))),
|
||||||
|
cols),
|
||||||
|
List.of("type", "status"));
|
||||||
|
assertEquals(2, tree.size());
|
||||||
|
assertNotEquals(tree.get(0).path(), tree.get(1).path());
|
||||||
|
var expansion = new GroupExpansion(true, 1000);
|
||||||
|
expansion.current(GroupProjection.paths(tree));
|
||||||
|
var parent = tree.get(0).path();
|
||||||
|
var child = tree.get(0).children().getFirst().path();
|
||||||
|
expansion.set(child, true);
|
||||||
|
expansion.set(parent, false);
|
||||||
|
expansion.set(parent, true);
|
||||||
|
assertTrue(expansion.expanded(child));
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
-2
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.6</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>encryption</artifactId>
|
<artifactId>encryption</artifactId>
|
||||||
@@ -18,13 +18,16 @@
|
|||||||
<launcher>${project.artifactId}</launcher>
|
<launcher>${project.artifactId}</launcher>
|
||||||
<appName>${project.artifactId}</appName>
|
<appName>${project.artifactId}</appName>
|
||||||
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
|
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
|
||||||
|
|
||||||
|
<!-- Dependency versions -->
|
||||||
|
<format-preserving-encryption.version>1.0.0</format-preserving-encryption.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.idealista</groupId>
|
<groupId>com.idealista</groupId>
|
||||||
<artifactId>format-preserving-encryption</artifactId>
|
<artifactId>format-preserving-encryption</artifactId>
|
||||||
<version>1.0.0</version>
|
<version>${format-preserving-encryption.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|||||||
@@ -30,12 +30,12 @@ From the NeitzelLib root with JDK 25:
|
|||||||
./mvnw -f fx-example/pom.xml javafx:run
|
./mvnw -f fx-example/pom.xml javafx:run
|
||||||
```
|
```
|
||||||
|
|
||||||
The first command installs local `1.0` 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.6` 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:
|
The packaged alternative, after `package` or `install`, is:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
java -jar fx-example/target/fx-example-1.0.jar
|
java -jar fx-example/target/fx-example-1.0.6.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.
|
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.
|
||||||
@@ -108,7 +108,7 @@ Inspect Surefire XML reports for test totals, failures and skips. JavaFX tests n
|
|||||||
|
|
||||||
## Open the example in NeitzelFXDesigner
|
## Open the example in NeitzelFXDesigner
|
||||||
|
|
||||||
The repository root includes `neitzel-fx-designer.json` with the `person-desk` context. It selects `fx-example`, classpath launch, the `designer-preview` Maven profile, the local runtime key `java21`, and `de.neitzel.fx.example.preview.DeskPreviewProvider`. Configure your own JDK path for that key; machine paths are not part of the shared project configuration.
|
The repository root includes `neitzel-fx-designer.json` with the `person-desk` context. It selects `fx-example`, classpath launch, the `designer-preview` Maven profile, the local runtime key `java25`, and `de.neitzel.fx.example.preview.DeskPreviewProvider`. Configure your own JDK path for that key; machine paths are not part of the shared project configuration.
|
||||||
|
|
||||||
The optional profile adds the Designer preview API only to the test source set, compiles `src/designer/java`, includes its resources, and produces Model metadata for Person, Address and Note. It does not add a runtime dependency to the ordinary application, replace its handwritten PersonViewModel, or generate a default ViewModel registry.
|
The optional profile adds the Designer preview API only to the test source set, compiles `src/designer/java`, includes its resources, and produces Model metadata for Person, Address and Note. It does not add a runtime dependency to the ordinary application, replace its handwritten PersonViewModel, or generate a default ViewModel registry.
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ From the repository root with JDK 25, build without installing runtime artifacts
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
./mvnw -pl fx-example -am package -DskipTests
|
./mvnw -pl fx-example -am package -DskipTests
|
||||||
java -cp 'fx-example/target/fx-example-1.0.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
|
java -cp 'fx-example/target/fx-example-1.0.6.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.
|
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.
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
|
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
java -cp 'fx-example/target/fx-example-1.0.jar:fx-example/target/libs/*' \
|
java -cp 'fx-example/target/fx-example-1.0.6.jar:fx-example/target/libs/*' \
|
||||||
de.neitzel.fx.example.theme.ThemeGalleryMain
|
de.neitzel.fx.example.theme.ThemeGalleryMain
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+25
-5
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.6</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>fx-example</artifactId>
|
<artifactId>fx-example</artifactId>
|
||||||
@@ -18,11 +18,17 @@
|
|||||||
<appName>${project.artifactId}</appName>
|
<appName>${project.artifactId}</appName>
|
||||||
<main.class>de.neitzel.fx.example.Main</main.class>
|
<main.class>de.neitzel.fx.example.Main</main.class>
|
||||||
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
|
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
|
||||||
|
|
||||||
|
<!-- Dependency versions -->
|
||||||
|
<designer.version>0.1.0</designer.version>
|
||||||
|
|
||||||
|
<!-- Plugin versions -->
|
||||||
|
<build.helper.maven.plugin>3.8.0</build.helper.maven.plugin>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid-jdbc</artifactId><version>${project.version}</version></dependency>
|
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid-jdbc</artifactId><version>${project.version}</version></dependency>
|
||||||
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version></dependency>
|
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>${h2.version}</version></dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
@@ -99,11 +105,25 @@
|
|||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<id>designer-preview</id>
|
<id>designer-preview</id>
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>gitea-neitzelfxdesigner</id>
|
||||||
|
<url>https://gitea.neitzel.de/api/packages/konrad/maven</url>
|
||||||
|
<snapshots><enabled>false</enabled></snapshots>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
|
<pluginRepositories>
|
||||||
|
<pluginRepository>
|
||||||
|
<id>gitea-neitzelfxdesigner</id>
|
||||||
|
<url>https://gitea.neitzel.de/api/packages/konrad/maven</url>
|
||||||
|
<snapshots><enabled>false</enabled></snapshots>
|
||||||
|
</pluginRepository>
|
||||||
|
</pluginRepositories>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.fxdesigner</groupId>
|
<groupId>de.neitzel.fxdesigner</groupId>
|
||||||
<artifactId>designer-preview-api</artifactId>
|
<artifactId>designer-preview-api</artifactId>
|
||||||
<version>0.1.0-SNAPSHOT</version>
|
<version>${designer.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@@ -112,7 +132,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>build-helper-maven-plugin</artifactId>
|
<artifactId>build-helper-maven-plugin</artifactId>
|
||||||
<version>3.8.0</version>
|
<version>${build.helper.maven.plugin}</version>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<id>designer-preview-sources</id>
|
<id>designer-preview-sources</id>
|
||||||
@@ -139,7 +159,7 @@
|
|||||||
<path>
|
<path>
|
||||||
<groupId>de.neitzel.fxdesigner</groupId>
|
<groupId>de.neitzel.fxdesigner</groupId>
|
||||||
<artifactId>designer-model-processor</artifactId>
|
<artifactId>designer-model-processor</artifactId>
|
||||||
<version>0.1.0-SNAPSHOT</version>
|
<version>${designer.version}</version>
|
||||||
</path>
|
</path>
|
||||||
</annotationProcessorPaths>
|
</annotationProcessorPaths>
|
||||||
<compilerArgs>
|
<compilerArgs>
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<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.6</version>
|
||||||
|
</parent>
|
||||||
|
<artifactId>fx-test</artifactId>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>de.neitzel.lib</groupId>
|
||||||
|
<artifactId>fx</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<glass.platform>Headless</glass.platform>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package de.neitzel.fx.test;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
import org.junit.jupiter.api.extension.ParameterContext;
|
||||||
|
import org.junit.jupiter.api.extension.ParameterResolver;
|
||||||
|
|
||||||
|
final class FxExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
|
||||||
|
private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create(FxExtension.class);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeEach(ExtensionContext context) throws Exception {
|
||||||
|
var fixture = new FxFixture();
|
||||||
|
fixture.start();
|
||||||
|
context.getStore(NAMESPACE).put(FxFixture.class, fixture);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterEach(ExtensionContext context) throws Exception {
|
||||||
|
var fixture = context.getStore(NAMESPACE).remove(FxFixture.class, FxFixture.class);
|
||||||
|
if (fixture != null) fixture.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supportsParameter(ParameterContext parameter, ExtensionContext context) {
|
||||||
|
return parameter.getParameter().getType() == FxFixture.class
|
||||||
|
&& parameter.getDeclaringExecutable() instanceof Method
|
||||||
|
&& context.getStore(NAMESPACE).get(FxFixture.class) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object resolveParameter(ParameterContext parameter, ExtensionContext context) {
|
||||||
|
return context.getStore(NAMESPACE).get(FxFixture.class, FxFixture.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
package de.neitzel.fx.test;
|
||||||
|
|
||||||
|
import de.neitzel.fx.view.LoadedView;
|
||||||
|
import de.neitzel.fx.view.ViewLoader;
|
||||||
|
import de.neitzel.fx.view.ViewModelContext;
|
||||||
|
import de.neitzel.injection.ApplicationContext;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.FutureTask;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
|
||||||
|
/** JavaFX test operations scoped to one JUnit test. Obtain the fixture through {@link FxTest}. */
|
||||||
|
public final class FxFixture {
|
||||||
|
private static final long TIMEOUT_SECONDS = 10;
|
||||||
|
|
||||||
|
private final ViewModelContext models = new ViewModelContext();
|
||||||
|
private final List<Throwable> callbackFailures = new ArrayList<>();
|
||||||
|
private List<Window> previousWindows;
|
||||||
|
private Thread.UncaughtExceptionHandler previousHandler;
|
||||||
|
|
||||||
|
/** An FX-thread action that may propagate a checked exception. */
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface Action {
|
||||||
|
/**
|
||||||
|
* Performs the action.
|
||||||
|
* @throws Exception on failure
|
||||||
|
*/
|
||||||
|
void run() throws Exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
FxFixture() {}
|
||||||
|
|
||||||
|
void start() throws Exception {
|
||||||
|
try {
|
||||||
|
Platform.startup(() -> {});
|
||||||
|
} catch (IllegalStateException alreadyStarted) {
|
||||||
|
// A previous test or another JavaFX client has started this JVM's toolkit.
|
||||||
|
}
|
||||||
|
run(() -> {
|
||||||
|
Platform.setImplicitExit(false);
|
||||||
|
previousWindows = List.copyOf(Window.getWindows());
|
||||||
|
previousHandler = Thread.currentThread().getUncaughtExceptionHandler();
|
||||||
|
Thread.currentThread().setUncaughtExceptionHandler((thread, error) -> callbackFailures.add(error));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs an action on the FX thread and propagates its failure to the test.
|
||||||
|
* @param action test action
|
||||||
|
* @throws Exception if the action fails or the wait is interrupted or times out
|
||||||
|
*/
|
||||||
|
public void run(Action action) throws Exception {
|
||||||
|
call(() -> {
|
||||||
|
action.run();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the result of an FX-thread operation, with a bounded wait on the calling thread.
|
||||||
|
* @param <T> result type
|
||||||
|
* @param action operation to perform
|
||||||
|
* @return the value returned by the operation
|
||||||
|
* @throws Exception if the operation fails or the wait is interrupted or times out
|
||||||
|
*/
|
||||||
|
public <T> T call(Callable<T> action) throws Exception {
|
||||||
|
if (Platform.isFxApplicationThread()) return action.call();
|
||||||
|
var task = new FutureTask<>(action);
|
||||||
|
Platform.runLater(task);
|
||||||
|
try {
|
||||||
|
return task.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
|
} catch (ExecutionException failure) {
|
||||||
|
if (failure.getCause() instanceof Exception exception) throw exception;
|
||||||
|
if (failure.getCause() instanceof Error error) throw error;
|
||||||
|
throw new AssertionError(failure.getCause());
|
||||||
|
} catch (TimeoutException | InterruptedException failure) {
|
||||||
|
task.cancel(false);
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Waits on the test thread while evaluating the named condition on the FX thread.
|
||||||
|
* @param description expected state, included in the timeout message
|
||||||
|
* @param condition UI predicate to evaluate
|
||||||
|
* @throws Exception if evaluation fails or waiting is interrupted
|
||||||
|
* @throws AssertionError if the condition stays false
|
||||||
|
*/
|
||||||
|
public void await(String description, BooleanSupplier condition) throws Exception {
|
||||||
|
if (Platform.isFxApplicationThread()) throw new IllegalStateException("await requires the test thread");
|
||||||
|
long start = System.nanoTime();
|
||||||
|
while (!call(condition::getAsBoolean)) {
|
||||||
|
if (System.nanoTime() - start >= TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)) {
|
||||||
|
throw new AssertionError("Timed out waiting for " + description);
|
||||||
|
}
|
||||||
|
Thread.sleep(15);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads production FXML on the FX thread in the test's automatically closed model context.
|
||||||
|
* @param fxml view resource
|
||||||
|
* @param model model for the view
|
||||||
|
* @param services controller and service container
|
||||||
|
* @return managed view
|
||||||
|
* @throws Exception if the view cannot be loaded or the wait is interrupted or times out
|
||||||
|
*/
|
||||||
|
public LoadedView load(URL fxml, Object model, ApplicationContext services) throws Exception {
|
||||||
|
return call(() -> ViewLoader.load(fxml, model, services, models));
|
||||||
|
}
|
||||||
|
|
||||||
|
void finish() throws Exception {
|
||||||
|
run(() -> {
|
||||||
|
try {
|
||||||
|
for (var window : List.copyOf(Window.getWindows()).reversed()) {
|
||||||
|
if (!previousWindows.contains(window)) window.hide();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
models.close();
|
||||||
|
} finally {
|
||||||
|
Thread.currentThread().setUncaughtExceptionHandler(previousHandler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!callbackFailures.isEmpty()) {
|
||||||
|
var failure = new AssertionError("Unhandled exception on the JavaFX application thread",
|
||||||
|
callbackFailures.getFirst());
|
||||||
|
callbackFailures.stream().skip(1).forEach(failure::addSuppressed);
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package de.neitzel.fx.test;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Inherited;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.junit.jupiter.api.parallel.Execution;
|
||||||
|
import org.junit.jupiter.api.parallel.ExecutionMode;
|
||||||
|
import org.junit.jupiter.api.parallel.Isolated;
|
||||||
|
|
||||||
|
/** Runs a JavaFX test class in isolation and supplies an FxFixture to each test method. */
|
||||||
|
@Target(ElementType.TYPE)
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Inherited
|
||||||
|
@Isolated
|
||||||
|
@Execution(ExecutionMode.SAME_THREAD)
|
||||||
|
@ExtendWith(FxExtension.class)
|
||||||
|
public @interface FxTest {}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package de.neitzel.fx.test;
|
||||||
|
|
||||||
|
import de.neitzel.injection.ApplicationContext;
|
||||||
|
import java.io.IOException;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextField;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@FxTest
|
||||||
|
public class FxFixtureTest {
|
||||||
|
@Getter @Setter
|
||||||
|
public static class Person {
|
||||||
|
private String name = "Ada";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void teardownDetachesLoadedViewsAndReportsUnhandledCallbacks(FxFixture fx) throws Exception {
|
||||||
|
var person = new Person();
|
||||||
|
var nested = new FxFixture();
|
||||||
|
var problem = new IllegalStateException("callback failed");
|
||||||
|
nested.start();
|
||||||
|
var view = nested.load(getClass().getResource("name.fxml"), person, new ApplicationContext(Person.class));
|
||||||
|
var field = nested.call(() -> (TextField) view.getRoot());
|
||||||
|
var stage = nested.call(() -> {
|
||||||
|
assertEquals("Ada", field.getText());
|
||||||
|
field.setText("Lin");
|
||||||
|
assertEquals("Lin", person.getName());
|
||||||
|
var window = new Stage();
|
||||||
|
window.setScene(new Scene(field));
|
||||||
|
window.show();
|
||||||
|
return window;
|
||||||
|
});
|
||||||
|
nested.run(() -> Platform.runLater(() -> { throw problem; }));
|
||||||
|
assertSame(problem, assertThrows(AssertionError.class, nested::finish).getCause());
|
||||||
|
|
||||||
|
fx.run(() -> {
|
||||||
|
assertFalse(stage.isShowing());
|
||||||
|
field.setText("Detached");
|
||||||
|
assertEquals("Lin", person.getName());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nestedCallsPropagateTheOriginalFailureAndCannotBlockTheFxThread(FxFixture fx) throws Exception {
|
||||||
|
var problem = new IOException("failed");
|
||||||
|
assertSame(problem, assertThrows(IOException.class, () -> fx.run(() -> {
|
||||||
|
assertTrue(fx.call(Platform::isFxApplicationThread));
|
||||||
|
assertThrows(IllegalStateException.class, () -> fx.await("next pulse", () -> false));
|
||||||
|
throw problem;
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?import de.neitzel.fx.view.BindingList?>
|
||||||
|
<?import de.neitzel.fx.view.DirectBinding?>
|
||||||
|
<?import javafx.scene.control.TextField?>
|
||||||
|
<TextField xmlns:fx="http://javafx.com/fxml/1" fx:id="field">
|
||||||
|
<fx:define><BindingList>
|
||||||
|
<DirectBinding control="field" property="text" path="name" direction="both"/>
|
||||||
|
</BindingList></fx:define>
|
||||||
|
</TextField>
|
||||||
+148
-6
@@ -2,11 +2,15 @@
|
|||||||
|
|
||||||
## Documentation map
|
## Documentation map
|
||||||
|
|
||||||
|
- [Message catalogs, FXML localization and language changes](docs/i18n.md).
|
||||||
|
- [FXML support for every public control](docs/fxml-controls.md).
|
||||||
|
|
||||||
- [Build a complete application from scratch](docs/quick-start.md).
|
- [Build a complete application from scratch](docs/quick-start.md).
|
||||||
- [Architecture, MVVM, identity, threading and lifetime](docs/architecture.md).
|
- [Architecture, MVVM, identity, threading and lifetime](docs/architecture.md).
|
||||||
- [Walk through the person desk](../fx-example/README.md).
|
- [Walk through the person desk](../fx-example/README.md).
|
||||||
- This page is the detailed FXML and runtime reference.
|
- This page is the detailed FXML and runtime reference.
|
||||||
- [Generated ViewModel classes and registries](docs/generated-viewmodels.md).
|
- [Generated ViewModel classes and registries](docs/generated-viewmodels.md).
|
||||||
|
- [Saved HTML and SingleFile viewing](docs/html-viewer.md).
|
||||||
- [Bounded integer spinners](docs/integer-spinners.md) and [system tray support](docs/tray-support.md).
|
- [Bounded integer spinners](docs/integer-spinners.md) and [system tray support](docs/tray-support.md).
|
||||||
- [Standalone toolbar and status bar](docs/bars.md), usable without MVVM.
|
- [Standalone toolbar and status bar](docs/bars.md), usable without MVVM.
|
||||||
- [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples.
|
- [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples.
|
||||||
@@ -21,6 +25,7 @@
|
|||||||
- [Dependency injection](../injection/README.md).
|
- [Dependency injection](../injection/README.md).
|
||||||
|
|
||||||
- [Local DataGrid and asynchronous coordination](docs/data-grid.md).
|
- [Local DataGrid and asynchronous coordination](docs/data-grid.md).
|
||||||
|
- [Interactive layout, grouping and optional application persistence](docs/data-grid-layout.md).
|
||||||
- [Transactional FXML filters and popup lifecycle](docs/filter-editors.md).
|
- [Transactional FXML filters and popup lifecycle](docs/filter-editors.md).
|
||||||
- [Versioned saved setups and atomic restoration](docs/saved-setups.md).
|
- [Versioned saved setups and atomic restoration](docs/saved-setups.md).
|
||||||
- [Opt-in shared themes](docs/themes.md) and the [theme gallery](../fx-example/docs/theme-gallery.md).
|
- [Opt-in shared themes](docs/themes.md) and the [theme gallery](../fx-example/docs/theme-gallery.md).
|
||||||
@@ -43,6 +48,8 @@ The launch class is `de.neitzel.fx.example.Main`. `Main` does not extend `Applic
|
|||||||
|
|
||||||
Depend on `de.neitzel.lib:fx`. That module depends on `core`, `injection` and on JavaFX base, controls, graphics, fxml, and web. Application types the container constructs use `jakarta.inject.Singleton` or `jakarta.inject.Named`.
|
Depend on `de.neitzel.lib:fx`. That module depends on `core`, `injection` and on JavaFX base, controls, graphics, fxml, and web. Application types the container constructs use `jakarta.inject.Singleton` or `jakarta.inject.Named`.
|
||||||
|
|
||||||
|
Use `ViewLoader.loadComponent(type, model, context, models)` to open a reusable Component directly from its own FXML. It returns a managed `LoadedView` with the same Component, ViewModel selection and binding lifetime as an embedded instance.
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
|
|
||||||
These are the versions configured by this source snapshot, not a promise of compatibility with every newer release:
|
These are the versions configured by this source snapshot, not a promise of compatibility with every newer release:
|
||||||
@@ -51,9 +58,10 @@ 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 |
|
| 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 |
|
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
|
||||||
| Library | `de.neitzel.lib:fx:1.0` | Use the Gitea Maven registry or install the local reactor |
|
| Library | `de.neitzel.lib:fx:1.0.6` | 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 |
|
| 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 |
|
| 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 |
|
||||||
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
|
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
|
||||||
| Injection annotations | `jakarta.inject-api` 2.0.1 | Use Jakarta annotations, not `javax.inject` |
|
| Injection annotations | `jakarta.inject-api` 2.0.1 | Use Jakarta annotations, not `javax.inject` |
|
||||||
| Logging | SLF4J API 2.0.20 | Choose one logging backend; the example uses `slf4j-simple` 2.0.20 at runtime |
|
| Logging | SLF4J API 2.0.20 | Choose one logging backend; the example uses `slf4j-simple` 2.0.20 at runtime |
|
||||||
@@ -165,9 +173,9 @@ 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.
|
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).
|
When the attribute value is already an `ObservableList`, the control property is set to that same list. With `direction="view"`, the control also follows replacement of the list reference, including a replacement with equal elements. Closing a managed View detaches that observation and restores the previous list if the control still holds the supplied list. Other directions retain their shared-list assignment. The writable observable-list path bypasses converters. See [A list of simple values](#a-list-of-simple-values).
|
||||||
|
|
||||||
A binding that names no such control fails with `No control "` and the id. A missing `xxxProperty()` method fails with `No property` and the property name. A method that returns something other than a `Property` fails with `did not return a property`.
|
A binding that names no such control fails with `No control "` and the id. A missing `xxxProperty()` method fails with `No property` and the property name. A method that returns something other than a `Property` fails with `did not return a property`.
|
||||||
|
|
||||||
@@ -179,6 +187,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. |
|
| `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. |
|
| `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
|
||||||
|
<DirectBinding control="save" property="disable" path="saveDisabled" direction="view"/>
|
||||||
|
```
|
||||||
|
|
||||||
|
`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.
|
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.
|
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.
|
||||||
@@ -187,7 +210,7 @@ For a complex last segment the control receives the model instance behind the vi
|
|||||||
|
|
||||||
## Paths
|
## 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.
|
`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.
|
||||||
|
|
||||||
@@ -195,7 +218,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 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
|
## Converter
|
||||||
|
|
||||||
@@ -245,6 +268,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.
|
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
|
||||||
|
<CommandBinding control="clearButton" path="clear"/>
|
||||||
|
<CommandBinding control="clearMenuItem" path="clear"/>
|
||||||
|
```
|
||||||
|
|
||||||
|
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<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
|
## 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.
|
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.
|
||||||
@@ -427,6 +537,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.
|
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
|
### 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.
|
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.
|
||||||
@@ -535,7 +671,8 @@ These are the `IllegalArgumentException` messages a document can produce. The vi
|
|||||||
| `No control "` | `fx:id` is missing |
|
| `No control "` | `fx:id` is missing |
|
||||||
| `No property ` | the control has no such JavaFX property |
|
| `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` |
|
| `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 |
|
| `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 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 |
|
| `No controller for ` / `No computed method "` | a computed binding has no controller or no such method |
|
||||||
@@ -573,3 +710,8 @@ The reference above covers the FXML declarations and their behavior. These are t
|
|||||||
`property(name)` returns `Property<?>`: cast to the known property type when writing from Java, for example `((StringProperty) loaded.property("name")).set("Grace")`. Generated accessors avoid these casts. `storedProperty` is for subclasses and reads only stored Model Attributes; it does not invoke custom reflective accessors. Internal loaders, appliers and identity-cache helpers are implementation details, not extension APIs.
|
`property(name)` returns `Property<?>`: cast to the known property type when writing from Java, for example `((StringProperty) loaded.property("name")).set("Grace")`. Generated accessors avoid these casts. `storedProperty` is for subclasses and reads only stored Model Attributes; it does not invoke custom reflective accessors. Internal loaders, appliers and identity-cache helpers are implementation details, not extension APIs.
|
||||||
|
|
||||||
For threading, strong identity retention, context reuse, the absence of a general disposal API, and JPMS reflection, see [architecture and lifetime](docs/architecture.md). For an independent application POM and runnable files, use the [complete quick start](docs/quick-start.md).
|
For threading, strong identity retention, context reuse, the absence of a general disposal API, and JPMS reflection, see [architecture and lifetime](docs/architecture.md). For an independent application POM and runnable files, use the [complete quick start](docs/quick-start.md).
|
||||||
|
|
||||||
|
DataGrid columns accept arbitrary string keys for group captions through the attached
|
||||||
|
`DataGridColumn.groupLabel` property. For example,
|
||||||
|
`<DataGridColumn.groupLabel><javafx.util.Pair key="Post/Eingang West" value="Eingang"/></DataGridColumn.groupLabel>`
|
||||||
|
writes the literal key into the same map as `<groupLabels Post="Postfach"/>`.
|
||||||
|
|||||||
+12
-3
@@ -5,9 +5,12 @@ Use JavaFX's `ToolBar` for toolbar content and NeitzelLib's
|
|||||||
ordinary application Nodes. They work in Java and ordinary FXML without a
|
ordinary application Nodes. They work in Java and ordinary FXML without a
|
||||||
DockingManager, ViewLoader, ViewModel or initialized injection context.
|
DockingManager, ViewLoader, ViewModel or initialized injection context.
|
||||||
|
|
||||||
The toolbar deliberately reuses JavaFX's existing public control: its item
|
Use JavaFX's `ToolBar` directly for permanent bars. `ToolBarPane` hosts a
|
||||||
list, orientation, overflow handling, accessibility and CSS already provide
|
horizontal JavaFX toolbar and adds an optional × at its left edge, outside
|
||||||
the required behavior. There is no second library toolbar API to learn.
|
the overflow menu. Set `dismissible` to show the button. Clicking it hides
|
||||||
|
the pane and calls `onDismiss` if supplied. Bind `managedProperty()` to
|
||||||
|
`visibleProperty()` when a hidden pane should release its layout space.
|
||||||
|
Show the pane again with `setVisible(true)`. Its items are retained.
|
||||||
|
|
||||||
## Java
|
## Java
|
||||||
|
|
||||||
@@ -98,3 +101,9 @@ required. The launch class is ordinary Java and delegates to the Application.
|
|||||||
The [MVVM docking editor](../../fx-example/docs/docking-mvvm.md) demonstrates
|
The [MVVM docking editor](../../fx-example/docs/docking-mvvm.md) demonstrates
|
||||||
Dockable-owned bars and optional MVVM bindings alongside a plain JavaFX editor.
|
Dockable-owned bars and optional MVVM bindings alongside a plain JavaFX editor.
|
||||||
The standalone controls also support ordinary JavaFX property bindings.
|
The standalone controls also support ordinary JavaFX property bindings.
|
||||||
|
|
||||||
|
## Window menus
|
||||||
|
|
||||||
|
Use `PlatformMenuBar.create(file, quit, view)` from `de.neitzel.fx.control` to build a window's JavaFX menu bar. Supply fresh menus and a localized Quit item with its action already set. Place the result at the top of the scene. On macOS the native menu bar follows the focused stage and supplies the Quit command. On other platforms the file menu includes the supplied Quit item. With docking, route its action to `manager.requestMainWindowClose()`.
|
||||||
|
|
||||||
|
For floating windows, set `FloatingWindowConfiguration.setMenuBarFactory(...)` in the floating window customizer. The factory receives the new window before it is shown. Use that window as the owner for dialogs launched by its menu.
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
# DataGrid layout, grouping and saved application setups
|
||||||
|
|
||||||
|
These features extend the opt-in queried DataGrid. Standalone collection/FXML
|
||||||
|
Table behavior is unchanged. Use Java 25 and call grid operations on the JavaFX
|
||||||
|
application thread.
|
||||||
|
|
||||||
|
## Group a returned page
|
||||||
|
|
||||||
|
Declare group values explicitly; never derive them from a rendered cell. A text
|
||||||
|
mapping is convenient for labels, while the full constructor supports integers,
|
||||||
|
exact decimals and booleans using `FilterValue` and `MemoryColumn.Kind`.
|
||||||
|
|
||||||
|
```java
|
||||||
|
// grid already has stable ResultColumn IDs and a source, as in data-grid.md.
|
||||||
|
grid.configureGrouping(
|
||||||
|
List.of(GroupColumn.<Person>text("name", Person::name),
|
||||||
|
GroupColumn.<Person>text("type", Person::type)),
|
||||||
|
true, // developer enables grouping
|
||||||
|
List.of("type"), // outer-to-inner default grouping columns
|
||||||
|
true, // unseen groups start collapsed
|
||||||
|
1000); // inactive expansion choices retained
|
||||||
|
```
|
||||||
|
|
||||||
|
`GroupColumn`, `GroupPath`, `GroupingSetup` and the projection/history models live
|
||||||
|
in `de.neitzel.grid`. All eligible values/labels are captured when a page publishes,
|
||||||
|
even for columns not currently grouped. `setGroupingColumns(List.of("type","name"))`
|
||||||
|
rearranges existing page components using those snapshots and issues no query.
|
||||||
|
`regroup()` explicitly recaptures group values after an application data update;
|
||||||
|
it does not change page membership. `refresh()` instead queries the source.
|
||||||
|
|
||||||
|
Text equality is exact, including case and whitespace; missing and empty text
|
||||||
|
are distinct. Decimal 1.0 and 1.00 share identity. Groups sort ascending, text
|
||||||
|
ignoring case with an exact tie-breaker, booleans false then true, missing last.
|
||||||
|
Rows within a leaf group retain their source order. Custom domains must map to
|
||||||
|
one declared scalar type; changing identity/normalization semantics requires a
|
||||||
|
schema migration. Labels never define identity. Invalid mappings fail visibly
|
||||||
|
without replacing the prior grouping.
|
||||||
|
|
||||||
|
Grouping applies only to the loaded page. The same value may recur on another
|
||||||
|
page; counts include collapsed data rows and exclude group headings. Explicit All
|
||||||
|
mode still uses the existing guard/confirmation protocol and retains all returned
|
||||||
|
row components. Collapsing it does not remove that memory cost.
|
||||||
|
|
||||||
|
## Interactions and row ownership
|
||||||
|
|
||||||
|
Drag a column's right boundary to preview a bounded width; release commits that
|
||||||
|
column and Escape restores its previous sizing intent. Drag a header label to
|
||||||
|
move a column, or into the grouping area to add a chip. Insertion feedback and
|
||||||
|
fixed-position constraints apply; invalid/outside drops cancel without sorting.
|
||||||
|
Drag chips to reorder grouping levels, and use × to remove a grouping level.
|
||||||
|
A header click sorts and the separate filter icon opens its editor. The Grid
|
||||||
|
setup menu offers keyboard-operable Column settings.
|
||||||
|
|
||||||
|
The arrow at the far right of the header opens a checklist of all columns.
|
||||||
|
Select a column to toggle its visibility. A column header's context menu offers
|
||||||
|
ascending and descending sorting, clearing that column's sort, filtering and
|
||||||
|
grouping where configured, resetting the column width, and hiding the column.
|
||||||
|
The arrow remains available when every column is hidden.
|
||||||
|
|
||||||
|
Applications can use `setColumnVisible(id, visible)`, `isColumnVisible(id)`,
|
||||||
|
and `columnVisibilityRevisionProperty()` to observe changes from either the UI or code.
|
||||||
|
Visibility applies to the open grid, including later pages. Hiding a column
|
||||||
|
preserves its order, width, filters, sorting, and grouping, and leaves existing
|
||||||
|
row components and drafts in place. Saved setups currently store the column
|
||||||
|
order and widths.
|
||||||
|
|
||||||
|
Each group has a disclosure triangle. Expansion follows the typed ordered path,
|
||||||
|
not its label or page number. Parent collapse preserves child choices. Current
|
||||||
|
paths are retained along with the configured LRU history of inactive explicit
|
||||||
|
choices; evicted paths return to the default. `setExpanded(path, boolean)` and
|
||||||
|
`resetExpansion()` provide programmatic equivalents. `setGroupingEnabled(false)`
|
||||||
|
hides grouped presentation without erasing valid dormant choices.
|
||||||
|
|
||||||
|
Reorder/regroup/collapse preserve current-page component identity and drafts.
|
||||||
|
Actual page replacement keeps the existing guard/staging/disposal rules. A hidden
|
||||||
|
selected record retains its key but has no actionable `selectedElement`. Expansion
|
||||||
|
never re-enables stale rows. If collapse/reset hides focus, focus moves to a visible
|
||||||
|
group heading. No historical rows are retained merely for expansion history.
|
||||||
|
|
||||||
|
## Attach optional persistence
|
||||||
|
|
||||||
|
`fx` does not depend on Gson. Add `de.neitzel.lib:gson` at the same library version
|
||||||
|
when using the supplied JSON/file integration. The neutral custom-store contracts
|
||||||
|
remain available without Gson.
|
||||||
|
|
||||||
|
```java
|
||||||
|
// Once per application, not per tab. No files/directories are created here.
|
||||||
|
var configuration = GridSetupFiles.forApplication("MyApplication");
|
||||||
|
|
||||||
|
// On each grid, after columns/grouping are configured, before the first query:
|
||||||
|
grid.configureSetups("people.records", 1,
|
||||||
|
Map.of("name", "text.v1", "type", "text.v1"), Map.of());
|
||||||
|
var attachment = grid.attachPersistence(configuration, "people.records");
|
||||||
|
attachment.loadAsync(); // read -> validate/restore or defaults -> one initial query
|
||||||
|
// attachment.ready() completes after initialization or explicit recovery succeeds.
|
||||||
|
```
|
||||||
|
|
||||||
|
Factory: `de.neitzel.gson.grid.GridSetupFiles`. Service/store:
|
||||||
|
`de.neitzel.grid.GridApplicationConfiguration` and `GridSetupStore`. Attachment:
|
||||||
|
`de.neitzel.fx.view.GridPersistenceAttachment`. An attachment overload accepts a
|
||||||
|
context key. `GridSetupFiles.forApplication(name, path)` selects an explicit grid
|
||||||
|
storage directory; another overload accepts pre-registered `GridSetupJson` codecs.
|
||||||
|
Custom stores implement blocking load/revision/conditional-save; the service runs
|
||||||
|
those operations off the FX thread.
|
||||||
|
|
||||||
|
The default directory is `ApplicationDirectories.configurationDirectory(name)`
|
||||||
|
plus `grids`. Grid/context keys map to opaque safe filenames, with identity checked
|
||||||
|
inside each document. Existing application preferences are never migrated.
|
||||||
|
Never-attached grids perform no persistence I/O. Attachments can be closed and
|
||||||
|
replaced; the application service owns accepted saves after detachment.
|
||||||
|
|
||||||
|
A stable grid ID/context shares one stored setup, not live displays. Newly opened
|
||||||
|
grids restore the latest successfully saved snapshot. Open grids keep their own
|
||||||
|
state until `attachment.loadAsync()` or Reload saved setup. The newest committed
|
||||||
|
change replaces the whole saved snapshot; fields from different views are not
|
||||||
|
merged. Closing an unchanged older tab cannot overwrite newer choices.
|
||||||
|
|
||||||
|
## Defaults, formats and recovery
|
||||||
|
|
||||||
|
The existing GridSetup format is extended with grouping and typed expansion
|
||||||
|
choices. Version-one documents remain readable; absent new preferences inherit
|
||||||
|
current developer grouping defaults. Current version-two documents require their
|
||||||
|
complete schema. Definition/type migrations, fixed-position validation, width
|
||||||
|
clamping and custom filter codecs retain their existing strict behavior.
|
||||||
|
Unsupported or incompatible files fail visibly, never by silently dropping fields.
|
||||||
|
|
||||||
|
`configureDefaults(GridSetup)` may configure the full default query/layout without
|
||||||
|
fetching, after definitions/mappings and before attachment/load. Otherwise defaults
|
||||||
|
are captured at attachment. Defaults stay separate from the restored display.
|
||||||
|
|
||||||
|
Committed changes autosave after a configurable debounce (500 ms by default).
|
||||||
|
`committedRevisionProperty()` is the FX notification seam; previews, cancelled
|
||||||
|
operations, drafts and failed/pending queries do not become saves. Query preferences
|
||||||
|
are saved only after successful publication. Saving/encoding failures retain the
|
||||||
|
latest unsaved snapshot and last good file. The grid shows nonmodal settings
|
||||||
|
feedback with Retry/Reload/Reset/Overwrite actions, separate from query status.
|
||||||
|
|
||||||
|
If no saved file exists, developer defaults apply. An unreadable/incompatible file blocks startup restoration
|
||||||
|
and initial query until retry or explicit reset succeeds. Full Reset setup uses
|
||||||
|
current defaults and the existing edit guard/transactional publication before
|
||||||
|
accepting a replacement save. Reset expansion only clears expansion choices and
|
||||||
|
never queries or resets other preferences.
|
||||||
|
|
||||||
|
The file store uses process coordination, revision-checked writes and atomic
|
||||||
|
replacement. A cross-process conflict requires explicit Reload or Overwrite.
|
||||||
|
Reload retires its abandoned pending generation only after successful guarded
|
||||||
|
restoration and cannot discard a newer change. Overwrite is still conditional
|
||||||
|
against a freshly observed revision. Unsupported atomic filesystem operations
|
||||||
|
fail rather than publishing a partial file.
|
||||||
|
|
||||||
|
## Close and application shutdown
|
||||||
|
|
||||||
|
```java
|
||||||
|
// Tab close, on FX thread:
|
||||||
|
attachment.close();
|
||||||
|
grid.close();
|
||||||
|
|
||||||
|
// Application shutdown: asynchronous; do not block the FX thread.
|
||||||
|
configuration.flushAsync();
|
||||||
|
configuration.closeAsync(); // also flushes; failure leaves the service retryable
|
||||||
|
// Only after explicit user consent to quit without settings:
|
||||||
|
configuration.discardAndCloseAsync();
|
||||||
|
```
|
||||||
|
|
||||||
|
Chain/await completion stages in the application exit coordinator; the snippet
|
||||||
|
lists operations, not permission to ignore their completion. A failed flush must
|
||||||
|
be handled before exit. Close does not own external executors. Explicit discard
|
||||||
|
retires pending work but cannot undo a write already committed. Detaching a grid
|
||||||
|
stops observation/cancels its unfinished restore, not already accepted app saves.
|
||||||
|
|
||||||
|
## Qualification
|
||||||
|
|
||||||
|
Automated component/state, codec, lifecycle and real separate-process storage tests
|
||||||
|
are provided. For native interaction qualification after running DataGridGroupingTest:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 fx/scripts/data-grid-probe.py
|
||||||
|
# macOS bundle for native accessibility tooling:
|
||||||
|
python3 fx/scripts/data-grid-probe.py --app
|
||||||
|
```
|
||||||
|
|
||||||
|
This opens actual JavaFX DataGrid controls with fictional records and a resource/
|
||||||
|
query trace. Use native pointer/keyboard input to qualify the recorded acceptance
|
||||||
|
scenarios; it is not a browser mock and emits no synthetic OS input. It has no
|
||||||
|
application persistence or real DNS/network data. Runtime/platform evidence and
|
||||||
|
remaining limits are recorded in the Workspace implementation record.
|
||||||
|
|
||||||
|
For repeatable macOS held-input checks (Escape during a drag, invalid/outside
|
||||||
|
native drops and timed edge hovering), the separate opt-in fixture uses AWT
|
||||||
|
Robot for pointer/keyboard input and JavaFX Robot for capture. It operates only
|
||||||
|
its fictional-data window and owned popups; no application data or DNS is used.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./mvnw -pl fx -am -Dtest=DataGridNativeInteractionTest \
|
||||||
|
-Dneitzellib.nativeGridTest=true -Dsurefire.failIfNoSpecifiedTests=false test
|
||||||
|
```
|
||||||
|
|
||||||
|
Without `neitzellib.nativeGridTest=true`, its five native tests are skipped.
|
||||||
|
On macOS the Java launcher and launching terminal or IDE need event-posting
|
||||||
|
permission in Privacy & Security → Accessibility. A permission-denied process
|
||||||
|
fails before posting input; that failure does not establish a gesture failure.
|
||||||
|
Restore any temporary permissions after testing. Keep the desktop idle: checks
|
||||||
|
stop if focus leaves their window and owned popups. Cleanup releases input and
|
||||||
|
disposes retained rows even on failure. Captures go to `fx/target/native-grid`.
|
||||||
|
Cancellation waits for the native drag-completion callback before releasing the
|
||||||
|
button or starting another gesture, including macOS's return animation.
|
||||||
+37
-2
@@ -1,5 +1,7 @@
|
|||||||
# Local DataGrid and request coordination
|
# Local DataGrid and request coordination
|
||||||
|
|
||||||
|
For direct declarations, columns and data bindings in FXML, see [FXML controls](fxml-controls.md).
|
||||||
|
|
||||||
`DataGrid<K,T>` composes the existing Table result renderer with paging controls and a toolkit-independent coordinator. All UI methods are called on the JavaFX application thread. The legacy Table FXML/collection path is unchanged.
|
`DataGrid<K,T>` composes the existing Table result renderer with paging controls and a toolkit-independent coordinator. All UI methods are called on the JavaFX application thread. The legacy Table FXML/collection path is unchanged.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@@ -23,13 +25,38 @@ Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` fo
|
|||||||
|
|
||||||
## Operations
|
## Operations
|
||||||
|
|
||||||
- First/Previous/Next/Last, page-size selection, Refresh and Retry are supplied. Page sizes offer 25/50/100/250 within source limits plus explicit All when supported. The initial page size is 50, bounded by source limits.
|
- Vertical separators mark column boundaries in headers and data rows, follow resizing/reordering, and use the active theme border color. Group headings span the columns.
|
||||||
|
- First/Previous/Next/Last use vector navigation icons with tooltips and accessible page names. Page-size selection, Refresh and Retry are supplied. Page sizes offer 25/50/100/250 within source limits plus explicit All when supported. The initial page size is 50, bounded by source limits.
|
||||||
- Header clicks alternate ascending/descending sort for that mapped column; `setSort(null)` clears user sorting. Sorting/filter/page-size changes request the first page (All remains All with fresh consent checks).
|
- Header clicks alternate ascending/descending sort for that mapped column; `setSort(null)` clears user sorting. Sorting/filter/page-size changes request the first page (All remains All with fresh consent checks).
|
||||||
- `setFilters`, `setSort`, `setPageRequest`, `setSource`, `load`, `refresh`, and `retry` delegate to the coordinator; returned rows are never locally filtered again.
|
- `setFilters`, `setSort`, `setPageRequest`, `setSource`, `load`, `refresh`, and `retry` delegate to the coordinator; returned rows are never locally filtered again.
|
||||||
- `stateProperty` exposes requested versus displayed query, result, phase and error. Loading/failed rows stay visible but disabled; selected loaded data becomes unavailable while those rows are stale. Query/navigation controls remain usable.
|
- `stateProperty` exposes requested versus displayed query, result, phase and error. Loading/failed rows stay visible but disabled; selected loaded data becomes unavailable while those rows are stale. Query/navigation controls remain usable.
|
||||||
- `selectedKeyProperty` retains an off-page identity. `selectedElementProperty` exposes only current displayed selected data. A successfully replaced source clears selection. `confirmedDeleted(key)` clears that key and refreshes; absence from a page alone does not imply deletion.
|
- `selectionMode` is configurable in Java or FXML: `NONE`, `SINGLE` (default), or `MULTIPLE`, using `RowSelectionMode`. Changing to NONE clears selection; changing to SINGLE keeps the lead key. Selection mode is application configuration and is not persisted in saved setups.
|
||||||
|
- `selectedKeysProperty` is a read-only observable list retaining off-page identities. `selectedElementsProperty` contains selected models only while their rows are visible and interactive. `selectedKeyProperty` / `selectedElementProperty` expose the lead key/model for compatibility. Single-item actions should require exactly one selected key and one loaded element.
|
||||||
|
- `select(key)` replaces selection (`null` clears); `selectKeys(keys)` replaces a multiple selection, with the last key as lead. Click replaces, Ctrl/Cmd-click toggles, Shift-click selects a range in visible grouped order, Ctrl/Cmd-Shift-click adds a range. Arrow/Home/End keys move through visible rows; Shift extends, Ctrl/Cmd moves focus, Space selects, Ctrl/Cmd-Space toggles, Ctrl/Cmd-A selects visible rows, Escape clears. Embedded editors keep their own keys. Rows have default selection colors even without an application theme.
|
||||||
|
- 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.
|
- 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
|
## 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.
|
`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.
|
||||||
@@ -43,3 +70,11 @@ The application must provide a serial owner-thread callback executor when using
|
|||||||
`close` cancels the active request, invalidates pending callbacks/alerts, closes the renderer and releases displayed rows. It does not close application-owned infrastructure. Observe `disposalFailureProperty` for row cleanup failures.
|
`close` cancels the active request, invalidates pending callbacks/alerts, closes the renderer and releases displayed rows. It does not close application-owned infrastructure. Observe `disposalFailureProperty` for row cleanup failures.
|
||||||
|
|
||||||
FXML filter editors and the opt-in popup host are now available; see [filter editors](filter-editors.md), including the recorded native qualification limitation. [JSON setup restore](saved-setups.md) is available through the optional Gson module. [Shared themes and window propagation](themes.md) are available opt-in. The optional [JDBC adapter and H2 example](../../fx-example/docs/product-grid.md) now demonstrate external execution. The default alert is ordinary JavaFX; native interaction/theme qualification remains part of those acceptance gates. Row mappings, programmatic order/width changes and cleanup retain the foundation guide's constraints in [table-results](table-results.md).
|
FXML filter editors and the opt-in popup host are now available; see [filter editors](filter-editors.md), including the recorded native qualification limitation. [JSON setup restore](saved-setups.md) is available through the optional Gson module. [Shared themes and window propagation](themes.md) are available opt-in. The optional [JDBC adapter and H2 example](../../fx-example/docs/product-grid.md) now demonstrate external execution. The default alert is ordinary JavaFX; native interaction/theme qualification remains part of those acceptance gates. Row mappings, programmatic order/width changes and cleanup retain the foundation guide's constraints in [table-results](table-results.md).
|
||||||
|
|
||||||
|
## Interactive layout and grouping
|
||||||
|
|
||||||
|
Column resize/reorder, grouping chips, disclosure and keyboard Column settings
|
||||||
|
are now opt-in DataGrid features. Application-name-based saved setups are an
|
||||||
|
optional attachment using the existing versioned setup model. See the
|
||||||
|
[layout, grouping and persistence guide](data-grid-layout.md) for mappings,
|
||||||
|
component lifetime, startup/recovery, storage concurrency and shutdown.
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
# Controls in FXML
|
||||||
|
|
||||||
|
Every public visual control supplied by `fx` can be declared in ordinary FXML.
|
||||||
|
`FXMLLoader` constructs the view without a database, DNS connection or injection
|
||||||
|
context. The optional `ViewLoader` applies NeitzelLib binding declarations.
|
||||||
|
|
||||||
|
| Control | FXML configuration | Data and lifetime |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `de.neitzel.fx.view.DataGrid` | Columns, typed attributes, widths, filters, grouping, page size, `selectionMode` and setup identity | Bind `items` or `source`; explicitly load after configuration, close with the view |
|
||||||
|
| `de.neitzel.fx.view.Table` | `collection`, `row`, `Column` declarations | Existing ViewLoader collection/Component rows and `selection` binding |
|
||||||
|
| `de.neitzel.fx.control.StatusBar` | `leftItems`, `rightItems` containing ordinary Nodes | Bind the properties of the contained controls |
|
||||||
|
| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes, fixed `suggestions` and a bindable `suggestionsSource` of type `ObservableList<String>` | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action |
|
||||||
|
| `de.neitzel.fx.control.HtmlViewer` | `mediaButtonVisible`, `mediaLoadText`, `mediaReloadText`, `mediaTooltipText`, `noExternalMediaText` | Bind local text to `html` or use `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) |
|
||||||
|
| `de.neitzel.fx.control.TagChip` | `text`, `removable` (false by default), `onRemove` | The action handler owns removing the tag from its model |
|
||||||
|
| `de.neitzel.fx.docking.DockPane` | `initialLayout`, `DockLayout`, group/split definitions | Attach a DockingManager to open application-owned content |
|
||||||
|
| `de.neitzel.fx.control.NonNegativeIntegerSpinner` | `minimum`, `maximum`, `initialValue` constructor attributes | Bind writable `number`, which shares the value factory's property |
|
||||||
|
| `javafx.scene.control.ToolBar` | Standard `items` and `orientation` | Standard JavaFX control, deliberately reused by the library |
|
||||||
|
| `de.neitzel.fx.control.ToolBarPane` | `items`, `dismissible`, `dismissText`, `onDismiss` | Uses a JavaFX ToolBar and keeps the optional dismissal button outside overflow |
|
||||||
|
|
||||||
|
Supporting objects such as coordinators, sources, setup stores, popup hosts,
|
||||||
|
result renderers, theme managers and tray integrations are application/runtime
|
||||||
|
objects, rather than controls to insert in a scene graph.
|
||||||
|
|
||||||
|
## DataGrid
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<?import de.neitzel.fx.view.*?>
|
||||||
|
<?import javafx.scene.layout.VBox?>
|
||||||
|
|
||||||
|
<VBox xmlns:fx="http://javafx.com/fxml/1">
|
||||||
|
<fx:define>
|
||||||
|
<BindingList>
|
||||||
|
<DirectBinding control="people" property="items"
|
||||||
|
path="people" direction="view"/>
|
||||||
|
</BindingList>
|
||||||
|
</fx:define>
|
||||||
|
<DataGrid fx:id="people" keyAttribute="id" pageSize="50"
|
||||||
|
maximumPageSize="250" groupingEnabled="true" groupBy="department"
|
||||||
|
groupsCollapsed="false" setupId="people" setupVersion="1">
|
||||||
|
<columns>
|
||||||
|
<DataGridColumn id="name" header="Name" width="200"
|
||||||
|
checklist="SOURCE_WIDE"/>
|
||||||
|
<DataGridColumn id="department" header="Department" width="180"/>
|
||||||
|
<DataGridColumn id="age" header="Age" kind="INTEGER"/>
|
||||||
|
</columns>
|
||||||
|
</DataGrid>
|
||||||
|
</VBox>
|
||||||
|
```
|
||||||
|
|
||||||
|
Initialize the model's `List<Person> people` before loading. Bean and Java record
|
||||||
|
rows are supported. After `ViewLoader.load`, call the injected grid's `load()` or
|
||||||
|
`loadAsync()` on the FX thread. The data binding shares the model's observable
|
||||||
|
list. Add, remove, replace, permute or use an extractor update on that list to
|
||||||
|
request a refresh immediately, invalidating older pending results. The existing
|
||||||
|
query (filters/sort/page) is retained; use `setAll` for a single batch update. Replacing `grid.items` detaches
|
||||||
|
the old list. Rows are snapshots: mutating a field without an observable update
|
||||||
|
requires `refresh()`.
|
||||||
|
|
||||||
|
Configure before the first runtime operation. `initialize()` completes setup
|
||||||
|
without querying, allowing an application to attach persistence before calling
|
||||||
|
`loadAsync()`. Nothing loads in the constructor, and FXML without data displays
|
||||||
|
column headers in a query-free preview. State is null until initialization.
|
||||||
|
|
||||||
|
For ordinary `FXMLLoader`, provide the list in its namespace and use
|
||||||
|
`items="$people"`, or assign/bind `itemsProperty()` after loading. The same
|
||||||
|
explicit loading and closing contract applies. `DirectBinding` requires
|
||||||
|
`ViewLoader`; the usual collection-binding limitations in the main reference
|
||||||
|
still apply, including replacing model attributes through the ViewModel.
|
||||||
|
|
||||||
|
A local grid requires a stable unique row key: `keyAttribute="id"` reads a public
|
||||||
|
bean getter or record accessor. Alternatively supply `keyFactory` and
|
||||||
|
`keyComparator` in Java before initialization. Keys must be comparable when no
|
||||||
|
comparator is supplied. Duplicate/null keys fail the query visibly. The local
|
||||||
|
grid owns its virtual-thread executor and releases it on `close()`.
|
||||||
|
|
||||||
|
For an external queried grid, bind `source` instead of `items`. Column IDs must
|
||||||
|
match the source mappings. The source and executor remain application-owned.
|
||||||
|
Changing an initialized source starts a request using the current filters/sort
|
||||||
|
and first page, as with the programmatic interface. External checklist filters
|
||||||
|
need an explicitly supplied `candidates` provider; local sources supply one.
|
||||||
|
|
||||||
|
Column defaults: `attribute` uses `id`, `kind="TEXT"`, width 150, minimum 80,
|
||||||
|
maximum 1200, fixed position -1 (movable), filterable true, checklist disabled.
|
||||||
|
Kinds are `TEXT`, `INTEGER`, `DECIMAL`, `BOOLEAN`. Text and numeric filter editors
|
||||||
|
are built in; boolean values can render/group and use programmatic conditions,
|
||||||
|
but have no built-in editor. Set `filterable="false"` for display-only columns.
|
||||||
|
`groupAttribute` optionally separates stable group values from displayed/filter
|
||||||
|
values; `groupLabels` maps those values to display labels without changing group
|
||||||
|
identity. `type` supplies a stable schema type for saved setups; the default is
|
||||||
|
`neitzel.<kind>.v1`. Keep type IDs and setup versions stable across upgrades.
|
||||||
|
|
||||||
|
The default row factory creates labels. Supply a Java `rowFactory` for custom
|
||||||
|
nodes, styles, tooltips or actions; use `DataGridColumn.getValue(row)` to share
|
||||||
|
the FXML mappings. FXML can also reference factories using `$factory` namespace
|
||||||
|
values. Selection is available through the stable read-only
|
||||||
|
`selectedKeyProperty()` and `selectedElementProperty()`; call `select(key)` to
|
||||||
|
change it. Existing programmatic constructor and queried-grid behavior remain
|
||||||
|
supported.
|
||||||
|
|
||||||
|
## Bounded integer spinner
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<?import de.neitzel.fx.control.NonNegativeIntegerSpinner?>
|
||||||
|
<NonNegativeIntegerSpinner xmlns:fx="http://javafx.com/fxml/1"
|
||||||
|
fx:id="quantity" minimum="0" maximum="100"
|
||||||
|
initialValue="1"/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `<DirectBinding control="quantity" property="number" path="quantity"
|
||||||
|
direction="both"/>` in a ViewLoader binding list. Valid typing commits
|
||||||
|
immediately; invalid typing and bounds follow [bounded integer inputs](integer-spinners.md).
|
||||||
|
The original `IntegerSpinners.nonNegative(...)` factory remains available.
|
||||||
|
|
||||||
|
See [bars](bars.md), [docking](docking.md) and the main [FXML reference](../README.md)
|
||||||
|
for the existing controls. The host designer needs the updated library on its
|
||||||
|
classpath; this feature does not replace a separately pinned Designer runtime.
|
||||||
|
|
||||||
|
### Model-driven suggestions
|
||||||
|
|
||||||
|
Use `<DirectBinding control="dynamic" property="suggestionsSource" path="tags" direction="view"/>`
|
||||||
|
for an observable list of strings. A non-null source (including an empty list) takes precedence over
|
||||||
|
the fixed FXML entries in `getSuggestions()`. The popup follows replacements and edits to the active
|
||||||
|
list while the field is attached. Choosing a match sets the field text and fires its action.
|
||||||
|
Setting the source to null or unbinding `suggestionsSourceProperty()` restores the fixed entries.
|
||||||
|
Closing a managed DirectBinding restores its previous list source. Removing the field from its
|
||||||
|
scene dismisses the popup and detaches its list listener.
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# Saved HTML viewer
|
||||||
|
|
||||||
|
`de.neitzel.fx.control.HtmlViewer` displays local HTML and SingleFile exports.
|
||||||
|
It preserves saved CSS, classes, inline styles, embedded fonts and background
|
||||||
|
images. SVGs are rendered as isolated images; embedded WebP is converted to PNG
|
||||||
|
in memory for WebView. Files are never rewritten. The control needs ordinary
|
||||||
|
JavaFX only, with no MVVM or injection initialization.
|
||||||
|
|
||||||
|
```java
|
||||||
|
// In Application.start(Stage stage):
|
||||||
|
var viewer = new HtmlViewer();
|
||||||
|
stage.setScene(new Scene(viewer, 900, 600));
|
||||||
|
stage.setOnHidden(event -> viewer.close());
|
||||||
|
stage.show();
|
||||||
|
viewer.load(Path.of("saved-page.html"));
|
||||||
|
```
|
||||||
|
|
||||||
|
`load(Path)` and `loadHtml(String)` prepare content on an owned virtual thread.
|
||||||
|
`loadHtml(String, URI)` additionally accepts an HTTP(S) source address for relative
|
||||||
|
images. It never fetches that address. A saved `<base href>` takes precedence.
|
||||||
|
Input is limited to 32 MiB (UTF-8 bytes for strings). File loads detect the saved encoding.
|
||||||
|
WebP conversion is bounded to 16 megapixels per image and a 64 MiB encoded-image
|
||||||
|
budget per preparation. Invalid or oversized images keep their original data.
|
||||||
|
|
||||||
|
For applications that already prepare documents in the background, use
|
||||||
|
`HtmlDocument.read(Path)` or `HtmlDocument.parse(String[, URI])` off the FX thread,
|
||||||
|
then `viewer.display(document)` on the FX thread. A prepared document is immutable
|
||||||
|
and may be shared between viewers; permissions are never shared with it.
|
||||||
|
|
||||||
|
All viewer operations and property access belong on the FX thread.
|
||||||
|
`loadingProperty()` covers preparation and browser loading; `errorProperty()`
|
||||||
|
reports the current preparation/rendering failure. A progress indicator and error
|
||||||
|
message are included. New loads cancel pending work and discard stale results.
|
||||||
|
`clear()` releases the current content and leaves the viewer reusable. `close()`
|
||||||
|
also cancels pending work, is idempotent, and makes future loads fail.
|
||||||
|
|
||||||
|
## Model-driven source
|
||||||
|
|
||||||
|
Bind a string toward the viewer with a DirectBinding such as
|
||||||
|
`<DirectBinding control="article" property="html" path="html" direction="view"/>`.
|
||||||
|
For plain JavaFX use `viewer.htmlProperty().bind(source)`. Each changed string uses
|
||||||
|
the offline `loadHtml` preparation. A null or blank value clears the document.
|
||||||
|
Rapid changes cancel older preparations and revoke earlier media grants.
|
||||||
|
The property contains the supplied source. Displaying a prepared document, loading a file,
|
||||||
|
granting image access or clearing the viewer changes the display without writing to the model.
|
||||||
|
The next change to the bound text takes effect. Unbinding leaves the current display in place.
|
||||||
|
Close the viewer on disposal to detach a JavaFX binding and cancel outstanding work.
|
||||||
|
|
||||||
|
## External images
|
||||||
|
|
||||||
|
Each displayed document starts offline. The included **Load external media**
|
||||||
|
button calls `loadExternalImages()`, which explicitly allows HTTP(S) images only
|
||||||
|
for that viewer and document. The same permission covers CSS background images.
|
||||||
|
`externalImagesAvailableProperty()` indicates detected external image addresses;
|
||||||
|
`externalImagesAllowedProperty()` reports whether permission was granted.
|
||||||
|
Loading or displaying another document, clearing, or closing revokes permission.
|
||||||
|
No permission is stored in configuration or in the source file.
|
||||||
|
|
||||||
|
JavaScript, embedded webpages, external stylesheets, external fonts and navigation
|
||||||
|
remain disabled. Embedded SVG is rendered in
|
||||||
|
[SVG secure image mode](https://www.w3.org/TR/SVG/latest/conform.html), rather than
|
||||||
|
as active SVG markup. The document CSP is also applied to saved CSS that the CSS
|
||||||
|
parser does not understand. This is a saved-document viewer; pages that require
|
||||||
|
JavaScript or missing source images cannot be reconstructed.
|
||||||
|
|
||||||
|
Set `mediaButtonVisible=false` if the application supplies its own action.
|
||||||
|
Bind that action to availability/loading and call `loadExternalImages()` on click.
|
||||||
|
Applications still own document tabs, archive paths, metadata, search text, and
|
||||||
|
opening files in external applications.
|
||||||
|
|
||||||
|
## FXML and translations
|
||||||
|
|
||||||
|
Construction performs no file or network I/O. Ordinary `FXMLLoader` can create
|
||||||
|
an idle viewer; the controller explicitly loads its document afterward.
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<?import de.neitzel.fx.control.HtmlViewer?>
|
||||||
|
<HtmlViewer xmlns:fx="http://javafx.com/fxml/1" fx:id="article"
|
||||||
|
mediaButtonVisible="true"
|
||||||
|
mediaLoadText="Externe Medien laden"
|
||||||
|
mediaReloadText="Externe Medien erneut laden"
|
||||||
|
mediaTooltipText="Lädt Bilder nur für diese Ansicht und kontaktiert deren Server."
|
||||||
|
noExternalMediaText="Keine auflösbaren externen Bildadressen gefunden."/>
|
||||||
|
```
|
||||||
|
|
||||||
|
The four text attributes also expose writable StringProperties for ordinary
|
||||||
|
binding or live `Messages.observable(...)` translations. Style classes are
|
||||||
|
`html-viewer` on the root and `html-viewer-media-load` on its action button.
|
||||||
|
|
||||||
|
The tests cover SVG/CSS/WebP rendering through WebView snapshot pixels, offline
|
||||||
|
opening, per-viewer grants, replacement/close, loopback network requests, error
|
||||||
|
handling, and ordinary FXML loading. They require a graphical JavaFX session.
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Message catalogs for Java and FXML
|
||||||
|
|
||||||
|
Create one Localizer per application. The initial locale can be null to use the JVM display locale. The second argument specifies the fallback language. Register the service with the same ApplicationContext used by ViewLoader.
|
||||||
|
|
||||||
|
```java
|
||||||
|
var language = new Localizer(initialLocale, Locale.ENGLISH,
|
||||||
|
new Localizer.Catalog(MyApp.class, "MyApp", "org.example.myapp"),
|
||||||
|
LanguageMenu.CATALOG);
|
||||||
|
context.addSingleton(Localizer.class, language);
|
||||||
|
var texts = language.forClass(AccountController.class);
|
||||||
|
label.setText(texts.text("account.saved", accountName));
|
||||||
|
```
|
||||||
|
|
||||||
|
Catalogs are UTF-8 properties files. For each key the search tries the requested locale's variants (for example de-CH before de), then variants of the fallback locale, then files without a language suffix. Each pass visits the view catalog beside its FXML, the controller's class catalog, package Messages catalogs up to the configured root, the named application catalog and the named library catalogs in registration order. For example, use Account_de.properties beside Account.fxml and MyApp_de.properties at the application resource root. Missing keys display as ⟦key⟧ and log once per locale and catalog context. Java calls with arguments use MessageFormat patterns.
|
||||||
|
|
||||||
|
ViewLoader supplies the same Messages bundle to the FXMLLoader and the controller. Use `<Button text="%account.save"/>` in FXML and `@FXML private Messages resources;` in the controller. A plain fx:include inherits the parent's bundle. Load reusable components separately for their own catalog. For an ordinary FXMLLoader, pass `language.forView(location, controllerClass)` as its ResourceBundle.
|
||||||
|
|
||||||
|
Change the language on the FX thread with `language.setLocale(locale)`. Ordinary text lookups return a string immediately. Bind individual live labels with `label.textProperty().bind(texts.observable("account.save"))` or observe `language.localeProperty()` to refresh a view. FXML attributes resolve again when the view is recreated. LanguageMenu.create supplies a selector with an owner for its notice and a callback for saving a user selection. Pass a Messages bundle to DockingOptions.setResourceBundle for localized docking commands.
|
||||||
@@ -24,3 +24,10 @@ container.getChildren().add(quantity);
|
|||||||
```
|
```
|
||||||
|
|
||||||
Import `javafx.scene.control.Spinner` and `de.neitzel.fx.control.IntegerSpinners`; `container` is your Pane. Read `quantity.getValue()` to obtain the committed number. Set a programmatic value through `quantity.getValueFactory().setValue(...)`. Use the factory's bounds as UI constraints and keep independent business validation where the value is saved. The helper does not add an FXML binding declaration or create a Model Attribute automatically.
|
Import `javafx.scene.control.Spinner` and `de.neitzel.fx.control.IntegerSpinners`; `container` is your Pane. Read `quantity.getValue()` to obtain the committed number. Set a programmatic value through `quantity.getValueFactory().setValue(...)`. Use the factory's bounds as UI constraints and keep independent business validation where the value is saved. The helper does not add an FXML binding declaration or create a Model Attribute automatically.
|
||||||
|
|
||||||
|
## FXML
|
||||||
|
|
||||||
|
Declare `NonNegativeIntegerSpinner` with `minimum`, `maximum`, and `initialValue`
|
||||||
|
constructor attributes. Bind its writable `number` property with `DirectBinding`;
|
||||||
|
it shares the value factory property and supports both directions. See the
|
||||||
|
[FXML controls guide](fxml-controls.md#bounded-integer-spinner).
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
# Your first JavaFX application
|
# 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. 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.6. The source build below uses the matching release tag.
|
||||||
|
|
||||||
## Prepare the library
|
## 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.
|
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
|
```bash
|
||||||
git clone --branch v1.0 https://gitea.neitzel.de/konrad/NeitzelLib.git
|
git clone --branch v1.0.6 https://gitea.neitzel.de/konrad/NeitzelLib.git
|
||||||
cd NeitzelLib
|
cd NeitzelLib
|
||||||
./mvnw -pl fx-example -am install
|
./mvnw -pl fx-example -am install
|
||||||
./mvnw -f fx-example/pom.xml javafx:run
|
./mvnw -f fx-example/pom.xml javafx:run
|
||||||
```
|
```
|
||||||
|
|
||||||
The `install` command installs the parent POM, `core`, `injection` and `fx` into your local Maven repository and builds the example. Surefire fails the build when a test fails. The XML reports show which tests ran. The `javafx:run` command opens the [person desk example](../../fx-example/README.md). Run `javafx:run` only on the example POM, not with `-am`: the reactor parent is not a JavaFX application.
|
The `install` command installs the parent POM, `core`, `data-grid`, `injection` and `fx` into your local Maven repository and builds the example. Surefire fails the build when a test fails. The XML reports show which tests ran. The `javafx:run` command opens the [person desk example](../../fx-example/README.md). Run `javafx:run` only on the example POM, not with `-am`: the reactor parent is not a JavaFX application.
|
||||||
|
|
||||||
Check test results after the build (requires Python 3):
|
Check test results after the build (requires Python 3):
|
||||||
|
|
||||||
@@ -66,7 +66,7 @@ hello-fx/
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.6</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
@@ -190,7 +190,7 @@ For a named-module application, see the [module and lifecycle notes](architectur
|
|||||||
|
|
||||||
| Symptom | Check |
|
| Symptom | Check |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Maven cannot resolve `de.neitzel.lib:fx:1.0` 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.6` 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. |
|
| `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. |
|
| 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. |
|
| `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. |
|
||||||
|
|||||||
+11
-1
@@ -1,6 +1,7 @@
|
|||||||
# Saved DataGrid setups
|
# Saved DataGrid setups
|
||||||
|
|
||||||
Saved setups are opt-in and preserve the legacy Table path. The `data-grid` module owns immutable models, definition validation and migrations; `fx` stages layout/result publication; the existing optional `gson` module owns JSON encoding. Applications choose storage and save/load timing. The FX library does not depend on Gson.
|
Saved setups are opt-in and preserve the legacy Table path. The `data-grid` module owns immutable models, definition validation and migrations; `fx` stages layout/result publication; the existing optional `gson` module owns JSON encoding. Applications choose storage and save/load timing. The FX library does not depend on Gson. An optional application-owned attachment
|
||||||
|
now supplies automatic storage/timing; see [layout and persistence](data-grid-layout.md).
|
||||||
|
|
||||||
## Configure and save
|
## Configure and save
|
||||||
|
|
||||||
@@ -48,3 +49,12 @@ Appending a new column does not itself require a migration when the saved defini
|
|||||||
Implement and register `GridSetupJson.FilterCodec` for a custom stable filter type ID. Declare the write version, readable versions, explicit JSON payload and decoding logic. The codec must preserve the requested column/type identity. `readableVersions` defaults to the current write version; support older payloads only with explicit decoding/migration logic. Missing codecs and unsupported payload versions fail visibly. Codec registration is independent of editor availability and local/adapter execution; successful decoding does not establish that the active source supports the condition.
|
Implement and register `GridSetupJson.FilterCodec` for a custom stable filter type ID. Declare the write version, readable versions, explicit JSON payload and decoding logic. The codec must preserve the requested column/type identity. `readableVersions` defaults to the current write version; support older payloads only with explicit decoding/migration logic. Missing codecs and unsupported payload versions fail visibly. Codec registration is independent of editor availability and local/adapter execution; successful decoding does not establish that the active source supports the condition.
|
||||||
|
|
||||||
Built-in text, number, missing/present and checklist codecs are supplied. The built-in editor registrations now declare persistence support through this optional module. See the [JDBC demonstration](../../fx-example/docs/product-grid.md) and [shared themes](themes.md) for opt-in integration.
|
Built-in text, number, missing/present and checklist codecs are supplied. The built-in editor registrations now declare persistence support through this optional module. See the [JDBC demonstration](../../fx-example/docs/product-grid.md) and [shared themes](themes.md) for opt-in integration.
|
||||||
|
|
||||||
|
## Grouping format and automatic storage
|
||||||
|
|
||||||
|
Format version 2 adds ordered grouping columns and typed expansion-path choices.
|
||||||
|
The version-one constructor/codec path remains available; compatible old documents
|
||||||
|
inherit developer grouping defaults at restore. Preserve explicit expansion choices
|
||||||
|
even when equal to defaults. The optional file integration wraps the setup in a
|
||||||
|
strict grid/context/revision document and uses conditional atomic replacement.
|
||||||
|
The plain GridSetupJson API remains available for application-managed storage.
|
||||||
|
|||||||
@@ -18,10 +18,15 @@ Factories may supply freshly bound FXML Components as HBox roots. They must map
|
|||||||
|
|
||||||
The renderer preserves supplied row order and does no local filtering, sorting, fetching or edit observation. The caller validates query results and handles guard approval before calling `show`. It stages new rows before replacing old ones. If construction or mapping validation fails, staged rows are disposed and the old page remains. Factory code that throws before returning a row owns cleanup of its partial construction.
|
The renderer preserves supplied row order and does no local filtering, sorting, fetching or edit observation. The caller validates query results and handles guard approval before calling `show`. It stages new rows before replacing old ones. If construction or mapping validation fails, staged rows are disposed and the old page remains. Factory code that throws before returning a row owns cleanup of its partial construction.
|
||||||
|
|
||||||
`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. This first integration point supplies programmatic ordering/sizing, not drag UI. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
|
`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. The result integration now also supplies native resize/reorder and grouping support
|
||||||
|
when composed by DataGrid; the stable programmatic operations remain available. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
|
||||||
|
|
||||||
`select(key)` retains an off-page key; the read-only loaded selected element becomes null until that key returns. Row clicks and blank-body clicks update this separate result selection. The old `Table.selectionProperty()` remains the legacy path and is not the result-mode selection API.
|
`setSelectionMode(RowSelectionMode.NONE/SINGLE/MULTIPLE)` configures selection (default SINGLE). `select(key)` replaces selection; `selectKeys(keys)` supports multiple identities, including off-page keys. `selectedKeysProperty()` and `selectedElementsProperty()` expose unmodifiable observable lists; loaded elements include only visible interactive rows. The singular properties expose the lead. `deselect(key)` removes one identity. See [DataGrid selection](data-grid.md) for mouse and keyboard gestures. Row clicks and blank-body clicks update this separate result selection. The old `Table.selectionProperty()` remains the legacy path and is not the result-mode selection API.
|
||||||
|
|
||||||
`close()` is idempotent, removes rows/handlers and disposes row resources. Disposal failures do not undo an already published page; observe `disposalFailureProperty()` to surface them. Explicit close is necessary; attaching/removing a Table from a Scene does not infer application ownership.
|
`close()` is idempotent, removes rows/handlers and disposes row resources. Disposal failures do not undo an already published page; observe `disposalFailureProperty()` to surface them. Explicit close is necessary; attaching/removing a Table from a Scene does not infer application ownership.
|
||||||
|
|
||||||
This is a rendering foundation, not the complete DataGrid. [Local DataGrid](data-grid.md) now supplies request coordination and local source execution. [FXML popup editors](filter-editors.md), [setup codecs](saved-setups.md), and [themes](themes.md) are implemented. Ordering and sizing use the documented programmatic API; drag reorder/resize is not supplied by this result renderer.
|
This is a rendering foundation, not the complete DataGrid. [Local DataGrid](data-grid.md) now supplies request coordination and local source execution. [FXML popup editors](filter-editors.md), [setup codecs](saved-setups.md), and [themes](themes.md) are implemented. DataGrid exposes both programmatic layout operations and native resize/reorder interactions over this result renderer.
|
||||||
|
|
||||||
|
[DataGrid layout/grouping](data-grid-layout.md) documents the component-preserving
|
||||||
|
projection path. Local grouping must not call `show` to recreate current-page
|
||||||
|
editors; `show` remains the guarded replacement/publication boundary.
|
||||||
|
|||||||
+23
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.6</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
@@ -18,6 +18,11 @@
|
|||||||
<launcher>${project.artifactId}</launcher>
|
<launcher>${project.artifactId}</launcher>
|
||||||
<appName>${project.artifactId}</appName>
|
<appName>${project.artifactId}</appName>
|
||||||
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
|
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
|
||||||
|
|
||||||
|
<!-- Dependency versions -->
|
||||||
|
<imageio-webp.version>3.15.3</imageio-webp.version>
|
||||||
|
<jsoup.version>1.23.2</jsoup.version>
|
||||||
|
<ph-css.version>8.2.3</ph-css.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@@ -43,6 +48,23 @@
|
|||||||
<artifactId>javafx-web</artifactId>
|
<artifactId>javafx-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Saved HTML rendering -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jsoup</groupId>
|
||||||
|
<artifactId>jsoup</artifactId>
|
||||||
|
<version>${jsoup.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.helger</groupId>
|
||||||
|
<artifactId>ph-css</artifactId>
|
||||||
|
<version>${ph-css.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.twelvemonkeys.imageio</groupId>
|
||||||
|
<artifactId>imageio-webp</artifactId>
|
||||||
|
<version>${imageio-webp.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- NeitzelLib dependencies -->
|
<!-- NeitzelLib dependencies -->
|
||||||
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Launch the real DataGrid native qualification surface after DataGridGroupingTest.
|
||||||
|
|
||||||
|
On macOS, --app creates an addressable app bundle for native accessibility tools.
|
||||||
|
All generated artifacts stay under fx/target. No application data or persistence.
|
||||||
|
"""
|
||||||
|
import pathlib
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
module = pathlib.Path(__file__).resolve().parent.parent
|
||||||
|
report = module / 'target/surefire-reports/TEST-de.neitzel.fx.view.DataGridGroupingTest.xml'
|
||||||
|
if not report.exists():
|
||||||
|
sys.exit('First run ./mvnw -pl fx -am -Dtest=DataGridGroupingTest -Dsurefire.failIfNoSpecifiedTests=false test')
|
||||||
|
properties = {p.get('name'): p.get('value') for p in ET.parse(report).getroot().find('properties')}
|
||||||
|
classpath = properties.get('surefire.test.class.path', properties['java.class.path'])
|
||||||
|
app_name = 'DataGridProbe'
|
||||||
|
main = 'de.neitzel.fx.view.DataGridNativeProbe'
|
||||||
|
if '--app' in sys.argv:
|
||||||
|
work = module / 'target/native-probe'
|
||||||
|
inputs = work / 'input'
|
||||||
|
inputs.mkdir(parents=True, exist_ok=True)
|
||||||
|
with zipfile.ZipFile(inputs / 'probe.jar', 'w') as archive:
|
||||||
|
seen = set()
|
||||||
|
for entry in classpath.split(':'):
|
||||||
|
path = pathlib.Path(entry)
|
||||||
|
if path.is_dir():
|
||||||
|
for file in path.rglob('*'):
|
||||||
|
if file.is_file() and str(file.relative_to(path)) not in seen:
|
||||||
|
relative = str(file.relative_to(path))
|
||||||
|
seen.add(relative)
|
||||||
|
archive.write(file, relative)
|
||||||
|
elif path.suffix == '.jar':
|
||||||
|
target = inputs / path.name
|
||||||
|
if target.exists() and target.read_bytes() != path.read_bytes():
|
||||||
|
sys.exit('Conflicting dependency filename: ' + path.name)
|
||||||
|
shutil.copy2(path, target)
|
||||||
|
app = work / (app_name + '.app')
|
||||||
|
if app.exists():
|
||||||
|
shutil.rmtree(app)
|
||||||
|
subprocess.run(['jpackage', '--type', 'app-image', '--name', app_name,
|
||||||
|
'--input', str(inputs), '--dest', str(work), '--main-jar', 'probe.jar',
|
||||||
|
'--main-class', main, '--mac-package-identifier', 'de.neitzel.datagrid.probe',
|
||||||
|
'--java-options', '--enable-native-access=ALL-UNNAMED',
|
||||||
|
'--java-options', '-Dneitzellib.nativeGridOutput=' + str(module / 'target/native-grid')], check=True)
|
||||||
|
print(app, flush=True)
|
||||||
|
raise SystemExit(subprocess.call([str(app / ('Contents/MacOS/' + app_name))]))
|
||||||
|
raise SystemExit(subprocess.call(['java', '--enable-native-access=ALL-UNNAMED', '-cp', classpath,
|
||||||
|
main], cwd=module.parent))
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import javafx.scene.control.ButtonBase;
|
||||||
|
import javafx.scene.control.ContentDisplay;
|
||||||
|
import javafx.scene.control.Tooltip;
|
||||||
|
import javafx.scene.layout.StackPane;
|
||||||
|
import javafx.scene.shape.SVGPath;
|
||||||
|
|
||||||
|
/** A button graphic that follows the control's text color and exposes a tooltip and accessible name. */
|
||||||
|
public final class ActionIcon {
|
||||||
|
private ActionIcon() {}
|
||||||
|
|
||||||
|
/** Installs an outlined icon drawn on a 16 by 16 coordinate grid. */
|
||||||
|
public static void install(ButtonBase button, String description, String path) {
|
||||||
|
var icon = new SVGPath();
|
||||||
|
icon.setContent(path);
|
||||||
|
icon.setFill(null);
|
||||||
|
icon.strokeProperty().bind(button.textFillProperty());
|
||||||
|
icon.setStrokeWidth(1.5);
|
||||||
|
icon.setStrokeLineCap(javafx.scene.shape.StrokeLineCap.ROUND);
|
||||||
|
icon.setStrokeLineJoin(javafx.scene.shape.StrokeLineJoin.ROUND);
|
||||||
|
var graphic = new StackPane(icon);
|
||||||
|
graphic.setMinSize(18, 18);
|
||||||
|
graphic.setPrefSize(18, 18);
|
||||||
|
graphic.setMaxSize(18, 18);
|
||||||
|
graphic.setMouseTransparent(true);
|
||||||
|
button.setGraphic(graphic);
|
||||||
|
button.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
|
||||||
|
button.setAccessibleText(description);
|
||||||
|
button.setTooltip(new Tooltip(description));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import javafx.beans.InvalidationListener;
|
||||||
|
import javafx.beans.property.ObjectProperty;
|
||||||
|
import javafx.beans.property.SimpleObjectProperty;
|
||||||
|
import javafx.collections.FXCollections;
|
||||||
|
import javafx.collections.ListChangeListener;
|
||||||
|
import javafx.collections.ObservableList;
|
||||||
|
import javafx.collections.WeakListChangeListener;
|
||||||
|
import javafx.event.ActionEvent;
|
||||||
|
import javafx.scene.control.ListView;
|
||||||
|
import javafx.scene.control.TextField;
|
||||||
|
import javafx.scene.input.KeyCode;
|
||||||
|
import javafx.scene.input.KeyEvent;
|
||||||
|
import javafx.scene.input.MouseButton;
|
||||||
|
import javafx.stage.Popup;
|
||||||
|
|
||||||
|
/** A free-form field offering case-insensitive prefix matches from an observable list. */
|
||||||
|
public final class AutoCompleteTextField extends TextField {
|
||||||
|
private static final int ROW_HEIGHT = 26;
|
||||||
|
private final ObservableList<String> suggestions = FXCollections.observableArrayList();
|
||||||
|
private final ObjectProperty<ObservableList<String>> suggestionsSource =
|
||||||
|
new SimpleObjectProperty<>(this, "suggestionsSource") {
|
||||||
|
@Override public void unbind() {
|
||||||
|
if (isBound()) {
|
||||||
|
super.unbind();
|
||||||
|
set(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
private final ListChangeListener<String> contentChanged = change -> updateSuggestions();
|
||||||
|
private final WeakListChangeListener<String> weakContentChanged = new WeakListChangeListener<>(contentChanged);
|
||||||
|
private ObservableList<String> observedSuggestions;
|
||||||
|
private final ListView<String> choices = new ListView<>();
|
||||||
|
private final Popup popup = new Popup();
|
||||||
|
private boolean accepting;
|
||||||
|
|
||||||
|
public AutoCompleteTextField() {
|
||||||
|
popup.setAutoHide(true);
|
||||||
|
popup.getContent().add(choices);
|
||||||
|
choices.setFocusTraversable(false);
|
||||||
|
choices.setFixedCellSize(ROW_HEIGHT);
|
||||||
|
choices.setOnMouseClicked(event -> {
|
||||||
|
var value = choices.getSelectionModel().getSelectedItem();
|
||||||
|
if (event.getButton() == MouseButton.PRIMARY && value != null) accept(value);
|
||||||
|
});
|
||||||
|
suggestionsSource.addListener((InvalidationListener) ignored -> observeSuggestions());
|
||||||
|
textProperty().addListener((property, before, after) -> updateSuggestions());
|
||||||
|
sceneProperty().addListener((property, before, after) -> {
|
||||||
|
popup.hide();
|
||||||
|
observeSuggestions();
|
||||||
|
});
|
||||||
|
disabledProperty().addListener((property, before, disabled) -> {
|
||||||
|
if (disabled) popup.hide();
|
||||||
|
});
|
||||||
|
addEventFilter(KeyEvent.KEY_PRESSED, this::handleKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObservableList<String> getSuggestions() {
|
||||||
|
return suggestions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Optional live catalogue. Without a source the fixed FXML suggestions are used. */
|
||||||
|
public ObjectProperty<ObservableList<String>> suggestionsSourceProperty() { return suggestionsSource; }
|
||||||
|
public ObservableList<String> getSuggestionsSource() { return suggestionsSource.get(); }
|
||||||
|
public void setSuggestionsSource(ObservableList<String> value) { suggestionsSource.set(value); }
|
||||||
|
|
||||||
|
private void observeSuggestions() {
|
||||||
|
var source = getSuggestionsSource();
|
||||||
|
var next = getScene() == null ? null : source == null ? suggestions : source;
|
||||||
|
if (observedSuggestions == next) return;
|
||||||
|
if (observedSuggestions != null) observedSuggestions.removeListener(weakContentChanged);
|
||||||
|
observedSuggestions = next;
|
||||||
|
if (next != null) next.addListener(weakContentChanged);
|
||||||
|
updateSuggestions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleKey(KeyEvent event) {
|
||||||
|
var selection = choices.getSelectionModel();
|
||||||
|
if (event.getCode() == KeyCode.DOWN || event.getCode() == KeyCode.UP && popup.isShowing()) {
|
||||||
|
if (!popup.isShowing()) updateSuggestions();
|
||||||
|
if (!popup.isShowing()) return;
|
||||||
|
if (event.getCode() == KeyCode.DOWN) selection.selectNext();
|
||||||
|
else selection.selectPrevious();
|
||||||
|
choices.scrollTo(selection.getSelectedIndex());
|
||||||
|
event.consume();
|
||||||
|
} else if (popup.isShowing() && event.getCode() == KeyCode.ESCAPE) {
|
||||||
|
popup.hide();
|
||||||
|
event.consume();
|
||||||
|
} else if (popup.isShowing() && event.getCode() == KeyCode.ENTER) {
|
||||||
|
var value = selection.getSelectedItem();
|
||||||
|
popup.hide();
|
||||||
|
if (value != null) {
|
||||||
|
accept(value);
|
||||||
|
event.consume();
|
||||||
|
}
|
||||||
|
} else if (event.getCode() == KeyCode.TAB) {
|
||||||
|
popup.hide();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateSuggestions() {
|
||||||
|
if (observedSuggestions == null || accepting || !isFocused() || isDisabled() || getScene() == null
|
||||||
|
|| getScene().getWindow() == null || !getScene().getWindow().isShowing()) return;
|
||||||
|
String prefix = getText() == null ? "" : getText().strip().toLowerCase(Locale.ROOT);
|
||||||
|
var matches = prefix.isEmpty() ? java.util.List.<String>of()
|
||||||
|
: observedSuggestions.stream().filter(value -> value != null && !value.isBlank())
|
||||||
|
.filter(value -> value.toLowerCase(Locale.ROOT).startsWith(prefix)).distinct().limit(10).toList();
|
||||||
|
choices.getItems().setAll(matches);
|
||||||
|
choices.getSelectionModel().clearSelection();
|
||||||
|
if (matches.isEmpty()) {
|
||||||
|
popup.hide();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var bounds = localToScreen(getBoundsInLocal());
|
||||||
|
if (bounds == null) return;
|
||||||
|
choices.setPrefSize(Math.max(170, bounds.getWidth()), ROW_HEIGHT * matches.size() + 2);
|
||||||
|
if (!popup.isShowing()) popup.show(this, bounds.getMinX(), bounds.getMaxY());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void accept(String value) {
|
||||||
|
accepting = true;
|
||||||
|
try {
|
||||||
|
popup.hide();
|
||||||
|
setText(value);
|
||||||
|
positionCaret(value.length());
|
||||||
|
fireEvent(new ActionEvent());
|
||||||
|
} finally {
|
||||||
|
accepting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import javax.imageio.stream.MemoryCacheImageInputStream;
|
||||||
|
|
||||||
|
/** WebView does not decode WebP. Convert embedded images once per preparation, without changing the file. */
|
||||||
|
final class EmbeddedImages {
|
||||||
|
private static final Pattern WEBP = Pattern.compile("data:image/webp;base64,[A-Za-z0-9+/=]+", Pattern.CASE_INSENSITIVE);
|
||||||
|
private static final long MAX_PIXELS = 16 * 1024 * 1024;
|
||||||
|
private final Map<String, String> converted = new HashMap<>();
|
||||||
|
private int remainingBytes = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
String adapt(String value) {
|
||||||
|
if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException();
|
||||||
|
return WEBP.matcher(value).replaceAll(match -> java.util.regex.Matcher.quoteReplacement(
|
||||||
|
converted.computeIfAbsent(match.group(), this::png)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String png(String value) {
|
||||||
|
if (remainingBytes <= 0) return value;
|
||||||
|
try (var input = new MemoryCacheImageInputStream(new ByteArrayInputStream(
|
||||||
|
Base64.getDecoder().decode(value.substring(value.indexOf(',') + 1))))) {
|
||||||
|
var readers = ImageIO.getImageReaders(input);
|
||||||
|
if (!readers.hasNext()) return value;
|
||||||
|
var reader = readers.next();
|
||||||
|
try {
|
||||||
|
reader.setInput(input, true, true);
|
||||||
|
if ((long) reader.getWidth(0) * reader.getHeight(0) > MAX_PIXELS) return value;
|
||||||
|
var image = reader.read(0);
|
||||||
|
var output = new ByteArrayOutputStream();
|
||||||
|
if (!ImageIO.write(image, "png", output)) return value;
|
||||||
|
if ((long) output.size() * 4 / 3 > remainingBytes) return value;
|
||||||
|
remainingBytes -= (output.size() + 2) / 3 * 4;
|
||||||
|
return "data:image/png;base64," + Base64.getEncoder().encodeToString(output.toByteArray());
|
||||||
|
} finally { reader.dispose(); }
|
||||||
|
} catch (IOException | IllegalArgumentException invalid) { return value; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.jsoup.Jsoup;
|
||||||
|
|
||||||
|
/** Immutable prepared HTML, shareable between viewers without sharing external-image permission.
|
||||||
|
* Preparation performs no network requests and may be expensive; call it off the FX thread.
|
||||||
|
*/
|
||||||
|
@lombok.RequiredArgsConstructor(access = lombok.AccessLevel.PACKAGE)
|
||||||
|
public final class HtmlDocument {
|
||||||
|
private static final int MAX_BYTES = 32 * 1024 * 1024;
|
||||||
|
private final String offlineHtml;
|
||||||
|
private final String externalImagesHtml;
|
||||||
|
private final boolean hasExternalImages;
|
||||||
|
|
||||||
|
/** Reads at most 32 MiB, detects the saved character encoding, and never modifies the file. */
|
||||||
|
public static HtmlDocument read(Path file) throws IOException {
|
||||||
|
Objects.requireNonNull(file, "file");
|
||||||
|
try (var input = Files.newInputStream(file)) {
|
||||||
|
byte[] bytes = input.readNBytes(MAX_BYTES + 1);
|
||||||
|
if (bytes.length > MAX_BYTES) throw new IOException("HTML exceeds the 32 MiB preview limit.");
|
||||||
|
return HtmlPresentation.prepare(Jsoup.parse(new ByteArrayInputStream(bytes), null, ""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static HtmlDocument parse(String html) { return parse(html, null); }
|
||||||
|
|
||||||
|
/** An optional HTTP(S) source address resolves relative images; it is never fetched. */
|
||||||
|
public static HtmlDocument parse(String html, URI source) {
|
||||||
|
Objects.requireNonNull(html, "html");
|
||||||
|
if (source != null && httpUri(source.toString()) == null) {
|
||||||
|
throw new IllegalArgumentException("HTML source must be an HTTP(S) address.");
|
||||||
|
}
|
||||||
|
if (html.length() > MAX_BYTES || html.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) {
|
||||||
|
throw new IllegalArgumentException("HTML exceeds the 32 MiB preview limit.");
|
||||||
|
}
|
||||||
|
return HtmlPresentation.prepare(Jsoup.parse(html, source == null ? "" : source.toASCIIString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasExternalImages() { return hasExternalImages; }
|
||||||
|
String offlineHtml() { return offlineHtml; }
|
||||||
|
String externalImagesHtml() { return externalImagesHtml; }
|
||||||
|
|
||||||
|
static URI imageUri(String value, URI base) {
|
||||||
|
if (value.isBlank()) return null;
|
||||||
|
try {
|
||||||
|
URI uri = new URI(value.startsWith("//") ? "https:" + value : value);
|
||||||
|
if (!uri.isAbsolute() && base != null) uri = base.resolve(uri);
|
||||||
|
return httpUri(uri.toString());
|
||||||
|
} catch (URISyntaxException invalid) { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
static URI httpUri(String value) {
|
||||||
|
try {
|
||||||
|
URI uri = new URI(value.strip());
|
||||||
|
return uri.getHost() != null && ("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme()))
|
||||||
|
? uri : null;
|
||||||
|
} catch (URISyntaxException invalid) { return null; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import com.helger.css.decl.CSSDeclaration;
|
||||||
|
import com.helger.css.decl.CSSExpressionMemberTermURI;
|
||||||
|
import com.helger.css.decl.CSSFontFaceRule;
|
||||||
|
import com.helger.css.decl.ICSSTopLevelRule;
|
||||||
|
import com.helger.css.decl.visit.CSSVisitor;
|
||||||
|
import com.helger.css.decl.visit.DefaultCSSUrlVisitor;
|
||||||
|
import com.helger.css.reader.CSSReader;
|
||||||
|
import com.helger.css.reader.CSSReaderSettings;
|
||||||
|
import com.helger.css.reader.errorhandler.CollectingCSSParseErrorHandler;
|
||||||
|
import com.helger.css.handler.DoNothingCSSParseExceptionCallback;
|
||||||
|
import com.helger.css.writer.CSSWriter;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import org.jsoup.nodes.DataNode;
|
||||||
|
import org.jsoup.nodes.Document;
|
||||||
|
import org.jsoup.safety.Cleaner;
|
||||||
|
import org.jsoup.safety.Safelist;
|
||||||
|
|
||||||
|
/** Presentation preserves saved CSS; text indexing deliberately uses the simpler reader markup. */
|
||||||
|
final class HtmlPresentation {
|
||||||
|
private static final Safelist SAFE = Safelist.relaxed()
|
||||||
|
.addTags("div", "main", "header", "footer", "nav", "aside", "section", "article", "figure",
|
||||||
|
"figcaption", "small", "mark", "s", "style", "picture", "details", "summary", "time",
|
||||||
|
"form", "fieldset", "legend", "label", "input", "button", "select", "option")
|
||||||
|
.addAttributes(":all", "class", "id", "style", "hidden", "dir", "lang")
|
||||||
|
.addAttributes("input", "type", "value", "placeholder", "checked", "disabled")
|
||||||
|
.addAttributes("button", "type", "disabled")
|
||||||
|
.addAttributes("option", "value", "selected")
|
||||||
|
.addAttributes("style", "media", "type")
|
||||||
|
.removeAttributes("a", "href")
|
||||||
|
.addProtocols("img", "src", "data");
|
||||||
|
private static final Pattern IMAGE = Pattern.compile(
|
||||||
|
"data:image/(?:png|jpeg|gif|webp|svg\\+xml)(?:;[^,]*)?,.+", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||||
|
|
||||||
|
static HtmlDocument prepare(Document source) {
|
||||||
|
checkCancelled();
|
||||||
|
var images = new EmbeddedImages();
|
||||||
|
for (var style : source.select("style")) {
|
||||||
|
String css = images.adapt(style.data());
|
||||||
|
style.empty().appendChild(new DataNode(css));
|
||||||
|
}
|
||||||
|
for (var element : source.select("[style]")) element.attr("style", images.adapt(element.attr("style")));
|
||||||
|
var baseElement = source.selectFirst("base[href]");
|
||||||
|
URI base = HtmlDocument.httpUri(baseElement == null ? source.baseUri() : baseElement.attr("href"));
|
||||||
|
// Export inline SVG as an isolated image too, keeping page logos and icons without active SVG DOM.
|
||||||
|
for (var svg : source.select("svg").stream()
|
||||||
|
.filter(svg -> svg.parents().stream().noneMatch(parent -> parent.tagName().equals("svg"))).toList()) {
|
||||||
|
svg.attr("xmlns", "http://www.w3.org/2000/svg");
|
||||||
|
var image = new org.jsoup.nodes.Element("img");
|
||||||
|
image.attributes().addAll(svg.attributes());
|
||||||
|
image.attr("src", "data:image/svg+xml;base64," + Base64.getEncoder()
|
||||||
|
.encodeToString(svg.outerHtml().getBytes(StandardCharsets.UTF_8)));
|
||||||
|
svg.replaceWith(image);
|
||||||
|
}
|
||||||
|
source.select("script, template, noscript, iframe, object, embed, link, meta, base").remove();
|
||||||
|
// Cleaner handles the body only. Keep saved styles in their original order, ahead of body styles.
|
||||||
|
var headStyles = source.head().select("style").stream().map(style -> style.clone()).toList();
|
||||||
|
// Embedded SVG remains an image, never active inline SVG markup (SVG secure image mode).
|
||||||
|
for (var image : source.select("img[src]")) {
|
||||||
|
String value = images.adapt(image.attr("src").strip());
|
||||||
|
image.attr("src", value);
|
||||||
|
if (IMAGE.matcher(value).matches()) continue;
|
||||||
|
var remote = HtmlDocument.imageUri(value, base);
|
||||||
|
if (remote == null) image.removeAttr("src");
|
||||||
|
else image.attr("src", remote.toASCIIString());
|
||||||
|
}
|
||||||
|
var safelist = new Safelist(SAFE);
|
||||||
|
for (var element : source.getAllElements()) {
|
||||||
|
checkCancelled();
|
||||||
|
// Saved custom-element wrappers are inert with JavaScript disabled, but their CSS still matters.
|
||||||
|
if (element.tagName().contains("-")) safelist.addTags(element.tagName());
|
||||||
|
for (var attribute : element.attributes()) {
|
||||||
|
if (presentationAttribute(attribute.getKey())) safelist.addAttributes(":all", attribute.getKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var clean = new Cleaner(safelist).clean(source);
|
||||||
|
copyAttributes(source.selectFirst("html"), clean.selectFirst("html"));
|
||||||
|
copyAttributes(source.body(), clean.body());
|
||||||
|
clean.title(source.title());
|
||||||
|
for (var style : headStyles) {
|
||||||
|
var saved = clean.head().appendElement("style");
|
||||||
|
if (style.hasAttr("media")) saved.attr("media", style.attr("media"));
|
||||||
|
saved.appendChild(new DataNode(style.data()));
|
||||||
|
}
|
||||||
|
var online = render(clean.clone(), base, true);
|
||||||
|
var offline = render(clean, base, false);
|
||||||
|
return new HtmlDocument(offline.html(), online.html(), online.external());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void copyAttributes(org.jsoup.nodes.Element source, org.jsoup.nodes.Element target) {
|
||||||
|
for (String name : new String[]{"class", "id", "style", "hidden", "dir", "lang"}) {
|
||||||
|
if (source.hasAttr(name)) target.attr(name, source.attr(name));
|
||||||
|
}
|
||||||
|
for (var attribute : source.attributes()) {
|
||||||
|
if (presentationAttribute(attribute.getKey())) target.attr(attribute.getKey(), attribute.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean presentationAttribute(String name) {
|
||||||
|
return name.startsWith("data-") || name.startsWith("aria-") || name.equals("role");
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Rendered(String html, boolean external) {}
|
||||||
|
|
||||||
|
private static Rendered render(Document document, URI base, boolean externalImages) {
|
||||||
|
boolean[] external = {false};
|
||||||
|
for (var image : document.select("img[src]")) {
|
||||||
|
if (HtmlDocument.httpUri(image.attr("src")) != null) {
|
||||||
|
external[0] = true;
|
||||||
|
if (!externalImages) image.removeAttr("src");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (var style : document.select("style")) {
|
||||||
|
String saved = style.data();
|
||||||
|
style.empty().appendChild(new DataNode(css(saved, base, externalImages, external)));
|
||||||
|
}
|
||||||
|
for (var element : document.select("[style]")) {
|
||||||
|
// Parse an attribute as a rule, so URL handling is identical for both kinds of saved CSS.
|
||||||
|
String sheet = css("x{" + element.attr("style") + "}", base, externalImages, external);
|
||||||
|
int start = sheet.indexOf('{'), end = sheet.lastIndexOf('}');
|
||||||
|
element.attr("style", start >= 0 && end > start ? sheet.substring(start + 1, end) : "");
|
||||||
|
}
|
||||||
|
document.head().prependElement("meta").attr("http-equiv", "Content-Security-Policy")
|
||||||
|
.attr("content", policy(externalImages));
|
||||||
|
document.head().prependElement("meta").attr("charset", "UTF-8");
|
||||||
|
document.head().appendElement("meta").attr("name", "viewport").attr("content", "width=device-width, initial-scale=1");
|
||||||
|
document.outputSettings().prettyPrint(false);
|
||||||
|
return new Rendered("<!doctype html>" + document.outerHtml(), external[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String css(String source, URI base, boolean allowExternal, boolean[] external) {
|
||||||
|
checkCancelled();
|
||||||
|
var errors = new CollectingCSSParseErrorHandler();
|
||||||
|
var settings = new CSSReaderSettings().setCustomErrorHandler(errors)
|
||||||
|
.setCustomExceptionHandler(new DoNothingCSSParseExceptionCallback());
|
||||||
|
var sheet = CSSReader.readFromStringReader(source, settings);
|
||||||
|
// Keep unsupported author CSS: the document CSP still enforces the resource boundary.
|
||||||
|
if (sheet == null || errors.hasParseErrors()) return source;
|
||||||
|
sheet.removeAllImportRules();
|
||||||
|
CSSVisitor.visitCSSUrl(sheet, new DefaultCSSUrlVisitor() {
|
||||||
|
@Override public void onUrlDeclaration(ICSSTopLevelRule rule, CSSDeclaration declaration,
|
||||||
|
CSSExpressionMemberTermURI term) {
|
||||||
|
String value = term.getURIString();
|
||||||
|
if (value.regionMatches(true, 0, "data:", 0, 5) || value.startsWith("#")) return;
|
||||||
|
URI remote = HtmlDocument.imageUri(value, base);
|
||||||
|
boolean image = !(rule instanceof CSSFontFaceRule);
|
||||||
|
if (remote != null && image) external[0] = true;
|
||||||
|
term.setURIString(remote != null && image && allowExternal ? remote.toASCIIString() : "data:,");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// A stylesheet's escaped strings must not terminate its HTML raw-text container.
|
||||||
|
return new CSSWriter().getCSSAsString(sheet).replaceAll("(?i)</style", "<\\\\/style");
|
||||||
|
}
|
||||||
|
|
||||||
|
static String policy(boolean externalImages) {
|
||||||
|
return "default-src 'none'; img-src data:" + (externalImages ? " https: http:" : "")
|
||||||
|
+ "; style-src 'unsafe-inline'; font-src data:; script-src 'none'; frame-src 'none';"
|
||||||
|
+ " object-src 'none'; connect-src 'none'; form-action 'none'; base-uri 'none'";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void checkCancelled() {
|
||||||
|
if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
private HtmlPresentation() {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Objects;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.binding.Bindings;
|
||||||
|
import javafx.beans.property.*;
|
||||||
|
import javafx.concurrent.Task;
|
||||||
|
import javafx.concurrent.Worker;
|
||||||
|
import javafx.geometry.Insets;
|
||||||
|
import javafx.scene.control.Button;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.control.ProgressIndicator;
|
||||||
|
import javafx.scene.control.Tooltip;
|
||||||
|
import javafx.scene.layout.BorderPane;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
import javafx.scene.layout.StackPane;
|
||||||
|
import javafx.scene.web.WebView;
|
||||||
|
|
||||||
|
/** Saved HTML viewer with offline defaults, isolated SVG images and per-document image permission.
|
||||||
|
* All instance methods must be called on the FX thread. Constructing the control performs no I/O.
|
||||||
|
* Loading a replacement, clearing or closing cancels pending work and revokes permission.
|
||||||
|
*/
|
||||||
|
public final class HtmlViewer extends BorderPane implements AutoCloseable {
|
||||||
|
private final WebView browser = new WebView();
|
||||||
|
private final ReadOnlyBooleanWrapper preparing = new ReadOnlyBooleanWrapper();
|
||||||
|
private final ReadOnlyBooleanWrapper loading = new ReadOnlyBooleanWrapper(this, "loading");
|
||||||
|
private final ReadOnlyObjectWrapper<Throwable> error = new ReadOnlyObjectWrapper<>(this, "error");
|
||||||
|
private final ReadOnlyBooleanWrapper externalImagesAvailable = new ReadOnlyBooleanWrapper(this, "externalImagesAvailable");
|
||||||
|
private final ReadOnlyBooleanWrapper externalImagesAllowed = new ReadOnlyBooleanWrapper(this, "externalImagesAllowed");
|
||||||
|
private final BooleanProperty mediaButtonVisible = new SimpleBooleanProperty(this, "mediaButtonVisible", true);
|
||||||
|
private final StringProperty mediaLoadText = new SimpleStringProperty(this, "mediaLoadText", "Load external media");
|
||||||
|
private final StringProperty mediaReloadText = new SimpleStringProperty(this, "mediaReloadText", "Reload external media");
|
||||||
|
private final StringProperty mediaTooltipText = new SimpleStringProperty(this, "mediaTooltipText", "Loads external images for this viewer only and contacts their servers.");
|
||||||
|
private final StringProperty noExternalMediaText = new SimpleStringProperty(this, "noExternalMediaText", "No resolvable external image addresses found.");
|
||||||
|
private final StringProperty html = new SimpleStringProperty(this, "html");
|
||||||
|
private HtmlDocument document;
|
||||||
|
private Task<HtmlDocument> pending;
|
||||||
|
private long generation;
|
||||||
|
private boolean closed;
|
||||||
|
|
||||||
|
public HtmlViewer() {
|
||||||
|
getStyleClass().add("html-viewer");
|
||||||
|
html.addListener((observable, before, value) -> {
|
||||||
|
if (closed) return;
|
||||||
|
if (value == null || value.isBlank()) clear();
|
||||||
|
else loadHtml(value);
|
||||||
|
});
|
||||||
|
browser.setContextMenuEnabled(false);
|
||||||
|
browser.getEngine().setJavaScriptEnabled(false);
|
||||||
|
loading.bind(preparing.or(browser.getEngine().getLoadWorker().runningProperty()));
|
||||||
|
browser.getEngine().getLoadWorker().stateProperty().addListener((property, old, state) -> {
|
||||||
|
if (state == Worker.State.FAILED && !preparing.get() && !closed) {
|
||||||
|
error.set(browser.getEngine().getLoadWorker().getException());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
var media = new Button();
|
||||||
|
media.getStyleClass().add("html-viewer-media-load");
|
||||||
|
media.textProperty().bind(Bindings.when(externalImagesAllowed).then(mediaReloadText).otherwise(mediaLoadText));
|
||||||
|
media.disableProperty().bind(loading.or(externalImagesAvailable.not()));
|
||||||
|
var tooltip = new Tooltip();
|
||||||
|
tooltip.textProperty().bind(Bindings.when(externalImagesAvailable).then(mediaTooltipText).otherwise(noExternalMediaText));
|
||||||
|
media.setTooltip(tooltip);
|
||||||
|
media.setOnAction(event -> loadExternalImages());
|
||||||
|
var toolbar = new HBox(media);
|
||||||
|
toolbar.setPadding(new Insets(8, 10, 5, 10));
|
||||||
|
toolbar.visibleProperty().bind(mediaButtonVisible);
|
||||||
|
toolbar.managedProperty().bind(mediaButtonVisible);
|
||||||
|
setTop(toolbar);
|
||||||
|
var progress = new ProgressIndicator();
|
||||||
|
progress.setMaxSize(36, 36);
|
||||||
|
progress.visibleProperty().bind(loading);
|
||||||
|
progress.managedProperty().bind(loading);
|
||||||
|
var failure = new Label();
|
||||||
|
failure.setWrapText(true);
|
||||||
|
failure.textProperty().bind(error.map(problem -> Objects.toString(problem.getMessage(), problem.getClass().getSimpleName())));
|
||||||
|
failure.visibleProperty().bind(error.isNotNull());
|
||||||
|
failure.managedProperty().bind(failure.visibleProperty());
|
||||||
|
setCenter(new StackPane(browser, progress, failure));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Prepare a file on an owned virtual thread, then display it offline. */
|
||||||
|
public void load(Path file) {
|
||||||
|
Objects.requireNonNull(file, "file");
|
||||||
|
prepare(() -> HtmlDocument.read(file));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void loadHtml(String html) { loadHtml(html, null); }
|
||||||
|
|
||||||
|
/** Prepare HTML off the FX thread; source is an optional HTTP(S) base, never a URL to fetch. */
|
||||||
|
public void loadHtml(String html, URI source) {
|
||||||
|
Objects.requireNonNull(html, "html");
|
||||||
|
prepare(() -> HtmlDocument.parse(html, source));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Display an immutable document already prepared by the caller. Permission starts revoked. */
|
||||||
|
public void display(HtmlDocument value) {
|
||||||
|
requireOpen();
|
||||||
|
Objects.requireNonNull(value, "document");
|
||||||
|
clear();
|
||||||
|
show(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void show(HtmlDocument value) {
|
||||||
|
document = value;
|
||||||
|
externalImagesAvailable.set(value.hasExternalImages());
|
||||||
|
browser.getEngine().loadContent(value.offlineHtml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@FunctionalInterface private interface Preparation { HtmlDocument run() throws Exception; }
|
||||||
|
|
||||||
|
private void prepare(Preparation work) {
|
||||||
|
requireOpen();
|
||||||
|
clear();
|
||||||
|
long request = generation;
|
||||||
|
preparing.set(true);
|
||||||
|
var task = new Task<HtmlDocument>() {
|
||||||
|
@Override protected HtmlDocument call() throws Exception { return work.run(); }
|
||||||
|
};
|
||||||
|
pending = task;
|
||||||
|
task.setOnSucceeded(event -> {
|
||||||
|
if (closed || request != generation) return;
|
||||||
|
pending = null;
|
||||||
|
show(task.getValue());
|
||||||
|
preparing.set(false);
|
||||||
|
});
|
||||||
|
task.setOnFailed(event -> {
|
||||||
|
if (closed || request != generation) return;
|
||||||
|
pending = null;
|
||||||
|
error.set(task.getException());
|
||||||
|
preparing.set(false);
|
||||||
|
});
|
||||||
|
Thread.ofVirtual().name("html-viewer-prepare").start(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicitly grants HTTP(S) image requests for the currently displayed document only. */
|
||||||
|
public void loadExternalImages() {
|
||||||
|
requireOpen();
|
||||||
|
if (document == null || !externalImagesAvailable.get()) return;
|
||||||
|
error.set(null);
|
||||||
|
externalImagesAllowed.set(true);
|
||||||
|
browser.getEngine().loadContent(document.externalImagesHtml());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clear() {
|
||||||
|
requireOpen();
|
||||||
|
generation++;
|
||||||
|
if (pending != null) { pending.cancel(true); pending = null; }
|
||||||
|
preparing.set(false);
|
||||||
|
document = null;
|
||||||
|
externalImagesAvailable.set(false);
|
||||||
|
externalImagesAllowed.set(false);
|
||||||
|
error.set(null);
|
||||||
|
browser.getEngine().getLoadWorker().cancel();
|
||||||
|
browser.getEngine().load(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void close() {
|
||||||
|
requireFxThread();
|
||||||
|
if (closed) return;
|
||||||
|
html.unbind();
|
||||||
|
clear();
|
||||||
|
closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireOpen() {
|
||||||
|
requireFxThread();
|
||||||
|
if (closed) throw new IllegalStateException("HtmlViewer is closed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void requireFxThread() {
|
||||||
|
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("HtmlViewer requires the JavaFX application thread.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Local source text. Imperative display operations do not publish values to this input. */
|
||||||
|
public StringProperty htmlProperty() { return html; }
|
||||||
|
public String getHtml() { return html.get(); }
|
||||||
|
public void setHtml(String value) { requireOpen(); html.set(value); }
|
||||||
|
|
||||||
|
public ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); }
|
||||||
|
public boolean isLoading() { return loading.get(); }
|
||||||
|
public ReadOnlyObjectProperty<Throwable> errorProperty() { return error.getReadOnlyProperty(); }
|
||||||
|
public Throwable getError() { return error.get(); }
|
||||||
|
public ReadOnlyBooleanProperty externalImagesAvailableProperty() { return externalImagesAvailable.getReadOnlyProperty(); }
|
||||||
|
public boolean isExternalImagesAvailable() { return externalImagesAvailable.get(); }
|
||||||
|
public ReadOnlyBooleanProperty externalImagesAllowedProperty() { return externalImagesAllowed.getReadOnlyProperty(); }
|
||||||
|
public boolean isExternalImagesAllowed() { return externalImagesAllowed.get(); }
|
||||||
|
public BooleanProperty mediaButtonVisibleProperty() { return mediaButtonVisible; }
|
||||||
|
public boolean isMediaButtonVisible() { return mediaButtonVisible.get(); }
|
||||||
|
public void setMediaButtonVisible(boolean value) { mediaButtonVisible.set(value); }
|
||||||
|
public StringProperty mediaLoadTextProperty() { return mediaLoadText; }
|
||||||
|
public String getMediaLoadText() { return mediaLoadText.get(); }
|
||||||
|
public void setMediaLoadText(String value) { mediaLoadText.set(value); }
|
||||||
|
public StringProperty mediaReloadTextProperty() { return mediaReloadText; }
|
||||||
|
public String getMediaReloadText() { return mediaReloadText.get(); }
|
||||||
|
public void setMediaReloadText(String value) { mediaReloadText.set(value); }
|
||||||
|
public StringProperty mediaTooltipTextProperty() { return mediaTooltipText; }
|
||||||
|
public String getMediaTooltipText() { return mediaTooltipText.get(); }
|
||||||
|
public void setMediaTooltipText(String value) { mediaTooltipText.set(value); }
|
||||||
|
public StringProperty noExternalMediaTextProperty() { return noExternalMediaText; }
|
||||||
|
public String getNoExternalMediaText() { return noExternalMediaText.get(); }
|
||||||
|
public void setNoExternalMediaText(String value) { noExternalMediaText.set(value); }
|
||||||
|
}
|
||||||
@@ -18,10 +18,13 @@ public final class IntegerSpinners {
|
|||||||
* @return an editable spinner
|
* @return an editable spinner
|
||||||
*/
|
*/
|
||||||
public static Spinner<Integer> nonNegative(int min, int max, int value) {
|
public static Spinner<Integer> nonNegative(int min, int max, int value) {
|
||||||
|
return new NonNegativeIntegerSpinner(min, max, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void configure(Spinner<Integer> spinner, int min, int max, int value) {
|
||||||
if (min < 0 || max < min || value < min || value > max) {
|
if (min < 0 || max < min || value < min || value > max) {
|
||||||
throw new IllegalArgumentException("Invalid nonnegative spinner bounds or value");
|
throw new IllegalArgumentException("Invalid nonnegative spinner bounds or value");
|
||||||
}
|
}
|
||||||
Spinner<Integer> spinner = new Spinner<>(min, max, value);
|
|
||||||
spinner.setEditable(true);
|
spinner.setEditable(true);
|
||||||
spinner.getEditor().setTextFormatter(new TextFormatter<String>(change -> {
|
spinner.getEditor().setTextFormatter(new TextFormatter<String>(change -> {
|
||||||
String text = change.getControlNewText();
|
String text = change.getControlNewText();
|
||||||
@@ -46,6 +49,5 @@ public final class IntegerSpinners {
|
|||||||
spinner.getEditor().setText(spinner.getValue().toString());
|
spinner.getEditor().setText(spinner.getValue().toString());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return spinner;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import javafx.beans.NamedArg;
|
||||||
|
import javafx.beans.property.ObjectProperty;
|
||||||
|
import javafx.scene.control.Spinner;
|
||||||
|
|
||||||
|
/** Bounded integer input available directly in FXML, including immediate valid typing. */
|
||||||
|
public final class NonNegativeIntegerSpinner extends Spinner<Integer> {
|
||||||
|
public NonNegativeIntegerSpinner(
|
||||||
|
@NamedArg(value = "minimum", defaultValue = "0") int minimum,
|
||||||
|
@NamedArg(value = "maximum", defaultValue = "2147483647") int maximum,
|
||||||
|
@NamedArg(value = "initialValue", defaultValue = "0") int initialValue) {
|
||||||
|
super(minimum, maximum, initialValue);
|
||||||
|
IntegerSpinners.configure(this, minimum, maximum, initialValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writable property for DirectBinding; Spinner.valueProperty itself is read-only. */
|
||||||
|
public ObjectProperty<Integer> numberProperty() {
|
||||||
|
return getValueFactory().valueProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getNumber() {
|
||||||
|
return numberProperty().get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNumber(Integer value) {
|
||||||
|
numberProperty().set(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import javafx.scene.control.Menu;
|
||||||
|
import javafx.scene.control.MenuBar;
|
||||||
|
import javafx.scene.control.MenuItem;
|
||||||
|
import javafx.scene.control.SeparatorMenuItem;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/** Builds one window's menu bar, using the native application Quit item on macOS. */
|
||||||
|
public final class PlatformMenuBar {
|
||||||
|
private PlatformMenuBar() {}
|
||||||
|
|
||||||
|
/** Supply fresh menus and a localized quit action for each window. */
|
||||||
|
public static MenuBar create(Menu file, MenuItem quit, Menu... otherMenus) {
|
||||||
|
var bar = new MenuBar(file);
|
||||||
|
bar.getMenus().addAll(otherMenus);
|
||||||
|
if (System.getProperty("os.name").toLowerCase(Locale.ROOT).startsWith("mac")) {
|
||||||
|
bar.setUseSystemMenuBar(true);
|
||||||
|
} else {
|
||||||
|
if (!file.getItems().isEmpty()) file.getItems().add(new SeparatorMenuItem());
|
||||||
|
file.getItems().add(quit);
|
||||||
|
}
|
||||||
|
return bar;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import javafx.beans.binding.Bindings;
|
||||||
|
import javafx.beans.property.BooleanProperty;
|
||||||
|
import javafx.beans.property.SimpleBooleanProperty;
|
||||||
|
import javafx.beans.property.StringProperty;
|
||||||
|
import javafx.event.ActionEvent;
|
||||||
|
import javafx.event.EventHandler;
|
||||||
|
import javafx.geometry.Pos;
|
||||||
|
import javafx.scene.control.Button;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
|
||||||
|
/** A rounded tag label with an optional remove action. */
|
||||||
|
public final class TagChip extends HBox {
|
||||||
|
private final Label label = new Label();
|
||||||
|
private final Button remove = new Button("×");
|
||||||
|
private final BooleanProperty removable = new SimpleBooleanProperty(this, "removable");
|
||||||
|
|
||||||
|
public TagChip() {
|
||||||
|
getStyleClass().add("tag-chip");
|
||||||
|
getStylesheets().add(TagChip.class.getResource("tag-chip.css").toExternalForm());
|
||||||
|
setAlignment(Pos.CENTER_LEFT);
|
||||||
|
setSpacing(3);
|
||||||
|
remove.getStyleClass().add("tag-chip-remove");
|
||||||
|
remove.accessibleTextProperty().bind(Bindings.concat("Remove ", label.textProperty()));
|
||||||
|
remove.visibleProperty().bind(removable);
|
||||||
|
remove.managedProperty().bind(removable);
|
||||||
|
getChildren().addAll(label, remove);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TagChip(String text) {
|
||||||
|
this();
|
||||||
|
setText(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
public StringProperty textProperty() { return label.textProperty(); }
|
||||||
|
public String getText() { return label.getText(); }
|
||||||
|
public void setText(String value) { label.setText(value); }
|
||||||
|
public BooleanProperty removableProperty() { return removable; }
|
||||||
|
public boolean isRemovable() { return removable.get(); }
|
||||||
|
public void setRemovable(boolean value) { removable.set(value); }
|
||||||
|
public EventHandler<ActionEvent> getOnRemove() { return remove.getOnAction(); }
|
||||||
|
public void setOnRemove(EventHandler<ActionEvent> handler) { remove.setOnAction(handler); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import javafx.beans.DefaultProperty;
|
||||||
|
import javafx.beans.property.BooleanProperty;
|
||||||
|
import javafx.beans.property.ObjectProperty;
|
||||||
|
import javafx.beans.property.SimpleBooleanProperty;
|
||||||
|
import javafx.beans.property.SimpleObjectProperty;
|
||||||
|
import javafx.collections.ObservableList;
|
||||||
|
import javafx.event.ActionEvent;
|
||||||
|
import javafx.event.EventHandler;
|
||||||
|
import javafx.geometry.Insets;
|
||||||
|
import javafx.geometry.Pos;
|
||||||
|
import javafx.scene.Node;
|
||||||
|
import javafx.scene.control.Button;
|
||||||
|
import javafx.scene.control.ToolBar;
|
||||||
|
import javafx.scene.layout.BorderPane;
|
||||||
|
|
||||||
|
/** A horizontal JavaFX toolbar with an optional dismissal button at its leading edge. */
|
||||||
|
@DefaultProperty("items")
|
||||||
|
public final class ToolBarPane extends BorderPane {
|
||||||
|
private final ToolBar toolbar = new ToolBar();
|
||||||
|
private final Button dismiss = new Button("×");
|
||||||
|
private final BooleanProperty dismissible = new SimpleBooleanProperty(this, "dismissible");
|
||||||
|
private final ObjectProperty<EventHandler<ActionEvent>> onDismiss =
|
||||||
|
new SimpleObjectProperty<>(this, "onDismiss");
|
||||||
|
|
||||||
|
public ToolBarPane() {
|
||||||
|
getStyleClass().add("tool-bar-pane");
|
||||||
|
setCenter(toolbar);
|
||||||
|
dismiss.getStyleClass().add("tool-bar-dismiss");
|
||||||
|
dismiss.setAccessibleText("Close toolbar");
|
||||||
|
BorderPane.setAlignment(dismiss, Pos.CENTER_LEFT);
|
||||||
|
BorderPane.setMargin(dismiss, new Insets(0, 3, 0, 3));
|
||||||
|
dismiss.visibleProperty().bind(dismissible);
|
||||||
|
dismiss.managedProperty().bind(dismissible);
|
||||||
|
dismissible.addListener((property, old, enabled) -> setLeft(enabled ? dismiss : null));
|
||||||
|
dismiss.setOnAction(event -> {
|
||||||
|
setVisible(false);
|
||||||
|
var handler = getOnDismiss();
|
||||||
|
if (handler != null) handler.handle(event);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObservableList<Node> getItems() {
|
||||||
|
return toolbar.getItems();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BooleanProperty dismissibleProperty() { return dismissible; }
|
||||||
|
public boolean isDismissible() { return dismissible.get(); }
|
||||||
|
public void setDismissible(boolean value) { dismissible.set(value); }
|
||||||
|
|
||||||
|
public ObjectProperty<EventHandler<ActionEvent>> onDismissProperty() { return onDismiss; }
|
||||||
|
public EventHandler<ActionEvent> getOnDismiss() { return onDismiss.get(); }
|
||||||
|
public void setOnDismiss(EventHandler<ActionEvent> value) { onDismiss.set(value); }
|
||||||
|
|
||||||
|
public String getDismissText() { return dismiss.getAccessibleText(); }
|
||||||
|
public void setDismissText(String value) { dismiss.setAccessibleText(value); }
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package de.neitzel.fx.docking;
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
import de.neitzel.fx.i18n.Messages;
|
||||||
import java.text.MessageFormat;
|
import java.text.MessageFormat;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
@@ -12,10 +13,12 @@ final class DockMessages {
|
|||||||
private final ResourceBundle defaults = ResourceBundle.getBundle("de.neitzel.fx.docking.Docking", Locale.ROOT);
|
private final ResourceBundle defaults = ResourceBundle.getBundle("de.neitzel.fx.docking.Docking", Locale.ROOT);
|
||||||
private final Map<String, String> overrides;
|
private final Map<String, String> overrides;
|
||||||
private final Locale locale;
|
private final Locale locale;
|
||||||
|
private final Messages live;
|
||||||
|
|
||||||
DockMessages(ResourceBundle resources) {
|
DockMessages(ResourceBundle resources) {
|
||||||
Map<String, String> captured = new HashMap<>();
|
Map<String, String> captured = new HashMap<>();
|
||||||
if (resources != null) {
|
live = resources instanceof Messages messages ? messages : null;
|
||||||
|
if (resources != null && live == null) {
|
||||||
for (String key : resources.keySet()) {
|
for (String key : resources.keySet()) {
|
||||||
if (resources.getObject(key) instanceof String text) captured.put(key, text);
|
if (resources.getObject(key) instanceof String text) captured.put(key, text);
|
||||||
}
|
}
|
||||||
@@ -24,13 +27,18 @@ final class DockMessages {
|
|||||||
locale = resources == null || resources.getLocale() == null ? Locale.ROOT : resources.getLocale();
|
locale = resources == null || resources.getLocale() == null ? Locale.ROOT : resources.getLocale();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String override(String key) {
|
||||||
|
return live != null && live.defines(key) ? live.text(key) : overrides.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
String text(String key) {
|
String text(String key) {
|
||||||
if (overrides.containsKey(key)) return overrides.get(key);
|
String wording = override(key);
|
||||||
|
if (wording != null) return wording;
|
||||||
return defaults.containsKey(key) ? defaults.getString(key) : defaults.getString("dock.failure.generic");
|
return defaults.containsKey(key) ? defaults.getString(key) : defaults.getString("dock.failure.generic");
|
||||||
}
|
}
|
||||||
|
|
||||||
String format(String key, Object... values) {
|
String format(String key, Object... values) {
|
||||||
return new MessageFormat(text(key), locale).format(values);
|
return new MessageFormat(text(key), live == null ? locale : live.getLocale()).format(values);
|
||||||
}
|
}
|
||||||
|
|
||||||
String failure(DockFailure failure) {
|
String failure(DockFailure failure) {
|
||||||
@@ -38,9 +46,10 @@ final class DockMessages {
|
|||||||
String codeKey = "dock.failure." + failure.code().name();
|
String codeKey = "dock.failure." + failure.code().name();
|
||||||
String applicationKey = failure.messageKey();
|
String applicationKey = failure.messageKey();
|
||||||
if (applicationKey != null && !applicationKey.isBlank()) {
|
if (applicationKey != null && !applicationKey.isBlank()) {
|
||||||
return overrides.getOrDefault(applicationKey, text(codeKey));
|
return Objects.requireNonNullElseGet(override(applicationKey), () -> text(codeKey));
|
||||||
}
|
}
|
||||||
if (overrides.containsKey(codeKey)) return overrides.get(codeKey);
|
String wording = override(codeKey);
|
||||||
|
if (wording != null) return wording;
|
||||||
// Keep the existing direct-message API useful when no localization key was supplied.
|
// Keep the existing direct-message API useful when no localization key was supplied.
|
||||||
return failure.message() == null || failure.message().isBlank() ? text(codeKey) : failure.message();
|
return failure.message() == null || failure.message().isBlank() ? text(codeKey) : failure.message();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1350,7 +1350,18 @@ public final class DockingManager {
|
|||||||
}
|
}
|
||||||
DockPane floatingPane = new DockPane();
|
DockPane floatingPane = new DockPane();
|
||||||
Stage floatingStage = new Stage();
|
Stage floatingStage = new Stage();
|
||||||
|
if (configuration.getMenuBarFactory() == null) {
|
||||||
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
|
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
var menu = Objects.requireNonNull(configuration.getMenuBarFactory().apply(floatingStage));
|
||||||
|
var root = new javafx.scene.layout.BorderPane(floatingPane);
|
||||||
|
root.setTop(menu);
|
||||||
|
floatingStage.setScene(new javafx.scene.Scene(root));
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
throw new FloatingPreparationFailure(failure);
|
||||||
|
}
|
||||||
|
}
|
||||||
de.neitzel.fx.theme.ThemeManager.link(floatingStage, stage.getScene());
|
de.neitzel.fx.theme.ThemeManager.link(floatingStage, stage.getScene());
|
||||||
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler = event -> {
|
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler = event -> {
|
||||||
event.consume();
|
event.consume();
|
||||||
|
|||||||
@@ -1,14 +1,19 @@
|
|||||||
package de.neitzel.fx.docking;
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
import javafx.scene.control.MenuBar;
|
||||||
import javafx.scene.image.Image;
|
import javafx.scene.image.Image;
|
||||||
|
import javafx.stage.Window;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
/** Appearance supplied before a managed window appears; its Stage and Scene remain manager-owned. */
|
/** Appearance supplied before a managed window appears; its Stage and Scene remain manager-owned. */
|
||||||
public final class FloatingWindowConfiguration {
|
public final class FloatingWindowConfiguration {
|
||||||
|
/** Optional factory for a fresh menu bar. The window provides context for actions and dialogs. */
|
||||||
|
@Getter @Setter private Function<Window, MenuBar> menuBarFactory;
|
||||||
@Getter @Setter private String title = "Docking";
|
@Getter @Setter private String title = "Docking";
|
||||||
@Getter private final List<Image> icons = new ArrayList<>();
|
@Getter private final List<Image> icons = new ArrayList<>();
|
||||||
@Getter private final List<String> stylesheets = new ArrayList<>();
|
@Getter private final List<String> stylesheets = new ArrayList<>();
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package de.neitzel.fx.i18n;
|
||||||
|
|
||||||
|
import javafx.scene.control.Alert;
|
||||||
|
import javafx.scene.control.Menu;
|
||||||
|
import javafx.scene.control.RadioMenuItem;
|
||||||
|
import javafx.scene.control.ToggleGroup;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/** Language selection shared by desktop windows. Only a changed user selection shows a notice. */
|
||||||
|
public final class LanguageMenu {
|
||||||
|
public static final Localizer.Catalog CATALOG = new Localizer.Catalog(LanguageMenu.class, "NeitzelLib-fx", "de.neitzel.fx");
|
||||||
|
|
||||||
|
private LanguageMenu() {}
|
||||||
|
|
||||||
|
public static Menu create(Localizer languages, Supplier<Window> owner, Consumer<Locale> remember,
|
||||||
|
Locale... choices) {
|
||||||
|
var texts = languages.forClass(LanguageMenu.class);
|
||||||
|
var menu = new Menu();
|
||||||
|
menu.textProperty().bind(languages.localeProperty().map(locale -> texts.text("language.menu")));
|
||||||
|
var group = new ToggleGroup();
|
||||||
|
for (Locale choice : choices) {
|
||||||
|
var item = new RadioMenuItem(choice.getDisplayName(choice));
|
||||||
|
item.setToggleGroup(group);
|
||||||
|
item.setUserData(choice);
|
||||||
|
item.setOnAction(event -> {
|
||||||
|
if (choice.equals(languages.getLocale())) return;
|
||||||
|
languages.setLocale(choice);
|
||||||
|
remember.accept(choice);
|
||||||
|
var notice = new Alert(Alert.AlertType.INFORMATION, texts.text("language.reopen"));
|
||||||
|
notice.initOwner(owner.get());
|
||||||
|
notice.setTitle(texts.text("language.menu"));
|
||||||
|
notice.setHeaderText(null);
|
||||||
|
notice.show();
|
||||||
|
});
|
||||||
|
menu.getItems().add(item);
|
||||||
|
}
|
||||||
|
menu.setOnShowing(event -> {
|
||||||
|
for (var toggle : group.getToggles()) {
|
||||||
|
Locale choice = (Locale) toggle.getUserData();
|
||||||
|
toggle.setSelected(choice.getLanguage().equals(languages.getLocale().getLanguage()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return menu;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package de.neitzel.fx.i18n;
|
||||||
|
|
||||||
|
import javafx.beans.property.ReadOnlyObjectProperty;
|
||||||
|
import javafx.beans.property.ReadOnlyObjectWrapper;
|
||||||
|
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/** Application-wide language selection and ordered property catalog sources. */
|
||||||
|
public final class Localizer {
|
||||||
|
public record Catalog(Class<?> anchor, String name, String packageRoot) {
|
||||||
|
public Catalog {
|
||||||
|
Objects.requireNonNull(anchor);
|
||||||
|
Objects.requireNonNull(packageRoot);
|
||||||
|
if (!name.matches("[\\w.-]+")) throw new IllegalArgumentException("Invalid catalog name: " + name);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Catalog(Class<?> anchor, String name) {
|
||||||
|
this(anchor, name, anchor.getPackageName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
record Family(Class<?> anchor, String path, URL siblingOf) {}
|
||||||
|
private record Missing(List<Family> context, Locale locale, String key) {}
|
||||||
|
private final Set<Missing> missing = ConcurrentHashMap.newKeySet();
|
||||||
|
private final ReadOnlyObjectWrapper<Locale> locale;
|
||||||
|
final Locale fallback;
|
||||||
|
private final List<Catalog> catalogs;
|
||||||
|
|
||||||
|
public Localizer(Locale initial, Locale fallback, Catalog application, Catalog... libraries) {
|
||||||
|
this.locale = new ReadOnlyObjectWrapper<>(initial == null ? Locale.getDefault(Locale.Category.DISPLAY) : initial);
|
||||||
|
this.fallback = Objects.requireNonNull(fallback);
|
||||||
|
var sources = new ArrayList<Catalog>();
|
||||||
|
sources.add(Objects.requireNonNull(application));
|
||||||
|
sources.addAll(List.of(libraries));
|
||||||
|
this.catalogs = List.copyOf(sources);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Locale getLocale() { return locale.get(); }
|
||||||
|
public ReadOnlyObjectProperty<Locale> localeProperty() { return locale.getReadOnlyProperty(); }
|
||||||
|
|
||||||
|
/** Set on the JavaFX thread when controls observe this property. */
|
||||||
|
public void setLocale(Locale value) {
|
||||||
|
if (!getLocale().equals(Objects.requireNonNull(value))) locale.set(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Messages forClass(Class<?> type) { return forView(null, type); }
|
||||||
|
|
||||||
|
public Messages forView(URL fxml, Class<?> controller) {
|
||||||
|
var families = new LinkedHashSet<Family>();
|
||||||
|
Class<?> anchor = controller == null ? catalogs.getFirst().anchor() : controller;
|
||||||
|
if (fxml != null) {
|
||||||
|
String path = fxml.getPath();
|
||||||
|
String file = path.substring(path.lastIndexOf('/') + 1);
|
||||||
|
families.add(new Family(anchor, file.replaceFirst("\\.fxml$", ""), fxml));
|
||||||
|
}
|
||||||
|
if (controller != null) families.add(new Family(controller, controller.getSimpleName(), null));
|
||||||
|
String pkg = anchor.getPackageName();
|
||||||
|
String root = catalogs.stream().map(Catalog::packageRoot)
|
||||||
|
.filter(p -> pkg.equals(p) || pkg.startsWith(p + "."))
|
||||||
|
.max(java.util.Comparator.comparingInt(String::length)).orElse(pkg);
|
||||||
|
if (fxml != null) {
|
||||||
|
String directory = fxml.getPath().substring(0, fxml.getPath().lastIndexOf('/') + 1);
|
||||||
|
catalogs.stream().filter(c -> !c.packageRoot().isEmpty()
|
||||||
|
&& directory.contains("/" + c.packageRoot().replace('.', '/') + "/"))
|
||||||
|
.max(java.util.Comparator.comparingInt(c -> c.packageRoot().length()))
|
||||||
|
.ifPresent(source -> {
|
||||||
|
String prefix = "/" + source.packageRoot().replace('.', '/') + "/";
|
||||||
|
String path = directory.substring(directory.lastIndexOf(prefix), directory.length() - 1);
|
||||||
|
addPackages(families, source.anchor(), path, source.packageRoot());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
addPackages(families, anchor, "/" + pkg.replace('.', '/'), root);
|
||||||
|
for (Catalog catalog : catalogs) families.add(new Family(catalog.anchor(), "/" + catalog.name(), null));
|
||||||
|
return new Messages(this, List.copyOf(families));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addPackages(Set<Family> result, Class<?> anchor, String path, String root) {
|
||||||
|
String boundary = "/" + root.replace('.', '/');
|
||||||
|
while (path.length() > 1) {
|
||||||
|
result.add(new Family(anchor, path + "/Messages", null));
|
||||||
|
if (path.equals(boundary)) break;
|
||||||
|
path = path.substring(0, path.lastIndexOf('/'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void reportMissing(List<Family> context, Locale language, String key) {
|
||||||
|
if (missing.add(new Missing(context, language, key))) {
|
||||||
|
System.getLogger(Localizer.class.getName()).log(System.Logger.Level.WARNING,
|
||||||
|
"Missing translation {0} for {1} in {2}", key, language, context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package de.neitzel.fx.i18n;
|
||||||
|
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.ResourceBundle;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/** A live ResourceBundle for FXML, controller injection and immediate Java lookups. */
|
||||||
|
public final class Messages extends ResourceBundle {
|
||||||
|
private static final Control RULES = Control.getControl(Control.FORMAT_PROPERTIES);
|
||||||
|
private final Localizer localizer;
|
||||||
|
private final List<Localizer.Family> families;
|
||||||
|
private Locale loaded;
|
||||||
|
private Map<String,String> entries;
|
||||||
|
|
||||||
|
Messages(Localizer localizer, List<Localizer.Family> families) {
|
||||||
|
this.localizer = localizer;
|
||||||
|
this.families = families;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opt-in live label for JavaFX property binding. */
|
||||||
|
public javafx.beans.value.ObservableValue<String> observable(String key) {
|
||||||
|
return localizer.localeProperty().map(locale -> text(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String text(String key, Object... arguments) {
|
||||||
|
String pattern = getString(key);
|
||||||
|
return arguments.length == 0 ? pattern : new MessageFormat(pattern, getLocale()).format(arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Localizer localizer() { return localizer; }
|
||||||
|
@Override public Locale getLocale() { return localizer.getLocale(); }
|
||||||
|
|
||||||
|
@Override protected Object handleGetObject(String key) {
|
||||||
|
String value = values().get(Objects.requireNonNull(key));
|
||||||
|
if (value != null) return value;
|
||||||
|
localizer.reportMissing(families, getLocale(), key);
|
||||||
|
return "⟦" + key + "⟧";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** FXMLLoader checks containsKey before getString. Every key has a visible fallback. */
|
||||||
|
@Override public boolean containsKey(String key) { Objects.requireNonNull(key); return true; }
|
||||||
|
public boolean defines(String key) { return values().containsKey(key); }
|
||||||
|
@Override public Enumeration<String> getKeys() { return Collections.enumeration(values().keySet()); }
|
||||||
|
@Override protected Set<String> handleKeySet() { return values().keySet(); }
|
||||||
|
|
||||||
|
private synchronized Map<String,String> values() {
|
||||||
|
Locale current = getLocale();
|
||||||
|
if (current.equals(loaded)) return entries;
|
||||||
|
var languages = new LinkedHashSet<>(RULES.getCandidateLocales("", current));
|
||||||
|
languages.addAll(RULES.getCandidateLocales("", localizer.fallback));
|
||||||
|
languages.remove(Locale.ROOT);
|
||||||
|
languages.add(Locale.ROOT);
|
||||||
|
var result = new HashMap<String,String>();
|
||||||
|
for (Locale language : languages) {
|
||||||
|
for (var family : families) read(family, language, result);
|
||||||
|
}
|
||||||
|
entries = Map.copyOf(result);
|
||||||
|
loaded = current;
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void read(Localizer.Family family, Locale locale, Map<String,String> result) {
|
||||||
|
String file = RULES.toBundleName(family.path(), locale) + ".properties";
|
||||||
|
try {
|
||||||
|
var url = family.siblingOf() == null ? family.anchor().getResource(file)
|
||||||
|
: new java.net.URL(family.siblingOf(), file);
|
||||||
|
if (url == null) return;
|
||||||
|
try (var reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) {
|
||||||
|
var properties = new Properties();
|
||||||
|
properties.load(reader);
|
||||||
|
for (var key : properties.stringPropertyNames()) result.putIfAbsent(key, properties.getProperty(key));
|
||||||
|
}
|
||||||
|
} catch (FileNotFoundException missingSibling) {
|
||||||
|
// A locale or layer may have no properties file.
|
||||||
|
} catch (IOException problem) {
|
||||||
|
throw new UncheckedIOException("Cannot read catalog " + file, problem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ import java.util.Map;
|
|||||||
* The list of binding elements declared inside {@code fx:define}.
|
* The list of binding elements declared inside {@code fx:define}.
|
||||||
* <p>
|
* <p>
|
||||||
* The list is not a scene-graph child. FXML adds each {@link DirectBinding},
|
* 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")
|
@DefaultProperty("elements")
|
||||||
public class BindingList {
|
public class BindingList {
|
||||||
@@ -42,14 +42,16 @@ public class BindingList {
|
|||||||
* @param context the container that creates a named Converter
|
* @param context the container that creates a named Converter
|
||||||
*/
|
*/
|
||||||
void apply(Map<String, Object> namespace, Object viewModel, Object controller, Parent root,
|
void apply(Map<String, Object> namespace, Object viewModel, Object controller, Parent root,
|
||||||
ApplicationContext context) {
|
ApplicationContext context, ViewLifetime lifetime) {
|
||||||
for (Object element : elements) {
|
for (Object element : elements) {
|
||||||
if (element instanceof DirectBinding directBinding) {
|
if (element instanceof DirectBinding directBinding) {
|
||||||
DirectBindingApplier.apply(namespace, viewModel, directBinding, context);
|
DirectBindingApplier.apply(namespace, viewModel, directBinding, context, lifetime);
|
||||||
} else if (element instanceof ComputedBinding computedBinding) {
|
} 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) {
|
} else if (element instanceof Repeat repeat) {
|
||||||
RepeatApplier.apply(namespace, viewModel, repeat, context);
|
RepeatApplier.apply(namespace, viewModel, repeat, context, lifetime);
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalArgumentException("Not a binding element: " + element);
|
throw new IllegalArgumentException("Not a binding element: " + element);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
import javafx.beans.value.ObservableBooleanValue;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One action with a live availability rule. Use the command and its availability on the
|
||||||
|
* JavaFX application thread.
|
||||||
|
*/
|
||||||
|
public final class Command {
|
||||||
|
|
||||||
|
/** The availability observed by each control displaying this command. */
|
||||||
|
@Getter
|
||||||
|
private final ObservableBooleanValue canExecute;
|
||||||
|
|
||||||
|
private final Runnable action;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a command for one action and execution context.
|
||||||
|
*
|
||||||
|
* @param canExecute live availability of the action
|
||||||
|
* @param action the work to start while the command is available
|
||||||
|
*/
|
||||||
|
public Command(ObservableBooleanValue canExecute, Runnable action) {
|
||||||
|
this.canExecute = Objects.requireNonNull(canExecute);
|
||||||
|
this.action = Objects.requireNonNull(action);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes the action after checking the current availability, including for keyboard
|
||||||
|
* shortcuts or callers without an attached control.
|
||||||
|
*/
|
||||||
|
public void execute() {
|
||||||
|
if (canExecute.get()) {
|
||||||
|
action.run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
/** Connects an FXML button or menu item to a command supplied by its ViewModel. */
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public final class CommandBinding {
|
||||||
|
|
||||||
|
/** The target control's {@code fx:id}. */
|
||||||
|
private String control;
|
||||||
|
|
||||||
|
/** The simple bean property name of the command on the ViewModel. */
|
||||||
|
private String path;
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.IdentityHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import javafx.fxml.FXMLLoader;
|
||||||
|
import javafx.scene.control.ButtonBase;
|
||||||
|
import javafx.scene.control.MenuItem;
|
||||||
|
|
||||||
|
final class CommandBindingApplier {
|
||||||
|
|
||||||
|
private CommandBindingApplier() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static void validate(List<BindingList> lists, Map<String, Object> namespace) {
|
||||||
|
var commands = new IdentityHashMap<Object, CommandBinding>();
|
||||||
|
var propertyBindings = new ArrayList<Object>();
|
||||||
|
for (BindingList list : lists) {
|
||||||
|
for (Object element : list.getElements()) {
|
||||||
|
if (element instanceof CommandBinding binding) {
|
||||||
|
Object control = target(namespace, binding);
|
||||||
|
if (commands.put(control, binding) != null) {
|
||||||
|
throw invalid(namespace, binding, "duplicate owner for disable and onAction");
|
||||||
|
}
|
||||||
|
} else if (element instanceof DirectBinding binding) {
|
||||||
|
addConflict(propertyBindings, namespace, binding.getControl(), binding.getProperty());
|
||||||
|
} else if (element instanceof ComputedBinding binding) {
|
||||||
|
addConflict(propertyBindings, namespace, binding.getControl(), binding.getProperty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (Object control : propertyBindings) {
|
||||||
|
CommandBinding command = commands.get(control);
|
||||||
|
if (command != null) {
|
||||||
|
throw invalid(namespace, command, "another binding owns disable or onAction");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addConflict(List<Object> targets, Map<String, Object> namespace,
|
||||||
|
String control, String property) {
|
||||||
|
if ("disable".equals(property) || "onAction".equals(property)) {
|
||||||
|
targets.add(namespace.get(control));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void apply(Map<String, Object> namespace, Object viewModel, CommandBinding binding,
|
||||||
|
ViewLifetime lifetime) {
|
||||||
|
if (!lifetime.managed()) {
|
||||||
|
throw invalid(namespace, binding, "CommandBinding requires a ViewModelContext");
|
||||||
|
}
|
||||||
|
var target = target(namespace, binding);
|
||||||
|
var command = command(namespace, binding, viewModel);
|
||||||
|
try {
|
||||||
|
var registration = target instanceof ButtonBase button
|
||||||
|
? CommandBindings.bind(button, command) : CommandBindings.bind((MenuItem) target, command);
|
||||||
|
lifetime.own(registration::close);
|
||||||
|
} catch (IllegalArgumentException failure) {
|
||||||
|
throw invalid(namespace, binding, failure.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object target(Map<String, Object> namespace, CommandBinding binding) {
|
||||||
|
var target = namespace.get(binding.getControl());
|
||||||
|
if (target == null) {
|
||||||
|
throw invalid(namespace, binding, "unknown target fx:id");
|
||||||
|
}
|
||||||
|
if (!(target instanceof ButtonBase) && !(target instanceof MenuItem)) {
|
||||||
|
throw invalid(namespace, binding, "target must be a ButtonBase or MenuItem");
|
||||||
|
}
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Command command(Map<String, Object> namespace, CommandBinding binding, Object viewModel) {
|
||||||
|
var path = binding.getPath();
|
||||||
|
if (path == null || path.isBlank() || path.contains(".")) {
|
||||||
|
throw invalid(namespace, binding, "expected a simple command path");
|
||||||
|
}
|
||||||
|
var getter = "get" + Character.toUpperCase(path.charAt(0)) + path.substring(1);
|
||||||
|
try {
|
||||||
|
var value = viewModel.getClass().getMethod(getter).invoke(viewModel);
|
||||||
|
if (value instanceof Command command) {
|
||||||
|
return command;
|
||||||
|
}
|
||||||
|
throw invalid(namespace, binding, getter + "() must return a Command instance");
|
||||||
|
} catch (NoSuchMethodException | IllegalAccessException failure) {
|
||||||
|
throw invalid(namespace, binding, "missing accessible command getter " + getter + "()");
|
||||||
|
} catch (InvocationTargetException failure) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
invalid(namespace, binding, "command getter " + getter + "() failed").getMessage(),
|
||||||
|
failure.getCause());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IllegalArgumentException invalid(Map<String, Object> namespace, CommandBinding binding,
|
||||||
|
String reason) {
|
||||||
|
return new IllegalArgumentException("Invalid CommandBinding in " + namespace.get(FXMLLoader.LOCATION_KEY)
|
||||||
|
+ " for " + binding.getControl() + " (disable/onAction), path " + binding.getPath() + ": " + reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import javafx.beans.property.BooleanProperty;
|
||||||
|
import javafx.beans.property.ObjectProperty;
|
||||||
|
import javafx.beans.value.ChangeListener;
|
||||||
|
import javafx.event.ActionEvent;
|
||||||
|
import javafx.event.EventHandler;
|
||||||
|
import javafx.scene.control.ButtonBase;
|
||||||
|
import javafx.scene.control.MenuItem;
|
||||||
|
|
||||||
|
/** Attaches reusable commands to JavaFX action controls. */
|
||||||
|
public final class CommandBindings {
|
||||||
|
|
||||||
|
private static final Object REGISTRATION_KEY = new Object();
|
||||||
|
|
||||||
|
private CommandBindings() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A single control's attachment to a command. Close on the JavaFX application thread. */
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface Registration extends AutoCloseable {
|
||||||
|
/** Removes this attachment. Subsequent calls have no effect. */
|
||||||
|
@Override
|
||||||
|
void close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attaches the command to a button's action and disable properties.
|
||||||
|
*
|
||||||
|
* @param button the action control
|
||||||
|
* @param command the command to execute
|
||||||
|
* @return the attachment to close when the control is no longer in use
|
||||||
|
*/
|
||||||
|
public static Registration bind(ButtonBase button, Command command) {
|
||||||
|
return attach(button.getProperties(), button.disableProperty(), button.onActionProperty(), command);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attaches the command to a menu item's action and disable properties.
|
||||||
|
*
|
||||||
|
* @param item the menu action
|
||||||
|
* @param command the command to execute
|
||||||
|
* @return the attachment to close when the menu item is no longer in use
|
||||||
|
*/
|
||||||
|
public static Registration bind(MenuItem item, Command command) {
|
||||||
|
return attach(item.getProperties(), item.disableProperty(), item.onActionProperty(), command);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Registration attach(Map<Object, Object> properties, BooleanProperty disable,
|
||||||
|
ObjectProperty<EventHandler<ActionEvent>> onAction, Command command) {
|
||||||
|
Objects.requireNonNull(command);
|
||||||
|
if (properties.containsKey(REGISTRATION_KEY) || disable.isBound()) {
|
||||||
|
throw new IllegalArgumentException("disable is already bound");
|
||||||
|
}
|
||||||
|
if (onAction.isBound() || onAction.get() != null) {
|
||||||
|
throw new IllegalArgumentException("onAction already has an owner");
|
||||||
|
}
|
||||||
|
var available = command.getCanExecute();
|
||||||
|
ChangeListener<Boolean> update = (observable, before, after) -> disable.set(!after);
|
||||||
|
EventHandler<ActionEvent> handler = event -> command.execute();
|
||||||
|
disable.set(!available.get());
|
||||||
|
onAction.set(handler);
|
||||||
|
available.addListener(update);
|
||||||
|
properties.put(REGISTRATION_KEY, handler);
|
||||||
|
return () -> {
|
||||||
|
if (properties.remove(REGISTRATION_KEY, handler)) {
|
||||||
|
available.removeListener(update);
|
||||||
|
if (onAction.get() == handler && !onAction.isBound()) {
|
||||||
|
onAction.set(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import java.util.Map;
|
|||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import javafx.beans.property.Property;
|
import javafx.beans.property.Property;
|
||||||
import javafx.fxml.FXMLLoader;
|
import javafx.fxml.FXMLLoader;
|
||||||
|
import javafx.scene.Node;
|
||||||
import javafx.scene.Parent;
|
import javafx.scene.Parent;
|
||||||
import javafx.util.Builder;
|
import javafx.util.Builder;
|
||||||
import lombok.AccessLevel;
|
import lombok.AccessLevel;
|
||||||
@@ -51,20 +52,20 @@ final class Components {
|
|||||||
* @param context the container that creates Components
|
* @param context the container that creates Components
|
||||||
* @return a builder for a Component, or {@code null} when the type is not a Component
|
* @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;
|
Object component;
|
||||||
try {
|
try {
|
||||||
component = context.getComponent(type.asSubclass(Object.class));
|
component = owner.managed() ? context.createComponent(type) : context.getComponent(type);
|
||||||
} catch (IllegalArgumentException notAComponent) {
|
} catch (IllegalArgumentException notAComponent) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (component.getClass() != type) {
|
if (component.getClass() != type) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (!LoadSession.claimFirst(type)) {
|
if (!owner.managed() && !LoadSession.claimFirst(type)) {
|
||||||
component = context.createComponent(type.asSubclass(Object.class));
|
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;
|
private final Object component;
|
||||||
/** The context used to load its document. */
|
/** The context used to load its document. */
|
||||||
private final ApplicationContext context;
|
private final ApplicationContext context;
|
||||||
|
private final ViewLifetime lifetime;
|
||||||
/** Values already resolved by the containing FXMLLoader. */
|
/** Values already resolved by the containing FXMLLoader. */
|
||||||
private final Map<String, Object> values = new LinkedHashMap<>();
|
private final Map<String, Object> values = new LinkedHashMap<>();
|
||||||
|
|
||||||
@@ -106,7 +108,7 @@ final class Components {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Object build() {
|
public Object build() {
|
||||||
Object result = load(component, context);
|
Object result = load(component, context, lifetime);
|
||||||
if (!values.isEmpty()) {
|
if (!values.isEmpty()) {
|
||||||
// A second fx:root load uses the public FXMLLoader API for bean setters,
|
// A second fx:root load uses the public FXMLLoader API for bean setters,
|
||||||
// enum/numeric coercion and diagnostics, without depending on BeanAdapter
|
// 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
|
* @param context the container that creates the instance and its dependencies
|
||||||
* @return the loaded Component
|
* @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));
|
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 component the Component
|
||||||
* @param model the Model instance
|
* @param model the Model instance
|
||||||
*/
|
*/
|
||||||
static void setModel(Object component, Object model) {
|
static void setModel(Object component, Object model, ViewLifetime lifetime) {
|
||||||
|
if (!lifetime.managed()) {
|
||||||
modelProperty(component).setValue(model);
|
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
|
* @param context the container that creates nested Components
|
||||||
* @return the loaded Component
|
* @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();
|
Class<?> type = component.getClass();
|
||||||
String document = type.getSimpleName() + ".fxml";
|
String document = type.getSimpleName() + ".fxml";
|
||||||
URL fxml = type.getResource(document);
|
URL fxml = type.getResource(document);
|
||||||
@@ -178,12 +191,19 @@ final class Components {
|
|||||||
}
|
}
|
||||||
LoadSession nested = LoadSession.nest();
|
LoadSession nested = LoadSession.nest();
|
||||||
try {
|
try {
|
||||||
FXMLLoader loader = new FXMLLoader(fxml);
|
FXMLLoader loader = new FXMLLoader(fxml, ViewLoader.resources(context, fxml, type));
|
||||||
|
FxmlHandlers.observe(loader, lifetime);
|
||||||
loader.setRoot(component);
|
loader.setRoot(component);
|
||||||
loader.setController(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();
|
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;
|
return component;
|
||||||
} catch (IOException failure) {
|
} catch (IOException failure) {
|
||||||
throw new IllegalStateException("Could not load component " + fxml, 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
|
* @param context the container that creates a named Converter
|
||||||
*/
|
*/
|
||||||
private static void watchModel(Object component, List<BindingList> lists, Map<String, Object> namespace,
|
private static void watchModel(Object component, List<BindingList> lists, Map<String, Object> namespace,
|
||||||
ApplicationContext context) {
|
ApplicationContext context, ViewLifetime lifetime) {
|
||||||
Property<Object> model = modelProperty(component);
|
Property<Object> model = modelProperty(component);
|
||||||
boolean[] applied = {false};
|
boolean[] applied = {false};
|
||||||
model.addListener((observable, oldValue, newValue) -> {
|
lifetime.listen(model, (observable, oldValue, newValue) -> {
|
||||||
if (newValue == null || applied[0]) {
|
if (newValue == null || applied[0]) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
applied[0] = true;
|
applied[0] = true;
|
||||||
Object viewModel = ViewModels.of(newValue, ViewModels.namedOn(component.getClass()));
|
try {
|
||||||
|
Object viewModel = ViewModels.of(lifetime.models(), newValue, ViewModels.namedOn(component.getClass()));
|
||||||
if (component instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) {
|
if (component instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) {
|
||||||
hasViewModel.setViewModel(bound);
|
hasViewModel.setViewModel(bound);
|
||||||
}
|
}
|
||||||
Parent root = (Parent) component;
|
Parent root = (Parent) component;
|
||||||
|
CommandBindingApplier.validate(lists, namespace);
|
||||||
for (BindingList list : lists) {
|
for (BindingList list : lists) {
|
||||||
list.apply(namespace, viewModel, component, root, context);
|
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.
|
* Returns the Component's {@code model} property.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ final class ComputedBindingApplier {
|
|||||||
Object viewModel,
|
Object viewModel,
|
||||||
Object controller,
|
Object controller,
|
||||||
Parent root,
|
Parent root,
|
||||||
ComputedBinding binding) {
|
ComputedBinding binding, ViewLifetime lifetime) {
|
||||||
Object control = namespace.get(binding.getControl());
|
Object control = namespace.get(binding.getControl());
|
||||||
if (control == null) {
|
if (control == null) {
|
||||||
throw new IllegalArgumentException("No control \"" + binding.getControl() + "\"");
|
throw new IllegalArgumentException("No control \"" + binding.getControl() + "\"");
|
||||||
@@ -49,9 +49,9 @@ final class ComputedBindingApplier {
|
|||||||
Property<Object> target = controlProperty(control, binding.getProperty());
|
Property<Object> target = controlProperty(control, binding.getProperty());
|
||||||
Runnable refresh = refresh(controller, binding.getMethod(), target);
|
Runnable refresh = refresh(controller, binding.getMethod(), target);
|
||||||
refresh.run();
|
refresh.run();
|
||||||
watchControls(root, target, refresh);
|
watchNode(root, target, refresh, lifetime);
|
||||||
if (viewModel instanceof ViewModel model) {
|
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.
|
* 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 target the property the method writes, which is not watched
|
||||||
* @param refresh the refresh to run when a watched property changes
|
* @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) {
|
if (node instanceof Control control) {
|
||||||
watchProperties(control, target, refresh);
|
watchProperties(control, target, refresh, lifetime);
|
||||||
}
|
}
|
||||||
if (node instanceof Parent parent) {
|
if (node instanceof Parent parent) {
|
||||||
for (Node child : parent.getChildrenUnmodifiable()) {
|
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
|
* @param refresh the refresh to run when a watched property changes
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@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<Object> listener = (observable, oldValue, newValue) -> refresh.run();
|
ChangeListener<Object> listener = (observable, oldValue, newValue) -> refresh.run();
|
||||||
for (Method method : bean.getClass().getMethods()) {
|
for (Method method : bean.getClass().getMethods()) {
|
||||||
if (method.getParameterCount() != 0 || !method.getName().endsWith("Property")) {
|
if (method.getParameterCount() != 0 || !method.getName().endsWith("Property")) {
|
||||||
@@ -128,7 +117,7 @@ final class ComputedBindingApplier {
|
|||||||
}
|
}
|
||||||
Object value = readProperty(bean, method);
|
Object value = readProperty(bean, method);
|
||||||
if (value instanceof ObservableValue<?> observable && observable != target) {
|
if (value instanceof ObservableValue<?> observable && observable != target) {
|
||||||
((ObservableValue<Object>) observable).addListener(listener);
|
lifetime.listen((ObservableValue<Object>) observable, listener);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,12 @@ import de.neitzel.fx.grid.filter.*;
|
|||||||
import de.neitzel.grid.*;
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.DefaultProperty;
|
||||||
import javafx.beans.property.*;
|
import javafx.beans.property.*;
|
||||||
|
import javafx.collections.*;
|
||||||
import javafx.scene.control.*;
|
import javafx.scene.control.*;
|
||||||
import javafx.scene.layout.*;
|
import javafx.scene.layout.*;
|
||||||
|
import javafx.scene.shape.SVGPath;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
@@ -18,22 +21,23 @@ import java.util.function.*;
|
|||||||
* load. The application owns the source and executor. Closing releases only this grid's requests
|
* load. The application owns the source and executor. Closing releases only this grid's requests
|
||||||
* and rows.
|
* and rows.
|
||||||
*/
|
*/
|
||||||
|
@DefaultProperty("columns")
|
||||||
public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
||||||
private final Table table = new Table();
|
private final Table table = new Table();
|
||||||
private final TableResults<K, T> renderer;
|
private TableResults<K, T> renderer;
|
||||||
private final GridCoordinator<K, T> coordinator;
|
private GridCoordinator<K, T> coordinator;
|
||||||
private final ReadOnlyObjectWrapper<GridCoordinator.State<K, T>> state =
|
private final ReadOnlyObjectWrapper<GridCoordinator.State<K, T>> state =
|
||||||
new ReadOnlyObjectWrapper<>();
|
new ReadOnlyObjectWrapper<>();
|
||||||
private final Label status = new Label("Not loaded");
|
private final Label status = new Label("Not loaded");
|
||||||
private final Button first = new Button("First"),
|
private final Button first = pagingButton("First page", "M0 0 H2 V14 H0 Z M4 7 L16 0 V14 Z"),
|
||||||
previous = new Button("Previous"),
|
previous = pagingButton("Previous page", "M2 7 L14 0 V14 Z"),
|
||||||
next = new Button("Next"),
|
next = pagingButton("Next page", "M2 0 L14 7 L2 14 Z"),
|
||||||
last = new Button("Last"),
|
last = pagingButton("Last page", "M0 0 L12 7 L0 14 Z M14 0 H16 V14 H14 Z"),
|
||||||
retry = new Button("Retry"),
|
retry = actionButton("Retry", "M2 8 A6 6 0 1 1 5 13 M2 3 V8 H7"),
|
||||||
refresh = new Button("Refresh");
|
refresh = actionButton("Refresh", "M14 7 A6 6 0 1 0 13 11 M14 2 V7 H9");
|
||||||
private final ComboBox<String> pageSize = new ComboBox<>();
|
private final ComboBox<String> pageSize = new ComboBox<>();
|
||||||
private final GridQuery initial;
|
private GridQuery initial;
|
||||||
private final List<ResultColumn> columnDefinitions;
|
private List<ResultColumn> columnDefinitions;
|
||||||
private GridDefinition setupDefinition;
|
private GridDefinition setupDefinition;
|
||||||
private Map<Integer, java.util.function.UnaryOperator<GridSetup>> setupMigrations = Map.of();
|
private Map<Integer, java.util.function.UnaryOperator<GridSetup>> setupMigrations = Map.of();
|
||||||
private final ReadOnlyObjectWrapper<List<String>> restorationAdjustments =
|
private final ReadOnlyObjectWrapper<List<String>> restorationAdjustments =
|
||||||
@@ -50,11 +54,226 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
private Alert pendingAlert;
|
private Alert pendingAlert;
|
||||||
private long alertGeneration;
|
private long alertGeneration;
|
||||||
|
|
||||||
|
private final HBox groupingBar = new HBox(8);
|
||||||
|
private final HBox filterSummary = new HBox(8);
|
||||||
|
private final Label activeFilters = new Label();
|
||||||
|
private final Label interactionStatus = new Label();
|
||||||
|
private final MenuButton setupMenu = new MenuButton("Grid setup");
|
||||||
|
private final MenuButton columnMenu = new MenuButton();
|
||||||
|
private final ReadOnlyLongWrapper columnVisibilityRevision = new ReadOnlyLongWrapper();
|
||||||
|
private final ReadOnlyLongWrapper committedRevision = new ReadOnlyLongWrapper();
|
||||||
|
private List<String> defaultGrouping = List.of();
|
||||||
|
private GridSetup developerDefaults;
|
||||||
|
private boolean hasPublished, restoredPublication;
|
||||||
|
private GridQuery lastPublishedQuery;
|
||||||
|
private long restoreSerial, lastRestoredSerial;
|
||||||
|
private GridPersistenceAttachment<K, T> attachment;
|
||||||
|
private GridColumnSettings<K, T> columnSettings;
|
||||||
|
|
||||||
|
private static Button actionButton(String description, String path) {
|
||||||
|
var button = new Button();
|
||||||
|
de.neitzel.fx.control.ActionIcon.install(button, description, path);
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Button pagingButton(String name, String path) {
|
||||||
|
var button = new Button();
|
||||||
|
var icon = new SVGPath();
|
||||||
|
icon.setContent(path);
|
||||||
|
icon.fillProperty().bind(button.textFillProperty());
|
||||||
|
var graphic = new StackPane(icon);
|
||||||
|
graphic.setMinSize(18, 16);
|
||||||
|
graphic.setPrefSize(18, 16);
|
||||||
|
graphic.setMaxSize(18, 16);
|
||||||
|
graphic.setMouseTransparent(true);
|
||||||
|
button.setGraphic(graphic);
|
||||||
|
button.setMinSize(36, 30);
|
||||||
|
button.setAccessibleText(name);
|
||||||
|
button.setTooltip(new Tooltip(name));
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<>(
|
||||||
|
FXCollections.emptyObservableList());
|
||||||
|
private final ReadOnlyListWrapper<T> selectedElements = new ReadOnlyListWrapper<>(
|
||||||
|
FXCollections.emptyObservableList());
|
||||||
|
private final ObjectProperty<RowSelectionMode> selectionMode =
|
||||||
|
new SimpleObjectProperty<>(this, "selectionMode", RowSelectionMode.SINGLE) {
|
||||||
|
@Override public void set(RowSelectionMode value) {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
super.set(Objects.requireNonNull(value));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Creates a query-free FXML control. Columns are visible before a source is attached. */
|
||||||
|
public DataGrid() {
|
||||||
|
requireFx();
|
||||||
|
getStyleClass().add("data-grid");
|
||||||
|
selectionMode.addListener((property, old, mode) -> {
|
||||||
|
if (renderer != null) renderer.setSelectionMode(mode);
|
||||||
|
});
|
||||||
|
setSpacing(8);
|
||||||
|
getChildren().addAll(declaration.preview(), status);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObservableList<DataGridColumn> getColumns() {
|
||||||
|
return declaration.columns();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObjectProperty<ObservableList<T>> itemsProperty() {
|
||||||
|
return declaration.itemsProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObservableList<T> getItems() {
|
||||||
|
return itemsProperty().get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setItems(ObservableList<T> items) {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (getSource() != null) throw new IllegalStateException("Choose items or source");
|
||||||
|
itemsProperty().set(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridSource<K, T> getSource() {
|
||||||
|
return declaration.sourceProperty().get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObjectProperty<GridSource<K, T>> sourceProperty() {
|
||||||
|
return declaration.sourceProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Function<T, ResultRow> getRowFactory() {
|
||||||
|
return declaration.rowFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRowFactory(Function<T, ResultRow> factory) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.rowFactory = factory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Function<T, K> getKeyFactory() {
|
||||||
|
return declaration.keyFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setKeyFactory(Function<T, K> factory) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.keyFactory = factory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Comparator<K> getKeyComparator() {
|
||||||
|
return declaration.keyComparator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setKeyComparator(Comparator<K> comparator) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.keyComparator = comparator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getKeyAttribute() {
|
||||||
|
return declaration.keyAttribute;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setKeyAttribute(String attribute) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.keyAttribute = attribute;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSetupId() {
|
||||||
|
return declaration.setupId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSetupId(String id) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.setupId = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSetupVersion() {
|
||||||
|
return declaration.setupVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSetupVersion(int version) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.setupVersion = version;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getMaximumPageSize() {
|
||||||
|
return declaration.maximumPageSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMaximumPageSize(int size) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
if (size < 1) throw new IllegalArgumentException("Positive maximum page size required");
|
||||||
|
declaration.maximumPageSize = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getGroupBy() {
|
||||||
|
return declaration.groupBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupBy(String columns) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.groupBy = columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isGroupsCollapsed() {
|
||||||
|
return declaration.groupsCollapsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupsCollapsed(boolean collapsed) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.groupsCollapsed = collapsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getInactiveGroupHistoryLimit() {
|
||||||
|
return declaration.inactiveGroupHistoryLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInactiveGroupHistoryLimit(int limit) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
if (limit < 0) throw new IllegalArgumentException("Negative group history limit");
|
||||||
|
declaration.inactiveGroupHistoryLimit = limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Completes declarative configuration without executing a query. */
|
||||||
|
public void initialize() {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (coordinator == null) {
|
||||||
|
try {
|
||||||
|
declaration.open();
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
try {
|
||||||
|
close();
|
||||||
|
} catch (RuntimeException cleanup) {
|
||||||
|
failure.addSuppressed(cleanup);
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public DataGrid(
|
public DataGrid(
|
||||||
List<ResultColumn> columns,
|
List<ResultColumn> columns,
|
||||||
Function<T, ResultRow> rowFactory,
|
Function<T, ResultRow> rowFactory,
|
||||||
GridSource<K, T> source) {
|
GridSource<K, T> source) {
|
||||||
|
this();
|
||||||
|
declaration.setInitialSource(source);
|
||||||
|
initialize(columns, rowFactory, source);
|
||||||
|
}
|
||||||
|
|
||||||
|
void initialize(
|
||||||
|
List<ResultColumn> columns,
|
||||||
|
Function<T, ResultRow> rowFactory,
|
||||||
|
GridSource<K, T> source) {
|
||||||
requireFx();
|
requireFx();
|
||||||
|
getChildren().clear();
|
||||||
columnDefinitions = List.copyOf(columns);
|
columnDefinitions = List.copyOf(columns);
|
||||||
Objects.requireNonNull(source);
|
Objects.requireNonNull(source);
|
||||||
initial =
|
initial =
|
||||||
@@ -63,16 +282,24 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
List.of(),
|
List.of(),
|
||||||
new PageRequest.Paged(
|
new PageRequest.Paged(
|
||||||
0, Math.min(50, source.capabilities().maximumPageSize())));
|
0, Math.min(50, source.capabilities().maximumPageSize())));
|
||||||
renderer = table.openResults(columns, rowFactory);
|
renderer = table.openResults(columns, rowFactory, columnMenu);
|
||||||
|
columnMenu.getStyleClass().add("data-grid-column-menu");
|
||||||
|
columnMenu.setAccessibleText("Column visibility");
|
||||||
|
columnMenu.setTooltip(new Tooltip("Column visibility"));
|
||||||
|
columnMenu.setOnShowing(event -> updateColumnMenu());
|
||||||
|
renderer.setHeaderMenuFactory(this::headerMenu);
|
||||||
|
renderer.setSelectionMode(getSelectionMode());
|
||||||
|
selectedKeys.bind(renderer.selectedKeysProperty());
|
||||||
|
selectedElements.bind(renderer.selectedElementsProperty());
|
||||||
|
renderer.enableColumnSeparators();
|
||||||
|
selectedKey.bind(renderer.selectedKeyProperty());
|
||||||
|
selectedElement.bind(renderer.selectedElementProperty());
|
||||||
|
selection.bind(renderer.selectionProperty());
|
||||||
coordinator =
|
coordinator =
|
||||||
new GridCoordinator<>(
|
new GridCoordinator<>(
|
||||||
source,
|
source, Platform::runLater, this::changed, result -> publishRows(result));
|
||||||
Platform::runLater,
|
|
||||||
this::changed,
|
|
||||||
result -> renderer.show(result.rows()));
|
|
||||||
coordinator.setConfirmation(this::confirmAll);
|
coordinator.setConfirmation(this::confirmAll);
|
||||||
renderer.setOnSortRequest(
|
renderer.setOnSortRequest(id -> {
|
||||||
id -> {
|
|
||||||
var q = query();
|
var q = query();
|
||||||
SortKey.Direction direction =
|
SortKey.Direction direction =
|
||||||
q.sort().size() == 1
|
q.sort().size() == 1
|
||||||
@@ -89,14 +316,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
last.setOnAction(e -> last());
|
last.setOnAction(e -> last());
|
||||||
retry.setOnAction(e -> coordinator.retry());
|
retry.setOnAction(e -> coordinator.retry());
|
||||||
refresh.setOnAction(e -> refresh());
|
refresh.setOnAction(e -> refresh());
|
||||||
pageSize.setOnAction(
|
pageSize.setOnAction(e -> {
|
||||||
e -> {
|
|
||||||
if (updating || pageSize.getValue() == null) return;
|
if (updating || pageSize.getValue() == null) return;
|
||||||
setPageRequest(
|
setPageRequest(
|
||||||
pageSize.getValue().equals("All")
|
pageSize.getValue().equals("All")
|
||||||
? new PageRequest.All()
|
? new PageRequest.All()
|
||||||
: new PageRequest.Paged(
|
: new PageRequest.Paged(0, Integer.parseInt(pageSize.getValue())));
|
||||||
0, Integer.parseInt(pageSize.getValue())));
|
|
||||||
});
|
});
|
||||||
status.setWrapText(true);
|
status.setWrapText(true);
|
||||||
status.getStyleClass().add("data-grid-status");
|
status.getStyleClass().add("data-grid-status");
|
||||||
@@ -112,9 +337,40 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
refresh,
|
refresh,
|
||||||
retry);
|
retry);
|
||||||
controls.getStyleClass().add("data-grid-paging");
|
controls.getStyleClass().add("data-grid-paging");
|
||||||
getStyleClass().add("data-grid");
|
renderer.setOnLayoutCommitted(this::layoutCommitted);
|
||||||
setSpacing(8);
|
renderer.setOnInteractionMessage(interactionStatus::setText);
|
||||||
getChildren().addAll(table, controls, status);
|
groupingBar.getStyleClass().add("data-grid-grouping");
|
||||||
|
groupingBar.setAccessibleText("Grouping columns");
|
||||||
|
groupingBar.setFocusTraversable(true);
|
||||||
|
groupingBar.setVisible(false);
|
||||||
|
groupingBar.setManaged(false);
|
||||||
|
renderer.gestures().groupTarget(groupingBar);
|
||||||
|
MenuItem columnsItem = new MenuItem("Column settings…");
|
||||||
|
columnsItem.setOnAction(e -> {
|
||||||
|
if (columnSettings != null) columnSettings.close();
|
||||||
|
columnSettings = new GridColumnSettings<>(this, renderer);
|
||||||
|
columnSettings.show();
|
||||||
|
});
|
||||||
|
MenuItem resetExpansion = new MenuItem("Reset expansion");
|
||||||
|
resetExpansion.setOnAction(e -> resetExpansion());
|
||||||
|
MenuItem clearFilters = new MenuItem("Clear filters");
|
||||||
|
clearFilters.setOnAction(e -> setFilters(List.of()));
|
||||||
|
setupMenu.getItems().addAll(columnsItem, resetExpansion, clearFilters);
|
||||||
|
controls.getChildren().add(setupMenu);
|
||||||
|
interactionStatus.setWrapText(true);
|
||||||
|
interactionStatus.getStyleClass().add("data-grid-interaction-status");
|
||||||
|
de.neitzel.fx.control.ActionIcon.install(setupMenu, "Grid setup",
|
||||||
|
"M2 4 H14 M2 8 H14 M2 12 H14 M5 2 V6 M11 6 V10 M7 10 V14");
|
||||||
|
var css = DataGrid.class.getResource("data-grid.css");
|
||||||
|
if (css != null) getStylesheets().add(css.toExternalForm());
|
||||||
|
Button clearActiveFilters = actionButton("Clear filters",
|
||||||
|
"M1 2 H15 L9 8 V14 L6 12 V8 Z M11 10 L15 14 M15 10 L11 14");
|
||||||
|
clearActiveFilters.setOnAction(e -> setFilters(List.of()));
|
||||||
|
filterSummary.getChildren().addAll(activeFilters, clearActiveFilters);
|
||||||
|
filterSummary.setVisible(false);
|
||||||
|
filterSummary.setManaged(false);
|
||||||
|
getChildren()
|
||||||
|
.addAll(groupingBar, table, filterSummary, controls, status, interactionStatus);
|
||||||
VBox.setVgrow(table, Priority.ALWAYS);
|
VBox.setVgrow(table, Priority.ALWAYS);
|
||||||
state.set(coordinator.state());
|
state.set(coordinator.state());
|
||||||
updateControls(coordinator.state());
|
updateControls(coordinator.state());
|
||||||
@@ -125,11 +381,38 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
|
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
|
||||||
return renderer.selectedKeyProperty();
|
return selectedKey.getReadOnlyProperty();
|
||||||
}
|
}
|
||||||
|
|
||||||
public ReadOnlyObjectProperty<T> selectedElementProperty() {
|
public ReadOnlyObjectProperty<T> selectedElementProperty() {
|
||||||
return renderer.selectedElementProperty();
|
return selectedElement.getReadOnlyProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObjectProperty<RowSelectionMode> selectionModeProperty() { return selectionMode; }
|
||||||
|
|
||||||
|
public RowSelectionMode getSelectionMode() { return selectionMode.get(); }
|
||||||
|
|
||||||
|
public void setSelectionMode(RowSelectionMode mode) { selectionMode.set(mode); }
|
||||||
|
|
||||||
|
public ReadOnlyListProperty<K> selectedKeysProperty() { return selectedKeys.getReadOnlyProperty(); }
|
||||||
|
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void select(K key) {
|
public void select(K key) {
|
||||||
@@ -139,7 +422,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
|
|
||||||
public void confirmedDeleted(K key) {
|
public void confirmedDeleted(K key) {
|
||||||
check();
|
check();
|
||||||
if (Objects.equals(key, selectedKeyProperty().get())) renderer.select(null);
|
renderer.deselect(key);
|
||||||
refresh();
|
refresh();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,6 +448,66 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
renderer.setColumnOrder(ids);
|
renderer.setColumnOrder(ids);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Returns whether this grid currently displays the column. */
|
||||||
|
public boolean isColumnVisible(String id) {
|
||||||
|
check();
|
||||||
|
return renderer.isColumnVisible(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shows or hides a column without fetching rows or changing the saved grid setup. */
|
||||||
|
public void setColumnVisible(String id, boolean visible) {
|
||||||
|
if (visible == isColumnVisible(id)) return;
|
||||||
|
closeFilter();
|
||||||
|
renderer.setColumnVisible(id, visible);
|
||||||
|
columnVisibilityRevision.set(columnVisibilityRevision.get() + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Observes effective visibility changes, which are independent of saved grid setups. */
|
||||||
|
public ReadOnlyLongProperty columnVisibilityRevisionProperty() {
|
||||||
|
return columnVisibilityRevision.getReadOnlyProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateColumnMenu() {
|
||||||
|
columnMenu.getItems().setAll(renderer.columnOrder().stream().map(id -> {
|
||||||
|
CheckMenuItem item = new CheckMenuItem(renderer.columnHeader(id));
|
||||||
|
item.setSelected(isColumnVisible(id));
|
||||||
|
item.setOnAction(e -> setColumnVisible(id, item.isSelected()));
|
||||||
|
return item;
|
||||||
|
}).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContextMenu headerMenu(String id, HBox cell) {
|
||||||
|
var menu = new ContextMenu(
|
||||||
|
menuItem("Sort ascending", () -> setSort(new SortKey(id, SortKey.Direction.ASCENDING))),
|
||||||
|
menuItem("Sort descending", () -> setSort(new SortKey(id, SortKey.Direction.DESCENDING))));
|
||||||
|
if (query().sort().stream().anyMatch(key -> key.columnId().equals(id)))
|
||||||
|
menu.getItems().add(menuItem("Clear sort", () -> setSort(null)));
|
||||||
|
if (filterColumns.containsKey(id)) {
|
||||||
|
var filterButton = cell.lookup(".filter-button");
|
||||||
|
menu.getItems().add(menuItem("Filter…", () -> openFilter(id, filterButton)));
|
||||||
|
}
|
||||||
|
if (renderer.canGroup(id)) {
|
||||||
|
boolean grouped = renderer.groupingColumns().contains(id);
|
||||||
|
menu.getItems().add(menuItem(grouped ? "Remove grouping" : "Group by column", () -> {
|
||||||
|
var nextGroups = new ArrayList<>(renderer.groupingColumns());
|
||||||
|
if (grouped) nextGroups.remove(id);
|
||||||
|
else if (!nextGroups.contains(id)) nextGroups.add(id);
|
||||||
|
setGroupingColumns(nextGroups);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
menu.getItems().addAll(
|
||||||
|
menuItem("Reset column width", () -> setColumnWidth(id, new ColumnWidth.Default())),
|
||||||
|
new SeparatorMenuItem(),
|
||||||
|
menuItem("Hide column", () -> setColumnVisible(id, false)));
|
||||||
|
return menu;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MenuItem menuItem(String text, Runnable action) {
|
||||||
|
var item = new MenuItem(text);
|
||||||
|
item.setOnAction(e -> action.run());
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
public double setColumnWidth(String id, ColumnWidth width) {
|
public double setColumnWidth(String id, ColumnWidth width) {
|
||||||
check();
|
check();
|
||||||
closeFilter();
|
closeFilter();
|
||||||
@@ -191,6 +534,15 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void setSource(GridSource<K, T> source) {
|
public void setSource(GridSource<K, T> source) {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (getItems() != null) throw new IllegalStateException("Choose items or source");
|
||||||
|
Objects.requireNonNull(source);
|
||||||
|
if (coordinator != null && source == getSource()) replaceSource(source);
|
||||||
|
else sourceProperty().set(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
void replaceSource(GridSource<K, T> source) {
|
||||||
check();
|
check();
|
||||||
closeFilter();
|
closeFilter();
|
||||||
var q = query();
|
var q = query();
|
||||||
@@ -220,8 +572,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
id,
|
id,
|
||||||
version,
|
version,
|
||||||
columnDefinitions.stream()
|
columnDefinitions.stream()
|
||||||
.map(
|
.map(c ->
|
||||||
c ->
|
|
||||||
new GridDefinition.Column(
|
new GridDefinition.Column(
|
||||||
c.id(),
|
c.id(),
|
||||||
types.get(c.id()),
|
types.get(c.id()),
|
||||||
@@ -247,18 +598,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
Map<String, String> types = new HashMap<>();
|
Map<String, String> types = new HashMap<>();
|
||||||
setupDefinition.columns().forEach(c -> types.put(c.id(), c.type()));
|
setupDefinition.columns().forEach(c -> types.put(c.id(), c.type()));
|
||||||
return new GridSetup(
|
return new GridSetup(
|
||||||
1,
|
2,
|
||||||
setupDefinition.id(),
|
setupDefinition.id(),
|
||||||
setupDefinition.version(),
|
setupDefinition.version(),
|
||||||
renderer.columnOrder().stream()
|
renderer.columnOrder().stream()
|
||||||
.map(
|
.map(id ->
|
||||||
id ->
|
|
||||||
new GridSetup.ColumnState(
|
new GridSetup.ColumnState(
|
||||||
id, types.get(id), renderer.columnWidths().get(id)))
|
id, types.get(id), renderer.columnWidths().get(id)))
|
||||||
.toList(),
|
.toList(),
|
||||||
committed.sort(),
|
committed.sort(),
|
||||||
committed.filters(),
|
committed.filters(),
|
||||||
firstPage(committed.page()));
|
firstPage(committed.page()),
|
||||||
|
renderer.groupingSetup());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ReadOnlyObjectProperty<List<String>> restorationAdjustmentsProperty() {
|
public ReadOnlyObjectProperty<List<String>> restorationAdjustmentsProperty() {
|
||||||
@@ -287,6 +638,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
coordinator.capabilities(),
|
coordinator.capabilities(),
|
||||||
condition -> coordinator.validateFilters(List.of(condition)));
|
condition -> coordinator.validateFilters(List.of(condition)));
|
||||||
var setup = prepared.setup();
|
var setup = prepared.setup();
|
||||||
|
var grouping =
|
||||||
|
setup.grouping() == null
|
||||||
|
? new GroupingSetup(defaultGrouping, List.of())
|
||||||
|
: setup.grouping();
|
||||||
|
renderer.validateGrouping(grouping);
|
||||||
|
long serial = restoreSerial;
|
||||||
Map<String, ColumnWidth> widths = new LinkedHashMap<>();
|
Map<String, ColumnWidth> widths = new LinkedHashMap<>();
|
||||||
setup.columns().forEach(c -> widths.put(c.id(), c.width()));
|
setup.columns().forEach(c -> widths.put(c.id(), c.width()));
|
||||||
coordinator.restoreSetup(
|
coordinator.restoreSetup(
|
||||||
@@ -296,7 +653,11 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
renderer.show(
|
renderer.show(
|
||||||
result.rows(),
|
result.rows(),
|
||||||
setup.columns().stream().map(GridSetup.ColumnState::id).toList(),
|
setup.columns().stream().map(GridSetup.ColumnState::id).toList(),
|
||||||
widths);
|
widths,
|
||||||
|
grouping);
|
||||||
|
lastRestoredSerial = serial;
|
||||||
|
restoredPublication = true;
|
||||||
|
drawGroupingBar();
|
||||||
restorationAdjustments.set(prepared.adjustments());
|
restorationAdjustments.set(prepared.adjustments());
|
||||||
});
|
});
|
||||||
} catch (RuntimeException error) {
|
} catch (RuntimeException error) {
|
||||||
@@ -431,10 +792,29 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
firstPage(q.page())));
|
firstPage(q.page())));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int getPageSize() {
|
||||||
|
return coordinator == null
|
||||||
|
? declaration.pageSize
|
||||||
|
: query().page() instanceof PageRequest.Paged page ? page.pageSize() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
public void setPageSize(int size) {
|
public void setPageSize(int size) {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (size < 1) throw new IllegalArgumentException("Positive page size required");
|
||||||
|
if (coordinator == null) {
|
||||||
|
declaration.pageSize = size;
|
||||||
|
return;
|
||||||
|
}
|
||||||
setPageRequest(new PageRequest.Paged(0, size));
|
setPageRequest(new PageRequest.Paged(0, size));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void setInitialPageSize(int size) {
|
||||||
|
coordinator.capabilities().validate(new PageRequest.Paged(0, size));
|
||||||
|
initial = new GridQuery(initial.filters(), initial.sort(), new PageRequest.Paged(0, size));
|
||||||
|
updateControls(coordinator.state());
|
||||||
|
}
|
||||||
|
|
||||||
public void showAll() {
|
public void showAll() {
|
||||||
setPageRequest(new PageRequest.All());
|
setPageRequest(new PageRequest.All());
|
||||||
}
|
}
|
||||||
@@ -502,11 +882,13 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
pseudoClassStateChanged(
|
pseudoClassStateChanged(
|
||||||
javafx.css.PseudoClass.getPseudoClass("error"),
|
javafx.css.PseudoClass.getPseudoClass("error"),
|
||||||
value.phase() == GridCoordinator.Phase.ERROR);
|
value.phase() == GridCoordinator.Phase.ERROR);
|
||||||
if (value.displayed() != null)
|
if (value.displayed() != null) {
|
||||||
renderer.setFilteredColumns(
|
renderer.setFilteredColumns(
|
||||||
value.displayed().filters().stream()
|
value.displayed().filters().stream()
|
||||||
.map(FilterCondition::columnId)
|
.map(FilterCondition::columnId)
|
||||||
.collect(java.util.stream.Collectors.toSet()));
|
.collect(java.util.stream.Collectors.toSet()));
|
||||||
|
renderer.setSortKeys(value.displayed().sort());
|
||||||
|
}
|
||||||
if (visibleSourceVersion != value.sourceVersion()) {
|
if (visibleSourceVersion != value.sourceVersion()) {
|
||||||
visibleSourceVersion = value.sourceVersion();
|
visibleSourceVersion = value.sourceVersion();
|
||||||
renderer.select(null);
|
renderer.select(null);
|
||||||
@@ -515,6 +897,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
updateControls(value);
|
updateControls(value);
|
||||||
}
|
}
|
||||||
state.set(value);
|
state.set(value);
|
||||||
|
if (!closed && value.phase() == GridCoordinator.Phase.READY) {
|
||||||
|
GridQuery published =
|
||||||
|
new GridQuery(
|
||||||
|
value.displayed().filters(),
|
||||||
|
value.displayed().sort(),
|
||||||
|
firstPage(value.displayed().page()));
|
||||||
|
boolean changedQuery = hasPublished && !Objects.equals(published, lastPublishedQuery);
|
||||||
|
hasPublished = true;
|
||||||
|
lastPublishedQuery = published;
|
||||||
|
if (changedQuery && !restoredPublication) fireCommitted();
|
||||||
|
restoredPublication = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void updateControls(GridCoordinator.State<K, T> s) {
|
private void updateControls(GridCoordinator.State<K, T> s) {
|
||||||
@@ -592,7 +986,27 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
yield pageLabel(requested.page()) + " — total unknown";
|
yield pageLabel(requested.page()) + " — total unknown";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
status.setText(message);
|
List<String> filtered =
|
||||||
|
s.displayed() == null
|
||||||
|
? List.of()
|
||||||
|
: s.displayed().filters().stream()
|
||||||
|
.map(f ->
|
||||||
|
columnDefinitions.stream()
|
||||||
|
.filter(c -> c.id().equals(f.columnId()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.header())
|
||||||
|
.toList();
|
||||||
|
activeFilters.setText("Active filters: " + String.join(", ", filtered));
|
||||||
|
filterSummary.setVisible(!filtered.isEmpty());
|
||||||
|
filterSummary.setManaged(!filtered.isEmpty());
|
||||||
|
status.setText(
|
||||||
|
message
|
||||||
|
+ (renderer.groupingEnabled() && !renderer.groupingColumns().isEmpty()
|
||||||
|
? (requested.page() instanceof PageRequest.All
|
||||||
|
? " · Grouping loaded result"
|
||||||
|
: " · Grouping current page")
|
||||||
|
: ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String pageLabel(PageRequest page) {
|
private static String pageLabel(PageRequest page) {
|
||||||
@@ -617,8 +1031,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
alert.initOwner(getScene().getWindow());
|
alert.initOwner(getScene().getWindow());
|
||||||
pendingAlert = alert;
|
pendingAlert = alert;
|
||||||
alertGeneration = coordinator.state().generation();
|
alertGeneration = coordinator.state().generation();
|
||||||
alert.setOnHidden(
|
alert.setOnHidden(e -> {
|
||||||
e -> {
|
|
||||||
if (pendingAlert == alert) pendingAlert = null;
|
if (pendingAlert == alert) pendingAlert = null;
|
||||||
answer.complete(alert.getResult() == proceed);
|
answer.complete(alert.getResult() == proceed);
|
||||||
});
|
});
|
||||||
@@ -626,6 +1039,271 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
return answer;
|
return answer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> loadAsync() {
|
||||||
|
return awaitOperation(this::load, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> restoreSetupAsync(GridSetup setup) {
|
||||||
|
long serial = ++restoreSerial;
|
||||||
|
return awaitOperation(() -> restoreSetup(setup), serial);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletionStage<Void> awaitOperation(Runnable action, long serial) {
|
||||||
|
check();
|
||||||
|
action.run();
|
||||||
|
long generation = coordinator.state().generation();
|
||||||
|
CompletableFuture<Void> future = new CompletableFuture<>();
|
||||||
|
javafx.beans.value.ChangeListener<GridCoordinator.State<K, T>> listener =
|
||||||
|
(observable, before, value) -> {
|
||||||
|
if (value.generation() != generation
|
||||||
|
|| value.phase() == GridCoordinator.Phase.CLOSED)
|
||||||
|
future.completeExceptionally(
|
||||||
|
new CancellationException("Grid operation superseded"));
|
||||||
|
else if (value.phase() == GridCoordinator.Phase.ERROR)
|
||||||
|
future.completeExceptionally(value.error());
|
||||||
|
else if (value.phase() == GridCoordinator.Phase.READY) {
|
||||||
|
if (serial < 0 || lastRestoredSerial == serial) future.complete(null);
|
||||||
|
else
|
||||||
|
future.completeExceptionally(
|
||||||
|
new CancellationException("Restore declined"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
state.addListener(listener);
|
||||||
|
future.whenComplete((ok, error) -> state.removeListener(listener));
|
||||||
|
listener.changed(state, state.get(), state.get());
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
|
||||||
|
GridSetup developerDefaults() {
|
||||||
|
return developerDefaults == null ? snapshotSetup() : developerDefaults;
|
||||||
|
}
|
||||||
|
|
||||||
|
void cancelOwnedRestore(long generation) {
|
||||||
|
if (!closed && state.get().generation() == generation) coordinator.cancelRestore();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ReadOnlyLongProperty committedRevisionProperty() {
|
||||||
|
return committedRevision.getReadOnlyProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> groupingColumns() {
|
||||||
|
return renderer.groupingColumns();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean groupingEnabled() {
|
||||||
|
return renderer.groupingEnabled();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void configureGrouping(
|
||||||
|
List<GroupColumn<T>> columns,
|
||||||
|
boolean enabled,
|
||||||
|
List<String> defaults,
|
||||||
|
boolean collapsed,
|
||||||
|
int inactiveHistoryLimit) {
|
||||||
|
check();
|
||||||
|
renderer.configureGrouping(columns, enabled, defaults, collapsed, inactiveHistoryLimit);
|
||||||
|
defaultGrouping = List.copyOf(defaults);
|
||||||
|
developerDefaults = null;
|
||||||
|
drawGroupingBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupingColumns(List<String> columns) {
|
||||||
|
check();
|
||||||
|
closeFilter();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
try {
|
||||||
|
renderer.setGroupingColumns(columns);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
interactionStatus.setText("Cannot change grouping: " + failure.getMessage());
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isGroupingEnabled() {
|
||||||
|
return coordinator == null ? declaration.groupingEnabled : groupingEnabled();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupingEnabled(boolean enabled) {
|
||||||
|
requireFx();
|
||||||
|
if (coordinator == null) {
|
||||||
|
declaration.groupingEnabled = enabled;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
check();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
renderer.setGroupingEnabled(enabled);
|
||||||
|
drawGroupingBar();
|
||||||
|
updateControls(coordinator.state());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetExpansion() {
|
||||||
|
check();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
renderer.resetExpansion();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExpanded(GroupPath path, boolean expanded) {
|
||||||
|
check();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
renderer.setExpanded(path, expanded);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void regroup() {
|
||||||
|
check();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
try {
|
||||||
|
renderer.regroup();
|
||||||
|
interactionStatus.setText("");
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
interactionStatus.setText("Cannot update grouping: " + failure.getMessage());
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void publishRows(PageResult<K, T> result) {
|
||||||
|
renderer.show(result.rows());
|
||||||
|
drawGroupingBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void layoutCommitted() {
|
||||||
|
if (closed) return;
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
drawGroupingBar();
|
||||||
|
updateControls(coordinator.state());
|
||||||
|
fireCommitted();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fireCommitted() {
|
||||||
|
committedRevision.set(committedRevision.get() + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawGroupingBar() {
|
||||||
|
groupingBar.setVisible(renderer.groupingEnabled());
|
||||||
|
groupingBar.setManaged(renderer.groupingEnabled());
|
||||||
|
NodeFocus focus = new NodeFocus(groupingBar);
|
||||||
|
groupingBar.getChildren().clear();
|
||||||
|
if (renderer.groupingColumns().isEmpty())
|
||||||
|
groupingBar
|
||||||
|
.getChildren()
|
||||||
|
.add(new Label("Drag a column here to group the current page"));
|
||||||
|
for (String id : renderer.groupingColumns()) {
|
||||||
|
String label =
|
||||||
|
columnDefinitions.stream()
|
||||||
|
.filter(c -> c.id().equals(id))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.header();
|
||||||
|
Label text = new Label(label);
|
||||||
|
Button remove = new Button("×");
|
||||||
|
remove.setAccessibleText("Remove grouping by " + label);
|
||||||
|
remove.setOnAction(e ->
|
||||||
|
setGroupingColumns(
|
||||||
|
renderer.groupingColumns().stream()
|
||||||
|
.filter(c -> !c.equals(id))
|
||||||
|
.toList()));
|
||||||
|
remove.addEventHandler(
|
||||||
|
javafx.scene.input.MouseEvent.DRAG_DETECTED, javafx.event.Event::consume);
|
||||||
|
HBox chip = new HBox(6, text, remove);
|
||||||
|
chip.getStyleClass().add("grouping-chip");
|
||||||
|
chip.setAccessibleText(
|
||||||
|
"Grouping level " + (groupingBar.getChildren().size() + 1) + ": " + label);
|
||||||
|
chip.setFocusTraversable(true);
|
||||||
|
renderer.gestures().chip(chip, id);
|
||||||
|
groupingBar.getChildren().add(chip);
|
||||||
|
}
|
||||||
|
focus.restore(groupingBar);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class NodeFocus {
|
||||||
|
private final boolean inside;
|
||||||
|
|
||||||
|
NodeFocus(javafx.scene.Parent parent) {
|
||||||
|
javafx.scene.Node focus =
|
||||||
|
parent.getScene() == null ? null : parent.getScene().getFocusOwner();
|
||||||
|
boolean found = false;
|
||||||
|
for (var node = focus; node != null; node = node.getParent())
|
||||||
|
if (node == parent) found = true;
|
||||||
|
inside = found;
|
||||||
|
}
|
||||||
|
|
||||||
|
void restore(javafx.scene.Parent parent) {
|
||||||
|
if (inside) parent.requestFocus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure defaults without fetching. Call after column/group definitions, before
|
||||||
|
* attachment/load.
|
||||||
|
*/
|
||||||
|
public void configureDefaults(GridSetup defaults) {
|
||||||
|
check();
|
||||||
|
if (hasPublished || attachment != null || state.get().phase() != GridCoordinator.Phase.IDLE)
|
||||||
|
throw new IllegalStateException("Configure defaults before attachment or loading");
|
||||||
|
if (setupDefinition == null)
|
||||||
|
throw new IllegalStateException("Configure the grid definition first");
|
||||||
|
var prepared =
|
||||||
|
setupDefinition
|
||||||
|
.prepare(
|
||||||
|
defaults,
|
||||||
|
setupMigrations,
|
||||||
|
coordinator.capabilities(),
|
||||||
|
condition -> coordinator.validateFilters(List.of(condition)))
|
||||||
|
.setup();
|
||||||
|
var groups =
|
||||||
|
prepared.grouping() == null
|
||||||
|
? new GroupingSetup(defaultGrouping, List.of())
|
||||||
|
: prepared.grouping();
|
||||||
|
renderer.validateGrouping(groups);
|
||||||
|
var widths = new LinkedHashMap<String, ColumnWidth>();
|
||||||
|
prepared.columns().forEach(c -> widths.put(c.id(), c.width()));
|
||||||
|
renderer.show(
|
||||||
|
List.of(),
|
||||||
|
prepared.columns().stream().map(GridSetup.ColumnState::id).toList(),
|
||||||
|
widths,
|
||||||
|
groups);
|
||||||
|
initial = new GridQuery(prepared.filters(), prepared.sort(), firstPage(prepared.page()));
|
||||||
|
defaultGrouping = groups.columns();
|
||||||
|
developerDefaults = snapshotSetup();
|
||||||
|
drawGroupingBar();
|
||||||
|
updateControls(coordinator.state());
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridSetup defaultSetup() {
|
||||||
|
check();
|
||||||
|
if (developerDefaults == null) developerDefaults = snapshotSetup();
|
||||||
|
return developerDefaults;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridPersistenceAttachment<K, T> attachPersistence(
|
||||||
|
GridApplicationConfiguration config, String gridId) {
|
||||||
|
return attachPersistence(config, gridId, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridPersistenceAttachment<K, T> attachPersistence(
|
||||||
|
GridApplicationConfiguration config, String gridId, String context) {
|
||||||
|
check();
|
||||||
|
if (attachment != null) throw new IllegalStateException("Persistence already attached");
|
||||||
|
if (developerDefaults == null) developerDefaults = snapshotSetup();
|
||||||
|
attachment =
|
||||||
|
new GridPersistenceAttachment<>(
|
||||||
|
this, config, new GridSetupStore.Key(gridId, context));
|
||||||
|
return attachment;
|
||||||
|
}
|
||||||
|
|
||||||
|
void addPersistenceControls(javafx.scene.Node feedback, List<MenuItem> items) {
|
||||||
|
getChildren().add(feedback);
|
||||||
|
setupMenu.getItems().addAll(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
void removePersistenceControls(javafx.scene.Node feedback, List<MenuItem> items) {
|
||||||
|
getChildren().remove(feedback);
|
||||||
|
setupMenu.getItems().removeAll(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
void detached(GridPersistenceAttachment<K, T> handle) {
|
||||||
|
if (attachment == handle) attachment = null;
|
||||||
|
}
|
||||||
|
|
||||||
private static void requireFx() {
|
private static void requireFx() {
|
||||||
if (!Platform.isFxApplicationThread())
|
if (!Platform.isFxApplicationThread())
|
||||||
throw new IllegalStateException("Use the JavaFX application thread");
|
throw new IllegalStateException("Use the JavaFX application thread");
|
||||||
@@ -634,19 +1312,55 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
private void check() {
|
private void check() {
|
||||||
requireFx();
|
requireFx();
|
||||||
if (closed) throw new IllegalStateException("Grid is closed");
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
void refreshItems() {
|
||||||
|
if (coordinator == null
|
||||||
|
|| closed
|
||||||
|
|| coordinator.state().phase() == GridCoordinator.Phase.IDLE) return;
|
||||||
|
if (attachment != null) {
|
||||||
|
var ready = attachment.ready().toCompletableFuture();
|
||||||
|
if (!ready.isDone() || ready.isCompletedExceptionally()) return;
|
||||||
|
}
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isInitialized() {
|
||||||
|
return coordinator != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isClosed() {
|
||||||
|
return closed;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void close() {
|
public void close() {
|
||||||
requireFx();
|
requireFx();
|
||||||
if (closed) return;
|
if (closed) return;
|
||||||
|
if (columnSettings != null) {
|
||||||
|
columnSettings.close();
|
||||||
|
columnSettings = null;
|
||||||
|
}
|
||||||
|
if (attachment != null) attachment.close();
|
||||||
closed = true;
|
closed = true;
|
||||||
|
columnMenu.hide();
|
||||||
closeFilter();
|
closeFilter();
|
||||||
coordinator.close();
|
declaration.close();
|
||||||
|
if (coordinator != null) coordinator.close();
|
||||||
if (pendingAlert != null) {
|
if (pendingAlert != null) {
|
||||||
pendingAlert.close();
|
pendingAlert.close();
|
||||||
pendingAlert = null;
|
pendingAlert = null;
|
||||||
}
|
}
|
||||||
renderer.close();
|
if (renderer != null) renderer.close();
|
||||||
|
selectedKey.unbind();
|
||||||
|
selectedElement.unbind();
|
||||||
|
selection.unbind();
|
||||||
|
selectedKeys.unbind();
|
||||||
|
selectedElements.unbind();
|
||||||
|
selectedKeys.set(FXCollections.emptyObservableList());
|
||||||
|
selectedElements.set(FXCollections.emptyObservableList());
|
||||||
|
selectedKey.set(null);
|
||||||
|
selectedElement.set(null);
|
||||||
getChildren().clear();
|
getChildren().clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.grid.filter.FilterColumn;
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
/** Declarative column shared by rendering, local queries, filters, grouping and saved setups. */
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public final class DataGridColumn {
|
||||||
|
private String id;
|
||||||
|
private String header;
|
||||||
|
private String attribute;
|
||||||
|
private String groupAttribute;
|
||||||
|
|
||||||
|
@Setter(lombok.AccessLevel.NONE)
|
||||||
|
private final java.util.Map<String, String> groupLabels = new java.util.LinkedHashMap<>();
|
||||||
|
|
||||||
|
/** Adds one FXML group label whose key can contain spaces, paths or other non-name characters. */
|
||||||
|
public static void setGroupLabel(DataGridColumn column, javafx.util.Pair<String, String> entry) {
|
||||||
|
column.groupLabels.put(java.util.Objects.requireNonNull(entry.getKey(), "group key"),
|
||||||
|
java.util.Objects.requireNonNull(entry.getValue(), "group label"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private double width = 150;
|
||||||
|
private double minimumWidth = 80;
|
||||||
|
private double maximumWidth = 1200;
|
||||||
|
private int fixedPosition = -1;
|
||||||
|
private MemoryColumn.Kind kind = MemoryColumn.Kind.TEXT;
|
||||||
|
private boolean filterable = true;
|
||||||
|
private FilterColumn.Checklist checklist = FilterColumn.Checklist.DISABLED;
|
||||||
|
private FilterCandidates.Provider candidates;
|
||||||
|
private String type;
|
||||||
|
|
||||||
|
ResultColumn definition() {
|
||||||
|
if (kind == null || checklist == null)
|
||||||
|
throw new IllegalArgumentException("Column kind and checklist are required");
|
||||||
|
return new ResultColumn(id, header, width, minimumWidth, maximumWidth, fixedPosition);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object getValue(Object row) {
|
||||||
|
return read(row, attribute == null ? id : attribute);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Object read(Object row, String attribute) {
|
||||||
|
if (row == null) return null;
|
||||||
|
if (attribute == null || attribute.isBlank())
|
||||||
|
throw new IllegalArgumentException("Missing row attribute");
|
||||||
|
String suffix = Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1);
|
||||||
|
for (String name : new String[] {"get" + suffix, "is" + suffix, attribute}) {
|
||||||
|
try {
|
||||||
|
return row.getClass().getMethod(name).invoke(row);
|
||||||
|
} catch (NoSuchMethodException absent) {
|
||||||
|
// JavaBeans and record-style scalar accessors are both supported.
|
||||||
|
} catch (IllegalAccessException | InvocationTargetException error) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Could not read row attribute " + attribute, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"No row attribute " + attribute + " on " + row.getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
FilterValue groupValue(Object row) {
|
||||||
|
return scalar(groupAttribute == null ? getValue(row) : read(row, groupAttribute));
|
||||||
|
}
|
||||||
|
|
||||||
|
String groupLabel(FilterValue value) {
|
||||||
|
String display = GroupColumn.display(value);
|
||||||
|
return groupLabels.getOrDefault(display, display);
|
||||||
|
}
|
||||||
|
|
||||||
|
FilterValue value(Object row) {
|
||||||
|
return scalar(getValue(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
private FilterValue scalar(Object value) {
|
||||||
|
if (value == null) return null;
|
||||||
|
return switch (kind) {
|
||||||
|
case TEXT -> new FilterValue.Text(value.toString());
|
||||||
|
case INTEGER ->
|
||||||
|
new FilterValue.IntegerValue(new BigDecimal(value.toString()).longValueExact());
|
||||||
|
case DECIMAL -> new FilterValue.Decimal(new BigDecimal(value.toString()));
|
||||||
|
case BOOLEAN -> {
|
||||||
|
if (!(value instanceof Boolean bool))
|
||||||
|
throw new IllegalArgumentException("Boolean value required for " + id);
|
||||||
|
yield new FilterValue.BooleanValue(bool);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
String schemaType() {
|
||||||
|
return type == null
|
||||||
|
? "neitzel." + kind.name().toLowerCase(java.util.Locale.ROOT) + ".v1"
|
||||||
|
: type;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.grid.filter.FilterColumn;
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.property.*;
|
||||||
|
import javafx.collections.*;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.function.*;
|
||||||
|
|
||||||
|
/** FXML construction and owned local-source lifetime, separate from query coordination. */
|
||||||
|
final class DataGridDeclaration<K, T> implements AutoCloseable {
|
||||||
|
private final DataGrid<K, T> grid;
|
||||||
|
private final ObservableList<DataGridColumn> columns = FXCollections.observableArrayList();
|
||||||
|
private final ObjectProperty<ObservableList<T>> items = new SimpleObjectProperty<>();
|
||||||
|
private final ObjectProperty<GridSource<K, T>> source = new SimpleObjectProperty<>();
|
||||||
|
private final HBox preview = new HBox();
|
||||||
|
private final ListChangeListener<T> itemsChanged = change -> changedItems();
|
||||||
|
private ExecutorService executor;
|
||||||
|
private boolean external;
|
||||||
|
private boolean assigningInitialSource;
|
||||||
|
Function<T, ResultRow> rowFactory;
|
||||||
|
Function<T, K> keyFactory;
|
||||||
|
Comparator<K> keyComparator;
|
||||||
|
String keyAttribute;
|
||||||
|
String setupId;
|
||||||
|
int setupVersion = 1;
|
||||||
|
int pageSize = 50;
|
||||||
|
int maximumPageSize = 250;
|
||||||
|
boolean groupingEnabled;
|
||||||
|
String groupBy = "";
|
||||||
|
boolean groupsCollapsed;
|
||||||
|
int inactiveGroupHistoryLimit = 1000;
|
||||||
|
|
||||||
|
DataGridDeclaration(DataGrid<K, T> grid) {
|
||||||
|
this.grid = grid;
|
||||||
|
preview.getStyleClass().add("data-grid-preview-header");
|
||||||
|
columns.addListener(
|
||||||
|
(ListChangeListener<DataGridColumn>)
|
||||||
|
change -> {
|
||||||
|
beforeOpen();
|
||||||
|
preview.getChildren().clear();
|
||||||
|
for (var column : columns) {
|
||||||
|
var label = new Label(column.getHeader());
|
||||||
|
label.setPrefWidth(column.getWidth());
|
||||||
|
label.getStyleClass().add("column-header");
|
||||||
|
preview.getChildren().add(label);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
items.addListener((observable, previous, current) -> {
|
||||||
|
requireFx();
|
||||||
|
if (grid.isClosed()) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (external && grid.isInitialized())
|
||||||
|
throw new IllegalStateException("External sources cannot use items");
|
||||||
|
if (previous != null) previous.removeListener(itemsChanged);
|
||||||
|
if (current != null) current.addListener(itemsChanged);
|
||||||
|
changedItems();
|
||||||
|
});
|
||||||
|
source.addListener((observable, previous, current) -> {
|
||||||
|
requireFx();
|
||||||
|
if (assigningInitialSource) return;
|
||||||
|
if (grid.isClosed()) throw new IllegalStateException("Grid is closed");
|
||||||
|
Objects.requireNonNull(current, "Missing source");
|
||||||
|
if (items.get() != null) throw new IllegalStateException("Choose items or source");
|
||||||
|
if (grid.isInitialized()) {
|
||||||
|
external = true;
|
||||||
|
grid.replaceSource(current);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void setInitialSource(GridSource<K, T> value) {
|
||||||
|
assigningInitialSource = true;
|
||||||
|
try {
|
||||||
|
source.set(Objects.requireNonNull(value));
|
||||||
|
external = true;
|
||||||
|
} finally {
|
||||||
|
assigningInitialSource = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ObservableList<DataGridColumn> columns() {
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjectProperty<ObservableList<T>> itemsProperty() {
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjectProperty<GridSource<K, T>> sourceProperty() {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
|
HBox preview() {
|
||||||
|
return preview;
|
||||||
|
}
|
||||||
|
|
||||||
|
void beforeOpen() {
|
||||||
|
requireFx();
|
||||||
|
if (grid.isClosed() || grid.isInitialized())
|
||||||
|
throw new IllegalStateException("Configure before initializing the grid");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void requireFx() {
|
||||||
|
if (!Platform.isFxApplicationThread())
|
||||||
|
throw new IllegalStateException("Use the JavaFX application thread");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void changedItems() {
|
||||||
|
requireFx();
|
||||||
|
grid.refreshItems();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void open() {
|
||||||
|
var definitions = columns.stream().map(DataGridColumn::definition).toList();
|
||||||
|
if (definitions.isEmpty())
|
||||||
|
throw new IllegalArgumentException("Declare DataGrid columns before loading");
|
||||||
|
if (definitions.stream().map(ResultColumn::id).distinct().count() != definitions.size())
|
||||||
|
throw new IllegalArgumentException("Duplicate DataGrid column ID");
|
||||||
|
GridSource<K, T> configured = source.get();
|
||||||
|
MemoryGridSource<K, T> memory = null;
|
||||||
|
if (configured == null) {
|
||||||
|
if (keyFactory == null && (keyAttribute == null || keyAttribute.isBlank()))
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Local DataGrid requires keyAttribute or keyFactory");
|
||||||
|
Function<T, K> key =
|
||||||
|
keyFactory != null
|
||||||
|
? keyFactory
|
||||||
|
: row -> (K) DataGridColumn.read(row, keyAttribute);
|
||||||
|
Comparator<K> order =
|
||||||
|
keyComparator != null
|
||||||
|
? keyComparator
|
||||||
|
: (a, b) -> {
|
||||||
|
if (!(a instanceof Comparable<?>))
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Row keys require a comparator");
|
||||||
|
return ((Comparable<Object>) a).compareTo(b);
|
||||||
|
};
|
||||||
|
executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||||
|
memory =
|
||||||
|
new MemoryGridSource<>(
|
||||||
|
() -> items.get() == null ? List.of() : items.get(),
|
||||||
|
key,
|
||||||
|
order,
|
||||||
|
columns.stream()
|
||||||
|
.map(c -> new MemoryColumn<T>(c.getId(), c.getKind(), c::value))
|
||||||
|
.toList(),
|
||||||
|
executor,
|
||||||
|
maximumPageSize);
|
||||||
|
configured = memory;
|
||||||
|
} else {
|
||||||
|
if (items.get() != null) throw new IllegalArgumentException("Choose items or source");
|
||||||
|
external = true;
|
||||||
|
}
|
||||||
|
configured.capabilities().validate(new PageRequest.Paged(0, pageSize));
|
||||||
|
grid.initialize(definitions, rowFactory == null ? this::render : rowFactory, configured);
|
||||||
|
grid.setInitialPageSize(pageSize);
|
||||||
|
for (var column : columns) {
|
||||||
|
if (!column.isFilterable()) continue;
|
||||||
|
FilterColumn filter =
|
||||||
|
switch (column.getKind()) {
|
||||||
|
case TEXT -> FilterColumn.text();
|
||||||
|
case INTEGER, DECIMAL ->
|
||||||
|
FilterColumn.number(
|
||||||
|
Locale.getDefault(),
|
||||||
|
column.getKind() == MemoryColumn.Kind.INTEGER,
|
||||||
|
null,
|
||||||
|
null);
|
||||||
|
case BOOLEAN -> null;
|
||||||
|
};
|
||||||
|
if (filter == null) {
|
||||||
|
if (column.getChecklist() != FilterColumn.Checklist.DISABLED)
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Boolean filter editor is not available; set filterable=false");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
var candidates = column.getCandidates();
|
||||||
|
if (candidates == null && memory != null)
|
||||||
|
candidates = memory.candidateProvider(GroupColumn::display);
|
||||||
|
grid.configureFilter(
|
||||||
|
column.getId(), filter.withChecklist(column.getChecklist(), candidates));
|
||||||
|
}
|
||||||
|
grid.configureGrouping(
|
||||||
|
columns.stream()
|
||||||
|
.map(c ->
|
||||||
|
new GroupColumn<T>(
|
||||||
|
c.getId(), c.getKind(), c::groupValue, c::groupLabel))
|
||||||
|
.toList(),
|
||||||
|
groupingEnabled,
|
||||||
|
groupBy.isBlank()
|
||||||
|
? List.of()
|
||||||
|
: Arrays.stream(groupBy.split(",")).map(String::trim).toList(),
|
||||||
|
groupsCollapsed,
|
||||||
|
inactiveGroupHistoryLimit);
|
||||||
|
if (setupId != null && !setupId.isBlank()) {
|
||||||
|
Map<String, String> types = new LinkedHashMap<>();
|
||||||
|
columns.forEach(c -> types.put(c.getId(), c.schemaType()));
|
||||||
|
grid.configureSetups(setupId, setupVersion, types, Map.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResultRow render(T row) {
|
||||||
|
HBox root = new HBox();
|
||||||
|
root.setUserData(row);
|
||||||
|
Map<String, Region> cells = new LinkedHashMap<>();
|
||||||
|
for (var column : columns) {
|
||||||
|
Label label = new Label(Objects.toString(column.getValue(row), ""));
|
||||||
|
root.getChildren().add(label);
|
||||||
|
cells.put(column.getId(), label);
|
||||||
|
}
|
||||||
|
return new ResultRow(root, cells, () -> {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
if (items.get() != null) items.get().removeListener(itemsChanged);
|
||||||
|
items.unbind();
|
||||||
|
source.unbind();
|
||||||
|
if (executor != null) executor.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,9 @@ import lombok.Setter;
|
|||||||
* View's ViewModel. Further names step into the ViewModel of a Complex attribute, and the
|
* 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
|
* 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
|
* 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
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
|
|||||||
@@ -5,8 +5,11 @@ import java.lang.reflect.InvocationTargetException;
|
|||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import javafx.beans.InvalidationListener;
|
||||||
import javafx.beans.property.Property;
|
import javafx.beans.property.Property;
|
||||||
|
import javafx.beans.value.ObservableValue;
|
||||||
import javafx.collections.ObservableList;
|
import javafx.collections.ObservableList;
|
||||||
|
import javafx.fxml.FXMLLoader;
|
||||||
import lombok.AccessLevel;
|
import lombok.AccessLevel;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
@@ -30,48 +33,70 @@ final class DirectBindingApplier {
|
|||||||
* @param context the container that creates a named Converter
|
* @param context the container that creates a named Converter
|
||||||
*/
|
*/
|
||||||
static void apply(Map<String, Object> namespace, Object viewModel, DirectBinding binding,
|
static void apply(Map<String, Object> namespace, Object viewModel, DirectBinding binding,
|
||||||
ApplicationContext context) {
|
ApplicationContext context, ViewLifetime lifetime) {
|
||||||
Object control = namespace.get(binding.getControl());
|
Object control = namespace.get(binding.getControl());
|
||||||
if (control == null) {
|
if (control == null) {
|
||||||
throw new IllegalArgumentException("No control \"" + binding.getControl() + "\"");
|
throw new IllegalArgumentException("No control \"" + binding.getControl() + "\"");
|
||||||
}
|
}
|
||||||
selectComponentViewModel(control, viewModel, binding);
|
selectComponentViewModel(control, viewModel, binding, lifetime);
|
||||||
Resolved resolved = resolve(viewModel, binding.getPath());
|
Resolved resolved = resolve(viewModel, binding.getPath());
|
||||||
if (resolved == null) {
|
if (resolved == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Property<?> controlProperty = controlProperty(control, binding.getProperty());
|
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) {
|
if (resolved.complex) {
|
||||||
switch (binding.getDirection()) {
|
switch (binding.getDirection()) {
|
||||||
case "both" -> alignBothComplex(controlProperty, attribute);
|
case "both" -> alignBothComplex(controlProperty, attribute, lifetime);
|
||||||
case "view" -> alignTowardViewComplex(controlProperty, attribute);
|
case "view" -> alignTowardViewComplex(controlProperty, attribute, lifetime);
|
||||||
case "model" -> alignTowardModelComplex(controlProperty, attribute);
|
case "model" -> alignTowardModelComplex(controlProperty, attribute, lifetime);
|
||||||
default -> throw new IllegalArgumentException("Not a direction: " + binding.getDirection());
|
default -> throw new IllegalArgumentException("Not a direction: " + binding.getDirection());
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (attribute.getValue() instanceof ObservableList<?> values) {
|
if (attribute.getValue() instanceof ObservableList<?> values) {
|
||||||
assignList(controlProperty, values);
|
if ("view".equals(binding.getDirection())) alignTowardView(controlProperty, attribute, lifetime);
|
||||||
|
else assignList(controlProperty, values, lifetime);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String converterName = binding.getConverter();
|
String converterName = binding.getConverter();
|
||||||
if (converterName == null || converterName.isEmpty()) {
|
if (converterName == null || converterName.isEmpty()) {
|
||||||
alignPlain(controlProperty, attribute, binding.getDirection());
|
alignPlain(controlProperty, attribute, binding.getDirection(), lifetime);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Converter converter = converter(context, converterName);
|
Converter converter = converter(context, converterName);
|
||||||
switch (binding.getDirection()) {
|
switch (binding.getDirection()) {
|
||||||
case "both" -> alignConverted(
|
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(
|
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(
|
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());
|
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<String, Object> 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.
|
* Aligns a plain Attribute in the named direction.
|
||||||
*
|
*
|
||||||
@@ -79,11 +104,11 @@ final class DirectBindingApplier {
|
|||||||
* @param attribute the Attribute
|
* @param attribute the Attribute
|
||||||
* @param direction {@code view}, {@code model}, or {@code both}
|
* @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) {
|
switch (direction) {
|
||||||
case "both" -> alignBoth(controlProperty, attribute);
|
case "both" -> alignBoth(controlProperty, attribute, lifetime);
|
||||||
case "view" -> alignTowardView(controlProperty, attribute);
|
case "view" -> alignTowardView(controlProperty, attribute, lifetime);
|
||||||
case "model" -> alignTowardModel(controlProperty, attribute);
|
case "model" -> alignTowardModel(controlProperty, attribute, lifetime);
|
||||||
default -> throw new IllegalArgumentException("Not a direction: " + direction);
|
default -> throw new IllegalArgumentException("Not a direction: " + direction);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,7 +125,10 @@ final class DirectBindingApplier {
|
|||||||
/**
|
/**
|
||||||
* The Attribute the Path names.
|
* 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.
|
* Whether that Attribute is complex.
|
||||||
@@ -153,13 +181,16 @@ final class DirectBindingApplier {
|
|||||||
current = child;
|
current = child;
|
||||||
}
|
}
|
||||||
String last = names[names.length - 1];
|
String last = names[names.length - 1];
|
||||||
Property<?> attribute = propertyOf(current, last);
|
Property<?> property = propertyOf(current, last);
|
||||||
if (attribute == null) {
|
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);
|
throw missing(path);
|
||||||
}
|
}
|
||||||
boolean complex = current instanceof ViewModel stepped && stepped.isComplex(last);
|
return new Resolved(source, false, false, owner, last);
|
||||||
ViewModel owner = current instanceof ViewModel model ? model : null;
|
|
||||||
return new Resolved(attribute, complex, owner, last);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -172,7 +203,7 @@ final class DirectBindingApplier {
|
|||||||
* @param viewModel the ViewModel for this View
|
* @param viewModel the ViewModel for this View
|
||||||
* @param binding the declaration
|
* @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())) {
|
if (!"model".equals(binding.getProperty())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -184,7 +215,7 @@ final class DirectBindingApplier {
|
|||||||
if (instance == null) {
|
if (instance == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ViewModels.of(instance, requested);
|
ViewModels.of(lifetime.models(), instance, requested);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -279,23 +310,24 @@ final class DirectBindingApplier {
|
|||||||
* which is the last name of the Path.
|
* which is the last name of the Path.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static void alignConverted(Property<?> controlProperty, Property<?> attribute, Converter converter,
|
private static void alignConverted(Property<?> controlProperty, ObservableValue<?> source, Converter converter,
|
||||||
ViewModel owner, String sourceName, boolean towardView, boolean towardModel) {
|
ViewModel owner, String sourceName, boolean towardView, boolean towardModel,
|
||||||
|
ViewLifetime lifetime) {
|
||||||
Property<Object> control = (Property<Object>) controlProperty;
|
Property<Object> control = (Property<Object>) controlProperty;
|
||||||
Property<Object> source = (Property<Object>) attribute;
|
|
||||||
Link link = new Link();
|
Link link = new Link();
|
||||||
pushControl(control, source, converter, owner, sourceName, link);
|
pushControl(control, source, converter, owner, sourceName, link);
|
||||||
if (towardView) {
|
if (towardView) {
|
||||||
source.addListener((observable, oldValue, newValue) -> {
|
lifetime.listen(source, (observable, oldValue, newValue) -> {
|
||||||
if (!link.applying) {
|
if (!link.applying) {
|
||||||
pushControl(control, source, converter, owner, sourceName, link);
|
pushControl(control, source, converter, owner, sourceName, link);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (towardModel) {
|
if (towardModel) {
|
||||||
control.addListener((observable, oldValue, newValue) -> {
|
Property<Object> target = (Property<Object>) source;
|
||||||
|
lifetime.listen(control, (observable, oldValue, newValue) -> {
|
||||||
if (!link.applying) {
|
if (!link.applying) {
|
||||||
pushAttribute(control, source, converter, owner, sourceName, link);
|
pushAttribute(control, target, converter, owner, sourceName, link);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -311,7 +343,7 @@ final class DirectBindingApplier {
|
|||||||
* @param source the Attribute name used as the failure source
|
* @param source the Attribute name used as the failure source
|
||||||
* @param link the guard against hearing this write
|
* @param link the guard against hearing this write
|
||||||
*/
|
*/
|
||||||
private static void pushControl(Property<Object> control, Property<Object> attribute, Converter converter,
|
private static void pushControl(Property<Object> control, ObservableValue<?> attribute, Converter converter,
|
||||||
ViewModel owner, String source, Link link) {
|
ViewModel owner, String source, Link link) {
|
||||||
try {
|
try {
|
||||||
Object shown = converter.toControlValue(attribute.getValue());
|
Object shown = converter.toControlValue(attribute.getValue());
|
||||||
@@ -321,8 +353,13 @@ final class DirectBindingApplier {
|
|||||||
} finally {
|
} finally {
|
||||||
link.applying = false;
|
link.applying = false;
|
||||||
}
|
}
|
||||||
|
if (owner != null) {
|
||||||
owner.clearBindingFailure(source);
|
owner.clearBindingFailure(source);
|
||||||
|
}
|
||||||
} catch (RuntimeException failure) {
|
} catch (RuntimeException failure) {
|
||||||
|
if (owner == null) {
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
owner.reportBindingFailure(source, failureText(failure));
|
owner.reportBindingFailure(source, failureText(failure));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -412,21 +449,21 @@ final class DirectBindingApplier {
|
|||||||
* @param attribute the complex Attribute
|
* @param attribute the complex Attribute
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static void alignBothComplex(Property<?> controlProperty, Property<?> attribute) {
|
private static void alignBothComplex(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
|
||||||
Property<Object> control = (Property<Object>) controlProperty;
|
Property<Object> control = (Property<Object>) controlProperty;
|
||||||
Property<Object> source = (Property<Object>) attribute;
|
Property<Object> source = (Property<Object>) attribute;
|
||||||
control.setValue(modelBehind(source.getValue()));
|
control.setValue(modelBehind(source.getValue()));
|
||||||
source.addListener((observable, oldValue, newValue) -> {
|
lifetime.listen(source, (observable, oldValue, newValue) -> {
|
||||||
Object model = modelBehind(newValue);
|
Object model = modelBehind(newValue);
|
||||||
if (control.getValue() != model) {
|
if (control.getValue() != model) {
|
||||||
control.setValue(model);
|
control.setValue(model);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
control.addListener((observable, oldValue, newValue) -> {
|
lifetime.listen(control, (observable, oldValue, newValue) -> {
|
||||||
if (modelBehind(source.getValue()) == newValue) {
|
if (modelBehind(source.getValue()) == newValue) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
source.setValue(newValue == null ? null : ViewModels.of(newValue));
|
source.setValue(newValue == null ? null : ViewModels.of(lifetime.models(), newValue, null));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -437,11 +474,11 @@ final class DirectBindingApplier {
|
|||||||
* @param attribute the complex Attribute
|
* @param attribute the complex Attribute
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static void alignTowardViewComplex(Property<?> controlProperty, Property<?> attribute) {
|
private static void alignTowardViewComplex(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
|
||||||
Property<Object> control = (Property<Object>) controlProperty;
|
Property<Object> control = (Property<Object>) controlProperty;
|
||||||
Property<Object> source = (Property<Object>) attribute;
|
Property<Object> source = (Property<Object>) attribute;
|
||||||
control.setValue(modelBehind(source.getValue()));
|
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 +488,15 @@ final class DirectBindingApplier {
|
|||||||
* @param attribute the complex Attribute
|
* @param attribute the complex Attribute
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static void alignTowardModelComplex(Property<?> controlProperty, Property<?> attribute) {
|
private static void alignTowardModelComplex(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
|
||||||
Property<Object> control = (Property<Object>) controlProperty;
|
Property<Object> control = (Property<Object>) controlProperty;
|
||||||
Property<Object> source = (Property<Object>) attribute;
|
Property<Object> source = (Property<Object>) attribute;
|
||||||
control.setValue(modelBehind(source.getValue()));
|
control.setValue(modelBehind(source.getValue()));
|
||||||
control.addListener((observable, oldValue, newValue) -> {
|
lifetime.listen(control, (observable, oldValue, newValue) -> {
|
||||||
if (modelBehind(source.getValue()) == newValue) {
|
if (modelBehind(source.getValue()) == newValue) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
source.setValue(newValue == null ? null : ViewModels.of(newValue));
|
source.setValue(newValue == null ? null : ViewModels.of(lifetime.models(), newValue, null));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -483,8 +520,13 @@ final class DirectBindingApplier {
|
|||||||
* @param values the list the ViewModel and the Model share
|
* @param values the list the ViewModel and the Model share
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static void assignList(Property<?> controlProperty, ObservableList<?> values) {
|
private static void assignList(Property<?> controlProperty, ObservableList<?> values, ViewLifetime lifetime) {
|
||||||
((Property<Object>) controlProperty).setValue(values);
|
Property<Object> target = (Property<Object>) controlProperty;
|
||||||
|
Object previous = target.getValue();
|
||||||
|
target.setValue(values);
|
||||||
|
lifetime.own(() -> {
|
||||||
|
if (target.getValue() == values) target.setValue(previous);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -494,8 +536,11 @@ final class DirectBindingApplier {
|
|||||||
* @param attribute the Attribute
|
* @param attribute the Attribute
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static void alignBoth(Property<?> controlProperty, Property<?> attribute) {
|
private static void alignBoth(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
|
||||||
((Property<Object>) controlProperty).bindBidirectional((Property<Object>) attribute);
|
Property<Object> control = (Property<Object>) controlProperty;
|
||||||
|
Property<Object> source = (Property<Object>) attribute;
|
||||||
|
control.bindBidirectional(source);
|
||||||
|
lifetime.own(() -> control.unbindBidirectional(source));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -505,11 +550,20 @@ final class DirectBindingApplier {
|
|||||||
* @param attribute the Attribute
|
* @param attribute the Attribute
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static void alignTowardView(Property<?> controlProperty, Property<?> attribute) {
|
private static void alignTowardView(Property<?> controlProperty, ObservableValue<?> attribute,
|
||||||
|
ViewLifetime lifetime) {
|
||||||
Property<Object> control = (Property<Object>) controlProperty;
|
Property<Object> control = (Property<Object>) controlProperty;
|
||||||
Property<Object> source = (Property<Object>) attribute;
|
Object previous = control.getValue();
|
||||||
control.setValue(source.getValue());
|
control.setValue(attribute.getValue());
|
||||||
source.addListener((observable, oldValue, newValue) -> control.setValue(newValue));
|
// ChangeListeners may suppress a new list whose elements equal the previous list.
|
||||||
|
InvalidationListener follow = ignored -> control.setValue(attribute.getValue());
|
||||||
|
attribute.addListener(follow);
|
||||||
|
lifetime.own(() -> {
|
||||||
|
attribute.removeListener(follow);
|
||||||
|
if ((previous instanceof ObservableList<?> || control.getValue() instanceof ObservableList<?>)
|
||||||
|
&& control.getValue() == attribute.getValue())
|
||||||
|
control.setValue(previous);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -519,10 +573,10 @@ final class DirectBindingApplier {
|
|||||||
* @param attribute the Attribute
|
* @param attribute the Attribute
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static void alignTowardModel(Property<?> controlProperty, Property<?> attribute) {
|
private static void alignTowardModel(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
|
||||||
Property<Object> control = (Property<Object>) controlProperty;
|
Property<Object> control = (Property<Object>) controlProperty;
|
||||||
Property<Object> target = (Property<Object>) attribute;
|
Property<Object> target = (Property<Object>) attribute;
|
||||||
control.setValue(target.getValue());
|
control.setValue(target.getValue());
|
||||||
control.addListener((observable, oldValue, newValue) -> target.setValue(newValue));
|
lifetime.listen(control, (observable, oldValue, newValue) -> target.setValue(newValue));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<List<String>> 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<String> 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) { }
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.grid.ColumnWidth;
|
||||||
|
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
import javafx.util.StringConverter;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Keyboard-operable equivalents of header resizing, reordering and grouping. */
|
||||||
|
final class GridColumnSettings<K, T> {
|
||||||
|
private final Dialog<Void> dialog = new Dialog<>();
|
||||||
|
|
||||||
|
GridColumnSettings(DataGrid<K, T> grid, TableResults<K, T> renderer) {
|
||||||
|
dialog.setTitle("Column settings");
|
||||||
|
if (grid.getScene() != null) dialog.initOwner(grid.getScene().getWindow());
|
||||||
|
dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
|
||||||
|
ComboBox<ResultColumn> column = new ComboBox<>();
|
||||||
|
column.getItems().setAll(renderer.definitions());
|
||||||
|
column.setConverter(
|
||||||
|
new StringConverter<>() {
|
||||||
|
public String toString(ResultColumn c) {
|
||||||
|
return c == null ? "" : c.header();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResultColumn fromString(String text) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
column.setAccessibleText("Column");
|
||||||
|
column.setId("gridSettingsColumn");
|
||||||
|
Spinner<Double> width = new Spinner<>();
|
||||||
|
width.setEditable(true);
|
||||||
|
width.setAccessibleText("Column width");
|
||||||
|
Button apply = new Button("Apply width"),
|
||||||
|
left = new Button("Move left"),
|
||||||
|
right = new Button("Move right"),
|
||||||
|
group = new Button("Group by column"),
|
||||||
|
earlier = new Button("Earlier grouping level"),
|
||||||
|
later = new Button("Later grouping level"),
|
||||||
|
remove = new Button("Remove grouping");
|
||||||
|
Label description = new Label(), message = new Label();
|
||||||
|
message.setWrapText(true);
|
||||||
|
Runnable update =
|
||||||
|
() -> {
|
||||||
|
var c = column.getValue();
|
||||||
|
if (c == null) return;
|
||||||
|
width.setValueFactory(
|
||||||
|
new SpinnerValueFactory.DoubleSpinnerValueFactory(
|
||||||
|
c.minimumWidth(),
|
||||||
|
c.maximumWidth(),
|
||||||
|
renderer.width(c.id()),
|
||||||
|
10));
|
||||||
|
int index = renderer.columnOrder().indexOf(c.id()),
|
||||||
|
level = renderer.groupingColumns().indexOf(c.id());
|
||||||
|
description.setText(
|
||||||
|
"Position "
|
||||||
|
+ (index + 1)
|
||||||
|
+ (c.fixedPosition() >= 0 ? " (fixed)" : "")
|
||||||
|
+ " · "
|
||||||
|
+ c.minimumWidth()
|
||||||
|
+ "–"
|
||||||
|
+ c.maximumWidth()
|
||||||
|
+ " px");
|
||||||
|
left.setDisable(!canMove(renderer, c.id(), index - 1));
|
||||||
|
right.setDisable(!canMove(renderer, c.id(), index + 1));
|
||||||
|
group.setDisable(!renderer.canGroup(c.id()) || level >= 0);
|
||||||
|
earlier.setDisable(!renderer.groupingEnabled() || level <= 0);
|
||||||
|
later.setDisable(
|
||||||
|
!renderer.groupingEnabled()
|
||||||
|
|| level < 0
|
||||||
|
|| level == renderer.groupingColumns().size() - 1);
|
||||||
|
remove.setDisable(!renderer.groupingEnabled() || level < 0);
|
||||||
|
};
|
||||||
|
java.util.function.Consumer<Runnable> perform =
|
||||||
|
action -> {
|
||||||
|
try {
|
||||||
|
action.run();
|
||||||
|
message.setText("Applied.");
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
message.setText(failure.getMessage());
|
||||||
|
}
|
||||||
|
update.run();
|
||||||
|
};
|
||||||
|
left.setOnAction(
|
||||||
|
e -> perform.accept(() -> move(grid, renderer, column.getValue().id(), -1)));
|
||||||
|
right.setOnAction(
|
||||||
|
e -> perform.accept(() -> move(grid, renderer, column.getValue().id(), 1)));
|
||||||
|
apply.setOnAction(e ->
|
||||||
|
perform.accept(() ->
|
||||||
|
grid.setColumnWidth(
|
||||||
|
column.getValue().id(),
|
||||||
|
new ColumnWidth.Explicit(
|
||||||
|
Double.parseDouble(width.getEditor().getText())))));
|
||||||
|
group.setOnAction(e ->
|
||||||
|
perform.accept(() -> {
|
||||||
|
var ids = new ArrayList<>(renderer.groupingColumns());
|
||||||
|
ids.add(column.getValue().id());
|
||||||
|
grid.setGroupingColumns(ids);
|
||||||
|
}));
|
||||||
|
remove.setOnAction(e ->
|
||||||
|
perform.accept(() ->
|
||||||
|
grid.setGroupingColumns(
|
||||||
|
renderer.groupingColumns().stream()
|
||||||
|
.filter(id -> !id.equals(column.getValue().id()))
|
||||||
|
.toList())));
|
||||||
|
earlier.setOnAction(
|
||||||
|
e -> perform.accept(() -> moveGroup(grid, renderer, column.getValue().id(), -1)));
|
||||||
|
later.setOnAction(
|
||||||
|
e -> perform.accept(() -> moveGroup(grid, renderer, column.getValue().id(), 1)));
|
||||||
|
VBox content =
|
||||||
|
new VBox(
|
||||||
|
10,
|
||||||
|
new Label("Column"),
|
||||||
|
column,
|
||||||
|
description,
|
||||||
|
new HBox(8, left, right),
|
||||||
|
new Label("Width in pixels"),
|
||||||
|
new HBox(8, width, apply),
|
||||||
|
new HBox(8, group, remove),
|
||||||
|
new HBox(8, earlier, later),
|
||||||
|
message);
|
||||||
|
dialog.getDialogPane().setContent(content);
|
||||||
|
column.valueProperty().addListener((o, b, a) -> update.run());
|
||||||
|
column.getSelectionModel().selectFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
void show() {
|
||||||
|
dialog.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
dialog.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean canMove(TableResults<?, ?> renderer, String id, int index) {
|
||||||
|
var order = new ArrayList<>(renderer.columnOrder());
|
||||||
|
if (index < 0 || index >= order.size()) return false;
|
||||||
|
order.remove(id);
|
||||||
|
order.add(index, id);
|
||||||
|
return renderer.definitions().stream()
|
||||||
|
.allMatch(
|
||||||
|
c -> c.fixedPosition() < 0 || order.get(c.fixedPosition()).equals(c.id()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <K, T> void move(
|
||||||
|
DataGrid<K, T> grid, TableResults<K, T> renderer, String id, int delta) {
|
||||||
|
var order = new ArrayList<>(renderer.columnOrder());
|
||||||
|
int index = order.indexOf(id);
|
||||||
|
order.remove(id);
|
||||||
|
order.add(index + delta, id);
|
||||||
|
grid.setColumnOrder(order);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <K, T> void moveGroup(
|
||||||
|
DataGrid<K, T> grid, TableResults<K, T> renderer, String id, int delta) {
|
||||||
|
var order = new ArrayList<>(renderer.groupingColumns());
|
||||||
|
int index = order.indexOf(id);
|
||||||
|
order.remove(id);
|
||||||
|
order.add(index + delta, id);
|
||||||
|
grid.setGroupingColumns(order);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.value.ChangeListener;
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
/** One FX view's opt-in storage adapter. Closing it never discards accepted application saves. */
|
||||||
|
public final class GridPersistenceAttachment<K, T> implements AutoCloseable {
|
||||||
|
private final DataGrid<K, T> grid;
|
||||||
|
private final GridApplicationConfiguration application;
|
||||||
|
private final GridSetupStore.Key key;
|
||||||
|
private final Label status = new Label("Grid settings not loaded");
|
||||||
|
private final Button retry = new Button("Retry settings"),
|
||||||
|
reload = new Button("Reload saved setup"),
|
||||||
|
reset = new Button("Reset setup"),
|
||||||
|
overwrite = new Button("Overwrite saved setup");
|
||||||
|
private final VBox feedback = new VBox(4);
|
||||||
|
private final HBox recovery = new HBox(8);
|
||||||
|
private final List<MenuItem> menu;
|
||||||
|
private final ChangeListener<Number> commits;
|
||||||
|
private final AutoCloseable observation;
|
||||||
|
private final CompletableFuture<Void> ready = new CompletableFuture<>();
|
||||||
|
private boolean initialized, closed, restoreFailed;
|
||||||
|
private long generation, ownSave = -1, operationGeneration = -1;
|
||||||
|
private Throwable restoreError;
|
||||||
|
|
||||||
|
GridPersistenceAttachment(
|
||||||
|
DataGrid<K, T> grid, GridApplicationConfiguration application, GridSetupStore.Key key) {
|
||||||
|
this.grid = grid;
|
||||||
|
this.application = application;
|
||||||
|
this.key = key;
|
||||||
|
status.setWrapText(true);
|
||||||
|
status.getStyleClass().add("grid-persistence-status");
|
||||||
|
status.setAccessibleText("Grid settings status");
|
||||||
|
recovery.getChildren().addAll(retry, reload, reset, overwrite);
|
||||||
|
recovery.setVisible(false);
|
||||||
|
recovery.setManaged(false);
|
||||||
|
feedback.getChildren().addAll(status, recovery);
|
||||||
|
MenuItem reloadItem = new MenuItem("Reload saved setup"),
|
||||||
|
resetItem = new MenuItem("Reset setup");
|
||||||
|
reloadItem.setOnAction(e -> loadAsync());
|
||||||
|
resetItem.setOnAction(e -> resetAsync());
|
||||||
|
menu = List.of(reloadItem, resetItem);
|
||||||
|
grid.addPersistenceControls(feedback, menu);
|
||||||
|
retry.setOnAction(e -> {
|
||||||
|
if (!initialized || restoreFailed) loadAsync();
|
||||||
|
else application.retryAsync(key);
|
||||||
|
});
|
||||||
|
reload.setOnAction(e -> loadAsync());
|
||||||
|
reset.setOnAction(e -> resetAsync());
|
||||||
|
overwrite.setOnAction(e -> overwriteAsync());
|
||||||
|
commits =
|
||||||
|
(o, b, a) -> {
|
||||||
|
if (initialized && !closed) {
|
||||||
|
try {
|
||||||
|
ownSave = application.accept(key, grid.snapshotSetup(), this);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
fail(new CompletableFuture<>(), failure);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
grid.committedRevisionProperty().addListener(commits);
|
||||||
|
observation =
|
||||||
|
application.observe(
|
||||||
|
key,
|
||||||
|
state ->
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
if (!closed) show(state);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> ready() {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> loadAsync() {
|
||||||
|
requireFx();
|
||||||
|
check();
|
||||||
|
long token = ++generation;
|
||||||
|
long discarded = ownSave;
|
||||||
|
restoreFailed = false;
|
||||||
|
restoreError = null;
|
||||||
|
CompletableFuture<Void> answer = new CompletableFuture<>();
|
||||||
|
CompletionStage<GridApplicationConfiguration.Loaded> loading;
|
||||||
|
try {
|
||||||
|
loading = application.loadAsync(key);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
fail(answer, failure);
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
loading.whenComplete((loaded, error) ->
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
if (!live(token)) {
|
||||||
|
answer.completeExceptionally(
|
||||||
|
new CancellationException("Attachment closed or superseded"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (error != null) {
|
||||||
|
fail(answer, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
GridSetup setup =
|
||||||
|
loaded.stored().setup() == null
|
||||||
|
? grid.developerDefaults()
|
||||||
|
: loaded.stored().setup();
|
||||||
|
CompletionStage<Void> restore = grid.restoreSetupAsync(setup);
|
||||||
|
operationGeneration = grid.stateProperty().get().generation();
|
||||||
|
restore.whenComplete((ok, failure) ->
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
if (!live(token)) {
|
||||||
|
answer.completeExceptionally(
|
||||||
|
new CancellationException(
|
||||||
|
"Attachment closed or superseded"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (failure != null) {
|
||||||
|
fail(answer, failure);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
application.adopt(loaded, discarded);
|
||||||
|
} catch (RuntimeException adoptionFailure) {
|
||||||
|
fail(answer, adoptionFailure);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
initialized = true;
|
||||||
|
restoreFailed = false;
|
||||||
|
restoreError = null;
|
||||||
|
show(application.state(key));
|
||||||
|
ready.complete(null);
|
||||||
|
answer.complete(null);
|
||||||
|
}));
|
||||||
|
}));
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> resetAsync() {
|
||||||
|
requireFx();
|
||||||
|
check();
|
||||||
|
long token = ++generation;
|
||||||
|
boolean recover = !initialized || restoreFailed;
|
||||||
|
CompletableFuture<Void> answer = new CompletableFuture<>();
|
||||||
|
CompletionStage<Void> restore = grid.restoreSetupAsync(grid.developerDefaults());
|
||||||
|
operationGeneration = grid.stateProperty().get().generation();
|
||||||
|
restore.whenComplete((ok, error) ->
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
if (!live(token)) {
|
||||||
|
answer.completeExceptionally(
|
||||||
|
new CancellationException("Attachment closed or superseded"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (error != null) {
|
||||||
|
fail(answer, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
initialized = true;
|
||||||
|
restoreFailed = false;
|
||||||
|
restoreError = null;
|
||||||
|
try {
|
||||||
|
ownSave =
|
||||||
|
recover
|
||||||
|
? application.acceptOverwrite(
|
||||||
|
key, grid.snapshotSetup(), this)
|
||||||
|
: application.accept(key, grid.snapshotSetup(), this);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
fail(answer, failure);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ready.complete(null);
|
||||||
|
answer.complete(null);
|
||||||
|
}));
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> overwriteAsync() {
|
||||||
|
requireFx();
|
||||||
|
check();
|
||||||
|
if (!initialized)
|
||||||
|
throw new IllegalStateException("Initialize or reset the view before saving");
|
||||||
|
ownSave = application.acceptOverwrite(key, grid.snapshotSetup(), this);
|
||||||
|
return application.retryAsync(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fail(CompletableFuture<Void> future, Throwable failure) {
|
||||||
|
restoreFailed = true;
|
||||||
|
restoreError = unwrap(failure);
|
||||||
|
status.setText("Grid settings unavailable: " + restoreError.getMessage());
|
||||||
|
recovery.setVisible(true);
|
||||||
|
recovery.setManaged(true);
|
||||||
|
overwrite.setDisable(!initialized);
|
||||||
|
future.completeExceptionally(restoreError);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void show(GridApplicationConfiguration.State state) {
|
||||||
|
if (restoreFailed) {
|
||||||
|
status.setText("Grid settings unavailable: " + restoreError.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
status.setText(
|
||||||
|
switch (state.phase()) {
|
||||||
|
case IDLE -> "Grid settings not loaded";
|
||||||
|
case LOADING -> "Loading grid settings…";
|
||||||
|
case PENDING -> "Grid settings have unsaved changes";
|
||||||
|
case SAVING -> "Saving grid settings…";
|
||||||
|
case SAVED -> "Grid settings saved";
|
||||||
|
case CLOSED -> "Grid settings closed";
|
||||||
|
case ERROR, CONFLICT -> "Grid settings: " + state.error().getMessage();
|
||||||
|
});
|
||||||
|
boolean failed =
|
||||||
|
state.phase() == GridApplicationConfiguration.Phase.ERROR
|
||||||
|
|| state.phase() == GridApplicationConfiguration.Phase.CONFLICT;
|
||||||
|
recovery.setVisible(failed);
|
||||||
|
recovery.setManaged(failed);
|
||||||
|
overwrite.setDisable(!initialized);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean live(long token) {
|
||||||
|
return !closed && generation == token;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void check() {
|
||||||
|
if (closed) throw new IllegalStateException("Attachment is closed");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void requireFx() {
|
||||||
|
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("Use FX thread");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Throwable unwrap(Throwable failure) {
|
||||||
|
while ((failure instanceof CompletionException || failure instanceof ExecutionException)
|
||||||
|
&& failure.getCause() != null) failure = failure.getCause();
|
||||||
|
return failure;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
requireFx();
|
||||||
|
if (closed) return;
|
||||||
|
closed = true;
|
||||||
|
generation++;
|
||||||
|
grid.committedRevisionProperty().removeListener(commits);
|
||||||
|
try {
|
||||||
|
observation.close();
|
||||||
|
} catch (Exception failure) {
|
||||||
|
throw new IllegalStateException(failure);
|
||||||
|
}
|
||||||
|
grid.cancelOwnedRestore(operationGeneration);
|
||||||
|
grid.removePersistenceControls(feedback, menu);
|
||||||
|
grid.detached(this);
|
||||||
|
if (!ready.isDone())
|
||||||
|
ready.completeExceptionally(new CancellationException("Attachment closed"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,7 +18,7 @@ import java.util.Set;
|
|||||||
final class LoadSession {
|
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<Deque<LoadSession>> STACK = new ThreadLocal<>();
|
private static final ThreadLocal<Deque<LoadSession>> STACK = new ThreadLocal<>();
|
||||||
|
|
||||||
@@ -32,25 +32,33 @@ final class LoadSession {
|
|||||||
*/
|
*/
|
||||||
private final Set<Class<?>> built = new HashSet<>();
|
private final Set<Class<?>> 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<LoadSession> 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.
|
* Prevents instantiation from outside this class.
|
||||||
*/
|
*/
|
||||||
private LoadSession() {
|
private LoadSession() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Starts a session on this thread.
|
|
||||||
*
|
|
||||||
* @return the open session
|
|
||||||
*/
|
|
||||||
static LoadSession open() {
|
|
||||||
Deque<LoadSession> stack = new ArrayDeque<>();
|
|
||||||
LoadSession session = new LoadSession();
|
|
||||||
stack.push(session);
|
|
||||||
STACK.set(stack);
|
|
||||||
return session;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Opens a nested session for a Component document.
|
* Opens a nested session for a Component document.
|
||||||
* <p>
|
* <p>
|
||||||
@@ -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.
|
* Registers a binding list created while a session is open.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import lombok.RequiredArgsConstructor;
|
|||||||
* The scene-graph root and ViewModel produced by loading a View for a Model instance.
|
* The scene-graph root and ViewModel produced by loading a View for a Model instance.
|
||||||
*/
|
*/
|
||||||
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
||||||
public final class LoadedView {
|
public final class LoadedView implements AutoCloseable {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The scene-graph root of the loaded View.
|
* The scene-graph root of the loaded View.
|
||||||
@@ -23,6 +23,17 @@ public final class LoadedView {
|
|||||||
*/
|
*/
|
||||||
private final Object viewModel;
|
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.
|
* Returns the ViewModel the View is bound to.
|
||||||
* <p>
|
* <p>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package de.neitzel.fx.view;
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
import javafx.beans.property.Property;
|
import javafx.beans.property.Property;
|
||||||
|
import javafx.beans.value.ObservableValue;
|
||||||
|
|
||||||
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.InvocationTargetException;
|
||||||
import java.lang.reflect.Method;
|
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
|
* @return the property, or {@code null} when {@code bean} declares none of that name
|
||||||
*/
|
*/
|
||||||
static Property<?> get(Object bean, String 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";
|
String methodName = name + "Property";
|
||||||
try {
|
try {
|
||||||
Method method = bean.getClass().getMethod(methodName);
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
Object value = method.invoke(bean);
|
return method.invoke(bean);
|
||||||
if (value instanceof Property<?> property) {
|
|
||||||
return property;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
} catch (NoSuchMethodException notDeclared) {
|
} catch (NoSuchMethodException notDeclared) {
|
||||||
return null;
|
return null;
|
||||||
} catch (IllegalAccessException | InvocationTargetException failure) {
|
} catch (IllegalAccessException | InvocationTargetException failure) {
|
||||||
|
|||||||
@@ -2,11 +2,12 @@ package de.neitzel.fx.view;
|
|||||||
|
|
||||||
import de.neitzel.injection.ApplicationContext;
|
import de.neitzel.injection.ApplicationContext;
|
||||||
import javafx.beans.property.Property;
|
import javafx.beans.property.Property;
|
||||||
import javafx.collections.ListChangeListener;
|
|
||||||
import javafx.collections.ObservableList;
|
import javafx.collections.ObservableList;
|
||||||
import javafx.scene.Node;
|
import javafx.scene.Node;
|
||||||
import javafx.scene.layout.Pane;
|
import javafx.scene.layout.Pane;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -34,7 +35,7 @@ final class RepeatApplier {
|
|||||||
* @param context the container that creates each Component
|
* @param context the container that creates each Component
|
||||||
*/
|
*/
|
||||||
static void apply(Map<String, Object> namespace, Object viewModel, Repeat repeat,
|
static void apply(Map<String, Object> namespace, Object viewModel, Repeat repeat,
|
||||||
ApplicationContext context) {
|
ApplicationContext context, ViewLifetime lifetime) {
|
||||||
Object named = namespace.get(repeat.getPane());
|
Object named = namespace.get(repeat.getPane());
|
||||||
if (!(named instanceof Pane pane)) {
|
if (!(named instanceof Pane pane)) {
|
||||||
throw new IllegalArgumentException("No pane \"" + repeat.getPane() + "\"");
|
throw new IllegalArgumentException("No pane \"" + repeat.getPane() + "\"");
|
||||||
@@ -44,10 +45,15 @@ final class RepeatApplier {
|
|||||||
throw new IllegalArgumentException("No collection \"" + repeat.getCollection() + "\"");
|
throw new IllegalArgumentException("No collection \"" + repeat.getCollection() + "\"");
|
||||||
}
|
}
|
||||||
Class<?> type = componentType(repeat.getComponent());
|
Class<?> type = componentType(repeat.getComponent());
|
||||||
|
int offset = pane.getChildren().size();
|
||||||
|
List<RepeatedChild> children = new ArrayList<>();
|
||||||
|
lifetime.own(() -> pane.getChildren().removeAll(children.stream().map(RepeatedChild::node).toList()));
|
||||||
for (Object element : values) {
|
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
|
* @param values the collection
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@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<RepeatedChild> children) {
|
||||||
ObservableList<Object> elements = (ObservableList<Object>) values;
|
ObservableList<Object> elements = (ObservableList<Object>) values;
|
||||||
elements.addListener((ListChangeListener<Object>) change -> {
|
lifetime.listen(elements, change -> {
|
||||||
while (change.next()) {
|
while (change.next()) {
|
||||||
if (change.wasPermutated() || change.wasUpdated()) {
|
if (change.wasPermutated() || change.wasUpdated()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (change.getRemovedSize() > 0) {
|
for (int removed = 0; removed < change.getRemovedSize(); removed++) {
|
||||||
pane.getChildren().remove(change.getFrom(), change.getFrom() + change.getRemovedSize());
|
RepeatedChild child = children.remove(change.getFrom());
|
||||||
|
pane.getChildren().remove(child.node());
|
||||||
|
child.lifetime().close();
|
||||||
}
|
}
|
||||||
for (int index = 0; index < change.getAddedSize(); index++) {
|
for (int index = 0; index < change.getAddedSize(); index++) {
|
||||||
pane.getChildren().add(
|
RepeatedChild child = child(type, context, change.getAddedSubList().get(index), lifetime);
|
||||||
change.getFrom() + index,
|
int position = change.getFrom() + index;
|
||||||
child(type, context, change.getAddedSubList().get(index)));
|
children.add(position, child);
|
||||||
|
pane.getChildren().add(offset + position, child.node());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -103,11 +113,20 @@ final class RepeatApplier {
|
|||||||
* @param element the Model instance
|
* @param element the Model instance
|
||||||
* @return the loaded Component
|
* @return the loaded Component
|
||||||
*/
|
*/
|
||||||
private static Node child(Class<?> type, ApplicationContext context, Object element) {
|
private static RepeatedChild child(Class<?> type, ApplicationContext context, Object element,
|
||||||
Object component = Components.fresh(type, context);
|
ViewLifetime owner) {
|
||||||
Components.setModel(component, element);
|
ViewLifetime lifetime = owner.child();
|
||||||
return (Node) component;
|
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.
|
* Returns the Component class named by the repeat.
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import javafx.scene.Group;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
import javafx.scene.shape.Line;
|
||||||
|
|
||||||
|
/** Row decoration that preserves field borders, component identity and hit testing. */
|
||||||
|
final class ResultColumnSeparators extends Group {
|
||||||
|
ResultColumnSeparators(HBox row, int columns) {
|
||||||
|
setManaged(false);
|
||||||
|
setMouseTransparent(true);
|
||||||
|
for (int i = 1; i < columns; i++) {
|
||||||
|
var line = new Line();
|
||||||
|
line.getStyleClass().add("column-separator-line");
|
||||||
|
line.endYProperty().bind(row.heightProperty());
|
||||||
|
getChildren().add(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static ResultColumnSeparators forHeader(HBox cell) {
|
||||||
|
var decoration = new ResultColumnSeparators(cell, 2);
|
||||||
|
var line = (Line) decoration.getChildren().getFirst();
|
||||||
|
line.startXProperty().bind(cell.widthProperty().subtract(.5));
|
||||||
|
line.endXProperty().bind(line.startXProperty());
|
||||||
|
return decoration;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean matchesColumnCount(int columns) {
|
||||||
|
return getChildren().size() == Math.max(0, columns - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void position(double[] widths) {
|
||||||
|
double x = 0;
|
||||||
|
for (int i = 0; i < getChildren().size(); i++) {
|
||||||
|
x += widths[i];
|
||||||
|
var line = (Line) getChildren().get(i);
|
||||||
|
line.setStartX(x - .5);
|
||||||
|
line.setEndX(x - .5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.grid.ColumnWidth;
|
||||||
|
|
||||||
|
import javafx.animation.AnimationTimer;
|
||||||
|
import javafx.event.EventHandler;
|
||||||
|
import javafx.scene.*;
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.input.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Native gesture routing for result-mode headers only. No source/query or storage ownership. */
|
||||||
|
final class ResultHeaderGestures implements AutoCloseable {
|
||||||
|
private static final DataFormat FORMAT = new DataFormat("application/x-neitzel-grid-header");
|
||||||
|
private final String owner = UUID.randomUUID().toString();
|
||||||
|
private final TableResults<?, ?> renderer;
|
||||||
|
private final HBox header;
|
||||||
|
private final VBox body;
|
||||||
|
private Runnable cancelResize;
|
||||||
|
private double pointerX, pointerY;
|
||||||
|
private AnimationTimer scrolling;
|
||||||
|
private Runnable finishDrag;
|
||||||
|
private long dragGeneration;
|
||||||
|
|
||||||
|
ResultHeaderGestures(TableResults<?, ?> renderer, HBox header, VBox body) {
|
||||||
|
this.renderer = renderer;
|
||||||
|
this.header = header;
|
||||||
|
this.body = body;
|
||||||
|
}
|
||||||
|
|
||||||
|
void header(HBox cell, Label label, Region handle, String id, Runnable sort) {
|
||||||
|
boolean[] dragged = {false};
|
||||||
|
cell.setOnMousePressed(e -> {
|
||||||
|
if (e.getButton() == MouseButton.PRIMARY) dragged[0] = false;
|
||||||
|
});
|
||||||
|
cell.setOnMouseClicked(e -> {
|
||||||
|
if (e.getButton() == MouseButton.PRIMARY && !dragged[0]) sort.run();
|
||||||
|
});
|
||||||
|
label.setOnDragDetected(e -> {
|
||||||
|
if (!e.isPrimaryButtonDown() && e.getButton() != MouseButton.PRIMARY) return;
|
||||||
|
dragged[0] = true;
|
||||||
|
start(label, "column", id);
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
cell.setOnDragOver(e -> {
|
||||||
|
var payload = payload(e.getDragboard());
|
||||||
|
if (payload == null) return;
|
||||||
|
pointerX = e.getSceneX();
|
||||||
|
pointerY = e.getSceneY();
|
||||||
|
clearTargets();
|
||||||
|
int index =
|
||||||
|
insertion(
|
||||||
|
renderer.columnOrder(), payload[1], id, e.getX() > cell.getWidth() / 2);
|
||||||
|
var order = move(renderer.columnOrder(), payload[1], index);
|
||||||
|
boolean valid = payload[0].equals("column") && valid(order);
|
||||||
|
cell.getStyleClass()
|
||||||
|
.add(
|
||||||
|
valid
|
||||||
|
? (e.getX() > cell.getWidth() / 2
|
||||||
|
? "drop-after"
|
||||||
|
: "drop-before")
|
||||||
|
: "drop-invalid");
|
||||||
|
if (valid) e.acceptTransferModes(TransferMode.MOVE);
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
cell.setOnDragDropped(e -> {
|
||||||
|
var payload = payload(e.getDragboard());
|
||||||
|
boolean success = false;
|
||||||
|
if (payload != null && payload[0].equals("column")) {
|
||||||
|
int index =
|
||||||
|
insertion(
|
||||||
|
renderer.columnOrder(),
|
||||||
|
payload[1],
|
||||||
|
id,
|
||||||
|
e.getX() > cell.getWidth() / 2);
|
||||||
|
var order = move(renderer.columnOrder(), payload[1], index);
|
||||||
|
if (valid(order)) {
|
||||||
|
renderer.setColumnOrder(order);
|
||||||
|
success = true;
|
||||||
|
} else renderer.message("Fixed column cannot be displaced.");
|
||||||
|
}
|
||||||
|
clearTargets();
|
||||||
|
e.setDropCompleted(success);
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
handle.setOnMouseClicked(MouseEvent::consume);
|
||||||
|
handle.setOnDragDetected(MouseEvent::consume);
|
||||||
|
handle.setOnMousePressed(e -> {
|
||||||
|
if (e.getButton() != MouseButton.PRIMARY) return;
|
||||||
|
dragged[0] = true;
|
||||||
|
if (cancelResize != null) cancelResize.run();
|
||||||
|
ColumnWidth original = renderer.columnWidths().get(id);
|
||||||
|
double start = e.getScreenX(), width = renderer.width(id);
|
||||||
|
var definition =
|
||||||
|
renderer.definitions().stream()
|
||||||
|
.filter(c -> c.id().equals(id))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow();
|
||||||
|
Scene scene = handle.getScene();
|
||||||
|
EventHandler<KeyEvent> escape =
|
||||||
|
key -> {
|
||||||
|
if (key.getCode() == KeyCode.ESCAPE && cancelResize != null) {
|
||||||
|
cancelResize.run();
|
||||||
|
key.consume();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
double[] preview = {width};
|
||||||
|
boolean[] active = {true};
|
||||||
|
javafx.beans.value.ChangeListener<Boolean> focus =
|
||||||
|
(o, b, focused) -> {
|
||||||
|
if (!focused && cancelResize != null) cancelResize.run();
|
||||||
|
};
|
||||||
|
var window = scene.getWindow();
|
||||||
|
Runnable cleanup =
|
||||||
|
() -> {
|
||||||
|
active[0] = false;
|
||||||
|
scene.removeEventFilter(KeyEvent.KEY_PRESSED, escape);
|
||||||
|
if (window != null) window.focusedProperty().removeListener(focus);
|
||||||
|
handle.setOnMouseDragged(null);
|
||||||
|
handle.setOnMouseReleased(null);
|
||||||
|
cancelResize = null;
|
||||||
|
};
|
||||||
|
cancelResize =
|
||||||
|
() -> {
|
||||||
|
renderer.previewWidth(id, original);
|
||||||
|
cleanup.run();
|
||||||
|
renderer.message("Resize cancelled.");
|
||||||
|
};
|
||||||
|
scene.addEventFilter(KeyEvent.KEY_PRESSED, escape);
|
||||||
|
if (window != null) window.focusedProperty().addListener(focus);
|
||||||
|
handle.setOnMouseDragged(event -> {
|
||||||
|
if (active[0]) {
|
||||||
|
preview[0] =
|
||||||
|
Math.clamp(
|
||||||
|
width + event.getScreenX() - start,
|
||||||
|
definition.minimumWidth(),
|
||||||
|
definition.maximumWidth());
|
||||||
|
renderer.previewWidth(id, new ColumnWidth.Explicit(preview[0]));
|
||||||
|
}
|
||||||
|
event.consume();
|
||||||
|
});
|
||||||
|
handle.setOnMouseReleased(event -> {
|
||||||
|
if (active[0]) {
|
||||||
|
cleanup.run();
|
||||||
|
renderer.setColumnWidth(id, new ColumnWidth.Explicit(preview[0]));
|
||||||
|
renderer.message("Width applied to " + definition.header() + ".");
|
||||||
|
}
|
||||||
|
event.consume();
|
||||||
|
});
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void groupTarget(HBox bar) {
|
||||||
|
bar.setOnDragOver(e -> {
|
||||||
|
var payload = payload(e.getDragboard());
|
||||||
|
if (payload == null) return;
|
||||||
|
clearTargets();
|
||||||
|
boolean valid =
|
||||||
|
renderer.canGroup(payload[1])
|
||||||
|
&& (payload[0].equals("group")
|
||||||
|
|| !renderer.groupingColumns().contains(payload[1]));
|
||||||
|
bar.getStyleClass().add(valid ? "drop-before" : "drop-invalid");
|
||||||
|
if (valid) {
|
||||||
|
e.acceptTransferModes(TransferMode.MOVE);
|
||||||
|
markGroupInsertion(bar, payload[1], e.getSceneX());
|
||||||
|
}
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
bar.setOnDragDropped(e -> {
|
||||||
|
var payload = payload(e.getDragboard());
|
||||||
|
boolean success = false;
|
||||||
|
if (payload != null
|
||||||
|
&& renderer.canGroup(payload[1])
|
||||||
|
&& (payload[0].equals("group")
|
||||||
|
|| !renderer.groupingColumns().contains(payload[1]))) {
|
||||||
|
var order = new ArrayList<>(renderer.groupingColumns());
|
||||||
|
order.remove(payload[1]);
|
||||||
|
int index = groupIndex(bar, payload[1], e.getSceneX());
|
||||||
|
order.add(Math.min(index, order.size()), payload[1]);
|
||||||
|
try {
|
||||||
|
renderer.setGroupingColumns(order);
|
||||||
|
success = true;
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
renderer.message("Grouping failed: " + failure.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!success && payload == null)
|
||||||
|
renderer.message("Column is already grouped or has no enabled grouping mapping.");
|
||||||
|
clearTargets();
|
||||||
|
e.setDropCompleted(success);
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
bar.setOnDragExited(e -> {
|
||||||
|
clearTargets();
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void chip(Region chip, String id) {
|
||||||
|
chip.setUserData(id);
|
||||||
|
chip.setOnDragDetected(e -> {
|
||||||
|
if (e.isPrimaryButtonDown() || e.getButton() == MouseButton.PRIMARY) {
|
||||||
|
start(chip, "group", id);
|
||||||
|
e.consume();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void start(Node node, String kind, String id) {
|
||||||
|
// Capture before entering native drag setup; snapshot uses the rendering pipeline.
|
||||||
|
var ghost = node.snapshot(null, null);
|
||||||
|
var board = node.startDragAndDrop(TransferMode.MOVE);
|
||||||
|
var content = new ClipboardContent();
|
||||||
|
content.put(FORMAT, owner + "\n" + kind + "\n" + id);
|
||||||
|
board.setContent(content);
|
||||||
|
board.setDragView(ghost);
|
||||||
|
if (finishDrag != null) finishDrag.run();
|
||||||
|
long generation = ++dragGeneration;
|
||||||
|
Scene scene = node.getScene();
|
||||||
|
// Header-only tracking leaves a stale edge x when the pointer exits
|
||||||
|
// vertically. Follow the whole scene and qualify its current y as well.
|
||||||
|
EventHandler<DragEvent> position =
|
||||||
|
event -> {
|
||||||
|
if (payload(event.getDragboard()) != null) {
|
||||||
|
pointerX = event.getSceneX();
|
||||||
|
pointerY = event.getSceneY();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
EventHandler<DragEvent> exited =
|
||||||
|
event -> {
|
||||||
|
if (event.getTarget() == scene || event.getTarget() == scene.getRoot()) {
|
||||||
|
pointerX = pointerY = Double.NaN;
|
||||||
|
clearTargets();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
scene.addEventFilter(DragEvent.DRAG_OVER, position);
|
||||||
|
scene.addEventFilter(DragEvent.DRAG_EXITED_TARGET, exited);
|
||||||
|
finishDrag =
|
||||||
|
() -> {
|
||||||
|
scene.removeEventFilter(DragEvent.DRAG_OVER, position);
|
||||||
|
scene.removeEventFilter(DragEvent.DRAG_EXITED_TARGET, exited);
|
||||||
|
pointerX = pointerY = Double.NaN;
|
||||||
|
clearTargets();
|
||||||
|
stopScroll();
|
||||||
|
finishDrag = null;
|
||||||
|
};
|
||||||
|
node.setOnDragDone(e -> {
|
||||||
|
if (generation != dragGeneration) return;
|
||||||
|
if (finishDrag != null) finishDrag.run();
|
||||||
|
renderer.message(
|
||||||
|
e.getTransferMode() == null
|
||||||
|
? "Drag cancelled; layout retained."
|
||||||
|
: "Layout applied.");
|
||||||
|
});
|
||||||
|
startScroll();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String[] payload(Dragboard board) {
|
||||||
|
if (!board.hasContent(FORMAT)) return null;
|
||||||
|
Object content = board.getContent(FORMAT);
|
||||||
|
if (!(content instanceof String text)) return null;
|
||||||
|
var parts = text.split("\n", 3);
|
||||||
|
return parts.length == 3 && parts[0].equals(owner)
|
||||||
|
? new String[] {parts[1], parts[2]}
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> move(List<String> current, String id, int index) {
|
||||||
|
var result = new ArrayList<>(current);
|
||||||
|
result.remove(id);
|
||||||
|
result.add(Math.clamp(index, 0, result.size()), id);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int insertion(List<String> current, String id, String target, boolean after) {
|
||||||
|
if (id.equals(target)) return current.indexOf(id);
|
||||||
|
var others = new ArrayList<>(current);
|
||||||
|
others.remove(id);
|
||||||
|
return others.indexOf(target) + (after ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean valid(List<String> order) {
|
||||||
|
if (!new HashSet<>(order).equals(new HashSet<>(renderer.columnOrder()))
|
||||||
|
|| order.size() != renderer.columnOrder().size()) return false;
|
||||||
|
for (var c : renderer.definitions())
|
||||||
|
if (c.fixedPosition() >= 0 && !order.get(c.fixedPosition()).equals(c.id()))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int groupIndex(HBox bar, String dragged, double sceneX) {
|
||||||
|
int index = 0;
|
||||||
|
for (Node node : bar.getChildren())
|
||||||
|
if (node.getUserData() instanceof String id && !id.equals(dragged)) {
|
||||||
|
var bounds = node.localToScene(node.getBoundsInLocal());
|
||||||
|
if (sceneX < bounds.getMinX() + bounds.getWidth() / 2) return index;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void markGroupInsertion(HBox bar, String dragged, double x) {
|
||||||
|
var chips =
|
||||||
|
bar.getChildren().stream()
|
||||||
|
.filter(n -> n.getUserData() instanceof String id && !id.equals(dragged))
|
||||||
|
.toList();
|
||||||
|
int index = groupIndex(bar, dragged, x);
|
||||||
|
if (!chips.isEmpty())
|
||||||
|
chips.get(Math.min(index, chips.size() - 1))
|
||||||
|
.getStyleClass()
|
||||||
|
.add(index < chips.size() ? "drop-before" : "drop-after");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void clearTargets() {
|
||||||
|
Parent root = header.getScene() == null ? header : header.getScene().getRoot();
|
||||||
|
for (String style : List.of("drop-before", "drop-after", "drop-invalid"))
|
||||||
|
root.lookupAll("." + style).forEach(n -> n.getStyleClass().remove(style));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void startScroll() {
|
||||||
|
stopScroll();
|
||||||
|
pointerX = pointerY = Double.NaN;
|
||||||
|
scrolling =
|
||||||
|
new AnimationTimer() {
|
||||||
|
long last;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handle(long now) {
|
||||||
|
if (now - last < 35_000_000) return;
|
||||||
|
last = now;
|
||||||
|
ScrollPane scroll = null;
|
||||||
|
for (Node node = body.getParent(); node != null; node = node.getParent())
|
||||||
|
if (node instanceof ScrollPane pane) {
|
||||||
|
scroll = pane;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ScrollPane headerViewport = null;
|
||||||
|
for (Node node = header.getParent(); node != null; node = node.getParent())
|
||||||
|
if (node instanceof ScrollPane pane) {
|
||||||
|
headerViewport = pane;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (scroll == null || headerViewport == null || Double.isNaN(pointerX))
|
||||||
|
return;
|
||||||
|
var bounds = headerViewport.localToScene(headerViewport.getBoundsInLocal());
|
||||||
|
if (!bounds.contains(pointerX, pointerY)) return;
|
||||||
|
double delta =
|
||||||
|
pointerX < bounds.getMinX() + 30
|
||||||
|
? -.012
|
||||||
|
: pointerX > bounds.getMaxX() - 30 ? .012 : 0;
|
||||||
|
scroll.setHvalue(Math.clamp(scroll.getHvalue() + delta, 0, 1));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
scrolling.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stopScroll() {
|
||||||
|
if (scrolling != null) {
|
||||||
|
scrolling.stop();
|
||||||
|
scrolling = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
if (cancelResize != null) cancelResize.run();
|
||||||
|
if (finishDrag != null) finishDrag.run();
|
||||||
|
stopScroll();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import javafx.beans.binding.Bindings;
|
||||||
|
import javafx.beans.binding.DoubleBinding;
|
||||||
|
import javafx.beans.binding.ObjectBinding;
|
||||||
|
import javafx.geometry.Insets;
|
||||||
|
import javafx.scene.control.ScrollPane;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
import javafx.scene.layout.VBox;
|
||||||
|
|
||||||
|
/** Makes equal normalized scroll values represent equal pixel offsets in queried results. */
|
||||||
|
final class ResultScrollAlignment implements AutoCloseable {
|
||||||
|
private final HBox header;
|
||||||
|
private final VBox body;
|
||||||
|
private final double originalMinimum;
|
||||||
|
private final Insets originalPadding;
|
||||||
|
private final ObjectBinding<Insets> bodyPadding;
|
||||||
|
private final DoubleBinding minimum;
|
||||||
|
private final DoubleBinding viewportDifference;
|
||||||
|
|
||||||
|
ResultScrollAlignment(
|
||||||
|
HBox header, VBox body, ScrollPane headerScroll, ScrollPane bodyScroll,
|
||||||
|
boolean hasHeaderAccessory) {
|
||||||
|
this.header = header;
|
||||||
|
this.body = body;
|
||||||
|
originalMinimum = header.getMinWidth();
|
||||||
|
originalPadding = body.getPadding();
|
||||||
|
viewportDifference = Bindings.createDoubleBinding(
|
||||||
|
() -> headerScroll.getViewportBounds().getWidth()
|
||||||
|
- bodyScroll.getViewportBounds().getWidth(),
|
||||||
|
headerScroll.viewportBoundsProperty(), bodyScroll.viewportBoundsProperty());
|
||||||
|
// The fixed header menu can make the header viewport narrower. Add trailing body space
|
||||||
|
// so the last column can scroll fully into view in both viewports.
|
||||||
|
bodyPadding = hasHeaderAccessory ? Bindings.createObjectBinding(
|
||||||
|
() -> new Insets(originalPadding.getTop(),
|
||||||
|
originalPadding.getRight() + Math.max(0, -viewportDifference.get()),
|
||||||
|
originalPadding.getBottom(), originalPadding.getLeft()),
|
||||||
|
viewportDifference) : null;
|
||||||
|
if (bodyPadding != null) body.paddingProperty().bind(bodyPadding);
|
||||||
|
// A vertical body scrollbar narrows its viewport. Trailing row actions can also
|
||||||
|
// make its content wider than the column headings. Reserve blank header space
|
||||||
|
// so both scrollable extents match; the existing two-way hvalue binding then
|
||||||
|
// moves every mapped field and heading by the same number of pixels.
|
||||||
|
minimum =
|
||||||
|
Bindings.createDoubleBinding(
|
||||||
|
() -> body.getLayoutBounds().getWidth()
|
||||||
|
+ (hasHeaderAccessory
|
||||||
|
? viewportDifference.get()
|
||||||
|
: Math.max(0, viewportDifference.get())),
|
||||||
|
body.layoutBoundsProperty(), viewportDifference);
|
||||||
|
header.minWidthProperty().bind(minimum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
header.minWidthProperty().unbind();
|
||||||
|
header.setMinWidth(originalMinimum);
|
||||||
|
minimum.dispose();
|
||||||
|
if (bodyPadding != null) {
|
||||||
|
body.paddingProperty().unbind();
|
||||||
|
body.setPadding(originalPadding);
|
||||||
|
bodyPadding.dispose();
|
||||||
|
}
|
||||||
|
viewportDifference.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
/** Configures row selection independently of querying and saved grid layouts. */
|
||||||
|
public enum RowSelectionMode {
|
||||||
|
NONE, SINGLE, MULTIPLE
|
||||||
|
}
|
||||||
@@ -25,6 +25,7 @@ import javafx.beans.property.Property;
|
|||||||
import javafx.beans.property.SimpleObjectProperty;
|
import javafx.beans.property.SimpleObjectProperty;
|
||||||
import javafx.collections.FXCollections;
|
import javafx.collections.FXCollections;
|
||||||
import javafx.collections.ListChangeListener;
|
import javafx.collections.ListChangeListener;
|
||||||
|
import javafx.event.EventHandler;
|
||||||
import javafx.collections.ObservableList;
|
import javafx.collections.ObservableList;
|
||||||
import javafx.scene.Node;
|
import javafx.scene.Node;
|
||||||
import javafx.scene.Parent;
|
import javafx.scene.Parent;
|
||||||
@@ -137,7 +138,15 @@ public class Table extends VBox {
|
|||||||
/**
|
/**
|
||||||
* The Rows currently showing.
|
* The Rows currently showing.
|
||||||
*/
|
*/
|
||||||
private final VBox body = new VBox();
|
private final VBox body = new VBox() {
|
||||||
|
private static final String SELECTION_CSS =
|
||||||
|
Table.class.getResource("result-selection.css").toExternalForm();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getUserAgentStylesheet() {
|
||||||
|
return SELECTION_CSS;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The column popup.
|
* The column popup.
|
||||||
@@ -148,6 +157,8 @@ public class Table extends VBox {
|
|||||||
* One Row per element that has been shown. A hidden element keeps its Row.
|
* One Row per element that has been shown. A hidden element keeps its Row.
|
||||||
*/
|
*/
|
||||||
private final Map<Object, Node> rows = new IdentityHashMap<>();
|
private final Map<Object, Node> rows = new IdentityHashMap<>();
|
||||||
|
private final Map<Object, ViewLifetime> rowLifetimes = new IdentityHashMap<>();
|
||||||
|
private ViewLifetime lifetime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The collection this Table shows.
|
* The collection this Table shows.
|
||||||
@@ -238,13 +249,28 @@ public class Table extends VBox {
|
|||||||
*/
|
*/
|
||||||
public <K, T> TableResults<K, T> openResults(List<ResultColumn> definitions,
|
public <K, T> TableResults<K, T> openResults(List<ResultColumn> definitions,
|
||||||
java.util.function.Function<T, ResultRow> factory) {
|
java.util.function.Function<T, ResultRow> factory) {
|
||||||
|
return openResults(definitions, factory, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
<K, T> TableResults<K, T> openResults(List<ResultColumn> definitions,
|
||||||
|
java.util.function.Function<T, ResultRow> factory, Region headerAccessory) {
|
||||||
if (!javafx.application.Platform.isFxApplicationThread()) {
|
if (!javafx.application.Platform.isFxApplicationThread()) {
|
||||||
throw new IllegalStateException("Use the JavaFX application thread");
|
throw new IllegalStateException("Use the JavaFX application thread");
|
||||||
}
|
}
|
||||||
if (opened || resultMode) {
|
if (opened || resultMode) {
|
||||||
throw new IllegalStateException("Table is already open");
|
throw new IllegalStateException("Table is already open");
|
||||||
}
|
}
|
||||||
TableResults<K, T> renderer = new TableResults<>(header, body, List.copyOf(definitions), factory);
|
TableResults<K, T> renderer = new TableResults<>(
|
||||||
|
header, body, List.copyOf(definitions), factory, headerScroll, scroll, headerAccessory);
|
||||||
|
if (headerAccessory != null) {
|
||||||
|
getChildren().remove(headerScroll);
|
||||||
|
headerScroll.setMinWidth(0);
|
||||||
|
HBox.setHgrow(headerScroll, Priority.ALWAYS);
|
||||||
|
headerAccessory.setMaxHeight(Double.MAX_VALUE);
|
||||||
|
getChildren().addFirst(new HBox(headerScroll, headerAccessory));
|
||||||
|
}
|
||||||
|
// DataGrid grows this Table; let its viewport consume that height as well.
|
||||||
|
VBox.setVgrow(scroll, Priority.ALWAYS);
|
||||||
resultMode = true;
|
resultMode = true;
|
||||||
return renderer;
|
return renderer;
|
||||||
}
|
}
|
||||||
@@ -337,8 +363,8 @@ public class Table extends VBox {
|
|||||||
* @param viewModel the ViewModel for this View
|
* @param viewModel the ViewModel for this View
|
||||||
* @param context the container that creates each Row
|
* @param context the container that creates each Row
|
||||||
*/
|
*/
|
||||||
static void openAll(Parent root, Object viewModel, ApplicationContext context) {
|
static void openAll(Parent root, Object viewModel, ApplicationContext context, ViewLifetime lifetime) {
|
||||||
walk(root, viewModel, context);
|
walk(root, root, viewModel, context, lifetime);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -347,7 +373,7 @@ public class Table extends VBox {
|
|||||||
* @param viewModel the ViewModel for this View
|
* @param viewModel the ViewModel for this View
|
||||||
* @param context the container that creates each Row
|
* @param context the container that creates each Row
|
||||||
*/
|
*/
|
||||||
void open(Object viewModel, ApplicationContext context) {
|
void open(Object viewModel, ApplicationContext context, ViewLifetime owner) {
|
||||||
if (resultMode) {
|
if (resultMode) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -356,6 +382,15 @@ public class Table extends VBox {
|
|||||||
}
|
}
|
||||||
opened = true;
|
opened = true;
|
||||||
this.context = context;
|
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()) {
|
if (columns.isEmpty()) {
|
||||||
throw new IllegalArgumentException("A table needs a column");
|
throw new IllegalArgumentException("A table needs a column");
|
||||||
}
|
}
|
||||||
@@ -370,7 +405,7 @@ public class Table extends VBox {
|
|||||||
}
|
}
|
||||||
buildHeader();
|
buildHeader();
|
||||||
ensureWidths();
|
ensureWidths();
|
||||||
elements.addListener((ListChangeListener<Object>) this::onCollectionChange);
|
lifetime.listen(elements, this::onCollectionChange);
|
||||||
refresh();
|
refresh();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1159,6 +1194,8 @@ public class Table extends VBox {
|
|||||||
}
|
}
|
||||||
for (Object removed : change.getRemoved()) {
|
for (Object removed : change.getRemoved()) {
|
||||||
rows.remove(removed);
|
rows.remove(removed);
|
||||||
|
ViewLifetime removedRow = rowLifetimes.remove(removed);
|
||||||
|
if (removedRow != null) removedRow.close();
|
||||||
if (selection.get() == removed) {
|
if (selection.get() == removed) {
|
||||||
selection.set(null);
|
selection.set(null);
|
||||||
}
|
}
|
||||||
@@ -1287,18 +1324,27 @@ public class Table extends VBox {
|
|||||||
* @return the Row
|
* @return the Row
|
||||||
*/
|
*/
|
||||||
private Node createRow(Object element) {
|
private Node createRow(Object element) {
|
||||||
Object component = Components.fresh(rowType, context);
|
ViewLifetime rowLifetime = lifetime.child();
|
||||||
Components.setModel(component, element);
|
try {
|
||||||
|
Object component = Components.fresh(rowType, context, rowLifetime);
|
||||||
|
Components.setModel(component, element, rowLifetime);
|
||||||
if (!(component instanceof Node node)) {
|
if (!(component instanceof Node node)) {
|
||||||
throw new IllegalArgumentException("Row is not a node: " + rowType.getName());
|
throw new IllegalArgumentException("Row is not a node: " + rowType.getName());
|
||||||
}
|
}
|
||||||
node.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
|
EventHandler<MouseEvent> select = event -> {
|
||||||
if (event.getButton() == MouseButton.PRIMARY) {
|
if (event.getButton() == MouseButton.PRIMARY) {
|
||||||
selection.set(element);
|
selection.set(element);
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
watchEdits(node);
|
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;
|
return node;
|
||||||
|
} catch (RuntimeException | Error failure) {
|
||||||
|
rowLifetime.rollback(failure);
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1306,13 +1352,13 @@ public class Table extends VBox {
|
|||||||
*
|
*
|
||||||
* @param node the Row or one of its fields
|
* @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) {
|
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) {
|
if (node instanceof Parent parent) {
|
||||||
for (Node child : parent.getChildrenUnmodifiable()) {
|
for (Node child : parent.getChildrenUnmodifiable()) {
|
||||||
watchEdits(child);
|
watchEdits(child, rowLifetime);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1520,18 +1566,20 @@ public class Table extends VBox {
|
|||||||
* @param viewModel the ViewModel for this View
|
* @param viewModel the ViewModel for this View
|
||||||
* @param context the container that creates each Row
|
* @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) {
|
if (node instanceof Table table) {
|
||||||
table.open(viewModel, context);
|
table.open(viewModel, context, lifetime);
|
||||||
}
|
}
|
||||||
if (!(node instanceof Parent parent)) {
|
if (!(node instanceof Parent parent)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (Node child : parent.getChildrenUnmodifiable()) {
|
for (Node child : parent.getChildrenUnmodifiable()) {
|
||||||
walk(child, viewModel, context);
|
walk(child, root, viewModel, context, lifetime);
|
||||||
}
|
}
|
||||||
if (parent instanceof ScrollPane pane && pane.getContent() != null) {
|
if (parent instanceof ScrollPane pane && pane.getContent() != null) {
|
||||||
walk(pane.getContent(), viewModel, context);
|
walk(pane.getContent(), root, viewModel, context, lifetime);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,23 +1,28 @@
|
|||||||
package de.neitzel.fx.view;
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
import de.neitzel.grid.ColumnWidth;
|
import de.neitzel.grid.*;
|
||||||
import de.neitzel.grid.GridRow;
|
|
||||||
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import javafx.beans.property.*;
|
import javafx.beans.property.*;
|
||||||
|
import javafx.collections.*;
|
||||||
import javafx.event.EventHandler;
|
import javafx.event.EventHandler;
|
||||||
import javafx.scene.Node;
|
import javafx.scene.Node;
|
||||||
import javafx.scene.control.Button;
|
import javafx.scene.control.Button;
|
||||||
|
import javafx.scene.control.ContextMenu;
|
||||||
import javafx.scene.control.Label;
|
import javafx.scene.control.Label;
|
||||||
import javafx.scene.control.Tooltip;
|
import javafx.scene.control.Tooltip;
|
||||||
|
import javafx.geometry.Side;
|
||||||
import javafx.scene.input.MouseButton;
|
import javafx.scene.input.MouseButton;
|
||||||
import javafx.scene.input.MouseEvent;
|
import javafx.scene.input.MouseEvent;
|
||||||
|
import javafx.scene.input.KeyEvent;
|
||||||
|
import javafx.scene.input.KeyCode;
|
||||||
import javafx.scene.layout.HBox;
|
import javafx.scene.layout.HBox;
|
||||||
import javafx.scene.layout.Region;
|
import javafx.scene.layout.Region;
|
||||||
import javafx.scene.layout.VBox;
|
import javafx.scene.layout.VBox;
|
||||||
import javafx.scene.shape.SVGPath;
|
import javafx.scene.shape.SVGPath;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.function.BiFunction;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,30 +34,68 @@ import java.util.function.Function;
|
|||||||
public final class TableResults<K, T> implements AutoCloseable {
|
public final class TableResults<K, T> implements AutoCloseable {
|
||||||
private final HBox header;
|
private final HBox header;
|
||||||
private final VBox body;
|
private final VBox body;
|
||||||
|
private final Region headerAccessory;
|
||||||
private final Function<T, ResultRow> factory;
|
private final Function<T, ResultRow> factory;
|
||||||
private final Map<String, ResultColumn> definitions = new LinkedHashMap<>();
|
private final Map<String, ResultColumn> definitions = new LinkedHashMap<>();
|
||||||
private final Map<String, ColumnWidth> widths = new LinkedHashMap<>();
|
private final Map<String, ColumnWidth> widths = new LinkedHashMap<>();
|
||||||
private List<String> order;
|
private List<String> order;
|
||||||
|
private final Set<String> hiddenColumns = new HashSet<>();
|
||||||
private List<Entry<K, T>> entries = List.of();
|
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<K> selectedKey = new ReadOnlyObjectWrapper<>();
|
||||||
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
|
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
|
||||||
|
private final ObservableList<K> selectedKeys = FXCollections.observableArrayList();
|
||||||
|
private final ObservableList<T> selectedElements = FXCollections.observableArrayList();
|
||||||
|
private final ReadOnlyListWrapper<K> keysView = new ReadOnlyListWrapper<>(
|
||||||
|
FXCollections.unmodifiableObservableList(selectedKeys));
|
||||||
|
private final ReadOnlyListWrapper<T> elementsView = new ReadOnlyListWrapper<>(
|
||||||
|
FXCollections.unmodifiableObservableList(selectedElements));
|
||||||
|
private RowSelectionMode selectionMode = RowSelectionMode.SINGLE;
|
||||||
|
private K anchor;
|
||||||
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
|
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
|
||||||
new ReadOnlyObjectWrapper<>();
|
new ReadOnlyObjectWrapper<>();
|
||||||
private boolean closed;
|
private boolean closed;
|
||||||
private boolean rowsInteractive = true;
|
private boolean rowsInteractive = true;
|
||||||
|
private boolean columnSeparators;
|
||||||
private Set<String> filterColumns = Set.of();
|
private Set<String> filterColumns = Set.of();
|
||||||
private Set<String> filteredColumns = Set.of();
|
private Set<String> filteredColumns = Set.of();
|
||||||
|
private List<SortKey> sortKeys = List.of();
|
||||||
private java.util.function.BiConsumer<String, Node> filterRequest = (id, node) -> {};
|
private java.util.function.BiConsumer<String, Node> filterRequest = (id, node) -> {};
|
||||||
private java.util.function.Consumer<String> sortRequest = id -> {};
|
private java.util.function.Consumer<String> sortRequest = id -> {};
|
||||||
|
private BiFunction<String, HBox, ContextMenu> headerMenuFactory;
|
||||||
|
private ContextMenu headerMenu;
|
||||||
|
|
||||||
private record Entry<K, T>(GridRow<K, T> row, ResultRow view, EventHandler<MouseEvent> click) {}
|
private List<GroupColumn<T>> groupColumns = List.of();
|
||||||
|
private List<String> grouping = List.of();
|
||||||
|
private boolean groupingEnabled, defaultCollapsed = true;
|
||||||
|
private int inactiveHistoryLimit = 1000;
|
||||||
|
private GroupExpansion expansion = new GroupExpansion(true, 1000);
|
||||||
|
private GroupProjection.Snapshot<K, T> captured = GroupProjection.capture(List.of(), List.of());
|
||||||
|
private List<GroupProjection.Node<K, T>> groupTree = List.of();
|
||||||
|
private final Map<GroupPath, Button> disclosure = new HashMap<>();
|
||||||
|
private Runnable layoutCommitted = () -> {};
|
||||||
|
private java.util.function.Consumer<String> interactionMessage = ignored -> {};
|
||||||
|
private final ResultHeaderGestures gestures;
|
||||||
|
private final ResultScrollAlignment scrollAlignment;
|
||||||
|
|
||||||
|
private record Entry<K, T>(GridRow<K, T> row, ResultRow view,
|
||||||
|
EventHandler<MouseEvent> click, EventHandler<KeyEvent> key) {}
|
||||||
|
|
||||||
TableResults(
|
TableResults(
|
||||||
HBox header, VBox body, List<ResultColumn> columns, Function<T, ResultRow> factory) {
|
HBox header,
|
||||||
|
VBox body,
|
||||||
|
List<ResultColumn> columns,
|
||||||
|
Function<T, ResultRow> factory,
|
||||||
|
javafx.scene.control.ScrollPane headerScroll,
|
||||||
|
javafx.scene.control.ScrollPane bodyScroll,
|
||||||
|
Region headerAccessory) {
|
||||||
requireFx();
|
requireFx();
|
||||||
this.header = header;
|
this.header = header;
|
||||||
this.body = body;
|
this.body = body;
|
||||||
|
this.headerAccessory = headerAccessory;
|
||||||
this.factory = Objects.requireNonNull(factory);
|
this.factory = Objects.requireNonNull(factory);
|
||||||
|
gestures = new ResultHeaderGestures(this, header, body);
|
||||||
if (columns.isEmpty())
|
if (columns.isEmpty())
|
||||||
throw new IllegalArgumentException("At least one column is required");
|
throw new IllegalArgumentException("At least one column is required");
|
||||||
for (var c : columns) {
|
for (var c : columns) {
|
||||||
@@ -62,13 +105,21 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
order = List.copyOf(definitions.keySet());
|
order = List.copyOf(definitions.keySet());
|
||||||
validateOrder(order);
|
validateOrder(order);
|
||||||
|
scrollAlignment = new ResultScrollAlignment(
|
||||||
|
header, body, headerScroll, bodyScroll, headerAccessory != null);
|
||||||
drawHeader();
|
drawHeader();
|
||||||
body.setOnMouseClicked(
|
body.setOnMouseClicked(e -> {
|
||||||
e -> {
|
|
||||||
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
|
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void enableColumnSeparators() {
|
||||||
|
checkOpen();
|
||||||
|
columnSeparators = true;
|
||||||
|
drawHeader();
|
||||||
|
applyWidths(widths);
|
||||||
|
}
|
||||||
|
|
||||||
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
|
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
|
||||||
return selectedKey.getReadOnlyProperty();
|
return selectedKey.getReadOnlyProperty();
|
||||||
}
|
}
|
||||||
@@ -77,6 +128,24 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
return selectedElement.getReadOnlyProperty();
|
return selectedElement.getReadOnlyProperty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ReadOnlyListProperty<K> selectedKeysProperty() { return keysView.getReadOnlyProperty(); }
|
||||||
|
|
||||||
|
/** 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) {
|
||||||
|
checkOpen();
|
||||||
|
selectionMode = Objects.requireNonNull(mode);
|
||||||
|
if (mode == RowSelectionMode.NONE) select(null);
|
||||||
|
else if (mode == RowSelectionMode.SINGLE && selectedKeys.size() > 1) select(selectedKey.get());
|
||||||
|
}
|
||||||
|
|
||||||
/** Cleanup failures are exposed separately: they do not roll back an already published page. */
|
/** Cleanup failures are exposed separately: they do not roll back an already published page. */
|
||||||
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
|
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
|
||||||
return disposalFailure.getReadOnlyProperty();
|
return disposalFailure.getReadOnlyProperty();
|
||||||
@@ -90,6 +159,27 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
return Map.copyOf(widths);
|
return Map.copyOf(widths);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
boolean isColumnVisible(String id) {
|
||||||
|
checkOpen();
|
||||||
|
if (!definitions.containsKey(id)) throw new IllegalArgumentException("Unknown column: " + id);
|
||||||
|
return !hiddenColumns.contains(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setColumnVisible(String id, boolean visible) {
|
||||||
|
if (visible == isColumnVisible(id)) return;
|
||||||
|
Node focus = header.getScene() == null ? null : header.getScene().getFocusOwner();
|
||||||
|
boolean headerFocused = focus != null && descendant(header, focus);
|
||||||
|
if (visible) hiddenColumns.remove(id);
|
||||||
|
else hiddenColumns.add(id);
|
||||||
|
drawHeader();
|
||||||
|
applyWidths(widths);
|
||||||
|
if (headerFocused && headerAccessory != null) headerAccessory.requestFocus();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> visibleOrder(List<String> ordering) {
|
||||||
|
return ordering.stream().filter(id -> !hiddenColumns.contains(id)).toList();
|
||||||
|
}
|
||||||
|
|
||||||
/** Marks retained rows unavailable without disabling header/query controls. */
|
/** Marks retained rows unavailable without disabling header/query controls. */
|
||||||
public void setRowsInteractive(boolean interactive) {
|
public void setRowsInteractive(boolean interactive) {
|
||||||
checkOpen();
|
checkOpen();
|
||||||
@@ -104,6 +194,11 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
sortRequest = Objects.requireNonNull(handler);
|
sortRequest = Objects.requireNonNull(handler);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void setHeaderMenuFactory(BiFunction<String, HBox, ContextMenu> factory) {
|
||||||
|
checkOpen();
|
||||||
|
headerMenuFactory = Objects.requireNonNull(factory);
|
||||||
|
}
|
||||||
|
|
||||||
/** Opt-in filter actions; clicking the icon never issues a sort request. */
|
/** Opt-in filter actions; clicking the icon never issues a sort request. */
|
||||||
public void setFilterActions(
|
public void setFilterActions(
|
||||||
Set<String> columns, java.util.function.BiConsumer<String, Node> handler) {
|
Set<String> columns, java.util.function.BiConsumer<String, Node> handler) {
|
||||||
@@ -130,6 +225,32 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
markFilter(button, (String) cell.getUserData());
|
markFilter(button, (String) cell.getUserData());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setSortKeys(List<SortKey> keys) {
|
||||||
|
checkOpen();
|
||||||
|
if (keys.size() > 1 || keys.stream().anyMatch(k -> !definitions.containsKey(k.columnId())))
|
||||||
|
throw new IllegalArgumentException("Unknown sort column");
|
||||||
|
sortKeys = List.copyOf(keys);
|
||||||
|
for (Node node : header.getChildren()) {
|
||||||
|
HBox cell = (HBox) node;
|
||||||
|
Label label = (Label) cell.getChildren().getFirst();
|
||||||
|
label.setText(headerText((String) cell.getUserData()));
|
||||||
|
label.setAccessibleText("Sort " + headerText((String) cell.getUserData()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String columnHeader(String id) {
|
||||||
|
return definitions.get(id).header();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String headerText(String id) {
|
||||||
|
return columnHeader(id)
|
||||||
|
+ sortKeys.stream()
|
||||||
|
.filter(k -> k.columnId().equals(id))
|
||||||
|
.map(k -> k.direction() == SortKey.Direction.ASCENDING ? " ↑" : " ↓")
|
||||||
|
.findFirst()
|
||||||
|
.orElse("");
|
||||||
|
}
|
||||||
|
|
||||||
private void markFilter(Button button, String id) {
|
private void markFilter(Button button, String id) {
|
||||||
boolean active = filteredColumns.contains(id);
|
boolean active = filteredColumns.contains(id);
|
||||||
button.pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("filtered"), active);
|
button.pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("filtered"), active);
|
||||||
@@ -144,16 +265,87 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
/** Retains an off-page key while exposing no loaded selected element. */
|
/** Retains an off-page key while exposing no loaded selected element. */
|
||||||
public void select(K key) {
|
public void select(K key) {
|
||||||
checkOpen();
|
checkOpen();
|
||||||
selectedKey.set(key);
|
selectKeys(key == null ? List.of() : List.of(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces selection, retaining off-page identities. The last key is the lead. */
|
||||||
|
public void selectKeys(Collection<? extends K> keys) {
|
||||||
|
checkOpen();
|
||||||
|
var next = new LinkedHashSet<K>();
|
||||||
|
keys.forEach(key -> next.add(Objects.requireNonNull(key)));
|
||||||
|
if (selectionMode == RowSelectionMode.NONE) next.clear();
|
||||||
|
if (selectionMode == RowSelectionMode.SINGLE && next.size() > 1)
|
||||||
|
throw new IllegalArgumentException("Multiple selection is disabled");
|
||||||
|
selectedKeys.setAll(next);
|
||||||
|
selectedKey.set(next.isEmpty() ? null : next.getLast());
|
||||||
|
anchor = selectedKey.get();
|
||||||
markSelection();
|
markSelection();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void deselect(K key) {
|
||||||
|
checkOpen();
|
||||||
|
var remaining = new ArrayList<>(selectedKeys);
|
||||||
|
remaining.remove(key);
|
||||||
|
selectKeys(remaining);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<K> visibleKeys() {
|
||||||
|
var byRoot = new IdentityHashMap<Node, K>();
|
||||||
|
entries.forEach(e -> byRoot.put(e.view().root(), e.row().key()));
|
||||||
|
return body.getChildren().stream().filter(byRoot::containsKey).map(byRoot::get).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void choose(K key, boolean shortcut, boolean shift) {
|
||||||
|
if (!rowsInteractive || selectionMode == RowSelectionMode.NONE) return;
|
||||||
|
if (selectionMode == RowSelectionMode.SINGLE) { select(key); return; }
|
||||||
|
K previousAnchor = anchor;
|
||||||
|
var next = new LinkedHashSet<K>();
|
||||||
|
if (shortcut) next.addAll(selectedKeys);
|
||||||
|
var visible = visibleKeys();
|
||||||
|
int start = visible.indexOf(anchor), end = visible.indexOf(key);
|
||||||
|
if (shift && start >= 0 && end >= 0) {
|
||||||
|
next.addAll(visible.subList(Math.min(start, end), Math.max(start, end) + 1));
|
||||||
|
next.remove(key);
|
||||||
|
next.add(key);
|
||||||
|
} else if (!shortcut || !next.remove(key)) next.add(key);
|
||||||
|
selectKeys(next);
|
||||||
|
anchor = shift && previousAnchor != null ? previousAnchor : key;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void keyPressed(K key, KeyEvent event) {
|
||||||
|
// Embedded editors retain their own keyboard behavior.
|
||||||
|
if (event.getTarget() != event.getSource() || !rowsInteractive
|
||||||
|
|| selectionMode == RowSelectionMode.NONE) return;
|
||||||
|
var visible = visibleKeys();
|
||||||
|
int index = visible.indexOf(key);
|
||||||
|
if (event.getCode() == KeyCode.A && event.isShortcutDown()
|
||||||
|
&& selectionMode == RowSelectionMode.MULTIPLE) selectKeys(visible);
|
||||||
|
else if (event.getCode() == KeyCode.ESCAPE) select(null);
|
||||||
|
else if (event.getCode() == KeyCode.SPACE) choose(key, event.isShortcutDown(), event.isShiftDown());
|
||||||
|
else {
|
||||||
|
int next = switch (event.getCode()) {
|
||||||
|
case UP -> Math.max(0, index - 1);
|
||||||
|
case DOWN -> Math.min(visible.size() - 1, index + 1);
|
||||||
|
case HOME -> 0;
|
||||||
|
case END -> visible.size() - 1;
|
||||||
|
default -> -1;
|
||||||
|
};
|
||||||
|
if (next < 0 || visible.isEmpty()) return;
|
||||||
|
K target = visible.get(next);
|
||||||
|
if (!event.isShortcutDown() || event.isShiftDown())
|
||||||
|
choose(target, event.isShortcutDown(), event.isShiftDown());
|
||||||
|
entries.stream().filter(e -> Objects.equals(e.row().key(), target))
|
||||||
|
.findFirst().ifPresent(e -> e.view().root().requestFocus());
|
||||||
|
}
|
||||||
|
event.consume();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stages fresh rows before replacing the visible page; failed construction preserves the old
|
* Stages fresh rows before replacing the visible page; failed construction preserves the old
|
||||||
* page.
|
* page.
|
||||||
*/
|
*/
|
||||||
public void show(List<GridRow<K, T>> result) {
|
public void show(List<GridRow<K, T>> result) {
|
||||||
show(result, order, widths);
|
show(result, order, widths, groupingSetup());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Stages both fresh rows and complete layout, publishing neither on preparation failure. */
|
/** Stages both fresh rows and complete layout, publishing neither on preparation failure. */
|
||||||
@@ -161,7 +353,21 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
List<GridRow<K, T>> result,
|
List<GridRow<K, T>> result,
|
||||||
List<String> nextOrder,
|
List<String> nextOrder,
|
||||||
Map<String, ColumnWidth> nextWidths) {
|
Map<String, ColumnWidth> nextWidths) {
|
||||||
|
show(result, nextOrder, nextWidths, groupingSetup());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void show(
|
||||||
|
List<GridRow<K, T>> result,
|
||||||
|
List<String> nextOrder,
|
||||||
|
Map<String, ColumnWidth> nextWidths,
|
||||||
|
GroupingSetup nextGrouping) {
|
||||||
checkOpen();
|
checkOpen();
|
||||||
|
validateGrouping(nextGrouping);
|
||||||
|
var nextCaptured = GroupProjection.capture(result, groupColumns);
|
||||||
|
var nextTree = GroupProjection.project(nextCaptured, nextGrouping.columns());
|
||||||
|
var nextExpansion = new GroupExpansion(defaultCollapsed, inactiveHistoryLimit);
|
||||||
|
nextExpansion.current(GroupProjection.paths(nextTree));
|
||||||
|
nextExpansion.restore(nextGrouping.choices());
|
||||||
nextOrder = List.copyOf(nextOrder);
|
nextOrder = List.copyOf(nextOrder);
|
||||||
validateOrder(nextOrder);
|
validateOrder(nextOrder);
|
||||||
nextWidths = Map.copyOf(nextWidths);
|
nextWidths = Map.copyOf(nextWidths);
|
||||||
@@ -177,7 +383,8 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
Math.clamp(e.value(), c.minimumWidth(), c.maximumWidth()))
|
Math.clamp(e.value(), c.minimumWidth(), c.maximumWidth()))
|
||||||
: width);
|
: width);
|
||||||
}
|
}
|
||||||
var nextHeader = headerNodes(nextOrder, preparedWidths);
|
var visibleOrder = visibleOrder(nextOrder);
|
||||||
|
var nextHeader = headerNodes(visibleOrder, preparedWidths);
|
||||||
result = List.copyOf(result);
|
result = List.copyOf(result);
|
||||||
Set<K> keys = new HashSet<>();
|
Set<K> keys = new HashSet<>();
|
||||||
for (var row : result)
|
for (var row : result)
|
||||||
@@ -195,13 +402,20 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
"Row factory must create detached fresh rows");
|
"Row factory must create detached fresh rows");
|
||||||
EventHandler<MouseEvent> click =
|
EventHandler<MouseEvent> click =
|
||||||
e -> {
|
e -> {
|
||||||
if (e.getButton() == MouseButton.PRIMARY) select(row.key());
|
if (e.getButton() == MouseButton.PRIMARY)
|
||||||
|
choose(row.key(), e.isShortcutDown(), e.isShiftDown());
|
||||||
|
if (e.getButton() == MouseButton.PRIMARY
|
||||||
|
&& (e.getTarget() == view.root() || e.getTarget() instanceof Label))
|
||||||
|
view.root().requestFocus();
|
||||||
};
|
};
|
||||||
next.add(new Entry<>(row, view, click));
|
EventHandler<KeyEvent> key = e -> keyPressed(row.key(), e);
|
||||||
|
next.add(new Entry<>(row, view, click, key));
|
||||||
validateRow(view);
|
validateRow(view);
|
||||||
view.root().getStyleClass().add("result-row");
|
view.root().getStyleClass().add("result-row");
|
||||||
layoutRow(view, nextOrder, preparedWidths);
|
layoutRow(view, visibleOrder, preparedWidths);
|
||||||
view.root().addEventHandler(MouseEvent.MOUSE_CLICKED, click);
|
view.root().addEventHandler(MouseEvent.MOUSE_CLICKED, click);
|
||||||
|
view.root().setFocusTraversable(true);
|
||||||
|
view.root().addEventHandler(KeyEvent.KEY_PRESSED, key);
|
||||||
}
|
}
|
||||||
} catch (RuntimeException failure) {
|
} catch (RuntimeException failure) {
|
||||||
release(next);
|
release(next);
|
||||||
@@ -212,9 +426,13 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
order = nextOrder;
|
order = nextOrder;
|
||||||
widths.clear();
|
widths.clear();
|
||||||
widths.putAll(preparedWidths);
|
widths.putAll(preparedWidths);
|
||||||
header.getChildren().setAll(nextHeader);
|
replaceHeader(nextHeader);
|
||||||
body.getChildren().setAll(entries.stream().map(e -> e.view().root()).toList());
|
captured = nextCaptured;
|
||||||
markSelection();
|
groupTree = nextTree;
|
||||||
|
grouping = nextGrouping.columns();
|
||||||
|
expansion = nextExpansion;
|
||||||
|
disclosure.clear();
|
||||||
|
drawGroups();
|
||||||
release(old);
|
release(old);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,7 +443,8 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
validateOrder(ids);
|
validateOrder(ids);
|
||||||
order = ids;
|
order = ids;
|
||||||
drawHeader();
|
drawHeader();
|
||||||
entries.forEach(e -> layoutRow(e.view()));
|
applyWidths(widths);
|
||||||
|
layoutCommitted.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -243,8 +462,8 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
widths.put(
|
widths.put(
|
||||||
id,
|
id,
|
||||||
width instanceof ColumnWidth.Explicit ? new ColumnWidth.Explicit(applied) : width);
|
width instanceof ColumnWidth.Explicit ? new ColumnWidth.Explicit(applied) : width);
|
||||||
drawHeader();
|
applyWidths(widths);
|
||||||
entries.forEach(e -> layoutRow(e.view()));
|
layoutCommitted.run();
|
||||||
return applied;
|
return applied;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,7 +490,7 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
"Mapped fields must be distinct direct children");
|
"Mapped fields must be distinct direct children");
|
||||||
}
|
}
|
||||||
|
|
||||||
private double width(String id) {
|
double width(String id) {
|
||||||
return width(id, widths);
|
return width(id, widths);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,20 +501,36 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void drawHeader() {
|
private void drawHeader() {
|
||||||
header.getChildren().setAll(headerNodes(order, widths));
|
replaceHeader(headerNodes(visibleOrder(order), widths));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void replaceHeader(List<Node> cells) {
|
||||||
|
if (headerMenu != null) {
|
||||||
|
headerMenu.hide();
|
||||||
|
headerMenu = null;
|
||||||
|
}
|
||||||
|
header.getChildren().setAll(cells);
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Node> headerNodes(List<String> ordering, Map<String, ColumnWidth> sizes) {
|
private List<Node> headerNodes(List<String> ordering, Map<String, ColumnWidth> sizes) {
|
||||||
List<Node> nodes = new ArrayList<>();
|
List<Node> nodes = new ArrayList<>();
|
||||||
for (String id : ordering) {
|
for (String id : ordering) {
|
||||||
Label label = new Label(definitions.get(id).header());
|
Label label = new Label(headerText(id));
|
||||||
label.getStyleClass().add("column-header");
|
label.getStyleClass().add("column-header");
|
||||||
HBox cell = new HBox(label);
|
HBox cell = new HBox(label);
|
||||||
cell.getStyleClass().add("column-cell");
|
cell.getStyleClass().add("column-cell");
|
||||||
cell.setUserData(id);
|
cell.setUserData(id);
|
||||||
cell.setOnMouseClicked(
|
HBox.setHgrow(label, javafx.scene.layout.Priority.ALWAYS);
|
||||||
event -> {
|
label.setMaxWidth(Double.MAX_VALUE);
|
||||||
if (event.getButton() == MouseButton.PRIMARY) sortRequest.accept(id);
|
label.setFocusTraversable(true);
|
||||||
|
label.setAccessibleRole(javafx.scene.AccessibleRole.BUTTON);
|
||||||
|
label.setAccessibleText("Sort " + definitions.get(id).header());
|
||||||
|
label.setOnKeyPressed(event -> {
|
||||||
|
if (event.getCode() == javafx.scene.input.KeyCode.ENTER
|
||||||
|
|| event.getCode() == javafx.scene.input.KeyCode.SPACE) {
|
||||||
|
sortRequest.accept(id);
|
||||||
|
event.consume();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
if (filterColumns.contains(id)) {
|
if (filterColumns.contains(id)) {
|
||||||
SVGPath icon = new SVGPath();
|
SVGPath icon = new SVGPath();
|
||||||
@@ -310,6 +545,24 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
button.addEventHandler(MouseEvent.MOUSE_CLICKED, MouseEvent::consume);
|
button.addEventHandler(MouseEvent.MOUSE_CLICKED, MouseEvent::consume);
|
||||||
cell.getChildren().add(button);
|
cell.getChildren().add(button);
|
||||||
}
|
}
|
||||||
|
Region handle = new Region();
|
||||||
|
handle.getStyleClass().add("column-resize");
|
||||||
|
handle.setMinWidth(9);
|
||||||
|
handle.setPrefWidth(9);
|
||||||
|
handle.setMaxWidth(9);
|
||||||
|
handle.setCursor(javafx.scene.Cursor.E_RESIZE);
|
||||||
|
cell.getChildren().add(handle);
|
||||||
|
if (columnSeparators && !id.equals(ordering.getLast()))
|
||||||
|
cell.getChildren().add(ResultColumnSeparators.forHeader(cell));
|
||||||
|
gestures.header(cell, label, handle, id, () -> sortRequest.accept(id));
|
||||||
|
cell.setOnContextMenuRequested(event -> {
|
||||||
|
if (headerMenuFactory == null) return;
|
||||||
|
if (headerMenu != null) headerMenu.hide();
|
||||||
|
headerMenu = headerMenuFactory.apply(id, cell);
|
||||||
|
if (event.isKeyboardTrigger()) headerMenu.show(cell, Side.BOTTOM, 0, 0);
|
||||||
|
else headerMenu.show(cell, event.getScreenX(), event.getScreenY());
|
||||||
|
event.consume();
|
||||||
|
});
|
||||||
size(cell, width(id, sizes));
|
size(cell, width(id, sizes));
|
||||||
nodes.add(cell);
|
nodes.add(cell);
|
||||||
}
|
}
|
||||||
@@ -322,10 +575,6 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
region.setMaxWidth(width);
|
region.setMaxWidth(width);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void layoutRow(ResultRow view) {
|
|
||||||
layoutRow(view, order, widths);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void layoutRow(ResultRow view, List<String> ordering, Map<String, ColumnWidth> sizes) {
|
private void layoutRow(ResultRow view, List<String> ordering, Map<String, ColumnWidth> sizes) {
|
||||||
Set<Region> fields = Collections.newSetFromMap(new IdentityHashMap<>());
|
Set<Region> fields = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||||
fields.addAll(view.fields().values());
|
fields.addAll(view.fields().values());
|
||||||
@@ -335,16 +584,36 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
size(field, width(id, sizes));
|
size(field, width(id, sizes));
|
||||||
children.add(field);
|
children.add(field);
|
||||||
}
|
}
|
||||||
for (Node child : view.root().getChildren())
|
ResultColumnSeparators separators = null;
|
||||||
if (!fields.contains(child)) children.add(child);
|
for (Node child : view.root().getChildren()) {
|
||||||
|
if (child instanceof ResultColumnSeparators existing) separators = existing;
|
||||||
|
else if (!fields.contains(child)) children.add(child);
|
||||||
|
}
|
||||||
|
if (columnSeparators) {
|
||||||
|
if (separators == null || !separators.matchesColumnCount(ordering.size()))
|
||||||
|
separators = new ResultColumnSeparators(view.root(), ordering.size());
|
||||||
|
separators.position(ordering.stream().mapToDouble(id -> width(id, sizes)).toArray());
|
||||||
|
children.add(separators);
|
||||||
|
}
|
||||||
view.root().setSpacing(0);
|
view.root().setSpacing(0);
|
||||||
|
if (!view.root().getChildren().equals(children)) {
|
||||||
|
Node focus =
|
||||||
|
view.root().getScene() == null ? null : view.root().getScene().getFocusOwner();
|
||||||
|
boolean restore = focus != null && descendant(view.root(), focus);
|
||||||
view.root().getChildren().setAll(children);
|
view.root().getChildren().setAll(children);
|
||||||
|
if (restore) {
|
||||||
|
if (descendant(view.root(), focus)) focus.requestFocus();
|
||||||
|
else view.root().requestFocus();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void markSelection() {
|
private void markSelection() {
|
||||||
T loaded = null;
|
T loaded = null;
|
||||||
|
List<T> actionable = new ArrayList<>();
|
||||||
|
Set<K> keys = new HashSet<>(selectedKeys);
|
||||||
for (var e : entries) {
|
for (var e : entries) {
|
||||||
boolean selected = Objects.equals(selectedKey.get(), e.row().key());
|
boolean selected = keys.contains(e.row().key());
|
||||||
e.view()
|
e.view()
|
||||||
.root()
|
.root()
|
||||||
.pseudoClassStateChanged(
|
.pseudoClassStateChanged(
|
||||||
@@ -352,16 +621,341 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
e.view().root().getStyleClass().remove("selected");
|
e.view().root().getStyleClass().remove("selected");
|
||||||
if (selected) {
|
if (selected) {
|
||||||
e.view().root().getStyleClass().add("selected");
|
e.view().root().getStyleClass().add("selected");
|
||||||
loaded = e.row().model();
|
if (rowsInteractive && e.view().root().getParent() == body) {
|
||||||
|
actionable.add(e.row().model());
|
||||||
|
if (Objects.equals(selectedKey.get(), e.row().key())) loaded = e.row().model();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
selectedElement.set(rowsInteractive ? loaded : null);
|
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) {
|
||||||
|
layoutCommitted = Objects.requireNonNull(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOnInteractionMessage(java.util.function.Consumer<String> handler) {
|
||||||
|
interactionMessage = Objects.requireNonNull(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
void message(String text) {
|
||||||
|
interactionMessage.accept(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ResultColumn> definitions() {
|
||||||
|
return List.copyOf(definitions.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
ResultHeaderGestures gestures() {
|
||||||
|
return gestures;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean canGroup(String id) {
|
||||||
|
return groupingEnabled && groupColumns.stream().anyMatch(c -> c.id().equals(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> groupingColumns() {
|
||||||
|
return grouping;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean groupingEnabled() {
|
||||||
|
return groupingEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupingSetup groupingSetup() {
|
||||||
|
return new GroupingSetup(grouping, expansion.snapshot());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void configureGrouping(
|
||||||
|
List<GroupColumn<T>> columns,
|
||||||
|
boolean enabled,
|
||||||
|
List<String> defaults,
|
||||||
|
boolean collapsed,
|
||||||
|
int historyLimit) {
|
||||||
|
checkOpen();
|
||||||
|
if (!entries.isEmpty())
|
||||||
|
throw new IllegalStateException("Configure grouping before first publication");
|
||||||
|
if (historyLimit < 0
|
||||||
|
|| !definitions
|
||||||
|
.keySet()
|
||||||
|
.containsAll(columns.stream().map(GroupColumn::id).toList()))
|
||||||
|
throw new IllegalArgumentException("Unknown group column or invalid history limit");
|
||||||
|
var snapshot = GroupProjection.<K, T>capture(List.of(), columns);
|
||||||
|
GroupProjection.project(snapshot, defaults);
|
||||||
|
groupColumns = List.copyOf(columns);
|
||||||
|
captured = snapshot;
|
||||||
|
groupingEnabled = enabled;
|
||||||
|
grouping = List.copyOf(defaults);
|
||||||
|
defaultCollapsed = collapsed;
|
||||||
|
inactiveHistoryLimit = historyLimit;
|
||||||
|
expansion = new GroupExpansion(collapsed, historyLimit);
|
||||||
|
drawGroups();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validateGrouping(GroupingSetup setup) {
|
||||||
|
Set<String> ids =
|
||||||
|
groupColumns.stream()
|
||||||
|
.map(GroupColumn::id)
|
||||||
|
.collect(java.util.stream.Collectors.toSet());
|
||||||
|
if (!ids.containsAll(setup.columns()))
|
||||||
|
throw new IllegalArgumentException("Column has no grouping mapping");
|
||||||
|
for (var choice : setup.choices())
|
||||||
|
for (var part : choice.path().segments()) {
|
||||||
|
var column =
|
||||||
|
groupColumns.stream()
|
||||||
|
.filter(c -> c.id().equals(part.columnId()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() ->
|
||||||
|
new IllegalArgumentException(
|
||||||
|
"Unknown group path column; provide migration"));
|
||||||
|
column.validate(part.value());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupingColumns(List<String> ids) {
|
||||||
|
checkOpen();
|
||||||
|
var setup = new GroupingSetup(ids, expansion.snapshot());
|
||||||
|
validateGrouping(setup);
|
||||||
|
var next = GroupProjection.project(captured, ids);
|
||||||
|
grouping = setup.columns();
|
||||||
|
groupTree = next;
|
||||||
|
expansion.current(GroupProjection.paths(next));
|
||||||
|
drawGroups();
|
||||||
|
layoutCommitted.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Refresh mapping snapshots only after an explicit application data-update signal. */
|
||||||
|
public void regroup() {
|
||||||
|
checkOpen();
|
||||||
|
var next = GroupProjection.capture(entries.stream().map(Entry::row).toList(), groupColumns);
|
||||||
|
var tree = GroupProjection.project(next, grouping);
|
||||||
|
captured = next;
|
||||||
|
groupTree = tree;
|
||||||
|
expansion.current(GroupProjection.paths(tree));
|
||||||
|
drawGroups();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupingEnabled(boolean enabled) {
|
||||||
|
checkOpen();
|
||||||
|
groupingEnabled = enabled;
|
||||||
|
drawGroups();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetExpansion() {
|
||||||
|
checkOpen();
|
||||||
|
expansion.reset();
|
||||||
|
drawGroups();
|
||||||
|
layoutCommitted.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExpanded(GroupPath path, boolean expanded) {
|
||||||
|
checkOpen();
|
||||||
|
if (!GroupProjection.paths(groupTree).contains(path))
|
||||||
|
throw new IllegalArgumentException("Group is not on current page");
|
||||||
|
Node focus = body.getScene() == null ? null : body.getScene().getFocusOwner();
|
||||||
|
boolean hidesFocus = !expanded && focus != null && descendantContainsFocus(path, focus);
|
||||||
|
expansion.set(path, expanded);
|
||||||
|
drawGroups();
|
||||||
|
if (hidesFocus) disclosure.get(path).requestFocus();
|
||||||
|
layoutCommitted.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean descendantContainsFocus(GroupPath path, Node focus) {
|
||||||
|
for (var row : entries) {
|
||||||
|
if (!descendant(row.view().root(), focus)) continue;
|
||||||
|
var values =
|
||||||
|
captured.rows().stream()
|
||||||
|
.filter(r -> Objects.equals(r.row().key(), row.row().key()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.values();
|
||||||
|
return path.segments().stream()
|
||||||
|
.allMatch(p -> Objects.equals(values.get(p.columnId()).key(), p.value()));
|
||||||
|
}
|
||||||
|
return disclosure.entrySet().stream()
|
||||||
|
.anyMatch(e ->
|
||||||
|
descendant(e.getValue(), focus)
|
||||||
|
&& e.getKey().segments().size() > path.segments().size()
|
||||||
|
&& e.getKey()
|
||||||
|
.segments()
|
||||||
|
.subList(0, path.segments().size())
|
||||||
|
.equals(path.segments()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean descendant(Node ancestor, Node node) {
|
||||||
|
for (Node current = node; current != null; current = current.getParent())
|
||||||
|
if (current == ancestor) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawGroups() {
|
||||||
|
Node focus = body.getScene() == null ? null : body.getScene().getFocusOwner();
|
||||||
|
boolean restoreFocus = focus != null && descendant(body, focus);
|
||||||
|
GroupPath focusedPath = restoreFocus ? focusPath(focus) : null;
|
||||||
|
disclosure.keySet().retainAll(new HashSet<>(GroupProjection.paths(groupTree)));
|
||||||
|
List<Node> nodes = new ArrayList<>();
|
||||||
|
Map<K, Node> rows = new HashMap<>();
|
||||||
|
entries.forEach(e -> rows.put(e.row().key(), e.view().root()));
|
||||||
|
if (!groupingEnabled || grouping.isEmpty())
|
||||||
|
entries.forEach(e -> nodes.add(e.view().root()));
|
||||||
|
else appendGroups(nodes, groupTree, rows);
|
||||||
|
if (!body.getChildren().equals(nodes)) body.getChildren().setAll(nodes);
|
||||||
|
if (restoreFocus) {
|
||||||
|
if (descendant(body, focus)) focus.requestFocus();
|
||||||
|
else {
|
||||||
|
Button destination = null;
|
||||||
|
if (focusedPath != null)
|
||||||
|
for (int level = 1; level <= focusedPath.segments().size(); level++) {
|
||||||
|
var candidate =
|
||||||
|
disclosure.get(
|
||||||
|
new GroupPath(focusedPath.segments().subList(0, level)));
|
||||||
|
if (candidate != null && candidate.getParent() == body)
|
||||||
|
destination = candidate;
|
||||||
|
if (candidate != null
|
||||||
|
&& !expansion.expanded(
|
||||||
|
new GroupPath(focusedPath.segments().subList(0, level))))
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (destination != null) destination.requestFocus();
|
||||||
|
else if (!header.getChildren().isEmpty())
|
||||||
|
((HBox) header.getChildren().getFirst())
|
||||||
|
.getChildren()
|
||||||
|
.getFirst()
|
||||||
|
.requestFocus();
|
||||||
|
else if (headerAccessory != null) headerAccessory.requestFocus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resizeGroupHeadings();
|
||||||
|
markSelection();
|
||||||
|
}
|
||||||
|
|
||||||
|
private GroupPath focusPath(Node focus) {
|
||||||
|
for (var entry : entries)
|
||||||
|
if (descendant(entry.view().root(), focus) && !grouping.isEmpty()) {
|
||||||
|
var values =
|
||||||
|
captured.rows().stream()
|
||||||
|
.filter(r -> Objects.equals(r.row().key(), entry.row().key()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.values();
|
||||||
|
return new GroupPath(
|
||||||
|
grouping.stream()
|
||||||
|
.map(id -> new GroupPath.Segment(id, values.get(id).key()))
|
||||||
|
.toList());
|
||||||
|
}
|
||||||
|
return disclosure.entrySet().stream()
|
||||||
|
.filter(e -> descendant(e.getValue(), focus))
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void appendGroups(
|
||||||
|
List<Node> nodes, List<GroupProjection.Node<K, T>> groups, Map<K, Node> rows) {
|
||||||
|
for (var group : groups) {
|
||||||
|
Button button =
|
||||||
|
disclosure.computeIfAbsent(
|
||||||
|
group.path(),
|
||||||
|
path -> {
|
||||||
|
Button control =
|
||||||
|
new Button() {
|
||||||
|
@Override
|
||||||
|
public Object queryAccessibleAttribute(
|
||||||
|
javafx.scene.AccessibleAttribute attribute,
|
||||||
|
Object... parameters) {
|
||||||
|
if (attribute
|
||||||
|
== javafx.scene.AccessibleAttribute
|
||||||
|
.EXPANDED)
|
||||||
|
return expansion.expanded(path);
|
||||||
|
if (attribute
|
||||||
|
== javafx.scene.AccessibleAttribute.LEAF)
|
||||||
|
return false;
|
||||||
|
return super.queryAccessibleAttribute(
|
||||||
|
attribute, parameters);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
control.setAccessibleRole(javafx.scene.AccessibleRole.TREE_ITEM);
|
||||||
|
control.getStyleClass().add("group-heading");
|
||||||
|
control.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
|
||||||
|
control.setOnAction(
|
||||||
|
e -> setExpanded(path, !expansion.expanded(path)));
|
||||||
|
control.setOnKeyPressed(e -> {
|
||||||
|
if (e.getCode() == javafx.scene.input.KeyCode.LEFT) {
|
||||||
|
setExpanded(path, false);
|
||||||
|
e.consume();
|
||||||
|
}
|
||||||
|
if (e.getCode() == javafx.scene.input.KeyCode.RIGHT) {
|
||||||
|
setExpanded(path, true);
|
||||||
|
e.consume();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return control;
|
||||||
|
});
|
||||||
|
String id = group.path().segments().getLast().columnId();
|
||||||
|
boolean open = expansion.expanded(group.path());
|
||||||
|
button.setText(
|
||||||
|
(open ? "▾ " : "▸ ")
|
||||||
|
+ definitions.get(id).header()
|
||||||
|
+ ": "
|
||||||
|
+ group.label()
|
||||||
|
+ " — "
|
||||||
|
+ group.count()
|
||||||
|
+ " records");
|
||||||
|
button.setAccessibleText(
|
||||||
|
definitions.get(id).header()
|
||||||
|
+ ": "
|
||||||
|
+ group.label()
|
||||||
|
+ ", "
|
||||||
|
+ group.count()
|
||||||
|
+ " records, "
|
||||||
|
+ (open ? "expanded" : "collapsed"));
|
||||||
|
button.setPadding(
|
||||||
|
new javafx.geometry.Insets(
|
||||||
|
6, 8, 6, 8 + 24 * (group.path().segments().size() - 1)));
|
||||||
|
button.notifyAccessibleAttributeChanged(javafx.scene.AccessibleAttribute.EXPANDED);
|
||||||
|
nodes.add(button);
|
||||||
|
if (open) {
|
||||||
|
if (group.children().isEmpty())
|
||||||
|
group.rows().forEach(row -> nodes.add(rows.get(row.key())));
|
||||||
|
else appendGroups(nodes, group.children(), rows);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resizeGroupHeadings() {
|
||||||
|
resizeGroupHeadings(visibleOrder(order), widths);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resizeGroupHeadings(List<String> visible, Map<String, ColumnWidth> sizes) {
|
||||||
|
double total = visible.stream().mapToDouble(id -> width(id, sizes)).sum();
|
||||||
|
disclosure.values().forEach(
|
||||||
|
button -> size(button, visible.isEmpty() ? Region.USE_COMPUTED_SIZE : total));
|
||||||
|
}
|
||||||
|
|
||||||
|
void previewWidth(String id, ColumnWidth value) {
|
||||||
|
var next = new LinkedHashMap<>(widths);
|
||||||
|
next.put(id, value);
|
||||||
|
applyWidths(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applyWidths(Map<String, ColumnWidth> sizes) {
|
||||||
|
for (Node node : header.getChildren())
|
||||||
|
size((Region) node, width((String) node.getUserData(), sizes));
|
||||||
|
var visible = visibleOrder(order);
|
||||||
|
entries.forEach(e -> layoutRow(e.view(), visible, sizes));
|
||||||
|
resizeGroupHeadings(visible, sizes);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void release(List<Entry<K, T>> retired) {
|
private void release(List<Entry<K, T>> retired) {
|
||||||
RuntimeException aggregate = null;
|
RuntimeException aggregate = null;
|
||||||
for (var e : retired) {
|
for (var e : retired) {
|
||||||
e.view().root().removeEventHandler(MouseEvent.MOUSE_CLICKED, e.click());
|
e.view().root().removeEventHandler(MouseEvent.MOUSE_CLICKED, e.click());
|
||||||
|
e.view().root().removeEventHandler(KeyEvent.KEY_PRESSED, e.key());
|
||||||
try {
|
try {
|
||||||
e.view().dispose().run();
|
e.view().dispose().run();
|
||||||
} catch (RuntimeException failure) {
|
} catch (RuntimeException failure) {
|
||||||
@@ -390,10 +984,20 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
var old = entries;
|
var old = entries;
|
||||||
entries = List.of();
|
entries = List.of();
|
||||||
body.getChildren().clear();
|
body.getChildren().clear();
|
||||||
header.getChildren().clear();
|
replaceHeader(List.of());
|
||||||
body.setOnMouseClicked(null);
|
body.setOnMouseClicked(null);
|
||||||
selectedKey.set(null);
|
selectedKey.set(null);
|
||||||
selectedElement.set(null);
|
selectedElement.set(null);
|
||||||
|
selectedKeys.clear();
|
||||||
|
selectedElements.clear();
|
||||||
|
selection.set(GridSelection.empty());
|
||||||
|
anchor = null;
|
||||||
|
captured = GroupProjection.capture(List.of(), List.of());
|
||||||
|
groupTree = List.of();
|
||||||
|
disclosure.clear();
|
||||||
|
expansion.reset();
|
||||||
|
gestures.close();
|
||||||
|
scrollAlignment.close();
|
||||||
release(old);
|
release(old);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<Runnable> 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<T> void listen(ObservableValue<T> observable, ChangeListener<? super T> listener) {
|
||||||
|
observable.addListener(listener);
|
||||||
|
own(() -> observable.removeListener(listener));
|
||||||
|
}
|
||||||
|
|
||||||
|
<T> void listen(ObservableList<T> observable, ListChangeListener<? super T> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
package de.neitzel.fx.view;
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.i18n.Localizer;
|
||||||
|
import de.neitzel.fx.i18n.Messages;
|
||||||
import de.neitzel.injection.ApplicationContext;
|
import de.neitzel.injection.ApplicationContext;
|
||||||
import javafx.fxml.FXMLLoader;
|
import javafx.fxml.FXMLLoader;
|
||||||
import javafx.scene.Parent;
|
import javafx.scene.Parent;
|
||||||
@@ -75,13 +77,59 @@ public final class ViewLoader {
|
|||||||
* @throws IllegalArgumentException when a Direct binding names a path that is not a read-write Attribute
|
* @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) {
|
public static LoadedView load(URL fxml, Object model, ApplicationContext context) {
|
||||||
Class<?> viewModelClass = ViewModels.namedOn(FxmlControllers.controllerClass(fxml));
|
return load(fxml, model, context, new ViewLifetime(ViewModels.LEGACY));
|
||||||
Object viewModel = ViewModels.of(model, viewModelClass);
|
}
|
||||||
LoadSession session = LoadSession.open();
|
|
||||||
|
/**
|
||||||
|
* 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens a Component's own fx:root document with the supplied Model. The Component selects
|
||||||
|
* its ViewModel in the same context as its nested Views. Closing the result detaches its
|
||||||
|
* bindings and releases its controller and children.
|
||||||
|
*
|
||||||
|
* @param type the injected Component class with a sibling ClassName.fxml
|
||||||
|
* @param model the initial non-null Model
|
||||||
|
* @param context the application container
|
||||||
|
* @param models the owner of the View and its Model identity
|
||||||
|
* @return the initialized Component and its effective ViewModel
|
||||||
|
*/
|
||||||
|
public static LoadedView loadComponent(Class<? extends Parent> type, Object model,
|
||||||
|
ApplicationContext context, ViewModelContext models) {
|
||||||
|
java.util.Objects.requireNonNull(model, "Component Model");
|
||||||
|
ViewLifetime lifetime = models.openView();
|
||||||
try {
|
try {
|
||||||
FXMLLoader loader = new FXMLLoader(fxml);
|
Parent root = type.cast(Components.fresh(type, context, lifetime));
|
||||||
loader.setControllerFactory(type -> controller(context, type));
|
Components.setModel(root, model, lifetime);
|
||||||
loader.setBuilderFactory(type -> Components.builder(type, context));
|
Object viewModel = ViewModels.of(models, model, ViewModels.namedOn(type));
|
||||||
|
return new LoadedView(root, viewModel, lifetime);
|
||||||
|
} catch (RuntimeException | Error failure) {
|
||||||
|
lifetime.rollback(failure);
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
FxmlHandlers.observe(loader, lifetime);
|
||||||
|
loader.setControllerFactory(type -> createController(context, type, lifetime));
|
||||||
|
loader.setBuilderFactory(type -> Components.builder(type, context, lifetime));
|
||||||
Object loaded = loader.load();
|
Object loaded = loader.load();
|
||||||
if (!(loaded instanceof Parent root)) {
|
if (!(loaded instanceof Parent root)) {
|
||||||
throw new IllegalArgumentException("View root must be a parent");
|
throw new IllegalArgumentException("View root must be a parent");
|
||||||
@@ -93,26 +141,39 @@ public final class ViewLoader {
|
|||||||
if (controller instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) {
|
if (controller instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) {
|
||||||
hasViewModel.setViewModel(bound);
|
hasViewModel.setViewModel(bound);
|
||||||
}
|
}
|
||||||
|
CommandBindingApplier.validate(session.bindingLists(), loader.getNamespace());
|
||||||
for (BindingList bindingList : session.bindingLists()) {
|
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);
|
Table.openAll(root, viewModel, context, lifetime);
|
||||||
return new LoadedView(root, viewModel);
|
session.checkFailure();
|
||||||
|
return new LoadedView(root, viewModel, lifetime);
|
||||||
} catch (IOException failure) {
|
} catch (IOException failure) {
|
||||||
|
lifetime.rollback(failure);
|
||||||
throw new IllegalStateException("Could not load view " + fxml, failure);
|
throw new IllegalStateException("Could not load view " + fxml, failure);
|
||||||
|
} catch (RuntimeException | Error failure) {
|
||||||
|
lifetime.rollback(failure);
|
||||||
|
throw failure;
|
||||||
} finally {
|
} finally {
|
||||||
LoadSession.close();
|
LoadSession.unnest();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
static Object createController(ApplicationContext context, Class<?> type, ViewLifetime lifetime) {
|
||||||
* Asks the container for the Controller class named by the document.
|
if (!lifetime.managed()) return context.getComponent(type);
|
||||||
*
|
Object controller = context.createComponent(type);
|
||||||
* @param context the container
|
lifetime.ownController(controller);
|
||||||
* @param type the Controller class
|
return controller;
|
||||||
* @return the Controller
|
|
||||||
*/
|
|
||||||
private static Object controller(ApplicationContext context, Class<?> type) {
|
|
||||||
return context.getComponent(type.asSubclass(Object.class));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static Messages resources(ApplicationContext context, URL fxml, Class<?> type) {
|
||||||
|
Localizer languages;
|
||||||
|
try {
|
||||||
|
languages = context.getComponent(Localizer.class);
|
||||||
|
} catch (IllegalArgumentException unregistered) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return languages.forView(fxml, type);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,6 +80,7 @@ public class ViewModel {
|
|||||||
* The Model instance this ViewModel was built for.
|
* The Model instance this ViewModel was built for.
|
||||||
*/
|
*/
|
||||||
private final Object model;
|
private final Object model;
|
||||||
|
private final ViewModelContext models;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JavaFX properties keyed by Attribute name.
|
* JavaFX properties keyed by Attribute name.
|
||||||
@@ -136,7 +137,8 @@ public class ViewModel {
|
|||||||
*/
|
*/
|
||||||
protected ViewModel(Object model) {
|
protected ViewModel(Object model) {
|
||||||
this.model = model;
|
this.model = model;
|
||||||
ViewModels.register(model, this);
|
models = ViewModels.constructingContext();
|
||||||
|
models.viewModels().put(model, this);
|
||||||
for (PropertyDescriptor descriptor : descriptors(model.getClass())) {
|
for (PropertyDescriptor descriptor : descriptors(model.getClass())) {
|
||||||
Method getter = descriptor.getReadMethod();
|
Method getter = descriptor.getReadMethod();
|
||||||
Method setter = descriptor.getWriteMethod();
|
Method setter = descriptor.getWriteMethod();
|
||||||
@@ -218,9 +220,9 @@ public class ViewModel {
|
|||||||
* @param listener the listener
|
* @param listener the listener
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
void addAttributeListener(ChangeListener<Object> listener) {
|
void addAttributeListener(ViewLifetime lifetime, ChangeListener<Object> listener) {
|
||||||
for (Property<?> property : properties.values()) {
|
for (Property<?> property : properties.values()) {
|
||||||
((Property<Object>) property).addListener(listener);
|
lifetime.listen((Property<Object>) property, listener);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -429,7 +431,7 @@ public class ViewModel {
|
|||||||
* Attaching the change listener reads the value. That read is ignored until
|
* Attaching the change listener reads the value. That read is ignored until
|
||||||
* {@link #attached()} so a Component annotation can name the class first.
|
* {@link #attached()} so a Component annotation can name the class first.
|
||||||
*/
|
*/
|
||||||
private static final class LazyComplex extends SimpleObjectProperty<Object> {
|
private final class LazyComplex extends SimpleObjectProperty<Object> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Model instance, kept until the nested ViewModel is built.
|
* The Model instance, kept until the nested ViewModel is built.
|
||||||
@@ -464,7 +466,7 @@ public class ViewModel {
|
|||||||
public Object get() {
|
public Object get() {
|
||||||
if (!attaching && !realized) {
|
if (!attaching && !realized) {
|
||||||
realized = true;
|
realized = true;
|
||||||
super.set(current == null ? null : ViewModels.of(current));
|
super.set(current == null ? null : ViewModels.of(models, current, null));
|
||||||
}
|
}
|
||||||
return super.get();
|
return super.get();
|
||||||
}
|
}
|
||||||
@@ -835,7 +837,7 @@ public class ViewModel {
|
|||||||
* @return {@code true} when the element is a simple value
|
* @return {@code true} when the element is a simple value
|
||||||
*/
|
*/
|
||||||
private static boolean isSimpleValue(Class<?> type) {
|
private static boolean isSimpleValue(Class<?> type) {
|
||||||
if (type == String.class || type == Boolean.class || type == boolean.class || type.isEnum()) {
|
if (type == String.class || type == Boolean.class || type == boolean.class || type.isEnum() || type.isRecord()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (type.isPrimitive()) {
|
if (type.isPrimitive()) {
|
||||||
|
|||||||
@@ -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<Object, Object> viewModels = new IdentityHashMap<>();
|
||||||
|
private final ViewLifetime views = new ViewLifetime(this);
|
||||||
|
private boolean closed;
|
||||||
|
|
||||||
|
ViewLifetime openView() {
|
||||||
|
checkOpen();
|
||||||
|
return views.child();
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<Object, Object> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ package de.neitzel.fx.view;
|
|||||||
|
|
||||||
import java.lang.reflect.Constructor;
|
import java.lang.reflect.Constructor;
|
||||||
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.InvocationTargetException;
|
||||||
import java.util.IdentityHashMap;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -15,7 +14,10 @@ final class ViewModels {
|
|||||||
/**
|
/**
|
||||||
* ViewModels already built, keyed by Model identity.
|
* ViewModels already built, keyed by Model identity.
|
||||||
*/
|
*/
|
||||||
private static final Map<Object, Object> 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<ViewModelContext> CONSTRUCTING = new ThreadLocal<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prevents instantiation.
|
* Prevents instantiation.
|
||||||
@@ -23,32 +25,26 @@ final class ViewModels {
|
|||||||
private 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) {
|
static Object of(Object model) {
|
||||||
return of(model, null);
|
return of(model, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the ViewModel for a Model instance.
|
|
||||||
* <p>
|
|
||||||
* 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) {
|
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<Object, Object> instances = context.viewModels();
|
||||||
Class<?> selected = ViewModelDefaults.select(model.getClass(), viewModelClass, model.getClass().getClassLoader());
|
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 (existing != null) {
|
||||||
if (viewModelClass != null && viewModelClass != ViewModel.class
|
if (viewModelClass != null && viewModelClass != ViewModel.class
|
||||||
&& !selected.isInstance(existing)) {
|
&& !selected.isInstance(existing)) {
|
||||||
@@ -58,8 +54,22 @@ final class ViewModels {
|
|||||||
}
|
}
|
||||||
return existing;
|
return existing;
|
||||||
}
|
}
|
||||||
if (selected == ViewModel.class) return new ViewModel(model);
|
ViewModelContext previous = CONSTRUCTING.get();
|
||||||
return construct(model, selected);
|
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.
|
* Constructs a ViewModel or a replacement with the Model instance.
|
||||||
* <p>
|
* <p>
|
||||||
* A result that is not a {@link ViewModel} is registered here. A {@link ViewModel} registers
|
* A {@link ViewModel} registers itself from its constructor, before its Attributes are walked.
|
||||||
* itself from its constructor, before its Attributes are walked.
|
|
||||||
*
|
*
|
||||||
* @param model the Model instance
|
* @param model the Model instance
|
||||||
* @param viewModelClass the class to construct
|
* @param viewModelClass the class to construct
|
||||||
@@ -94,13 +103,8 @@ final class ViewModels {
|
|||||||
Constructor<?> constructor = constructor(model, viewModelClass);
|
Constructor<?> constructor = constructor(model, viewModelClass);
|
||||||
constructor.setAccessible(true);
|
constructor.setAccessible(true);
|
||||||
try {
|
try {
|
||||||
Object created = constructor.newInstance(model);
|
return constructor.newInstance(model);
|
||||||
if (!(created instanceof ViewModel)) {
|
|
||||||
register(model, created);
|
|
||||||
}
|
|
||||||
return created;
|
|
||||||
} catch (InvocationTargetException failure) {
|
} catch (InvocationTargetException failure) {
|
||||||
BY_INSTANCE.remove(model);
|
|
||||||
if (failure.getCause() instanceof RuntimeException runtime) {
|
if (failure.getCause() instanceof RuntimeException runtime) {
|
||||||
throw runtime;
|
throw runtime;
|
||||||
}
|
}
|
||||||
@@ -138,13 +142,4 @@ final class ViewModels {
|
|||||||
return chosen;
|
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
language.menu=Language
|
||||||
|
language.reopen=The language has changed. Some texts update when you reopen the window.
|
||||||
|
|
||||||
|
dock.action.move=Move to
|
||||||
|
dock.action.split=Split
|
||||||
|
dock.action.close=Close
|
||||||
|
dock.action.float=Float
|
||||||
|
dock.action.return=Return to main
|
||||||
|
dock.action.pin=Pin group
|
||||||
|
dock.side.TOP=Above
|
||||||
|
dock.side.RIGHT=Right
|
||||||
|
dock.side.BOTTOM=Below
|
||||||
|
dock.side.LEFT=Left
|
||||||
|
dock.action.unavailable={0} ({1})
|
||||||
|
dock.action.noChange={0} (Already here)
|
||||||
|
dock.failure.generic=The operation cannot be completed
|
||||||
|
dock.failure.LAYOUT_CHANGE_IN_PROGRESS=A layout change is in progress
|
||||||
|
dock.failure.RESTORE_REQUIRES_EMPTY_MANAGER=Restore requires an empty manager
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_VERSION=This snapshot version is not supported
|
||||||
|
dock.failure.INVALID_SNAPSHOT=The snapshot is invalid
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_FEATURE=This snapshot feature is not supported
|
||||||
|
dock.failure.DOCKABLE_LOAD_FAILED=The content could not be loaded
|
||||||
|
dock.failure.MISSING_DOCKABLE=The requested content is unavailable
|
||||||
|
dock.failure.INVALID_GROUP_CONFIGURATION=The group settings are incompatible
|
||||||
|
dock.failure.COLLAPSE_DISABLED=This group cannot collapse
|
||||||
|
dock.failure.SPLIT_DISABLED=This group cannot split in that direction
|
||||||
|
dock.failure.SPLIT_TOO_SMALL=There is not enough space to split this group
|
||||||
|
dock.failure.TARGET_NOT_FOUND=The destination is unavailable
|
||||||
|
dock.failure.REFERENCE_TAB_NOT_FOUND=The reference tab is unavailable
|
||||||
|
dock.failure.DOCKABLE_NOT_FOUND=The content is not open
|
||||||
|
dock.failure.CONTENT_ALREADY_ATTACHED=The content already belongs to a view
|
||||||
|
dock.failure.PLACEMENT_REJECTED=This placement is not allowed
|
||||||
|
dock.failure.PLACEMENT_CHECK_FAILED=The placement check failed
|
||||||
|
dock.failure.ID_MISMATCH=The created content has a different identity
|
||||||
|
dock.failure.FACTORY_FAILED=The content could not be created
|
||||||
|
dock.failure.MAIN_WINDOW_ONLY=This content must remain in the main window
|
||||||
|
dock.failure.CLOSE_IN_PROGRESS=A close decision is pending
|
||||||
|
dock.failure.CLOSE_CHECK_FAILED=The close check failed
|
||||||
|
dock.failure.CLEANUP_FAILED=Resource release failed
|
||||||
|
dock.failure.INVALID_WINDOW_BOUNDS=The window bounds are invalid
|
||||||
|
dock.failure.WINDOW_CREATION_FAILED=The floating window could not be prepared
|
||||||
|
|
||||||
|
dock.failure.SHUTDOWN_CALLBACK_FAILED=The shutdown preparation failed
|
||||||
|
dock.failure.MANAGER_CLOSED=The docking manager has ended
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
language.menu=Sprache
|
||||||
|
language.reopen=Die Sprache wurde geändert. Einige Texte werden beim erneuten Öffnen des Fensters aktualisiert.
|
||||||
|
|
||||||
|
dock.action.move=Verschieben nach
|
||||||
|
dock.action.split=Teilen
|
||||||
|
dock.action.close=Schließen
|
||||||
|
dock.action.float=Abdocken
|
||||||
|
dock.action.return=Ins Hauptfenster zurückholen
|
||||||
|
dock.action.pin=Gruppe anheften
|
||||||
|
dock.side.TOP=Oben
|
||||||
|
dock.side.RIGHT=Rechts
|
||||||
|
dock.side.BOTTOM=Unten
|
||||||
|
dock.side.LEFT=Links
|
||||||
|
dock.action.unavailable={0} ({1})
|
||||||
|
dock.action.noChange={0} (bereits hier)
|
||||||
|
dock.failure.generic=Der Vorgang konnte nicht abgeschlossen werden.
|
||||||
|
dock.failure.LAYOUT_CHANGE_IN_PROGRESS=Eine Layoutänderung läuft.
|
||||||
|
dock.failure.RESTORE_REQUIRES_EMPTY_MANAGER=Zum Wiederherstellen muss der Arbeitsbereich leer sein.
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_VERSION=Diese Layoutversion wird nicht unterstützt.
|
||||||
|
dock.failure.INVALID_SNAPSHOT=Das gespeicherte Layout ist ungültig.
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_FEATURE=Dieses Layoutmerkmal wird nicht unterstützt.
|
||||||
|
dock.failure.DOCKABLE_LOAD_FAILED=Der Inhalt konnte nicht geladen werden.
|
||||||
|
dock.failure.MISSING_DOCKABLE=Der angeforderte Inhalt ist nicht verfügbar.
|
||||||
|
dock.failure.INVALID_GROUP_CONFIGURATION=Die Gruppeneinstellungen sind inkompatibel.
|
||||||
|
dock.failure.COLLAPSE_DISABLED=Diese Gruppe kann nicht eingeklappt werden.
|
||||||
|
dock.failure.SPLIT_DISABLED=Die Gruppe kann in dieser Richtung nicht geteilt werden.
|
||||||
|
dock.failure.SPLIT_TOO_SMALL=Zum Teilen der Gruppe fehlt Platz.
|
||||||
|
dock.failure.TARGET_NOT_FOUND=Das Ziel ist nicht verfügbar.
|
||||||
|
dock.failure.REFERENCE_TAB_NOT_FOUND=Der Referenzreiter ist nicht verfügbar.
|
||||||
|
dock.failure.DOCKABLE_NOT_FOUND=Der Inhalt ist nicht geöffnet.
|
||||||
|
dock.failure.CONTENT_ALREADY_ATTACHED=Der Inhalt gehört bereits zu einer Ansicht.
|
||||||
|
dock.failure.PLACEMENT_REJECTED=Diese Platzierung ist nicht zulässig.
|
||||||
|
dock.failure.PLACEMENT_CHECK_FAILED=Die Platzierung konnte nicht geprüft werden.
|
||||||
|
dock.failure.ID_MISMATCH=Der erzeugte Inhalt hat eine andere Identität.
|
||||||
|
dock.failure.FACTORY_FAILED=Der Inhalt konnte nicht erzeugt werden.
|
||||||
|
dock.failure.MAIN_WINDOW_ONLY=Dieser Inhalt muss im Hauptfenster bleiben.
|
||||||
|
dock.failure.CLOSE_IN_PROGRESS=Eine Schließanfrage ist bereits offen.
|
||||||
|
dock.failure.CLOSE_CHECK_FAILED=Die Schließanfrage konnte nicht geprüft werden.
|
||||||
|
dock.failure.CLEANUP_FAILED=Ressourcen konnten nicht freigegeben werden.
|
||||||
|
dock.failure.INVALID_WINDOW_BOUNDS=Die Fensterabmessungen sind ungültig.
|
||||||
|
dock.failure.WINDOW_CREATION_FAILED=Das abgedockte Fenster konnte nicht vorbereitet werden.
|
||||||
|
dock.failure.SHUTDOWN_CALLBACK_FAILED=Das Beenden konnte nicht vorbereitet werden.
|
||||||
|
dock.failure.MANAGER_CLOSED=Der Arbeitsbereich wurde bereits geschlossen.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
language.menu=Language
|
||||||
|
language.reopen=The language has changed. Some texts update when you reopen the window.
|
||||||
|
|
||||||
|
dock.action.move=Move to
|
||||||
|
dock.action.split=Split
|
||||||
|
dock.action.close=Close
|
||||||
|
dock.action.float=Float
|
||||||
|
dock.action.return=Return to main
|
||||||
|
dock.action.pin=Pin group
|
||||||
|
dock.side.TOP=Above
|
||||||
|
dock.side.RIGHT=Right
|
||||||
|
dock.side.BOTTOM=Below
|
||||||
|
dock.side.LEFT=Left
|
||||||
|
dock.action.unavailable={0} ({1})
|
||||||
|
dock.action.noChange={0} (Already here)
|
||||||
|
dock.failure.generic=The operation cannot be completed
|
||||||
|
dock.failure.LAYOUT_CHANGE_IN_PROGRESS=A layout change is in progress
|
||||||
|
dock.failure.RESTORE_REQUIRES_EMPTY_MANAGER=Restore requires an empty manager
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_VERSION=This snapshot version is not supported
|
||||||
|
dock.failure.INVALID_SNAPSHOT=The snapshot is invalid
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_FEATURE=This snapshot feature is not supported
|
||||||
|
dock.failure.DOCKABLE_LOAD_FAILED=The content could not be loaded
|
||||||
|
dock.failure.MISSING_DOCKABLE=The requested content is unavailable
|
||||||
|
dock.failure.INVALID_GROUP_CONFIGURATION=The group settings are incompatible
|
||||||
|
dock.failure.COLLAPSE_DISABLED=This group cannot collapse
|
||||||
|
dock.failure.SPLIT_DISABLED=This group cannot split in that direction
|
||||||
|
dock.failure.SPLIT_TOO_SMALL=There is not enough space to split this group
|
||||||
|
dock.failure.TARGET_NOT_FOUND=The destination is unavailable
|
||||||
|
dock.failure.REFERENCE_TAB_NOT_FOUND=The reference tab is unavailable
|
||||||
|
dock.failure.DOCKABLE_NOT_FOUND=The content is not open
|
||||||
|
dock.failure.CONTENT_ALREADY_ATTACHED=The content already belongs to a view
|
||||||
|
dock.failure.PLACEMENT_REJECTED=This placement is not allowed
|
||||||
|
dock.failure.PLACEMENT_CHECK_FAILED=The placement check failed
|
||||||
|
dock.failure.ID_MISMATCH=The created content has a different identity
|
||||||
|
dock.failure.FACTORY_FAILED=The content could not be created
|
||||||
|
dock.failure.MAIN_WINDOW_ONLY=This content must remain in the main window
|
||||||
|
dock.failure.CLOSE_IN_PROGRESS=A close decision is pending
|
||||||
|
dock.failure.CLOSE_CHECK_FAILED=The close check failed
|
||||||
|
dock.failure.CLEANUP_FAILED=Resource release failed
|
||||||
|
dock.failure.INVALID_WINDOW_BOUNDS=The window bounds are invalid
|
||||||
|
dock.failure.WINDOW_CREATION_FAILED=The floating window could not be prepared
|
||||||
|
|
||||||
|
dock.failure.SHUTDOWN_CALLBACK_FAILED=The shutdown preparation failed
|
||||||
|
dock.failure.MANAGER_CLOSED=The docking manager has ended
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
.tag-chip {
|
||||||
|
-fx-background-color: derive(-fx-base, 12%);
|
||||||
|
-fx-background-radius: 14;
|
||||||
|
-fx-border-color: -fx-outer-border;
|
||||||
|
-fx-border-radius: 14;
|
||||||
|
-fx-padding: 2 8 2 8;
|
||||||
|
}
|
||||||
|
.tag-chip .tag-chip-remove {
|
||||||
|
-fx-background-color: transparent;
|
||||||
|
-fx-padding: 0 1 0 3;
|
||||||
|
}
|
||||||
|
.tag-chip .tag-chip-remove:hover,
|
||||||
|
.tag-chip .tag-chip-remove:focused {
|
||||||
|
-fx-background-color: -fx-outer-border;
|
||||||
|
-fx-background-radius: 10;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
.data-grid-grouping { -fx-padding: 8; -fx-border-color: #8a9eb5; -fx-border-style: dashed; -fx-min-height: 42; }
|
||||||
|
.grouping-chip { -fx-padding: 4 8; -fx-alignment: center-left; -fx-background-color: #e8eff7; -fx-border-color: #8a9eb5; -fx-cursor: open-hand; }
|
||||||
|
.data-grid .column-cell { -fx-alignment: center-left; -fx-min-height: 32; }
|
||||||
|
.data-grid .column-header { -fx-padding: 5 6; }
|
||||||
|
.data-grid .data-grid-column-menu, .data-grid .data-grid-column-menu > .label { -fx-padding: 0; }
|
||||||
|
.data-grid .data-grid-column-menu > .arrow-button { -fx-padding: 0 8; }
|
||||||
|
.neitzel-theme .data-grid .data-grid-column-menu:focused { -fx-border-color: -nl-focus; }
|
||||||
|
.data-grid .column-resize:hover { -fx-background-color: #3776b6; }
|
||||||
|
.group-heading { -fx-background-color: #e8eff7; -fx-text-fill: #182b3b; -fx-border-color: transparent transparent #b4c4d5 transparent; -fx-background-radius: 0; -fx-alignment: center-left; }
|
||||||
|
.group-heading:focused { -fx-border-color: #3776b6; -fx-border-width: 2; }
|
||||||
|
.data-grid .drop-before { -fx-border-color: #2869bd; -fx-border-width: 0 0 0 4; }
|
||||||
|
.data-grid .drop-after { -fx-border-color: #2869bd; -fx-border-width: 0 4 0 0; }
|
||||||
|
.data-grid .drop-invalid { -fx-border-color: #a62e2e; -fx-border-width: 2; }
|
||||||
|
.neitzel-theme .grouping-chip, .neitzel-theme .group-heading { -fx-background-color: -nl-raised; -fx-text-fill: -nl-text; }
|
||||||
|
.neitzel-theme .group-heading:disabled { -fx-opacity: 1; }
|
||||||
|
.neitzel-theme .group-heading:focused { -fx-border-color: -nl-focus; }
|
||||||
|
.neitzel-theme .data-grid-grouping, .neitzel-theme .grouping-chip { -fx-border-color: -nl-border; }
|
||||||
|
.neitzel-theme .data-grid .column-resize:hover { -fx-background-color: -nl-focus; }
|
||||||
|
.grid-persistence-status { -fx-padding: 4 0; }
|
||||||
|
|
||||||
|
.data-grid .column-separator-line { -fx-stroke: -fx-box-border; -fx-stroke-width: 1; }
|
||||||
|
.neitzel-theme .data-grid .column-separator-line { -fx-stroke: -nl-border; }
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
.result-row:selected { -fx-background-color: -fx-selection-bar; }
|
||||||
|
.result-row:selected .label { -fx-text-fill: -fx-selection-bar-text; }
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import org.jsoup.Jsoup;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class HtmlDocumentTest {
|
||||||
|
@TempDir Path temporary;
|
||||||
|
|
||||||
|
@Test void stringSourceResolvesRelativeImagesWithoutFetchingItsAddress() {
|
||||||
|
var document = HtmlDocument.parse("<img src='../image.png'>", java.net.URI.create("https://example.test/path/page.html"));
|
||||||
|
assertTrue(document.hasExternalImages());
|
||||||
|
assertEquals("https://example.test/image.png", Jsoup.parse(document.externalImagesHtml()).selectFirst("img").attr("src"));
|
||||||
|
assertFalse(Jsoup.parse(document.offlineHtml()).selectFirst("img").hasAttr("src"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> HtmlDocument.parse("<p>Text</p>", java.net.URI.create("file:///tmp/page.html")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void resolvesOnlyWebImagesAndKeepsOfflineIndexingAndOriginalFileUnchanged() throws Exception {
|
||||||
|
String source = """
|
||||||
|
<base href="https://example.test/folder/page.html"><title>Example</title>
|
||||||
|
<script src="https://example.test/script"></script><iframe src="https://example.test/frame"></iframe>
|
||||||
|
<img src="picture.png" onerror="alert(1)"><img src="//cdn.example.test/image.jpg">
|
||||||
|
<img src="file:///etc/passwd"><img src="javascript:alert(1)">
|
||||||
|
<img src="data:image/svg+xml;base64,PHN2Zz4="><img src="data:image/png;base64,YWJj">
|
||||||
|
<a href="https://example.test/link">Text</a>
|
||||||
|
""";
|
||||||
|
var file = Files.writeString(temporary.resolve("page.html"), source);
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
assertTrue(preview.hasExternalImages());
|
||||||
|
var online = Jsoup.parse(preview.externalImagesHtml());
|
||||||
|
assertEquals(java.util.List.of("https://example.test/folder/picture.png", "https://cdn.example.test/image.jpg",
|
||||||
|
"data:image/svg+xml;base64,PHN2Zz4=", "data:image/png;base64,YWJj"), online.select("img[src]").eachAttr("src"));
|
||||||
|
assertTrue(online.select("script,iframe,base,[onerror],a[href]").isEmpty());
|
||||||
|
assertEquals(java.util.List.of("data:image/svg+xml;base64,PHN2Zz4=", "data:image/png;base64,YWJj"),
|
||||||
|
Jsoup.parse(preview.offlineHtml()).select("img[src]").eachAttr("src"));
|
||||||
|
assertEquals(source, Files.readString(file));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void relativeImagesWithoutWebBaseRemainUnavailable() throws Exception {
|
||||||
|
var file = Files.writeString(temporary.resolve("local.html"), "<img src='local.png'><img src='file:///tmp/local.png'>");
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
assertFalse(preview.hasExternalImages());
|
||||||
|
assertTrue(Jsoup.parse(preview.externalImagesHtml()).select("img[src]").isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void keepsSavedLayoutAndEmbeddedBackgroundsWhileGatingRemoteImages() throws Exception {
|
||||||
|
String svg = "data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E";
|
||||||
|
var file = Files.writeString(temporary.resolve("saved.html"), """
|
||||||
|
<html class="saved"><head><base href="https://example.test/path/">
|
||||||
|
<style>@import 'https://example.test/track.css';
|
||||||
|
.hero { width: 120px; background-image:url("%s"); }
|
||||||
|
@media (min-width: 200px) { .remote {background: url('../background.png')} }
|
||||||
|
@font-face {font-family: saved;src:url('https://example.test/font.woff2')}
|
||||||
|
</style></head><body class="page" style="margin:0">
|
||||||
|
<div class="hero" style="height:80px;background-image:url('%s')">Article</div>
|
||||||
|
<svg onload="alert(1)"></svg><script>alert(1)</script>
|
||||||
|
</body></html>
|
||||||
|
""".formatted(svg, svg.replace("'", "%27")));
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
assertTrue(preview.hasExternalImages(), "CSS backgrounds must enable the per-tab media button");
|
||||||
|
var offline = Jsoup.parse(preview.offlineHtml());
|
||||||
|
var online = Jsoup.parse(preview.externalImagesHtml());
|
||||||
|
assertEquals("saved", offline.selectFirst("html").className());
|
||||||
|
assertEquals("page", offline.body().className());
|
||||||
|
assertTrue(offline.selectFirst(".hero").attr("style").contains("data:image/svg+xml"));
|
||||||
|
assertTrue(offline.selectFirst("style").data().contains("data:image/svg+xml"));
|
||||||
|
assertFalse(offline.selectFirst("style").data().contains("background.png"));
|
||||||
|
assertTrue(online.selectFirst("style").data().contains("https://example.test/background.png"));
|
||||||
|
assertFalse(online.selectFirst("style").data().contains("track.css"));
|
||||||
|
assertFalse(online.selectFirst("style").data().contains("https://example.test/font.woff2"));
|
||||||
|
assertTrue(offline.select("script,iframe,svg,link,base,[onload]").isEmpty());
|
||||||
|
assertTrue(offline.selectFirst("meta[http-equiv]").attr("content").contains("img-src data:;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void preservesCustomWrappersAndCssThatTheParserDoesNotUnderstand() throws Exception {
|
||||||
|
String css = ".before {color: blue} @supports selector(:focus-visible) {.after {color:red}}";
|
||||||
|
var file = Files.writeString(temporary.resolve("modern.html"), "<html data-theme='light'><style>" + css
|
||||||
|
+ "</style><body><a-menu data-open='false' aria-hidden='true' class='menu'>Text</a-menu></body></html>");
|
||||||
|
var document = Jsoup.parse(HtmlDocument.read(file).offlineHtml());
|
||||||
|
assertEquals(css, document.selectFirst("style").data());
|
||||||
|
assertEquals("false", document.selectFirst("a-menu").attr("data-open"));
|
||||||
|
assertEquals("true", document.selectFirst("a-menu").attr("aria-hidden"));
|
||||||
|
assertEquals("light", document.selectFirst("html").attr("data-theme"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void aBrokenEmbeddedWebpDoesNotPreventOpeningTheDocument() throws Exception {
|
||||||
|
var file = Files.writeString(temporary.resolve("broken.html"), "<img src='data:image/webp;base64,abcde'><p>Readable text</p>");
|
||||||
|
assertTrue(HtmlDocument.read(file).offlineHtml().contains("Readable text"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.concurrent.Worker;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.layout.VBox;
|
||||||
|
import javafx.scene.web.WebView;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class HtmlViewerTest {
|
||||||
|
@TempDir Path temporary;
|
||||||
|
@BeforeAll static void toolkit() throws Exception {
|
||||||
|
var started = new CountDownLatch(1);
|
||||||
|
try { Platform.startup(started::countDown); }
|
||||||
|
catch (IllegalStateException running) { started.countDown(); }
|
||||||
|
assertTrue(started.await(10, TimeUnit.SECONDS));
|
||||||
|
fx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
private static void fx(Runnable action) throws Exception {
|
||||||
|
var task = new FutureTask<Void>(action, null);
|
||||||
|
Platform.runLater(task); task.get(10, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
private static void await(BooleanSupplier condition) throws Exception {
|
||||||
|
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
|
||||||
|
var matched = new AtomicBoolean();
|
||||||
|
while (System.nanoTime() < deadline) {
|
||||||
|
fx(() -> matched.set(condition.getAsBoolean()));
|
||||||
|
if (matched.get()) return;
|
||||||
|
Thread.sleep(20);
|
||||||
|
}
|
||||||
|
fail("Timed out waiting for HTML load");
|
||||||
|
}
|
||||||
|
private static WebView browser(HtmlViewer pane) { return (WebView) pane.lookup("WebView"); }
|
||||||
|
private static boolean loaded(HtmlViewer pane) {
|
||||||
|
return browser(pane).getEngine().getLoadWorker().getState() == Worker.State.SUCCEEDED;
|
||||||
|
}
|
||||||
|
private static String imageSource(HtmlViewer pane) {
|
||||||
|
return browser(pane).getEngine().getDocument().getElementsByTagName("img").item(0)
|
||||||
|
.getAttributes().getNamedItem("src") == null ? "" : browser(pane).getEngine().getDocument()
|
||||||
|
.getElementsByTagName("img").item(0).getAttributes().getNamedItem("src").getNodeValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HtmlViewer viewer(HtmlDocument document) {
|
||||||
|
var viewer = new HtmlViewer(); viewer.display(document); return viewer;
|
||||||
|
}
|
||||||
|
private static javafx.scene.control.Button media(HtmlViewer viewer) {
|
||||||
|
return (javafx.scene.control.Button) viewer.lookup(".html-viewer-media-load");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void boundLocalTextReplacesPendingWorkAndDetachesOnClose() throws Exception {
|
||||||
|
var ref = new AtomicReference<HtmlViewer>();
|
||||||
|
var source = new javafx.beans.property.SimpleStringProperty("<p>First</p>");
|
||||||
|
var replacement = new javafx.beans.property.SimpleStringProperty("<p>Second</p>");
|
||||||
|
fx(() -> {
|
||||||
|
var viewer = new HtmlViewer();
|
||||||
|
ref.set(viewer);
|
||||||
|
viewer.htmlProperty().bind(source);
|
||||||
|
viewer.htmlProperty().bind(replacement);
|
||||||
|
source.set("<p>Detached</p>");
|
||||||
|
replacement.set("<p>Third</p>");
|
||||||
|
});
|
||||||
|
var viewer = ref.get();
|
||||||
|
try {
|
||||||
|
await(() -> !viewer.isLoading() && loaded(viewer) && browser(viewer).getEngine().getDocument()
|
||||||
|
.getDocumentElement().getTextContent().contains("Third"));
|
||||||
|
fx(() -> {
|
||||||
|
viewer.clear();
|
||||||
|
assertEquals("<p>Third</p>", replacement.get());
|
||||||
|
replacement.set(null);
|
||||||
|
replacement.set(" ");
|
||||||
|
assertNull(viewer.getError());
|
||||||
|
assertFalse(viewer.isExternalImagesAllowed());
|
||||||
|
replacement.set("<p>Pending</p>");
|
||||||
|
viewer.close();
|
||||||
|
assertFalse(viewer.htmlProperty().isBound());
|
||||||
|
replacement.set("<p>Too late</p>");
|
||||||
|
assertFalse(viewer.isLoading());
|
||||||
|
assertEquals("<p>Pending</p>", viewer.getHtml());
|
||||||
|
});
|
||||||
|
} finally { fx(viewer::close); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void ordinaryFxmlConstructsAnIdleLocalizableControl() throws Exception {
|
||||||
|
fx(() -> {
|
||||||
|
var loader = new javafx.fxml.FXMLLoader();
|
||||||
|
String fxml = """
|
||||||
|
<?import de.neitzel.fx.control.HtmlViewer?>
|
||||||
|
<HtmlViewer xmlns:fx="http://javafx.com/fxml/1" mediaButtonVisible="false"
|
||||||
|
mediaLoadText="Bilder laden" mediaReloadText="Erneut laden"
|
||||||
|
mediaTooltipText="Nur diese Ansicht" noExternalMediaText="Keine externen Bilder"/>
|
||||||
|
""";
|
||||||
|
try {
|
||||||
|
HtmlViewer viewer = loader.load(new java.io.ByteArrayInputStream(fxml.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
try {
|
||||||
|
assertFalse(viewer.isLoading()); assertNull(viewer.getError());
|
||||||
|
assertFalse(viewer.isExternalImagesAvailable()); assertFalse(viewer.isExternalImagesAllowed());
|
||||||
|
assertFalse(viewer.isMediaButtonVisible()); assertFalse(viewer.getTop().isManaged());
|
||||||
|
assertEquals("Bilder laden", media(viewer).getText());
|
||||||
|
assertEquals("Keine externen Bilder", media(viewer).getTooltip().getText());
|
||||||
|
viewer.setMediaLoadText("Load images");
|
||||||
|
assertEquals("Load images", media(viewer).getText());
|
||||||
|
} finally { viewer.close(); }
|
||||||
|
} catch (java.io.IOException failure) { throw new RuntimeException(failure); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void asynchronousFailureReplacementAndCloseDoNotPublishStaleContent() throws Exception {
|
||||||
|
var ref = new AtomicReference<HtmlViewer>();
|
||||||
|
fx(() -> { ref.set(new HtmlViewer()); ref.get().load(temporary.resolve("missing.html")); });
|
||||||
|
try {
|
||||||
|
await(() -> !ref.get().isLoading() && ref.get().getError() != null);
|
||||||
|
fx(() -> {
|
||||||
|
assertInstanceOf(java.io.IOException.class, ref.get().getError());
|
||||||
|
ref.get().loadHtml("<p>Stale preparation</p>");
|
||||||
|
assertTrue(ref.get().isLoading());
|
||||||
|
ref.get().display(HtmlDocument.parse("<p>Current document</p>"));
|
||||||
|
});
|
||||||
|
await(() -> !ref.get().isLoading() && loaded(ref.get()));
|
||||||
|
fx(() -> {
|
||||||
|
assertNull(ref.get().getError());
|
||||||
|
assertEquals("Current document", browser(ref.get()).getEngine().getDocument().getElementsByTagName("p").item(0).getTextContent());
|
||||||
|
ref.get().clear();
|
||||||
|
assertFalse(ref.get().isExternalImagesAvailable()); assertFalse(ref.get().isExternalImagesAllowed());
|
||||||
|
ref.get().loadHtml("<p>Pending on close</p>");
|
||||||
|
ref.get().close();
|
||||||
|
assertFalse(ref.get().isLoading());
|
||||||
|
assertThrows(IllegalStateException.class, () -> ref.get().loadHtml("<p>Closed</p>"));
|
||||||
|
});
|
||||||
|
for (int i = 0; i < 4; i++) fx(() -> {});
|
||||||
|
fx(() -> {
|
||||||
|
assertFalse(ref.get().isLoading()); assertNull(ref.get().getError());
|
||||||
|
assertFalse(ref.get().isExternalImagesAvailable());
|
||||||
|
});
|
||||||
|
} finally { fx(() -> ref.get().close()); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void displaysEmbeddedSvgAndStylesheetAndInlineBackgroundImages() throws Exception {
|
||||||
|
String red = svg("red"), blue = svg("blue"), green = svg("lime");
|
||||||
|
var file = Files.writeString(temporary.resolve("embedded.html"), """
|
||||||
|
<style>body{margin:0;background:white}img,.tile{width:40px;height:40px;display:block}
|
||||||
|
.tile{background-image:url('%s')}</style>
|
||||||
|
<img src="%s"><div class="tile"></div>
|
||||||
|
<div style="width:40px;height:40px;background-image:url('%s')"></div>
|
||||||
|
<img src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4TBUAAAAvJ8AJAAcQ/Y/+B4CE8P+8GtH/1AAA">
|
||||||
|
<div style="width:40px;height:40px;background-image:url('data:image/webp;base64,UklGRiIAAABXRUJQVlA4TBUAAAAvJ8AJAAcQ/Y/+B4CE8P+8GtH/1AAA')"></div>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="40" height="40" fill="blue"/></svg>
|
||||||
|
""".formatted(blue, red, green));
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
assertFalse(preview.hasExternalImages());
|
||||||
|
var pane = new AtomicReference<HtmlViewer>(); var stage = new AtomicReference<Stage>();
|
||||||
|
try {
|
||||||
|
fx(() -> {
|
||||||
|
pane.set(viewer(preview));
|
||||||
|
var window = new Stage(); stage.set(window);
|
||||||
|
window.setScene(new Scene(pane.get(), 240, 300)); window.show();
|
||||||
|
assertTrue(media(pane.get()).isDisabled());
|
||||||
|
});
|
||||||
|
await(() -> loaded(pane.get()));
|
||||||
|
// Snapshot pixels exercise the actual WebKit SVG decoder and CSS layout, with JavaScript disabled.
|
||||||
|
await(() -> {
|
||||||
|
var pixels = browser(pane.get()).snapshot(null, null).getPixelReader();
|
||||||
|
return pixels.getColor(20, 20).getRed() > .9 && pixels.getColor(20, 20).getGreen() < .1
|
||||||
|
&& pixels.getColor(20, 60).getBlue() > .9 && pixels.getColor(20, 60).getRed() < .1
|
||||||
|
&& pixels.getColor(20, 100).getGreen() > .9 && pixels.getColor(20, 100).getRed() < .1
|
||||||
|
&& pixels.getColor(20, 140).getRed() > .9 && pixels.getColor(20, 140).getGreen() < .1
|
||||||
|
&& pixels.getColor(20, 180).getRed() > .9 && pixels.getColor(20, 180).getGreen() < .1
|
||||||
|
&& pixels.getColor(20, 220).getBlue() > .9 && pixels.getColor(20, 220).getRed() < .1;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fx(() -> { if (pane.get() != null) pane.get().close(); if (stage.get() != null) stage.get().hide(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String svg(String color) {
|
||||||
|
return "data:image/svg+xml," + URLEncoder.encode("<svg xmlns='http://www.w3.org/2000/svg' width='40' height='40'>"
|
||||||
|
+ "<rect width='40' height='40' fill='" + color + "'/></svg>", StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void networkImagesRequireExplicitPermissionPerViewAndReopeningStartsOffline() throws Exception {
|
||||||
|
var images = new AtomicInteger(); var forbidden = new AtomicInteger();
|
||||||
|
var bytes = new ByteArrayOutputStream();
|
||||||
|
ImageIO.write(new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB), "png", bytes);
|
||||||
|
var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
server.createContext("/image.png", exchange -> {
|
||||||
|
images.incrementAndGet();
|
||||||
|
exchange.getResponseHeaders().set("Content-Type", "image/png");
|
||||||
|
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||||
|
exchange.sendResponseHeaders(200, bytes.size());
|
||||||
|
try (var output = exchange.getResponseBody()) { output.write(bytes.toByteArray()); }
|
||||||
|
});
|
||||||
|
server.createContext("/forbidden", exchange -> {
|
||||||
|
forbidden.incrementAndGet(); exchange.sendResponseHeaders(204, -1); exchange.close();
|
||||||
|
});
|
||||||
|
server.createContext("/background.png", exchange -> {
|
||||||
|
images.incrementAndGet();
|
||||||
|
exchange.getResponseHeaders().set("Content-Type", "image/png");
|
||||||
|
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||||
|
exchange.sendResponseHeaders(200, bytes.size());
|
||||||
|
try (var output = exchange.getResponseBody()) { output.write(bytes.toByteArray()); }
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
String base = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||||
|
var first = new AtomicReference<HtmlViewer>(); var second = new AtomicReference<HtmlViewer>();
|
||||||
|
var reopened = new AtomicReference<HtmlViewer>(); var stage = new AtomicReference<Stage>();
|
||||||
|
try {
|
||||||
|
var file = Files.writeString(temporary.resolve("page.html"), "<img src='" + base + "/image.png'>"
|
||||||
|
+ "<script src='" + base + "/forbidden'></script><iframe src='" + base + "/forbidden'></iframe>"
|
||||||
|
+ "<style>@import '" + base + "/forbidden'; @font-face{font-family:evil;src:url('" + base + "/forbidden')}"
|
||||||
|
+ ".remote{width:40px;height:40px;background-image:url('" + base + "/background.png')}</style>"
|
||||||
|
+ "<div class='remote'>Background</div><img src=\"data:image/svg+xml,"
|
||||||
|
+ URLEncoder.encode("<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'>"
|
||||||
|
+ "<script href='" + base + "/forbidden'/><image href='" + base + "/forbidden'/></svg>",
|
||||||
|
StandardCharsets.UTF_8).replace("+", "%20") + "\">");
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
fx(() -> {
|
||||||
|
first.set(viewer(preview)); second.set(viewer(preview));
|
||||||
|
var window = new Stage(); stage.set(window);
|
||||||
|
window.setScene(new Scene(new VBox(first.get(), second.get()), 600, 600)); window.show();
|
||||||
|
});
|
||||||
|
await(() -> loaded(first.get()) && loaded(second.get()));
|
||||||
|
assertEquals(0, images.get(), "Opening HTML must never fetch remote images");
|
||||||
|
fx(() -> {
|
||||||
|
assertEquals("", imageSource(first.get())); assertEquals("", imageSource(second.get()));
|
||||||
|
media(first.get()).fire();
|
||||||
|
});
|
||||||
|
await(() -> images.get() == 2 && loaded(first.get()));
|
||||||
|
fx(() -> {
|
||||||
|
assertEquals(base + "/image.png", imageSource(first.get()));
|
||||||
|
assertEquals("", imageSource(second.get()), "Permission must not spread to another tab");
|
||||||
|
assertFalse(browser(first.get()).getEngine().isJavaScriptEnabled());
|
||||||
|
assertFalse(browser(second.get()).getEngine().isJavaScriptEnabled());
|
||||||
|
assertTrue(first.get().isExternalImagesAllowed());
|
||||||
|
first.get().display(HtmlDocument.parse("<p>Replacement</p>"));
|
||||||
|
assertFalse(first.get().isExternalImagesAllowed(), "Replacing the document revokes permission");
|
||||||
|
assertFalse(first.get().isExternalImagesAvailable());
|
||||||
|
first.get().close();
|
||||||
|
reopened.set(viewer(preview));
|
||||||
|
((VBox) stage.get().getScene().getRoot()).getChildren().set(0, reopened.get());
|
||||||
|
});
|
||||||
|
await(() -> loaded(reopened.get()));
|
||||||
|
fx(() -> assertEquals("", imageSource(reopened.get())));
|
||||||
|
assertEquals(2, images.get(), "Reopening must require a fresh grant");
|
||||||
|
assertEquals(0, forbidden.get(), "Scripts and embedded pages must never load");
|
||||||
|
} finally {
|
||||||
|
fx(() -> {
|
||||||
|
if (first.get() != null) first.get().close();
|
||||||
|
if (second.get() != null) second.get().close();
|
||||||
|
if (reopened.get() != null) reopened.get().close();
|
||||||
|
if (stage.get() != null) stage.get().hide();
|
||||||
|
});
|
||||||
|
server.stop(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,125 +9,53 @@ import de.neitzel.fx.docking.Dockable;
|
|||||||
import de.neitzel.fx.docking.DockableId;
|
import de.neitzel.fx.docking.DockableId;
|
||||||
import de.neitzel.fx.docking.DockingManager;
|
import de.neitzel.fx.docking.DockingManager;
|
||||||
import de.neitzel.fx.docking.DockingOptions;
|
import de.neitzel.fx.docking.DockingOptions;
|
||||||
import javafx.animation.AnimationTimer;
|
|
||||||
import javafx.application.Platform;
|
|
||||||
import javafx.beans.value.ChangeListener;
|
|
||||||
import javafx.geometry.Bounds;
|
|
||||||
import javafx.scene.Scene;
|
import javafx.scene.Scene;
|
||||||
import javafx.scene.control.TextArea;
|
import javafx.scene.control.TextArea;
|
||||||
import javafx.scene.input.MouseButton;
|
|
||||||
import javafx.scene.robot.Robot;
|
|
||||||
import javafx.stage.Stage;
|
import javafx.stage.Stage;
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.util.concurrent.CountDownLatch;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.mockito.Mockito.clearInvocations;
|
||||||
|
import static org.mockito.Mockito.doReturn;
|
||||||
|
import static org.mockito.Mockito.spy;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
/** Activating a background window is an applied action even when its selected tab stays the same. */
|
/** Activating a background window is an applied action even when its selected tab stays the same. */
|
||||||
class ActivateDockingWindowTest {
|
class ActivateDockingWindowTest {
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
static void startJavaFx() throws Exception {
|
static void startJavaFx() throws Exception {
|
||||||
FxThread.start();
|
FxThread.start();
|
||||||
FxThread.onFx(() -> Platform.setImplicitExit(false));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void activatingTheSameContentInABackgroundWindowReportsApplied() throws Exception {
|
void activatingTheSameContentInABackgroundWindowReportsApplied() throws Exception {
|
||||||
AtomicReference<Fixture> state = new AtomicReference<>();
|
|
||||||
FxThread.onFx(() -> {
|
FxThread.onFx(() -> {
|
||||||
DockLayout initial = new DockLayout();
|
DockLayout initial = new DockLayout();
|
||||||
initial.setCenter(new DockGroupDefinition("editors"));
|
initial.setCenter(new DockGroupDefinition("editors"));
|
||||||
DockPane pane = new DockPane();
|
DockPane pane = new DockPane();
|
||||||
pane.setInitialLayout(initial);
|
pane.setInitialLayout(initial);
|
||||||
Stage main = new Stage();
|
Stage main = spy(new Stage());
|
||||||
main.setScene(new Scene(pane, 480, 280));
|
main.setScene(new Scene(pane, 480, 280));
|
||||||
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
TextArea editor = new TextArea("Unsaved text");
|
TextArea editor = new TextArea("Unsaved text");
|
||||||
Dockable dockable = new Dockable(new DockableId("notes"), editor);
|
Dockable dockable = new Dockable(new DockableId("notes"), editor);
|
||||||
manager.open(dockable, DockTarget.area("editors"));
|
manager.open(dockable, DockTarget.area("editors"));
|
||||||
Stage other = new Stage();
|
|
||||||
other.setScene(new Scene(new TextArea("Other window"), 240, 160));
|
// Only the desktop's window state is simulated. Selection, scene focus and
|
||||||
state.set(new Fixture(main, other, manager, dockable));
|
// the activation result all come from the real controls and manager.
|
||||||
main.show();
|
doReturn(true).when(main).isShowing();
|
||||||
|
doReturn(true).when(main).isFocused();
|
||||||
manager.activate(dockable.getId());
|
manager.activate(dockable.getId());
|
||||||
});
|
assertSame(dockable, manager.activeDockable());
|
||||||
Fixture fixture = state.get();
|
assertSame(editor, main.getScene().getFocusOwner());
|
||||||
try {
|
assertInstanceOf(ActionResult.NoChange.class, manager.activate(dockable.getId()));
|
||||||
focus(fixture.main());
|
|
||||||
FxThread.onFx(() -> fixture.other().show());
|
|
||||||
focus(fixture.other());
|
|
||||||
FxThread.onFx(() -> {
|
|
||||||
assertFalse(fixture.main().isFocused());
|
|
||||||
assertSame(fixture.dockable(), fixture.manager().activeDockable());
|
|
||||||
assertSame(fixture.dockable().getContent(), fixture.main().getScene().getFocusOwner());
|
|
||||||
assertInstanceOf(ActionResult.Applied.class, fixture.manager().activate(fixture.dockable().getId()));
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
FxThread.onFx(() -> {
|
|
||||||
fixture.other().hide();
|
|
||||||
fixture.main().hide();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void focus(Stage stage) throws Exception {
|
doReturn(false).when(main).isFocused();
|
||||||
CountDownLatch focused = new CountDownLatch(1);
|
clearInvocations(main);
|
||||||
ChangeListener<Boolean> listener = (observable, old, current) -> {
|
assertInstanceOf(ActionResult.Applied.class, manager.activate(dockable.getId()));
|
||||||
if (current) focused.countDown();
|
verify(main).requestFocus();
|
||||||
};
|
|
||||||
AnimationTimer clickAfterDisplay = new AnimationTimer() {
|
|
||||||
private int pulses;
|
|
||||||
private long lastClick;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void handle(long now) {
|
|
||||||
if (stage.isFocused()) {
|
|
||||||
focused.countDown();
|
|
||||||
stop();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (++pulses < 2) return;
|
|
||||||
if (now - lastClick < 250_000_000) return;
|
|
||||||
lastClick = now;
|
|
||||||
Bounds bounds = stage.getScene().getRoot().localToScreen(
|
|
||||||
stage.getScene().getRoot().getBoundsInLocal());
|
|
||||||
Robot robot = new Robot();
|
|
||||||
robot.mouseMove(bounds.getCenterX(), bounds.getCenterY());
|
|
||||||
robot.mouseClick(MouseButton.PRIMARY);
|
|
||||||
if (stage.isFocused()) focused.countDown();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
FxThread.onFx(() -> {
|
|
||||||
stage.focusedProperty().addListener(listener);
|
|
||||||
stage.setAlwaysOnTop(true);
|
|
||||||
stage.toFront();
|
|
||||||
stage.requestFocus();
|
|
||||||
stage.getScene().getRoot().applyCss();
|
|
||||||
stage.getScene().getRoot().layout();
|
|
||||||
clickAfterDisplay.start();
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
// A native click activates the application even if the previous test or
|
|
||||||
// another application owned desktop focus. RequestFocus alone cannot
|
|
||||||
// establish that precondition reliably on macOS. FX pulses do not
|
|
||||||
// guarantee that the native compositor has displayed the window;
|
|
||||||
// retry only this focus precondition within the bounded wait.
|
|
||||||
assertTrue(focused.await(5, TimeUnit.SECONDS), "Desktop did not focus the requested window");
|
|
||||||
} finally {
|
|
||||||
FxThread.onFx(() -> {
|
|
||||||
clickAfterDisplay.stop();
|
|
||||||
stage.focusedProperty().removeListener(listener);
|
|
||||||
stage.setAlwaysOnTop(false);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private record Fixture(Stage main, Stage other, DockingManager manager, Dockable dockable) { }
|
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user