Merge docking prerequisites and DataGrid implementation

This commit is contained in:
2026-11-16 17:50:37 +01:00
279 changed files with 29551 additions and 17 deletions
+9 -1
View File
@@ -42,9 +42,17 @@ 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 library that binds an FXML view to an ordinary Java model. See [fx/README.md](fx/README.md).
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).
### injection
+29
View File
@@ -0,0 +1,29 @@
# Optional JDBC DataGrid source
`data-grid-jdbc` depends only on the neutral `data-grid` contracts and the JDK JDBC API. It adds no driver or JavaFX dependency. The application supplies a DataSource, executor, approved simple table/key/column identifiers and a row mapper. The stable key must be unique and non-null. The initial dialect is H2, qualified with **2.5.252**; other databases are not claimed compatible.
```java
var source = new JdbcGridSource<Long, Product>(
dataSource, applicationExecutor, JdbcDialect.h2(), "products", "id",
List.of(JdbcColumn.text("name", "name", "name_key"),
JdbcColumn.decimal("price", "price", 12, 2)),
rs -> new GridRow<>(rs.getLong("id"), mapProduct(rs)), 250, 10);
```
The projection includes the stable key and all mapped physical columns. Identifiers accept only simple ASCII names, supplied by developers; SQL expressions, arbitrary joins and user-provided identifiers are intentionally unavailable. Filter operands and paging values use bound parameters. Custom conditions without a translator are explicitly rejected, never dropped. Date/time and boolean mappings are outside this initial adapter.
## Matching and consistency
Text mappings require a companion key column maintained with Java `Locale.ROOT` lowercasing whenever original values change. Store original text unchanged; checklist equality uses it. The adapter does not repair inconsistent application data or use SQL LOWER. Text sorting uses comparison keys; nulls sort last in either direction, followed by the stable key ascending. The H2 dialect rejects configured linguistic collation; default OFF collation is qualified against Java String comparison, including supplementary Unicode and combining marks. LIKE escapes `%`, `_` and the escape character `!`; all operands remain literal.
Integer operands must fit a signed long exactly. Decimal mappings enforce precision and scale with no rounding; numerically equal values with extra trailing zeros remain valid. The application must use matching SQL types (the example uses BIGINT and DECIMAL(12,2)). Missing/present, exact checklist membership and AND-combined filters are supported. The translator validates both condition type and column type before borrowing a connection.
Each request borrows one idle auto-commit connection, checks H2/collation, starts H2's vendor SNAPSHOT isolation (6), counts and fetches in the same transaction, commits before returning, and restores isolation/auto-commit before close. A non-auto-commit borrowed connection is rejected rather than committing an application transaction. The mapper must not mutate connection settings or execute writes. The application owns transaction cleanliness and pool reset policy. Close failures fail the request; cleanup errors are retained as suppressed exceptions.
All-mode checks its warning threshold after counting and before selecting rows. If approval is required, it rolls back and releases all borrowed resources before completing with `AllRowsConfirmationRequired`. Approval starts a fresh snapshot and recounts: it acknowledges an unpaged load, not a fixed maximum number of rows. The existing coordinator handles query-scoped approval and stale completions. Never save approval in a setup.
Every prepared query has the configured JDBC timeout. Cancellation attempts `Statement.cancel`, marks the request cancelled and stops mapping; cancellation is best effort and does not interrupt embedded driver threads. A cancelled future can complete before worker cleanup finishes, so application shutdown must drain the executor before disposing the DataSource. Closing a DataGrid does not own either resource.
The example explicitly supplies current-page checklist candidates; the adapter does not pretend a page is a complete source-wide candidate set. Applications needing source-wide candidates supply their own `FilterCandidates.Provider`, independently of SQL condition execution.
See [the complete runnable example](../fx-example/docs/product-grid.md) for fixture parity, fault controls, saved setups and limitations.
+5
View File
@@ -0,0 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0-SNAPSHOT</version></parent>
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
<dependencies><dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
@@ -0,0 +1,65 @@
package de.neitzel.grid.jdbc;
import de.neitzel.grid.*;
import java.math.*;
import java.util.*;
/** Approved physical identifier and scalar domain. Text keys are maintained by the application. */
public record JdbcColumn(
String id, String sqlName, Kind kind, String comparisonKey, int precision, int scale) {
public enum Kind {
TEXT,
INTEGER,
DECIMAL
}
public JdbcColumn {
if (id == null || id.isBlank())
throw new IllegalArgumentException("Missing column identity");
identifier(sqlName);
Objects.requireNonNull(kind);
if (kind == Kind.TEXT) identifier(comparisonKey);
else if (comparisonKey != null)
throw new IllegalArgumentException("Only text has comparison keys");
if (kind == Kind.DECIMAL && (precision < 1 || scale < 0 || scale > precision))
throw new IllegalArgumentException("Invalid decimal domain");
}
public static JdbcColumn text(String id, String column, String key) {
return new JdbcColumn(id, column, Kind.TEXT, key, 0, 0);
}
public static JdbcColumn integer(String id, String column) {
return new JdbcColumn(id, column, Kind.INTEGER, null, 0, 0);
}
public static JdbcColumn decimal(String id, String column, int precision, int scale) {
return new JdbcColumn(id, column, Kind.DECIMAL, null, precision, scale);
}
static String identifier(String name) {
if (name == null || !name.matches("[A-Za-z_][A-Za-z0-9_]*"))
throw new IllegalArgumentException("Expected an approved simple SQL identifier");
return name;
}
void number(BigDecimal value) {
if (kind == Kind.INTEGER) value.longValueExact();
else if (kind == Kind.DECIMAL) {
if (value.setScale(scale, RoundingMode.UNNECESSARY).precision() > precision)
throw new IllegalArgumentException("Decimal exceeds " + precision + "," + scale);
} else
throw new IllegalArgumentException("Numeric condition requires numeric column " + id);
}
Object value(FilterValue value) {
if (kind == Kind.TEXT && value instanceof FilterValue.Text t) return t.value();
if (kind == Kind.INTEGER && value instanceof FilterValue.IntegerValue n) return n.value();
if (kind == Kind.DECIMAL && value instanceof FilterValue.Decimal n) {
number(n.value());
return n.value();
}
throw new IllegalArgumentException("Checklist type does not match " + id);
}
}
@@ -0,0 +1,48 @@
package de.neitzel.grid.jdbc;
import java.sql.*;
/** Explicit dialect boundary; only H2 is qualified by this delivery. */
public interface JdbcDialect {
String executionId();
void beginSnapshot(Connection connection, int timeoutSeconds) throws SQLException;
String paging();
private static ResultSet execute(PreparedStatement statement, int timeoutSeconds)
throws SQLException {
statement.setQueryTimeout(timeoutSeconds);
return statement.executeQuery();
}
/** H2 default binary/Java-string collation and its vendor snapshot isolation level. */
static JdbcDialect h2() {
return new JdbcDialect() {
public String executionId() {
return "jdbc-h2";
}
public void beginSnapshot(Connection connection, int timeoutSeconds)
throws SQLException {
if (!connection.getMetaData().getDatabaseProductName().equals("H2"))
throw new SQLException("H2 dialect requires H2");
try (var s =
connection.prepareStatement(
"SELECT SETTING_VALUE FROM INFORMATION_SCHEMA.SETTINGS"
+ " WHERE SETTING_NAME = 'COLLATION'");
var rs = execute(s, timeoutSeconds)) {
if (rs.next() && !rs.getString(1).equals("OFF"))
throw new SQLException("Only H2 OFF collation is qualified");
}
connection.setTransactionIsolation(
6); // H2 TRANSACTION_SNAPSHOT, not JDBC REPEATABLE_READ.
connection.setAutoCommit(false);
}
public String paging() {
return " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
}
};
}
}
@@ -0,0 +1,321 @@
package de.neitzel.grid.jdbc;
import de.neitzel.grid.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import javax.sql.DataSource;
/** Mapped, parameterized queries. The application owns the DataSource and executor. */
public final class JdbcGridSource<K, T> implements GridSource<K, T> {
@FunctionalInterface
public interface RowMapper<K, T> {
GridRow<K, T> read(ResultSet result) throws SQLException;
}
private final DataSource dataSource;
private final Executor executor;
private final JdbcDialect dialect;
private final String table, key, projection;
private final Map<String, JdbcColumn> columns;
private final RowMapper<K, T> mapper;
private final int timeoutSeconds;
private final SourceCapabilities capabilities;
public JdbcGridSource(
DataSource dataSource,
Executor executor,
JdbcDialect dialect,
String table,
String key,
List<JdbcColumn> columns,
RowMapper<K, T> mapper,
int maximumPageSize,
int timeoutSeconds) {
this.dataSource = Objects.requireNonNull(dataSource);
this.executor = Objects.requireNonNull(executor);
this.dialect = Objects.requireNonNull(dialect);
this.table = JdbcColumn.identifier(table);
this.key = JdbcColumn.identifier(key);
this.mapper = Objects.requireNonNull(mapper);
if (timeoutSeconds < 1)
throw new IllegalArgumentException("A positive query timeout is required");
this.timeoutSeconds = timeoutSeconds;
capabilities = new SourceCapabilities(true, true, maximumPageSize);
var mapped = new LinkedHashMap<String, JdbcColumn>();
var selected = new LinkedHashSet<String>();
selected.add(key);
for (var c : columns) {
if (mapped.put(c.id(), c) != null)
throw new IllegalArgumentException("Duplicate column");
selected.add(c.sqlName());
}
this.columns = Map.copyOf(mapped);
projection = String.join(",", selected);
}
public SourceCapabilities capabilities() {
return capabilities;
}
public String filterExecutionId() {
return dialect.executionId();
}
private JdbcColumn column(String id) {
var c = columns.get(id);
if (c == null) throw new IllegalArgumentException("Unknown column: " + id);
return c;
}
public void validateFilter(FilterCondition filter) {
compile(filter, new ArrayList<>());
}
public QueryExecution<K, T> query(GridQuery query) {
return query(query, QueryOptions.defaults());
}
public QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
Objects.requireNonNull(query);
Objects.requireNonNull(options);
var execution = new Execution();
try {
capabilities.validate(query.page());
var parameters = new ArrayList<Object>();
String where = where(query.filters(), parameters);
var order = new ArrayList<String>();
for (var sort : query.sort()) {
var c = column(sort.columnId());
order.add(
(c.kind() == JdbcColumn.Kind.TEXT ? c.comparisonKey() : c.sqlName())
+ (sort.direction() == SortKey.Direction.ASCENDING
? " ASC"
: " DESC")
+ " NULLS LAST");
}
order.add(key + " ASC");
String rows =
"SELECT "
+ projection
+ " FROM "
+ table
+ where
+ " ORDER BY "
+ String.join(",", order)
+ (query.page() instanceof PageRequest.Paged ? dialect.paging() : "");
executor.execute(
() -> {
try {
execution.check();
execution.result.complete(
execute(execution, query, options, where, rows, parameters));
} catch (Exception failure) {
execution.result.completeExceptionally(failure);
}
});
} catch (RuntimeException failure) {
execution.result.completeExceptionally(failure);
}
return execution;
}
private PageResult<K, T> execute(
Execution execution,
GridQuery query,
QueryOptions options,
String where,
String sql,
List<Object> parameters)
throws SQLException {
try (var connection = dataSource.getConnection()) {
boolean auto = connection.getAutoCommit();
int isolation = connection.getTransactionIsolation();
if (!auto)
throw new SQLException("Borrowed connection must be idle with autoCommit=true");
Throwable primary = null;
try {
dialect.beginSnapshot(connection, timeoutSeconds);
execution.check();
long count;
try (var statement =
execution.prepare(
connection,
"SELECT COUNT(*) FROM " + table + where,
parameters);
var rs = statement.executeQuery()) {
rs.next();
count = rs.getLong(1);
}
execution.active.set(null);
execution.check();
if (query.page() instanceof PageRequest.All
&& count > options.allWarningThreshold()
&& !options.allApproved()) throw new AllRowsConfirmationRequired(count);
var values = new ArrayList<>(parameters);
if (query.page() instanceof PageRequest.Paged p) {
values.add(p.offset());
values.add(p.pageSize());
}
var result = new ArrayList<GridRow<K, T>>();
try (var statement = execution.prepare(connection, sql, values);
var rs = statement.executeQuery()) {
while (rs.next()) {
execution.check();
result.add(mapper.read(rs));
}
}
execution.active.set(null);
execution.check();
var page =
new PageResult<>(
query.page(),
result,
OptionalLong.of(count),
query.page() instanceof PageRequest.Paged p
&& count - p.offset() > p.pageSize());
connection.commit();
return page;
} catch (SQLException | RuntimeException | Error failure) {
primary = failure;
throw failure;
} finally {
execution.active.set(null);
SQLException cleanup = null;
try {
connection.rollback();
} catch (SQLException ex) {
cleanup = ex;
}
try {
connection.setTransactionIsolation(isolation);
} catch (SQLException ex) {
if (cleanup == null) cleanup = ex;
else cleanup.addSuppressed(ex);
}
try {
connection.setAutoCommit(auto);
} catch (SQLException ex) {
if (cleanup == null) cleanup = ex;
else cleanup.addSuppressed(ex);
}
if (cleanup != null) {
if (primary != null) primary.addSuppressed(cleanup);
else throw cleanup;
}
}
}
}
private String where(List<FilterCondition> filters, List<Object> args) {
if (filters.isEmpty()) return "";
return " WHERE "
+ String.join(
" AND ", filters.stream().map(f -> "(" + compile(f, args) + ")").toList());
}
private String compile(FilterCondition f, List<Object> args) {
var c = column(f.columnId());
String field = c.sqlName();
if (f instanceof MissingFilter m)
return field + (m.missing() ? " IS NULL" : " IS NOT NULL");
if (f instanceof TextFilter t) {
if (c.kind() != JdbcColumn.Kind.TEXT)
throw new IllegalArgumentException("Text filter requires text column");
field = t.caseSensitive() ? field : c.comparisonKey();
String operand = t.caseSensitive() ? t.operand() : t.operand().toLowerCase(Locale.ROOT);
if (t.operator() == TextFilter.Operator.EQUALS) {
args.add(operand);
return field + " = ?";
}
operand = operand.replace("!", "!!").replace("%", "!%").replace("_", "!_");
args.add(
switch (t.operator()) {
case CONTAINS -> "%" + operand + "%";
case STARTS_WITH -> operand + "%";
case ENDS_WITH -> "%" + operand;
default -> throw new IllegalStateException();
});
return field + " LIKE ? ESCAPE '!'";
}
if (f instanceof NumericFilter n) {
c.number(n.operand());
args.add(n.operand());
if (n.operator() == NumericFilter.Operator.RANGE) {
c.number(n.upper());
args.add(n.upper());
return field + " BETWEEN ? AND ?";
}
return field
+ switch (n.operator()) {
case EQUALS -> " = ?";
case LESS -> " < ?";
case LESS_OR_EQUAL -> " <= ?";
case GREATER -> " > ?";
case GREATER_OR_EQUAL -> " >= ?";
default -> throw new IllegalStateException();
};
}
if (f instanceof ValueFilter v) {
var marks = new ArrayList<String>();
for (var value : v.values()) {
args.add(c.value(value));
marks.add("?");
}
String membership =
marks.isEmpty() ? "1=0" : field + " IN (" + String.join(",", marks) + ")";
return membership + (v.includeMissing() ? " OR " + field + " IS NULL" : "");
}
throw new UnsupportedOperationException("JDBC does not support filter: " + f.typeId());
}
private final class Execution implements QueryExecution<K, T> {
final CompletableFuture<PageResult<K, T>> result = new CompletableFuture<>();
final AtomicBoolean cancelled = new AtomicBoolean();
final AtomicReference<Statement> active = new AtomicReference<>();
public CompletionStage<PageResult<K, T>> result() {
return result;
}
public void cancel() {
cancelled.set(true);
var statement = active.get();
if (statement != null)
try {
statement.cancel();
} catch (SQLException ignored) {
/* Best effort; obsolete publication is independently rejected. */
}
result.cancel(false);
}
void check() {
if (cancelled.get()) throw new CancellationException("JDBC request cancelled");
}
PreparedStatement prepare(Connection connection, String sql, List<Object> parameters)
throws SQLException {
check();
var statement = connection.prepareStatement(sql);
try {
statement.setQueryTimeout(timeoutSeconds);
for (int i = 0; i < parameters.size(); i++)
statement.setObject(i + 1, parameters.get(i));
active.set(statement);
check();
return statement;
} catch (SQLException | RuntimeException failure) {
try {
statement.close();
} catch (SQLException close) {
failure.addSuppressed(close);
}
throw failure;
}
}
}
}
+39
View File
@@ -0,0 +1,39 @@
# data-grid foundations
Toolkit-independent contracts for opt-in DataGrid development. This module does not depend on JavaFX or a JDBC driver. Parent-provided compile/test tooling is inherited, including Lombok annotation processing; immutable public models are Java records.
- `FilterCondition` is open to custom immutable implementations. Built-ins provide literal text, exact decimal, missing/present and explicit checklist conditions. A custom type must declare capabilities separately; editor registration is in `fx`, codecs are in optional `gson`, and adapter compilation remains separate.
- `GridQuery` combines one condition per column with AND and ordered sort keys. The source must append its stable row-key tie-breaker and validate column types, precision, matching semantics and capabilities.
- `PageRequest.Paged` uses zero-based indexes; `All` is explicit. `PageResult` defensively copies lists and checks row identities/count consistency, allowing empty out-of-range pages for coordinator recovery.
- `GridSource` separates asynchronous result completion from best-effort cancellation. The coordinator must independently discard obsolete completions. Models inside `GridRow` remain application-owned; they are not deep-copied.
- `GridSetup` separates format and definition versions, default versus explicit widths, and All versus paging. It rejects persisted nonzero page indexes. Selection, credentials and warning approvals are deliberately absent.
`TextFilter.matches` uses Locale.ROOT lowercasing with no normalization; `%` and `_` are literal. `NumericFilter` accepts BigDecimal operands and compares numerically, avoiding double conversion. The mapping layer remains responsible for the declared integer/decimal domain and scale limits. `FilterValue.Decimal` canonicalizes scale so checklist membership treats 1.0 and 1.00 equally. Text checklist membership is exact.
`MemoryGridSource` now executes mapped local queries, and `GridCoordinator` manages guarded requests, All confirmation, stale-result rejection, recovery and publication. Definition migrations are available here and JSON codecs are in optional `gson`; SQL execution is available in the optional [data-grid-jdbc module](../data-grid-jdbc/README.md). No executor is created or shut down by these classes.
Run from the repository root: `./mvnw -pl data-grid test`.
## Local execution
`MemoryGridSource<K,T>` accepts a collection supplier, stable-key function and comparator, explicit `MemoryColumn<T>` scalar mappings, an application-owned executor and a maximum page size. Built-in mappings cover text, long integers, arbitrary-precision decimals and booleans; null mapping values mean missing. Per-column custom filter compilers explicitly opt into additional local conditions; unsupported types fail rather than being ignored. Numeric mapping constraints beyond the generic long/BigDecimal domains remain the application's responsibility.
A query captures collection membership, keys and mapped scalar values on the calling thread. The supplier/readers must provide a consistent view (for example, call from the FX thread for FX-owned models, or synchronize the snapshot). Filtering, sorting and slicing run on the supplied executor. This preserves scalar/count consistency across later model changes without reading FX-owned properties on a worker. Model objects in results are application-owned references, not deep copies. Snapshot capture is O(n) caller-thread work; use a source with its own background snapshot mechanism for very large mutable datasets.
Filters combine with AND. Text sort uses Locale.ROOT lowercase lexical comparison; nulls remain last in either direction. The key comparator provides the final tie-breaker and must distinguish unique keys. Data is never reordered in the source collection.
`query(query, QueryOptions)` is the guarded All protocol. Without attempt-scoped approval, a count above the configured threshold fails with `AllRowsConfirmationRequired` before sorting/materializing the unpaged result. The caller asks the person, then submits the same query with approval in a **fresh** snapshot. A changed query or later attempt needs fresh approval. Sources not overriding the guarded overload reject All by default. Do not fetch All first and then ask.
## Owner-thread coordinator
Create `GridCoordinator` on its owner thread and supply an executor that **queues** callbacks to that same thread (`Platform::runLater` for FX). Public mutators also run there. Observers should not throw. A publisher may reject a result before committing it, allowing the coordinator to preserve its prior displayed state. Observer-triggered requests are queued rather than applied reentrantly.
State exposes requested versus displayed query, result, phase and error. The coordinator validates page identity and declared exact-count support, attempts cancellation but independently ignores superseded successes/failures, and permits only one corrective page request per user attempt. A guard may approve/block edits asynchronously. All confirmation is asynchronous and never retains an execution snapshot while awaiting input.
Rejected guards and declined All warnings restore the displayed query. A replacement source is committed only when it successfully publishes a result; cancellation keeps the previous source. Retry uses the latest requested query/source. Close invalidates pending callbacks and drops retained results without closing application sources/executors. Source selection and loaded row identity are presentation responsibilities.
Collection changes do not automatically trigger requests in this slice. Call refresh explicitly from application mutation handlers; automatic collection subscriptions can be added without changing the query contract.
## Saved setups
`GridDefinition.prepare` applies explicit definition migrations and validates column types/order, widths and source support. `GridSetup.ColumnState` carries stable type IDs. JSON is provided separately by `de.neitzel.lib:gson`; `data-grid` does not depend on JavaFX or Gson. See the [saved setup guide](../fx/docs/saved-setups.md).
+6
View File
@@ -0,0 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0-SNAPSHOT</version></parent>
<artifactId>data-grid</artifactId>
<description>Toolkit-independent filter, query and grid setup contracts</description>
</project>
@@ -0,0 +1,19 @@
package de.neitzel.grid;
/**
* Source stopped before materializing an unpaged result. Any snapshot/transaction has been
* released.
*/
public final class AllRowsConfirmationRequired extends RuntimeException {
private final long count;
public AllRowsConfirmationRequired(long count) {
super("Loading all " + count + " matching rows requires confirmation");
if (count < 0) throw new IllegalArgumentException("Negative count");
this.count = count;
}
public long count() {
return count;
}
}
@@ -0,0 +1,11 @@
package de.neitzel.grid;
final class Checks {
private Checks() {}
static String id(String value) {
if (value == null || value.isBlank())
throw new IllegalArgumentException("Identifier must not be blank");
return value;
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
/** Saved sizing intention, independent of a theme's current default. */
public sealed interface ColumnWidth {
record Default() implements ColumnWidth {}
record Explicit(double value) implements ColumnWidth {
public Explicit {
if (!Double.isFinite(value) || value <= 0)
throw new IllegalArgumentException("Width must be finite and positive");
}
}
}
@@ -0,0 +1,161 @@
package de.neitzel.grid;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/** Explicit, typed candidate lookup. A session owns its snapshot and pending lookups. */
public final class FilterCandidates {
private FilterCandidates() {}
public enum Scope {
CURRENT_PAGE,
SOURCE_WIDE
}
/** A null value explicitly represents missing; labels never determine equality. */
public record Candidate(FilterValue value, String label) {
public Candidate {
Objects.requireNonNull(label);
}
}
public record Context(String columnId, Scope scope, List<FilterCondition> otherFilters) {
public Context {
Checks.id(columnId);
Objects.requireNonNull(scope);
otherFilters = List.copyOf(otherFilters);
if (otherFilters.stream().anyMatch(f -> f.columnId().equals(columnId)))
throw new IllegalArgumentException("Candidate context must exclude its own filter");
}
}
public record Request(Context context, String search, int offset, int limit) {
public Request {
Objects.requireNonNull(context);
Objects.requireNonNull(search);
if (offset < 0 || limit < 1)
throw new IllegalArgumentException("Invalid candidate batch");
}
}
public record Batch(List<Candidate> candidates, boolean hasMore) {
public Batch {
candidates = List.copyOf(candidates);
}
}
public interface Provider {
Set<Scope> scopes();
Session open(Context context);
}
public interface Session extends AutoCloseable {
CompletionStage<Batch> load(Request request);
@Override
void close();
}
/** Captures current-page values at open, never claims source-wide completeness. */
public static Provider currentPage(Supplier<List<Candidate>> values) {
return snapshot(
Set.of(Scope.CURRENT_PAGE),
c -> {
var copy = List.copyOf(values.get());
return () -> copy;
},
Runnable::run);
}
/** Capture on open's thread; evaluate the captured snapshot on the supplied executor. */
public static Provider snapshot(
Set<Scope> scopes,
Function<Context, Supplier<List<Candidate>>> capture,
Executor executor) {
Set<Scope> supported = Set.copyOf(scopes);
Objects.requireNonNull(capture);
Objects.requireNonNull(executor);
return new Provider() {
public Set<Scope> scopes() {
return supported;
}
public Session open(Context context) {
if (!supported.contains(context.scope()))
throw new UnsupportedOperationException(
"Candidate scope unavailable: " + context.scope());
var captured =
new java.util.concurrent.atomic.AtomicReference<>(
Objects.requireNonNull(capture.apply(context)));
return new Session() {
private boolean closed;
private final Set<CompletableFuture<Batch>> pending = new HashSet<>();
public synchronized CompletionStage<Batch> load(Request request) {
if (closed) throw new IllegalStateException("Candidate session closed");
if (!context.equals(request.context()))
throw new IllegalArgumentException("Wrong candidate context");
var future = new CompletableFuture<Batch>();
pending.add(future);
try {
executor.execute(
() -> {
try {
if (future.isDone()) return;
Map<FilterValue, Candidate> distinct =
new LinkedHashMap<>();
var work = captured.get();
if (work == null) {
future.cancel(false);
return;
}
for (var candidate : work.get()) {
if (future.isDone()) return;
if (candidate
.label()
.toLowerCase(Locale.ROOT)
.contains(
request.search()
.toLowerCase(Locale.ROOT)))
distinct.putIfAbsent(
candidate.value(), candidate);
}
var found = new ArrayList<>(distinct.values());
int from = Math.min(request.offset(), found.size());
int to =
(int)
Math.min(
(long) from + request.limit(),
found.size());
future.complete(
new Batch(
found.subList(from, to),
to < found.size()));
} catch (RuntimeException error) {
future.completeExceptionally(error);
} finally {
synchronized (this) {
pending.remove(future);
}
}
});
} catch (RuntimeException error) {
pending.remove(future);
future.completeExceptionally(error);
}
return future;
}
public synchronized void close() {
closed = true;
captured.set(null);
for (var future : pending) future.cancel(false);
pending.clear();
}
};
}
};
}
}
@@ -0,0 +1,15 @@
package de.neitzel.grid;
import java.util.Set;
/**
* Independent registration capabilities; a translator must additionally validate each concrete
* condition.
*/
public record FilterCapabilities(
boolean localEvaluation, boolean persistence, Set<String> adapters) {
public FilterCapabilities {
adapters = Set.copyOf(adapters);
adapters.forEach(Checks::id);
}
}
@@ -0,0 +1,11 @@
package de.neitzel.grid;
/**
* Immutable column condition. Custom implementations must preserve value semantics and declare a
* stable type ID.
*/
public interface FilterCondition {
String columnId();
String typeId();
}
@@ -0,0 +1,24 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.Objects;
/** Immutable portable checklist values; missing is represented separately by ValueFilter. */
public sealed interface FilterValue {
record Text(String value) implements FilterValue {
public Text {
Objects.requireNonNull(value);
}
}
record IntegerValue(long value) implements FilterValue {}
record Decimal(BigDecimal value) implements FilterValue {
public Decimal {
Objects.requireNonNull(value);
value = value.stripTrailingZeros();
}
}
record BooleanValue(boolean value) implements FilterValue {}
}
@@ -0,0 +1,469 @@
package de.neitzel.grid;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/**
* Serial, owner-thread coordinator. Supply an executor that dispatches callbacks to the creating
* thread, always enqueueing rather than invoking inline (for JavaFX, Platform::runLater). It never
* owns/shuts down sources or executors.
*/
public final class GridCoordinator<K, T> implements AutoCloseable {
public enum Phase {
IDLE,
GUARD,
LOADING,
CONFIRMATION,
READY,
ERROR,
CLOSED
}
public record State<K, T>(
long generation,
GridQuery requested,
GridQuery displayed,
PageResult<K, T> result,
Phase phase,
Throwable error,
long sourceVersion) {}
private final Thread owner = Thread.currentThread();
private final Executor dispatch;
private final Consumer<State<K, T>> observer;
private final Consumer<PageResult<K, T>> publisher;
private GridSource<K, T> source;
private GridSource<K, T> requestedSource;
private GridSource.QueryExecution<K, T> execution;
private State<K, T> state = new State<>(0, null, null, null, Phase.IDLE, null, 0);
private long generation, sourceVersion;
private long threshold = 1000;
private boolean closed;
private boolean notifying;
private boolean restoring;
private State<K, T> restoreBefore;
private Consumer<PageResult<K, T>> requestPublisher;
private Function<GridQuery, CompletionStage<Boolean>> guard =
q -> CompletableFuture.completedFuture(true);
private BiFunction<GridQuery, Long, CompletionStage<Boolean>> confirmation =
(q, n) ->
CompletableFuture.failedFuture(
new IllegalStateException("No All confirmation handler configured"));
public GridCoordinator(
GridSource<K, T> source,
Executor dispatch,
Consumer<State<K, T>> observer,
Consumer<PageResult<K, T>> publisher) {
this.source = Objects.requireNonNull(source);
this.requestedSource = source;
this.dispatch = Objects.requireNonNull(dispatch);
this.observer = Objects.requireNonNull(observer);
this.publisher = Objects.requireNonNull(publisher);
}
public State<K, T> state() {
return state;
}
public SourceCapabilities capabilities() {
check();
return requestedSource.capabilities();
}
public String filterExecutionId() {
check();
return requestedSource.filterExecutionId();
}
public void validateFilters(List<FilterCondition> filters) {
check();
filters.forEach(requestedSource::validateFilter);
}
public void setGuard(Function<GridQuery, CompletionStage<Boolean>> guard) {
check();
this.guard = Objects.requireNonNull(guard);
}
public void setConfirmation(
BiFunction<GridQuery, Long, CompletionStage<Boolean>> confirmation) {
check();
this.confirmation = Objects.requireNonNull(confirmation);
}
public void setAllWarningThreshold(long value) {
check();
if (value < 0) throw new IllegalArgumentException("Negative warning threshold");
threshold = value;
}
public void request(GridQuery query) {
request(requestedSource, query);
}
/** A replacement source becomes committed only after its guarded query succeeds. */
public void request(GridSource<K, T> replacement, GridQuery query) {
request(replacement, query, () -> {}, publisher, false);
}
/** A newer layout-only operation supersedes pending restoration without querying. */
public void cancelRestore() {
check();
if (!restoring) return;
if (notifying) {
dispatch.execute(
() -> {
if (!closed) cancelRestore();
});
return;
}
++generation;
cancelExecution();
var before = restoreBefore;
restore(before);
}
public boolean isRestoring() {
return restoring;
}
/**
* Validated restore: one guard, then one initial query, then atomic application publication.
*/
public void restoreSetup(
GridQuery query, Runnable afterGuard, Consumer<PageResult<K, T>> publish) {
request(
requestedSource,
query,
Objects.requireNonNull(afterGuard),
Objects.requireNonNull(publish),
true);
}
/** Report decode/preparation failure without querying or discarding displayed data. */
public void rejectSetup(Throwable failure) {
check();
if (notifying) {
dispatch.execute(
() -> {
if (!closed) rejectSetup(failure);
});
return;
}
++generation;
cancelExecution();
restoring = false;
restoreBefore = null;
requestPublisher = null;
requestedSource = source;
update(state.displayed(), Phase.ERROR, Objects.requireNonNull(failure));
}
private void request(
GridSource<K, T> replacement,
GridQuery query,
Runnable afterGuard,
Consumer<PageResult<K, T>> publish,
boolean transactional) {
check();
Objects.requireNonNull(replacement);
Objects.requireNonNull(query);
if (notifying) {
dispatch.execute(
() -> {
if (!closed)
request(replacement, query, afterGuard, publish, transactional);
});
return;
}
long token = ++generation;
cancelExecution();
requestedSource = replacement;
var before =
new State<K, T>(
token,
state.displayed() != null ? state.displayed() : state.requested(),
state.displayed(),
state.result(),
state.result() == null ? Phase.IDLE : Phase.READY,
null,
sourceVersion);
restoring = transactional;
restoreBefore = transactional ? before : null;
requestPublisher = publish;
update(query, Phase.GUARD, null);
if (!current(token)) return;
try {
replacement.capabilities().validate(query.page());
await(
Objects.requireNonNull(guard.apply(query)),
token,
(allowed, failure) -> {
if (failure != null) {
fail(query, failure);
return;
}
if (!Boolean.TRUE.equals(allowed)) {
restore(before);
return;
}
try {
afterGuard.run();
if (current(token))
execute(replacement, query, token, false, false, before, threshold);
} catch (RuntimeException error) {
if (current(token)) fail(query, error);
}
});
} catch (RuntimeException failure) {
fail(query, failure);
}
}
public void retry() {
check();
if (state.requested() != null) request(state.requested());
}
public void refresh() {
retry();
}
private void execute(
GridSource<K, T> target,
GridQuery query,
long token,
boolean approved,
boolean corrected,
State<K, T> before,
long attemptThreshold) {
if (!current(token)) return;
update(query, Phase.LOADING, null);
if (!current(token)) return;
try {
execution =
Objects.requireNonNull(
target.query(query, new QueryOptions(attemptThreshold, approved)),
"Missing execution");
await(
Objects.requireNonNull(execution.result()),
token,
(result, failure) -> {
execution = null;
if (failure != null) {
Throwable cause = unwrap(failure);
if (cause instanceof AllRowsConfirmationRequired required
&& query.page() instanceof PageRequest.All
&& !approved) {
update(query, Phase.CONFIRMATION, null);
if (!current(token)) return;
try {
await(
Objects.requireNonNull(
confirmation.apply(query, required.count())),
token,
(allowed, error) -> {
if (error != null) fail(query, error);
else if (Boolean.TRUE.equals(allowed))
execute(
target,
query,
token,
true,
corrected,
before,
attemptThreshold);
else restore(before);
});
} catch (RuntimeException error) {
fail(query, error);
}
} else fail(query, cause);
return;
}
try {
Objects.requireNonNull(result, "Missing page result");
if (!query.page().equals(result.request()))
throw new IllegalArgumentException(
"Source returned a different page request");
if (target.capabilities().exactTotal() && result.total().isEmpty())
throw new IllegalArgumentException(
"Source promised an exact count");
if (query.page() instanceof PageRequest.Paged page
&& page.pageIndex() > 0
&& result.rows().isEmpty()
&& (result.total().isEmpty()
|| result.total().getAsLong() > 0)) {
if (corrected)
throw new IllegalStateException(
"Page changed again during recovery; retry");
long last =
result.total().isPresent()
? (result.total().getAsLong() - 1) / page.pageSize()
: 0;
execute(
target,
new GridQuery(
query.filters(),
query.sort(),
new PageRequest.Paged(last, page.pageSize())),
token,
approved,
true,
before,
attemptThreshold);
return;
}
notifying = true;
try {
requestPublisher.accept(result);
} finally {
notifying = false;
}
if (!current(token)) return;
if (source != target) {
source = target;
sourceVersion++;
}
restoring = false;
restoreBefore = null;
requestPublisher = null;
state =
new State<>(
generation,
query,
query,
result,
Phase.READY,
null,
sourceVersion);
notifyState();
} catch (RuntimeException invalid) {
fail(query, invalid);
}
});
} catch (RuntimeException failure) {
execution = null;
fail(query, failure);
}
}
private <V> void await(
CompletionStage<V> stage, long token, BiConsumer<V, Throwable> callback) {
stage.whenComplete(
(value, failure) ->
dispatch.execute(
() -> {
checkThread();
if (current(token)) callback.accept(value, failure);
}));
}
private void restore(State<K, T> before) {
restoring = false;
restoreBefore = null;
requestPublisher = null;
requestedSource = source;
state =
new State<>(
generation,
before.requested(),
before.displayed(),
before.result(),
before.phase(),
null,
sourceVersion);
notifyState();
}
private void update(GridQuery query, Phase phase, Throwable error) {
state =
new State<>(
generation,
query,
state.displayed(),
state.result(),
phase,
error,
sourceVersion);
notifyState();
}
private void notifyState() {
notifying = true;
try {
observer.accept(state);
} finally {
notifying = false;
}
}
private void fail(GridQuery query, Throwable error) {
if (closed) return;
if (restoring) {
query = restoreBefore.requested();
requestedSource = source;
restoring = false;
restoreBefore = null;
}
requestPublisher = null;
update(query, Phase.ERROR, unwrap(error));
}
private static Throwable unwrap(Throwable failure) {
while ((failure instanceof CompletionException || failure instanceof ExecutionException)
&& failure.getCause() != null) failure = failure.getCause();
return failure;
}
private boolean current(long token) {
return !closed && generation == token;
}
private void cancelExecution() {
if (execution != null) {
var old = execution;
execution = null;
try {
old.cancel();
} catch (RuntimeException ignored) {
/* cancellation is advisory; identity still rejects stale completion */
}
}
}
private void checkThread() {
if (Thread.currentThread() != owner)
throw new IllegalStateException("Use the coordinator owner thread");
}
private void check() {
checkThread();
if (closed) throw new IllegalStateException("Coordinator is closed");
}
public void close() {
checkThread();
if (closed) return;
closed = true;
restoring = false;
restoreBefore = null;
requestPublisher = null;
generation++;
cancelExecution();
state =
new State<>(
generation,
state.requested(),
null,
null,
Phase.CLOSED,
null,
sourceVersion);
source = null;
requestedSource = null;
notifyState();
}
}
@@ -0,0 +1,129 @@
package de.neitzel.grid;
import java.util.*;
import java.util.function.*;
/** Definition identity and layout constraints, independent of JSON and JavaFX. */
public record GridDefinition(String id, int version, List<Column> columns) {
public record Column(
String id,
String type,
double defaultWidth,
double minimumWidth,
double maximumWidth,
int fixedPosition) {
public Column {
Checks.id(id);
Checks.id(type);
if (!Double.isFinite(defaultWidth)
|| !Double.isFinite(minimumWidth)
|| !Double.isFinite(maximumWidth)
|| minimumWidth <= 0
|| defaultWidth < minimumWidth
|| maximumWidth < defaultWidth
|| fixedPosition < -1)
throw new IllegalArgumentException("Invalid column constraints: " + id);
}
}
public GridDefinition {
Checks.id(id);
if (version < 1) throw new IllegalArgumentException("Invalid definition version");
columns = List.copyOf(columns);
if (columns.isEmpty()) throw new IllegalArgumentException("Missing columns");
Set<String> ids = new HashSet<>();
for (int i = 0; i < columns.size(); i++) {
var c = columns.get(i);
if (!ids.add(c.id())) throw new IllegalArgumentException("Duplicate definition column");
if (c.fixedPosition() != -1 && c.fixedPosition() != i)
throw new IllegalArgumentException("Fixed column must match declaration position");
}
}
public record Prepared(GridSetup setup, List<String> adjustments) {
public Prepared {
Objects.requireNonNull(setup);
adjustments = List.copyOf(adjustments);
}
}
/**
* Each migration explicitly advances exactly one definition version; output is fully validated.
*/
public Prepared prepare(
GridSetup input,
Map<Integer, UnaryOperator<GridSetup>> migrations,
SourceCapabilities source,
Consumer<FilterCondition> validateFilter) {
Objects.requireNonNull(input);
Objects.requireNonNull(migrations);
if (input.formatVersion() != 1)
throw new IllegalArgumentException(
"Unsupported setup format version: " + input.formatVersion());
if (!id.equals(input.definitionId()))
throw new IllegalArgumentException(
"Setup belongs to another grid definition: " + input.definitionId());
if (input.definitionVersion() > version)
throw new IllegalArgumentException("Setup uses a future definition version");
GridSetup setup = input;
while (setup.definitionVersion() < version) {
int old = setup.definitionVersion();
var migrate = migrations.get(old);
if (migrate == null)
throw new IllegalArgumentException(
"Missing definition migration from version " + old);
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
if (!id.equals(setup.definitionId())
|| setup.definitionVersion() != old + 1
|| setup.formatVersion() != 1)
throw new IllegalArgumentException(
"Migration must preserve identity/format and advance one definition"
+ " version");
}
Map<String, Column> definitions = new LinkedHashMap<>();
columns.forEach(c -> definitions.put(c.id(), c));
List<GridSetup.ColumnState> next = new ArrayList<>();
List<String> adjustments = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (var saved : setup.columns()) {
var c = definitions.get(saved.id());
if (c == null)
throw new IllegalArgumentException(
"Unknown saved column: " + saved.id() + "; provide a migration");
if (!c.type().equals(saved.type()))
throw new IllegalArgumentException(
"Column type changed: " + saved.id() + "; provide a migration");
ColumnWidth width = saved.width();
if (width instanceof ColumnWidth.Explicit explicit) {
double clamped = Math.clamp(explicit.value(), c.minimumWidth(), c.maximumWidth());
if (clamped != explicit.value())
adjustments.add(
"Column "
+ c.id()
+ " width clamped from "
+ explicit.value()
+ " to "
+ clamped);
width = new ColumnWidth.Explicit(clamped);
}
next.add(new GridSetup.ColumnState(c.id(), c.type(), width));
seen.add(c.id());
}
for (var c : columns)
if (!seen.contains(c.id()))
next.add(new GridSetup.ColumnState(c.id(), c.type(), new ColumnWidth.Default()));
for (int i = 0; i < next.size(); i++) {
int fixed = definitions.get(next.get(i).id()).fixedPosition();
if (fixed >= 0 && fixed != i)
throw new IllegalArgumentException(
"Saved order violates fixed position for "
+ next.get(i).id()
+ "; provide a migration");
}
source.validate(setup.page());
setup.filters().forEach(validateFilter);
return new Prepared(
new GridSetup(1, id, version, next, setup.sort(), setup.filters(), setup.page()),
adjustments);
}
}
@@ -0,0 +1,24 @@
package de.neitzel.grid;
import java.util.*;
/**
* Immutable query. Filters combine with AND; sort keys include the source's stable-key tie-breaker.
*/
public record GridQuery(List<FilterCondition> filters, List<SortKey> sort, PageRequest page) {
public GridQuery {
filters = List.copyOf(filters);
sort = List.copyOf(sort);
Objects.requireNonNull(page);
Set<String> ids = new HashSet<>();
for (var f : filters) {
Checks.id(f.columnId());
Checks.id(f.typeId());
if (!ids.add(f.columnId()))
throw new IllegalArgumentException("Multiple filters for " + f.columnId());
}
ids.clear();
for (var key : sort)
if (!ids.add(key.columnId())) throw new IllegalArgumentException("Duplicate sort key");
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
import java.util.Objects;
/**
* Row identity is independent of page position. The model is application-owned, not deep-copied.
*/
public record GridRow<K, T>(K key, T model) {
public GridRow {
Objects.requireNonNull(key);
Objects.requireNonNull(model);
}
}
@@ -0,0 +1,50 @@
package de.neitzel.grid;
import java.util.*;
/** Plain versioned setup. No selection, credentials, page index, drafts, or approval tokens. */
public record GridSetup(
int formatVersion,
String definitionId,
int definitionVersion,
List<ColumnState> columns,
List<SortKey> sort,
List<FilterCondition> filters,
PageRequest page) {
public record ColumnState(String id, String type, ColumnWidth width) {
/** Older callers must supply a definition type before persistence/restoration. */
public ColumnState(String id, ColumnWidth width) {
this(id, "unspecified", width);
}
public ColumnState {
Checks.id(id);
Checks.id(type);
Objects.requireNonNull(width);
}
}
public GridSetup {
if (formatVersion <= 0 || definitionVersion <= 0)
throw new IllegalArgumentException("Invalid version");
Checks.id(definitionId);
columns = List.copyOf(columns);
sort = List.copyOf(sort);
filters = List.copyOf(filters);
Objects.requireNonNull(page);
Set<String> ids = new HashSet<>();
for (var c : columns)
if (!ids.add(c.id())) throw new IllegalArgumentException("Duplicate column ID");
if (sort.size() > 1)
throw new IllegalArgumentException("Only one user-selected sort is supported");
for (var key : sort)
if (!ids.contains(key.columnId()))
throw new IllegalArgumentException("Unknown sort column");
for (var f : filters)
if (!ids.contains(f.columnId()))
throw new IllegalArgumentException("Unknown filter column");
new GridQuery(filters, sort, page);
if (page instanceof PageRequest.Paged p && p.pageIndex() != 0)
throw new IllegalArgumentException("Setups must start on the first page");
}
}
@@ -0,0 +1,56 @@
package de.neitzel.grid;
import java.util.concurrent.CompletionStage;
/**
* Toolkit-independent source. Implementations validate mappings/semantics and own per-request
* resources.
*/
public interface GridSource<K, T> {
SourceCapabilities capabilities();
QueryExecution<K, T> query(GridQuery query);
/** Stable execution capability ID: "local" or an adapter-specific registration ID. */
default String filterExecutionId() {
return "unspecified";
}
/** Validate concrete semantics before accepting an editor/programmatic draft. */
default void validateFilter(FilterCondition condition) {
throw new UnsupportedOperationException(
"Source does not declare filter support: " + condition.typeId());
}
/**
* Guarded execution. Sources supporting All must override and count in their execution snapshot
* before materializing rows, failing with AllRowsConfirmationRequired when consent is needed.
* The default deliberately rejects All rather than performing an unsafe fetch-first check.
*/
default QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
java.util.Objects.requireNonNull(options);
if (query.page() instanceof PageRequest.All) {
var failure =
java.util.concurrent.CompletableFuture.<PageResult<K, T>>failedFuture(
new UnsupportedOperationException(
"Source does not support guarded All execution"));
return new QueryExecution<>() {
public CompletionStage<PageResult<K, T>> result() {
return failure;
}
public void cancel() {}
};
}
return query(query);
}
/**
* Cancellation is best-effort; coordinators must reject superseded completions independently.
*/
interface QueryExecution<K, T> {
CompletionStage<PageResult<K, T>> result();
void cancel();
}
}
@@ -0,0 +1,44 @@
package de.neitzel.grid;
import java.util.*;
import java.util.function.*;
/**
* Explicit scalar mapping; custom compilers validate their condition and produce local evaluators.
*/
public record MemoryColumn<T>(
String id,
Kind kind,
Function<T, FilterValue> read,
Map<String, Function<FilterCondition, Predicate<FilterValue>>> customFilters) {
public enum Kind {
TEXT,
INTEGER,
DECIMAL,
BOOLEAN
}
public MemoryColumn(String id, Kind kind, Function<T, FilterValue> read) {
this(id, kind, read, Map.of());
}
public MemoryColumn {
Checks.id(id);
Objects.requireNonNull(kind);
Objects.requireNonNull(read);
customFilters = Map.copyOf(customFilters);
customFilters.keySet().forEach(Checks::id);
}
void validate(FilterValue value) {
if (value == null) return;
boolean valid =
switch (kind) {
case TEXT -> value instanceof FilterValue.Text;
case INTEGER -> value instanceof FilterValue.IntegerValue;
case DECIMAL -> value instanceof FilterValue.Decimal;
case BOOLEAN -> value instanceof FilterValue.BooleanValue;
};
if (!valid) throw new IllegalArgumentException("Value type does not match column " + id);
}
}
@@ -0,0 +1,268 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.*;
/**
* Local source with caller-thread scalar snapshot capture and executor-based query processing. The
* supplier must return a consistent view; FX-owned lists may be captured on the FX caller thread.
* Captured scalar values are immutable; row models remain application-owned. No executor is closed.
*/
public final class MemoryGridSource<K, T> implements GridSource<K, T> {
private final Supplier<? extends Collection<T>> data;
private final Function<T, K> key;
private final Comparator<K> keyOrder;
private final Map<String, MemoryColumn<T>> columns;
private final Executor executor;
private final SourceCapabilities capabilities;
private record Snapshot<K, T>(K key, T model, Map<String, FilterValue> values) {}
public MemoryGridSource(
Supplier<? extends Collection<T>> data,
Function<T, K> key,
Comparator<K> keyOrder,
List<MemoryColumn<T>> columns,
Executor executor,
int maximumPageSize) {
this.data = Objects.requireNonNull(data);
this.key = Objects.requireNonNull(key);
this.keyOrder = Objects.requireNonNull(keyOrder);
this.executor = Objects.requireNonNull(executor);
Map<String, MemoryColumn<T>> mapped = new LinkedHashMap<>();
for (var column : columns)
if (mapped.putIfAbsent(column.id(), column) != null)
throw new IllegalArgumentException("Duplicate column mapping");
this.columns = Map.copyOf(mapped);
capabilities = new SourceCapabilities(true, true, maximumPageSize);
}
public SourceCapabilities capabilities() {
return capabilities;
}
public QueryExecution<K, T> query(GridQuery query) {
return query(query, QueryOptions.defaults());
}
public QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
CompletableFuture<PageResult<K, T>> result = new CompletableFuture<>();
AtomicBoolean cancelled = new AtomicBoolean();
try {
Objects.requireNonNull(query);
Objects.requireNonNull(options);
capabilities.validate(query.page());
List<Predicate<Snapshot<K, T>>> predicates = new ArrayList<>();
for (var condition : query.filters()) {
var column = column(condition.columnId());
var test = compile(column, condition);
predicates.add(row -> test.test(row.values().get(column.id())));
}
for (var sort : query.sort()) column(sort.columnId());
List<Snapshot<K, T>> snapshot = new ArrayList<>();
Set<K> keys = new HashSet<>();
for (T model : List.copyOf(data.get())) {
K id = Objects.requireNonNull(key.apply(model), "Missing row key");
if (!keys.add(id)) throw new IllegalArgumentException("Duplicate row key");
Map<String, FilterValue> values = new HashMap<>();
for (var column : columns.values()) {
FilterValue value = column.read().apply(model);
column.validate(value);
values.put(column.id(), value);
}
snapshot.add(new Snapshot<>(id, model, Collections.unmodifiableMap(values)));
}
executor.execute(
() -> {
try {
checkCancelled(cancelled);
List<Snapshot<K, T>> matching = new ArrayList<>();
for (var row : snapshot) {
checkCancelled(cancelled);
if (predicates.stream().allMatch(p -> p.test(row)))
matching.add(row);
}
long count = matching.size();
if (query.page() instanceof PageRequest.All
&& !options.allApproved()
&& count > options.allWarningThreshold())
throw new AllRowsConfirmationRequired(count);
matching.sort(
(left, right) -> {
checkCancelled(cancelled);
for (var sort : query.sort()) {
FilterValue a = left.values().get(sort.columnId()),
b = right.values().get(sort.columnId());
if (a == null || b == null) {
if (a != b) return a == null ? 1 : -1;
continue;
}
int c = compare(a, b);
if (c != 0)
return sort.direction()
== SortKey.Direction.ASCENDING
? c
: -c;
}
int byKey = keyOrder.compare(left.key(), right.key());
if (byKey == 0
&& !Objects.equals(left.key(), right.key())) {
throw new IllegalArgumentException(
"Row key comparator must distinguish keys");
}
return byKey;
});
int from = 0, to = matching.size();
boolean hasNext = false;
if (query.page() instanceof PageRequest.Paged page) {
from = (int) Math.min(count, page.offset());
to = (int) Math.min(count, (long) from + page.pageSize());
hasNext = to < count;
}
List<GridRow<K, T>> rows = new ArrayList<>();
for (int i = from; i < to; i++) {
checkCancelled(cancelled);
var row = matching.get(i);
rows.add(new GridRow<>(row.key(), row.model()));
}
checkCancelled(cancelled);
result.complete(
new PageResult<>(
query.page(), rows, OptionalLong.of(count), hasNext));
} catch (RuntimeException failure) {
result.completeExceptionally(failure);
}
});
} catch (RuntimeException failure) {
result.completeExceptionally(failure);
}
return new QueryExecution<>() {
public CompletionStage<PageResult<K, T>> result() {
return result;
}
public void cancel() {
cancelled.set(true);
result.completeExceptionally(new CancellationException("Superseded query"));
}
};
}
@Override
public String filterExecutionId() {
return "local";
}
@Override
public void validateFilter(FilterCondition condition) {
compile(column(condition.columnId()), condition);
}
/** Explicitly attached source-wide candidates; all other column conditions are respected. */
public FilterCandidates.Provider candidateProvider(Function<FilterValue, String> label) {
Objects.requireNonNull(label);
return FilterCandidates.snapshot(
Set.of(FilterCandidates.Scope.SOURCE_WIDE),
context -> {
var selected = column(context.columnId());
var tests =
context.otherFilters().stream()
.map(
condition ->
Map.entry(
condition.columnId(),
compile(
column(condition.columnId()),
condition)))
.toList();
List<Map<String, FilterValue>> snapshot = new ArrayList<>();
for (T model : List.copyOf(data.get())) {
Map<String, FilterValue> values = new HashMap<>();
for (var column : columns.values()) {
var value = column.read().apply(model);
column.validate(value);
values.put(column.id(), value);
}
snapshot.add(Collections.unmodifiableMap(values));
}
return () ->
snapshot.stream()
.filter(
values ->
tests.stream()
.allMatch(
test ->
test.getValue()
.test(
values
.get(
test
.getKey()))))
.map(values -> values.get(selected.id()))
.distinct()
.map(
value ->
new FilterCandidates.Candidate(
value, label.apply(value)))
.toList();
},
executor);
}
private MemoryColumn<T> column(String id) {
var column = columns.get(id);
if (column == null) throw new IllegalArgumentException("Unknown column: " + id);
return column;
}
private Predicate<FilterValue> compile(MemoryColumn<T> column, FilterCondition condition) {
if (condition instanceof MissingFilter filter) return value -> filter.matches(value);
if (condition instanceof ValueFilter filter) {
filter.values().forEach(column::validate);
return filter::matches;
}
if (condition instanceof TextFilter filter) {
if (column.kind() != MemoryColumn.Kind.TEXT)
throw new IllegalArgumentException("Text filter requires a text column");
return value ->
filter.matches(value == null ? null : ((FilterValue.Text) value).value());
}
if (condition instanceof NumericFilter filter) {
if (column.kind() != MemoryColumn.Kind.INTEGER
&& column.kind() != MemoryColumn.Kind.DECIMAL)
throw new IllegalArgumentException("Numeric filter requires a numeric column");
if (column.kind() == MemoryColumn.Kind.INTEGER) {
filter.operand().longValueExact();
if (filter.upper() != null) filter.upper().longValueExact();
}
return value -> filter.matches(value == null ? null : number(value));
}
var compiler = column.customFilters().get(condition.typeId());
if (compiler == null)
throw new UnsupportedOperationException("Unsupported filter: " + condition.typeId());
return Objects.requireNonNull(compiler.apply(condition));
}
private static BigDecimal number(FilterValue value) {
return value instanceof FilterValue.IntegerValue i
? BigDecimal.valueOf(i.value())
: ((FilterValue.Decimal) value).value();
}
private static int compare(FilterValue a, FilterValue b) {
if (a instanceof FilterValue.Text text)
return text.value()
.toLowerCase(Locale.ROOT)
.compareTo(((FilterValue.Text) b).value().toLowerCase(Locale.ROOT));
if (a instanceof FilterValue.BooleanValue bool)
return Boolean.compare(bool.value(), ((FilterValue.BooleanValue) b).value());
return number(a).compareTo(number(b));
}
private static void checkCancelled(AtomicBoolean cancelled) {
if (cancelled.get()) throw new CancellationException("Superseded query");
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
/** Explicit missing/present test; empty strings are present. */
public record MissingFilter(String columnId, boolean missing) implements FilterCondition {
public MissingFilter {
Checks.id(columnId);
}
public String typeId() {
return "neitzel.missing";
}
public boolean matches(Object value) {
return (value == null) == missing;
}
}
@@ -0,0 +1,46 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.Objects;
/** Exact numeric comparison. Column/domain precision validation belongs to the source mapping. */
public record NumericFilter(
String columnId, Operator operator, BigDecimal operand, BigDecimal upper)
implements FilterCondition {
public enum Operator {
EQUALS,
LESS,
LESS_OR_EQUAL,
GREATER,
GREATER_OR_EQUAL,
RANGE
}
public NumericFilter {
Checks.id(columnId);
Objects.requireNonNull(operator);
Objects.requireNonNull(operand);
if (operator == Operator.RANGE) {
Objects.requireNonNull(upper);
if (operand.compareTo(upper) > 0) throw new IllegalArgumentException("Reversed range");
} else if (upper != null)
throw new IllegalArgumentException("Upper bound is only valid for a range");
}
public String typeId() {
return "neitzel.number";
}
public boolean matches(BigDecimal value) {
if (value == null) return false;
int c = value.compareTo(operand);
return switch (operator) {
case EQUALS -> c == 0;
case LESS -> c < 0;
case LESS_OR_EQUAL -> c <= 0;
case GREATER -> c > 0;
case GREATER_OR_EQUAL -> c >= 0;
case RANGE -> c >= 0 && value.compareTo(upper) <= 0;
};
}
}
@@ -0,0 +1,18 @@
package de.neitzel.grid;
/** Explicit offset paging or unpaged execution. All is never encoded as a magic page size. */
public sealed interface PageRequest {
/** Zero-based page index. UI page labels may be one-based. */
record Paged(long pageIndex, int pageSize) implements PageRequest {
public Paged {
if (pageIndex < 0 || pageSize <= 0) throw new IllegalArgumentException("Invalid page");
Math.multiplyExact(pageIndex, (long) pageSize);
}
public long offset() {
return Math.multiplyExact(pageIndex, (long) pageSize);
}
}
record All() implements PageRequest {}
}
@@ -0,0 +1,29 @@
package de.neitzel.grid;
import java.util.*;
/** A materialized result with exact filtered total or an explicit next-page indication. */
public record PageResult<K, T>(
PageRequest request, List<GridRow<K, T>> rows, OptionalLong total, boolean hasNext) {
public PageResult {
Objects.requireNonNull(request);
rows = List.copyOf(rows);
Objects.requireNonNull(total);
Set<K> keys = new HashSet<>();
for (var row : rows)
if (!keys.add(row.key())) throw new IllegalArgumentException("Duplicate row key");
if (total.isPresent() && total.getAsLong() < 0)
throw new IllegalArgumentException("Negative total");
if (request instanceof PageRequest.Paged p) {
if (rows.size() > p.pageSize()) throw new IllegalArgumentException("Too many rows");
if (total.isPresent()) {
long remaining = Math.max(0, total.getAsLong() - p.offset());
if (rows.size() != Math.min(remaining, p.pageSize())
|| hasNext != (remaining > p.pageSize()))
throw new IllegalArgumentException("Rows/count/navigation disagree");
} else if (hasNext && rows.size() != p.pageSize())
throw new IllegalArgumentException("Next page requires a full page");
} else if (hasNext || (total.isPresent() && total.getAsLong() != rows.size()))
throw new IllegalArgumentException("Invalid unpaged result");
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
/** Per-attempt execution consent. Never persist this with a setup or reuse across user requests. */
public record QueryOptions(long allWarningThreshold, boolean allApproved) {
public QueryOptions {
if (allWarningThreshold < 0)
throw new IllegalArgumentException("Negative All warning threshold");
}
public static QueryOptions defaults() {
return new QueryOptions(1000, false);
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
import java.util.Objects;
/** Sort by mapped column, with missing values last in either direction. */
public record SortKey(String columnId, Direction direction) {
public enum Direction {
ASCENDING,
DESCENDING
}
public SortKey {
Checks.id(columnId);
Objects.requireNonNull(direction);
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
/** Source-level page support; filter semantics are validated separately. */
public record SourceCapabilities(boolean exactTotal, boolean all, int maximumPageSize) {
public SourceCapabilities {
if (maximumPageSize <= 0) throw new IllegalArgumentException("Invalid maximum page size");
}
public void validate(PageRequest request) {
java.util.Objects.requireNonNull(request);
if (request instanceof PageRequest.All && !all)
throw new IllegalArgumentException("Source does not support All");
if (request instanceof PageRequest.Paged p && p.pageSize() > maximumPageSize)
throw new IllegalArgumentException("Unsupported page size");
}
}
@@ -0,0 +1,41 @@
package de.neitzel.grid;
import java.util.Locale;
import java.util.Objects;
/**
* Literal text comparison; missing values never match. No accent removal or Unicode normalization.
*/
public record TextFilter(String columnId, Operator operator, String operand, boolean caseSensitive)
implements FilterCondition {
public enum Operator {
EQUALS,
CONTAINS,
STARTS_WITH,
ENDS_WITH
}
public TextFilter {
Checks.id(columnId);
Objects.requireNonNull(operator);
Objects.requireNonNull(operand);
if (operand.isEmpty() && operator != Operator.EQUALS)
throw new IllegalArgumentException("Empty search operand");
}
public String typeId() {
return "neitzel.text";
}
public boolean matches(String value) {
if (value == null) return false;
String left = caseSensitive ? value : value.toLowerCase(Locale.ROOT),
right = caseSensitive ? operand : operand.toLowerCase(Locale.ROOT);
return switch (operator) {
case EQUALS -> left.equals(right);
case CONTAINS -> left.contains(right);
case STARTS_WITH -> left.startsWith(right);
case ENDS_WITH -> left.endsWith(right);
};
}
}
@@ -0,0 +1,22 @@
package de.neitzel.grid;
import java.util.Set;
/**
* Explicit allowed values. An empty set with includeMissing=false matches nothing, not everything.
*/
public record ValueFilter(String columnId, Set<FilterValue> values, boolean includeMissing)
implements FilterCondition {
public ValueFilter {
Checks.id(columnId);
values = Set.copyOf(values);
}
public String typeId() {
return "neitzel.values";
}
public boolean matches(FilterValue value) {
return value == null ? includeMissing : values.contains(value);
}
}
@@ -0,0 +1,101 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.*;
class FilterCandidatesTest {
@Test
void currentPageCapturesAtOpenAndSeparatesLabelsFromValues() throws Exception {
var values =
new ArrayList<>(
List.of(
new FilterCandidates.Candidate(new FilterValue.Text("a"), "Same"),
new FilterCandidates.Candidate(new FilterValue.Text("b"), "Same"),
new FilterCandidates.Candidate(null, "Missing")));
var provider = FilterCandidates.currentPage(() -> values);
var context =
new FilterCandidates.Context("x", FilterCandidates.Scope.CURRENT_PAGE, List.of());
try (var session = provider.open(context)) {
values.clear();
var first =
session.load(new FilterCandidates.Request(context, "same", 0, 1))
.toCompletableFuture()
.get();
assertTrue(first.hasMore());
assertEquals(new FilterValue.Text("a"), first.candidates().getFirst().value());
var next =
session.load(new FilterCandidates.Request(context, "same", 1, 1))
.toCompletableFuture()
.get();
assertFalse(next.hasMore());
assertEquals(new FilterValue.Text("b"), next.candidates().getFirst().value());
}
assertThrows(
UnsupportedOperationException.class,
() ->
provider.open(
new FilterCandidates.Context(
"x", FilterCandidates.Scope.SOURCE_WIDE, List.of())));
assertThrows(
IllegalArgumentException.class,
() ->
new FilterCandidates.Context(
"x",
FilterCandidates.Scope.SOURCE_WIDE,
List.of(new MissingFilter("x", true))));
}
@Test
void sourceWideRespectsOtherFiltersAndClosingCancelsPendingWork() throws Exception {
record Item(long id, String value, long group) {}
var jobs = new ArrayDeque<Runnable>();
var data =
new ArrayList<>(
List.of(new Item(1, "a", 1), new Item(2, "b", 2), new Item(3, "a", 1)));
var source =
new MemoryGridSource<Long, Item>(
() -> data,
Item::id,
Long::compare,
List.of(
new MemoryColumn<>(
"x",
MemoryColumn.Kind.TEXT,
i -> new FilterValue.Text(i.value())),
new MemoryColumn<>(
"group",
MemoryColumn.Kind.INTEGER,
i -> new FilterValue.IntegerValue(i.group()))),
jobs::add,
50);
var context =
new FilterCandidates.Context(
"x",
FilterCandidates.Scope.SOURCE_WIDE,
List.of(
new ValueFilter(
"group", Set.of(new FilterValue.IntegerValue(1)), false)));
var session = source.candidateProvider(v -> ((FilterValue.Text) v).value()).open(context);
data.clear();
var first =
session.load(new FilterCandidates.Request(context, "", 0, 10))
.toCompletableFuture();
jobs.remove().run();
assertEquals(
List.of(new FilterCandidates.Candidate(new FilterValue.Text("a"), "a")),
first.get().candidates());
var pending =
session.load(new FilterCandidates.Request(context, "", 0, 10))
.toCompletableFuture();
session.close();
jobs.remove().run();
assertTrue(pending.isCancelled());
assertThrows(
IllegalStateException.class,
() -> session.load(new FilterCandidates.Request(context, "", 0, 10)));
}
}
@@ -0,0 +1,114 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.*;
class GridContractsTest {
@Test
void textIsLiteralAndMissingIsNotEmpty() {
assertTrue(
new TextFilter("name", TextFilter.Operator.CONTAINS, "%_", false).matches("a%_B"));
assertFalse(new TextFilter("name", TextFilter.Operator.EQUALS, "", false).matches(null));
assertTrue(new TextFilter("name", TextFilter.Operator.EQUALS, "", false).matches(""));
assertThrows(
IllegalArgumentException.class,
() -> new TextFilter("name", TextFilter.Operator.CONTAINS, "", false));
assertFalse(new TextFilter("name", TextFilter.Operator.EQUALS, "ss", false).matches("ß"));
}
@Test
void decimalsAreExactAndChecklistsKeepExactText() {
assertTrue(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("9007199254740993.00"),
null)
.matches(new BigDecimal("9007199254740993")));
assertFalse(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("9007199254740993"),
null)
.matches(new BigDecimal("9007199254740992")));
var values =
new ValueFilter(
"price", Set.of(new FilterValue.Decimal(new BigDecimal("1.0"))), false);
assertTrue(values.matches(new FilterValue.Decimal(new BigDecimal("1.00"))));
assertFalse(
new ValueFilter("name", Set.of(new FilterValue.Text("Alpha")), false)
.matches(new FilterValue.Text("alpha")));
assertFalse(new ValueFilter("name", Set.of(), false).matches(null));
assertTrue(new MissingFilter("name", false).matches(""));
}
@Test
void queryAndSetupAreDefensivelyCopiedAndRejectAmbiguity() {
var filters = new ArrayList<FilterCondition>();
filters.add(new MissingFilter("name", true));
var q = new GridQuery(filters, List.of(), new PageRequest.All());
filters.clear();
assertEquals(1, q.filters().size());
assertThrows(UnsupportedOperationException.class, () -> q.filters().clear());
assertThrows(
IllegalArgumentException.class,
() ->
new GridQuery(
List.of(
new MissingFilter("a", true),
new MissingFilter("a", false)),
List.of(),
new PageRequest.All()));
assertThrows(
IllegalArgumentException.class,
() ->
new GridSetup(
1,
"products",
1,
List.of(new GridSetup.ColumnState("a", new ColumnWidth.Default())),
List.of(),
List.of(),
new PageRequest.Paged(1, 50)));
assertThrows(IllegalArgumentException.class, () -> new ColumnWidth.Explicit(Double.NaN));
}
@Test
void resultsValidateCountsButAllowDisappearedPages() {
var row = new GridRow<>(1, "one");
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.Paged(0, 2),
List.of(row, row),
OptionalLong.of(2),
false));
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.Paged(0, 2),
List.of(row),
OptionalLong.of(3),
true));
assertDoesNotThrow(
() ->
new PageResult<>(
new PageRequest.Paged(4, 2), List.of(), OptionalLong.of(2), false));
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.All(), List.of(row), OptionalLong.of(2), false));
assertThrows(ArithmeticException.class, () -> new PageRequest.Paged(Long.MAX_VALUE, 250));
assertThrows(
IllegalArgumentException.class,
() -> new SourceCapabilities(true, false, 100).validate(new PageRequest.All()));
}
}
@@ -0,0 +1,301 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class GridCoordinatorTest {
static class Source implements GridSource<Integer, String> {
List<CompletableFuture<PageResult<Integer, String>>> futures = new ArrayList<>();
List<GridQuery> queries = new ArrayList<>();
List<QueryOptions> options = new ArrayList<>();
int cancellations;
public SourceCapabilities capabilities() {
return new SourceCapabilities(true, true, 250);
}
public QueryExecution<Integer, String> query(GridQuery q) {
return query(q, QueryOptions.defaults());
}
public QueryExecution<Integer, String> query(GridQuery q, QueryOptions o) {
queries.add(q);
options.add(o);
var f = new CompletableFuture<PageResult<Integer, String>>();
futures.add(f);
return new QueryExecution<>() {
public CompletionStage<PageResult<Integer, String>> result() {
return f;
}
public void cancel() {
cancellations++;
}
};
}
}
static GridQuery q(long page) {
return new GridQuery(List.of(), List.of(), new PageRequest.Paged(page, 1));
}
static PageResult<Integer, String> page(long index, int key) {
return new PageResult<>(
new PageRequest.Paged(index, 1),
List.of(new GridRow<>(key, "row" + key)),
OptionalLong.of(10),
index < 9);
}
static class Harness {
Source source = new Source();
ArrayDeque<Runnable> callbacks = new ArrayDeque<>();
List<PageResult<Integer, String>> published = new ArrayList<>();
GridCoordinator<Integer, String> c =
new GridCoordinator<>(source, callbacks::add, s -> {}, published::add);
void drain() {
while (!callbacks.isEmpty()) callbacks.remove().run();
}
void request(GridQuery q) {
c.request(q);
drain();
}
}
@Test
void staleSuccessFailureAndGuardApprovalCannotPublish() {
var h = new Harness();
h.request(q(0));
h.request(q(1));
assertEquals(1, h.source.cancellations);
h.source.futures.get(1).complete(page(1, 2));
h.drain();
h.source.futures.get(0).completeExceptionally(new IllegalStateException("old"));
h.drain();
assertEquals(1, h.published.size());
assertEquals(GridCoordinator.Phase.READY, h.c.state().phase());
CompletableFuture<Boolean> guard = new CompletableFuture<>();
h.c.setGuard(q -> guard);
h.c.request(q(2));
h.c.setGuard(q -> CompletableFuture.completedFuture(true));
h.request(q(3));
guard.complete(true);
h.drain();
assertEquals(3, h.source.queries.size());
assertEquals(q(3), h.source.queries.getLast());
h.c.close();
h.source.futures.getLast().complete(page(3, 4));
h.drain();
assertEquals(1, h.published.size());
}
@Test
void errorsRetainPageAndRetryLatestQuery() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
h.request(q(1));
h.source.futures.getLast().completeExceptionally(new IllegalStateException("unavailable"));
h.drain();
assertEquals(GridCoordinator.Phase.ERROR, h.c.state().phase());
assertEquals(q(0), h.c.state().displayed());
h.c.retry();
h.drain();
assertEquals(q(1), h.source.queries.getLast());
h.source.futures.getLast().complete(page(1, 2));
h.drain();
assertEquals(q(1), h.c.state().displayed());
}
@Test
void disappearingPagesHaveOnlyOneCorrection() {
var h = new Harness();
h.request(q(9));
h.source
.futures
.getFirst()
.complete(new PageResult<>(q(9).page(), List.of(), OptionalLong.of(2), false));
h.drain();
assertEquals(q(1), h.source.queries.getLast());
h.source
.futures
.getLast()
.complete(new PageResult<>(q(1).page(), List.of(), OptionalLong.of(1), false));
h.drain();
assertEquals(2, h.source.queries.size());
assertEquals(GridCoordinator.Phase.ERROR, h.c.state().phase());
}
@Test
void allApprovalIsAttemptScopedAndCancellationRestoresPage() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
var all = new GridQuery(List.of(), List.of(), new PageRequest.All());
CompletableFuture<Boolean> consent = new CompletableFuture<>();
h.c.setConfirmation((q, count) -> consent);
h.request(all);
h.source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertEquals(GridCoordinator.Phase.CONFIRMATION, h.c.state().phase());
consent.complete(false);
h.drain();
assertEquals(q(0), h.c.state().requested());
assertEquals(1, h.published.size());
h.c.setConfirmation((q, count) -> CompletableFuture.completedFuture(true));
h.request(all);
h.source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertTrue(h.source.options.getLast().allApproved());
h.request(q(2));
h.source
.futures
.get(h.source.futures.size() - 2)
.complete(
new PageResult<>(
new PageRequest.All(), List.of(), OptionalLong.of(0), false));
h.drain();
assertEquals(1, h.published.size());
}
@Test
void sourceReplacementIsNotCommittedWhenAllWarningIsCancelled() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
var replacement = new Source();
h.c.setConfirmation((q, n) -> CompletableFuture.completedFuture(false));
h.c.request(replacement, new GridQuery(List.of(), List.of(), new PageRequest.All()));
h.drain();
replacement.futures.getFirst().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertEquals(0, h.c.state().sourceVersion());
h.c.refresh();
h.drain();
assertEquals(2, h.source.queries.size());
}
@Test
void unknownTotalsRecoverToFirstPageAndInvalidResponsesAreErrors() {
var source =
new Source() {
public SourceCapabilities capabilities() {
return new SourceCapabilities(false, false, 250);
}
};
var jobs = new ArrayDeque<Runnable>();
var coordinator =
new GridCoordinator<Integer, String>(source, jobs::add, state -> {}, result -> {});
coordinator.request(q(4));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures
.getFirst()
.complete(new PageResult<>(q(4).page(), List.of(), OptionalLong.empty(), false));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(q(0), source.queries.getLast());
source.futures
.getLast()
.complete(
new PageResult<>(
q(0).page(),
List.of(new GridRow<>(1, "a")),
OptionalLong.empty(),
true));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.READY, coordinator.state().phase());
coordinator.request(q(1));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getLast().complete(page(0, 2));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.ERROR, coordinator.state().phase());
assertEquals(q(0), coordinator.state().displayed());
coordinator.close();
assertNull(coordinator.state().result());
}
@Test
void lateConfirmationAndObserverTriggeredRequestsAreSerialized() {
var source = new Source();
var jobs = new ArrayDeque<Runnable>();
var holder = new AtomicReference<GridCoordinator<Integer, String>>();
var jumped = new AtomicBoolean();
var coordinator =
new GridCoordinator<Integer, String>(
source,
jobs::add,
state -> {
if (state.phase() == GridCoordinator.Phase.READY
&& jumped.compareAndSet(false, true))
holder.get().request(q(1));
},
result -> {});
holder.set(coordinator);
coordinator.request(q(0));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getFirst().complete(page(0, 1));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(q(1), coordinator.state().requested());
assertEquals(GridCoordinator.Phase.LOADING, coordinator.state().phase());
var consent = new CompletableFuture<Boolean>();
coordinator.setConfirmation((q, n) -> consent);
coordinator.request(new GridQuery(List.of(), List.of(), new PageRequest.All()));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
while (!jobs.isEmpty()) jobs.remove().run();
coordinator.request(q(2));
while (!jobs.isEmpty()) jobs.remove().run();
int count = source.queries.size();
consent.complete(true);
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(count, source.queries.size());
assertEquals(q(2), coordinator.state().requested());
}
@Test
void closeDuringPublicationOrConfirmationDoesNotResurrectCoordinator() {
for (boolean closeInPublisher : List.of(true, false)) {
var source = new Source();
var jobs = new ArrayDeque<Runnable>();
var holder = new AtomicReference<GridCoordinator<Integer, String>>();
var coordinator =
new GridCoordinator<Integer, String>(
source,
jobs::add,
state -> {
if (!closeInPublisher
&& state.phase() == GridCoordinator.Phase.CONFIRMATION)
holder.get().close();
},
result -> holder.get().close());
holder.set(coordinator);
coordinator.setConfirmation(
(q, n) -> {
fail("Closed coordinator must not open confirmation");
return CompletableFuture.completedFuture(true);
});
coordinator.request(
closeInPublisher
? q(0)
: new GridQuery(List.of(), List.of(), new PageRequest.All()));
while (!jobs.isEmpty()) jobs.remove().run();
if (closeInPublisher) source.futures.getFirst().complete(page(0, 1));
else
source.futures
.getFirst()
.completeExceptionally(new AllRowsConfirmationRequired(1001));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.CLOSED, coordinator.state().phase());
assertNull(coordinator.state().result());
}
}
}
@@ -0,0 +1,176 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
class GridDefinitionTest {
static GridDefinition.Column column(String id, String type, int fixed) {
return new GridDefinition.Column(id, type, 100, 50, 200, fixed);
}
static GridSetup saved(String type) {
return new GridSetup(
1,
"products",
1,
List.of(new GridSetup.ColumnState("a", type, new ColumnWidth.Explicit(300))),
List.of(),
List.of(),
new PageRequest.Paged(0, 25));
}
@Test
void addsNewColumnsClampsWidthsAndPreservesDefaultIntent() {
var d =
new GridDefinition(
"products",
1,
List.of(column("a", "text", -1), column("b", "integer", -1)));
var prepared =
d.prepare(saved("text"), Map.of(), new SourceCapabilities(true, true, 50), f -> {});
assertEquals(
List.of(
new GridSetup.ColumnState("a", "text", new ColumnWidth.Explicit(200)),
new GridSetup.ColumnState("b", "integer", new ColumnWidth.Default())),
prepared.setup().columns());
assertEquals(1, prepared.adjustments().size());
}
@Test
void identityTypesUnknownColumnsAndFixedPositionsRequireExplicitMigration() {
var d =
new GridDefinition(
"products", 1, List.of(column("b", "text", 0), column("a", "text", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var changed = new GridDefinition("products", 1, List.of(column("a", "integer", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
changed.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var removed = new GridDefinition("products", 1, List.of(column("b", "text", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
removed.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
assertThrows(
IllegalArgumentException.class,
() ->
new GridDefinition("other", 1, List.of(column("a", "text", -1)))
.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
}
@Test
void migrationsMustAdvanceAndRemainSubjectToFullValidation() {
var d = new GridDefinition("products", 2, List.of(column("a", "integer", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var result =
d.prepare(
saved("text"),
Map.of(
1,
s ->
new GridSetup(
1,
s.definitionId(),
2,
List.of(
new GridSetup.ColumnState(
"a",
"integer",
new ColumnWidth.Default())),
s.sort(),
s.filters(),
s.page())),
new SourceCapabilities(true, true, 50),
f -> {});
assertEquals(2, result.setup().definitionVersion());
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(1, s -> s),
new SourceCapabilities(true, true, 50),
f -> {}));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(
1,
s ->
new GridSetup(
1,
s.definitionId(),
2,
s.columns(),
s.sort(),
s.filters(),
s.page())),
new SourceCapabilities(true, true, 50),
f -> {}));
}
@Test
void actualFilterAndPageCapabilitiesAreCheckedBeforeExecution() {
var d = new GridDefinition("products", 1, List.of(column("a", "text", -1)));
var s = saved("text");
var filtered =
new GridSetup(
1,
"products",
1,
s.columns(),
List.of(),
List.of(new MissingFilter("a", true)),
new PageRequest.All());
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
filtered,
Map.of(),
new SourceCapabilities(true, false, 50),
f -> {}));
assertThrows(
UnsupportedOperationException.class,
() ->
d.prepare(
filtered,
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {
throw new UnsupportedOperationException("Missing unsupported");
}));
}
}
@@ -0,0 +1,247 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
class MemoryGridSourceTest {
record Product(long id, String name, Long quantity, BigDecimal price) {}
static MemoryGridSource<Long, Product> source(List<Product> rows, Executor executor) {
return new MemoryGridSource<>(
() -> rows,
Product::id,
Long::compare,
List.of(
new MemoryColumn<>(
"name",
MemoryColumn.Kind.TEXT,
p -> p.name() == null ? null : new FilterValue.Text(p.name())),
new MemoryColumn<>(
"quantity",
MemoryColumn.Kind.INTEGER,
p ->
p.quantity() == null
? null
: new FilterValue.IntegerValue(p.quantity())),
new MemoryColumn<>(
"price",
MemoryColumn.Kind.DECIMAL,
p ->
p.price() == null
? null
: new FilterValue.Decimal(p.price()))),
executor,
250);
}
static GridQuery query(List<FilterCondition> f, PageRequest p) {
return new GridQuery(f, List.of(new SortKey("name", SortKey.Direction.DESCENDING)), p);
}
@Test
void filteringSortingAndPagingUseWholeSnapshotAndStableKeys() {
var rows =
new ArrayList<>(
List.of(
new Product(3, "alpha", 3L, new BigDecimal("1.00")),
new Product(1, "Alpha", 1L, new BigDecimal("1.0")),
new Product(2, null, 2L, null),
new Product(4, "Zulu", 4L, new BigDecimal("2"))));
var source = source(rows, Runnable::run);
var page =
source.query(query(List.of(), new PageRequest.Paged(1, 2)))
.result()
.toCompletableFuture()
.join();
assertEquals(List.of(3L, 2L), page.rows().stream().map(GridRow::key).toList());
assertEquals(4, page.total().orElseThrow());
assertFalse(page.hasNext());
var filtered =
source.query(
query(
List.of(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("1"),
null)),
new PageRequest.Paged(0, 1)))
.result()
.toCompletableFuture()
.join();
assertEquals(1L, filtered.rows().getFirst().key());
assertEquals(2, filtered.total().orElseThrow());
assertTrue(filtered.hasNext());
assertEquals(List.of(3L, 1L, 2L, 4L), rows.stream().map(Product::id).toList());
}
@Test
void snapshotIsCapturedBeforeExecutorAndCancellationDoesNotInterrupt() {
var jobs = new ArrayDeque<Runnable>();
var rows = new ArrayList<>(List.of(new Product(1, "original", 1L, null)));
var source = source(rows, jobs::add);
var request = source.query(query(List.of(), new PageRequest.Paged(0, 25)));
rows.clear();
jobs.remove().run();
assertEquals(1, request.result().toCompletableFuture().join().rows().size());
var cancelled = source.query(query(List.of(), new PageRequest.Paged(0, 25)));
cancelled.cancel();
jobs.remove().run();
assertThrows(
CancellationException.class, () -> cancelled.result().toCompletableFuture().join());
}
@Test
void allChecksFilteredCountBeforeReturningRowsAndRechecksOnApproval() {
var rows =
new ArrayList<>(
List.of(new Product(1, "a", 1L, null), new Product(2, "b", 2L, null)));
var source = source(rows, Runnable::run);
var q = query(List.of(), new PageRequest.All());
var error =
assertThrows(
CompletionException.class,
() ->
source.query(q, new QueryOptions(1, false))
.result()
.toCompletableFuture()
.join());
assertInstanceOf(AllRowsConfirmationRequired.class, error.getCause());
rows.add(new Product(3, "c", 3L, null));
assertEquals(
3,
source.query(q, new QueryOptions(1, true))
.result()
.toCompletableFuture()
.join()
.rows()
.size());
assertEquals(
3,
source.query(q, new QueryOptions(3, false))
.result()
.toCompletableFuture()
.join()
.rows()
.size());
}
@Test
void typesUnsupportedConditionsAndDuplicateKeysFailVisibly() {
var source = source(List.of(new Product(1, "a", 1L, null)), Runnable::run);
assertThrows(
CompletionException.class,
() ->
source.query(
query(
List.of(
new NumericFilter(
"quantity",
NumericFilter.Operator.EQUALS,
new BigDecimal("1.5"),
null)),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join());
FilterCondition custom =
new FilterCondition() {
public String columnId() {
return "name";
}
public String typeId() {
return "unsupported";
}
};
assertInstanceOf(
UnsupportedOperationException.class,
assertThrows(
CompletionException.class,
() ->
source.query(
query(
List.of(custom),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join())
.getCause());
var dup =
source(
List.of(new Product(1, "a", 1L, null), new Product(1, "b", 2L, null)),
Runnable::run);
assertThrows(
CompletionException.class,
() ->
dup.query(query(List.of(), new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join());
}
private record LongName(String columnId) implements FilterCondition {
public String typeId() {
return "demo.long-name";
}
}
@Test
void registeredCustomEvaluationRunsOnApplicationExecutor() throws Exception {
Thread caller = Thread.currentThread();
var evaluatedOn = new java.util.concurrent.atomic.AtomicReference<Thread>();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
MemoryColumn<Product> name =
new MemoryColumn<>(
"name",
MemoryColumn.Kind.TEXT,
p -> {
assertSame(caller, Thread.currentThread());
return new FilterValue.Text(p.name());
},
Map.of(
"demo.long-name",
condition -> {
if (!(condition instanceof LongName))
throw new IllegalArgumentException(
"Unsupported custom condition");
return value -> {
evaluatedOn.set(Thread.currentThread());
return value instanceof FilterValue.Text text
&& text.value().length() > 3;
};
}));
var source =
new MemoryGridSource<Long, Product>(
() ->
List.of(
new Product(1, "Alpha", 1L, null),
new Product(2, "Bee", 2L, null)),
Product::id,
Long::compare,
List.of(name),
executor,
100);
var result =
source.query(
new GridQuery(
List.of(new LongName("name")),
List.of(),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.get(5, TimeUnit.SECONDS);
assertEquals(List.of(1L), result.rows().stream().map(GridRow::key).toList());
assertNotSame(caller, evaluatedOn.get());
assertFalse(executor.isShutdown());
} finally {
executor.shutdownNow();
}
}
}
+26 -1
View File
@@ -2,6 +2,25 @@
This runnable application demonstrates [NeitzelLib FX](../fx/README.md) and [injection](../injection/README.md) together. It edits one Person with a home Address, nested Note, visit list, selected visit and tags. Use it as a reference for wiring a real screen; the [minimal quick start](../fx/docs/quick-start.md) is the smaller starting point for a new project.
Separate Java/FXML launchers demonstrate [standalone bars](../fx/docs/bars.md)
and [docking](../fx/docs/docking.md) without initializing MVVM or injection.
Their guides describe the implemented behavior and launch options. The
[MVVM docking editor](docs/docking-mvvm.md) shows how an already loaded View and
its local bars move between windows while global commands follow the active editor.
The [live reset example](docs/docking-reset.md) restores the starting arrangement
without replacing editors, and demonstrates an atomic rejection under changed placement rules.
The [snapshot example](../fx/docs/docking-snapshots.md) restores a saved arrangement
into a fresh workspace before it is shown, with load and cleanup diagnostics.
The [Quit/Replace example](../fx/docs/docking-shutdown.md) holds every window open
while saving or retrying, and can attach a fresh manager to the same main window.
The [complete workspace](../fx/docs/docking-workspace.md) combines Java/FXML startup,
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:
@@ -71,6 +90,12 @@ Changing a JavaBean setter directly after loading does not notify controls. All
## Automated regression coverage
The standalone `de.neitzel.fx.example.docking.CloseDockingMain` launcher shows
an editor waiting for an asynchronous close decision. Choose Close Notes, then
Keep open to continue editing or Allow close to release its content. The tab
close control and context menu use the same consent callback. See the
[tab-close guide](../fx/docs/docking-close.md) for the library contract.
`src/test/java/de/neitzel/fx/example/DeskLoadsTest.java` loads the real Desk FXML on JavaFX and checks initial values, all binding directions, derived/computed text, conversion failures and recovery, child messages, Table edits/removal, message severities and boolean/enum write-back. It also demonstrates that a direct bean setter leaves controls unchanged and that another simple View reuses the same Model's ViewModel.
Run the reactor tests without installing artifacts with:
@@ -79,7 +104,7 @@ Run the reactor tests without installing artifacts with:
./mvnw -pl fx-example -am clean verify
```
Inspect Surefire XML reports; a successful Maven exit alone is insufficient with the current parent configuration. JavaFX tests need a usable graphical environment. See the Designer integration section below for the optional preview setup; ordinary application tests do not require the Designer.
Inspect Surefire XML reports for test totals, failures and skips. JavaFX tests need a usable graphical environment. See the Designer integration section below for the optional preview setup; ordinary application tests do not require the Designer.
## Open the example in NeitzelFXDesigner
+55
View File
@@ -0,0 +1,55 @@
# MVVM content and local/global bars
The docking API accepts an ordinary Node. This example passes the root of one
`LoadedView` to a `Dockable`; the manager never loads that View again. Its Note
JavaBean, ViewModel, TextArea, local toolbar and local status bar remain the same
objects when the tab moves, floats or returns. A second editor uses a plain
TextArea without a ViewModel.
Build from the repository root with Java 25, without replacing installed runtime
artifacts used by the Designer:
```sh
./mvnw -pl fx-example -am package
java --enable-native-access=ALL-UNNAMED \
-cp 'fx-example/target/classes:fx/target/classes:fx-example/target/libs/*' \
de.neitzel.fx.example.docking.mvvm.MvvmDockingMain
```
In the example:
1. Edit Notes. Its tab title gains an asterisk and the local character count changes.
2. Choose **Move Notes to tools**, **Float Notes**, then **Return Notes**. The
local Clear note button and status bar travel with the editor; the global
command and status bars stay in the main window.
3. While Notes is floating, click **Checkpoint active** in the main window.
Notes keeps its command target when focus enters that toolbar. The command
records a checkpoint in memory and clears the asterisk; it does not save a file.
4. Select Plain editor. The checkpoint command is disabled for this content, and
the global status identifies the newly active Dockable.
5. Close Notes with its tab close button to run the application's close hook.
`MvvmEditor.fxml` declares a bidirectional DirectBinding between the TextArea and
the Note's `text` attribute. Application updates use `LoadedView.property("text")`;
calling a JavaBean setter directly does not notify an already loaded ViewModel.
`MvvmEditor` binds the Dockable title and local status to presentation properties.
`MvvmDockingWorkspace` binds the global command availability and status to
`activeDockableProperty()`. These are application bindings, not a docking-specific
MVVM service.
The application adapter owns its change listener and derived bindings. Its
`onClosed` and `onDiscarded` hooks release those resources explicitly. Moves,
collapse and veto do not run those hooks. A rejected factory-created editor is
discarded; rejection of a directly supplied Dockable leaves cleanup to its caller.
This does not dispose the LoadedView or evict the runtime's strong Model-to-ViewModel
identity cache. See the [MVVM lifetime contract](../../fx/docs/architecture.md).
`MvvmDockingTest` loads the actual example FXML and checks model/property/control
edits before and after moves, object identity, bar ownership, global toolbar
focus and resource hooks. Its Scene-focus assertions complement the separately
qualified [native keyboard transfer tests](../../fx/docs/docking-floating.md);
this integration test does not claim to inject native keystrokes.
For entirely independent docking and bars without initializing MVVM or injection,
use the [plain docking example](../../fx/docs/docking.md) and
[standalone bars example](../../fx/docs/bars.md).
+41
View File
@@ -0,0 +1,41 @@
# Reset a live workspace
`DockingManager.resetLayout()` restores the initial layout captured at attachment
while keeping every open Dockable and its content instance. Unsaved editor text,
selection and application resources remain live. Reset does not invoke close
consent, `onClosed` or `onDiscarded`.
The first successful open records the Dockable's intended initial area. Later
moves do not change that intention. Reset checks that area and then the configured
fallback for each live Dockable. A Dockable initially opened in a floating window
uses the main-window fallback. Changing the original Java/FXML configuration
objects after attachment does not change the captured starting layout.
Relative fallback positions are resolved after the intended home placements, so
their reference tab may have been opened later. Retired concrete group IDs stay
retired; use stable area IDs to address restored destinations.
All destinations are checked before any live content moves. A rejection names the
affected Dockable and leaves windows, selection and layout intact. Success removes
the emptied floating windows, restores the starting edge settings and publishes
one completed layout. A pending close protects its contents from a global reset.
The runnable example loads the ordinary `Docking.fxml` definition. Build and run
from the repository root with Java 25 without installing changed runtime artifacts:
```sh
./mvnw -pl fx-example -am package
java --enable-native-access=ALL-UNNAMED \
-cp 'fx-example/target/classes:fx/target/classes:fx-example/target/libs/*' \
de.neitzel.fx.example.docking.ResetDockingMain
```
1. Edit Notes and select some text.
2. Choose **Rearrange** to float Notes, split Readme below the editor area and move Project into that area.
3. Clear **Allow Project placement**, then choose **Reset layout**. The status
explains the rejection; the floating window and current arrangement remain.
4. Enable Project placement and reset again. Both editors return to the editor
area and Project returns to its starting side group, retaining the edits.
Use reset for an already populated manager. Snapshot restoration is the separate
startup operation that resolves new content for an empty manager. Applications
retain control of file saving and storage.
+34
View File
@@ -0,0 +1,34 @@
# Product DataGrid: memory and H2
This separate launcher uses the accepted DataGrid APIs without changing the person-desk application or legacy Table behavior. The application owns an embedded H2 **2.5.252** pool, its anchor connection, a four-worker executor, completion timer, immutable product fixtures and saved setup file. No server, credentials or stored procedures are needed. JDBC is in the optional `data-grid-jdbc` module; H2 remains example-owned.
From the repository root with JDK 25, build without installing runtime artifacts:
```sh
./mvnw -pl fx-example -am package -DskipTests
java -cp 'fx-example/target/fx-example-1.0-SNAPSHOT.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
```
The default catalog has 10,000 products. Both backends use identical stable IDs, names, categories, quantities and DECIMAL(12,2) prices. Fixtures include duplicate sort values, nulls, empty text, mixed case, Unicode, apostrophes and literal SQL wildcard characters. One `ProductCatalog` service maintains original text and Locale.ROOT comparison keys together on insertion/reset. Mutations run on application workers and explicitly refresh the grid; browsing is read-only.
## Interactive walkthrough
1. Browse 50 rows initially. Use header sorting and first/previous/next/last, then choose 25/100/250. Name filtering has a developer-configured **current-page** checklist; its scope is shown by the editor, and candidate values are exact originals. Other columns use comparison/missing modes. Source-wide checklist configuration remains available through the provider API but is not silently inferred here.
2. Open text/quantity/price filters. `%`, `_`, `!` and apostrophes are literal. Try a decimal range, empty text equality, missing prices and an empty checklist. Toggle **Custom budget editor** to use a separate FXML/controller that emits the same portable numeric condition. It runs on both sources and persists with the built-in numeric codec.
3. Select **Memory**, then **Memory-only filter** (names of at most five UTF-16 units). Switch to H2: the condition is rejected visibly, the previous result remains, and no SQL silently substitutes different behavior. Clear filters, then switch again. Saving a memory-only condition is also rejected because no codec is registered.
4. Toggle outside-click acceptance and OK/Cancel independently of the editor. Enter/Escape use the existing popup lifecycle. Native input qualification remains under the previously recorded waiver; these options do not claim a new OS-input qualification.
5. Choose a theme, select a row, widen Name or move Price first. **Save setup** writes atomically to `~/.neitzellib-example/products-setup.json`; **Load setup** decodes/validates and stages its layout/query atomically. Invalid JSON, unsupported versions/conditions and execution failures are visible and retain committed layout/data. Setup data never contains credentials, row data, selection or warning approval. **Load v1 setup** demonstrates an explicit migration from the former `group` column to `category`, updating column order, sort and text/checklist/missing conditions before querying the current definition version 2.
6. Choose **All**. Above the configurable default threshold of 1,000 matches, Continue/Cancel explains that all matching rows become real Components, consuming memory and potentially blocking responsiveness. Exactly the threshold does not warn. Cancel retains the previous setup/page. Loading a saved All setup asks again. Filtering, source switching or a newer request invalidates old approval. No connection stays borrowed while waiting for an answer.
7. Use **Slow next refresh** to inspect loading while old rows remain unavailable. **Fail next refresh** exposes the error; Retry succeeds normally. **Late success then failure** leaves the later failure visible. **Late failure then success** leaves the later success visible. These are deterministic completion delays/failures around real requests, not simulated SQL slowness; cancel-resistant completions deliberately exercise stale-result rejection.
8. Open **Request diagnostics** for local request IDs, requested/displayed pages, duration, row count, cancellation and obsolete completions. Source IDs restart for each wrapper; the selected source and coordinator generation disambiguate them.
9. Insert/delete selected/reset fixtures and refresh. Navigate to the last page and **Delete displayed page** to exercise bounded recovery when that page disappears. Deletion updates both datasets; this is demonstration tooling, not a CRUD framework.
## Qualification and limits
`JdbcProductTest` compares memory/SQL results for every supported condition/operator, exact membership, Unicode ordering, ties, boundaries, nulls and decimals. It injects a writer between count and row queries, observes borrowed resources/settings, checks cancellation and mapper failure, rejects invalid mappings before connection acquisition, and verifies the All warning race with a changed dataset.
`ProductGridDemoTest` loads real row/editor FXML, switches sources/themes, tests saving/restoring, visible capability errors, late responses, Retry, disappearing pages, cancelled/superseded All decisions and restored-All warnings. It measures an explicitly approved 10,000-row FXML materialization. New FX tests capture uncaught application-thread errors.
Outputs are `target/jdbc-evidence/{timings.txt,fx-materialization.txt,demo.png}`. Source timings include the full source query but exclude UI Components; the FX timing includes All confirmation scheduling, query and UI publication. These are single-run observations, not benchmarks or scale guarantees. Offset paging can require scanning/sorting earlier rows. All mode is unvirtualized and its render cost is substantially greater than a page. The optional 100,000-row run is not part of this qualification.
H2's default collation and snapshot behavior are the qualified database semantics. No claim covers other dialects, linguistic collation, JPA/Hibernate, arbitrary joins, date/time filters or arbitrary application overrides.
+22
View File
@@ -0,0 +1,22 @@
# Shared theme gallery
`de.neitzel.fx.example.theme.ThemeGalleryMain` opens the opt-in Light/Dark/High contrast gallery. It includes normal/hover/focus/disabled buttons, text edits, invalid/error/warning messages, check/radio/combo/date controls, a selected standard TableView, a filtered/selected DataGrid, a loading indicator, dialogs and floating editors.
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
```sh
java -cp 'fx-example/target/fx-example-1.0-SNAPSHOT.jar:fx-example/target/libs/*' \
de.neitzel.fx.example.theme.ThemeGalleryMain
```
Choose a theme in the top selector. Open a filter editor through the funnel button, a dialog or floating editor, and edit text. Theme changes preserve model/query/selection/layout and text drafts; an ordinary outside click still follows the filter popup's dismissal policy. API-driven switching while a draft is open is tested independently of that policy. The hover/focus buttons are labelled CSS-state specimens; they do not pretend to be native-input tests.
FILE/LIVE/REMOVE are example textual indicators which remain readable under selection. They are not a qualification of DNSCheck's actual domain palette, legends or workflows; that work remains in its integration ticket.
## Automated rendered evidence
`ThemeGalleryTest` writes `target/theme-gallery/light.png`, `dark.png`, `high-contrast.png`, matching popup images, `contrast.txt` and `window-contrast.txt`. The tests read actual JavaFX paints/backgrounds after CSS resolution, enforce the agreed contrast targets, check stable button dimensions and preserved grid/draft state, and fail on uncaught FX-thread errors. Main and popup snapshots are visually reviewed for clipping, focus/state distinctions and readability. The workspace implementation ticket stores durable copies and the qualified runtime baseline.
`ThemeManagerTest` covers opt-in behavior, application overrides, scene-root replacement, rollback across scenes, unavailable saved themes, live filter/nested-popup/dialog propagation, new-window registration, docking floating windows and cleanup. Existing legacy Table/docking tests remain in verification.
See [theme API and customization](../../fx/docs/themes.md) for ownership, CSS precedence, public palette/hooks and failure limitations. Application overrides, other fonts/scales/platforms, SubScene and HTML content need separate qualification.
+7
View File
@@ -21,11 +21,18 @@
</properties>
<dependencies>
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid-jdbc</artifactId><version>${project.version}</version></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version></dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>gson</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
@@ -0,0 +1,79 @@
package de.neitzel.fx.example.bars;
import de.neitzel.fx.control.StatusBar;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.IOException;
/** An ordinary JavaFX editor demonstrating standalone toolbar and status content. */
public final class BarsApp extends Application {
@Override
public void start(Stage stage) throws IOException {
boolean fxml = getParameters().getRaw().contains("fxml");
stage.setTitle("Standalone bars — " + (fxml ? "FXML" : "Java"));
stage.setScene(new Scene(create(fxml), 640, 360));
stage.show();
}
/**
* Builds the same screen using Java or ordinary FXMLLoader, without MVVM.
*
* @param fxml whether to load the FXML version
* @return a screen ready to place in a Scene
* @throws IOException if the example FXML cannot be loaded
*/
public static Parent create(boolean fxml) throws IOException {
if (fxml) {
FXMLLoader loader = new FXMLLoader(BarsApp.class.getResource("Bars.fxml"));
Parent root = loader.load();
var nodes = loader.getNamespace();
connect((TextArea) nodes.get("editor"), (Button) nodes.get("clear"),
(Button) nodes.get("append"), (Label) nodes.get("status"),
(Label) nodes.get("cursor"), (ProgressBar) nodes.get("progress"));
return root;
}
TextArea editor = new TextArea();
editor.setId("editor");
editor.setPromptText("Type here, or append sample text.");
Button clear = new Button("Clear");
clear.setId("clear");
Button append = new Button("Append");
append.setId("append");
Label status = new Label();
status.setId("status");
Label cursor = new Label();
cursor.setId("cursor");
ProgressBar progress = new ProgressBar(0);
progress.setId("progress");
progress.setPrefWidth(120);
StatusBar bar = new StatusBar();
bar.getLeftItems().add(status);
bar.getRightItems().addAll(cursor, progress);
BorderPane root = new BorderPane(editor);
root.setTop(new ToolBar(clear, append));
root.setBottom(bar);
connect(editor, clear, append, status, cursor, progress);
return root;
}
private static void connect(TextArea editor, Button clear, Button append,
Label status, Label cursor, ProgressBar progress) {
clear.setOnAction(event -> editor.clear());
append.setOnAction(event -> editor.appendText("Hello"));
status.textProperty().bind(Bindings.when(editor.textProperty().isEmpty())
.then("Ready").otherwise("Edited"));
cursor.textProperty().bind(editor.caretPositionProperty().asString("Offset %d"));
progress.progressProperty().bind(Bindings.min(1.0, editor.lengthProperty().divide(100.0)));
}
}
@@ -0,0 +1,18 @@
package de.neitzel.fx.example.bars;
import javafx.application.Application;
/** Plain launcher for the standalone bars example, usable on the classpath. */
public final class BarsMain {
private BarsMain() {
}
/**
* Starts the example.
*
* @param args include {@code fxml} to use the FXML screen
*/
public static void main(String[] args) {
Application.launch(BarsApp.class, args);
}
}
@@ -0,0 +1,70 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.CloseConsent;
import de.neitzel.fx.docking.CloseResult;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.concurrent.CompletableFuture;
/** Demonstrates a pending close decision while the editor remains open. */
public final class CloseDockingApp extends Application {
@Override
public void start(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Label notice = new Label("Close Notes, then allow the close or keep the editor open.");
Button close = new Button("Close Notes");
Button allow = new Button("Allow close");
Button veto = new Button("Keep open");
var pending = new SimpleObjectProperty<CompletableFuture<CloseConsent>>();
allow.disableProperty().bind(pending.isNull());
veto.disableProperty().bind(pending.isNull());
BorderPane shell = new BorderPane(pane);
shell.setTop(new ToolBar(close, allow, veto));
shell.setBottom(notice);
stage.setScene(new Scene(shell, 760, 420));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
Dockable editor = new Dockable(new DockableId("notes"), new TextArea("Edit these notes before closing."));
editor.setTitle("Notes");
editor.setCloseCheck(request -> {
notice.setText("Notes remains open while you decide.");
CompletableFuture<CloseConsent> answer = new CompletableFuture<>();
pending.set(answer);
return answer;
});
editor.setOnClosed(() -> {
close.setDisable(true);
notice.setText("Notes closed. Its resources can now be released.");
});
manager.open(editor, DockTarget.area("editors"));
close.setOnAction(event -> manager.requestTabClose(editor.getId()).thenAcceptAsync(result -> {
if (result instanceof CloseResult.Vetoed) notice.setText("Close canceled. Notes remains editable.");
}, Platform::runLater));
allow.setOnAction(event -> answer(pending, CloseConsent.ALLOW));
veto.setOnAction(event -> answer(pending, CloseConsent.VETO));
stage.setTitle("NeitzelLib — asynchronous tab close");
stage.show();
}
private static void answer(SimpleObjectProperty<CompletableFuture<CloseConsent>> pending, CloseConsent consent) {
CompletableFuture<CloseConsent> answer = pending.get();
pending.set(null);
if (answer != null) answer.complete(consent);
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain Java launcher for the asynchronous close example. */
public final class CloseDockingMain {
private CloseDockingMain() { }
public static void main(String[] args) {
Application.launch(CloseDockingApp.class, args);
}
}
@@ -0,0 +1,127 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockGroupChanges;
import de.neitzel.fx.docking.DockLayoutView;
import de.neitzel.fx.docking.DockSplitDefinition;
import de.neitzel.fx.docking.SplitDirections;
import javafx.geometry.Orientation;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockLayout;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/** A small ordinary JavaFX application with editor and tool tabs, without MVVM. */
public final class DockingApp extends Application {
@Override
public void start(Stage stage) throws Exception {
boolean splits = getParameters().getRaw().contains("--splits");
DockPane pane = getParameters().getRaw().contains("--fxml")
? FXMLLoader.load(DockingApp.class.getResource(splits ? "SplitDocking.fxml" : "Docking.fxml"))
: initialPane(splits);
Button activate = new Button("Activate Notes");
Button toTools = new Button("Move Notes to tools");
Button toEditors = new Button("Move Notes to editors");
Button splitNotes = new Button("Split Notes right");
Button toggleTools = new Button("Toggle tools");
Button widenTools = new Button("Tools width 260");
Label status = new Label("Drag a tab to an edge to split; drag dividers to resize.");
BorderPane shell = new BorderPane(pane);
shell.setTop(new ToolBar(activate, toTools, toEditors, splitNotes, toggleTools, widenTools));
shell.setBottom(status);
stage.setScene(new Scene(shell, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
DockableId notesId = new DockableId("notes");
TextArea notes = new TextArea("Unsaved notes stay in this live editor.");
Dockable editor = new Dockable(notesId, notes);
editor.setTitle("Notes");
manager.open(editor, DockTarget.area("editors"));
Dockable other = new Dockable(new DockableId("readme"), new TextArea("Readme"));
other.setTitle("Readme");
manager.open(other, DockTarget.area(splits ? "preview" : "editors"));
if (splits) {
Dockable output = new Dockable(new DockableId("output"), new TextArea("Build output"));
output.setTitle("Output");
manager.open(output, DockTarget.area("output"));
}
Dockable changes = new Dockable(new DockableId("changes"), new TextArea("Changed files"));
changes.setTitle("Changed files");
changes.setIcon(new Label("Δ"));
manager.open(changes, DockTarget.area("tools"));
Dockable project = new Dockable(new DockableId("project"), new Label("Project files"));
project.setTitle("Project");
project.setIcon(new Label("▦"));
manager.open(project, DockTarget.area("tools"));
activate.setOnAction(event -> manager.activate(notesId));
toTools.setOnAction(event -> report(status, manager.move(notesId, DockTarget.area("tools"))));
toEditors.setOnAction(event -> report(status, manager.move(notesId, DockTarget.area("editors"))));
splitNotes.setOnAction(event -> manager.layout().windows().stream()
.flatMap(window -> window.areas().stream()).flatMap(area -> area.groups().stream())
.filter(group -> group.dockableIds().contains(notesId)).findFirst()
.ifPresent(group -> report(status, manager.move(notesId, DockTarget.split(group.id(), Side.RIGHT)))));
toggleTools.setOnAction(event -> toolsGroup(manager).ifPresent(group ->
report(status, manager.setGroupCollapsed(group.id(), !group.collapsed()))));
widenTools.setOnAction(event -> toolsGroup(manager).ifPresent(group ->
report(status, manager.updateGroup(group.id(), DockGroupChanges.builder().preferredWidth(260).build()))));
stage.setTitle("NeitzelLib docking — Java or ordinary FXML");
stage.show();
manager.activate(notesId);
}
private static void report(Label status, ActionResult result) {
status.setText(switch (result) {
case ActionResult.Applied ignored -> "Layout updated.";
case ActionResult.NoChange ignored -> "The layout already has that state.";
case ActionResult.Rejected rejected -> rejected.failure().message();
});
}
private static java.util.Optional<DockLayoutView.Group> toolsGroup(DockingManager manager) {
return manager.layout().windows().stream().flatMap(window -> window.areas().stream())
.filter(area -> area.id().value().equals("tools"))
.flatMap(area -> area.groups().stream()).findFirst();
}
private static DockPane initialPane(boolean splits) {
DockLayout layout = new DockLayout();
if (splits) {
DockSplitDefinition secondary = new DockSplitDefinition();
secondary.setDestinationId("secondary");
secondary.setOrientation(Orientation.VERTICAL);
secondary.setFirst(new DockGroupDefinition("preview"));
secondary.setSecond(new DockGroupDefinition("output"));
DockSplitDefinition editors = new DockSplitDefinition();
editors.setDestinationId("editors");
editors.setFirst(new DockGroupDefinition("primary"));
editors.setSecond(secondary);
layout.setCenter(editors);
} else {
layout.setCenter(new DockGroupDefinition("editors"));
}
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT);
tools.setCollapsible(true);
tools.setPreferredWidth(200);
tools.setSplitDirections(SplitDirections.VERTICAL);
tools.setVisibleWhenEmpty(false);
tools.setReleaseSpaceWhenEmpty(true);
layout.setRight(tools);
DockPane pane = new DockPane();
pane.setInitialLayout(layout);
return pane;
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain launcher for the docking example; pass --fxml to load the equivalent FXML layout. */
public final class DockingMain {
private DockingMain() { }
public static void main(String[] args) {
Application.launch(DockingApp.class, args);
}
}
@@ -0,0 +1,113 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.CloseConsent;
import de.neitzel.fx.docking.CloseResult;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.DockWindowId;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/** Two editors make early/late vetoes and independent window requests visible. */
public final class FloatingCloseDockingApp extends Application {
private final SimpleObjectProperty<PendingAnswer> pending = new SimpleObjectProperty<>();
private final TextArea history = new TextArea();
private final Label question = new Label("Close Editors to ask First and Second in order.");
@Override
public void start(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Button close = new Button("Close Editors");
Button join = new Button("Repeat Editors close");
Button tab = new Button("Close Second tab");
Button other = new Button("Close Other window");
Button allow = new Button("Save and allow");
Button veto = new Button("Keep open");
allow.disableProperty().bind(pending.isNull());
veto.disableProperty().bind(pending.isNull());
allow.setOnAction(event -> answer(CloseConsent.ALLOW));
veto.setOnAction(event -> answer(CloseConsent.VETO));
history.setEditable(false);
history.setPrefRowCount(10);
BorderPane shell = new BorderPane(pane);
shell.setTop(new VBox(new ToolBar(close, join, tab, other), new ToolBar(allow, veto), question));
shell.setBottom(history);
stage.setScene(new Scene(shell, 920, 460));
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("Editors — close me to ask every tab"));
DockingManager manager = DockingManager.attach(stage, pane, options);
stage.setTitle("NeitzelLib — shared floating-window consent");
stage.show();
Dockable first = editor("First");
Dockable second = editor("Second");
manager.open(first, DockTarget.floating());
var editors = manager.layout().windows().getLast();
DockWindowId editorsId = editors.id();
manager.open(second, DockTarget.group(editors.areas().getFirst().groups().getFirst().id()));
Dockable independent = editor("Other");
manager.open(independent, DockTarget.floating());
DockWindowId otherId = manager.layout().windows().getLast().id();
close.setOnAction(event -> report("Editors", manager.requestFloatingWindowClose(editorsId)));
join.setOnAction(event -> report("Repeated Editors", manager.requestFloatingWindowClose(editorsId)));
tab.setOnAction(event -> report("Second tab", manager.requestTabClose(second.getId())));
other.setOnAction(event -> report("Other window", manager.requestFloatingWindowClose(otherId)));
stage.setOnHidden(event -> {
if (first.getContent().getScene() != null) first.getContent().getScene().getWindow().hide();
if (independent.getContent().getScene() != null) independent.getContent().getScene().getWindow().hide();
});
}
private Dockable editor(String title) {
TextArea content = new TextArea(title + " unsaved text");
Dockable editor = new Dockable(new DockableId(title.toLowerCase(java.util.Locale.ROOT)), content);
editor.setTitle(title);
editor.setCloseCheck(request -> {
log("Checking " + title + " in " + request.scope().kind() + "; every editor stays open.");
question.setText("Decision for " + title + " — Save and allow, or Keep open");
CompletableFuture<CloseConsent> answer = new CompletableFuture<>();
pending.set(new PendingAnswer(title, content, answer));
return answer;
});
editor.setOnClosed(() -> log("Released " + title + " after the complete close."));
return editor;
}
private void answer(CloseConsent consent) {
PendingAnswer current = pending.get();
if (current == null) return;
pending.set(null);
if (consent == CloseConsent.ALLOW) {
log("Saved " + current.title + ": " + current.content.getText());
} else {
log("Veto from " + current.title + "; remaining editors will still be asked.");
}
question.setText("Decision recorded.");
current.answer.complete(consent);
}
private void report(String label, CompletionStage<CloseResult> result) {
result.thenAccept(outcome -> log(label + ": " + outcome));
}
private void log(String message) { history.appendText(message + "\n"); }
private record PendingAnswer(String title, TextArea content, CompletableFuture<CloseConsent> answer) { }
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain Java launcher for the floating-window consent example. */
public final class FloatingCloseDockingMain {
private FloatingCloseDockingMain() { }
public static void main(String[] args) {
Application.launch(FloatingCloseDockingApp.class, args);
}
}
@@ -0,0 +1,89 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import de.neitzel.fx.docking.MoveCheck;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/** Demonstrates live editor transfers between the main window and floating windows. */
public final class FloatingDockingApp extends Application {
@Override
public void start(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
pane.getInitialLayout().setLeft(new DockGroupDefinition("project"));
Label notice = new Label("Edit Notes and select a word before moving it. Project stays in the main window.");
BorderPane shell = new BorderPane(pane);
shell.setBottom(notice);
stage.setScene(new Scene(shell, 1040, 560));
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("NeitzelLib — floating editor"));
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable notes = editor("notes", "Notes", "Unsaved notes travel with this editor.\nSelect a word, float the tab, and continue typing.");
Dockable readme = editor("readme", "Readme", "A second editor can share a floating window with Notes.");
Dockable project = editor("project", "Project", "This panel is restricted to the main window.\nIts Float menu command is disabled.");
project.setMainWindowOnly(true);
manager.open(project, DockTarget.area("project"));
manager.open(readme, DockTarget.area("editors"));
manager.open(notes, DockTarget.area("editors"));
Button floatNotes = new Button("Float Notes");
Button floatReadme = new Button("Float Readme");
Button join = new Button("Join Readme");
Button returnNotes = new Button("Return Notes");
Button returnReadme = new Button("Return Readme");
shell.setTop(new ToolBar(floatNotes, floatReadme, join, returnNotes, returnReadme));
floatNotes.setOnAction(event -> move(manager, notes, DockTarget.floating(), notice));
floatReadme.setOnAction(event -> move(manager, readme, DockTarget.floating(), notice));
join.setOnAction(event -> {
DockTarget target = floatingGroup(manager, readme.getId());
if (target != null) move(manager, notes, target, notice);
});
returnNotes.setOnAction(event -> move(manager, notes, DockTarget.returnToMain(), notice));
returnReadme.setOnAction(event -> move(manager, readme, DockTarget.returnToMain(), notice));
Runnable refresh = () -> {
floatNotes.setDisable(!(manager.checkMove(notes.getId(), DockTarget.floating()) instanceof MoveCheck.Allowed));
floatReadme.setDisable(!(manager.checkMove(readme.getId(), DockTarget.floating()) instanceof MoveCheck.Allowed));
returnNotes.setDisable(!(manager.checkMove(notes.getId(), DockTarget.returnToMain()) instanceof MoveCheck.Allowed));
returnReadme.setDisable(!(manager.checkMove(readme.getId(), DockTarget.returnToMain()) instanceof MoveCheck.Allowed));
DockTarget target = floatingGroup(manager, readme.getId());
join.setDisable(target == null || !(manager.checkMove(notes.getId(), target) instanceof MoveCheck.Allowed));
};
manager.layoutProperty().addListener((observable, old, current) -> refresh.run());
refresh.run();
stage.setTitle("NeitzelLib — floating windows");
stage.show();
}
private static Dockable editor(String id, String title, String text) {
Dockable editor = new Dockable(new DockableId(id), new TextArea(text));
editor.setTitle(title);
return editor;
}
private static DockTarget floatingGroup(DockingManager manager, DockableId id) {
return manager.layout().windows().stream().filter(window -> !window.main())
.flatMap(window -> window.areas().stream()).flatMap(area -> area.groups().stream())
.filter(group -> group.dockableIds().contains(id)).findFirst()
.map(group -> DockTarget.group(group.id())).orElse(null);
}
private static void move(DockingManager manager, Dockable editor, DockTarget target, Label notice) {
ActionResult result = manager.move(editor.getId(), target);
notice.setText(result instanceof ActionResult.Rejected rejected ? rejected.failure().message()
: editor.getTitle() + " moved. Continue editing in its destination window.");
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain Java launcher for the floating editor example. */
public final class FloatingDockingMain {
private FloatingDockingMain() { }
public static void main(String[] args) {
Application.launch(FloatingDockingApp.class, args);
}
}
@@ -0,0 +1,129 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.*;
import javafx.application.Application;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.List;
import java.util.ListResourceBundle;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/** Keyboard menus, icon names, translated policy failures and a shared application theme. */
public final class KeyboardThemeDockingApp extends Application {
@Override public void start(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("project");
tools.setCollapsible(true);
tools.setTabSide(Side.LEFT);
tools.setPreferredWidth(220);
pane.getInitialLayout().setLeft(tools);
Button focusTabs = new Button("Focus active tab strip");
Button checkFloat = new Button("Check Float");
CheckBox blockFloat = new CheckBox("Block floating");
CheckBox missingKey = new CheckBox("Missing translation key");
CheckBox allowClose = new CheckBox("Allow Notes to close");
Label message = new Label("Focus a tab strip, press Shift+F10, then use arrows and Enter.");
message.setWrapText(true);
Label active = new Label();
StatusBar status = new StatusBar();
status.getLeftItems().add(message);
status.getRightItems().add(active);
BorderPane shell = new BorderPane(pane);
shell.setTop(new VBox(new ToolBar(focusTabs, checkFloat, blockFloat, missingKey),
new ToolBar(allowClose, new Label("Notes initially vetoes Close. Project is an icon-only tab."))));
shell.setBottom(status);
String theme = getClass().getResource("KeyboardThemeDocking.css").toExternalForm();
stage.setScene(new Scene(shell, 1000, 620));
stage.getScene().getStylesheets().add(theme);
stage.setTitle("NeitzelLib — keyboard, names and application styles");
DockingOptions options = new DockingOptions();
options.setResourceBundle(translations());
options.setFloatingWindowCustomizer(configuration -> {
configuration.setTitle("Themed floating editor — Shift+F10 to return");
configuration.getStylesheets().add(theme);
});
options.setPlacementRule((dockable, target) -> blockFloat.isSelected()
&& target instanceof ResolvedDockTarget.Detachment
? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(),
"Demo policy disabled detachment", null,
missingKey.isSelected() ? "demo.unknownKey" : "demo.floatingBlocked")) : Optional.empty());
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable notes = editor("notes", "Notes", "abcdef\nMove this tab with its keyboard menu, then keep typing.");
Dockable readme = editor("readme", "Readme", "Move/Split/Float/Return use the same rules as dragging.\n"
+ "Toggle Block floating and Missing translation key, then compare Check Float with the tab menu.");
Dockable project = editor("project", "", "Project files\nThis icon-only tab is named for assistive technology.");
project.setIcon(new Label("▦"));
project.setAccessibleName("Project files");
project.setMainWindowOnly(true);
notes.setCloseCheck(request -> CompletableFuture.completedFuture(
allowClose.isSelected() ? CloseConsent.ALLOW : CloseConsent.VETO));
notes.setOnClosed(() -> message.setText("Notes closed after consent."));
manager.open(project, DockTarget.area("project"));
manager.open(readme, DockTarget.area("editors"));
manager.open(notes, DockTarget.area("editors"));
focusTabs.setOnAction(event -> {
Dockable current = manager.activeDockable();
if (current == null) return;
current.getContent().getScene().getRoot().lookupAll(".dock-group").stream()
.filter(node -> node instanceof TabPane tabs && tabs.getTabs().stream()
.anyMatch(tab -> tab.getContent() == current.getContent()))
.findFirst().ifPresent(node -> node.requestFocus());
});
checkFloat.setOnAction(event -> {
Dockable current = manager.activeDockable();
if (current == null) return;
MoveCheck result = manager.checkMove(current.getId(), DockTarget.floating());
message.setText(result instanceof MoveCheck.Rejected rejected
? manager.describeFailure(rejected.failure()) + " [" + rejected.failure().code()
+ "; key=" + rejected.failure().messageKey() + "]"
: "Float is available. Open the tab menu to execute it.");
});
Runnable refresh = () -> {
Dockable current = manager.activeDockable();
active.setText(current == null ? "No active tab" : current.getTitle().isBlank()
? current.getAccessibleName() : current.getTitle());
};
manager.activeDockableProperty().addListener((observable, old, current) -> refresh.run());
refresh.run();
stage.setOnHidden(event -> {
for (Dockable dockable : List.of(notes, readme, project)) {
Scene scene = dockable.getContent().getScene();
if (scene != null && scene.getWindow() != stage) scene.getWindow().hide();
}
});
stage.show();
manager.activate(notes.getId());
((TextArea) notes.getContent()).selectRange(2, 4);
}
private static Dockable editor(String id, String title, String text) {
Dockable dockable = new Dockable(new DockableId(id), new TextArea(text));
dockable.setTitle(title);
return dockable;
}
private static ListResourceBundle translations() {
return new ListResourceBundle() {
@Override protected Object[][] getContents() {
return new Object[][] {
{"dock.action.move", "Verschieben"}, {"dock.action.split", "Unterteilen"},
{"dock.action.close", "Schließen"}, {"dock.action.float", "Abkoppeln"},
{"dock.action.return", "Zurück ins Hauptfenster"}, {"dock.action.pin", "Gruppe anheften"},
{"dock.failure.PLACEMENT_REJECTED", "Diese Platzierung ist nicht erlaubt"},
{"demo.floatingBlocked", "Abkoppeln ist in dieser Ansicht gesperrt"}
};
}
};
}
}
@@ -0,0 +1,9 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain launcher for the keyboard and theme exercise. */
public final class KeyboardThemeDockingMain {
private KeyboardThemeDockingMain() { }
public static void main(String[] args) { Application.launch(KeyboardThemeDockingApp.class, args); }
}
@@ -0,0 +1,120 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockGroupMode;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import de.neitzel.fx.docking.MoveCheck;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
import java.util.List;
/** A desktop exercise for live tab transfers, selection preservation and invalid destinations. */
public final class NativeDragDockingApp extends Application {
@Override
public void start(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition projectGroup = new DockGroupDefinition("project");
projectGroup.setTabSide(Side.LEFT);
projectGroup.setCollapsible(true);
projectGroup.setMode(DockGroupMode.OVERLAY);
projectGroup.setPreferredWidth(240);
pane.getInitialLayout().setLeft(projectGroup);
Button showProject = new Button("Show Project");
Button floatReadme = new Button("Separate Readme window");
Button returnNotes = new Button("Return Notes");
Button returnReadme = new Button("Return Readme");
ToolBar toolbar = new ToolBar(showProject, floatReadme, returnNotes, returnReadme,
new Label("Toolbar: no drop destination"));
Label active = new Label();
Label hint = new Label("Drag Notes' tab; then keep typing without clicking. Escape cancels a drag.");
Label count = new Label();
StatusBar status = new StatusBar();
status.getLeftItems().add(active);
status.getRightItems().add(count);
BorderPane shell = new BorderPane(pane);
shell.setTop(toolbar);
hint.setWrapText(true);
shell.setBottom(new VBox(hint, status));
Rectangle2D screen = Screen.getPrimary().getVisualBounds();
double mainWidth = Math.min(920, screen.getWidth() * .60);
stage.setScene(new Scene(shell, mainWidth, Math.min(560, screen.getHeight() - 120)));
stage.setX(screen.getMinX() + 24);
stage.setY(screen.getMinY() + 70);
stage.setTitle("NeitzelLib — drag tabs between windows");
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("NeitzelLib — floating drop destination"));
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable notes = editor("notes", "Notes", "abcdef\nSelect a word, move this tab, then type without an extra click.");
Dockable readme = editor("readme", "Readme", "This floating editor is a destination.\nDrop Notes onto its tab strip or content area.");
Dockable project = editor("project", "Project", "Project stays in the main window.\nDragging it outside or into a floating window is rejected.");
project.setIcon(new Label("▦"));
project.setMainWindowOnly(true);
manager.open(project, DockTarget.area("project"));
manager.open(readme, DockTarget.area("editors"));
manager.open(notes, DockTarget.area("editors"));
manager.setGroupCollapsed(new de.neitzel.fx.docking.DockGroupId("project"), true);
Rectangle2D destination = new Rectangle2D(screen.getMinX() + mainWidth + 48,
screen.getMinY() + 100, Math.min(500, screen.getWidth() * .34), 400);
floatReadme.setOnAction(event -> move(manager, readme, DockTarget.floating(destination), hint));
returnNotes.setOnAction(event -> move(manager, notes, DockTarget.returnToMain(), hint));
returnReadme.setOnAction(event -> move(manager, readme, DockTarget.returnToMain(), hint));
showProject.setOnAction(event -> manager.activate(project.getId()));
Runnable refresh = () -> {
Dockable current = manager.activeDockable();
active.setText("Active: " + (current == null ? "none" : current.getTitle()));
count.setText(manager.layout().windows().size() + " windows");
floatReadme.setDisable(!(manager.checkMove(readme.getId(), DockTarget.floating(destination)) instanceof MoveCheck.Allowed));
returnNotes.setDisable(!(manager.checkMove(notes.getId(), DockTarget.returnToMain()) instanceof MoveCheck.Allowed));
returnReadme.setDisable(!(manager.checkMove(readme.getId(), DockTarget.returnToMain()) instanceof MoveCheck.Allowed));
showProject.setDisable(manager.findDockable(project.getId()).isEmpty());
};
manager.layoutProperty().addListener((observable, previous, current) -> refresh.run());
manager.activeDockableProperty().addListener((observable, previous, current) -> refresh.run());
stage.setOnHidden(event -> {
for (Dockable document : List.of(notes, readme, project)) {
if (document.getContent().getScene() != null && document.getContent().getScene().getWindow() != stage) {
document.getContent().getScene().getWindow().hide();
}
}
});
stage.show();
manager.move(readme.getId(), DockTarget.floating(destination));
manager.activate(notes.getId());
((TextArea) notes.getContent()).selectRange(2, 4);
refresh.run();
}
private static Dockable editor(String id, String title, String text) {
Dockable result = new Dockable(new DockableId(id), new TextArea(text));
result.setTitle(title);
return result;
}
private static void move(DockingManager manager, Dockable editor, DockTarget destination, Label hint) {
ActionResult result = manager.move(editor.getId(), destination);
hint.setText(result instanceof ActionResult.Rejected rejected ? rejected.failure().message()
: editor.getTitle() + " is ready. Continue typing without another click.");
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain Java launcher for native cross-window tab dragging. */
public final class NativeDragDockingMain {
private NativeDragDockingMain() { }
public static void main(String[] args) {
Application.launch(NativeDragDockingApp.class, args);
}
}
@@ -0,0 +1,103 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockGroupChanges;
import de.neitzel.fx.docking.DockGroupMode;
import de.neitzel.fx.docking.DockLayoutView;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.Optional;
/** An ordinary FXML application with mutually exclusive overlays and pinnable tool groups. */
public final class OverlayDockingApp extends Application {
@Override
public void start(Stage stage) throws Exception {
DockPane pane = FXMLLoader.load(OverlayDockingApp.class.getResource("OverlayDocking.fxml"));
Button showProject = new Button("Show Project");
Button showChanges = new Button("Show Changes");
Button showEditor = new Button("Focus Editor");
Button pinProject = new Button("Pin Project");
Button pinChanges = new Button("Pin Changes");
Label status = new Label();
BorderPane shell = new BorderPane(pane);
shell.setTop(new ToolBar(showProject, showChanges, showEditor, pinProject, pinChanges));
shell.setBottom(status);
stage.setScene(new Scene(shell, 920, 540));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
Dockable editor = content("notes", "Notes", "Edit these notes. Opening an overlay keeps the editor's layout space.");
Dockable project = content("project", "Project", "src/\n main/\n test/\ndocs/");
Dockable changes = content("changes", "Changes", "Modified files:\n Notes.java\n README.md");
project.setIcon(new Label("▦"));
changes.setIcon(new Label("Δ"));
manager.open(editor, DockTarget.area("editors"));
manager.open(project, DockTarget.area("project"));
manager.open(changes, DockTarget.area("changes"));
manager.setGroupCollapsed(group(manager, project.getId()).orElseThrow().id(), true);
manager.setGroupCollapsed(group(manager, changes.getId()).orElseThrow().id(), true);
manager.activate(editor.getId());
Runnable update = () -> {
describePinButton(pinProject, "Project", group(manager, project.getId()));
describePinButton(pinChanges, "Changes", group(manager, changes.getId()));
showProject.setDisable(manager.findDockable(project.getId()).isEmpty());
showChanges.setDisable(manager.findDockable(changes.getId()).isEmpty());
showEditor.setDisable(manager.findDockable(editor.getId()).isEmpty());
status.setText("Project: " + state(group(manager, project.getId()))
+ " | Changes: " + state(group(manager, changes.getId())));
};
manager.layoutProperty().addListener((observable, previous, current) -> update.run());
showProject.setOnAction(event -> manager.activate(project.getId()));
showChanges.setOnAction(event -> manager.activate(changes.getId()));
showEditor.setOnAction(event -> manager.activate(editor.getId()));
pinProject.setOnAction(event -> togglePin(manager, project.getId(), status));
pinChanges.setOnAction(event -> togglePin(manager, changes.getId(), status));
update.run();
stage.setTitle("NeitzelLib — overlays and pinned groups");
stage.show();
}
private static Dockable content(String id, String title, String text) {
Dockable dockable = new Dockable(new DockableId(id), new TextArea(text));
dockable.setTitle(title);
return dockable;
}
private static Optional<DockLayoutView.Group> group(DockingManager manager, DockableId id) {
return manager.layout().windows().stream().flatMap(window -> window.areas().stream())
.flatMap(area -> area.groups().stream()).filter(group -> group.dockableIds().contains(id)).findFirst();
}
private static void togglePin(DockingManager manager, DockableId id, Label status) {
// A toolbar press may dismiss an overlay before the action is delivered.
manager.activate(id);
group(manager, id).ifPresent(group -> {
ActionResult result = manager.updateGroup(group.id(), DockGroupChanges.builder()
.mode(group.mode() == DockGroupMode.OVERLAY ? DockGroupMode.DOCKED : DockGroupMode.OVERLAY).build());
if (result instanceof ActionResult.Rejected) status.setText("The group cannot change while another operation is pending.");
});
}
private static void describePinButton(Button button, String title, Optional<DockLayoutView.Group> group) {
button.setDisable(group.isEmpty());
button.setText(group.map(value -> value.mode() == DockGroupMode.DOCKED ? "Unpin " : "Pin ").orElse("Pin ") + title);
}
private static String state(Optional<DockLayoutView.Group> group) {
return group.map(value -> (value.mode() == DockGroupMode.OVERLAY ? "overlay" : "pinned")
+ (value.collapsed() ? ", closed" : ", open")).orElse("tab closed");
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain Java launcher for the FXML overlay example. */
public final class OverlayDockingMain {
private OverlayDockingMain() { }
public static void main(String[] args) {
Application.launch(OverlayDockingApp.class, args);
}
}
@@ -0,0 +1,72 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockFailure;
import de.neitzel.fx.docking.DockGroupId;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.Optional;
/** Demonstrates reset with live editors and atomic rejection under changed placement rules. */
public final class ResetDockingApp extends Application {
@Override public void start(Stage stage) throws Exception {
DockPane pane = FXMLLoader.load(DockingApp.class.getResource("Docking.fxml"));
Button rearrange = new Button("Rearrange");
Button reset = new Button("Reset layout");
reset.setId("resetLayout");
CheckBox allowProject = new CheckBox("Allow Project placement");
allowProject.setSelected(true);
Label status = new Label("Edit Notes, rearrange, then reset. Disable Project placement to see a rejected reset.");
stage.setScene(new Scene(new BorderPane(pane, new ToolBar(rearrange, reset, allowProject),
null, status, null), 1000, 600));
DockingOptions options = new DockingOptions();
options.setPlacementRule((dockable, destination) -> allowProject.isSelected() || !dockable.getId().value().equals("project")
? Optional.empty() : Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED,
dockable.getId(), "Project placement is disabled", null)));
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("These unsaved edits survive reset."));
notes.setTitle("Notes");
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme stays open."));
readme.setTitle("Readme");
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project tools"));
project.setTitle("Project");
manager.open(notes, DockTarget.area("editors"));
manager.open(readme, DockTarget.area("editors"));
manager.open(project, DockTarget.area("tools"));
rearrange.setOnAction(event -> {
ActionResult moved = manager.move(project.getId(), DockTarget.area("editors"));
if (moved instanceof ActionResult.Rejected) { report(status, moved); return; }
manager.move(readme.getId(), DockTarget.split(new DockGroupId("editors"), Side.BOTTOM));
manager.move(notes.getId(), DockTarget.floating());
manager.setGroupCollapsed(new DockGroupId("tools"), true);
status.setText("Notes is floating, Readme is split and Project moved. Reset restores the starting arrangement.");
});
reset.setOnAction(event -> report(status, manager.resetLayout()));
stage.setTitle("NeitzelLib — reset without losing edits");
stage.show();
}
private static void report(Label status, ActionResult result) {
status.setText(switch (result) {
case ActionResult.Applied ignored -> "Starting layout restored; all document contents remain open.";
case ActionResult.NoChange ignored -> "The layout already has its starting arrangement.";
case ActionResult.Rejected rejected -> "Layout unchanged: " + rejected.failure().message();
});
}
}
@@ -0,0 +1,10 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain classpath launcher for the reset example. */
public final class ResetDockingMain {
private ResetDockingMain() { }
public static void main(String[] args) { Application.launch(ResetDockingApp.class, args); }
}
@@ -0,0 +1,215 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.*;
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/** A visible save/retry workflow owns storage decisions while the manager owns close ordering. */
public final class ShutdownDockingApp extends Application {
private final SimpleObjectProperty<CompletableFuture<ShutdownDecision>> pendingSave = new SimpleObjectProperty<>();
private final SimpleObjectProperty<CompletableFuture<CloseConsent>> pendingConsent = new SimpleObjectProperty<>();
private final SimpleBooleanProperty shutdownRequested = new SimpleBooleanProperty();
private final SimpleBooleanProperty ended = new SimpleBooleanProperty();
private final Label status = new Label();
private final TextArea history = new TextArea();
private final CheckBox delayFloating = new CheckBox("Delay Preview window consent");
private final CheckBox lateVeto = new CheckBox("Preview vetoes last");
private final CheckBox saveFails = new CheckBox("Simulate save failure");
private final CheckBox throwShutdown = new CheckBox("Throw before saving");
private final ComboBox<MainWindowCloseMode> nextOwnership = new ComboBox<>();
private final Button quit = new Button("Quit workspace");
private final Button replace = new Button("Replace workspace");
private final Button applicationClose = new Button("Close application window");
private DockingManager manager;
private DockPane pane;
private Stage stage;
private MainWindowCloseMode ownership;
private LayoutSnapshot pendingSnapshot;
private LayoutSnapshot savedSnapshot;
private int generation;
private int retries;
@Override public void start(Stage stage) throws IOException {
this.stage = stage;
pane = FXMLLoader.load(ShutdownDockingApp.class.getResource("ShutdownDocking.fxml"));
status.setId("shutdown-status"); history.setId("shutdown-history");
history.setEditable(false); history.setPrefRowCount(9);
lateVeto.setId("late-veto"); saveFails.setId("save-fails"); throwShutdown.setId("throw-shutdown");
saveFails.setSelected(true);
delayFloating.setId("delay-floating-consent"); delayFloating.setSelected(true);
nextOwnership.setId("next-ownership");
nextOwnership.getItems().setAll(MainWindowCloseMode.values());
nextOwnership.setValue(MainWindowCloseMode.AUTOMATIC);
nextOwnership.setConverter(new StringConverter<>() {
@Override public String toString(MainWindowCloseMode value) {
return value == MainWindowCloseMode.AUTOMATIC ? "Library closes main" : "Application closes main";
}
@Override public MainWindowCloseMode fromString(String text) { throw new UnsupportedOperationException("Selection only"); }
});
quit.setId("quit-workspace"); replace.setId("replace-workspace"); applicationClose.setId("close-application-window");
applicationClose.setDisable(true);
quit.setOnAction(event -> requestClose(false));
replace.setOnAction(event -> requestClose(true));
applicationClose.setOnAction(event -> stage.hide());
Button retry = saveButton("Retry save", "retry-save", () -> attemptSave(false));
Button proceed = saveButton("Save successfully", "proceed-save", () -> attemptSave(true));
Button cancel = saveButton("Cancel shutdown", "cancel-save", () -> finishSave(ShutdownDecision.CANCEL, null));
Button fail = saveButton("Fail asynchronously", "fail-save", () -> finishSave(null,
new IllegalStateException("Simulated asynchronous storage failure")));
Button closePreview = new Button("Close Preview window"); closePreview.setId("close-preview-window");
closePreview.disableProperty().bind(pendingConsent.isNotNull().or(shutdownRequested).or(ended));
closePreview.setOnAction(event -> requestPreviewClose());
Button allowPreview = consentButton("Allow Preview", "allow-preview", CloseConsent.ALLOW);
Button vetoPreview = consentButton("Veto Preview", "veto-preview", CloseConsent.VETO);
BorderPane shell = new BorderPane(pane);
shell.setTop(new VBox(new ToolBar(quit, replace, applicationClose),
new ToolBar(lateVeto, saveFails, throwShutdown),
new ToolBar(delayFloating, closePreview, allowPreview, vetoPreview),
new ToolBar(new Label("Next workspace:"), nextOwnership, retry, proceed, cancel, fail), status));
shell.setBottom(history);
stage.setScene(new Scene(shell, 1100, 640));
stage.setTitle("NeitzelLib — Quit, save and replace");
stage.setOnCloseRequest(event -> {
if (ownership == MainWindowCloseMode.APPLICATION_COORDINATED && !ended.get()) {
event.consume(); requestClose(false);
}
});
attachWorkspace();
stage.show();
}
private Button saveButton(String text, String id, Runnable action) {
Button button = new Button(text); button.setId(id);
button.disableProperty().bind(pendingSave.isNull());
button.setOnAction(event -> action.run()); return button;
}
private Button consentButton(String text, String id, CloseConsent answer) {
Button button = new Button(text); button.setId(id);
button.disableProperty().bind(pendingConsent.isNull());
button.setOnAction(event -> {
CompletableFuture<CloseConsent> pending = pendingConsent.get();
if (pending == null) return;
pendingConsent.set(null); pending.complete(answer);
});
return button;
}
private void requestPreviewClose() {
var window = manager.layout().windows().stream().filter(candidate -> !candidate.main())
.filter(candidate -> candidate.areas().stream().flatMap(area -> area.groups().stream())
.anyMatch(group -> group.dockableIds().contains(new DockableId("preview")))).findFirst();
if (window.isEmpty()) { status.setText("Preview is not in a floating window."); return; }
manager.requestFloatingWindowClose(window.get().id()).thenAccept(result -> {
log("Preview window: " + result);
if (!shutdownRequested.get()) status.setText("Preview window: " + result);
});
}
private void attachWorkspace() {
ownership = nextOwnership.getValue();
DockingOptions options = new DockingOptions();
options.setMainWindowCloseMode(ownership);
options.setBeforeShutdown(this::beforeShutdown);
options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("Preview — included in Quit and Replace"));
manager = DockingManager.attach(stage, pane, options);
ended.set(false); shutdownRequested.set(false);
quit.disableProperty().unbind(); replace.disableProperty().unbind();
var scope = manager.closingScopeProperty();
var globalBusy = javafx.beans.binding.Bindings.createBooleanBinding(() -> scope.get() != null
&& (scope.get().kind() == CloseScope.Kind.MAIN_WINDOW || scope.get().kind() == CloseScope.Kind.MANAGER_ONLY), scope);
quit.disableProperty().bind(globalBusy.or(shutdownRequested).or(ended));
replace.disableProperty().bind(globalBusy.or(shutdownRequested).or(ended));
applicationClose.setDisable(true);
generation++;
manager.open(editor("notes", "Notes"), DockTarget.area("editors"));
manager.open(editor("project", "Project"), DockTarget.area("tools"));
manager.setGroupCollapsed(new DockGroupId("tools"), true);
manager.open(editor("preview", "Preview"), DockTarget.floating());
status.setText("Workspace " + generation + " attached; Project is collapsed, Preview is floating.");
log("Attached workspace " + generation + " with " + ownership);
}
private Dockable editor(String id, String title) {
TextArea content = new TextArea(title + " in workspace " + generation); content.setId(id + "-content");
Dockable dockable = new Dockable(new DockableId(id), content); dockable.setTitle(title);
dockable.setCloseCheck(request -> {
log("Checked " + id + " in " + request.scope().kind() + "; all contents remain open.");
if (id.equals("preview") && delayFloating.isSelected() && request.scope().kind() == CloseScope.Kind.FLOATING_WINDOW) {
CompletableFuture<CloseConsent> answer = new CompletableFuture<>(); pendingConsent.set(answer);
status.setText("Preview consent pending; Quit can wait for this window.");
return answer;
}
boolean veto = id.equals("preview") && lateVeto.isSelected();
if (veto) status.setText("Late veto from Preview; no content was closed.");
return CompletableFuture.completedFuture(veto ? CloseConsent.VETO : CloseConsent.ALLOW);
});
dockable.setOnClosed(() -> log("Released " + id));
return dockable;
}
private CompletionStage<ShutdownDecision> beforeShutdown(ShutdownRequest request) {
if (throwShutdown.isSelected()) throw new IllegalStateException("Simulated synchronous save setup failure");
pendingSnapshot = request.snapshot(); retries = 0;
log("Snapshot " + request.reason() + ": " + pendingSnapshot.windows().size() + " windows before any content closes.");
status.setText("Save pending: " + request.reason() + ". Retry, save successfully, cancel or fail.");
CompletableFuture<ShutdownDecision> decision = new CompletableFuture<>(); pendingSave.set(decision);
return decision;
}
private void attemptSave(boolean forceSuccess) {
if (pendingSave.get() == null) return;
if (!forceSuccess && saveFails.isSelected()) {
retries++; status.setText("Retry failed (" + retries + "); the same shutdown remains pending.");
log("Retry " + retries + " failed; every window and editor stays open."); return;
}
savedSnapshot = pendingSnapshot;
log("Saved " + savedSnapshot.windows().size() + " windows in application-owned memory.");
finishSave(ShutdownDecision.PROCEED, null);
}
private void finishSave(ShutdownDecision decision, RuntimeException failure) {
CompletableFuture<ShutdownDecision> pending = pendingSave.get();
if (pending == null) return;
pendingSave.set(null); pendingSnapshot = null;
status.setText(failure == null ? "Save decision: " + decision : "Save failed: " + failure.getMessage());
if (failure == null) pending.complete(decision); else pending.completeExceptionally(failure);
}
private void requestClose(boolean replaceWorkspace) {
CloseScope scope = manager.closingScopeProperty().get();
if (scope != null && scope.kind() == CloseScope.Kind.FLOATING_WINDOW) {
status.setText((replaceWorkspace ? "Replacement" : "Quit") + " waiting for Preview consent.");
}
shutdownRequested.set(true);
CompletionStage<CloseResult> request = replaceWorkspace ? manager.requestManagerClose() : manager.requestMainWindowClose();
request.thenAccept(result -> {
shutdownRequested.set(false);
status.setText(result.toString()); log(result.toString());
if (result instanceof CloseResult.Closed) {
ended.set(true);
if (replaceWorkspace) attachWorkspace();
else if (ownership == MainWindowCloseMode.APPLICATION_COORDINATED) applicationClose.setDisable(false);
}
});
}
private void log(String message) { history.appendText(message + "\n"); }
}
@@ -0,0 +1,9 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain launcher for the application-owned shutdown/save workflow. */
public final class ShutdownDockingMain {
private ShutdownDockingMain() { }
public static void main(String[] args) { Application.launch(ShutdownDockingApp.class, args); }
}
@@ -0,0 +1,222 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockFailure;
import de.neitzel.fx.docking.DockGroupId;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockableResolution;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import de.neitzel.fx.docking.LayoutSnapshot;
import de.neitzel.fx.docking.RestoreResult;
import de.neitzel.fx.docking.ResolvedDockTarget;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Window;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
/** Keeps layout data in application memory and restores fresh content before showing another workspace. */
public final class SnapshotDockingApp extends Application {
private static final List<Document> DOCUMENTS = List.of(
new Document("notes", "primary", "Notes", "Notes loaded from the application document source."),
new Document("readme", "secondary", "Readme", "The saved layout contains identities, not this text."),
new Document("preview", "preview", "Preview", "Preview belongs to a nested editor split."),
new Document("project", "tools", "Project", "Project is a temporary overlay."));
private LayoutSnapshot saved;
@Override public void start(Stage stage) throws Exception {
DockPane pane = loadPane();
Label status = new Label("Rearrange the workspace, capture its layout, then restore into a fresh window.");
status.setId("snapshotStatus");
status.setWrapText(true);
Button capture = new Button("Capture layout");
Button restore = new Button("Restore saved layout");
Button incompatible = new Button("Try incompatible version");
Button failed = new Button("Simulate load failure");
Button missing = new Button("Restore without Preview/Project");
Button changedRule = new Button("Restore with changed rule");
Button rejected = new Button("Reject Project placement");
Button floating = new Button("Prepare floating snapshot");
Button partialFloating = new Button("Restore partial floating");
Button offscreen = new Button("Restore off-screen windows");
Button abortCustomizer = new Button("Abort floating customizer");
CheckBox cleanupFailure = new CheckBox("Simulate cleanup failure");
stage.setScene(new Scene(new BorderPane(pane, new VBox(new ToolBar(capture, restore, incompatible, failed, cleanupFailure),
new ToolBar(missing, changedRule, rejected), new ToolBar(floating, offscreen, partialFloating, abortCustomizer)),
null, status, null), 1120, 680));
DockingManager manager = DockingManager.attach(stage, pane, restoreOptions(RestoreScenario.NORMAL));
DOCUMENTS.forEach(document -> manager.open(content(document), DockTarget.area(document.area())));
saved = manager.snapshot();
Runnable updateFloatingActions = () -> {
long count = saved.windows().stream().filter(window -> !window.main()).count();
partialFloating.setDisable(count == 0);
offscreen.setDisable(count == 0);
abortCustomizer.setDisable(count < 2);
};
updateFloatingActions.run();
capture.setOnAction(event -> {
saved = manager.snapshot();
updateFloatingActions.run();
status.setText("Captured layout in application memory; document text remains outside the snapshot.");
});
restore.setOnAction(event -> restoreWindow(saved, RestoreScenario.NORMAL, false, status));
incompatible.setOnAction(event -> restoreWindow(new LayoutSnapshot(saved.version() + 1,
saved.windows(), saved.activeDockableId(), saved.returnPositions(), saved.initialIntents()), RestoreScenario.NORMAL, false, status));
failed.setOnAction(event -> restoreWindow(saved, RestoreScenario.LOAD_FAILURE, cleanupFailure.isSelected(), status));
missing.setOnAction(event -> restoreWindow(saved, RestoreScenario.MISSING_CONTENT, false, status));
changedRule.setOnAction(event -> restoreWindow(saved, RestoreScenario.PROJECT_FALLBACK, false, status));
rejected.setOnAction(event -> restoreWindow(saved, RestoreScenario.REJECT_PROJECT, false, status));
floating.setOnAction(event -> {
for (String id : List.of("preview", "project")) {
ActionResult moved = manager.move(new DockableId(id), DockTarget.floating());
if (moved instanceof ActionResult.Rejected failure) {
status.setText(manager.describeFailure(failure.failure()));
return;
}
}
saved = manager.snapshot();
updateFloatingActions.run();
status.setText("Captured " + saved.windows().stream().filter(window -> !window.main()).count()
+ " floating windows; Project retains its tools-area return target.");
});
partialFloating.setOnAction(event -> restoreWindow(saved, RestoreScenario.PARTIAL_FLOATING, false, status));
offscreen.setOnAction(event -> restoreWindow(offscreenSnapshot(saved), RestoreScenario.OFFSCREEN, false, status));
abortCustomizer.setOnAction(event -> restoreWindow(saved, RestoreScenario.ABORT_CUSTOMIZER, false, status));
stage.setTitle("NeitzelLib — application-owned layout snapshots");
stage.show();
}
private static void restoreWindow(LayoutSnapshot snapshot, RestoreScenario scenario, boolean failCleanup, Label sourceStatus) {
List<Window> visibleBefore = List.copyOf(Window.getWindows());
Stage target = new Stage();
try {
DockPane pane = loadPane();
Label status = new Label();
status.setId("snapshotStatus");
status.setWrapText(true);
target.setScene(new Scene(new BorderPane(pane, null, null, status, null), 1000, 650));
DockingManager manager = DockingManager.attach(target, pane, restoreOptions(scenario));
AtomicInteger prepared = new AtomicInteger();
AtomicInteger discarded = new AtomicInteger();
RestoreResult result = manager.restore(snapshot, id -> {
if ((scenario == RestoreScenario.MISSING_CONTENT
&& (id.value().equals("preview") || id.value().equals("project")))
|| scenario == RestoreScenario.PARTIAL_FLOATING && id.value().equals("preview")) {
return new DockableResolution.Missing();
}
if (scenario == RestoreScenario.LOAD_FAILURE && id.value().equals("readme")) {
return new DockableResolution.Failed(new IllegalStateException("Demo document source is unavailable"));
}
Document document = DOCUMENTS.stream().filter(candidate -> candidate.id().equals(id.value())).findFirst().orElseThrow();
Dockable content = content(document);
if (scenario == RestoreScenario.PARTIAL_FLOATING && id.value().equals("project")) content.setMainWindowOnly(true);
prepared.incrementAndGet();
content.setOnDiscarded(() -> {
discarded.incrementAndGet();
if (failCleanup) throw new IllegalStateException("Demo cleanup could not finish");
});
return new DockableResolution.Available(content);
});
String message = switch (result) {
case RestoreResult.Applied applied -> "Restored before showing this window; prepared " + prepared.get()
+ " fresh contents, missing " + applied.missingIds().size()
+ (applied.missingIds().isEmpty() ? "." : " " + applied.missingIds().stream().map(DockableId::value).toList() + ".")
+ (scenario == RestoreScenario.PROJECT_FALLBACK || scenario == RestoreScenario.PARTIAL_FLOATING
? " Configured editor fallback (primary)." : "")
+ (scenario == RestoreScenario.OFFSCREEN ? " Saved off-screen bounds fitted to available displays." : "");
case RestoreResult.Rejected rejected -> "Fallback layout retained: " + rejected.failure().code()
+ (rejected.failure().dockableId() == null ? "" : " (" + rejected.failure().dockableId().value() + ")")
+ "; prepared " + prepared.get() + ", discarded " + discarded.get()
+ ", cleanup diagnostics " + rejected.cleanupFailures().size() + "."
+ " " + manager.describeFailure(rejected.failure())
+ (rejected.failure().cause() == null ? "" : " " + rejected.failure().cause().getMessage());
};
Button returnProject = new Button("Return Project");
DockableId projectId = new DockableId("project");
returnProject.setDisable(manager.findDockable(projectId).isEmpty());
returnProject.setOnAction(event -> status.setText(switch (manager.move(projectId, DockTarget.returnToMain())) {
case ActionResult.Applied ignored -> "Project returned to its preserved main-window target.";
case ActionResult.NoChange ignored -> "Project is already in the main window.";
case ActionResult.Rejected rejected -> manager.describeFailure(rejected.failure());
}));
((BorderPane) target.getScene().getRoot()).setTop(new ToolBar(returnProject));
target.setTitle(result instanceof RestoreResult.Applied ? "Restored snapshot" : "Unchanged fallback layout");
long beforeShow = visibleFloatingWindows(visibleBefore, target);
target.show();
message += " Floating windows before main show: " + beforeShow + "; now: "
+ visibleFloatingWindows(visibleBefore, target) + ".";
status.setText(message);
sourceStatus.setText(message);
} catch (java.io.IOException failure) {
target.hide();
sourceStatus.setText("Cannot load the workspace FXML: " + failure.getMessage());
}
}
private static DockPane loadPane() throws java.io.IOException {
return FXMLLoader.load(SnapshotDockingApp.class.getResource("SnapshotDocking.fxml"));
}
private static long visibleFloatingWindows(List<Window> previous, Stage main) {
return Window.getWindows().stream().filter(window -> window != main && !previous.contains(window)).count();
}
private static LayoutSnapshot offscreenSnapshot(LayoutSnapshot snapshot) {
return new LayoutSnapshot(snapshot.version(), snapshot.windows().stream().map(window -> window.main() ? window
: new LayoutSnapshot.Window(window.id(), false,
new Rectangle2D(-100_000, -100_000, window.bounds().getWidth(), window.bounds().getHeight()),
window.roots())).toList(), snapshot.activeDockableId(), snapshot.returnPositions(), snapshot.initialIntents());
}
private static DockingOptions restoreOptions(RestoreScenario scenario) {
DockingOptions options = new DockingOptions();
AtomicInteger configured = new AtomicInteger();
options.setFloatingWindowCustomizer(configuration -> {
if (scenario == RestoreScenario.ABORT_CUSTOMIZER && configured.incrementAndGet() == 2) {
throw new IllegalStateException("Demo customizer rejected the second floating window");
}
configuration.setTitle("Snapshot floating content");
});
if (scenario == RestoreScenario.PARTIAL_FLOATING) options.setFallbackTarget(DockTarget.area("primary"));
if (scenario == RestoreScenario.PROJECT_FALLBACK || scenario == RestoreScenario.REJECT_PROJECT) {
options.setFallbackTarget(DockTarget.area("primary"));
DockGroupId tools = new DockGroupId("tools");
options.setPlacementRule((dockable, destination) -> {
boolean forbidden = dockable.getId().value().equals("project")
&& (scenario == RestoreScenario.REJECT_PROJECT
|| destination instanceof ResolvedDockTarget.Insertion insertion && insertion.groupId().equals(tools));
return forbidden ? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED,
dockable.getId(), "Project is not allowed in this destination", null)) : Optional.empty();
});
}
return options;
}
private static Dockable content(Document document) {
Dockable content = new Dockable(new DockableId(document.id()), new TextArea(document.text()));
content.setTitle(document.title());
return content;
}
private record Document(String id, String area, String title, String text) { }
private enum RestoreScenario {
NORMAL, LOAD_FAILURE, MISSING_CONTENT, PROJECT_FALLBACK, REJECT_PROJECT,
PARTIAL_FLOATING, OFFSCREEN, ABORT_CUSTOMIZER
}
}
@@ -0,0 +1,9 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain classpath launcher for the snapshot example. */
public final class SnapshotDockingMain {
private SnapshotDockingMain() { }
public static void main(String[] args) { Application.launch(SnapshotDockingApp.class, args); }
}
@@ -0,0 +1,19 @@
package de.neitzel.fx.example.docking.mvvm;
import javafx.application.Application;
import javafx.stage.Stage;
/** Visible example of optional MVVM content hosted by the plain docking API. */
public final class MvvmDockingApp extends Application {
private MvvmDockingWorkspace workspace;
@Override public void start(Stage stage) {
workspace = new MvvmDockingWorkspace(stage);
stage.setTitle("NeitzelLib — MVVM editor and local/global bars");
stage.show();
}
@Override public void stop() {
if (workspace != null) workspace.close();
}
}
@@ -0,0 +1,10 @@
package de.neitzel.fx.example.docking.mvvm;
import javafx.application.Application;
/** Classpath launcher that does not extend JavaFX Application. */
public final class MvvmDockingMain {
private MvvmDockingMain() { }
public static void main(String[] args) { Application.launch(MvvmDockingApp.class, args); }
}
@@ -0,0 +1,91 @@
package de.neitzel.fx.example.docking.mvvm;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.scene.Scene;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.StringBinding;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import lombok.Getter;
/** Composes global bars with an optional MVVM editor and ordinary JavaFX content. */
public final class MvvmDockingWorkspace implements AutoCloseable {
@Getter private final DockingManager manager;
@Getter private final MvvmEditor editor;
@Getter private final Dockable plain;
private final ToolBar globalTools;
private final Button save;
private final Label active;
private final BooleanBinding saveDisabled;
private final StringBinding activeText;
public MvvmDockingWorkspace(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setPreferredWidth(360);
pane.getInitialLayout().setRight(tools);
Button move = new Button("Move Notes to tools");
Button floating = new Button("Float Notes");
Button returning = new Button("Return Notes");
save = new Button("Checkpoint active");
save.setId("saveActive");
globalTools = new ToolBar(save, move, floating, returning);
globalTools.setId("globalTools");
StatusBar globalStatus = new StatusBar();
globalStatus.setId("globalStatus");
active = new Label();
active.setId("activeStatus");
globalStatus.getLeftItems().add(active);
globalStatus.getRightItems().add(new Label("Checkpoints stay in memory"));
BorderPane shell = new BorderPane(pane, globalTools, null, globalStatus, null);
stage.setScene(new Scene(shell, 1040, 620));
manager = DockingManager.attach(stage, pane, new DockingOptions());
editor = new MvvmEditor("notes");
plain = new Dockable(new DockableId("plain"), new TextArea("A plain JavaFX editor needs no ViewLoader."));
plain.setTitle("Plain editor");
saveDisabled = Bindings.createBooleanBinding(
() -> manager.activeDockable() != editor.getDockable() || !editor.dirtyProperty().get(),
manager.activeDockableProperty(), editor.dirtyProperty());
save.disableProperty().bind(saveDisabled);
activeText = Bindings.createStringBinding(
() -> manager.activeDockable() == null ? "No active content" : "Active: " + manager.activeDockable().getTitle(),
manager.activeDockableProperty(), editor.getDockable().titleProperty(), plain.titleProperty());
active.textProperty().bind(activeText);
save.setOnAction(event -> {
if (manager.activeDockable() == editor.getDockable()) editor.checkpoint();
});
manager.open(plain, DockTarget.area("editors"));
manager.open(editor.getDockable(), DockTarget.area("editors"));
move.setOnAction(event -> manager.move(editor.getDockable().getId(), DockTarget.area("tools")));
floating.setOnAction(event -> manager.move(editor.getDockable().getId(), DockTarget.floating()));
returning.setOnAction(event -> manager.move(editor.getDockable().getId(), DockTarget.returnToMain()));
}
/** Releases application-owned global bindings when this demonstration ends. */
@Override public void close() {
save.disableProperty().unbind();
saveDisabled.dispose();
active.textProperty().unbind();
activeText.dispose();
for (var item : globalTools.getItems()) {
if (item instanceof Button button) {
button.setOnAction(null);
button.setDisable(true);
}
}
editor.close();
}
}
@@ -0,0 +1,80 @@
package de.neitzel.fx.example.docking.mvvm;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.example.model.Note;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.injection.ApplicationContext;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.Property;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.value.ChangeListener;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import lombok.Getter;
/** Application adapter: one loaded View becomes ordinary Dockable content. */
public final class MvvmEditor implements AutoCloseable {
@Getter private final Note model = new Note("Edit this note, then move or float its tab.");
@Getter private final LoadedView view;
@Getter private final Dockable dockable;
private final Property<String> text;
private final Label status;
private final Button clear;
private final StringBinding titleBinding;
private final StringBinding statusBinding;
private String checkpoint;
private boolean released;
private final ReadOnlyBooleanWrapper dirty = new ReadOnlyBooleanWrapper(this, "dirty");
private final ChangeListener<String> changed = (observable, old, current) -> dirty.set(!java.util.Objects.equals(checkpoint, current));
@SuppressWarnings("unchecked")
public MvvmEditor(String id) {
view = ViewLoader.load(MvvmEditor.class.getResource("MvvmEditor.fxml"), model,
new ApplicationContext(MvvmEditor.class));
text = (Property<String>) view.property("text");
TextArea input = (TextArea) view.getRoot().lookup("#text");
dockable = new Dockable(new DockableId(id), view.getRoot());
dockable.setFocusTarget(() -> input);
checkpoint = model.getText();
text.addListener(changed);
titleBinding = Bindings.createStringBinding(() -> "Notes" + (dirty.get() ? " *" : ""), dirty);
dockable.titleProperty().bind(titleBinding);
status = (Label) view.getRoot().lookup("#localMessage");
statusBinding = Bindings.createStringBinding(() -> java.util.Objects.toString(text.getValue(), "").length() + " characters", text);
status.textProperty().bind(statusBinding);
ToolBar tools = (ToolBar) view.getRoot().lookup("#localTools");
clear = (Button) tools.getItems().getFirst();
clear.setOnAction(event -> input.clear());
dockable.setOnClosed(this::close);
dockable.setOnDiscarded(this::close);
}
public ReadOnlyBooleanProperty dirtyProperty() { return dirty.getReadOnlyProperty(); }
/** Records an in-memory checkpoint; this example does not write a file. */
public void checkpoint() {
if (released) return;
checkpoint = text.getValue();
dirty.set(false);
}
/** Releases this adapter's resources, not the LoadedView or global ViewModel identity cache. */
@Override public void close() {
if (released) return;
released = true;
text.removeListener(changed);
dockable.titleProperty().unbind();
titleBinding.dispose();
status.textProperty().unbind();
statusBinding.dispose();
status.setText("Released application listeners");
clear.setOnAction(null);
clear.setDisable(true);
}
}
@@ -0,0 +1,242 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** Application-owned persistence, editor resources and save decisions around an independent docking manager. */
public final class ReferenceWorkspace implements AutoCloseable {
private final Stage stage;
private final WorkspaceStore store;
private final boolean mvvm;
private final DockPane pane;
private final ExecutorService storage = Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().name("workspace-storage").factory());
private final Map<DockableId, WorkspaceEditor> editors = new LinkedHashMap<>();
private final Label status = identified(new Label(), "workspaceStatus");
private final Label active = identified(new Label(), "activeLabel");
private final TextArea events = identified(new TextArea(), "workspaceEvents");
private final CheckBox veto = check("Readme vetoes close", "vetoReadme");
private final CheckBox saveFailure = check("Simulate save failure", "saveFailure");
private final CheckBox skipReadme = check("Readme missing on reload", "skipReadme");
private final CheckBox mainOnly = check("Project main window only", "projectMainOnly");
private final CheckBox blockProject = check("Project cannot use original group", "blockProject");
private final CheckBox fallback = check("Allow designated editor fallback", "allowFallback");
private final SimpleObjectProperty<CompletableFuture<ShutdownDecision>> pending = new SimpleObjectProperty<>();
private DockingManager manager;
private LayoutSnapshot pendingLayout;
private StoredWorkspace lastSaved;
private boolean saving;
private boolean closeRequested;
private boolean closed;
public ReferenceWorkspace(Stage stage, boolean fxml, boolean mvvm, WorkspaceStore store,
Optional<StoredWorkspace> saved) throws IOException {
this.stage = stage; this.store = store; this.mvvm = mvvm; pane = WorkspaceView.create(fxml);
fallback.setSelected(true);
ToolBar tools = identified(new ToolBar(
button("Save workspace", "saveWorkspace", () -> save(null)),
button("Reload saved", "reloadWorkspace", this::reload),
button("Reset layout", "resetLayout", () -> report(manager.resetLayout())),
button("Replace workspace", "replaceWorkspace", () -> requestClose(true)),
button("Quit", "quitWorkspace", () -> requestClose(false))), "globalTools");
ToolBar placement = new ToolBar(
button("Float active", "floatActive", () -> moveActive(DockTarget.floating())),
button("Return active", "returnActive", () -> moveActive(DockTarget.returnToMain())),
button("Split active right", "splitActive", this::splitActive),
button("Project", "showProject", () -> report(manager.activate(new DockableId("project")))),
button("Changed files", "showChanges", () -> report(manager.activate(new DockableId("changes")))),
button("Clear active editor", "clearActive", this::clearActive));
Button retry = button("Save / Retry", "retrySave", () -> save(pending.get()));
Button cancel = button("Cancel close", "cancelSave", this::cancelSave);
retry.disableProperty().bind(pending.isNull()); cancel.disableProperty().bind(pending.isNull());
TitledPane scenarios = new TitledPane("Restore and close scenarios", new VBox(
new ToolBar(skipReadme, mainOnly, blockProject), new ToolBar(fallback, veto, saveFailure)));
scenarios.setExpanded(false); scenarios.setId("workspaceScenarios");
events.setEditable(false); events.setPrefRowCount(4);
StatusBar globalStatus = identified(new StatusBar(), "globalStatus");
globalStatus.getLeftItems().add(status); globalStatus.getRightItems().add(active);
BorderPane shell = new BorderPane(pane);
shell.setTop(new VBox(tools, placement, scenarios, new ToolBar(retry, cancel)));
shell.setBottom(new VBox(events, globalStatus));
stage.setTitle("NeitzelLib — Reference workspace" + (mvvm ? " (MVVM Notes)" : " (plain JavaFX)"));
stage.setScene(new Scene(shell, 1180, 780));
attach(saved); stage.show();
}
private void attach(Optional<StoredWorkspace> saved) {
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(this::beforeShutdown);
options.setFallbackTarget(fallback.isSelected() ? DockTarget.area("editors") : null);
options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("Reference workspace — floating"));
options.setPlacementRule((dockable, target) -> blockProject.isSelected() && dockable.getId().value().equals("project")
&& target instanceof ResolvedDockTarget.Insertion insertion && insertion.groupId().value().equals("project")
? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), "Project group disabled by application", null))
: Optional.empty());
manager = DockingManager.attach(stage, pane, options);
active.textProperty().unbind();
active.textProperty().bind(javafx.beans.binding.Bindings.createStringBinding(() -> {
Dockable selected = manager.activeDockableProperty().get();
return "Active: " + (selected == null ? "none" : selected.getId().value());
}, manager.activeDockableProperty()));
if (saved.isPresent()) {
lastSaved = saved.get();
RestoreResult result = manager.restore(lastSaved.layout(), id -> resolve(id, lastSaved));
report(result);
if (result instanceof RestoreResult.Applied) { log("Restored workspace before showing new windows"); return; }
log("Restore rejected atomically; opening initial layout");
defaults();
status.setText("Restore rejected: " + ((RestoreResult.Rejected) result).failure().code()
+ "; opened initial workspace. See events for details.");
return;
}
defaults();
}
private void defaults() {
manager.open(editor("readme", new StoredWorkspace.Document("Readme", "Drag a tab, resize groups, or open its keyboard menu with Shift+F10.")), DockTarget.area("editors"));
manager.open(editor("notes", new StoredWorkspace.Document("Notes", "Write notes here. Unsaved text survives move, float and reset.")), DockTarget.area("editors"));
manager.open(tool("project"), DockTarget.area("project"));
manager.open(tool("changes"), DockTarget.area("changes"));
manager.activate(new DockableId("notes"));
status.setText("Workspace ready; " + store.getFile());
}
private DockableResolution resolve(DockableId id, StoredWorkspace saved) {
if (id.value().equals("readme") && skipReadme.isSelected()) return new DockableResolution.Missing();
if (id.value().equals("project") || id.value().equals("changes")) return new DockableResolution.Available(tool(id.value()));
StoredWorkspace.Document document = saved.documents().get(id);
return document == null ? new DockableResolution.Missing() : new DockableResolution.Available(editor(id.value(), document));
}
private Dockable editor(String id, StoredWorkspace.Document document) {
WorkspaceEditor editor = new WorkspaceEditor(id, document, mvvm && id.equals("notes"));
editors.put(editor.getDockable().getId(), editor);
lifecycle(editor.getDockable(), () -> { editors.remove(editor.getDockable().getId(), editor); editor.close(); });
return editor.getDockable();
}
private Dockable tool(String id) {
ListView<String> content = new ListView<>(); content.setId(id + "Content");
content.getItems().addAll(id.equals("project") ? new String[]{"Notes", "Readme", "Workspace layout"}
: new String[]{"Application owns document state", "Save workspace stores current text"});
Dockable dockable = new Dockable(new DockableId(id), content);
dockable.setIcon(new Label(id.equals("project") ? "P" : "Δ"));
dockable.setAccessibleName(id.equals("project") ? "Project" : "Changed files");
dockable.setFocusTarget(() -> content); dockable.setMainWindowOnly(id.equals("project") && mainOnly.isSelected());
lifecycle(dockable, () -> { }); return dockable;
}
private void lifecycle(Dockable dockable, Runnable cleanup) {
dockable.setCloseCheck(request -> {
log("Checked " + dockable.getId().value() + " — " + request.scope().kind());
return CompletableFuture.completedFuture(dockable.getId().value().equals("readme") && veto.isSelected()
? CloseConsent.VETO : CloseConsent.ALLOW);
});
dockable.setOnClosed(() -> { cleanup.run(); log("Closed " + dockable.getId().value()); });
dockable.setOnDiscarded(() -> { cleanup.run(); log("Discarded " + dockable.getId().value()); });
}
private CompletionStage<ShutdownDecision> beforeShutdown(ShutdownRequest request) {
pendingLayout = request.snapshot();
CompletableFuture<ShutdownDecision> decision = new CompletableFuture<>(); pending.set(decision);
status.setText("Save pending — Save / Retry or Cancel close"); log("All consent obtained; save pending " + request.reason());
return decision;
}
private StoredWorkspace capture(LayoutSnapshot layout) {
Map<DockableId, StoredWorkspace.Document> documents = new LinkedHashMap<>();
editors.forEach((id, editor) -> documents.put(id, editor.document()));
return new StoredWorkspace(StoredWorkspace.CURRENT_VERSION, layout, documents);
}
private void save(CompletableFuture<ShutdownDecision> decision) {
if (saving || closed) return;
if (decision == null && pending.get() != null) { status.setText("Use Save / Retry for the pending close"); return; }
StoredWorkspace snapshot = capture(decision == null ? manager.snapshot() : pendingLayout);
if (saveFailure.isSelected()) { status.setText("Save failed (simulated); retry or cancel keeps every editor open"); return; }
saving = true; status.setText("Saving workspace…");
CompletableFuture.runAsync(() -> {
try { store.save(snapshot); } catch (IOException failure) { throw new java.util.concurrent.CompletionException(failure); }
}, storage).whenComplete((unused, failure) -> Platform.runLater(() -> {
saving = false;
if (closed || decision != null && pending.get() != decision) return;
if (failure != null) { status.setText("Save failed: " + failure.getCause().getMessage() + "; retry or cancel"); return; }
lastSaved = snapshot;
if (!capture(snapshot.layout()).documents().equals(snapshot.documents())) {
status.setText("Text changed while saving; save again before closing"); return;
}
editors.values().forEach(WorkspaceEditor::checkpoint);
status.setText("Saved workspace to " + store.getFile()); log("Saved " + snapshot.layout().windows().size() + " windows");
if (decision != null) { pending.set(null); pendingLayout = null; decision.complete(ShutdownDecision.PROCEED); }
}));
}
private void cancelSave() {
CompletableFuture<ShutdownDecision> decision = pending.get();
if (decision == null) return;
pending.set(null); pendingLayout = null; decision.complete(ShutdownDecision.CANCEL);
}
private void requestClose(boolean replace) {
if (closeRequested) return;
closeRequested = true;
CompletionStage<CloseResult> result = replace ? manager.requestManagerClose() : manager.requestMainWindowClose();
result.thenAccept(answer -> {
closeRequested = false;
report(answer);
if (answer instanceof CloseResult.Closed) {
active.textProperty().unbind();
if (replace) { attach(Optional.ofNullable(lastSaved)); log("Reattached workspace to the same Stage and DockPane"); }
else close();
}
});
}
private void reload() {
if (lastSaved == null) { status.setText("Save a workspace first; Reload uses that immutable saved state"); return; }
// The same consent and save protocol protects existing content before replacement.
requestClose(true);
}
private void moveActive(DockTarget target) {
Dockable selected = manager.activeDockableProperty().get();
if (selected != null) report(manager.move(selected.getId(), target));
}
private void splitActive() {
Dockable selected = manager.activeDockableProperty().get(); if (selected == null) return;
manager.layout().windows().stream().flatMap(window -> window.areas().stream()).flatMap(area -> area.groups().stream())
.filter(group -> group.dockableIds().contains(selected.getId())).findFirst()
.ifPresent(group -> report(manager.move(selected.getId(), DockTarget.split(group.id(), Side.RIGHT))));
}
private void clearActive() {
Dockable selected = manager.activeDockableProperty().get();
if (selected != null && editors.containsKey(selected.getId())) editors.get(selected.getId()).getInput().clear();
}
private void report(Object result) { status.setText(result.toString()); log(result.toString()); }
private void log(String text) { events.appendText(text + "\n"); }
private static Button button(String title, String id, Runnable action) {
Button button = identified(new Button(title), id); button.setOnAction(event -> action.run()); return button;
}
private static CheckBox check(String title, String id) { return identified(new CheckBox(title), id); }
private static <T extends javafx.scene.Node> T identified(T node, String id) { node.setId(id); return node; }
/** Stops application I/O and bindings; it does not bypass the manager's consent protocol. */
@Override public void close() {
if (closed) return; closed = true; storage.shutdown();
active.textProperty().unbind(); editors.values().forEach(WorkspaceEditor::close);
}
}
@@ -0,0 +1,40 @@
package de.neitzel.fx.example.docking.workspace;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.nio.file.Path;
import java.util.Optional;
/** Reads application data off the FX thread, then restores before showing any workspace windows. */
public final class ReferenceWorkspaceApp extends Application {
private ReferenceWorkspace workspace;
private volatile boolean stopped;
@Override public void start(Stage stage) {
String location = getParameters().getNamed().get("store");
if (location == null || location.isBlank()) {
stage.setScene(new Scene(new Label("Supply --store=/absolute/path/workspace.json; optional: java, mvvm"), 720, 100));
stage.show(); return;
}
WorkspaceStore store = new WorkspaceStore(Path.of(location));
boolean fxml = !getParameters().getUnnamed().contains("java");
boolean mvvm = getParameters().getUnnamed().contains("mvvm");
Thread.ofVirtual().name("workspace-startup").start(() -> {
try {
Optional<StoredWorkspace> saved = store.read();
Platform.runLater(() -> {
if (stopped) return;
try { workspace = new ReferenceWorkspace(stage, fxml, mvvm, store, saved); }
catch (Exception failure) { showFailure(stage, failure); }
});
} catch (Exception failure) { Platform.runLater(() -> { if (!stopped) showFailure(stage, failure); }); }
});
}
private void showFailure(Stage stage, Exception failure) {
stage.setScene(new Scene(new Label("Workspace was not loaded: " + failure.getMessage()
+ "\nThe existing file has not been changed."), 850, 120)); stage.show();
}
@Override public void stop() { stopped = true; if (workspace != null) workspace.close(); }
}
@@ -0,0 +1,9 @@
package de.neitzel.fx.example.docking.workspace;
import javafx.application.Application;
/** Launcher: --store=/absolute/path/workspace.json [java] [mvvm]. */
public final class ReferenceWorkspaceMain {
private ReferenceWorkspaceMain() { }
public static void main(String[] args) { Application.launch(ReferenceWorkspaceApp.class, args); }
}
@@ -0,0 +1,25 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.LayoutSnapshot;
import java.util.Map;
import java.util.Objects;
/** Application data: document contents are stored separately from the library's layout snapshot. */
public record StoredWorkspace(int version, LayoutSnapshot layout, Map<DockableId, Document> documents) {
public static final int CURRENT_VERSION = 1;
public StoredWorkspace {
Objects.requireNonNull(layout, "layout");
documents = Map.copyOf(documents);
}
/** Text documents have no dependency on their plain-JavaFX or optional MVVM presentation. */
public record Document(String title, String text) {
public Document {
Objects.requireNonNull(title, "title");
Objects.requireNonNull(text, "text");
}
}
}
@@ -0,0 +1,65 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.example.docking.mvvm.MvvmEditor;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import lombok.Getter;
/** Application-owned editor resources. Moving content never rebuilds this adapter. */
final class WorkspaceEditor implements AutoCloseable {
@Getter private final Dockable dockable;
@Getter private final TextArea input;
private final String title;
private final MvvmEditor mvvm;
private final StringBinding titleBinding;
private final StringBinding countBinding;
private final Label count;
private final Button clear;
private String saved;
private boolean released;
WorkspaceEditor(String id, StoredWorkspace.Document document, boolean useMvvm) {
title = document.title(); saved = document.text();
if (useMvvm) {
mvvm = new MvvmEditor(id); dockable = mvvm.getDockable();
input = (TextArea) mvvm.getView().getRoot().lookup("#text");
input.setText(saved); mvvm.checkpoint();
mvvm.getView().getRoot().lookup("#localTools").setId(id + "LocalTools");
mvvm.getView().getRoot().lookup("#localStatus").setId(id + "LocalStatus");
titleBinding = null; countBinding = null; count = null; clear = null;
} else {
mvvm = null; input = new TextArea(saved);
clear = new Button("Clear " + title); clear.setOnAction(event -> input.clear());
ToolBar local = new ToolBar(clear); local.setId(id + "LocalTools");
count = new Label(); countBinding = Bindings.createStringBinding(() -> input.getLength() + " characters", input.textProperty());
count.textProperty().bind(countBinding);
StatusBar status = new StatusBar(); status.setId(id + "LocalStatus"); status.getLeftItems().add(count);
BorderPane root = new BorderPane(input); root.setTop(local); root.setBottom(status);
dockable = new Dockable(new DockableId(id), root);
titleBinding = Bindings.createStringBinding(() -> title + (input.getText().equals(saved) ? "" : " *"), input.textProperty());
dockable.titleProperty().bind(titleBinding);
}
input.setId(id + "Text"); dockable.setFocusTarget(() -> input);
}
StoredWorkspace.Document document() { return new StoredWorkspace.Document(title, input.getText()); }
void checkpoint() {
saved = input.getText();
if (mvvm != null) mvvm.checkpoint(); else titleBinding.invalidate();
}
@Override public void close() {
if (released) return; released = true;
if (mvvm != null) mvvm.close();
else {
dockable.titleProperty().unbind(); titleBinding.dispose();
count.textProperty().unbind(); countBinding.dispose(); clear.setOnAction(null);
}
}
}
@@ -0,0 +1,92 @@
package de.neitzel.fx.example.docking.workspace;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import de.neitzel.fx.docking.DockAreaId;
import de.neitzel.fx.docking.DockGroupId;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.DockWindowId;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.LayoutSnapshot;
import de.neitzel.fx.docking.TabPosition;
import javafx.geometry.Rectangle2D;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.function.Function;
/** The example's explicit JSON shape; no adapter is registered in the fx library. */
final class WorkspaceJson {
private WorkspaceJson() { }
static Gson create() {
return new GsonBuilder().setPrettyPrinting().enableComplexMapKeySerialization()
.registerTypeAdapter(DockableId.class, new Identifier<>(DockableId::value, DockableId::new))
.registerTypeAdapter(DockAreaId.class, new Identifier<>(DockAreaId::value, DockAreaId::new))
.registerTypeAdapter(DockGroupId.class, new Identifier<>(DockGroupId::value, DockGroupId::new))
.registerTypeAdapter(DockWindowId.class, new Identifier<>(DockWindowId::value, DockWindowId::new))
.registerTypeAdapter(Rectangle2D.class, new Bounds())
.registerTypeAdapter(LayoutSnapshot.Branch.class, new Tagged<LayoutSnapshot.Branch>(Map.of(
"group", LayoutSnapshot.Group.class, "split", LayoutSnapshot.Split.class)))
.registerTypeAdapter(DockTarget.class, new Tagged<DockTarget>(Map.of(
"area", DockTarget.Area.class, "group", DockTarget.Group.class)))
.registerTypeAdapter(TabPosition.class, new Tagged<TabPosition>(Map.of(
"append", TabPosition.Append.class, "before", TabPosition.Before.class, "after", TabPosition.After.class)))
.create();
}
private record Identifier<T>(Function<T, String> print, Function<String, T> parse)
implements JsonSerializer<T>, JsonDeserializer<T> {
@Override public JsonElement serialize(T value, Type type, JsonSerializationContext context) {
return new JsonPrimitive(print.apply(value));
}
@Override public T deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
if (!json.isJsonPrimitive() || !json.getAsJsonPrimitive().isString()) {
throw new JsonParseException("An identity must be a string");
}
return parse.apply(json.getAsString());
}
}
private record Tagged<T>(Map<String, Class<? extends T>> variants)
implements JsonSerializer<T>, JsonDeserializer<T> {
@Override public JsonElement serialize(T value, Type type, JsonSerializationContext context) {
var variant = variants.entrySet().stream().filter(entry -> entry.getValue() == value.getClass())
.findFirst().orElseThrow(() -> new JsonParseException("Unsupported stored layout value"));
JsonObject object = context.serialize(value, variant.getValue()).getAsJsonObject();
object.addProperty("kind", variant.getKey());
return object;
}
@Override public T deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
JsonObject object = json.getAsJsonObject();
JsonElement kind = object.get("kind");
Class<? extends T> variant = kind == null ? null : variants.get(kind.getAsString());
if (variant == null) throw new JsonParseException("Unknown stored layout kind: " + kind);
return context.deserialize(json, variant);
}
}
private static final class Bounds implements JsonSerializer<Rectangle2D>, JsonDeserializer<Rectangle2D> {
@Override public JsonElement serialize(Rectangle2D value, Type type, JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.addProperty("x", value.getMinX());
object.addProperty("y", value.getMinY());
object.addProperty("width", value.getWidth());
object.addProperty("height", value.getHeight());
return object;
}
@Override public Rectangle2D deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
JsonObject object = json.getAsJsonObject();
return new Rectangle2D(object.get("x").getAsDouble(), object.get("y").getAsDouble(),
object.get("width").getAsDouble(), object.get("height").getAsDouble());
}
}
}
@@ -0,0 +1,62 @@
package de.neitzel.fx.example.docking.workspace;
import lombok.Getter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Files;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.Optional;
/** Application-owned storage used by the reference workspace; it is not a library serialization API. */
public final class WorkspaceStore {
private static final com.google.gson.Gson JSON = WorkspaceJson.create();
@Getter private final Path file;
public WorkspaceStore(Path file) {
this.file = Objects.requireNonNull(file, "file").toAbsolutePath().normalize();
if (this.file.getFileName() == null) throw new IllegalArgumentException("A workspace file name is required");
}
public Optional<StoredWorkspace> read() throws IOException {
if (!Files.exists(file)) return Optional.empty();
try (var input = Files.newBufferedReader(file)) {
StoredWorkspace workspace = JSON.fromJson(input, StoredWorkspace.class);
if (workspace == null) throw new IOException("Workspace file contains no workspace");
requireSupportedVersion(workspace);
return Optional.of(workspace);
} catch (RuntimeException invalid) {
throw new IOException("Cannot read workspace data", invalid);
}
}
public void save(StoredWorkspace workspace) throws IOException {
Objects.requireNonNull(workspace, "workspace");
requireSupportedVersion(workspace);
String json;
try { json = JSON.toJson(workspace); }
catch (RuntimeException invalid) { throw new IOException("Cannot encode workspace data", invalid); }
Files.createDirectories(file.getParent());
Path prepared = Files.createTempFile(file.getParent(), file.getFileName() + ".", ".pending");
try {
Files.writeString(prepared, json);
try {
Files.move(prepared, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException unsupported) {
Files.move(prepared, file, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException failure) {
try { Files.deleteIfExists(prepared); }
catch (IOException cleanup) { failure.addSuppressed(cleanup); }
throw failure;
}
}
private static void requireSupportedVersion(StoredWorkspace workspace) throws IOException {
if (workspace.version() != StoredWorkspace.CURRENT_VERSION) {
throw new IOException("Unsupported application workspace version: " + workspace.version());
}
}
}
@@ -0,0 +1,26 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.docking.*;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Side;
import java.io.IOException;
/** Equivalent ordinary FXML and Java definitions; neither requires MVVM. */
final class WorkspaceView {
private WorkspaceView() { }
static DockPane create(boolean fxml) throws IOException {
if (fxml) return FXMLLoader.load(WorkspaceView.class.getResource("ReferenceWorkspace.fxml"));
DockLayout layout = new DockLayout();
layout.setCenter(new DockGroupDefinition("editors"));
layout.setLeft(side("project", Side.LEFT, 240));
DockGroupDefinition changes = side("changes", Side.RIGHT, 220); changes.setMode(DockGroupMode.OVERLAY);
layout.setRight(changes);
DockGroupDefinition bottom = side("bottom", Side.TOP, 200); bottom.setPreferredHeight(160);
layout.setBottom(bottom);
DockPane pane = new DockPane(); pane.setId("workspaceDock"); pane.setInitialLayout(layout); return pane;
}
private static DockGroupDefinition side(String id, Side side, double width) {
DockGroupDefinition group = new DockGroupDefinition(id); group.setTabSide(side); group.setPreferredWidth(width);
group.setCollapsible(true); group.setVisibleWhenEmpty(false); group.setReleaseSpaceWhenEmpty(true); return group;
}
}
@@ -0,0 +1,21 @@
package de.neitzel.fx.example.grid;
/** Best-effort release of independent application-owned resources, preserving failures. */
final class DemoResources {
private DemoResources() {}
static void closeAll(AutoCloseable... resources) {
RuntimeException failure = null;
for (var resource : resources) {
if (resource == null) continue;
try {
resource.close();
} catch (Exception error) {
if (failure == null)
failure = new IllegalStateException("Could not release demo resources", error);
else failure.addSuppressed(error);
}
}
if (failure != null) throw failure;
}
}
@@ -0,0 +1,129 @@
package de.neitzel.fx.example.grid;
import de.neitzel.grid.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.Consumer;
/**
* Demo-only controlled completion delays. No sleeps, driver interruption or altered SQL semantics.
*/
public final class DiagnosticSource implements GridSource<Long, Product> {
private final GridSource<Long, Product> delegate;
private final ScheduledExecutorService clock;
private final Consumer<String> log;
private final Consumer<FilterCondition> domainValidation;
private final AtomicLong ids = new AtomicLong();
private volatile long delay;
private volatile boolean fail, late;
public DiagnosticSource(
GridSource<Long, Product> delegate,
ScheduledExecutorService clock,
Consumer<String> log,
Consumer<FilterCondition> domainValidation) {
this.delegate = delegate;
this.clock = clock;
this.log = log;
this.domainValidation = domainValidation;
}
public void next(long milliseconds, boolean failure, boolean deliverAfterCancel) {
delay = milliseconds;
fail = failure;
late = deliverAfterCancel;
}
public SourceCapabilities capabilities() {
return delegate.capabilities();
}
public String filterExecutionId() {
return delegate.filterExecutionId();
}
public void validateFilter(FilterCondition condition) {
domainValidation.accept(condition);
delegate.validateFilter(condition);
}
public QueryExecution<Long, Product> query(GridQuery query) {
return query(query, QueryOptions.defaults());
}
public QueryExecution<Long, Product> query(GridQuery query, QueryOptions options) {
long id = ids.incrementAndGet(), started = System.nanoTime(), wait = delay;
boolean failure = fail, ignoreCancel = late;
next(0, false, false);
var result = new CompletableFuture<PageResult<Long, Product>>();
var cancelled = new AtomicBoolean();
log.accept("Request " + id + " requested " + query.page());
try {
query.filters().forEach(this::validateFilter);
} catch (RuntimeException error) {
result.completeExceptionally(error);
return new QueryExecution<>() {
public CompletionStage<PageResult<Long, Product>> result() {
return result;
}
public void cancel() {
result.cancel(false);
}
};
}
var execution = delegate.query(query, options);
execution
.result()
.whenComplete(
(page, error) -> {
try {
clock.schedule(
() -> {
log.accept(
"Request "
+ id
+ " "
+ (cancelled.get()
? "obsolete completion"
+ " (coordinator must"
+ " ignore)"
: "completion")
+ " "
+ ((System.nanoTime() - started)
/ 1_000_000)
+ " ms; rows="
+ (page == null
? 0
: page.rows().size()));
if (error != null) result.completeExceptionally(error);
else if (failure)
result.completeExceptionally(
new IllegalStateException(
"Injected query failure; Retry runs"
+ " normally"));
else result.complete(page);
},
wait,
TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException rejected) {
result.completeExceptionally(rejected);
}
});
return new QueryExecution<>() {
public CompletionStage<PageResult<Long, Product>> result() {
return result;
}
public void cancel() {
cancelled.set(true);
log.accept("Request " + id + " cancellation requested");
if (!ignoreCancel) {
execution.cancel();
result.cancel(false);
}
}
};
}
}
@@ -0,0 +1,10 @@
package de.neitzel.fx.example.grid;
import de.neitzel.grid.FilterCondition;
/** Deliberately memory-only condition used to demonstrate visible backend rejection. */
public record LocalNameLength(String columnId) implements FilterCondition {
public String typeId() {
return "demo.name-length";
}
}
@@ -0,0 +1,66 @@
package de.neitzel.fx.example.grid;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.beans.property.*;
import javafx.fxml.*;
import javafx.scene.Parent;
import javafx.scene.control.TextField;
import java.io.IOException;
import java.math.BigDecimal;
/** Custom FXML editor emitting the portable numeric condition, executable on both backends. */
public final class PricePresetEditor implements FilterEditor {
@FXML private TextField maximum;
private Parent root;
private String column;
private final ReadOnlyStringWrapper validation = new ReadOnlyStringWrapper("");
public static PricePresetEditor load(FilterEditorContext context) {
try {
var loader =
new FXMLLoader(PricePresetEditor.class.getResource("PricePresetEditor.fxml"));
Parent root = loader.load();
PricePresetEditor editor = loader.getController();
editor.root = root;
editor.column = context.columnId();
if (context.committed() instanceof NumericFilter n)
editor.maximum.setText(n.operand().toPlainString());
editor.maximum.textProperty().addListener((o, a, b) -> editor.validate());
editor.validate();
return editor;
} catch (IOException e) {
throw new IllegalStateException("Cannot load price preset", e);
}
}
private void validate() {
try {
draft();
validation.set("");
} catch (RuntimeException e) {
validation.set(
"Enter an exact price with at most two decimal places (0–9,999,999,999.99)");
}
}
public FilterCondition draft() {
var price =
new BigDecimal(maximum.getText()).setScale(2, java.math.RoundingMode.UNNECESSARY);
if (price.signum() < 0 || price.precision() > 12)
throw new IllegalArgumentException("Price outside domain");
return new NumericFilter(column, NumericFilter.Operator.LESS_OR_EQUAL, price, null);
}
public Parent view() {
return root;
}
public ReadOnlyStringProperty validationMessageProperty() {
return validation.getReadOnlyProperty();
}
public void close() {}
}
@@ -0,0 +1,6 @@
package de.neitzel.fx.example.grid;
import java.math.BigDecimal;
/** Immutable demo row; no FX-owned state is read on a worker. */
public record Product(long id, String name, String category, Long quantity, BigDecimal price) {}
@@ -0,0 +1,237 @@
package de.neitzel.fx.example.grid;
import de.neitzel.grid.*;
import de.neitzel.grid.jdbc.*;
import org.h2.jdbcx.JdbcConnectionPool;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
/** Application-owned database, fixture service and execution pool. */
public final class ProductCatalog implements AutoCloseable {
public final ExecutorService workers;
public final JdbcConnectionPool database;
public final MemoryGridSource<Long, Product> memory;
public final JdbcGridSource<Long, Product> jdbc;
private List<Product> products = List.of();
private final int size;
// Keeps this in-memory database alive without DB_CLOSE_DELAY=-1 leaking it after close.
private final Connection anchor;
public ProductCatalog(int size) throws SQLException {
this(
size,
JdbcConnectionPool.create("jdbc:h2:mem:grid_" + UUID.randomUUID(), "sa", ""),
Executors.newFixedThreadPool(4));
}
ProductCatalog(int size, JdbcConnectionPool database, ExecutorService workers)
throws SQLException {
this.size = size;
this.database = Objects.requireNonNull(database);
this.workers = Objects.requireNonNull(workers);
Connection borrowed = null;
try {
borrowed = database.getConnection();
anchor = borrowed;
try (var s = anchor.createStatement()) {
s.execute(
"CREATE TABLE products (id BIGINT PRIMARY KEY, name VARCHAR(200), name_key"
+ " VARCHAR(250), category VARCHAR(100), category_key VARCHAR(120),"
+ " quantity BIGINT, price DECIMAL(12,2))");
}
reset();
memory =
new MemoryGridSource<>(
this::snapshot,
Product::id,
Long::compare,
memoryColumns(),
workers,
250);
jdbc =
new JdbcGridSource<>(
database,
workers,
JdbcDialect.h2(),
"products",
"id",
jdbcColumns(),
ProductCatalog::read,
250,
10);
} catch (SQLException | RuntimeException error) {
try {
DemoResources.closeAll(borrowed, database::dispose, workers::shutdown);
} catch (RuntimeException cleanup) {
error.addSuppressed(cleanup);
}
throw error;
}
}
public static List<Product> fixtures(int size) {
var rows = new ArrayList<Product>();
String[] specials = {
null,
"",
"Alpha",
"alpha",
"Äpfel",
"İstanbul",
"ß",
"ss",
"a%b",
"a_b",
"!literal",
"O'Reilly",
"😀",
"𐀀",
"",
"é",
"é",
" trailing "
};
for (int i = 1; i <= size; i++)
rows.add(
new Product(
i,
i <= specials.length ? specials[i - 1] : "Product " + (i % 137),
i % 17 == 0
? null
: List.of("Hardware", "Office", "Food", "").get(i % 4),
i % 19 == 0 ? null : (long) (i % 80),
i % 23 == 0 ? null : BigDecimal.valueOf(i % 10007, 2)));
return List.copyOf(rows);
}
public static List<JdbcColumn> jdbcColumns() {
return List.of(
JdbcColumn.integer("id", "id"),
JdbcColumn.text("name", "name", "name_key"),
JdbcColumn.text("category", "category", "category_key"),
JdbcColumn.integer("quantity", "quantity"),
JdbcColumn.decimal("price", "price", 12, 2));
}
public static List<MemoryColumn<Product>> memoryColumns() {
return List.of(
new MemoryColumn<>(
"id", MemoryColumn.Kind.INTEGER, p -> new FilterValue.IntegerValue(p.id())),
new MemoryColumn<>(
"name",
MemoryColumn.Kind.TEXT,
p -> p.name() == null ? null : new FilterValue.Text(p.name()),
Map.of(
"demo.name-length",
f -> {
if (!(f instanceof LocalNameLength))
throw new IllegalArgumentException(
"Wrong custom condition");
return v ->
v instanceof FilterValue.Text t
&& t.value().length() <= 5;
})),
new MemoryColumn<>(
"category",
MemoryColumn.Kind.TEXT,
p -> p.category() == null ? null : new FilterValue.Text(p.category())),
new MemoryColumn<>(
"quantity",
MemoryColumn.Kind.INTEGER,
p ->
p.quantity() == null
? null
: new FilterValue.IntegerValue(p.quantity())),
new MemoryColumn<>(
"price",
MemoryColumn.Kind.DECIMAL,
p -> p.price() == null ? null : new FilterValue.Decimal(p.price())));
}
public static GridRow<Long, Product> read(ResultSet rs) throws SQLException {
var p =
new Product(
rs.getLong("id"),
rs.getString("name"),
rs.getString("category"),
(Long) rs.getObject("quantity"),
rs.getBigDecimal("price"));
return new GridRow<>(p.id(), p);
}
public synchronized List<Product> snapshot() {
return products;
}
public synchronized void reset() throws SQLException {
replace(fixtures(size));
}
public synchronized void insert() throws SQLException {
var copy = new ArrayList<>(products);
long id = copy.stream().mapToLong(Product::id).max().orElse(0) + 1;
var p = new Product(id, "Inserted " + id, "Office", 1L, new BigDecimal("1.00"));
try (var c = database.getConnection()) {
insert(c, List.of(p));
}
copy.add(p);
products = List.copyOf(copy);
}
public synchronized void delete(long id) throws SQLException {
try (var c = database.getConnection();
var s = c.prepareStatement("DELETE FROM products WHERE id=?")) {
s.setLong(1, id);
s.executeUpdate();
}
products = products.stream().filter(p -> p.id() != id).toList();
}
private void replace(List<Product> rows) throws SQLException {
try (var c = database.getConnection()) {
c.setAutoCommit(false);
try (var s = c.createStatement()) {
s.executeUpdate("DELETE FROM products");
}
insert(c, rows);
c.commit();
}
products = List.copyOf(rows);
}
public static void insert(Connection c, List<Product> rows) throws SQLException {
try (var s = c.prepareStatement("INSERT INTO products VALUES (?,?,?,?,?,?,?)")) {
for (var p : rows) {
s.setLong(1, p.id());
s.setString(2, p.name());
s.setString(3, key(p.name()));
s.setString(4, p.category());
s.setString(5, key(p.category()));
s.setObject(6, p.quantity());
s.setBigDecimal(7, p.price());
s.addBatch();
}
s.executeBatch();
}
}
private static String key(String text) {
return text == null ? null : text.toLowerCase(Locale.ROOT);
}
public void close() {
workers.shutdown();
try {
if (!workers.awaitTermination(15, TimeUnit.SECONDS))
throw new IllegalStateException("Queries did not finish before database shutdown");
DemoResources.closeAll(anchor, database::dispose);
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new IllegalStateException(error);
}
}
}
@@ -0,0 +1,36 @@
package de.neitzel.fx.example.grid;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.nio.file.Path;
/** Standalone entry point; resources are application-owned and released on shutdown. */
public final class ProductGridApp extends Application {
private ProductCatalog catalog;
private ProductGridDemo demo;
public void init() throws Exception {
catalog = new ProductCatalog(10000);
}
public void start(Stage stage) {
demo =
new ProductGridDemo(
catalog,
Path.of(
System.getProperty("user.home"),
".neitzellib-example",
"products-setup.json"));
var scene = new Scene(demo, 1120, 820);
demo.install(scene);
stage.setScene(scene);
stage.setTitle("DataGrid — Memory and H2");
stage.show();
}
public void stop() {
DemoResources.closeAll(demo, catalog);
}
}
@@ -0,0 +1,438 @@
package de.neitzel.fx.example.grid;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.fx.theme.ThemeManager;
import de.neitzel.fx.view.*;
import de.neitzel.grid.*;
import de.neitzel.gson.grid.GridSetupJson;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import java.math.BigDecimal;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
/** Application-owned composition; existing person-desk launcher and legacy Table are unchanged. */
public final class ProductGridDemo extends VBox implements AutoCloseable {
public final DataGrid<Long, Product> grid;
public final ThemeManager themes = new ThemeManager();
public final ComboBox<String> sourcePicker = new ComboBox<>(), themePicker = new ComboBox<>();
public final TextArea diagnostics = new TextArea();
public final Label message = new Label();
public final ProductCatalog catalog;
private final ScheduledExecutorService clock = Executors.newSingleThreadScheduledExecutor();
private final DiagnosticSource memory, jdbc;
private DiagnosticSource requested;
private final GridSetupJson codec = new GridSetupJson();
private final Path setupFile;
private boolean closed;
public ProductGridDemo(ProductCatalog catalog, Path setupFile) {
this.catalog = catalog;
this.setupFile = setupFile;
setSpacing(8);
setStyle("-fx-padding: 12;");
memory =
new DiagnosticSource(
catalog.memory,
clock,
this::log,
condition -> {
if (!(condition instanceof LocalNameLength))
catalog.jdbc.validateFilter(condition);
});
jdbc = new DiagnosticSource(catalog.jdbc, clock, this::log, catalog.jdbc::validateFilter);
requested = jdbc;
grid =
new DataGrid<>(
List.of(
new ResultColumn("id", "ID", 80, 60, 140, -1),
new ResultColumn("name", "Name", 260, 120, 600, -1),
new ResultColumn("category", "Category", 150, 90, 300, -1),
new ResultColumn("quantity", "Quantity", 110, 80, 220, -1),
new ResultColumn("price", "Price", 120, 90, 240, -1)),
ProductRow::create,
jdbc);
grid.configureSetups(
"demo.products",
2,
Map.of(
"id",
"long.v1",
"name",
"text.v1",
"category",
"text.v1",
"quantity",
"long.v1",
"price",
"decimal12-2.v1"),
Map.of(1, ProductGridDemo::migrateLegacy));
var editors = FilterEditors.builtIns(Set.of("jdbc-h2"));
editors.register(
new FilterEditors.Registration(
"demo.budget",
new FilterCapabilities(true, true, Set.of("jdbc-h2")),
Set.of("neitzel.number"),
PricePresetEditor::load));
grid.setFilterEditors(editors);
var pageNames =
FilterCandidates.currentPage(
() -> {
var state = grid.stateProperty().get();
if (state.result() == null) return List.of();
return state.result().rows().stream()
.map(
row ->
new FilterCandidates.Candidate(
row.model().name() == null
? null
: new FilterValue.Text(
row.model().name()),
row.model().name() == null
? "(missing)"
: row.model().name()))
.toList();
});
grid.configureFilter(
"name",
FilterColumn.text().withChecklist(FilterColumn.Checklist.CURRENT_PAGE, pageNames));
grid.configureFilter("category", FilterColumn.text());
grid.configureFilter("quantity", FilterColumn.number(Locale.ROOT, true, null, null));
grid.configureFilter(
"price",
FilterColumn.number(
Locale.ROOT, false, BigDecimal.ZERO, new BigDecimal("9999999999.99")));
grid.configureFilter("id", FilterColumn.number(Locale.ROOT, true, BigDecimal.ONE, null));
sourcePicker.getItems().setAll("JDBC / H2", "Memory");
sourcePicker.setValue("JDBC / H2");
sourcePicker.setOnAction(
e -> {
requested = sourcePicker.getValue().equals("Memory") ? memory : jdbc;
grid.setSource(requested);
});
themePicker.getItems().setAll("light", "dark", "high-contrast");
themePicker.setValue("light");
themePicker.setOnAction(e -> themes.select(themePicker.getValue()));
var threshold = new Spinner<Integer>(0, 100000, 1000, 250);
threshold.setPrefWidth(110);
threshold.valueProperty().addListener((o, a, b) -> grid.setAllWarningThreshold(b));
var custom = new CheckBox("Custom budget editor");
custom.setOnAction(
e ->
grid.configureFilter(
"price",
custom.isSelected()
? new FilterColumn(
"demo.budget",
Locale.ROOT,
false,
false,
BigDecimal.ZERO,
new BigDecimal("9999999999.99"),
FilterColumn.Checklist.DISABLED,
null)
: FilterColumn.number(
Locale.ROOT,
false,
BigDecimal.ZERO,
new BigDecimal("9999999999.99"))));
var outside = new CheckBox("Accept on outside click");
var actions = new CheckBox("Show OK / Cancel");
actions.setSelected(true);
Runnable popup =
() ->
grid.setFilterPopupOptions(
new FilterPopup.Options(
outside.isSelected()
? FilterPopup.Outside.ACCEPT
: FilterPopup.Outside.CANCEL,
actions.isSelected(),
actions.isSelected()));
outside.setOnAction(e -> popup.run());
actions.setOnAction(e -> popup.run());
Button save = button("Save setup", this::save), load = button("Load setup", this::restore);
Button legacy = button("Load v1 setup", this::restoreLegacy);
Button clear = button("Clear filters", () -> grid.setFilters(List.of())),
unsupported =
button(
"Memory-only filter",
() -> grid.setFilters(List.of(new LocalNameLength("name"))));
Button slow =
button(
"Slow next refresh",
() -> {
requested.next(2500, false, false);
grid.refresh();
});
Button failure =
button(
"Fail next refresh",
() -> {
requested.next(500, true, false);
grid.refresh();
});
Button late =
button(
"Late success then failure",
() -> {
requested.next(2500, false, true);
grid.refresh();
Platform.runLater(
() -> {
if (!closed) {
requested.next(100, true, false);
grid.refresh();
}
});
});
Button lateFailure =
button(
"Late failure then success",
() -> {
requested.next(2500, true, true);
grid.refresh();
Platform.runLater(
() -> {
if (!closed) grid.refresh();
});
});
Button insert = button("Insert fixture", () -> mutate(() -> catalog.insert()));
Button delete =
button(
"Delete selected",
() -> {
Long id = grid.selectedKeyProperty().get();
if (id == null)
throw new IllegalArgumentException("Select a row first");
mutate(() -> catalog.delete(id), () -> grid.confirmedDeleted(id));
});
Button reset = button("Reset fixtures", () -> mutate(() -> catalog.reset()));
Button tail =
button(
"Delete displayed page",
() -> {
var state = grid.stateProperty().get();
if (state.result() == null) return;
var ids = state.result().rows().stream().map(GridRow::key).toList();
mutate(
() -> {
for (long id : ids) catalog.delete(id);
});
});
Button reorder =
button(
"Price first",
() ->
grid.setColumnOrder(
List.of("price", "id", "name", "category", "quantity")));
Button width =
button(
"Widen name",
() -> grid.setColumnWidth("name", new ColumnWidth.Explicit(400)));
message.getStyleClass().add("theme-error");
message.setWrapText(true);
diagnostics.setEditable(false);
diagnostics.setPrefRowCount(7);
var detail = new TitledPane("Request diagnostics", diagnostics);
detail.setExpanded(false);
grid.stateProperty()
.addListener(
(o, a, b) ->
log(
"Grid generation "
+ b.generation()
+ ": "
+ b.phase()
+ "; requested="
+ b.requested().page()
+ "; displayed="
+ (b.displayed() == null
? "none"
: b.displayed().page())));
getChildren()
.addAll(
new Label("Product catalog — deterministic memory / H2 demonstration"),
new FlowPane(
8,
8,
new Label("Source"),
sourcePicker,
new Label("Theme"),
themePicker,
new Label("All warning threshold"),
threshold),
new FlowPane(8, 8, save, load, legacy, reorder, width, clear, unsupported),
new FlowPane(8, 8, custom, outside, actions),
new FlowPane(8, 8, insert, delete, tail, reset),
new FlowPane(8, 8, slow, failure, late, lateFailure),
message,
grid,
detail);
VBox.setVgrow(grid, Priority.ALWAYS);
grid.setPrefHeight(450);
grid.load();
}
@FunctionalInterface
private interface Work {
void run() throws Exception;
}
private Button button(String text, Work action) {
var b = new Button(text);
b.setOnAction(
e -> {
try {
message.setText("");
action.run();
} catch (Exception error) {
message.setText(error.getMessage());
}
});
return b;
}
private void mutate(Work work) {
mutate(work, grid::refresh);
}
private void mutate(Work work, Runnable publish) {
CompletableFuture.runAsync(
() -> {
try {
work.run();
} catch (Exception e) {
throw new CompletionException(e);
}
},
catalog.workers)
.whenComplete(
(v, e) ->
Platform.runLater(
() -> {
if (closed) return;
if (e != null)
message.setText(e.getCause().getMessage());
else publish.run();
}));
}
public void save() throws java.io.IOException {
String document = codec.encode(grid.snapshotSetup());
Files.createDirectories(setupFile.toAbsolutePath().getParent());
var temporary =
Files.createTempFile(setupFile.toAbsolutePath().getParent(), "grid-", ".json");
try {
Files.writeString(temporary, document);
Files.move(
temporary,
setupFile,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temporary);
}
message.setText("Saved setup to " + setupFile);
}
/** Demonstrates an explicit column rename, not heuristic recovery of unknown columns. */
public void restoreLegacy() {
var current = grid.snapshotSetup();
var columns =
current.columns().stream()
.map(
c ->
new GridSetup.ColumnState(
c.id().equals("category") ? "group" : c.id(),
c.type(),
c.width()))
.toList();
grid.restoreSetup(
new GridSetup(
1,
"demo.products",
1,
columns,
List.of(new SortKey("group", SortKey.Direction.ASCENDING)),
List.of(
new TextFilter(
"group", TextFilter.Operator.EQUALS, "Office", true)),
new PageRequest.Paged(0, 50)));
}
private static GridSetup migrateLegacy(GridSetup old) {
var columns =
old.columns().stream()
.map(c -> new GridSetup.ColumnState(rename(c.id()), c.type(), c.width()))
.toList();
var sorts =
old.sort().stream()
.map(s -> new SortKey(rename(s.columnId()), s.direction()))
.toList();
var filters =
old.filters().stream()
.map(
f -> {
if (!f.columnId().equals("group")) return f;
if (f instanceof TextFilter t)
return (FilterCondition)
new TextFilter(
"category",
t.operator(),
t.operand(),
t.caseSensitive());
if (f instanceof MissingFilter m)
return (FilterCondition)
new MissingFilter("category", m.missing());
if (f instanceof ValueFilter v)
return (FilterCondition)
new ValueFilter(
"category", v.values(), v.includeMissing());
throw new IllegalArgumentException(
"Cannot migrate legacy group filter " + f.typeId());
})
.toList();
return new GridSetup(
old.formatVersion(), old.definitionId(), 2, columns, sorts, filters, old.page());
}
private static String rename(String id) {
return id.equals("group") ? "category" : id;
}
public void restore() {
grid.restoreSetup(
() -> {
try {
return codec.decode(Files.readString(setupFile));
} catch (java.io.IOException e) {
throw new IllegalArgumentException(
"Cannot read setup: " + e.getMessage(), e);
}
});
}
private void log(String text) {
Platform.runLater(
() -> {
if (!closed) {
if (diagnostics.getLength() > 16000) diagnostics.deleteText(0, 8000);
diagnostics.appendText(text + "\n");
}
});
}
public void install(Scene scene) {
themes.register(scene);
}
public void close() {
closed = true;
DemoResources.closeAll(grid, themes, clock::shutdown);
}
}
@@ -0,0 +1,10 @@
package de.neitzel.fx.example.grid;
/** Classpath launcher separate from Application for JavaFX startup. */
public final class ProductGridMain {
private ProductGridMain() {}
public static void main(String[] args) {
javafx.application.Application.launch(ProductGridApp.class, args);
}
}
@@ -0,0 +1,48 @@
package de.neitzel.fx.example.grid;
import de.neitzel.fx.view.ResultRow;
import javafx.fxml.*;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.util.Map;
/** A fresh FXML row bound once to an immutable Product. */
public final class ProductRow {
@FXML private Label id, name, category, quantity, price;
public static ResultRow create(Product p) {
try {
var loader = new FXMLLoader(ProductRow.class.getResource("ProductRow.fxml"));
HBox root = loader.load();
ProductRow c = loader.getController();
c.id.setText(Long.toString(p.id()));
c.name.setText(show(p.name()));
c.category.setText(show(p.category()));
c.quantity.setText(show(p.quantity()));
c.price.setText(show(p.price()));
return new ResultRow(
root,
Map.of(
"id",
c.id,
"name",
c.name,
"category",
c.category,
"quantity",
c.quantity,
"price",
c.price),
() -> {});
} catch (IOException e) {
throw new IllegalStateException("Cannot load product row", e);
}
}
private static String show(Object v) {
return v == null ? "(missing)" : v.toString();
}
}
@@ -0,0 +1,170 @@
package de.neitzel.fx.example.theme;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.fx.theme.*;
import de.neitzel.fx.view.*;
import de.neitzel.grid.*;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.css.PseudoClass;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import java.util.*;
/** Runnable state gallery; no stored preference, source credentials or application data. */
public final class ThemeGallery extends VBox implements AutoCloseable {
public final ThemeManager themes = new ThemeManager();
public final Button normal = new Button("Normal"),
hovered = new Button("Hovered"),
focused = new Button("Focused"),
disabled = new Button("Disabled");
public final TextField invalid = new TextField("invalid input"),
draft = new TextField("An unfinished edit survives theme changes");
public final Label error = new Label("! Invalid value — check the input"),
warning = new Label("! Warning — review this value");
public final TableView<String> standard = new TableView<>();
public final DataGrid<Integer, String> grid;
private final List<Stage> floating = new ArrayList<>();
public ThemeGallery() {
setSpacing(12);
setStyle("-fx-padding: 18;");
getStyleClass().add("theme-gallery");
var picker = new ComboBox<String>();
picker.getItems().setAll("light", "dark", "high-contrast");
picker.setValue("light");
picker.setOnAction(
e -> {
if (!picker.getValue().equals(themes.selectedThemeProperty().get().id()))
themes.select(picker.getValue());
});
themes.selectedThemeProperty().addListener((o, a, b) -> picker.setValue(b.id()));
var failure = new Label();
failure.setWrapText(true);
failure.getStyleClass().add("theme-error");
themes.failureProperty()
.addListener((o, a, b) -> failure.setText(b == null ? "" : b.message()));
Label title = new Label("Shared theme gallery");
title.setStyle("-fx-font-size: 20px; -fx-font-weight: bold;");
hovered.pseudoClassStateChanged(PseudoClass.getPseudoClass("hover"), true);
focused.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), true);
disabled.setDisable(true);
invalid.pseudoClassStateChanged(PseudoClass.getPseudoClass("invalid"), true);
invalid.setAccessibleText("Invalid value; check the input");
error.getStyleClass().add("theme-error");
warning.getStyleClass().add("theme-warning");
CheckBox checked = new CheckBox("Checked");
checked.setSelected(true);
RadioButton radio = new RadioButton("Selected radio");
radio.setSelected(true);
DatePicker date = new DatePicker();
date.setPromptText("Nested date chooser");
ComboBox<String> combo = new ComboBox<>();
combo.getItems().addAll("Choose a value", "Alpha", "Beta");
combo.getSelectionModel().selectFirst();
TableColumn<String, String> state =
new TableColumn<>("Record indicator (text survives selection)");
state.setCellValueFactory(c -> new ReadOnlyStringWrapper(c.getValue()));
state.setPrefWidth(380);
standard.getColumns().add(state);
standard.getItems()
.setAll(
"FILE — from saved input",
"LIVE — observed record",
"REMOVE — pending removal");
standard.getSelectionModel().select(2);
standard.setPrefHeight(135);
var source =
new MemoryGridSource<Integer, String>(
() -> List.of("Alpha", "Beta", "Gamma"),
value -> List.of("Alpha", "Beta", "Gamma").indexOf(value),
Integer::compare,
List.of(
new MemoryColumn<>(
"name", MemoryColumn.Kind.TEXT, FilterValue.Text::new)),
Runnable::run,
100);
grid =
new DataGrid<>(
List.of(new ResultColumn("name", "Name", 430, 160, 600, -1)),
value -> {
Label label = new Label(value);
label.setPadding(new javafx.geometry.Insets(6));
return new ResultRow(new HBox(label), Map.of("name", label), () -> {});
},
source);
grid.configureFilter(
"name",
FilterColumn.text()
.withChecklist(
FilterColumn.Checklist.SOURCE_WIDE,
source.candidateProvider(
value -> ((FilterValue.Text) value).value())));
grid.setFilters(List.of(new TextFilter("name", TextFilter.Operator.CONTAINS, "a", false)));
grid.select(0);
grid.setPrefHeight(210);
Button dialog = new Button("Open dialog"),
floatWindow = new Button("Open floating window"),
loading = new Button("Toggle loading sample");
dialog.setOnAction(
e -> {
Alert alert =
new Alert(
Alert.AlertType.INFORMATION,
"Dialogs inherit the selected theme, including newly opened"
+ " windows.",
ButtonType.OK);
alert.initOwner(getScene().getWindow());
alert.show();
});
floatWindow.setOnAction(
e -> {
Stage stage = new Stage();
stage.initOwner(getScene().getWindow());
stage.setTitle("Themed floating window");
var field =
new TextArea("Edit this text, then change the theme in the gallery.");
stage.setScene(
new Scene(new VBox(12, new Label("Floating editor"), field), 420, 200));
floating.add(stage);
stage.show();
});
Label loadingStatus = new Label("Loading… retained rows are unavailable");
loadingStatus.getStyleClass().add("data-grid-status");
HBox loadingState = new HBox(10, new ProgressIndicator(), loadingStatus);
loadingState.getStyleClass().add("data-grid");
loadingState.pseudoClassStateChanged(PseudoClass.getPseudoClass("loading"), true);
((ProgressIndicator) loadingState.getChildren().getFirst()).setPrefSize(22, 22);
loading.setOnAction(e -> loadingState.setVisible(!loadingState.isVisible()));
getChildren()
.addAll(
new HBox(16, title, picker),
new Label(
"Explicit state specimens: hover / focus are CSS states, not a"
+ " native input test."),
new HBox(10, normal, hovered, focused, disabled),
draft,
new HBox(10, checked, radio, combo, date),
invalid,
error,
warning,
standard,
grid,
loadingState,
new HBox(10, dialog, floatWindow, loading),
failure);
}
public void install(Scene scene) {
themes.register(scene);
}
public void close() {
grid.close();
for (var stage : floating) stage.close();
themes.close();
}
}
@@ -0,0 +1,22 @@
package de.neitzel.fx.example.theme;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public final class ThemeGalleryApp extends Application {
private ThemeGallery gallery;
public void start(Stage stage) {
gallery = new ThemeGallery();
Scene scene = new Scene(gallery, 920, 900);
gallery.install(scene);
stage.setTitle("NeitzelLib theme gallery");
stage.setScene(scene);
stage.show();
}
public void stop() {
if (gallery != null) gallery.close();
}
}
@@ -0,0 +1,9 @@
package de.neitzel.fx.example.theme;
public final class ThemeGalleryMain {
private ThemeGalleryMain() {}
public static void main(String[] args) {
javafx.application.Application.launch(ThemeGalleryApp.class, args);
}
}
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.control.StatusBar?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ProgressBar?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.ToolBar?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1">
<top>
<ToolBar>
<items>
<Button fx:id="clear" text="Clear"/>
<Button fx:id="append" text="Append"/>
</items>
</ToolBar>
</top>
<center>
<TextArea fx:id="editor" promptText="Type here, or append sample text."/>
</center>
<bottom>
<StatusBar>
<leftItems><Label fx:id="status"/></leftItems>
<rightItems>
<Label fx:id="cursor"/>
<ProgressBar fx:id="progress" progress="0" prefWidth="120"/>
</rightItems>
</StatusBar>
</bottom>
</BorderPane>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.DockPane?>
<?import de.neitzel.fx.docking.DockLayout?>
<?import de.neitzel.fx.docking.DockGroupDefinition?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center><DockGroupDefinition destinationId="editors"/></center>
<right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true" preferredWidth="200" splitDirections="VERTICAL"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></right>
</DockLayout>
</initialLayout>
</DockPane>
@@ -0,0 +1,14 @@
.dock-pane {
-fx-base: #dce8f1;
-fx-accent: #156b83;
-fx-focus-color: #0c617b;
}
.dock-tab-header { -fx-background-color: #dce8f1; }
.dock-tab-header:selected { -fx-background-color: #faf3dc; }
.dock-tab-header:focused .focus-indicator { -fx-border-color: #0c617b; }
.dock-divider, .dock-area-divider { -fx-background-color: #53869b; }
.dock-edge-area { -fx-background-color: #b9d2dc; }
.dock-drop-indicator { -fx-fill: rgba(15, 120, 130, 0.25); -fx-stroke: #0f7882; }
.dock-drop-indicator:no-change { -fx-fill: rgba(130, 100, 20, 0.2); -fx-stroke: #826414; }
.dock-floating-preview-frame { -fx-fill: rgba(15, 120, 130, 0.25); -fx-stroke: #0f7882; }
.dock-floating-preview-label { -fx-background-color: #faf3dc; -fx-text-fill: #173b4a; }
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.DockPane?>
<?import de.neitzel.fx.docking.DockLayout?>
<?import de.neitzel.fx.docking.DockGroupDefinition?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center><DockGroupDefinition destinationId="editors" collapsible="false"
releaseSpaceWhenEmpty="false"/></center>
<left><DockGroupDefinition destinationId="project" tabSide="LEFT"
mode="OVERLAY" collapsible="true" preferredWidth="240" minimumWidth="120"/></left>
<right><DockGroupDefinition destinationId="changes" tabSide="RIGHT"
mode="OVERLAY" collapsible="true" preferredWidth="260" minimumWidth="120"/></right>
</DockLayout>
</initialLayout>
</DockPane>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.DockPane?>
<?import de.neitzel.fx.docking.DockLayout?>
<?import de.neitzel.fx.docking.DockGroupDefinition?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center><DockGroupDefinition destinationId="editors"/></center>
<left><DockGroupDefinition destinationId="tools" tabSide="LEFT" collapsible="true" preferredWidth="220"/></left>
</DockLayout>
</initialLayout>
</DockPane>
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.DockPane?>
<?import de.neitzel.fx.docking.DockLayout?>
<?import de.neitzel.fx.docking.DockGroupDefinition?>
<?import de.neitzel.fx.docking.DockSplitDefinition?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center>
<DockSplitDefinition destinationId="editors" orientation="HORIZONTAL" position="0.55">
<first><DockGroupDefinition destinationId="primary"/></first>
<second>
<DockSplitDefinition destinationId="auxiliary" orientation="VERTICAL" position="0.6">
<first><DockGroupDefinition destinationId="secondary"/></first>
<second><DockGroupDefinition destinationId="preview"/></second>
</DockSplitDefinition>
</second>
</DockSplitDefinition>
</center>
<right>
<DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true"
mode="OVERLAY" preferredWidth="240" visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/>
</right>
</DockLayout>
</initialLayout>
</DockPane>
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.DockPane?>
<?import de.neitzel.fx.docking.DockLayout?>
<?import de.neitzel.fx.docking.DockGroupDefinition?>
<?import de.neitzel.fx.docking.DockSplitDefinition?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center>
<DockSplitDefinition destinationId="editors" orientation="HORIZONTAL">
<first><DockGroupDefinition destinationId="primary"/></first>
<second>
<DockSplitDefinition destinationId="secondary" orientation="VERTICAL">
<first><DockGroupDefinition destinationId="preview"/></first>
<second><DockGroupDefinition destinationId="output"/></second>
</DockSplitDefinition>
</second>
</DockSplitDefinition>
</center>
<right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true" preferredWidth="200" splitDirections="VERTICAL"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></right>
</DockLayout>
</initialLayout>
</DockPane>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<?neitzel-model de.neitzel.fx.example.model.Note?>
<?import de.neitzel.fx.control.StatusBar?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.ToolBar?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList><DirectBinding control="text" property="text" path="text" direction="both"/></BindingList>
</fx:define>
<top><ToolBar fx:id="localTools"><items><Button fx:id="clear" text="Clear note"/></items></ToolBar></top>
<center><TextArea fx:id="text" wrapText="true"/></center>
<bottom><StatusBar fx:id="localStatus">
<leftItems><Label fx:id="localMessage"/></leftItems>
<rightItems><Label text="This bar travels with Notes"/></rightItems>
</StatusBar></bottom>
</BorderPane>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.*?>
<DockPane id="workspaceDock" xmlns:fx="http://javafx.com/fxml/1">
<initialLayout><DockLayout>
<center><DockGroupDefinition destinationId="editors"/></center>
<left><DockGroupDefinition destinationId="project" tabSide="LEFT" collapsible="true"
preferredWidth="240" visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></left>
<right><DockGroupDefinition destinationId="changes" tabSide="RIGHT" collapsible="true" mode="OVERLAY"
preferredWidth="220" visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></right>
<bottom><DockGroupDefinition destinationId="bottom" collapsible="true" preferredHeight="160"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></bottom>
</DockLayout></initialLayout>
</DockPane>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?><?import javafx.scene.control.Label?><?import javafx.scene.control.TextField?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.example.grid.PricePresetEditor" spacing="8" styleClass="filter-editor">
<Label text="Budget price (custom FXML editor)"/><Label text="Include prices up to this exact amount:"/><TextField fx:id="maximum" text="10.00"/>
</VBox>

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