40 Commits
Author SHA1 Message Date
konrad 4022519ab7 Merge NeitzelLib 1.0.8-SNAPSHOT development 2026-11-26 16:12:19 +01:00
konrad 7ec8c45c09 Start NeitzelLib 1.0.8-SNAPSHOT development 2026-11-26 16:12:18 +01:00
konrad 28b3fb1458 Merge NeitzelLib 1.0.7 with optional FX dependency injection 2026-11-26 16:01:48 +01:00
konrad 5759c2295e Prepare NeitzelLib 1.0.7 2026-11-26 16:01:47 +01:00
konrad 20249f5790 Separate JavaFX loading from the Neitzel injection container 2026-11-26 16:01:19 +01:00
konrad efda8c2d14 Merge NeitzelLib 1.0.7-SNAPSHOT development 2026-11-26 12:23:06 +01:00
konrad abfd58b051 Start NeitzelLib 1.0.7-SNAPSHOT development 2026-11-26 12:20:16 +01:00
konrad f585ab9cd9 Merge the Person desk preview release coordinates 2026-11-26 10:41:44 +01:00
konrad 82067cfc1a Use Designer 0.1.0 in the optional Person desk preview 2026-11-26 10:41:43 +01:00
konrad 407ecc28c7 Merge NeitzelLib 1.0.6 release 2026-11-26 10:39:11 +01:00
konrad 0037f089b9 Prepare NeitzelLib 1.0.6 2026-11-26 10:39:11 +01:00
konrad 83e0bdf8d4 Merge literal DataGrid group label keys 2026-11-25 14:49:02 +01:00
konrad 2625616b2f Accept literal group keys in DataGrid column FXML 2026-11-25 13:30:55 +01:00
konrad 9522ed90ce Merge managed FXML views and bindable document inputs 2026-11-24 22:27:05 +01:00
konrad 4a455e63ab Document one-way list replacement in the FX binding guide 2026-11-24 20:52:35 +01:00
konrad e4f1fd3c96 Bind saved HTML and replaceable suggestion catalogues toward the view 2026-11-24 20:49:45 +01:00
konrad 514cc7fb8e Open an independent FXML component in a managed view context 2026-11-24 14:31:31 +01:00
konrad ac992167bc Reconcile read-only FXML binding branch with managed view lifetimes 2026-11-23 19:38:14 +01:00
konrad 50046be154 Land JavaFX test fixtures and 1.0.6-SNAPSHOT development 2026-11-23 19:38:06 +01:00
konrad 597252f676 Merge JavaFX JUnit fixtures and deterministic docking activation test 2026-11-23 19:29:33 +01:00
konrad 073b4a65dc Merge Maven version properties 2026-11-23 19:18:34 +01:00
konrad f1b2fd24d4 Test docking activation independently of desktop focus arbitration
Glass Headless can report both stages focused. On macOS the desktop can deny the input needed to establish the initial focus. Drive both reported window states explicitly with a Stage spy so the real manager must distinguish NoChange from Applied and request focus.
2026-11-23 19:16:45 +01:00
konrad d8b2871f24 Centralize Maven dependency and plugin versions 2026-11-23 19:11:01 +01:00
konrad 7b3f98f489 Provide managed JavaFX fixtures for JUnit Jupiter 2026-11-23 19:01:29 +01:00
konrad e37a66dfa8 Start NeitzelLib 1.0.6-SNAPSHOT development 2026-11-23 18:56:26 +01:00
konrad 081d94e373 Land NeitzelLib 1.0.5 release 2026-11-23 18:55:09 +01:00
konrad 13cd3c8c7f Prepare NeitzelLib 1.0.5 with async commands and grid selection 2026-11-23 18:35:30 +01:00
konrad 2553d04e82 Add exclusive asynchronous FX commands 2026-11-23 18:34:52 +01:00
konrad ad5b901bbe Expose coherent DataGrid selection snapshots for view bindings 2026-11-23 18:28:05 +01:00
konrad 1ff9753de8 Prepare NeitzelLib 1.0.4 with managed FXML and commands 2026-11-23 18:24:22 +01:00
konrad a3f7d2423f Bind reusable commands to JavaFX action controls 2026-11-23 18:24:22 +01:00
konrad 981cd68f49 Bind named read-only observables toward FXML views 2026-11-23 18:22:59 +01:00
konrad e915ed392f Scope FXML view models and dispose managed views 2026-11-23 18:22:54 +01:00
konrad 2d12a7d393 Bind named read-only observables toward FXML views 2026-11-23 18:18:45 +01:00
konrad 8aefe53ad1 Start NeitzelLib 1.0.4-SNAPSHOT development 2026-11-23 14:14:42 +01:00
konrad 12aad4d3a1 Land NeitzelLib 1.0.3 release 2026-11-23 14:07:40 +01:00
konrad fba2735e1e Prepare NeitzelLib 1.0.3 release 2026-11-23 14:07:40 +01:00
konrad 17c36ccae7 Merge DataGrid column visibility controls 2026-11-23 14:07:11 +01:00
konrad 42c1ee19a1 Add DataGrid column visibility controls and action icons 2026-11-23 13:05:31 +01:00
konrad dcd26a088f Start local NeitzelLib 1.0.3-SNAPSHOT development 2026-11-22 20:13:07 +01:00
155 changed files with 4696 additions and 944 deletions
+32 -4
View File
@@ -54,13 +54,24 @@ Optional mapped JDBC DataGrid source, initially qualified with H2. See [data-gri
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). 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.loadWithDependencies(fxml, model, dependencies)` 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`.
### fx-injection
Optional adapter since FX 1.0.7 for applications using Neitzel's `ApplicationContext`.
It brings in `fx` and `injection`. See [adapter setup and migration](fx-injection/README.md).
### injection ### injection
Package scanner and type-based container used by `fx`. See [injection/README.md](injection/README.md). Standalone package scanner and type-based container. See [injection/README.md](injection/README.md).
### fx-example ### fx-example
Person desk that shows how to use `fx` and `injection`. Build with `./mvnw -pl fx-example -am install`, then run `./mvnw -f fx-example/pom.xml javafx:run`. See [fx-example/README.md](fx-example/README.md). Person desk that shows how to use FX with `fx-injection`. Build with `./mvnw -pl fx-example -am install`, then run `./mvnw -f fx-example/pom.xml javafx:run`. See [fx-example/README.md](fx-example/README.md).
### gson ### gson
@@ -84,6 +95,23 @@ 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.7
- Use `fx` and `fx-test` with an application-supplied `ViewDependencies` adapter.
- Add `fx-injection` to keep using Neitzel's `ApplicationContext` from the new loaders. See [migration](fx-injection/README.md#migrate-an-existing-fx-application).
## 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 ## 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. - 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.
@@ -93,7 +121,7 @@ Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven
## Use a release from Maven ## Use a release from Maven
To use release `1.0.2`, add the Gitea registry to the consuming project's POM and use the release To use release `1.0.7`, 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
@@ -108,7 +136,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.2</version> <version>1.0.7</version>
</dependency> </dependency>
</dependencies> </dependencies>
``` ```
+5 -7
View File
@@ -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.2</version> <version>1.0.8-SNAPSHOT</version>
</parent> </parent>
<artifactId>core</artifactId> <artifactId>core</artifactId>
@@ -18,18 +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>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
+2 -2
View File
@@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <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.2</version></parent> <modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.8-SNAPSHOT</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>
+1 -1
View File
@@ -1,6 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <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.2</version></parent> <parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.8-SNAPSHOT</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>
+5 -2
View File
@@ -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.2</version> <version>1.0.8-SNAPSHOT</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>
+5 -5
View File
@@ -1,6 +1,6 @@
# Person desk reference application # Person desk reference application
This runnable application demonstrates [NeitzelLib FX](../fx/README.md) and [injection](../injection/README.md) together. It edits one Person with a home Address, nested Note, visit list, selected visit and tags. Use it as a reference for wiring a real screen; the [minimal quick start](../fx/docs/quick-start.md) is the smaller starting point for a new project. This runnable application demonstrates [NeitzelLib FX](../fx/README.md) with the [optional Neitzel adapter](../fx-injection/README.md). It edits one Person with a home Address, nested Note, visit list, selected visit and tags. Use it as a reference for wiring a real screen; the [minimal quick start](../fx/docs/quick-start.md) is the smaller starting point for a new project.
Separate Java/FXML launchers demonstrate [standalone bars](../fx/docs/bars.md) Separate Java/FXML launchers demonstrate [standalone bars](../fx/docs/bars.md)
and [docking](../fx/docs/docking.md) without initializing MVVM or injection. and [docking](../fx/docs/docking.md) without initializing MVVM or injection.
@@ -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.2` 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 the checkout’s Maven 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.2.jar java -jar fx-example/target/fx-example-1.0.8-SNAPSHOT.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.
@@ -47,7 +47,7 @@ Paths below are relative to this module. Java sources share `src/main/java/de/ne
| File/type | Responsibility | | File/type | Responsibility |
| --- | --- | | --- | --- |
| `Main` | Plain Java launcher calling `Application.launch` | | `Main` | Plain Java launcher calling `Application.launch` |
| `DeskApp` | Scan configuration, fresh sample Model, ViewLoader, Scene and message popup registration | | `DeskApp` | Scan configuration, sample Model, Component registrations in `DeskApp.dependencies(person)`, ViewLoader and window-owned Model context |
| `model/Person`, `Address`, `Note`, `Role` | JavaBean data and enum; no JavaFX properties required | | `model/Person`, `Address`, `Note`, `Role` | JavaBean data and enum; no JavaFX properties required |
| `view/DeskController` and `Desk.fxml` | Screen handlers, computed greeting, controls and binding declarations | | `view/DeskController` and `Desk.fxml` | Screen handlers, computed greeting, controls and binding declarations |
| `view/PersonViewModel` | Handwritten ViewModel subclass with a derived title | | `view/PersonViewModel` | Handwritten ViewModel subclass with a derived title |
@@ -81,7 +81,7 @@ normal build needs no Designer processor; Lombok still runs.
2. Edit Age using its `years ` text format. An invalid value stays visible while the previous Model value is retained. A message explains the failure; a valid value clears that conversion failure. 2. Edit Age using its `years ` text format. An invalid value stays visible while the previous Model value is retained. A message explains the failure; a valid value clears that conversion failure.
3. Edit the home street. The path-bound label follows. Empty street input fails through `StreetConverter`; the parent receives the child message with the `home.street` source prefix. 3. Edit the home street. The path-bound label follows. Empty street input fails through `StreetConverter`; the parent receives the child message with the `home.street` source prefix.
4. Edit the nested note. AddressForm's inner NoteForm binds to its own Model. The `Opened as ...` label records initial setup rather than tracking every later city edit. 4. Edit the nested note. AddressForm's inner NoteForm binds to its own Model. The `Opened as ...` label records initial setup rather than tracking every later city edit.
5. Add a visit. Both the repeated forms and Table gain a row. Edit a street in one representation and observe the same Address in the other. The Table's Remove button delegates to the controller. 5. Add a visit. Both the repeated forms and Table gain a row. Edit a street in one representation and observe the same Address in the other. The Table's Remove button uses the desk's shared `VisitActions` service.
6. Select a visit in the ComboBox or Table. Both use the `selectedVisit` Attribute. Resize, sort and filter Table columns; filtering and sorting affect displayed rows without reordering the Model's list. 6. Select a visit in the ComboBox or Table. Both use the `selectedVisit` Attribute. Resize, sort and filter Table columns; filtering and sorting affect displayed rows without reordering the Model's list.
7. Edit the visited date in ISO form (`yyyy-MM-dd`). Invalid text keeps the old date. Add a tag to see a shared ObservableList of simple values. 7. Edit the visited date in ISO form (`yyyy-MM-dd`). Invalid text keeps the old date. Add a tag to see a shared ObservableList of simple values.
8. Try the information, warning and fatal message buttons. Severity is data and logging behavior; a fatal message does not itself exit the application. Close each non-blocking popup normally. 8. Try the information, warning and fatal message buttons. Severity is data and logging behavior; a fatal message does not itself exit the application. Close each non-blocking popup normally.
+3 -2
View File
@@ -41,8 +41,9 @@ The application adapter owns its change listener and derived bindings. Its
`onClosed` and `onDiscarded` hooks release those resources explicitly. Moves, `onClosed` and `onDiscarded` hooks release those resources explicitly. Moves,
collapse and veto do not run those hooks. A rejected factory-created editor is collapse and veto do not run those hooks. A rejected factory-created editor is
discarded; rejection of a directly supplied Dockable leaves cleanup to its caller. discarded; rejection of a directly supplied Dockable leaves cleanup to its caller.
This does not dispose the LoadedView or evict the runtime's strong Model-to-ViewModel The same hooks close the editor's `ViewModelContext`, which closes the
identity cache. See the [MVVM lifetime contract](../../fx/docs/architecture.md). `LoadedView` and clears its Model-to-ViewModel registrations. See the
[MVVM lifetime contract](../../fx/docs/architecture.md).
`MvvmDockingTest` loads the actual example FXML and checks model/property/control `MvvmDockingTest` loads the actual example FXML and checks model/property/control
edits before and after moves, object identity, bar ownership, global toolbar edits before and after moves, object identity, bar ownership, global toolbar
+1 -1
View File
@@ -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.2.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain java -cp 'fx-example/target/fx-example-1.0.8-SNAPSHOT.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.
+1 -1
View File
@@ -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.2.jar:fx-example/target/libs/*' \ java -cp 'fx-example/target/fx-example-1.0.8-SNAPSHOT.jar:fx-example/target/libs/*' \
de.neitzel.fx.example.theme.ThemeGalleryMain de.neitzel.fx.example.theme.ThemeGalleryMain
``` ```
+26 -6
View File
@@ -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.2</version> <version>1.0.8-SNAPSHOT</version>
</parent> </parent>
<artifactId>fx-example</artifactId> <artifactId>fx-example</artifactId>
@@ -18,14 +18,20 @@
<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-injection</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency> <dependency>
@@ -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>
@@ -2,29 +2,23 @@ package de.neitzel.fx.example.preview;
import de.neitzel.fx.example.DeskApp; import de.neitzel.fx.example.DeskApp;
import de.neitzel.fx.example.model.Address; import de.neitzel.fx.example.model.Address;
import de.neitzel.fx.example.view.DeskController;
import de.neitzel.fx.example.view.PersonViewModel;
import de.neitzel.fxdesigner.preview.PreviewProvider; import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession; import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.injection.ApplicationContext; import de.neitzel.fx.view.ViewDependencies;
/** Independent samples for the nested, repeated and table-row Address components. */ /** Independent samples for the nested, repeated and table-row Address components. */
public final class AddressPreviewProvider implements PreviewProvider<Address, ApplicationContext> { public final class AddressPreviewProvider implements PreviewProvider<Address, ViewDependencies> {
@Override @Override
public Class<Address> modelType() { public Class<Address> modelType() {
return Address.class; return Address.class;
} }
@Override @Override
public PreviewSession<Address, ApplicationContext> open(String id) { public PreviewSession<Address, ViewDependencies> open(String id) {
if (!java.util.Set.of("address", "visit", "row").contains(id)) if (!java.util.Set.of("address", "visit", "row").contains(id))
throw new IllegalArgumentException("Unknown address example: " + id); throw new IllegalArgumentException("Unknown address example: " + id);
var person = DeskApp.sample(); var person = DeskApp.sample();
var context = new ApplicationContext(DeskApp.class); var context = DeskApp.dependencies(person);
// An independently previewed row still needs the parent action's state.
// No Desk.fxml is loaded and no popup listener is installed.
if ("row".equals(id))
context.getComponent(DeskController.class).setViewModel(new PersonViewModel(person));
return new SampleSession<>( return new SampleSession<>(
"address".equals(id) ? person.getHome() : person.getVisits().getFirst(), context); "address".equals(id) ? person.getHome() : person.getVisits().getFirst(), context);
} }
@@ -4,18 +4,19 @@ import de.neitzel.fx.example.DeskApp;
import de.neitzel.fx.example.model.Person; import de.neitzel.fx.example.model.Person;
import de.neitzel.fxdesigner.preview.PreviewProvider; import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession; import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.injection.ApplicationContext; import de.neitzel.fx.view.ViewDependencies;
/** Optional test-source preview adapter; it never enters the application distribution. */ /** Optional test-source preview adapter; it never enters the application distribution. */
public final class DeskPreviewProvider implements PreviewProvider<Person, ApplicationContext> { public final class DeskPreviewProvider implements PreviewProvider<Person, ViewDependencies> {
@Override @Override
public Class<Person> modelType() { public Class<Person> modelType() {
return Person.class; return Person.class;
} }
@Override @Override
public PreviewSession<Person, ApplicationContext> open(String id) { public PreviewSession<Person, ViewDependencies> open(String id) {
if (!"desk".equals(id)) throw new IllegalArgumentException("Unknown desk example: " + id); if (!"desk".equals(id)) throw new IllegalArgumentException("Unknown desk example: " + id);
return new SampleSession<>(DeskApp.sample(), new ApplicationContext(DeskApp.class)); var person = DeskApp.sample();
return new SampleSession<>(person, DeskApp.dependencies(person));
} }
} }
@@ -4,19 +4,19 @@ import de.neitzel.fx.example.DeskApp;
import de.neitzel.fx.example.model.Note; import de.neitzel.fx.example.model.Note;
import de.neitzel.fxdesigner.preview.PreviewProvider; import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession; import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.injection.ApplicationContext; import de.neitzel.fx.view.ViewDependencies;
/** Independent sample for the nested note editor. */ /** Independent sample for the nested note editor. */
public final class NotePreviewProvider implements PreviewProvider<Note, ApplicationContext> { public final class NotePreviewProvider implements PreviewProvider<Note, ViewDependencies> {
@Override @Override
public Class<Note> modelType() { public Class<Note> modelType() {
return Note.class; return Note.class;
} }
@Override @Override
public PreviewSession<Note, ApplicationContext> open(String id) { public PreviewSession<Note, ViewDependencies> open(String id) {
if (!"note".equals(id)) throw new IllegalArgumentException("Unknown note example: " + id); if (!"note".equals(id)) throw new IllegalArgumentException("Unknown note example: " + id);
return new SampleSession<>( var person = DeskApp.sample();
DeskApp.sample().getHome().getNote(), new ApplicationContext(DeskApp.class)); return new SampleSession<>(person.getHome().getNote(), DeskApp.dependencies(person));
} }
} }
@@ -3,7 +3,9 @@ package de.neitzel.fx.example.preview;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.example.view.DeskController; import de.neitzel.fx.example.view.DeskController;
import de.neitzel.fx.example.view.VisitRow;
import de.neitzel.fx.view.ViewLoader; import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import javafx.application.Platform; import javafx.application.Platform;
@@ -48,12 +50,12 @@ class PreviewProvidersTest {
assertNotSame(first.model(), second.model()); assertNotSame(first.model(), second.model());
assertNotSame(first.model().getHome(), second.model().getHome()); assertNotSame(first.model().getHome(), second.model().getHome());
assertNotSame(first.context(), second.context()); assertNotSame(first.context(), second.context());
var view = try (var models = new ViewModelContext()) {
ViewLoader.load( var view = ViewLoader.loadWithDependencies(
DeskController.class.getResource("Desk.fxml"), DeskController.class.getResource("Desk.fxml"),
first.model(), first.model(), first.context(), models);
first.context()); assertNotNull(view.getRoot().lookup("#nameField"));
assertNotNull(view.getRoot().lookup("#nameField")); }
assertEquals("Ada Lovelace", first.model().getName()); assertEquals("Ada Lovelace", first.model().getName());
assertTrue(first.ready().toCompletableFuture().isDone()); assertTrue(first.ready().toCompletableFuture().isDone());
assertThrows(IllegalArgumentException.class, () -> provider.open("unknown")); assertThrows(IllegalArgumentException.class, () -> provider.open("unknown"));
@@ -70,11 +72,11 @@ class PreviewProvidersTest {
var visit = addresses.open("visit"); var visit = addresses.open("visit");
assertNotNull(visit.model().getVisitedOn()); assertNotNull(visit.model().getVisitedOn());
var row = addresses.open("row"); var row = addresses.open("row");
assertDoesNotThrow( try (var models = new ViewModelContext()) {
() -> var view = ViewLoader.loadComponentWithDependencies(
row.context() VisitRow.class, row.model(), row.context(), models);
.getComponent(DeskController.class) assertDoesNotThrow(((VisitRow) view.getRoot())::remove);
.removeVisit(row.model())); }
var note = new NotePreviewProvider().open("note"); var note = new NotePreviewProvider().open("note");
assertEquals("Kept at home", note.model().getText()); assertEquals("Kept at home", note.model().getText());
assertThrows(IllegalArgumentException.class, () -> addresses.open("desk")); assertThrows(IllegalArgumentException.class, () -> addresses.open("desk"));
@@ -1,11 +1,11 @@
package de.neitzel.fx.example.preview; package de.neitzel.fx.example.preview;
import de.neitzel.fxdesigner.preview.PreviewSession; import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.injection.ApplicationContext; import de.neitzel.fx.view.ViewDependencies;
/** The sample owns no timers, network connections or background work to release. */ /** The sample owns no timers, network connections or background work to release. */
record SampleSession<M>(M model, ApplicationContext context) record SampleSession<M>(M model, ViewDependencies context)
implements PreviewSession<M, ApplicationContext> { implements PreviewSession<M, ViewDependencies> {
@Override @Override
public void close() {} public void close() {}
} }
@@ -4,19 +4,28 @@ import de.neitzel.fx.example.model.Address;
import de.neitzel.fx.example.model.Note; import de.neitzel.fx.example.model.Note;
import de.neitzel.fx.example.model.Person; import de.neitzel.fx.example.model.Person;
import de.neitzel.fx.example.model.Role; import de.neitzel.fx.example.model.Role;
import de.neitzel.fx.example.view.AddressForm;
import de.neitzel.fx.example.view.DeskController; import de.neitzel.fx.example.view.DeskController;
import de.neitzel.fx.example.view.NoteForm;
import de.neitzel.fx.example.view.VisitActions;
import de.neitzel.fx.example.view.VisitForm;
import de.neitzel.fx.example.view.VisitRow;
import de.neitzel.fx.injection.NeitzelViewDependencies;
import de.neitzel.fx.view.LoadedView; import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.MessagePopup; import de.neitzel.fx.view.MessagePopup;
import de.neitzel.fx.view.ViewLoader; import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext; import de.neitzel.injection.ApplicationContext;
import de.neitzel.injection.annotation.Config; import de.neitzel.injection.annotation.Config;
import javafx.application.Application; import javafx.application.Application;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.stage.Stage; import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set;
/** /**
* Opens the person desk for one ordinary {@link Person}. * Opens the person desk for one ordinary {@link Person}.
@@ -60,6 +69,14 @@ public class DeskApp extends Application {
return person; return person;
} }
/** Configures one Model and shared service context for the app or a preview. */
public static NeitzelViewDependencies dependencies(Person person) {
var context = new ApplicationContext(DeskApp.class);
context.getComponent(VisitActions.class).setPerson(person);
return new NeitzelViewDependencies(context,
Set.of(AddressForm.class, NoteForm.class, VisitForm.class, VisitRow.class));
}
/** /**
* Launches the desk. * Launches the desk.
* *
@@ -76,9 +93,11 @@ public class DeskApp extends Application {
*/ */
@Override @Override
public void start(Stage stage) { public void start(Stage stage) {
ApplicationContext context = new ApplicationContext(DeskApp.class);
Person person = sample(); Person person = sample();
LoadedView loaded = ViewLoader.load(DeskController.class.getResource("Desk.fxml"), person, context); var models = new ViewModelContext();
LoadedView loaded = ViewLoader.loadWithDependencies(
DeskController.class.getResource("Desk.fxml"), person, dependencies(person), models);
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close());
MessagePopup.showNewMessages(loaded.getViewModel()); MessagePopup.showNewMessages(loaded.getViewModel());
stage.setTitle("fx example"); stage.setTitle("fx example");
stage.setScene(new Scene(loaded.getRoot())); stage.setScene(new Scene(loaded.getRoot()));
@@ -3,9 +3,12 @@ package de.neitzel.fx.example.docking.mvvm;
import de.neitzel.fx.docking.Dockable; import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId; import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.example.model.Note; import de.neitzel.fx.example.model.Note;
import de.neitzel.fx.injection.NeitzelViewDependencies;
import de.neitzel.fx.view.LoadedView; import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader; import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext; import de.neitzel.injection.ApplicationContext;
import java.util.Set;
import javafx.beans.binding.Bindings; import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding; import javafx.beans.binding.StringBinding;
import javafx.beans.property.Property; import javafx.beans.property.Property;
@@ -21,6 +24,7 @@ import lombok.Getter;
/** Application adapter: one loaded View becomes ordinary Dockable content. */ /** Application adapter: one loaded View becomes ordinary Dockable content. */
public final class MvvmEditor implements AutoCloseable { public final class MvvmEditor implements AutoCloseable {
@Getter private final Note model = new Note("Edit this note, then move or float its tab."); @Getter private final Note model = new Note("Edit this note, then move or float its tab.");
private final ViewModelContext models = new ViewModelContext();
@Getter private final LoadedView view; @Getter private final LoadedView view;
@Getter private final Dockable dockable; @Getter private final Dockable dockable;
private final Property<String> text; private final Property<String> text;
@@ -35,8 +39,9 @@ public final class MvvmEditor implements AutoCloseable {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public MvvmEditor(String id) { public MvvmEditor(String id) {
view = ViewLoader.load(MvvmEditor.class.getResource("MvvmEditor.fxml"), model, var dependencies = new NeitzelViewDependencies(new ApplicationContext(MvvmEditor.class), Set.of());
new ApplicationContext(MvvmEditor.class)); view = ViewLoader.loadWithDependencies(
MvvmEditor.class.getResource("MvvmEditor.fxml"), model, dependencies, models);
text = (Property<String>) view.property("text"); text = (Property<String>) view.property("text");
TextArea input = (TextArea) view.getRoot().lookup("#text"); TextArea input = (TextArea) view.getRoot().lookup("#text");
dockable = new Dockable(new DockableId(id), view.getRoot()); dockable = new Dockable(new DockableId(id), view.getRoot());
@@ -64,7 +69,7 @@ public final class MvvmEditor implements AutoCloseable {
dirty.set(false); dirty.set(false);
} }
/** Releases this adapter's resources, not the LoadedView or global ViewModel identity cache. */ /** Releases the editor's bindings and its managed View. */
@Override public void close() { @Override public void close() {
if (released) return; if (released) return;
released = true; released = true;
@@ -76,5 +81,6 @@ public final class MvvmEditor implements AutoCloseable {
status.setText("Released application listeners"); status.setText("Released application listeners");
clear.setOnAction(null); clear.setOnAction(null);
clear.setDisable(true); clear.setDisable(true);
models.close();
} }
} }
@@ -95,18 +95,6 @@ public class DeskController implements HasViewModel {
visits().add(created); visits().add(created);
} }
/**
* Removes a visit from the list the table and Repeat are watching.
*
* @param visit the visit
*/
public void removeVisit(Address visit) {
if (visit == null) {
return;
}
visits().remove(visit);
}
/** /**
* Adds the tag field's text to the tag list and clears the field. * Adds the tag field's text to the tag list and clears the field.
*/ */
@@ -0,0 +1,17 @@
package de.neitzel.fx.example.view;
import de.neitzel.fx.example.model.Address;
import de.neitzel.fx.example.model.Person;
import jakarta.inject.Singleton;
import lombok.Setter;
/** Removes a visit from the Model that owns the repeated forms and table rows. */
@Singleton
public final class VisitActions {
@Setter
private Person person;
public void remove(Address visit) {
person.getVisits().remove(visit);
}
}
@@ -21,9 +21,9 @@ import lombok.RequiredArgsConstructor;
public class VisitRow extends HBox { public class VisitRow extends HBox {
/** /**
* The desk controller that removes a visit from the person. * The shared action that removes a visit from the person.
*/ */
private final DeskController desk; private final VisitActions visits;
/** /**
* The visit this row edits. The table sets it once. * The visit this row edits. The table sets it once.
@@ -63,7 +63,7 @@ public class VisitRow extends HBox {
@FXML @FXML
public void remove() { public void remove() {
if (getModel() instanceof Address address) { if (getModel() instanceof Address address) {
desk.removeVisit(address); visits.remove(address);
} }
} }
} }
@@ -9,7 +9,8 @@ import de.neitzel.fx.example.view.VisitForm;
import de.neitzel.fx.example.view.VisitRow; import de.neitzel.fx.example.view.VisitRow;
import de.neitzel.fx.view.LoadedView; import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader; import de.neitzel.fx.view.ViewLoader;
import de.neitzel.injection.ApplicationContext; import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewModelContext;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.scene.Node; import javafx.scene.Node;
import javafx.scene.Parent; import javafx.scene.Parent;
@@ -122,16 +123,13 @@ class DeskLoadsTest {
/** /**
* A second view of the same person reuses the view model, so a name edit shows on both. * A second view of the same person reuses the view model, so a name edit shows on both.
* <p>
* The second document is only a name field. Loading the desk again would rebuild the home
* address form, and that form is the cached singleton already showing.
*/ */
@Test @Test
void secondViewReusesTheViewModel() throws Exception { void secondViewReusesTheViewModel() throws Exception {
onFx(() -> { onFx(() -> {
Loaded first = load(); Loaded first = load();
LoadedView second = ViewLoader.load( LoadedView second = ViewLoader.loadWithDependencies(
DeskLoadsTest.class.getResource("NameLine.fxml"), first.person(), first.context()); DeskLoadsTest.class.getResource("NameLine.fxml"), first.person(), first.context(), first.models());
assertSame(first.view().getViewModel(), second.getViewModel()); assertSame(first.view().getViewModel(), second.getViewModel());
textField(first.root(), "nameField").setText("Grace"); textField(first.root(), "nameField").setText("Grace");
assertEquals("Grace", first.person().getName()); assertEquals("Grace", first.person().getName());
@@ -261,16 +259,15 @@ class DeskLoadsTest {
onFx(() -> { onFx(() -> {
Loaded loaded = load(); Loaded loaded = load();
Parent root = loaded.root(); Parent root = loaded.root();
DeskController desk = loaded.context().getComponent(DeskController.class); fire(root, "Leave a note");
desk.leaveNote();
assertEquals(de.neitzel.fx.view.Message.Severity.INFO, assertEquals(de.neitzel.fx.view.Message.Severity.INFO,
loaded.view().getViewModel().getLatestMessage().getSeverity()); loaded.view().getViewModel().getLatestMessage().getSeverity());
assertEquals("The model already has the name Ada Lovelace.", text(root, "noticeLabel")); assertEquals("The model already has the name Ada Lovelace.", text(root, "noticeLabel"));
desk.leaveWarning(); fire(root, "Leave a warning");
assertEquals(de.neitzel.fx.view.Message.Severity.WARN, assertEquals(de.neitzel.fx.view.Message.Severity.WARN,
loaded.view().getViewModel().getLatestMessage().getSeverity()); loaded.view().getViewModel().getLatestMessage().getSeverity());
assertEquals("Check the age before leaving the desk.", text(root, "noticeLabel")); assertEquals("Check the age before leaving the desk.", text(root, "noticeLabel"));
desk.leaveFatal(); fire(root, "Leave a fatal notice");
assertEquals(de.neitzel.fx.view.Message.Severity.FATAL, assertEquals(de.neitzel.fx.view.Message.Severity.FATAL,
loaded.view().getViewModel().getLatestMessage().getSeverity()); loaded.view().getViewModel().getLatestMessage().getSeverity());
assertEquals("The desk cannot store this person.", text(root, "noticeLabel")); assertEquals("The desk cannot store this person.", text(root, "noticeLabel"));
@@ -300,9 +297,10 @@ class DeskLoadsTest {
* *
* @param person the model * @param person the model
* @param view the loaded view * @param view the loaded view
* @param context the container * @param context the adapter
* @param models the ViewModel context
*/ */
private record Loaded(Person person, LoadedView view, ApplicationContext context) { private record Loaded(Person person, LoadedView view, ViewDependencies context, ViewModelContext models) {
/** /**
* Returns the scene-graph root. * Returns the scene-graph root.
@@ -321,9 +319,16 @@ class DeskLoadsTest {
*/ */
private static Loaded load() { private static Loaded load() {
Person person = DeskApp.sample(); Person person = DeskApp.sample();
ApplicationContext context = new ApplicationContext(DeskApp.class); var context = DeskApp.dependencies(person);
LoadedView view = ViewLoader.load(DeskController.class.getResource("Desk.fxml"), person, context); var models = new ViewModelContext();
return new Loaded(person, view, context); var view = ViewLoader.loadWithDependencies(
DeskController.class.getResource("Desk.fxml"), person, context, models);
return new Loaded(person, view, context, models);
}
private static void fire(Parent root, String text) {
root.lookupAll(".button").stream().filter(Button.class::isInstance).map(Button.class::cast)
.filter(button -> text.equals(button.getText())).findFirst().orElseThrow().fire();
} }
/** /**
+64
View File
@@ -0,0 +1,64 @@
# Neitzel DI adapter for FX
The adapter is available from NeitzelLib 1.0.7. See the
[Maven repository setup](../README.md#use-a-release-from-maven). For a
local source build, run `./mvnw -pl fx-injection -am install` from the
NeitzelLib root with JDK 25 and the application’s Maven repository.
```xml
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx-injection</artifactId>
<version>1.0.7</version>
</dependency>
```
Use the same version for all NeitzelLib modules. The adapter resolves `fx`,
`injection` and its scanner dependencies. Applications with their own
`ViewDependencies` can depend on `fx` directly.
Import the adapter from `de.neitzel.fx.injection`, the container from
`de.neitzel.injection` and the loader and Model context from
`de.neitzel.fx.view`.
```java
var services = new ApplicationContext(MyApplication.class);
var dependencies = new NeitzelViewDependencies(services, Set.of(AddressForm.class, VisitRow.class));
var models = new ViewModelContext();
var view = ViewLoader.loadWithDependencies(fxml, model, dependencies, models);
stage.setScene(new Scene(view.getRoot()));
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close());
```
The registration set contains the exact FXML Component classes, including
those used by Repeat and Table. The adapter asks the context for a fresh
controller or Component and gives FX the corresponding release action.
The release action closes UI instances that implement `AutoCloseable`.
Converters and Localizer come from the context's ordinary lookup. The adapter
reports a missing service as an empty result and propagates lookup or
creation errors. The application owns the context and its shared services.
The JPMS module name is `de.neitzel.fx.injection`. Named applications
keep the package access needed by FXML and Neitzel's package scanner.
Declare `requires de.neitzel.fx.injection` for the adapter and `requires fx` and
`requires injection` for their directly imported types. The Neitzel package
scanner still needs access to its scanned packages in named applications.
## Migrate an existing FX application
Use `ViewLoader.loadWithDependencies(..., dependencies, models)`,
`ViewLoader.loadComponentWithDependencies(..., dependencies, models)`,
and `FxFixture.loadWithDependencies(..., dependencies)` for the new
FX artifacts. Replace the previous public `ApplicationContext` loader
calls and recompile. Retain the Model context with its window or
dockable and close it when that owner ends. Each View load gets its own
controller and Components. If a row previously called a cached controller,
inject the shared action it needs. The [Person Desk](../fx-example/README.md)
does this with `VisitActions`.
A Designer provider on the new artifacts returns the configured adapter
from `PreviewSession.context()` and declares `ViewDependencies` as its
context type. Existing providers returning `ApplicationContext` continue to
run with compatible older FX artifacts such as 1.0.6. Consumers of the standalone
[Neitzel injection container](../injection/README.md) can keep using its
existing API.
+54
View File
@@ -0,0 +1,54 @@
<?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.8-SNAPSHOT</version>
</parent>
<artifactId>fx-injection</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>injection</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx-test</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Automatic-Module-Name>de.neitzel.fx.injection</Automatic-Module-Name>
</manifestEntries>
</archive>
</configuration>
</plugin>
<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,53 @@
package de.neitzel.fx.injection;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.injection.MissingComponentException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/** Connects managed FX Views to an application-owned Neitzel injection context. */
public record NeitzelViewDependencies(ApplicationContext context, Set<Class<?>> components)
implements ViewDependencies {
/** Creates an adapter with the concrete classes used as FXML Components and rows. */
public NeitzelViewDependencies {
Objects.requireNonNull(context, "Application context");
components = Set.copyOf(components);
}
@Override
public boolean isComponent(Class<?> type) {
return components.contains(type);
}
@Override
public <T> Optional<T> findService(Class<T> type) {
try {
return Optional.of(context.getComponent(type));
} catch (MissingComponentException missing) {
if (missing.getComponentType() == type) return Optional.empty();
throw missing;
}
}
@Override
public <T> ViewObject<T> createViewObject(Class<T> type) {
T instance = context.createComponent(type);
return new ViewObject<>(instance, () -> release(instance));
}
private static void release(Object instance) {
if (instance instanceof AutoCloseable closeable) {
try {
closeable.close();
} catch (RuntimeException failure) {
throw failure;
} catch (Exception failure) {
throw new IllegalStateException("Could not close " + instance.getClass().getName(), failure);
}
}
}
}
@@ -0,0 +1,126 @@
package de.neitzel.fx.injection;
import de.neitzel.fx.i18n.Localizer;
import de.neitzel.fx.injection.fixture.Card;
import de.neitzel.fx.injection.fixture.Controller;
import de.neitzel.fx.injection.fixture.Entry;
import de.neitzel.fx.injection.fixture.Lifecycle;
import de.neitzel.fx.test.FxFixture;
import de.neitzel.fx.test.FxTest;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import lombok.Getter;
import lombok.Setter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@FxTest
class NeitzelViewDependenciesTest {
@Getter
@Setter
public static final class Model {
private String name = "Ada";
private List<Entry> entries = new ArrayList<>(List.of(new Entry()));
}
@Test
void loadsRepeatTableAndStandaloneComponentWithOneApplicationContext(FxFixture fx) throws Exception {
fx.run(() -> {
var context = new ApplicationContext(Controller.class);
var lifecycle = context.getComponent(Lifecycle.class);
context.addSingleton(Localizer.class, new Localizer(Locale.ENGLISH, Locale.ENGLISH,
new Localizer.Catalog(Controller.class, "View")));
var dependencies = new NeitzelViewDependencies(context, Set.of(Card.class));
var cached = context.getComponent(Card.class);
assertSame(cached, context.getComponent(VBox.class));
assertFalse(dependencies.isComponent(VBox.class));
try (var models = new ViewModelContext()) {
var model = new Model();
var fxml = Controller.class.getResource("View.fxml");
var first = ViewLoader.loadWithDependencies(fxml, model, dependencies, models);
var second = ViewLoader.loadWithDependencies(fxml, new Model(), dependencies, models);
assertEquals(VBox.class, first.getRoot().getClass());
var caption = (Label) first.getRoot().lookup("#caption");
assertEquals("[Ada]", caption.getText());
assertEquals("Localized", caption.getAccessibleText());
var controller = (Controller) caption.getUserData();
var other = (Controller) second.getRoot().lookup("#caption").getUserData();
assertNotSame(controller, other);
assertSame(lifecycle, controller.getLifecycle());
assertSame(lifecycle, other.getLifecycle());
var embedded = (Card) first.getRoot().lookup("#card");
var repeated = (Card) ((VBox) first.getRoot().lookup("#repeat")).getChildren().getFirst();
var table = first.getRoot().lookup("#table");
var rows = (VBox) ((ScrollPane) table.lookup(".table-scroll")).getContent();
var row = (Card) rows.getChildren().getFirst();
assertNotSame(cached, embedded);
assertNotSame(embedded, repeated);
assertNotSame(repeated, row);
model.getEntries().clear();
assertEquals(1, lifecycle.closeCount(repeated));
assertEquals(1, lifecycle.closeCount(row));
var separate = ViewLoader.loadComponentWithDependencies(Card.class, new Entry(), dependencies, models);
assertEquals("Ada", ((Label) separate.getRoot().lookup("#name")).getText());
separate.close();
assertEquals(1, lifecycle.closeCount(separate.getRoot()));
first.close();
first.close();
assertEquals(1, lifecycle.closeCount(embedded));
assertEquals(1, lifecycle.closeCount(controller));
assertEquals(0, lifecycle.closeCount(other));
assertSame(cached, context.getComponent(Card.class));
}
});
}
@Test
void rollsBackAndDistinguishesMissingServicesFromOverrides(FxFixture fx) throws Exception {
fx.run(() -> {
var failedLookup = new IllegalArgumentException("Lookup override failed");
var context = new ApplicationContext(Controller.class) {
@Override
public <T> T getComponent(Class<? extends T> type) {
if (type == String.class) return type.cast("override");
if (type == Integer.class) throw failedLookup;
return super.getComponent(type);
}
};
var dependencies = new NeitzelViewDependencies(context, Set.of(Card.class));
assertTrue(dependencies.findService(Localizer.class).isEmpty());
assertEquals("override", dependencies.findService(String.class).orElseThrow());
assertSame(failedLookup, assertThrows(IllegalArgumentException.class,
() -> dependencies.findService(Integer.class)));
var acquired = new ArrayList<>();
var tracking = new de.neitzel.fx.view.ViewDependencies() {
public boolean isComponent(Class<?> type) { return dependencies.isComponent(type); }
public <T> java.util.Optional<T> findService(Class<T> type) {
return dependencies.findService(type);
}
public <T> de.neitzel.fx.view.ViewObject<T> createViewObject(Class<T> type) {
var found = dependencies.createViewObject(type);
acquired.add(found.instance());
return found;
}
};
try (var models = new ViewModelContext()) {
assertThrows(IllegalStateException.class, () -> ViewLoader.loadWithDependencies(
Controller.class.getResource("Invalid.fxml"), new Model(), tracking, models));
}
var lifecycle = context.getComponent(Lifecycle.class);
assertEquals(2, acquired.size());
assertTrue(acquired.stream().allMatch(value -> lifecycle.closeCount(value) == 1));
});
}
}
@@ -0,0 +1,28 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.VBox;
@Singleton
public final class Card extends VBox implements AutoCloseable {
private final Lifecycle lifecycle;
private final ObjectProperty<Entry> model = new SimpleObjectProperty<>(this, "model");
@Inject
public Card(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
lifecycle.opened(this);
}
public ObjectProperty<Entry> modelProperty() { return model; }
public Entry getModel() { return model.get(); }
public void setModel(Entry entry) { model.set(entry); }
@Override
public void close() { lifecycle.closed(this); }
}
@@ -0,0 +1,32 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javafx.scene.control.Label;
import javafx.fxml.FXML;
import lombok.Getter;
@Singleton
public final class Controller implements AutoCloseable {
@Getter
private final Lifecycle lifecycle;
@FXML
private Label caption;
@Inject
public Controller(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
lifecycle.opened(this);
}
@FXML
private void initialize() {
caption.setUserData(this);
}
@Override
public void close() {
lifecycle.closed(this);
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.injection.fixture;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@RequiredArgsConstructor
public final class Entry {
private String name = "Ada";
}
@@ -0,0 +1,13 @@
package de.neitzel.fx.injection.fixture;
import de.neitzel.fx.view.Converter;
import jakarta.inject.Singleton;
@Singleton
public final class FormatName implements Converter {
@Override
public Object toControlValue(Object value) { return "[" + value + "]"; }
@Override
public Object toAttributeValue(Object value) { return value; }
}
@@ -0,0 +1,16 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Singleton;
import java.util.IdentityHashMap;
import java.util.Map;
@Singleton
public final class Lifecycle {
private final Map<Object, Integer> counts = new IdentityHashMap<>();
public void opened(Object instance) { counts.put(instance, 0); }
public void closed(Object instance) { counts.computeIfPresent(instance, (key, count) -> count + 1); }
public int closeCount(Object instance) { return counts.get(instance); }
}
@@ -0,0 +1,10 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList><DirectBinding control="name" property="text" path="name" direction="view"/></BindingList>
</fx:define>
<Label fx:id="name"/>
</fx:root>
@@ -0,0 +1,7 @@
<?import de.neitzel.fx.injection.fixture.Card?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.injection.fixture.Controller">
<Label fx:id="caption"/>
<Card unknownProperty="fails after acquisition"/>
</VBox>
@@ -0,0 +1,23 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.Column?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import de.neitzel.fx.view.Repeat?>
<?import de.neitzel.fx.view.Table?>
<?import de.neitzel.fx.injection.fixture.Card?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.injection.fixture.Controller">
<fx:define>
<BindingList>
<DirectBinding control="caption" property="text" path="name" direction="view"
converter="de.neitzel.fx.injection.fixture.FormatName"/>
<Repeat pane="repeat" collection="entries" component="de.neitzel.fx.injection.fixture.Card"/>
</BindingList>
</fx:define>
<Label fx:id="caption" accessibleText="%view.caption"/>
<Card fx:id="card"/>
<VBox fx:id="repeat"/>
<Table fx:id="table" collection="entries" row="de.neitzel.fx.injection.fixture.Card">
<Column header="Name" attribute="name"/>
</Table>
</VBox>
@@ -0,0 +1 @@
view.caption=Localized
+37
View File
@@ -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.8-SNAPSHOT</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.ViewDependencies;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
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 managed FXML with application-supplied dependencies on the FX thread.
* @param fxml view resource
* @param model model for the view
* @param dependencies adapter for View objects and services
* @return managed view
* @throws Exception if the view cannot be loaded or the wait is interrupted or times out
*/
public LoadedView loadWithDependencies(URL fxml, Object model, ViewDependencies dependencies) throws Exception {
return call(() -> ViewLoader.loadWithDependencies(fxml, model, dependencies, 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,65 @@
package de.neitzel.fx.test;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import java.util.Optional;
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.loadWithDependencies(getClass().getResource("name.fxml"), person, new ViewDependencies() {
public boolean isComponent(Class<?> type) { return false; }
public <T> Optional<T> findService(Class<T> type) { return Optional.empty(); }
public <T> ViewObject<T> createViewObject(Class<T> type) {
throw new AssertionError("Unexpected view type: " + type);
}
});
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>
+218 -38
View File
@@ -35,7 +35,7 @@
`fx` includes docking and standalone bars for ordinary JavaFX applications; these controls do not require MVVM initialization. Its optional MVVM functionality binds an FXML view to an ordinary Java model. The model stays a JavaBean. The library builds one view model for that instance, loads the view, and applies the binding elements declared in the FXML. `fx` includes docking and standalone bars for ordinary JavaFX applications; these controls do not require MVVM initialization. Its optional MVVM functionality binds an FXML view to an ordinary Java model. The model stays a JavaBean. The library builds one view model for that instance, loads the view, and applies the binding elements declared in the FXML.
You write the model, the FXML, and, where a screen needs them, a controller, reusable components, and converters. The library creates the view model. The [injection](../injection/README.md) container creates the controller, each component, and each converter. You write the model, the FXML, and, where a screen needs them, a controller, reusable components, and converters. The library creates the view model. The application's `ViewDependencies` supplies controllers, components and converters.
The worked example is the `fx-example` module, package `de.neitzel.fx.example`. From the NeitzelLib root, with Java 25: The worked example is the `fx-example` module, package `de.neitzel.fx.example`. From the NeitzelLib root, with Java 25:
@@ -46,7 +46,11 @@ The worked example is the `fx-example` module, package `de.neitzel.fx.example`.
The launch class is `de.neitzel.fx.example.Main`. `Main` does not extend `Application`. It calls `Application.launch(DeskApp.class, args)`, and `DeskApp.start` builds the scene on the JavaFX thread. The launch class is `de.neitzel.fx.example.Main`. `Main` does not extend `Application`. It calls `Application.launch(DeskApp.class, args)`, and `DeskApp.start` builds the scene on the JavaFX thread.
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` for your own adapter. For Neitzel's
`ApplicationContext`, depend on [`de.neitzel.lib:fx-injection`](../fx-injection/README.md).
That artifact brings in `fx` and `injection`.
Use `ViewLoader.loadComponentWithDependencies(type, model, dependencies, 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
@@ -56,27 +60,26 @@ 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.2` | Use the Gitea Maven registry or install the local reactor | | Library | `de.neitzel.lib:fx:1.0.7` | See [Maven setup](../README.md#use-a-release-from-maven). |
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven | | Internal modules | `fx` directly depends on `core` 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 | | 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` | | Optional Neitzel DI | `fx-injection` → `injection`, Reflections and Jakarta Inject | Include when you choose Neitzel's container |
| 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 |
| Library build | Lombok 1.18.48 and test/analysis tooling | Not required in ordinary consumer source; use your own annotations only if wanted | | Library build | Lombok 1.18.48 and test/analysis tooling | Not required in ordinary consumer source; use your own annotations only if wanted |
| Designer | Optional preview API / Model processor | Needed only for the selected Designer workflow, not normal `ViewLoader` use | | Designer | Optional preview API / Model processor | Needed only for the selected Designer workflow, not normal `ViewLoader` use |
The quick-start POM adds only `fx` and a logging backend. Do not copy library build-time dependencies into an application just to obtain runtime binding. A project using injection alone needs the `injection` artifact and does not need JavaFX. The published 1.0.6 quick start uses its matching POM and APIs. Do not copy library build-time dependencies into an application just to obtain runtime binding. A project using injection alone needs the `injection` artifact and does not need JavaFX.
## Quick start ## Quick start
`DeskApp` scans its package, loads one person into `Desk.fxml`, and asks for a dialog when a new message is added: `DeskApp` scans its package, loads one person into `Desk.fxml`, and asks for a dialog when a new message is added:
```java ```java
ApplicationContext context = new ApplicationContext(DeskApp.class);
Person person = DeskApp.sample(); Person person = DeskApp.sample();
LoadedView loaded = ViewLoader.load( ViewModelContext models = new ViewModelContext();
DeskController.class.getResource("Desk.fxml"), person, context); LoadedView loaded = ViewLoader.loadWithDependencies(
DeskController.class.getResource("Desk.fxml"), person, DeskApp.dependencies(person), models);
MessagePopup.showNewMessages(loaded.getViewModel()); MessagePopup.showNewMessages(loaded.getViewModel());
Parent root = loaded.getRoot(); Parent root = loaded.getRoot();
``` ```
@@ -92,9 +95,9 @@ Parent root = loaded.getRoot();
<TextField fx:id="nameField"/> <TextField fx:id="nameField"/>
``` ```
`ApplicationContext` scans the package of the class you pass, and its subpackages. `DeskApp` carries `@Config(basePackage = "de.neitzel.fx.example")`, which is that package. `ViewLoader.load` reuses the view model already built for that person, or builds one, then loads the FXML and applies the binding elements. `ApplicationContext` scans the package of the class you pass, and its subpackages. `DeskApp` carries `@Config(basePackage = "de.neitzel.fx.example")`, which is that package. `ViewLoader.loadWithDependencies` reuses the view model already built in its Model context for that person, or builds one, then loads the FXML and applies the binding elements.
One model instance has one view model. The first view fixes the view model class. The desk's controller names `PersonViewModel`, so that is the class for this person. One Model instance has one ViewModel per Model context. The first view fixes the view model class. The desk's controller names `PersonViewModel`, so that is the class for this person.
## The person desk ## The person desk
@@ -148,7 +151,8 @@ After the view model exists, it is the writer. A property change calls the sette
## Load a view ## Load a view
```java ```java
public static LoadedView load(URL fxml, Object model, ApplicationContext context) public static LoadedView loadWithDependencies(URL fxml, Object model,
ViewDependencies dependencies, ViewModelContext models)
``` ```
The load reads `fx:controller` from the document first, so it can see `@ViewModelClass`, and builds or reuses the view model. It then loads the FXML. The container supplies the controller. Components come from the container as well. The root must be a `Parent`. Bindings run after `@FXML` fields are filled. Tables under the root open last, including a table inside a scroll pane. The load reads `fx:controller` from the document first, so it can see `@ViewModelClass`, and builds or reuses the view model. It then loads the FXML. The container supplies the controller. Components come from the container as well. The root must be a `Parent`. Bindings run after `@FXML` fields are filled. Tables under the root open last, including a table inside a scroll pane.
@@ -157,9 +161,50 @@ The load reads `fx:controller` from the document first, so it can see `@ViewMode
`LoadedView.property(String)` returns the JavaFX property for an attribute name, for `latestMessage`, or for a `nameProperty()` method on the view model. A missing name returns null. A binding whose path does not resolve fails the load. `LoadedView.property(String)` returns the JavaFX property for an attribute name, for `latestMessage`, or for a `nameProperty()` method on the view model. A missing name returns null. A binding whose path does not resolve fails the load.
FXML that cannot be read becomes `IllegalStateException` `Could not load view` and the URL. A missing controller class is `IllegalArgumentException` `No controller` and the name. FXML that cannot be read becomes `IllegalStateException` `Could not load view` and the URL. A missing controller class is reported with `No controller` and the name in the cause.
`DeskLoadsTest.secondViewReusesTheViewModel` loads a second document, `NameLine.fxml`, for the same person. The second document names no controller and no view model class. It reuses `PersonViewModel`. Typing in the desk's name field updates the second field, and the title becomes `titled-Grace`. Loading `Desk.fxml` a second time while the first desk is showing does not work: the home `AddressForm` is the cached singleton and already has children. See [Component](#component). `DeskLoadsTest.secondViewReusesTheViewModel` loads a second document, `NameLine.fxml`, for the same person. The second document names no controller and no view model class. It reuses `PersonViewModel`. Typing in the desk's name field updates the second field, and the title becomes `titled-Grace`.
### Use an application DI container
Use `ViewDependencies` with the managed loader when your application owns a
DI container. Construct the adapter once for that container. Open views on
the JavaFX application thread and keep their `ViewModelContext` for their
lifetime.
```java
ViewModelContext models = new ViewModelContext();
LoadedView view = ViewLoader.loadWithDependencies(fxml, model, dependencies, models);
stage.setScene(new Scene(view.getRoot()));
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close());
```
Use `ViewLoader.loadComponentWithDependencies(ComponentType.class, model,
dependencies, models)` for a Component's own `fx:root` document.
`FxFixture.loadWithDependencies(fxml, model, dependencies)` loads the
same way on the test's JavaFX thread and owns its model context.
Implement the three methods of `ViewDependencies`.
- `isComponent(type)` checks an exact Component registration before FXML
creates the object. A set of the Component classes with their own FXML is
sufficient. Return false for ordinary JavaFX elements.
- `createViewObject(type)` supplies a fresh injected Controller or Component
and a release action in a `ViewObject`. Use concrete FXML types and an
unshared scope for UI classes. Register services such as storage separately
with the scope they need. In Spring, a named prototype bean and
`destroyBean(name, instance)` are one way to implement this method.
- `findService(type)` resolves application-owned Converters and the optional
`Localizer`. Return `Optional.empty()` for an absent binding. Propagate
lookup and creation failures so the load can report the right cause.
DI construction precedes `@FXML` injection. Use JavaFX `initialize()`
for access to FXML fields and the ViewModel handoff for work that needs that
ViewModel. When a view is closed, a dynamic child is removed or a load rolls
back, FX detaches its bindings and calls the associated release action.
Close your container after its views. To update a caller that used the
published `ApplicationContext` overloads, follow the
[Neitzel adapter migration](../fx-injection/README.md#migrate-an-existing-fx-application).
## Direct binding ## Direct binding
@@ -171,9 +216,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`.
@@ -185,6 +230,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.
@@ -193,7 +253,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.
@@ -201,7 +261,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
@@ -251,15 +311,104 @@ 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 adapter creates a fresh instance for the View. `@FXML` fields are filled during load, before the bindings run.
Leave `fx:controller` off and the library supplies a controller, which is enough for a view that has only direct bindings. `NameLine.fxml` in the test is that shape. You cannot obtain the supplied controller from `LoadedView`. Leave `fx:controller` off and the library supplies a controller, which is enough for a view that has only direct bindings. `NameLine.fxml` in the test is that shape. You cannot obtain the supplied controller from `LoadedView`.
Implement `HasViewModel` when your code needs the view model. The library calls `setViewModel` after construction and before the bindings run, and only when the selected object is a `ViewModel`. The desk stores it and reads `visits`, `tags`, `name`, and `age` from it. Implement `HasViewModel` when your code needs the view model. The library calls `setViewModel` after construction and before the bindings run, and only when the selected object is a `ViewModel`. The desk stores it and reads `visits`, `tags`, `name`, and `age` from it.
A second view whose document names the same controller class receives that same singleton. FXML then injects the second view's fields into it. The desk is one window, so its controller fields stay on that window. Give a second screen its own controller class when each screen needs its own `@FXML` fields. Each load receives its own controller and `@FXML` fields. Share
application state through a service. The desk shares `VisitActions` with
its table rows.
## Choosing the ViewModel class ## Choosing the ViewModel class
@@ -309,7 +458,7 @@ remain handled by the containing FXMLLoader.
A component is a class the container can create. It extends `Parent` (usually a Pane subclass such as `VBox`), loads `ClassName.fxml` from its own package through `fx:root`, and is the controller of that file. It has no `fx:controller`. It exposes one JavaFX property named `model`. A component is a class the container can create. It extends `Parent` (usually a Pane subclass such as `VBox`), loads `ClassName.fxml` from its own package through `fx:root`, and is the controller of that file. It has no `fx:controller`. It exposes one JavaFX property named `model`.
`AddressForm` edits the home address. `VisitForm` edits one visit in the repeated list. `NoteForm` edits a note. `VisitRow` edits one table row. Each is `@Singleton`, extends `VBox` or `HBox`, and has `modelProperty()`. `AddressForm` edits the home address. `VisitForm` edits one visit in the repeated list. `NoteForm` edits a note. `VisitRow` edits one table row. Each extends `VBox` or `HBox` and has `modelProperty()`. In the example, `@Singleton` marks the classes for Neitzel's scanner. The adapter creates a fresh instance for each occurrence.
The home document binds the form and sets `model` from the path. When the path's last segment is complex, the value assigned is the model instance behind that view model. The home document binds the form and sets `model` from the path. When the path's last segment is complex, the value assigned is the model instance behind that view model.
@@ -322,9 +471,9 @@ The component's own bindings run once, the first time `model` becomes non-null.
`initialize` runs during the component's FXML load, before `model` is set. `AddressForm` uses that moment to copy the injected heading onto its label, which does not need the address. For a Component implementing `HasViewModel`, `setViewModel` runs after `model` is set to a non-null Model and before its bindings, but only when the selected presentation object extends `ViewModel`. An arbitrary replacement does not receive this callback. `AddressForm` implements `HasViewModel` and writes `Opened as ` plus the city at that moment. Editing the city afterward leaves the label on the city the form opened with. The sample home opens as `Opened as Sample City`. `initialize` runs during the component's FXML load, before `model` is set. `AddressForm` uses that moment to copy the injected heading onto its label, which does not need the address. For a Component implementing `HasViewModel`, `setViewModel` runs after `model` is set to a non-null Model and before its bindings, but only when the selected presentation object extends `ViewModel`. An arbitrary replacement does not receive this callback. `AddressForm` implements `HasViewModel` and writes `Opened as ` plus the city at that moment. Editing the city afterward leaves the label on the city the form opened with. The sample home opens as `Opened as Sample City`.
The first component of a class in one load is `context.getComponent`, the cached singleton. Each further one in that same load is `context.createComponent`. Repeat and table rows always use `createComponent`, so they are new instances and the cached singleton of that class stays unused by the rows. `getComponent(VisitForm.class)` after the desk loads is still the singleton, and the three forms in the visit pane are other instances. Every registered FXML Component is created fresh, including Repeat children
and table rows. The Neitzel adapter uses `createComponent` and leaves the
A later load starts over. Its first component of a class is the cached singleton again. The home `AddressForm` is that singleton and is already in the scene, so loading `Desk.fxml` a second time fails while building the home form: a node cannot be added to a second parent. The test's second view is a document with no component. context's shared registrations available to other callers.
A component class needs `ClassName.fxml` beside it. A missing document fails with `No component document`. A missing `modelProperty` method fails with `No model property on`. A method that does not return a `Property` fails with `modelProperty did not return a property`. A component class needs `ClassName.fxml` beside it. A missing document fails with `No component document`. A missing `modelProperty` method fails with `No model property on`. A method that does not return a `Property` fails with `modelProperty did not return a property`.
@@ -334,7 +483,8 @@ A nested component is the same mechanism one level down. The child document name
`AddressForm.fxml` binds `noteForm` to path `note` and contains `<NoteForm fx:id="noteForm"/>`. `NoteForm.fxml` binds its text field to path `text`. The sample home note is `Kept at home`. Editing the note field writes `text` on the existing `Note` held by `Address.note`; it does not replace that Note object. `AddressForm.fxml` binds `noteForm` to path `note` and contains `<NoteForm fx:id="noteForm"/>`. `NoteForm.fxml` binds its text field to path `text`. The sample home note is `Kept at home`. Editing the note field writes `text` on the existing `Note` held by `Address.note`; it does not replace that Note object.
`VisitForm` does not contain `NoteForm`. A visit added after the desk has loaded is built in a new load. The first component of a class in that load is the cached singleton again, so a `NoteForm` nested in the repeated form would be the instance already showing under the home address. Keeping the note on the home form, which is loaded once, leaves that singleton where it was placed. `VisitForm` displays the visit fields. The desk shows a note editor in
the home address form.
A null `note` leaves the nested binding unapplied. `NoteForm` stays empty and the load succeeds. The sample home has a note, so its bindings run. A null `note` leaves the nested binding unapplied. `NoteForm` stays empty and the load succeeds. The sample home has a note, so its bindings run.
@@ -419,7 +569,7 @@ Add and remove update the body. A permutation or an extractor update notificatio
A column attribute must be a simple value: string, boolean, enum, a primitive other than `char` and `void`, a `Number`, a `Date`, a `Calendar`, or a `java.time` temporal. `visitedOn` is a `LocalDate`, so it is a column. A complex attribute fails the load with `Attribute "` name `" is not a simple value`. A column attribute must be a simple value: string, boolean, enum, a primitive other than `char` and `void`, a `Number`, a `Date`, a `Calendar`, or a `java.time` temporal. `visitedOn` is a `LocalDate`, so it is a column. A complex attribute fails the load with `Attribute "` name `" is not a simple value`.
Other load failures, all `IllegalArgumentException`: Other load failures reported in the cause:
| Condition | Message | | Condition | Message |
| --- | --- | | --- | --- |
@@ -433,6 +583,28 @@ 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.loadWithDependencies(fxml, model, dependencies, 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 adapter supplies a fresh Controller or Component and its release action. FX invokes
that action on close and when it rolls back an unsuccessful load. The Neitzel adapter
calls `AutoCloseable.close()` for UI instances that implement it. Use these handles
on the FX application thread.
### 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.
@@ -519,21 +691,21 @@ A list element is not a nested view model. A failure recorded on a visit is carr
## What the container creates ## What the container creates
`ViewLoader.load` takes an `ApplicationContext`. The view model is never created by the container. `ViewDependencies` provides the following objects. The Model context
creates or reuses the ViewModel.
| Object | How it is created | | Object | How it is resolved |
| --- | --- | | --- | --- |
| Controller named by `fx:controller` | `getComponent`, once | | Controller named by `fx:controller` | A fresh `ViewObject` from `createViewObject` |
| Converter named on a direct binding | `getComponent` | | Converter named on a direct binding | `findService` on the declared class |
| First component of a class in a load | `getComponent`, when that instance is free to place | | Embedded and standalone Components, Repeat children and table rows | Exact registration and a fresh `ViewObject` per instance |
| Another element of that class in the same load | `createComponent` | | Optional `Localizer` | `findService(Localizer.class)` |
| Repeat children and table rows | `createComponent` |
Details of scanning, `@Singleton`, `@Named`, constructor, field, and setter injection, and `@Config` are in the [injection guide](../injection/README.md). The desk's scan root is `DeskApp`. Details of scanning, `@Singleton`, `@Named`, constructor, field, and setter injection, and `@Config` are in the [injection guide](../injection/README.md). The desk's scan root is `DeskApp`.
## When a load fails ## When a load fails
These are the `IllegalArgumentException` messages a document can produce. The view is not shown. The loader reports the FXML resource and preserves the exception with the specific cause.
| Message | Cause | | Message | Cause |
| --- | --- | | --- | --- |
@@ -541,7 +713,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 |
@@ -567,7 +740,9 @@ The reference above covers the FXML declarations and their behavior. These are t
| Responsibility | Types and key members | | Responsibility | Types and key members |
| --- | --- | | --- | --- |
| Load | `ViewLoader.load`, `LoadedView.getRoot`, `getViewModel`, `property` | | Load | `ViewLoader.loadWithDependencies`, `loadComponentWithDependencies`, `LoadedView.getRoot`, `getViewModel`, `property` |
| Lifetime | `ViewModelContext`, `LoadedView.close()` |
| Dependency integration | `ViewDependencies`, `ViewObject` |
| Presentation state | `ViewModel.property`, protected `storedProperty`, `HasViewModel.setViewModel`, `@ViewModelClass` | | Presentation state | `ViewModel.property`, protected `storedProperty`, `HasViewModel.setViewModel`, `@ViewModelClass` |
| Declarations | `BindingList`, `DirectBinding`, `ComputedBinding`, `Repeat`; JavaBean setters correspond to the FXML attributes described above | | Declarations | `BindingList`, `DirectBinding`, `ComputedBinding`, `Repeat`; JavaBean setters correspond to the FXML attributes described above |
| Convert values | `Converter.toControlValue`, `toAttributeValue` | | Convert values | `Converter.toControlValue`, `toAttributeValue` |
@@ -578,4 +753,9 @@ 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, Model identity, resource release and reflective module access, see [architecture and lifetime](docs/architecture.md). For an independent application POM and runnable files using the 1.0.6 release, 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"/>`.
+23 -19
View File
@@ -8,14 +8,14 @@ NeitzelLib creates that presentation layer at runtime. You can subclass it for a
```mermaid ```mermaid
flowchart TD flowchart TD
App[Application: Model + ApplicationContext] --> Loader[ViewLoader] App[Application: Model + ViewDependencies] --> Loader[ViewLoader]
FXML[FXML: controls and binding declarations] --> Loader FXML[FXML: controls and binding declarations] --> Loader
Loader --> View[LoadedView: JavaFX root] Loader --> View[LoadedView: JavaFX root]
Loader --> VM[Runtime ViewModel] Loader --> VM[Runtime ViewModel]
Model[JavaBean Model] -->|Initial getter read / lazy child resolution| VM Model[JavaBean Model] -->|Initial getter read / lazy child resolution| VM
VM -->|Property change calls setter| Model VM -->|Property change calls setter| Model
View <-->|DirectBinding| VM View <-->|DirectBinding| VM
Context[ApplicationContext] --> Controller[Controller / Computed methods] Context[ViewDependencies] --> Controller[Controller / Computed methods]
Context --> Converter[Converters] Context --> Converter[Converters]
Context --> Component[Component root and controller] Context --> Component[Component root and controller]
Controller --> View Controller --> View
@@ -30,7 +30,7 @@ The [dependency baseline](../README.md#dependencies) distinguishes application r
## Loading order ## Loading order
`ViewLoader.load` reads the controller declaration and its ViewModel selection, obtains or creates the Model's ViewModel, then loads FXML. The injection context supplies controllers, Components and Converters. JavaFX performs normal `@FXML` field injection and calls `initialize`. After loading, the library supplies the ViewModel to `HasViewModel` only when the selected object extends `ViewModel` (replacement objects do not receive this callback), applies BindingLists in document order, and opens custom Tables. `ViewLoader.loadWithDependencies` reads the controller declaration and its ViewModel selection, obtains or creates the Model's ViewModel, then loads FXML. The adapter supplies controllers, Components and Converters. JavaFX performs normal `@FXML` field injection and calls `initialize`. After loading, the library supplies the ViewModel to `HasViewModel` only when the selected object extends `ViewModel` (replacement objects do not receive this callback), applies BindingLists in document order, and opens custom Tables.
Consequently, `initialize` must not assume that `HasViewModel.setViewModel` has already run. A Component's own bindings wait for its first non-null Model. Binding order can matter when an earlier declaration causes a nested Model's ViewModel to be created before a later Component requests a more specific class. Consequently, `initialize` must not assume that `HasViewModel.setViewModel` has already run. A Component's own bindings wait for its first non-null Model. Binding order can matter when an earlier declaration causes a nested Model's ViewModel to be created before a later Component requests a more specific class.
@@ -40,7 +40,11 @@ Consequently, `initialize` must not assume that `HasViewModel.setViewModel` has
Attributes are JavaBeans properties with both a getter and setter. Runtime properties are initialized from the bean and changes to them call its setter. Direct calls to a bean setter do not send notifications back to the runtime property. Update the ViewModel on the JavaFX application thread when application logic should update an existing View. Attributes are JavaBeans properties with both a getter and setter. Runtime properties are initialized from the bean and changes to them call its setter. Direct calls to a bean setter do not send notifications back to the runtime property. Update the ViewModel on the JavaFX application thread when application logic should update an existing View.
The runtime holds a **global, strong, identity-based cache** of Model-to-ViewModel associations. The same Model object shares one ViewModel across Views and contexts; equal but distinct beans do not. Registration before traversing children supports cyclic graphs. There is no public eviction or release API. Treat this as an explicit limitation for applications with many short-lived Models. Each managed `ViewModelContext` stores Model-to-ViewModel associations
by object identity. Views in the same context can share the ViewModel
for the same Model object. Independent contexts have independent
registrations. Registration before traversing children supports cyclic graphs.
Closing the context releases its registrations and closes the remaining Views.
Complex Attributes are mapped lazily to nested ViewModels. A null child stays null. A dotted binding resolves intermediate objects when the binding is applied; it does not dynamically reattach after replacing an intermediate child. Bind a Component's `model` to the complex Attribute when you want a subform, but note that the current Component implementation also applies its internal bindings only for its first non-null Model. Complex Attributes are mapped lazily to nested ViewModels. A null child stays null. A dotted binding resolves intermediate objects when the binding is applied; it does not dynamically reattach after replacing an intermediate child. Bind a Component's `model` to the complex Attribute when you want a subform, but note that the current Component implementation also applies its internal bindings only for its first non-null Model.
@@ -48,24 +52,24 @@ Lists are shared ObservableLists when possible. A `List` bean setter generally a
## Context and View lifetime ## Context and View lifetime
The [injection context](../../injection/README.md) caches one instance of every scanned class. This includes controllers and converters. Reusing a controller in multiple live Views overwrites its injected FXML fields. Components reuse the context instance for the first occurrence of a class in a load and create fresh instances for additional occurrences; Repeat and Table explicitly create fresh row roots. Nested Components still need care when the same context is reused across independent loads. Use one adapter for a container and give each logical window or document
a Model context. Related Views can share a Model context. Each View
receives fresh Controller and Component instances. Share services through
the adapter.
Use a separate context for independent windows unless shared controller/component lifetime is intentional. This does not isolate the global Model identity cache: use separate Model instances if you need independent drafts. Close a `LoadedView` when it leaves the application. Its bindings and
listeners are detached, and the adapter's release actions run for its
There is no general `LoadedView.close()`, ViewModel disposal, unbind-all operation, or container shutdown hook. Bindings, collection listeners and MessagePopup listeners can retain objects. Closing a Stage does not constitute a documented cleanup contract for these listeners. Install popup listeners once, keep application lifetimes bounded, and test long-running/repeated-window workloads before depending on this snapshot. Controller and child Components. Close the Model context when its owner
ends. Close the application-owned container after its Views. The optional
[Neitzel adapter](../../fx-injection/README.md) uses the existing
ApplicationContext lookup for shared services and fresh instances for the UI.
Run loading, scene changes, observable property updates and message operations on the JavaFX application thread. The context and ViewModel cache are not concurrent services. Perform slow I/O separately and deliver results with `Platform.runLater`; do not perform it inside Computed methods or property listeners. Run loading, scene changes, observable property updates and message operations on the JavaFX application thread. The context and ViewModel cache are not concurrent services. Perform slow I/O separately and deliver results with `Platform.runLater`; do not perform it inside Computed methods or property listeners.
## Modules and reflection ## Modules and reflection
The library artifacts currently act as automatic modules named `fx` and `injection`. An application using JPMS generally needs `requires fx`, `requires injection`, `requires jakarta.inject`, `requires javafx.controls` and `requires javafx.fxml`. The precise requirements depend on its imports. A named application using FX typically declares `requires fx`,
`requires javafx.controls` and `requires javafx.fxml`. An application
Open bean packages to `fx` for reflective Attribute access. FXML controller and Component packages need reflective access for JavaFX and the library/container; an unqualified `opens your.controls;` is a straightforward starting point while diagnosing a modular application. Injection may invoke non-public constructors and members. Generated ViewModel packages also require suitable exports/opens, and a named-module registry uses `provides de.neitzel.fx.view.ViewModelRegistry with ...` rather than only a classpath service file. using the optional Neitzel adapter adds `requires de.neitzel.fx.injection`
and declares `requires injection` and `requires jakarta.inject` where
Package scanning depends on the runtime's class/module paths. Verify the real modular launch; success on the classpath does not prove a module configuration is correct. The Designer separately validates classpath and module-path target applications and keeps its Kit runtime distinct from the application's JavaFX runtime. it uses those types. Each container's own requirements apply to its adapter.
## Choosing extensions
Start with generic runtime properties. Add a ViewModel subclass for derived presentation state and a controller for event handling. Use [generated ViewModels](generated-viewmodels.md) for typed access and shared discovery metadata. Use [Components, Repeat and Table](../README.md#component) to reuse form structure. The Designer is an optional authoring tool: the application remains runnable without it.
The library is a development snapshot and a personal helper collection. In particular, it is not a transactional form engine, a virtualized table, a dependency-tracking expression language, or a full dependency injection framework. Keep business validation and persistence boundaries explicit in application code.
+16 -3
View File
@@ -47,9 +47,22 @@ 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 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 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. fixed-position constraints apply; invalid/outside drops cancel without sorting.
Grouped columns remain visible. Drag chips to reorder levels, and use × to remove Drag chips to reorder grouping levels, and use × to remove a grouping level.
a grouping level. A header click still sorts and the separate filter icon opens A header click sorts and the separate filter icon opens its editor. The Grid
its editor. The Grid setup menu offers keyboard-operable Column settings. 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, Each group has a disclosure triangle. Expansion follows the typed ordered path,
not its label or page number. Parent collapse preserves child choices. Current not its label or page number. Parent collapse preserves child choices. Current
+21
View File
@@ -36,6 +36,27 @@ Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` fo
- A successfully replaced source clears all selection. `confirmedDeleted(key)` removes only that key and refreshes; absence from a page alone does not imply deletion. Collapsed groups retain their keys but expose no actionable elements for hidden rows. - 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.
+13 -3
View File
@@ -9,8 +9,8 @@ context. The optional `ViewLoader` applies NeitzelLib binding declarations.
| `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.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.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.StatusBar` | `leftItems`, `rightItems` containing ordinary Nodes | Bind the properties of the contained controls |
| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes and a `suggestions` list of strings | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action | | `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` | Explicit `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) | | `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.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.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 | | `de.neitzel.fx.control.NonNegativeIntegerSpinner` | `minimum`, `maximum`, `initialValue` constructor attributes | Bind writable `number`, which shares the value factory's property |
@@ -48,7 +48,7 @@ objects, rather than controls to insert in a scene graph.
``` ```
Initialize the model's `List<Person> people` before loading. Bean and Java record 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 rows are supported. After loading with `ViewLoader.loadWithDependencies`, call the grid's `load()` or
`loadAsync()` on the FX thread. The data binding shares the model's observable `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 list. Add, remove, replace, permute or use an extractor update on that list to
request a refresh immediately, invalidating older pending results. The existing request a refresh immediately, invalidating older pending results. The existing
@@ -114,3 +114,13 @@ The original `IntegerSpinners.nonNegative(...)` factory remains available.
See [bars](bars.md), [docking](docking.md) and the main [FXML reference](../README.md) 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 for the existing controls. The host designer needs the updated library on its
classpath; this feature does not replace a separately pinned Designer runtime. 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.
+12
View File
@@ -34,6 +34,18 @@ message are included. New loads cancel pending work and discard stale results.
`clear()` releases the current content and leaves the viewer reusable. `close()` `clear()` releases the current content and leaves the viewer reusable. `close()`
also cancels pending work, is idempotent, and makes future loads fail. 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 ## External images
Each displayed document starts offline. The included **Load external media** Each displayed document starts offline. The included **Load external media**
+1 -1
View File
@@ -1,6 +1,6 @@
# Message catalogs for Java and FXML # 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. Create one Localizer per application. The initial locale can be null to use the JVM display locale. The second argument specifies the fallback language. Expose the service through `ViewDependencies.findService(Localizer.class)`. With the Neitzel adapter, register it in the underlying `ApplicationContext`.
```java ```java
var language = new Localizer(initialLocale, Locale.ENGLISH, var language = new Localizer(initialLocale, Locale.ENGLISH,
+15 -5
View File
@@ -1,13 +1,17 @@
# 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.2. 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.
For the separated FX runtime introduced in 1.0.7 and its managed loader, see
[FX loading](../README.md#load-a-view) and the
[optional Neitzel adapter](../../fx-injection/README.md).
## 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.2 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
@@ -33,7 +37,7 @@ print(f'{len(reports)} test suites passed')
PYTHON PYTHON
``` ```
Use a clean build when qualifying a change so stale reports cannot stand in for tests that did not run. Use a clean build when qualifying a change so stale reports cannot stand in for tests that did not run. The standalone POM below can also resolve the published 1.0.6 artifacts directly.
## Create the application ## Create the application
@@ -62,11 +66,17 @@ hello-fx/
<maven.compiler.release>25</maven.compiler.release> <maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<repositories>
<repository>
<id>gitea-neitzellib</id>
<url>https://gitea.neitzel.de/api/packages/konrad/maven</url>
</repository>
</repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>de.neitzel.lib</groupId> <groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId> <artifactId>fx</artifactId>
<version>1.0.2</version> <version>1.0.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
@@ -190,7 +200,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.2` 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. |
+9 -9
View File
@@ -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.2</version> <version>1.0.8-SNAPSHOT</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>
@@ -47,17 +52,17 @@
<dependency> <dependency>
<groupId>org.jsoup</groupId> <groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId> <artifactId>jsoup</artifactId>
<version>1.23.2</version> <version>${jsoup.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.helger</groupId> <groupId>com.helger</groupId>
<artifactId>ph-css</artifactId> <artifactId>ph-css</artifactId>
<version>8.2.3</version> <version>${ph-css.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.twelvemonkeys.imageio</groupId> <groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-webp</artifactId> <artifactId>imageio-webp</artifactId>
<version>3.15.3</version> <version>${imageio-webp.version}</version>
</dependency> </dependency>
<!-- NeitzelLib dependencies --> <!-- NeitzelLib dependencies -->
@@ -67,11 +72,6 @@
<artifactId>core</artifactId> <artifactId>core</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>injection</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@@ -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));
}
}
@@ -1,9 +1,13 @@
package de.neitzel.fx.control; package de.neitzel.fx.control;
import java.util.Locale; 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.FXCollections;
import javafx.collections.ListChangeListener; import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.collections.WeakListChangeListener;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.scene.control.ListView; import javafx.scene.control.ListView;
import javafx.scene.control.TextField; import javafx.scene.control.TextField;
@@ -16,6 +20,18 @@ import javafx.stage.Popup;
public final class AutoCompleteTextField extends TextField { public final class AutoCompleteTextField extends TextField {
private static final int ROW_HEIGHT = 26; private static final int ROW_HEIGHT = 26;
private final ObservableList<String> suggestions = FXCollections.observableArrayList(); 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 ListView<String> choices = new ListView<>();
private final Popup popup = new Popup(); private final Popup popup = new Popup();
private boolean accepting; private boolean accepting;
@@ -29,9 +45,12 @@ public final class AutoCompleteTextField extends TextField {
var value = choices.getSelectionModel().getSelectedItem(); var value = choices.getSelectionModel().getSelectedItem();
if (event.getButton() == MouseButton.PRIMARY && value != null) accept(value); if (event.getButton() == MouseButton.PRIMARY && value != null) accept(value);
}); });
suggestions.addListener((ListChangeListener<String>) change -> updateSuggestions()); suggestionsSource.addListener((InvalidationListener) ignored -> observeSuggestions());
textProperty().addListener((property, before, after) -> updateSuggestions()); textProperty().addListener((property, before, after) -> updateSuggestions());
sceneProperty().addListener((property, before, after) -> popup.hide()); sceneProperty().addListener((property, before, after) -> {
popup.hide();
observeSuggestions();
});
disabledProperty().addListener((property, before, disabled) -> { disabledProperty().addListener((property, before, disabled) -> {
if (disabled) popup.hide(); if (disabled) popup.hide();
}); });
@@ -42,6 +61,21 @@ public final class AutoCompleteTextField extends TextField {
return suggestions; 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) { private void handleKey(KeyEvent event) {
var selection = choices.getSelectionModel(); var selection = choices.getSelectionModel();
if (event.getCode() == KeyCode.DOWN || event.getCode() == KeyCode.UP && popup.isShowing()) { if (event.getCode() == KeyCode.DOWN || event.getCode() == KeyCode.UP && popup.isShowing()) {
@@ -67,11 +101,11 @@ public final class AutoCompleteTextField extends TextField {
} }
private void updateSuggestions() { private void updateSuggestions() {
if (accepting || !isFocused() || isDisabled() || getScene() == null if (observedSuggestions == null || accepting || !isFocused() || isDisabled() || getScene() == null
|| getScene().getWindow() == null || !getScene().getWindow().isShowing()) return; || getScene().getWindow() == null || !getScene().getWindow().isShowing()) return;
String prefix = getText() == null ? "" : getText().strip().toLowerCase(Locale.ROOT); String prefix = getText() == null ? "" : getText().strip().toLowerCase(Locale.ROOT);
var matches = prefix.isEmpty() ? java.util.List.<String>of() var matches = prefix.isEmpty() ? java.util.List.<String>of()
: suggestions.stream().filter(value -> value != null && !value.isBlank()) : observedSuggestions.stream().filter(value -> value != null && !value.isBlank())
.filter(value -> value.toLowerCase(Locale.ROOT).startsWith(prefix)).distinct().limit(10).toList(); .filter(value -> value.toLowerCase(Locale.ROOT).startsWith(prefix)).distinct().limit(10).toList();
choices.getItems().setAll(matches); choices.getItems().setAll(matches);
choices.getSelectionModel().clearSelection(); choices.getSelectionModel().clearSelection();
@@ -34,6 +34,7 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
private final StringProperty mediaReloadText = new SimpleStringProperty(this, "mediaReloadText", "Reload 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 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 noExternalMediaText = new SimpleStringProperty(this, "noExternalMediaText", "No resolvable external image addresses found.");
private final StringProperty html = new SimpleStringProperty(this, "html");
private HtmlDocument document; private HtmlDocument document;
private Task<HtmlDocument> pending; private Task<HtmlDocument> pending;
private long generation; private long generation;
@@ -41,6 +42,11 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
public HtmlViewer() { public HtmlViewer() {
getStyleClass().add("html-viewer"); 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.setContextMenuEnabled(false);
browser.getEngine().setJavaScriptEnabled(false); browser.getEngine().setJavaScriptEnabled(false);
loading.bind(preparing.or(browser.getEngine().getLoadWorker().runningProperty())); loading.bind(preparing.or(browser.getEngine().getLoadWorker().runningProperty()));
@@ -153,6 +159,7 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
@Override public void close() { @Override public void close() {
requireFxThread(); requireFxThread();
if (closed) return; if (closed) return;
html.unbind();
clear(); clear();
closed = true; closed = true;
} }
@@ -166,6 +173,11 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("HtmlViewer requires the JavaFX application thread."); 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 ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); }
public boolean isLoading() { return loading.get(); } public boolean isLoading() { return loading.get(); }
public ReadOnlyObjectProperty<Throwable> errorProperty() { return error.getReadOnlyProperty(); } public ReadOnlyObjectProperty<Throwable> errorProperty() { return error.getReadOnlyProperty(); }
@@ -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);
}
}
}
}
@@ -1,6 +1,5 @@
package de.neitzel.fx.view; package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import javafx.beans.DefaultProperty; import javafx.beans.DefaultProperty;
import javafx.scene.Parent; import javafx.scene.Parent;
import lombok.Getter; import lombok.Getter;
@@ -13,7 +12,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 +41,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) { ViewInstances 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,99 @@
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) {
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);
}
}
};
}
}
@@ -1,6 +1,5 @@
package de.neitzel.fx.view; package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@@ -14,6 +13,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;
@@ -36,35 +36,9 @@ final class Components {
private Components() { private Components() {
} }
/** /** Returns a Component builder or leaves the requested type to JavaFX. */
* Returns a builder for a type the container knows. static Builder<?> builder(Class<?> type, ViewInstances context, ViewLifetime owner) {
* <p> return context.isComponent(type) ? new ComponentBuilder(type, context, owner.child()) : null;
* An unknown type, such as a JavaFX control, makes {@link ApplicationContext#getComponent}
* throw {@link IllegalArgumentException}. This method returns null so FXML constructs that
* type itself. A Component that extends a JavaFX class is also left to FXML when the document
* names that JavaFX class: the container would otherwise hand back the Component. A failure
* while creating a known Component is not caught. The first Component of a class in one load
* is the cached singleton. A second Component of that class is a new injected instance, so the
* document can show two of them.
*
* @param type the type FXML is about to construct
* @param context the container that creates Components
* @return a builder for a Component, or {@code null} when the type is not a Component
*/
static Builder<?> builder(Class<?> type, ApplicationContext context) {
Object component;
try {
component = context.getComponent(type.asSubclass(Object.class));
} catch (IllegalArgumentException notAComponent) {
return null;
}
if (component.getClass() != type) {
return null;
}
if (!LoadSession.claimFirst(type)) {
component = context.createComponent(type.asSubclass(Object.class));
}
return new ComponentBuilder(component, context);
} }
/** /**
@@ -73,10 +47,11 @@ final class Components {
*/ */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE) @RequiredArgsConstructor(access = AccessLevel.PRIVATE)
private static final class ComponentBuilder extends AbstractMap<String, Object> implements Builder<Object> { private static final class ComponentBuilder extends AbstractMap<String, Object> implements Builder<Object> {
/** The injected instance. */ /** The exact Component class declared by FXML. */
private final Object component; private final Class<?> type;
/** The context used to load its document. */ /** The context used to load its document. */
private final ApplicationContext context; private final ViewInstances 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 +81,7 @@ final class Components {
*/ */
@Override @Override
public Object build() { public Object build() {
Object result = load(component, context); Object result = load(context.createComponent(type, lifetime), 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
@@ -135,19 +110,9 @@ final class Components {
} }
} }
/** /** Creates a fresh Component and loads its document before setting its Model. */
* Creates a new Component and loads its document. static Object fresh(Class<?> type, ViewInstances context, ViewLifetime lifetime) {
* <p> return load(context.component(type, lifetime), context, lifetime);
* The instance is not the cached singleton. Its dependencies still come from
* {@link ApplicationContext#getComponent}. Bindings wait until {@link #setModel} runs.
*
* @param type the Component class
* @param context the container that creates the instance and its dependencies
* @return the loaded Component
*/
static Object fresh(Class<?> type, ApplicationContext context) {
Object component = context.createComponent(type.asSubclass(Object.class));
return load(component, context);
} }
/** /**
@@ -158,8 +123,14 @@ 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) {
modelProperty(component).setValue(model); LoadSession session = LoadSession.nest();
try {
modelProperty(component).setValue(model);
session.checkFailure();
} finally {
LoadSession.unnest();
}
} }
/** /**
@@ -169,7 +140,7 @@ 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, ViewInstances context, ViewLifetime lifetime) {
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);
@@ -179,11 +150,18 @@ final class Components {
LoadSession nested = LoadSession.nest(); LoadSession nested = LoadSession.nest();
try { try {
FXMLLoader loader = new FXMLLoader(fxml, ViewLoader.resources(context, fxml, type)); 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 -> context.controller(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 (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 +179,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) { ViewInstances 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 {
if (component instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) { Object viewModel = ViewModels.of(lifetime.models(), newValue, ViewModels.namedOn(component.getClass()));
hasViewModel.setViewModel(bound); if (component instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) {
} hasViewModel.setViewModel(bound);
Parent root = (Parent) component; }
for (BindingList list : lists) { Parent root = (Parent) component;
list.apply(namespace, viewModel, component, root, context); CommandBindingApplier.validate(lists, namespace);
for (BindingList list : lists) {
list.apply(namespace, viewModel, component, root, context, lifetime);
}
Table.openAll(root, viewModel, context, lifetime);
} catch (RuntimeException | Error failure) {
lifetime.rollback(failure);
if (!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);
} }
} }
} }
@@ -33,8 +33,8 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
previous = pagingButton("Previous page", "M2 7 L14 0 V14 Z"), previous = pagingButton("Previous page", "M2 7 L14 0 V14 Z"),
next = pagingButton("Next page", "M2 0 L14 7 L2 14 Z"), next = pagingButton("Next page", "M2 0 L14 7 L2 14 Z"),
last = pagingButton("Last page", "M0 0 L12 7 L0 14 Z M14 0 H16 V14 H14 Z"), 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 GridQuery initial; private GridQuery initial;
private List<ResultColumn> columnDefinitions; private List<ResultColumn> columnDefinitions;
@@ -59,6 +59,8 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private final Label activeFilters = new Label(); private final Label activeFilters = new Label();
private final Label interactionStatus = new Label(); private final Label interactionStatus = new Label();
private final MenuButton setupMenu = new MenuButton("Grid setup"); 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 final ReadOnlyLongWrapper committedRevision = new ReadOnlyLongWrapper();
private List<String> defaultGrouping = List.of(); private List<String> defaultGrouping = List.of();
private GridSetup developerDefaults; private GridSetup developerDefaults;
@@ -68,6 +70,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private GridPersistenceAttachment<K, T> attachment; private GridPersistenceAttachment<K, T> attachment;
private GridColumnSettings<K, T> columnSettings; 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) { private static Button pagingButton(String name, String path) {
var button = new Button(); var button = new Button();
var icon = new SVGPath(); var icon = new SVGPath();
@@ -86,6 +94,8 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
} }
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this); 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<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>(); private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ReadOnlyListWrapper<K> selectedKeys = new ReadOnlyListWrapper<>( private final ReadOnlyListWrapper<K> selectedKeys = new ReadOnlyListWrapper<>(
@@ -272,13 +282,19 @@ 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()); renderer.setSelectionMode(getSelectionMode());
selectedKeys.bind(renderer.selectedKeysProperty()); selectedKeys.bind(renderer.selectedKeysProperty());
selectedElements.bind(renderer.selectedElementsProperty()); selectedElements.bind(renderer.selectedElementsProperty());
renderer.enableColumnSeparators(); renderer.enableColumnSeparators();
selectedKey.bind(renderer.selectedKeyProperty()); selectedKey.bind(renderer.selectedKeyProperty());
selectedElement.bind(renderer.selectedElementProperty()); selectedElement.bind(renderer.selectedElementProperty());
selection.bind(renderer.selectionProperty());
coordinator = coordinator =
new GridCoordinator<>( new GridCoordinator<>(
source, Platform::runLater, this::changed, result -> publishRows(result)); source, Platform::runLater, this::changed, result -> publishRows(result));
@@ -343,9 +359,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
controls.getChildren().add(setupMenu); controls.getChildren().add(setupMenu);
interactionStatus.setWrapText(true); interactionStatus.setWrapText(true);
interactionStatus.getStyleClass().add("data-grid-interaction-status"); 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"); var css = DataGrid.class.getResource("data-grid.css");
if (css != null) getStylesheets().add(css.toExternalForm()); if (css != null) getStylesheets().add(css.toExternalForm());
Button clearActiveFilters = new Button("Clear filters"); 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())); clearActiveFilters.setOnAction(e -> setFilters(List.of()));
filterSummary.getChildren().addAll(activeFilters, clearActiveFilters); filterSummary.getChildren().addAll(activeFilters, clearActiveFilters);
filterSummary.setVisible(false); filterSummary.setVisible(false);
@@ -379,6 +398,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
public ReadOnlyListProperty<T> selectedElementsProperty() { return selectedElements.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) { public void selectKeys(Collection<? extends K> keys) {
check(); check();
renderer.selectKeys(keys); renderer.selectKeys(keys);
@@ -417,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();
@@ -1252,6 +1343,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
} }
if (attachment != null) attachment.close(); if (attachment != null) attachment.close();
closed = true; closed = true;
columnMenu.hide();
closeFilter(); closeFilter();
declaration.close(); declaration.close();
if (coordinator != null) coordinator.close(); if (coordinator != null) coordinator.close();
@@ -1262,6 +1354,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
if (renderer != null) renderer.close(); if (renderer != null) renderer.close();
selectedKey.unbind(); selectedKey.unbind();
selectedElement.unbind(); selectedElement.unbind();
selection.unbind();
selectedKeys.unbind(); selectedKeys.unbind();
selectedElements.unbind(); selectedElements.unbind();
selectedKeys.set(FXCollections.emptyObservableList()); selectedKeys.set(FXCollections.emptyObservableList());
@@ -21,6 +21,12 @@ public final class DataGridColumn {
@Setter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE)
private final java.util.Map<String, String> groupLabels = new java.util.LinkedHashMap<>(); 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 width = 150;
private double minimumWidth = 80; private double minimumWidth = 80;
private double maximumWidth = 1200; private double maximumWidth = 1200;
@@ -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
@@ -1,12 +1,14 @@
package de.neitzel.fx.view; package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import java.lang.reflect.InvocationTargetException; 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 +32,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) { ViewInstances 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, ViewInstances 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 +103,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 +124,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 +180,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 +202,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 +214,7 @@ final class DirectBindingApplier {
if (instance == null) { if (instance == null) {
return; return;
} }
ViewModels.of(instance, requested); ViewModels.of(lifetime.models(), instance, requested);
} }
/** /**
@@ -261,10 +291,10 @@ final class DirectBindingApplier {
* @param className the Converter class name * @param className the Converter class name
* @return the Converter * @return the Converter
*/ */
private static Converter converter(ApplicationContext context, String className) { private static Converter converter(ViewInstances context, String className) {
try { try {
Class<?> type = Class.forName(className); Class<?> type = Class.forName(className);
Object instance = context.getComponent(type.asSubclass(Object.class)); Object instance = context.requiredService(type);
if (!(instance instanceof Converter created)) { if (!(instance instanceof Converter created)) {
throw new IllegalArgumentException("Not a converter: " + className); throw new IllegalArgumentException("Not a converter: " + className);
} }
@@ -279,23 +309,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 +342,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 +352,13 @@ final class DirectBindingApplier {
} finally { } finally {
link.applying = false; link.applying = false;
} }
owner.clearBindingFailure(source); if (owner != null) {
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 +448,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 +473,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 +487,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 +519,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 +535,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 +549,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 +572,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) {
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,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;
}
}
@@ -3,9 +3,7 @@ package de.neitzel.fx.view;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Deque; import java.util.Deque;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
/** /**
* Holds the binding lists instantiated while one View is loading. * Holds the binding lists instantiated while one View is loading.
@@ -18,7 +16,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<>();
@@ -27,10 +25,26 @@ final class LoadSession {
*/ */
private final List<BindingList> bindingLists = new ArrayList<>(); private final List<BindingList> bindingLists = new ArrayList<>();
/** private Throwable bindingFailure;
* Component classes already built during the outermost load.
*/ // JavaFX reports exceptions from a property listener to the thread's uncaught handler.
private final Set<Class<?>> built = new HashSet<>(); // 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.
@@ -38,19 +52,6 @@ final class LoadSession {
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 +85,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.
* *
@@ -104,23 +98,6 @@ final class LoadSession {
stack.peek().bindingLists.add(bindingList); stack.peek().bindingLists.add(bindingList);
} }
/**
* Records the first Component of {@code type} built during this load.
* <p>
* Nested documents share the outermost session, so a second Component of the same class
* anywhere in the load is not the first.
*
* @param type the Component class
* @return {@code true} when this is the first time that class is built during the load
*/
static boolean claimFirst(Class<?> type) {
Deque<LoadSession> stack = STACK.get();
if (stack == null || stack.isEmpty()) {
return true;
}
return stack.peekLast().built.add(type);
}
/** /**
* Returns the lists registered during this session, in document order. * Returns the lists registered during this session, in document order.
* *
@@ -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) {
@@ -1,12 +1,12 @@
package de.neitzel.fx.view; package de.neitzel.fx.view;
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;
/** /**
@@ -23,10 +23,10 @@ final class RepeatApplier {
/** /**
* Fills the named pane with one new Component for each element, in list order. * Fills the named pane with one new Component for each element, in list order.
* <p> * <p>
* Each Component is a new injected instance. The cached singleton of that class is left * The adapter creates a fresh Component for each occurrence. Its model property is the
* in place. The child's model property is the element. Adding or removing an element * element. Adding an element loads a child. Removing one releases that child's View.
* adds or removes the matching child. The list is the one the entity holds, so a change * The list is the one the entity holds, so a change on either side is visible in the pane.
* on either side is visible in the pane. * The parent's View lifetime also owns the remaining children.
* *
* @param namespace objects addressed by {@code fx:id} * @param namespace objects addressed by {@code fx:id}
* @param viewModel the ViewModel for this View, or a replacement that exposes the collection by name * @param viewModel the ViewModel for this View, or a replacement that exposes the collection by name
@@ -34,7 +34,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) { ViewInstances 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 +44,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 +81,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, ViewInstances 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,12 +112,21 @@ 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, ViewInstances 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.
* *
@@ -25,6 +25,10 @@ final class ResultColumnSeparators extends Group {
return decoration; return decoration;
} }
boolean matchesColumnCount(int columns) {
return getChildren().size() == Math.max(0, columns - 1);
}
void position(double[] widths) { void position(double[] widths) {
double x = 0; double x = 0;
for (int i = 0; i < getChildren().size(); i++) { for (int i = 0; i < getChildren().size(); i++) {
@@ -343,13 +343,10 @@ final class ResultHeaderGestures implements AutoCloseable {
headerViewport = pane; headerViewport = pane;
break; break;
} }
if (scroll == null if (scroll == null || headerViewport == null || Double.isNaN(pointerX))
|| headerViewport == null return;
|| Double.isNaN(pointerX) var bounds = headerViewport.localToScene(headerViewport.getBoundsInLocal());
|| !headerViewport if (!bounds.contains(pointerX, pointerY)) return;
.localToScene(headerViewport.getBoundsInLocal())
.contains(pointerX, pointerY)) return;
var bounds = scroll.localToScene(scroll.getViewportBounds());
double delta = double delta =
pointerX < bounds.getMinX() + 30 pointerX < bounds.getMinX() + 30
? -.012 ? -.012
@@ -2,6 +2,8 @@ package de.neitzel.fx.view;
import javafx.beans.binding.Bindings; import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleBinding; import javafx.beans.binding.DoubleBinding;
import javafx.beans.binding.ObjectBinding;
import javafx.geometry.Insets;
import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox; import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
@@ -9,29 +11,43 @@ import javafx.scene.layout.VBox;
/** Makes equal normalized scroll values represent equal pixel offsets in queried results. */ /** Makes equal normalized scroll values represent equal pixel offsets in queried results. */
final class ResultScrollAlignment implements AutoCloseable { final class ResultScrollAlignment implements AutoCloseable {
private final HBox header; private final HBox header;
private final VBox body;
private final double originalMinimum; private final double originalMinimum;
private final Insets originalPadding;
private final ObjectBinding<Insets> bodyPadding;
private final DoubleBinding minimum; private final DoubleBinding minimum;
private final DoubleBinding viewportDifference;
ResultScrollAlignment(HBox header, VBox body, ScrollPane headerScroll, ScrollPane bodyScroll) { ResultScrollAlignment(
HBox header, VBox body, ScrollPane headerScroll, ScrollPane bodyScroll,
boolean hasHeaderAccessory) {
this.header = header; this.header = header;
this.body = body;
originalMinimum = header.getMinWidth(); 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 // A vertical body scrollbar narrows its viewport. Trailing row actions can also
// make its content wider than the column headings. Reserve blank header space // make its content wider than the column headings. Reserve blank header space
// so both scrollable extents match; the existing two-way hvalue binding then // so both scrollable extents match; the existing two-way hvalue binding then
// moves every mapped field and heading by the same number of pixels. // moves every mapped field and heading by the same number of pixels.
minimum = minimum =
Bindings.createDoubleBinding( Bindings.createDoubleBinding(
() -> () -> body.getLayoutBounds().getWidth()
body.getLayoutBounds().getWidth() + (hasHeaderAccessory
+ Math.max( ? viewportDifference.get()
0, : Math.max(0, viewportDifference.get())),
headerScroll.getViewportBounds().getWidth() body.layoutBoundsProperty(), viewportDifference);
- bodyScroll
.getViewportBounds()
.getWidth()),
body.layoutBoundsProperty(),
headerScroll.viewportBoundsProperty(),
bodyScroll.viewportBoundsProperty());
header.minWidthProperty().bind(minimum); header.minWidthProperty().bind(minimum);
} }
@@ -40,5 +56,11 @@ final class ResultScrollAlignment implements AutoCloseable {
header.minWidthProperty().unbind(); header.minWidthProperty().unbind();
header.setMinWidth(originalMinimum); header.setMinWidth(originalMinimum);
minimum.dispose(); minimum.dispose();
if (bodyPadding != null) {
body.paddingProperty().unbind();
body.setPadding(originalPadding);
bodyPadding.dispose();
}
viewportDifference.dispose();
} }
} }
+62 -25
View File
@@ -1,6 +1,5 @@
package de.neitzel.fx.view; package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import java.beans.PropertyDescriptor; import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@@ -25,6 +24,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;
@@ -156,6 +156,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.
@@ -229,7 +231,7 @@ public class Table extends VBox {
/** /**
* The container that creates Rows. * The container that creates Rows.
*/ */
private ApplicationContext context; private ViewInstances context;
/** /**
* The Row class. * The Row class.
@@ -246,13 +248,26 @@ 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, headerScroll, scroll); 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. // DataGrid grows this Table; let its viewport consume that height as well.
VBox.setVgrow(scroll, Priority.ALWAYS); VBox.setVgrow(scroll, Priority.ALWAYS);
resultMode = true; resultMode = true;
@@ -347,8 +362,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, ViewInstances context, ViewLifetime lifetime) {
walk(root, viewModel, context); walk(root, root, viewModel, context, lifetime);
} }
/** /**
@@ -357,7 +372,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, ViewInstances context, ViewLifetime owner) {
if (resultMode) { if (resultMode) {
return; return;
} }
@@ -366,6 +381,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");
} }
@@ -380,7 +404,7 @@ public class Table extends VBox {
} }
buildHeader(); buildHeader();
ensureWidths(); ensureWidths();
elements.addListener((ListChangeListener<Object>) this::onCollectionChange); lifetime.listen(elements, this::onCollectionChange);
refresh(); refresh();
} }
@@ -1169,6 +1193,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);
} }
@@ -1297,18 +1323,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 {
if (!(component instanceof Node node)) { Object component = Components.fresh(rowType, context, rowLifetime);
throw new IllegalArgumentException("Row is not a node: " + rowType.getName()); Components.setModel(component, element, rowLifetime);
} if (!(component instanceof Node node)) {
node.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> { throw new IllegalArgumentException("Row is not a node: " + rowType.getName());
if (event.getButton() == MouseButton.PRIMARY) {
selection.set(element);
} }
}); EventHandler<MouseEvent> select = event -> {
watchEdits(node); if (event.getButton() == MouseButton.PRIMARY) {
return node; selection.set(element);
}
};
node.addEventFilter(MouseEvent.MOUSE_CLICKED, select);
rowLifetime.own(() -> node.removeEventFilter(MouseEvent.MOUSE_CLICKED, select));
watchEdits(node, rowLifetime);
rowLifetimes.put(element, rowLifetime);
return node;
} catch (RuntimeException | Error failure) {
rowLifetime.rollback(failure);
throw failure;
}
} }
/** /**
@@ -1316,13 +1351,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);
} }
} }
} }
@@ -1530,18 +1565,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, ViewInstances 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);
} }
} }
@@ -8,8 +8,10 @@ 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.KeyEvent;
@@ -20,6 +22,7 @@ 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;
/** /**
@@ -31,11 +34,15 @@ 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<K> selectedKeys = FXCollections.observableArrayList();
@@ -56,6 +63,8 @@ public final class TableResults<K, T> implements AutoCloseable {
private List<SortKey> sortKeys = List.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 List<GroupColumn<T>> groupColumns = List.of(); private List<GroupColumn<T>> groupColumns = List.of();
private List<String> grouping = List.of(); private List<String> grouping = List.of();
@@ -79,10 +88,12 @@ public final class TableResults<K, T> implements AutoCloseable {
List<ResultColumn> columns, List<ResultColumn> columns,
Function<T, ResultRow> factory, Function<T, ResultRow> factory,
javafx.scene.control.ScrollPane headerScroll, javafx.scene.control.ScrollPane headerScroll,
javafx.scene.control.ScrollPane bodyScroll) { 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); gestures = new ResultHeaderGestures(this, header, body);
if (columns.isEmpty()) if (columns.isEmpty())
@@ -94,7 +105,8 @@ 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); scrollAlignment = new ResultScrollAlignment(
header, body, headerScroll, bodyScroll, headerAccessory != null);
drawHeader(); drawHeader();
body.setOnMouseClicked(e -> { body.setOnMouseClicked(e -> {
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null); if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
@@ -105,7 +117,7 @@ public final class TableResults<K, T> implements AutoCloseable {
checkOpen(); checkOpen();
columnSeparators = true; columnSeparators = true;
drawHeader(); drawHeader();
entries.forEach(e -> layoutRow(e.view())); applyWidths(widths);
} }
public ReadOnlyObjectProperty<K> selectedKeyProperty() { public ReadOnlyObjectProperty<K> selectedKeyProperty() {
@@ -121,6 +133,10 @@ public final class TableResults<K, T> implements AutoCloseable {
/** Only selected models currently visible and interactive are actionable. */ /** Only selected models currently visible and interactive are actionable. */
public ReadOnlyListProperty<T> selectedElementsProperty() { return elementsView.getReadOnlyProperty(); } public ReadOnlyListProperty<T> selectedElementsProperty() { return elementsView.getReadOnlyProperty(); }
ReadOnlyObjectProperty<GridSelection<K, T>> selectionProperty() {
return selection.getReadOnlyProperty();
}
public RowSelectionMode getSelectionMode() { return selectionMode; } public RowSelectionMode getSelectionMode() { return selectionMode; }
public void setSelectionMode(RowSelectionMode mode) { public void setSelectionMode(RowSelectionMode mode) {
@@ -143,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();
@@ -157,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) {
@@ -196,8 +238,12 @@ public final class TableResults<K, T> implements AutoCloseable {
} }
} }
String columnHeader(String id) {
return definitions.get(id).header();
}
private String headerText(String id) { private String headerText(String id) {
return definitions.get(id).header() return columnHeader(id)
+ sortKeys.stream() + sortKeys.stream()
.filter(k -> k.columnId().equals(id)) .filter(k -> k.columnId().equals(id))
.map(k -> k.direction() == SortKey.Direction.ASCENDING ? " ↑" : " ↓") .map(k -> k.direction() == SortKey.Direction.ASCENDING ? " ↑" : " ↓")
@@ -337,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)
@@ -365,7 +412,7 @@ public final class TableResults<K, T> implements AutoCloseable {
next.add(new Entry<>(row, view, click, key)); 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().setFocusTraversable(true);
view.root().addEventHandler(KeyEvent.KEY_PRESSED, key); view.root().addEventHandler(KeyEvent.KEY_PRESSED, key);
@@ -379,7 +426,7 @@ 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);
captured = nextCaptured; captured = nextCaptured;
groupTree = nextTree; groupTree = nextTree;
grouping = nextGrouping.columns(); grouping = nextGrouping.columns();
@@ -396,8 +443,7 @@ 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);
resizeGroupHeadings();
layoutCommitted.run(); layoutCommitted.run();
} }
@@ -455,7 +501,15 @@ 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) {
@@ -501,6 +555,14 @@ public final class TableResults<K, T> implements AutoCloseable {
if (columnSeparators && !id.equals(ordering.getLast())) if (columnSeparators && !id.equals(ordering.getLast()))
cell.getChildren().add(ResultColumnSeparators.forHeader(cell)); cell.getChildren().add(ResultColumnSeparators.forHeader(cell));
gestures.header(cell, label, handle, id, () -> sortRequest.accept(id)); 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);
} }
@@ -513,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());
@@ -532,7 +590,7 @@ public final class TableResults<K, T> implements AutoCloseable {
else if (!fields.contains(child)) children.add(child); else if (!fields.contains(child)) children.add(child);
} }
if (columnSeparators) { if (columnSeparators) {
if (separators == null) if (separators == null || !separators.matchesColumnCount(ordering.size()))
separators = new ResultColumnSeparators(view.root(), ordering.size()); separators = new ResultColumnSeparators(view.root(), ordering.size());
separators.position(ordering.stream().mapToDouble(id -> width(id, sizes)).toArray()); separators.position(ordering.stream().mapToDouble(id -> width(id, sizes)).toArray());
children.add(separators); children.add(separators);
@@ -543,7 +601,10 @@ public final class TableResults<K, T> implements AutoCloseable {
view.root().getScene() == null ? null : view.root().getScene().getFocusOwner(); view.root().getScene() == null ? null : view.root().getScene().getFocusOwner();
boolean restore = focus != null && descendant(view.root(), focus); boolean restore = focus != null && descendant(view.root(), focus);
view.root().getChildren().setAll(children); view.root().getChildren().setAll(children);
if (restore) focus.requestFocus(); if (restore) {
if (descendant(view.root(), focus)) focus.requestFocus();
else view.root().requestFocus();
}
} }
} }
@@ -568,6 +629,10 @@ public final class TableResults<K, T> implements AutoCloseable {
} }
selectedElement.set(rowsInteractive ? loaded : null); selectedElement.set(rowsInteractive ? loaded : null);
selectedElements.setAll(actionable); 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) { public void setOnLayoutCommitted(Runnable handler) {
@@ -762,6 +827,7 @@ public final class TableResults<K, T> implements AutoCloseable {
.getChildren() .getChildren()
.getFirst() .getFirst()
.requestFocus(); .requestFocus();
else if (headerAccessory != null) headerAccessory.requestFocus();
} }
} }
resizeGroupHeadings(); resizeGroupHeadings();
@@ -862,8 +928,13 @@ public final class TableResults<K, T> implements AutoCloseable {
} }
private void resizeGroupHeadings() { private void resizeGroupHeadings() {
double total = order.stream().mapToDouble(this::width).sum(); resizeGroupHeadings(visibleOrder(order), widths);
disclosure.values().forEach(button -> size(button, total)); }
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) { void previewWidth(String id, ColumnWidth value) {
@@ -875,9 +946,9 @@ public final class TableResults<K, T> implements AutoCloseable {
private void applyWidths(Map<String, ColumnWidth> sizes) { private void applyWidths(Map<String, ColumnWidth> sizes) {
for (Node node : header.getChildren()) for (Node node : header.getChildren())
size((Region) node, width((String) node.getUserData(), sizes)); size((Region) node, width((String) node.getUserData(), sizes));
entries.forEach(e -> layoutRow(e.view(), order, sizes)); var visible = visibleOrder(order);
double total = order.stream().mapToDouble(id -> width(id, sizes)).sum(); entries.forEach(e -> layoutRow(e.view(), visible, sizes));
disclosure.values().forEach(button -> size(button, total)); resizeGroupHeadings(visible, sizes);
} }
private void release(List<Entry<K, T>> retired) { private void release(List<Entry<K, T>> retired) {
@@ -913,12 +984,13 @@ 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(); selectedKeys.clear();
selectedElements.clear(); selectedElements.clear();
selection.set(GridSelection.empty());
anchor = null; anchor = null;
captured = GroupProjection.capture(List.of(), List.of()); captured = GroupProjection.capture(List.of(), List.of());
groupTree = List.of(); groupTree = List.of();
@@ -0,0 +1,22 @@
package de.neitzel.fx.view;
import java.util.Optional;
/** Supplies a View's objects from the application's dependency injection configuration. */
public interface ViewDependencies {
/** Checks whether the exact FXML type is a Component, without creating an instance. */
boolean isComponent(Class<?> type);
/**
* Looks up an application-owned service such as a Converter or Localizer.
* Report lookup and creation failures as exceptions. An empty result means the service is absent.
*/
<T> Optional<T> findService(Class<T> type);
/**
* Creates a fresh Controller or Component and supplies its release action.
* The adapter owns any partial allocations until it returns the object.
*/
<T> ViewObject<T> createViewObject(Class<T> type);
}
@@ -0,0 +1,66 @@
package de.neitzel.fx.view;
import de.neitzel.fx.i18n.Localizer;
import java.util.Objects;
import java.util.Optional;
/** Instance selection shared by the FXML factories and the binding appliers. */
record ViewInstances(ViewDependencies dependencies) {
ViewInstances {
Objects.requireNonNull(dependencies, "View dependencies");
}
Object controller(Class<?> type, ViewLifetime lifetime) {
return create(type, lifetime);
}
boolean isComponent(Class<?> type) {
return dependencies.isComponent(type);
}
Object component(Class<?> type, ViewLifetime lifetime) {
if (!dependencies.isComponent(type)) {
throw new IllegalArgumentException("No Component registered for " + type.getName());
}
return createComponent(type, lifetime);
}
Object createComponent(Class<?> type, ViewLifetime lifetime) {
Object instance = create(type, lifetime);
if (instance.getClass() != type) {
throw new IllegalArgumentException("Expected exact Component type " + type.getName()
+ ", got " + instance.getClass().getName());
}
return instance;
}
private Object create(Class<?> type, ViewLifetime lifetime) {
try {
ViewObject<?> view = dependencies.createViewObject(type);
// Each instance owns a distinct cleanup entry even if actions are shared.
lifetime.own(() -> view.release().run());
return type.cast(view.instance());
} catch (RuntimeException failure) {
throw new IllegalStateException("Could not create View object " + type.getName(), failure);
}
}
Object requiredService(Class<?> type) {
return service(type)
.orElseThrow(() -> new IllegalArgumentException("No View service for " + type.getName()));
}
Localizer localizer() {
return service(Localizer.class).orElse(null);
}
private <T> Optional<T> service(Class<T> type) {
try {
return dependencies.findService(type);
} catch (RuntimeException failure) {
throw new IllegalStateException("Could not resolve View service " + type.getName(), failure);
}
}
}
@@ -0,0 +1,79 @@
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;
}
void own(Runnable removal) {
if (closed) {
removal.run();
} else {
cleanup.addLast(removal);
}
}
<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);
}
}
}
@@ -2,12 +2,12 @@ package de.neitzel.fx.view;
import de.neitzel.fx.i18n.Localizer; import de.neitzel.fx.i18n.Localizer;
import de.neitzel.fx.i18n.Messages; import de.neitzel.fx.i18n.Messages;
import de.neitzel.injection.ApplicationContext;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
import javafx.scene.Parent; import javafx.scene.Parent;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.Objects;
/** /**
* Loads a View for one Model instance. * Loads a View for one Model instance.
@@ -21,70 +21,61 @@ public final class ViewLoader {
} }
/** /**
* Loads a View for one Model instance. * Loads FXML with application-supplied dependencies and a managed Model context.
* <p> * Load and close the View on the JavaFX application thread. The caller owns the dependencies.
* Reuses the ViewModel already built for {@code model}, or builds one, then loads {@code fxml} * @param fxml the FXML document
* and applies binding elements declared in {@code fx:define}. A Computed binding writes a * @param model the Model instance
* Controller method result to a control and does not write the Model. Direction {@code both} * @param dependencies the adapter for View objects and services
* keeps the control and the Attribute * @param models the Model context that owns the View
* aligned, so editing the control writes the Attribute immediately. Direction {@code view}
* shows the Attribute and follows later property changes without writing the Attribute back.
* Direction {@code model} shows the current value, writes the Attribute when the control
* changes, and does not push later property changes to the control. A Path of one name is an
* Attribute of this View's ViewModel. Further names step into a nested ViewModel, and the
* direction applies to the last name. When a Complex attribute along the Path is null, the
* control and the Model keep their current values. A collection of simple values is one shared
* list: the Direct binding sets the control property to that
* {@link javafx.collections.ObservableList}, so an add or remove is visible on both sides.
* A path that is not a read-write Attribute fails the load. The context creates a Controller
* the document names, and injects that Controller's services. When the document names no
* Controller, the library supplies one. A Controller that implements {@link HasViewModel}
* receives the ViewModel after construction and before bindings. {@link ViewModelClass} on that
* Controller names the ViewModel class. The library constructs it with the Model instance
* before load. With no annotation, the library builds the generic ViewModel. The first View of a
* Model instance fixes that class. A later View that names a different class fails the load,
* and the earlier View stays as it was. A later View that names none reuses the ViewModel.
* The context creates a
* Converter when a Direct binding names one. A converter that cannot produce a value
* keeps the previous value and records one error Message on the ViewModel that owns the last
* Attribute, with that Attribute's name as the source. A parent carries a copy with the source
* extended. It does not fail the load.
* A parent document names a Component class as an element. The context creates that Component
* and injects its services. A second element of the same class is another injected instance,
* and the cached singleton stays the first one. The Component document {@code ClassName.fxml},
* in the same package, is loaded with the Component as {@code fx:root} and as the Controller.
* That document's bindings are not applied during this load. They run when the Component's
* model property becomes a non-null Model. {@link ViewModelClass} on the Component names the
* ViewModel class for that Model. A Component that implements {@link HasViewModel} receives
* that ViewModel after the property is set and before those bindings run.
* A {@link Repeat} in the same list names a pane, a Component class, and a collection
* Attribute. One new Component child is placed in that pane for each Model instance, in list
* order. Adding or removing an element updates that pane. Those instances are created with
* {@link de.neitzel.injection.ApplicationContext#createComponent} so the cached singleton of
* that class stays in place. A collection of Model instances is an
* {@link javafx.collections.ObservableList} of those instances, shared with the entity.
* Selection is a separate Attribute of the parent Model. Null means nothing is selected.
* A Direct binding can tie a control property to that Attribute. The repeated Component does
* not store the selection.
* Loading does not open a popup or fill a status bar. A Direct binding whose path is
* {@code latestMessage} shows the latest Message text. {@link MessagePopup#showNewMessages}
* shows each newly added Message in a dialog.
*
* @param fxml the FXML document
* @param model the Model instance
* @param context the application context
* @return the loaded View * @return the loaded View
* @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 loadWithDependencies(URL fxml, Object model,
Class<?> controllerType = FxmlControllers.controllerClass(fxml); ViewDependencies dependencies, ViewModelContext models) {
Class<?> viewModelClass = ViewModels.namedOn(controllerType); return load(fxml, model, new ViewInstances(dependencies), models.openView());
Object viewModel = ViewModels.of(model, viewModelClass); }
LoadSession session = LoadSession.open();
/**
* Loads a managed Component from its sibling ClassName.fxml on the JavaFX application thread.
* @param type the registered Component class
* @param model the initial non-null Model
* @param dependencies the adapter for View objects and services
* @param models the Model context that owns the View
* @return the initialized Component and its effective ViewModel
*/
public static LoadedView loadComponentWithDependencies(Class<? extends Parent> type, Object model,
ViewDependencies dependencies, ViewModelContext models) {
return loadComponent(type, model, new ViewInstances(dependencies), models);
}
private static LoadedView loadComponent(Class<? extends Parent> type, Object model,
ViewInstances context, ViewModelContext models) {
Objects.requireNonNull(model, "Component Model");
ViewLifetime lifetime = models.openView();
try { try {
Parent root = type.cast(Components.fresh(type, context, lifetime));
Components.setModel(root, model, lifetime);
Object viewModel = ViewModels.of(models, model, ViewModels.namedOn(type));
return new LoadedView(root, viewModel, lifetime);
} catch (RuntimeException | Error failure) {
lifetime.rollback(failure);
if (failure instanceof RuntimeException) {
throw new IllegalStateException("Could not load Component " + type.getName() + " from "
+ type.getSimpleName() + ".fxml: " + failure.getMessage(), failure);
}
throw failure;
}
}
private static LoadedView load(URL fxml, Object model, ViewInstances 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)); FXMLLoader loader = new FXMLLoader(fxml, resources(context, fxml, controllerType));
loader.setControllerFactory(type -> controller(context, type)); FxmlHandlers.observe(loader, lifetime);
loader.setBuilderFactory(type -> Components.builder(type, context)); loader.setControllerFactory(type -> context.controller(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");
@@ -96,36 +87,29 @@ 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);
if (failure instanceof RuntimeException) {
throw new IllegalStateException("Could not load view " + fxml + ": " + failure.getMessage(), failure);
}
throw failure;
} finally { } finally {
LoadSession.close(); LoadSession.unnest();
} }
} }
static Messages resources(ApplicationContext context, URL fxml, Class<?> type) { static Messages resources(ViewInstances context, URL fxml, Class<?> type) {
Localizer languages; Localizer languages = context.localizer();
try { return languages == null ? null : languages.forView(fxml, type);
languages = context.getComponent(Localizer.class);
} catch (IllegalArgumentException unregistered) {
return null;
}
return languages.forView(fxml, type);
}
/**
* Asks the container for the Controller class named by the document.
*
* @param context the container
* @param type the Controller class
* @return the Controller
*/
private static Object controller(ApplicationContext context, Class<?> type) {
return context.getComponent(type.asSubclass(Object.class));
} }
} }
@@ -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();
} }
@@ -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,15 @@
package de.neitzel.fx.view;
import java.util.Objects;
/**
* An instance and the action its View invokes once on release. Use an empty action when the
* instance has no cleanup. The action is responsible for any container-specific destruction.
*/
public record ViewObject<T>(T instance, Runnable release) {
public ViewObject {
Objects.requireNonNull(instance, "View object");
Objects.requireNonNull(release, "View object release action");
}
}
@@ -2,6 +2,9 @@
.grouping-chip { -fx-padding: 4 8; -fx-alignment: center-left; -fx-background-color: #e8eff7; -fx-border-color: #8a9eb5; -fx-cursor: open-hand; } .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-cell { -fx-alignment: center-left; -fx-min-height: 32; }
.data-grid .column-header { -fx-padding: 5 6; } .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; } .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 { -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; } .group-heading:focused { -fx-border-color: #3776b6; -fx-border-width: 2; }
@@ -62,6 +62,39 @@ class HtmlViewerTest {
return (javafx.scene.control.Button) viewer.lookup(".html-viewer-media-load"); 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 { @Test void ordinaryFxmlConstructsAnIdleLocalizableControl() throws Exception {
fx(() -> { fx(() -> {
var loader = new javafx.fxml.FXMLLoader(); var loader = new javafx.fxml.FXMLLoader();
@@ -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());
assertSame(editor, main.getScene().getFocusOwner());
assertInstanceOf(ActionResult.NoChange.class, manager.activate(dockable.getId()));
doReturn(false).when(main).isFocused();
clearInvocations(main);
assertInstanceOf(ActionResult.Applied.class, manager.activate(dockable.getId()));
verify(main).requestFocus();
}); });
Fixture fixture = state.get();
try {
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 {
CountDownLatch focused = new CountDownLatch(1);
ChangeListener<Boolean> listener = (observable, old, current) -> {
if (current) focused.countDown();
};
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) { }
} }
@@ -0,0 +1,287 @@
package de.neitzel.fx.view;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static de.neitzel.fx.view.AsyncCommand.Phase.*;
import static org.junit.jupiter.api.Assertions.*;
class AsyncCommandTest {
@BeforeAll
static void start() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void publishesRunningBeforeSchedulingAndReportsProgressAndOneResult() throws Exception {
var available = new SimpleBooleanProperty(false);
var queue = new QueueExecutor();
var command = new AtomicReference<AsyncCommand<String>>();
var states = new ArrayList<AsyncCommand.State<String>>();
var calls = new AtomicInteger();
FxThread.onFx(() -> {
var async = new AsyncCommand<>(available, action -> {
assertEquals(RUNNING, command.get().getState().phase());
queue.execute(action);
}, () -> new Task<String>() {
@Override
protected String call() {
calls.incrementAndGet();
updateMessage("Saving");
updateProgress(1, 2);
return "saved";
}
});
command.set(async);
async.stateProperty().addListener((source, previous, next) -> {
assertTrue(Platform.isFxApplicationThread());
states.add(next);
});
async.getCommand().execute();
assertEquals(IDLE, async.getState().phase());
available.set(true);
async.getCommand().execute();
async.getCommand().execute();
assertFalse(async.cancel());
assertFalse(async.getCommand().getCanExecute().get());
assertEquals(1, queue.size());
});
runWorker(queue.remove());
FxThread.onFx(() -> {
var async = command.get();
assertEquals(1, calls.get());
assertTrue(states.stream().anyMatch(state -> state.running() && state.message().equals("Saving")));
assertEquals(1, states.stream().filter(state -> state.phase() == SUCCEEDED).count());
assertEquals(new AsyncCommand.State<>(SUCCEEDED, "saved", null, 0.5, "Saving"), async.getState());
assertTrue(async.getCommand().getCanExecute().get());
async.close();
});
}
@Test
void reportsSynchronousAndWorkerFailuresAndAllowsRetry() throws Exception {
var queue = new QueueExecutor();
var command = new AtomicReference<AsyncCommand<String>>();
var starts = new AtomicInteger();
var failures = new ArrayList<Throwable>();
var factoryFailure = new IllegalArgumentException("factory");
var schedulingFailure = new RejectedExecutionException("executor");
var operationFailure = new IllegalStateException("worker");
FxThread.onFx(() -> {
var async = new AsyncCommand<>(new SimpleBooleanProperty(true), work -> {
if (starts.get() == 2) throw schedulingFailure;
queue.execute(work);
}, () -> switch (starts.incrementAndGet()) {
case 1 -> throw factoryFailure;
case 2 -> task(() -> "not scheduled");
case 3 -> task(() -> { throw operationFailure; });
default -> task(() -> "retry");
});
command.set(async);
async.stateProperty().addListener((source, previous, next) -> {
if (next.phase() == FAILED) failures.add(next.error());
});
async.getCommand().execute();
assertSame(factoryFailure, async.getState().error());
async.getCommand().execute();
assertSame(schedulingFailure, async.getState().error());
async.getCommand().execute();
});
runWorker(queue.remove());
FxThread.onFx(() -> {
assertEquals(List.of(factoryFailure, schedulingFailure, operationFailure), failures);
assertSame(operationFailure, command.get().getState().error());
command.get().getCommand().execute();
});
runWorker(queue.remove());
FxThread.onFx(() -> {
assertEquals("retry", command.get().getState().result());
command.get().close();
});
}
@Test
void cancellationKeepsSlotUntilTheWorkerLeavesAndPublishesOneCompletion() throws Exception {
var queue = new QueueExecutor();
var command = new AtomicReference<AsyncCommand<String>>();
var entered = new CountDownLatch(1);
var interrupted = new CountDownLatch(1);
var release = new CountDownLatch(1);
var cancellations = new AtomicInteger();
FxThread.onFx(() -> {
var async = new AsyncCommand<>(new SimpleBooleanProperty(true), queue, () -> task(() -> {
entered.countDown();
try {
new CountDownLatch(1).await();
} catch (InterruptedException cancellation) {
interrupted.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS), "waiting to clean up after interrupt");
}
return "ignored";
}), true);
command.set(async);
async.stateProperty().addListener((source, previous, next) -> {
if (next.phase() == CANCELLED) cancellations.incrementAndGet();
});
async.getCommand().execute();
});
var worker = Thread.ofVirtual().start(queue.remove());
try {
assertTrue(entered.await(5, TimeUnit.SECONDS));
FxThread.onFx(() -> assertTrue(command.get().cancel()));
assertTrue(interrupted.await(5, TimeUnit.SECONDS));
FxThread.onFx(() -> {
var async = command.get();
assertTrue(async.getState().running());
async.getCommand().execute();
assertEquals(0, queue.size());
});
} finally {
release.countDown();
worker.join(5000);
}
FxThread.onFx(() -> {
var async = command.get();
assertEquals(CANCELLED, async.getState().phase());
assertEquals(1, cancellations.get());
assertTrue(async.getCommand().getCanExecute().get());
async.close();
});
}
@Test
void oldCancellationCannotOverwriteANewerRunAndCloseDoesNotStopItsWorker() throws Exception {
var queue = new QueueExecutor();
var command = new AtomicReference<AsyncCommand<String>>();
var calls = new AtomicInteger();
var phases = new ArrayList<AsyncCommand.Phase>();
FxThread.onFx(() -> {
var async = new AsyncCommand<>(new SimpleBooleanProperty(true), queue,
() -> task(() -> "run " + calls.incrementAndGet()), true);
command.set(async);
async.stateProperty().addListener((source, previous, next) -> phases.add(next.phase()));
async.getCommand().execute();
assertTrue(async.cancel());
assertEquals(CANCELLED, async.getState().phase());
async.getCommand().execute();
});
runWorker(queue.remove());
FxThread.onFx(() -> {
var async = command.get();
assertEquals(RUNNING, async.getState().phase());
assertEquals(0, calls.get());
async.close();
async.close();
async.getCommand().execute();
assertFalse(async.cancel());
assertFalse(async.getCommand().getCanExecute().get());
});
runWorker(queue.remove());
FxThread.onFx(() -> {
assertEquals(1, calls.get());
assertEquals(List.of(RUNNING, CANCELLED, RUNNING, CLOSED), phases);
assertEquals(CLOSED, command.get().getState().phase());
});
}
@Test
void aGeneratedDialogButtonClosesOnlyAfterASuccessfulTask() throws Exception {
var queue = new QueueExecutor();
var dialogRef = new AtomicReference<Dialog<Boolean>>();
var saveButtonRef = new AtomicReference<Button>();
FxThread.onFx(() -> {
var dialog = new Dialog<Boolean>();
dialogRef.set(dialog);
var save = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().setAll(save, ButtonType.CANCEL);
dialog.setResultConverter(button -> false);
var async = new AsyncCommand<>(new SimpleBooleanProperty(true), queue, () -> task(() -> "saved"));
var button = (Button) dialog.getDialogPane().lookupButton(save);
saveButtonRef.set(button);
button.disableProperty().bind(Bindings.not(async.getCommand().getCanExecute()));
button.addEventFilter(ActionEvent.ACTION, event -> {
event.consume();
async.getCommand().execute();
});
dialog.setOnCloseRequest(event -> {
if (async.getState().running()) event.consume();
});
async.stateProperty().addListener((source, previous, state) -> {
if (state.phase() == SUCCEEDED) {
dialog.setResult(true);
dialog.close();
}
});
dialog.setOnHidden(event -> async.close());
dialog.show();
button.fire();
assertTrue(dialog.isShowing());
assertTrue(button.isDisable());
assertTrue(async.getState().running());
});
runWorker(queue.remove());
FxThread.onFx(() -> {
assertFalse(dialogRef.get().isShowing());
assertEquals(Boolean.TRUE, dialogRef.get().getResult());
assertTrue(saveButtonRef.get().isDisable());
});
}
private static Task<String> task(Callable<String> work) {
return new Task<>() {
@Override
protected String call() throws Exception {
return work.call();
}
};
}
private static void runWorker(Runnable job) throws InterruptedException {
var worker = Thread.ofVirtual().start(job);
worker.join(5000);
assertFalse(worker.isAlive());
}
private static final class QueueExecutor implements Executor {
private final ArrayDeque<Runnable> work = new ArrayDeque<>();
@Override
public void execute(Runnable action) {
work.addLast(action);
}
int size() {
return work.size();
}
Runnable remove() {
return work.removeFirst();
}
}
}
@@ -0,0 +1,110 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.command.CommandController;
import java.nio.file.Files;
import java.nio.file.Path;
import javafx.scene.control.Button;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BindCommandTest {
@TempDir
Path directory;
@BeforeAll
static void start() throws InterruptedException {
FxThread.start();
}
@Test
void connectsOneCommandToButtonMenuAndKeyboardUntilClosed() throws Exception {
var url = view("commands.fxml", """
<CommandBinding control="button" path="clear"/>
<CommandBinding control="item" path="clear"/>
""");
FxThread.onFx(() -> {
try (var models = new ViewModelContext()) {
var view = ViewLoader.loadWithDependencies(url, new CommandController.Subject(), services(), models);
var model = (CommandController.Model) view.getViewModel();
var button = (Button) view.getRoot().lookup("#button");
var menu = ((MenuBar) view.getRoot().lookup("#menu")).getMenus().getFirst();
var item = menu.getItems().getFirst();
var dynamic = new MenuItem();
try (var registration = CommandBindings.bind(dynamic, model.getClear())) {
assertTrue(button.isDisable());
assertTrue(item.isDisable());
item.fire();
model.getClear().execute();
assertEquals(0, model.getCalls());
model.getEnabled().set(true);
assertFalse(button.isDisable());
assertFalse(item.isDisable());
button.fire();
item.fire();
model.getClear().execute();
dynamic.fire();
assertEquals(4, model.getCalls());
}
dynamic.fire();
assertEquals(4, model.getCalls());
view.close();
assertNull(button.getOnAction());
assertNull(item.getOnAction());
model.getEnabled().set(false);
assertFalse(button.isDisable());
assertFalse(item.isDisable());
}
});
}
@Test
void rejectsUnknownTargetsAndConflictingOwners() throws Exception {
var scenarios = new String[][] {
{"<CommandBinding control='unknown' path='clear'/>", "unknown"},
{"<CommandBinding control='button' path='unknown'/>", "unknown"},
{"<CommandBinding control='menu' path='clear'/>", "ButtonBase or MenuItem"},
{"<CommandBinding control='button' path='clear'/><CommandBinding control='button' path='clear'/>", "duplicate"},
{"<CommandBinding control='button' path='clear'/><ComputedBinding control='button' property='disable' method='#unused'/>", "disable"}
};
for (var scenario : scenarios) {
var url = view("invalid-command.fxml", scenario[0]);
FxThread.onFx(() -> {
try (var models = new ViewModelContext()) {
var failure = assertThrows(IllegalStateException.class,
() -> ViewLoader.loadWithDependencies(url, new CommandController.Subject(), services(), models));
assertTrue(failure.getMessage().contains("invalid-command.fxml"));
assertTrue(failure.getMessage().contains(scenario[1]));
}
});
}
}
private TestViews services() {
return new TestViews();
}
private java.net.URL view(String name, String bindings) throws Exception {
return Files.writeString(directory.resolve(name), """
<?import de.neitzel.fx.view.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.view.command.CommandController">
<fx:define><BindingList>%s</BindingList></fx:define>
<Button fx:id="button"/>
<MenuBar fx:id="menu"><menus><Menu><items><MenuItem fx:id="item"/></items></Menu></menus></MenuBar>
</VBox>
""".formatted(bindings)).toUri().toURL();
}
}
@@ -0,0 +1,91 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.fx.view.readable.ReadableSourcesController.Sources;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** DirectBinding reads declared observables toward the view. */
class BindReadOnlySourcesTest {
private static final URL DOCUMENT = BindReadOnlySourcesTest.class.getResource("readable-sources.fxml");
@BeforeAll
static void startJavaFx() throws InterruptedException {
FxThread.start();
}
@Test
void followsOnlyDependenciesOfTheViewModelSource() throws Exception {
FxThread.onFx(() -> {
LoadedView view = TestViews.load(DOCUMENT, new Person("Ada"), context());
Sources sources = (Sources) view.getViewModel();
Button commit = (Button) view.getRoot().lookup("#commit");
Label title = (Label) view.getRoot().lookup("#title");
Label caption = (Label) view.getRoot().lookup("#caption");
TextField unrelated = (TextField) view.getRoot().lookup("#unrelated");
assertTrue(commit.isDisable());
assertEquals("First", title.getText());
assertEquals("Caption: First", caption.getText());
assertNull(view.property("title"));
int evaluations = sources.getEvaluations();
unrelated.setText("A change outside the binding's dependencies");
assertEquals(evaluations, sources.getEvaluations());
sources.getChoices().add("A");
assertFalse(commit.isDisable());
sources.getChoices().clear();
assertTrue(commit.isDisable());
assertEquals(evaluations + 2, sources.getEvaluations());
title.setText("A local edit");
assertEquals("First", sources.titleProperty().get());
sources.setTitle("");
assertEquals("", title.getText());
assertEquals("Caption: First", caption.getText());
assertEquals("observableTitle", sources.getLatestMessage().getSource());
sources.setTitle("Second");
assertEquals("Second", title.getText());
assertEquals("Caption: Second", caption.getText());
assertNull(sources.getLatestMessage());
});
}
@ParameterizedTest
@ValueSource(strings = {"both", "model"})
void identifiesAnInvalidWriteBackWithItsDocumentAndEndpoints(String direction, @TempDir Path temporary)
throws Exception {
Path invalid = temporary.resolve("invalid-" + direction + ".fxml");
String fxml = Files.readString(Path.of(DOCUMENT.toURI()));
Files.writeString(invalid, fxml.replace("path=\"observableTitle\" direction=\"view\"",
"path=\"observableTitle\" direction=\"" + direction + "\""));
FxThread.onFx(() -> {
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> TestViews.load(invalid.toUri().toURL(), new Person("Ada"), context()));
assertTrue(failure.getMessage().contains("Read-only source"), failure.getMessage());
assertTrue(failure.getMessage().contains("observableTitle"), failure.getMessage());
assertTrue(failure.getMessage().contains("caption.text"), failure.getMessage());
assertTrue(failure.getMessage().contains(invalid.getFileName().toString()), failure.getMessage());
});
}
private static TestViews context() {
return new TestViews();
}
}
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Address; import de.neitzel.fx.view.fixture.Address;
import de.neitzel.fx.view.fixture.Household; import de.neitzel.fx.view.fixture.Household;
import de.neitzel.fx.view.fixture.Person; import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.beans.property.Property; import javafx.beans.property.Property;
import javafx.scene.control.TextField; import javafx.scene.control.TextField;
@@ -55,8 +54,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main")); person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("name-both-ways.fxml"); URL fxml = CarryChildMessageTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
ViewModel personModel = loaded.getViewModel(); ViewModel personModel = loaded.getViewModel();
ViewModel addressModel = (ViewModel) personModel.property("address").getValue(); ViewModel addressModel = (ViewModel) personModel.property("address").getValue();
addressModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street")); addressModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street"));
@@ -85,8 +84,8 @@ class CarryChildMessageTest {
household.setPerson(person); household.setPerson(person);
URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml"); URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, household, context); LoadedView loaded = TestViews.load(fxml, household, context);
ViewModel householdModel = loaded.getViewModel(); ViewModel householdModel = loaded.getViewModel();
ViewModel personModel = (ViewModel) householdModel.property("person").getValue(); ViewModel personModel = (ViewModel) householdModel.property("person").getValue();
ViewModel addressModel = (ViewModel) personModel.property("address").getValue(); ViewModel addressModel = (ViewModel) personModel.property("address").getValue();
@@ -112,8 +111,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main")); person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml"); URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
streetField.setText("nope"); streetField.setText("nope");
@@ -145,8 +144,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main")); person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml"); URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
streetField.setText("nope"); streetField.setText("nope");
streetField.setText("ok Oak"); streetField.setText("ok Oak");
@@ -173,8 +172,8 @@ class CarryChildMessageTest {
household.setPerson(person); household.setPerson(person);
URL fxml = CarryChildMessageTest.class.getResource("household-street-converted.fxml"); URL fxml = CarryChildMessageTest.class.getResource("household-street-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, household, context); LoadedView loaded = TestViews.load(fxml, household, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
streetField.setText("nope"); streetField.setText("nope");
@@ -217,8 +216,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main")); person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml"); URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
ViewModel personModel = loaded.getViewModel(); ViewModel personModel = loaded.getViewModel();
ViewModel addressModel = (ViewModel) personModel.property("address").getValue(); ViewModel addressModel = (ViewModel) personModel.property("address").getValue();
addressModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street")); addressModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street"));
@@ -235,7 +234,7 @@ class CarryChildMessageTest {
assertEquals("lane is closed", addressModel.getMessages().get(0).getText()); assertEquals("lane is closed", addressModel.getMessages().get(0).getText());
Address moved = new Address("Oak"); Address moved = new Address("Oak");
LoadedView movedView = ViewLoader.load(fxml, moved, context); LoadedView movedView = TestViews.load(fxml, moved, context);
movedView.getViewModel().addMessage(new Message(Message.Severity.WARN, "under repair", "street")); movedView.getViewModel().addMessage(new Message(Message.Severity.WARN, "under repair", "street"));
address.setValue(movedView.getViewModel()); address.setValue(movedView.getViewModel());
@@ -259,8 +258,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main")); person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml"); URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
ViewModel personModel = loaded.getViewModel(); ViewModel personModel = loaded.getViewModel();
personModel.addMessage(new Message(Message.Severity.INFO, "keep me", "form")); personModel.addMessage(new Message(Message.Severity.INFO, "keep me", "form"));
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
@@ -304,8 +303,8 @@ class CarryChildMessageTest {
household.setPerson(person); household.setPerson(person);
URL fxml = CarryChildMessageTest.class.getResource("household-street-converted.fxml"); URL fxml = CarryChildMessageTest.class.getResource("household-street-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, household, context); LoadedView loaded = TestViews.load(fxml, household, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
streetField.setText("nope"); streetField.setText("nope");
streetField.setText("ok Oak"); streetField.setText("ok Oak");
@@ -335,8 +334,8 @@ class CarryChildMessageTest {
person.setWork(shared); person.setWork(shared);
URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml"); URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
ViewModel personModel = loaded.getViewModel(); ViewModel personModel = loaded.getViewModel();
ViewModel homeModel = (ViewModel) personModel.property("home").getValue(); ViewModel homeModel = (ViewModel) personModel.property("home").getValue();
homeModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street")); homeModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street"));
@@ -2,7 +2,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Address; import de.neitzel.fx.view.fixture.Address;
import de.neitzel.fx.view.fixture.Person; import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.beans.property.Property; import javafx.beans.property.Property;
import javafx.scene.control.Label; import javafx.scene.control.Label;
@@ -51,8 +50,8 @@ class ChooseControllerAndViewModelTest {
Person person = new Person("Ada"); Person person = new Person("Ada");
URL fxml = ChooseControllerAndViewModelTest.class.getResource("handed-name.fxml"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("handed-name.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label handedLabel = (Label) loaded.getRoot().lookup("#handedLabel"); Label handedLabel = (Label) loaded.getRoot().lookup("#handedLabel");
assertEquals("handed-Ada", handedLabel.getText()); assertEquals("handed-Ada", handedLabel.getText());
}); });
@@ -67,8 +66,8 @@ class ChooseControllerAndViewModelTest {
Person person = new Person("Ada"); Person person = new Person("Ada");
URL fxml = ChooseControllerAndViewModelTest.class.getResource("desk-greeting.fxml"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("desk-greeting.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label deskLabel = (Label) loaded.getRoot().lookup("#deskLabel"); Label deskLabel = (Label) loaded.getRoot().lookup("#deskLabel");
assertEquals("from-the-desk", deskLabel.getText()); assertEquals("from-the-desk", deskLabel.getText());
}); });
@@ -83,8 +82,8 @@ class ChooseControllerAndViewModelTest {
Person person = new Person("Ada"); Person person = new Person("Ada");
URL fxml = ChooseControllerAndViewModelTest.class.getResource("titled-name.fxml"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("titled-name.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label titleLabel = (Label) loaded.getRoot().lookup("#titleLabel"); Label titleLabel = (Label) loaded.getRoot().lookup("#titleLabel");
assertEquals("titled-Ada", titleLabel.getText()); assertEquals("titled-Ada", titleLabel.getText());
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -105,8 +104,8 @@ class ChooseControllerAndViewModelTest {
Person person = new Person("Ada"); Person person = new Person("Ada");
URL fxml = ChooseControllerAndViewModelTest.class.getResource("badge-name.fxml"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("badge-name.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label badgeLabel = (Label) loaded.getRoot().lookup("#badgeLabel"); Label badgeLabel = (Label) loaded.getRoot().lookup("#badgeLabel");
assertEquals("badge-Ada", badgeLabel.getText()); assertEquals("badge-Ada", badgeLabel.getText());
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -128,8 +127,8 @@ class ChooseControllerAndViewModelTest {
person.setAddress(new Address("Main")); person.setAddress(new Address("Main"));
URL fxml = ChooseControllerAndViewModelTest.class.getResource("caption-address.fxml"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("caption-address.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label captionLabel = (Label) loaded.getRoot().lookup("#captionLabel"); Label captionLabel = (Label) loaded.getRoot().lookup("#captionLabel");
assertEquals("caption-Main", captionLabel.getText()); assertEquals("caption-Main", captionLabel.getText());
}); });
@@ -146,12 +145,12 @@ class ChooseControllerAndViewModelTest {
URL badge = ChooseControllerAndViewModelTest.class.getResource("badge-name.fxml"); URL badge = ChooseControllerAndViewModelTest.class.getResource("badge-name.fxml");
assertNotNull(titled); assertNotNull(titled);
assertNotNull(badge); assertNotNull(badge);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); TestViews context = new TestViews();
LoadedView first = ViewLoader.load(titled, person, context); LoadedView first = TestViews.load(titled, person, context);
Label titleLabel = (Label) first.getRoot().lookup("#titleLabel"); Label titleLabel = (Label) first.getRoot().lookup("#titleLabel");
assertEquals("titled-Ada", titleLabel.getText()); assertEquals("titled-Ada", titleLabel.getText());
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> ViewLoader.load(badge, person, context)); () -> TestViews.load(badge, person, context));
assertTrue(failure.getMessage().contains("TitledViewModel"), failure.getMessage()); assertTrue(failure.getMessage().contains("TitledViewModel"), failure.getMessage());
assertTrue(failure.getMessage().contains("BadgeViewModel"), failure.getMessage()); assertTrue(failure.getMessage().contains("BadgeViewModel"), failure.getMessage());
assertEquals("titled-Ada", titleLabel.getText()); assertEquals("titled-Ada", titleLabel.getText());
@@ -169,9 +168,9 @@ class ChooseControllerAndViewModelTest {
URL plain = ChooseControllerAndViewModelTest.class.getResource("name-both-ways.fxml"); URL plain = ChooseControllerAndViewModelTest.class.getResource("name-both-ways.fxml");
assertNotNull(named); assertNotNull(named);
assertNotNull(plain); assertNotNull(plain);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); TestViews context = new TestViews();
LoadedView first = ViewLoader.load(named, person, context); LoadedView first = TestViews.load(named, person, context);
LoadedView second = ViewLoader.load(plain, person, context); LoadedView second = TestViews.load(plain, person, context);
TextField firstName = (TextField) first.getRoot().lookup("#nameField"); TextField firstName = (TextField) first.getRoot().lookup("#nameField");
TextField secondName = (TextField) second.getRoot().lookup("#nameField"); TextField secondName = (TextField) second.getRoot().lookup("#nameField");
assertEquals("Ada", firstName.getText()); assertEquals("Ada", firstName.getText());
@@ -1,7 +1,6 @@
package de.neitzel.fx.view; package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Person; import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.beans.property.Property; import javafx.beans.property.Property;
import javafx.scene.control.Label; import javafx.scene.control.Label;
@@ -49,8 +48,8 @@ class ComputeAValueTest {
person.setAge(36); person.setAge(36);
URL fxml = ComputeAValueTest.class.getResource("working-age.fxml"); URL fxml = ComputeAValueTest.class.getResource("working-age.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel"); Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel");
assertEquals("initial-age", workingAgeLabel.getText()); assertEquals("initial-age", workingAgeLabel.getText());
assertEquals("Ada", person.getName()); assertEquals("Ada", person.getName());
@@ -67,8 +66,8 @@ class ComputeAValueTest {
Person person = new Person("Ada"); Person person = new Person("Ada");
URL fxml = ComputeAValueTest.class.getResource("working-age.fxml"); URL fxml = ComputeAValueTest.class.getResource("working-age.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField nameField = (TextField) loaded.getRoot().lookup("#nameField"); TextField nameField = (TextField) loaded.getRoot().lookup("#nameField");
Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel"); Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel");
nameField.setText("Grace"); nameField.setText("Grace");
@@ -86,8 +85,8 @@ class ComputeAValueTest {
Person person = new Person("Ada"); Person person = new Person("Ada");
URL fxml = ComputeAValueTest.class.getResource("working-age.fxml"); URL fxml = ComputeAValueTest.class.getResource("working-age.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel"); Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel");
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Property<String> name = (Property<String>) loaded.property("name"); Property<String> name = (Property<String>) loaded.property("name");
@@ -106,8 +105,8 @@ class ComputeAValueTest {
Person person = new Person("Ada"); Person person = new Person("Ada");
URL fxml = ComputeAValueTest.class.getResource("working-age.fxml"); URL fxml = ComputeAValueTest.class.getResource("working-age.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel"); Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel");
assertEquals("initial-age", workingAgeLabel.getText()); assertEquals("initial-age", workingAgeLabel.getText());
workingAgeLabel.setText("sentinel"); workingAgeLabel.setText("sentinel");
@@ -1,7 +1,6 @@
package de.neitzel.fx.view; package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Person; import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.beans.property.IntegerProperty; import javafx.beans.property.IntegerProperty;
import javafx.scene.control.Label; import javafx.scene.control.Label;
@@ -56,8 +55,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
assertEquals("years:42", ageField.getText()); assertEquals("years:42", ageField.getText());
}); });
@@ -73,8 +72,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ageField.setText("years:11"); ageField.setText("years:11");
assertEquals(11, person.getAge()); assertEquals(11, person.getAge());
@@ -91,8 +90,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-view-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-view-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
Label ageLabel = (Label) loaded.getRoot().lookup("#ageLabel"); Label ageLabel = (Label) loaded.getRoot().lookup("#ageLabel");
assertEquals("shown 42", ageLabel.getText()); assertEquals("shown 42", ageLabel.getText());
ageLabel.setText("shown 99"); ageLabel.setText("shown 99");
@@ -110,8 +109,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-and-view-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-and-view-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
Label ageLabel = (Label) loaded.getRoot().lookup("#ageLabel"); Label ageLabel = (Label) loaded.getRoot().lookup("#ageLabel");
assertEquals("shown 42", ageLabel.getText()); assertEquals("shown 42", ageLabel.getText());
@@ -131,8 +130,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-model-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-model-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
assertEquals("years:42", ageField.getText()); assertEquals("years:42", ageField.getText());
((IntegerProperty) loaded.property("age")).set(7); ((IntegerProperty) loaded.property("age")).set(7);
@@ -154,8 +153,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ageField.setText("nope"); ageField.setText("nope");
assertEquals(Integer.valueOf(42), person.getAge()); assertEquals(Integer.valueOf(42), person.getAge());
@@ -180,8 +179,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ageField.setText("nope"); ageField.setText("nope");
ViewModel viewModel = loaded.getViewModel(); ViewModel viewModel = loaded.getViewModel();
@@ -205,8 +204,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ageField.setText("nope"); ageField.setText("nope");
ageField.setText("years:11"); ageField.setText("years:11");
@@ -227,8 +226,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ViewModel viewModel = loaded.getViewModel(); ViewModel viewModel = loaded.getViewModel();
ageField.setText("nope"); ageField.setText("nope");
@@ -255,8 +254,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42); person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ViewModel viewModel = loaded.getViewModel(); ViewModel viewModel = loaded.getViewModel();
String log = captureErr(() -> { String log = captureErr(() -> {
@@ -6,7 +6,6 @@ import de.neitzel.fx.control.NonNegativeIntegerSpinner;
import de.neitzel.fx.control.StatusBar; import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.DockPane; import de.neitzel.fx.docking.DockPane;
import de.neitzel.grid.*; import de.neitzel.grid.*;
import de.neitzel.injection.ApplicationContext;
import javafx.collections.*; import javafx.collections.*;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
@@ -55,6 +54,22 @@ class DataGridFxmlTest {
</DataGrid> </DataGrid>
"""; """;
@Test
void groupLabelEntriesRetainLiteralKeysAlongsideMapAttributes() throws IOException {
String xml = """
<?import de.neitzel.fx.view.DataGridColumn?>
<DataGridColumn>
<groupLabels Post="Postfach"/>
<DataGridColumn.groupLabel><javafx.util.Pair key="/" value="Wurzel"/></DataGridColumn.groupLabel>
<DataGridColumn.groupLabel><javafx.util.Pair key="Post/Eingang" value="Eingang"/></DataGridColumn.groupLabel>
<DataGridColumn.groupLabel><javafx.util.Pair key="Ohne Endung" value="Sonstige"/></DataGridColumn.groupLabel>
</DataGridColumn>
""";
DataGridColumn column = new FXMLLoader().load(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
assertEquals(Map.of("Post", "Postfach", "/", "Wurzel", "Post/Eingang", "Eingang", "Ohne Endung", "Sonstige"),
column.getGroupLabels());
}
@Test @Test
void loadsReusableTagAndCompletionControls() throws Exception { void loadsReusableTagAndCompletionControls() throws Exception {
DataGridTest.fx(() -> { DataGridTest.fx(() -> {
@@ -225,10 +240,10 @@ class DataGridFxmlTest {
DataGridTest.fx(() -> { DataGridTest.fx(() -> {
try { try {
var view = var view =
ViewLoader.load( TestViews.load(
document.toUri().toURL(), document.toUri().toURL(),
model, model,
new ApplicationContext("de.neitzel.fx.view.fixture")); new TestViews());
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
var grid = (DataGrid<Long, Item>) view.getRoot().lookup("#grid"); var grid = (DataGrid<Long, Item>) view.getRoot().lookup("#grid");
ref.set(grid); ref.set(grid);
@@ -5,9 +5,13 @@ import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.grid.*; import de.neitzel.grid.*;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.layout.*; import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.*; import org.junit.jupiter.api.*;
@@ -95,6 +99,137 @@ class DataGridGroupingTest {
return new GroupPath(List.of(new GroupPath.Segment("type", new FilterValue.Text(type)))); return new GroupPath(List.of(new GroupPath.Segment("type", new FilterValue.Text(type))));
} }
@Test
void headerMenusChangeVisibilityWithoutReplacingRowsOrLosingLayout() throws Exception {
var reads = new AtomicInteger();
var disposed = new AtomicInteger();
Map<Long, TextField> fields = new HashMap<>();
var grid = fx(() -> grid(reads, disposed, fields));
var stage = fx(Stage::new);
try {
fx(grid::loadAsync).toCompletableFuture().get(5, TimeUnit.SECONDS);
fx(() -> {
stage.setScene(grid.getScene());
stage.show();
grid.setExpanded(path("A"), true);
grid.setColumnOrder(List.of("status", "type"));
grid.setColumnWidth("type", new ColumnWidth.Explicit(235));
var editor = fields.get(1L);
editor.setText("unfinished draft");
var row = (HBox) editor.getParent();
assertSame(editor, row.getChildren().get(1));
var menu = (MenuButton) grid.lookup(".data-grid-column-menu");
var header = (HBox) grid.lookup(".column-header-row");
long visibility = grid.columnVisibilityRevisionProperty().get();
var context = showColumnContextMenu(header.getChildren().get(1), false);
context.getItems().getLast().fire();
assertEquals(++visibility, grid.columnVisibilityRevisionProperty().get());
grid.setColumnVisible("type", false);
assertEquals(visibility, grid.columnVisibilityRevisionProperty().get());
assertFalse(context.isShowing());
assertFalse(grid.isColumnVisible("type"));
assertNull(editor.getParent());
assertEquals(1, header.getChildren().size());
assertEquals(List.of("type"), grid.groupingColumns());
menu.show();
assertTrue(menu.isShowing());
var status = (CheckMenuItem) menu.getItems().getFirst();
var type = (CheckMenuItem) menu.getItems().getLast();
assertEquals("Status", status.getText());
assertTrue(status.isSelected());
assertEquals("Type", type.getText());
assertFalse(type.isSelected());
status.setSelected(false);
status.fire();
menu.hide();
assertTrue(header.getChildren().isEmpty());
assertTrue(menu.isVisible());
menu.show();
type = (CheckMenuItem) menu.getItems().getLast();
type.setSelected(true);
type.fire();
menu.hide();
assertEquals(visibility + 2, grid.columnVisibilityRevisionProperty().get());
assertSame(editor, row.getChildren().getFirst());
assertEquals(235, editor.getPrefWidth());
assertEquals("unfinished draft", editor.getText());
assertEquals(0, disposed.get());
assertEquals(1, reads.get());
return null;
});
fx(() -> {
var header = (HBox) grid.lookup(".column-header-row");
var context = showColumnContextMenu(header.getChildren().getFirst(), true);
context.getItems().stream()
.filter(item -> "Sort descending".equals(item.getText()))
.findFirst().orElseThrow().fire();
context.hide();
return null;
});
DataGridTest.drain();
fx(() -> {
assertEquals(List.of(new SortKey("type", SortKey.Direction.DESCENDING)),
grid.stateProperty().get().displayed().sort());
assertFalse(grid.isColumnVisible("status"));
assertTrue(grid.isColumnVisible("type"));
assertEquals(1, ((HBox) grid.lookup(".column-header-row")).getChildren().size());
assertEquals(2, reads.get());
return null;
});
} finally {
fx(() -> {
grid.close();
stage.close();
return null;
});
}
}
private static ContextMenu showColumnContextMenu(Node cell, boolean fromKeyboard) {
var point = cell.localToScreen(0, 0);
cell.fireEvent(new ContextMenuEvent(ContextMenuEvent.CONTEXT_MENU_REQUESTED,
0, 0, point.getX(), point.getY(), fromKeyboard, null));
return Window.getWindows().stream()
.filter(ContextMenu.class::isInstance).map(ContextMenu.class::cast)
.filter(ContextMenu::isShowing).findFirst().orElseThrow();
}
@Test
void selectorStaysFixedAndHeadersAlignAtTheRightScrollEdge() throws Exception {
var fields = new HashMap<Long, TextField>();
var grid = fx(() -> grid(new AtomicInteger(), new AtomicInteger(), fields));
try {
fx(grid::loadAsync).toCompletableFuture().get(5, TimeUnit.SECONDS);
fx(() -> {
grid.setExpanded(path("A"), true);
grid.setColumnWidth("type", new ColumnWidth.Explicit(400));
grid.setColumnWidth("status", new ColumnWidth.Explicit(400));
var root = grid.getScene().getRoot();
root.resize(640, 500);
root.layout();
var menu = grid.lookup(".data-grid-column-menu");
double menuX = menu.localToScene(0, 0).getX();
var scroll = (ScrollPane) grid.lookup(".table-scroll");
var header = (HBox) grid.lookup(".column-header-row");
scroll.setHvalue(1);
root.layout();
assertEquals(menuX, menu.localToScene(0, 0).getX(), .5);
var type = fields.get(1L);
assertEquals(type.localToScene(0, 0).getX(),
header.getChildren().getFirst().localToScene(0, 0).getX(), 1);
var last = header.getChildren().getLast();
assertEquals(menuX, last.localToScene(last.getBoundsInLocal()).getMaxX(), 1);
return null;
});
} finally {
fx(() -> {
grid.close();
return null;
});
}
}
@Test @Test
void presentationChangesPreserveComponentsDraftsAndHiddenSelectionWithoutQueries() void presentationChangesPreserveComponentsDraftsAndHiddenSelectionWithoutQueries()
throws Exception { throws Exception {
@@ -326,7 +326,10 @@ class DataGridNativeInteractionTest {
ScrollPane scroll = fx(() -> (ScrollPane) grid.lookup(".table-scroll")); ScrollPane scroll = fx(() -> (ScrollPane) grid.lookup(".table-scroll"));
var original = order(); var original = order();
begin(fx(() -> label("name"))); begin(fx(() -> label("name")));
Bounds viewport = fx(() -> scroll.localToScreen(scroll.getViewportBounds())); Bounds viewport = fx(() -> {
var headerScroll = grid.lookup(".table-header-scroll");
return headerScroll.localToScreen(headerScroll.getBoundsInLocal());
});
move(new Point2D(viewport.getMaxX() - 10, point(fx(() -> header("type")), .5, .5).getY())); move(new Point2D(viewport.getMaxX() - 10, point(fx(() -> header("type")), .5, .5).getY()));
waitFor(() -> scroll.getHvalue() > .1, "Native edge hover scrolls"); waitFor(() -> scroll.getHvalue() > .1, "Native edge hover scrolls");
capture("edge-scroll"); capture("edge-scroll");
@@ -5,7 +5,6 @@ import de.neitzel.fx.view.component.Envelope;
import de.neitzel.fx.view.component.Letter; import de.neitzel.fx.view.component.Letter;
import de.neitzel.fx.view.fixture.Address; import de.neitzel.fx.view.fixture.Address;
import de.neitzel.fx.view.fixture.Person; import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.control.TextField; import javafx.scene.control.TextField;
@@ -55,8 +54,8 @@ class EditAddressInAComponentTest {
person.setAddress(address); person.setAddress(address);
URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml"); URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm"); AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm");
assertNotNull(form); assertNotNull(form);
assertSame(address, form.getModel()); assertSame(address, form.getModel());
@@ -76,8 +75,8 @@ class EditAddressInAComponentTest {
Person person = new Person("Ada"); Person person = new Person("Ada");
URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml"); URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm"); AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm");
assertNotNull(form); assertNotNull(form);
assertNull(form.getModel()); assertNull(form.getModel());
@@ -97,8 +96,8 @@ class EditAddressInAComponentTest {
person.setAddress(new Address("Main")); person.setAddress(new Address("Main"));
URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml"); URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm"); AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm");
Label streetLabel = (Label) form.lookup("#streetLabel"); Label streetLabel = (Label) form.lookup("#streetLabel");
assertEquals("Lane", streetLabel.getText()); assertEquals("Lane", streetLabel.getText());
@@ -116,8 +115,8 @@ class EditAddressInAComponentTest {
person.setAddress(address); person.setAddress(address);
URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml"); URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, person, context); LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm"); AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm");
assertSame(loaded.property("address").getValue(), form.receivedViewModel()); assertSame(loaded.property("address").getValue(), form.receivedViewModel());
assertEquals("kept", form.streetTextAtHandOff()); assertEquals("kept", form.streetTextAtHandOff());
@@ -136,8 +135,8 @@ class EditAddressInAComponentTest {
Letter letter = new Letter(new Envelope(address)); Letter letter = new Letter(new Envelope(address));
URL fxml = EditAddressInAComponentTest.class.getResource("letter-envelope.fxml"); URL fxml = EditAddressInAComponentTest.class.getResource("letter-envelope.fxml");
assertNotNull(fxml); assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); TestViews context = new TestViews();
LoadedView loaded = ViewLoader.load(fxml, letter, context); LoadedView loaded = TestViews.load(fxml, letter, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
assertEquals("Main", streetField.getText()); assertEquals("Main", streetField.getText());
streetField.setText("Oak"); streetField.setText("Oak");
@@ -151,8 +150,8 @@ class EditAddressInAComponentTest {
@Test @Test
void componentAttributesApplyAfterInitialization() throws Exception { void componentAttributesApplyAfterInitialization() throws Exception {
onFx(() -> { onFx(() -> {
var context = new ApplicationContext("de.neitzel.fx.view.component"); var context = new TestViews();
var loaded = ViewLoader.load(getClass().getResource("address-component-attributes.fxml"), var loaded = TestViews.load(getClass().getResource("address-component-attributes.fxml"),
new Person("Ada"), context); new Person("Ada"), context);
var first = (AddressForm) loaded.getRoot().lookup("#first"); var first = (AddressForm) loaded.getRoot().lookup("#first");
var second = (AddressForm) loaded.getRoot().lookup("#second"); var second = (AddressForm) loaded.getRoot().lookup("#second");
@@ -165,7 +164,7 @@ class EditAddressInAComponentTest {
assertSame(first.getModel(), second.getModel()); assertSame(first.getModel(), second.getModel());
assertEquals("Second", second.getCaption()); assertEquals("Second", second.getCaption());
assertEquals(280, second.getPrefWidth()); assertEquals(280, second.getPrefWidth());
assertSame(first, context.getComponent(AddressForm.class)); org.junit.jupiter.api.Assertions.assertNotSame(first, second);
TextField field = (TextField) first.lookup("#streetField"); TextField field = (TextField) first.lookup("#streetField");
assertEquals("Main", field.getText()); assertEquals("Main", field.getText());
field.setText("Oak"); field.setText("Oak");
@@ -180,9 +179,9 @@ class EditAddressInAComponentTest {
void invalidComponentAttributesFailTheLoad() throws Exception { void invalidComponentAttributesFailTheLoad() throws Exception {
onFx(() -> { onFx(() -> {
for (String kind : java.util.List.of("unknown", "number")) { for (String kind : java.util.List.of("unknown", "number")) {
var context = new ApplicationContext("de.neitzel.fx.view.component"); var context = new TestViews();
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class,
() -> ViewLoader.load(getClass().getResource("address-component-invalid-" + kind + ".fxml"), () -> TestViews.load(getClass().getResource("address-component-invalid-" + kind + ".fxml"),
new Person("Ada"), context)); new Person("Ada"), context));
} }
}); });
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.component.VisitRow; import de.neitzel.fx.view.component.VisitRow;
import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Visit; import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.scene.Node; import javafx.scene.Node;
import javafx.scene.control.Button; import javafx.scene.control.Button;
@@ -151,7 +150,7 @@ class FilterByChecklistTest {
private static LoadedView load(Host host) { private static LoadedView load(Host host) {
URL fxml = FilterByChecklistTest.class.getResource("show-visits-selection.fxml"); URL fxml = FilterByChecklistTest.class.getResource("show-visits-selection.fxml");
assertNotNull(fxml); assertNotNull(fxml);
return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); return TestViews.load(fxml, host, new TestViews());
} }
/** /**
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Role; import de.neitzel.fx.view.fixture.Role;
import de.neitzel.fx.view.fixture.Visit; import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.Node; import javafx.scene.Node;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.CheckBox; import javafx.scene.control.CheckBox;
@@ -206,7 +205,7 @@ class FilterByComparisonTest {
private static LoadedView load(Host host) { private static LoadedView load(Host host) {
URL fxml = FilterByComparisonTest.class.getResource("show-two-tables.fxml"); URL fxml = FilterByComparisonTest.class.getResource("show-two-tables.fxml");
assertNotNull(fxml); assertNotNull(fxml);
return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); return TestViews.load(fxml, host, new TestViews());
} }
/** /**

Some files were not shown because too many files have changed in this diff Show More