23 Commits
Author SHA1 Message Date
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 2d12a7d393 Bind named read-only observables toward FXML views 2026-11-23 18:18:45 +01:00
47 changed files with 1556 additions and 148 deletions
+15 -3
View File
@@ -54,6 +54,12 @@ 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).
### fx-test
JavaFX fixtures for JUnit Jupiter. Add `de.neitzel.lib:fx-test` at the same version as `fx` with Maven scope `test`. Annotate the class with `@FxTest` and accept an `FxFixture` parameter in each test. Use `fx.run` for actions, `fx.call` for values and `fx.await("dialog closed", () -> !dialog.isShowing())` to wait from the test thread. `fx.load(fxml, model, services)` uses the production ViewLoader and a fresh ViewModelContext per test.
The extension keeps JavaFX running between tests, isolates the class with JUnit's `@Isolated`, hides windows opened by each test, closes its view context and reports unhandled FX callbacks at teardown. Complete background work before the test ends. Select the backend in the test JVM before toolkit startup, for example `-Dglass.platform=Headless`.
### injection
Package scanner and type-based container used by `fx`. See [injection/README.md](injection/README.md).
@@ -84,7 +90,13 @@ The [complete quick start](fx/docs/quick-start.md) includes local installation,
Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven 3.9.11 or later. Surefire fails the build if tests fail.
## Changes in 1.0.4
## Changes in 1.0.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.
@@ -99,7 +111,7 @@ Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven
## Use a release from Maven
To use release `1.0.4`, add the Gitea registry to the consuming project's POM and use the release
To use release `1.0.6`, add the Gitea registry to the consuming project's POM and use the release
version for the module you need:
```xml
@@ -114,7 +126,7 @@ version for the module you need:
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</dependency>
</dependencies>
```
+5 -2
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>core</artifactId>
@@ -18,13 +18,16 @@
<launcher>${project.artifactId}</launcher>
<appName>${project.artifactId}</appName>
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency versions -->
<jna.version>5.19.1</jna.version>
</properties>
<dependencies>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.19.1</version>
<version>${jna.version}</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
+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">
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.4</version></parent>
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.6</version></parent>
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
<dependencies><dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
<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">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.4</version></parent>
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.6</version></parent>
<artifactId>data-grid</artifactId>
<description>Toolkit-independent filter, query and grid setup contracts</description>
</project>
+5 -2
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>encryption</artifactId>
@@ -18,13 +18,16 @@
<launcher>${project.artifactId}</launcher>
<appName>${project.artifactId}</appName>
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency versions -->
<format-preserving-encryption.version>1.0.0</format-preserving-encryption.version>
</properties>
<dependencies>
<dependency>
<groupId>com.idealista</groupId>
<artifactId>format-preserving-encryption</artifactId>
<version>1.0.0</version>
<version>${format-preserving-encryption.version}</version>
</dependency>
</dependencies>
+2 -2
View File
@@ -30,12 +30,12 @@ From the NeitzelLib root with JDK 25:
./mvnw -f fx-example/pom.xml javafx:run
```
The first command installs local `1.0.4` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
The first command installs local `1.0.6` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
The packaged alternative, after `package` or `install`, is:
```bash
java -jar fx-example/target/fx-example-1.0.4.jar
java -jar fx-example/target/fx-example-1.0.6.jar
```
Keep the adjacent `target/libs` directory with the JAR: the manifest refers to those copied runtime dependencies. A desktop session is required. This example has no `module-info.java`; it is a classpath application.
+1 -1
View File
@@ -6,7 +6,7 @@ From the repository root with JDK 25, build without installing runtime artifacts
```sh
./mvnw -pl fx-example -am package -DskipTests
java -cp 'fx-example/target/fx-example-1.0.4.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
java -cp 'fx-example/target/fx-example-1.0.6.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
```
The default catalog has 10,000 products. Both backends use identical stable IDs, names, categories, quantities and DECIMAL(12,2) prices. Fixtures include duplicate sort values, nulls, empty text, mixed case, Unicode, apostrophes and literal SQL wildcard characters. One `ProductCatalog` service maintains original text and Locale.ROOT comparison keys together on insertion/reset. Mutations run on application workers and explicitly refresh the grid; browsing is read-only.
+1 -1
View File
@@ -5,7 +5,7 @@
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
```sh
java -cp 'fx-example/target/fx-example-1.0.4.jar:fx-example/target/libs/*' \
java -cp 'fx-example/target/fx-example-1.0.6.jar:fx-example/target/libs/*' \
de.neitzel.fx.example.theme.ThemeGalleryMain
```
+25 -5
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>fx-example</artifactId>
@@ -18,11 +18,17 @@
<appName>${project.artifactId}</appName>
<main.class>de.neitzel.fx.example.Main</main.class>
<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>
<dependencies>
<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>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
@@ -99,11 +105,25 @@
<profiles>
<profile>
<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>
<dependency>
<groupId>de.neitzel.fxdesigner</groupId>
<artifactId>designer-preview-api</artifactId>
<version>0.1.0-SNAPSHOT</version>
<version>${designer.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -112,7 +132,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.8.0</version>
<version>${build.helper.maven.plugin}</version>
<executions>
<execution>
<id>designer-preview-sources</id>
@@ -139,7 +159,7 @@
<path>
<groupId>de.neitzel.fxdesigner</groupId>
<artifactId>designer-model-processor</artifactId>
<version>0.1.0-SNAPSHOT</version>
<version>${designer.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
+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.6</version>
</parent>
<artifactId>fx-test</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<glass.platform>Headless</glass.platform>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,37 @@
package de.neitzel.fx.test;
import java.lang.reflect.Method;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
final class FxExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create(FxExtension.class);
@Override
public void beforeEach(ExtensionContext context) throws Exception {
var fixture = new FxFixture();
fixture.start();
context.getStore(NAMESPACE).put(FxFixture.class, fixture);
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
var fixture = context.getStore(NAMESPACE).remove(FxFixture.class, FxFixture.class);
if (fixture != null) fixture.finish();
}
@Override
public boolean supportsParameter(ParameterContext parameter, ExtensionContext context) {
return parameter.getParameter().getType() == FxFixture.class
&& parameter.getDeclaringExecutable() instanceof Method
&& context.getStore(NAMESPACE).get(FxFixture.class) != null;
}
@Override
public Object resolveParameter(ParameterContext parameter, ExtensionContext context) {
return context.getStore(NAMESPACE).get(FxFixture.class, FxFixture.class);
}
}
@@ -0,0 +1,140 @@
package de.neitzel.fx.test;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BooleanSupplier;
import javafx.application.Platform;
import javafx.stage.Window;
/** JavaFX test operations scoped to one JUnit test. Obtain the fixture through {@link FxTest}. */
public final class FxFixture {
private static final long TIMEOUT_SECONDS = 10;
private final ViewModelContext models = new ViewModelContext();
private final List<Throwable> callbackFailures = new ArrayList<>();
private List<Window> previousWindows;
private Thread.UncaughtExceptionHandler previousHandler;
/** An FX-thread action that may propagate a checked exception. */
@FunctionalInterface
public interface Action {
/**
* Performs the action.
* @throws Exception on failure
*/
void run() throws Exception;
}
FxFixture() {}
void start() throws Exception {
try {
Platform.startup(() -> {});
} catch (IllegalStateException alreadyStarted) {
// A previous test or another JavaFX client has started this JVM's toolkit.
}
run(() -> {
Platform.setImplicitExit(false);
previousWindows = List.copyOf(Window.getWindows());
previousHandler = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread().setUncaughtExceptionHandler((thread, error) -> callbackFailures.add(error));
});
}
/**
* Runs an action on the FX thread and propagates its failure to the test.
* @param action test action
* @throws Exception if the action fails or the wait is interrupted or times out
*/
public void run(Action action) throws Exception {
call(() -> {
action.run();
return null;
});
}
/**
* Returns the result of an FX-thread operation, with a bounded wait on the calling thread.
* @param <T> result type
* @param action operation to perform
* @return the value returned by the operation
* @throws Exception if the operation fails or the wait is interrupted or times out
*/
public <T> T call(Callable<T> action) throws Exception {
if (Platform.isFxApplicationThread()) return action.call();
var task = new FutureTask<>(action);
Platform.runLater(task);
try {
return task.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (ExecutionException failure) {
if (failure.getCause() instanceof Exception exception) throw exception;
if (failure.getCause() instanceof Error error) throw error;
throw new AssertionError(failure.getCause());
} catch (TimeoutException | InterruptedException failure) {
task.cancel(false);
throw failure;
}
}
/**
* Waits on the test thread while evaluating the named condition on the FX thread.
* @param description expected state, included in the timeout message
* @param condition UI predicate to evaluate
* @throws Exception if evaluation fails or waiting is interrupted
* @throws AssertionError if the condition stays false
*/
public void await(String description, BooleanSupplier condition) throws Exception {
if (Platform.isFxApplicationThread()) throw new IllegalStateException("await requires the test thread");
long start = System.nanoTime();
while (!call(condition::getAsBoolean)) {
if (System.nanoTime() - start >= TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)) {
throw new AssertionError("Timed out waiting for " + description);
}
Thread.sleep(15);
}
}
/**
* Loads production FXML on the FX thread in the test's automatically closed model context.
* @param fxml view resource
* @param model model for the view
* @param services controller and service container
* @return managed view
* @throws Exception if the view cannot be loaded or the wait is interrupted or times out
*/
public LoadedView load(URL fxml, Object model, ApplicationContext services) throws Exception {
return call(() -> ViewLoader.load(fxml, model, services, models));
}
void finish() throws Exception {
run(() -> {
try {
for (var window : List.copyOf(Window.getWindows()).reversed()) {
if (!previousWindows.contains(window)) window.hide();
}
} finally {
try {
models.close();
} finally {
Thread.currentThread().setUncaughtExceptionHandler(previousHandler);
}
}
if (!callbackFailures.isEmpty()) {
var failure = new AssertionError("Unhandled exception on the JavaFX application thread",
callbackFailures.getFirst());
callbackFailures.stream().skip(1).forEach(failure::addSuppressed);
throw failure;
}
});
}
}
@@ -0,0 +1,20 @@
package de.neitzel.fx.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.api.parallel.Isolated;
/** Runs a JavaFX test class in isolation and supplies an FxFixture to each test method. */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Isolated
@Execution(ExecutionMode.SAME_THREAD)
@ExtendWith(FxExtension.class)
public @interface FxTest {}
@@ -0,0 +1,57 @@
package de.neitzel.fx.test;
import de.neitzel.injection.ApplicationContext;
import java.io.IOException;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.Setter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@FxTest
public class FxFixtureTest {
@Getter @Setter
public static class Person {
private String name = "Ada";
}
@Test
void teardownDetachesLoadedViewsAndReportsUnhandledCallbacks(FxFixture fx) throws Exception {
var person = new Person();
var nested = new FxFixture();
var problem = new IllegalStateException("callback failed");
nested.start();
var view = nested.load(getClass().getResource("name.fxml"), person, new ApplicationContext(Person.class));
var field = nested.call(() -> (TextField) view.getRoot());
var stage = nested.call(() -> {
assertEquals("Ada", field.getText());
field.setText("Lin");
assertEquals("Lin", person.getName());
var window = new Stage();
window.setScene(new Scene(field));
window.show();
return window;
});
nested.run(() -> Platform.runLater(() -> { throw problem; }));
assertSame(problem, assertThrows(AssertionError.class, nested::finish).getCause());
fx.run(() -> {
assertFalse(stage.isShowing());
field.setText("Detached");
assertEquals("Lin", person.getName());
});
}
@Test
void nestedCallsPropagateTheOriginalFailureAndCannotBlockTheFxThread(FxFixture fx) throws Exception {
var problem = new IOException("failed");
assertSame(problem, assertThrows(IOException.class, () -> fx.run(() -> {
assertTrue(fx.call(Platform::isFxApplicationThread));
assertThrows(IllegalStateException.class, () -> fx.await("next pulse", () -> false));
throw problem;
})));
}
}
@@ -0,0 +1,8 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.TextField?>
<TextField xmlns:fx="http://javafx.com/fxml/1" fx:id="field">
<fx:define><BindingList>
<DirectBinding control="field" property="text" path="name" direction="both"/>
</BindingList></fx:define>
</TextField>
+64 -2
View File
@@ -48,6 +48,8 @@ The launch class is `de.neitzel.fx.example.Main`. `Main` does not extend `Applic
Depend on `de.neitzel.lib:fx`. That module depends on `core`, `injection` and on JavaFX base, controls, graphics, fxml, and web. Application types the container constructs use `jakarta.inject.Singleton` or `jakarta.inject.Named`.
Use `ViewLoader.loadComponent(type, model, context, models)` to open a reusable Component directly from its own FXML. It returns a managed `LoadedView` with the same Component, ViewModel selection and binding lifetime as an embedded instance.
## Dependencies
These are the versions configured by this source snapshot, not a promise of compatibility with every newer release:
@@ -56,7 +58,7 @@ These are the versions configured by this source snapshot, not a promise of comp
| --- | --- | --- |
| JDK | Java 25 | Select a matching JDK for compilation and launch |
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
| Library | `de.neitzel.lib:fx:1.0.4` | Use the Gitea Maven registry or install the local reactor |
| Library | `de.neitzel.lib:fx:1.0.6` | Use the Gitea Maven registry or install the local reactor |
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
| 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 |
@@ -173,7 +175,7 @@ For `both` and `model`, the write happens when the JavaFX property changes, incl
`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`.
@@ -298,6 +300,61 @@ availability as the condition for disabling these controls. The managed View det
both bindings on close. For dynamically created menu items, keep the registration from
`CommandBindings.bind(item, command)` and close it when discarding the item.
### Asynchronous Commands
Use `AsyncCommand<T>` when a Command starts a JavaFX `Task<T>`. The application supplies
an executor and a factory for a fresh Task on each execution. Use `getCommand()` from the
ViewModel's public getter, or from a keyboard handler or a dynamic menu. Availability combines
the application rule with the state of the current execution. The worker slot is occupied before
the executor receives the Task. Failures from the factory, executor, and worker appear in
`stateProperty()` alongside progress and the Task message. A terminal observation has
`running() == false`, so a completion listener can retry or close the host.
Pass `true` as the last constructor argument for a Task that supports cancellation. Call
`cancel()` to cancel it and let the worker finish any cooperative cleanup. The worker slot
becomes available again when the worker exits. Closing an `AsyncCommand` detaches its Task
listeners and disables future invocations. Call `cancel()` before closing if the View explicitly
owns the work and should cancel it.
A dialog's generated button has its own standard close handler. In the following example,
`valid` is the form's observable validity, `executor` runs background tasks, and
`createSaveTask` supplies a fresh `Task<Void>`. Filter the action, and close the dialog only
after success. In the failure branch, the user can correct the form and retry.
```java
var dialog = new Dialog<Boolean>();
var save = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().setAll(save, ButtonType.CANCEL);
dialog.setResultConverter(button -> false);
var saveButton = dialog.getDialogPane().lookupButton(save);
try (var saving = new AsyncCommand<Void>(valid, executor, createSaveTask)) {
saveButton.disableProperty().bind(Bindings.not(saving.getCommand().getCanExecute()));
EventHandler<ActionEvent> saveAction = event -> {
event.consume();
saving.getCommand().execute();
};
saveButton.addEventFilter(ActionEvent.ACTION, saveAction);
dialog.setOnCloseRequest(event -> {
if (saving.getState().running()) event.consume();
});
try {
saving.stateProperty().addListener((source, previous, state) -> {
if (state.phase() == AsyncCommand.Phase.SUCCEEDED) {
dialog.setResult(true);
dialog.close();
} else if (state.phase() == AsyncCommand.Phase.FAILED) {
dialog.getDialogPane().setHeaderText(state.error().getMessage());
}
});
dialog.showAndWait();
} finally {
saveButton.removeEventFilter(ActionEvent.ACTION, saveAction);
saveButton.disableProperty().unbind();
dialog.setOnCloseRequest(null);
}
}
```
## Controller
Name the class on the root with `fx:controller`. The container creates it with `getComponent`, so it is the cached singleton. `@FXML` fields are filled during load, before the bindings run.
@@ -653,3 +710,8 @@ The reference above covers the FXML declarations and their behavior. These are t
`property(name)` returns `Property<?>`: cast to the known property type when writing from Java, for example `((StringProperty) loaded.property("name")).set("Grace")`. Generated accessors avoid these casts. `storedProperty` is for subclasses and reads only stored Model Attributes; it does not invoke custom reflective accessors. Internal loaders, appliers and identity-cache helpers are implementation details, not extension APIs.
For threading, strong identity retention, context reuse, the absence of a general disposal API, and JPMS reflection, see [architecture and lifetime](docs/architecture.md). For an independent application POM and runnable files, use the [complete quick start](docs/quick-start.md).
DataGrid columns accept arbitrary string keys for group captions through the attached
`DataGridColumn.groupLabel` property. For example,
`<DataGridColumn.groupLabel><javafx.util.Pair key="Post/Eingang West" value="Eingang"/></DataGridColumn.groupLabel>`
writes the literal key into the same map as `<groupLabels Post="Postfach"/>`.
+21
View File
@@ -36,6 +36,27 @@ Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` fo
- A successfully replaced source clears all selection. `confirmedDeleted(key)` removes only that key and refreshes; absence from a page alone does not imply deletion. Collapsed groups retain their keys but expose no actionable elements for hidden rows.
- Empty results disable navigation. Unknown totals are displayed as unknown and disable Last. A disappeared page receives one bounded correction; subsequent invalidation becomes an error with Retry.
## Selection in a ViewModel
Use `grid.observeSelection()` for a single read-only property containing both selected keys and available elements. The initial snapshot reflects the current grid. Each subsequent snapshot captures both lists after selection or row availability changes. Keys follow selection order and elements follow display order. A selected key can remain present while its row is unavailable. An action that needs every selected row can compare the two list sizes in one snapshot before capturing that snapshot for confirmation.
For example, a ViewModel can derive a label from the adapter.
```java
var selection = grid.observeSelection();
var summary = selection.selectionProperty().map(state ->
state.selectedKeys().size() + " selected, "
+ state.selectedElements().size() + " visible");
```
Expose the result through a public `ObservableValue<String> summaryProperty()` on the ViewModel and declare the label binding.
```xml
<DirectBinding control="summary" property="text" path="summary" direction="view"/>
```
Restore keys explicitly with `selection.selectKeys(savedKeys)` or restore one with `selection.select(key)`. The adapter delegates to the grid and respects its selection mode. The owner closes the adapter on the JavaFX thread when the ViewModel stops observing. Closing detaches the adapter and freezes its last snapshot while the grid and other observers continue to work independently. See the [FXML integration test](../src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java).
## Guards, warnings and supersession
`setEditGuard(query -> CompletionStage<Boolean>)` lets the application save/discard/block unfinished edits. `setAllConfirmation((query, count) -> CompletionStage<Boolean>)` can replace the default nonblocking Continue/Cancel alert. Neither dialog handling nor guard completion runs inside a source transaction. Superseded answers cannot publish or restart old requests.
+12 -2
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.Table` | `collection`, `row`, `Column` declarations | Existing ViewLoader collection/Component rows and `selection` binding |
| `de.neitzel.fx.control.StatusBar` | `leftItems`, `rightItems` containing ordinary Nodes | Bind the properties of the contained controls |
| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes 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.HtmlViewer` | `mediaButtonVisible`, `mediaLoadText`, `mediaReloadText`, `mediaTooltipText`, `noExternalMediaText` | Explicit `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) |
| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes, fixed `suggestions` and a bindable `suggestionsSource` of type `ObservableList<String>` | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action |
| `de.neitzel.fx.control.HtmlViewer` | `mediaButtonVisible`, `mediaLoadText`, `mediaReloadText`, `mediaTooltipText`, `noExternalMediaText` | Bind local text to `html` or use `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) |
| `de.neitzel.fx.control.TagChip` | `text`, `removable` (false by default), `onRemove` | The action handler owns removing the tag from its model |
| `de.neitzel.fx.docking.DockPane` | `initialLayout`, `DockLayout`, group/split definitions | Attach a DockingManager to open application-owned content |
| `de.neitzel.fx.control.NonNegativeIntegerSpinner` | `minimum`, `maximum`, `initialValue` constructor attributes | Bind writable `number`, which shares the value factory's property |
@@ -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)
for the existing controls. The host designer needs the updated library on its
classpath; this feature does not replace a separately pinned Designer runtime.
### Model-driven suggestions
Use `<DirectBinding control="dynamic" property="suggestionsSource" path="tags" direction="view"/>`
for an observable list of strings. A non-null source (including an empty list) takes precedence over
the fixed FXML entries in `getSuggestions()`. The popup follows replacements and edits to the active
list while the field is attached. Choosing a match sets the field text and fires its action.
Setting the source to null or unbinding `suggestionsSourceProperty()` restores the fixed entries.
Closing a managed DirectBinding restores its previous list source. Removing the field from its
scene dismisses the popup and detaches its list listener.
+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()`
also cancels pending work, is idempotent, and makes future loads fail.
## Model-driven source
Bind a string toward the viewer with a DirectBinding such as
`<DirectBinding control="article" property="html" path="html" direction="view"/>`.
For plain JavaFX use `viewer.htmlProperty().bind(source)`. Each changed string uses
the offline `loadHtml` preparation. A null or blank value clears the document.
Rapid changes cancel older preparations and revoke earlier media grants.
The property contains the supplied source. Displaying a prepared document, loading a file,
granting image access or clearing the viewer changes the display without writing to the model.
The next change to the bound text takes effect. Unbinding leaves the current display in place.
Close the viewer on disposal to detach a JavaFX binding and cancel outstanding work.
## External images
Each displayed document starts offline. The included **Load external media**
+4 -4
View File
@@ -1,13 +1,13 @@
# Your first JavaFX application
This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.4. The source build below uses the matching release tag.
This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.6. The source build below uses the matching release tag.
## Prepare the library
Install a JDK 25. Use the library's Maven wrapper (3.9.11), or a separate Maven installation version 3.9.11 or newer. Check `java -version` and `./mvnw -version` before building; on macOS, select the JDK with `export JAVA_HOME=$(/usr/libexec/java_home -v 25)` if necessary.
```bash
git clone --branch v1.0.4 https://gitea.neitzel.de/konrad/NeitzelLib.git
git clone --branch v1.0.6 https://gitea.neitzel.de/konrad/NeitzelLib.git
cd NeitzelLib
./mvnw -pl fx-example -am install
./mvnw -f fx-example/pom.xml javafx:run
@@ -66,7 +66,7 @@ hello-fx/
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@@ -190,7 +190,7 @@ For a named-module application, see the [module and lifecycle notes](architectur
| Symptom | Check |
| --- | --- |
| Maven cannot resolve `de.neitzel.lib:fx:1.0.4` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
| Maven cannot resolve `de.neitzel.lib:fx:1.0.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. |
| 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. |
+9 -4
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>fx</artifactId>
@@ -18,6 +18,11 @@
<launcher>${project.artifactId}</launcher>
<appName>${project.artifactId}</appName>
<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>
<dependencies>
@@ -47,17 +52,17 @@
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.23.2</version>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>com.helger</groupId>
<artifactId>ph-css</artifactId>
<version>8.2.3</version>
<version>${ph-css.version}</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-webp</artifactId>
<version>3.15.3</version>
<version>${imageio-webp.version}</version>
</dependency>
<!-- NeitzelLib dependencies -->
@@ -1,9 +1,13 @@
package de.neitzel.fx.control;
import java.util.Locale;
import javafx.beans.InvalidationListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.WeakListChangeListener;
import javafx.event.ActionEvent;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
@@ -16,6 +20,18 @@ import javafx.stage.Popup;
public final class AutoCompleteTextField extends TextField {
private static final int ROW_HEIGHT = 26;
private final ObservableList<String> suggestions = FXCollections.observableArrayList();
private final ObjectProperty<ObservableList<String>> suggestionsSource =
new SimpleObjectProperty<>(this, "suggestionsSource") {
@Override public void unbind() {
if (isBound()) {
super.unbind();
set(null);
}
}
};
private final ListChangeListener<String> contentChanged = change -> updateSuggestions();
private final WeakListChangeListener<String> weakContentChanged = new WeakListChangeListener<>(contentChanged);
private ObservableList<String> observedSuggestions;
private final ListView<String> choices = new ListView<>();
private final Popup popup = new Popup();
private boolean accepting;
@@ -29,9 +45,12 @@ public final class AutoCompleteTextField extends TextField {
var value = choices.getSelectionModel().getSelectedItem();
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());
sceneProperty().addListener((property, before, after) -> popup.hide());
sceneProperty().addListener((property, before, after) -> {
popup.hide();
observeSuggestions();
});
disabledProperty().addListener((property, before, disabled) -> {
if (disabled) popup.hide();
});
@@ -42,6 +61,21 @@ public final class AutoCompleteTextField extends TextField {
return suggestions;
}
/** Optional live catalogue. Without a source the fixed FXML suggestions are used. */
public ObjectProperty<ObservableList<String>> suggestionsSourceProperty() { return suggestionsSource; }
public ObservableList<String> getSuggestionsSource() { return suggestionsSource.get(); }
public void setSuggestionsSource(ObservableList<String> value) { suggestionsSource.set(value); }
private void observeSuggestions() {
var source = getSuggestionsSource();
var next = getScene() == null ? null : source == null ? suggestions : source;
if (observedSuggestions == next) return;
if (observedSuggestions != null) observedSuggestions.removeListener(weakContentChanged);
observedSuggestions = next;
if (next != null) next.addListener(weakContentChanged);
updateSuggestions();
}
private void handleKey(KeyEvent event) {
var selection = choices.getSelectionModel();
if (event.getCode() == KeyCode.DOWN || event.getCode() == KeyCode.UP && popup.isShowing()) {
@@ -67,11 +101,11 @@ public final class AutoCompleteTextField extends TextField {
}
private void updateSuggestions() {
if (accepting || !isFocused() || isDisabled() || getScene() == null
if (observedSuggestions == null || accepting || !isFocused() || isDisabled() || getScene() == null
|| getScene().getWindow() == null || !getScene().getWindow().isShowing()) return;
String prefix = getText() == null ? "" : getText().strip().toLowerCase(Locale.ROOT);
var matches = prefix.isEmpty() ? java.util.List.<String>of()
: 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();
choices.getItems().setAll(matches);
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 mediaTooltipText = new SimpleStringProperty(this, "mediaTooltipText", "Loads external images for this viewer only and contacts their servers.");
private final StringProperty noExternalMediaText = new SimpleStringProperty(this, "noExternalMediaText", "No resolvable external image addresses found.");
private final StringProperty html = new SimpleStringProperty(this, "html");
private HtmlDocument document;
private Task<HtmlDocument> pending;
private long generation;
@@ -41,6 +42,11 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
public HtmlViewer() {
getStyleClass().add("html-viewer");
html.addListener((observable, before, value) -> {
if (closed) return;
if (value == null || value.isBlank()) clear();
else loadHtml(value);
});
browser.setContextMenuEnabled(false);
browser.getEngine().setJavaScriptEnabled(false);
loading.bind(preparing.or(browser.getEngine().getLoadWorker().runningProperty()));
@@ -153,6 +159,7 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
@Override public void close() {
requireFxThread();
if (closed) return;
html.unbind();
clear();
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.");
}
/** Local source text. Imperative display operations do not publish values to this input. */
public StringProperty htmlProperty() { return html; }
public String getHtml() { return html.get(); }
public void setHtml(String value) { requireOpen(); html.set(value); }
public ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); }
public boolean isLoading() { return loading.get(); }
public ReadOnlyObjectProperty<Throwable> errorProperty() { return error.getReadOnlyProperty(); }
@@ -0,0 +1,205 @@
package de.neitzel.fx.view;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableBooleanValue;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import lombok.Getter;
/**
* A Command that runs one JavaFX Task at a time on a caller-provided executor.
* Create and use it, including its Command and state, on the JavaFX application thread.
*/
public final class AsyncCommand<T> implements AutoCloseable {
/** The execution phase reported to the View. */
public enum Phase { IDLE, RUNNING, SUCCEEDED, FAILED, CANCELLED, CLOSED }
/**
* One observation of an execution, published on the FX application thread.
*
* @param phase execution phase
* @param result value from a successful execution
* @param error failure from task creation, scheduling or execution
* @param progress progress in the range 0 to 1, or -1 for indeterminate work
* @param message current task message
* @param <T> result type
*/
public record State<T>(Phase phase, T result, Throwable error, double progress, String message) {
/** Returns whether an execution occupies this Command's worker slot. */
public boolean running() {
return phase == Phase.RUNNING;
}
private static <T> State<T> of(Phase phase) {
return new State<>(phase, null, null, -1, "");
}
}
/** The Command shared by controls, FXML bindings and keyboard actions. */
@Getter
private final Command command;
private final ReadOnlyObjectWrapper<State<T>> state = new ReadOnlyObjectWrapper<>(State.of(Phase.IDLE));
private final Executor executor;
private final Supplier<? extends Task<T>> tasks;
private final boolean cancellable;
private Execution current;
/**
* Creates a command with no user cancellation.
*
* @param available the application's availability rule
* @param executor the executor that runs tasks outside the FX application thread
* @param tasks factory invoked on the FX application thread to supply a fresh, ready task
*/
public AsyncCommand(ObservableBooleanValue available, Executor executor, Supplier<? extends Task<T>> tasks) {
this(available, executor, tasks, false);
}
/**
* Creates a command with optional cancellation. A cancellable Task must cooperate with
* interruption and implement any application-specific rollback in its worker.
*
* @param available the application's availability rule
* @param executor the executor that runs tasks outside the FX application thread
* @param tasks factory invoked on the FX application thread to supply a fresh, ready task
* @param cancellable whether {@link #cancel()} may cancel a running execution
*/
public AsyncCommand(ObservableBooleanValue available, Executor executor, Supplier<? extends Task<T>> tasks,
boolean cancellable) {
Objects.requireNonNull(available);
this.executor = Objects.requireNonNull(executor);
this.tasks = Objects.requireNonNull(tasks);
this.cancellable = cancellable;
var canStart = Bindings.createBooleanBinding(() -> available.get() && !state.get().running()
&& state.get().phase() != Phase.CLOSED, available, state);
command = new Command(canStart, this::start);
}
/** Returns the current observation of the command. */
public State<T> getState() {
return state.get();
}
/** Returns a read-only property for observing progress and completion together. */
public ReadOnlyObjectProperty<State<T>> stateProperty() {
return state.getReadOnlyProperty();
}
/**
* Requests cancellation if this Command allows it. The worker slot stays occupied until
* the Task's worker has left, including when it needs time to handle interruption.
*
* @return whether a cancellation request was accepted
*/
public boolean cancel() {
var execution = current;
if (!cancellable || execution == null) return false;
if (execution.task != null) return execution.task.cancel();
finish(execution, State.of(Phase.CANCELLED));
return true;
}
/**
* Ends observation and disables the Command. A running task retains its own lifetime.
* If a View owns cancellable work, call {@link #cancel()} explicitly before closing.
*/
@Override
public void close() {
if (getState().phase() == Phase.CLOSED) return;
var execution = current;
current = null;
if (execution != null) execution.detach();
state.set(State.of(Phase.CLOSED));
}
private void start() {
if (current != null || getState().phase() == Phase.CLOSED) return;
var execution = new Execution();
current = execution;
state.set(State.of(Phase.RUNNING));
if (current != execution) return;
try {
var task = Objects.requireNonNull(tasks.get(), "Task factory returned null");
if (current != execution) return;
if (task.getState() != Worker.State.READY) {
throw new IllegalArgumentException("Task factory must return a fresh Task");
}
execution.attach(task);
executor.execute(execution::run);
} catch (RuntimeException failure) {
finish(execution, new State<>(Phase.FAILED, null, failure, -1, ""));
}
}
private void finish(Execution execution, State<T> terminal) {
if (current != execution) return;
current = null;
execution.detach();
state.set(terminal);
}
/** Identifies one execution, with FX-thread observations and a worker-thread completion flag. */
private final class Execution {
private Task<T> task;
private final AtomicBoolean working = new AtomicBoolean();
private final InvalidationListener progress = ignored -> {
if (current == this) state.set(observation(Phase.RUNNING, null, null));
};
private final ChangeListener<Worker.State> phase = (observable, before, after) -> {
if (current != this) return;
switch (after) {
case SUCCEEDED -> finish(this, observation(Phase.SUCCEEDED, task.getValue(), null));
case FAILED -> finish(this, observation(Phase.FAILED, null, task.getException()));
case CANCELLED -> finishCancellation();
default -> { }
}
};
private void attach(Task<T> started) {
task = started;
started.progressProperty().addListener(progress);
started.messageProperty().addListener(progress);
started.stateProperty().addListener(phase);
}
private void run() {
working.set(true);
try {
task.run();
} finally {
working.set(false);
if (task.isCancelled()) Platform.runLater(this::finishCancellation);
}
}
private void finishCancellation() {
if (current == this && !working.get()) {
finish(this, observation(Phase.CANCELLED, null, null));
}
}
private State<T> observation(Phase phase, T result, Throwable error) {
return new State<>(phase, result, error, task.getProgress(), task.getMessage());
}
private void detach() {
if (task != null) {
task.progressProperty().removeListener(progress);
task.messageProperty().removeListener(progress);
task.stateProperty().removeListener(phase);
}
}
}
}
@@ -94,6 +94,8 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
}
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this);
private final ReadOnlyObjectWrapper<GridSelection<K, T>> selection =
new ReadOnlyObjectWrapper<>(GridSelection.empty());
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ReadOnlyListWrapper<K> selectedKeys = new ReadOnlyListWrapper<>(
@@ -292,6 +294,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
renderer.enableColumnSeparators();
selectedKey.bind(renderer.selectedKeyProperty());
selectedElement.bind(renderer.selectedElementProperty());
selection.bind(renderer.selectionProperty());
coordinator =
new GridCoordinator<>(
source, Platform::runLater, this::changed, result -> publishRows(result));
@@ -395,6 +398,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
public ReadOnlyListProperty<T> selectedElementsProperty() { return selectedElements.getReadOnlyProperty(); }
/**
* Observes selection as one snapshot from the current state, including before the first load.
* The caller owns the adapter and closes it when the observing ViewModel stops using it.
*
* @return an independently closeable selection adapter for this grid
*/
public DataGridSelection<K, T> observeSelection() {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
return new DataGridSelection<>(this, selection.getReadOnlyProperty());
}
public void selectKeys(Collection<? extends K> keys) {
check();
renderer.selectKeys(keys);
@@ -1339,6 +1354,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
if (renderer != null) renderer.close();
selectedKey.unbind();
selectedElement.unbind();
selection.unbind();
selectedKeys.unbind();
selectedElements.unbind();
selectedKeys.set(FXCollections.emptyObservableList());
@@ -21,6 +21,12 @@ public final class DataGridColumn {
@Setter(lombok.AccessLevel.NONE)
private final java.util.Map<String, String> groupLabels = new java.util.LinkedHashMap<>();
/** Adds one FXML group label whose key can contain spaces, paths or other non-name characters. */
public static void setGroupLabel(DataGridColumn column, javafx.util.Pair<String, String> entry) {
column.groupLabels.put(java.util.Objects.requireNonNull(entry.getKey(), "group key"),
java.util.Objects.requireNonNull(entry.getValue(), "group label"));
}
private double width = 150;
private double minimumWidth = 80;
private double maximumWidth = 1200;
@@ -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;
}
}
@@ -5,6 +5,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import javafx.beans.InvalidationListener;
import javafx.beans.property.Property;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
@@ -58,7 +59,8 @@ final class DirectBindingApplier {
return;
}
if (attribute.getValue() instanceof ObservableList<?> values) {
assignList(controlProperty, values, lifetime);
if ("view".equals(binding.getDirection())) alignTowardView(controlProperty, attribute, lifetime);
else assignList(controlProperty, values, lifetime);
return;
}
String converterName = binding.getConverter();
@@ -551,8 +553,17 @@ final class DirectBindingApplier {
private static void alignTowardView(Property<?> controlProperty, ObservableValue<?> attribute,
ViewLifetime lifetime) {
Property<Object> control = (Property<Object>) controlProperty;
Object previous = control.getValue();
control.setValue(attribute.getValue());
lifetime.listen(attribute, (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);
});
}
/**
@@ -0,0 +1,45 @@
package de.neitzel.fx.view;
import java.util.List;
import java.util.Objects;
/**
* One published selection of a grid. Keys retain their selection order and can include keys outside
* the current page. Elements follow the grid's display order and contain only available selected
* rows. The lead element is null when the lead key has no available row.
*
* @param selectedKeys selected keys, including retained off-page keys
* @param selectedElements selected models of visible and interactive rows
* @param leadKey lead key, or null for an empty selection
* @param leadElement lead model, or null when unavailable
* @param <K> row key type
* @param <T> row model type
*/
public record GridSelection<K, T>(
List<K> selectedKeys, List<T> selectedElements, K leadKey, T leadElement) {
/** Copies both lists so a published selection remains stable as the grid changes. */
public GridSelection {
selectedKeys = List.copyOf(selectedKeys);
selectedElements = List.copyOf(selectedElements);
}
static <K, T> GridSelection<K, T> empty() {
return new GridSelection<>(List.of(), List.of(), null, null);
}
/** A refreshed row can replace an equal model with a different instance. */
boolean sameSelection(GridSelection<K, T> previous) {
if (!selectedKeys.equals(previous.selectedKeys) || !Objects.equals(leadKey, previous.leadKey)
|| leadElement != previous.leadElement
|| selectedElements.size() != previous.selectedElements.size()) {
return false;
}
for (int index = 0; index < selectedElements.size(); index++) {
if (selectedElements.get(index) != previous.selectedElements.get(index)) {
return false;
}
}
return true;
}
}
@@ -41,6 +41,8 @@ public final class TableResults<K, T> implements AutoCloseable {
private List<String> order;
private final Set<String> hiddenColumns = new HashSet<>();
private List<Entry<K, T>> entries = List.of();
private final ReadOnlyObjectWrapper<GridSelection<K, T>> selection =
new ReadOnlyObjectWrapper<>(GridSelection.empty());
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ObservableList<K> selectedKeys = FXCollections.observableArrayList();
@@ -131,6 +133,10 @@ public final class TableResults<K, T> implements AutoCloseable {
/** Only selected models currently visible and interactive are actionable. */
public ReadOnlyListProperty<T> selectedElementsProperty() { return elementsView.getReadOnlyProperty(); }
ReadOnlyObjectProperty<GridSelection<K, T>> selectionProperty() {
return selection.getReadOnlyProperty();
}
public RowSelectionMode getSelectionMode() { return selectionMode; }
public void setSelectionMode(RowSelectionMode mode) {
@@ -623,6 +629,10 @@ public final class TableResults<K, T> implements AutoCloseable {
}
selectedElement.set(rowsInteractive ? loaded : null);
selectedElements.setAll(actionable);
GridSelection<K, T> snapshot = new GridSelection<>(
selectedKeys, selectedElements, selectedKey.get(), selectedElement.get());
if (!snapshot.sameSelection(selection.get())) selection.set(snapshot);
}
public void setOnLayoutCommitted(Runnable handler) {
@@ -980,6 +990,7 @@ public final class TableResults<K, T> implements AutoCloseable {
selectedElement.set(null);
selectedKeys.clear();
selectedElements.clear();
selection.set(GridSelection.empty());
anchor = null;
captured = GroupProjection.capture(List.of(), List.of());
groupTree = List.of();
@@ -94,6 +94,32 @@ public final class ViewLoader {
return load(fxml, model, context, models.openView());
}
/**
* Opens a Component's own fx:root document with the supplied Model. The Component selects
* its ViewModel in the same context as its nested Views. Closing the result detaches its
* bindings and releases its controller and children.
*
* @param type the injected Component class with a sibling ClassName.fxml
* @param model the initial non-null Model
* @param context the application container
* @param models the owner of the View and its Model identity
* @return the initialized Component and its effective ViewModel
*/
public static LoadedView loadComponent(Class<? extends Parent> type, Object model,
ApplicationContext context, ViewModelContext models) {
java.util.Objects.requireNonNull(model, "Component Model");
ViewLifetime lifetime = models.openView();
try {
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);
throw failure;
}
}
private static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewLifetime lifetime) {
LoadSession session = LoadSession.nest();
try {
@@ -62,6 +62,39 @@ class HtmlViewerTest {
return (javafx.scene.control.Button) viewer.lookup(".html-viewer-media-load");
}
@Test void boundLocalTextReplacesPendingWorkAndDetachesOnClose() throws Exception {
var ref = new AtomicReference<HtmlViewer>();
var source = new javafx.beans.property.SimpleStringProperty("<p>First</p>");
var replacement = new javafx.beans.property.SimpleStringProperty("<p>Second</p>");
fx(() -> {
var viewer = new HtmlViewer();
ref.set(viewer);
viewer.htmlProperty().bind(source);
viewer.htmlProperty().bind(replacement);
source.set("<p>Detached</p>");
replacement.set("<p>Third</p>");
});
var viewer = ref.get();
try {
await(() -> !viewer.isLoading() && loaded(viewer) && browser(viewer).getEngine().getDocument()
.getDocumentElement().getTextContent().contains("Third"));
fx(() -> {
viewer.clear();
assertEquals("<p>Third</p>", replacement.get());
replacement.set(null);
replacement.set(" ");
assertNull(viewer.getError());
assertFalse(viewer.isExternalImagesAllowed());
replacement.set("<p>Pending</p>");
viewer.close();
assertFalse(viewer.htmlProperty().isBound());
replacement.set("<p>Too late</p>");
assertFalse(viewer.isLoading());
assertEquals("<p>Pending</p>", viewer.getHtml());
});
} finally { fx(viewer::close); }
}
@Test void ordinaryFxmlConstructsAnIdleLocalizableControl() throws Exception {
fx(() -> {
var loader = new javafx.fxml.FXMLLoader();
@@ -9,125 +9,53 @@ import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
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.control.TextArea;
import javafx.scene.input.MouseButton;
import javafx.scene.robot.Robot;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
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.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. */
class ActivateDockingWindowTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void activatingTheSameContentInABackgroundWindowReportsApplied() throws Exception {
AtomicReference<Fixture> state = new AtomicReference<>();
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage main = new Stage();
Stage main = spy(new Stage());
main.setScene(new Scene(pane, 480, 280));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea editor = new TextArea("Unsaved text");
Dockable dockable = new Dockable(new DockableId("notes"), editor);
manager.open(dockable, DockTarget.area("editors"));
Stage other = new Stage();
other.setScene(new Scene(new TextArea("Other window"), 240, 160));
state.set(new Fixture(main, other, manager, dockable));
main.show();
// Only the desktop's window state is simulated. Selection, scene focus and
// the activation result all come from the real controls and manager.
doReturn(true).when(main).isShowing();
doReturn(true).when(main).isFocused();
manager.activate(dockable.getId());
});
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();
});
}
}
assertSame(dockable, manager.activeDockable());
assertSame(editor, main.getScene().getFocusOwner());
assertInstanceOf(ActionResult.NoChange.class, manager.activate(dockable.getId()));
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);
doReturn(false).when(main).isFocused();
clearInvocations(main);
assertInstanceOf(ActionResult.Applied.class, manager.activate(dockable.getId()));
verify(main).requestFocus();
});
}
}
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();
}
}
}
@@ -55,6 +55,22 @@ class DataGridFxmlTest {
</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
void loadsReusableTagAndCompletionControls() throws Exception {
DataGridTest.fx(() -> {
@@ -0,0 +1,62 @@
package de.neitzel.fx.view;
import de.neitzel.fx.control.AutoCompleteTextField;
import de.neitzel.injection.ApplicationContext;
import java.util.Map;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.ComboBox;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ListSourceBindingTest {
public static class Tags {
private final ListProperty<String> tags =
new SimpleListProperty<>(FXCollections.observableArrayList("First"));
public ListProperty<String> tagsProperty() { return tags; }
}
@BeforeAll static void toolkit() throws Exception { DataGridTest.start(); }
@Test void viewBindingTracksEqualListReplacementAndRestoresThePreviousItems() throws Exception {
DataGridTest.fx(() -> {
var model = new Tags();
var combo = new ComboBox<String>();
var previous = combo.getItems();
var binding = new DirectBinding();
binding.setControl("combo");
binding.setProperty("items");
binding.setPath("tags");
binding.setDirection("view");
try (var models = new ViewModelContext(); var lifetime = new ViewLifetime(models)) {
DirectBindingApplier.apply(Map.of("combo", combo), model, binding, new ApplicationContext(Tags.class), lifetime);
assertSame(model.tags.get(), combo.getItems());
var replacement = FXCollections.observableArrayList("First");
model.tags.set(replacement);
assertSame(replacement, combo.getItems());
model.tags.set(null);
assertNull(combo.getItems());
}
assertSame(previous, combo.getItems());
model.tags.set(FXCollections.observableArrayList("Detached"));
assertSame(previous, combo.getItems());
});
}
@Test void ordinaryJavaFxBindingReturnsToFixedSuggestionsOnUnbind() throws Exception {
DataGridTest.fx(() -> {
var field = new AutoCompleteTextField();
field.getSuggestions().add("Fixed");
var model = new Tags();
field.suggestionsSourceProperty().bind(model.tags);
assertSame(model.tags.get(), field.getSuggestionsSource());
field.suggestionsSourceProperty().unbind();
assertNull(field.getSuggestionsSource());
model.tags.set(FXCollections.observableArrayList("Detached"));
assertNull(field.getSuggestionsSource());
assertEquals(java.util.List.of("Fixed"), field.getSuggestions());
});
}
}
@@ -93,6 +93,26 @@ class ManagedViewTest {
});
}
@Test
void opensAComponentDirectlyAndDetachesOnlyItsOwnBindings() throws Exception {
FxThread.onFx(() -> {
var model = new Address("Main");
var services = new ApplicationContext("de.neitzel.fx.view.component");
var type = de.neitzel.fx.view.component.AddressForm.class;
try (var models = new ViewModelContext()) {
var first = ViewLoader.loadComponent(type, model, services, models);
var second = ViewLoader.loadComponent(type, model, services, models);
assertSame(first.getViewModel(), second.getViewModel());
var input = field(first.getRoot(), "#streetField");
input.setText("Shared");
assertEquals("Shared", field(second.getRoot(), "#streetField").getText());
first.close();
input.setText("Detached");
assertEquals("Shared", model.getStreet());
}
});
}
@Test
void removingARepeatChildDetachesItsBindings() throws Exception {
FxThread.onFx(() -> {
@@ -0,0 +1,144 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.DataGridTest.Item;
import de.neitzel.grid.TextFilter;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.Label;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ObserveGridSelectionTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
}
@Test
void publishesOneCoherentChangeToTheViewAndStopsAfterClose() throws Exception {
var first = new Item(1, "Alpha");
var second = new Item(2, "Beta");
var grid = new AtomicReference<DataGrid<Long, Item>>();
FxThread.onFx(() -> {
grid.set(DataGridTest.grid(List.of(first, second), new AtomicInteger()));
grid.get().refresh();
});
try {
DataGridTest.drain();
FxThread.onFx(() -> {
var control = grid.get();
control.select(1L);
var document = getClass().getResource("grid-selection-summary.fxml");
var context = new ApplicationContext("de.neitzel.fx.view.selection");
try (var selection = control.observeSelection();
var models = new ViewModelContext();
var view = ViewLoader.load(document, selection, context, models)) {
var initial = selection.getSelection();
var summary = (Label) view.getRoot().lookup("#summary");
assertEquals(List.of(1L), initial.selectedKeys());
assertEquals(List.of(first), initial.selectedElements());
assertEquals("[1] · 1 visible", summary.getText());
assertThrows(UnsupportedOperationException.class, () -> initial.selectedKeys().clear());
assertThrows(UnsupportedOperationException.class, () -> initial.selectedElements().clear());
var changes = new ArrayList<GridSelection<Long, Item>>();
selection.selectionProperty().addListener((observable, before, after) -> {
changes.add(after);
selection.selectKeys(after.selectedKeys());
});
var liveKeys = control.selectedKeysProperty().get();
selection.select(2L);
assertSame(liveKeys, control.selectedKeysProperty().get());
assertEquals(List.of(new GridSelection<>(List.of(2L), List.of(second), 2L, second)), changes);
assertEquals("[2] · 1 visible", summary.getText());
assertEquals(List.of(first), initial.selectedElements());
selection.close();
selection.close();
control.select(1L);
assertEquals("[2] · 1 visible", summary.getText());
assertEquals(1, changes.size());
assertEquals(List.of(1L), control.selectedKeysProperty());
assertThrows(IllegalStateException.class, () -> selection.select(2L));
}
});
} finally {
FxThread.onFx(() -> grid.get().close());
}
}
@Test
void keepsUnloadedKeysThroughPagingFiltersDeletionAndRestoration() throws Exception {
var first = new Item(1, "Alpha");
var second = new Item(2, "Beta");
var items = new ArrayList<>(List.of(first, second));
var grid = new AtomicReference<DataGrid<Long, Item>>();
var selected = new AtomicReference<DataGridSelection<Long, Item>>();
FxThread.onFx(() -> {
var control = DataGridTest.grid(items, new AtomicInteger());
grid.set(control);
control.setSelectionMode(RowSelectionMode.MULTIPLE);
selected.set(control.observeSelection());
assertEquals(GridSelection.empty(), selected.get().getSelection());
control.setPageSize(1);
});
try {
DataGridTest.drain();
FxThread.onFx(() -> {
var adapter = selected.get();
adapter.selectKeys(List.of(1L, 2L));
var current = adapter.getSelection();
assertEquals(List.of(1L, 2L), current.selectedKeys());
assertEquals(List.of(first), current.selectedElements());
assertEquals(2L, current.leadKey());
assertNull(current.leadElement());
grid.get().next();
assertEquals(List.of(), adapter.getSelection().selectedElements());
});
DataGridTest.drain();
FxThread.onFx(() -> {
var current = selected.get().getSelection();
assertEquals(List.of(1L, 2L), current.selectedKeys());
assertEquals(List.of(second), current.selectedElements());
assertSame(second, current.leadElement());
grid.get().setFilters(List.of(new TextFilter("text", TextFilter.Operator.EQUALS, "Alpha", false)));
});
DataGridTest.drain();
FxThread.onFx(() -> {
assertEquals(List.of(1L, 2L), selected.get().getSelection().selectedKeys());
assertEquals(List.of(first), selected.get().getSelection().selectedElements());
items.remove(first);
grid.get().confirmedDeleted(1L);
assertEquals(List.of(2L), selected.get().getSelection().selectedKeys());
grid.get().setFilters(List.of());
});
DataGridTest.drain();
FxThread.onFx(() -> {
var adapter = selected.get();
assertEquals(List.of(second), adapter.getSelection().selectedElements());
adapter.select(null);
assertEquals(GridSelection.empty(), adapter.getSelection());
adapter.selectKeys(List.of(2L));
assertSame(second, adapter.getSelection().leadElement());
grid.get().close();
assertEquals(GridSelection.empty(), adapter.getSelection());
});
} finally {
FxThread.onFx(() -> {
selected.get().close();
grid.get().close();
});
}
}
}
@@ -0,0 +1,25 @@
package de.neitzel.fx.view.selection;
import de.neitzel.fx.view.DataGridSelection;
import de.neitzel.fx.view.ViewModelClass;
import jakarta.inject.Singleton;
import javafx.beans.value.ObservableValue;
/** Supplies a read-only summary of the selected keys and available rows. */
@Singleton
@ViewModelClass(SelectionSummaryController.Summary.class)
public class SelectionSummaryController {
public static class Summary {
private final ObservableValue<String> summary;
public Summary(DataGridSelection<?, ?> selection) {
summary = selection.selectionProperty().map(state ->
state.selectedKeys() + " · " + state.selectedElements().size() + " visible");
}
public ObservableValue<String> summaryProperty() {
return summary;
}
}
}
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1"
fx:controller="de.neitzel.fx.view.selection.SelectionSummaryController">
<fx:define>
<BindingList>
<DirectBinding control="summary" property="text" path="summary" direction="view"/>
</BindingList>
</fx:define>
<Label fx:id="summary"/>
</VBox>
+3 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>gson</artifactId>
@@ -20,6 +20,8 @@
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency Versions -->
<!-- Dependency versions -->
<gson.version>2.15.0</gson.version>
</properties>
+3 -3
View File
@@ -8,13 +8,13 @@ The worked example is the person desk in `fx-example`, package `de.neitzel.fx.ex
## Quick start
Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0.1 (plus shared logging dependencies). The parent artifact is `de.neitzel.lib:neitzellib:1.0.4`. Java 25.
Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0.1 (plus shared logging dependencies). The parent artifact is `de.neitzel.lib:neitzellib:1.0.6`. Java 25.
```xml
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>injection</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</dependency>
```
@@ -175,7 +175,7 @@ It does not match qualifiers, read `@Named` values, inject by name, bind configu
## A standalone service example
Injection does not require a JavaFX application or toolkit. After installing the local snapshot as described in the [complete Maven quick start](../fx/docs/quick-start.md), use the dependency above and put these public types in separate files in the same `example.services` package:
Injection does not require a JavaFX application or toolkit. After installing the library as described in the [complete Maven quick start](../fx/docs/quick-start.md), use the dependency above and put these public types in separate files in the same `example.services` package:
```java
package example.services;
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>injection</artifactId>
+3 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>log4j</artifactId>
@@ -20,6 +20,8 @@
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency Versions -->
<!-- Dependency versions -->
<log4j.version>1.2.17</log4j.version>
</properties>
+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>net</artifactId>
+15 -13
View File
@@ -6,7 +6,7 @@
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
<packaging>pom</packaging>
@@ -24,6 +24,7 @@
<module>data-grid</module>
<module>data-grid-jdbc</module>
<module>fx</module>
<module>fx-test</module>
<module>fx-example</module>
<module>gson</module>
<module>net</module>
@@ -35,7 +36,16 @@
<java.version>25</java.version>
<required.maven.version>3.9.11</required.maven.version>
<!-- other properties -->
<pmd.target>pmd</pmd.target>
<spotbugs.target>spotbugs</spotbugs.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.release>${java.version}</maven.compiler.release>
<!-- Dependency versions -->
<h2.version>2.5.252</h2.version>
<jakarta-inject-api>2.0.1</jakarta-inject-api>
<javafx.version>27.0.1</javafx.version>
<jetbrains.annotations.version>26.1.0</jetbrains.annotations.version>
@@ -45,10 +55,11 @@
<reflections.version>0.10.2</reflections.version>
<slf4j.version>2.0.20</slf4j.version>
<!-- Plugin dependencies -->
<!-- Plugin versions -->
<codehaus.version.plugin>2.25.2</codehaus.version.plugin>
<javafx.maven.plugin>0.0.8</javafx.maven.plugin>
<jpackage.maven.plugin>0.1.5</jpackage.maven.plugin>
<lombok.maven.plugin>1.18.20.0</lombok.maven.plugin>
<maven.clean.plugin>3.5.0</maven.clean.plugin>
<maven.compiler.plugin>3.16.0</maven.compiler.plugin>
<maven.dependency.plugin>3.11.0</maven.dependency.plugin>
@@ -57,23 +68,14 @@
<maven.install.plugin>3.2.0</maven.install.plugin>
<maven.jar.plugin>3.5.1</maven.jar.plugin>
<maven.javadoc.plugin>3.12.0</maven.javadoc.plugin>
<maven.pmd.plugin>3.28.0</maven.pmd.plugin>
<maven.project.info.reports.plugin>3.9.0</maven.project.info.reports.plugin>
<maven.resources.plugin>3.5.0</maven.resources.plugin>
<maven.shade.plugin>3.5.3</maven.shade.plugin>
<maven.site.plugin>4.0.0-M16</maven.site.plugin>
<maven.surfire.plugin>3.6.1</maven.surfire.plugin>
<moditect.maven.plugin>1.0.0.RC2</moditect.maven.plugin>
<maven.pmd.plugin>3.28.0</maven.pmd.plugin>
<spotbugs.maven.plugin>4.10.5.0</spotbugs.maven.plugin>
<!-- other properties -->
<pmd.target>pmd</pmd.target>
<spotbugs.target>spotbugs</spotbugs.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.release>${java.version}</maven.compiler.release>
</properties>
<dependencyManagement>
@@ -280,7 +282,7 @@
<plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>1.18.20.0</version>
<version>${lombok.maven.plugin}</version>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
+2 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.4</version>
<version>1.0.6</version>
</parent>
<artifactId>quarkus</artifactId>
@@ -19,6 +19,7 @@
<appName>${project.artifactId}</appName>
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency versions -->
<quarkus.platform.version>3.40.1.2</quarkus.platform.version>
</properties>