diff --git a/README.md b/README.md index d05fb05..e22eb2b 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/data-grid-jdbc/README.md b/data-grid-jdbc/README.md new file mode 100644 index 0000000..7ec6ea1 --- /dev/null +++ b/data-grid-jdbc/README.md @@ -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( + 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. diff --git a/data-grid-jdbc/pom.xml b/data-grid-jdbc/pom.xml new file mode 100644 index 0000000..5097444 --- /dev/null +++ b/data-grid-jdbc/pom.xml @@ -0,0 +1,5 @@ + +4.0.0de.neitzel.libneitzellib1.0-SNAPSHOT +data-grid-jdbcOptional mapped JDBC grid source +de.neitzel.libdata-grid${project.version} +com.h2databaseh22.5.252test diff --git a/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcColumn.java b/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcColumn.java new file mode 100644 index 0000000..962302c --- /dev/null +++ b/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcColumn.java @@ -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); + } +} diff --git a/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcDialect.java b/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcDialect.java new file mode 100644 index 0000000..fd6d4fc --- /dev/null +++ b/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcDialect.java @@ -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"; + } + }; + } +} diff --git a/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcGridSource.java b/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcGridSource.java new file mode 100644 index 0000000..76a2f92 --- /dev/null +++ b/data-grid-jdbc/src/main/java/de/neitzel/grid/jdbc/JdbcGridSource.java @@ -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 implements GridSource { + @FunctionalInterface + public interface RowMapper { + GridRow 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 columns; + private final RowMapper mapper; + private final int timeoutSeconds; + private final SourceCapabilities capabilities; + + public JdbcGridSource( + DataSource dataSource, + Executor executor, + JdbcDialect dialect, + String table, + String key, + List columns, + RowMapper 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(); + var selected = new LinkedHashSet(); + 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 query(GridQuery query) { + return query(query, QueryOptions.defaults()); + } + + public QueryExecution query(GridQuery query, QueryOptions options) { + Objects.requireNonNull(query); + Objects.requireNonNull(options); + var execution = new Execution(); + try { + capabilities.validate(query.page()); + var parameters = new ArrayList(); + String where = where(query.filters(), parameters); + var order = new ArrayList(); + 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 execute( + Execution execution, + GridQuery query, + QueryOptions options, + String where, + String sql, + List 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>(); + 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 filters, List args) { + if (filters.isEmpty()) return ""; + return " WHERE " + + String.join( + " AND ", filters.stream().map(f -> "(" + compile(f, args) + ")").toList()); + } + + private String compile(FilterCondition f, List 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(); + 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 { + final CompletableFuture> result = new CompletableFuture<>(); + final AtomicBoolean cancelled = new AtomicBoolean(); + final AtomicReference active = new AtomicReference<>(); + + public CompletionStage> 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 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; + } + } + } +} diff --git a/data-grid/README.md b/data-grid/README.md new file mode 100644 index 0000000..e536c5d --- /dev/null +++ b/data-grid/README.md @@ -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` accepts a collection supplier, stable-key function and comparator, explicit `MemoryColumn` 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). diff --git a/data-grid/pom.xml b/data-grid/pom.xml new file mode 100644 index 0000000..a6bb952 --- /dev/null +++ b/data-grid/pom.xml @@ -0,0 +1,6 @@ + + 4.0.0 + de.neitzel.libneitzellib1.0-SNAPSHOT + data-grid + Toolkit-independent filter, query and grid setup contracts + diff --git a/data-grid/src/main/java/de/neitzel/grid/AllRowsConfirmationRequired.java b/data-grid/src/main/java/de/neitzel/grid/AllRowsConfirmationRequired.java new file mode 100644 index 0000000..a301e24 --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/AllRowsConfirmationRequired.java @@ -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; + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/Checks.java b/data-grid/src/main/java/de/neitzel/grid/Checks.java new file mode 100644 index 0000000..275302a --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/Checks.java @@ -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; + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/ColumnWidth.java b/data-grid/src/main/java/de/neitzel/grid/ColumnWidth.java new file mode 100644 index 0000000..a90068d --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/ColumnWidth.java @@ -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"); + } + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/FilterCandidates.java b/data-grid/src/main/java/de/neitzel/grid/FilterCandidates.java new file mode 100644 index 0000000..0b0552c --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/FilterCandidates.java @@ -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 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 candidates, boolean hasMore) { + public Batch { + candidates = List.copyOf(candidates); + } + } + + public interface Provider { + Set scopes(); + + Session open(Context context); + } + + public interface Session extends AutoCloseable { + CompletionStage load(Request request); + + @Override + void close(); + } + + /** Captures current-page values at open, never claims source-wide completeness. */ + public static Provider currentPage(Supplier> 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 scopes, + Function>> capture, + Executor executor) { + Set supported = Set.copyOf(scopes); + Objects.requireNonNull(capture); + Objects.requireNonNull(executor); + return new Provider() { + public Set 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> pending = new HashSet<>(); + + public synchronized CompletionStage 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(); + pending.add(future); + try { + executor.execute( + () -> { + try { + if (future.isDone()) return; + Map 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(); + } + }; + } + }; + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/FilterCapabilities.java b/data-grid/src/main/java/de/neitzel/grid/FilterCapabilities.java new file mode 100644 index 0000000..6ca57ba --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/FilterCapabilities.java @@ -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 adapters) { + public FilterCapabilities { + adapters = Set.copyOf(adapters); + adapters.forEach(Checks::id); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/FilterCondition.java b/data-grid/src/main/java/de/neitzel/grid/FilterCondition.java new file mode 100644 index 0000000..04e9608 --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/FilterCondition.java @@ -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(); +} diff --git a/data-grid/src/main/java/de/neitzel/grid/FilterValue.java b/data-grid/src/main/java/de/neitzel/grid/FilterValue.java new file mode 100644 index 0000000..9145eaf --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/FilterValue.java @@ -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 {} +} diff --git a/data-grid/src/main/java/de/neitzel/grid/GridCoordinator.java b/data-grid/src/main/java/de/neitzel/grid/GridCoordinator.java new file mode 100644 index 0000000..0a848b0 --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/GridCoordinator.java @@ -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 implements AutoCloseable { + public enum Phase { + IDLE, + GUARD, + LOADING, + CONFIRMATION, + READY, + ERROR, + CLOSED + } + + public record State( + long generation, + GridQuery requested, + GridQuery displayed, + PageResult result, + Phase phase, + Throwable error, + long sourceVersion) {} + + private final Thread owner = Thread.currentThread(); + private final Executor dispatch; + private final Consumer> observer; + private final Consumer> publisher; + private GridSource source; + private GridSource requestedSource; + private GridSource.QueryExecution execution; + private State 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 restoreBefore; + private Consumer> requestPublisher; + private Function> guard = + q -> CompletableFuture.completedFuture(true); + private BiFunction> confirmation = + (q, n) -> + CompletableFuture.failedFuture( + new IllegalStateException("No All confirmation handler configured")); + + public GridCoordinator( + GridSource source, + Executor dispatch, + Consumer> observer, + Consumer> 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 state() { + return state; + } + + public SourceCapabilities capabilities() { + check(); + return requestedSource.capabilities(); + } + + public String filterExecutionId() { + check(); + return requestedSource.filterExecutionId(); + } + + public void validateFilters(List filters) { + check(); + filters.forEach(requestedSource::validateFilter); + } + + public void setGuard(Function> guard) { + check(); + this.guard = Objects.requireNonNull(guard); + } + + public void setConfirmation( + BiFunction> 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 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> 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 replacement, + GridQuery query, + Runnable afterGuard, + Consumer> 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( + 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 target, + GridQuery query, + long token, + boolean approved, + boolean corrected, + State 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 void await( + CompletionStage stage, long token, BiConsumer callback) { + stage.whenComplete( + (value, failure) -> + dispatch.execute( + () -> { + checkThread(); + if (current(token)) callback.accept(value, failure); + })); + } + + private void restore(State 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(); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/GridDefinition.java b/data-grid/src/main/java/de/neitzel/grid/GridDefinition.java new file mode 100644 index 0000000..593648c --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/GridDefinition.java @@ -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 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 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 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> migrations, + SourceCapabilities source, + Consumer 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 definitions = new LinkedHashMap<>(); + columns.forEach(c -> definitions.put(c.id(), c)); + List next = new ArrayList<>(); + List adjustments = new ArrayList<>(); + Set 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); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/GridQuery.java b/data-grid/src/main/java/de/neitzel/grid/GridQuery.java new file mode 100644 index 0000000..4482d0d --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/GridQuery.java @@ -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 filters, List sort, PageRequest page) { + public GridQuery { + filters = List.copyOf(filters); + sort = List.copyOf(sort); + Objects.requireNonNull(page); + Set 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"); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/GridRow.java b/data-grid/src/main/java/de/neitzel/grid/GridRow.java new file mode 100644 index 0000000..fe7e22b --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/GridRow.java @@ -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 key, T model) { + public GridRow { + Objects.requireNonNull(key); + Objects.requireNonNull(model); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/GridSetup.java b/data-grid/src/main/java/de/neitzel/grid/GridSetup.java new file mode 100644 index 0000000..d9247ad --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/GridSetup.java @@ -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 columns, + List sort, + List 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 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"); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/GridSource.java b/data-grid/src/main/java/de/neitzel/grid/GridSource.java new file mode 100644 index 0000000..8fd586a --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/GridSource.java @@ -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 { + SourceCapabilities capabilities(); + + QueryExecution 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 query(GridQuery query, QueryOptions options) { + java.util.Objects.requireNonNull(options); + if (query.page() instanceof PageRequest.All) { + var failure = + java.util.concurrent.CompletableFuture.>failedFuture( + new UnsupportedOperationException( + "Source does not support guarded All execution")); + return new QueryExecution<>() { + public CompletionStage> result() { + return failure; + } + + public void cancel() {} + }; + } + return query(query); + } + + /** + * Cancellation is best-effort; coordinators must reject superseded completions independently. + */ + interface QueryExecution { + CompletionStage> result(); + + void cancel(); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/MemoryColumn.java b/data-grid/src/main/java/de/neitzel/grid/MemoryColumn.java new file mode 100644 index 0000000..88d00ef --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/MemoryColumn.java @@ -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( + String id, + Kind kind, + Function read, + Map>> customFilters) { + public enum Kind { + TEXT, + INTEGER, + DECIMAL, + BOOLEAN + } + + public MemoryColumn(String id, Kind kind, Function 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); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/MemoryGridSource.java b/data-grid/src/main/java/de/neitzel/grid/MemoryGridSource.java new file mode 100644 index 0000000..c52b360 --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/MemoryGridSource.java @@ -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 implements GridSource { + private final Supplier> data; + private final Function key; + private final Comparator keyOrder; + private final Map> columns; + private final Executor executor; + private final SourceCapabilities capabilities; + + private record Snapshot(K key, T model, Map values) {} + + public MemoryGridSource( + Supplier> data, + Function key, + Comparator keyOrder, + List> 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> 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 query(GridQuery query) { + return query(query, QueryOptions.defaults()); + } + + public QueryExecution query(GridQuery query, QueryOptions options) { + CompletableFuture> result = new CompletableFuture<>(); + AtomicBoolean cancelled = new AtomicBoolean(); + try { + Objects.requireNonNull(query); + Objects.requireNonNull(options); + capabilities.validate(query.page()); + List>> 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 = new ArrayList<>(); + Set 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 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> 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> 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> 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 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> snapshot = new ArrayList<>(); + for (T model : List.copyOf(data.get())) { + Map 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 column(String id) { + var column = columns.get(id); + if (column == null) throw new IllegalArgumentException("Unknown column: " + id); + return column; + } + + private Predicate compile(MemoryColumn 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"); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/MissingFilter.java b/data-grid/src/main/java/de/neitzel/grid/MissingFilter.java new file mode 100644 index 0000000..6aa1ae3 --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/MissingFilter.java @@ -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; + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/NumericFilter.java b/data-grid/src/main/java/de/neitzel/grid/NumericFilter.java new file mode 100644 index 0000000..670387b --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/NumericFilter.java @@ -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; + }; + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/PageRequest.java b/data-grid/src/main/java/de/neitzel/grid/PageRequest.java new file mode 100644 index 0000000..39b2e32 --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/PageRequest.java @@ -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 {} +} diff --git a/data-grid/src/main/java/de/neitzel/grid/PageResult.java b/data-grid/src/main/java/de/neitzel/grid/PageResult.java new file mode 100644 index 0000000..888b81d --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/PageResult.java @@ -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( + PageRequest request, List> rows, OptionalLong total, boolean hasNext) { + public PageResult { + Objects.requireNonNull(request); + rows = List.copyOf(rows); + Objects.requireNonNull(total); + Set 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"); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/QueryOptions.java b/data-grid/src/main/java/de/neitzel/grid/QueryOptions.java new file mode 100644 index 0000000..38c27ba --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/QueryOptions.java @@ -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); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/SortKey.java b/data-grid/src/main/java/de/neitzel/grid/SortKey.java new file mode 100644 index 0000000..192cf3e --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/SortKey.java @@ -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); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/SourceCapabilities.java b/data-grid/src/main/java/de/neitzel/grid/SourceCapabilities.java new file mode 100644 index 0000000..ad53345 --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/SourceCapabilities.java @@ -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"); + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/TextFilter.java b/data-grid/src/main/java/de/neitzel/grid/TextFilter.java new file mode 100644 index 0000000..947936f --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/TextFilter.java @@ -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); + }; + } +} diff --git a/data-grid/src/main/java/de/neitzel/grid/ValueFilter.java b/data-grid/src/main/java/de/neitzel/grid/ValueFilter.java new file mode 100644 index 0000000..aa4b024 --- /dev/null +++ b/data-grid/src/main/java/de/neitzel/grid/ValueFilter.java @@ -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 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); + } +} diff --git a/data-grid/src/test/java/de/neitzel/grid/FilterCandidatesTest.java b/data-grid/src/test/java/de/neitzel/grid/FilterCandidatesTest.java new file mode 100644 index 0000000..0b55823 --- /dev/null +++ b/data-grid/src/test/java/de/neitzel/grid/FilterCandidatesTest.java @@ -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(); + 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( + () -> 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))); + } +} diff --git a/data-grid/src/test/java/de/neitzel/grid/GridContractsTest.java b/data-grid/src/test/java/de/neitzel/grid/GridContractsTest.java new file mode 100644 index 0000000..d109b33 --- /dev/null +++ b/data-grid/src/test/java/de/neitzel/grid/GridContractsTest.java @@ -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(); + 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())); + } +} diff --git a/data-grid/src/test/java/de/neitzel/grid/GridCoordinatorTest.java b/data-grid/src/test/java/de/neitzel/grid/GridCoordinatorTest.java new file mode 100644 index 0000000..e381ef6 --- /dev/null +++ b/data-grid/src/test/java/de/neitzel/grid/GridCoordinatorTest.java @@ -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 { + List>> futures = new ArrayList<>(); + List queries = new ArrayList<>(); + List options = new ArrayList<>(); + int cancellations; + + public SourceCapabilities capabilities() { + return new SourceCapabilities(true, true, 250); + } + + public QueryExecution query(GridQuery q) { + return query(q, QueryOptions.defaults()); + } + + public QueryExecution query(GridQuery q, QueryOptions o) { + queries.add(q); + options.add(o); + var f = new CompletableFuture>(); + futures.add(f); + return new QueryExecution<>() { + public CompletionStage> 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 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 callbacks = new ArrayDeque<>(); + List> published = new ArrayList<>(); + GridCoordinator 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 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 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(); + var coordinator = + new GridCoordinator(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(); + var holder = new AtomicReference>(); + var jumped = new AtomicBoolean(); + var coordinator = + new GridCoordinator( + 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(); + 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(); + var holder = new AtomicReference>(); + var coordinator = + new GridCoordinator( + 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()); + } + } +} diff --git a/data-grid/src/test/java/de/neitzel/grid/GridDefinitionTest.java b/data-grid/src/test/java/de/neitzel/grid/GridDefinitionTest.java new file mode 100644 index 0000000..84e92e4 --- /dev/null +++ b/data-grid/src/test/java/de/neitzel/grid/GridDefinitionTest.java @@ -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"); + })); + } +} diff --git a/data-grid/src/test/java/de/neitzel/grid/MemoryGridSourceTest.java b/data-grid/src/test/java/de/neitzel/grid/MemoryGridSourceTest.java new file mode 100644 index 0000000..be0ca8b --- /dev/null +++ b/data-grid/src/test/java/de/neitzel/grid/MemoryGridSourceTest.java @@ -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 source(List 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 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(); + 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(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + MemoryColumn 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( + () -> + 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(); + } + } +} diff --git a/fx-example/README.md b/fx-example/README.md index f927561..acb8632 100644 --- a/fx-example/README.md +++ b/fx-example/README.md @@ -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: diff --git a/fx-example/docs/product-grid.md b/fx-example/docs/product-grid.md new file mode 100644 index 0000000..8b02961 --- /dev/null +++ b/fx-example/docs/product-grid.md @@ -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. diff --git a/fx-example/docs/theme-gallery.md b/fx-example/docs/theme-gallery.md new file mode 100644 index 0000000..984d6e5 --- /dev/null +++ b/fx-example/docs/theme-gallery.md @@ -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. diff --git a/fx-example/pom.xml b/fx-example/pom.xml index 6637457..051c372 100644 --- a/fx-example/pom.xml +++ b/fx-example/pom.xml @@ -21,6 +21,8 @@ + de.neitzel.libdata-grid-jdbc${project.version} + com.h2databaseh22.5.252 de.neitzel.lib fx diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/DemoResources.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/DemoResources.java new file mode 100644 index 0000000..43eed57 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/DemoResources.java @@ -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; + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/DiagnosticSource.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/DiagnosticSource.java new file mode 100644 index 0000000..dbcbdf3 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/DiagnosticSource.java @@ -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 { + private final GridSource delegate; + private final ScheduledExecutorService clock; + private final Consumer log; + private final Consumer domainValidation; + private final AtomicLong ids = new AtomicLong(); + private volatile long delay; + private volatile boolean fail, late; + + public DiagnosticSource( + GridSource delegate, + ScheduledExecutorService clock, + Consumer log, + Consumer 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 query(GridQuery query) { + return query(query, QueryOptions.defaults()); + } + + public QueryExecution 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>(); + 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> 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> result() { + return result; + } + + public void cancel() { + cancelled.set(true); + log.accept("Request " + id + " cancellation requested"); + if (!ignoreCancel) { + execution.cancel(); + result.cancel(false); + } + } + }; + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/LocalNameLength.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/LocalNameLength.java new file mode 100644 index 0000000..35e3b55 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/LocalNameLength.java @@ -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"; + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/PricePresetEditor.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/PricePresetEditor.java new file mode 100644 index 0000000..023bd15 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/PricePresetEditor.java @@ -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() {} +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/Product.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/Product.java new file mode 100644 index 0000000..c356b78 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/Product.java @@ -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) {} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductCatalog.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductCatalog.java new file mode 100644 index 0000000..c0a8ca0 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductCatalog.java @@ -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 memory; + public final JdbcGridSource jdbc; + private List 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 fixtures(int size) { + var rows = new ArrayList(); + 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 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> 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 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 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 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 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); + } + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridApp.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridApp.java new file mode 100644 index 0000000..c0e4dcd --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridApp.java @@ -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); + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridDemo.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridDemo.java new file mode 100644 index 0000000..5428c1f --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridDemo.java @@ -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 grid; + public final ThemeManager themes = new ThemeManager(); + public final ComboBox 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(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); + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridMain.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridMain.java new file mode 100644 index 0000000..168ddc9 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductGridMain.java @@ -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); + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductRow.java b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductRow.java new file mode 100644 index 0000000..03bab31 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/grid/ProductRow.java @@ -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(); + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGallery.java b/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGallery.java new file mode 100644 index 0000000..9a793fe --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGallery.java @@ -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 standard = new TableView<>(); + public final DataGrid grid; + private final List floating = new ArrayList<>(); + + public ThemeGallery() { + setSpacing(12); + setStyle("-fx-padding: 18;"); + getStyleClass().add("theme-gallery"); + var picker = new ComboBox(); + 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 combo = new ComboBox<>(); + combo.getItems().addAll("Choose a value", "Alpha", "Beta"); + combo.getSelectionModel().selectFirst(); + TableColumn 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( + () -> 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(); + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGalleryApp.java b/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGalleryApp.java new file mode 100644 index 0000000..5e47d2e --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGalleryApp.java @@ -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(); + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGalleryMain.java b/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGalleryMain.java new file mode 100644 index 0000000..0980555 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/theme/ThemeGalleryMain.java @@ -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); + } +} diff --git a/fx-example/src/main/resources/de/neitzel/fx/example/grid/PricePresetEditor.fxml b/fx-example/src/main/resources/de/neitzel/fx/example/grid/PricePresetEditor.fxml new file mode 100644 index 0000000..ef733ec --- /dev/null +++ b/fx-example/src/main/resources/de/neitzel/fx/example/grid/PricePresetEditor.fxml @@ -0,0 +1,5 @@ + + + + diff --git a/fx-example/src/main/resources/de/neitzel/fx/example/grid/ProductRow.fxml b/fx-example/src/main/resources/de/neitzel/fx/example/grid/ProductRow.fxml new file mode 100644 index 0000000..a79665c --- /dev/null +++ b/fx-example/src/main/resources/de/neitzel/fx/example/grid/ProductRow.fxml @@ -0,0 +1,5 @@ + + + + diff --git a/fx-example/src/test/java/de/neitzel/fx/example/grid/DemoResourcesTest.java b/fx-example/src/test/java/de/neitzel/fx/example/grid/DemoResourcesTest.java new file mode 100644 index 0000000..1155080 --- /dev/null +++ b/fx-example/src/test/java/de/neitzel/fx/example/grid/DemoResourcesTest.java @@ -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(); + 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(); + } + } +} diff --git a/fx-example/src/test/java/de/neitzel/fx/example/grid/JdbcProductTest.java b/fx-example/src/test/java/de/neitzel/fx/example/grid/JdbcProductTest.java new file mode 100644 index 0000000..1716709 --- /dev/null +++ b/fx-example/src/test/java/de/neitzel/fx/example/grid/JdbcProductTest.java @@ -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 result(GridSource source, GridQuery q) + throws Exception { + return source.query(q, new QueryOptions(1000, true)) + .result() + .toCompletableFuture() + .get(20, TimeUnit.SECONDS); + } + + static GridQuery query(List filters, List sort, PageRequest page) { + return new GridQuery(filters, sort, page); + } + + void parity(List filters, List 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( + 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(); + var source = + new JdbcGridSource( + 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( + 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(); + 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 source( + Tracking tracking, JdbcGridSource.RowMapper 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 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 wrap(Class type, T target, InvocationHandler handler) { + return type.cast( + Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, handler)); + } + } +} diff --git a/fx-example/src/test/java/de/neitzel/fx/example/grid/ProductGridDemoTest.java b/fx-example/src/test/java/de/neitzel/fx/example/grid/ProductGridDemoTest.java new file mode 100644 index 0000000..da98005 --- /dev/null +++ b/fx-example/src/test/java/de/neitzel/fx/example/grid/ProductGridDemoTest.java @@ -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 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(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(); + 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(); + 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(); + 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(); + 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"); + } +} diff --git a/fx-example/src/test/java/de/neitzel/fx/example/theme/ThemeGalleryTest.java b/fx-example/src/test/java/de/neitzel/fx/example/theme/ThemeGalleryTest.java new file mode 100644 index 0000000..5f382cd --- /dev/null +++ b/fx-example/src/test/java/de/neitzel/fx/example/theme/ThemeGalleryTest.java @@ -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 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(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 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(); + var window = new AtomicReference(); + 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 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 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); + } + } +} diff --git a/fx/README.md b/fx/README.md index 68e860c..6379438 100644 --- a/fx/README.md +++ b/fx/README.md @@ -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` | diff --git a/fx/docs/data-grid.md b/fx/docs/data-grid.md new file mode 100644 index 0000000..2b9691b --- /dev/null +++ b/fx/docs/data-grid.md @@ -0,0 +1,45 @@ +# Local DataGrid and request coordination + +`DataGrid` 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( + () -> 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( + 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)` lets the application save/discard/block unfinished edits. `setAllConfirmation((query, count) -> CompletionStage)` 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). diff --git a/fx/docs/filter-editors.md b/fx/docs/filter-editors.md new file mode 100644 index 0000000..1df0c3b --- /dev/null +++ b/fx/docs/filter-editors.md @@ -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. diff --git a/fx/docs/saved-setups.md b/fx/docs/saved-setups.md new file mode 100644 index 0000000..9c10fb0 --- /dev/null +++ b/fx/docs/saved-setups.md @@ -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>` 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. diff --git a/fx/docs/table-results.md b/fx/docs/table-results.md new file mode 100644 index 0000000..1b499a8 --- /dev/null +++ b/fx/docs/table-results.md @@ -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 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. diff --git a/fx/docs/themes.md b/fx/docs/themes.md new file mode 100644 index 0000000..edd9ed4 --- /dev/null +++ b/fx/docs/themes.md @@ -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. diff --git a/fx/pom.xml b/fx/pom.xml index 82184e4..3cdc59f 100644 --- a/fx/pom.xml +++ b/fx/pom.xml @@ -44,6 +44,7 @@ + de.neitzel.libdata-grid${project.version} de.neitzel.lib core diff --git a/fx/scripts/filter-popup-probe.py b/fx/scripts/filter-popup-probe.py new file mode 100644 index 0000000..5ed5d87 --- /dev/null +++ b/fx/scripts/filter-popup-probe.py @@ -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)) diff --git a/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java b/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java index 66b6d96..93968b4 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java +++ b/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java @@ -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 closeHandler = event -> { event.consume(); requestFloatingWindowClose(windowId); diff --git a/fx/src/main/java/de/neitzel/fx/grid/filter/BuiltInFilterEditor.java b/fx/src/main/java/de/neitzel/fx/grid/filter/BuiltInFilterEditor.java new file mode 100644 index 0000000..b2e6974 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/grid/filter/BuiltInFilterEditor.java @@ -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 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 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 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(); + } + } +} diff --git a/fx/src/main/java/de/neitzel/fx/grid/filter/FilterColumn.java b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterColumn.java new file mode 100644 index 0000000..b40b281 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterColumn.java @@ -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); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditor.java b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditor.java new file mode 100644 index 0000000..4fb29bf --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditor.java @@ -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(); +} diff --git a/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditorContext.java b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditorContext.java new file mode 100644 index 0000000..02dd3cd --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditorContext.java @@ -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 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"); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditors.java b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditors.java new file mode 100644 index 0000000..deaae97 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterEditors.java @@ -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 conditionTypes, + Function 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 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 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; + } +} diff --git a/fx/src/main/java/de/neitzel/fx/grid/filter/FilterPopup.java b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterPopup.java new file mode 100644 index 0000000..c4e5609 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/grid/filter/FilterPopup.java @@ -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 validate, commit; + private final Options options; + private final Popup popup = new Popup(); + private final Label error = new Label(); + private final ReadOnlyObjectWrapper disposalFailure = + new ReadOnlyObjectWrapper<>(); + private final VBox root; + private boolean closed, reopening; + private final EventHandler ownerHidden = e -> close(); + private final ChangeListener detached = + (o, a, b) -> { + if (a != b) close(); + }; + + public FilterPopup( + Node opener, + FilterEditor editor, + Options options, + Consumer validate, + Consumer 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 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> choosers() { + List> found = new ArrayList<>(); + collect(editor.view(), found); + return found; + } + + private static void collect(Node node, List> 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"); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/theme/Theme.java b/fx/src/main/java/de/neitzel/fx/theme/Theme.java new file mode 100644 index 0000000..c4f7acf --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/theme/Theme.java @@ -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 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(); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/theme/ThemeManager.java b/fx/src/main/java/de/neitzel/fx/theme/ThemeManager.java new file mode 100644 index 0000000..d52b9f8 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/theme/ThemeManager.java @@ -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 themes = new LinkedHashMap<>(); + private final Map scenes = new LinkedHashMap<>(); + private final Map automatic = new IdentityHashMap<>(); + private final ReadOnlyObjectWrapper selected = + new ReadOnlyObjectWrapper<>(Theme.light()); + private final ReadOnlyObjectWrapper failure = new ReadOnlyObjectWrapper<>(); + private Consumer installationCheck = scene -> {}; + private boolean closed, switching; + private final ListChangeListener 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 selectedThemeProperty() { + return selected.getReadOnlyProperty(); + } + + public ReadOnlyObjectProperty failureProperty() { + return failure.getReadOnlyProperty(); + } + + public List 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 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> before = new LinkedHashMap<>(); + Map> 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 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 reserved() { + Set 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 managed = List.of(); + private Parent marked; + private boolean addedClass, disposed; + private final ChangeListener 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(); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/DataGrid.java b/fx/src/main/java/de/neitzel/fx/view/DataGrid.java new file mode 100644 index 0000000..794e92e --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/DataGrid.java @@ -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 extends VBox implements AutoCloseable { + private final Table table = new Table(); + private final TableResults renderer; + private final GridCoordinator coordinator; + private final ReadOnlyObjectWrapper> 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 pageSize = new ComboBox<>(); + private final GridQuery initial; + private final List columnDefinitions; + private GridDefinition setupDefinition; + private Map> setupMigrations = Map.of(); + private final ReadOnlyObjectWrapper> restorationAdjustments = + new ReadOnlyObjectWrapper<>(List.of()); + private final Map 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 filterDisposalFailure = + new ReadOnlyObjectWrapper<>(); + private boolean updating, closed; + private long visibleSourceVersion; + private Alert pendingAlert; + private long alertGeneration; + + public DataGrid( + List columns, + Function rowFactory, + GridSource 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> stateProperty() { + return state.getReadOnlyProperty(); + } + + public ReadOnlyObjectProperty selectedKeyProperty() { + return renderer.selectedKeyProperty(); + } + + public ReadOnlyObjectProperty 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> guard) { + check(); + coordinator.setGuard(guard); + } + + public void setAllConfirmation(BiFunction> handler) { + check(); + coordinator.setConfirmation(handler); + } + + public void setAllWarningThreshold(long count) { + check(); + coordinator.setAllWarningThreshold(count); + } + + public void setColumnOrder(List 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 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 source) { + check(); + closeFilter(); + var q = query(); + coordinator.request(source, new GridQuery(q.filters(), q.sort(), firstPage(q.page()))); + } + + public void setFilters(List 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 types, + Map> 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> 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 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> 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 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 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 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 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 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 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 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 confirmAll(GridQuery query, long count) { + CompletableFuture 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(); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/MessagePopup.java b/fx/src/main/java/de/neitzel/fx/view/MessagePopup.java index cca9c57..c2d5de7 100644 --- a/fx/src/main/java/de/neitzel/fx/view/MessagePopup.java +++ b/fx/src/main/java/de/neitzel/fx/view/MessagePopup.java @@ -6,38 +6,42 @@ import javafx.scene.control.Label; /** * Shows each newly added {@link Message} in a dialog when the developer asks. - *

- * The library shows nothing until {@link #showNewMessages(ViewModel)} is called. An in-place + * + *

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. - *

- * The dialog is shown with {@link Dialog#show()}, so the caller is not blocked. Messages + * + *

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 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); diff --git a/fx/src/main/java/de/neitzel/fx/view/ResultColumn.java b/fx/src/main/java/de/neitzel/fx/view/ResultColumn.java new file mode 100644 index 0000000..c2f670e --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/ResultColumn.java @@ -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"); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/ResultRow.java b/fx/src/main/java/de/neitzel/fx/view/ResultRow.java new file mode 100644 index 0000000..7824851 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/ResultRow.java @@ -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 fields, Runnable dispose) { + public ResultRow { + Objects.requireNonNull(root); + fields = Map.copyOf(fields); + Objects.requireNonNull(dispose); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/Table.java b/fx/src/main/java/de/neitzel/fx/view/Table.java index 70e05ab..3f67a0d 100644 --- a/fx/src/main/java/de/neitzel/fx/view/Table.java +++ b/fx/src/main/java/de/neitzel/fx/view/Table.java @@ -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 TableResults openResults(List definitions, + java.util.function.Function 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 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; } diff --git a/fx/src/main/java/de/neitzel/fx/view/TableResults.java b/fx/src/main/java/de/neitzel/fx/view/TableResults.java new file mode 100644 index 0000000..ac86b26 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/TableResults.java @@ -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 implements AutoCloseable { + private final HBox header; + private final VBox body; + private final Function factory; + private final Map definitions = new LinkedHashMap<>(); + private final Map widths = new LinkedHashMap<>(); + private List order; + private List> entries = List.of(); + private final ReadOnlyObjectWrapper selectedKey = new ReadOnlyObjectWrapper<>(); + private final ReadOnlyObjectWrapper selectedElement = new ReadOnlyObjectWrapper<>(); + private final ReadOnlyObjectWrapper disposalFailure = + new ReadOnlyObjectWrapper<>(); + private boolean closed; + private boolean rowsInteractive = true; + private Set filterColumns = Set.of(); + private Set filteredColumns = Set.of(); + private java.util.function.BiConsumer filterRequest = (id, node) -> {}; + private java.util.function.Consumer sortRequest = id -> {}; + + private record Entry(GridRow row, ResultRow view, EventHandler click) {} + + TableResults( + HBox header, VBox body, List columns, Function 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 selectedKeyProperty() { + return selectedKey.getReadOnlyProperty(); + } + + public ReadOnlyObjectProperty selectedElementProperty() { + return selectedElement.getReadOnlyProperty(); + } + + /** Cleanup failures are exposed separately: they do not roll back an already published page. */ + public ReadOnlyObjectProperty disposalFailureProperty() { + return disposalFailure.getReadOnlyProperty(); + } + + public List columnOrder() { + return order; + } + + public Map 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 handler) { + checkOpen(); + sortRequest = Objects.requireNonNull(handler); + } + + /** Opt-in filter actions; clicking the icon never issues a sort request. */ + public void setFilterActions( + Set columns, java.util.function.BiConsumer 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 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> result) { + show(result, order, widths); + } + + /** Stages both fresh rows and complete layout, publishing neither on preparation failure. */ + public void show( + List> result, + List nextOrder, + Map 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 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 keys = new HashSet<>(); + for (var row : result) + if (!keys.add(row.key())) throw new IllegalArgumentException("Duplicate row key"); + List> next = new ArrayList<>(); + Set 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 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 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 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 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 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 headerNodes(List ordering, Map sizes) { + List 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 ordering, Map sizes) { + Set fields = Collections.newSetFromMap(new IdentityHashMap<>()); + fields.addAll(view.fields().values()); + List 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> 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); + } +} diff --git a/fx/src/main/resources/de/neitzel/fx/grid/filter/BuiltInFilterEditor.fxml b/fx/src/main/resources/de/neitzel/fx/grid/filter/BuiltInFilterEditor.fxml new file mode 100644 index 0000000..256555d --- /dev/null +++ b/fx/src/main/resources/de/neitzel/fx/grid/filter/BuiltInFilterEditor.fxml @@ -0,0 +1,24 @@ + + + + +