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
+8
View File
@@ -42,6 +42,14 @@ Some encryption classes that use format-preserving-encryption.
**Important** This is not for production use! Please use secure encryption in production!
### data-grid
Toolkit-independent filter, query/result and setup contracts for DataGrid. See [data-grid/README.md](data-grid/README.md).
### data-grid-jdbc
Optional mapped JDBC DataGrid source, initially qualified with H2. See [data-grid-jdbc/README.md](data-grid-jdbc/README.md).
### fx
JavaFX docking, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md).
+29
View File
@@ -0,0 +1,29 @@
# Optional JDBC DataGrid source
`data-grid-jdbc` depends only on the neutral `data-grid` contracts and the JDK JDBC API. It adds no driver or JavaFX dependency. The application supplies a DataSource, executor, approved simple table/key/column identifiers and a row mapper. The stable key must be unique and non-null. The initial dialect is H2, qualified with **2.5.252**; other databases are not claimed compatible.
```java
var source = new JdbcGridSource<Long, Product>(
dataSource, applicationExecutor, JdbcDialect.h2(), "products", "id",
List.of(JdbcColumn.text("name", "name", "name_key"),
JdbcColumn.decimal("price", "price", 12, 2)),
rs -> new GridRow<>(rs.getLong("id"), mapProduct(rs)), 250, 10);
```
The projection includes the stable key and all mapped physical columns. Identifiers accept only simple ASCII names, supplied by developers; SQL expressions, arbitrary joins and user-provided identifiers are intentionally unavailable. Filter operands and paging values use bound parameters. Custom conditions without a translator are explicitly rejected, never dropped. Date/time and boolean mappings are outside this initial adapter.
## Matching and consistency
Text mappings require a companion key column maintained with Java `Locale.ROOT` lowercasing whenever original values change. Store original text unchanged; checklist equality uses it. The adapter does not repair inconsistent application data or use SQL LOWER. Text sorting uses comparison keys; nulls sort last in either direction, followed by the stable key ascending. The H2 dialect rejects configured linguistic collation; default OFF collation is qualified against Java String comparison, including supplementary Unicode and combining marks. LIKE escapes `%`, `_` and the escape character `!`; all operands remain literal.
Integer operands must fit a signed long exactly. Decimal mappings enforce precision and scale with no rounding; numerically equal values with extra trailing zeros remain valid. The application must use matching SQL types (the example uses BIGINT and DECIMAL(12,2)). Missing/present, exact checklist membership and AND-combined filters are supported. The translator validates both condition type and column type before borrowing a connection.
Each request borrows one idle auto-commit connection, checks H2/collation, starts H2's vendor SNAPSHOT isolation (6), counts and fetches in the same transaction, commits before returning, and restores isolation/auto-commit before close. A non-auto-commit borrowed connection is rejected rather than committing an application transaction. The mapper must not mutate connection settings or execute writes. The application owns transaction cleanliness and pool reset policy. Close failures fail the request; cleanup errors are retained as suppressed exceptions.
All-mode checks its warning threshold after counting and before selecting rows. If approval is required, it rolls back and releases all borrowed resources before completing with `AllRowsConfirmationRequired`. Approval starts a fresh snapshot and recounts: it acknowledges an unpaged load, not a fixed maximum number of rows. The existing coordinator handles query-scoped approval and stale completions. Never save approval in a setup.
Every prepared query has the configured JDBC timeout. Cancellation attempts `Statement.cancel`, marks the request cancelled and stops mapping; cancellation is best effort and does not interrupt embedded driver threads. A cancelled future can complete before worker cleanup finishes, so application shutdown must drain the executor before disposing the DataSource. Closing a DataGrid does not own either resource.
The example explicitly supplies current-page checklist candidates; the adapter does not pretend a page is a complete source-wide candidate set. Applications needing source-wide candidates supply their own `FilterCandidates.Provider`, independently of SQL condition execution.
See [the complete runnable example](../fx-example/docs/product-grid.md) for fixture parity, fault controls, saved setups and limitations.
+5
View File
@@ -0,0 +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-SNAPSHOT</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>
@@ -0,0 +1,65 @@
package de.neitzel.grid.jdbc;
import de.neitzel.grid.*;
import java.math.*;
import java.util.*;
/** Approved physical identifier and scalar domain. Text keys are maintained by the application. */
public record JdbcColumn(
String id, String sqlName, Kind kind, String comparisonKey, int precision, int scale) {
public enum Kind {
TEXT,
INTEGER,
DECIMAL
}
public JdbcColumn {
if (id == null || id.isBlank())
throw new IllegalArgumentException("Missing column identity");
identifier(sqlName);
Objects.requireNonNull(kind);
if (kind == Kind.TEXT) identifier(comparisonKey);
else if (comparisonKey != null)
throw new IllegalArgumentException("Only text has comparison keys");
if (kind == Kind.DECIMAL && (precision < 1 || scale < 0 || scale > precision))
throw new IllegalArgumentException("Invalid decimal domain");
}
public static JdbcColumn text(String id, String column, String key) {
return new JdbcColumn(id, column, Kind.TEXT, key, 0, 0);
}
public static JdbcColumn integer(String id, String column) {
return new JdbcColumn(id, column, Kind.INTEGER, null, 0, 0);
}
public static JdbcColumn decimal(String id, String column, int precision, int scale) {
return new JdbcColumn(id, column, Kind.DECIMAL, null, precision, scale);
}
static String identifier(String name) {
if (name == null || !name.matches("[A-Za-z_][A-Za-z0-9_]*"))
throw new IllegalArgumentException("Expected an approved simple SQL identifier");
return name;
}
void number(BigDecimal value) {
if (kind == Kind.INTEGER) value.longValueExact();
else if (kind == Kind.DECIMAL) {
if (value.setScale(scale, RoundingMode.UNNECESSARY).precision() > precision)
throw new IllegalArgumentException("Decimal exceeds " + precision + "," + scale);
} else
throw new IllegalArgumentException("Numeric condition requires numeric column " + id);
}
Object value(FilterValue value) {
if (kind == Kind.TEXT && value instanceof FilterValue.Text t) return t.value();
if (kind == Kind.INTEGER && value instanceof FilterValue.IntegerValue n) return n.value();
if (kind == Kind.DECIMAL && value instanceof FilterValue.Decimal n) {
number(n.value());
return n.value();
}
throw new IllegalArgumentException("Checklist type does not match " + id);
}
}
@@ -0,0 +1,48 @@
package de.neitzel.grid.jdbc;
import java.sql.*;
/** Explicit dialect boundary; only H2 is qualified by this delivery. */
public interface JdbcDialect {
String executionId();
void beginSnapshot(Connection connection, int timeoutSeconds) throws SQLException;
String paging();
private static ResultSet execute(PreparedStatement statement, int timeoutSeconds)
throws SQLException {
statement.setQueryTimeout(timeoutSeconds);
return statement.executeQuery();
}
/** H2 default binary/Java-string collation and its vendor snapshot isolation level. */
static JdbcDialect h2() {
return new JdbcDialect() {
public String executionId() {
return "jdbc-h2";
}
public void beginSnapshot(Connection connection, int timeoutSeconds)
throws SQLException {
if (!connection.getMetaData().getDatabaseProductName().equals("H2"))
throw new SQLException("H2 dialect requires H2");
try (var s =
connection.prepareStatement(
"SELECT SETTING_VALUE FROM INFORMATION_SCHEMA.SETTINGS"
+ " WHERE SETTING_NAME = 'COLLATION'");
var rs = execute(s, timeoutSeconds)) {
if (rs.next() && !rs.getString(1).equals("OFF"))
throw new SQLException("Only H2 OFF collation is qualified");
}
connection.setTransactionIsolation(
6); // H2 TRANSACTION_SNAPSHOT, not JDBC REPEATABLE_READ.
connection.setAutoCommit(false);
}
public String paging() {
return " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
}
};
}
}
@@ -0,0 +1,321 @@
package de.neitzel.grid.jdbc;
import de.neitzel.grid.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import javax.sql.DataSource;
/** Mapped, parameterized queries. The application owns the DataSource and executor. */
public final class JdbcGridSource<K, T> implements GridSource<K, T> {
@FunctionalInterface
public interface RowMapper<K, T> {
GridRow<K, T> read(ResultSet result) throws SQLException;
}
private final DataSource dataSource;
private final Executor executor;
private final JdbcDialect dialect;
private final String table, key, projection;
private final Map<String, JdbcColumn> columns;
private final RowMapper<K, T> mapper;
private final int timeoutSeconds;
private final SourceCapabilities capabilities;
public JdbcGridSource(
DataSource dataSource,
Executor executor,
JdbcDialect dialect,
String table,
String key,
List<JdbcColumn> columns,
RowMapper<K, T> mapper,
int maximumPageSize,
int timeoutSeconds) {
this.dataSource = Objects.requireNonNull(dataSource);
this.executor = Objects.requireNonNull(executor);
this.dialect = Objects.requireNonNull(dialect);
this.table = JdbcColumn.identifier(table);
this.key = JdbcColumn.identifier(key);
this.mapper = Objects.requireNonNull(mapper);
if (timeoutSeconds < 1)
throw new IllegalArgumentException("A positive query timeout is required");
this.timeoutSeconds = timeoutSeconds;
capabilities = new SourceCapabilities(true, true, maximumPageSize);
var mapped = new LinkedHashMap<String, JdbcColumn>();
var selected = new LinkedHashSet<String>();
selected.add(key);
for (var c : columns) {
if (mapped.put(c.id(), c) != null)
throw new IllegalArgumentException("Duplicate column");
selected.add(c.sqlName());
}
this.columns = Map.copyOf(mapped);
projection = String.join(",", selected);
}
public SourceCapabilities capabilities() {
return capabilities;
}
public String filterExecutionId() {
return dialect.executionId();
}
private JdbcColumn column(String id) {
var c = columns.get(id);
if (c == null) throw new IllegalArgumentException("Unknown column: " + id);
return c;
}
public void validateFilter(FilterCondition filter) {
compile(filter, new ArrayList<>());
}
public QueryExecution<K, T> query(GridQuery query) {
return query(query, QueryOptions.defaults());
}
public QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
Objects.requireNonNull(query);
Objects.requireNonNull(options);
var execution = new Execution();
try {
capabilities.validate(query.page());
var parameters = new ArrayList<Object>();
String where = where(query.filters(), parameters);
var order = new ArrayList<String>();
for (var sort : query.sort()) {
var c = column(sort.columnId());
order.add(
(c.kind() == JdbcColumn.Kind.TEXT ? c.comparisonKey() : c.sqlName())
+ (sort.direction() == SortKey.Direction.ASCENDING
? " ASC"
: " DESC")
+ " NULLS LAST");
}
order.add(key + " ASC");
String rows =
"SELECT "
+ projection
+ " FROM "
+ table
+ where
+ " ORDER BY "
+ String.join(",", order)
+ (query.page() instanceof PageRequest.Paged ? dialect.paging() : "");
executor.execute(
() -> {
try {
execution.check();
execution.result.complete(
execute(execution, query, options, where, rows, parameters));
} catch (Exception failure) {
execution.result.completeExceptionally(failure);
}
});
} catch (RuntimeException failure) {
execution.result.completeExceptionally(failure);
}
return execution;
}
private PageResult<K, T> execute(
Execution execution,
GridQuery query,
QueryOptions options,
String where,
String sql,
List<Object> parameters)
throws SQLException {
try (var connection = dataSource.getConnection()) {
boolean auto = connection.getAutoCommit();
int isolation = connection.getTransactionIsolation();
if (!auto)
throw new SQLException("Borrowed connection must be idle with autoCommit=true");
Throwable primary = null;
try {
dialect.beginSnapshot(connection, timeoutSeconds);
execution.check();
long count;
try (var statement =
execution.prepare(
connection,
"SELECT COUNT(*) FROM " + table + where,
parameters);
var rs = statement.executeQuery()) {
rs.next();
count = rs.getLong(1);
}
execution.active.set(null);
execution.check();
if (query.page() instanceof PageRequest.All
&& count > options.allWarningThreshold()
&& !options.allApproved()) throw new AllRowsConfirmationRequired(count);
var values = new ArrayList<>(parameters);
if (query.page() instanceof PageRequest.Paged p) {
values.add(p.offset());
values.add(p.pageSize());
}
var result = new ArrayList<GridRow<K, T>>();
try (var statement = execution.prepare(connection, sql, values);
var rs = statement.executeQuery()) {
while (rs.next()) {
execution.check();
result.add(mapper.read(rs));
}
}
execution.active.set(null);
execution.check();
var page =
new PageResult<>(
query.page(),
result,
OptionalLong.of(count),
query.page() instanceof PageRequest.Paged p
&& count - p.offset() > p.pageSize());
connection.commit();
return page;
} catch (SQLException | RuntimeException | Error failure) {
primary = failure;
throw failure;
} finally {
execution.active.set(null);
SQLException cleanup = null;
try {
connection.rollback();
} catch (SQLException ex) {
cleanup = ex;
}
try {
connection.setTransactionIsolation(isolation);
} catch (SQLException ex) {
if (cleanup == null) cleanup = ex;
else cleanup.addSuppressed(ex);
}
try {
connection.setAutoCommit(auto);
} catch (SQLException ex) {
if (cleanup == null) cleanup = ex;
else cleanup.addSuppressed(ex);
}
if (cleanup != null) {
if (primary != null) primary.addSuppressed(cleanup);
else throw cleanup;
}
}
}
}
private String where(List<FilterCondition> filters, List<Object> args) {
if (filters.isEmpty()) return "";
return " WHERE "
+ String.join(
" AND ", filters.stream().map(f -> "(" + compile(f, args) + ")").toList());
}
private String compile(FilterCondition f, List<Object> args) {
var c = column(f.columnId());
String field = c.sqlName();
if (f instanceof MissingFilter m)
return field + (m.missing() ? " IS NULL" : " IS NOT NULL");
if (f instanceof TextFilter t) {
if (c.kind() != JdbcColumn.Kind.TEXT)
throw new IllegalArgumentException("Text filter requires text column");
field = t.caseSensitive() ? field : c.comparisonKey();
String operand = t.caseSensitive() ? t.operand() : t.operand().toLowerCase(Locale.ROOT);
if (t.operator() == TextFilter.Operator.EQUALS) {
args.add(operand);
return field + " = ?";
}
operand = operand.replace("!", "!!").replace("%", "!%").replace("_", "!_");
args.add(
switch (t.operator()) {
case CONTAINS -> "%" + operand + "%";
case STARTS_WITH -> operand + "%";
case ENDS_WITH -> "%" + operand;
default -> throw new IllegalStateException();
});
return field + " LIKE ? ESCAPE '!'";
}
if (f instanceof NumericFilter n) {
c.number(n.operand());
args.add(n.operand());
if (n.operator() == NumericFilter.Operator.RANGE) {
c.number(n.upper());
args.add(n.upper());
return field + " BETWEEN ? AND ?";
}
return field
+ switch (n.operator()) {
case EQUALS -> " = ?";
case LESS -> " < ?";
case LESS_OR_EQUAL -> " <= ?";
case GREATER -> " > ?";
case GREATER_OR_EQUAL -> " >= ?";
default -> throw new IllegalStateException();
};
}
if (f instanceof ValueFilter v) {
var marks = new ArrayList<String>();
for (var value : v.values()) {
args.add(c.value(value));
marks.add("?");
}
String membership =
marks.isEmpty() ? "1=0" : field + " IN (" + String.join(",", marks) + ")";
return membership + (v.includeMissing() ? " OR " + field + " IS NULL" : "");
}
throw new UnsupportedOperationException("JDBC does not support filter: " + f.typeId());
}
private final class Execution implements QueryExecution<K, T> {
final CompletableFuture<PageResult<K, T>> result = new CompletableFuture<>();
final AtomicBoolean cancelled = new AtomicBoolean();
final AtomicReference<Statement> active = new AtomicReference<>();
public CompletionStage<PageResult<K, T>> result() {
return result;
}
public void cancel() {
cancelled.set(true);
var statement = active.get();
if (statement != null)
try {
statement.cancel();
} catch (SQLException ignored) {
/* Best effort; obsolete publication is independently rejected. */
}
result.cancel(false);
}
void check() {
if (cancelled.get()) throw new CancellationException("JDBC request cancelled");
}
PreparedStatement prepare(Connection connection, String sql, List<Object> parameters)
throws SQLException {
check();
var statement = connection.prepareStatement(sql);
try {
statement.setQueryTimeout(timeoutSeconds);
for (int i = 0; i < parameters.size(); i++)
statement.setObject(i + 1, parameters.get(i));
active.set(statement);
check();
return statement;
} catch (SQLException | RuntimeException failure) {
try {
statement.close();
} catch (SQLException close) {
failure.addSuppressed(close);
}
throw failure;
}
}
}
}
+39
View File
@@ -0,0 +1,39 @@
# data-grid foundations
Toolkit-independent contracts for opt-in DataGrid development. This module does not depend on JavaFX or a JDBC driver. Parent-provided compile/test tooling is inherited, including Lombok annotation processing; immutable public models are Java records.
- `FilterCondition` is open to custom immutable implementations. Built-ins provide literal text, exact decimal, missing/present and explicit checklist conditions. A custom type must declare capabilities separately; editor registration is in `fx`, codecs are in optional `gson`, and adapter compilation remains separate.
- `GridQuery` combines one condition per column with AND and ordered sort keys. The source must append its stable row-key tie-breaker and validate column types, precision, matching semantics and capabilities.
- `PageRequest.Paged` uses zero-based indexes; `All` is explicit. `PageResult` defensively copies lists and checks row identities/count consistency, allowing empty out-of-range pages for coordinator recovery.
- `GridSource` separates asynchronous result completion from best-effort cancellation. The coordinator must independently discard obsolete completions. Models inside `GridRow` remain application-owned; they are not deep-copied.
- `GridSetup` separates format and definition versions, default versus explicit widths, and All versus paging. It rejects persisted nonzero page indexes. Selection, credentials and warning approvals are deliberately absent.
`TextFilter.matches` uses Locale.ROOT lowercasing with no normalization; `%` and `_` are literal. `NumericFilter` accepts BigDecimal operands and compares numerically, avoiding double conversion. The mapping layer remains responsible for the declared integer/decimal domain and scale limits. `FilterValue.Decimal` canonicalizes scale so checklist membership treats 1.0 and 1.00 equally. Text checklist membership is exact.
`MemoryGridSource` now executes mapped local queries, and `GridCoordinator` manages guarded requests, All confirmation, stale-result rejection, recovery and publication. Definition migrations are available here and JSON codecs are in optional `gson`; SQL execution is available in the optional [data-grid-jdbc module](../data-grid-jdbc/README.md). No executor is created or shut down by these classes.
Run from the repository root: `./mvnw -pl data-grid test`.
## Local execution
`MemoryGridSource<K,T>` accepts a collection supplier, stable-key function and comparator, explicit `MemoryColumn<T>` scalar mappings, an application-owned executor and a maximum page size. Built-in mappings cover text, long integers, arbitrary-precision decimals and booleans; null mapping values mean missing. Per-column custom filter compilers explicitly opt into additional local conditions; unsupported types fail rather than being ignored. Numeric mapping constraints beyond the generic long/BigDecimal domains remain the application's responsibility.
A query captures collection membership, keys and mapped scalar values on the calling thread. The supplier/readers must provide a consistent view (for example, call from the FX thread for FX-owned models, or synchronize the snapshot). Filtering, sorting and slicing run on the supplied executor. This preserves scalar/count consistency across later model changes without reading FX-owned properties on a worker. Model objects in results are application-owned references, not deep copies. Snapshot capture is O(n) caller-thread work; use a source with its own background snapshot mechanism for very large mutable datasets.
Filters combine with AND. Text sort uses Locale.ROOT lowercase lexical comparison; nulls remain last in either direction. The key comparator provides the final tie-breaker and must distinguish unique keys. Data is never reordered in the source collection.
`query(query, QueryOptions)` is the guarded All protocol. Without attempt-scoped approval, a count above the configured threshold fails with `AllRowsConfirmationRequired` before sorting/materializing the unpaged result. The caller asks the person, then submits the same query with approval in a **fresh** snapshot. A changed query or later attempt needs fresh approval. Sources not overriding the guarded overload reject All by default. Do not fetch All first and then ask.
## Owner-thread coordinator
Create `GridCoordinator` on its owner thread and supply an executor that **queues** callbacks to that same thread (`Platform::runLater` for FX). Public mutators also run there. Observers should not throw. A publisher may reject a result before committing it, allowing the coordinator to preserve its prior displayed state. Observer-triggered requests are queued rather than applied reentrantly.
State exposes requested versus displayed query, result, phase and error. The coordinator validates page identity and declared exact-count support, attempts cancellation but independently ignores superseded successes/failures, and permits only one corrective page request per user attempt. A guard may approve/block edits asynchronously. All confirmation is asynchronous and never retains an execution snapshot while awaiting input.
Rejected guards and declined All warnings restore the displayed query. A replacement source is committed only when it successfully publishes a result; cancellation keeps the previous source. Retry uses the latest requested query/source. Close invalidates pending callbacks and drops retained results without closing application sources/executors. Source selection and loaded row identity are presentation responsibilities.
Collection changes do not automatically trigger requests in this slice. Call refresh explicitly from application mutation handlers; automatic collection subscriptions can be added without changing the query contract.
## Saved setups
`GridDefinition.prepare` applies explicit definition migrations and validates column types/order, widths and source support. `GridSetup.ColumnState` carries stable type IDs. JSON is provided separately by `de.neitzel.lib:gson`; `data-grid` does not depend on JavaFX or Gson. See the [saved setup guide](../fx/docs/saved-setups.md).
+6
View File
@@ -0,0 +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-SNAPSHOT</version></parent>
<artifactId>data-grid</artifactId>
<description>Toolkit-independent filter, query and grid setup contracts</description>
</project>
@@ -0,0 +1,19 @@
package de.neitzel.grid;
/**
* Source stopped before materializing an unpaged result. Any snapshot/transaction has been
* released.
*/
public final class AllRowsConfirmationRequired extends RuntimeException {
private final long count;
public AllRowsConfirmationRequired(long count) {
super("Loading all " + count + " matching rows requires confirmation");
if (count < 0) throw new IllegalArgumentException("Negative count");
this.count = count;
}
public long count() {
return count;
}
}
@@ -0,0 +1,11 @@
package de.neitzel.grid;
final class Checks {
private Checks() {}
static String id(String value) {
if (value == null || value.isBlank())
throw new IllegalArgumentException("Identifier must not be blank");
return value;
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
/** Saved sizing intention, independent of a theme's current default. */
public sealed interface ColumnWidth {
record Default() implements ColumnWidth {}
record Explicit(double value) implements ColumnWidth {
public Explicit {
if (!Double.isFinite(value) || value <= 0)
throw new IllegalArgumentException("Width must be finite and positive");
}
}
}
@@ -0,0 +1,161 @@
package de.neitzel.grid;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/** Explicit, typed candidate lookup. A session owns its snapshot and pending lookups. */
public final class FilterCandidates {
private FilterCandidates() {}
public enum Scope {
CURRENT_PAGE,
SOURCE_WIDE
}
/** A null value explicitly represents missing; labels never determine equality. */
public record Candidate(FilterValue value, String label) {
public Candidate {
Objects.requireNonNull(label);
}
}
public record Context(String columnId, Scope scope, List<FilterCondition> otherFilters) {
public Context {
Checks.id(columnId);
Objects.requireNonNull(scope);
otherFilters = List.copyOf(otherFilters);
if (otherFilters.stream().anyMatch(f -> f.columnId().equals(columnId)))
throw new IllegalArgumentException("Candidate context must exclude its own filter");
}
}
public record Request(Context context, String search, int offset, int limit) {
public Request {
Objects.requireNonNull(context);
Objects.requireNonNull(search);
if (offset < 0 || limit < 1)
throw new IllegalArgumentException("Invalid candidate batch");
}
}
public record Batch(List<Candidate> candidates, boolean hasMore) {
public Batch {
candidates = List.copyOf(candidates);
}
}
public interface Provider {
Set<Scope> scopes();
Session open(Context context);
}
public interface Session extends AutoCloseable {
CompletionStage<Batch> load(Request request);
@Override
void close();
}
/** Captures current-page values at open, never claims source-wide completeness. */
public static Provider currentPage(Supplier<List<Candidate>> values) {
return snapshot(
Set.of(Scope.CURRENT_PAGE),
c -> {
var copy = List.copyOf(values.get());
return () -> copy;
},
Runnable::run);
}
/** Capture on open's thread; evaluate the captured snapshot on the supplied executor. */
public static Provider snapshot(
Set<Scope> scopes,
Function<Context, Supplier<List<Candidate>>> capture,
Executor executor) {
Set<Scope> supported = Set.copyOf(scopes);
Objects.requireNonNull(capture);
Objects.requireNonNull(executor);
return new Provider() {
public Set<Scope> scopes() {
return supported;
}
public Session open(Context context) {
if (!supported.contains(context.scope()))
throw new UnsupportedOperationException(
"Candidate scope unavailable: " + context.scope());
var captured =
new java.util.concurrent.atomic.AtomicReference<>(
Objects.requireNonNull(capture.apply(context)));
return new Session() {
private boolean closed;
private final Set<CompletableFuture<Batch>> pending = new HashSet<>();
public synchronized CompletionStage<Batch> load(Request request) {
if (closed) throw new IllegalStateException("Candidate session closed");
if (!context.equals(request.context()))
throw new IllegalArgumentException("Wrong candidate context");
var future = new CompletableFuture<Batch>();
pending.add(future);
try {
executor.execute(
() -> {
try {
if (future.isDone()) return;
Map<FilterValue, Candidate> distinct =
new LinkedHashMap<>();
var work = captured.get();
if (work == null) {
future.cancel(false);
return;
}
for (var candidate : work.get()) {
if (future.isDone()) return;
if (candidate
.label()
.toLowerCase(Locale.ROOT)
.contains(
request.search()
.toLowerCase(Locale.ROOT)))
distinct.putIfAbsent(
candidate.value(), candidate);
}
var found = new ArrayList<>(distinct.values());
int from = Math.min(request.offset(), found.size());
int to =
(int)
Math.min(
(long) from + request.limit(),
found.size());
future.complete(
new Batch(
found.subList(from, to),
to < found.size()));
} catch (RuntimeException error) {
future.completeExceptionally(error);
} finally {
synchronized (this) {
pending.remove(future);
}
}
});
} catch (RuntimeException error) {
pending.remove(future);
future.completeExceptionally(error);
}
return future;
}
public synchronized void close() {
closed = true;
captured.set(null);
for (var future : pending) future.cancel(false);
pending.clear();
}
};
}
};
}
}
@@ -0,0 +1,15 @@
package de.neitzel.grid;
import java.util.Set;
/**
* Independent registration capabilities; a translator must additionally validate each concrete
* condition.
*/
public record FilterCapabilities(
boolean localEvaluation, boolean persistence, Set<String> adapters) {
public FilterCapabilities {
adapters = Set.copyOf(adapters);
adapters.forEach(Checks::id);
}
}
@@ -0,0 +1,11 @@
package de.neitzel.grid;
/**
* Immutable column condition. Custom implementations must preserve value semantics and declare a
* stable type ID.
*/
public interface FilterCondition {
String columnId();
String typeId();
}
@@ -0,0 +1,24 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.Objects;
/** Immutable portable checklist values; missing is represented separately by ValueFilter. */
public sealed interface FilterValue {
record Text(String value) implements FilterValue {
public Text {
Objects.requireNonNull(value);
}
}
record IntegerValue(long value) implements FilterValue {}
record Decimal(BigDecimal value) implements FilterValue {
public Decimal {
Objects.requireNonNull(value);
value = value.stripTrailingZeros();
}
}
record BooleanValue(boolean value) implements FilterValue {}
}
@@ -0,0 +1,469 @@
package de.neitzel.grid;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/**
* Serial, owner-thread coordinator. Supply an executor that dispatches callbacks to the creating
* thread, always enqueueing rather than invoking inline (for JavaFX, Platform::runLater). It never
* owns/shuts down sources or executors.
*/
public final class GridCoordinator<K, T> implements AutoCloseable {
public enum Phase {
IDLE,
GUARD,
LOADING,
CONFIRMATION,
READY,
ERROR,
CLOSED
}
public record State<K, T>(
long generation,
GridQuery requested,
GridQuery displayed,
PageResult<K, T> result,
Phase phase,
Throwable error,
long sourceVersion) {}
private final Thread owner = Thread.currentThread();
private final Executor dispatch;
private final Consumer<State<K, T>> observer;
private final Consumer<PageResult<K, T>> publisher;
private GridSource<K, T> source;
private GridSource<K, T> requestedSource;
private GridSource.QueryExecution<K, T> execution;
private State<K, T> state = new State<>(0, null, null, null, Phase.IDLE, null, 0);
private long generation, sourceVersion;
private long threshold = 1000;
private boolean closed;
private boolean notifying;
private boolean restoring;
private State<K, T> restoreBefore;
private Consumer<PageResult<K, T>> requestPublisher;
private Function<GridQuery, CompletionStage<Boolean>> guard =
q -> CompletableFuture.completedFuture(true);
private BiFunction<GridQuery, Long, CompletionStage<Boolean>> confirmation =
(q, n) ->
CompletableFuture.failedFuture(
new IllegalStateException("No All confirmation handler configured"));
public GridCoordinator(
GridSource<K, T> source,
Executor dispatch,
Consumer<State<K, T>> observer,
Consumer<PageResult<K, T>> publisher) {
this.source = Objects.requireNonNull(source);
this.requestedSource = source;
this.dispatch = Objects.requireNonNull(dispatch);
this.observer = Objects.requireNonNull(observer);
this.publisher = Objects.requireNonNull(publisher);
}
public State<K, T> state() {
return state;
}
public SourceCapabilities capabilities() {
check();
return requestedSource.capabilities();
}
public String filterExecutionId() {
check();
return requestedSource.filterExecutionId();
}
public void validateFilters(List<FilterCondition> filters) {
check();
filters.forEach(requestedSource::validateFilter);
}
public void setGuard(Function<GridQuery, CompletionStage<Boolean>> guard) {
check();
this.guard = Objects.requireNonNull(guard);
}
public void setConfirmation(
BiFunction<GridQuery, Long, CompletionStage<Boolean>> confirmation) {
check();
this.confirmation = Objects.requireNonNull(confirmation);
}
public void setAllWarningThreshold(long value) {
check();
if (value < 0) throw new IllegalArgumentException("Negative warning threshold");
threshold = value;
}
public void request(GridQuery query) {
request(requestedSource, query);
}
/** A replacement source becomes committed only after its guarded query succeeds. */
public void request(GridSource<K, T> replacement, GridQuery query) {
request(replacement, query, () -> {}, publisher, false);
}
/** A newer layout-only operation supersedes pending restoration without querying. */
public void cancelRestore() {
check();
if (!restoring) return;
if (notifying) {
dispatch.execute(
() -> {
if (!closed) cancelRestore();
});
return;
}
++generation;
cancelExecution();
var before = restoreBefore;
restore(before);
}
public boolean isRestoring() {
return restoring;
}
/**
* Validated restore: one guard, then one initial query, then atomic application publication.
*/
public void restoreSetup(
GridQuery query, Runnable afterGuard, Consumer<PageResult<K, T>> publish) {
request(
requestedSource,
query,
Objects.requireNonNull(afterGuard),
Objects.requireNonNull(publish),
true);
}
/** Report decode/preparation failure without querying or discarding displayed data. */
public void rejectSetup(Throwable failure) {
check();
if (notifying) {
dispatch.execute(
() -> {
if (!closed) rejectSetup(failure);
});
return;
}
++generation;
cancelExecution();
restoring = false;
restoreBefore = null;
requestPublisher = null;
requestedSource = source;
update(state.displayed(), Phase.ERROR, Objects.requireNonNull(failure));
}
private void request(
GridSource<K, T> replacement,
GridQuery query,
Runnable afterGuard,
Consumer<PageResult<K, T>> publish,
boolean transactional) {
check();
Objects.requireNonNull(replacement);
Objects.requireNonNull(query);
if (notifying) {
dispatch.execute(
() -> {
if (!closed)
request(replacement, query, afterGuard, publish, transactional);
});
return;
}
long token = ++generation;
cancelExecution();
requestedSource = replacement;
var before =
new State<K, T>(
token,
state.displayed() != null ? state.displayed() : state.requested(),
state.displayed(),
state.result(),
state.result() == null ? Phase.IDLE : Phase.READY,
null,
sourceVersion);
restoring = transactional;
restoreBefore = transactional ? before : null;
requestPublisher = publish;
update(query, Phase.GUARD, null);
if (!current(token)) return;
try {
replacement.capabilities().validate(query.page());
await(
Objects.requireNonNull(guard.apply(query)),
token,
(allowed, failure) -> {
if (failure != null) {
fail(query, failure);
return;
}
if (!Boolean.TRUE.equals(allowed)) {
restore(before);
return;
}
try {
afterGuard.run();
if (current(token))
execute(replacement, query, token, false, false, before, threshold);
} catch (RuntimeException error) {
if (current(token)) fail(query, error);
}
});
} catch (RuntimeException failure) {
fail(query, failure);
}
}
public void retry() {
check();
if (state.requested() != null) request(state.requested());
}
public void refresh() {
retry();
}
private void execute(
GridSource<K, T> target,
GridQuery query,
long token,
boolean approved,
boolean corrected,
State<K, T> before,
long attemptThreshold) {
if (!current(token)) return;
update(query, Phase.LOADING, null);
if (!current(token)) return;
try {
execution =
Objects.requireNonNull(
target.query(query, new QueryOptions(attemptThreshold, approved)),
"Missing execution");
await(
Objects.requireNonNull(execution.result()),
token,
(result, failure) -> {
execution = null;
if (failure != null) {
Throwable cause = unwrap(failure);
if (cause instanceof AllRowsConfirmationRequired required
&& query.page() instanceof PageRequest.All
&& !approved) {
update(query, Phase.CONFIRMATION, null);
if (!current(token)) return;
try {
await(
Objects.requireNonNull(
confirmation.apply(query, required.count())),
token,
(allowed, error) -> {
if (error != null) fail(query, error);
else if (Boolean.TRUE.equals(allowed))
execute(
target,
query,
token,
true,
corrected,
before,
attemptThreshold);
else restore(before);
});
} catch (RuntimeException error) {
fail(query, error);
}
} else fail(query, cause);
return;
}
try {
Objects.requireNonNull(result, "Missing page result");
if (!query.page().equals(result.request()))
throw new IllegalArgumentException(
"Source returned a different page request");
if (target.capabilities().exactTotal() && result.total().isEmpty())
throw new IllegalArgumentException(
"Source promised an exact count");
if (query.page() instanceof PageRequest.Paged page
&& page.pageIndex() > 0
&& result.rows().isEmpty()
&& (result.total().isEmpty()
|| result.total().getAsLong() > 0)) {
if (corrected)
throw new IllegalStateException(
"Page changed again during recovery; retry");
long last =
result.total().isPresent()
? (result.total().getAsLong() - 1) / page.pageSize()
: 0;
execute(
target,
new GridQuery(
query.filters(),
query.sort(),
new PageRequest.Paged(last, page.pageSize())),
token,
approved,
true,
before,
attemptThreshold);
return;
}
notifying = true;
try {
requestPublisher.accept(result);
} finally {
notifying = false;
}
if (!current(token)) return;
if (source != target) {
source = target;
sourceVersion++;
}
restoring = false;
restoreBefore = null;
requestPublisher = null;
state =
new State<>(
generation,
query,
query,
result,
Phase.READY,
null,
sourceVersion);
notifyState();
} catch (RuntimeException invalid) {
fail(query, invalid);
}
});
} catch (RuntimeException failure) {
execution = null;
fail(query, failure);
}
}
private <V> void await(
CompletionStage<V> stage, long token, BiConsumer<V, Throwable> callback) {
stage.whenComplete(
(value, failure) ->
dispatch.execute(
() -> {
checkThread();
if (current(token)) callback.accept(value, failure);
}));
}
private void restore(State<K, T> before) {
restoring = false;
restoreBefore = null;
requestPublisher = null;
requestedSource = source;
state =
new State<>(
generation,
before.requested(),
before.displayed(),
before.result(),
before.phase(),
null,
sourceVersion);
notifyState();
}
private void update(GridQuery query, Phase phase, Throwable error) {
state =
new State<>(
generation,
query,
state.displayed(),
state.result(),
phase,
error,
sourceVersion);
notifyState();
}
private void notifyState() {
notifying = true;
try {
observer.accept(state);
} finally {
notifying = false;
}
}
private void fail(GridQuery query, Throwable error) {
if (closed) return;
if (restoring) {
query = restoreBefore.requested();
requestedSource = source;
restoring = false;
restoreBefore = null;
}
requestPublisher = null;
update(query, Phase.ERROR, unwrap(error));
}
private static Throwable unwrap(Throwable failure) {
while ((failure instanceof CompletionException || failure instanceof ExecutionException)
&& failure.getCause() != null) failure = failure.getCause();
return failure;
}
private boolean current(long token) {
return !closed && generation == token;
}
private void cancelExecution() {
if (execution != null) {
var old = execution;
execution = null;
try {
old.cancel();
} catch (RuntimeException ignored) {
/* cancellation is advisory; identity still rejects stale completion */
}
}
}
private void checkThread() {
if (Thread.currentThread() != owner)
throw new IllegalStateException("Use the coordinator owner thread");
}
private void check() {
checkThread();
if (closed) throw new IllegalStateException("Coordinator is closed");
}
public void close() {
checkThread();
if (closed) return;
closed = true;
restoring = false;
restoreBefore = null;
requestPublisher = null;
generation++;
cancelExecution();
state =
new State<>(
generation,
state.requested(),
null,
null,
Phase.CLOSED,
null,
sourceVersion);
source = null;
requestedSource = null;
notifyState();
}
}
@@ -0,0 +1,129 @@
package de.neitzel.grid;
import java.util.*;
import java.util.function.*;
/** Definition identity and layout constraints, independent of JSON and JavaFX. */
public record GridDefinition(String id, int version, List<Column> columns) {
public record Column(
String id,
String type,
double defaultWidth,
double minimumWidth,
double maximumWidth,
int fixedPosition) {
public Column {
Checks.id(id);
Checks.id(type);
if (!Double.isFinite(defaultWidth)
|| !Double.isFinite(minimumWidth)
|| !Double.isFinite(maximumWidth)
|| minimumWidth <= 0
|| defaultWidth < minimumWidth
|| maximumWidth < defaultWidth
|| fixedPosition < -1)
throw new IllegalArgumentException("Invalid column constraints: " + id);
}
}
public GridDefinition {
Checks.id(id);
if (version < 1) throw new IllegalArgumentException("Invalid definition version");
columns = List.copyOf(columns);
if (columns.isEmpty()) throw new IllegalArgumentException("Missing columns");
Set<String> ids = new HashSet<>();
for (int i = 0; i < columns.size(); i++) {
var c = columns.get(i);
if (!ids.add(c.id())) throw new IllegalArgumentException("Duplicate definition column");
if (c.fixedPosition() != -1 && c.fixedPosition() != i)
throw new IllegalArgumentException("Fixed column must match declaration position");
}
}
public record Prepared(GridSetup setup, List<String> adjustments) {
public Prepared {
Objects.requireNonNull(setup);
adjustments = List.copyOf(adjustments);
}
}
/**
* Each migration explicitly advances exactly one definition version; output is fully validated.
*/
public Prepared prepare(
GridSetup input,
Map<Integer, UnaryOperator<GridSetup>> migrations,
SourceCapabilities source,
Consumer<FilterCondition> validateFilter) {
Objects.requireNonNull(input);
Objects.requireNonNull(migrations);
if (input.formatVersion() != 1)
throw new IllegalArgumentException(
"Unsupported setup format version: " + input.formatVersion());
if (!id.equals(input.definitionId()))
throw new IllegalArgumentException(
"Setup belongs to another grid definition: " + input.definitionId());
if (input.definitionVersion() > version)
throw new IllegalArgumentException("Setup uses a future definition version");
GridSetup setup = input;
while (setup.definitionVersion() < version) {
int old = setup.definitionVersion();
var migrate = migrations.get(old);
if (migrate == null)
throw new IllegalArgumentException(
"Missing definition migration from version " + old);
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
if (!id.equals(setup.definitionId())
|| setup.definitionVersion() != old + 1
|| setup.formatVersion() != 1)
throw new IllegalArgumentException(
"Migration must preserve identity/format and advance one definition"
+ " version");
}
Map<String, Column> definitions = new LinkedHashMap<>();
columns.forEach(c -> definitions.put(c.id(), c));
List<GridSetup.ColumnState> next = new ArrayList<>();
List<String> adjustments = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (var saved : setup.columns()) {
var c = definitions.get(saved.id());
if (c == null)
throw new IllegalArgumentException(
"Unknown saved column: " + saved.id() + "; provide a migration");
if (!c.type().equals(saved.type()))
throw new IllegalArgumentException(
"Column type changed: " + saved.id() + "; provide a migration");
ColumnWidth width = saved.width();
if (width instanceof ColumnWidth.Explicit explicit) {
double clamped = Math.clamp(explicit.value(), c.minimumWidth(), c.maximumWidth());
if (clamped != explicit.value())
adjustments.add(
"Column "
+ c.id()
+ " width clamped from "
+ explicit.value()
+ " to "
+ clamped);
width = new ColumnWidth.Explicit(clamped);
}
next.add(new GridSetup.ColumnState(c.id(), c.type(), width));
seen.add(c.id());
}
for (var c : columns)
if (!seen.contains(c.id()))
next.add(new GridSetup.ColumnState(c.id(), c.type(), new ColumnWidth.Default()));
for (int i = 0; i < next.size(); i++) {
int fixed = definitions.get(next.get(i).id()).fixedPosition();
if (fixed >= 0 && fixed != i)
throw new IllegalArgumentException(
"Saved order violates fixed position for "
+ next.get(i).id()
+ "; provide a migration");
}
source.validate(setup.page());
setup.filters().forEach(validateFilter);
return new Prepared(
new GridSetup(1, id, version, next, setup.sort(), setup.filters(), setup.page()),
adjustments);
}
}
@@ -0,0 +1,24 @@
package de.neitzel.grid;
import java.util.*;
/**
* Immutable query. Filters combine with AND; sort keys include the source's stable-key tie-breaker.
*/
public record GridQuery(List<FilterCondition> filters, List<SortKey> sort, PageRequest page) {
public GridQuery {
filters = List.copyOf(filters);
sort = List.copyOf(sort);
Objects.requireNonNull(page);
Set<String> ids = new HashSet<>();
for (var f : filters) {
Checks.id(f.columnId());
Checks.id(f.typeId());
if (!ids.add(f.columnId()))
throw new IllegalArgumentException("Multiple filters for " + f.columnId());
}
ids.clear();
for (var key : sort)
if (!ids.add(key.columnId())) throw new IllegalArgumentException("Duplicate sort key");
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
import java.util.Objects;
/**
* Row identity is independent of page position. The model is application-owned, not deep-copied.
*/
public record GridRow<K, T>(K key, T model) {
public GridRow {
Objects.requireNonNull(key);
Objects.requireNonNull(model);
}
}
@@ -0,0 +1,50 @@
package de.neitzel.grid;
import java.util.*;
/** Plain versioned setup. No selection, credentials, page index, drafts, or approval tokens. */
public record GridSetup(
int formatVersion,
String definitionId,
int definitionVersion,
List<ColumnState> columns,
List<SortKey> sort,
List<FilterCondition> filters,
PageRequest page) {
public record ColumnState(String id, String type, ColumnWidth width) {
/** Older callers must supply a definition type before persistence/restoration. */
public ColumnState(String id, ColumnWidth width) {
this(id, "unspecified", width);
}
public ColumnState {
Checks.id(id);
Checks.id(type);
Objects.requireNonNull(width);
}
}
public GridSetup {
if (formatVersion <= 0 || definitionVersion <= 0)
throw new IllegalArgumentException("Invalid version");
Checks.id(definitionId);
columns = List.copyOf(columns);
sort = List.copyOf(sort);
filters = List.copyOf(filters);
Objects.requireNonNull(page);
Set<String> ids = new HashSet<>();
for (var c : columns)
if (!ids.add(c.id())) throw new IllegalArgumentException("Duplicate column ID");
if (sort.size() > 1)
throw new IllegalArgumentException("Only one user-selected sort is supported");
for (var key : sort)
if (!ids.contains(key.columnId()))
throw new IllegalArgumentException("Unknown sort column");
for (var f : filters)
if (!ids.contains(f.columnId()))
throw new IllegalArgumentException("Unknown filter column");
new GridQuery(filters, sort, page);
if (page instanceof PageRequest.Paged p && p.pageIndex() != 0)
throw new IllegalArgumentException("Setups must start on the first page");
}
}
@@ -0,0 +1,56 @@
package de.neitzel.grid;
import java.util.concurrent.CompletionStage;
/**
* Toolkit-independent source. Implementations validate mappings/semantics and own per-request
* resources.
*/
public interface GridSource<K, T> {
SourceCapabilities capabilities();
QueryExecution<K, T> query(GridQuery query);
/** Stable execution capability ID: "local" or an adapter-specific registration ID. */
default String filterExecutionId() {
return "unspecified";
}
/** Validate concrete semantics before accepting an editor/programmatic draft. */
default void validateFilter(FilterCondition condition) {
throw new UnsupportedOperationException(
"Source does not declare filter support: " + condition.typeId());
}
/**
* Guarded execution. Sources supporting All must override and count in their execution snapshot
* before materializing rows, failing with AllRowsConfirmationRequired when consent is needed.
* The default deliberately rejects All rather than performing an unsafe fetch-first check.
*/
default QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
java.util.Objects.requireNonNull(options);
if (query.page() instanceof PageRequest.All) {
var failure =
java.util.concurrent.CompletableFuture.<PageResult<K, T>>failedFuture(
new UnsupportedOperationException(
"Source does not support guarded All execution"));
return new QueryExecution<>() {
public CompletionStage<PageResult<K, T>> result() {
return failure;
}
public void cancel() {}
};
}
return query(query);
}
/**
* Cancellation is best-effort; coordinators must reject superseded completions independently.
*/
interface QueryExecution<K, T> {
CompletionStage<PageResult<K, T>> result();
void cancel();
}
}
@@ -0,0 +1,44 @@
package de.neitzel.grid;
import java.util.*;
import java.util.function.*;
/**
* Explicit scalar mapping; custom compilers validate their condition and produce local evaluators.
*/
public record MemoryColumn<T>(
String id,
Kind kind,
Function<T, FilterValue> read,
Map<String, Function<FilterCondition, Predicate<FilterValue>>> customFilters) {
public enum Kind {
TEXT,
INTEGER,
DECIMAL,
BOOLEAN
}
public MemoryColumn(String id, Kind kind, Function<T, FilterValue> read) {
this(id, kind, read, Map.of());
}
public MemoryColumn {
Checks.id(id);
Objects.requireNonNull(kind);
Objects.requireNonNull(read);
customFilters = Map.copyOf(customFilters);
customFilters.keySet().forEach(Checks::id);
}
void validate(FilterValue value) {
if (value == null) return;
boolean valid =
switch (kind) {
case TEXT -> value instanceof FilterValue.Text;
case INTEGER -> value instanceof FilterValue.IntegerValue;
case DECIMAL -> value instanceof FilterValue.Decimal;
case BOOLEAN -> value instanceof FilterValue.BooleanValue;
};
if (!valid) throw new IllegalArgumentException("Value type does not match column " + id);
}
}
@@ -0,0 +1,268 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.*;
/**
* Local source with caller-thread scalar snapshot capture and executor-based query processing. The
* supplier must return a consistent view; FX-owned lists may be captured on the FX caller thread.
* Captured scalar values are immutable; row models remain application-owned. No executor is closed.
*/
public final class MemoryGridSource<K, T> implements GridSource<K, T> {
private final Supplier<? extends Collection<T>> data;
private final Function<T, K> key;
private final Comparator<K> keyOrder;
private final Map<String, MemoryColumn<T>> columns;
private final Executor executor;
private final SourceCapabilities capabilities;
private record Snapshot<K, T>(K key, T model, Map<String, FilterValue> values) {}
public MemoryGridSource(
Supplier<? extends Collection<T>> data,
Function<T, K> key,
Comparator<K> keyOrder,
List<MemoryColumn<T>> columns,
Executor executor,
int maximumPageSize) {
this.data = Objects.requireNonNull(data);
this.key = Objects.requireNonNull(key);
this.keyOrder = Objects.requireNonNull(keyOrder);
this.executor = Objects.requireNonNull(executor);
Map<String, MemoryColumn<T>> mapped = new LinkedHashMap<>();
for (var column : columns)
if (mapped.putIfAbsent(column.id(), column) != null)
throw new IllegalArgumentException("Duplicate column mapping");
this.columns = Map.copyOf(mapped);
capabilities = new SourceCapabilities(true, true, maximumPageSize);
}
public SourceCapabilities capabilities() {
return capabilities;
}
public QueryExecution<K, T> query(GridQuery query) {
return query(query, QueryOptions.defaults());
}
public QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
CompletableFuture<PageResult<K, T>> result = new CompletableFuture<>();
AtomicBoolean cancelled = new AtomicBoolean();
try {
Objects.requireNonNull(query);
Objects.requireNonNull(options);
capabilities.validate(query.page());
List<Predicate<Snapshot<K, T>>> predicates = new ArrayList<>();
for (var condition : query.filters()) {
var column = column(condition.columnId());
var test = compile(column, condition);
predicates.add(row -> test.test(row.values().get(column.id())));
}
for (var sort : query.sort()) column(sort.columnId());
List<Snapshot<K, T>> snapshot = new ArrayList<>();
Set<K> keys = new HashSet<>();
for (T model : List.copyOf(data.get())) {
K id = Objects.requireNonNull(key.apply(model), "Missing row key");
if (!keys.add(id)) throw new IllegalArgumentException("Duplicate row key");
Map<String, FilterValue> values = new HashMap<>();
for (var column : columns.values()) {
FilterValue value = column.read().apply(model);
column.validate(value);
values.put(column.id(), value);
}
snapshot.add(new Snapshot<>(id, model, Collections.unmodifiableMap(values)));
}
executor.execute(
() -> {
try {
checkCancelled(cancelled);
List<Snapshot<K, T>> matching = new ArrayList<>();
for (var row : snapshot) {
checkCancelled(cancelled);
if (predicates.stream().allMatch(p -> p.test(row)))
matching.add(row);
}
long count = matching.size();
if (query.page() instanceof PageRequest.All
&& !options.allApproved()
&& count > options.allWarningThreshold())
throw new AllRowsConfirmationRequired(count);
matching.sort(
(left, right) -> {
checkCancelled(cancelled);
for (var sort : query.sort()) {
FilterValue a = left.values().get(sort.columnId()),
b = right.values().get(sort.columnId());
if (a == null || b == null) {
if (a != b) return a == null ? 1 : -1;
continue;
}
int c = compare(a, b);
if (c != 0)
return sort.direction()
== SortKey.Direction.ASCENDING
? c
: -c;
}
int byKey = keyOrder.compare(left.key(), right.key());
if (byKey == 0
&& !Objects.equals(left.key(), right.key())) {
throw new IllegalArgumentException(
"Row key comparator must distinguish keys");
}
return byKey;
});
int from = 0, to = matching.size();
boolean hasNext = false;
if (query.page() instanceof PageRequest.Paged page) {
from = (int) Math.min(count, page.offset());
to = (int) Math.min(count, (long) from + page.pageSize());
hasNext = to < count;
}
List<GridRow<K, T>> rows = new ArrayList<>();
for (int i = from; i < to; i++) {
checkCancelled(cancelled);
var row = matching.get(i);
rows.add(new GridRow<>(row.key(), row.model()));
}
checkCancelled(cancelled);
result.complete(
new PageResult<>(
query.page(), rows, OptionalLong.of(count), hasNext));
} catch (RuntimeException failure) {
result.completeExceptionally(failure);
}
});
} catch (RuntimeException failure) {
result.completeExceptionally(failure);
}
return new QueryExecution<>() {
public CompletionStage<PageResult<K, T>> result() {
return result;
}
public void cancel() {
cancelled.set(true);
result.completeExceptionally(new CancellationException("Superseded query"));
}
};
}
@Override
public String filterExecutionId() {
return "local";
}
@Override
public void validateFilter(FilterCondition condition) {
compile(column(condition.columnId()), condition);
}
/** Explicitly attached source-wide candidates; all other column conditions are respected. */
public FilterCandidates.Provider candidateProvider(Function<FilterValue, String> label) {
Objects.requireNonNull(label);
return FilterCandidates.snapshot(
Set.of(FilterCandidates.Scope.SOURCE_WIDE),
context -> {
var selected = column(context.columnId());
var tests =
context.otherFilters().stream()
.map(
condition ->
Map.entry(
condition.columnId(),
compile(
column(condition.columnId()),
condition)))
.toList();
List<Map<String, FilterValue>> snapshot = new ArrayList<>();
for (T model : List.copyOf(data.get())) {
Map<String, FilterValue> values = new HashMap<>();
for (var column : columns.values()) {
var value = column.read().apply(model);
column.validate(value);
values.put(column.id(), value);
}
snapshot.add(Collections.unmodifiableMap(values));
}
return () ->
snapshot.stream()
.filter(
values ->
tests.stream()
.allMatch(
test ->
test.getValue()
.test(
values
.get(
test
.getKey()))))
.map(values -> values.get(selected.id()))
.distinct()
.map(
value ->
new FilterCandidates.Candidate(
value, label.apply(value)))
.toList();
},
executor);
}
private MemoryColumn<T> column(String id) {
var column = columns.get(id);
if (column == null) throw new IllegalArgumentException("Unknown column: " + id);
return column;
}
private Predicate<FilterValue> compile(MemoryColumn<T> column, FilterCondition condition) {
if (condition instanceof MissingFilter filter) return value -> filter.matches(value);
if (condition instanceof ValueFilter filter) {
filter.values().forEach(column::validate);
return filter::matches;
}
if (condition instanceof TextFilter filter) {
if (column.kind() != MemoryColumn.Kind.TEXT)
throw new IllegalArgumentException("Text filter requires a text column");
return value ->
filter.matches(value == null ? null : ((FilterValue.Text) value).value());
}
if (condition instanceof NumericFilter filter) {
if (column.kind() != MemoryColumn.Kind.INTEGER
&& column.kind() != MemoryColumn.Kind.DECIMAL)
throw new IllegalArgumentException("Numeric filter requires a numeric column");
if (column.kind() == MemoryColumn.Kind.INTEGER) {
filter.operand().longValueExact();
if (filter.upper() != null) filter.upper().longValueExact();
}
return value -> filter.matches(value == null ? null : number(value));
}
var compiler = column.customFilters().get(condition.typeId());
if (compiler == null)
throw new UnsupportedOperationException("Unsupported filter: " + condition.typeId());
return Objects.requireNonNull(compiler.apply(condition));
}
private static BigDecimal number(FilterValue value) {
return value instanceof FilterValue.IntegerValue i
? BigDecimal.valueOf(i.value())
: ((FilterValue.Decimal) value).value();
}
private static int compare(FilterValue a, FilterValue b) {
if (a instanceof FilterValue.Text text)
return text.value()
.toLowerCase(Locale.ROOT)
.compareTo(((FilterValue.Text) b).value().toLowerCase(Locale.ROOT));
if (a instanceof FilterValue.BooleanValue bool)
return Boolean.compare(bool.value(), ((FilterValue.BooleanValue) b).value());
return number(a).compareTo(number(b));
}
private static void checkCancelled(AtomicBoolean cancelled) {
if (cancelled.get()) throw new CancellationException("Superseded query");
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
/** Explicit missing/present test; empty strings are present. */
public record MissingFilter(String columnId, boolean missing) implements FilterCondition {
public MissingFilter {
Checks.id(columnId);
}
public String typeId() {
return "neitzel.missing";
}
public boolean matches(Object value) {
return (value == null) == missing;
}
}
@@ -0,0 +1,46 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.Objects;
/** Exact numeric comparison. Column/domain precision validation belongs to the source mapping. */
public record NumericFilter(
String columnId, Operator operator, BigDecimal operand, BigDecimal upper)
implements FilterCondition {
public enum Operator {
EQUALS,
LESS,
LESS_OR_EQUAL,
GREATER,
GREATER_OR_EQUAL,
RANGE
}
public NumericFilter {
Checks.id(columnId);
Objects.requireNonNull(operator);
Objects.requireNonNull(operand);
if (operator == Operator.RANGE) {
Objects.requireNonNull(upper);
if (operand.compareTo(upper) > 0) throw new IllegalArgumentException("Reversed range");
} else if (upper != null)
throw new IllegalArgumentException("Upper bound is only valid for a range");
}
public String typeId() {
return "neitzel.number";
}
public boolean matches(BigDecimal value) {
if (value == null) return false;
int c = value.compareTo(operand);
return switch (operator) {
case EQUALS -> c == 0;
case LESS -> c < 0;
case LESS_OR_EQUAL -> c <= 0;
case GREATER -> c > 0;
case GREATER_OR_EQUAL -> c >= 0;
case RANGE -> c >= 0 && value.compareTo(upper) <= 0;
};
}
}
@@ -0,0 +1,18 @@
package de.neitzel.grid;
/** Explicit offset paging or unpaged execution. All is never encoded as a magic page size. */
public sealed interface PageRequest {
/** Zero-based page index. UI page labels may be one-based. */
record Paged(long pageIndex, int pageSize) implements PageRequest {
public Paged {
if (pageIndex < 0 || pageSize <= 0) throw new IllegalArgumentException("Invalid page");
Math.multiplyExact(pageIndex, (long) pageSize);
}
public long offset() {
return Math.multiplyExact(pageIndex, (long) pageSize);
}
}
record All() implements PageRequest {}
}
@@ -0,0 +1,29 @@
package de.neitzel.grid;
import java.util.*;
/** A materialized result with exact filtered total or an explicit next-page indication. */
public record PageResult<K, T>(
PageRequest request, List<GridRow<K, T>> rows, OptionalLong total, boolean hasNext) {
public PageResult {
Objects.requireNonNull(request);
rows = List.copyOf(rows);
Objects.requireNonNull(total);
Set<K> keys = new HashSet<>();
for (var row : rows)
if (!keys.add(row.key())) throw new IllegalArgumentException("Duplicate row key");
if (total.isPresent() && total.getAsLong() < 0)
throw new IllegalArgumentException("Negative total");
if (request instanceof PageRequest.Paged p) {
if (rows.size() > p.pageSize()) throw new IllegalArgumentException("Too many rows");
if (total.isPresent()) {
long remaining = Math.max(0, total.getAsLong() - p.offset());
if (rows.size() != Math.min(remaining, p.pageSize())
|| hasNext != (remaining > p.pageSize()))
throw new IllegalArgumentException("Rows/count/navigation disagree");
} else if (hasNext && rows.size() != p.pageSize())
throw new IllegalArgumentException("Next page requires a full page");
} else if (hasNext || (total.isPresent() && total.getAsLong() != rows.size()))
throw new IllegalArgumentException("Invalid unpaged result");
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
/** Per-attempt execution consent. Never persist this with a setup or reuse across user requests. */
public record QueryOptions(long allWarningThreshold, boolean allApproved) {
public QueryOptions {
if (allWarningThreshold < 0)
throw new IllegalArgumentException("Negative All warning threshold");
}
public static QueryOptions defaults() {
return new QueryOptions(1000, false);
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
import java.util.Objects;
/** Sort by mapped column, with missing values last in either direction. */
public record SortKey(String columnId, Direction direction) {
public enum Direction {
ASCENDING,
DESCENDING
}
public SortKey {
Checks.id(columnId);
Objects.requireNonNull(direction);
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
/** Source-level page support; filter semantics are validated separately. */
public record SourceCapabilities(boolean exactTotal, boolean all, int maximumPageSize) {
public SourceCapabilities {
if (maximumPageSize <= 0) throw new IllegalArgumentException("Invalid maximum page size");
}
public void validate(PageRequest request) {
java.util.Objects.requireNonNull(request);
if (request instanceof PageRequest.All && !all)
throw new IllegalArgumentException("Source does not support All");
if (request instanceof PageRequest.Paged p && p.pageSize() > maximumPageSize)
throw new IllegalArgumentException("Unsupported page size");
}
}
@@ -0,0 +1,41 @@
package de.neitzel.grid;
import java.util.Locale;
import java.util.Objects;
/**
* Literal text comparison; missing values never match. No accent removal or Unicode normalization.
*/
public record TextFilter(String columnId, Operator operator, String operand, boolean caseSensitive)
implements FilterCondition {
public enum Operator {
EQUALS,
CONTAINS,
STARTS_WITH,
ENDS_WITH
}
public TextFilter {
Checks.id(columnId);
Objects.requireNonNull(operator);
Objects.requireNonNull(operand);
if (operand.isEmpty() && operator != Operator.EQUALS)
throw new IllegalArgumentException("Empty search operand");
}
public String typeId() {
return "neitzel.text";
}
public boolean matches(String value) {
if (value == null) return false;
String left = caseSensitive ? value : value.toLowerCase(Locale.ROOT),
right = caseSensitive ? operand : operand.toLowerCase(Locale.ROOT);
return switch (operator) {
case EQUALS -> left.equals(right);
case CONTAINS -> left.contains(right);
case STARTS_WITH -> left.startsWith(right);
case ENDS_WITH -> left.endsWith(right);
};
}
}
@@ -0,0 +1,22 @@
package de.neitzel.grid;
import java.util.Set;
/**
* Explicit allowed values. An empty set with includeMissing=false matches nothing, not everything.
*/
public record ValueFilter(String columnId, Set<FilterValue> values, boolean includeMissing)
implements FilterCondition {
public ValueFilter {
Checks.id(columnId);
values = Set.copyOf(values);
}
public String typeId() {
return "neitzel.values";
}
public boolean matches(FilterValue value) {
return value == null ? includeMissing : values.contains(value);
}
}
@@ -0,0 +1,101 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.*;
class FilterCandidatesTest {
@Test
void currentPageCapturesAtOpenAndSeparatesLabelsFromValues() throws Exception {
var values =
new ArrayList<>(
List.of(
new FilterCandidates.Candidate(new FilterValue.Text("a"), "Same"),
new FilterCandidates.Candidate(new FilterValue.Text("b"), "Same"),
new FilterCandidates.Candidate(null, "Missing")));
var provider = FilterCandidates.currentPage(() -> values);
var context =
new FilterCandidates.Context("x", FilterCandidates.Scope.CURRENT_PAGE, List.of());
try (var session = provider.open(context)) {
values.clear();
var first =
session.load(new FilterCandidates.Request(context, "same", 0, 1))
.toCompletableFuture()
.get();
assertTrue(first.hasMore());
assertEquals(new FilterValue.Text("a"), first.candidates().getFirst().value());
var next =
session.load(new FilterCandidates.Request(context, "same", 1, 1))
.toCompletableFuture()
.get();
assertFalse(next.hasMore());
assertEquals(new FilterValue.Text("b"), next.candidates().getFirst().value());
}
assertThrows(
UnsupportedOperationException.class,
() ->
provider.open(
new FilterCandidates.Context(
"x", FilterCandidates.Scope.SOURCE_WIDE, List.of())));
assertThrows(
IllegalArgumentException.class,
() ->
new FilterCandidates.Context(
"x",
FilterCandidates.Scope.SOURCE_WIDE,
List.of(new MissingFilter("x", true))));
}
@Test
void sourceWideRespectsOtherFiltersAndClosingCancelsPendingWork() throws Exception {
record Item(long id, String value, long group) {}
var jobs = new ArrayDeque<Runnable>();
var data =
new ArrayList<>(
List.of(new Item(1, "a", 1), new Item(2, "b", 2), new Item(3, "a", 1)));
var source =
new MemoryGridSource<Long, Item>(
() -> data,
Item::id,
Long::compare,
List.of(
new MemoryColumn<>(
"x",
MemoryColumn.Kind.TEXT,
i -> new FilterValue.Text(i.value())),
new MemoryColumn<>(
"group",
MemoryColumn.Kind.INTEGER,
i -> new FilterValue.IntegerValue(i.group()))),
jobs::add,
50);
var context =
new FilterCandidates.Context(
"x",
FilterCandidates.Scope.SOURCE_WIDE,
List.of(
new ValueFilter(
"group", Set.of(new FilterValue.IntegerValue(1)), false)));
var session = source.candidateProvider(v -> ((FilterValue.Text) v).value()).open(context);
data.clear();
var first =
session.load(new FilterCandidates.Request(context, "", 0, 10))
.toCompletableFuture();
jobs.remove().run();
assertEquals(
List.of(new FilterCandidates.Candidate(new FilterValue.Text("a"), "a")),
first.get().candidates());
var pending =
session.load(new FilterCandidates.Request(context, "", 0, 10))
.toCompletableFuture();
session.close();
jobs.remove().run();
assertTrue(pending.isCancelled());
assertThrows(
IllegalStateException.class,
() -> session.load(new FilterCandidates.Request(context, "", 0, 10)));
}
}
@@ -0,0 +1,114 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.*;
class GridContractsTest {
@Test
void textIsLiteralAndMissingIsNotEmpty() {
assertTrue(
new TextFilter("name", TextFilter.Operator.CONTAINS, "%_", false).matches("a%_B"));
assertFalse(new TextFilter("name", TextFilter.Operator.EQUALS, "", false).matches(null));
assertTrue(new TextFilter("name", TextFilter.Operator.EQUALS, "", false).matches(""));
assertThrows(
IllegalArgumentException.class,
() -> new TextFilter("name", TextFilter.Operator.CONTAINS, "", false));
assertFalse(new TextFilter("name", TextFilter.Operator.EQUALS, "ss", false).matches("ß"));
}
@Test
void decimalsAreExactAndChecklistsKeepExactText() {
assertTrue(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("9007199254740993.00"),
null)
.matches(new BigDecimal("9007199254740993")));
assertFalse(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("9007199254740993"),
null)
.matches(new BigDecimal("9007199254740992")));
var values =
new ValueFilter(
"price", Set.of(new FilterValue.Decimal(new BigDecimal("1.0"))), false);
assertTrue(values.matches(new FilterValue.Decimal(new BigDecimal("1.00"))));
assertFalse(
new ValueFilter("name", Set.of(new FilterValue.Text("Alpha")), false)
.matches(new FilterValue.Text("alpha")));
assertFalse(new ValueFilter("name", Set.of(), false).matches(null));
assertTrue(new MissingFilter("name", false).matches(""));
}
@Test
void queryAndSetupAreDefensivelyCopiedAndRejectAmbiguity() {
var filters = new ArrayList<FilterCondition>();
filters.add(new MissingFilter("name", true));
var q = new GridQuery(filters, List.of(), new PageRequest.All());
filters.clear();
assertEquals(1, q.filters().size());
assertThrows(UnsupportedOperationException.class, () -> q.filters().clear());
assertThrows(
IllegalArgumentException.class,
() ->
new GridQuery(
List.of(
new MissingFilter("a", true),
new MissingFilter("a", false)),
List.of(),
new PageRequest.All()));
assertThrows(
IllegalArgumentException.class,
() ->
new GridSetup(
1,
"products",
1,
List.of(new GridSetup.ColumnState("a", new ColumnWidth.Default())),
List.of(),
List.of(),
new PageRequest.Paged(1, 50)));
assertThrows(IllegalArgumentException.class, () -> new ColumnWidth.Explicit(Double.NaN));
}
@Test
void resultsValidateCountsButAllowDisappearedPages() {
var row = new GridRow<>(1, "one");
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.Paged(0, 2),
List.of(row, row),
OptionalLong.of(2),
false));
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.Paged(0, 2),
List.of(row),
OptionalLong.of(3),
true));
assertDoesNotThrow(
() ->
new PageResult<>(
new PageRequest.Paged(4, 2), List.of(), OptionalLong.of(2), false));
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.All(), List.of(row), OptionalLong.of(2), false));
assertThrows(ArithmeticException.class, () -> new PageRequest.Paged(Long.MAX_VALUE, 250));
assertThrows(
IllegalArgumentException.class,
() -> new SourceCapabilities(true, false, 100).validate(new PageRequest.All()));
}
}
@@ -0,0 +1,301 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class GridCoordinatorTest {
static class Source implements GridSource<Integer, String> {
List<CompletableFuture<PageResult<Integer, String>>> futures = new ArrayList<>();
List<GridQuery> queries = new ArrayList<>();
List<QueryOptions> options = new ArrayList<>();
int cancellations;
public SourceCapabilities capabilities() {
return new SourceCapabilities(true, true, 250);
}
public QueryExecution<Integer, String> query(GridQuery q) {
return query(q, QueryOptions.defaults());
}
public QueryExecution<Integer, String> query(GridQuery q, QueryOptions o) {
queries.add(q);
options.add(o);
var f = new CompletableFuture<PageResult<Integer, String>>();
futures.add(f);
return new QueryExecution<>() {
public CompletionStage<PageResult<Integer, String>> result() {
return f;
}
public void cancel() {
cancellations++;
}
};
}
}
static GridQuery q(long page) {
return new GridQuery(List.of(), List.of(), new PageRequest.Paged(page, 1));
}
static PageResult<Integer, String> page(long index, int key) {
return new PageResult<>(
new PageRequest.Paged(index, 1),
List.of(new GridRow<>(key, "row" + key)),
OptionalLong.of(10),
index < 9);
}
static class Harness {
Source source = new Source();
ArrayDeque<Runnable> callbacks = new ArrayDeque<>();
List<PageResult<Integer, String>> published = new ArrayList<>();
GridCoordinator<Integer, String> c =
new GridCoordinator<>(source, callbacks::add, s -> {}, published::add);
void drain() {
while (!callbacks.isEmpty()) callbacks.remove().run();
}
void request(GridQuery q) {
c.request(q);
drain();
}
}
@Test
void staleSuccessFailureAndGuardApprovalCannotPublish() {
var h = new Harness();
h.request(q(0));
h.request(q(1));
assertEquals(1, h.source.cancellations);
h.source.futures.get(1).complete(page(1, 2));
h.drain();
h.source.futures.get(0).completeExceptionally(new IllegalStateException("old"));
h.drain();
assertEquals(1, h.published.size());
assertEquals(GridCoordinator.Phase.READY, h.c.state().phase());
CompletableFuture<Boolean> guard = new CompletableFuture<>();
h.c.setGuard(q -> guard);
h.c.request(q(2));
h.c.setGuard(q -> CompletableFuture.completedFuture(true));
h.request(q(3));
guard.complete(true);
h.drain();
assertEquals(3, h.source.queries.size());
assertEquals(q(3), h.source.queries.getLast());
h.c.close();
h.source.futures.getLast().complete(page(3, 4));
h.drain();
assertEquals(1, h.published.size());
}
@Test
void errorsRetainPageAndRetryLatestQuery() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
h.request(q(1));
h.source.futures.getLast().completeExceptionally(new IllegalStateException("unavailable"));
h.drain();
assertEquals(GridCoordinator.Phase.ERROR, h.c.state().phase());
assertEquals(q(0), h.c.state().displayed());
h.c.retry();
h.drain();
assertEquals(q(1), h.source.queries.getLast());
h.source.futures.getLast().complete(page(1, 2));
h.drain();
assertEquals(q(1), h.c.state().displayed());
}
@Test
void disappearingPagesHaveOnlyOneCorrection() {
var h = new Harness();
h.request(q(9));
h.source
.futures
.getFirst()
.complete(new PageResult<>(q(9).page(), List.of(), OptionalLong.of(2), false));
h.drain();
assertEquals(q(1), h.source.queries.getLast());
h.source
.futures
.getLast()
.complete(new PageResult<>(q(1).page(), List.of(), OptionalLong.of(1), false));
h.drain();
assertEquals(2, h.source.queries.size());
assertEquals(GridCoordinator.Phase.ERROR, h.c.state().phase());
}
@Test
void allApprovalIsAttemptScopedAndCancellationRestoresPage() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
var all = new GridQuery(List.of(), List.of(), new PageRequest.All());
CompletableFuture<Boolean> consent = new CompletableFuture<>();
h.c.setConfirmation((q, count) -> consent);
h.request(all);
h.source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertEquals(GridCoordinator.Phase.CONFIRMATION, h.c.state().phase());
consent.complete(false);
h.drain();
assertEquals(q(0), h.c.state().requested());
assertEquals(1, h.published.size());
h.c.setConfirmation((q, count) -> CompletableFuture.completedFuture(true));
h.request(all);
h.source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertTrue(h.source.options.getLast().allApproved());
h.request(q(2));
h.source
.futures
.get(h.source.futures.size() - 2)
.complete(
new PageResult<>(
new PageRequest.All(), List.of(), OptionalLong.of(0), false));
h.drain();
assertEquals(1, h.published.size());
}
@Test
void sourceReplacementIsNotCommittedWhenAllWarningIsCancelled() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
var replacement = new Source();
h.c.setConfirmation((q, n) -> CompletableFuture.completedFuture(false));
h.c.request(replacement, new GridQuery(List.of(), List.of(), new PageRequest.All()));
h.drain();
replacement.futures.getFirst().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertEquals(0, h.c.state().sourceVersion());
h.c.refresh();
h.drain();
assertEquals(2, h.source.queries.size());
}
@Test
void unknownTotalsRecoverToFirstPageAndInvalidResponsesAreErrors() {
var source =
new Source() {
public SourceCapabilities capabilities() {
return new SourceCapabilities(false, false, 250);
}
};
var jobs = new ArrayDeque<Runnable>();
var coordinator =
new GridCoordinator<Integer, String>(source, jobs::add, state -> {}, result -> {});
coordinator.request(q(4));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures
.getFirst()
.complete(new PageResult<>(q(4).page(), List.of(), OptionalLong.empty(), false));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(q(0), source.queries.getLast());
source.futures
.getLast()
.complete(
new PageResult<>(
q(0).page(),
List.of(new GridRow<>(1, "a")),
OptionalLong.empty(),
true));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.READY, coordinator.state().phase());
coordinator.request(q(1));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getLast().complete(page(0, 2));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.ERROR, coordinator.state().phase());
assertEquals(q(0), coordinator.state().displayed());
coordinator.close();
assertNull(coordinator.state().result());
}
@Test
void lateConfirmationAndObserverTriggeredRequestsAreSerialized() {
var source = new Source();
var jobs = new ArrayDeque<Runnable>();
var holder = new AtomicReference<GridCoordinator<Integer, String>>();
var jumped = new AtomicBoolean();
var coordinator =
new GridCoordinator<Integer, String>(
source,
jobs::add,
state -> {
if (state.phase() == GridCoordinator.Phase.READY
&& jumped.compareAndSet(false, true))
holder.get().request(q(1));
},
result -> {});
holder.set(coordinator);
coordinator.request(q(0));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getFirst().complete(page(0, 1));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(q(1), coordinator.state().requested());
assertEquals(GridCoordinator.Phase.LOADING, coordinator.state().phase());
var consent = new CompletableFuture<Boolean>();
coordinator.setConfirmation((q, n) -> consent);
coordinator.request(new GridQuery(List.of(), List.of(), new PageRequest.All()));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
while (!jobs.isEmpty()) jobs.remove().run();
coordinator.request(q(2));
while (!jobs.isEmpty()) jobs.remove().run();
int count = source.queries.size();
consent.complete(true);
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(count, source.queries.size());
assertEquals(q(2), coordinator.state().requested());
}
@Test
void closeDuringPublicationOrConfirmationDoesNotResurrectCoordinator() {
for (boolean closeInPublisher : List.of(true, false)) {
var source = new Source();
var jobs = new ArrayDeque<Runnable>();
var holder = new AtomicReference<GridCoordinator<Integer, String>>();
var coordinator =
new GridCoordinator<Integer, String>(
source,
jobs::add,
state -> {
if (!closeInPublisher
&& state.phase() == GridCoordinator.Phase.CONFIRMATION)
holder.get().close();
},
result -> holder.get().close());
holder.set(coordinator);
coordinator.setConfirmation(
(q, n) -> {
fail("Closed coordinator must not open confirmation");
return CompletableFuture.completedFuture(true);
});
coordinator.request(
closeInPublisher
? q(0)
: new GridQuery(List.of(), List.of(), new PageRequest.All()));
while (!jobs.isEmpty()) jobs.remove().run();
if (closeInPublisher) source.futures.getFirst().complete(page(0, 1));
else
source.futures
.getFirst()
.completeExceptionally(new AllRowsConfirmationRequired(1001));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.CLOSED, coordinator.state().phase());
assertNull(coordinator.state().result());
}
}
}
@@ -0,0 +1,176 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
class GridDefinitionTest {
static GridDefinition.Column column(String id, String type, int fixed) {
return new GridDefinition.Column(id, type, 100, 50, 200, fixed);
}
static GridSetup saved(String type) {
return new GridSetup(
1,
"products",
1,
List.of(new GridSetup.ColumnState("a", type, new ColumnWidth.Explicit(300))),
List.of(),
List.of(),
new PageRequest.Paged(0, 25));
}
@Test
void addsNewColumnsClampsWidthsAndPreservesDefaultIntent() {
var d =
new GridDefinition(
"products",
1,
List.of(column("a", "text", -1), column("b", "integer", -1)));
var prepared =
d.prepare(saved("text"), Map.of(), new SourceCapabilities(true, true, 50), f -> {});
assertEquals(
List.of(
new GridSetup.ColumnState("a", "text", new ColumnWidth.Explicit(200)),
new GridSetup.ColumnState("b", "integer", new ColumnWidth.Default())),
prepared.setup().columns());
assertEquals(1, prepared.adjustments().size());
}
@Test
void identityTypesUnknownColumnsAndFixedPositionsRequireExplicitMigration() {
var d =
new GridDefinition(
"products", 1, List.of(column("b", "text", 0), column("a", "text", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var changed = new GridDefinition("products", 1, List.of(column("a", "integer", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
changed.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var removed = new GridDefinition("products", 1, List.of(column("b", "text", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
removed.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
assertThrows(
IllegalArgumentException.class,
() ->
new GridDefinition("other", 1, List.of(column("a", "text", -1)))
.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
}
@Test
void migrationsMustAdvanceAndRemainSubjectToFullValidation() {
var d = new GridDefinition("products", 2, List.of(column("a", "integer", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var result =
d.prepare(
saved("text"),
Map.of(
1,
s ->
new GridSetup(
1,
s.definitionId(),
2,
List.of(
new GridSetup.ColumnState(
"a",
"integer",
new ColumnWidth.Default())),
s.sort(),
s.filters(),
s.page())),
new SourceCapabilities(true, true, 50),
f -> {});
assertEquals(2, result.setup().definitionVersion());
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(1, s -> s),
new SourceCapabilities(true, true, 50),
f -> {}));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(
1,
s ->
new GridSetup(
1,
s.definitionId(),
2,
s.columns(),
s.sort(),
s.filters(),
s.page())),
new SourceCapabilities(true, true, 50),
f -> {}));
}
@Test
void actualFilterAndPageCapabilitiesAreCheckedBeforeExecution() {
var d = new GridDefinition("products", 1, List.of(column("a", "text", -1)));
var s = saved("text");
var filtered =
new GridSetup(
1,
"products",
1,
s.columns(),
List.of(),
List.of(new MissingFilter("a", true)),
new PageRequest.All());
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
filtered,
Map.of(),
new SourceCapabilities(true, false, 50),
f -> {}));
assertThrows(
UnsupportedOperationException.class,
() ->
d.prepare(
filtered,
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {
throw new UnsupportedOperationException("Missing unsupported");
}));
}
}
@@ -0,0 +1,247 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
class MemoryGridSourceTest {
record Product(long id, String name, Long quantity, BigDecimal price) {}
static MemoryGridSource<Long, Product> source(List<Product> rows, Executor executor) {
return new MemoryGridSource<>(
() -> rows,
Product::id,
Long::compare,
List.of(
new MemoryColumn<>(
"name",
MemoryColumn.Kind.TEXT,
p -> p.name() == null ? null : new FilterValue.Text(p.name())),
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()))),
executor,
250);
}
static GridQuery query(List<FilterCondition> f, PageRequest p) {
return new GridQuery(f, List.of(new SortKey("name", SortKey.Direction.DESCENDING)), p);
}
@Test
void filteringSortingAndPagingUseWholeSnapshotAndStableKeys() {
var rows =
new ArrayList<>(
List.of(
new Product(3, "alpha", 3L, new BigDecimal("1.00")),
new Product(1, "Alpha", 1L, new BigDecimal("1.0")),
new Product(2, null, 2L, null),
new Product(4, "Zulu", 4L, new BigDecimal("2"))));
var source = source(rows, Runnable::run);
var page =
source.query(query(List.of(), new PageRequest.Paged(1, 2)))
.result()
.toCompletableFuture()
.join();
assertEquals(List.of(3L, 2L), page.rows().stream().map(GridRow::key).toList());
assertEquals(4, page.total().orElseThrow());
assertFalse(page.hasNext());
var filtered =
source.query(
query(
List.of(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("1"),
null)),
new PageRequest.Paged(0, 1)))
.result()
.toCompletableFuture()
.join();
assertEquals(1L, filtered.rows().getFirst().key());
assertEquals(2, filtered.total().orElseThrow());
assertTrue(filtered.hasNext());
assertEquals(List.of(3L, 1L, 2L, 4L), rows.stream().map(Product::id).toList());
}
@Test
void snapshotIsCapturedBeforeExecutorAndCancellationDoesNotInterrupt() {
var jobs = new ArrayDeque<Runnable>();
var rows = new ArrayList<>(List.of(new Product(1, "original", 1L, null)));
var source = source(rows, jobs::add);
var request = source.query(query(List.of(), new PageRequest.Paged(0, 25)));
rows.clear();
jobs.remove().run();
assertEquals(1, request.result().toCompletableFuture().join().rows().size());
var cancelled = source.query(query(List.of(), new PageRequest.Paged(0, 25)));
cancelled.cancel();
jobs.remove().run();
assertThrows(
CancellationException.class, () -> cancelled.result().toCompletableFuture().join());
}
@Test
void allChecksFilteredCountBeforeReturningRowsAndRechecksOnApproval() {
var rows =
new ArrayList<>(
List.of(new Product(1, "a", 1L, null), new Product(2, "b", 2L, null)));
var source = source(rows, Runnable::run);
var q = query(List.of(), new PageRequest.All());
var error =
assertThrows(
CompletionException.class,
() ->
source.query(q, new QueryOptions(1, false))
.result()
.toCompletableFuture()
.join());
assertInstanceOf(AllRowsConfirmationRequired.class, error.getCause());
rows.add(new Product(3, "c", 3L, null));
assertEquals(
3,
source.query(q, new QueryOptions(1, true))
.result()
.toCompletableFuture()
.join()
.rows()
.size());
assertEquals(
3,
source.query(q, new QueryOptions(3, false))
.result()
.toCompletableFuture()
.join()
.rows()
.size());
}
@Test
void typesUnsupportedConditionsAndDuplicateKeysFailVisibly() {
var source = source(List.of(new Product(1, "a", 1L, null)), Runnable::run);
assertThrows(
CompletionException.class,
() ->
source.query(
query(
List.of(
new NumericFilter(
"quantity",
NumericFilter.Operator.EQUALS,
new BigDecimal("1.5"),
null)),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join());
FilterCondition custom =
new FilterCondition() {
public String columnId() {
return "name";
}
public String typeId() {
return "unsupported";
}
};
assertInstanceOf(
UnsupportedOperationException.class,
assertThrows(
CompletionException.class,
() ->
source.query(
query(
List.of(custom),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join())
.getCause());
var dup =
source(
List.of(new Product(1, "a", 1L, null), new Product(1, "b", 2L, null)),
Runnable::run);
assertThrows(
CompletionException.class,
() ->
dup.query(query(List.of(), new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join());
}
private record LongName(String columnId) implements FilterCondition {
public String typeId() {
return "demo.long-name";
}
}
@Test
void registeredCustomEvaluationRunsOnApplicationExecutor() throws Exception {
Thread caller = Thread.currentThread();
var evaluatedOn = new java.util.concurrent.atomic.AtomicReference<Thread>();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
MemoryColumn<Product> name =
new MemoryColumn<>(
"name",
MemoryColumn.Kind.TEXT,
p -> {
assertSame(caller, Thread.currentThread());
return new FilterValue.Text(p.name());
},
Map.of(
"demo.long-name",
condition -> {
if (!(condition instanceof LongName))
throw new IllegalArgumentException(
"Unsupported custom condition");
return value -> {
evaluatedOn.set(Thread.currentThread());
return value instanceof FilterValue.Text text
&& text.value().length() > 3;
};
}));
var source =
new MemoryGridSource<Long, Product>(
() ->
List.of(
new Product(1, "Alpha", 1L, null),
new Product(2, "Bee", 2L, null)),
Product::id,
Long::compare,
List.of(name),
executor,
100);
var result =
source.query(
new GridQuery(
List.of(new LongName("name")),
List.of(),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.get(5, TimeUnit.SECONDS);
assertEquals(List.of(1L), result.rows().stream().map(GridRow::key).toList());
assertNotSame(caller, evaluatedOn.get());
assertFalse(executor.isShutdown());
} finally {
executor.shutdownNow();
}
}
}
+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);
}
}
}
+7 -1
View File
@@ -20,6 +20,12 @@
- [Keyboard access, translations and themes](docs/docking-accessibility.md).
- [Dependency injection](../injection/README.md).
- [Local DataGrid and asynchronous coordination](docs/data-grid.md).
- [Transactional FXML filters and popup lifecycle](docs/filter-editors.md).
- [Versioned saved setups and atomic restoration](docs/saved-setups.md).
- [Opt-in shared themes](docs/themes.md) and the [theme gallery](../fx-example/docs/theme-gallery.md).
- [Opt-in queried Table results](docs/table-results.md), the DataGrid rendering foundation.
## Introduction
`fx` includes docking and standalone bars for ordinary JavaFX applications; these controls do not require MVVM initialization. Its optional MVVM functionality binds an FXML view to an ordinary Java model. The model stays a JavaBean. The library builds one view model for that instance, loads the view, and applies the binding elements declared in the FXML.
@@ -46,7 +52,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-SNAPSHOT` | Install the local reactor first; no Central publication is assumed |
| Internal modules | `fx` directly depends on `core` and `injection` | Resolved transitively through Maven |
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
| JavaFX | 27.0.1: base, graphics, controls, FXML and web | Resolved transitively; deployment still needs platform-native artifacts |
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
| Injection annotations | `jakarta.inject-api` 2.0.1 | Use Jakarta annotations, not `javax.inject` |
+45
View File
@@ -0,0 +1,45 @@
# Local DataGrid and request coordination
`DataGrid<K,T>` composes the existing Table result renderer with paging controls and a toolkit-independent coordinator. All UI methods are called on the JavaFX application thread. The legacy Table FXML/collection path is unchanged.
```java
var source = new MemoryGridSource<Long, Person>(
() -> people, Person::getId, Long::compare,
List.of(new MemoryColumn<>("name", MemoryColumn.Kind.TEXT,
person -> person.getName() == null ? null : new FilterValue.Text(person.getName()))),
applicationExecutor, 250);
var grid = new DataGrid<Long, Person>(
List.of(new ResultColumn("name", "Name", 180, 80, 400, -1)),
person -> {
Label name = new Label(person.getName());
return new ResultRow(new HBox(name), Map.of("name", name), () -> { });
}, source);
grid.setAllWarningThreshold(1000);
// Set optional edit guard / custom confirmation handler before the first request.
grid.load();
```
Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` for DataGrid/result rendering. The application owns the executor and closes the grid when its view is disposed. No query runs in the constructor.
## Operations
- First/Previous/Next/Last, page-size selection, Refresh and Retry are supplied. Page sizes offer 25/50/100/250 within source limits plus explicit All when supported. The initial page size is 50, bounded by source limits.
- Header clicks alternate ascending/descending sort for that mapped column; `setSort(null)` clears user sorting. Sorting/filter/page-size changes request the first page (All remains All with fresh consent checks).
- `setFilters`, `setSort`, `setPageRequest`, `setSource`, `load`, `refresh`, and `retry` delegate to the coordinator; returned rows are never locally filtered again.
- `stateProperty` exposes requested versus displayed query, result, phase and error. Loading/failed rows stay visible but disabled; selected loaded data becomes unavailable while those rows are stale. Query/navigation controls remain usable.
- `selectedKeyProperty` retains an off-page identity. `selectedElementProperty` exposes only current displayed selected data. A successfully replaced source clears selection. `confirmedDeleted(key)` clears that key and refreshes; absence from a page alone does not imply deletion.
- 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.
## 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.
The default All warning is based on the source's count in its execution snapshot, before unpaged rows are returned. Exactly the threshold does not warn. Cancel restores the prior displayed query/page. A subsequent approved attempt takes a fresh source snapshot; approval is not stored in setup data or reused for later query changes. The coordinator requires a source that implements the guarded All overload, not just a flag claiming All support.
The application must provide a serial owner-thread callback executor when using the neutral coordinator directly. DataGrid always uses Platform.runLater and keeps row publication on the FX thread. Requests triggered by state/selection observers are queued after publication.
## Lifecycle and remaining slices
`close` cancels the active request, invalidates pending callbacks/alerts, closes the renderer and releases displayed rows. It does not close application-owned infrastructure. Observe `disposalFailureProperty` for row cleanup failures.
FXML filter editors and the opt-in popup host are now available; see [filter editors](filter-editors.md), including the recorded native qualification limitation. [JSON setup restore](saved-setups.md) is available through the optional Gson module. [Shared themes and window propagation](themes.md) are available opt-in. The optional [JDBC adapter and H2 example](../../fx-example/docs/product-grid.md) now demonstrate external execution. The default alert is ordinary JavaFX; native interaction/theme qualification remains part of those acceptance gates. Row mappings, programmatic order/width changes and cleanup retain the foundation guide's constraints in [table-results](table-results.md).
+78
View File
@@ -0,0 +1,78 @@
# Transactional FXML filters
`DataGrid` filtering is opt-in. Existing `Table` FXML, checklist and comparison behavior is unchanged. The new API uses one immutable condition per column, with AND across columns. Editors create drafts; only the popup host accepts or cancels them. SQL and persistence do not belong in a controller.
```java
grid.configureFilter("name", FilterColumn.text());
grid.configureFilter("quantity", FilterColumn.number(
Locale.GERMANY, true, BigDecimal.ZERO, BigDecimal.valueOf(Integer.MAX_VALUE)));
grid.setFilterPopupOptions(new FilterPopup.Options(FilterPopup.Outside.CANCEL, true, true));
```
Types are in `de.neitzel.fx.grid.filter`; conditions and candidate contracts are in `de.neitzel.grid`. Each configured header gets an accessible vector filter button which does not sort the column. Standalone `TableResults.setFilterActions` delegates the same button to an application-supplied handler.
## Built-in editor
`BuiltInFilterEditor.fxml` and its controller implement text, numbers, missing/present and checklist modes. Clear filter removes the condition; an empty checklist instead matches nothing. Switching modes modifies only the current draft. Each opening creates a fresh controller, initialized from the committed condition.
Text is literal: `%`, `_`, empty equality and intentional spaces are preserved. Other text operations reject empty operands. Case-insensitive matching is the default; construct a `FilterColumn` with `caseSensitive=true` to override it.
Numeric parsing uses the configured locale and exact `BigDecimal`. Grouping separators are deliberately rejected rather than silently interpreted; use the locale's decimal separator. Integer columns reject fractions and signed-64-bit overflow, and configured minimum/maximum bounds enforce narrower types. NaN, infinity, reversed ranges and out-of-domain values fail with a visible explanation. No rounding occurs.
## Checklist providers
The grid default is `DISABLED`. A column can inherit it or select `DISABLED`, `CURRENT_PAGE`, or `SOURCE_WIDE`. The developer chooses the scope; it is not an end-user setting. Enabled columns must have an explicit provider, including when inheriting an enabled grid default.
```java
// Attach explicitly; the source is never implicitly inferred from loaded UI rows.
var sourceWide = memorySource.candidateProvider(value -> value == null ? "Missing" : display(value));
grid.configureFilter("name", FilterColumn.text()
.withChecklist(FilterColumn.Checklist.SOURCE_WIDE, sourceWide));
// For current-page values, supply typed Candidate entries from the displayed result.
var currentPage = FilterCandidates.currentPage(() -> candidatesFromDisplayedPage());
grid.configureFilter("name", FilterColumn.text()
.withChecklist(FilterColumn.Checklist.CURRENT_PAGE, currentPage));
```
`currentPage` copies supplied entries when the editor opens. `MemoryGridSource.candidateProvider` captures scalar values then evaluates other columns' filters on its executor, excluding the edited column's condition. Provider sessions accept a context, search text and offset/limit. Results carry typed values and independent labels; a null candidate value explicitly means missing. Distinctness never depends on the label.
Source-wide providers must declare that scope and implement search/batching; unsupported scopes show an explanation and cannot be accepted. Comparison modes remain usable. No fallback to the loaded page occurs. Select all shown and Uncheck shown affect only displayed candidates. Off-page/off-search selections survive searches, batches and failures. Async results after a newer search or disposal are ignored. A failure is displayed with Retry and preserves the draft; it is never treated as an empty successful result.
## Custom FXML controllers and capabilities
Implement `FilterEditor`: supply a detached fresh `Parent`, a read-only validation message, `draft()` and `close()`. Load FXML with `FXMLLoader` inside a registration factory; applications can supply their own controller factory/injection. `draft()` returns an immutable `FilterCondition` or null for Clear, and throws an actionable validation exception for invalid input. It must not modify a grid or execute SQL. Release external listeners and pending lookup work in `close()`.
```java
var editors = FilterEditors.builtIns();
editors.register(new FilterEditors.Registration(
"app.custom", new FilterCapabilities(true, false, Set.of()),
Set.of("app.custom"), context -> MyFxmlEditor.load(context)));
grid.setFilterEditors(editors);
```
Configure a column with that editor ID. Registration declares emitted condition IDs plus independent local, persistence and adapter capabilities. The popup checks emitted IDs and the active source's execution capability ID; the source then validates the concrete condition. An editor declaration alone never makes a condition executable. Memory columns need a matching custom compiler in `MemoryColumn.customFilters`. External sources override `filterExecutionId()` and `validateFilter()`; the default visibly rejects undeclared support. `DataGrid.setFilters` also validates through the source before changing requested state.
The built-in registry declares local evaluation and persistence through the optional Gson module; see [saved setups](saved-setups.md). Use `FilterEditors.builtIns(Set.of("jdbc-h2"))` to explicitly declare the qualified H2 adapter in an application; source validation still checks each concrete condition. The no-argument registry retains local-only declarations. See the [H2 demonstration](../../fx-example/docs/product-grid.md). Duplicate editor IDs and missing registrations fail explicitly.
## Popup completion and disposal
`FilterPopup` hosts any editor with independent optional OK/Cancel actions and Clear filter. Enter accepts; Escape cancels. Open ComboBox/DatePicker choosers get their own Enter/Escape first. Custom nonstandard nested popups implement `nestedPopupShowing` and `closeNestedPopup`.
Outside dismissal defaults to Cancel and can be configured to Accept. Invalid or unsupported outside-accept keeps/reopens the draft with an error and preserves the committed condition. Opener re-click uses the same policy. Explicit completion requests focus back to the opener; outside completion leaves focus with the clicked target. Owner hiding or detaching the opener cancels and disposes the session. `close()` is idempotent and always rolls back. Cleanup failures are exposed by `FilterPopup.disposalFailureProperty` after the popup has released its window listeners and content.
These are the implemented policies. The user waived the remaining native/manual qualification for this popup implementation. Native OS input routing, placement and other-application dismissal remain unverified; handler tests do not establish them. See the workspace implementation ticket and the probe below.
## Reproducible native qualification
After running tests including `FilterEditorsTest`, from the repository root:
```sh
python3 fx/scripts/filter-popup-probe.py --manual
# Optional automated OS-input attempt; it fails rather than substituting synthetic events:
python3 fx/scripts/filter-popup-probe.py
```
The manual probe opens the production popup/editor plus a DatePicker to qualify custom nested controls. Check real typing + Enter (with actions visible and hidden), Escape rollback, ComboBox selection and first-Escape handling, DatePicker selection and first-Escape handling, second Escape, both outside policies, invalid outside-accept, opener re-click, focus return versus outside target focus, owner disposal, repeated reopening, other-application dismissal, and placement near screen edges. Close the window to end the probe. The remaining manual qualification was waived by the user; this launcher remains available for future native evidence.
CSS hooks: `filter-button`, `filter-icon`, `filter-popup`, `filter-editor`, `filter-actions`, `filter-validation`. The popup includes owner-scene stylesheets at open. [Shared themes](themes.md) propagate live through the owner manager and include resolved popup text-contrast checks.
+50
View File
@@ -0,0 +1,50 @@
# Saved DataGrid setups
Saved setups are opt-in and preserve the legacy Table path. The `data-grid` module owns immutable models, definition validation and migrations; `fx` stages layout/result publication; the existing optional `gson` module owns JSON encoding. Applications choose storage and save/load timing. The FX library does not depend on Gson.
## Configure and save
```java
grid.configureSetups("inventory.products", 1,
Map.of("name", "text.v1", "quantity", "int32.v1"), Map.of());
GridSetupJson json = new GridSetupJson(); // de.neitzel.gson.grid; optional gson module
String document = json.encode(grid.snapshotSetup());
```
Use a stable definition ID and stable column type/schema identifiers. Labels and Java Attribute names are not identities. Every column needs a type. The existing two-argument `ColumnState(id,width)` constructor remains available for earlier model callers, but its `unspecified` type must be supplied before saving/restoring against a definition.
Snapshots include column order, default-versus-explicit widths, one user sort, committed conditions and page size or explicit All mode. They omit current page, selection, row data, credentials, unfinished drafts and All approval. Saving neither commits nor closes a filter editor and does not invoke the edit guard. Pending/failed queries do not become committed saved filters; snapshots use the last successfully displayed query, or the initial configuration before first success.
The complete JSON string is produced only if every filter can be encoded. No unsupported condition is omitted. Filesystem/database writes and atomic replacement of stored files remain application-owned.
## Restore
```java
// Configure before load(); constructor issues no query.
grid.restoreSetup(() -> json.decode(document));
```
The supplier overload presents decode errors through the same visible coordinator error state. It does not issue a default query. Alternatively pass an already decoded `GridSetup`.
Restoration validates format/definition versions, column identity/type, order constraints, source page limits and concrete filter support. New columns missing from a compatible document are appended in declaration order with default widths. Removed columns or changed types require migration. Fixed columns cannot move or be displaced by appended columns. Valid explicit widths are clamped to current limits; `restorationAdjustmentsProperty` reports these adjustments after successful publication. Negative, zero and non-finite widths are invalid.
Only after preparation succeeds does the asynchronous edit guard run. Guard denial retains any open filter draft. Approval cancels that draft and issues one initial query on the first page. The current layout and page remain displayed until both new rows and layout have been prepared successfully. Query or row-construction failure retains the previous committed setup/page and exposes an error. A cancelled draft is not resurrected on failure.
A newer query or layout operation supersedes a pending restore; late guard/query/confirmation results cannot install it. Selection keys survive restoration according to ordinary paging rules; selection is not read from a document. Filter lookup/editor validation and external-source validation remain independent.
All restores use the existing count-warning protocol with configurable threshold (default 1000): count first, release the attempt, ask Continue/Cancel, then start a fresh approved attempt. Consent is never saved. Cancel retains the previous setup. A newer request invalidates old consent. A failed restore returns requested settings to the previous committed configuration; retrying the saved candidate requires calling `restoreSetup` again.
## Explicit migrations
Supply `Map<Integer, UnaryOperator<GridSetup>>` to `configureSetups`. The key is the old definition version; each migration must return exactly the next version, retain the definition ID and supported format, and explicitly repair removed/renamed IDs, type changes and dependent filters/sorts. Migrations run consecutively until the configured version. Missing migration steps, future versions and output violating current constraints fail without querying. A migration cannot bypass source validation.
Appending a new column does not itself require a migration when the saved definition version remains compatible; if the developer advances the definition version, an explicit migration is required even if it simply confirms compatible existing state.
## JSON and custom filters
`GridSetupJson` format version 1 uses explicit objects and typed scalar values. Exact decimal operands and integer checklist values use strings to avoid conversion through floating point. Missing checklist values remain separate from empty strings. Strict parsing rejects duplicate/unknown properties, trailing input, incorrect scalar types and unsupported versions. No arbitrary Java object deserialization is used.
Implement and register `GridSetupJson.FilterCodec` for a custom stable filter type ID. Declare the write version, readable versions, explicit JSON payload and decoding logic. The codec must preserve the requested column/type identity. `readableVersions` defaults to the current write version; support older payloads only with explicit decoding/migration logic. Missing codecs and unsupported payload versions fail visibly. Codec registration is independent of editor availability and local/adapter execution; successful decoding does not establish that the active source supports the condition.
Built-in text, number, missing/present and checklist codecs are supplied. The built-in editor registrations now declare persistence support through this optional module. See the [JDBC demonstration](../../fx-example/docs/product-grid.md) and [shared themes](themes.md) for opt-in integration.
+27
View File
@@ -0,0 +1,27 @@
# Opt-in queried Table results
`Table.openResults` is a presentation integration point for the DataGrid coordinator. It does not replace the existing ViewLoader/FXML collection Table. Call it on a fresh Table on the JavaFX application thread; a Table cannot switch between modes or be opened twice.
```java
Table table = new Table();
TableResults<Long, Person> renderer = table.openResults(
List.of(new ResultColumn("name", "Name", 180, 80, 400, -1)),
person -> {
Label name = new Label(person.getName());
HBox root = new HBox(name);
return new ResultRow(root, Map.of("name", name), () -> { });
});
renderer.show(List.of(new GridRow<>(person.getId(), person)));
```
Factories may supply freshly bound FXML Components as HBox roots. They must map every column ID to a distinct direct-child Region. Any unmapped children are trailing action controls. Supply a disposer to release application bindings/listeners; the renderer removes its own click handler. Never return an existing attached root or reuse a row between results. No Component is rebound to a new model.
The renderer preserves supplied row order and does no local filtering, sorting, fetching or edit observation. The caller validates query results and handles guard approval before calling `show`. It stages new rows before replacing old ones. If construction or mapping validation fails, staged rows are disposed and the old page remains. Factory code that throws before returning a row owns cleanup of its partial construction.
`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. This first integration point supplies programmatic ordering/sizing, not drag UI. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
`select(key)` retains an off-page key; the read-only loaded selected element becomes null until that key returns. Row clicks and blank-body clicks update this separate result selection. The old `Table.selectionProperty()` remains the legacy path and is not the result-mode selection API.
`close()` is idempotent, removes rows/handlers and disposes row resources. Disposal failures do not undo an already published page; observe `disposalFailureProperty()` to surface them. Explicit close is necessary; attaching/removing a Table from a Scene does not infer application ownership.
This is a rendering foundation, not the complete DataGrid. [Local DataGrid](data-grid.md) now supplies request coordination and local source execution. [FXML popup editors](filter-editors.md), [setup codecs](saved-setups.md), and [themes](themes.md) are implemented. Ordering and sizing use the documented programmatic API; drag reorder/resize is not supplied by this result renderer.
+74
View File
@@ -0,0 +1,74 @@
# Opt-in shared themes
`de.neitzel.fx.theme.ThemeManager` is application-owned and uses the JavaFX application thread. Existing applications, including legacy Table users, retain their appearance until they register a scene. The bundled themes are `light`, `dark` and `high-contrast` (dark polarity). They share typography, spacing and dimensions; no filter behavior, query, page setting, selection or explicit column width is changed by a theme switch.
```java
ThemeManager themes = new ThemeManager();
ThemeManager.Registration registration = themes.register(scene);
themes.failureProperty().addListener((observable, old, failure) -> {
if (failure != null) showThemeFailure(failure.message());
});
themes.selectSaved(applicationPreference); // unavailable preference falls back to light with explanation
// Later:
themes.select("high-contrast");
// At application/view disposal:
registration.close();
themes.close();
```
Applications persist the theme ID separately from DataGrid setups. OS-following is not enabled. A second high-contrast polarity can be supplied through `addTheme(new Theme(id, stylesheetUrls))`.
## Windows and lifetime
Register application scenes explicitly. Owned popups/dialogs inherit the manager when shown; this includes filter editors, ComboBox/DatePicker nested windows, tooltips and DataGrid confirmation alerts. A dialog must have an owner to inherit automatically. `MessagePopup.showNewMessages(model, owner)` supplies an opt-in owned-message path; the original overload remains unchanged.
Docking floating windows carry an explicit link to the main scene without changing their native ownership or close semantics. `ThemeManager.link(childWindow, ownerScene)` provides the same hook for other library windows. Ordinary owned application stages also inherit. Windows created after selection receive the current theme. Automatically registered scenes release their registration when hidden and are registered again on reopening. Explicit registrations are application-owned and must be closed; the manager closes all remaining registrations and its window listener on disposal.
Standard JavaFX Dialogs bind their stylesheet list to the owner's list. The manager scopes and validates those scenes but does not mutate the bound target list. Popups have copied stylesheet lists and are updated separately. This distinction is covered by tests that fail on uncaught FX-thread errors.
Do not use one scene with two theme managers. SubScene and web/HTML content have separate styling domains and are not covered by this scene manager.
## Cascade and customization
Managed CSS order is component defaults, shared base/selected palette, then application styles. Application stylesheet ordering is preserved on changes and shutdown. Theme bundle URLs explicitly registered with the manager are reserved as manager-owned; keep application overrides in separate URLs. Filter popups copy application styles without copying a frozen palette.
JavaFX specificity and scope still apply: parent-level sheets can outrank scene-level sheets, and inline styles outrank ordinary stylesheet rules. A later sheet alone does not guarantee an override. Use matching documented selectors, or an intentional parent/inline override. For example, an application stylesheet appended after registration can set `.neitzel-theme { -nl-focus: #005fcc; }`. Custom palettes/overrides require their own contrast qualification.
CSS controls colors, fonts, padding, borders, backgrounds, focus/state indicators and icon appearance. APIs control source/filter behavior, dismissal policy, paging, selection and saved/explicit widths. No new styleable Java properties were needed; standard JavaFX CSS properties and looked-up colors express the presentation contract.
## Palette and public hooks
All bundled palette colors are opaque. Stable looked-up colors:
| Token | Meaning |
| --- | --- |
| `-nl-surface`, `-nl-raised`, `-nl-hover` | Main, raised and hovered surfaces |
| `-nl-text`, `-nl-muted` | Normal and readable disabled/secondary text |
| `-nl-selection`, `-nl-selection-text` | Selected surface and its text |
| `-nl-focus`, `-nl-border` | Focus and control boundaries |
| `-nl-error`, `-nl-warning` | Error and warning text/indicators |
The manager adds `neitzel-theme` only to registered roots. Public library hooks include:
- `data-grid`, `data-grid-status`, `data-grid-paging`; DataGrid publishes `:loading` and `:error`.
- `result-row` and `:selected`; the previous `selected` style class remains supported. Stale/disabled selected rows retain readable text.
- `filter-button`, `filter-icon`, `filter-popup`, `filter-editor`, `filter-actions`, `filter-validation`; active buttons expose `:filtered`, a dot, a dashed boundary and an accessible active description.
- Legacy `table`, `column-header-row`, `column-cell`, `column-header`, `column-opener.filtered`, `column-popup`, `table-scroll`; behavior is unchanged.
- Existing docking hooks, including `dock-divider`, `dock-area-divider`, `dock-drop-indicator` and `dock-floating-preview-frame`.
- `theme-error` and `theme-warning` for application messages. Supply explanatory text/symbols, not color alone. Applications can use `:invalid` on input controls alongside an explanation.
Standard-control coverage includes buttons/toggles, text inputs, checkboxes/radio buttons, combo/date controls, TableView/ListView/TreeView selection, menu/dialog/tooltip surfaces and progress indicators. Internal skin selectors used by the shipped sheets follow the pinned JavaFX baseline; applications should prefer the palette/public hooks rather than duplicating skin structure.
## Failure handling
A missing theme or unreadable stylesheet leaves the previous selection and managed sheets intact and sets `failureProperty`. `selectSaved` explicitly falls back to light and retains an explanation. `select` returns success/failure; failures are not silently ignored by the gallery.
An optional `setInstallationCheck(scene -> ...)` can perform application-specific post-CSS validation. Throwing rolls back managed sheets across registered scenes. Checks should be read-only and must not create/dispose windows or reenter the manager. JavaFX does not surface every CSS warning as an exception; the manager does not claim transactional detection/recovery for every parser diagnostic or visual defect.
## Qualification
The shared gallery tests measure resolved control foreground/background combinations after CSS application, including normal, hover, focus, disabled, invalid, selected TableView/DataGrid, selected disabled rows, errors/warnings, filter icons, checkbox boundaries, popup drafts, dialogs and floating windows. Light/dark normal text targets 4.5:1, high-contrast text 7:1, meaningful boundaries/icons/focus 3:1. These are desktop design targets, not a claim of full WCAG or accessibility conformance.
See the [runnable gallery](../../fx-example/docs/theme-gallery.md) for screenshots, measurements and scope. Focus/hover specimens deliberately expose CSS states; they are not evidence of native keyboard routing. The user's earlier popup-native-test waiver remains separate from theme-state rendering qualification.
DNSCheck owns file/live/removal palette entries and row/legend semantics. This library does not introduce DNS domain colors. Actual DNSCheck integration/selection combinations remain the dedicated downstream ticket; the gallery's FILE/LIVE/REMOVE text demonstrates non-color indicators only.
+1
View File
@@ -44,6 +44,7 @@
</dependency>
<!-- NeitzelLib dependencies -->
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>core</artifactId>
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python3
"""Run the opt-in native/manual probe using the last focused test classpath."""
import pathlib
import subprocess
import sys
import xml.etree.ElementTree as ET
module = pathlib.Path(__file__).resolve().parent.parent
report = module / 'target/surefire-reports/TEST-de.neitzel.fx.view.FilterEditorsTest.xml'
if not report.exists():
sys.exit('First run the documented focused Maven tests including FilterEditorsTest.')
properties = {p.get('name'): p.get('value') for p in ET.parse(report).getroot().find('properties')}
classpath = properties.get('surefire.test.class.path', properties['java.class.path'])
raise SystemExit(subprocess.call(['java', '--enable-native-access=ALL-UNNAMED', '-cp', classpath,
'de.neitzel.fx.view.FilterPopupNativeProbe', *sys.argv[1:]], cwd=module.parent))
@@ -1351,6 +1351,7 @@ public final class DockingManager {
DockPane floatingPane = new DockPane();
Stage floatingStage = new Stage();
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
de.neitzel.fx.theme.ThemeManager.link(floatingStage, stage.getScene());
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler = event -> {
event.consume();
requestFloatingWindowClose(windowId);
@@ -0,0 +1,344 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.fxml.*;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.*;
import java.util.*;
/**
* FXML controller for literal text, exact numeric, missing/present and explicit membership drafts.
*/
public final class BuiltInFilterEditor implements FilterEditor {
@FXML private ComboBox<String> mode, operator;
@FXML private TextField operand, upper, search;
@FXML private CheckBox caseSensitive;
@FXML private VBox comparison, checklistPane, candidates;
@FXML private Label scope, validation, lookupMessage, selectionSummary;
@FXML private Button selectShown, clearShown, more, retry;
private Parent view;
private FilterEditorContext context;
private final ReadOnlyStringWrapper message = new ReadOnlyStringWrapper("");
private final Set<FilterValue> selected = new LinkedHashSet<>();
private boolean missing, closed, configuring, numeric, available;
private long generation;
private int offset;
private FilterCandidates.Context candidateContext;
private FilterCandidates.Session session;
private final List<FilterCandidates.Candidate> shown = new ArrayList<>();
public static BuiltInFilterEditor load(FilterEditorContext context) {
try {
var loader =
new FXMLLoader(
BuiltInFilterEditor.class.getResource("BuiltInFilterEditor.fxml"));
Parent root = loader.load();
BuiltInFilterEditor editor = loader.getController();
editor.view = root;
try {
editor.configure(context);
} catch (RuntimeException error) {
editor.close();
throw error;
}
return editor;
} catch (IOException error) {
throw new IllegalStateException("Cannot load built-in filter FXML", error);
}
}
private void configure(FilterEditorContext context) {
this.context = context;
configuring = true;
numeric = context.configuration().editorId().equals("neitzel.number");
mode.getItems().setAll("Comparison", "Missing", "Present", "Clear filter");
if (numeric)
for (var op : NumericFilter.Operator.values()) operator.getItems().add(op.name());
else for (var op : TextFilter.Operator.values()) operator.getItems().add(op.name());
operator.setValue("EQUALS");
mode.setValue("Comparison");
caseSensitive.setSelected(context.configuration().caseSensitive());
caseSensitive.setVisible(!numeric);
caseSensitive.setManaged(!numeric);
if (context.checklist() != FilterColumn.Checklist.DISABLED) {
var requestedScope =
context.checklist() == FilterColumn.Checklist.CURRENT_PAGE
? FilterCandidates.Scope.CURRENT_PAGE
: FilterCandidates.Scope.SOURCE_WIDE;
candidateContext =
new FilterCandidates.Context(
context.columnId(), requestedScope, context.otherFilters());
available = context.configuration().candidates().scopes().contains(requestedScope);
scope.setText(
available
? (requestedScope == FilterCandidates.Scope.CURRENT_PAGE
? "Current page only — captured when opened"
: "Source-wide — excluding this column's filter")
: "Checklist unavailable: provider does not support "
+ requestedScope
+ ". Use a comparison or supply a capable provider.");
// Keep the unavailable mode visible with an explanation, never substitute a scope.
mode.getItems().add("Checklist");
if (available) {
try {
session = context.configuration().candidates().open(candidateContext);
} catch (RuntimeException error) {
lookupMessage.setText("Lookup failed: " + error.getMessage());
}
}
}
FilterCondition committed = context.committed();
if (committed instanceof TextFilter f && !numeric) {
operator.setValue(f.operator().name());
operand.setText(f.operand());
caseSensitive.setSelected(f.caseSensitive());
} else if (committed instanceof NumericFilter f && numeric) {
operator.setValue(f.operator().name());
operand.setText(format(f.operand()));
if (f.upper() != null) upper.setText(format(f.upper()));
} else if (committed instanceof MissingFilter f)
mode.setValue(f.missing() ? "Missing" : "Present");
else if (committed instanceof ValueFilter f) {
selected.addAll(f.values());
missing = f.includeMissing();
if (!mode.getItems().contains("Checklist"))
throw new IllegalArgumentException(
"Existing checklist requires an enabled candidate provider; clear it"
+ " explicitly or restore the configuration");
mode.setValue("Checklist");
} else if (committed != null)
throw new IllegalArgumentException("Editor cannot restore " + committed.typeId());
else mode.setValue("Clear filter");
validation.textProperty().bind(message);
mode.valueProperty().addListener((o, a, b) -> changed());
operator.valueProperty().addListener((o, a, b) -> changed());
operand.textProperty().addListener((o, a, b) -> changed());
upper.textProperty().addListener((o, a, b) -> changed());
caseSensitive.selectedProperty().addListener((o, a, b) -> changed());
search.textProperty().addListener((o, a, b) -> lookup(false));
selectShown.setOnAction(e -> selectShown(true));
clearShown.setOnAction(e -> selectShown(false));
more.setOnAction(e -> lookup(true));
retry.setOnAction(e -> lookup(false));
configuring = false;
changed();
if (available) lookup(false);
}
private String format(BigDecimal value) {
return value.toPlainString()
.replace(
'.',
DecimalFormatSymbols.getInstance(context.configuration().locale())
.getDecimalSeparator());
}
private BigDecimal number(String text) {
// Grouping deliberately disallowed: malformed grouping must never be silently ignored.
var format =
(DecimalFormat) NumberFormat.getNumberInstance(context.configuration().locale());
format.setGroupingUsed(false);
format.setParseBigDecimal(true);
String input = text.strip();
var position = new ParsePosition(0);
Number parsed = format.parse(input, position);
if (!(parsed instanceof BigDecimal value) || position.getIndex() != input.length())
throw new IllegalArgumentException(
"Enter a finite number for "
+ context.configuration().locale()
+ " without grouping separators");
var config = context.configuration();
if (config.integer()) {
try {
value.longValueExact();
} catch (ArithmeticException error) {
throw new IllegalArgumentException(
"Enter a whole number within the signed 64-bit range");
}
}
if ((config.minimum() != null && value.compareTo(config.minimum()) < 0)
|| (config.maximum() != null && value.compareTo(config.maximum()) > 0))
throw new IllegalArgumentException("Number is outside the configured column range");
return value;
}
public FilterCondition draft() {
if (closed) throw new IllegalStateException("Editor closed");
return switch (mode.getValue()) {
case "Clear filter" -> null;
case "Missing" -> new MissingFilter(context.columnId(), true);
case "Present" -> new MissingFilter(context.columnId(), false);
case "Checklist" -> {
if (!available)
throw new IllegalArgumentException(
"Checklist scope is unavailable; configure a capable provider");
yield new ValueFilter(context.columnId(), selected, missing);
}
case "Comparison" ->
numeric
? new NumericFilter(
context.columnId(),
NumericFilter.Operator.valueOf(operator.getValue()),
number(operand.getText()),
operator.getValue().equals("RANGE")
? number(upper.getText())
: null)
: new TextFilter(
context.columnId(),
TextFilter.Operator.valueOf(operator.getValue()),
operand.getText(),
caseSensitive.isSelected());
default -> throw new IllegalArgumentException("Select a filter mode");
};
}
private void changed() {
if (configuring || closed) return;
boolean comparing = mode.getValue().equals("Comparison"),
checklist = mode.getValue().equals("Checklist");
comparison.setVisible(comparing);
comparison.setManaged(comparing);
checklistPane.setVisible(checklist);
checklistPane.setManaged(checklist);
boolean range = numeric && "RANGE".equals(operator.getValue());
upper.setVisible(range);
upper.setManaged(range);
selectionSummary.setText(
selected.size()
+ " selected values"
+ (missing ? " plus missing" : "")
+ " (including values outside this batch)");
try {
draft();
message.set("");
} catch (RuntimeException error) {
message.set(error.getMessage());
}
}
private void selectShown(boolean select) {
for (var value : shown) {
if (value.value() == null) missing = select;
else if (select) selected.add(value.value());
else selected.remove(value.value());
}
render();
changed();
}
private void render() {
candidates.getChildren().clear();
for (var value : shown) {
var box = new CheckBox(value.label());
box.setSelected(value.value() == null ? missing : selected.contains(value.value()));
box.setOnAction(
e -> {
if (value.value() == null) missing = box.isSelected();
else if (box.isSelected()) selected.add(value.value());
else selected.remove(value.value());
changed();
});
candidates.getChildren().add(box);
}
}
private void lookup(boolean append) {
if (closed || !available) return;
long token = ++generation;
int requestedOffset = append ? offset : 0;
lookupMessage.setText("Loading candidates…");
more.setDisable(true);
retry.setDisable(true);
try {
if (session == null)
session = context.configuration().candidates().open(candidateContext);
session.load(
new FilterCandidates.Request(
candidateContext, search.getText(), requestedOffset, 50))
.whenComplete(
(batch, error) ->
Platform.runLater(
() -> {
if (closed || generation != token) return;
retry.setDisable(false);
if (error != null || batch == null) {
lookupMessage.setText(
"Lookup failed: "
+ (error == null
? "missing batch"
: error.getMessage())
+ ". Selections preserved;"
+ " retry available.");
return;
}
if (!append) shown.clear();
// Count provider rows, not de-duplicated display
// rows, for the next offset.
offset =
Math.addExact(
requestedOffset,
batch.candidates().size());
for (var candidate : batch.candidates())
if (shown.stream()
.noneMatch(
c ->
Objects.equals(
c.value(),
candidate
.value())))
shown.add(candidate);
more.setDisable(
!batch.hasMore()
|| batch.candidates().isEmpty());
lookupMessage.setText(
batch.hasMore()
? "More candidates available"
: "End of candidate results");
render();
changed();
}));
} catch (RuntimeException error) {
retry.setDisable(false);
lookupMessage.setText(
"Lookup failed: " + error.getMessage() + ". Selections preserved.");
}
}
public Parent view() {
return view;
}
public ReadOnlyStringProperty validationMessageProperty() {
return message.getReadOnlyProperty();
}
public boolean nestedPopupShowing() {
return mode.isShowing() || operator.isShowing();
}
public void closeNestedPopup() {
mode.hide();
operator.hide();
}
public void close() {
if (closed) return;
closed = true;
generation++;
closeNestedPopup();
validation.textProperty().unbind();
if (session != null) {
var retired = session;
session = null;
retired.close();
}
}
}
@@ -0,0 +1,66 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.FilterCandidates;
import java.math.BigDecimal;
import java.util.*;
/** Developer configuration. Bounds express the actual numeric domain, without rounding. */
public record FilterColumn(
String editorId,
Locale locale,
boolean caseSensitive,
boolean integer,
BigDecimal minimum,
BigDecimal maximum,
Checklist checklist,
FilterCandidates.Provider candidates) {
public enum Checklist {
INHERIT,
DISABLED,
CURRENT_PAGE,
SOURCE_WIDE
}
public FilterColumn {
Objects.requireNonNull(editorId);
Objects.requireNonNull(locale);
Objects.requireNonNull(checklist);
if (minimum != null && maximum != null && minimum.compareTo(maximum) > 0)
throw new IllegalArgumentException("Reversed numeric domain");
if ((checklist == Checklist.CURRENT_PAGE || checklist == Checklist.SOURCE_WIDE)
&& candidates == null)
throw new IllegalArgumentException(
"Enabled checklist requires a developer-supplied provider");
}
public static FilterColumn text() {
return new FilterColumn(
"neitzel.text",
Locale.getDefault(),
false,
false,
null,
null,
Checklist.INHERIT,
null);
}
public static FilterColumn number(
Locale locale, boolean integer, BigDecimal minimum, BigDecimal maximum) {
return new FilterColumn(
"neitzel.number",
locale,
false,
integer,
minimum,
maximum,
Checklist.INHERIT,
null);
}
public FilterColumn withChecklist(Checklist mode, FilterCandidates.Provider provider) {
return new FilterColumn(
editorId, locale, caseSensitive, integer, minimum, maximum, mode, provider);
}
}
@@ -0,0 +1,25 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.FilterCondition;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.scene.Parent;
/** Fresh per session; controllers own drafts only. Null draft explicitly clears the filter. */
public interface FilterEditor extends AutoCloseable {
Parent view();
ReadOnlyStringProperty validationMessageProperty();
/** Throws an actionable IllegalArgumentException for invalid input; never mutates a query. */
FilterCondition draft();
default boolean nestedPopupShowing() {
return false;
}
default void closeNestedPopup() {}
@Override
void close();
}
@@ -0,0 +1,28 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.*;
import java.util.*;
public record FilterEditorContext(
String columnId,
FilterColumn configuration,
FilterCondition committed,
List<FilterCondition> otherFilters,
FilterColumn.Checklist checklist) {
public FilterEditorContext {
Objects.requireNonNull(columnId);
Objects.requireNonNull(configuration);
Objects.requireNonNull(checklist);
otherFilters = List.copyOf(otherFilters);
if (checklist == FilterColumn.Checklist.INHERIT)
throw new IllegalArgumentException("Resolve checklist default first");
if (checklist != FilterColumn.Checklist.DISABLED && configuration.candidates() == null)
throw new IllegalArgumentException(
"Enabled checklist requires a provider for " + columnId);
if (committed != null && !columnId.equals(committed.columnId()))
throw new IllegalArgumentException("Wrong committed column");
if (otherFilters.stream().anyMatch(c -> c.columnId().equals(columnId)))
throw new IllegalArgumentException("Own filter in candidate context");
}
}
@@ -0,0 +1,77 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.*;
import java.util.*;
import java.util.function.Function;
/** Editor availability never implies evaluation, persistence or adapter support. */
public final class FilterEditors {
public record Registration(
String id,
FilterCapabilities capabilities,
Set<String> conditionTypes,
Function<FilterEditorContext, FilterEditor> factory) {
public Registration {
if (id == null || id.isBlank())
throw new IllegalArgumentException("Missing stable editor ID");
Objects.requireNonNull(capabilities);
conditionTypes = Set.copyOf(conditionTypes);
if (conditionTypes.isEmpty())
throw new IllegalArgumentException("Declare emitted condition types");
Objects.requireNonNull(factory);
}
public void requireEvaluation(String executionId) {
boolean supported =
executionId.equals("local")
? capabilities.localEvaluation()
: capabilities.adapters().contains(executionId);
if (!supported)
throw new UnsupportedOperationException(
"Editor "
+ id
+ " does not declare evaluation for "
+ executionId
+ "; register a compatible filter or change source");
}
public void validate(FilterCondition condition) {
if (condition != null && !conditionTypes.contains(condition.typeId()))
throw new UnsupportedOperationException(
"Editor " + id + " did not declare condition " + condition.typeId());
}
}
private final Map<String, Registration> registrations = new LinkedHashMap<>();
public void register(Registration registration) {
if (registrations.putIfAbsent(registration.id(), registration) != null)
throw new IllegalArgumentException(
"Duplicate editor registration: " + registration.id());
}
public Registration require(String id) {
var registration = registrations.get(id);
if (registration == null)
throw new IllegalArgumentException("Register the missing filter editor: " + id);
return registration;
}
public static FilterEditors builtIns() {
return builtIns(Set.of());
}
/** Application-declared adapter support; every concrete condition is still source-validated. */
public static FilterEditors builtIns(Set<String> adapters) {
var editors = new FilterEditors();
for (String id : List.of("neitzel.text", "neitzel.number"))
editors.register(
new Registration(
id,
new FilterCapabilities(true, true, adapters),
Set.of(id, "neitzel.missing", "neitzel.values"),
BuiltInFilterEditor::load));
return editors;
}
}
@@ -0,0 +1,245 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.FilterCondition;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ChangeListener;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import java.util.*;
import java.util.function.Consumer;
/** One transactional edit session. All methods run on the FX thread; close always rolls back. */
public final class FilterPopup implements AutoCloseable {
public enum Outside {
CANCEL,
ACCEPT
}
public record Options(Outside outside, boolean showOk, boolean showCancel) {
public Options {
Objects.requireNonNull(outside);
}
public static Options defaults() {
return new Options(Outside.CANCEL, true, true);
}
}
private final Node opener;
private final Window owner;
private final FilterEditor editor;
private final Consumer<FilterCondition> validate, commit;
private final Options options;
private final Popup popup = new Popup();
private final Label error = new Label();
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
new ReadOnlyObjectWrapper<>();
private final VBox root;
private boolean closed, reopening;
private final EventHandler<WindowEvent> ownerHidden = e -> close();
private final ChangeListener<Scene> detached =
(o, a, b) -> {
if (a != b) close();
};
public FilterPopup(
Node opener,
FilterEditor editor,
Options options,
Consumer<FilterCondition> validate,
Consumer<FilterCondition> commit) {
requireFx();
this.opener = Objects.requireNonNull(opener);
this.editor = Objects.requireNonNull(editor);
this.options = Objects.requireNonNull(options);
this.validate = Objects.requireNonNull(validate);
this.commit = Objects.requireNonNull(commit);
if (opener.getScene() == null
|| opener.getScene().getWindow() == null
|| !opener.getScene().getWindow().isShowing())
throw new IllegalArgumentException("Filter opener needs a visible owner window");
owner = opener.getScene().getWindow();
Button ok = new Button("OK"),
cancel = new Button("Cancel"),
clear = new Button("Clear filter");
ok.setId("filter-ok");
cancel.setId("filter-cancel");
clear.setId("filter-clear");
ok.setOnAction(e -> accept());
cancel.setOnAction(e -> cancel());
clear.setOnAction(e -> finish(true, true, true));
ok.setVisible(options.showOk());
ok.setManaged(options.showOk());
cancel.setVisible(options.showCancel());
cancel.setManaged(options.showCancel());
HBox actions = new HBox(8, ok, cancel, clear);
actions.getStyleClass().add("filter-actions");
error.setWrapText(true);
error.getStyleClass().add("filter-validation");
root = new VBox(8, editor.view(), error, actions);
root.getStyleClass().addAll("root", "filter-popup");
root.setFocusTraversable(true);
root.getStylesheets().add(FilterPopup.class.getResource("filters.css").toExternalForm());
root.getStylesheets()
.addAll(de.neitzel.fx.theme.ThemeManager.applicationStyles(opener.getScene()));
popup.getContent().add(root);
popup.setAutoHide(true);
popup.setHideOnEscape(false);
popup.setConsumeAutoHidingEvents(false);
popup.setOnAutoHide(e -> outside());
popup.setOnHidden(
e ->
Platform.runLater(
() -> {
if (!closed && !reopening && !popup.isShowing()) close();
}));
root.addEventFilter(
KeyEvent.KEY_PRESSED,
e -> {
if (e.getCode() != KeyCode.ENTER && e.getCode() != KeyCode.ESCAPE) return;
if (nested()) {
if (e.getCode() == KeyCode.ESCAPE) {
hideNested();
e.consume();
}
return;
}
e.consume();
if (e.getCode() == KeyCode.ENTER) accept();
else cancel();
});
owner.addEventHandler(WindowEvent.WINDOW_HIDING, ownerHidden);
opener.sceneProperty().addListener(detached);
}
public void show() {
requireFx();
if (closed) throw new IllegalStateException("Filter session closed");
var bounds = opener.localToScreen(opener.getBoundsInLocal());
if (bounds == null || !owner.isShowing()) {
close();
return;
}
popup.show(opener, bounds.getMinX(), bounds.getMaxY());
Platform.runLater(
() -> {
if (!closed && popup.isShowing()) {
Node field = editor.view().lookup(".text-field");
(field == null || !visible(field) ? root : field).requestFocus();
}
});
}
public boolean isOpen() {
return !closed;
}
public boolean isShowing() {
return popup.isShowing();
}
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
return disposalFailure.getReadOnlyProperty();
}
public String errorMessage() {
return error.getText();
}
public void accept() {
finish(true, true, false);
}
public void cancel() {
finish(false, true, false);
}
/** Used for outside dismissal and an opener re-click; leaves focus with the clicked target. */
public void outside() {
finish(options.outside() == Outside.ACCEPT, false, false);
}
private void finish(boolean accept, boolean focus, boolean clear) {
requireFx();
if (closed) return;
if (accept) {
try {
FilterCondition condition = clear ? null : editor.draft();
validate.accept(condition);
commit.accept(condition);
} catch (RuntimeException invalid) {
error.setText(
Objects.toString(invalid.getMessage(), invalid.getClass().getSimpleName()));
if (!popup.isShowing() && owner.isShowing()) {
reopening = true;
Platform.runLater(
() -> {
if (!closed) show();
reopening = false;
});
}
return;
}
}
close();
if (focus && owner.isShowing() && opener.getScene() != null) opener.requestFocus();
}
private static boolean visible(Node node) {
for (Node current = node; current != null; current = current.getParent())
if (!current.isVisible() || current.isDisabled()) return false;
return true;
}
private List<ComboBoxBase<?>> choosers() {
List<ComboBoxBase<?>> found = new ArrayList<>();
collect(editor.view(), found);
return found;
}
private static void collect(Node node, List<ComboBoxBase<?>> found) {
if (node instanceof ComboBoxBase<?> chooser) found.add(chooser);
if (node instanceof Parent parent)
for (Node child : parent.getChildrenUnmodifiable()) collect(child, found);
}
private boolean nested() {
return editor.nestedPopupShowing() || choosers().stream().anyMatch(ComboBoxBase::isShowing);
}
private void hideNested() {
editor.closeNestedPopup();
choosers().forEach(ComboBoxBase::hide);
}
public void close() {
requireFx();
if (closed) return;
closed = true;
owner.removeEventHandler(WindowEvent.WINDOW_HIDING, ownerHidden);
opener.sceneProperty().removeListener(detached);
popup.setOnAutoHide(null);
popup.setOnHidden(null);
popup.hide();
try {
editor.close();
} catch (RuntimeException failure) {
disposalFailure.set(failure);
} finally {
popup.getContent().clear();
}
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the FX application thread");
}
}
@@ -0,0 +1,34 @@
package de.neitzel.fx.theme;
import java.util.*;
/** A named CSS bundle. Themes contain presentation only; applications own preference storage. */
public record Theme(String id, List<String> stylesheets) {
public Theme {
if (id == null || id.isBlank()) throw new IllegalArgumentException("Missing theme ID");
stylesheets = List.copyOf(stylesheets);
if (stylesheets.isEmpty()) throw new IllegalArgumentException("Missing theme stylesheets");
}
public static Theme light() {
return bundled("light");
}
public static Theme dark() {
return bundled("dark");
}
public static Theme highContrast() {
return bundled("high-contrast");
}
private static Theme bundled(String id) {
return new Theme(id, List.of(resource("theme-base.css"), resource(id + ".css")));
}
private static String resource(String name) {
return Objects.requireNonNull(
Theme.class.getResource(name), "Missing bundled theme: " + name)
.toExternalForm();
}
}
@@ -0,0 +1,317 @@
package de.neitzel.fx.theme;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.beans.value.ChangeListener;
import javafx.collections.ListChangeListener;
import javafx.scene.*;
import javafx.stage.*;
import java.net.URI;
import java.util.*;
import java.util.function.Consumer;
/** Opt-in, application-owned theme lifetime. All operations use the FX application thread. */
public final class ThemeManager implements AutoCloseable {
private static final Object MANAGER = new Object(), OWNER_SCENE = new Object();
private static final String SCOPE = "neitzel-theme";
public record Failure(String message, Throwable cause) {}
private final Map<String, Theme> themes = new LinkedHashMap<>();
private final Map<Scene, Registration> scenes = new LinkedHashMap<>();
private final Map<Window, Registration> automatic = new IdentityHashMap<>();
private final ReadOnlyObjectWrapper<Theme> selected =
new ReadOnlyObjectWrapper<>(Theme.light());
private final ReadOnlyObjectWrapper<Failure> failure = new ReadOnlyObjectWrapper<>();
private Consumer<Scene> installationCheck = scene -> {};
private boolean closed, switching;
private final ListChangeListener<Window> windows =
change -> {
while (change.next()) {
if (change.wasRemoved())
for (var window : change.getRemoved()) {
var r = automatic.remove(window);
if (r != null) r.close();
}
if (change.wasAdded())
for (var window : change.getAddedSubList()) inherit(window);
}
};
public ThemeManager() {
requireFx();
for (var theme : List.of(Theme.light(), Theme.dark(), Theme.highContrast()))
themes.put(theme.id(), theme);
Window.getWindows().addListener(windows);
}
public ReadOnlyObjectProperty<Theme> selectedThemeProperty() {
return selected.getReadOnlyProperty();
}
public ReadOnlyObjectProperty<Failure> failureProperty() {
return failure.getReadOnlyProperty();
}
public List<Theme> themes() {
return List.copyOf(themes.values());
}
public void addTheme(Theme theme) {
check();
if (themes.putIfAbsent(theme.id(), theme) != null)
throw new IllegalArgumentException("Duplicate theme ID: " + theme.id());
}
/**
* Optional application CSS qualification; throwing rolls back a detectable installation
* failure.
*/
public void setInstallationCheck(Consumer<Scene> check) {
check();
installationCheck = Objects.requireNonNull(check);
}
public Registration register(Scene scene) {
check();
Objects.requireNonNull(scene);
if (scenes.containsKey(scene))
throw new IllegalArgumentException("Scene already registered");
if (scene.getProperties().containsKey(MANAGER))
throw new IllegalArgumentException("Scene belongs to another theme manager");
preflight(selected.get());
var registration = new Registration(scene);
var original = List.copyOf(scene.getStylesheets());
try {
registration.install(selected.get());
installationCheck.accept(scene);
scenes.put(scene, registration);
scene.getProperties().put(MANAGER, this);
scene.rootProperty().addListener(registration.rootChanged);
for (var window : List.copyOf(Window.getWindows())) inherit(window);
return registration;
} catch (RuntimeException error) {
registration.unmark(scene.getRoot());
if (!registration.ownerBound) scene.getStylesheets().setAll(original);
failure.set(new Failure("Could not theme scene: " + error.getMessage(), error));
throw error;
}
}
public boolean select(String id) {
check();
if (switching) throw new IllegalStateException("Theme switch already in progress");
var theme = themes.get(id);
if (theme == null) {
failure.set(
new Failure("Theme unavailable: " + id + ". Choose a registered theme.", null));
return false;
}
Map<Registration, List<String>> before = new LinkedHashMap<>();
Map<Registration, List<String>> owned = new LinkedHashMap<>();
switching = true;
try {
preflight(theme);
for (var r : scenes.values()) {
if (!r.ownerBound) {
before.put(r, List.copyOf(r.scene.getStylesheets()));
owned.put(r, r.managed);
}
}
for (var r : List.copyOf(scenes.values())) {
r.install(theme);
installationCheck.accept(r.scene);
}
selected.set(theme);
failure.set(null);
return true;
} catch (RuntimeException error) {
for (var entry : before.entrySet()) {
try {
entry.getKey().scene.getStylesheets().setAll(entry.getValue());
entry.getKey().managed = owned.get(entry.getKey());
entry.getKey().scene.getRoot().applyCss();
} catch (RuntimeException rollback) {
error.addSuppressed(rollback);
}
}
failure.set(
new Failure(
"Could not install theme "
+ id
+ "; retained "
+ selected.get().id()
+ ": "
+ error.getMessage(),
error));
return false;
} finally {
switching = false;
}
}
/** Startup fallback is explicit, and retains an explanation even after Light installs. */
public boolean selectSaved(String id) {
if (select(id)) return true;
var problem = failure.get();
if (select("light"))
failure.set(
new Failure(
"Saved theme unavailable; using light. " + problem.message(),
problem.cause()));
return false;
}
/** Link a library-owned floating window without imposing JavaFX window ownership semantics. */
public static void link(Window child, Scene owner) {
requireFx();
child.getProperties().put(OWNER_SCENE, Objects.requireNonNull(owner));
}
/** Copy application/default CSS to another surface without freezing a selected theme there. */
public static List<String> applicationStyles(Scene scene) {
var manager = (ThemeManager) scene.getProperties().get(MANAGER);
if (manager == null) return List.copyOf(scene.getStylesheets());
var reserved = manager.reserved();
return scene.getStylesheets().stream().filter(s -> !reserved.contains(s)).toList();
}
private Set<String> reserved() {
Set<String> urls = new HashSet<>();
themes.values().forEach(t -> urls.addAll(t.stylesheets()));
return urls;
}
private void inherit(Window window) {
if (closed
|| automatic.containsKey(window)
|| window.getScene() == null
|| scenes.containsKey(window.getScene())) return;
Scene owner = (Scene) window.getProperties().get(OWNER_SCENE);
if (owner == null) {
Window parent =
window instanceof PopupWindow p
? p.getOwnerWindow()
: window instanceof Stage s ? s.getOwner() : null;
if (parent != null) owner = parent.getScene();
}
if (owner != null && owner.getProperties().get(MANAGER) == this) {
try {
automatic.put(window, register(window.getScene()));
} catch (RuntimeException error) {
failure.set(
new Failure("Could not theme new window: " + error.getMessage(), error));
}
}
}
private static void preflight(Theme theme) {
for (String url : theme.stylesheets())
try {
var connection = URI.create(url).toURL().openConnection();
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
try (var stream = connection.getInputStream()) {
stream.read();
}
} catch (Exception error) {
throw new IllegalArgumentException(
"Missing or unreadable theme stylesheet: " + url, error);
}
}
public final class Registration implements AutoCloseable {
private final Scene scene;
private final boolean ownerBound;
private List<String> managed = List.of();
private Parent marked;
private boolean addedClass, disposed;
private final ChangeListener<Parent> rootChanged =
(o, old, next) -> {
unmark(old);
mark(next);
next.applyCss();
};
private Registration(Scene scene) {
this.scene = scene;
// Standard JavaFX Dialogs bind this list to their owner. Never edit the bound target.
this.ownerBound =
scene.getRoot() instanceof javafx.scene.control.DialogPane
&& scene.getWindow() instanceof Stage window
&& window.getOwner() instanceof Stage owner
&& owner.getScene() != null
&& scene.getStylesheets().equals(owner.getScene().getStylesheets());
if (ownerBound
&& ((Stage) ((Stage) scene.getWindow()).getOwner())
.getScene()
.getProperties()
.get(MANAGER)
!= ThemeManager.this)
throw new IllegalArgumentException(
"Register a dialog's owner scene before the dialog");
}
private void mark(Parent root) {
marked = root;
addedClass = !root.getStyleClass().contains(SCOPE);
if (addedClass) root.getStyleClass().add(SCOPE);
}
private void unmark(Parent root) {
if (root == marked && addedClass) root.getStyleClass().remove(SCOPE);
}
private void install(Theme theme) {
if (marked == null) mark(scene.getRoot());
if (ownerBound) {
scene.getRoot().applyCss();
return;
}
var next = new ArrayList<>(scene.getStylesheets());
// Reserved bundle URLs copied from an owner are theme-owned, never application
// overrides.
next.removeIf(reserved()::contains);
int index = 0;
while (index < next.size()
&& (next.get(index).endsWith("/docking.css")
|| next.get(index).endsWith("/filters.css"))) index++;
next.addAll(index, theme.stylesheets());
scene.getStylesheets().setAll(next);
managed = theme.stylesheets();
scene.getRoot().applyCss();
}
public void close() {
requireFx();
if (disposed) return;
disposed = true;
scene.rootProperty().removeListener(rootChanged);
if (!ownerBound) scene.getStylesheets().removeAll(managed);
unmark(scene.getRoot());
scenes.remove(scene);
if (scene.getProperties().get(MANAGER) == ThemeManager.this)
scene.getProperties().remove(MANAGER);
}
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the FX application thread");
}
private void check() {
requireFx();
if (closed) throw new IllegalStateException("Theme manager closed");
}
public void close() {
requireFx();
if (closed) return;
closed = true;
Window.getWindows().removeListener(windows);
for (var r : List.copyOf(scenes.values())) r.close();
automatic.clear();
}
}
@@ -0,0 +1,652 @@
package de.neitzel.fx.view;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/**
* Local/external data grid coordinator and paging presentation. Construct and use on the FX thread.
* No query runs until load/refresh or an explicit query change, allowing configuration before first
* load. The application owns the source and executor. Closing releases only this grid's requests
* and rows.
*/
public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private final Table table = new Table();
private final TableResults<K, T> renderer;
private final GridCoordinator<K, T> coordinator;
private final ReadOnlyObjectWrapper<GridCoordinator.State<K, T>> state =
new ReadOnlyObjectWrapper<>();
private final Label status = new Label("Not loaded");
private final Button first = new Button("First"),
previous = new Button("Previous"),
next = new Button("Next"),
last = new Button("Last"),
retry = new Button("Retry"),
refresh = new Button("Refresh");
private final ComboBox<String> pageSize = new ComboBox<>();
private final GridQuery initial;
private final List<ResultColumn> columnDefinitions;
private GridDefinition setupDefinition;
private Map<Integer, java.util.function.UnaryOperator<GridSetup>> setupMigrations = Map.of();
private final ReadOnlyObjectWrapper<List<String>> restorationAdjustments =
new ReadOnlyObjectWrapper<>(List.of());
private final Map<String, FilterColumn> filterColumns = new LinkedHashMap<>();
private FilterEditors filterEditors = FilterEditors.builtIns();
private FilterColumn.Checklist defaultChecklist = FilterColumn.Checklist.DISABLED;
private FilterPopup.Options filterPopupOptions = FilterPopup.Options.defaults();
private FilterPopup filterPopup;
private final ReadOnlyObjectWrapper<RuntimeException> filterDisposalFailure =
new ReadOnlyObjectWrapper<>();
private boolean updating, closed;
private long visibleSourceVersion;
private Alert pendingAlert;
private long alertGeneration;
public DataGrid(
List<ResultColumn> columns,
Function<T, ResultRow> rowFactory,
GridSource<K, T> source) {
requireFx();
columnDefinitions = List.copyOf(columns);
Objects.requireNonNull(source);
initial =
new GridQuery(
List.of(),
List.of(),
new PageRequest.Paged(
0, Math.min(50, source.capabilities().maximumPageSize())));
renderer = table.openResults(columns, rowFactory);
coordinator =
new GridCoordinator<>(
source,
Platform::runLater,
this::changed,
result -> renderer.show(result.rows()));
coordinator.setConfirmation(this::confirmAll);
renderer.setOnSortRequest(
id -> {
var q = query();
SortKey.Direction direction =
q.sort().size() == 1
&& q.sort().getFirst().columnId().equals(id)
&& q.sort().getFirst().direction()
== SortKey.Direction.ASCENDING
? SortKey.Direction.DESCENDING
: SortKey.Direction.ASCENDING;
setSort(new SortKey(id, direction));
});
first.setOnAction(e -> first());
previous.setOnAction(e -> previous());
next.setOnAction(e -> next());
last.setOnAction(e -> last());
retry.setOnAction(e -> coordinator.retry());
refresh.setOnAction(e -> refresh());
pageSize.setOnAction(
e -> {
if (updating || pageSize.getValue() == null) return;
setPageRequest(
pageSize.getValue().equals("All")
? new PageRequest.All()
: new PageRequest.Paged(
0, Integer.parseInt(pageSize.getValue())));
});
status.setWrapText(true);
status.getStyleClass().add("data-grid-status");
HBox controls =
new HBox(
8,
first,
previous,
next,
last,
new Label("Rows"),
pageSize,
refresh,
retry);
controls.getStyleClass().add("data-grid-paging");
getStyleClass().add("data-grid");
setSpacing(8);
getChildren().addAll(table, controls, status);
VBox.setVgrow(table, Priority.ALWAYS);
state.set(coordinator.state());
updateControls(coordinator.state());
}
public ReadOnlyObjectProperty<GridCoordinator.State<K, T>> stateProperty() {
return state.getReadOnlyProperty();
}
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
return renderer.selectedKeyProperty();
}
public ReadOnlyObjectProperty<T> selectedElementProperty() {
return renderer.selectedElementProperty();
}
public void select(K key) {
check();
renderer.select(key);
}
public void confirmedDeleted(K key) {
check();
if (Objects.equals(key, selectedKeyProperty().get())) renderer.select(null);
refresh();
}
public void setEditGuard(Function<GridQuery, CompletionStage<Boolean>> guard) {
check();
coordinator.setGuard(guard);
}
public void setAllConfirmation(BiFunction<GridQuery, Long, CompletionStage<Boolean>> handler) {
check();
coordinator.setConfirmation(handler);
}
public void setAllWarningThreshold(long count) {
check();
coordinator.setAllWarningThreshold(count);
}
public void setColumnOrder(List<String> ids) {
check();
closeFilter();
coordinator.cancelRestore();
renderer.setColumnOrder(ids);
}
public double setColumnWidth(String id, ColumnWidth width) {
check();
closeFilter();
coordinator.cancelRestore();
return renderer.setColumnWidth(id, width);
}
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
return renderer.disposalFailureProperty();
}
public void load() {
check();
coordinator.request(query());
}
public void refresh() {
load();
}
public void retry() {
check();
coordinator.retry();
}
public void setSource(GridSource<K, T> source) {
check();
closeFilter();
var q = query();
coordinator.request(source, new GridQuery(q.filters(), q.sort(), firstPage(q.page())));
}
public void setFilters(List<FilterCondition> filters) {
check();
coordinator.validateFilters(filters);
var q = query();
coordinator.request(new GridQuery(filters, q.sort(), firstPage(q.page())));
}
/**
* Definition type IDs are stable schema identifiers, not display labels or Java class names.
*/
public void configureSetups(
String id,
int version,
Map<String, String> types,
Map<Integer, java.util.function.UnaryOperator<GridSetup>> migrations) {
check();
if (!types.keySet().equals(new HashSet<>(renderer.columnOrder())))
throw new IllegalArgumentException("Declare a type for every column");
GridDefinition definition =
new GridDefinition(
id,
version,
columnDefinitions.stream()
.map(
c ->
new GridDefinition.Column(
c.id(),
types.get(c.id()),
c.defaultWidth(),
c.minimumWidth(),
c.maximumWidth(),
c.fixedPosition()))
.toList());
Map<Integer, java.util.function.UnaryOperator<GridSetup>> next = Map.copyOf(migrations);
if (coordinator.isRestoring())
throw new IllegalStateException("Cannot change definition during restoration");
setupDefinition = definition;
setupMigrations = next;
}
/** Snapshots committed settings only; never accepts or cancels an open draft. */
public GridSetup snapshotSetup() {
check();
if (setupDefinition == null)
throw new IllegalStateException("Configure the grid definition before saving");
var committed =
coordinator.state().displayed() == null ? initial : coordinator.state().displayed();
Map<String, String> types = new HashMap<>();
setupDefinition.columns().forEach(c -> types.put(c.id(), c.type()));
return new GridSetup(
1,
setupDefinition.id(),
setupDefinition.version(),
renderer.columnOrder().stream()
.map(
id ->
new GridSetup.ColumnState(
id, types.get(id), renderer.columnWidths().get(id)))
.toList(),
committed.sort(),
committed.filters(),
firstPage(committed.page()));
}
public ReadOnlyObjectProperty<List<String>> restorationAdjustmentsProperty() {
return restorationAdjustments.getReadOnlyProperty();
}
/** Decode through a supplier so parse errors receive the same visible, query-free rollback. */
public void restoreSetup(java.util.function.Supplier<GridSetup> decode) {
check();
try {
restoreSetup(Objects.requireNonNull(decode.get()));
} catch (RuntimeException error) {
coordinator.rejectSetup(error);
}
}
public void restoreSetup(GridSetup saved) {
check();
try {
if (setupDefinition == null)
throw new IllegalStateException("Configure the grid definition before restoring");
var prepared =
setupDefinition.prepare(
saved,
setupMigrations,
coordinator.capabilities(),
condition -> coordinator.validateFilters(List.of(condition)));
var setup = prepared.setup();
Map<String, ColumnWidth> widths = new LinkedHashMap<>();
setup.columns().forEach(c -> widths.put(c.id(), c.width()));
coordinator.restoreSetup(
new GridQuery(setup.filters(), setup.sort(), setup.page()),
this::closeFilter,
result -> {
renderer.show(
result.rows(),
setup.columns().stream().map(GridSetup.ColumnState::id).toList(),
widths);
restorationAdjustments.set(prepared.adjustments());
});
} catch (RuntimeException error) {
coordinator.rejectSetup(error);
}
}
public void setFilterEditors(FilterEditors editors) {
check();
Objects.requireNonNull(editors);
filterColumns.values().forEach(c -> editors.require(c.editorId()));
closeFilter();
filterEditors = editors;
}
public void setDefaultChecklist(FilterColumn.Checklist mode) {
check();
Objects.requireNonNull(mode);
if (mode == FilterColumn.Checklist.INHERIT)
throw new IllegalArgumentException("Grid default cannot inherit");
for (var entry : filterColumns.values())
if (entry.checklist() == FilterColumn.Checklist.INHERIT
&& mode != FilterColumn.Checklist.DISABLED
&& entry.candidates() == null)
throw new IllegalArgumentException(
"Each enabled column needs a candidate provider");
closeFilter();
defaultChecklist = mode;
}
public void setFilterPopupOptions(FilterPopup.Options options) {
check();
closeFilter();
filterPopupOptions = Objects.requireNonNull(options);
}
public void configureFilter(String column, FilterColumn configuration) {
check();
Objects.requireNonNull(configuration);
if (!renderer.columnOrder().contains(column))
throw new IllegalArgumentException("Unknown filter column: " + column);
filterEditors.require(configuration.editorId());
if (configuration.checklist() == FilterColumn.Checklist.INHERIT
&& defaultChecklist != FilterColumn.Checklist.DISABLED
&& configuration.candidates() == null)
throw new IllegalArgumentException("Enabled checklist requires a provider");
closeFilter();
filterColumns.put(column, configuration);
renderer.setFilterActions(filterColumns.keySet(), this::openFilter);
}
private void openFilter(String column, javafx.scene.Node opener) {
check();
if (filterPopup != null && filterPopup.isOpen()) {
filterPopup.outside();
return;
}
var config = filterColumns.get(column);
var registration = filterEditors.require(config.editorId());
var current = query().filters();
var committed =
current.stream().filter(f -> f.columnId().equals(column)).findFirst().orElse(null);
var others = current.stream().filter(f -> !f.columnId().equals(column)).toList();
FilterEditor editor = null;
try {
editor =
registration
.factory()
.apply(
new FilterEditorContext(
column,
config,
committed,
others,
config.checklist() == FilterColumn.Checklist.INHERIT
? defaultChecklist
: config.checklist()));
filterPopup =
new FilterPopup(
opener,
editor,
filterPopupOptions,
condition -> {
registration.validate(condition);
if (condition != null) {
registration.requireEvaluation(coordinator.filterExecutionId());
if (!condition.columnId().equals(column))
throw new IllegalArgumentException(
"Editor returned another column");
coordinator.validateFilters(List.of(condition));
}
},
condition -> {
// Preserve current other-column state, even if it changed while
// this editor was open.
List<FilterCondition> nextFilters =
new ArrayList<>(
query().filters().stream()
.filter(f -> !f.columnId().equals(column))
.toList());
if (condition != null) nextFilters.add(condition);
setFilters(nextFilters);
});
filterPopup
.disposalFailureProperty()
.addListener((o, old, failure) -> filterDisposalFailure.set(failure));
filterPopup.show();
} catch (RuntimeException error) {
if (editor != null) editor.close();
status.setText("Cannot open filter: " + error.getMessage());
}
}
public ReadOnlyObjectProperty<RuntimeException> filterDisposalFailureProperty() {
return filterDisposalFailure.getReadOnlyProperty();
}
private void closeFilter() {
if (filterPopup != null) {
filterPopup.close();
filterPopup = null;
}
}
public void setSort(SortKey sort) {
check();
var q = query();
coordinator.request(
new GridQuery(
q.filters(),
sort == null ? List.of() : List.of(sort),
firstPage(q.page())));
}
public void setPageSize(int size) {
setPageRequest(new PageRequest.Paged(0, size));
}
public void showAll() {
setPageRequest(new PageRequest.All());
}
public void setPageRequest(PageRequest page) {
check();
var q = query();
coordinator.request(new GridQuery(q.filters(), q.sort(), page));
}
public void first() {
check();
if (query().page() instanceof PageRequest.Paged p)
setPageRequest(new PageRequest.Paged(0, p.pageSize()));
}
public void previous() {
check();
if (query().page() instanceof PageRequest.Paged p && p.pageIndex() > 0)
setPageRequest(new PageRequest.Paged(p.pageIndex() - 1, p.pageSize()));
}
public void next() {
check();
if (query().page() instanceof PageRequest.Paged p) {
var s = coordinator.state();
if (s.phase() == GridCoordinator.Phase.READY && !s.result().hasNext()) return;
setPageRequest(new PageRequest.Paged(Math.incrementExact(p.pageIndex()), p.pageSize()));
}
}
public void last() {
check();
var s = coordinator.state();
if (s.phase() == GridCoordinator.Phase.READY
&& s.result().total().isPresent()
&& query().page() instanceof PageRequest.Paged p) {
long count = s.result().total().getAsLong();
if (count > 0)
setPageRequest(new PageRequest.Paged((count - 1) / p.pageSize(), p.pageSize()));
}
}
private GridQuery query() {
if (coordinator.isRestoring())
return coordinator.state().displayed() == null
? initial
: coordinator.state().displayed();
return coordinator.state().requested() == null ? initial : coordinator.state().requested();
}
private static PageRequest firstPage(PageRequest page) {
return page instanceof PageRequest.Paged p ? new PageRequest.Paged(0, p.pageSize()) : page;
}
private void changed(GridCoordinator.State<K, T> value) {
if (pendingAlert != null && value.generation() != alertGeneration) {
pendingAlert.close();
pendingAlert = null;
}
if (!closed) {
pseudoClassStateChanged(
javafx.css.PseudoClass.getPseudoClass("loading"),
value.phase() == GridCoordinator.Phase.LOADING);
pseudoClassStateChanged(
javafx.css.PseudoClass.getPseudoClass("error"),
value.phase() == GridCoordinator.Phase.ERROR);
if (value.displayed() != null)
renderer.setFilteredColumns(
value.displayed().filters().stream()
.map(FilterCondition::columnId)
.collect(java.util.stream.Collectors.toSet()));
if (visibleSourceVersion != value.sourceVersion()) {
visibleSourceVersion = value.sourceVersion();
renderer.select(null);
}
renderer.setRowsInteractive(value.phase() == GridCoordinator.Phase.READY);
updateControls(value);
}
state.set(value);
}
private void updateControls(GridCoordinator.State<K, T> s) {
GridQuery requested = s.requested() == null ? initial : s.requested();
boolean ready = s.phase() == GridCoordinator.Phase.READY;
boolean empty = ready && s.result().rows().isEmpty();
long index = requested.page() instanceof PageRequest.Paged p ? p.pageIndex() : 0;
boolean paged = requested.page() instanceof PageRequest.Paged;
first.setDisable(!paged || index == 0 || empty);
previous.setDisable(first.isDisabled());
next.setDisable(!paged || empty || (ready && !s.result().hasNext()));
last.setDisable(
!paged || empty || !ready || s.result().total().isEmpty() || !s.result().hasNext());
retry.setDisable(s.phase() != GridCoordinator.Phase.ERROR);
updating = true;
try {
int max = coordinator.capabilities().maximumPageSize();
List<String> sizes = new ArrayList<>();
for (int n : new int[] {25, 50, 100, 250}) if (n <= max) sizes.add(Integer.toString(n));
if (requested.page() instanceof PageRequest.Paged p
&& !sizes.contains(Integer.toString(p.pageSize())))
sizes.add(Integer.toString(p.pageSize()));
if (coordinator.capabilities().all()) sizes.add("All");
pageSize.getItems().setAll(sizes);
pageSize.setValue(
requested.page() instanceof PageRequest.All
? "All"
: Integer.toString(((PageRequest.Paged) requested.page()).pageSize()));
} finally {
updating = false;
}
String shown =
s.result() == null
? ""
: " Displayed "
+ pageLabel(s.displayed().page())
+ " ("
+ s.result().rows().size()
+ " rows).";
String message =
switch (s.phase()) {
case IDLE -> "Not loaded";
case GUARD ->
"Waiting for edit approval. Requested "
+ pageLabel(requested.page())
+ "."
+ shown;
case LOADING ->
"Loading "
+ pageLabel(requested.page())
+ ". Previous rows are outdated."
+ shown;
case CONFIRMATION ->
"Waiting for permission to load all matching rows." + shown;
case ERROR ->
"Query failed: "
+ String.valueOf(s.error().getMessage())
+ ". Retry is available; previous rows are outdated."
+ shown;
case CLOSED -> "Closed";
case READY -> {
if (empty) yield "No results";
if (s.result().total().isPresent()) {
long total = s.result().total().getAsLong();
yield requested.page() instanceof PageRequest.Paged p
? "Page "
+ (p.pageIndex() + 1)
+ " of "
+ (total == 0 ? 0 : 1 + (total - 1) / p.pageSize())
+ " — "
+ total
+ " matching rows"
: "All " + total + " matching rows";
}
yield pageLabel(requested.page()) + " — total unknown";
}
};
status.setText(message);
}
private static String pageLabel(PageRequest page) {
return page instanceof PageRequest.Paged p ? "page " + (p.pageIndex() + 1) : "all rows";
}
private CompletionStage<Boolean> confirmAll(GridQuery query, long count) {
CompletableFuture<Boolean> answer = new CompletableFuture<>();
ButtonType proceed = new ButtonType("Continue", ButtonBar.ButtonData.OK_DONE);
Alert alert =
new Alert(
Alert.AlertType.CONFIRMATION,
"Load all "
+ count
+ " matching rows? This may use substantial memory and reduce"
+ " responsiveness.",
proceed,
ButtonType.CANCEL);
alert.setTitle("Load all rows");
alert.setHeaderText("Paging will be disabled");
if (getScene() != null && getScene().getWindow() != null)
alert.initOwner(getScene().getWindow());
pendingAlert = alert;
alertGeneration = coordinator.state().generation();
alert.setOnHidden(
e -> {
if (pendingAlert == alert) pendingAlert = null;
answer.complete(alert.getResult() == proceed);
});
alert.show();
return answer;
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the JavaFX application thread");
}
private void check() {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
}
public void close() {
requireFx();
if (closed) return;
closed = true;
closeFilter();
coordinator.close();
if (pendingAlert != null) {
pendingAlert.close();
pendingAlert = null;
}
renderer.close();
getChildren().clear();
}
}
@@ -6,38 +6,42 @@ import javafx.scene.control.Label;
/**
* Shows each newly added {@link Message} in a dialog when the developer asks.
* <p>
* The library shows nothing until {@link #showNewMessages(ViewModel)} is called. An in-place
*
* <p>The library shows nothing until {@link #showNewMessages(ViewModel)} is called. An in-place
* update of an existing binding failure is not a new Message, so it does not open another dialog.
*/
public final class MessagePopup {
/**
* Prevents instantiation.
*/
private MessagePopup() {
}
/** Prevents instantiation. */
private MessagePopup() {}
/**
* Shows each Message added to {@code viewModel} after this call in a dialog.
* <p>
* The dialog is shown with {@link Dialog#show()}, so the caller is not blocked. Messages
*
* <p>The dialog is shown with {@link Dialog#show()}, so the caller is not blocked. Messages
* already on the ViewModel stay where they are. A later in-place update of a binding failure
* does not open another dialog.
*
* @param viewModel the ViewModel whose new Messages should be shown
*/
public static void showNewMessages(ViewModel viewModel) {
viewModel.whenMessageAdded(MessagePopup::show);
viewModel.whenMessageAdded(message -> show(message, null));
}
/**
* Opens a dialog whose content is the Message text.
* Shows new messages in owned dialogs, allowing theme inheritance from the owner scene.
*
* @param message the notice to show
* @param viewModel the ViewModel whose new Messages should be shown
* @param owner the application window that owns the dialogs
*/
private static void show(Message message) {
public static void showNewMessages(ViewModel viewModel, javafx.stage.Window owner) {
java.util.Objects.requireNonNull(owner);
viewModel.whenMessageAdded(message -> show(message, owner));
}
private static void show(Message message, javafx.stage.Window owner) {
Dialog<Void> dialog = new Dialog<>();
if (owner != null) dialog.initOwner(owner);
dialog.setHeaderText(null);
dialog.getDialogPane().setContent(new Label(message.getText()));
dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
@@ -0,0 +1,24 @@
package de.neitzel.fx.view;
/** Immutable result-column definition. fixedPosition is zero-based, or -1 for movable. */
public record ResultColumn(
String id,
String header,
double defaultWidth,
double minimumWidth,
double maximumWidth,
int fixedPosition) {
public ResultColumn {
if (id == null || id.isBlank() || header == null)
throw new IllegalArgumentException("Invalid column identity/header");
if (!Double.isFinite(minimumWidth)
|| !Double.isFinite(maximumWidth)
|| minimumWidth <= 0
|| maximumWidth < minimumWidth
|| !Double.isFinite(defaultWidth)
|| defaultWidth < minimumWidth
|| defaultWidth > maximumWidth
|| fixedPosition < -1)
throw new IllegalArgumentException("Invalid column width/position");
}
}
@@ -0,0 +1,19 @@
package de.neitzel.fx.view;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import java.util.Map;
import java.util.Objects;
/**
* A freshly bound row with explicit direct-child field mapping and application-owned cleanup.
* Unmapped children are trailing action controls. A factory must return fresh nodes for every call.
*/
public record ResultRow(HBox root, Map<String, Region> fields, Runnable dispose) {
public ResultRow {
Objects.requireNonNull(root);
fields = Map.copyOf(fields);
Objects.requireNonNull(dispose);
}
}
@@ -228,6 +228,27 @@ public class Table extends VBox {
*/
private Class<?> rowType;
/** True once the explicit queried-result rendering path has been selected. */
private boolean resultMode;
/**
* Opens the opt-in queried-result renderer on a fresh Table. Existing FXML/collection behavior
* is unchanged. This must be called on the FX thread before legacy ViewLoader initialization.
* The returned renderer owns rows until closed; its factory supplies mapped, already-bound nodes.
*/
public <K, T> TableResults<K, T> openResults(List<ResultColumn> definitions,
java.util.function.Function<T, ResultRow> factory) {
if (!javafx.application.Platform.isFxApplicationThread()) {
throw new IllegalStateException("Use the JavaFX application thread");
}
if (opened || resultMode) {
throw new IllegalStateException("Table is already open");
}
TableResults<K, T> renderer = new TableResults<>(header, body, List.copyOf(definitions), factory);
resultMode = true;
return renderer;
}
/**
* Creates a Table and prepares its header, scrolling body, and popup.
*/
@@ -327,6 +348,9 @@ public class Table extends VBox {
* @param context the container that creates each Row
*/
void open(Object viewModel, ApplicationContext context) {
if (resultMode) {
return;
}
if (opened) {
return;
}
@@ -0,0 +1,399 @@
package de.neitzel.fx.view;
import de.neitzel.grid.ColumnWidth;
import de.neitzel.grid.GridRow;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.shape.SVGPath;
import java.util.*;
import java.util.function.Function;
/**
* Opt-in presentation of already queried rows. All operations run on the FX thread. This object
* never queries, sorts, filters, or rebinds models. The future grid coordinator owns those
* decisions. Closing releases rows; the Table remains in result mode and cannot be reopened as a
* legacy Table.
*/
public final class TableResults<K, T> implements AutoCloseable {
private final HBox header;
private final VBox body;
private final Function<T, ResultRow> factory;
private final Map<String, ResultColumn> definitions = new LinkedHashMap<>();
private final Map<String, ColumnWidth> widths = new LinkedHashMap<>();
private List<String> order;
private List<Entry<K, T>> entries = List.of();
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
new ReadOnlyObjectWrapper<>();
private boolean closed;
private boolean rowsInteractive = true;
private Set<String> filterColumns = Set.of();
private Set<String> filteredColumns = Set.of();
private java.util.function.BiConsumer<String, Node> filterRequest = (id, node) -> {};
private java.util.function.Consumer<String> sortRequest = id -> {};
private record Entry<K, T>(GridRow<K, T> row, ResultRow view, EventHandler<MouseEvent> click) {}
TableResults(
HBox header, VBox body, List<ResultColumn> columns, Function<T, ResultRow> factory) {
requireFx();
this.header = header;
this.body = body;
this.factory = Objects.requireNonNull(factory);
if (columns.isEmpty())
throw new IllegalArgumentException("At least one column is required");
for (var c : columns) {
if (definitions.putIfAbsent(c.id(), c) != null)
throw new IllegalArgumentException("Duplicate column ID");
widths.put(c.id(), new ColumnWidth.Default());
}
order = List.copyOf(definitions.keySet());
validateOrder(order);
drawHeader();
body.setOnMouseClicked(
e -> {
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
});
}
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
return selectedKey.getReadOnlyProperty();
}
public ReadOnlyObjectProperty<T> selectedElementProperty() {
return selectedElement.getReadOnlyProperty();
}
/** Cleanup failures are exposed separately: they do not roll back an already published page. */
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
return disposalFailure.getReadOnlyProperty();
}
public List<String> columnOrder() {
return order;
}
public Map<String, ColumnWidth> columnWidths() {
return Map.copyOf(widths);
}
/** Marks retained rows unavailable without disabling header/query controls. */
public void setRowsInteractive(boolean interactive) {
checkOpen();
rowsInteractive = interactive;
body.setDisable(!interactive);
markSelection();
}
/** Header requests are delegated to the coordinator, never applied locally. */
public void setOnSortRequest(java.util.function.Consumer<String> handler) {
checkOpen();
sortRequest = Objects.requireNonNull(handler);
}
/** Opt-in filter actions; clicking the icon never issues a sort request. */
public void setFilterActions(
Set<String> columns, java.util.function.BiConsumer<String, Node> handler) {
checkOpen();
if (!definitions.keySet().containsAll(columns))
throw new IllegalArgumentException("Unknown filter column");
filterColumns = Set.copyOf(columns);
filterRequest = Objects.requireNonNull(handler);
drawHeader();
}
/**
* Published filter state; updates existing header controls without recreating an open editor.
*/
public void setFilteredColumns(Set<String> ids) {
checkOpen();
if (filteredColumns.equals(ids)) return;
filteredColumns = Set.copyOf(ids);
for (Node cell : header.getChildren())
if (cell instanceof HBox box)
for (Node child : box.getChildren())
if (child instanceof Button button
&& button.getStyleClass().contains("filter-button"))
markFilter(button, (String) cell.getUserData());
}
private void markFilter(Button button, String id) {
boolean active = filteredColumns.contains(id);
button.pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("filtered"), active);
button.setText(active ? "•" : "");
button.setAccessibleText(
"Filter " + definitions.get(id).header() + (active ? " (active)" : ""));
button.setTooltip(
new Tooltip(
"Filter " + definitions.get(id).header() + (active ? " — active" : "")));
}
/** Retains an off-page key while exposing no loaded selected element. */
public void select(K key) {
checkOpen();
selectedKey.set(key);
markSelection();
}
/**
* Stages fresh rows before replacing the visible page; failed construction preserves the old
* page.
*/
public void show(List<GridRow<K, T>> result) {
show(result, order, widths);
}
/** Stages both fresh rows and complete layout, publishing neither on preparation failure. */
public void show(
List<GridRow<K, T>> result,
List<String> nextOrder,
Map<String, ColumnWidth> nextWidths) {
checkOpen();
nextOrder = List.copyOf(nextOrder);
validateOrder(nextOrder);
nextWidths = Map.copyOf(nextWidths);
if (!nextWidths.keySet().equals(definitions.keySet()))
throw new IllegalArgumentException("Width mapping must match columns");
Map<String, ColumnWidth> preparedWidths = new LinkedHashMap<>();
for (var c : definitions.values()) {
var width = nextWidths.get(c.id());
preparedWidths.put(
c.id(),
width instanceof ColumnWidth.Explicit e
? new ColumnWidth.Explicit(
Math.clamp(e.value(), c.minimumWidth(), c.maximumWidth()))
: width);
}
var nextHeader = headerNodes(nextOrder, preparedWidths);
result = List.copyOf(result);
Set<K> keys = new HashSet<>();
for (var row : result)
if (!keys.add(row.key())) throw new IllegalArgumentException("Duplicate row key");
List<Entry<K, T>> next = new ArrayList<>();
Set<Node> roots = Collections.newSetFromMap(new IdentityHashMap<>());
try {
for (var row : result) {
ResultRow view =
Objects.requireNonNull(
factory.apply(row.model()), "Row factory returned null");
// Never dispose a live row accidentally returned by a faulty factory.
if (view.root().getParent() != null || !roots.add(view.root()))
throw new IllegalArgumentException(
"Row factory must create detached fresh rows");
EventHandler<MouseEvent> click =
e -> {
if (e.getButton() == MouseButton.PRIMARY) select(row.key());
};
next.add(new Entry<>(row, view, click));
validateRow(view);
view.root().getStyleClass().add("result-row");
layoutRow(view, nextOrder, preparedWidths);
view.root().addEventHandler(MouseEvent.MOUSE_CLICKED, click);
}
} catch (RuntimeException failure) {
release(next);
throw failure;
}
var old = entries;
entries = List.copyOf(next);
order = nextOrder;
widths.clear();
widths.putAll(preparedWidths);
header.getChildren().setAll(nextHeader);
body.getChildren().setAll(entries.stream().map(e -> e.view().root()).toList());
markSelection();
release(old);
}
/** Changes header and mapped row order atomically after validating fixed positions. */
public void setColumnOrder(List<String> ids) {
checkOpen();
ids = List.copyOf(ids);
validateOrder(ids);
order = ids;
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
}
/**
* Returns the applied width; explicit widths are clamped to current limits, preserving
* default-vs-explicit intent.
*/
public double setColumnWidth(String id, ColumnWidth width) {
checkOpen();
ResultColumn c = Objects.requireNonNull(definitions.get(id), "Unknown column");
Objects.requireNonNull(width);
double applied =
width instanceof ColumnWidth.Explicit e
? Math.clamp(e.value(), c.minimumWidth(), c.maximumWidth())
: c.defaultWidth();
widths.put(
id,
width instanceof ColumnWidth.Explicit ? new ColumnWidth.Explicit(applied) : width);
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
return applied;
}
private void validateOrder(List<String> ids) {
if (ids.size() != definitions.size() || !new HashSet<>(ids).equals(definitions.keySet()))
throw new IllegalArgumentException("Order must contain each column exactly once");
for (int i = 0; i < ids.size(); i++) {
int fixed = definitions.get(ids.get(i)).fixedPosition();
if (fixed >= 0 && fixed != i)
throw new IllegalArgumentException("Fixed column displaced");
}
}
private void validateRow(ResultRow view) {
if (!view.root().getPadding().equals(javafx.geometry.Insets.EMPTY))
throw new IllegalArgumentException(
"Result row padding must be zero; put padding inside mapped fields");
if (!view.fields().keySet().equals(definitions.keySet()))
throw new IllegalArgumentException("Row mapping must match columns");
Set<Node> nodes = Collections.newSetFromMap(new IdentityHashMap<>());
for (var field : view.fields().values())
if (!nodes.add(field) || field.getParent() != view.root())
throw new IllegalArgumentException(
"Mapped fields must be distinct direct children");
}
private double width(String id) {
return width(id, widths);
}
private double width(String id, Map<String, ColumnWidth> sizes) {
return sizes.get(id) instanceof ColumnWidth.Explicit e
? e.value()
: definitions.get(id).defaultWidth();
}
private void drawHeader() {
header.getChildren().setAll(headerNodes(order, widths));
}
private List<Node> headerNodes(List<String> ordering, Map<String, ColumnWidth> sizes) {
List<Node> nodes = new ArrayList<>();
for (String id : ordering) {
Label label = new Label(definitions.get(id).header());
label.getStyleClass().add("column-header");
HBox cell = new HBox(label);
cell.getStyleClass().add("column-cell");
cell.setUserData(id);
cell.setOnMouseClicked(
event -> {
if (event.getButton() == MouseButton.PRIMARY) sortRequest.accept(id);
});
if (filterColumns.contains(id)) {
SVGPath icon = new SVGPath();
icon.setContent("M0 0 H14 L9 6 V12 L5 14 V6 Z");
icon.getStyleClass().add("filter-icon");
Button button = new Button("", icon);
button.getStyleClass().add("filter-button");
button.setAccessibleText("Filter " + definitions.get(id).header());
button.setTooltip(new Tooltip("Filter " + definitions.get(id).header()));
markFilter(button, id);
button.setOnAction(e -> filterRequest.accept(id, button));
button.addEventHandler(MouseEvent.MOUSE_CLICKED, MouseEvent::consume);
cell.getChildren().add(button);
}
size(cell, width(id, sizes));
nodes.add(cell);
}
return nodes;
}
private static void size(Region region, double width) {
region.setMinWidth(width);
region.setPrefWidth(width);
region.setMaxWidth(width);
}
private void layoutRow(ResultRow view) {
layoutRow(view, order, widths);
}
private void layoutRow(ResultRow view, List<String> ordering, Map<String, ColumnWidth> sizes) {
Set<Region> fields = Collections.newSetFromMap(new IdentityHashMap<>());
fields.addAll(view.fields().values());
List<Node> children = new ArrayList<>();
for (String id : ordering) {
Region field = view.fields().get(id);
size(field, width(id, sizes));
children.add(field);
}
for (Node child : view.root().getChildren())
if (!fields.contains(child)) children.add(child);
view.root().setSpacing(0);
view.root().getChildren().setAll(children);
}
private void markSelection() {
T loaded = null;
for (var e : entries) {
boolean selected = Objects.equals(selectedKey.get(), e.row().key());
e.view()
.root()
.pseudoClassStateChanged(
javafx.css.PseudoClass.getPseudoClass("selected"), selected);
e.view().root().getStyleClass().remove("selected");
if (selected) {
e.view().root().getStyleClass().add("selected");
loaded = e.row().model();
}
}
selectedElement.set(rowsInteractive ? loaded : null);
}
private void release(List<Entry<K, T>> retired) {
RuntimeException aggregate = null;
for (var e : retired) {
e.view().root().removeEventHandler(MouseEvent.MOUSE_CLICKED, e.click());
try {
e.view().dispose().run();
} catch (RuntimeException failure) {
if (aggregate == null) aggregate = new IllegalStateException("Row disposal failed");
aggregate.addSuppressed(failure);
}
}
if (aggregate != null) disposalFailure.set(aggregate);
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the JavaFX application thread");
}
private void checkOpen() {
requireFx();
if (closed) throw new IllegalStateException("Result renderer is closed");
}
@Override
public void close() {
requireFx();
if (closed) return;
closed = true;
var old = entries;
entries = List.of();
body.getChildren().clear();
header.getChildren().clear();
body.setOnMouseClicked(null);
selectedKey.set(null);
selectedElement.set(null);
release(old);
}
}
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.grid.filter.BuiltInFilterEditor" spacing="8" prefWidth="330" styleClass="filter-editor">
<Label text="Filter mode" labelFor="$mode"/>
<ComboBox fx:id="mode" maxWidth="Infinity"/>
<VBox fx:id="comparison" spacing="8">
<Label text="Comparison" labelFor="$operator"/>
<ComboBox fx:id="operator" maxWidth="Infinity"/>
<TextField fx:id="operand" promptText="Value" accessibleText="Filter value"/>
<TextField fx:id="upper" promptText="Inclusive upper value" accessibleText="Inclusive upper value"/>
<CheckBox fx:id="caseSensitive" text="Case sensitive"/>
</VBox>
<VBox fx:id="checklistPane" spacing="8">
<Label fx:id="scope" wrapText="true"/>
<TextField fx:id="search" promptText="Search candidates" accessibleText="Search candidates"/>
<HBox spacing="8"><Button fx:id="selectShown" text="Select all shown"/><Button fx:id="clearShown" text="Uncheck shown"/></HBox>
<ScrollPane fitToWidth="true" prefViewportHeight="140"><content><VBox fx:id="candidates" spacing="4"/></content></ScrollPane>
<Label fx:id="selectionSummary" wrapText="true"/>
<Label fx:id="lookupMessage" wrapText="true"/>
<HBox spacing="8"><Button fx:id="more" text="More"/><Button fx:id="retry" text="Retry lookup"/></HBox>
</VBox>
<Label fx:id="validation" wrapText="true" styleClass="filter-validation"/>
</VBox>
@@ -0,0 +1,9 @@
.filter-popup {
-fx-padding: 14;
-fx-background-color: -fx-control-inner-background;
-fx-border-color: -fx-box-border;
-fx-border-width: 1;
}
.filter-validation { -fx-font-weight: bold; }
.filter-button { -fx-padding: 4; }
.filter-icon { -fx-fill: -fx-text-base-color; }
@@ -0,0 +1,13 @@
.neitzel-theme {
-nl-surface: #151b24;
-nl-raised: #242e3d;
-nl-text: #f2f5fa;
-nl-muted: #c0cad8;
-nl-selection: #385e87;
-nl-selection-text: #ffffff;
-nl-focus: #8dccff;
-nl-error: #ffb4b4;
-nl-warning: #ffe09a;
-nl-border: #91a4bc;
-nl-hover: #34445b;
}
@@ -0,0 +1,13 @@
.neitzel-theme {
-nl-surface: #080a0d;
-nl-raised: #111820;
-nl-text: #ffffff;
-nl-muted: #e4eaf2;
-nl-selection: #143e68;
-nl-selection-text: #ffffff;
-nl-focus: #ffdf00;
-nl-error: #ffc2bd;
-nl-warning: #ffe09a;
-nl-border: #e4eaf2;
-nl-hover: #24374b;
}
@@ -0,0 +1,13 @@
.neitzel-theme {
-nl-surface: #ffffff;
-nl-raised: #eef2f7;
-nl-text: #172033;
-nl-muted: #4b5563;
-nl-selection: #164e8a;
-nl-selection-text: #ffffff;
-nl-focus: #005fcc;
-nl-error: #a61b1b;
-nl-warning: #704300;
-nl-border: #65758b;
-nl-hover: #dce7f5;
}
@@ -0,0 +1,94 @@
/* Opt-in scope. Geometry is identical in all bundled palettes. */
.neitzel-theme, .neitzel-theme .root {
-fx-font-family: "System";
-fx-font-size: 13px;
-fx-base: -nl-raised;
-fx-background: -nl-surface;
-fx-control-inner-background: -nl-surface;
-fx-control-inner-background-alt: -nl-raised;
-fx-text-base-color: -nl-text;
-fx-text-background-color: -nl-text;
-fx-text-inner-color: -nl-text;
-fx-accent: -nl-selection;
-fx-selection-bar: -nl-selection;
-fx-selection-bar-non-focused: -nl-selection;
-fx-selection-bar-text: -nl-selection-text;
-fx-focus-color: -nl-focus;
-fx-faint-focus-color: transparent;
-fx-box-border: -nl-border;
-fx-inner-border: -nl-raised;
-fx-mark-color: -nl-text;
-fx-background-color: -nl-surface;
}
.neitzel-theme .label, .neitzel-theme .check-box, .neitzel-theme .radio-button { -fx-text-fill: -nl-text; }
.neitzel-theme .button, .neitzel-theme .toggle-button, .neitzel-theme .combo-box-base, .neitzel-theme .menu-button {
-fx-background-color: -nl-raised; -fx-text-fill: -nl-text;
-fx-border-color: -nl-border; -fx-border-width: 2; -fx-background-radius: 3; -fx-border-radius: 3;
-fx-padding: 4 8;
}
.neitzel-theme .button:hover, .neitzel-theme .toggle-button:hover, .neitzel-theme .combo-box-base:hover { -fx-background-color: -nl-hover; }
.neitzel-theme .button:focused, .neitzel-theme .toggle-button:focused, .neitzel-theme .combo-box-base:focused,
.neitzel-theme .text-input:focused, .neitzel-theme .table-view:focused, .neitzel-theme .list-view:focused { -fx-border-color: -nl-focus; }
.neitzel-theme .text-input {
-fx-text-fill: -nl-text; -fx-prompt-text-fill: -nl-muted; -fx-background-color: -nl-surface;
-fx-border-color: -nl-border; -fx-border-width: 2; -fx-padding: 4 6;
-fx-highlight-fill: -nl-selection; -fx-highlight-text-fill: -nl-selection-text;
}
.neitzel-theme .text-area .content { -fx-background-color: -nl-surface; }
.neitzel-theme .text-input:invalid { -fx-border-color: -nl-error; -fx-border-style: dashed; }
.neitzel-theme .button:disabled, .neitzel-theme .text-input:disabled, .neitzel-theme .combo-box-base:disabled,
.neitzel-theme .check-box:disabled, .neitzel-theme .radio-button:disabled { -fx-opacity: 1; -fx-text-fill: -nl-muted; -fx-border-style: dashed; }
.neitzel-theme .label:disabled { -fx-opacity: 1; -fx-text-fill: -nl-muted; }
.neitzel-theme .table:disabled, .neitzel-theme .data-grid:disabled { -fx-opacity: 1; }
.neitzel-theme .table-row-cell, .neitzel-theme .list-cell, .neitzel-theme .tree-cell, .neitzel-theme .table-cell {
-fx-background-color: -nl-surface; -fx-text-fill: -nl-text;
}
.neitzel-theme .table-row-cell:odd { -fx-background-color: -nl-raised; }
.neitzel-theme .table-row-cell:odd .table-cell { -fx-background-color: transparent; }
.neitzel-theme .table-row-cell:selected, .neitzel-theme .table-row-cell:selected .table-cell,
.neitzel-theme .list-cell:selected, .neitzel-theme .tree-cell:selected {
-fx-background-color: -nl-selection; -fx-text-fill: -nl-selection-text;
}
.neitzel-theme .list-cell:filled:hover, .neitzel-theme .tree-cell:filled:hover { -fx-background-color: -nl-hover; -fx-text-fill: -nl-text; }
.neitzel-theme .list-cell:filled:selected, .neitzel-theme .tree-cell:filled:selected { -fx-background-color: -nl-selection; -fx-text-fill: -nl-selection-text; }
.neitzel-theme .table-row-cell:selected:focused, .neitzel-theme .list-cell:selected:focused { -fx-border-color: -nl-focus; -fx-border-width: 2; }
.neitzel-theme .table-view, .neitzel-theme .list-view, .neitzel-theme .tree-view { -fx-background-color: -nl-surface; -fx-border-color: -nl-border; -fx-border-width: 2; }
.neitzel-theme .table-header, .neitzel-theme .column-cell, .neitzel-theme .column-header, .neitzel-theme .column-header-background { -fx-background-color: -nl-raised; }
.neitzel-theme .table .selected, .neitzel-theme .result-row:selected { -fx-background-color: -nl-selection; }
.neitzel-theme .table .selected .label, .neitzel-theme .result-row:selected .label { -fx-text-fill: -nl-selection-text; }
.neitzel-theme .result-row { -fx-padding: 0; -fx-border-color: transparent; -fx-border-width: 0; }
.neitzel-theme .result-row:disabled { -fx-opacity: 1; }
.neitzel-theme .result-row:disabled .label { -fx-text-fill: -nl-muted; }
.neitzel-theme .filter-button { -fx-padding: 4; }
.neitzel-theme .filter-icon { -fx-fill: -nl-text; }
.neitzel-theme .filter-button:filtered, .neitzel-theme .column-opener.filtered { -fx-border-style: segments(3, 2); -fx-border-color: -nl-focus; }
.neitzel-theme .filter-validation, .neitzel-theme .theme-error { -fx-text-fill: -nl-error; -fx-font-weight: bold; }
.neitzel-theme .theme-warning { -fx-text-fill: -nl-warning; }
.neitzel-theme .data-grid-status { -fx-text-fill: -nl-text; }
.neitzel-theme .data-grid:error .data-grid-status { -fx-text-fill: -nl-error; -fx-font-weight: bold; }
.neitzel-theme .data-grid:loading .data-grid-status { -fx-font-style: italic; }
.neitzel-theme .filter-popup, .neitzel-theme .context-menu, .neitzel-theme .dialog-pane, .neitzel-theme .tooltip { -fx-background-color: -nl-surface; -fx-border-color: -nl-border; -fx-border-width: 2; }
.neitzel-theme .menu-item .label { -fx-text-fill: -nl-text; }
.neitzel-theme .menu-item:focused { -fx-background-color: -nl-selection; }
.neitzel-theme .menu-item:focused .label { -fx-text-fill: -nl-selection-text; }
.neitzel-theme .dock-drop-indicator, .neitzel-theme .dock-floating-preview-frame { -fx-fill: transparent; -fx-stroke: -nl-focus; -fx-stroke-width: 2; }
.neitzel-theme .dock-drop-indicator:no-change { -fx-stroke: -nl-muted; -fx-stroke-dash-array: 4 3; }
.neitzel-theme .dock-divider, .neitzel-theme .dock-area-divider { -fx-background-color: -nl-border; }
.neitzel-theme .result-row:selected:disabled .label { -fx-text-fill: -nl-selection-text; }
.neitzel-theme.tooltip, .neitzel-theme .tooltip { -fx-text-fill: -nl-text; -fx-background-color: -nl-surface; }
.neitzel-theme .progress-indicator { -fx-progress-color: -nl-focus; }
.neitzel-theme .progress-bar .bar { -fx-background-color: -nl-focus; }
.neitzel-theme .combo-box-base > .list-cell, .neitzel-theme .combo-box-base > .list-cell:filled:selected {
-fx-background-color: transparent; -fx-text-fill: -nl-text;
}
.neitzel-theme .column-cell { -fx-alignment: center-left; -fx-spacing: 6; -fx-padding: 4 6; }
.neitzel-theme .check-box .box, .neitzel-theme .radio-button .radio {
-fx-background-color: -nl-raised; -fx-border-color: -nl-border; -fx-border-width: 2; -fx-padding: 3;
}
.neitzel-theme .radio-button .radio { -fx-border-radius: 100; -fx-background-radius: 100; }
.neitzel-theme .check-box:focused .box, .neitzel-theme .radio-button:focused .radio { -fx-border-color: -nl-focus; }
.neitzel-theme .check-box:selected .mark, .neitzel-theme .radio-button:selected .dot { -fx-background-color: -nl-text; }
.neitzel-theme .combo-box-base > .list-cell, .neitzel-theme .combo-box-base > .list-cell:filled:selected { -fx-border-width: 0; }
.neitzel-theme .column-header-row { -fx-background-color: -nl-raised; }
.neitzel-theme .column-popup { -fx-background-color: -nl-surface; -fx-border-color: -nl-border; -fx-border-width: 2; -fx-padding: 8; }
@@ -0,0 +1,373 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.grid.filter.FilterColumn;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import org.junit.jupiter.api.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class DataGridSetupTest {
@BeforeAll
static void start() throws Exception {
DataGridTest.start();
DataGridTest.fx(() -> Platform.setImplicitExit(false));
}
static class Source implements GridSource<Integer, String> {
List<GridQuery> queries = new ArrayList<>();
List<QueryOptions> options = new ArrayList<>();
List<CompletableFuture<PageResult<Integer, String>>> pending = new ArrayList<>();
public SourceCapabilities capabilities() {
return new SourceCapabilities(true, true, 100);
}
public String filterExecutionId() {
return "local";
}
public void validateFilter(FilterCondition filter) {
if (!(filter instanceof TextFilter))
throw new UnsupportedOperationException("Only text comparisons supported");
}
public QueryExecution<Integer, String> query(GridQuery q) {
return query(q, QueryOptions.defaults());
}
public QueryExecution<Integer, String> query(GridQuery q, QueryOptions o) {
queries.add(q);
options.add(o);
var f = new CompletableFuture<PageResult<Integer, String>>();
pending.add(f);
return new QueryExecution<>() {
public CompletionStage<PageResult<Integer, String>> result() {
return f;
}
public void cancel() {}
};
}
void success(int index, String model) {
pending.get(index)
.complete(
new PageResult<>(
queries.get(index).page(),
List.of(new GridRow<>(9, model)),
OptionalLong.of(1),
false));
}
}
static class Harness {
Source source = new Source();
AtomicInteger disposed = new AtomicInteger();
DataGrid<Integer, String> grid;
Harness() {
grid =
new DataGrid<>(
List.of(
new ResultColumn("a", "A", 100, 50, 200, -1),
new ResultColumn("b", "B", 80, 40, 200, -1)),
value -> {
if (value.equals("bad"))
throw new IllegalArgumentException("Cannot construct row");
var a = new Label(value);
var b = new Label(value);
return new ResultRow(
new HBox(a, b),
Map.of("a", a, "b", b),
disposed::incrementAndGet);
},
source);
grid.configureSetups("items", 1, Map.of("a", "text", "b", "text"), Map.of());
}
GridSetup candidate(PageRequest page) {
return new GridSetup(
1,
"items",
1,
List.of(
new GridSetup.ColumnState("b", "text", new ColumnWidth.Explicit(999)),
new GridSetup.ColumnState("a", "text", new ColumnWidth.Default())),
List.of(new SortKey("b", SortKey.Direction.DESCENDING)),
List.of(new TextFilter("a", TextFilter.Operator.CONTAINS, "v", false)),
page);
}
}
static Harness create() throws Exception {
var ref = new AtomicReference<Harness>();
DataGridTest.fx(() -> ref.set(new Harness()));
return ref.get();
}
static void loaded(Harness h) throws Exception {
DataGridTest.fx(h.grid::load);
DataGridTest.drain();
DataGridTest.fx(() -> h.source.success(0, "old"));
DataGridTest.drain();
}
@Test
void startupRestoreIssuesOneQueryAndPublishesLayoutAndRowsTogether() throws Exception {
var h = create();
var original = new AtomicReference<GridSetup>();
DataGridTest.fx(
() -> {
original.set(h.grid.snapshotSetup());
h.grid.select(9);
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
assertTrue(h.source.queries.isEmpty());
assertEquals(original.get(), h.grid.snapshotSetup());
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(1, h.source.queries.size());
assertEquals(new PageRequest.Paged(0, 25), h.source.queries.getFirst().page());
h.source.success(0, "value");
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
var saved = h.grid.snapshotSetup();
assertEquals(
List.of("b", "a"),
saved.columns().stream().map(GridSetup.ColumnState::id).toList());
assertEquals(new ColumnWidth.Explicit(200), saved.columns().getFirst().width());
assertEquals(1, h.grid.restorationAdjustmentsProperty().get().size());
assertEquals("value", h.grid.selectedElementProperty().get());
h.grid.close();
});
}
@Test
void decodeValidationQueryAndRowConstructionFailuresPreserveCommittedState() throws Exception {
var h = create();
loaded(h);
var before = new AtomicReference<GridSetup>();
DataGridTest.fx(
() -> {
before.set(h.grid.snapshotSetup());
h.grid.restoreSetup(
() -> {
throw new IllegalArgumentException("Malformed JSON");
});
assertEquals(1, h.source.queries.size());
assertEquals(before.get(), h.grid.snapshotSetup());
var invalid = h.candidate(new PageRequest.Paged(0, 25));
h.grid.restoreSetup(
new GridSetup(
1,
"wrong",
1,
invalid.columns(),
invalid.sort(),
invalid.filters(),
invalid.page()));
assertEquals(1, h.source.queries.size());
h.grid.restoreSetup(invalid);
});
DataGridTest.drain();
DataGridTest.fx(
() ->
h.source
.pending
.getLast()
.completeExceptionally(new IllegalStateException("offline")));
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(before.get(), h.grid.snapshotSetup());
assertEquals(GridCoordinator.Phase.ERROR, h.grid.stateProperty().get().phase());
assertEquals(
"old", h.grid.stateProperty().get().result().rows().getFirst().model());
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
});
DataGridTest.drain();
DataGridTest.fx(() -> h.source.success(h.source.queries.size() - 1, "bad"));
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(before.get(), h.grid.snapshotSetup());
assertEquals(0, h.disposed.get());
assertTrue(
h.grid.stateProperty()
.get()
.error()
.getMessage()
.contains("construct"));
h.grid.close();
});
}
@Test
void newerQueryAndLayoutChangesSupersedeRestoreAndLateApproval() throws Exception {
var h = create();
loaded(h);
var guard = new CompletableFuture<Boolean>();
DataGridTest.fx(
() -> {
h.grid.setEditGuard(q -> guard);
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
h.grid.setEditGuard(q -> CompletableFuture.completedFuture(true));
h.grid.setFilters(
List.of(new TextFilter("a", TextFilter.Operator.EQUALS, "new", true)));
guard.complete(true);
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(2, h.source.queries.size());
assertEquals(new PageRequest.Paged(0, 50), h.source.queries.getLast().page());
h.source.success(1, "new");
});
DataGridTest.drain();
DataGridTest.fx(() -> h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25))));
DataGridTest.drain();
DataGridTest.fx(
() -> {
h.grid.setColumnWidth("a", new ColumnWidth.Explicit(150));
h.source.success(2, "late");
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(
"new", h.grid.stateProperty().get().result().rows().getFirst().model());
assertEquals("a", h.grid.snapshotSetup().columns().getFirst().id());
assertEquals(
new ColumnWidth.Explicit(150),
h.grid.snapshotSetup().columns().getFirst().width());
h.grid.close();
});
}
@Test
void allRestoreRequiresFreshConfirmationAndCancelDoesNotInstallLayout() throws Exception {
var h = create();
loaded(h);
var before = new AtomicReference<GridSetup>();
var confirmation = new CompletableFuture<Boolean>();
DataGridTest.fx(
() -> {
before.set(h.grid.snapshotSetup());
h.grid.setAllConfirmation((q, n) -> confirmation);
h.grid.restoreSetup(h.candidate(new PageRequest.All()));
});
DataGridTest.drain();
DataGridTest.fx(
() ->
h.source
.pending
.getLast()
.completeExceptionally(new AllRowsConfirmationRequired(1001)));
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(before.get(), h.grid.snapshotSetup());
confirmation.complete(false);
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(before.get(), h.grid.snapshotSetup());
h.grid.setAllConfirmation((q, n) -> CompletableFuture.completedFuture(true));
h.grid.restoreSetup(h.candidate(new PageRequest.All()));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertFalse(h.source.options.getLast().allApproved());
h.source
.pending
.getLast()
.completeExceptionally(new AllRowsConfirmationRequired(1001));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertTrue(h.source.options.getLast().allApproved());
h.source.success(h.source.queries.size() - 1, "all");
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertInstanceOf(PageRequest.All.class, h.grid.snapshotSetup().page());
h.grid.close();
});
}
@Test
void savingLeavesDraftOpenAndRestoreCancelsItOnlyAfterGuardAllows() throws Exception {
var h = create();
loaded(h);
var stage = new AtomicReference<Stage>();
var guard = new CompletableFuture<Boolean>();
var popup = new AtomicReference<Window>();
DataGridTest.fx(
() -> {
h.grid.configureFilter("a", FilterColumn.text());
var window = new Stage();
window.setScene(new Scene(h.grid, 600, 400));
window.show();
stage.set(window);
((Button) h.grid.lookup(".filter-button")).fire();
popup.set(
Window.getWindows().stream()
.filter(
w ->
w != window
&& w.getScene()
.getRoot()
.lookup("#filter-ok")
!= null)
.findFirst()
.orElseThrow());
h.grid.snapshotSetup();
assertTrue(popup.get().isShowing());
h.grid.setEditGuard(q -> guard);
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertTrue(popup.get().isShowing());
guard.complete(false);
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertTrue(popup.get().isShowing());
h.grid.setEditGuard(q -> CompletableFuture.completedFuture(true));
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertFalse(popup.get().isShowing());
assertEquals(2, h.source.queries.size());
h.grid.close();
stage.get().close();
});
}
}
@@ -0,0 +1,213 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import org.junit.jupiter.api.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class DataGridTest {
record Item(long id, String text) {}
@BeforeAll
static void start() throws Exception {
CountDownLatch ready = new CountDownLatch(1);
try {
Platform.startup(ready::countDown);
} catch (IllegalStateException running) {
ready.countDown();
}
assertTrue(ready.await(10, TimeUnit.SECONDS));
}
static void fx(Runnable code) throws Exception {
FutureTask<Void> task = new FutureTask<>(code, null);
Platform.runLater(task);
task.get(10, TimeUnit.SECONDS);
}
static void drain() throws Exception {
for (int i = 0; i < 4; i++) fx(() -> {});
}
static DataGrid<Long, Item> grid(List<Item> items, AtomicInteger disposed) {
var source =
new MemoryGridSource<Long, Item>(
() -> items,
Item::id,
Long::compare,
List.of(
new MemoryColumn<>(
"text",
MemoryColumn.Kind.TEXT,
i -> new FilterValue.Text(i.text()))),
Runnable::run,
250);
return new DataGrid<>(
List.of(new ResultColumn("text", "Text", 120, 50, 300, -1)),
i -> {
Label label = new Label(i.text());
return new ResultRow(
new HBox(label), Map.of("text", label), disposed::incrementAndGet);
},
source);
}
@Test
void pagingFilteringSelectionAndAllUseCoordinatorWithoutChangingLegacyTable() throws Exception {
var ref = new AtomicReference<DataGrid<Long, Item>>();
AtomicInteger disposed = new AtomicInteger();
var items =
new ArrayList<>(
List.of(new Item(1, "Zulu"), new Item(2, "Alpha"), new Item(3, "Beta")));
fx(
() -> {
ref.set(grid(items, disposed));
assertEquals(
GridCoordinator.Phase.IDLE, ref.get().stateProperty().get().phase());
ref.get().setPageSize(1);
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(1, g.stateProperty().get().result().rows().size());
g.select(1L);
assertEquals("Zulu", g.selectedElementProperty().get().text());
g.next();
assertNull(g.selectedElementProperty().get());
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(1L, g.selectedKeyProperty().get());
assertNull(g.selectedElementProperty().get());
g.setSort(new SortKey("text", SortKey.Direction.ASCENDING));
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(
"Alpha",
g.stateProperty().get().result().rows().getFirst().model().text());
assertEquals(
0,
((PageRequest.Paged) g.stateProperty().get().requested().page())
.pageIndex());
g.setAllWarningThreshold(1);
g.setAllConfirmation((q, count) -> CompletableFuture.completedFuture(false));
g.showAll();
});
drain();
fx(
() -> {
var g = ref.get();
assertInstanceOf(
PageRequest.Paged.class, g.stateProperty().get().requested().page());
g.setAllConfirmation((q, count) -> CompletableFuture.completedFuture(true));
g.showAll();
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(3, g.stateProperty().get().result().rows().size());
assertEquals("Zulu", g.selectedElementProperty().get().text());
g.setFilters(
List.of(
new TextFilter(
"text", TextFilter.Operator.EQUALS, "alpha", false)));
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(1, g.stateProperty().get().result().rows().size());
assertNull(g.selectedElementProperty().get());
g.close();
assertEquals(GridCoordinator.Phase.CLOSED, g.stateProperty().get().phase());
assertTrue(disposed.get() > 0);
assertThrows(IllegalStateException.class, g::load);
});
}
@Test
void pendingGuardDoesNotPublishAfterGridCloses() throws Exception {
var ref = new AtomicReference<DataGrid<Long, Item>>();
var guard = new CompletableFuture<Boolean>();
fx(
() -> {
ref.set(grid(List.of(new Item(1, "a")), new AtomicInteger()));
ref.get().setEditGuard(q -> guard);
ref.get().load();
ref.get().close();
});
guard.complete(true);
drain();
fx(
() ->
assertEquals(
GridCoordinator.Phase.CLOSED,
ref.get().stateProperty().get().phase()));
}
@Test
void successfulSourceReplacementClearsSelectionAndPublishesOnFx() throws Exception {
var ref = new AtomicReference<DataGrid<Long, Item>>();
fx(
() -> {
ref.set(grid(List.of(new Item(1, "old")), new AtomicInteger()));
ref.get().load();
});
drain();
fx(
() -> {
var replacement =
new MemoryGridSource<Long, Item>(
() -> List.of(new Item(1, "new")),
Item::id,
Long::compare,
List.of(
new MemoryColumn<>(
"text",
MemoryColumn.Kind.TEXT,
i -> new FilterValue.Text(i.text()))),
Runnable::run,
250);
ref.get().select(1L);
ref.get()
.stateProperty()
.addListener(
(obs, old, value) ->
assertTrue(Platform.isFxApplicationThread()));
ref.get().setSource(replacement);
});
drain();
fx(
() -> {
assertNull(ref.get().selectedKeyProperty().get());
assertNull(ref.get().selectedElementProperty().get());
assertEquals(
"new",
ref.get()
.stateProperty()
.get()
.result()
.rows()
.getFirst()
.model()
.text());
ref.get().close();
});
}
}
@@ -0,0 +1,494 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import org.junit.jupiter.api.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class FilterEditorsTest {
@BeforeAll
static void start() throws Exception {
DataGridTest.start();
DataGridTest.fx(() -> javafx.application.Platform.setImplicitExit(false));
}
static <T extends Node> T node(FilterEditor e, String id, Class<T> type) {
return type.cast(e.view().lookup("#" + id));
}
@SuppressWarnings("unchecked")
static void choice(FilterEditor e, String id, String value) {
((ComboBox<String>) e.view().lookup("#" + id)).setValue(value);
}
static FilterEditorContext context(FilterColumn config, FilterCondition committed) {
return new FilterEditorContext(
"x",
config,
committed,
List.of(),
config.checklist() == FilterColumn.Checklist.INHERIT
? FilterColumn.Checklist.DISABLED
: config.checklist());
}
@Test
void realFxmlPreservesLiteralTextAndExactLocaleNumbers() throws Exception {
DataGridTest.fx(
() -> {
try (var editor =
BuiltInFilterEditor.load(context(FilterColumn.text(), null))) {
choice(editor, "mode", "Comparison");
node(editor, "operand", TextField.class).setText(" %_ ");
assertEquals(
new TextFilter("x", TextFilter.Operator.EQUALS, " %_ ", false),
editor.draft());
node(editor, "operand", TextField.class).setText("");
assertNotNull(editor.draft());
choice(editor, "operator", "CONTAINS");
assertThrows(IllegalArgumentException.class, editor::draft);
assertFalse(editor.validationMessageProperty().get().isBlank());
choice(editor, "mode", "Missing");
assertEquals(new MissingFilter("x", true), editor.draft());
choice(editor, "mode", "Clear filter");
assertNull(editor.draft());
}
var config =
FilterColumn.number(
Locale.GERMANY,
false,
new BigDecimal("-100"),
new BigDecimal("100"));
try (var editor =
BuiltInFilterEditor.load(
context(
config,
new NumericFilter(
"x",
NumericFilter.Operator.EQUALS,
new BigDecimal("1.20"),
null)))) {
assertEquals("1,20", node(editor, "operand", TextField.class).getText());
assertEquals(
new BigDecimal("1.20"), ((NumericFilter) editor.draft()).operand());
for (String invalid :
List.of("NaN", "Infinity", "1.234,50", "101", "bad")) {
node(editor, "operand", TextField.class).setText(invalid);
assertThrows(IllegalArgumentException.class, editor::draft);
}
node(editor, "operand", TextField.class).setText("2");
choice(editor, "operator", "RANGE");
node(editor, "upper", TextField.class).setText("1");
assertThrows(IllegalArgumentException.class, editor::draft);
}
try (var editor =
BuiltInFilterEditor.load(
context(
FilterColumn.number(
Locale.US,
true,
BigDecimal.ZERO,
BigDecimal.valueOf(Integer.MAX_VALUE)),
null))) {
choice(editor, "mode", "Comparison");
for (String invalid : List.of("1.5", "2147483648", "9223372036854775808")) {
node(editor, "operand", TextField.class).setText(invalid);
assertThrows(IllegalArgumentException.class, editor::draft);
}
}
});
}
@Test
void lookupRacesFailuresAndSearchNeverEraseOffBatchSelections() throws Exception {
var pending = new ArrayList<CompletableFuture<FilterCandidates.Batch>>();
AtomicInteger disposed = new AtomicInteger();
FilterCandidates.Provider provider =
new FilterCandidates.Provider() {
public Set<FilterCandidates.Scope> scopes() {
return Set.of(FilterCandidates.Scope.CURRENT_PAGE);
}
public FilterCandidates.Session open(FilterCandidates.Context c) {
return new FilterCandidates.Session() {
public CompletionStage<FilterCandidates.Batch> load(
FilterCandidates.Request r) {
var f = new CompletableFuture<FilterCandidates.Batch>();
pending.add(f);
return f;
}
public void close() {
disposed.incrementAndGet();
}
};
}
};
var ref = new AtomicReference<BuiltInFilterEditor>();
DataGridTest.fx(
() -> {
ref.set(
BuiltInFilterEditor.load(
context(
FilterColumn.text()
.withChecklist(
FilterColumn.Checklist.CURRENT_PAGE,
provider),
new ValueFilter(
"x",
Set.of(new FilterValue.Text("off-page")),
true))));
node(ref.get(), "search", TextField.class).setText("b");
pending.get(1)
.complete(
new FilterCandidates.Batch(
List.of(
new FilterCandidates.Candidate(
new FilterValue.Text("b"), "B")),
false));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
pending.getFirst()
.complete(
new FilterCandidates.Batch(
List.of(
new FilterCandidates.Candidate(
new FilterValue.Text("old"), "Old")),
false));
node(ref.get(), "selectShown", Button.class).fire();
assertEquals(
Set.of(new FilterValue.Text("off-page"), new FilterValue.Text("b")),
((ValueFilter) ref.get().draft()).values());
node(ref.get(), "search", TextField.class).setText("fail");
pending.getLast().completeExceptionally(new IllegalStateException("offline"));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertTrue(
node(ref.get(), "lookupMessage", Label.class)
.getText()
.contains("offline"));
assertEquals(2, ((ValueFilter) ref.get().draft()).values().size());
node(ref.get(), "retry", Button.class).fire();
ref.get().close();
pending.getLast().complete(new FilterCandidates.Batch(List.of(), false));
assertEquals(1, disposed.get());
});
DataGridTest.drain();
}
@Test
void configurationAndCapabilitiesFailVisiblyWithoutFallback() throws Exception {
DataGridTest.fx(
() -> {
assertThrows(
IllegalArgumentException.class,
() ->
FilterColumn.text()
.withChecklist(
FilterColumn.Checklist.CURRENT_PAGE, null));
var config =
FilterColumn.text()
.withChecklist(
FilterColumn.Checklist.SOURCE_WIDE,
FilterCandidates.currentPage(List::of));
try (var e = BuiltInFilterEditor.load(context(config, null))) {
choice(e, "mode", "Checklist");
assertThrows(IllegalArgumentException.class, e::draft);
assertTrue(node(e, "scope", Label.class).getText().contains("unavailable"));
choice(e, "mode", "Comparison");
assertNotNull(e.draft());
}
var registry = FilterEditors.builtIns();
assertThrows(IllegalArgumentException.class, () -> registry.require("absent"));
assertThrows(
UnsupportedOperationException.class,
() ->
registry.require("neitzel.text")
.requireEvaluation("jdbc-unknown"));
assertTrue(registry.require("neitzel.text").capabilities().persistence());
assertThrows(
UnsupportedOperationException.class,
() ->
registry.require("neitzel.text")
.validate(
new NumericFilter(
"x",
NumericFilter.Operator.EQUALS,
BigDecimal.ONE,
null)));
});
}
@Test
void popupDraftValidationDismissalNestedEscapeAndOwnerCleanup() throws Exception {
AtomicReference<FilterCondition> committed =
new AtomicReference<>(
new TextFilter("x", TextFilter.Operator.EQUALS, "old", false));
DataGridTest.fx(
() -> {
Stage stage = new Stage();
Button opener = new Button("Filter");
stage.setScene(new Scene(new VBox(opener), 500, 400));
stage.show();
try {
var editor =
BuiltInFilterEditor.load(
context(FilterColumn.text(), committed.get()));
var popup =
new FilterPopup(
opener,
editor,
new FilterPopup.Options(
FilterPopup.Outside.ACCEPT, false, false),
c -> {
if (c instanceof TextFilter f
&& f.operand().equals("unsupported"))
throw new UnsupportedOperationException(
"Unsupported source semantics");
},
committed::set);
popup.show();
node(editor, "operand", TextField.class).setText("unsupported");
popup.outside();
assertTrue(popup.isOpen());
assertTrue(popup.errorMessage().contains("Unsupported"));
assertEquals("old", ((TextFilter) committed.get()).operand());
node(editor, "operand", TextField.class).setText("new");
ComboBox<?> chooser = node(editor, "operator", ComboBox.class);
chooser.show();
javafx.event.Event.fireEvent(
editor.view(),
new KeyEvent(
KeyEvent.KEY_PRESSED,
"",
"",
KeyCode.ESCAPE,
false,
false,
false,
false));
assertFalse(chooser.isShowing());
assertTrue(popup.isOpen());
javafx.event.Event.fireEvent(
editor.view(),
new KeyEvent(
KeyEvent.KEY_PRESSED,
"",
"",
KeyCode.ENTER,
false,
false,
false,
false));
assertFalse(popup.isOpen());
assertEquals("new", ((TextFilter) committed.get()).operand());
var second =
BuiltInFilterEditor.load(
context(FilterColumn.text(), committed.get()));
var cancel =
new FilterPopup(
opener,
second,
FilterPopup.Options.defaults(),
c -> {},
committed::set);
cancel.show();
node(second, "operand", TextField.class).setText("discard");
cancel.outside();
assertEquals("new", ((TextFilter) committed.get()).operand());
var third =
BuiltInFilterEditor.load(
context(FilterColumn.text(), committed.get()));
var disposed =
new FilterPopup(
opener,
third,
FilterPopup.Options.defaults(),
c -> {},
committed::set);
disposed.show();
stage.close();
assertFalse(disposed.isOpen());
assertThrows(IllegalStateException.class, third::draft);
} finally {
stage.close();
}
});
DataGridTest.drain();
}
public record Prefix(String columnId, String operand) implements FilterCondition {
public String typeId() {
return "test.prefix";
}
}
public static final class CustomEditor implements FilterEditor {
@javafx.fxml.FXML private TextField value;
private Parent root;
private String column;
private final javafx.beans.property.ReadOnlyStringWrapper message =
new javafx.beans.property.ReadOnlyStringWrapper("");
static CustomEditor load(FilterEditorContext context) {
try {
var loader =
new javafx.fxml.FXMLLoader(
FilterEditorsTest.class.getResource("CustomFilterEditor.fxml"));
var editor = new CustomEditor();
loader.setController(editor);
editor.root = loader.load();
editor.column = context.columnId();
editor.value.setText(context.committed() instanceof Prefix f ? f.operand() : "a");
return editor;
} catch (java.io.IOException failure) {
throw new IllegalStateException(failure);
}
}
public Parent view() {
return root;
}
public javafx.beans.property.ReadOnlyStringProperty validationMessageProperty() {
return message.getReadOnlyProperty();
}
public FilterCondition draft() {
return new Prefix(column, value.getText());
}
public void close() {}
}
@Test
void customFxmlRegistrationAndHeaderActionRespectActualSourceCapabilities() throws Exception {
var ref = new AtomicReference<DataGrid<Long, String>>();
var window = new AtomicReference<Stage>();
DataGridTest.fx(
() -> {
var source =
new MemoryGridSource<Long, String>(
() -> List.of("alpha", "beta"),
s -> (long) s.length(),
Long::compare,
List.of(
new MemoryColumn<>(
"text",
MemoryColumn.Kind.TEXT,
FilterValue.Text::new,
Map.of(
"test.prefix",
c ->
v ->
v
instanceof
FilterValue
.Text
t
&& t.value()
.startsWith(
((Prefix)
c)
.operand())))),
Runnable::run,
50);
var grid =
new DataGrid<Long, String>(
List.of(new ResultColumn("text", "Text", 200, 50, 300, -1)),
value -> {
var label = new Label(value);
return new ResultRow(
new HBox(label), Map.of("text", label), () -> {});
},
source);
var registry = new FilterEditors();
registry.register(
new FilterEditors.Registration(
"test.prefix",
new FilterCapabilities(true, false, Set.of()),
Set.of("test.prefix"),
CustomEditor::load));
grid.setFilterEditors(registry);
grid.configureFilter(
"text",
new FilterColumn(
"test.prefix",
Locale.US,
false,
false,
null,
null,
FilterColumn.Checklist.DISABLED,
null));
Stage stage = new Stage();
stage.setScene(new Scene(grid, 500, 400));
stage.show();
window.set(stage);
ref.set(grid);
grid.load();
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
var grid = ref.get();
var before = grid.stateProperty().get().generation();
((Button) grid.lookup(".filter-button")).fire();
assertEquals(
before,
grid.stateProperty().get().generation()); // Opener must not sort.
Parent popup =
javafx.stage.Window.getWindows().stream()
.map(w -> w.getScene().getRoot())
.filter(root -> root.lookup("#filter-ok") != null)
.findFirst()
.orElseThrow();
((Button) popup.lookup("#filter-ok")).fire();
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
var grid = ref.get();
assertEquals(
List.of(new Prefix("text", "a")),
grid.stateProperty().get().displayed().filters());
assertEquals(
"alpha", grid.stateProperty().get().result().rows().getFirst().model());
long generation = grid.stateProperty().get().generation();
assertThrows(
UnsupportedOperationException.class,
() ->
grid.setFilters(
List.of(
new FilterCondition() {
public String columnId() {
return "text";
}
public String typeId() {
return "unknown";
}
})));
assertEquals(generation, grid.stateProperty().get().generation());
grid.close();
window.get().close();
});
}
}
@@ -0,0 +1,350 @@
package de.neitzel.fx.view;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
/**
* Explicit desktop acceptance probe, not part of unattended Surefire execution. Uses native OS
* input.
*/
public final class FilterPopupNativeProbe {
private static Stage stage;
private static Button opener;
private static TextField outside;
private static BuiltInFilterEditor editor;
private static DatePicker date;
private static FilterPopup popup;
private static FilterCondition committed =
new NumericFilter("x", NumericFilter.Operator.EQUALS, BigDecimal.TEN, null);
private static FilterPopup.Options options = FilterPopup.Options.defaults();
private static Robot robot;
private static <T> T fx(Callable<T> work) throws Exception {
var task = new FutureTask<>(work);
Platform.runLater(task);
return task.get(10, TimeUnit.SECONDS);
}
private static void settle() throws Exception {
Thread.sleep(350);
fx(() -> null);
}
private static void click(Node node) throws Exception {
double[] point =
fx(
() -> {
var b = node.localToScreen(node.getBoundsInLocal());
return new double[] {b.getCenterX(), b.getCenterY()};
});
robot.mouseMove((int) point[0], (int) point[1]);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
settle();
}
private static void key(int code) throws Exception {
robot.keyPress(code);
robot.keyRelease(code);
settle();
}
private static TextField operand() {
return (TextField) editor.view().lookup("#operand");
}
private static void check(boolean value, String message) {
if (!value) throw new AssertionError(message);
System.out.println("PASS " + message);
}
private static void open() {
if (popup != null && popup.isOpen()) {
popup.outside();
return;
}
editor =
BuiltInFilterEditor.load(
new FilterEditorContext(
"x",
FilterColumn.number(Locale.US, true, null, null),
committed,
List.of(),
FilterColumn.Checklist.DISABLED));
date = new DatePicker();
date.setAccessibleText("Nested date chooser probe");
VBox content = new VBox(8, editor.view(), date);
FilterEditor wrapped =
new FilterEditor() {
public Parent view() {
return content;
}
public FilterCondition draft() {
return editor.draft();
}
public ReadOnlyStringProperty validationMessageProperty() {
return editor.validationMessageProperty();
}
public void close() {
date.hide();
editor.close();
}
};
popup = new FilterPopup(opener, wrapped, options, c -> {}, c -> committed = c);
popup.show();
}
private static Region spacer() {
Region spacer = new Region();
spacer.setPrefHeight(300);
return spacer;
}
public static void main(String[] args) throws Exception {
try {
DataGridTest.start();
fx(
() -> {
Platform.setImplicitExit(false);
stage = new Stage();
opener = new Button("Filter");
opener.setOnAction(e -> open());
outside = new TextField();
outside.setPromptText("Outside target");
VBox root =
new VBox(
20,
new Label("Native filter popup qualification"),
opener,
spacer(),
outside);
root.setStyle("-fx-padding: 24;");
stage.setScene(new Scene(root, 650, 600));
stage.setTitle("DataGrid native filter qualification");
stage.show();
stage.toFront();
stage.requestFocus();
return null;
});
if (Arrays.asList(args).contains("--manual")) {
var finished = new CountDownLatch(1);
fx(
() -> {
CheckBox acceptOutside = new CheckBox("Accept on outside click");
CheckBox showActions = new CheckBox("Show OK / Cancel");
showActions.setSelected(true);
Runnable configure =
() ->
options =
new FilterPopup.Options(
acceptOutside.isSelected()
? FilterPopup.Outside.ACCEPT
: FilterPopup.Outside.CANCEL,
showActions.isSelected(),
showActions.isSelected());
acceptOutside.setOnAction(e -> configure.run());
showActions.setOnAction(e -> configure.run());
((VBox) stage.getScene().getRoot())
.getChildren()
.addAll(acceptOutside, showActions);
stage.setOnHidden(e -> finished.countDown());
return null;
});
System.out.println("MANUAL PROBE READY; close its window to finish");
finished.await();
return;
}
robot = new Robot();
robot.setAutoDelay(100);
settle();
click(opener);
check(
fx(() -> popup != null && popup.isShowing()),
"native opener click and anchored placement");
click(operand());
key(KeyEvent.VK_END);
key(KeyEvent.VK_2);
key(KeyEvent.VK_ENTER);
check(
fx(
() ->
!popup.isOpen()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("102"))),
"native typing and Enter commit");
check(fx(() -> opener.isFocused()), "explicit acceptance returns focus to opener");
click(opener);
fx(
() -> {
operand().setText("44");
return null;
});
key(KeyEvent.VK_ESCAPE);
check(
fx(
() ->
!popup.isOpen()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("102"))),
"Escape rollback and fresh reopen");
click(opener);
fx(
() -> {
operand().setText("55");
return null;
});
click(outside);
check(
fx(
() ->
!popup.isOpen()
&& outside.isFocused()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("102"))),
"outside Cancel preserves filter and clicked target focus");
fx(
() -> {
options = new FilterPopup.Options(FilterPopup.Outside.ACCEPT, false, false);
return null;
});
click(opener);
fx(
() -> {
operand().setText("66");
return null;
});
click(outside);
check(
fx(
() ->
!popup.isOpen()
&& outside.isFocused()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("66"))),
"outside Accept with hidden OK/Cancel");
click(opener);
fx(
() -> {
operand().setText("bad");
return null;
});
click(outside);
settle();
check(
fx(
() ->
popup.isShowing()
&& !popup.errorMessage().isBlank()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("66"))),
"invalid outside Accept reopens with error and retains committed filter");
fx(
() -> {
operand().setText("77");
return null;
});
key(KeyEvent.VK_ENTER);
check(
fx(
() ->
!popup.isOpen()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("77"))),
"Enter works without action buttons");
click(opener);
fx(
() -> {
operand().setText("88");
return null;
});
click(opener);
check(
fx(
() ->
!popup.isOpen()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("88"))),
"opener re-click follows outside policy without reopening");
click(opener);
ComboBox<?> combo = fx(() -> (ComboBox<?>) editor.view().lookup("#operator"));
click(combo);
check(fx(combo::isShowing), "native nested ComboBox opens");
key(KeyEvent.VK_ESCAPE);
check(
fx(() -> !combo.isShowing() && popup.isShowing()),
"first Escape closes nested ComboBox only");
click(combo);
key(KeyEvent.VK_DOWN);
key(KeyEvent.VK_ENTER);
check(
fx(() -> !combo.isShowing() && popup.isOpen()),
"nested ComboBox selection does not accept parent");
Node arrow = fx(() -> date.lookup(".arrow-button"));
click(arrow);
check(fx(date::isShowing), "native nested DatePicker opens");
key(KeyEvent.VK_ESCAPE);
check(
fx(() -> !date.isShowing() && popup.isOpen()),
"first Escape closes nested DatePicker only");
key(KeyEvent.VK_ESCAPE);
check(fx(() -> !popup.isOpen()), "second Escape cancels parent");
click(opener);
new ProcessBuilder("osascript", "-e", "tell application \"Finder\" to activate")
.start()
.waitFor();
settle();
check(fx(() -> !popup.isOpen()), "other-application dismissal");
fx(
() -> {
stage.toFront();
stage.requestFocus();
return null;
});
settle();
click(opener);
fx(
() -> {
stage.close();
return null;
});
settle();
check(fx(() -> !popup.isOpen()), "owner disposal cancels and releases editor");
System.out.println("NATIVE MATRIX PASSED");
} catch (Throwable failure) {
failure.printStackTrace();
System.exit(1);
} finally {
if (stage != null)
fx(
() -> {
stage.close();
return null;
});
Platform.exit();
}
}
}
@@ -0,0 +1,195 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import org.junit.jupiter.api.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
class TableResultsTest {
@BeforeAll
static void start() throws Exception {
CountDownLatch started = new CountDownLatch(1);
try {
Platform.startup(started::countDown);
} catch (IllegalStateException e) {
started.countDown();
}
assertTrue(started.await(10, TimeUnit.SECONDS));
}
static void fx(Runnable r) throws Exception {
FutureTask<Void> task = new FutureTask<>(r, null);
Platform.runLater(task);
task.get(10, TimeUnit.SECONDS);
}
static List<ResultColumn> columns() {
return List.of(
new ResultColumn("name", "Name", 120, 60, 300, -1),
new ResultColumn("city", "City", 100, 50, 200, -1));
}
static ResultRow row(String model, AtomicInteger disposed) {
Label name = new Label(model), city = new Label("City");
Button action = new Button("Edit");
HBox root = new HBox(name, city, action);
return new ResultRow(root, Map.of("name", name, "city", city), disposed::incrementAndGet);
}
@Test
void resultOrderMappingSelectionAndLifetime() throws Exception {
fx(
() -> {
Table table = new Table();
AtomicInteger disposed = new AtomicInteger();
List<ResultRow> views = new ArrayList<>();
TableResults<Integer, String> renderer =
table.openResults(
columns(),
s -> {
var v = row(s, disposed);
views.add(v);
return v;
});
renderer.show(List.of(new GridRow<>(2, "Z"), new GridRow<>(1, "A")));
VBox body = (VBox) ((ScrollPane) table.getChildren().get(1)).getContent();
assertEquals(
"Z",
((Label) ((HBox) body.getChildren().get(0)).getChildren().get(0))
.getText());
renderer.select(2);
assertEquals("Z", renderer.selectedElementProperty().get());
renderer.setColumnOrder(List.of("city", "name"));
assertSame(
views.get(0).fields().get("city"),
views.get(0).root().getChildren().get(0));
assertInstanceOf(Button.class, views.get(0).root().getChildren().get(2));
assertEquals(
200, renderer.setColumnWidth("city", new ColumnWidth.Explicit(999)));
assertEquals(200, views.get(0).fields().get("city").getPrefWidth());
assertThrows(
IllegalArgumentException.class,
() -> renderer.setColumnOrder(List.of("name", "name")));
renderer.show(List.of(new GridRow<>(1, "New A")));
assertEquals(2, disposed.get());
assertEquals(2, renderer.selectedKeyProperty().get());
assertNull(renderer.selectedElementProperty().get());
renderer.show(List.of(new GridRow<>(2, "New Z")));
assertEquals("New Z", renderer.selectedElementProperty().get());
assertEquals(3, disposed.get());
renderer.close();
renderer.close();
assertEquals(4, disposed.get());
assertTrue(body.getChildren().isEmpty());
assertThrows(IllegalStateException.class, () -> renderer.show(List.of()));
});
}
@Test
void failedReplacementKeepsOldRowsAndReleasesStagedRows() throws Exception {
fx(
() -> {
AtomicInteger disposed = new AtomicInteger();
Table t = new Table();
TableResults<Integer, String> r =
t.openResults(
columns(),
s -> {
if (s.equals("fail"))
throw new IllegalArgumentException("factory failure");
return row(s, disposed);
});
r.show(List.of(new GridRow<>(1, "old")));
r.select(1);
assertThrows(
IllegalArgumentException.class,
() ->
r.show(
List.of(
new GridRow<>(2, "staged"),
new GridRow<>(3, "fail"))));
assertEquals(1, disposed.get());
assertEquals("old", r.selectedElementProperty().get());
assertThrows(
IllegalArgumentException.class,
() -> r.show(List.of(new GridRow<>(2, "a"), new GridRow<>(2, "b"))));
assertEquals(1, disposed.get());
r.close();
assertEquals(2, disposed.get());
});
}
@Test
void fixedColumnsAndModeAreValidated() throws Exception {
fx(
() -> {
Table t = new Table();
var defs =
List.of(
new ResultColumn("name", "Name", 120, 60, 300, 0),
new ResultColumn("city", "City", 100, 50, 200, -1));
var r = t.openResults(defs, s -> row(String.valueOf(s), new AtomicInteger()));
assertThrows(
IllegalArgumentException.class,
() -> r.setColumnOrder(List.of("city", "name")));
assertThrows(
IllegalStateException.class,
() ->
t.openResults(
defs,
s -> row(String.valueOf(s), new AtomicInteger())));
r.close();
});
}
@Test
void malformedMappingAndDisposalFailureAreObservable() throws Exception {
fx(
() -> {
AtomicInteger releases = new AtomicInteger();
Table table = new Table();
TableResults<Integer, String> renderer =
table.openResults(
columns(),
model -> {
Label name = new Label(model);
Label city = new Label("City");
HBox root = new HBox(name, city);
return new ResultRow(
root,
model.equals("invalid")
? Map.of("name", name)
: Map.of("name", name, "city", city),
() -> {
releases.incrementAndGet();
if (model.equals("old"))
throw new IllegalStateException(
"cleanup failed");
});
});
renderer.show(List.of(new GridRow<>(1, "old")));
renderer.select(1);
assertThrows(
IllegalArgumentException.class,
() -> renderer.show(List.of(new GridRow<>(2, "invalid"))));
assertEquals("old", renderer.selectedElementProperty().get());
assertEquals(1, releases.get());
renderer.show(List.of(new GridRow<>(3, "new")));
assertEquals(2, releases.get());
assertNotNull(renderer.disposalFailureProperty().get());
renderer.select(3);
assertEquals("new", renderer.selectedElementProperty().get());
renderer.close();
assertEquals(3, releases.get());
});
}
}
@@ -0,0 +1,266 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.docking.*;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.fx.theme.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import org.junit.jupiter.api.*;
import java.util.*;
class ThemeManagerTest {
private static final java.util.Queue<Throwable> uncaught =
new java.util.concurrent.ConcurrentLinkedQueue<>();
private static Thread.UncaughtExceptionHandler previousHandler;
@BeforeEach
void captureFxErrors() throws Exception {
DataGridTest.fx(
() -> {
previousHandler = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread()
.setUncaughtExceptionHandler((thread, error) -> uncaught.add(error));
});
}
@AfterEach
void verifyFxErrors() throws Exception {
DataGridTest.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 {
DataGridTest.start();
DataGridTest.fx(() -> Platform.setImplicitExit(false));
}
@Test
void optInSwitchPreservesApplicationStylesAndCloseRemovesOnlyOwnedStyles() throws Exception {
DataGridTest.fx(
() -> {
Button button = new Button("Unchanged unless opted in");
Scene scene = new Scene(new VBox(button));
String app =
getClass().getResource("shared-theme-override.css").toExternalForm();
scene.getStylesheets().add(app);
assertFalse(scene.getRoot().getStyleClass().contains("neitzel-theme"));
var manager = new ThemeManager();
var registration = manager.register(scene);
assertEquals(app, scene.getStylesheets().getLast());
for (String id : List.of("dark", "high-contrast", "light")) {
assertTrue(manager.select(id));
scene.getRoot().applyCss();
assertEquals(app, scene.getStylesheets().getLast());
assertEquals(3, scene.getStylesheets().size());
assertEquals(
9,
button.getBackground()
.getFills()
.getFirst()
.getRadii()
.getTopLeftHorizontalRadius(),
0.01);
}
var old = scene.getRoot();
scene.setRoot(new VBox(new Label("Replacement root")));
assertFalse(old.getStyleClass().contains("neitzel-theme"));
assertTrue(scene.getRoot().getStyleClass().contains("neitzel-theme"));
registration.close();
assertEquals(List.of(app), scene.getStylesheets());
assertFalse(scene.getRoot().getStyleClass().contains("neitzel-theme"));
manager.close();
manager.close();
});
}
@Test
void missingThemeAndDetectablePartialInstallationRollBackEveryScene() throws Exception {
DataGridTest.fx(
() -> {
var manager = new ThemeManager();
Scene one = new Scene(new VBox()), two = new Scene(new VBox());
manager.register(one);
manager.register(two);
manager.select("dark");
var oldOne = List.copyOf(one.getStylesheets());
var oldTwo = List.copyOf(two.getStylesheets());
manager.addTheme(
new Theme("missing", List.of("file:/missing/neitzel-theme.css")));
assertFalse(manager.select("missing"));
assertEquals("dark", manager.selectedThemeProperty().get().id());
assertEquals(oldOne, one.getStylesheets());
manager.setInstallationCheck(
s -> {
if (s == two)
throw new IllegalArgumentException(
"Application CSS check failed");
});
assertFalse(manager.select("light"));
assertEquals(oldOne, one.getStylesheets());
assertEquals(oldTwo, two.getStylesheets());
assertEquals("dark", manager.selectedThemeProperty().get().id());
assertTrue(manager.failureProperty().get().message().contains("retained dark"));
manager.setInstallationCheck(s -> {});
assertFalse(manager.selectSaved("deleted-user-theme"));
assertEquals("light", manager.selectedThemeProperty().get().id());
assertTrue(manager.failureProperty().get().message().contains("using light"));
manager.close();
});
}
@Test
void filterDraftNestedChooserDialogAndFutureOwnedWindowFollowLiveTheme() throws Exception {
DataGridTest.fx(
() -> {
Stage stage = new Stage();
Button opener = new Button("Filter");
stage.setScene(new Scene(new VBox(opener), 500, 400));
var manager = new ThemeManager();
manager.register(stage.getScene());
stage.show();
var editor =
BuiltInFilterEditor.load(
new FilterEditorContext(
"x",
FilterColumn.text(),
new TextFilter(
"x",
TextFilter.Operator.EQUALS,
"unfinished",
false),
List.of(),
FilterColumn.Checklist.DISABLED));
var popup =
new FilterPopup(
opener,
editor,
FilterPopup.Options.defaults(),
c -> {},
c -> {});
popup.show();
Alert alert =
new Alert(Alert.AlertType.INFORMATION, "Owned dialog", ButtonType.OK);
alert.initOwner(stage);
try {
manager.select("dark");
assertTrue(popup.isOpen());
assertEquals(
"unfinished",
((TextField) editor.view().lookup("#operand")).getText());
assertTrue(
editor.view()
.getScene()
.getStylesheets()
.containsAll(Theme.dark().stylesheets()));
assertFalse(
editor.view()
.getStylesheets()
.contains(Theme.light().stylesheets().getLast()));
ComboBox<?> chooser = (ComboBox<?>) editor.view().lookup("#operator");
chooser.show();
var nested =
Window.getWindows().stream()
.filter(
w ->
w instanceof PopupWindow p
&& p.getOwnerWindow()
== editor.view()
.getScene()
.getWindow())
.toList();
assertFalse(nested.isEmpty());
manager.select("high-contrast");
for (var w : nested)
assertTrue(
w.getScene()
.getStylesheets()
.containsAll(Theme.highContrast().stylesheets()));
chooser.hide();
popup.close();
alert.show();
assertTrue(
alert.getDialogPane()
.getScene()
.getStylesheets()
.containsAll(Theme.highContrast().stylesheets()));
manager.select("dark");
assertTrue(
alert.getDialogPane()
.getScene()
.getStylesheets()
.containsAll(Theme.dark().stylesheets()));
manager.select("high-contrast");
Stage future = new Stage();
future.initOwner(stage);
future.setScene(new Scene(new VBox(new Label("Future"))));
future.show();
assertTrue(
future.getScene()
.getStylesheets()
.containsAll(Theme.highContrast().stylesheets()));
future.close();
assertFalse(
future.getScene()
.getStylesheets()
.contains(Theme.highContrast().stylesheets().getLast()));
} finally {
alert.close();
popup.close();
stage.close();
manager.close();
}
});
}
@Test
void dockingFloatingWindowsInheritWithoutChangingWindowOwnership() throws Exception {
DataGridTest.fx(
() -> {
Stage stage = new Stage();
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
stage.setScene(new Scene(pane, 600, 400));
var themes = new ThemeManager();
themes.register(stage.getScene());
themes.select("dark");
var docking = DockingManager.attach(stage, pane, new DockingOptions());
Dockable item =
new Dockable(new DockableId("example"), new TextArea("Keep this edit"));
docking.open(item, DockTarget.area("editors"));
stage.show();
try {
docking.move(item.getId(), DockTarget.floating());
Scene floating = item.getContent().getScene();
assertTrue(
floating.getStylesheets().containsAll(Theme.dark().stylesheets()));
themes.select("high-contrast");
assertTrue(
floating.getStylesheets()
.containsAll(Theme.highContrast().stylesheets()));
assertEquals("Keep this edit", ((TextArea) item.getContent()).getText());
} finally {
for (var w : List.copyOf(Window.getWindows()))
if (w != stage
&& w.getScene() != null
&& w.getScene()
.getStylesheets()
.contains(Theme.highContrast().stylesheets().getLast()))
w.hide();
stage.hide();
themes.close();
}
});
}
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1"><TextField fx:id="value" accessibleText="Custom prefix"/></VBox>
@@ -0,0 +1 @@
.neitzel-theme .button { -fx-background-radius: 9; }
+7
View File
@@ -0,0 +1,7 @@
# Gson helpers
This module supplies existing Gson configuration/type adapters and optional DataGrid setup JSON support.
`de.neitzel.gson.grid.GridSetupJson` encodes explicit format-version-1 documents with independently versioned filter codecs. It depends on neutral `data-grid` contracts, not JavaFX. See [saved setups](../fx/docs/saved-setups.md) for schema behavior, custom codecs and application-owned storage. The `fx` and `data-grid` modules do not depend on this JSON implementation.
Use the repository's declared Java 25/Maven wrapper baseline. Run the Gson tests and affected data-grid/FX integration tests when changing the saved setup schema.
+1
View File
@@ -24,6 +24,7 @@
</properties>
<dependencies>
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
@@ -0,0 +1,379 @@
package de.neitzel.gson.grid;
import com.google.gson.*;
import com.google.gson.stream.*;
import de.neitzel.grid.*;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
/** Explicit versioned schema. Never serializes Java classes, row data, approval or credentials. */
public final class GridSetupJson {
public interface FilterCodec {
String typeId();
int version();
default Set<Integer> readableVersions() {
return Set.of(version());
}
JsonObject encode(FilterCondition condition);
FilterCondition decode(String columnId, int version, JsonObject data);
}
private final Map<String, FilterCodec> codecs = new LinkedHashMap<>();
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
public GridSetupJson() {
for (String id :
List.of("neitzel.text", "neitzel.number", "neitzel.missing", "neitzel.values"))
register(new BuiltIn(id));
}
public void register(FilterCodec codec) {
Objects.requireNonNull(codec);
if (codec.typeId() == null || codec.typeId().isBlank() || codec.version() < 1)
throw new IllegalArgumentException("Invalid codec identity/version");
if (codecs.putIfAbsent(codec.typeId(), codec) != null)
throw new IllegalArgumentException("Duplicate filter codec: " + codec.typeId());
}
private FilterCodec codec(String id) {
var codec = codecs.get(id);
if (codec == null)
throw new IllegalArgumentException("Register a persistence codec for filter: " + id);
return codec;
}
public String encode(GridSetup setup) {
if (setup.formatVersion() != 1)
throw new IllegalArgumentException("Unsupported setup format version");
JsonObject root = new JsonObject();
root.addProperty("formatVersion", 1);
root.addProperty("definitionId", setup.definitionId());
root.addProperty("definitionVersion", setup.definitionVersion());
JsonArray columns = new JsonArray();
for (var c : setup.columns()) {
if (c.type().equals("unspecified"))
throw new IllegalArgumentException("Declare column type before saving: " + c.id());
JsonObject column = new JsonObject();
column.addProperty("id", c.id());
column.addProperty("type", c.type());
JsonObject width = new JsonObject();
width.addProperty(
"kind", c.width() instanceof ColumnWidth.Default ? "default" : "explicit");
if (c.width() instanceof ColumnWidth.Explicit explicit)
width.addProperty("value", explicit.value());
column.add("width", width);
columns.add(column);
}
root.add("columns", columns);
JsonArray sort = new JsonArray();
for (var s : setup.sort()) {
JsonObject item = new JsonObject();
item.addProperty("column", s.columnId());
item.addProperty("direction", s.direction().name());
sort.add(item);
}
root.add("sort", sort);
JsonArray filters = new JsonArray();
for (var filter : setup.filters()) {
var codec = codec(filter.typeId());
JsonObject item = new JsonObject();
item.addProperty("type", filter.typeId());
item.addProperty("version", codec.version());
item.addProperty("column", filter.columnId());
item.add(
"data",
Objects.requireNonNull(codec.encode(filter), "Codec returned no payload"));
filters.add(item);
}
root.add("filters", filters);
JsonObject page = new JsonObject();
page.addProperty("mode", setup.page() instanceof PageRequest.All ? "all" : "paged");
if (setup.page() instanceof PageRequest.Paged p) page.addProperty("size", p.pageSize());
root.add("page", page);
return gson.toJson(root);
}
public GridSetup decode(String json) {
try (var reader = new JsonReader(new StringReader(Objects.requireNonNull(json)))) {
reader.setStrictness(Strictness.STRICT);
reader.setNestingLimit(64);
JsonObject root = object(read(reader));
if (reader.peek() != JsonToken.END_DOCUMENT)
throw new IllegalArgumentException("Trailing JSON content");
keys(
root,
"formatVersion",
"definitionId",
"definitionVersion",
"columns",
"sort",
"filters",
"page");
int format = integer(root, "formatVersion");
if (format != 1)
throw new IllegalArgumentException("Unsupported setup format version: " + format);
List<GridSetup.ColumnState> columns = new ArrayList<>();
for (var entry : array(root, "columns")) {
var c = object(entry);
keys(c, "id", "type", "width");
var w = object(required(c, "width"));
ColumnWidth width;
switch (string(w, "kind")) {
case "default" -> {
keys(w, "kind");
width = new ColumnWidth.Default();
}
case "explicit" -> {
keys(w, "kind", "value");
width = new ColumnWidth.Explicit(number(w, "value").doubleValue());
}
default -> throw new IllegalArgumentException("Unknown width kind");
}
columns.add(new GridSetup.ColumnState(string(c, "id"), string(c, "type"), width));
}
List<SortKey> sort = new ArrayList<>();
for (var entry : array(root, "sort")) {
var s = object(entry);
keys(s, "column", "direction");
sort.add(
new SortKey(
string(s, "column"),
SortKey.Direction.valueOf(string(s, "direction"))));
}
List<FilterCondition> filters = new ArrayList<>();
for (var entry : array(root, "filters")) {
var f = object(entry);
keys(f, "type", "version", "column", "data");
String type = string(f, "type"), column = string(f, "column");
int version = integer(f, "version");
var codec = codec(type);
if (!codec.readableVersions().contains(version))
throw new IllegalArgumentException(
"Unsupported codec version " + version + " for " + type);
var condition =
Objects.requireNonNull(
codec.decode(column, version, object(required(f, "data"))));
if (!type.equals(condition.typeId()) || !column.equals(condition.columnId()))
throw new IllegalArgumentException("Codec changed filter identity");
filters.add(condition);
}
var p = object(required(root, "page"));
PageRequest page;
switch (string(p, "mode")) {
case "all" -> {
keys(p, "mode");
page = new PageRequest.All();
}
case "paged" -> {
keys(p, "mode", "size");
page = new PageRequest.Paged(0, integer(p, "size"));
}
default -> throw new IllegalArgumentException("Unknown page mode");
}
return new GridSetup(
format,
string(root, "definitionId"),
integer(root, "definitionVersion"),
columns,
sort,
filters,
page);
} catch (IOException | IllegalStateException | ArithmeticException error) {
throw new IllegalArgumentException("Invalid saved setup: " + error.getMessage(), error);
}
}
private static JsonElement read(JsonReader reader) throws IOException {
return switch (reader.peek()) {
case BEGIN_OBJECT -> {
reader.beginObject();
var object = new JsonObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (object.has(name))
throw new IllegalArgumentException("Duplicate JSON property: " + name);
object.add(name, read(reader));
}
reader.endObject();
yield object;
}
case BEGIN_ARRAY -> {
reader.beginArray();
var array = new JsonArray();
while (reader.hasNext()) array.add(read(reader));
reader.endArray();
yield array;
}
case STRING -> new JsonPrimitive(reader.nextString());
case NUMBER -> new JsonPrimitive(new BigDecimal(reader.nextString()));
case BOOLEAN -> new JsonPrimitive(reader.nextBoolean());
case NULL -> {
reader.nextNull();
yield JsonNull.INSTANCE;
}
default ->
throw new IllegalArgumentException("Unexpected JSON token: " + reader.peek());
};
}
private static void keys(JsonObject o, String... names) {
if (!o.keySet().equals(Set.of(names)))
throw new IllegalArgumentException(
"Expected properties " + Arrays.toString(names) + ", found " + o.keySet());
}
private static JsonElement required(JsonObject o, String name) {
var v = o.get(name);
if (v == null || v.isJsonNull())
throw new IllegalArgumentException("Missing property: " + name);
return v;
}
private static JsonObject object(JsonElement v) {
if (!v.isJsonObject()) throw new IllegalArgumentException("Expected JSON object");
return v.getAsJsonObject();
}
private static JsonArray array(JsonObject o, String name) {
var v = required(o, name);
if (!v.isJsonArray()) throw new IllegalArgumentException("Expected array: " + name);
return v.getAsJsonArray();
}
private static String string(JsonObject o, String name) {
var v = required(o, name);
if (!v.isJsonPrimitive() || !v.getAsJsonPrimitive().isString())
throw new IllegalArgumentException("Expected string: " + name);
return v.getAsString();
}
private static BigDecimal number(JsonObject o, String name) {
var v = required(o, name);
if (!v.isJsonPrimitive() || !v.getAsJsonPrimitive().isNumber())
throw new IllegalArgumentException("Expected number: " + name);
return v.getAsBigDecimal();
}
private static int integer(JsonObject o, String name) {
return number(o, name).intValueExact();
}
private static boolean bool(JsonObject o, String name) {
var v = required(o, name);
if (!v.isJsonPrimitive() || !v.getAsJsonPrimitive().isBoolean())
throw new IllegalArgumentException("Expected boolean: " + name);
return v.getAsBoolean();
}
private record BuiltIn(String typeId) implements FilterCodec {
public int version() {
return 1;
}
public JsonObject encode(FilterCondition condition) {
JsonObject data = new JsonObject();
switch (condition) {
case TextFilter f -> {
data.addProperty("operator", f.operator().name());
data.addProperty("operand", f.operand());
data.addProperty("caseSensitive", f.caseSensitive());
}
case NumericFilter f -> {
data.addProperty("operator", f.operator().name());
data.addProperty("operand", f.operand().toString());
if (f.upper() != null) data.addProperty("upper", f.upper().toString());
}
case MissingFilter f -> data.addProperty("missing", f.missing());
case ValueFilter f -> {
data.addProperty("includeMissing", f.includeMissing());
var values = new JsonArray();
for (var v : f.values()) values.add(value(v));
data.add("values", values);
}
default ->
throw new IllegalArgumentException(
"Wrong built-in condition class: " + condition.typeId());
}
return data;
}
public FilterCondition decode(String column, int version, JsonObject d) {
return switch (typeId) {
case "neitzel.text" -> {
keys(d, "operator", "operand", "caseSensitive");
yield new TextFilter(
column,
TextFilter.Operator.valueOf(string(d, "operator")),
string(d, "operand"),
bool(d, "caseSensitive"));
}
case "neitzel.number" -> {
var op = NumericFilter.Operator.valueOf(string(d, "operator"));
if (op == NumericFilter.Operator.RANGE) keys(d, "operator", "operand", "upper");
else keys(d, "operator", "operand");
yield new NumericFilter(
column,
op,
new BigDecimal(string(d, "operand")),
op == NumericFilter.Operator.RANGE
? new BigDecimal(string(d, "upper"))
: null);
}
case "neitzel.missing" -> {
keys(d, "missing");
yield new MissingFilter(column, bool(d, "missing"));
}
case "neitzel.values" -> {
keys(d, "includeMissing", "values");
Set<FilterValue> values = new LinkedHashSet<>();
for (var v : array(d, "values"))
if (!values.add(value(object(v))))
throw new IllegalArgumentException("Duplicate checklist value");
yield new ValueFilter(column, values, bool(d, "includeMissing"));
}
default -> throw new IllegalArgumentException("Unknown built-in codec");
};
}
private static JsonObject value(FilterValue value) {
var o = new JsonObject();
switch (value) {
case FilterValue.Text v -> {
o.addProperty("type", "text");
o.addProperty("value", v.value());
}
case FilterValue.IntegerValue v -> {
o.addProperty("type", "integer");
o.addProperty("value", Long.toString(v.value()));
}
case FilterValue.Decimal v -> {
o.addProperty("type", "decimal");
o.addProperty("value", v.value().toString());
}
case FilterValue.BooleanValue v -> {
o.addProperty("type", "boolean");
o.addProperty("value", v.value());
}
}
return o;
}
private static FilterValue value(JsonObject o) {
keys(o, "type", "value");
return switch (string(o, "type")) {
case "text" -> new FilterValue.Text(string(o, "value"));
case "integer" -> new FilterValue.IntegerValue(Long.parseLong(string(o, "value")));
case "decimal" -> new FilterValue.Decimal(new BigDecimal(string(o, "value")));
case "boolean" -> new FilterValue.BooleanValue(bool(o, "value"));
default -> throw new IllegalArgumentException("Unknown checklist scalar type");
};
}
}
}

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