Add compatible DataGrid, filter editors, themes and JDBC example

This commit is contained in:
2026-11-16 17:29:19 +01:00
parent a35664dabe
commit 889846ca19
102 changed files with 10970 additions and 14 deletions
+4
View File
@@ -17,6 +17,10 @@ The [complete workspace](../fx/docs/docking-workspace.md) combines Java/FXML sta
plain or optional MVVM editors, real application-owned JSON storage, floating-window
restoration, reset and all-consent shutdown with Retry/Cancel and manager replacement.
The [shared theme gallery](docs/theme-gallery.md) demonstrates opt-in light, dark and high-contrast styles, live window propagation and measured control-state contrast.
The [product DataGrid demonstration](docs/product-grid.md) adds equivalent memory/H2 sources, saved setups, themes, mutation and request-failure scenarios through a separate launcher.
## Build and run
From the NeitzelLib root with JDK 25:
+34
View File
@@ -0,0 +1,34 @@
# Product DataGrid: memory and H2
This separate launcher uses the accepted DataGrid APIs without changing the person-desk application or legacy Table behavior. The application owns an embedded H2 **2.5.252** pool, its anchor connection, a four-worker executor, completion timer, immutable product fixtures and saved setup file. No server, credentials or stored procedures are needed. JDBC is in the optional `data-grid-jdbc` module; H2 remains example-owned.
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-SNAPSHOT.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
```
The default catalog has 10,000 products. Both backends use identical stable IDs, names, categories, quantities and DECIMAL(12,2) prices. Fixtures include duplicate sort values, nulls, empty text, mixed case, Unicode, apostrophes and literal SQL wildcard characters. One `ProductCatalog` service maintains original text and Locale.ROOT comparison keys together on insertion/reset. Mutations run on application workers and explicitly refresh the grid; browsing is read-only.
## Interactive walkthrough
1. Browse 50 rows initially. Use header sorting and first/previous/next/last, then choose 25/100/250. Name filtering has a developer-configured **current-page** checklist; its scope is shown by the editor, and candidate values are exact originals. Other columns use comparison/missing modes. Source-wide checklist configuration remains available through the provider API but is not silently inferred here.
2. Open text/quantity/price filters. `%`, `_`, `!` and apostrophes are literal. Try a decimal range, empty text equality, missing prices and an empty checklist. Toggle **Custom budget editor** to use a separate FXML/controller that emits the same portable numeric condition. It runs on both sources and persists with the built-in numeric codec.
3. Select **Memory**, then **Memory-only filter** (names of at most five UTF-16 units). Switch to H2: the condition is rejected visibly, the previous result remains, and no SQL silently substitutes different behavior. Clear filters, then switch again. Saving a memory-only condition is also rejected because no codec is registered.
4. Toggle outside-click acceptance and OK/Cancel independently of the editor. Enter/Escape use the existing popup lifecycle. Native input qualification remains under the previously recorded waiver; these options do not claim a new OS-input qualification.
5. Choose a theme, select a row, widen Name or move Price first. **Save setup** writes atomically to `~/.neitzellib-example/products-setup.json`; **Load setup** decodes/validates and stages its layout/query atomically. Invalid JSON, unsupported versions/conditions and execution failures are visible and retain committed layout/data. Setup data never contains credentials, row data, selection or warning approval. **Load v1 setup** demonstrates an explicit migration from the former `group` column to `category`, updating column order, sort and text/checklist/missing conditions before querying the current definition version 2.
6. Choose **All**. Above the configurable default threshold of 1,000 matches, Continue/Cancel explains that all matching rows become real Components, consuming memory and potentially blocking responsiveness. Exactly the threshold does not warn. Cancel retains the previous setup/page. Loading a saved All setup asks again. Filtering, source switching or a newer request invalidates old approval. No connection stays borrowed while waiting for an answer.
7. Use **Slow next refresh** to inspect loading while old rows remain unavailable. **Fail next refresh** exposes the error; Retry succeeds normally. **Late success then failure** leaves the later failure visible. **Late failure then success** leaves the later success visible. These are deterministic completion delays/failures around real requests, not simulated SQL slowness; cancel-resistant completions deliberately exercise stale-result rejection.
8. Open **Request diagnostics** for local request IDs, requested/displayed pages, duration, row count, cancellation and obsolete completions. Source IDs restart for each wrapper; the selected source and coordinator generation disambiguate them.
9. Insert/delete selected/reset fixtures and refresh. Navigate to the last page and **Delete displayed page** to exercise bounded recovery when that page disappears. Deletion updates both datasets; this is demonstration tooling, not a CRUD framework.
## Qualification and limits
`JdbcProductTest` compares memory/SQL results for every supported condition/operator, exact membership, Unicode ordering, ties, boundaries, nulls and decimals. It injects a writer between count and row queries, observes borrowed resources/settings, checks cancellation and mapper failure, rejects invalid mappings before connection acquisition, and verifies the All warning race with a changed dataset.
`ProductGridDemoTest` loads real row/editor FXML, switches sources/themes, tests saving/restoring, visible capability errors, late responses, Retry, disappearing pages, cancelled/superseded All decisions and restored-All warnings. It measures an explicitly approved 10,000-row FXML materialization. New FX tests capture uncaught application-thread errors.
Outputs are `target/jdbc-evidence/{timings.txt,fx-materialization.txt,demo.png}`. Source timings include the full source query but exclude UI Components; the FX timing includes All confirmation scheduling, query and UI publication. These are single-run observations, not benchmarks or scale guarantees. Offset paging can require scanning/sorting earlier rows. All mode is unvirtualized and its render cost is substantially greater than a page. The optional 100,000-row run is not part of this qualification.
H2's default collation and snapshot behavior are the qualified database semantics. No claim covers other dialects, linguistic collation, JPA/Hibernate, arbitrary joins, date/time filters or arbitrary application overrides.
+22
View File
@@ -0,0 +1,22 @@
# Shared theme gallery
`de.neitzel.fx.example.theme.ThemeGalleryMain` opens the opt-in Light/Dark/High contrast gallery. It includes normal/hover/focus/disabled buttons, text edits, invalid/error/warning messages, check/radio/combo/date controls, a selected standard TableView, a filtered/selected DataGrid, a loading indicator, dialogs and floating editors.
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-SNAPSHOT.jar:fx-example/target/libs/*' \
de.neitzel.fx.example.theme.ThemeGalleryMain
```
Choose a theme in the top selector. Open a filter editor through the funnel button, a dialog or floating editor, and edit text. Theme changes preserve model/query/selection/layout and text drafts; an ordinary outside click still follows the filter popup's dismissal policy. API-driven switching while a draft is open is tested independently of that policy. The hover/focus buttons are labelled CSS-state specimens; they do not pretend to be native-input tests.
FILE/LIVE/REMOVE are example textual indicators which remain readable under selection. They are not a qualification of DNSCheck's actual domain palette, legends or workflows; that work remains in its integration ticket.
## Automated rendered evidence
`ThemeGalleryTest` writes `target/theme-gallery/light.png`, `dark.png`, `high-contrast.png`, matching popup images, `contrast.txt` and `window-contrast.txt`. The tests read actual JavaFX paints/backgrounds after CSS resolution, enforce the agreed contrast targets, check stable button dimensions and preserved grid/draft state, and fail on uncaught FX-thread errors. Main and popup snapshots are visually reviewed for clipping, focus/state distinctions and readability. The workspace implementation ticket stores durable copies and the qualified runtime baseline.
`ThemeManagerTest` covers opt-in behavior, application overrides, scene-root replacement, rollback across scenes, unavailable saved themes, live filter/nested-popup/dialog propagation, new-window registration, docking floating windows and cleanup. Existing legacy Table/docking tests remain in verification.
See [theme API and customization](../../fx/docs/themes.md) for ownership, CSS precedence, public palette/hooks and failure limitations. Application overrides, other fonts/scales/platforms, SubScene and HTML content need separate qualification.
+2
View File
@@ -21,6 +21,8 @@
</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>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
@@ -0,0 +1,21 @@
package de.neitzel.fx.example.grid;
/** Best-effort release of independent application-owned resources, preserving failures. */
final class DemoResources {
private DemoResources() {}
static void closeAll(AutoCloseable... resources) {
RuntimeException failure = null;
for (var resource : resources) {
if (resource == null) continue;
try {
resource.close();
} catch (Exception error) {
if (failure == null)
failure = new IllegalStateException("Could not release demo resources", error);
else failure.addSuppressed(error);
}
}
if (failure != null) throw failure;
}
}
@@ -0,0 +1,129 @@
package de.neitzel.fx.example.grid;
import de.neitzel.grid.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.Consumer;
/**
* Demo-only controlled completion delays. No sleeps, driver interruption or altered SQL semantics.
*/
public final class DiagnosticSource implements GridSource<Long, Product> {
private final GridSource<Long, Product> delegate;
private final ScheduledExecutorService clock;
private final Consumer<String> log;
private final Consumer<FilterCondition> domainValidation;
private final AtomicLong ids = new AtomicLong();
private volatile long delay;
private volatile boolean fail, late;
public DiagnosticSource(
GridSource<Long, Product> delegate,
ScheduledExecutorService clock,
Consumer<String> log,
Consumer<FilterCondition> domainValidation) {
this.delegate = delegate;
this.clock = clock;
this.log = log;
this.domainValidation = domainValidation;
}
public void next(long milliseconds, boolean failure, boolean deliverAfterCancel) {
delay = milliseconds;
fail = failure;
late = deliverAfterCancel;
}
public SourceCapabilities capabilities() {
return delegate.capabilities();
}
public String filterExecutionId() {
return delegate.filterExecutionId();
}
public void validateFilter(FilterCondition condition) {
domainValidation.accept(condition);
delegate.validateFilter(condition);
}
public QueryExecution<Long, Product> query(GridQuery query) {
return query(query, QueryOptions.defaults());
}
public QueryExecution<Long, Product> query(GridQuery query, QueryOptions options) {
long id = ids.incrementAndGet(), started = System.nanoTime(), wait = delay;
boolean failure = fail, ignoreCancel = late;
next(0, false, false);
var result = new CompletableFuture<PageResult<Long, Product>>();
var cancelled = new AtomicBoolean();
log.accept("Request " + id + " requested " + query.page());
try {
query.filters().forEach(this::validateFilter);
} catch (RuntimeException error) {
result.completeExceptionally(error);
return new QueryExecution<>() {
public CompletionStage<PageResult<Long, Product>> result() {
return result;
}
public void cancel() {
result.cancel(false);
}
};
}
var execution = delegate.query(query, options);
execution
.result()
.whenComplete(
(page, error) -> {
try {
clock.schedule(
() -> {
log.accept(
"Request "
+ id
+ " "
+ (cancelled.get()
? "obsolete completion"
+ " (coordinator must"
+ " ignore)"
: "completion")
+ " "
+ ((System.nanoTime() - started)
/ 1_000_000)
+ " ms; rows="
+ (page == null
? 0
: page.rows().size()));
if (error != null) result.completeExceptionally(error);
else if (failure)
result.completeExceptionally(
new IllegalStateException(
"Injected query failure; Retry runs"
+ " normally"));
else result.complete(page);
},
wait,
TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException rejected) {
result.completeExceptionally(rejected);
}
});
return new QueryExecution<>() {
public CompletionStage<PageResult<Long, Product>> result() {
return result;
}
public void cancel() {
cancelled.set(true);
log.accept("Request " + id + " cancellation requested");
if (!ignoreCancel) {
execution.cancel();
result.cancel(false);
}
}
};
}
}
@@ -0,0 +1,10 @@
package de.neitzel.fx.example.grid;
import de.neitzel.grid.FilterCondition;
/** Deliberately memory-only condition used to demonstrate visible backend rejection. */
public record LocalNameLength(String columnId) implements FilterCondition {
public String typeId() {
return "demo.name-length";
}
}
@@ -0,0 +1,66 @@
package de.neitzel.fx.example.grid;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.beans.property.*;
import javafx.fxml.*;
import javafx.scene.Parent;
import javafx.scene.control.TextField;
import java.io.IOException;
import java.math.BigDecimal;
/** Custom FXML editor emitting the portable numeric condition, executable on both backends. */
public final class PricePresetEditor implements FilterEditor {
@FXML private TextField maximum;
private Parent root;
private String column;
private final ReadOnlyStringWrapper validation = new ReadOnlyStringWrapper("");
public static PricePresetEditor load(FilterEditorContext context) {
try {
var loader =
new FXMLLoader(PricePresetEditor.class.getResource("PricePresetEditor.fxml"));
Parent root = loader.load();
PricePresetEditor editor = loader.getController();
editor.root = root;
editor.column = context.columnId();
if (context.committed() instanceof NumericFilter n)
editor.maximum.setText(n.operand().toPlainString());
editor.maximum.textProperty().addListener((o, a, b) -> editor.validate());
editor.validate();
return editor;
} catch (IOException e) {
throw new IllegalStateException("Cannot load price preset", e);
}
}
private void validate() {
try {
draft();
validation.set("");
} catch (RuntimeException e) {
validation.set(
"Enter an exact price with at most two decimal places (0–9,999,999,999.99)");
}
}
public FilterCondition draft() {
var price =
new BigDecimal(maximum.getText()).setScale(2, java.math.RoundingMode.UNNECESSARY);
if (price.signum() < 0 || price.precision() > 12)
throw new IllegalArgumentException("Price outside domain");
return new NumericFilter(column, NumericFilter.Operator.LESS_OR_EQUAL, price, null);
}
public Parent view() {
return root;
}
public ReadOnlyStringProperty validationMessageProperty() {
return validation.getReadOnlyProperty();
}
public void close() {}
}
@@ -0,0 +1,6 @@
package de.neitzel.fx.example.grid;
import java.math.BigDecimal;
/** Immutable demo row; no FX-owned state is read on a worker. */
public record Product(long id, String name, String category, Long quantity, BigDecimal price) {}
@@ -0,0 +1,237 @@
package de.neitzel.fx.example.grid;
import de.neitzel.grid.*;
import de.neitzel.grid.jdbc.*;
import org.h2.jdbcx.JdbcConnectionPool;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
/** Application-owned database, fixture service and execution pool. */
public final class ProductCatalog implements AutoCloseable {
public final ExecutorService workers;
public final JdbcConnectionPool database;
public final MemoryGridSource<Long, Product> memory;
public final JdbcGridSource<Long, Product> jdbc;
private List<Product> products = List.of();
private final int size;
// Keeps this in-memory database alive without DB_CLOSE_DELAY=-1 leaking it after close.
private final Connection anchor;
public ProductCatalog(int size) throws SQLException {
this(
size,
JdbcConnectionPool.create("jdbc:h2:mem:grid_" + UUID.randomUUID(), "sa", ""),
Executors.newFixedThreadPool(4));
}
ProductCatalog(int size, JdbcConnectionPool database, ExecutorService workers)
throws SQLException {
this.size = size;
this.database = Objects.requireNonNull(database);
this.workers = Objects.requireNonNull(workers);
Connection borrowed = null;
try {
borrowed = database.getConnection();
anchor = borrowed;
try (var s = anchor.createStatement()) {
s.execute(
"CREATE TABLE products (id BIGINT PRIMARY KEY, name VARCHAR(200), name_key"
+ " VARCHAR(250), category VARCHAR(100), category_key VARCHAR(120),"
+ " quantity BIGINT, price DECIMAL(12,2))");
}
reset();
memory =
new MemoryGridSource<>(
this::snapshot,
Product::id,
Long::compare,
memoryColumns(),
workers,
250);
jdbc =
new JdbcGridSource<>(
database,
workers,
JdbcDialect.h2(),
"products",
"id",
jdbcColumns(),
ProductCatalog::read,
250,
10);
} catch (SQLException | RuntimeException error) {
try {
DemoResources.closeAll(borrowed, database::dispose, workers::shutdown);
} catch (RuntimeException cleanup) {
error.addSuppressed(cleanup);
}
throw error;
}
}
public static List<Product> fixtures(int size) {
var rows = new ArrayList<Product>();
String[] specials = {
null,
"",
"Alpha",
"alpha",
"Äpfel",
"İstanbul",
"ß",
"ss",
"a%b",
"a_b",
"!literal",
"O'Reilly",
"😀",
"𐀀",
"",
"é",
"é",
" trailing "
};
for (int i = 1; i <= size; i++)
rows.add(
new Product(
i,
i <= specials.length ? specials[i - 1] : "Product " + (i % 137),
i % 17 == 0
? null
: List.of("Hardware", "Office", "Food", "").get(i % 4),
i % 19 == 0 ? null : (long) (i % 80),
i % 23 == 0 ? null : BigDecimal.valueOf(i % 10007, 2)));
return List.copyOf(rows);
}
public static List<JdbcColumn> jdbcColumns() {
return List.of(
JdbcColumn.integer("id", "id"),
JdbcColumn.text("name", "name", "name_key"),
JdbcColumn.text("category", "category", "category_key"),
JdbcColumn.integer("quantity", "quantity"),
JdbcColumn.decimal("price", "price", 12, 2));
}
public static List<MemoryColumn<Product>> memoryColumns() {
return List.of(
new MemoryColumn<>(
"id", MemoryColumn.Kind.INTEGER, p -> new FilterValue.IntegerValue(p.id())),
new MemoryColumn<>(
"name",
MemoryColumn.Kind.TEXT,
p -> p.name() == null ? null : new FilterValue.Text(p.name()),
Map.of(
"demo.name-length",
f -> {
if (!(f instanceof LocalNameLength))
throw new IllegalArgumentException(
"Wrong custom condition");
return v ->
v instanceof FilterValue.Text t
&& t.value().length() <= 5;
})),
new MemoryColumn<>(
"category",
MemoryColumn.Kind.TEXT,
p -> p.category() == null ? null : new FilterValue.Text(p.category())),
new MemoryColumn<>(
"quantity",
MemoryColumn.Kind.INTEGER,
p ->
p.quantity() == null
? null
: new FilterValue.IntegerValue(p.quantity())),
new MemoryColumn<>(
"price",
MemoryColumn.Kind.DECIMAL,
p -> p.price() == null ? null : new FilterValue.Decimal(p.price())));
}
public static GridRow<Long, Product> read(ResultSet rs) throws SQLException {
var p =
new Product(
rs.getLong("id"),
rs.getString("name"),
rs.getString("category"),
(Long) rs.getObject("quantity"),
rs.getBigDecimal("price"));
return new GridRow<>(p.id(), p);
}
public synchronized List<Product> snapshot() {
return products;
}
public synchronized void reset() throws SQLException {
replace(fixtures(size));
}
public synchronized void insert() throws SQLException {
var copy = new ArrayList<>(products);
long id = copy.stream().mapToLong(Product::id).max().orElse(0) + 1;
var p = new Product(id, "Inserted " + id, "Office", 1L, new BigDecimal("1.00"));
try (var c = database.getConnection()) {
insert(c, List.of(p));
}
copy.add(p);
products = List.copyOf(copy);
}
public synchronized void delete(long id) throws SQLException {
try (var c = database.getConnection();
var s = c.prepareStatement("DELETE FROM products WHERE id=?")) {
s.setLong(1, id);
s.executeUpdate();
}
products = products.stream().filter(p -> p.id() != id).toList();
}
private void replace(List<Product> rows) throws SQLException {
try (var c = database.getConnection()) {
c.setAutoCommit(false);
try (var s = c.createStatement()) {
s.executeUpdate("DELETE FROM products");
}
insert(c, rows);
c.commit();
}
products = List.copyOf(rows);
}
public static void insert(Connection c, List<Product> rows) throws SQLException {
try (var s = c.prepareStatement("INSERT INTO products VALUES (?,?,?,?,?,?,?)")) {
for (var p : rows) {
s.setLong(1, p.id());
s.setString(2, p.name());
s.setString(3, key(p.name()));
s.setString(4, p.category());
s.setString(5, key(p.category()));
s.setObject(6, p.quantity());
s.setBigDecimal(7, p.price());
s.addBatch();
}
s.executeBatch();
}
}
private static String key(String text) {
return text == null ? null : text.toLowerCase(Locale.ROOT);
}
public void close() {
workers.shutdown();
try {
if (!workers.awaitTermination(15, TimeUnit.SECONDS))
throw new IllegalStateException("Queries did not finish before database shutdown");
DemoResources.closeAll(anchor, database::dispose);
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new IllegalStateException(error);
}
}
}
@@ -0,0 +1,36 @@
package de.neitzel.fx.example.grid;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.nio.file.Path;
/** Standalone entry point; resources are application-owned and released on shutdown. */
public final class ProductGridApp extends Application {
private ProductCatalog catalog;
private ProductGridDemo demo;
public void init() throws Exception {
catalog = new ProductCatalog(10000);
}
public void start(Stage stage) {
demo =
new ProductGridDemo(
catalog,
Path.of(
System.getProperty("user.home"),
".neitzellib-example",
"products-setup.json"));
var scene = new Scene(demo, 1120, 820);
demo.install(scene);
stage.setScene(scene);
stage.setTitle("DataGrid — Memory and H2");
stage.show();
}
public void stop() {
DemoResources.closeAll(demo, catalog);
}
}
@@ -0,0 +1,438 @@
package de.neitzel.fx.example.grid;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.fx.theme.ThemeManager;
import de.neitzel.fx.view.*;
import de.neitzel.grid.*;
import de.neitzel.gson.grid.GridSetupJson;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import java.math.BigDecimal;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
/** Application-owned composition; existing person-desk launcher and legacy Table are unchanged. */
public final class ProductGridDemo extends VBox implements AutoCloseable {
public final DataGrid<Long, Product> grid;
public final ThemeManager themes = new ThemeManager();
public final ComboBox<String> sourcePicker = new ComboBox<>(), themePicker = new ComboBox<>();
public final TextArea diagnostics = new TextArea();
public final Label message = new Label();
public final ProductCatalog catalog;
private final ScheduledExecutorService clock = Executors.newSingleThreadScheduledExecutor();
private final DiagnosticSource memory, jdbc;
private DiagnosticSource requested;
private final GridSetupJson codec = new GridSetupJson();
private final Path setupFile;
private boolean closed;
public ProductGridDemo(ProductCatalog catalog, Path setupFile) {
this.catalog = catalog;
this.setupFile = setupFile;
setSpacing(8);
setStyle("-fx-padding: 12;");
memory =
new DiagnosticSource(
catalog.memory,
clock,
this::log,
condition -> {
if (!(condition instanceof LocalNameLength))
catalog.jdbc.validateFilter(condition);
});
jdbc = new DiagnosticSource(catalog.jdbc, clock, this::log, catalog.jdbc::validateFilter);
requested = jdbc;
grid =
new DataGrid<>(
List.of(
new ResultColumn("id", "ID", 80, 60, 140, -1),
new ResultColumn("name", "Name", 260, 120, 600, -1),
new ResultColumn("category", "Category", 150, 90, 300, -1),
new ResultColumn("quantity", "Quantity", 110, 80, 220, -1),
new ResultColumn("price", "Price", 120, 90, 240, -1)),
ProductRow::create,
jdbc);
grid.configureSetups(
"demo.products",
2,
Map.of(
"id",
"long.v1",
"name",
"text.v1",
"category",
"text.v1",
"quantity",
"long.v1",
"price",
"decimal12-2.v1"),
Map.of(1, ProductGridDemo::migrateLegacy));
var editors = FilterEditors.builtIns(Set.of("jdbc-h2"));
editors.register(
new FilterEditors.Registration(
"demo.budget",
new FilterCapabilities(true, true, Set.of("jdbc-h2")),
Set.of("neitzel.number"),
PricePresetEditor::load));
grid.setFilterEditors(editors);
var pageNames =
FilterCandidates.currentPage(
() -> {
var state = grid.stateProperty().get();
if (state.result() == null) return List.of();
return state.result().rows().stream()
.map(
row ->
new FilterCandidates.Candidate(
row.model().name() == null
? null
: new FilterValue.Text(
row.model().name()),
row.model().name() == null
? "(missing)"
: row.model().name()))
.toList();
});
grid.configureFilter(
"name",
FilterColumn.text().withChecklist(FilterColumn.Checklist.CURRENT_PAGE, pageNames));
grid.configureFilter("category", FilterColumn.text());
grid.configureFilter("quantity", FilterColumn.number(Locale.ROOT, true, null, null));
grid.configureFilter(
"price",
FilterColumn.number(
Locale.ROOT, false, BigDecimal.ZERO, new BigDecimal("9999999999.99")));
grid.configureFilter("id", FilterColumn.number(Locale.ROOT, true, BigDecimal.ONE, null));
sourcePicker.getItems().setAll("JDBC / H2", "Memory");
sourcePicker.setValue("JDBC / H2");
sourcePicker.setOnAction(
e -> {
requested = sourcePicker.getValue().equals("Memory") ? memory : jdbc;
grid.setSource(requested);
});
themePicker.getItems().setAll("light", "dark", "high-contrast");
themePicker.setValue("light");
themePicker.setOnAction(e -> themes.select(themePicker.getValue()));
var threshold = new Spinner<Integer>(0, 100000, 1000, 250);
threshold.setPrefWidth(110);
threshold.valueProperty().addListener((o, a, b) -> grid.setAllWarningThreshold(b));
var custom = new CheckBox("Custom budget editor");
custom.setOnAction(
e ->
grid.configureFilter(
"price",
custom.isSelected()
? new FilterColumn(
"demo.budget",
Locale.ROOT,
false,
false,
BigDecimal.ZERO,
new BigDecimal("9999999999.99"),
FilterColumn.Checklist.DISABLED,
null)
: FilterColumn.number(
Locale.ROOT,
false,
BigDecimal.ZERO,
new BigDecimal("9999999999.99"))));
var outside = new CheckBox("Accept on outside click");
var actions = new CheckBox("Show OK / Cancel");
actions.setSelected(true);
Runnable popup =
() ->
grid.setFilterPopupOptions(
new FilterPopup.Options(
outside.isSelected()
? FilterPopup.Outside.ACCEPT
: FilterPopup.Outside.CANCEL,
actions.isSelected(),
actions.isSelected()));
outside.setOnAction(e -> popup.run());
actions.setOnAction(e -> popup.run());
Button save = button("Save setup", this::save), load = button("Load setup", this::restore);
Button legacy = button("Load v1 setup", this::restoreLegacy);
Button clear = button("Clear filters", () -> grid.setFilters(List.of())),
unsupported =
button(
"Memory-only filter",
() -> grid.setFilters(List.of(new LocalNameLength("name"))));
Button slow =
button(
"Slow next refresh",
() -> {
requested.next(2500, false, false);
grid.refresh();
});
Button failure =
button(
"Fail next refresh",
() -> {
requested.next(500, true, false);
grid.refresh();
});
Button late =
button(
"Late success then failure",
() -> {
requested.next(2500, false, true);
grid.refresh();
Platform.runLater(
() -> {
if (!closed) {
requested.next(100, true, false);
grid.refresh();
}
});
});
Button lateFailure =
button(
"Late failure then success",
() -> {
requested.next(2500, true, true);
grid.refresh();
Platform.runLater(
() -> {
if (!closed) grid.refresh();
});
});
Button insert = button("Insert fixture", () -> mutate(() -> catalog.insert()));
Button delete =
button(
"Delete selected",
() -> {
Long id = grid.selectedKeyProperty().get();
if (id == null)
throw new IllegalArgumentException("Select a row first");
mutate(() -> catalog.delete(id), () -> grid.confirmedDeleted(id));
});
Button reset = button("Reset fixtures", () -> mutate(() -> catalog.reset()));
Button tail =
button(
"Delete displayed page",
() -> {
var state = grid.stateProperty().get();
if (state.result() == null) return;
var ids = state.result().rows().stream().map(GridRow::key).toList();
mutate(
() -> {
for (long id : ids) catalog.delete(id);
});
});
Button reorder =
button(
"Price first",
() ->
grid.setColumnOrder(
List.of("price", "id", "name", "category", "quantity")));
Button width =
button(
"Widen name",
() -> grid.setColumnWidth("name", new ColumnWidth.Explicit(400)));
message.getStyleClass().add("theme-error");
message.setWrapText(true);
diagnostics.setEditable(false);
diagnostics.setPrefRowCount(7);
var detail = new TitledPane("Request diagnostics", diagnostics);
detail.setExpanded(false);
grid.stateProperty()
.addListener(
(o, a, b) ->
log(
"Grid generation "
+ b.generation()
+ ": "
+ b.phase()
+ "; requested="
+ b.requested().page()
+ "; displayed="
+ (b.displayed() == null
? "none"
: b.displayed().page())));
getChildren()
.addAll(
new Label("Product catalog — deterministic memory / H2 demonstration"),
new FlowPane(
8,
8,
new Label("Source"),
sourcePicker,
new Label("Theme"),
themePicker,
new Label("All warning threshold"),
threshold),
new FlowPane(8, 8, save, load, legacy, reorder, width, clear, unsupported),
new FlowPane(8, 8, custom, outside, actions),
new FlowPane(8, 8, insert, delete, tail, reset),
new FlowPane(8, 8, slow, failure, late, lateFailure),
message,
grid,
detail);
VBox.setVgrow(grid, Priority.ALWAYS);
grid.setPrefHeight(450);
grid.load();
}
@FunctionalInterface
private interface Work {
void run() throws Exception;
}
private Button button(String text, Work action) {
var b = new Button(text);
b.setOnAction(
e -> {
try {
message.setText("");
action.run();
} catch (Exception error) {
message.setText(error.getMessage());
}
});
return b;
}
private void mutate(Work work) {
mutate(work, grid::refresh);
}
private void mutate(Work work, Runnable publish) {
CompletableFuture.runAsync(
() -> {
try {
work.run();
} catch (Exception e) {
throw new CompletionException(e);
}
},
catalog.workers)
.whenComplete(
(v, e) ->
Platform.runLater(
() -> {
if (closed) return;
if (e != null)
message.setText(e.getCause().getMessage());
else publish.run();
}));
}
public void save() throws java.io.IOException {
String document = codec.encode(grid.snapshotSetup());
Files.createDirectories(setupFile.toAbsolutePath().getParent());
var temporary =
Files.createTempFile(setupFile.toAbsolutePath().getParent(), "grid-", ".json");
try {
Files.writeString(temporary, document);
Files.move(
temporary,
setupFile,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temporary);
}
message.setText("Saved setup to " + setupFile);
}
/** Demonstrates an explicit column rename, not heuristic recovery of unknown columns. */
public void restoreLegacy() {
var current = grid.snapshotSetup();
var columns =
current.columns().stream()
.map(
c ->
new GridSetup.ColumnState(
c.id().equals("category") ? "group" : c.id(),
c.type(),
c.width()))
.toList();
grid.restoreSetup(
new GridSetup(
1,
"demo.products",
1,
columns,
List.of(new SortKey("group", SortKey.Direction.ASCENDING)),
List.of(
new TextFilter(
"group", TextFilter.Operator.EQUALS, "Office", true)),
new PageRequest.Paged(0, 50)));
}
private static GridSetup migrateLegacy(GridSetup old) {
var columns =
old.columns().stream()
.map(c -> new GridSetup.ColumnState(rename(c.id()), c.type(), c.width()))
.toList();
var sorts =
old.sort().stream()
.map(s -> new SortKey(rename(s.columnId()), s.direction()))
.toList();
var filters =
old.filters().stream()
.map(
f -> {
if (!f.columnId().equals("group")) return f;
if (f instanceof TextFilter t)
return (FilterCondition)
new TextFilter(
"category",
t.operator(),
t.operand(),
t.caseSensitive());
if (f instanceof MissingFilter m)
return (FilterCondition)
new MissingFilter("category", m.missing());
if (f instanceof ValueFilter v)
return (FilterCondition)
new ValueFilter(
"category", v.values(), v.includeMissing());
throw new IllegalArgumentException(
"Cannot migrate legacy group filter " + f.typeId());
})
.toList();
return new GridSetup(
old.formatVersion(), old.definitionId(), 2, columns, sorts, filters, old.page());
}
private static String rename(String id) {
return id.equals("group") ? "category" : id;
}
public void restore() {
grid.restoreSetup(
() -> {
try {
return codec.decode(Files.readString(setupFile));
} catch (java.io.IOException e) {
throw new IllegalArgumentException(
"Cannot read setup: " + e.getMessage(), e);
}
});
}
private void log(String text) {
Platform.runLater(
() -> {
if (!closed) {
if (diagnostics.getLength() > 16000) diagnostics.deleteText(0, 8000);
diagnostics.appendText(text + "\n");
}
});
}
public void install(Scene scene) {
themes.register(scene);
}
public void close() {
closed = true;
DemoResources.closeAll(grid, themes, clock::shutdown);
}
}
@@ -0,0 +1,10 @@
package de.neitzel.fx.example.grid;
/** Classpath launcher separate from Application for JavaFX startup. */
public final class ProductGridMain {
private ProductGridMain() {}
public static void main(String[] args) {
javafx.application.Application.launch(ProductGridApp.class, args);
}
}
@@ -0,0 +1,48 @@
package de.neitzel.fx.example.grid;
import de.neitzel.fx.view.ResultRow;
import javafx.fxml.*;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.util.Map;
/** A fresh FXML row bound once to an immutable Product. */
public final class ProductRow {
@FXML private Label id, name, category, quantity, price;
public static ResultRow create(Product p) {
try {
var loader = new FXMLLoader(ProductRow.class.getResource("ProductRow.fxml"));
HBox root = loader.load();
ProductRow c = loader.getController();
c.id.setText(Long.toString(p.id()));
c.name.setText(show(p.name()));
c.category.setText(show(p.category()));
c.quantity.setText(show(p.quantity()));
c.price.setText(show(p.price()));
return new ResultRow(
root,
Map.of(
"id",
c.id,
"name",
c.name,
"category",
c.category,
"quantity",
c.quantity,
"price",
c.price),
() -> {});
} catch (IOException e) {
throw new IllegalStateException("Cannot load product row", e);
}
}
private static String show(Object v) {
return v == null ? "(missing)" : v.toString();
}
}
@@ -0,0 +1,170 @@
package de.neitzel.fx.example.theme;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.fx.theme.*;
import de.neitzel.fx.view.*;
import de.neitzel.grid.*;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.css.PseudoClass;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import java.util.*;
/** Runnable state gallery; no stored preference, source credentials or application data. */
public final class ThemeGallery extends VBox implements AutoCloseable {
public final ThemeManager themes = new ThemeManager();
public final Button normal = new Button("Normal"),
hovered = new Button("Hovered"),
focused = new Button("Focused"),
disabled = new Button("Disabled");
public final TextField invalid = new TextField("invalid input"),
draft = new TextField("An unfinished edit survives theme changes");
public final Label error = new Label("! Invalid value — check the input"),
warning = new Label("! Warning — review this value");
public final TableView<String> standard = new TableView<>();
public final DataGrid<Integer, String> grid;
private final List<Stage> floating = new ArrayList<>();
public ThemeGallery() {
setSpacing(12);
setStyle("-fx-padding: 18;");
getStyleClass().add("theme-gallery");
var picker = new ComboBox<String>();
picker.getItems().setAll("light", "dark", "high-contrast");
picker.setValue("light");
picker.setOnAction(
e -> {
if (!picker.getValue().equals(themes.selectedThemeProperty().get().id()))
themes.select(picker.getValue());
});
themes.selectedThemeProperty().addListener((o, a, b) -> picker.setValue(b.id()));
var failure = new Label();
failure.setWrapText(true);
failure.getStyleClass().add("theme-error");
themes.failureProperty()
.addListener((o, a, b) -> failure.setText(b == null ? "" : b.message()));
Label title = new Label("Shared theme gallery");
title.setStyle("-fx-font-size: 20px; -fx-font-weight: bold;");
hovered.pseudoClassStateChanged(PseudoClass.getPseudoClass("hover"), true);
focused.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), true);
disabled.setDisable(true);
invalid.pseudoClassStateChanged(PseudoClass.getPseudoClass("invalid"), true);
invalid.setAccessibleText("Invalid value; check the input");
error.getStyleClass().add("theme-error");
warning.getStyleClass().add("theme-warning");
CheckBox checked = new CheckBox("Checked");
checked.setSelected(true);
RadioButton radio = new RadioButton("Selected radio");
radio.setSelected(true);
DatePicker date = new DatePicker();
date.setPromptText("Nested date chooser");
ComboBox<String> combo = new ComboBox<>();
combo.getItems().addAll("Choose a value", "Alpha", "Beta");
combo.getSelectionModel().selectFirst();
TableColumn<String, String> state =
new TableColumn<>("Record indicator (text survives selection)");
state.setCellValueFactory(c -> new ReadOnlyStringWrapper(c.getValue()));
state.setPrefWidth(380);
standard.getColumns().add(state);
standard.getItems()
.setAll(
"FILE — from saved input",
"LIVE — observed record",
"REMOVE — pending removal");
standard.getSelectionModel().select(2);
standard.setPrefHeight(135);
var source =
new MemoryGridSource<Integer, String>(
() -> List.of("Alpha", "Beta", "Gamma"),
value -> List.of("Alpha", "Beta", "Gamma").indexOf(value),
Integer::compare,
List.of(
new MemoryColumn<>(
"name", MemoryColumn.Kind.TEXT, FilterValue.Text::new)),
Runnable::run,
100);
grid =
new DataGrid<>(
List.of(new ResultColumn("name", "Name", 430, 160, 600, -1)),
value -> {
Label label = new Label(value);
label.setPadding(new javafx.geometry.Insets(6));
return new ResultRow(new HBox(label), Map.of("name", label), () -> {});
},
source);
grid.configureFilter(
"name",
FilterColumn.text()
.withChecklist(
FilterColumn.Checklist.SOURCE_WIDE,
source.candidateProvider(
value -> ((FilterValue.Text) value).value())));
grid.setFilters(List.of(new TextFilter("name", TextFilter.Operator.CONTAINS, "a", false)));
grid.select(0);
grid.setPrefHeight(210);
Button dialog = new Button("Open dialog"),
floatWindow = new Button("Open floating window"),
loading = new Button("Toggle loading sample");
dialog.setOnAction(
e -> {
Alert alert =
new Alert(
Alert.AlertType.INFORMATION,
"Dialogs inherit the selected theme, including newly opened"
+ " windows.",
ButtonType.OK);
alert.initOwner(getScene().getWindow());
alert.show();
});
floatWindow.setOnAction(
e -> {
Stage stage = new Stage();
stage.initOwner(getScene().getWindow());
stage.setTitle("Themed floating window");
var field =
new TextArea("Edit this text, then change the theme in the gallery.");
stage.setScene(
new Scene(new VBox(12, new Label("Floating editor"), field), 420, 200));
floating.add(stage);
stage.show();
});
Label loadingStatus = new Label("Loading… retained rows are unavailable");
loadingStatus.getStyleClass().add("data-grid-status");
HBox loadingState = new HBox(10, new ProgressIndicator(), loadingStatus);
loadingState.getStyleClass().add("data-grid");
loadingState.pseudoClassStateChanged(PseudoClass.getPseudoClass("loading"), true);
((ProgressIndicator) loadingState.getChildren().getFirst()).setPrefSize(22, 22);
loading.setOnAction(e -> loadingState.setVisible(!loadingState.isVisible()));
getChildren()
.addAll(
new HBox(16, title, picker),
new Label(
"Explicit state specimens: hover / focus are CSS states, not a"
+ " native input test."),
new HBox(10, normal, hovered, focused, disabled),
draft,
new HBox(10, checked, radio, combo, date),
invalid,
error,
warning,
standard,
grid,
loadingState,
new HBox(10, dialog, floatWindow, loading),
failure);
}
public void install(Scene scene) {
themes.register(scene);
}
public void close() {
grid.close();
for (var stage : floating) stage.close();
themes.close();
}
}
@@ -0,0 +1,22 @@
package de.neitzel.fx.example.theme;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public final class ThemeGalleryApp extends Application {
private ThemeGallery gallery;
public void start(Stage stage) {
gallery = new ThemeGallery();
Scene scene = new Scene(gallery, 920, 900);
gallery.install(scene);
stage.setTitle("NeitzelLib theme gallery");
stage.setScene(scene);
stage.show();
}
public void stop() {
if (gallery != null) gallery.close();
}
}
@@ -0,0 +1,9 @@
package de.neitzel.fx.example.theme;
public final class ThemeGalleryMain {
private ThemeGalleryMain() {}
public static void main(String[] args) {
javafx.application.Application.launch(ThemeGalleryApp.class, args);
}
}
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?><?import javafx.scene.control.Label?><?import javafx.scene.control.TextField?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.example.grid.PricePresetEditor" spacing="8" styleClass="filter-editor">
<Label text="Budget price (custom FXML editor)"/><Label text="Include prices up to this exact amount:"/><TextField fx:id="maximum" text="10.00"/>
</VBox>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.HBox?><?import javafx.scene.control.Label?>
<HBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.example.grid.ProductRow">
<Label style="-fx-padding: 4;" fx:id="id"/><Label style="-fx-padding: 4;" fx:id="name"/><Label style="-fx-padding: 4;" fx:id="category"/><Label style="-fx-padding: 4;" fx:id="quantity"/><Label style="-fx-padding: 4;" fx:id="price"/>
</HBox>
@@ -0,0 +1,49 @@
package de.neitzel.fx.example.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.h2.jdbcx.JdbcConnectionPool;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.*;
class DemoResourcesTest {
@Test
void independentCleanupContinuesAndPreservesFailures() {
var attempts = new ArrayList<String>();
var first = new java.sql.SQLException("anchor close");
var second = new IllegalStateException("pool close");
var failure =
assertThrows(
IllegalStateException.class,
() ->
DemoResources.closeAll(
() -> {
attempts.add("anchor");
throw first;
},
() -> {
attempts.add("pool");
throw second;
},
() -> attempts.add("executor")));
assertEquals(List.of("anchor", "pool", "executor"), attempts);
assertSame(first, failure.getCause());
assertArrayEquals(new Throwable[] {second}, failure.getSuppressed());
}
@Test
void failedInitialBorrowStillReleasesOwnedExecutor() {
var pool = JdbcConnectionPool.create("jdbc:h2:mem:closed_" + UUID.randomUUID(), "sa", "");
var workers = Executors.newSingleThreadExecutor();
pool.dispose();
try {
assertThrows(Exception.class, () -> new ProductCatalog(10, pool, workers));
assertTrue(workers.isShutdown());
} finally {
workers.shutdown();
pool.dispose();
}
}
}
@@ -0,0 +1,585 @@
package de.neitzel.fx.example.grid;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.grid.*;
import de.neitzel.grid.jdbc.*;
import org.junit.jupiter.api.*;
import java.lang.reflect.*;
import java.math.*;
import java.nio.file.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import javax.sql.DataSource;
class JdbcProductTest {
static ProductCatalog catalog;
@BeforeAll
static void start() throws Exception {
catalog = new ProductCatalog(10000);
}
@AfterAll
static void stop() {
catalog.close();
}
@BeforeEach
void reset() throws Exception {
catalog.reset();
}
static PageResult<Long, Product> result(GridSource<Long, Product> source, GridQuery q)
throws Exception {
return source.query(q, new QueryOptions(1000, true))
.result()
.toCompletableFuture()
.get(20, TimeUnit.SECONDS);
}
static GridQuery query(List<FilterCondition> filters, List<SortKey> sort, PageRequest page) {
return new GridQuery(filters, sort, page);
}
void parity(List<FilterCondition> filters, List<SortKey> sort, PageRequest page)
throws Exception {
var q = query(filters, sort, page);
assertEquals(result(catalog.memory, q), result(catalog.jdbc, q), q.toString());
}
@Test
void everyOperatorAndUnicodeExactChecklistAndOrderingAgree() throws Exception {
for (var op : TextFilter.Operator.values())
for (boolean sensitive : List.of(false, true))
for (String text :
List.of(
"Alpha",
"a",
"%",
"_",
"!",
"İ",
"ß",
"ss",
"😀",
"é",
"e\u0301",
"' OR 1=1 --"))
parity(
List.of(new TextFilter("name", op, text, sensitive)),
List.of(new SortKey("name", SortKey.Direction.ASCENDING)),
new PageRequest.All());
parity(
List.of(new TextFilter("name", TextFilter.Operator.EQUALS, "", true)),
List.of(),
new PageRequest.All());
for (var op : NumericFilter.Operator.values())
for (String col : List.of("quantity", "price"))
parity(
List.of(
new NumericFilter(
col,
op,
new BigDecimal("1.0"),
op == NumericFilter.Operator.RANGE
? new BigDecimal("20.00")
: null)),
List.of(),
new PageRequest.All());
for (String col : List.of("name", "category", "quantity", "price"))
for (boolean missing : List.of(true, false))
parity(
List.of(new MissingFilter(col, missing)),
List.of(),
new PageRequest.Paged(0, 50));
for (boolean missing : List.of(true, false)) {
parity(
List.of(
new ValueFilter(
"name",
Set.of(
new FilterValue.Text("Alpha"),
new FilterValue.Text("a%b")),
missing)),
List.of(),
new PageRequest.All());
parity(
List.of(new ValueFilter("name", Set.of(), missing)),
List.of(),
new PageRequest.All());
parity(
List.of(
new ValueFilter(
"quantity", Set.of(new FilterValue.IntegerValue(1)), missing)),
List.of(),
new PageRequest.All());
parity(
List.of(
new ValueFilter(
"price",
Set.of(new FilterValue.Decimal(new BigDecimal("1.0"))),
missing)),
List.of(),
new PageRequest.All());
}
for (String col : List.of("name", "category", "quantity", "price"))
for (var dir : SortKey.Direction.values())
parity(List.of(), List.of(new SortKey(col, dir)), new PageRequest.All());
parity(
List.of(
new TextFilter("name", TextFilter.Operator.CONTAINS, "product", false),
new NumericFilter(
"price", NumericFilter.Operator.LESS, new BigDecimal("10"), null)),
List.of(
new SortKey("category", SortKey.Direction.DESCENDING),
new SortKey("price", SortKey.Direction.ASCENDING)),
new PageRequest.Paged(3, 25));
for (int page : List.of(0, 1, 199, 200, 999))
parity(List.of(), List.of(), new PageRequest.Paged(page, 50));
}
@Test
void unsupportedAndInvalidSemanticsFailBeforeBorrowing() throws Exception {
var tracking = new Tracking(catalog.database);
var source = source(tracking, ProductCatalog::read);
for (FilterCondition invalid :
List.of(
new LocalNameLength("name"),
new TextFilter("price", TextFilter.Operator.EQUALS, "1", true),
new NumericFilter(
"quantity",
NumericFilter.Operator.EQUALS,
new BigDecimal("1.1"),
null),
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("1.001"),
null),
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("10000000000"),
null),
new ValueFilter("quantity", Set.of(new FilterValue.Text("1")), false),
new MissingFilter("not_mapped", true))) {
assertThrows(RuntimeException.class, () -> source.validateFilter(invalid));
assertThrows(
ExecutionException.class,
() ->
result(
source,
query(
List.of(invalid),
List.of(),
new PageRequest.Paged(0, 50))));
}
assertEquals(0, tracking.opened.get());
assertThrows(
IllegalArgumentException.class,
() -> JdbcColumn.text("bad", "name; DROP TABLE products", "key"));
assertEquals(
2,
result(
catalog.memory,
query(
List.of(
new ValueFilter(
"name",
Set.of(
new FilterValue.Text("Alpha"),
new FilterValue.Text("alpha")),
false)),
List.of(),
new PageRequest.All()))
.rows()
.size());
}
@Test
void snapshotContainsCountAndRowsDespiteConcurrentWriter() throws Exception {
var tracking = new Tracking(catalog.database);
tracking.afterCount =
() -> {
try (var connection = catalog.database.getConnection()) {
ProductCatalog.insert(
connection,
List.of(
new Product(
10001,
"Concurrent",
"Office",
1L,
new BigDecimal("1.00"))));
}
};
var page =
result(
source(tracking, ProductCatalog::read),
query(List.of(), List.of(), new PageRequest.All()));
assertEquals(10000, page.total().orElseThrow());
assertEquals(10000, page.rows().size());
assertEquals(
10001,
result(catalog.jdbc, query(List.of(), List.of(), new PageRequest.All()))
.rows()
.size());
tracking.assertReleased();
assertEquals(1, tracking.opened.get());
}
@Test
void allWarningClosesResourcesAndRecountsOnApproval() throws Exception {
var tracking = new Tracking(catalog.database);
var source = source(tracking, ProductCatalog::read);
var q = query(List.of(), List.of(), new PageRequest.All());
var error =
assertThrows(
ExecutionException.class,
() ->
source.query(q, new QueryOptions(9999, false))
.result()
.toCompletableFuture()
.get());
assertInstanceOf(AllRowsConfirmationRequired.class, error.getCause());
assertEquals(0, tracking.rowQueries.get());
tracking.assertReleased();
catalog.insert();
var page =
source.query(q, new QueryOptions(9999, true)).result().toCompletableFuture().get();
assertEquals(10001, page.rows().size());
tracking.assertReleased();
assertEquals(
10001,
source.query(q, new QueryOptions(10001, false))
.result()
.toCompletableFuture()
.get()
.rows()
.size());
var small =
query(
List.of(
new NumericFilter(
"id",
NumericFilter.Operator.LESS_OR_EQUAL,
new BigDecimal("1000"),
null)),
List.of(),
new PageRequest.All());
assertEquals(
1000,
source.query(small, QueryOptions.defaults())
.result()
.toCompletableFuture()
.get()
.rows()
.size());
var above =
query(
List.of(
new NumericFilter(
"id",
NumericFilter.Operator.LESS_OR_EQUAL,
new BigDecimal("1001"),
null)),
List.of(),
new PageRequest.All());
assertInstanceOf(
AllRowsConfirmationRequired.class,
assertThrows(
ExecutionException.class,
() ->
source.query(above, QueryOptions.defaults())
.result()
.toCompletableFuture()
.get())
.getCause());
tracking.assertReleased();
}
@Test
void failuresCancellationAndExecutorRejectionReleaseResources() throws Exception {
var tracking = new Tracking(catalog.database);
var source =
source(
tracking,
rs -> {
throw new SQLException("Injected mapper failure");
});
assertThrows(
ExecutionException.class,
() -> result(source, query(List.of(), List.of(), new PageRequest.Paged(0, 50))));
tracking.assertReleased();
var entered = new CountDownLatch(1);
var release = new CountDownLatch(1);
var blocking =
source(
tracking,
rs -> {
entered.countDown();
try {
if (!release.await(5, TimeUnit.SECONDS))
throw new SQLException("test timed out");
} catch (InterruptedException e) {
throw new SQLException(e);
}
return ProductCatalog.read(rs);
});
var execution = blocking.query(query(List.of(), List.of(), new PageRequest.Paged(0, 50)));
assertTrue(entered.await(5, TimeUnit.SECONDS));
execution.cancel();
release.countDown();
assertThrows(
CancellationException.class, () -> execution.result().toCompletableFuture().join());
long limit = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (tracking.closed.get() < tracking.opened.get() && System.nanoTime() < limit)
Thread.sleep(10);
tracking.assertReleased();
assertTrue(tracking.cancels.get() > 0);
var rejected =
new JdbcGridSource<Long, Product>(
tracking.proxy(),
r -> {
throw new RejectedExecutionException("closed executor");
},
JdbcDialect.h2(),
"products",
"id",
ProductCatalog.jdbcColumns(),
ProductCatalog::read,
250,
3);
int before = tracking.opened.get();
assertThrows(
ExecutionException.class,
() -> result(rejected, query(List.of(), List.of(), new PageRequest.Paged(0, 50))));
assertEquals(before, tracking.opened.get());
}
@Test
void queuedCancellationAndUnqualifiedCollationAreRejected() throws Exception {
var tracking = new Tracking(catalog.database);
var queued = new java.util.ArrayList<Runnable>();
var source =
new JdbcGridSource<Long, Product>(
tracking.proxy(),
queued::add,
JdbcDialect.h2(),
"products",
"id",
ProductCatalog.jdbcColumns(),
ProductCatalog::read,
250,
3);
var execution = source.query(query(List.of(), List.of(), new PageRequest.Paged(0, 50)));
execution.cancel();
queued.removeFirst().run();
assertEquals(0, tracking.opened.get());
var other =
org.h2.jdbcx.JdbcConnectionPool.create(
"jdbc:h2:mem:collated_" + UUID.randomUUID(), "sa", "");
try (var anchor = other.getConnection()) {
try (var statement = anchor.createStatement()) {
statement.execute("SET COLLATION ENGLISH");
}
var unqualified =
new JdbcGridSource<Long, Product>(
other,
Runnable::run,
JdbcDialect.h2(),
"products",
"id",
ProductCatalog.jdbcColumns(),
ProductCatalog::read,
250,
3);
var error =
assertThrows(
ExecutionException.class,
() ->
result(
unqualified,
query(
List.of(),
List.of(),
new PageRequest.Paged(0, 50))));
assertTrue(error.getCause().getMessage().contains("collation"));
} finally {
other.dispose();
}
}
@Test
void mutationKeysAndTimings() throws Exception {
catalog.insert();
parity(
List.of(
new TextFilter(
"name", TextFilter.Operator.EQUALS, "INSERTED 10001", false)),
List.of(),
new PageRequest.All());
catalog.delete(10001);
parity(List.of(), List.of(), new PageRequest.Paged(199, 50));
var lines = new ArrayList<String>();
lines.add(
"10,000 immutable Product rows; source materialization only, excludes FX"
+ " Components; single observed run, no performance guarantee.");
for (var source : List.of(catalog.memory, catalog.jdbc))
for (PageRequest page :
List.of(
new PageRequest.Paged(0, 50),
new PageRequest.Paged(199, 50),
new PageRequest.All())) {
long before = System.nanoTime();
var response =
result(
source,
query(
List.of(),
List.of(new SortKey("name", SortKey.Direction.ASCENDING)),
page));
lines.add(
source.filterExecutionId()
+ " "
+ page
+ " rows="
+ response.rows().size()
+ " durationMs="
+ (System.nanoTime() - before) / 1_000_000.0);
}
Path path = Path.of("target/jdbc-evidence");
Files.createDirectories(path);
Files.write(path.resolve("timings.txt"), lines);
}
JdbcGridSource<Long, Product> source(
Tracking tracking, JdbcGridSource.RowMapper<Long, Product> mapper) {
return new JdbcGridSource<>(
tracking.proxy(),
catalog.workers,
JdbcDialect.h2(),
"products",
"id",
ProductCatalog.jdbcColumns(),
mapper,
250,
3);
}
@FunctionalInterface
interface SqlAction {
void run() throws SQLException;
}
static final class Tracking {
final DataSource target;
final AtomicInteger opened = new AtomicInteger(),
closed = new AtomicInteger(),
statements = new AtomicInteger(),
results = new AtomicInteger(),
rowQueries = new AtomicInteger(),
cancels = new AtomicInteger();
final List<Throwable> problems = new CopyOnWriteArrayList<>();
SqlAction afterCount = () -> {};
Tracking(DataSource target) {
this.target = target;
}
DataSource proxy() {
return wrap(
DataSource.class,
target,
(object, method, args) -> {
Object value = invoke(target, method, args);
if (method.getName().equals("getConnection")) {
opened.incrementAndGet();
return connection((Connection) value);
}
return value;
});
}
Connection connection(Connection c) throws SQLException {
int original = c.getTransactionIsolation();
boolean auto = c.getAutoCommit();
return wrap(
Connection.class,
c,
(object, method, args) -> {
if (method.getName().equals("close")) {
try {
assertEquals(auto, c.getAutoCommit());
assertEquals(original, c.getTransactionIsolation());
} catch (Throwable problem) {
problems.add(problem);
}
closed.incrementAndGet();
}
Object value = invoke(c, method, args);
if (value instanceof PreparedStatement s)
return statement(s, (String) args[0]);
return value;
});
}
PreparedStatement statement(PreparedStatement s, String sql) {
statements.incrementAndGet();
boolean count = sql.startsWith("SELECT COUNT");
if (sql.startsWith("SELECT id")) rowQueries.incrementAndGet();
return wrap(
PreparedStatement.class,
s,
(object, method, args) -> {
if (method.getName().equals("close")) statements.decrementAndGet();
if (method.getName().equals("cancel")) cancels.incrementAndGet();
if (method.getName().equals("executeQuery")
&& !sql.contains("INFORMATION_SCHEMA"))
assertEquals(3, s.getQueryTimeout());
Object value = invoke(s, method, args);
if (value instanceof ResultSet rs) {
results.incrementAndGet();
return wrap(
ResultSet.class,
rs,
(o, m, a) -> {
Object answer = invoke(rs, m, a);
if (m.getName().equals("close")) {
results.decrementAndGet();
if (count) afterCount.run();
}
return answer;
});
}
return value;
});
}
void assertReleased() {
assertEquals(opened.get(), closed.get());
assertEquals(0, statements.get());
assertEquals(0, results.get());
assertTrue(problems.isEmpty(), problems.toString());
}
static Object invoke(Object object, Method method, Object[] args) throws Throwable {
try {
return method.invoke(object, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
static <T> T wrap(Class<T> type, T target, InvocationHandler handler) {
return type.cast(
Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, handler));
}
}
}
@@ -0,0 +1,492 @@
package de.neitzel.fx.example.grid;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import org.junit.jupiter.api.*;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.BooleanSupplier;
import javax.imageio.ImageIO;
class ProductGridDemoTest {
static final Queue<Throwable> uncaught = new ConcurrentLinkedQueue<>();
ProductCatalog catalog;
ProductGridDemo demo;
Stage stage;
Path setup;
Thread.UncaughtExceptionHandler previous;
@BeforeAll
static void startup() throws Exception {
var ready = new CountDownLatch(1);
try {
Platform.startup(ready::countDown);
} catch (IllegalStateException already) {
ready.countDown();
}
assertTrue(ready.await(10, TimeUnit.SECONDS));
fx(() -> Platform.setImplicitExit(false));
}
static void fx(Runnable work) throws Exception {
var f = new FutureTask<Void>(work, null);
Platform.runLater(f);
f.get(90, TimeUnit.SECONDS);
}
@BeforeEach
void open() throws Exception {
catalog = new ProductCatalog(10000);
setup = Files.createTempDirectory("grid-demo-test").resolve("setup.json");
fx(
() -> {
previous = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> uncaught.add(e));
demo = new ProductGridDemo(catalog, setup);
stage = new Stage();
var scene = new Scene(demo, 1120, 820);
demo.install(scene);
stage.setScene(scene);
stage.show();
});
ready();
}
@AfterEach
void close() throws Exception {
fx(
() -> {
demo.close();
stage.close();
Thread.currentThread().setUncaughtExceptionHandler(previous);
});
catalog.close();
Files.deleteIfExists(setup);
Files.deleteIfExists(setup.getParent());
assertTrue(uncaught.isEmpty(), uncaught.toString());
uncaught.clear();
}
void await(BooleanSupplier condition) throws Exception {
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(45);
var value = new AtomicBoolean();
while (System.nanoTime() < until) {
fx(() -> value.set(condition.getAsBoolean()));
if (value.get()) return;
Thread.sleep(20);
}
fail("Timed out waiting for demo state");
}
void ready() throws Exception {
await(() -> demo.grid.stateProperty().get().phase() == GridCoordinator.Phase.READY);
}
void click(String label) {
Button button =
(Button)
demo.lookupAll(".button").stream()
.filter(n -> n instanceof Button b && b.getText().equals(label))
.findFirst()
.orElseThrow();
button.fire();
}
@Test
void fxmlFieldsAlignWithHeadersAfterCssAndReorder() throws Exception {
fx(
() -> {
for (String theme : List.of("light", "dark", "high-contrast")) {
demo.themePicker.setValue(theme);
demo.grid.setColumnOrder(
List.of("price", "id", "name", "category", "quantity"));
demo.grid.setColumnWidth("name", new ColumnWidth.Explicit(400));
demo.applyCss();
demo.layout();
var row = (javafx.scene.layout.HBox) demo.grid.lookup(".result-row");
assertEquals(javafx.geometry.Insets.EMPTY, row.getPadding());
var headers =
demo.grid.lookupAll(".column-cell").stream()
.sorted(
java.util.Comparator.comparingDouble(
n ->
n.localToScene(n.getBoundsInLocal())
.getMinX()))
.toList();
assertEquals(5, headers.size());
for (int index = 0; index < headers.size(); index++) {
var field = row.getChildren().get(index);
assertEquals(
headers.get(index)
.localToScene(headers.get(index).getBoundsInLocal())
.getMinX(),
field.localToScene(field.getBoundsInLocal()).getMinX(),
.1);
assertEquals(
headers.get(index).getBoundsInLocal().getWidth(),
field.getBoundsInLocal().getWidth(),
.1);
assertEquals(4, ((Label) field).getPadding().getLeft(), .1);
}
}
});
}
@Test
void currentPageChecklistKeepsExactOriginalValues() throws Exception {
var root = new AtomicReference<javafx.scene.Parent>();
fx(
() -> {
var opener =
(Button)
demo.lookupAll(".filter-button").stream()
.filter(
n ->
"Filter Name"
.equals(n.getAccessibleText()))
.findFirst()
.orElseThrow();
opener.fire();
var window =
javafx.stage.Window.getWindows().stream()
.filter(
w ->
w != stage
&& w.getScene()
.getRoot()
.lookup("#mode")
!= null)
.findFirst()
.orElseThrow();
root.set(window.getScene().getRoot());
});
// Select the mode by its displayed name without assuming the internal list ordering.
fx(
() -> {
var box = (ComboBox<?>) root.get().lookup("#mode");
box.getSelectionModel().select(box.getItems().indexOf("Checklist"));
});
await(
() ->
root.get().lookupAll(".check-box").stream()
.anyMatch(
n ->
n instanceof CheckBox b
&& "Alpha".equals(b.getText())));
fx(
() -> {
assertTrue(
((Label) root.get().lookup("#scope"))
.getText()
.contains("Current page"));
var choices =
root.get().lookupAll(".check-box").stream()
.map(n -> (CheckBox) n)
.toList();
assertTrue(choices.stream().anyMatch(b -> "alpha".equals(b.getText())));
choices.stream()
.filter(b -> "Alpha".equals(b.getText()))
.findFirst()
.orElseThrow()
.fire();
((Button)
root.get().lookupAll(".button").stream()
.filter(
n ->
n instanceof Button b
&& "OK".equals(b.getText()))
.findFirst()
.orElseThrow())
.fire();
});
ready();
fx(
() ->
assertEquals(
List.of("Alpha"),
demo.grid.stateProperty().get().result().rows().stream()
.map(r -> r.model().name())
.toList()));
}
@Test
void actualFxmlEditorsSourceSwitchSetupThemesAndCapabilityErrors() throws Exception {
fx(
() -> {
var context =
new FilterEditorContext(
"price",
FilterColumn.number(Locale.ROOT, false, null, null),
null,
List.of(),
FilterColumn.Checklist.DISABLED);
var editor = PricePresetEditor.load(context);
assertEquals(
new NumericFilter(
"price",
NumericFilter.Operator.LESS_OR_EQUAL,
new BigDecimal("10.00"),
null),
editor.draft());
TextField field = (TextField) editor.view().lookup("#maximum");
field.setText("1.001");
assertFalse(editor.validationMessageProperty().get().isEmpty());
field.setText("1.0");
catalog.jdbc.validateFilter(editor.draft());
demo.grid.setFilters(List.of(editor.draft()));
editor.close();
});
ready();
fx(
() -> {
assertTrue(
demo.grid.stateProperty().get().result().rows().stream()
.allMatch(
r -> r.model().price().compareTo(BigDecimal.ONE) <= 0));
demo.grid.select(1L);
demo.grid.setColumnOrder(
List.of("price", "id", "name", "category", "quantity"));
demo.grid.setColumnWidth("name", new ColumnWidth.Explicit(400));
try {
demo.save();
} catch (Exception e) {
throw new RuntimeException(e);
}
demo.themePicker.setValue("dark");
demo.grid.setFilters(List.of());
});
ready();
fx(() -> demo.restoreLegacy());
ready();
fx(
() -> {
assertEquals(2, demo.grid.snapshotSetup().definitionVersion());
assertTrue(
demo.grid.stateProperty().get().result().rows().stream()
.allMatch(r -> "Office".equals(r.model().category())));
demo.restore();
});
ready();
fx(
() -> {
assertEquals("price", demo.grid.snapshotSetup().columns().getFirst().id());
assertEquals(1, demo.grid.snapshotSetup().filters().size());
demo.sourcePicker.setValue("Memory");
});
ready();
fx(
() -> {
click("Memory-only filter");
});
ready();
fx(
() -> {
assertTrue(
demo.grid.stateProperty().get().result().rows().stream()
.allMatch(r -> r.model().name().length() <= 5));
demo.sourcePicker.setValue("JDBC / H2");
});
await(() -> demo.grid.stateProperty().get().phase() == GridCoordinator.Phase.ERROR);
fx(
() -> {
assertTrue(
demo.grid
.stateProperty()
.get()
.error()
.getMessage()
.contains("does not support"));
click("Clear filters");
});
ready();
fx(() -> demo.sourcePicker.setValue("Memory"));
ready();
fx(() -> demo.sourcePicker.setValue("JDBC / H2"));
ready();
fx(
() -> {
demo.themePicker.setValue("high-contrast");
stage.getScene().getRoot().applyCss();
stage.getScene().getRoot().layout();
var image = demo.snapshot(null, null);
var buffered =
new BufferedImage(
(int) image.getWidth(),
(int) image.getHeight(),
BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < buffered.getHeight(); y++)
for (int x = 0; x < buffered.getWidth(); x++)
buffered.setRGB(x, y, image.getPixelReader().getArgb(x, y));
try {
Files.createDirectories(Path.of("target/jdbc-evidence"));
ImageIO.write(
buffered, "png", Path.of("target/jdbc-evidence/demo.png").toFile());
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
@Test
void lateSuccessFailureRetryAndDisappearingPage() throws Exception {
fx(() -> click("Late success then failure"));
await(() -> demo.grid.stateProperty().get().phase() == GridCoordinator.Phase.ERROR);
Thread.sleep(2800);
fx(
() -> {
assertEquals(
GridCoordinator.Phase.ERROR, demo.grid.stateProperty().get().phase());
demo.grid.retry();
});
ready();
fx(() -> click("Late failure then success"));
ready();
Thread.sleep(2800);
fx(
() -> {
assertEquals(
GridCoordinator.Phase.READY, demo.grid.stateProperty().get().phase());
assertTrue(demo.diagnostics.getText().contains("obsolete completion"));
demo.grid.last();
});
ready();
fx(
() -> {
assertEquals(
199,
((PageRequest.Paged) demo.grid.stateProperty().get().displayed().page())
.pageIndex());
click("Delete displayed page");
});
await(
() ->
demo.grid.stateProperty().get().phase() == GridCoordinator.Phase.READY
&& demo.grid.stateProperty().get().result().total().orElseThrow()
== 9950);
fx(
() ->
assertEquals(
198,
((PageRequest.Paged)
demo.grid.stateProperty().get().displayed().page())
.pageIndex()));
}
@Test
void allCancellationSupersessionRestorationAndFullMaterialization() throws Exception {
var decision = new CompletableFuture<Boolean>();
var asked = new AtomicLong();
fx(
() -> {
demo.grid.setAllConfirmation(
(q, count) -> {
asked.set(count);
return decision;
});
demo.grid.showAll();
});
await(() -> asked.get() == 10000);
assertEquals(
1,
catalog.database.getActiveConnections(),
"Only application anchor remains while awaiting person");
fx(() -> decision.complete(false));
ready();
fx(() -> assertInstanceOf(PageRequest.Paged.class, demo.grid.snapshotSetup().page()));
var obsolete = new CompletableFuture<Boolean>();
asked.set(0);
fx(
() -> {
demo.grid.setAllConfirmation(
(q, count) -> {
asked.set(count);
return obsolete;
});
demo.grid.showAll();
});
await(() -> asked.get() == 10000);
fx(
() ->
demo.grid.setFilters(
List.of(
new NumericFilter(
"id",
NumericFilter.Operator.LESS_OR_EQUAL,
new BigDecimal("25"),
null))));
ready();
fx(() -> obsolete.complete(true));
ready();
fx(() -> assertEquals(25, demo.grid.stateProperty().get().result().rows().size()));
fx(
() -> {
demo.grid.setPageSize(50);
demo.grid.setFilters(List.of());
});
ready();
// One measured, explicitly approved All load of real FXML Components (not virtualization).
long before = System.nanoTime();
var approvals = new AtomicInteger();
fx(
() -> {
demo.grid.setAllConfirmation(
(q, count) -> {
approvals.incrementAndGet();
return CompletableFuture.completedFuture(true);
});
demo.grid.showAll();
});
ready();
long elapsed = (System.nanoTime() - before) / 1_000_000;
fx(
() -> {
assertEquals(10000, demo.grid.stateProperty().get().result().rows().size());
assertInstanceOf(PageRequest.All.class, demo.grid.snapshotSetup().page());
try {
demo.save();
} catch (Exception e) {
throw new RuntimeException(e);
}
demo.grid.setPageSize(50);
});
ready();
asked.set(0);
var restoreDecision = new CompletableFuture<Boolean>();
fx(
() -> {
demo.grid.setAllConfirmation(
(q, count) -> {
asked.set(count);
return restoreDecision;
});
demo.restore();
});
await(() -> asked.get() == 10000);
fx(() -> restoreDecision.complete(false));
ready();
fx(() -> assertInstanceOf(PageRequest.Paged.class, demo.grid.snapshotSetup().page()));
assertEquals(1, approvals.get());
Files.createDirectories(Path.of("target/jdbc-evidence"));
Files.writeString(
Path.of("target/jdbc-evidence/fx-materialization.txt"),
"10,000 H2 rows as fresh FXML Components; count/approval/fetch/publication"
+ " elapsedMs="
+ elapsed
+ "; includes UI materialization, no virtualization. Single observed"
+ " run.\n");
}
}
@@ -0,0 +1,428 @@
package de.neitzel.fx.example.theme;
import static org.junit.jupiter.api.Assertions.*;
import javafx.application.Platform;
import javafx.css.PseudoClass;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.stage.Stage;
import org.junit.jupiter.api.*;
import java.awt.image.BufferedImage;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import javax.imageio.ImageIO;
class ThemeGalleryTest {
private static final java.util.Queue<Throwable> uncaught =
new java.util.concurrent.ConcurrentLinkedQueue<>();
private static Thread.UncaughtExceptionHandler previousHandler;
@BeforeEach
void captureFxErrors() throws Exception {
fx(
() -> {
previousHandler = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread()
.setUncaughtExceptionHandler((thread, error) -> uncaught.add(error));
});
}
@AfterEach
void verifyFxErrors() throws Exception {
fx(() -> Thread.currentThread().setUncaughtExceptionHandler(previousHandler));
var errors = new java.util.ArrayList<>(uncaught);
uncaught.clear();
assertTrue(errors.isEmpty(), "Uncaught FX errors: " + errors);
}
@BeforeAll
static void start() throws Exception {
CountDownLatch ready = new CountDownLatch(1);
try {
Platform.startup(ready::countDown);
} catch (IllegalStateException e) {
ready.countDown();
}
assertTrue(ready.await(10, TimeUnit.SECONDS));
fx(() -> Platform.setImplicitExit(false));
}
static void fx(Runnable code) throws Exception {
var task = new FutureTask<Void>(code, null);
Platform.runLater(task);
task.get(15, TimeUnit.SECONDS);
}
static double luminance(Color c) {
return .2126 * linear(c.getRed())
+ .7152 * linear(c.getGreen())
+ .0722 * linear(c.getBlue());
}
static double linear(double c) {
return c <= .04045 ? c / 12.92 : Math.pow((c + .055) / 1.055, 2.4);
}
static double contrast(Color a, Color b) {
double x = luminance(a), y = luminance(b);
return (Math.max(x, y) + .05) / (Math.min(x, y) + .05);
}
static Color background(Node node) {
for (Node current = node; current != null; current = current.getParent())
if (current instanceof Region r && r.getBackground() != null)
for (int i = r.getBackground().getFills().size() - 1; i >= 0; i--) {
Paint p = r.getBackground().getFills().get(i).getFill();
if (p instanceof Color c && c.getOpacity() == 1) return c;
}
throw new AssertionError("No opaque resolved background for " + node);
}
static void measure(
String theme,
String name,
Paint foreground,
Node node,
double target,
List<String> report) {
assertInstanceOf(Color.class, foreground);
Color fg = (Color) foreground, bg = background(node);
double ratio = contrast(fg, bg);
report.add(
theme
+ " | "
+ name
+ " | "
+ fg
+ " | "
+ bg
+ " | "
+ String.format(Locale.ROOT, "%.2f", ratio));
assertTrue(ratio >= target, theme + " " + name + " contrast " + ratio + " < " + target);
}
@Test
void resolvedStateContrastStableGeometryAndThemeSwitchingPreserveGridState() throws Exception {
var ref = new AtomicReference<ThemeGallery>();
var window = new AtomicReference<Stage>();
fx(
() -> {
var gallery = new ThemeGallery();
ref.set(gallery);
Stage stage = new Stage();
window.set(stage);
Scene scene = new Scene(gallery, 920, 900);
gallery.install(scene);
stage.setScene(scene);
stage.show();
});
for (int i = 0; i < 5; i++) fx(() -> {});
List<String> report = new ArrayList<>();
try {
fx(
() -> {
var g = ref.get();
var selected = g.grid.selectedKeyProperty().get();
var query = g.grid.stateProperty().get().displayed();
g.draft.setText("Unfinished draft");
g.grid.setColumnWidth(
"name", new de.neitzel.grid.ColumnWidth.Explicit(475));
double[] normalSize = new double[2];
for (String theme : List.of("light", "dark", "high-contrast")) {
assertTrue(g.themes.select(theme));
g.hovered.pseudoClassStateChanged(
PseudoClass.getPseudoClass("hover"), true);
g.focused.pseudoClassStateChanged(
PseudoClass.getPseudoClass("focused"), true);
g.applyCss();
g.layout();
double target = theme.equals("high-contrast") ? 7 : 4.5;
for (var button : List.of(g.normal, g.hovered, g.focused, g.disabled))
measure(
theme,
button.getText(),
button.getTextFill(),
button,
target,
report);
measure(
theme,
"invalid",
g.invalid.lookupAll(".text").stream()
.filter(
n ->
n instanceof javafx.scene.text.Text t
&& t.getText()
.equals(
g.invalid
.getText()))
.map(n -> ((javafx.scene.text.Text) n).getFill())
.findFirst()
.orElseThrow(),
g.invalid,
target,
report);
measure(theme, "error", g.error.getTextFill(), g.error, target, report);
measure(
theme,
"warning",
g.warning.getTextFill(),
g.warning,
target,
report);
var focus =
(Color)
g.focused
.getBorder()
.getStrokes()
.getFirst()
.getTopStroke();
double focusRatio = contrast(focus, background(g.focused));
report.add(
theme
+ " | focus border | "
+ focus
+ " | "
+ background(g.focused)
+ " | "
+ focusRatio);
assertTrue(focusRatio >= 3);
var box = (Region) g.lookup(".check-box .box");
measure(
theme,
"checkbox boundary",
box.getBorder().getStrokes().getFirst().getTopStroke(),
box,
3,
report);
var icon = (javafx.scene.shape.SVGPath) g.grid.lookup(".filter-icon");
measure(theme, "filter icon", icon.getFill(), icon, 3, report);
var filterButton = (Button) g.grid.lookup(".filter-button");
assertTrue(filterButton.getAccessibleText().contains("active"));
assertFalse(filterButton.getText().isBlank());
var cells =
g.standard.lookupAll(".table-cell").stream()
.filter(
n ->
n instanceof TableCell<?, ?> cell
&& cell.getText() != null
&& cell.getText()
.startsWith("REMOVE"))
.toList();
assertEquals(1, cells.size());
var cell = (TableCell<?, ?>) cells.getFirst();
measure(
theme,
"selected TableView",
cell.getTextFill(),
cell,
target,
report);
var selectedLabel =
(Label) g.grid.lookup(".result-row:selected .label");
assertNotNull(selectedLabel);
measure(
theme,
"selected DataGrid",
selectedLabel.getTextFill(),
selectedLabel,
target,
report);
selectedLabel.getParent().setDisable(true);
g.applyCss();
measure(
theme,
"selected disabled row",
selectedLabel.getTextFill(),
selectedLabel,
target,
report);
selectedLabel.getParent().setDisable(false);
g.applyCss();
assertEquals(selected, g.grid.selectedKeyProperty().get());
assertEquals(query, g.grid.stateProperty().get().displayed());
assertEquals(
475, ((Region) g.grid.lookup(".column-cell")).getWidth(), .01);
assertEquals("Unfinished draft", g.draft.getText());
if (theme.equals("light")) {
normalSize[0] = g.normal.getWidth();
normalSize[1] = g.normal.getHeight();
} else {
assertEquals(normalSize[0], g.normal.getWidth(), .01);
assertEquals(normalSize[1], g.normal.getHeight(), .01);
}
try {
Path output = Path.of("target/theme-gallery");
Files.createDirectories(output);
WritableImage shot = g.snapshot(null, null);
BufferedImage image =
new BufferedImage(
(int) shot.getWidth(),
(int) shot.getHeight(),
BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < image.getHeight(); y++)
for (int x = 0; x < image.getWidth(); x++)
image.setRGB(x, y, shot.getPixelReader().getArgb(x, y));
ImageIO.write(
image, "png", output.resolve(theme + ".png").toFile());
} catch (java.io.IOException e) {
throw new RuntimeException(e);
}
}
});
} finally {
fx(
() -> {
ref.get().close();
window.get().close();
});
Path output = Path.of("target/theme-gallery");
Files.createDirectories(output);
Files.write(output.resolve("contrast.txt"), report);
}
}
@Test
void popupDialogAndFloatingWindowResolvedTextMeetThemeTargets() throws Exception {
List<String> report = new ArrayList<>();
fx(
() -> {
var manager = new de.neitzel.fx.theme.ThemeManager();
Stage owner = new Stage();
Button opener = new Button("Open filter");
owner.setScene(new Scene(new VBox(opener), 500, 400));
manager.register(owner.getScene());
owner.show();
var editor =
de.neitzel.fx.grid.filter.BuiltInFilterEditor.load(
new de.neitzel.fx.grid.filter.FilterEditorContext(
"x",
de.neitzel.fx.grid.filter.FilterColumn.text(),
new de.neitzel.grid.TextFilter(
"x",
de.neitzel.grid.TextFilter.Operator.EQUALS,
"Typed draft",
false),
List.of(),
de.neitzel.fx.grid.filter.FilterColumn.Checklist
.DISABLED));
var popup =
new de.neitzel.fx.grid.filter.FilterPopup(
opener,
editor,
de.neitzel.fx.grid.filter.FilterPopup.Options.defaults(),
c -> {},
c -> {});
popup.show();
try {
for (String theme : List.of("light", "dark", "high-contrast")) {
manager.select(theme);
editor.view().applyCss();
editor.view().layout();
var input = (TextField) editor.view().lookup("#operand");
var text =
input.lookupAll(".text").stream()
.filter(
n ->
n instanceof javafx.scene.text.Text t
&& t.getText()
.equals("Typed draft"))
.map(n -> (javafx.scene.text.Text) n)
.findFirst()
.orElseThrow();
measure(
theme,
"popup draft",
text.getFill(),
input,
theme.equals("high-contrast") ? 7 : 4.5,
report);
assertTrue(popup.isOpen());
assertEquals("Typed draft", input.getText());
snapshot(editor.view().getScene().getRoot(), theme + "-popup");
}
popup.close();
Alert dialog = new Alert(Alert.AlertType.INFORMATION);
dialog.initOwner(owner);
Label content = new Label("Dialog content remains readable");
dialog.getDialogPane().setContent(content);
dialog.show();
try {
for (String theme : List.of("light", "dark", "high-contrast")) {
manager.select(theme);
dialog.getDialogPane().applyCss();
dialog.getDialogPane().layout();
measure(
theme,
"dialog",
content.getTextFill(),
content,
theme.equals("high-contrast") ? 7 : 4.5,
report);
}
} finally {
dialog.close();
}
Stage floating = new Stage();
floating.initOwner(owner);
Label label = new Label("Floating editor");
floating.setScene(
new Scene(
new VBox(label, new TextField("Unfinished edit")),
400,
150));
floating.show();
try {
for (String theme : List.of("light", "dark", "high-contrast")) {
manager.select(theme);
floating.getScene().getRoot().applyCss();
measure(
theme,
"floating",
label.getTextFill(),
label,
theme.equals("high-contrast") ? 7 : 4.5,
report);
}
} finally {
floating.close();
}
} finally {
popup.close();
owner.close();
manager.close();
}
});
Path output = Path.of("target/theme-gallery");
Files.createDirectories(output);
Files.write(output.resolve("window-contrast.txt"), report);
}
static void snapshot(Parent root, String name) {
try {
Path output = Path.of("target/theme-gallery");
Files.createDirectories(output);
WritableImage shot = root.snapshot(null, null);
BufferedImage image =
new BufferedImage(
(int) shot.getWidth(),
(int) shot.getHeight(),
BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < image.getHeight(); y++)
for (int x = 0; x < image.getWidth(); x++)
image.setRGB(x, y, shot.getPixelReader().getArgb(x, y));
ImageIO.write(image, "png", output.resolve(name + ".png").toFile());
} catch (java.io.IOException error) {
throw new RuntimeException(error);
}
}
}