Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a14d1d7e48 | ||
|
|
257e0edb28 | ||
|
|
91d9cdccaa | ||
|
|
7f2a62777d |
@@ -87,7 +87,8 @@ Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven
|
|||||||
|
|
||||||
## Use a release from Maven
|
## Use a release from Maven
|
||||||
|
|
||||||
Add the Gitea registry to the consuming project's POM and use the release
|
The main branch builds `1.0.1`. For the published `1.0.1` release,
|
||||||
|
add the Gitea registry to the consuming project's POM and use the release
|
||||||
version for the module you need:
|
version for the module you need:
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
@@ -102,7 +103,7 @@ version for the module you need:
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
```
|
```
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>core</artifactId>
|
<artifactId>core</artifactId>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<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</version></parent>
|
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.1</version></parent>
|
||||||
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
|
<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>
|
<dependencies><dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
||||||
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
|
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
|
||||||
|
|||||||
@@ -37,3 +37,16 @@ Collection changes do not automatically trigger requests in this slice. Call ref
|
|||||||
## Saved setups
|
## 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).
|
`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).
|
||||||
|
|
||||||
|
## Page-local grouping and application configuration
|
||||||
|
|
||||||
|
`GroupColumn`, `GroupProjection`, `GroupPath` and `GroupExpansion` capture typed
|
||||||
|
values and project a returned page without fetching or mutating source order.
|
||||||
|
GroupingSetup extends GridSetup v2 with ordered columns and explicit path choices;
|
||||||
|
old constructors/version-one documents remain supported. Group expansion retains
|
||||||
|
current choices plus a configurable inactive LRU history, never historical rows.
|
||||||
|
|
||||||
|
`GridApplicationConfiguration` owns debounced immutable setup snapshots and queued
|
||||||
|
saves after views detach. `GridSetupStore` requires revision-aware conditional
|
||||||
|
writes. The default optional JSON/file implementation is in Gson; no toolkit or
|
||||||
|
JSON dependency is introduced here. See the [integration guide](../fx/docs/data-grid-layout.md).
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0</version></parent>
|
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.1</version></parent>
|
||||||
<artifactId>data-grid</artifactId>
|
<artifactId>data-grid</artifactId>
|
||||||
<description>Toolkit-independent filter, query and grid setup contracts</description>
|
<description>Toolkit-independent filter, query and grid setup contracts</description>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -0,0 +1,378 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Application-owned, toolkit-independent save coordination. Accept immutable snapshots on the owner
|
||||||
|
* thread; this service serializes blocking store work on its scheduled worker. No I/O runs in
|
||||||
|
* construction. A detached view does not own or discard already accepted saves.
|
||||||
|
*/
|
||||||
|
public final class GridApplicationConfiguration {
|
||||||
|
public enum Phase {
|
||||||
|
IDLE,
|
||||||
|
LOADING,
|
||||||
|
PENDING,
|
||||||
|
SAVING,
|
||||||
|
SAVED,
|
||||||
|
ERROR,
|
||||||
|
CONFLICT,
|
||||||
|
CLOSED
|
||||||
|
}
|
||||||
|
|
||||||
|
public record State(Phase phase, long generation, boolean dirty, Throwable error) {}
|
||||||
|
|
||||||
|
public record Loaded(
|
||||||
|
GridSetupStore.Key key, GridSetupStore.Stored stored, long storageVersion) {}
|
||||||
|
|
||||||
|
private record Pending(long generation, GridSetup setup, boolean overwrite) {}
|
||||||
|
|
||||||
|
private static final class Slot {
|
||||||
|
final java.util.concurrent.locks.ReentrantLock io =
|
||||||
|
new java.util.concurrent.locks.ReentrantLock();
|
||||||
|
String revision;
|
||||||
|
long generation, storageVersion;
|
||||||
|
Pending pending;
|
||||||
|
ScheduledFuture<?> delay;
|
||||||
|
State state = new State(Phase.IDLE, 0, false, null);
|
||||||
|
final List<Consumer<State>> listeners = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
@lombok.Getter
|
||||||
|
@lombok.experimental.Accessors(fluent = true)
|
||||||
|
private final String applicationName;
|
||||||
|
|
||||||
|
private final GridSetupStore store;
|
||||||
|
private final ScheduledExecutorService worker;
|
||||||
|
private final boolean ownsWorker;
|
||||||
|
private final long debounceMillis;
|
||||||
|
private final Map<GridSetupStore.Key, Slot> slots = new LinkedHashMap<>();
|
||||||
|
private boolean closing, closed;
|
||||||
|
|
||||||
|
public GridApplicationConfiguration(String applicationName, GridSetupStore store) {
|
||||||
|
this(
|
||||||
|
applicationName,
|
||||||
|
store,
|
||||||
|
Duration.ofMillis(500),
|
||||||
|
Executors.newSingleThreadScheduledExecutor(r -> {
|
||||||
|
Thread thread = new Thread(r, "grid-setup-storage");
|
||||||
|
thread.setDaemon(true);
|
||||||
|
return thread;
|
||||||
|
}),
|
||||||
|
true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridApplicationConfiguration(
|
||||||
|
String applicationName,
|
||||||
|
GridSetupStore store,
|
||||||
|
Duration debounce,
|
||||||
|
ScheduledExecutorService worker,
|
||||||
|
boolean ownsWorker) {
|
||||||
|
if (applicationName == null
|
||||||
|
|| applicationName.isBlank()
|
||||||
|
|| applicationName.equals(".")
|
||||||
|
|| applicationName.equals("..")
|
||||||
|
|| applicationName.contains("/")
|
||||||
|
|| applicationName.contains("\\")
|
||||||
|
|| applicationName.indexOf(0) >= 0)
|
||||||
|
throw new IllegalArgumentException("Application name must be a directory name");
|
||||||
|
this.applicationName = applicationName;
|
||||||
|
this.store = Objects.requireNonNull(store);
|
||||||
|
debounceMillis = Objects.requireNonNull(debounce).toMillis();
|
||||||
|
if (debounceMillis < 0) throw new IllegalArgumentException("Negative debounce");
|
||||||
|
this.worker = Objects.requireNonNull(worker);
|
||||||
|
this.ownsWorker = ownsWorker;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Slot slot(GridSetupStore.Key key) {
|
||||||
|
return slots.computeIfAbsent(key, k -> new Slot());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireOpen() {
|
||||||
|
if (closed || closing) throw new IllegalStateException("Configuration is closing/closed");
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized State state(GridSetupStore.Key key) {
|
||||||
|
return slot(key).state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Listener callbacks may run on the storage thread; an FX adapter must dispatch them. */
|
||||||
|
public synchronized AutoCloseable observe(GridSetupStore.Key key, Consumer<State> listener) {
|
||||||
|
requireOpen();
|
||||||
|
var s = slot(key);
|
||||||
|
s.listeners.add(listener);
|
||||||
|
listener.accept(s.state);
|
||||||
|
return () -> {
|
||||||
|
synchronized (this) {
|
||||||
|
s.listeners.remove(listener);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private void emit(Slot slot, Phase phase, Throwable error) {
|
||||||
|
slot.state = new State(phase, slot.generation, slot.pending != null, error);
|
||||||
|
for (var listener : List.copyOf(slot.listeners)) listener.accept(slot.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Loaded> loadAsync(GridSetupStore.Key key) {
|
||||||
|
synchronized (this) {
|
||||||
|
requireOpen();
|
||||||
|
emit(slot(key), Phase.LOADING, null);
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
Slot target;
|
||||||
|
synchronized (this) {
|
||||||
|
target = slot(key);
|
||||||
|
}
|
||||||
|
target.io.lock();
|
||||||
|
try {
|
||||||
|
GridSetupStore.Stored loaded = store.load(key);
|
||||||
|
synchronized (this) {
|
||||||
|
return new Loaded(key, loaded, target.storageVersion);
|
||||||
|
}
|
||||||
|
} catch (Exception failure) {
|
||||||
|
synchronized (this) {
|
||||||
|
emit(target, Phase.ERROR, failure);
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
} finally {
|
||||||
|
target.io.unlock();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Called only after the grid has successfully validated/published this loaded setup. */
|
||||||
|
public synchronized void adopt(Loaded loaded, long discardedOwnGeneration) {
|
||||||
|
requireOpen();
|
||||||
|
Slot s = slot(loaded.key());
|
||||||
|
if (s.storageVersion == loaded.storageVersion()) s.revision = loaded.stored().revision();
|
||||||
|
if (s.pending != null && s.pending.generation() == discardedOwnGeneration) {
|
||||||
|
s.pending = null;
|
||||||
|
if (s.delay != null) s.delay.cancel(false);
|
||||||
|
}
|
||||||
|
emit(s, s.pending == null ? Phase.SAVED : Phase.PENDING, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized long accept(GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||||
|
return accept(key, setup, owner, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized long acceptOverwrite(
|
||||||
|
GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||||
|
return accept(key, setup, owner, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long accept(GridSetupStore.Key key, GridSetup setup, Object owner, boolean overwrite) {
|
||||||
|
requireOpen();
|
||||||
|
Slot s = slot(key);
|
||||||
|
// Owner is an attribution token, never retained: it may be a closed UI view.
|
||||||
|
Objects.requireNonNull(owner);
|
||||||
|
s.pending = new Pending(++s.generation, Objects.requireNonNull(setup), overwrite);
|
||||||
|
if (s.delay != null) s.delay.cancel(false);
|
||||||
|
emit(s, Phase.PENDING, null);
|
||||||
|
long acceptedGeneration = s.generation;
|
||||||
|
s.delay =
|
||||||
|
worker.schedule(
|
||||||
|
() -> {
|
||||||
|
try {
|
||||||
|
write(key, acceptedGeneration);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
/* retained and exposed through state */
|
||||||
|
}
|
||||||
|
},
|
||||||
|
debounceMillis,
|
||||||
|
TimeUnit.MILLISECONDS);
|
||||||
|
return s.generation;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicit user recovery: still performs a conditional write against a fresh revision. */
|
||||||
|
public CompletionStage<Void> overwriteAsync(
|
||||||
|
GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||||
|
synchronized (this) {
|
||||||
|
accept(key, setup, owner, true);
|
||||||
|
}
|
||||||
|
return retryAsync(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> retryAsync(GridSetupStore.Key key) {
|
||||||
|
synchronized (this) {
|
||||||
|
requireOpen();
|
||||||
|
Slot s = slot(key);
|
||||||
|
if (s.delay != null) s.delay.cancel(false);
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
write(key);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void write(GridSetupStore.Key key) throws Exception {
|
||||||
|
write(key, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void write(GridSetupStore.Key key, long scheduledGeneration) throws Exception {
|
||||||
|
Slot target;
|
||||||
|
synchronized (this) {
|
||||||
|
target = slot(key);
|
||||||
|
}
|
||||||
|
target.io.lock();
|
||||||
|
try {
|
||||||
|
writeLocked(key, scheduledGeneration);
|
||||||
|
} finally {
|
||||||
|
target.io.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeLocked(GridSetupStore.Key key, long scheduledGeneration) throws Exception {
|
||||||
|
Pending pending;
|
||||||
|
String expected;
|
||||||
|
synchronized (this) {
|
||||||
|
Slot s = slot(key);
|
||||||
|
pending = s.pending;
|
||||||
|
if (pending == null
|
||||||
|
|| closed
|
||||||
|
|| (scheduledGeneration >= 0 && pending.generation() != scheduledGeneration))
|
||||||
|
return;
|
||||||
|
expected = s.revision;
|
||||||
|
emit(s, Phase.SAVING, null);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (pending.overwrite()) expected = store.revision(key);
|
||||||
|
if (expected == null)
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"Load or explicitly reset the saved setup before writing");
|
||||||
|
String revision = store.save(key, expected, pending.setup());
|
||||||
|
synchronized (this) {
|
||||||
|
Slot s = slot(key);
|
||||||
|
s.revision = revision;
|
||||||
|
s.storageVersion++;
|
||||||
|
if (s.pending != null && s.pending.generation() == pending.generation())
|
||||||
|
s.pending = null;
|
||||||
|
emit(s, s.pending == null ? Phase.SAVED : Phase.PENDING, null);
|
||||||
|
}
|
||||||
|
} catch (Exception failure) {
|
||||||
|
synchronized (this) {
|
||||||
|
emit(
|
||||||
|
slot(key),
|
||||||
|
failure instanceof GridSetupStore.Conflict ? Phase.CONFLICT : Phase.ERROR,
|
||||||
|
failure);
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> flushAsync() {
|
||||||
|
synchronized (this) {
|
||||||
|
if (closed) return CompletableFuture.completedFuture(null);
|
||||||
|
cancelDelays();
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
flush();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cancelDelays() {
|
||||||
|
slots.values()
|
||||||
|
.forEach(s -> {
|
||||||
|
if (s.delay != null) s.delay.cancel(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void flush() throws Exception {
|
||||||
|
while (true) {
|
||||||
|
List<GridSetupStore.Key> pending;
|
||||||
|
synchronized (this) {
|
||||||
|
pending =
|
||||||
|
slots.entrySet().stream()
|
||||||
|
.filter(e -> e.getValue().pending != null)
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
if (pending.isEmpty()) return;
|
||||||
|
for (var key : pending) write(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> closeAsync() {
|
||||||
|
synchronized (this) {
|
||||||
|
if (closed) return CompletableFuture.completedFuture(null);
|
||||||
|
if (closing) throw new IllegalStateException("Close already pending");
|
||||||
|
closing = true;
|
||||||
|
cancelDelays();
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
try {
|
||||||
|
flush();
|
||||||
|
finishClose();
|
||||||
|
return null;
|
||||||
|
} catch (Exception failure) {
|
||||||
|
synchronized (this) {
|
||||||
|
closing = false;
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicit quit-without-saving path. It cannot undo a write already committed. */
|
||||||
|
public CompletionStage<Void> discardAndCloseAsync() {
|
||||||
|
synchronized (this) {
|
||||||
|
if (closed) return CompletableFuture.completedFuture(null);
|
||||||
|
closing = true;
|
||||||
|
cancelDelays();
|
||||||
|
slots.values().forEach(s -> s.pending = null);
|
||||||
|
}
|
||||||
|
return submit(() -> {
|
||||||
|
finishClose();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishClose() {
|
||||||
|
// A supplied scheduler may have multiple workers. Drain all in-flight slot I/O
|
||||||
|
// before publishing CLOSED, including an already-committing discarded write.
|
||||||
|
List<Slot> targets;
|
||||||
|
synchronized (this) {
|
||||||
|
targets = List.copyOf(slots.values());
|
||||||
|
}
|
||||||
|
targets.forEach(s -> s.io.lock());
|
||||||
|
try {
|
||||||
|
finishCloseLocked();
|
||||||
|
} finally {
|
||||||
|
for (int index = targets.size() - 1; index >= 0; index--)
|
||||||
|
targets.get(index).io.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishCloseLocked() {
|
||||||
|
synchronized (this) {
|
||||||
|
closed = true;
|
||||||
|
closing = false;
|
||||||
|
slots.values()
|
||||||
|
.forEach(s -> {
|
||||||
|
emit(s, Phase.CLOSED, null);
|
||||||
|
s.listeners.clear();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (ownsWorker) worker.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
private <V> CompletionStage<V> submit(Callable<V> action) {
|
||||||
|
CompletableFuture<V> future = new CompletableFuture<>();
|
||||||
|
try {
|
||||||
|
worker.execute(() -> {
|
||||||
|
try {
|
||||||
|
future.complete(action.call());
|
||||||
|
} catch (Exception failure) {
|
||||||
|
future.completeExceptionally(failure);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (RejectedExecutionException failure) {
|
||||||
|
future.completeExceptionally(failure);
|
||||||
|
}
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -57,7 +57,7 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
|||||||
Consumer<FilterCondition> validateFilter) {
|
Consumer<FilterCondition> validateFilter) {
|
||||||
Objects.requireNonNull(input);
|
Objects.requireNonNull(input);
|
||||||
Objects.requireNonNull(migrations);
|
Objects.requireNonNull(migrations);
|
||||||
if (input.formatVersion() != 1)
|
if (input.formatVersion() != 1 && input.formatVersion() != 2)
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"Unsupported setup format version: " + input.formatVersion());
|
"Unsupported setup format version: " + input.formatVersion());
|
||||||
if (!id.equals(input.definitionId()))
|
if (!id.equals(input.definitionId()))
|
||||||
@@ -75,7 +75,7 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
|||||||
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
|
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
|
||||||
if (!id.equals(setup.definitionId())
|
if (!id.equals(setup.definitionId())
|
||||||
|| setup.definitionVersion() != old + 1
|
|| setup.definitionVersion() != old + 1
|
||||||
|| setup.formatVersion() != 1)
|
|| setup.formatVersion() != input.formatVersion())
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"Migration must preserve identity/format and advance one definition"
|
"Migration must preserve identity/format and advance one definition"
|
||||||
+ " version");
|
+ " version");
|
||||||
@@ -123,7 +123,15 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
|||||||
source.validate(setup.page());
|
source.validate(setup.page());
|
||||||
setup.filters().forEach(validateFilter);
|
setup.filters().forEach(validateFilter);
|
||||||
return new Prepared(
|
return new Prepared(
|
||||||
new GridSetup(1, id, version, next, setup.sort(), setup.filters(), setup.page()),
|
new GridSetup(
|
||||||
|
setup.formatVersion(),
|
||||||
|
id,
|
||||||
|
version,
|
||||||
|
next,
|
||||||
|
setup.sort(),
|
||||||
|
setup.filters(),
|
||||||
|
setup.page(),
|
||||||
|
setup.grouping()),
|
||||||
adjustments);
|
adjustments);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,16 @@ import java.util.*;
|
|||||||
|
|
||||||
/** Plain versioned setup. No selection, credentials, page index, drafts, or approval tokens. */
|
/** Plain versioned setup. No selection, credentials, page index, drafts, or approval tokens. */
|
||||||
public record GridSetup(
|
public record GridSetup(
|
||||||
|
int formatVersion,
|
||||||
|
String definitionId,
|
||||||
|
int definitionVersion,
|
||||||
|
List<ColumnState> columns,
|
||||||
|
List<SortKey> sort,
|
||||||
|
List<FilterCondition> filters,
|
||||||
|
PageRequest page,
|
||||||
|
GroupingSetup grouping) {
|
||||||
|
/** Source/binary-compatible constructor for version-one clients. */
|
||||||
|
public GridSetup(
|
||||||
int formatVersion,
|
int formatVersion,
|
||||||
String definitionId,
|
String definitionId,
|
||||||
int definitionVersion,
|
int definitionVersion,
|
||||||
@@ -11,6 +21,9 @@ public record GridSetup(
|
|||||||
List<SortKey> sort,
|
List<SortKey> sort,
|
||||||
List<FilterCondition> filters,
|
List<FilterCondition> filters,
|
||||||
PageRequest page) {
|
PageRequest page) {
|
||||||
|
this(formatVersion, definitionId, definitionVersion, columns, sort, filters, page, null);
|
||||||
|
}
|
||||||
|
|
||||||
public record ColumnState(String id, String type, ColumnWidth width) {
|
public record ColumnState(String id, String type, ColumnWidth width) {
|
||||||
/** Older callers must supply a definition type before persistence/restoration. */
|
/** Older callers must supply a definition type before persistence/restoration. */
|
||||||
public ColumnState(String id, ColumnWidth width) {
|
public ColumnState(String id, ColumnWidth width) {
|
||||||
@@ -43,6 +56,17 @@ public record GridSetup(
|
|||||||
for (var f : filters)
|
for (var f : filters)
|
||||||
if (!ids.contains(f.columnId()))
|
if (!ids.contains(f.columnId()))
|
||||||
throw new IllegalArgumentException("Unknown filter column");
|
throw new IllegalArgumentException("Unknown filter column");
|
||||||
|
if (formatVersion == 2 && grouping == null)
|
||||||
|
throw new IllegalArgumentException("Version two requires grouping preferences");
|
||||||
|
if (grouping != null) {
|
||||||
|
for (String id : grouping.columns())
|
||||||
|
if (!ids.contains(id))
|
||||||
|
throw new IllegalArgumentException("Unknown grouping column");
|
||||||
|
for (var choice : grouping.choices())
|
||||||
|
for (var segment : choice.path().segments())
|
||||||
|
if (!ids.contains(segment.columnId()))
|
||||||
|
throw new IllegalArgumentException("Unknown group path column");
|
||||||
|
}
|
||||||
new GridQuery(filters, sort, page);
|
new GridQuery(filters, sort, page);
|
||||||
if (page instanceof PageRequest.Paged p && p.pageIndex() != 0)
|
if (page instanceof PageRequest.Paged p && p.pageIndex() != 0)
|
||||||
throw new IllegalArgumentException("Setups must start on the first page");
|
throw new IllegalArgumentException("Setups must start on the first page");
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/** Blocking store port. The configuration service calls it off the UI thread. */
|
||||||
|
public interface GridSetupStore {
|
||||||
|
record Key(String gridId, String context) {
|
||||||
|
public Key {
|
||||||
|
Checks.id(gridId);
|
||||||
|
if (context != null) Checks.id(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
record Stored(GridSetup setup, String revision) {
|
||||||
|
public Stored {
|
||||||
|
Objects.requireNonNull(revision);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Stored load(Key key) throws IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Revision alone must remain readable even when setup decoding fails, for explicit recovery.
|
||||||
|
*/
|
||||||
|
String revision(Key key) throws IOException;
|
||||||
|
|
||||||
|
/** Atomically compare revision and replace the entire setup; never a blind overwrite. */
|
||||||
|
String save(Key key, String expectedRevision, GridSetup setup) throws IOException;
|
||||||
|
|
||||||
|
final class Conflict extends IOException {
|
||||||
|
public Conflict() {
|
||||||
|
super(
|
||||||
|
"Saved grid setup changed in another application instance. Reload or explicitly"
|
||||||
|
+ " overwrite.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
/** Explicit owner-thread mapping. Labels never determine identity or ordering. */
|
||||||
|
public record GroupColumn<T>(
|
||||||
|
String id,
|
||||||
|
MemoryColumn.Kind kind,
|
||||||
|
Function<T, FilterValue> read,
|
||||||
|
Function<FilterValue, String> label) {
|
||||||
|
public GroupColumn {
|
||||||
|
Checks.id(id);
|
||||||
|
Objects.requireNonNull(kind);
|
||||||
|
Objects.requireNonNull(read);
|
||||||
|
Objects.requireNonNull(label);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> GroupColumn<T> text(String id, Function<T, String> reader) {
|
||||||
|
return new GroupColumn<>(
|
||||||
|
id,
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
row -> {
|
||||||
|
String value = reader.apply(row);
|
||||||
|
return value == null ? null : new FilterValue.Text(value);
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> GroupColumn<T> integer(String id, Function<T, Long> reader) {
|
||||||
|
return new GroupColumn<>(
|
||||||
|
id,
|
||||||
|
MemoryColumn.Kind.INTEGER,
|
||||||
|
row -> {
|
||||||
|
Long value = reader.apply(row);
|
||||||
|
return value == null ? null : new FilterValue.IntegerValue(value);
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> GroupColumn<T> decimal(String id, Function<T, java.math.BigDecimal> reader) {
|
||||||
|
return new GroupColumn<>(
|
||||||
|
id,
|
||||||
|
MemoryColumn.Kind.DECIMAL,
|
||||||
|
row -> {
|
||||||
|
var value = reader.apply(row);
|
||||||
|
return value == null ? null : new FilterValue.Decimal(value);
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> GroupColumn<T> bool(String id, Function<T, Boolean> reader) {
|
||||||
|
return new GroupColumn<>(
|
||||||
|
id,
|
||||||
|
MemoryColumn.Kind.BOOLEAN,
|
||||||
|
row -> {
|
||||||
|
Boolean value = reader.apply(row);
|
||||||
|
return value == null ? null : new FilterValue.BooleanValue(value);
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
}
|
||||||
|
|
||||||
|
public 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("Grouping value type changed: " + id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String display(FilterValue value) {
|
||||||
|
return switch (value) {
|
||||||
|
case null -> "(Missing)";
|
||||||
|
case FilterValue.Text t -> t.value().isEmpty() ? "(Empty)" : t.value();
|
||||||
|
case FilterValue.IntegerValue i -> Long.toString(i.value());
|
||||||
|
case FilterValue.Decimal d -> d.value().toPlainString();
|
||||||
|
case FilterValue.BooleanValue b -> Boolean.toString(b.value());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int compare(FilterValue a, FilterValue b) {
|
||||||
|
if (a == null) return b == null ? 0 : 1;
|
||||||
|
if (b == null) return -1;
|
||||||
|
return switch (a) {
|
||||||
|
case FilterValue.Text t -> {
|
||||||
|
String right = ((FilterValue.Text) b).value();
|
||||||
|
int order =
|
||||||
|
t.value()
|
||||||
|
.toLowerCase(Locale.ROOT)
|
||||||
|
.compareTo(right.toLowerCase(Locale.ROOT));
|
||||||
|
yield order == 0 ? t.value().compareTo(right) : order;
|
||||||
|
}
|
||||||
|
case FilterValue.IntegerValue i ->
|
||||||
|
Long.compare(i.value(), ((FilterValue.IntegerValue) b).value());
|
||||||
|
case FilterValue.Decimal d -> d.value().compareTo(((FilterValue.Decimal) b).value());
|
||||||
|
case FilterValue.BooleanValue v ->
|
||||||
|
Boolean.compare(v.value(), ((FilterValue.BooleanValue) b).value());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Owner-thread expansion history retaining scalar paths, never rows/models. */
|
||||||
|
public final class GroupExpansion {
|
||||||
|
private final LinkedHashMap<GroupPath, Boolean> choices = new LinkedHashMap<>();
|
||||||
|
private Set<GroupPath> current = Set.of();
|
||||||
|
private boolean defaultCollapsed;
|
||||||
|
private int inactiveLimit;
|
||||||
|
|
||||||
|
public GroupExpansion(boolean defaultCollapsed, int inactiveLimit) {
|
||||||
|
configure(defaultCollapsed, inactiveLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void configure(boolean collapsed, int limit) {
|
||||||
|
if (limit < 0) throw new IllegalArgumentException("Negative expansion history capacity");
|
||||||
|
defaultCollapsed = collapsed;
|
||||||
|
inactiveLimit = limit;
|
||||||
|
trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean expanded(GroupPath path) {
|
||||||
|
return choices.getOrDefault(path, !defaultCollapsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void set(GroupPath path, boolean expanded) {
|
||||||
|
choices.remove(path);
|
||||||
|
choices.put(path, expanded);
|
||||||
|
trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void current(Collection<GroupPath> paths) {
|
||||||
|
current = Set.copyOf(paths);
|
||||||
|
for (var path : paths)
|
||||||
|
if (choices.containsKey(path)) {
|
||||||
|
boolean choice = choices.remove(path);
|
||||||
|
choices.put(path, choice);
|
||||||
|
}
|
||||||
|
trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<GroupingSetup.Choice> snapshot() {
|
||||||
|
return choices.entrySet().stream()
|
||||||
|
.map(e -> new GroupingSetup.Choice(e.getKey(), e.getValue()))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void restore(List<GroupingSetup.Choice> saved) {
|
||||||
|
choices.clear();
|
||||||
|
saved.forEach(c -> choices.put(c.path(), c.expanded()));
|
||||||
|
trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reset() {
|
||||||
|
choices.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void trim() {
|
||||||
|
int inactive = (int) choices.keySet().stream().filter(p -> !current.contains(p)).count();
|
||||||
|
for (var iterator = choices.keySet().iterator();
|
||||||
|
inactive > inactiveLimit && iterator.hasNext(); ) {
|
||||||
|
if (!current.contains(iterator.next())) {
|
||||||
|
iterator.remove();
|
||||||
|
inactive--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Stable typed identity, independent of labels, page position and row identity. */
|
||||||
|
public record GroupPath(List<Segment> segments) {
|
||||||
|
public record Segment(String columnId, FilterValue value) {
|
||||||
|
public Segment {
|
||||||
|
Checks.id(columnId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupPath {
|
||||||
|
segments = List.copyOf(segments);
|
||||||
|
if (segments.isEmpty()) throw new IllegalArgumentException("Empty group path");
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (var segment : segments)
|
||||||
|
if (!seen.add(segment.columnId()))
|
||||||
|
throw new IllegalArgumentException("Repeated group column");
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupPath child(String column, FilterValue value) {
|
||||||
|
var next = new ArrayList<>(segments);
|
||||||
|
next.add(new Segment(column, value));
|
||||||
|
return new GroupPath(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Pure current-page projection. Capture all eligible scalar values before publishing a page. */
|
||||||
|
public final class GroupProjection {
|
||||||
|
private GroupProjection() {}
|
||||||
|
|
||||||
|
public record Value(FilterValue key, String label) {
|
||||||
|
public Value {
|
||||||
|
Objects.requireNonNull(label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Captured<K, T>(GridRow<K, T> row, Map<String, Value> values) {
|
||||||
|
public Captured {
|
||||||
|
Objects.requireNonNull(row);
|
||||||
|
values = Map.copyOf(values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Snapshot<K, T>(List<Captured<K, T>> rows, Map<String, GroupColumn<T>> columns) {
|
||||||
|
public Snapshot {
|
||||||
|
rows = List.copyOf(rows);
|
||||||
|
columns = Map.copyOf(columns);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Node<K, T>(
|
||||||
|
GroupPath path, String label, List<Node<K, T>> children, List<GridRow<K, T>> rows) {
|
||||||
|
public Node {
|
||||||
|
children = List.copyOf(children);
|
||||||
|
rows = List.copyOf(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int count() {
|
||||||
|
return rows.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <K, T> Snapshot<K, T> capture(
|
||||||
|
List<GridRow<K, T>> rows, Collection<GroupColumn<T>> columns) {
|
||||||
|
Map<String, GroupColumn<T>> mappings = new LinkedHashMap<>();
|
||||||
|
for (var c : columns)
|
||||||
|
if (mappings.putIfAbsent(c.id(), c) != null)
|
||||||
|
throw new IllegalArgumentException("Duplicate group mapping");
|
||||||
|
List<Captured<K, T>> captured = new ArrayList<>();
|
||||||
|
for (var row : rows) {
|
||||||
|
Map<String, Value> values = new LinkedHashMap<>();
|
||||||
|
for (var c : columns) {
|
||||||
|
FilterValue key = c.read().apply(row.model());
|
||||||
|
c.validate(key);
|
||||||
|
values.put(c.id(), new Value(key, c.label().apply(key)));
|
||||||
|
}
|
||||||
|
captured.add(new Captured<>(row, values));
|
||||||
|
}
|
||||||
|
return new Snapshot<>(captured, mappings);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <K, T> List<Node<K, T>> project(Snapshot<K, T> snapshot, List<String> order) {
|
||||||
|
if (new HashSet<>(order).size() != order.size()
|
||||||
|
|| !snapshot.columns().keySet().containsAll(order))
|
||||||
|
throw new IllegalArgumentException("Unknown/repeated grouping column");
|
||||||
|
return build(snapshot.rows(), order, 0, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <K, T> List<Node<K, T>> build(
|
||||||
|
List<Captured<K, T>> rows, List<String> order, int depth, GroupPath parent) {
|
||||||
|
if (depth == order.size()) return List.of();
|
||||||
|
String id = order.get(depth);
|
||||||
|
Map<FilterValue, List<Captured<K, T>>> buckets = new LinkedHashMap<>();
|
||||||
|
for (var row : rows)
|
||||||
|
buckets.computeIfAbsent(row.values().get(id).key(), ignored -> new ArrayList<>())
|
||||||
|
.add(row);
|
||||||
|
List<FilterValue> keys = new ArrayList<>(buckets.keySet());
|
||||||
|
keys.sort(GroupColumn::compare);
|
||||||
|
List<Node<K, T>> nodes = new ArrayList<>();
|
||||||
|
for (var key : keys) {
|
||||||
|
var bucket = buckets.get(key);
|
||||||
|
String label = bucket.getFirst().values().get(id).label();
|
||||||
|
if (bucket.stream().anyMatch(r -> !r.values().get(id).label().equals(label)))
|
||||||
|
throw new IllegalArgumentException("Inconsistent label for group value in " + id);
|
||||||
|
GroupPath path =
|
||||||
|
parent == null
|
||||||
|
? new GroupPath(List.of(new GroupPath.Segment(id, key)))
|
||||||
|
: parent.child(id, key);
|
||||||
|
nodes.add(
|
||||||
|
new Node<>(
|
||||||
|
path,
|
||||||
|
label,
|
||||||
|
build(bucket, order, depth + 1, path),
|
||||||
|
bucket.stream().map(Captured::row).toList()));
|
||||||
|
}
|
||||||
|
return List.copyOf(nodes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <K, T> List<GroupPath> paths(List<Node<K, T>> nodes) {
|
||||||
|
List<GroupPath> paths = new ArrayList<>();
|
||||||
|
for (var node : nodes) {
|
||||||
|
paths.add(node.path());
|
||||||
|
paths.addAll(paths(node.children()));
|
||||||
|
}
|
||||||
|
return paths;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Committed grouping preferences. Choices are ordered least-recently to most-recently used. */
|
||||||
|
public record GroupingSetup(List<String> columns, List<Choice> choices) {
|
||||||
|
public record Choice(GroupPath path, boolean expanded) {
|
||||||
|
public Choice {
|
||||||
|
Objects.requireNonNull(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupingSetup {
|
||||||
|
columns = List.copyOf(columns);
|
||||||
|
choices = List.copyOf(choices);
|
||||||
|
Set<String> ids = new HashSet<>();
|
||||||
|
for (String id : columns) {
|
||||||
|
Checks.id(id);
|
||||||
|
if (!ids.add(id)) throw new IllegalArgumentException("Repeated grouping column");
|
||||||
|
}
|
||||||
|
Set<GroupPath> paths = new HashSet<>();
|
||||||
|
for (var choice : choices)
|
||||||
|
if (!paths.add(choice.path()))
|
||||||
|
throw new IllegalArgumentException("Repeated expansion choice");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static GroupingSetup empty() {
|
||||||
|
return new GroupingSetup(List.of(), List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
package de.neitzel.grid;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
class GridConfigurationTest {
|
||||||
|
static GridSetup setup(double width) {
|
||||||
|
return new GridSetup(
|
||||||
|
2,
|
||||||
|
"records",
|
||||||
|
1,
|
||||||
|
List.of(new GridSetup.ColumnState("type", "text", new ColumnWidth.Explicit(width))),
|
||||||
|
List.of(),
|
||||||
|
List.of(),
|
||||||
|
new PageRequest.Paged(0, 50),
|
||||||
|
new GroupingSetup(List.of("type"), List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
static final GridSetupStore.Key KEY = new GridSetupStore.Key("records", null);
|
||||||
|
|
||||||
|
static final class MemoryStore implements GridSetupStore {
|
||||||
|
GridSetup value;
|
||||||
|
int revision, writes;
|
||||||
|
boolean fail;
|
||||||
|
|
||||||
|
public synchronized Stored load(Key key) {
|
||||||
|
return new Stored(value, Integer.toString(revision));
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized String revision(Key key) {
|
||||||
|
return Integer.toString(revision);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized String save(Key key, String expected, GridSetup setup)
|
||||||
|
throws IOException {
|
||||||
|
if (fail) throw new IOException("disk unavailable");
|
||||||
|
if (!expected.equals(Integer.toString(revision))) throw new Conflict();
|
||||||
|
value = setup;
|
||||||
|
writes++;
|
||||||
|
return Integer.toString(++revision);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static GridApplicationConfiguration config(MemoryStore store) {
|
||||||
|
return new GridApplicationConfiguration(
|
||||||
|
"Example",
|
||||||
|
store,
|
||||||
|
Duration.ofHours(1),
|
||||||
|
Executors.newSingleThreadScheduledExecutor(),
|
||||||
|
true);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void load(GridApplicationConfiguration config) throws Exception {
|
||||||
|
config.adopt(config.loadAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS), -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void coalescesWholeSnapshotsAndDoesNotSaveUnchangedLoadsOrClose() throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var config = config(store);
|
||||||
|
load(config);
|
||||||
|
assertEquals(0, store.writes);
|
||||||
|
config.accept(KEY, setup(100), new Object());
|
||||||
|
config.accept(KEY, setup(200), new Object());
|
||||||
|
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failedCloseRetainsLatestUnsavedStateAndCanRetry() throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var config = config(store);
|
||||||
|
load(config);
|
||||||
|
config.accept(KEY, setup(100), this);
|
||||||
|
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
store.fail = true;
|
||||||
|
config.accept(KEY, setup(200), this);
|
||||||
|
assertThrows(
|
||||||
|
ExecutionException.class,
|
||||||
|
() -> config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||||
|
assertEquals(setup(100), store.value);
|
||||||
|
assertTrue(config.state(KEY).dirty());
|
||||||
|
store.fail = false;
|
||||||
|
config.retryAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reloadCannotDiscardAnotherViewsNewerGeneration() throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var config = config(store);
|
||||||
|
load(config);
|
||||||
|
long old = config.accept(KEY, setup(100), this);
|
||||||
|
var read = config.loadAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
config.accept(KEY, setup(200), new Object());
|
||||||
|
config.adopt(read, old);
|
||||||
|
assertTrue(config.state(KEY).dirty());
|
||||||
|
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void crossInstanceConflictRequiresExplicitOverwriteAndDiscardCloseDoesNotWrite()
|
||||||
|
throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var first = config(store);
|
||||||
|
var second = config(store);
|
||||||
|
load(first);
|
||||||
|
load(second);
|
||||||
|
first.accept(KEY, setup(100), first);
|
||||||
|
first.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
second.accept(KEY, setup(200), second);
|
||||||
|
assertThrows(
|
||||||
|
ExecutionException.class,
|
||||||
|
() -> second.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||||
|
assertEquals(GridApplicationConfiguration.Phase.CONFLICT, second.state(KEY).phase());
|
||||||
|
second.overwriteAsync(KEY, setup(200), second)
|
||||||
|
.toCompletableFuture()
|
||||||
|
.get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
second.accept(KEY, setup(300), second);
|
||||||
|
second.discardAndCloseAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
first.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void debounceWaitsForQuietPeriodRatherThanSavingEveryChange() throws Exception {
|
||||||
|
var store = new MemoryStore();
|
||||||
|
var clock = new Clock();
|
||||||
|
var config =
|
||||||
|
new GridApplicationConfiguration(
|
||||||
|
"Example", store, Duration.ofMillis(500), clock, false);
|
||||||
|
load(config);
|
||||||
|
config.accept(KEY, setup(100), this);
|
||||||
|
clock.advance(499);
|
||||||
|
assertEquals(0, store.writes);
|
||||||
|
config.accept(KEY, setup(200), this);
|
||||||
|
clock.advance(1);
|
||||||
|
assertEquals(0, store.writes);
|
||||||
|
clock.advance(499);
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
assertEquals(setup(200), store.value);
|
||||||
|
config.closeAsync().toCompletableFuture().get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void discardCloseWaitsForAnAlreadyCommittingWriteOnAParallelScheduler() throws Exception {
|
||||||
|
var entered = new CountDownLatch(1);
|
||||||
|
var release = new CountDownLatch(1);
|
||||||
|
var closed = new CountDownLatch(1);
|
||||||
|
var backing = new MemoryStore();
|
||||||
|
GridSetupStore store =
|
||||||
|
new GridSetupStore() {
|
||||||
|
public Stored load(Key key) {
|
||||||
|
return backing.load(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String revision(Key key) {
|
||||||
|
return backing.revision(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String save(Key key, String revision, GridSetup setup)
|
||||||
|
throws IOException {
|
||||||
|
entered.countDown();
|
||||||
|
try {
|
||||||
|
if (!release.await(5, TimeUnit.SECONDS))
|
||||||
|
throw new IOException("Timed out");
|
||||||
|
} catch (InterruptedException failure) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new IOException(failure);
|
||||||
|
}
|
||||||
|
return backing.save(key, revision, setup);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var worker = Executors.newScheduledThreadPool(2);
|
||||||
|
var config =
|
||||||
|
new GridApplicationConfiguration(
|
||||||
|
"Example", store, Duration.ofHours(1), worker, true);
|
||||||
|
load(config);
|
||||||
|
config.observe(
|
||||||
|
KEY,
|
||||||
|
state -> {
|
||||||
|
if (state.phase() == GridApplicationConfiguration.Phase.CLOSED)
|
||||||
|
closed.countDown();
|
||||||
|
});
|
||||||
|
config.accept(KEY, setup(100), this);
|
||||||
|
var write = config.retryAsync(KEY);
|
||||||
|
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||||
|
var close = config.discardAndCloseAsync();
|
||||||
|
try {
|
||||||
|
assertFalse(closed.await(100, TimeUnit.MILLISECONDS));
|
||||||
|
} finally {
|
||||||
|
release.countDown();
|
||||||
|
}
|
||||||
|
close.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
write.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(GridApplicationConfiguration.Phase.CLOSED, config.state(KEY).phase());
|
||||||
|
assertFalse(config.state(KEY).dirty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deterministic scheduled worker: no wall-clock sleeps in debounce assertions. */
|
||||||
|
static final class Clock extends java.util.concurrent.AbstractExecutorService
|
||||||
|
implements java.util.concurrent.ScheduledExecutorService {
|
||||||
|
long now;
|
||||||
|
boolean shutdown;
|
||||||
|
final List<Job> jobs = new ArrayList<>();
|
||||||
|
|
||||||
|
static final class Job extends java.util.concurrent.FutureTask<Void>
|
||||||
|
implements java.util.concurrent.ScheduledFuture<Void> {
|
||||||
|
final long due;
|
||||||
|
|
||||||
|
Job(Runnable action, long due) {
|
||||||
|
super(action, null);
|
||||||
|
this.due = due;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getDelay(java.util.concurrent.TimeUnit unit) {
|
||||||
|
return unit.convert(due, java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int compareTo(java.util.concurrent.Delayed other) {
|
||||||
|
return Long.compare(due, ((Job) other).due);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void advance(long millis) {
|
||||||
|
now += millis;
|
||||||
|
var ready = jobs.stream().filter(job -> job.due <= now).toList();
|
||||||
|
jobs.removeAll(ready);
|
||||||
|
ready.forEach(Job::run);
|
||||||
|
}
|
||||||
|
|
||||||
|
public java.util.concurrent.ScheduledFuture<?> schedule(
|
||||||
|
Runnable action, long delay, java.util.concurrent.TimeUnit unit) {
|
||||||
|
var job = new Job(action, now + unit.toMillis(delay));
|
||||||
|
jobs.add(job);
|
||||||
|
return job;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <V> java.util.concurrent.ScheduledFuture<V> schedule(
|
||||||
|
java.util.concurrent.Callable<V> action,
|
||||||
|
long delay,
|
||||||
|
java.util.concurrent.TimeUnit unit) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public java.util.concurrent.ScheduledFuture<?> scheduleAtFixedRate(
|
||||||
|
Runnable r, long a, long b, java.util.concurrent.TimeUnit u) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public java.util.concurrent.ScheduledFuture<?> scheduleWithFixedDelay(
|
||||||
|
Runnable r, long a, long b, java.util.concurrent.TimeUnit u) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void execute(Runnable command) {
|
||||||
|
command.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void shutdown() {
|
||||||
|
shutdown = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Runnable> shutdownNow() {
|
||||||
|
shutdown = true;
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isShutdown() {
|
||||||
|
return shutdown;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isTerminated() {
|
||||||
|
return shutdown;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) {
|
||||||
|
return shutdown;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
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.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
class GroupingTest {
|
||||||
|
record Item(String type, String status) {}
|
||||||
|
|
||||||
|
static GroupPath path(String value) {
|
||||||
|
return new GroupPath(List.of(new GroupPath.Segment("type", new FilterValue.Text(value))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void snapshotSeparatesExactIdentityAndLabelsFromOrderingAndRetainsLeafSourceOrder() {
|
||||||
|
AtomicInteger calls = new AtomicInteger();
|
||||||
|
var mapping =
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> {
|
||||||
|
calls.incrementAndGet();
|
||||||
|
return i.type() == null ? null : new FilterValue.Text(i.type());
|
||||||
|
},
|
||||||
|
GroupColumn::display);
|
||||||
|
var rows =
|
||||||
|
List.of(
|
||||||
|
new GridRow<>(1, new Item("a", "one")),
|
||||||
|
new GridRow<>(2, new Item(null, "two")),
|
||||||
|
new GridRow<>(3, new Item("A", "three")),
|
||||||
|
new GridRow<>(4, new Item("a", "four")),
|
||||||
|
new GridRow<>(5, new Item("", "five")));
|
||||||
|
var snapshot = GroupProjection.capture(rows, List.of(mapping));
|
||||||
|
var groups = GroupProjection.project(snapshot, List.of("type"));
|
||||||
|
assertEquals(
|
||||||
|
List.of("(Empty)", "A", "a", "(Missing)"),
|
||||||
|
groups.stream().map(GroupProjection.Node::label).toList());
|
||||||
|
assertEquals(List.of(1, 4), groups.get(2).rows().stream().map(GridRow::key).toList());
|
||||||
|
assertEquals(5, calls.get());
|
||||||
|
GroupProjection.project(snapshot, List.of("type"));
|
||||||
|
assertEquals(5, calls.get(), "Regroup must use captured scalars, not reread models");
|
||||||
|
assertEquals(List.of(1, 2, 3, 4, 5), rows.stream().map(GridRow::key).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void decimalScaleDoesNotCreateDifferentGroupsAndWrongTypesFailBeforePublication() {
|
||||||
|
var mapping =
|
||||||
|
new GroupColumn<BigDecimal>(
|
||||||
|
"amount",
|
||||||
|
MemoryColumn.Kind.DECIMAL,
|
||||||
|
FilterValue.Decimal::new,
|
||||||
|
GroupColumn::display);
|
||||||
|
var groups =
|
||||||
|
GroupProjection.project(
|
||||||
|
GroupProjection.capture(
|
||||||
|
List.of(
|
||||||
|
new GridRow<>(1, new BigDecimal("1.0")),
|
||||||
|
new GridRow<>(2, new BigDecimal("1.00"))),
|
||||||
|
List.of(mapping)),
|
||||||
|
List.of("amount"));
|
||||||
|
assertEquals(1, groups.size());
|
||||||
|
assertEquals(2, groups.getFirst().count());
|
||||||
|
var invalid =
|
||||||
|
new GroupColumn<String>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
s -> new FilterValue.BooleanValue(true),
|
||||||
|
GroupColumn::display);
|
||||||
|
assertThrows(
|
||||||
|
IllegalArgumentException.class,
|
||||||
|
() -> GroupProjection.capture(List.of(new GridRow<>(1, "x")), List.of(invalid)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void expansionPreservesCurrentChoicesAndBoundsOnlyInactiveHistory() {
|
||||||
|
var expansion = new GroupExpansion(true, 1);
|
||||||
|
expansion.current(List.of(path("A"), path("B")));
|
||||||
|
expansion.set(path("A"), true);
|
||||||
|
expansion.set(path("B"), false);
|
||||||
|
expansion.set(path("C"), true);
|
||||||
|
expansion.set(path("D"), true);
|
||||||
|
assertEquals(3, expansion.snapshot().size());
|
||||||
|
assertTrue(expansion.expanded(path("A")));
|
||||||
|
assertFalse(expansion.expanded(path("C")));
|
||||||
|
expansion.configure(false, 1);
|
||||||
|
assertFalse(
|
||||||
|
expansion.expanded(path("B")),
|
||||||
|
"Explicit choice equal to old default must survive default change");
|
||||||
|
expansion.reset();
|
||||||
|
assertTrue(expansion.expanded(path("B")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nestedCountsAndPathsDoNotConflateEqualLabelsOrParentCollapse() {
|
||||||
|
var cols =
|
||||||
|
List.of(
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.type()),
|
||||||
|
v -> "same"),
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"status",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.status()),
|
||||||
|
GroupColumn::display));
|
||||||
|
var tree =
|
||||||
|
GroupProjection.project(
|
||||||
|
GroupProjection.capture(
|
||||||
|
List.of(
|
||||||
|
new GridRow<>(1, new Item("A", "live")),
|
||||||
|
new GridRow<>(2, new Item("B", "live"))),
|
||||||
|
cols),
|
||||||
|
List.of("type", "status"));
|
||||||
|
assertEquals(2, tree.size());
|
||||||
|
assertNotEquals(tree.get(0).path(), tree.get(1).path());
|
||||||
|
var expansion = new GroupExpansion(true, 1000);
|
||||||
|
expansion.current(GroupProjection.paths(tree));
|
||||||
|
var parent = tree.get(0).path();
|
||||||
|
var child = tree.get(0).children().getFirst().path();
|
||||||
|
expansion.set(child, true);
|
||||||
|
expansion.set(parent, false);
|
||||||
|
expansion.set(parent, true);
|
||||||
|
assertTrue(expansion.expanded(child));
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>encryption</artifactId>
|
<artifactId>encryption</artifactId>
|
||||||
|
|||||||
@@ -30,12 +30,12 @@ From the NeitzelLib root with JDK 25:
|
|||||||
./mvnw -f fx-example/pom.xml javafx:run
|
./mvnw -f fx-example/pom.xml javafx:run
|
||||||
```
|
```
|
||||||
|
|
||||||
The first command installs local `1.0` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
|
The first command installs local `1.0.1` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
|
||||||
|
|
||||||
The packaged alternative, after `package` or `install`, is:
|
The packaged alternative, after `package` or `install`, is:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
java -jar fx-example/target/fx-example-1.0.jar
|
java -jar fx-example/target/fx-example-1.0.1.jar
|
||||||
```
|
```
|
||||||
|
|
||||||
Keep the adjacent `target/libs` directory with the JAR: the manifest refers to those copied runtime dependencies. A desktop session is required. This example has no `module-info.java`; it is a classpath application.
|
Keep the adjacent `target/libs` directory with the JAR: the manifest refers to those copied runtime dependencies. A desktop session is required. This example has no `module-info.java`; it is a classpath application.
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ From the repository root with JDK 25, build without installing runtime artifacts
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
./mvnw -pl fx-example -am package -DskipTests
|
./mvnw -pl fx-example -am package -DskipTests
|
||||||
java -cp 'fx-example/target/fx-example-1.0.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
|
java -cp 'fx-example/target/fx-example-1.0.1.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.
|
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.
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
|
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
java -cp 'fx-example/target/fx-example-1.0.jar:fx-example/target/libs/*' \
|
java -cp 'fx-example/target/fx-example-1.0.1.jar:fx-example/target/libs/*' \
|
||||||
de.neitzel.fx.example.theme.ThemeGalleryMain
|
de.neitzel.fx.example.theme.ThemeGalleryMain
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>fx-example</artifactId>
|
<artifactId>fx-example</artifactId>
|
||||||
|
|||||||
+4
-1
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Documentation map
|
## Documentation map
|
||||||
|
|
||||||
|
- [FXML support for every public control](docs/fxml-controls.md).
|
||||||
|
|
||||||
- [Build a complete application from scratch](docs/quick-start.md).
|
- [Build a complete application from scratch](docs/quick-start.md).
|
||||||
- [Architecture, MVVM, identity, threading and lifetime](docs/architecture.md).
|
- [Architecture, MVVM, identity, threading and lifetime](docs/architecture.md).
|
||||||
- [Walk through the person desk](../fx-example/README.md).
|
- [Walk through the person desk](../fx-example/README.md).
|
||||||
@@ -21,6 +23,7 @@
|
|||||||
- [Dependency injection](../injection/README.md).
|
- [Dependency injection](../injection/README.md).
|
||||||
|
|
||||||
- [Local DataGrid and asynchronous coordination](docs/data-grid.md).
|
- [Local DataGrid and asynchronous coordination](docs/data-grid.md).
|
||||||
|
- [Interactive layout, grouping and optional application persistence](docs/data-grid-layout.md).
|
||||||
- [Transactional FXML filters and popup lifecycle](docs/filter-editors.md).
|
- [Transactional FXML filters and popup lifecycle](docs/filter-editors.md).
|
||||||
- [Versioned saved setups and atomic restoration](docs/saved-setups.md).
|
- [Versioned saved setups and atomic restoration](docs/saved-setups.md).
|
||||||
- [Opt-in shared themes](docs/themes.md) and the [theme gallery](../fx-example/docs/theme-gallery.md).
|
- [Opt-in shared themes](docs/themes.md) and the [theme gallery](../fx-example/docs/theme-gallery.md).
|
||||||
@@ -51,7 +54,7 @@ These are the versions configured by this source snapshot, not a promise of comp
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| JDK | Java 25 | Select a matching JDK for compilation and launch |
|
| JDK | Java 25 | Select a matching JDK for compilation and launch |
|
||||||
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
|
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
|
||||||
| Library | `de.neitzel.lib:fx:1.0` | Use the Gitea Maven registry or install the local reactor |
|
| Library | `de.neitzel.lib:fx:1.0.1` | Use the Gitea Maven registry or install the local reactor |
|
||||||
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
|
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
|
||||||
| JavaFX | 27.0.1: base, graphics, controls, FXML and web | Resolved transitively; deployment still needs platform-native artifacts |
|
| JavaFX | 27.0.1: base, graphics, controls, FXML and web | Resolved transitively; deployment still needs platform-native artifacts |
|
||||||
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
|
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
# DataGrid layout, grouping and saved application setups
|
||||||
|
|
||||||
|
These features extend the opt-in queried DataGrid. Standalone collection/FXML
|
||||||
|
Table behavior is unchanged. Use Java 25 and call grid operations on the JavaFX
|
||||||
|
application thread.
|
||||||
|
|
||||||
|
## Group a returned page
|
||||||
|
|
||||||
|
Declare group values explicitly; never derive them from a rendered cell. A text
|
||||||
|
mapping is convenient for labels, while the full constructor supports integers,
|
||||||
|
exact decimals and booleans using `FilterValue` and `MemoryColumn.Kind`.
|
||||||
|
|
||||||
|
```java
|
||||||
|
// grid already has stable ResultColumn IDs and a source, as in data-grid.md.
|
||||||
|
grid.configureGrouping(
|
||||||
|
List.of(GroupColumn.<Person>text("name", Person::name),
|
||||||
|
GroupColumn.<Person>text("type", Person::type)),
|
||||||
|
true, // developer enables grouping
|
||||||
|
List.of("type"), // outer-to-inner default grouping columns
|
||||||
|
true, // unseen groups start collapsed
|
||||||
|
1000); // inactive expansion choices retained
|
||||||
|
```
|
||||||
|
|
||||||
|
`GroupColumn`, `GroupPath`, `GroupingSetup` and the projection/history models live
|
||||||
|
in `de.neitzel.grid`. All eligible values/labels are captured when a page publishes,
|
||||||
|
even for columns not currently grouped. `setGroupingColumns(List.of("type","name"))`
|
||||||
|
rearranges existing page components using those snapshots and issues no query.
|
||||||
|
`regroup()` explicitly recaptures group values after an application data update;
|
||||||
|
it does not change page membership. `refresh()` instead queries the source.
|
||||||
|
|
||||||
|
Text equality is exact, including case and whitespace; missing and empty text
|
||||||
|
are distinct. Decimal 1.0 and 1.00 share identity. Groups sort ascending, text
|
||||||
|
ignoring case with an exact tie-breaker, booleans false then true, missing last.
|
||||||
|
Rows within a leaf group retain their source order. Custom domains must map to
|
||||||
|
one declared scalar type; changing identity/normalization semantics requires a
|
||||||
|
schema migration. Labels never define identity. Invalid mappings fail visibly
|
||||||
|
without replacing the prior grouping.
|
||||||
|
|
||||||
|
Grouping applies only to the loaded page. The same value may recur on another
|
||||||
|
page; counts include collapsed data rows and exclude group headings. Explicit All
|
||||||
|
mode still uses the existing guard/confirmation protocol and retains all returned
|
||||||
|
row components. Collapsing it does not remove that memory cost.
|
||||||
|
|
||||||
|
## Interactions and row ownership
|
||||||
|
|
||||||
|
Drag a column's right boundary to preview a bounded width; release commits that
|
||||||
|
column and Escape restores its previous sizing intent. Drag a header label to
|
||||||
|
move a column, or into the grouping area to add a chip. Insertion feedback and
|
||||||
|
fixed-position constraints apply; invalid/outside drops cancel without sorting.
|
||||||
|
Grouped columns remain visible. Drag chips to reorder levels, and use × to remove
|
||||||
|
a grouping level. A header click still sorts and the separate filter icon opens
|
||||||
|
its editor. The Grid setup menu offers keyboard-operable Column settings.
|
||||||
|
|
||||||
|
Each group has a disclosure triangle. Expansion follows the typed ordered path,
|
||||||
|
not its label or page number. Parent collapse preserves child choices. Current
|
||||||
|
paths are retained along with the configured LRU history of inactive explicit
|
||||||
|
choices; evicted paths return to the default. `setExpanded(path, boolean)` and
|
||||||
|
`resetExpansion()` provide programmatic equivalents. `setGroupingEnabled(false)`
|
||||||
|
hides grouped presentation without erasing valid dormant choices.
|
||||||
|
|
||||||
|
Reorder/regroup/collapse preserve current-page component identity and drafts.
|
||||||
|
Actual page replacement keeps the existing guard/staging/disposal rules. A hidden
|
||||||
|
selected record retains its key but has no actionable `selectedElement`. Expansion
|
||||||
|
never re-enables stale rows. If collapse/reset hides focus, focus moves to a visible
|
||||||
|
group heading. No historical rows are retained merely for expansion history.
|
||||||
|
|
||||||
|
## Attach optional persistence
|
||||||
|
|
||||||
|
`fx` does not depend on Gson. Add `de.neitzel.lib:gson` at the same library version
|
||||||
|
when using the supplied JSON/file integration. The neutral custom-store contracts
|
||||||
|
remain available without Gson.
|
||||||
|
|
||||||
|
```java
|
||||||
|
// Once per application, not per tab. No files/directories are created here.
|
||||||
|
var configuration = GridSetupFiles.forApplication("MyApplication");
|
||||||
|
|
||||||
|
// On each grid, after columns/grouping are configured, before the first query:
|
||||||
|
grid.configureSetups("people.records", 1,
|
||||||
|
Map.of("name", "text.v1", "type", "text.v1"), Map.of());
|
||||||
|
var attachment = grid.attachPersistence(configuration, "people.records");
|
||||||
|
attachment.loadAsync(); // read -> validate/restore or defaults -> one initial query
|
||||||
|
// attachment.ready() completes after initialization or explicit recovery succeeds.
|
||||||
|
```
|
||||||
|
|
||||||
|
Factory: `de.neitzel.gson.grid.GridSetupFiles`. Service/store:
|
||||||
|
`de.neitzel.grid.GridApplicationConfiguration` and `GridSetupStore`. Attachment:
|
||||||
|
`de.neitzel.fx.view.GridPersistenceAttachment`. An attachment overload accepts a
|
||||||
|
context key. `GridSetupFiles.forApplication(name, path)` selects an explicit grid
|
||||||
|
storage directory; another overload accepts pre-registered `GridSetupJson` codecs.
|
||||||
|
Custom stores implement blocking load/revision/conditional-save; the service runs
|
||||||
|
those operations off the FX thread.
|
||||||
|
|
||||||
|
The default directory is `ApplicationDirectories.configurationDirectory(name)`
|
||||||
|
plus `grids`. Grid/context keys map to opaque safe filenames, with identity checked
|
||||||
|
inside each document. Existing application preferences are never migrated.
|
||||||
|
Never-attached grids perform no persistence I/O. Attachments can be closed and
|
||||||
|
replaced; the application service owns accepted saves after detachment.
|
||||||
|
|
||||||
|
A stable grid ID/context shares one stored setup, not live displays. Newly opened
|
||||||
|
grids restore the latest successfully saved snapshot. Open grids keep their own
|
||||||
|
state until `attachment.loadAsync()` or Reload saved setup. The newest committed
|
||||||
|
change replaces the whole saved snapshot; fields from different views are not
|
||||||
|
merged. Closing an unchanged older tab cannot overwrite newer choices.
|
||||||
|
|
||||||
|
## Defaults, formats and recovery
|
||||||
|
|
||||||
|
The existing GridSetup format is extended with grouping and typed expansion
|
||||||
|
choices. Version-one documents remain readable; absent new preferences inherit
|
||||||
|
current developer grouping defaults. Current version-two documents require their
|
||||||
|
complete schema. Definition/type migrations, fixed-position validation, width
|
||||||
|
clamping and custom filter codecs retain their existing strict behavior.
|
||||||
|
Unsupported or incompatible files fail visibly, never by silently dropping fields.
|
||||||
|
|
||||||
|
`configureDefaults(GridSetup)` may configure the full default query/layout without
|
||||||
|
fetching, after definitions/mappings and before attachment/load. Otherwise defaults
|
||||||
|
are captured at attachment. Defaults stay separate from the restored display.
|
||||||
|
|
||||||
|
Committed changes autosave after a configurable debounce (500 ms by default).
|
||||||
|
`committedRevisionProperty()` is the FX notification seam; previews, cancelled
|
||||||
|
operations, drafts and failed/pending queries do not become saves. Query preferences
|
||||||
|
are saved only after successful publication. Saving/encoding failures retain the
|
||||||
|
latest unsaved snapshot and last good file. The grid shows nonmodal settings
|
||||||
|
feedback with Retry/Reload/Reset/Overwrite actions, separate from query status.
|
||||||
|
|
||||||
|
If no saved file exists, developer defaults apply. An unreadable/incompatible file blocks startup restoration
|
||||||
|
and initial query until retry or explicit reset succeeds. Full Reset setup uses
|
||||||
|
current defaults and the existing edit guard/transactional publication before
|
||||||
|
accepting a replacement save. Reset expansion only clears expansion choices and
|
||||||
|
never queries or resets other preferences.
|
||||||
|
|
||||||
|
The file store uses process coordination, revision-checked writes and atomic
|
||||||
|
replacement. A cross-process conflict requires explicit Reload or Overwrite.
|
||||||
|
Reload retires its abandoned pending generation only after successful guarded
|
||||||
|
restoration and cannot discard a newer change. Overwrite is still conditional
|
||||||
|
against a freshly observed revision. Unsupported atomic filesystem operations
|
||||||
|
fail rather than publishing a partial file.
|
||||||
|
|
||||||
|
## Close and application shutdown
|
||||||
|
|
||||||
|
```java
|
||||||
|
// Tab close, on FX thread:
|
||||||
|
attachment.close();
|
||||||
|
grid.close();
|
||||||
|
|
||||||
|
// Application shutdown: asynchronous; do not block the FX thread.
|
||||||
|
configuration.flushAsync();
|
||||||
|
configuration.closeAsync(); // also flushes; failure leaves the service retryable
|
||||||
|
// Only after explicit user consent to quit without settings:
|
||||||
|
configuration.discardAndCloseAsync();
|
||||||
|
```
|
||||||
|
|
||||||
|
Chain/await completion stages in the application exit coordinator; the snippet
|
||||||
|
lists operations, not permission to ignore their completion. A failed flush must
|
||||||
|
be handled before exit. Close does not own external executors. Explicit discard
|
||||||
|
retires pending work but cannot undo a write already committed. Detaching a grid
|
||||||
|
stops observation/cancels its unfinished restore, not already accepted app saves.
|
||||||
|
|
||||||
|
## Qualification
|
||||||
|
|
||||||
|
Automated component/state, codec, lifecycle and real separate-process storage tests
|
||||||
|
are provided. For native interaction qualification after running DataGridGroupingTest:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 fx/scripts/data-grid-probe.py
|
||||||
|
# macOS bundle for native accessibility tooling:
|
||||||
|
python3 fx/scripts/data-grid-probe.py --app
|
||||||
|
```
|
||||||
|
|
||||||
|
This opens actual JavaFX DataGrid controls with fictional records and a resource/
|
||||||
|
query trace. Use native pointer/keyboard input to qualify the recorded acceptance
|
||||||
|
scenarios; it is not a browser mock and emits no synthetic OS input. It has no
|
||||||
|
application persistence or real DNS/network data. Runtime/platform evidence and
|
||||||
|
remaining limits are recorded in the Workspace implementation record.
|
||||||
|
|
||||||
|
For repeatable macOS held-input checks (Escape during a drag, invalid/outside
|
||||||
|
native drops and timed edge hovering), the separate opt-in fixture uses AWT
|
||||||
|
Robot for pointer/keyboard input and JavaFX Robot for capture. It operates only
|
||||||
|
its fictional-data window and owned popups; no application data or DNS is used.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./mvnw -pl fx -am -Dtest=DataGridNativeInteractionTest \
|
||||||
|
-Dneitzellib.nativeGridTest=true -Dsurefire.failIfNoSpecifiedTests=false test
|
||||||
|
```
|
||||||
|
|
||||||
|
Without `neitzellib.nativeGridTest=true`, its five native tests are skipped.
|
||||||
|
On macOS the Java launcher and launching terminal or IDE need event-posting
|
||||||
|
permission in Privacy & Security → Accessibility. A permission-denied process
|
||||||
|
fails before posting input; that failure does not establish a gesture failure.
|
||||||
|
Restore any temporary permissions after testing. Keep the desktop idle: checks
|
||||||
|
stop if focus leaves their window and owned popups. Cleanup releases input and
|
||||||
|
disposes retained rows even on failure. Captures go to `fx/target/native-grid`.
|
||||||
|
Cancellation waits for the native drag-completion callback before releasing the
|
||||||
|
button or starting another gesture, including macOS's return animation.
|
||||||
+12
-1
@@ -1,5 +1,7 @@
|
|||||||
# Local DataGrid and request coordination
|
# Local DataGrid and request coordination
|
||||||
|
|
||||||
|
For direct declarations, columns and data bindings in FXML, see [FXML controls](fxml-controls.md).
|
||||||
|
|
||||||
`DataGrid<K,T>` composes the existing Table result renderer with paging controls and a toolkit-independent coordinator. All UI methods are called on the JavaFX application thread. The legacy Table FXML/collection path is unchanged.
|
`DataGrid<K,T>` composes the existing Table result renderer with paging controls and a toolkit-independent coordinator. All UI methods are called on the JavaFX application thread. The legacy Table FXML/collection path is unchanged.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@@ -23,7 +25,8 @@ Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` fo
|
|||||||
|
|
||||||
## Operations
|
## Operations
|
||||||
|
|
||||||
- First/Previous/Next/Last, page-size selection, Refresh and Retry are supplied. Page sizes offer 25/50/100/250 within source limits plus explicit All when supported. The initial page size is 50, bounded by source limits.
|
- Vertical separators mark column boundaries in headers and data rows, follow resizing/reordering, and use the active theme border color. Group headings span the columns.
|
||||||
|
- First/Previous/Next/Last use vector navigation icons with tooltips and accessible page names. Page-size selection, Refresh and Retry are supplied. Page sizes offer 25/50/100/250 within source limits plus explicit All when supported. The initial page size is 50, bounded by source limits.
|
||||||
- Header clicks alternate ascending/descending sort for that mapped column; `setSort(null)` clears user sorting. Sorting/filter/page-size changes request the first page (All remains All with fresh consent checks).
|
- Header clicks alternate ascending/descending sort for that mapped column; `setSort(null)` clears user sorting. Sorting/filter/page-size changes request the first page (All remains All with fresh consent checks).
|
||||||
- `setFilters`, `setSort`, `setPageRequest`, `setSource`, `load`, `refresh`, and `retry` delegate to the coordinator; returned rows are never locally filtered again.
|
- `setFilters`, `setSort`, `setPageRequest`, `setSource`, `load`, `refresh`, and `retry` delegate to the coordinator; returned rows are never locally filtered again.
|
||||||
- `stateProperty` exposes requested versus displayed query, result, phase and error. Loading/failed rows stay visible but disabled; selected loaded data becomes unavailable while those rows are stale. Query/navigation controls remain usable.
|
- `stateProperty` exposes requested versus displayed query, result, phase and error. Loading/failed rows stay visible but disabled; selected loaded data becomes unavailable while those rows are stale. Query/navigation controls remain usable.
|
||||||
@@ -43,3 +46,11 @@ The application must provide a serial owner-thread callback executor when using
|
|||||||
`close` cancels the active request, invalidates pending callbacks/alerts, closes the renderer and releases displayed rows. It does not close application-owned infrastructure. Observe `disposalFailureProperty` for row cleanup failures.
|
`close` cancels the active request, invalidates pending callbacks/alerts, closes the renderer and releases displayed rows. It does not close application-owned infrastructure. Observe `disposalFailureProperty` for row cleanup failures.
|
||||||
|
|
||||||
FXML filter editors and the opt-in popup host are now available; see [filter editors](filter-editors.md), including the recorded native qualification limitation. [JSON setup restore](saved-setups.md) is available through the optional Gson module. [Shared themes and window propagation](themes.md) are available opt-in. The optional [JDBC adapter and H2 example](../../fx-example/docs/product-grid.md) now demonstrate external execution. The default alert is ordinary JavaFX; native interaction/theme qualification remains part of those acceptance gates. Row mappings, programmatic order/width changes and cleanup retain the foundation guide's constraints in [table-results](table-results.md).
|
FXML filter editors and the opt-in popup host are now available; see [filter editors](filter-editors.md), including the recorded native qualification limitation. [JSON setup restore](saved-setups.md) is available through the optional Gson module. [Shared themes and window propagation](themes.md) are available opt-in. The optional [JDBC adapter and H2 example](../../fx-example/docs/product-grid.md) now demonstrate external execution. The default alert is ordinary JavaFX; native interaction/theme qualification remains part of those acceptance gates. Row mappings, programmatic order/width changes and cleanup retain the foundation guide's constraints in [table-results](table-results.md).
|
||||||
|
|
||||||
|
## Interactive layout and grouping
|
||||||
|
|
||||||
|
Column resize/reorder, grouping chips, disclosure and keyboard Column settings
|
||||||
|
are now opt-in DataGrid features. Application-name-based saved setups are an
|
||||||
|
optional attachment using the existing versioned setup model. See the
|
||||||
|
[layout, grouping and persistence guide](data-grid-layout.md) for mappings,
|
||||||
|
component lifetime, startup/recovery, storage concurrency and shutdown.
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
# Controls in FXML
|
||||||
|
|
||||||
|
Every public visual control supplied by `fx` can be declared in ordinary FXML.
|
||||||
|
`FXMLLoader` constructs the view without a database, DNS connection or injection
|
||||||
|
context. The optional `ViewLoader` applies NeitzelLib binding declarations.
|
||||||
|
|
||||||
|
| Control | FXML configuration | Data and lifetime |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `de.neitzel.fx.view.DataGrid` | Columns, typed attributes, widths, filters, grouping, page size and setup identity | Bind `items` or `source`; explicitly load after configuration, close with the view |
|
||||||
|
| `de.neitzel.fx.view.Table` | `collection`, `row`, `Column` declarations | Existing ViewLoader collection/Component rows and `selection` binding |
|
||||||
|
| `de.neitzel.fx.control.StatusBar` | `leftItems`, `rightItems` containing ordinary Nodes | Bind the properties of the contained controls |
|
||||||
|
| `de.neitzel.fx.docking.DockPane` | `initialLayout`, `DockLayout`, group/split definitions | Attach a DockingManager to open application-owned content |
|
||||||
|
| `de.neitzel.fx.control.NonNegativeIntegerSpinner` | `minimum`, `maximum`, `initialValue` constructor attributes | Bind writable `number`, which shares the value factory's property |
|
||||||
|
| `javafx.scene.control.ToolBar` | Standard `items` and `orientation` | Standard JavaFX control, deliberately reused by the library |
|
||||||
|
|
||||||
|
Supporting objects such as coordinators, sources, setup stores, popup hosts,
|
||||||
|
result renderers, theme managers and tray integrations are application/runtime
|
||||||
|
objects, rather than controls to insert in a scene graph.
|
||||||
|
|
||||||
|
## DataGrid
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<?import de.neitzel.fx.view.*?>
|
||||||
|
<?import javafx.scene.layout.VBox?>
|
||||||
|
|
||||||
|
<VBox xmlns:fx="http://javafx.com/fxml/1">
|
||||||
|
<fx:define>
|
||||||
|
<BindingList>
|
||||||
|
<DirectBinding control="people" property="items"
|
||||||
|
path="people" direction="view"/>
|
||||||
|
</BindingList>
|
||||||
|
</fx:define>
|
||||||
|
<DataGrid fx:id="people" keyAttribute="id" pageSize="50"
|
||||||
|
maximumPageSize="250" groupingEnabled="true" groupBy="department"
|
||||||
|
groupsCollapsed="false" setupId="people" setupVersion="1">
|
||||||
|
<columns>
|
||||||
|
<DataGridColumn id="name" header="Name" width="200"
|
||||||
|
checklist="SOURCE_WIDE"/>
|
||||||
|
<DataGridColumn id="department" header="Department" width="180"/>
|
||||||
|
<DataGridColumn id="age" header="Age" kind="INTEGER"/>
|
||||||
|
</columns>
|
||||||
|
</DataGrid>
|
||||||
|
</VBox>
|
||||||
|
```
|
||||||
|
|
||||||
|
Initialize the model's `List<Person> people` before loading. Bean and Java record
|
||||||
|
rows are supported. After `ViewLoader.load`, call the injected grid's `load()` or
|
||||||
|
`loadAsync()` on the FX thread. The data binding shares the model's observable
|
||||||
|
list. Add, remove, replace, permute or use an extractor update on that list to
|
||||||
|
request a refresh immediately, invalidating older pending results. The existing
|
||||||
|
query (filters/sort/page) is retained; use `setAll` for a single batch update. Replacing `grid.items` detaches
|
||||||
|
the old list. Rows are snapshots: mutating a field without an observable update
|
||||||
|
requires `refresh()`.
|
||||||
|
|
||||||
|
Configure before the first runtime operation. `initialize()` completes setup
|
||||||
|
without querying, allowing an application to attach persistence before calling
|
||||||
|
`loadAsync()`. Nothing loads in the constructor, and FXML without data displays
|
||||||
|
column headers in a query-free preview. State is null until initialization.
|
||||||
|
|
||||||
|
For ordinary `FXMLLoader`, provide the list in its namespace and use
|
||||||
|
`items="$people"`, or assign/bind `itemsProperty()` after loading. The same
|
||||||
|
explicit loading and closing contract applies. `DirectBinding` requires
|
||||||
|
`ViewLoader`; the usual collection-binding limitations in the main reference
|
||||||
|
still apply, including replacing model attributes through the ViewModel.
|
||||||
|
|
||||||
|
A local grid requires a stable unique row key: `keyAttribute="id"` reads a public
|
||||||
|
bean getter or record accessor. Alternatively supply `keyFactory` and
|
||||||
|
`keyComparator` in Java before initialization. Keys must be comparable when no
|
||||||
|
comparator is supplied. Duplicate/null keys fail the query visibly. The local
|
||||||
|
grid owns its virtual-thread executor and releases it on `close()`.
|
||||||
|
|
||||||
|
For an external queried grid, bind `source` instead of `items`. Column IDs must
|
||||||
|
match the source mappings. The source and executor remain application-owned.
|
||||||
|
Changing an initialized source starts a request using the current filters/sort
|
||||||
|
and first page, as with the programmatic interface. External checklist filters
|
||||||
|
need an explicitly supplied `candidates` provider; local sources supply one.
|
||||||
|
|
||||||
|
Column defaults: `attribute` uses `id`, `kind="TEXT"`, width 150, minimum 80,
|
||||||
|
maximum 1200, fixed position -1 (movable), filterable true, checklist disabled.
|
||||||
|
Kinds are `TEXT`, `INTEGER`, `DECIMAL`, `BOOLEAN`. Text and numeric filter editors
|
||||||
|
are built in; boolean values can render/group and use programmatic conditions,
|
||||||
|
but have no built-in editor. Set `filterable="false"` for display-only columns.
|
||||||
|
`groupAttribute` optionally separates stable group values from displayed/filter
|
||||||
|
values; `groupLabels` maps those values to display labels without changing group
|
||||||
|
identity. `type` supplies a stable schema type for saved setups; the default is
|
||||||
|
`neitzel.<kind>.v1`. Keep type IDs and setup versions stable across upgrades.
|
||||||
|
|
||||||
|
The default row factory creates labels. Supply a Java `rowFactory` for custom
|
||||||
|
nodes, styles, tooltips or actions; use `DataGridColumn.getValue(row)` to share
|
||||||
|
the FXML mappings. FXML can also reference factories using `$factory` namespace
|
||||||
|
values. Selection is available through the stable read-only
|
||||||
|
`selectedKeyProperty()` and `selectedElementProperty()`; call `select(key)` to
|
||||||
|
change it. Existing programmatic constructor and queried-grid behavior remain
|
||||||
|
supported.
|
||||||
|
|
||||||
|
## Bounded integer spinner
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<?import de.neitzel.fx.control.NonNegativeIntegerSpinner?>
|
||||||
|
<NonNegativeIntegerSpinner xmlns:fx="http://javafx.com/fxml/1"
|
||||||
|
fx:id="quantity" minimum="0" maximum="100"
|
||||||
|
initialValue="1"/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `<DirectBinding control="quantity" property="number" path="quantity"
|
||||||
|
direction="both"/>` in a ViewLoader binding list. Valid typing commits
|
||||||
|
immediately; invalid typing and bounds follow [bounded integer inputs](integer-spinners.md).
|
||||||
|
The original `IntegerSpinners.nonNegative(...)` factory remains available.
|
||||||
|
|
||||||
|
See [bars](bars.md), [docking](docking.md) and the main [FXML reference](../README.md)
|
||||||
|
for the existing controls. The host designer needs the updated library on its
|
||||||
|
classpath; this feature does not replace a separately pinned Designer runtime.
|
||||||
@@ -24,3 +24,10 @@ container.getChildren().add(quantity);
|
|||||||
```
|
```
|
||||||
|
|
||||||
Import `javafx.scene.control.Spinner` and `de.neitzel.fx.control.IntegerSpinners`; `container` is your Pane. Read `quantity.getValue()` to obtain the committed number. Set a programmatic value through `quantity.getValueFactory().setValue(...)`. Use the factory's bounds as UI constraints and keep independent business validation where the value is saved. The helper does not add an FXML binding declaration or create a Model Attribute automatically.
|
Import `javafx.scene.control.Spinner` and `de.neitzel.fx.control.IntegerSpinners`; `container` is your Pane. Read `quantity.getValue()` to obtain the committed number. Set a programmatic value through `quantity.getValueFactory().setValue(...)`. Use the factory's bounds as UI constraints and keep independent business validation where the value is saved. The helper does not add an FXML binding declaration or create a Model Attribute automatically.
|
||||||
|
|
||||||
|
## FXML
|
||||||
|
|
||||||
|
Declare `NonNegativeIntegerSpinner` with `minimum`, `maximum`, and `initialValue`
|
||||||
|
constructor attributes. Bind its writable `number` property with `DirectBinding`;
|
||||||
|
it shares the value factory property and supports both directions. See the
|
||||||
|
[FXML controls guide](fxml-controls.md#bounded-integer-spinner).
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
# Your first JavaFX application
|
# Your first JavaFX application
|
||||||
|
|
||||||
This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0. The source build below uses the matching release tag.
|
This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.1. The source build below uses the matching release tag.
|
||||||
|
|
||||||
## Prepare the library
|
## Prepare the library
|
||||||
|
|
||||||
Install a JDK 25. Use the library's Maven wrapper (3.9.11), or a separate Maven installation version 3.9.11 or newer. Check `java -version` and `./mvnw -version` before building; on macOS, select the JDK with `export JAVA_HOME=$(/usr/libexec/java_home -v 25)` if necessary.
|
Install a JDK 25. Use the library's Maven wrapper (3.9.11), or a separate Maven installation version 3.9.11 or newer. Check `java -version` and `./mvnw -version` before building; on macOS, select the JDK with `export JAVA_HOME=$(/usr/libexec/java_home -v 25)` if necessary.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone --branch v1.0 https://gitea.neitzel.de/konrad/NeitzelLib.git
|
git clone --branch v1.0.1 https://gitea.neitzel.de/konrad/NeitzelLib.git
|
||||||
cd NeitzelLib
|
cd NeitzelLib
|
||||||
./mvnw -pl fx-example -am install
|
./mvnw -pl fx-example -am install
|
||||||
./mvnw -f fx-example/pom.xml javafx:run
|
./mvnw -f fx-example/pom.xml javafx:run
|
||||||
@@ -66,7 +66,7 @@ hello-fx/
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
@@ -190,7 +190,7 @@ For a named-module application, see the [module and lifecycle notes](architectur
|
|||||||
|
|
||||||
| Symptom | Check |
|
| Symptom | Check |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Maven cannot resolve `de.neitzel.lib:fx:1.0` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
|
| Maven cannot resolve `de.neitzel.lib:fx:1.0.1` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
|
||||||
| `No plugin found for prefix 'javafx'` | Invoke the example POM directly, or use the complete application POM above. Do not invoke the goal on the library reactor parent. |
|
| `No plugin found for prefix 'javafx'` | Invoke the example POM directly, or use the complete application POM above. Do not invoke the goal on the library reactor parent. |
|
||||||
| JavaFX runtime/native library failure | Check the JDK version, architecture and JavaFX dependencies actually resolved; avoid mixing native artifacts from different platforms or JavaFX versions. |
|
| JavaFX runtime/native library failure | Check the JDK version, architecture and JavaFX dependencies actually resolved; avoid mixing native artifacts from different platforms or JavaFX versions. |
|
||||||
| `getResource(...)` returns null | The FXML belongs under `src/main/resources` in the matching package; verify it was copied to `target/classes`. Resource names are case-sensitive. |
|
| `getResource(...)` returns null | The FXML belongs under `src/main/resources` in the matching package; verify it was copied to `target/classes`. Resource names are case-sensitive. |
|
||||||
|
|||||||
+11
-1
@@ -1,6 +1,7 @@
|
|||||||
# Saved DataGrid setups
|
# Saved DataGrid setups
|
||||||
|
|
||||||
Saved setups are opt-in and preserve the legacy Table path. The `data-grid` module owns immutable models, definition validation and migrations; `fx` stages layout/result publication; the existing optional `gson` module owns JSON encoding. Applications choose storage and save/load timing. The FX library does not depend on Gson.
|
Saved setups are opt-in and preserve the legacy Table path. The `data-grid` module owns immutable models, definition validation and migrations; `fx` stages layout/result publication; the existing optional `gson` module owns JSON encoding. Applications choose storage and save/load timing. The FX library does not depend on Gson. An optional application-owned attachment
|
||||||
|
now supplies automatic storage/timing; see [layout and persistence](data-grid-layout.md).
|
||||||
|
|
||||||
## Configure and save
|
## Configure and save
|
||||||
|
|
||||||
@@ -48,3 +49,12 @@ Appending a new column does not itself require a migration when the saved defini
|
|||||||
Implement and register `GridSetupJson.FilterCodec` for a custom stable filter type ID. Declare the write version, readable versions, explicit JSON payload and decoding logic. The codec must preserve the requested column/type identity. `readableVersions` defaults to the current write version; support older payloads only with explicit decoding/migration logic. Missing codecs and unsupported payload versions fail visibly. Codec registration is independent of editor availability and local/adapter execution; successful decoding does not establish that the active source supports the condition.
|
Implement and register `GridSetupJson.FilterCodec` for a custom stable filter type ID. Declare the write version, readable versions, explicit JSON payload and decoding logic. The codec must preserve the requested column/type identity. `readableVersions` defaults to the current write version; support older payloads only with explicit decoding/migration logic. Missing codecs and unsupported payload versions fail visibly. Codec registration is independent of editor availability and local/adapter execution; successful decoding does not establish that the active source supports the condition.
|
||||||
|
|
||||||
Built-in text, number, missing/present and checklist codecs are supplied. The built-in editor registrations now declare persistence support through this optional module. See the [JDBC demonstration](../../fx-example/docs/product-grid.md) and [shared themes](themes.md) for opt-in integration.
|
Built-in text, number, missing/present and checklist codecs are supplied. The built-in editor registrations now declare persistence support through this optional module. See the [JDBC demonstration](../../fx-example/docs/product-grid.md) and [shared themes](themes.md) for opt-in integration.
|
||||||
|
|
||||||
|
## Grouping format and automatic storage
|
||||||
|
|
||||||
|
Format version 2 adds ordered grouping columns and typed expansion-path choices.
|
||||||
|
The version-one constructor/codec path remains available; compatible old documents
|
||||||
|
inherit developer grouping defaults at restore. Preserve explicit expansion choices
|
||||||
|
even when equal to defaults. The optional file integration wraps the setup in a
|
||||||
|
strict grid/context/revision document and uses conditional atomic replacement.
|
||||||
|
The plain GridSetupJson API remains available for application-managed storage.
|
||||||
|
|||||||
@@ -18,10 +18,15 @@ Factories may supply freshly bound FXML Components as HBox roots. They must map
|
|||||||
|
|
||||||
The renderer preserves supplied row order and does no local filtering, sorting, fetching or edit observation. The caller validates query results and handles guard approval before calling `show`. It stages new rows before replacing old ones. If construction or mapping validation fails, staged rows are disposed and the old page remains. Factory code that throws before returning a row owns cleanup of its partial construction.
|
The renderer preserves supplied row order and does no local filtering, sorting, fetching or edit observation. The caller validates query results and handles guard approval before calling `show`. It stages new rows before replacing old ones. If construction or mapping validation fails, staged rows are disposed and the old page remains. Factory code that throws before returning a row owns cleanup of its partial construction.
|
||||||
|
|
||||||
`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. This first integration point supplies programmatic ordering/sizing, not drag UI. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
|
`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. The result integration now also supplies native resize/reorder and grouping support
|
||||||
|
when composed by DataGrid; the stable programmatic operations remain available. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
|
||||||
|
|
||||||
`select(key)` retains an off-page key; the read-only loaded selected element becomes null until that key returns. Row clicks and blank-body clicks update this separate result selection. The old `Table.selectionProperty()` remains the legacy path and is not the result-mode selection API.
|
`select(key)` retains an off-page key; the read-only loaded selected element becomes null until that key returns. Row clicks and blank-body clicks update this separate result selection. The old `Table.selectionProperty()` remains the legacy path and is not the result-mode selection API.
|
||||||
|
|
||||||
`close()` is idempotent, removes rows/handlers and disposes row resources. Disposal failures do not undo an already published page; observe `disposalFailureProperty()` to surface them. Explicit close is necessary; attaching/removing a Table from a Scene does not infer application ownership.
|
`close()` is idempotent, removes rows/handlers and disposes row resources. Disposal failures do not undo an already published page; observe `disposalFailureProperty()` to surface them. Explicit close is necessary; attaching/removing a Table from a Scene does not infer application ownership.
|
||||||
|
|
||||||
This is a rendering foundation, not the complete DataGrid. [Local DataGrid](data-grid.md) now supplies request coordination and local source execution. [FXML popup editors](filter-editors.md), [setup codecs](saved-setups.md), and [themes](themes.md) are implemented. Ordering and sizing use the documented programmatic API; drag reorder/resize is not supplied by this result renderer.
|
This is a rendering foundation, not the complete DataGrid. [Local DataGrid](data-grid.md) now supplies request coordination and local source execution. [FXML popup editors](filter-editors.md), [setup codecs](saved-setups.md), and [themes](themes.md) are implemented. DataGrid exposes both programmatic layout operations and native resize/reorder interactions over this result renderer.
|
||||||
|
|
||||||
|
[DataGrid layout/grouping](data-grid-layout.md) documents the component-preserving
|
||||||
|
projection path. Local grouping must not call `show` to recreate current-page
|
||||||
|
editors; `show` remains the guarded replacement/publication boundary.
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Launch the real DataGrid native qualification surface after DataGridGroupingTest.
|
||||||
|
|
||||||
|
On macOS, --app creates an addressable app bundle for native accessibility tools.
|
||||||
|
All generated artifacts stay under fx/target. No application data or persistence.
|
||||||
|
"""
|
||||||
|
import pathlib
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
module = pathlib.Path(__file__).resolve().parent.parent
|
||||||
|
report = module / 'target/surefire-reports/TEST-de.neitzel.fx.view.DataGridGroupingTest.xml'
|
||||||
|
if not report.exists():
|
||||||
|
sys.exit('First run ./mvnw -pl fx -am -Dtest=DataGridGroupingTest -Dsurefire.failIfNoSpecifiedTests=false test')
|
||||||
|
properties = {p.get('name'): p.get('value') for p in ET.parse(report).getroot().find('properties')}
|
||||||
|
classpath = properties.get('surefire.test.class.path', properties['java.class.path'])
|
||||||
|
app_name = 'DataGridProbe'
|
||||||
|
main = 'de.neitzel.fx.view.DataGridNativeProbe'
|
||||||
|
if '--app' in sys.argv:
|
||||||
|
work = module / 'target/native-probe'
|
||||||
|
inputs = work / 'input'
|
||||||
|
inputs.mkdir(parents=True, exist_ok=True)
|
||||||
|
with zipfile.ZipFile(inputs / 'probe.jar', 'w') as archive:
|
||||||
|
seen = set()
|
||||||
|
for entry in classpath.split(':'):
|
||||||
|
path = pathlib.Path(entry)
|
||||||
|
if path.is_dir():
|
||||||
|
for file in path.rglob('*'):
|
||||||
|
if file.is_file() and str(file.relative_to(path)) not in seen:
|
||||||
|
relative = str(file.relative_to(path))
|
||||||
|
seen.add(relative)
|
||||||
|
archive.write(file, relative)
|
||||||
|
elif path.suffix == '.jar':
|
||||||
|
target = inputs / path.name
|
||||||
|
if target.exists() and target.read_bytes() != path.read_bytes():
|
||||||
|
sys.exit('Conflicting dependency filename: ' + path.name)
|
||||||
|
shutil.copy2(path, target)
|
||||||
|
app = work / (app_name + '.app')
|
||||||
|
if app.exists():
|
||||||
|
shutil.rmtree(app)
|
||||||
|
subprocess.run(['jpackage', '--type', 'app-image', '--name', app_name,
|
||||||
|
'--input', str(inputs), '--dest', str(work), '--main-jar', 'probe.jar',
|
||||||
|
'--main-class', main, '--mac-package-identifier', 'de.neitzel.datagrid.probe',
|
||||||
|
'--java-options', '--enable-native-access=ALL-UNNAMED',
|
||||||
|
'--java-options', '-Dneitzellib.nativeGridOutput=' + str(module / 'target/native-grid')], check=True)
|
||||||
|
print(app, flush=True)
|
||||||
|
raise SystemExit(subprocess.call([str(app / ('Contents/MacOS/' + app_name))]))
|
||||||
|
raise SystemExit(subprocess.call(['java', '--enable-native-access=ALL-UNNAMED', '-cp', classpath,
|
||||||
|
main], cwd=module.parent))
|
||||||
@@ -18,10 +18,13 @@ public final class IntegerSpinners {
|
|||||||
* @return an editable spinner
|
* @return an editable spinner
|
||||||
*/
|
*/
|
||||||
public static Spinner<Integer> nonNegative(int min, int max, int value) {
|
public static Spinner<Integer> nonNegative(int min, int max, int value) {
|
||||||
|
return new NonNegativeIntegerSpinner(min, max, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void configure(Spinner<Integer> spinner, int min, int max, int value) {
|
||||||
if (min < 0 || max < min || value < min || value > max) {
|
if (min < 0 || max < min || value < min || value > max) {
|
||||||
throw new IllegalArgumentException("Invalid nonnegative spinner bounds or value");
|
throw new IllegalArgumentException("Invalid nonnegative spinner bounds or value");
|
||||||
}
|
}
|
||||||
Spinner<Integer> spinner = new Spinner<>(min, max, value);
|
|
||||||
spinner.setEditable(true);
|
spinner.setEditable(true);
|
||||||
spinner.getEditor().setTextFormatter(new TextFormatter<String>(change -> {
|
spinner.getEditor().setTextFormatter(new TextFormatter<String>(change -> {
|
||||||
String text = change.getControlNewText();
|
String text = change.getControlNewText();
|
||||||
@@ -46,6 +49,5 @@ public final class IntegerSpinners {
|
|||||||
spinner.getEditor().setText(spinner.getValue().toString());
|
spinner.getEditor().setText(spinner.getValue().toString());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return spinner;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import javafx.beans.NamedArg;
|
||||||
|
import javafx.beans.property.ObjectProperty;
|
||||||
|
import javafx.scene.control.Spinner;
|
||||||
|
|
||||||
|
/** Bounded integer input available directly in FXML, including immediate valid typing. */
|
||||||
|
public final class NonNegativeIntegerSpinner extends Spinner<Integer> {
|
||||||
|
public NonNegativeIntegerSpinner(
|
||||||
|
@NamedArg(value = "minimum", defaultValue = "0") int minimum,
|
||||||
|
@NamedArg(value = "maximum", defaultValue = "2147483647") int maximum,
|
||||||
|
@NamedArg(value = "initialValue", defaultValue = "0") int initialValue) {
|
||||||
|
super(minimum, maximum, initialValue);
|
||||||
|
IntegerSpinners.configure(this, minimum, maximum, initialValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writable property for DirectBinding; Spinner.valueProperty itself is read-only. */
|
||||||
|
public ObjectProperty<Integer> numberProperty() {
|
||||||
|
return getValueFactory().valueProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getNumber() {
|
||||||
|
return numberProperty().get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNumber(Integer value) {
|
||||||
|
numberProperty().set(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,12 @@ import de.neitzel.fx.grid.filter.*;
|
|||||||
import de.neitzel.grid.*;
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.DefaultProperty;
|
||||||
import javafx.beans.property.*;
|
import javafx.beans.property.*;
|
||||||
|
import javafx.collections.*;
|
||||||
import javafx.scene.control.*;
|
import javafx.scene.control.*;
|
||||||
import javafx.scene.layout.*;
|
import javafx.scene.layout.*;
|
||||||
|
import javafx.scene.shape.SVGPath;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
@@ -18,22 +21,23 @@ import java.util.function.*;
|
|||||||
* load. The application owns the source and executor. Closing releases only this grid's requests
|
* load. The application owns the source and executor. Closing releases only this grid's requests
|
||||||
* and rows.
|
* and rows.
|
||||||
*/
|
*/
|
||||||
|
@DefaultProperty("columns")
|
||||||
public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
||||||
private final Table table = new Table();
|
private final Table table = new Table();
|
||||||
private final TableResults<K, T> renderer;
|
private TableResults<K, T> renderer;
|
||||||
private final GridCoordinator<K, T> coordinator;
|
private GridCoordinator<K, T> coordinator;
|
||||||
private final ReadOnlyObjectWrapper<GridCoordinator.State<K, T>> state =
|
private final ReadOnlyObjectWrapper<GridCoordinator.State<K, T>> state =
|
||||||
new ReadOnlyObjectWrapper<>();
|
new ReadOnlyObjectWrapper<>();
|
||||||
private final Label status = new Label("Not loaded");
|
private final Label status = new Label("Not loaded");
|
||||||
private final Button first = new Button("First"),
|
private final Button first = pagingButton("First page", "M0 0 H2 V14 H0 Z M4 7 L16 0 V14 Z"),
|
||||||
previous = new Button("Previous"),
|
previous = pagingButton("Previous page", "M2 7 L14 0 V14 Z"),
|
||||||
next = new Button("Next"),
|
next = pagingButton("Next page", "M2 0 L14 7 L2 14 Z"),
|
||||||
last = new Button("Last"),
|
last = pagingButton("Last page", "M0 0 L12 7 L0 14 Z M14 0 H16 V14 H14 Z"),
|
||||||
retry = new Button("Retry"),
|
retry = new Button("Retry"),
|
||||||
refresh = new Button("Refresh");
|
refresh = new Button("Refresh");
|
||||||
private final ComboBox<String> pageSize = new ComboBox<>();
|
private final ComboBox<String> pageSize = new ComboBox<>();
|
||||||
private final GridQuery initial;
|
private GridQuery initial;
|
||||||
private final List<ResultColumn> columnDefinitions;
|
private List<ResultColumn> columnDefinitions;
|
||||||
private GridDefinition setupDefinition;
|
private GridDefinition setupDefinition;
|
||||||
private Map<Integer, java.util.function.UnaryOperator<GridSetup>> setupMigrations = Map.of();
|
private Map<Integer, java.util.function.UnaryOperator<GridSetup>> setupMigrations = Map.of();
|
||||||
private final ReadOnlyObjectWrapper<List<String>> restorationAdjustments =
|
private final ReadOnlyObjectWrapper<List<String>> restorationAdjustments =
|
||||||
@@ -50,11 +54,201 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
private Alert pendingAlert;
|
private Alert pendingAlert;
|
||||||
private long alertGeneration;
|
private long alertGeneration;
|
||||||
|
|
||||||
|
private final HBox groupingBar = new HBox(8);
|
||||||
|
private final HBox filterSummary = new HBox(8);
|
||||||
|
private final Label activeFilters = new Label();
|
||||||
|
private final Label interactionStatus = new Label();
|
||||||
|
private final MenuButton setupMenu = new MenuButton("Grid setup");
|
||||||
|
private final ReadOnlyLongWrapper committedRevision = new ReadOnlyLongWrapper();
|
||||||
|
private List<String> defaultGrouping = List.of();
|
||||||
|
private GridSetup developerDefaults;
|
||||||
|
private boolean hasPublished, restoredPublication;
|
||||||
|
private GridQuery lastPublishedQuery;
|
||||||
|
private long restoreSerial, lastRestoredSerial;
|
||||||
|
private GridPersistenceAttachment<K, T> attachment;
|
||||||
|
private GridColumnSettings<K, T> columnSettings;
|
||||||
|
|
||||||
|
private static Button pagingButton(String name, String path) {
|
||||||
|
var button = new Button();
|
||||||
|
var icon = new SVGPath();
|
||||||
|
icon.setContent(path);
|
||||||
|
icon.fillProperty().bind(button.textFillProperty());
|
||||||
|
var graphic = new StackPane(icon);
|
||||||
|
graphic.setMinSize(18, 16);
|
||||||
|
graphic.setPrefSize(18, 16);
|
||||||
|
graphic.setMaxSize(18, 16);
|
||||||
|
graphic.setMouseTransparent(true);
|
||||||
|
button.setGraphic(graphic);
|
||||||
|
button.setMinSize(36, 30);
|
||||||
|
button.setAccessibleText(name);
|
||||||
|
button.setTooltip(new Tooltip(name));
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
|
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this);
|
||||||
|
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
|
||||||
|
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
|
||||||
|
|
||||||
|
/** Creates a query-free FXML control. Columns are visible before a source is attached. */
|
||||||
|
public DataGrid() {
|
||||||
|
requireFx();
|
||||||
|
getStyleClass().add("data-grid");
|
||||||
|
setSpacing(8);
|
||||||
|
getChildren().addAll(declaration.preview(), status);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObservableList<DataGridColumn> getColumns() {
|
||||||
|
return declaration.columns();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObjectProperty<ObservableList<T>> itemsProperty() {
|
||||||
|
return declaration.itemsProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObservableList<T> getItems() {
|
||||||
|
return itemsProperty().get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setItems(ObservableList<T> items) {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (getSource() != null) throw new IllegalStateException("Choose items or source");
|
||||||
|
itemsProperty().set(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridSource<K, T> getSource() {
|
||||||
|
return declaration.sourceProperty().get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObjectProperty<GridSource<K, T>> sourceProperty() {
|
||||||
|
return declaration.sourceProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Function<T, ResultRow> getRowFactory() {
|
||||||
|
return declaration.rowFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRowFactory(Function<T, ResultRow> factory) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.rowFactory = factory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Function<T, K> getKeyFactory() {
|
||||||
|
return declaration.keyFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setKeyFactory(Function<T, K> factory) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.keyFactory = factory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Comparator<K> getKeyComparator() {
|
||||||
|
return declaration.keyComparator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setKeyComparator(Comparator<K> comparator) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.keyComparator = comparator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getKeyAttribute() {
|
||||||
|
return declaration.keyAttribute;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setKeyAttribute(String attribute) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.keyAttribute = attribute;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSetupId() {
|
||||||
|
return declaration.setupId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSetupId(String id) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.setupId = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSetupVersion() {
|
||||||
|
return declaration.setupVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSetupVersion(int version) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.setupVersion = version;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getMaximumPageSize() {
|
||||||
|
return declaration.maximumPageSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMaximumPageSize(int size) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
if (size < 1) throw new IllegalArgumentException("Positive maximum page size required");
|
||||||
|
declaration.maximumPageSize = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getGroupBy() {
|
||||||
|
return declaration.groupBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupBy(String columns) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.groupBy = columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isGroupsCollapsed() {
|
||||||
|
return declaration.groupsCollapsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupsCollapsed(boolean collapsed) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
declaration.groupsCollapsed = collapsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getInactiveGroupHistoryLimit() {
|
||||||
|
return declaration.inactiveGroupHistoryLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInactiveGroupHistoryLimit(int limit) {
|
||||||
|
declaration.beforeOpen();
|
||||||
|
if (limit < 0) throw new IllegalArgumentException("Negative group history limit");
|
||||||
|
declaration.inactiveGroupHistoryLimit = limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Completes declarative configuration without executing a query. */
|
||||||
|
public void initialize() {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (coordinator == null) {
|
||||||
|
try {
|
||||||
|
declaration.open();
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
try {
|
||||||
|
close();
|
||||||
|
} catch (RuntimeException cleanup) {
|
||||||
|
failure.addSuppressed(cleanup);
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public DataGrid(
|
public DataGrid(
|
||||||
List<ResultColumn> columns,
|
List<ResultColumn> columns,
|
||||||
Function<T, ResultRow> rowFactory,
|
Function<T, ResultRow> rowFactory,
|
||||||
GridSource<K, T> source) {
|
GridSource<K, T> source) {
|
||||||
|
this();
|
||||||
|
declaration.setInitialSource(source);
|
||||||
|
initialize(columns, rowFactory, source);
|
||||||
|
}
|
||||||
|
|
||||||
|
void initialize(
|
||||||
|
List<ResultColumn> columns,
|
||||||
|
Function<T, ResultRow> rowFactory,
|
||||||
|
GridSource<K, T> source) {
|
||||||
requireFx();
|
requireFx();
|
||||||
|
getChildren().clear();
|
||||||
columnDefinitions = List.copyOf(columns);
|
columnDefinitions = List.copyOf(columns);
|
||||||
Objects.requireNonNull(source);
|
Objects.requireNonNull(source);
|
||||||
initial =
|
initial =
|
||||||
@@ -64,15 +258,14 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
new PageRequest.Paged(
|
new PageRequest.Paged(
|
||||||
0, Math.min(50, source.capabilities().maximumPageSize())));
|
0, Math.min(50, source.capabilities().maximumPageSize())));
|
||||||
renderer = table.openResults(columns, rowFactory);
|
renderer = table.openResults(columns, rowFactory);
|
||||||
|
renderer.enableColumnSeparators();
|
||||||
|
selectedKey.bind(renderer.selectedKeyProperty());
|
||||||
|
selectedElement.bind(renderer.selectedElementProperty());
|
||||||
coordinator =
|
coordinator =
|
||||||
new GridCoordinator<>(
|
new GridCoordinator<>(
|
||||||
source,
|
source, Platform::runLater, this::changed, result -> publishRows(result));
|
||||||
Platform::runLater,
|
|
||||||
this::changed,
|
|
||||||
result -> renderer.show(result.rows()));
|
|
||||||
coordinator.setConfirmation(this::confirmAll);
|
coordinator.setConfirmation(this::confirmAll);
|
||||||
renderer.setOnSortRequest(
|
renderer.setOnSortRequest(id -> {
|
||||||
id -> {
|
|
||||||
var q = query();
|
var q = query();
|
||||||
SortKey.Direction direction =
|
SortKey.Direction direction =
|
||||||
q.sort().size() == 1
|
q.sort().size() == 1
|
||||||
@@ -89,14 +282,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
last.setOnAction(e -> last());
|
last.setOnAction(e -> last());
|
||||||
retry.setOnAction(e -> coordinator.retry());
|
retry.setOnAction(e -> coordinator.retry());
|
||||||
refresh.setOnAction(e -> refresh());
|
refresh.setOnAction(e -> refresh());
|
||||||
pageSize.setOnAction(
|
pageSize.setOnAction(e -> {
|
||||||
e -> {
|
|
||||||
if (updating || pageSize.getValue() == null) return;
|
if (updating || pageSize.getValue() == null) return;
|
||||||
setPageRequest(
|
setPageRequest(
|
||||||
pageSize.getValue().equals("All")
|
pageSize.getValue().equals("All")
|
||||||
? new PageRequest.All()
|
? new PageRequest.All()
|
||||||
: new PageRequest.Paged(
|
: new PageRequest.Paged(0, Integer.parseInt(pageSize.getValue())));
|
||||||
0, Integer.parseInt(pageSize.getValue())));
|
|
||||||
});
|
});
|
||||||
status.setWrapText(true);
|
status.setWrapText(true);
|
||||||
status.getStyleClass().add("data-grid-status");
|
status.getStyleClass().add("data-grid-status");
|
||||||
@@ -112,9 +303,37 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
refresh,
|
refresh,
|
||||||
retry);
|
retry);
|
||||||
controls.getStyleClass().add("data-grid-paging");
|
controls.getStyleClass().add("data-grid-paging");
|
||||||
getStyleClass().add("data-grid");
|
renderer.setOnLayoutCommitted(this::layoutCommitted);
|
||||||
setSpacing(8);
|
renderer.setOnInteractionMessage(interactionStatus::setText);
|
||||||
getChildren().addAll(table, controls, status);
|
groupingBar.getStyleClass().add("data-grid-grouping");
|
||||||
|
groupingBar.setAccessibleText("Grouping columns");
|
||||||
|
groupingBar.setFocusTraversable(true);
|
||||||
|
groupingBar.setVisible(false);
|
||||||
|
groupingBar.setManaged(false);
|
||||||
|
renderer.gestures().groupTarget(groupingBar);
|
||||||
|
MenuItem columnsItem = new MenuItem("Column settings…");
|
||||||
|
columnsItem.setOnAction(e -> {
|
||||||
|
if (columnSettings != null) columnSettings.close();
|
||||||
|
columnSettings = new GridColumnSettings<>(this, renderer);
|
||||||
|
columnSettings.show();
|
||||||
|
});
|
||||||
|
MenuItem resetExpansion = new MenuItem("Reset expansion");
|
||||||
|
resetExpansion.setOnAction(e -> resetExpansion());
|
||||||
|
MenuItem clearFilters = new MenuItem("Clear filters");
|
||||||
|
clearFilters.setOnAction(e -> setFilters(List.of()));
|
||||||
|
setupMenu.getItems().addAll(columnsItem, resetExpansion, clearFilters);
|
||||||
|
controls.getChildren().add(setupMenu);
|
||||||
|
interactionStatus.setWrapText(true);
|
||||||
|
interactionStatus.getStyleClass().add("data-grid-interaction-status");
|
||||||
|
var css = DataGrid.class.getResource("data-grid.css");
|
||||||
|
if (css != null) getStylesheets().add(css.toExternalForm());
|
||||||
|
Button clearActiveFilters = new Button("Clear filters");
|
||||||
|
clearActiveFilters.setOnAction(e -> setFilters(List.of()));
|
||||||
|
filterSummary.getChildren().addAll(activeFilters, clearActiveFilters);
|
||||||
|
filterSummary.setVisible(false);
|
||||||
|
filterSummary.setManaged(false);
|
||||||
|
getChildren()
|
||||||
|
.addAll(groupingBar, table, filterSummary, controls, status, interactionStatus);
|
||||||
VBox.setVgrow(table, Priority.ALWAYS);
|
VBox.setVgrow(table, Priority.ALWAYS);
|
||||||
state.set(coordinator.state());
|
state.set(coordinator.state());
|
||||||
updateControls(coordinator.state());
|
updateControls(coordinator.state());
|
||||||
@@ -125,11 +344,11 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
|
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
|
||||||
return renderer.selectedKeyProperty();
|
return selectedKey.getReadOnlyProperty();
|
||||||
}
|
}
|
||||||
|
|
||||||
public ReadOnlyObjectProperty<T> selectedElementProperty() {
|
public ReadOnlyObjectProperty<T> selectedElementProperty() {
|
||||||
return renderer.selectedElementProperty();
|
return selectedElement.getReadOnlyProperty();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void select(K key) {
|
public void select(K key) {
|
||||||
@@ -191,6 +410,15 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void setSource(GridSource<K, T> source) {
|
public void setSource(GridSource<K, T> source) {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (getItems() != null) throw new IllegalStateException("Choose items or source");
|
||||||
|
Objects.requireNonNull(source);
|
||||||
|
if (coordinator != null && source == getSource()) replaceSource(source);
|
||||||
|
else sourceProperty().set(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
void replaceSource(GridSource<K, T> source) {
|
||||||
check();
|
check();
|
||||||
closeFilter();
|
closeFilter();
|
||||||
var q = query();
|
var q = query();
|
||||||
@@ -220,8 +448,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
id,
|
id,
|
||||||
version,
|
version,
|
||||||
columnDefinitions.stream()
|
columnDefinitions.stream()
|
||||||
.map(
|
.map(c ->
|
||||||
c ->
|
|
||||||
new GridDefinition.Column(
|
new GridDefinition.Column(
|
||||||
c.id(),
|
c.id(),
|
||||||
types.get(c.id()),
|
types.get(c.id()),
|
||||||
@@ -247,18 +474,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
Map<String, String> types = new HashMap<>();
|
Map<String, String> types = new HashMap<>();
|
||||||
setupDefinition.columns().forEach(c -> types.put(c.id(), c.type()));
|
setupDefinition.columns().forEach(c -> types.put(c.id(), c.type()));
|
||||||
return new GridSetup(
|
return new GridSetup(
|
||||||
1,
|
2,
|
||||||
setupDefinition.id(),
|
setupDefinition.id(),
|
||||||
setupDefinition.version(),
|
setupDefinition.version(),
|
||||||
renderer.columnOrder().stream()
|
renderer.columnOrder().stream()
|
||||||
.map(
|
.map(id ->
|
||||||
id ->
|
|
||||||
new GridSetup.ColumnState(
|
new GridSetup.ColumnState(
|
||||||
id, types.get(id), renderer.columnWidths().get(id)))
|
id, types.get(id), renderer.columnWidths().get(id)))
|
||||||
.toList(),
|
.toList(),
|
||||||
committed.sort(),
|
committed.sort(),
|
||||||
committed.filters(),
|
committed.filters(),
|
||||||
firstPage(committed.page()));
|
firstPage(committed.page()),
|
||||||
|
renderer.groupingSetup());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ReadOnlyObjectProperty<List<String>> restorationAdjustmentsProperty() {
|
public ReadOnlyObjectProperty<List<String>> restorationAdjustmentsProperty() {
|
||||||
@@ -287,6 +514,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
coordinator.capabilities(),
|
coordinator.capabilities(),
|
||||||
condition -> coordinator.validateFilters(List.of(condition)));
|
condition -> coordinator.validateFilters(List.of(condition)));
|
||||||
var setup = prepared.setup();
|
var setup = prepared.setup();
|
||||||
|
var grouping =
|
||||||
|
setup.grouping() == null
|
||||||
|
? new GroupingSetup(defaultGrouping, List.of())
|
||||||
|
: setup.grouping();
|
||||||
|
renderer.validateGrouping(grouping);
|
||||||
|
long serial = restoreSerial;
|
||||||
Map<String, ColumnWidth> widths = new LinkedHashMap<>();
|
Map<String, ColumnWidth> widths = new LinkedHashMap<>();
|
||||||
setup.columns().forEach(c -> widths.put(c.id(), c.width()));
|
setup.columns().forEach(c -> widths.put(c.id(), c.width()));
|
||||||
coordinator.restoreSetup(
|
coordinator.restoreSetup(
|
||||||
@@ -296,7 +529,11 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
renderer.show(
|
renderer.show(
|
||||||
result.rows(),
|
result.rows(),
|
||||||
setup.columns().stream().map(GridSetup.ColumnState::id).toList(),
|
setup.columns().stream().map(GridSetup.ColumnState::id).toList(),
|
||||||
widths);
|
widths,
|
||||||
|
grouping);
|
||||||
|
lastRestoredSerial = serial;
|
||||||
|
restoredPublication = true;
|
||||||
|
drawGroupingBar();
|
||||||
restorationAdjustments.set(prepared.adjustments());
|
restorationAdjustments.set(prepared.adjustments());
|
||||||
});
|
});
|
||||||
} catch (RuntimeException error) {
|
} catch (RuntimeException error) {
|
||||||
@@ -431,10 +668,29 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
firstPage(q.page())));
|
firstPage(q.page())));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int getPageSize() {
|
||||||
|
return coordinator == null
|
||||||
|
? declaration.pageSize
|
||||||
|
: query().page() instanceof PageRequest.Paged page ? page.pageSize() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
public void setPageSize(int size) {
|
public void setPageSize(int size) {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (size < 1) throw new IllegalArgumentException("Positive page size required");
|
||||||
|
if (coordinator == null) {
|
||||||
|
declaration.pageSize = size;
|
||||||
|
return;
|
||||||
|
}
|
||||||
setPageRequest(new PageRequest.Paged(0, size));
|
setPageRequest(new PageRequest.Paged(0, size));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void setInitialPageSize(int size) {
|
||||||
|
coordinator.capabilities().validate(new PageRequest.Paged(0, size));
|
||||||
|
initial = new GridQuery(initial.filters(), initial.sort(), new PageRequest.Paged(0, size));
|
||||||
|
updateControls(coordinator.state());
|
||||||
|
}
|
||||||
|
|
||||||
public void showAll() {
|
public void showAll() {
|
||||||
setPageRequest(new PageRequest.All());
|
setPageRequest(new PageRequest.All());
|
||||||
}
|
}
|
||||||
@@ -502,11 +758,13 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
pseudoClassStateChanged(
|
pseudoClassStateChanged(
|
||||||
javafx.css.PseudoClass.getPseudoClass("error"),
|
javafx.css.PseudoClass.getPseudoClass("error"),
|
||||||
value.phase() == GridCoordinator.Phase.ERROR);
|
value.phase() == GridCoordinator.Phase.ERROR);
|
||||||
if (value.displayed() != null)
|
if (value.displayed() != null) {
|
||||||
renderer.setFilteredColumns(
|
renderer.setFilteredColumns(
|
||||||
value.displayed().filters().stream()
|
value.displayed().filters().stream()
|
||||||
.map(FilterCondition::columnId)
|
.map(FilterCondition::columnId)
|
||||||
.collect(java.util.stream.Collectors.toSet()));
|
.collect(java.util.stream.Collectors.toSet()));
|
||||||
|
renderer.setSortKeys(value.displayed().sort());
|
||||||
|
}
|
||||||
if (visibleSourceVersion != value.sourceVersion()) {
|
if (visibleSourceVersion != value.sourceVersion()) {
|
||||||
visibleSourceVersion = value.sourceVersion();
|
visibleSourceVersion = value.sourceVersion();
|
||||||
renderer.select(null);
|
renderer.select(null);
|
||||||
@@ -515,6 +773,18 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
updateControls(value);
|
updateControls(value);
|
||||||
}
|
}
|
||||||
state.set(value);
|
state.set(value);
|
||||||
|
if (!closed && value.phase() == GridCoordinator.Phase.READY) {
|
||||||
|
GridQuery published =
|
||||||
|
new GridQuery(
|
||||||
|
value.displayed().filters(),
|
||||||
|
value.displayed().sort(),
|
||||||
|
firstPage(value.displayed().page()));
|
||||||
|
boolean changedQuery = hasPublished && !Objects.equals(published, lastPublishedQuery);
|
||||||
|
hasPublished = true;
|
||||||
|
lastPublishedQuery = published;
|
||||||
|
if (changedQuery && !restoredPublication) fireCommitted();
|
||||||
|
restoredPublication = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void updateControls(GridCoordinator.State<K, T> s) {
|
private void updateControls(GridCoordinator.State<K, T> s) {
|
||||||
@@ -592,7 +862,27 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
yield pageLabel(requested.page()) + " — total unknown";
|
yield pageLabel(requested.page()) + " — total unknown";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
status.setText(message);
|
List<String> filtered =
|
||||||
|
s.displayed() == null
|
||||||
|
? List.of()
|
||||||
|
: s.displayed().filters().stream()
|
||||||
|
.map(f ->
|
||||||
|
columnDefinitions.stream()
|
||||||
|
.filter(c -> c.id().equals(f.columnId()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.header())
|
||||||
|
.toList();
|
||||||
|
activeFilters.setText("Active filters: " + String.join(", ", filtered));
|
||||||
|
filterSummary.setVisible(!filtered.isEmpty());
|
||||||
|
filterSummary.setManaged(!filtered.isEmpty());
|
||||||
|
status.setText(
|
||||||
|
message
|
||||||
|
+ (renderer.groupingEnabled() && !renderer.groupingColumns().isEmpty()
|
||||||
|
? (requested.page() instanceof PageRequest.All
|
||||||
|
? " · Grouping loaded result"
|
||||||
|
: " · Grouping current page")
|
||||||
|
: ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String pageLabel(PageRequest page) {
|
private static String pageLabel(PageRequest page) {
|
||||||
@@ -617,8 +907,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
alert.initOwner(getScene().getWindow());
|
alert.initOwner(getScene().getWindow());
|
||||||
pendingAlert = alert;
|
pendingAlert = alert;
|
||||||
alertGeneration = coordinator.state().generation();
|
alertGeneration = coordinator.state().generation();
|
||||||
alert.setOnHidden(
|
alert.setOnHidden(e -> {
|
||||||
e -> {
|
|
||||||
if (pendingAlert == alert) pendingAlert = null;
|
if (pendingAlert == alert) pendingAlert = null;
|
||||||
answer.complete(alert.getResult() == proceed);
|
answer.complete(alert.getResult() == proceed);
|
||||||
});
|
});
|
||||||
@@ -626,6 +915,271 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
return answer;
|
return answer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> loadAsync() {
|
||||||
|
return awaitOperation(this::load, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> restoreSetupAsync(GridSetup setup) {
|
||||||
|
long serial = ++restoreSerial;
|
||||||
|
return awaitOperation(() -> restoreSetup(setup), serial);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletionStage<Void> awaitOperation(Runnable action, long serial) {
|
||||||
|
check();
|
||||||
|
action.run();
|
||||||
|
long generation = coordinator.state().generation();
|
||||||
|
CompletableFuture<Void> future = new CompletableFuture<>();
|
||||||
|
javafx.beans.value.ChangeListener<GridCoordinator.State<K, T>> listener =
|
||||||
|
(observable, before, value) -> {
|
||||||
|
if (value.generation() != generation
|
||||||
|
|| value.phase() == GridCoordinator.Phase.CLOSED)
|
||||||
|
future.completeExceptionally(
|
||||||
|
new CancellationException("Grid operation superseded"));
|
||||||
|
else if (value.phase() == GridCoordinator.Phase.ERROR)
|
||||||
|
future.completeExceptionally(value.error());
|
||||||
|
else if (value.phase() == GridCoordinator.Phase.READY) {
|
||||||
|
if (serial < 0 || lastRestoredSerial == serial) future.complete(null);
|
||||||
|
else
|
||||||
|
future.completeExceptionally(
|
||||||
|
new CancellationException("Restore declined"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
state.addListener(listener);
|
||||||
|
future.whenComplete((ok, error) -> state.removeListener(listener));
|
||||||
|
listener.changed(state, state.get(), state.get());
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
|
||||||
|
GridSetup developerDefaults() {
|
||||||
|
return developerDefaults == null ? snapshotSetup() : developerDefaults;
|
||||||
|
}
|
||||||
|
|
||||||
|
void cancelOwnedRestore(long generation) {
|
||||||
|
if (!closed && state.get().generation() == generation) coordinator.cancelRestore();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ReadOnlyLongProperty committedRevisionProperty() {
|
||||||
|
return committedRevision.getReadOnlyProperty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> groupingColumns() {
|
||||||
|
return renderer.groupingColumns();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean groupingEnabled() {
|
||||||
|
return renderer.groupingEnabled();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void configureGrouping(
|
||||||
|
List<GroupColumn<T>> columns,
|
||||||
|
boolean enabled,
|
||||||
|
List<String> defaults,
|
||||||
|
boolean collapsed,
|
||||||
|
int inactiveHistoryLimit) {
|
||||||
|
check();
|
||||||
|
renderer.configureGrouping(columns, enabled, defaults, collapsed, inactiveHistoryLimit);
|
||||||
|
defaultGrouping = List.copyOf(defaults);
|
||||||
|
developerDefaults = null;
|
||||||
|
drawGroupingBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupingColumns(List<String> columns) {
|
||||||
|
check();
|
||||||
|
closeFilter();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
try {
|
||||||
|
renderer.setGroupingColumns(columns);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
interactionStatus.setText("Cannot change grouping: " + failure.getMessage());
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isGroupingEnabled() {
|
||||||
|
return coordinator == null ? declaration.groupingEnabled : groupingEnabled();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupingEnabled(boolean enabled) {
|
||||||
|
requireFx();
|
||||||
|
if (coordinator == null) {
|
||||||
|
declaration.groupingEnabled = enabled;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
check();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
renderer.setGroupingEnabled(enabled);
|
||||||
|
drawGroupingBar();
|
||||||
|
updateControls(coordinator.state());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetExpansion() {
|
||||||
|
check();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
renderer.resetExpansion();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExpanded(GroupPath path, boolean expanded) {
|
||||||
|
check();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
renderer.setExpanded(path, expanded);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void regroup() {
|
||||||
|
check();
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
try {
|
||||||
|
renderer.regroup();
|
||||||
|
interactionStatus.setText("");
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
interactionStatus.setText("Cannot update grouping: " + failure.getMessage());
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void publishRows(PageResult<K, T> result) {
|
||||||
|
renderer.show(result.rows());
|
||||||
|
drawGroupingBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void layoutCommitted() {
|
||||||
|
if (closed) return;
|
||||||
|
coordinator.cancelRestore();
|
||||||
|
drawGroupingBar();
|
||||||
|
updateControls(coordinator.state());
|
||||||
|
fireCommitted();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fireCommitted() {
|
||||||
|
committedRevision.set(committedRevision.get() + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawGroupingBar() {
|
||||||
|
groupingBar.setVisible(renderer.groupingEnabled());
|
||||||
|
groupingBar.setManaged(renderer.groupingEnabled());
|
||||||
|
NodeFocus focus = new NodeFocus(groupingBar);
|
||||||
|
groupingBar.getChildren().clear();
|
||||||
|
if (renderer.groupingColumns().isEmpty())
|
||||||
|
groupingBar
|
||||||
|
.getChildren()
|
||||||
|
.add(new Label("Drag a column here to group the current page"));
|
||||||
|
for (String id : renderer.groupingColumns()) {
|
||||||
|
String label =
|
||||||
|
columnDefinitions.stream()
|
||||||
|
.filter(c -> c.id().equals(id))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.header();
|
||||||
|
Label text = new Label(label);
|
||||||
|
Button remove = new Button("×");
|
||||||
|
remove.setAccessibleText("Remove grouping by " + label);
|
||||||
|
remove.setOnAction(e ->
|
||||||
|
setGroupingColumns(
|
||||||
|
renderer.groupingColumns().stream()
|
||||||
|
.filter(c -> !c.equals(id))
|
||||||
|
.toList()));
|
||||||
|
remove.addEventHandler(
|
||||||
|
javafx.scene.input.MouseEvent.DRAG_DETECTED, javafx.event.Event::consume);
|
||||||
|
HBox chip = new HBox(6, text, remove);
|
||||||
|
chip.getStyleClass().add("grouping-chip");
|
||||||
|
chip.setAccessibleText(
|
||||||
|
"Grouping level " + (groupingBar.getChildren().size() + 1) + ": " + label);
|
||||||
|
chip.setFocusTraversable(true);
|
||||||
|
renderer.gestures().chip(chip, id);
|
||||||
|
groupingBar.getChildren().add(chip);
|
||||||
|
}
|
||||||
|
focus.restore(groupingBar);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class NodeFocus {
|
||||||
|
private final boolean inside;
|
||||||
|
|
||||||
|
NodeFocus(javafx.scene.Parent parent) {
|
||||||
|
javafx.scene.Node focus =
|
||||||
|
parent.getScene() == null ? null : parent.getScene().getFocusOwner();
|
||||||
|
boolean found = false;
|
||||||
|
for (var node = focus; node != null; node = node.getParent())
|
||||||
|
if (node == parent) found = true;
|
||||||
|
inside = found;
|
||||||
|
}
|
||||||
|
|
||||||
|
void restore(javafx.scene.Parent parent) {
|
||||||
|
if (inside) parent.requestFocus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure defaults without fetching. Call after column/group definitions, before
|
||||||
|
* attachment/load.
|
||||||
|
*/
|
||||||
|
public void configureDefaults(GridSetup defaults) {
|
||||||
|
check();
|
||||||
|
if (hasPublished || attachment != null || state.get().phase() != GridCoordinator.Phase.IDLE)
|
||||||
|
throw new IllegalStateException("Configure defaults before attachment or loading");
|
||||||
|
if (setupDefinition == null)
|
||||||
|
throw new IllegalStateException("Configure the grid definition first");
|
||||||
|
var prepared =
|
||||||
|
setupDefinition
|
||||||
|
.prepare(
|
||||||
|
defaults,
|
||||||
|
setupMigrations,
|
||||||
|
coordinator.capabilities(),
|
||||||
|
condition -> coordinator.validateFilters(List.of(condition)))
|
||||||
|
.setup();
|
||||||
|
var groups =
|
||||||
|
prepared.grouping() == null
|
||||||
|
? new GroupingSetup(defaultGrouping, List.of())
|
||||||
|
: prepared.grouping();
|
||||||
|
renderer.validateGrouping(groups);
|
||||||
|
var widths = new LinkedHashMap<String, ColumnWidth>();
|
||||||
|
prepared.columns().forEach(c -> widths.put(c.id(), c.width()));
|
||||||
|
renderer.show(
|
||||||
|
List.of(),
|
||||||
|
prepared.columns().stream().map(GridSetup.ColumnState::id).toList(),
|
||||||
|
widths,
|
||||||
|
groups);
|
||||||
|
initial = new GridQuery(prepared.filters(), prepared.sort(), firstPage(prepared.page()));
|
||||||
|
defaultGrouping = groups.columns();
|
||||||
|
developerDefaults = snapshotSetup();
|
||||||
|
drawGroupingBar();
|
||||||
|
updateControls(coordinator.state());
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridSetup defaultSetup() {
|
||||||
|
check();
|
||||||
|
if (developerDefaults == null) developerDefaults = snapshotSetup();
|
||||||
|
return developerDefaults;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridPersistenceAttachment<K, T> attachPersistence(
|
||||||
|
GridApplicationConfiguration config, String gridId) {
|
||||||
|
return attachPersistence(config, gridId, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridPersistenceAttachment<K, T> attachPersistence(
|
||||||
|
GridApplicationConfiguration config, String gridId, String context) {
|
||||||
|
check();
|
||||||
|
if (attachment != null) throw new IllegalStateException("Persistence already attached");
|
||||||
|
if (developerDefaults == null) developerDefaults = snapshotSetup();
|
||||||
|
attachment =
|
||||||
|
new GridPersistenceAttachment<>(
|
||||||
|
this, config, new GridSetupStore.Key(gridId, context));
|
||||||
|
return attachment;
|
||||||
|
}
|
||||||
|
|
||||||
|
void addPersistenceControls(javafx.scene.Node feedback, List<MenuItem> items) {
|
||||||
|
getChildren().add(feedback);
|
||||||
|
setupMenu.getItems().addAll(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
void removePersistenceControls(javafx.scene.Node feedback, List<MenuItem> items) {
|
||||||
|
getChildren().remove(feedback);
|
||||||
|
setupMenu.getItems().removeAll(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
void detached(GridPersistenceAttachment<K, T> handle) {
|
||||||
|
if (attachment == handle) attachment = null;
|
||||||
|
}
|
||||||
|
|
||||||
private static void requireFx() {
|
private static void requireFx() {
|
||||||
if (!Platform.isFxApplicationThread())
|
if (!Platform.isFxApplicationThread())
|
||||||
throw new IllegalStateException("Use the JavaFX application thread");
|
throw new IllegalStateException("Use the JavaFX application thread");
|
||||||
@@ -634,19 +1188,49 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
private void check() {
|
private void check() {
|
||||||
requireFx();
|
requireFx();
|
||||||
if (closed) throw new IllegalStateException("Grid is closed");
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
void refreshItems() {
|
||||||
|
if (coordinator == null
|
||||||
|
|| closed
|
||||||
|
|| coordinator.state().phase() == GridCoordinator.Phase.IDLE) return;
|
||||||
|
if (attachment != null) {
|
||||||
|
var ready = attachment.ready().toCompletableFuture();
|
||||||
|
if (!ready.isDone() || ready.isCompletedExceptionally()) return;
|
||||||
|
}
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isInitialized() {
|
||||||
|
return coordinator != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isClosed() {
|
||||||
|
return closed;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void close() {
|
public void close() {
|
||||||
requireFx();
|
requireFx();
|
||||||
if (closed) return;
|
if (closed) return;
|
||||||
|
if (columnSettings != null) {
|
||||||
|
columnSettings.close();
|
||||||
|
columnSettings = null;
|
||||||
|
}
|
||||||
|
if (attachment != null) attachment.close();
|
||||||
closed = true;
|
closed = true;
|
||||||
closeFilter();
|
closeFilter();
|
||||||
coordinator.close();
|
declaration.close();
|
||||||
|
if (coordinator != null) coordinator.close();
|
||||||
if (pendingAlert != null) {
|
if (pendingAlert != null) {
|
||||||
pendingAlert.close();
|
pendingAlert.close();
|
||||||
pendingAlert = null;
|
pendingAlert = null;
|
||||||
}
|
}
|
||||||
renderer.close();
|
if (renderer != null) renderer.close();
|
||||||
|
selectedKey.unbind();
|
||||||
|
selectedElement.unbind();
|
||||||
|
selectedKey.set(null);
|
||||||
|
selectedElement.set(null);
|
||||||
getChildren().clear();
|
getChildren().clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.grid.filter.FilterColumn;
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
/** Declarative column shared by rendering, local queries, filters, grouping and saved setups. */
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public final class DataGridColumn {
|
||||||
|
private String id;
|
||||||
|
private String header;
|
||||||
|
private String attribute;
|
||||||
|
private String groupAttribute;
|
||||||
|
|
||||||
|
@Setter(lombok.AccessLevel.NONE)
|
||||||
|
private final java.util.Map<String, String> groupLabels = new java.util.LinkedHashMap<>();
|
||||||
|
|
||||||
|
private double width = 150;
|
||||||
|
private double minimumWidth = 80;
|
||||||
|
private double maximumWidth = 1200;
|
||||||
|
private int fixedPosition = -1;
|
||||||
|
private MemoryColumn.Kind kind = MemoryColumn.Kind.TEXT;
|
||||||
|
private boolean filterable = true;
|
||||||
|
private FilterColumn.Checklist checklist = FilterColumn.Checklist.DISABLED;
|
||||||
|
private FilterCandidates.Provider candidates;
|
||||||
|
private String type;
|
||||||
|
|
||||||
|
ResultColumn definition() {
|
||||||
|
if (kind == null || checklist == null)
|
||||||
|
throw new IllegalArgumentException("Column kind and checklist are required");
|
||||||
|
return new ResultColumn(id, header, width, minimumWidth, maximumWidth, fixedPosition);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object getValue(Object row) {
|
||||||
|
return read(row, attribute == null ? id : attribute);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Object read(Object row, String attribute) {
|
||||||
|
if (row == null) return null;
|
||||||
|
if (attribute == null || attribute.isBlank())
|
||||||
|
throw new IllegalArgumentException("Missing row attribute");
|
||||||
|
String suffix = Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1);
|
||||||
|
for (String name : new String[] {"get" + suffix, "is" + suffix, attribute}) {
|
||||||
|
try {
|
||||||
|
return row.getClass().getMethod(name).invoke(row);
|
||||||
|
} catch (NoSuchMethodException absent) {
|
||||||
|
// JavaBeans and record-style scalar accessors are both supported.
|
||||||
|
} catch (IllegalAccessException | InvocationTargetException error) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Could not read row attribute " + attribute, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"No row attribute " + attribute + " on " + row.getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
FilterValue groupValue(Object row) {
|
||||||
|
return scalar(groupAttribute == null ? getValue(row) : read(row, groupAttribute));
|
||||||
|
}
|
||||||
|
|
||||||
|
String groupLabel(FilterValue value) {
|
||||||
|
String display = GroupColumn.display(value);
|
||||||
|
return groupLabels.getOrDefault(display, display);
|
||||||
|
}
|
||||||
|
|
||||||
|
FilterValue value(Object row) {
|
||||||
|
return scalar(getValue(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
private FilterValue scalar(Object value) {
|
||||||
|
if (value == null) return null;
|
||||||
|
return switch (kind) {
|
||||||
|
case TEXT -> new FilterValue.Text(value.toString());
|
||||||
|
case INTEGER ->
|
||||||
|
new FilterValue.IntegerValue(new BigDecimal(value.toString()).longValueExact());
|
||||||
|
case DECIMAL -> new FilterValue.Decimal(new BigDecimal(value.toString()));
|
||||||
|
case BOOLEAN -> {
|
||||||
|
if (!(value instanceof Boolean bool))
|
||||||
|
throw new IllegalArgumentException("Boolean value required for " + id);
|
||||||
|
yield new FilterValue.BooleanValue(bool);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
String schemaType() {
|
||||||
|
return type == null
|
||||||
|
? "neitzel." + kind.name().toLowerCase(java.util.Locale.ROOT) + ".v1"
|
||||||
|
: type;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.grid.filter.FilterColumn;
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.property.*;
|
||||||
|
import javafx.collections.*;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.function.*;
|
||||||
|
|
||||||
|
/** FXML construction and owned local-source lifetime, separate from query coordination. */
|
||||||
|
final class DataGridDeclaration<K, T> implements AutoCloseable {
|
||||||
|
private final DataGrid<K, T> grid;
|
||||||
|
private final ObservableList<DataGridColumn> columns = FXCollections.observableArrayList();
|
||||||
|
private final ObjectProperty<ObservableList<T>> items = new SimpleObjectProperty<>();
|
||||||
|
private final ObjectProperty<GridSource<K, T>> source = new SimpleObjectProperty<>();
|
||||||
|
private final HBox preview = new HBox();
|
||||||
|
private final ListChangeListener<T> itemsChanged = change -> changedItems();
|
||||||
|
private ExecutorService executor;
|
||||||
|
private boolean external;
|
||||||
|
private boolean assigningInitialSource;
|
||||||
|
Function<T, ResultRow> rowFactory;
|
||||||
|
Function<T, K> keyFactory;
|
||||||
|
Comparator<K> keyComparator;
|
||||||
|
String keyAttribute;
|
||||||
|
String setupId;
|
||||||
|
int setupVersion = 1;
|
||||||
|
int pageSize = 50;
|
||||||
|
int maximumPageSize = 250;
|
||||||
|
boolean groupingEnabled;
|
||||||
|
String groupBy = "";
|
||||||
|
boolean groupsCollapsed;
|
||||||
|
int inactiveGroupHistoryLimit = 1000;
|
||||||
|
|
||||||
|
DataGridDeclaration(DataGrid<K, T> grid) {
|
||||||
|
this.grid = grid;
|
||||||
|
preview.getStyleClass().add("data-grid-preview-header");
|
||||||
|
columns.addListener(
|
||||||
|
(ListChangeListener<DataGridColumn>)
|
||||||
|
change -> {
|
||||||
|
beforeOpen();
|
||||||
|
preview.getChildren().clear();
|
||||||
|
for (var column : columns) {
|
||||||
|
var label = new Label(column.getHeader());
|
||||||
|
label.setPrefWidth(column.getWidth());
|
||||||
|
label.getStyleClass().add("column-header");
|
||||||
|
preview.getChildren().add(label);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
items.addListener((observable, previous, current) -> {
|
||||||
|
requireFx();
|
||||||
|
if (grid.isClosed()) throw new IllegalStateException("Grid is closed");
|
||||||
|
if (external && grid.isInitialized())
|
||||||
|
throw new IllegalStateException("External sources cannot use items");
|
||||||
|
if (previous != null) previous.removeListener(itemsChanged);
|
||||||
|
if (current != null) current.addListener(itemsChanged);
|
||||||
|
changedItems();
|
||||||
|
});
|
||||||
|
source.addListener((observable, previous, current) -> {
|
||||||
|
requireFx();
|
||||||
|
if (assigningInitialSource) return;
|
||||||
|
if (grid.isClosed()) throw new IllegalStateException("Grid is closed");
|
||||||
|
Objects.requireNonNull(current, "Missing source");
|
||||||
|
if (items.get() != null) throw new IllegalStateException("Choose items or source");
|
||||||
|
if (grid.isInitialized()) {
|
||||||
|
external = true;
|
||||||
|
grid.replaceSource(current);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void setInitialSource(GridSource<K, T> value) {
|
||||||
|
assigningInitialSource = true;
|
||||||
|
try {
|
||||||
|
source.set(Objects.requireNonNull(value));
|
||||||
|
external = true;
|
||||||
|
} finally {
|
||||||
|
assigningInitialSource = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ObservableList<DataGridColumn> columns() {
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjectProperty<ObservableList<T>> itemsProperty() {
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjectProperty<GridSource<K, T>> sourceProperty() {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
|
HBox preview() {
|
||||||
|
return preview;
|
||||||
|
}
|
||||||
|
|
||||||
|
void beforeOpen() {
|
||||||
|
requireFx();
|
||||||
|
if (grid.isClosed() || grid.isInitialized())
|
||||||
|
throw new IllegalStateException("Configure before initializing the grid");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void requireFx() {
|
||||||
|
if (!Platform.isFxApplicationThread())
|
||||||
|
throw new IllegalStateException("Use the JavaFX application thread");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void changedItems() {
|
||||||
|
requireFx();
|
||||||
|
grid.refreshItems();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void open() {
|
||||||
|
var definitions = columns.stream().map(DataGridColumn::definition).toList();
|
||||||
|
if (definitions.isEmpty())
|
||||||
|
throw new IllegalArgumentException("Declare DataGrid columns before loading");
|
||||||
|
if (definitions.stream().map(ResultColumn::id).distinct().count() != definitions.size())
|
||||||
|
throw new IllegalArgumentException("Duplicate DataGrid column ID");
|
||||||
|
GridSource<K, T> configured = source.get();
|
||||||
|
MemoryGridSource<K, T> memory = null;
|
||||||
|
if (configured == null) {
|
||||||
|
if (keyFactory == null && (keyAttribute == null || keyAttribute.isBlank()))
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Local DataGrid requires keyAttribute or keyFactory");
|
||||||
|
Function<T, K> key =
|
||||||
|
keyFactory != null
|
||||||
|
? keyFactory
|
||||||
|
: row -> (K) DataGridColumn.read(row, keyAttribute);
|
||||||
|
Comparator<K> order =
|
||||||
|
keyComparator != null
|
||||||
|
? keyComparator
|
||||||
|
: (a, b) -> {
|
||||||
|
if (!(a instanceof Comparable<?>))
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Row keys require a comparator");
|
||||||
|
return ((Comparable<Object>) a).compareTo(b);
|
||||||
|
};
|
||||||
|
executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||||
|
memory =
|
||||||
|
new MemoryGridSource<>(
|
||||||
|
() -> items.get() == null ? List.of() : items.get(),
|
||||||
|
key,
|
||||||
|
order,
|
||||||
|
columns.stream()
|
||||||
|
.map(c -> new MemoryColumn<T>(c.getId(), c.getKind(), c::value))
|
||||||
|
.toList(),
|
||||||
|
executor,
|
||||||
|
maximumPageSize);
|
||||||
|
configured = memory;
|
||||||
|
} else {
|
||||||
|
if (items.get() != null) throw new IllegalArgumentException("Choose items or source");
|
||||||
|
external = true;
|
||||||
|
}
|
||||||
|
configured.capabilities().validate(new PageRequest.Paged(0, pageSize));
|
||||||
|
grid.initialize(definitions, rowFactory == null ? this::render : rowFactory, configured);
|
||||||
|
grid.setInitialPageSize(pageSize);
|
||||||
|
for (var column : columns) {
|
||||||
|
if (!column.isFilterable()) continue;
|
||||||
|
FilterColumn filter =
|
||||||
|
switch (column.getKind()) {
|
||||||
|
case TEXT -> FilterColumn.text();
|
||||||
|
case INTEGER, DECIMAL ->
|
||||||
|
FilterColumn.number(
|
||||||
|
Locale.getDefault(),
|
||||||
|
column.getKind() == MemoryColumn.Kind.INTEGER,
|
||||||
|
null,
|
||||||
|
null);
|
||||||
|
case BOOLEAN -> null;
|
||||||
|
};
|
||||||
|
if (filter == null) {
|
||||||
|
if (column.getChecklist() != FilterColumn.Checklist.DISABLED)
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Boolean filter editor is not available; set filterable=false");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
var candidates = column.getCandidates();
|
||||||
|
if (candidates == null && memory != null)
|
||||||
|
candidates = memory.candidateProvider(GroupColumn::display);
|
||||||
|
grid.configureFilter(
|
||||||
|
column.getId(), filter.withChecklist(column.getChecklist(), candidates));
|
||||||
|
}
|
||||||
|
grid.configureGrouping(
|
||||||
|
columns.stream()
|
||||||
|
.map(c ->
|
||||||
|
new GroupColumn<T>(
|
||||||
|
c.getId(), c.getKind(), c::groupValue, c::groupLabel))
|
||||||
|
.toList(),
|
||||||
|
groupingEnabled,
|
||||||
|
groupBy.isBlank()
|
||||||
|
? List.of()
|
||||||
|
: Arrays.stream(groupBy.split(",")).map(String::trim).toList(),
|
||||||
|
groupsCollapsed,
|
||||||
|
inactiveGroupHistoryLimit);
|
||||||
|
if (setupId != null && !setupId.isBlank()) {
|
||||||
|
Map<String, String> types = new LinkedHashMap<>();
|
||||||
|
columns.forEach(c -> types.put(c.getId(), c.schemaType()));
|
||||||
|
grid.configureSetups(setupId, setupVersion, types, Map.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResultRow render(T row) {
|
||||||
|
HBox root = new HBox();
|
||||||
|
root.setUserData(row);
|
||||||
|
Map<String, Region> cells = new LinkedHashMap<>();
|
||||||
|
for (var column : columns) {
|
||||||
|
Label label = new Label(Objects.toString(column.getValue(row), ""));
|
||||||
|
root.getChildren().add(label);
|
||||||
|
cells.put(column.getId(), label);
|
||||||
|
}
|
||||||
|
return new ResultRow(root, cells, () -> {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
if (items.get() != null) items.get().removeListener(itemsChanged);
|
||||||
|
items.unbind();
|
||||||
|
source.unbind();
|
||||||
|
if (executor != null) executor.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.grid.ColumnWidth;
|
||||||
|
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
import javafx.util.StringConverter;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Keyboard-operable equivalents of header resizing, reordering and grouping. */
|
||||||
|
final class GridColumnSettings<K, T> {
|
||||||
|
private final Dialog<Void> dialog = new Dialog<>();
|
||||||
|
|
||||||
|
GridColumnSettings(DataGrid<K, T> grid, TableResults<K, T> renderer) {
|
||||||
|
dialog.setTitle("Column settings");
|
||||||
|
if (grid.getScene() != null) dialog.initOwner(grid.getScene().getWindow());
|
||||||
|
dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
|
||||||
|
ComboBox<ResultColumn> column = new ComboBox<>();
|
||||||
|
column.getItems().setAll(renderer.definitions());
|
||||||
|
column.setConverter(
|
||||||
|
new StringConverter<>() {
|
||||||
|
public String toString(ResultColumn c) {
|
||||||
|
return c == null ? "" : c.header();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResultColumn fromString(String text) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
column.setAccessibleText("Column");
|
||||||
|
column.setId("gridSettingsColumn");
|
||||||
|
Spinner<Double> width = new Spinner<>();
|
||||||
|
width.setEditable(true);
|
||||||
|
width.setAccessibleText("Column width");
|
||||||
|
Button apply = new Button("Apply width"),
|
||||||
|
left = new Button("Move left"),
|
||||||
|
right = new Button("Move right"),
|
||||||
|
group = new Button("Group by column"),
|
||||||
|
earlier = new Button("Earlier grouping level"),
|
||||||
|
later = new Button("Later grouping level"),
|
||||||
|
remove = new Button("Remove grouping");
|
||||||
|
Label description = new Label(), message = new Label();
|
||||||
|
message.setWrapText(true);
|
||||||
|
Runnable update =
|
||||||
|
() -> {
|
||||||
|
var c = column.getValue();
|
||||||
|
if (c == null) return;
|
||||||
|
width.setValueFactory(
|
||||||
|
new SpinnerValueFactory.DoubleSpinnerValueFactory(
|
||||||
|
c.minimumWidth(),
|
||||||
|
c.maximumWidth(),
|
||||||
|
renderer.width(c.id()),
|
||||||
|
10));
|
||||||
|
int index = renderer.columnOrder().indexOf(c.id()),
|
||||||
|
level = renderer.groupingColumns().indexOf(c.id());
|
||||||
|
description.setText(
|
||||||
|
"Position "
|
||||||
|
+ (index + 1)
|
||||||
|
+ (c.fixedPosition() >= 0 ? " (fixed)" : "")
|
||||||
|
+ " · "
|
||||||
|
+ c.minimumWidth()
|
||||||
|
+ "–"
|
||||||
|
+ c.maximumWidth()
|
||||||
|
+ " px");
|
||||||
|
left.setDisable(!canMove(renderer, c.id(), index - 1));
|
||||||
|
right.setDisable(!canMove(renderer, c.id(), index + 1));
|
||||||
|
group.setDisable(!renderer.canGroup(c.id()) || level >= 0);
|
||||||
|
earlier.setDisable(!renderer.groupingEnabled() || level <= 0);
|
||||||
|
later.setDisable(
|
||||||
|
!renderer.groupingEnabled()
|
||||||
|
|| level < 0
|
||||||
|
|| level == renderer.groupingColumns().size() - 1);
|
||||||
|
remove.setDisable(!renderer.groupingEnabled() || level < 0);
|
||||||
|
};
|
||||||
|
java.util.function.Consumer<Runnable> perform =
|
||||||
|
action -> {
|
||||||
|
try {
|
||||||
|
action.run();
|
||||||
|
message.setText("Applied.");
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
message.setText(failure.getMessage());
|
||||||
|
}
|
||||||
|
update.run();
|
||||||
|
};
|
||||||
|
left.setOnAction(
|
||||||
|
e -> perform.accept(() -> move(grid, renderer, column.getValue().id(), -1)));
|
||||||
|
right.setOnAction(
|
||||||
|
e -> perform.accept(() -> move(grid, renderer, column.getValue().id(), 1)));
|
||||||
|
apply.setOnAction(e ->
|
||||||
|
perform.accept(() ->
|
||||||
|
grid.setColumnWidth(
|
||||||
|
column.getValue().id(),
|
||||||
|
new ColumnWidth.Explicit(
|
||||||
|
Double.parseDouble(width.getEditor().getText())))));
|
||||||
|
group.setOnAction(e ->
|
||||||
|
perform.accept(() -> {
|
||||||
|
var ids = new ArrayList<>(renderer.groupingColumns());
|
||||||
|
ids.add(column.getValue().id());
|
||||||
|
grid.setGroupingColumns(ids);
|
||||||
|
}));
|
||||||
|
remove.setOnAction(e ->
|
||||||
|
perform.accept(() ->
|
||||||
|
grid.setGroupingColumns(
|
||||||
|
renderer.groupingColumns().stream()
|
||||||
|
.filter(id -> !id.equals(column.getValue().id()))
|
||||||
|
.toList())));
|
||||||
|
earlier.setOnAction(
|
||||||
|
e -> perform.accept(() -> moveGroup(grid, renderer, column.getValue().id(), -1)));
|
||||||
|
later.setOnAction(
|
||||||
|
e -> perform.accept(() -> moveGroup(grid, renderer, column.getValue().id(), 1)));
|
||||||
|
VBox content =
|
||||||
|
new VBox(
|
||||||
|
10,
|
||||||
|
new Label("Column"),
|
||||||
|
column,
|
||||||
|
description,
|
||||||
|
new HBox(8, left, right),
|
||||||
|
new Label("Width in pixels"),
|
||||||
|
new HBox(8, width, apply),
|
||||||
|
new HBox(8, group, remove),
|
||||||
|
new HBox(8, earlier, later),
|
||||||
|
message);
|
||||||
|
dialog.getDialogPane().setContent(content);
|
||||||
|
column.valueProperty().addListener((o, b, a) -> update.run());
|
||||||
|
column.getSelectionModel().selectFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
void show() {
|
||||||
|
dialog.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
dialog.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean canMove(TableResults<?, ?> renderer, String id, int index) {
|
||||||
|
var order = new ArrayList<>(renderer.columnOrder());
|
||||||
|
if (index < 0 || index >= order.size()) return false;
|
||||||
|
order.remove(id);
|
||||||
|
order.add(index, id);
|
||||||
|
return renderer.definitions().stream()
|
||||||
|
.allMatch(
|
||||||
|
c -> c.fixedPosition() < 0 || order.get(c.fixedPosition()).equals(c.id()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <K, T> void move(
|
||||||
|
DataGrid<K, T> grid, TableResults<K, T> renderer, String id, int delta) {
|
||||||
|
var order = new ArrayList<>(renderer.columnOrder());
|
||||||
|
int index = order.indexOf(id);
|
||||||
|
order.remove(id);
|
||||||
|
order.add(index + delta, id);
|
||||||
|
grid.setColumnOrder(order);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <K, T> void moveGroup(
|
||||||
|
DataGrid<K, T> grid, TableResults<K, T> renderer, String id, int delta) {
|
||||||
|
var order = new ArrayList<>(renderer.groupingColumns());
|
||||||
|
int index = order.indexOf(id);
|
||||||
|
order.remove(id);
|
||||||
|
order.add(index + delta, id);
|
||||||
|
grid.setGroupingColumns(order);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.value.ChangeListener;
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
/** One FX view's opt-in storage adapter. Closing it never discards accepted application saves. */
|
||||||
|
public final class GridPersistenceAttachment<K, T> implements AutoCloseable {
|
||||||
|
private final DataGrid<K, T> grid;
|
||||||
|
private final GridApplicationConfiguration application;
|
||||||
|
private final GridSetupStore.Key key;
|
||||||
|
private final Label status = new Label("Grid settings not loaded");
|
||||||
|
private final Button retry = new Button("Retry settings"),
|
||||||
|
reload = new Button("Reload saved setup"),
|
||||||
|
reset = new Button("Reset setup"),
|
||||||
|
overwrite = new Button("Overwrite saved setup");
|
||||||
|
private final VBox feedback = new VBox(4);
|
||||||
|
private final HBox recovery = new HBox(8);
|
||||||
|
private final List<MenuItem> menu;
|
||||||
|
private final ChangeListener<Number> commits;
|
||||||
|
private final AutoCloseable observation;
|
||||||
|
private final CompletableFuture<Void> ready = new CompletableFuture<>();
|
||||||
|
private boolean initialized, closed, restoreFailed;
|
||||||
|
private long generation, ownSave = -1, operationGeneration = -1;
|
||||||
|
private Throwable restoreError;
|
||||||
|
|
||||||
|
GridPersistenceAttachment(
|
||||||
|
DataGrid<K, T> grid, GridApplicationConfiguration application, GridSetupStore.Key key) {
|
||||||
|
this.grid = grid;
|
||||||
|
this.application = application;
|
||||||
|
this.key = key;
|
||||||
|
status.setWrapText(true);
|
||||||
|
status.getStyleClass().add("grid-persistence-status");
|
||||||
|
status.setAccessibleText("Grid settings status");
|
||||||
|
recovery.getChildren().addAll(retry, reload, reset, overwrite);
|
||||||
|
recovery.setVisible(false);
|
||||||
|
recovery.setManaged(false);
|
||||||
|
feedback.getChildren().addAll(status, recovery);
|
||||||
|
MenuItem reloadItem = new MenuItem("Reload saved setup"),
|
||||||
|
resetItem = new MenuItem("Reset setup");
|
||||||
|
reloadItem.setOnAction(e -> loadAsync());
|
||||||
|
resetItem.setOnAction(e -> resetAsync());
|
||||||
|
menu = List.of(reloadItem, resetItem);
|
||||||
|
grid.addPersistenceControls(feedback, menu);
|
||||||
|
retry.setOnAction(e -> {
|
||||||
|
if (!initialized || restoreFailed) loadAsync();
|
||||||
|
else application.retryAsync(key);
|
||||||
|
});
|
||||||
|
reload.setOnAction(e -> loadAsync());
|
||||||
|
reset.setOnAction(e -> resetAsync());
|
||||||
|
overwrite.setOnAction(e -> overwriteAsync());
|
||||||
|
commits =
|
||||||
|
(o, b, a) -> {
|
||||||
|
if (initialized && !closed) {
|
||||||
|
try {
|
||||||
|
ownSave = application.accept(key, grid.snapshotSetup(), this);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
fail(new CompletableFuture<>(), failure);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
grid.committedRevisionProperty().addListener(commits);
|
||||||
|
observation =
|
||||||
|
application.observe(
|
||||||
|
key,
|
||||||
|
state ->
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
if (!closed) show(state);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> ready() {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> loadAsync() {
|
||||||
|
requireFx();
|
||||||
|
check();
|
||||||
|
long token = ++generation;
|
||||||
|
long discarded = ownSave;
|
||||||
|
restoreFailed = false;
|
||||||
|
restoreError = null;
|
||||||
|
CompletableFuture<Void> answer = new CompletableFuture<>();
|
||||||
|
CompletionStage<GridApplicationConfiguration.Loaded> loading;
|
||||||
|
try {
|
||||||
|
loading = application.loadAsync(key);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
fail(answer, failure);
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
loading.whenComplete((loaded, error) ->
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
if (!live(token)) {
|
||||||
|
answer.completeExceptionally(
|
||||||
|
new CancellationException("Attachment closed or superseded"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (error != null) {
|
||||||
|
fail(answer, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
GridSetup setup =
|
||||||
|
loaded.stored().setup() == null
|
||||||
|
? grid.developerDefaults()
|
||||||
|
: loaded.stored().setup();
|
||||||
|
CompletionStage<Void> restore = grid.restoreSetupAsync(setup);
|
||||||
|
operationGeneration = grid.stateProperty().get().generation();
|
||||||
|
restore.whenComplete((ok, failure) ->
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
if (!live(token)) {
|
||||||
|
answer.completeExceptionally(
|
||||||
|
new CancellationException(
|
||||||
|
"Attachment closed or superseded"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (failure != null) {
|
||||||
|
fail(answer, failure);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
application.adopt(loaded, discarded);
|
||||||
|
} catch (RuntimeException adoptionFailure) {
|
||||||
|
fail(answer, adoptionFailure);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
initialized = true;
|
||||||
|
restoreFailed = false;
|
||||||
|
restoreError = null;
|
||||||
|
show(application.state(key));
|
||||||
|
ready.complete(null);
|
||||||
|
answer.complete(null);
|
||||||
|
}));
|
||||||
|
}));
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> resetAsync() {
|
||||||
|
requireFx();
|
||||||
|
check();
|
||||||
|
long token = ++generation;
|
||||||
|
boolean recover = !initialized || restoreFailed;
|
||||||
|
CompletableFuture<Void> answer = new CompletableFuture<>();
|
||||||
|
CompletionStage<Void> restore = grid.restoreSetupAsync(grid.developerDefaults());
|
||||||
|
operationGeneration = grid.stateProperty().get().generation();
|
||||||
|
restore.whenComplete((ok, error) ->
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
if (!live(token)) {
|
||||||
|
answer.completeExceptionally(
|
||||||
|
new CancellationException("Attachment closed or superseded"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (error != null) {
|
||||||
|
fail(answer, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
initialized = true;
|
||||||
|
restoreFailed = false;
|
||||||
|
restoreError = null;
|
||||||
|
try {
|
||||||
|
ownSave =
|
||||||
|
recover
|
||||||
|
? application.acceptOverwrite(
|
||||||
|
key, grid.snapshotSetup(), this)
|
||||||
|
: application.accept(key, grid.snapshotSetup(), this);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
fail(answer, failure);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ready.complete(null);
|
||||||
|
answer.complete(null);
|
||||||
|
}));
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletionStage<Void> overwriteAsync() {
|
||||||
|
requireFx();
|
||||||
|
check();
|
||||||
|
if (!initialized)
|
||||||
|
throw new IllegalStateException("Initialize or reset the view before saving");
|
||||||
|
ownSave = application.acceptOverwrite(key, grid.snapshotSetup(), this);
|
||||||
|
return application.retryAsync(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fail(CompletableFuture<Void> future, Throwable failure) {
|
||||||
|
restoreFailed = true;
|
||||||
|
restoreError = unwrap(failure);
|
||||||
|
status.setText("Grid settings unavailable: " + restoreError.getMessage());
|
||||||
|
recovery.setVisible(true);
|
||||||
|
recovery.setManaged(true);
|
||||||
|
overwrite.setDisable(!initialized);
|
||||||
|
future.completeExceptionally(restoreError);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void show(GridApplicationConfiguration.State state) {
|
||||||
|
if (restoreFailed) {
|
||||||
|
status.setText("Grid settings unavailable: " + restoreError.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
status.setText(
|
||||||
|
switch (state.phase()) {
|
||||||
|
case IDLE -> "Grid settings not loaded";
|
||||||
|
case LOADING -> "Loading grid settings…";
|
||||||
|
case PENDING -> "Grid settings have unsaved changes";
|
||||||
|
case SAVING -> "Saving grid settings…";
|
||||||
|
case SAVED -> "Grid settings saved";
|
||||||
|
case CLOSED -> "Grid settings closed";
|
||||||
|
case ERROR, CONFLICT -> "Grid settings: " + state.error().getMessage();
|
||||||
|
});
|
||||||
|
boolean failed =
|
||||||
|
state.phase() == GridApplicationConfiguration.Phase.ERROR
|
||||||
|
|| state.phase() == GridApplicationConfiguration.Phase.CONFLICT;
|
||||||
|
recovery.setVisible(failed);
|
||||||
|
recovery.setManaged(failed);
|
||||||
|
overwrite.setDisable(!initialized);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean live(long token) {
|
||||||
|
return !closed && generation == token;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void check() {
|
||||||
|
if (closed) throw new IllegalStateException("Attachment is closed");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void requireFx() {
|
||||||
|
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("Use FX thread");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Throwable unwrap(Throwable failure) {
|
||||||
|
while ((failure instanceof CompletionException || failure instanceof ExecutionException)
|
||||||
|
&& failure.getCause() != null) failure = failure.getCause();
|
||||||
|
return failure;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
requireFx();
|
||||||
|
if (closed) return;
|
||||||
|
closed = true;
|
||||||
|
generation++;
|
||||||
|
grid.committedRevisionProperty().removeListener(commits);
|
||||||
|
try {
|
||||||
|
observation.close();
|
||||||
|
} catch (Exception failure) {
|
||||||
|
throw new IllegalStateException(failure);
|
||||||
|
}
|
||||||
|
grid.cancelOwnedRestore(operationGeneration);
|
||||||
|
grid.removePersistenceControls(feedback, menu);
|
||||||
|
grid.detached(this);
|
||||||
|
if (!ready.isDone())
|
||||||
|
ready.completeExceptionally(new CancellationException("Attachment closed"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import javafx.scene.Group;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
import javafx.scene.shape.Line;
|
||||||
|
|
||||||
|
/** Row decoration that preserves field borders, component identity and hit testing. */
|
||||||
|
final class ResultColumnSeparators extends Group {
|
||||||
|
ResultColumnSeparators(HBox row, int columns) {
|
||||||
|
setManaged(false);
|
||||||
|
setMouseTransparent(true);
|
||||||
|
for (int i = 1; i < columns; i++) {
|
||||||
|
var line = new Line();
|
||||||
|
line.getStyleClass().add("column-separator-line");
|
||||||
|
line.endYProperty().bind(row.heightProperty());
|
||||||
|
getChildren().add(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static ResultColumnSeparators forHeader(HBox cell) {
|
||||||
|
var decoration = new ResultColumnSeparators(cell, 2);
|
||||||
|
var line = (Line) decoration.getChildren().getFirst();
|
||||||
|
line.startXProperty().bind(cell.widthProperty().subtract(.5));
|
||||||
|
line.endXProperty().bind(line.startXProperty());
|
||||||
|
return decoration;
|
||||||
|
}
|
||||||
|
|
||||||
|
void position(double[] widths) {
|
||||||
|
double x = 0;
|
||||||
|
for (int i = 0; i < getChildren().size(); i++) {
|
||||||
|
x += widths[i];
|
||||||
|
var line = (Line) getChildren().get(i);
|
||||||
|
line.setStartX(x - .5);
|
||||||
|
line.setEndX(x - .5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.grid.ColumnWidth;
|
||||||
|
|
||||||
|
import javafx.animation.AnimationTimer;
|
||||||
|
import javafx.event.EventHandler;
|
||||||
|
import javafx.scene.*;
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.input.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Native gesture routing for result-mode headers only. No source/query or storage ownership. */
|
||||||
|
final class ResultHeaderGestures implements AutoCloseable {
|
||||||
|
private static final DataFormat FORMAT = new DataFormat("application/x-neitzel-grid-header");
|
||||||
|
private final String owner = UUID.randomUUID().toString();
|
||||||
|
private final TableResults<?, ?> renderer;
|
||||||
|
private final HBox header;
|
||||||
|
private final VBox body;
|
||||||
|
private Runnable cancelResize;
|
||||||
|
private double pointerX, pointerY;
|
||||||
|
private AnimationTimer scrolling;
|
||||||
|
private Runnable finishDrag;
|
||||||
|
private long dragGeneration;
|
||||||
|
|
||||||
|
ResultHeaderGestures(TableResults<?, ?> renderer, HBox header, VBox body) {
|
||||||
|
this.renderer = renderer;
|
||||||
|
this.header = header;
|
||||||
|
this.body = body;
|
||||||
|
}
|
||||||
|
|
||||||
|
void header(HBox cell, Label label, Region handle, String id, Runnable sort) {
|
||||||
|
boolean[] dragged = {false};
|
||||||
|
cell.setOnMousePressed(e -> {
|
||||||
|
if (e.getButton() == MouseButton.PRIMARY) dragged[0] = false;
|
||||||
|
});
|
||||||
|
cell.setOnMouseClicked(e -> {
|
||||||
|
if (e.getButton() == MouseButton.PRIMARY && !dragged[0]) sort.run();
|
||||||
|
});
|
||||||
|
label.setOnDragDetected(e -> {
|
||||||
|
if (!e.isPrimaryButtonDown() && e.getButton() != MouseButton.PRIMARY) return;
|
||||||
|
dragged[0] = true;
|
||||||
|
start(label, "column", id);
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
cell.setOnDragOver(e -> {
|
||||||
|
var payload = payload(e.getDragboard());
|
||||||
|
if (payload == null) return;
|
||||||
|
pointerX = e.getSceneX();
|
||||||
|
pointerY = e.getSceneY();
|
||||||
|
clearTargets();
|
||||||
|
int index =
|
||||||
|
insertion(
|
||||||
|
renderer.columnOrder(), payload[1], id, e.getX() > cell.getWidth() / 2);
|
||||||
|
var order = move(renderer.columnOrder(), payload[1], index);
|
||||||
|
boolean valid = payload[0].equals("column") && valid(order);
|
||||||
|
cell.getStyleClass()
|
||||||
|
.add(
|
||||||
|
valid
|
||||||
|
? (e.getX() > cell.getWidth() / 2
|
||||||
|
? "drop-after"
|
||||||
|
: "drop-before")
|
||||||
|
: "drop-invalid");
|
||||||
|
if (valid) e.acceptTransferModes(TransferMode.MOVE);
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
cell.setOnDragDropped(e -> {
|
||||||
|
var payload = payload(e.getDragboard());
|
||||||
|
boolean success = false;
|
||||||
|
if (payload != null && payload[0].equals("column")) {
|
||||||
|
int index =
|
||||||
|
insertion(
|
||||||
|
renderer.columnOrder(),
|
||||||
|
payload[1],
|
||||||
|
id,
|
||||||
|
e.getX() > cell.getWidth() / 2);
|
||||||
|
var order = move(renderer.columnOrder(), payload[1], index);
|
||||||
|
if (valid(order)) {
|
||||||
|
renderer.setColumnOrder(order);
|
||||||
|
success = true;
|
||||||
|
} else renderer.message("Fixed column cannot be displaced.");
|
||||||
|
}
|
||||||
|
clearTargets();
|
||||||
|
e.setDropCompleted(success);
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
handle.setOnMouseClicked(MouseEvent::consume);
|
||||||
|
handle.setOnDragDetected(MouseEvent::consume);
|
||||||
|
handle.setOnMousePressed(e -> {
|
||||||
|
if (e.getButton() != MouseButton.PRIMARY) return;
|
||||||
|
dragged[0] = true;
|
||||||
|
if (cancelResize != null) cancelResize.run();
|
||||||
|
ColumnWidth original = renderer.columnWidths().get(id);
|
||||||
|
double start = e.getScreenX(), width = renderer.width(id);
|
||||||
|
var definition =
|
||||||
|
renderer.definitions().stream()
|
||||||
|
.filter(c -> c.id().equals(id))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow();
|
||||||
|
Scene scene = handle.getScene();
|
||||||
|
EventHandler<KeyEvent> escape =
|
||||||
|
key -> {
|
||||||
|
if (key.getCode() == KeyCode.ESCAPE && cancelResize != null) {
|
||||||
|
cancelResize.run();
|
||||||
|
key.consume();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
double[] preview = {width};
|
||||||
|
boolean[] active = {true};
|
||||||
|
javafx.beans.value.ChangeListener<Boolean> focus =
|
||||||
|
(o, b, focused) -> {
|
||||||
|
if (!focused && cancelResize != null) cancelResize.run();
|
||||||
|
};
|
||||||
|
var window = scene.getWindow();
|
||||||
|
Runnable cleanup =
|
||||||
|
() -> {
|
||||||
|
active[0] = false;
|
||||||
|
scene.removeEventFilter(KeyEvent.KEY_PRESSED, escape);
|
||||||
|
if (window != null) window.focusedProperty().removeListener(focus);
|
||||||
|
handle.setOnMouseDragged(null);
|
||||||
|
handle.setOnMouseReleased(null);
|
||||||
|
cancelResize = null;
|
||||||
|
};
|
||||||
|
cancelResize =
|
||||||
|
() -> {
|
||||||
|
renderer.previewWidth(id, original);
|
||||||
|
cleanup.run();
|
||||||
|
renderer.message("Resize cancelled.");
|
||||||
|
};
|
||||||
|
scene.addEventFilter(KeyEvent.KEY_PRESSED, escape);
|
||||||
|
if (window != null) window.focusedProperty().addListener(focus);
|
||||||
|
handle.setOnMouseDragged(event -> {
|
||||||
|
if (active[0]) {
|
||||||
|
preview[0] =
|
||||||
|
Math.clamp(
|
||||||
|
width + event.getScreenX() - start,
|
||||||
|
definition.minimumWidth(),
|
||||||
|
definition.maximumWidth());
|
||||||
|
renderer.previewWidth(id, new ColumnWidth.Explicit(preview[0]));
|
||||||
|
}
|
||||||
|
event.consume();
|
||||||
|
});
|
||||||
|
handle.setOnMouseReleased(event -> {
|
||||||
|
if (active[0]) {
|
||||||
|
cleanup.run();
|
||||||
|
renderer.setColumnWidth(id, new ColumnWidth.Explicit(preview[0]));
|
||||||
|
renderer.message("Width applied to " + definition.header() + ".");
|
||||||
|
}
|
||||||
|
event.consume();
|
||||||
|
});
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void groupTarget(HBox bar) {
|
||||||
|
bar.setOnDragOver(e -> {
|
||||||
|
var payload = payload(e.getDragboard());
|
||||||
|
if (payload == null) return;
|
||||||
|
clearTargets();
|
||||||
|
boolean valid =
|
||||||
|
renderer.canGroup(payload[1])
|
||||||
|
&& (payload[0].equals("group")
|
||||||
|
|| !renderer.groupingColumns().contains(payload[1]));
|
||||||
|
bar.getStyleClass().add(valid ? "drop-before" : "drop-invalid");
|
||||||
|
if (valid) {
|
||||||
|
e.acceptTransferModes(TransferMode.MOVE);
|
||||||
|
markGroupInsertion(bar, payload[1], e.getSceneX());
|
||||||
|
}
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
bar.setOnDragDropped(e -> {
|
||||||
|
var payload = payload(e.getDragboard());
|
||||||
|
boolean success = false;
|
||||||
|
if (payload != null
|
||||||
|
&& renderer.canGroup(payload[1])
|
||||||
|
&& (payload[0].equals("group")
|
||||||
|
|| !renderer.groupingColumns().contains(payload[1]))) {
|
||||||
|
var order = new ArrayList<>(renderer.groupingColumns());
|
||||||
|
order.remove(payload[1]);
|
||||||
|
int index = groupIndex(bar, payload[1], e.getSceneX());
|
||||||
|
order.add(Math.min(index, order.size()), payload[1]);
|
||||||
|
try {
|
||||||
|
renderer.setGroupingColumns(order);
|
||||||
|
success = true;
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
renderer.message("Grouping failed: " + failure.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!success && payload == null)
|
||||||
|
renderer.message("Column is already grouped or has no enabled grouping mapping.");
|
||||||
|
clearTargets();
|
||||||
|
e.setDropCompleted(success);
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
bar.setOnDragExited(e -> {
|
||||||
|
clearTargets();
|
||||||
|
e.consume();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void chip(Region chip, String id) {
|
||||||
|
chip.setUserData(id);
|
||||||
|
chip.setOnDragDetected(e -> {
|
||||||
|
if (e.isPrimaryButtonDown() || e.getButton() == MouseButton.PRIMARY) {
|
||||||
|
start(chip, "group", id);
|
||||||
|
e.consume();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void start(Node node, String kind, String id) {
|
||||||
|
// Capture before entering native drag setup; snapshot uses the rendering pipeline.
|
||||||
|
var ghost = node.snapshot(null, null);
|
||||||
|
var board = node.startDragAndDrop(TransferMode.MOVE);
|
||||||
|
var content = new ClipboardContent();
|
||||||
|
content.put(FORMAT, owner + "\n" + kind + "\n" + id);
|
||||||
|
board.setContent(content);
|
||||||
|
board.setDragView(ghost);
|
||||||
|
if (finishDrag != null) finishDrag.run();
|
||||||
|
long generation = ++dragGeneration;
|
||||||
|
Scene scene = node.getScene();
|
||||||
|
// Header-only tracking leaves a stale edge x when the pointer exits
|
||||||
|
// vertically. Follow the whole scene and qualify its current y as well.
|
||||||
|
EventHandler<DragEvent> position =
|
||||||
|
event -> {
|
||||||
|
if (payload(event.getDragboard()) != null) {
|
||||||
|
pointerX = event.getSceneX();
|
||||||
|
pointerY = event.getSceneY();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
EventHandler<DragEvent> exited =
|
||||||
|
event -> {
|
||||||
|
if (event.getTarget() == scene || event.getTarget() == scene.getRoot()) {
|
||||||
|
pointerX = pointerY = Double.NaN;
|
||||||
|
clearTargets();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
scene.addEventFilter(DragEvent.DRAG_OVER, position);
|
||||||
|
scene.addEventFilter(DragEvent.DRAG_EXITED_TARGET, exited);
|
||||||
|
finishDrag =
|
||||||
|
() -> {
|
||||||
|
scene.removeEventFilter(DragEvent.DRAG_OVER, position);
|
||||||
|
scene.removeEventFilter(DragEvent.DRAG_EXITED_TARGET, exited);
|
||||||
|
pointerX = pointerY = Double.NaN;
|
||||||
|
clearTargets();
|
||||||
|
stopScroll();
|
||||||
|
finishDrag = null;
|
||||||
|
};
|
||||||
|
node.setOnDragDone(e -> {
|
||||||
|
if (generation != dragGeneration) return;
|
||||||
|
if (finishDrag != null) finishDrag.run();
|
||||||
|
renderer.message(
|
||||||
|
e.getTransferMode() == null
|
||||||
|
? "Drag cancelled; layout retained."
|
||||||
|
: "Layout applied.");
|
||||||
|
});
|
||||||
|
startScroll();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String[] payload(Dragboard board) {
|
||||||
|
if (!board.hasContent(FORMAT)) return null;
|
||||||
|
Object content = board.getContent(FORMAT);
|
||||||
|
if (!(content instanceof String text)) return null;
|
||||||
|
var parts = text.split("\n", 3);
|
||||||
|
return parts.length == 3 && parts[0].equals(owner)
|
||||||
|
? new String[] {parts[1], parts[2]}
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> move(List<String> current, String id, int index) {
|
||||||
|
var result = new ArrayList<>(current);
|
||||||
|
result.remove(id);
|
||||||
|
result.add(Math.clamp(index, 0, result.size()), id);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int insertion(List<String> current, String id, String target, boolean after) {
|
||||||
|
if (id.equals(target)) return current.indexOf(id);
|
||||||
|
var others = new ArrayList<>(current);
|
||||||
|
others.remove(id);
|
||||||
|
return others.indexOf(target) + (after ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean valid(List<String> order) {
|
||||||
|
if (!new HashSet<>(order).equals(new HashSet<>(renderer.columnOrder()))
|
||||||
|
|| order.size() != renderer.columnOrder().size()) return false;
|
||||||
|
for (var c : renderer.definitions())
|
||||||
|
if (c.fixedPosition() >= 0 && !order.get(c.fixedPosition()).equals(c.id()))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int groupIndex(HBox bar, String dragged, double sceneX) {
|
||||||
|
int index = 0;
|
||||||
|
for (Node node : bar.getChildren())
|
||||||
|
if (node.getUserData() instanceof String id && !id.equals(dragged)) {
|
||||||
|
var bounds = node.localToScene(node.getBoundsInLocal());
|
||||||
|
if (sceneX < bounds.getMinX() + bounds.getWidth() / 2) return index;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void markGroupInsertion(HBox bar, String dragged, double x) {
|
||||||
|
var chips =
|
||||||
|
bar.getChildren().stream()
|
||||||
|
.filter(n -> n.getUserData() instanceof String id && !id.equals(dragged))
|
||||||
|
.toList();
|
||||||
|
int index = groupIndex(bar, dragged, x);
|
||||||
|
if (!chips.isEmpty())
|
||||||
|
chips.get(Math.min(index, chips.size() - 1))
|
||||||
|
.getStyleClass()
|
||||||
|
.add(index < chips.size() ? "drop-before" : "drop-after");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void clearTargets() {
|
||||||
|
Parent root = header.getScene() == null ? header : header.getScene().getRoot();
|
||||||
|
for (String style : List.of("drop-before", "drop-after", "drop-invalid"))
|
||||||
|
root.lookupAll("." + style).forEach(n -> n.getStyleClass().remove(style));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void startScroll() {
|
||||||
|
stopScroll();
|
||||||
|
pointerX = pointerY = Double.NaN;
|
||||||
|
scrolling =
|
||||||
|
new AnimationTimer() {
|
||||||
|
long last;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handle(long now) {
|
||||||
|
if (now - last < 35_000_000) return;
|
||||||
|
last = now;
|
||||||
|
ScrollPane scroll = null;
|
||||||
|
for (Node node = body.getParent(); node != null; node = node.getParent())
|
||||||
|
if (node instanceof ScrollPane pane) {
|
||||||
|
scroll = pane;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ScrollPane headerViewport = null;
|
||||||
|
for (Node node = header.getParent(); node != null; node = node.getParent())
|
||||||
|
if (node instanceof ScrollPane pane) {
|
||||||
|
headerViewport = pane;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (scroll == null
|
||||||
|
|| headerViewport == null
|
||||||
|
|| Double.isNaN(pointerX)
|
||||||
|
|| !headerViewport
|
||||||
|
.localToScene(headerViewport.getBoundsInLocal())
|
||||||
|
.contains(pointerX, pointerY)) return;
|
||||||
|
var bounds = scroll.localToScene(scroll.getViewportBounds());
|
||||||
|
double delta =
|
||||||
|
pointerX < bounds.getMinX() + 30
|
||||||
|
? -.012
|
||||||
|
: pointerX > bounds.getMaxX() - 30 ? .012 : 0;
|
||||||
|
scroll.setHvalue(Math.clamp(scroll.getHvalue() + delta, 0, 1));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
scrolling.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stopScroll() {
|
||||||
|
if (scrolling != null) {
|
||||||
|
scrolling.stop();
|
||||||
|
scrolling = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
if (cancelResize != null) cancelResize.run();
|
||||||
|
if (finishDrag != null) finishDrag.run();
|
||||||
|
stopScroll();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import javafx.beans.binding.Bindings;
|
||||||
|
import javafx.beans.binding.DoubleBinding;
|
||||||
|
import javafx.scene.control.ScrollPane;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
import javafx.scene.layout.VBox;
|
||||||
|
|
||||||
|
/** Makes equal normalized scroll values represent equal pixel offsets in queried results. */
|
||||||
|
final class ResultScrollAlignment implements AutoCloseable {
|
||||||
|
private final HBox header;
|
||||||
|
private final double originalMinimum;
|
||||||
|
private final DoubleBinding minimum;
|
||||||
|
|
||||||
|
ResultScrollAlignment(HBox header, VBox body, ScrollPane headerScroll, ScrollPane bodyScroll) {
|
||||||
|
this.header = header;
|
||||||
|
originalMinimum = header.getMinWidth();
|
||||||
|
// A vertical body scrollbar narrows its viewport. Trailing row actions can also
|
||||||
|
// make its content wider than the column headings. Reserve blank header space
|
||||||
|
// so both scrollable extents match; the existing two-way hvalue binding then
|
||||||
|
// moves every mapped field and heading by the same number of pixels.
|
||||||
|
minimum =
|
||||||
|
Bindings.createDoubleBinding(
|
||||||
|
() ->
|
||||||
|
body.getLayoutBounds().getWidth()
|
||||||
|
+ Math.max(
|
||||||
|
0,
|
||||||
|
headerScroll.getViewportBounds().getWidth()
|
||||||
|
- bodyScroll
|
||||||
|
.getViewportBounds()
|
||||||
|
.getWidth()),
|
||||||
|
body.layoutBoundsProperty(),
|
||||||
|
headerScroll.viewportBoundsProperty(),
|
||||||
|
bodyScroll.viewportBoundsProperty());
|
||||||
|
header.minWidthProperty().bind(minimum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
header.minWidthProperty().unbind();
|
||||||
|
header.setMinWidth(originalMinimum);
|
||||||
|
minimum.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -244,7 +244,9 @@ public class Table extends VBox {
|
|||||||
if (opened || resultMode) {
|
if (opened || resultMode) {
|
||||||
throw new IllegalStateException("Table is already open");
|
throw new IllegalStateException("Table is already open");
|
||||||
}
|
}
|
||||||
TableResults<K, T> renderer = new TableResults<>(header, body, List.copyOf(definitions), factory);
|
TableResults<K, T> renderer = new TableResults<>(header, body, List.copyOf(definitions), factory, headerScroll, scroll);
|
||||||
|
// DataGrid grows this Table; let its viewport consume that height as well.
|
||||||
|
VBox.setVgrow(scroll, Priority.ALWAYS);
|
||||||
resultMode = true;
|
resultMode = true;
|
||||||
return renderer;
|
return renderer;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package de.neitzel.fx.view;
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
import de.neitzel.grid.ColumnWidth;
|
import de.neitzel.grid.*;
|
||||||
import de.neitzel.grid.GridRow;
|
|
||||||
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import javafx.beans.property.*;
|
import javafx.beans.property.*;
|
||||||
@@ -40,19 +39,40 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
new ReadOnlyObjectWrapper<>();
|
new ReadOnlyObjectWrapper<>();
|
||||||
private boolean closed;
|
private boolean closed;
|
||||||
private boolean rowsInteractive = true;
|
private boolean rowsInteractive = true;
|
||||||
|
private boolean columnSeparators;
|
||||||
private Set<String> filterColumns = Set.of();
|
private Set<String> filterColumns = Set.of();
|
||||||
private Set<String> filteredColumns = Set.of();
|
private Set<String> filteredColumns = Set.of();
|
||||||
|
private List<SortKey> sortKeys = List.of();
|
||||||
private java.util.function.BiConsumer<String, Node> filterRequest = (id, node) -> {};
|
private java.util.function.BiConsumer<String, Node> filterRequest = (id, node) -> {};
|
||||||
private java.util.function.Consumer<String> sortRequest = id -> {};
|
private java.util.function.Consumer<String> sortRequest = id -> {};
|
||||||
|
|
||||||
|
private List<GroupColumn<T>> groupColumns = List.of();
|
||||||
|
private List<String> grouping = List.of();
|
||||||
|
private boolean groupingEnabled, defaultCollapsed = true;
|
||||||
|
private int inactiveHistoryLimit = 1000;
|
||||||
|
private GroupExpansion expansion = new GroupExpansion(true, 1000);
|
||||||
|
private GroupProjection.Snapshot<K, T> captured = GroupProjection.capture(List.of(), List.of());
|
||||||
|
private List<GroupProjection.Node<K, T>> groupTree = List.of();
|
||||||
|
private final Map<GroupPath, Button> disclosure = new HashMap<>();
|
||||||
|
private Runnable layoutCommitted = () -> {};
|
||||||
|
private java.util.function.Consumer<String> interactionMessage = ignored -> {};
|
||||||
|
private final ResultHeaderGestures gestures;
|
||||||
|
private final ResultScrollAlignment scrollAlignment;
|
||||||
|
|
||||||
private record Entry<K, T>(GridRow<K, T> row, ResultRow view, EventHandler<MouseEvent> click) {}
|
private record Entry<K, T>(GridRow<K, T> row, ResultRow view, EventHandler<MouseEvent> click) {}
|
||||||
|
|
||||||
TableResults(
|
TableResults(
|
||||||
HBox header, VBox body, List<ResultColumn> columns, Function<T, ResultRow> factory) {
|
HBox header,
|
||||||
|
VBox body,
|
||||||
|
List<ResultColumn> columns,
|
||||||
|
Function<T, ResultRow> factory,
|
||||||
|
javafx.scene.control.ScrollPane headerScroll,
|
||||||
|
javafx.scene.control.ScrollPane bodyScroll) {
|
||||||
requireFx();
|
requireFx();
|
||||||
this.header = header;
|
this.header = header;
|
||||||
this.body = body;
|
this.body = body;
|
||||||
this.factory = Objects.requireNonNull(factory);
|
this.factory = Objects.requireNonNull(factory);
|
||||||
|
gestures = new ResultHeaderGestures(this, header, body);
|
||||||
if (columns.isEmpty())
|
if (columns.isEmpty())
|
||||||
throw new IllegalArgumentException("At least one column is required");
|
throw new IllegalArgumentException("At least one column is required");
|
||||||
for (var c : columns) {
|
for (var c : columns) {
|
||||||
@@ -62,13 +82,20 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
order = List.copyOf(definitions.keySet());
|
order = List.copyOf(definitions.keySet());
|
||||||
validateOrder(order);
|
validateOrder(order);
|
||||||
|
scrollAlignment = new ResultScrollAlignment(header, body, headerScroll, bodyScroll);
|
||||||
drawHeader();
|
drawHeader();
|
||||||
body.setOnMouseClicked(
|
body.setOnMouseClicked(e -> {
|
||||||
e -> {
|
|
||||||
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
|
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void enableColumnSeparators() {
|
||||||
|
checkOpen();
|
||||||
|
columnSeparators = true;
|
||||||
|
drawHeader();
|
||||||
|
entries.forEach(e -> layoutRow(e.view()));
|
||||||
|
}
|
||||||
|
|
||||||
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
|
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
|
||||||
return selectedKey.getReadOnlyProperty();
|
return selectedKey.getReadOnlyProperty();
|
||||||
}
|
}
|
||||||
@@ -130,6 +157,28 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
markFilter(button, (String) cell.getUserData());
|
markFilter(button, (String) cell.getUserData());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setSortKeys(List<SortKey> keys) {
|
||||||
|
checkOpen();
|
||||||
|
if (keys.size() > 1 || keys.stream().anyMatch(k -> !definitions.containsKey(k.columnId())))
|
||||||
|
throw new IllegalArgumentException("Unknown sort column");
|
||||||
|
sortKeys = List.copyOf(keys);
|
||||||
|
for (Node node : header.getChildren()) {
|
||||||
|
HBox cell = (HBox) node;
|
||||||
|
Label label = (Label) cell.getChildren().getFirst();
|
||||||
|
label.setText(headerText((String) cell.getUserData()));
|
||||||
|
label.setAccessibleText("Sort " + headerText((String) cell.getUserData()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String headerText(String id) {
|
||||||
|
return definitions.get(id).header()
|
||||||
|
+ sortKeys.stream()
|
||||||
|
.filter(k -> k.columnId().equals(id))
|
||||||
|
.map(k -> k.direction() == SortKey.Direction.ASCENDING ? " ↑" : " ↓")
|
||||||
|
.findFirst()
|
||||||
|
.orElse("");
|
||||||
|
}
|
||||||
|
|
||||||
private void markFilter(Button button, String id) {
|
private void markFilter(Button button, String id) {
|
||||||
boolean active = filteredColumns.contains(id);
|
boolean active = filteredColumns.contains(id);
|
||||||
button.pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("filtered"), active);
|
button.pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("filtered"), active);
|
||||||
@@ -153,7 +202,7 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
* page.
|
* page.
|
||||||
*/
|
*/
|
||||||
public void show(List<GridRow<K, T>> result) {
|
public void show(List<GridRow<K, T>> result) {
|
||||||
show(result, order, widths);
|
show(result, order, widths, groupingSetup());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Stages both fresh rows and complete layout, publishing neither on preparation failure. */
|
/** Stages both fresh rows and complete layout, publishing neither on preparation failure. */
|
||||||
@@ -161,7 +210,21 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
List<GridRow<K, T>> result,
|
List<GridRow<K, T>> result,
|
||||||
List<String> nextOrder,
|
List<String> nextOrder,
|
||||||
Map<String, ColumnWidth> nextWidths) {
|
Map<String, ColumnWidth> nextWidths) {
|
||||||
|
show(result, nextOrder, nextWidths, groupingSetup());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void show(
|
||||||
|
List<GridRow<K, T>> result,
|
||||||
|
List<String> nextOrder,
|
||||||
|
Map<String, ColumnWidth> nextWidths,
|
||||||
|
GroupingSetup nextGrouping) {
|
||||||
checkOpen();
|
checkOpen();
|
||||||
|
validateGrouping(nextGrouping);
|
||||||
|
var nextCaptured = GroupProjection.capture(result, groupColumns);
|
||||||
|
var nextTree = GroupProjection.project(nextCaptured, nextGrouping.columns());
|
||||||
|
var nextExpansion = new GroupExpansion(defaultCollapsed, inactiveHistoryLimit);
|
||||||
|
nextExpansion.current(GroupProjection.paths(nextTree));
|
||||||
|
nextExpansion.restore(nextGrouping.choices());
|
||||||
nextOrder = List.copyOf(nextOrder);
|
nextOrder = List.copyOf(nextOrder);
|
||||||
validateOrder(nextOrder);
|
validateOrder(nextOrder);
|
||||||
nextWidths = Map.copyOf(nextWidths);
|
nextWidths = Map.copyOf(nextWidths);
|
||||||
@@ -213,8 +276,12 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
widths.clear();
|
widths.clear();
|
||||||
widths.putAll(preparedWidths);
|
widths.putAll(preparedWidths);
|
||||||
header.getChildren().setAll(nextHeader);
|
header.getChildren().setAll(nextHeader);
|
||||||
body.getChildren().setAll(entries.stream().map(e -> e.view().root()).toList());
|
captured = nextCaptured;
|
||||||
markSelection();
|
groupTree = nextTree;
|
||||||
|
grouping = nextGrouping.columns();
|
||||||
|
expansion = nextExpansion;
|
||||||
|
disclosure.clear();
|
||||||
|
drawGroups();
|
||||||
release(old);
|
release(old);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,6 +293,8 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
order = ids;
|
order = ids;
|
||||||
drawHeader();
|
drawHeader();
|
||||||
entries.forEach(e -> layoutRow(e.view()));
|
entries.forEach(e -> layoutRow(e.view()));
|
||||||
|
resizeGroupHeadings();
|
||||||
|
layoutCommitted.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -243,8 +312,8 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
widths.put(
|
widths.put(
|
||||||
id,
|
id,
|
||||||
width instanceof ColumnWidth.Explicit ? new ColumnWidth.Explicit(applied) : width);
|
width instanceof ColumnWidth.Explicit ? new ColumnWidth.Explicit(applied) : width);
|
||||||
drawHeader();
|
applyWidths(widths);
|
||||||
entries.forEach(e -> layoutRow(e.view()));
|
layoutCommitted.run();
|
||||||
return applied;
|
return applied;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,7 +340,7 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
"Mapped fields must be distinct direct children");
|
"Mapped fields must be distinct direct children");
|
||||||
}
|
}
|
||||||
|
|
||||||
private double width(String id) {
|
double width(String id) {
|
||||||
return width(id, widths);
|
return width(id, widths);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,14 +357,22 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
private List<Node> headerNodes(List<String> ordering, Map<String, ColumnWidth> sizes) {
|
private List<Node> headerNodes(List<String> ordering, Map<String, ColumnWidth> sizes) {
|
||||||
List<Node> nodes = new ArrayList<>();
|
List<Node> nodes = new ArrayList<>();
|
||||||
for (String id : ordering) {
|
for (String id : ordering) {
|
||||||
Label label = new Label(definitions.get(id).header());
|
Label label = new Label(headerText(id));
|
||||||
label.getStyleClass().add("column-header");
|
label.getStyleClass().add("column-header");
|
||||||
HBox cell = new HBox(label);
|
HBox cell = new HBox(label);
|
||||||
cell.getStyleClass().add("column-cell");
|
cell.getStyleClass().add("column-cell");
|
||||||
cell.setUserData(id);
|
cell.setUserData(id);
|
||||||
cell.setOnMouseClicked(
|
HBox.setHgrow(label, javafx.scene.layout.Priority.ALWAYS);
|
||||||
event -> {
|
label.setMaxWidth(Double.MAX_VALUE);
|
||||||
if (event.getButton() == MouseButton.PRIMARY) sortRequest.accept(id);
|
label.setFocusTraversable(true);
|
||||||
|
label.setAccessibleRole(javafx.scene.AccessibleRole.BUTTON);
|
||||||
|
label.setAccessibleText("Sort " + definitions.get(id).header());
|
||||||
|
label.setOnKeyPressed(event -> {
|
||||||
|
if (event.getCode() == javafx.scene.input.KeyCode.ENTER
|
||||||
|
|| event.getCode() == javafx.scene.input.KeyCode.SPACE) {
|
||||||
|
sortRequest.accept(id);
|
||||||
|
event.consume();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
if (filterColumns.contains(id)) {
|
if (filterColumns.contains(id)) {
|
||||||
SVGPath icon = new SVGPath();
|
SVGPath icon = new SVGPath();
|
||||||
@@ -310,6 +387,16 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
button.addEventHandler(MouseEvent.MOUSE_CLICKED, MouseEvent::consume);
|
button.addEventHandler(MouseEvent.MOUSE_CLICKED, MouseEvent::consume);
|
||||||
cell.getChildren().add(button);
|
cell.getChildren().add(button);
|
||||||
}
|
}
|
||||||
|
Region handle = new Region();
|
||||||
|
handle.getStyleClass().add("column-resize");
|
||||||
|
handle.setMinWidth(9);
|
||||||
|
handle.setPrefWidth(9);
|
||||||
|
handle.setMaxWidth(9);
|
||||||
|
handle.setCursor(javafx.scene.Cursor.E_RESIZE);
|
||||||
|
cell.getChildren().add(handle);
|
||||||
|
if (columnSeparators && !id.equals(ordering.getLast()))
|
||||||
|
cell.getChildren().add(ResultColumnSeparators.forHeader(cell));
|
||||||
|
gestures.header(cell, label, handle, id, () -> sortRequest.accept(id));
|
||||||
size(cell, width(id, sizes));
|
size(cell, width(id, sizes));
|
||||||
nodes.add(cell);
|
nodes.add(cell);
|
||||||
}
|
}
|
||||||
@@ -335,10 +422,25 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
size(field, width(id, sizes));
|
size(field, width(id, sizes));
|
||||||
children.add(field);
|
children.add(field);
|
||||||
}
|
}
|
||||||
for (Node child : view.root().getChildren())
|
ResultColumnSeparators separators = null;
|
||||||
if (!fields.contains(child)) children.add(child);
|
for (Node child : view.root().getChildren()) {
|
||||||
|
if (child instanceof ResultColumnSeparators existing) separators = existing;
|
||||||
|
else if (!fields.contains(child)) children.add(child);
|
||||||
|
}
|
||||||
|
if (columnSeparators) {
|
||||||
|
if (separators == null)
|
||||||
|
separators = new ResultColumnSeparators(view.root(), ordering.size());
|
||||||
|
separators.position(ordering.stream().mapToDouble(id -> width(id, sizes)).toArray());
|
||||||
|
children.add(separators);
|
||||||
|
}
|
||||||
view.root().setSpacing(0);
|
view.root().setSpacing(0);
|
||||||
|
if (!view.root().getChildren().equals(children)) {
|
||||||
|
Node focus =
|
||||||
|
view.root().getScene() == null ? null : view.root().getScene().getFocusOwner();
|
||||||
|
boolean restore = focus != null && descendant(view.root(), focus);
|
||||||
view.root().getChildren().setAll(children);
|
view.root().getChildren().setAll(children);
|
||||||
|
if (restore) focus.requestFocus();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void markSelection() {
|
private void markSelection() {
|
||||||
@@ -352,12 +454,322 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
e.view().root().getStyleClass().remove("selected");
|
e.view().root().getStyleClass().remove("selected");
|
||||||
if (selected) {
|
if (selected) {
|
||||||
e.view().root().getStyleClass().add("selected");
|
e.view().root().getStyleClass().add("selected");
|
||||||
loaded = e.row().model();
|
if (e.view().root().getParent() == body) loaded = e.row().model();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
selectedElement.set(rowsInteractive ? loaded : null);
|
selectedElement.set(rowsInteractive ? loaded : null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setOnLayoutCommitted(Runnable handler) {
|
||||||
|
layoutCommitted = Objects.requireNonNull(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOnInteractionMessage(java.util.function.Consumer<String> handler) {
|
||||||
|
interactionMessage = Objects.requireNonNull(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
void message(String text) {
|
||||||
|
interactionMessage.accept(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ResultColumn> definitions() {
|
||||||
|
return List.copyOf(definitions.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
ResultHeaderGestures gestures() {
|
||||||
|
return gestures;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean canGroup(String id) {
|
||||||
|
return groupingEnabled && groupColumns.stream().anyMatch(c -> c.id().equals(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> groupingColumns() {
|
||||||
|
return grouping;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean groupingEnabled() {
|
||||||
|
return groupingEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupingSetup groupingSetup() {
|
||||||
|
return new GroupingSetup(grouping, expansion.snapshot());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void configureGrouping(
|
||||||
|
List<GroupColumn<T>> columns,
|
||||||
|
boolean enabled,
|
||||||
|
List<String> defaults,
|
||||||
|
boolean collapsed,
|
||||||
|
int historyLimit) {
|
||||||
|
checkOpen();
|
||||||
|
if (!entries.isEmpty())
|
||||||
|
throw new IllegalStateException("Configure grouping before first publication");
|
||||||
|
if (historyLimit < 0
|
||||||
|
|| !definitions
|
||||||
|
.keySet()
|
||||||
|
.containsAll(columns.stream().map(GroupColumn::id).toList()))
|
||||||
|
throw new IllegalArgumentException("Unknown group column or invalid history limit");
|
||||||
|
var snapshot = GroupProjection.<K, T>capture(List.of(), columns);
|
||||||
|
GroupProjection.project(snapshot, defaults);
|
||||||
|
groupColumns = List.copyOf(columns);
|
||||||
|
captured = snapshot;
|
||||||
|
groupingEnabled = enabled;
|
||||||
|
grouping = List.copyOf(defaults);
|
||||||
|
defaultCollapsed = collapsed;
|
||||||
|
inactiveHistoryLimit = historyLimit;
|
||||||
|
expansion = new GroupExpansion(collapsed, historyLimit);
|
||||||
|
drawGroups();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validateGrouping(GroupingSetup setup) {
|
||||||
|
Set<String> ids =
|
||||||
|
groupColumns.stream()
|
||||||
|
.map(GroupColumn::id)
|
||||||
|
.collect(java.util.stream.Collectors.toSet());
|
||||||
|
if (!ids.containsAll(setup.columns()))
|
||||||
|
throw new IllegalArgumentException("Column has no grouping mapping");
|
||||||
|
for (var choice : setup.choices())
|
||||||
|
for (var part : choice.path().segments()) {
|
||||||
|
var column =
|
||||||
|
groupColumns.stream()
|
||||||
|
.filter(c -> c.id().equals(part.columnId()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() ->
|
||||||
|
new IllegalArgumentException(
|
||||||
|
"Unknown group path column; provide migration"));
|
||||||
|
column.validate(part.value());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupingColumns(List<String> ids) {
|
||||||
|
checkOpen();
|
||||||
|
var setup = new GroupingSetup(ids, expansion.snapshot());
|
||||||
|
validateGrouping(setup);
|
||||||
|
var next = GroupProjection.project(captured, ids);
|
||||||
|
grouping = setup.columns();
|
||||||
|
groupTree = next;
|
||||||
|
expansion.current(GroupProjection.paths(next));
|
||||||
|
drawGroups();
|
||||||
|
layoutCommitted.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Refresh mapping snapshots only after an explicit application data-update signal. */
|
||||||
|
public void regroup() {
|
||||||
|
checkOpen();
|
||||||
|
var next = GroupProjection.capture(entries.stream().map(Entry::row).toList(), groupColumns);
|
||||||
|
var tree = GroupProjection.project(next, grouping);
|
||||||
|
captured = next;
|
||||||
|
groupTree = tree;
|
||||||
|
expansion.current(GroupProjection.paths(tree));
|
||||||
|
drawGroups();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupingEnabled(boolean enabled) {
|
||||||
|
checkOpen();
|
||||||
|
groupingEnabled = enabled;
|
||||||
|
drawGroups();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetExpansion() {
|
||||||
|
checkOpen();
|
||||||
|
expansion.reset();
|
||||||
|
drawGroups();
|
||||||
|
layoutCommitted.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExpanded(GroupPath path, boolean expanded) {
|
||||||
|
checkOpen();
|
||||||
|
if (!GroupProjection.paths(groupTree).contains(path))
|
||||||
|
throw new IllegalArgumentException("Group is not on current page");
|
||||||
|
Node focus = body.getScene() == null ? null : body.getScene().getFocusOwner();
|
||||||
|
boolean hidesFocus = !expanded && focus != null && descendantContainsFocus(path, focus);
|
||||||
|
expansion.set(path, expanded);
|
||||||
|
drawGroups();
|
||||||
|
if (hidesFocus) disclosure.get(path).requestFocus();
|
||||||
|
layoutCommitted.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean descendantContainsFocus(GroupPath path, Node focus) {
|
||||||
|
for (var row : entries) {
|
||||||
|
if (!descendant(row.view().root(), focus)) continue;
|
||||||
|
var values =
|
||||||
|
captured.rows().stream()
|
||||||
|
.filter(r -> Objects.equals(r.row().key(), row.row().key()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.values();
|
||||||
|
return path.segments().stream()
|
||||||
|
.allMatch(p -> Objects.equals(values.get(p.columnId()).key(), p.value()));
|
||||||
|
}
|
||||||
|
return disclosure.entrySet().stream()
|
||||||
|
.anyMatch(e ->
|
||||||
|
descendant(e.getValue(), focus)
|
||||||
|
&& e.getKey().segments().size() > path.segments().size()
|
||||||
|
&& e.getKey()
|
||||||
|
.segments()
|
||||||
|
.subList(0, path.segments().size())
|
||||||
|
.equals(path.segments()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean descendant(Node ancestor, Node node) {
|
||||||
|
for (Node current = node; current != null; current = current.getParent())
|
||||||
|
if (current == ancestor) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawGroups() {
|
||||||
|
Node focus = body.getScene() == null ? null : body.getScene().getFocusOwner();
|
||||||
|
boolean restoreFocus = focus != null && descendant(body, focus);
|
||||||
|
GroupPath focusedPath = restoreFocus ? focusPath(focus) : null;
|
||||||
|
disclosure.keySet().retainAll(new HashSet<>(GroupProjection.paths(groupTree)));
|
||||||
|
List<Node> nodes = new ArrayList<>();
|
||||||
|
Map<K, Node> rows = new HashMap<>();
|
||||||
|
entries.forEach(e -> rows.put(e.row().key(), e.view().root()));
|
||||||
|
if (!groupingEnabled || grouping.isEmpty())
|
||||||
|
entries.forEach(e -> nodes.add(e.view().root()));
|
||||||
|
else appendGroups(nodes, groupTree, rows);
|
||||||
|
if (!body.getChildren().equals(nodes)) body.getChildren().setAll(nodes);
|
||||||
|
if (restoreFocus) {
|
||||||
|
if (descendant(body, focus)) focus.requestFocus();
|
||||||
|
else {
|
||||||
|
Button destination = null;
|
||||||
|
if (focusedPath != null)
|
||||||
|
for (int level = 1; level <= focusedPath.segments().size(); level++) {
|
||||||
|
var candidate =
|
||||||
|
disclosure.get(
|
||||||
|
new GroupPath(focusedPath.segments().subList(0, level)));
|
||||||
|
if (candidate != null && candidate.getParent() == body)
|
||||||
|
destination = candidate;
|
||||||
|
if (candidate != null
|
||||||
|
&& !expansion.expanded(
|
||||||
|
new GroupPath(focusedPath.segments().subList(0, level))))
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (destination != null) destination.requestFocus();
|
||||||
|
else if (!header.getChildren().isEmpty())
|
||||||
|
((HBox) header.getChildren().getFirst())
|
||||||
|
.getChildren()
|
||||||
|
.getFirst()
|
||||||
|
.requestFocus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resizeGroupHeadings();
|
||||||
|
markSelection();
|
||||||
|
}
|
||||||
|
|
||||||
|
private GroupPath focusPath(Node focus) {
|
||||||
|
for (var entry : entries)
|
||||||
|
if (descendant(entry.view().root(), focus) && !grouping.isEmpty()) {
|
||||||
|
var values =
|
||||||
|
captured.rows().stream()
|
||||||
|
.filter(r -> Objects.equals(r.row().key(), entry.row().key()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.values();
|
||||||
|
return new GroupPath(
|
||||||
|
grouping.stream()
|
||||||
|
.map(id -> new GroupPath.Segment(id, values.get(id).key()))
|
||||||
|
.toList());
|
||||||
|
}
|
||||||
|
return disclosure.entrySet().stream()
|
||||||
|
.filter(e -> descendant(e.getValue(), focus))
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void appendGroups(
|
||||||
|
List<Node> nodes, List<GroupProjection.Node<K, T>> groups, Map<K, Node> rows) {
|
||||||
|
for (var group : groups) {
|
||||||
|
Button button =
|
||||||
|
disclosure.computeIfAbsent(
|
||||||
|
group.path(),
|
||||||
|
path -> {
|
||||||
|
Button control =
|
||||||
|
new Button() {
|
||||||
|
@Override
|
||||||
|
public Object queryAccessibleAttribute(
|
||||||
|
javafx.scene.AccessibleAttribute attribute,
|
||||||
|
Object... parameters) {
|
||||||
|
if (attribute
|
||||||
|
== javafx.scene.AccessibleAttribute
|
||||||
|
.EXPANDED)
|
||||||
|
return expansion.expanded(path);
|
||||||
|
if (attribute
|
||||||
|
== javafx.scene.AccessibleAttribute.LEAF)
|
||||||
|
return false;
|
||||||
|
return super.queryAccessibleAttribute(
|
||||||
|
attribute, parameters);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
control.setAccessibleRole(javafx.scene.AccessibleRole.TREE_ITEM);
|
||||||
|
control.getStyleClass().add("group-heading");
|
||||||
|
control.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
|
||||||
|
control.setOnAction(
|
||||||
|
e -> setExpanded(path, !expansion.expanded(path)));
|
||||||
|
control.setOnKeyPressed(e -> {
|
||||||
|
if (e.getCode() == javafx.scene.input.KeyCode.LEFT) {
|
||||||
|
setExpanded(path, false);
|
||||||
|
e.consume();
|
||||||
|
}
|
||||||
|
if (e.getCode() == javafx.scene.input.KeyCode.RIGHT) {
|
||||||
|
setExpanded(path, true);
|
||||||
|
e.consume();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return control;
|
||||||
|
});
|
||||||
|
String id = group.path().segments().getLast().columnId();
|
||||||
|
boolean open = expansion.expanded(group.path());
|
||||||
|
button.setText(
|
||||||
|
(open ? "▾ " : "▸ ")
|
||||||
|
+ definitions.get(id).header()
|
||||||
|
+ ": "
|
||||||
|
+ group.label()
|
||||||
|
+ " — "
|
||||||
|
+ group.count()
|
||||||
|
+ " records");
|
||||||
|
button.setAccessibleText(
|
||||||
|
definitions.get(id).header()
|
||||||
|
+ ": "
|
||||||
|
+ group.label()
|
||||||
|
+ ", "
|
||||||
|
+ group.count()
|
||||||
|
+ " records, "
|
||||||
|
+ (open ? "expanded" : "collapsed"));
|
||||||
|
button.setPadding(
|
||||||
|
new javafx.geometry.Insets(
|
||||||
|
6, 8, 6, 8 + 24 * (group.path().segments().size() - 1)));
|
||||||
|
button.notifyAccessibleAttributeChanged(javafx.scene.AccessibleAttribute.EXPANDED);
|
||||||
|
nodes.add(button);
|
||||||
|
if (open) {
|
||||||
|
if (group.children().isEmpty())
|
||||||
|
group.rows().forEach(row -> nodes.add(rows.get(row.key())));
|
||||||
|
else appendGroups(nodes, group.children(), rows);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resizeGroupHeadings() {
|
||||||
|
double total = order.stream().mapToDouble(this::width).sum();
|
||||||
|
disclosure.values().forEach(button -> size(button, total));
|
||||||
|
}
|
||||||
|
|
||||||
|
void previewWidth(String id, ColumnWidth value) {
|
||||||
|
var next = new LinkedHashMap<>(widths);
|
||||||
|
next.put(id, value);
|
||||||
|
applyWidths(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applyWidths(Map<String, ColumnWidth> sizes) {
|
||||||
|
for (Node node : header.getChildren())
|
||||||
|
size((Region) node, width((String) node.getUserData(), sizes));
|
||||||
|
entries.forEach(e -> layoutRow(e.view(), order, sizes));
|
||||||
|
double total = order.stream().mapToDouble(id -> width(id, sizes)).sum();
|
||||||
|
disclosure.values().forEach(button -> size(button, total));
|
||||||
|
}
|
||||||
|
|
||||||
private void release(List<Entry<K, T>> retired) {
|
private void release(List<Entry<K, T>> retired) {
|
||||||
RuntimeException aggregate = null;
|
RuntimeException aggregate = null;
|
||||||
for (var e : retired) {
|
for (var e : retired) {
|
||||||
@@ -394,6 +806,12 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
body.setOnMouseClicked(null);
|
body.setOnMouseClicked(null);
|
||||||
selectedKey.set(null);
|
selectedKey.set(null);
|
||||||
selectedElement.set(null);
|
selectedElement.set(null);
|
||||||
|
captured = GroupProjection.capture(List.of(), List.of());
|
||||||
|
groupTree = List.of();
|
||||||
|
disclosure.clear();
|
||||||
|
expansion.reset();
|
||||||
|
gestures.close();
|
||||||
|
scrollAlignment.close();
|
||||||
release(old);
|
release(old);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -835,7 +835,7 @@ public class ViewModel {
|
|||||||
* @return {@code true} when the element is a simple value
|
* @return {@code true} when the element is a simple value
|
||||||
*/
|
*/
|
||||||
private static boolean isSimpleValue(Class<?> type) {
|
private static boolean isSimpleValue(Class<?> type) {
|
||||||
if (type == String.class || type == Boolean.class || type == boolean.class || type.isEnum()) {
|
if (type == String.class || type == Boolean.class || type == boolean.class || type.isEnum() || type.isRecord()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (type.isPrimitive()) {
|
if (type.isPrimitive()) {
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
.data-grid-grouping { -fx-padding: 8; -fx-border-color: #8a9eb5; -fx-border-style: dashed; -fx-min-height: 42; }
|
||||||
|
.grouping-chip { -fx-padding: 4 8; -fx-alignment: center-left; -fx-background-color: #e8eff7; -fx-border-color: #8a9eb5; -fx-cursor: open-hand; }
|
||||||
|
.data-grid .column-cell { -fx-alignment: center-left; -fx-min-height: 32; }
|
||||||
|
.data-grid .column-header { -fx-padding: 5 6; }
|
||||||
|
.data-grid .column-resize:hover { -fx-background-color: #3776b6; }
|
||||||
|
.group-heading { -fx-background-color: #e8eff7; -fx-text-fill: #182b3b; -fx-border-color: transparent transparent #b4c4d5 transparent; -fx-background-radius: 0; -fx-alignment: center-left; }
|
||||||
|
.group-heading:focused { -fx-border-color: #3776b6; -fx-border-width: 2; }
|
||||||
|
.data-grid .drop-before { -fx-border-color: #2869bd; -fx-border-width: 0 0 0 4; }
|
||||||
|
.data-grid .drop-after { -fx-border-color: #2869bd; -fx-border-width: 0 4 0 0; }
|
||||||
|
.data-grid .drop-invalid { -fx-border-color: #a62e2e; -fx-border-width: 2; }
|
||||||
|
.neitzel-theme .grouping-chip, .neitzel-theme .group-heading { -fx-background-color: -nl-raised; -fx-text-fill: -nl-text; }
|
||||||
|
.neitzel-theme .group-heading:disabled { -fx-opacity: 1; }
|
||||||
|
.neitzel-theme .group-heading:focused { -fx-border-color: -nl-focus; }
|
||||||
|
.neitzel-theme .data-grid-grouping, .neitzel-theme .grouping-chip { -fx-border-color: -nl-border; }
|
||||||
|
.neitzel-theme .data-grid .column-resize:hover { -fx-background-color: -nl-focus; }
|
||||||
|
.grid-persistence-status { -fx-padding: 4 0; }
|
||||||
|
|
||||||
|
.data-grid .column-separator-line { -fx-stroke: -fx-box-border; -fx-stroke-width: 1; }
|
||||||
|
.neitzel-theme .data-grid .column-separator-line { -fx-stroke: -nl-border; }
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import de.neitzel.fx.control.NonNegativeIntegerSpinner;
|
||||||
|
import de.neitzel.fx.control.StatusBar;
|
||||||
|
import de.neitzel.fx.docking.DockPane;
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
import de.neitzel.injection.ApplicationContext;
|
||||||
|
|
||||||
|
import javafx.collections.*;
|
||||||
|
import javafx.fxml.FXMLLoader;
|
||||||
|
import javafx.scene.Parent;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
|
|
||||||
|
class DataGridFxmlTest {
|
||||||
|
public record Item(long id, String text, int count) {}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public static class Model {
|
||||||
|
private List<Item> rows = new ArrayList<>();
|
||||||
|
private int quantity = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
@TempDir Path directory;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void toolkit() throws Exception {
|
||||||
|
DataGridTest.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final String GRID =
|
||||||
|
"""
|
||||||
|
<?import de.neitzel.fx.view.*?>
|
||||||
|
<DataGrid xmlns:fx="http://javafx.com/fxml/1" keyAttribute="id" pageSize="1"
|
||||||
|
groupingEnabled="true" groupBy="text" setupId="sample" setupVersion="1">
|
||||||
|
<columns>
|
||||||
|
<DataGridColumn id="text" header="Text" width="180" checklist="SOURCE_WIDE"/>
|
||||||
|
<DataGridColumn id="count" header="Count" kind="INTEGER"/>
|
||||||
|
</columns>
|
||||||
|
</DataGrid>
|
||||||
|
""";
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static DataGrid<Long, Item> load(String fxml, Map<String, Object> namespace)
|
||||||
|
throws IOException {
|
||||||
|
FXMLLoader loader = new FXMLLoader();
|
||||||
|
loader.getNamespace().putAll(namespace);
|
||||||
|
return loader.load(new ByteArrayInputStream(fxml.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ordinaryFxmlShowsColumnsWithoutStartingQueries() throws Exception {
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
try {
|
||||||
|
var grid = load(GRID, Map.of());
|
||||||
|
assertNull(grid.stateProperty().get());
|
||||||
|
assertTrue(
|
||||||
|
grid.lookupAll(".column-header").stream()
|
||||||
|
.map(Label.class::cast)
|
||||||
|
.anyMatch(l -> l.getText().equals("Text")));
|
||||||
|
grid.close();
|
||||||
|
assertThrows(IllegalStateException.class, grid::initialize);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void localItemsRefreshReplaceAndDisposeWithTypedQueriesAndSavedDefaults() throws Exception {
|
||||||
|
var ref = new AtomicReference<DataGrid<Long, Item>>();
|
||||||
|
var list = FXCollections.observableArrayList(new Item(1, "b", 20), new Item(2, "a", 3));
|
||||||
|
var future = new AtomicReference<CompletionStage<Void>>();
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
try {
|
||||||
|
ref.set(
|
||||||
|
load(
|
||||||
|
GRID.replace("keyAttribute=", "items=\"$rows\" keyAttribute="),
|
||||||
|
Map.of("rows", list)));
|
||||||
|
future.set(ref.get().loadAsync());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
future.get().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
var grid = ref.get();
|
||||||
|
assertSame(list, grid.getItems());
|
||||||
|
assertEquals(1, grid.stateProperty().get().result().rows().size());
|
||||||
|
assertEquals(1, ((PageRequest.Paged) grid.snapshotSetup().page()).pageSize());
|
||||||
|
assertEquals(List.of("text"), grid.groupingColumns());
|
||||||
|
grid.setSort(new SortKey("count", SortKey.Direction.ASCENDING));
|
||||||
|
});
|
||||||
|
await(
|
||||||
|
ref.get(),
|
||||||
|
() ->
|
||||||
|
ref.get().stateProperty().get().result().rows().getFirst().model().count()
|
||||||
|
== 3);
|
||||||
|
DataGridTest.fx(() -> list.setAll(new Item(7, "new", 8)));
|
||||||
|
await(
|
||||||
|
ref.get(),
|
||||||
|
() -> ref.get().stateProperty().get().result().rows().getFirst().key() == 7L);
|
||||||
|
DataGridTest.fx(() ->
|
||||||
|
ref.get()
|
||||||
|
.setItems(
|
||||||
|
FXCollections.observableArrayList(new Item(9, "replacement", 1))));
|
||||||
|
await(
|
||||||
|
ref.get(),
|
||||||
|
() -> ref.get().stateProperty().get().result().rows().getFirst().key() == 9L);
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
long generation = ref.get().stateProperty().get().generation();
|
||||||
|
list.add(new Item(10, "detached", 2));
|
||||||
|
assertEquals(generation, ref.get().stateProperty().get().generation());
|
||||||
|
ref.get().close();
|
||||||
|
ref.get().getItems().clear();
|
||||||
|
});
|
||||||
|
DataGridTest.drain();
|
||||||
|
DataGridTest.fx(() ->
|
||||||
|
assertEquals(
|
||||||
|
GridCoordinator.Phase.CLOSED, ref.get().stateProperty().get().phase()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void bindsModelCollectionThroughViewLoader() throws Exception {
|
||||||
|
Path document = directory.resolve("bound.fxml");
|
||||||
|
Files.writeString(
|
||||||
|
document,
|
||||||
|
"""
|
||||||
|
<?import de.neitzel.fx.view.*?>
|
||||||
|
<?import javafx.scene.layout.VBox?>
|
||||||
|
<?import de.neitzel.fx.control.NonNegativeIntegerSpinner?>
|
||||||
|
<VBox xmlns:fx="http://javafx.com/fxml/1">
|
||||||
|
<fx:define><BindingList>
|
||||||
|
<DirectBinding control="grid" property="items" path="rows" direction="view"/>
|
||||||
|
<DirectBinding control="quantity" property="number" path="quantity" direction="both"/>
|
||||||
|
</BindingList></fx:define>
|
||||||
|
<NonNegativeIntegerSpinner fx:id="quantity" minimum="0" maximum="100" initialValue="0"/>
|
||||||
|
<DataGrid fx:id="grid" keyAttribute="id">
|
||||||
|
<columns><DataGridColumn id="text" header="Text"/></columns>
|
||||||
|
</DataGrid>
|
||||||
|
</VBox>
|
||||||
|
""");
|
||||||
|
Model model = new Model();
|
||||||
|
model.getRows().add(new Item(1, "bound", 1));
|
||||||
|
var ref = new AtomicReference<DataGrid<Long, Item>>();
|
||||||
|
var future = new AtomicReference<CompletionStage<Void>>();
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
try {
|
||||||
|
var view =
|
||||||
|
ViewLoader.load(
|
||||||
|
document.toUri().toURL(),
|
||||||
|
model,
|
||||||
|
new ApplicationContext("de.neitzel.fx.view.fixture"));
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
var grid = (DataGrid<Long, Item>) view.getRoot().lookup("#grid");
|
||||||
|
ref.set(grid);
|
||||||
|
assertSame(model.getRows(), grid.getItems());
|
||||||
|
var spinner = (NonNegativeIntegerSpinner) view.getRoot().lookup("#quantity");
|
||||||
|
assertEquals(10, spinner.getNumber());
|
||||||
|
spinner.getEditor().setText("11");
|
||||||
|
assertEquals(11, model.getQuantity());
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
var quantity = (javafx.beans.property.Property<Number>) view.property("quantity");
|
||||||
|
quantity.setValue(17);
|
||||||
|
assertEquals(17, spinner.getNumber());
|
||||||
|
future.set(grid.loadAsync());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
future.get().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||||
|
DataGridTest.fx(() -> model.getRows().add(new Item(2, "added", 2)));
|
||||||
|
await(ref.get(), () -> ref.get().stateProperty().get().result().rows().size() == 2);
|
||||||
|
DataGridTest.fx(() -> ref.get().close());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void externalSourceIsAssignedWithoutLoadingAndUsesTheSameFxmlColumns() throws Exception {
|
||||||
|
var calls = new AtomicInteger();
|
||||||
|
var source =
|
||||||
|
new MemoryGridSource<Long, Item>(
|
||||||
|
() -> {
|
||||||
|
calls.incrementAndGet();
|
||||||
|
return List.of(new Item(5, "external", 10));
|
||||||
|
},
|
||||||
|
Item::id,
|
||||||
|
Long::compareTo,
|
||||||
|
List.of(
|
||||||
|
new MemoryColumn<Item>(
|
||||||
|
"text",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.text())),
|
||||||
|
new MemoryColumn<Item>(
|
||||||
|
"count",
|
||||||
|
MemoryColumn.Kind.INTEGER,
|
||||||
|
i -> new FilterValue.IntegerValue(i.count()))),
|
||||||
|
Runnable::run,
|
||||||
|
250);
|
||||||
|
var ref = new AtomicReference<DataGrid<Long, Item>>();
|
||||||
|
var future = new AtomicReference<CompletionStage<Void>>();
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
try {
|
||||||
|
ref.set(
|
||||||
|
load(
|
||||||
|
GRID.replace("keyAttribute=\"id\"", "source=\"$source\"")
|
||||||
|
.replace("checklist=\"SOURCE_WIDE\"", ""),
|
||||||
|
Map.of("source", source)));
|
||||||
|
assertSame(source, ref.get().getSource());
|
||||||
|
assertEquals(0, calls.get());
|
||||||
|
future.set(ref.get().loadAsync());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
future.get().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
assertEquals(5L, ref.get().stateProperty().get().result().rows().getFirst().key());
|
||||||
|
ref.get().close();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void allPublicControlsCanBeConstructedByOrdinaryFxml() throws Exception {
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
try {
|
||||||
|
FXMLLoader loader = new FXMLLoader();
|
||||||
|
Parent root =
|
||||||
|
loader.load(
|
||||||
|
new ByteArrayInputStream(
|
||||||
|
"""
|
||||||
|
<?import de.neitzel.fx.control.*?>
|
||||||
|
<?import de.neitzel.fx.view.*?>
|
||||||
|
<?import de.neitzel.fx.docking.*?>
|
||||||
|
<?import javafx.scene.control.*?>
|
||||||
|
<?import javafx.scene.layout.VBox?>
|
||||||
|
<VBox xmlns:fx="http://javafx.com/fxml/1">
|
||||||
|
<StatusBar fx:id="status"><leftItems><Label text="Ready"/></leftItems></StatusBar>
|
||||||
|
<ToolBar><items><Button text="Save"/></items></ToolBar>
|
||||||
|
<NonNegativeIntegerSpinner fx:id="spinner" minimum="2" maximum="20" initialValue="7"/>
|
||||||
|
<DockPane fx:id="dock"><initialLayout><DockLayout><center>
|
||||||
|
<DockGroupDefinition destinationId="documents"/>
|
||||||
|
</center></DockLayout></initialLayout></DockPane>
|
||||||
|
<Table fx:id="table" collection="rows" row="example.Row">
|
||||||
|
<columns><Column header="Text" attribute="text"/></columns>
|
||||||
|
</Table>
|
||||||
|
<DataGrid fx:id="grid"><columns><DataGridColumn id="text" header="Text"/></columns></DataGrid>
|
||||||
|
</VBox>
|
||||||
|
"""
|
||||||
|
.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
assertNotNull(root);
|
||||||
|
assertEquals(
|
||||||
|
1, ((StatusBar) loader.getNamespace().get("status")).getLeftItems().size());
|
||||||
|
var spinner = (NonNegativeIntegerSpinner) loader.getNamespace().get("spinner");
|
||||||
|
assertEquals(7, spinner.getValue());
|
||||||
|
spinner.getEditor().setText("11");
|
||||||
|
assertEquals(11, spinner.getValue());
|
||||||
|
spinner.getEditor().setText("21");
|
||||||
|
assertEquals("11", spinner.getEditor().getText());
|
||||||
|
assertEquals(
|
||||||
|
"documents",
|
||||||
|
((de.neitzel.fx.docking.DockGroupDefinition)
|
||||||
|
((DockPane) loader.getNamespace().get("dock"))
|
||||||
|
.getInitialLayout()
|
||||||
|
.getCenter())
|
||||||
|
.getDestinationId());
|
||||||
|
((DataGrid<?, ?>) loader.getNamespace().get("grid")).close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void await(DataGrid<?, ?> grid, java.util.function.BooleanSupplier condition)
|
||||||
|
throws Exception {
|
||||||
|
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||||
|
var done = new AtomicBoolean();
|
||||||
|
while (!done.get() && System.nanoTime() < deadline) {
|
||||||
|
DataGridTest.fx(() ->
|
||||||
|
done.set(
|
||||||
|
grid.stateProperty().get().phase() == GridCoordinator.Phase.READY
|
||||||
|
&& condition.getAsBoolean()));
|
||||||
|
if (!done.get()) Thread.sleep(10);
|
||||||
|
}
|
||||||
|
assertTrue(done.get(), "Grid did not publish expected rows");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
|
|
||||||
|
class DataGridGroupingTest {
|
||||||
|
record Item(long id, String type, String status) {}
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void toolkit() throws Exception {
|
||||||
|
DataGridTest.start();
|
||||||
|
Platform.setImplicitExit(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
static <V> V fx(Callable<V> action) throws Exception {
|
||||||
|
var task = new FutureTask<>(action);
|
||||||
|
Platform.runLater(task);
|
||||||
|
return task.get(10, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
static DataGrid<Long, Item> grid(
|
||||||
|
AtomicInteger reads, AtomicInteger disposed, Map<Long, TextField> fields) {
|
||||||
|
var items =
|
||||||
|
List.of(
|
||||||
|
new Item(1, "A", "live"),
|
||||||
|
new Item(2, "MX", "live"),
|
||||||
|
new Item(3, "A", "missing"));
|
||||||
|
var source =
|
||||||
|
new MemoryGridSource<Long, Item>(
|
||||||
|
() -> {
|
||||||
|
reads.incrementAndGet();
|
||||||
|
return items;
|
||||||
|
},
|
||||||
|
Item::id,
|
||||||
|
Long::compare,
|
||||||
|
List.of(
|
||||||
|
new MemoryColumn<>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.type()))),
|
||||||
|
Runnable::run,
|
||||||
|
250);
|
||||||
|
var grid =
|
||||||
|
new DataGrid<Long, Item>(
|
||||||
|
List.of(
|
||||||
|
new ResultColumn("type", "Type", 150, 80, 400, -1),
|
||||||
|
new ResultColumn("status", "Status", 150, 80, 400, -1)),
|
||||||
|
i -> {
|
||||||
|
TextField field = new TextField(i.type());
|
||||||
|
fields.put(i.id(), field);
|
||||||
|
Label status = new Label(i.status());
|
||||||
|
return new ResultRow(
|
||||||
|
new HBox(field, status),
|
||||||
|
Map.of("type", field, "status", status),
|
||||||
|
disposed::incrementAndGet);
|
||||||
|
},
|
||||||
|
source);
|
||||||
|
grid.configureGrouping(
|
||||||
|
List.of(
|
||||||
|
new GroupColumn<>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.type()),
|
||||||
|
GroupColumn::display),
|
||||||
|
new GroupColumn<>(
|
||||||
|
"status",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.status()),
|
||||||
|
GroupColumn::display)),
|
||||||
|
true,
|
||||||
|
List.of("type"),
|
||||||
|
true,
|
||||||
|
1000);
|
||||||
|
grid.configureSetups(
|
||||||
|
"example", 1, Map.of("type", "text.v1", "status", "text.v1"), Map.of());
|
||||||
|
new Scene(new StackPane(grid), 800, 500);
|
||||||
|
grid.applyCss();
|
||||||
|
grid.layout();
|
||||||
|
return grid;
|
||||||
|
}
|
||||||
|
|
||||||
|
static GroupPath path(String type) {
|
||||||
|
return new GroupPath(List.of(new GroupPath.Segment("type", new FilterValue.Text(type))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void presentationChangesPreserveComponentsDraftsAndHiddenSelectionWithoutQueries()
|
||||||
|
throws Exception {
|
||||||
|
var reads = new AtomicInteger();
|
||||||
|
var disposed = new AtomicInteger();
|
||||||
|
Map<Long, TextField> fields = new HashMap<>();
|
||||||
|
var grid = fx(() -> grid(reads, disposed, fields));
|
||||||
|
fx(() -> grid.loadAsync()).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
try {
|
||||||
|
fx(() -> {
|
||||||
|
var editor = fields.get(1L);
|
||||||
|
editor.setText("unfinished draft");
|
||||||
|
grid.select(1L);
|
||||||
|
assertNull(grid.selectedElementProperty().get());
|
||||||
|
grid.setExpanded(path("A"), true);
|
||||||
|
assertEquals(1L, grid.selectedElementProperty().get().id());
|
||||||
|
grid.setGroupingColumns(List.of("type", "status"));
|
||||||
|
var child = path("A").child("status", new FilterValue.Text("live"));
|
||||||
|
grid.setExpanded(child, true);
|
||||||
|
grid.setColumnOrder(List.of("status", "type"));
|
||||||
|
grid.setColumnWidth("type", new ColumnWidth.Explicit(235));
|
||||||
|
grid.setExpanded(path("A"), false);
|
||||||
|
assertNull(grid.selectedElementProperty().get());
|
||||||
|
assertEquals(1L, grid.selectedKeyProperty().get());
|
||||||
|
grid.setExpanded(path("A"), true);
|
||||||
|
assertSame(editor, fields.get(1L));
|
||||||
|
assertEquals("unfinished draft", editor.getText());
|
||||||
|
assertEquals(0, disposed.get());
|
||||||
|
assertEquals(1, reads.get());
|
||||||
|
assertEquals(1L, grid.selectedElementProperty().get().id());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fx(() -> {
|
||||||
|
grid.close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assertEquals(3, disposed.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void oldSetupUsesConfiguredGroupingDefaultsAndRestorePublishesOnlyOnce() throws Exception {
|
||||||
|
var reads = new AtomicInteger();
|
||||||
|
var grid = fx(() -> grid(reads, new AtomicInteger(), new HashMap<>()));
|
||||||
|
try {
|
||||||
|
var snapshot = fx(grid::snapshotSetup);
|
||||||
|
var old =
|
||||||
|
new GridSetup(
|
||||||
|
1,
|
||||||
|
snapshot.definitionId(),
|
||||||
|
snapshot.definitionVersion(),
|
||||||
|
snapshot.columns(),
|
||||||
|
snapshot.sort(),
|
||||||
|
snapshot.filters(),
|
||||||
|
snapshot.page());
|
||||||
|
fx(() -> grid.restoreSetupAsync(old)).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
fx(() -> {
|
||||||
|
assertEquals(List.of("type"), grid.groupingColumns());
|
||||||
|
assertEquals(1, reads.get());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fx(() -> {
|
||||||
|
grid.close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fullDefaultsCanBeConfiguredBeforeAnySourceQuery() throws Exception {
|
||||||
|
var reads = new AtomicInteger();
|
||||||
|
var grid = fx(() -> grid(reads, new AtomicInteger(), new HashMap<>()));
|
||||||
|
try {
|
||||||
|
fx(() -> {
|
||||||
|
var state = grid.snapshotSetup();
|
||||||
|
grid.configureDefaults(
|
||||||
|
new GridSetup(
|
||||||
|
2,
|
||||||
|
state.definitionId(),
|
||||||
|
state.definitionVersion(),
|
||||||
|
state.columns(),
|
||||||
|
List.of(),
|
||||||
|
List.of(
|
||||||
|
new TextFilter(
|
||||||
|
"type", TextFilter.Operator.EQUALS, "A", true)),
|
||||||
|
new PageRequest.Paged(0, 25),
|
||||||
|
state.grouping()));
|
||||||
|
assertEquals(0, reads.get());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
fx(grid::loadAsync).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
fx(() -> {
|
||||||
|
assertEquals(2, grid.stateProperty().get().result().rows().size());
|
||||||
|
assertEquals(new PageRequest.Paged(0, 25), grid.defaultSetup().page());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fx(() -> {
|
||||||
|
grid.close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void explicitDataUpdateRecapturesValuesWithoutReplacingRowsOrQuerying() throws Exception {
|
||||||
|
var groupValue = new AtomicReference<>("A");
|
||||||
|
var reads = new AtomicInteger();
|
||||||
|
var fields = new HashMap<Long, TextField>();
|
||||||
|
var disposed = new AtomicInteger();
|
||||||
|
var grid =
|
||||||
|
fx(() -> {
|
||||||
|
var value = grid(reads, disposed, fields);
|
||||||
|
value.configureGrouping(
|
||||||
|
List.of(GroupColumn.<Item>text("type", item -> groupValue.get())),
|
||||||
|
true,
|
||||||
|
List.of("type"),
|
||||||
|
true,
|
||||||
|
1000);
|
||||||
|
return value;
|
||||||
|
});
|
||||||
|
fx(grid::loadAsync).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
try {
|
||||||
|
fx(() -> {
|
||||||
|
var editor = fields.get(1L);
|
||||||
|
groupValue.set("B");
|
||||||
|
assertEquals(1, grid.lookupAll(".group-heading").size());
|
||||||
|
assertTrue(
|
||||||
|
grid.lookupAll(".group-heading").stream()
|
||||||
|
.map(Button.class::cast)
|
||||||
|
.allMatch(button -> button.getText().contains("Type: A")));
|
||||||
|
grid.regroup();
|
||||||
|
assertTrue(
|
||||||
|
grid.lookupAll(".group-heading").stream()
|
||||||
|
.map(Button.class::cast)
|
||||||
|
.allMatch(button -> button.getText().contains("Type: B")));
|
||||||
|
assertSame(editor, fields.get(1L));
|
||||||
|
assertEquals(1, reads.get());
|
||||||
|
assertEquals(0, disposed.get());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fx(() -> {
|
||||||
|
grid.close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,617 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import de.neitzel.fx.grid.filter.FilterColumn;
|
||||||
|
import de.neitzel.fx.theme.ThemeManager;
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.geometry.*;
|
||||||
|
import javafx.scene.*;
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.image.PixelFormat;
|
||||||
|
import javafx.scene.input.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
import javafx.scene.robot.Robot;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||||
|
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
|
||||||
|
/** Opt-in native OS input, restricted to this suite's fictional-data window. */
|
||||||
|
@EnabledIfSystemProperty(named = "neitzellib.nativeGridTest", matches = "true")
|
||||||
|
@Timeout(120)
|
||||||
|
class DataGridNativeInteractionTest {
|
||||||
|
record Item(long id, String type, String status) {}
|
||||||
|
|
||||||
|
Stage stage;
|
||||||
|
Robot robot;
|
||||||
|
java.awt.Robot pointer;
|
||||||
|
DataGrid<Long, Item> grid;
|
||||||
|
ThemeManager themes;
|
||||||
|
VBox root;
|
||||||
|
CountDownLatch dragDone;
|
||||||
|
final List<Throwable> fxFailures = new CopyOnWriteArrayList<>();
|
||||||
|
Thread.UncaughtExceptionHandler previousExceptionHandler;
|
||||||
|
Map<Long, TextField> editors = new HashMap<>();
|
||||||
|
AtomicInteger queries = new AtomicInteger(),
|
||||||
|
created = new AtomicInteger(),
|
||||||
|
disposed = new AtomicInteger();
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void toolkit() throws Exception {
|
||||||
|
DataGridTest.start();
|
||||||
|
Platform.setImplicitExit(false);
|
||||||
|
assertTrue(
|
||||||
|
canPostInput(),
|
||||||
|
"macOS denies native event posting; grant the Java launcher and launching terminal"
|
||||||
|
+ " or IDE access");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean canPostInput() {
|
||||||
|
if (!System.getProperty("os.name").startsWith("Mac")) return true;
|
||||||
|
var library =
|
||||||
|
com.sun.jna.NativeLibrary.getInstance(
|
||||||
|
"/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics");
|
||||||
|
return (byte)
|
||||||
|
library.getFunction("CGPreflightPostEventAccess")
|
||||||
|
.invoke(byte.class, new Object[0])
|
||||||
|
!= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void open() throws Exception {
|
||||||
|
pointer = new java.awt.Robot();
|
||||||
|
pointer.setAutoDelay(15);
|
||||||
|
fx(() -> {
|
||||||
|
var thread = Thread.currentThread();
|
||||||
|
previousExceptionHandler = thread.getUncaughtExceptionHandler();
|
||||||
|
thread.setUncaughtExceptionHandler((failedThread, problem) -> fxFailures.add(problem));
|
||||||
|
var items =
|
||||||
|
java.util.stream.LongStream.range(0, 24)
|
||||||
|
.mapToObj(i ->
|
||||||
|
new Item(
|
||||||
|
i,
|
||||||
|
i % 2 == 0 ? "A" : "MX",
|
||||||
|
i % 3 == 0 ? "Missing" : "Live"))
|
||||||
|
.toList();
|
||||||
|
var source =
|
||||||
|
new MemoryGridSource<Long, Item>(
|
||||||
|
() -> {
|
||||||
|
queries.incrementAndGet();
|
||||||
|
return items;
|
||||||
|
},
|
||||||
|
Item::id,
|
||||||
|
Long::compare,
|
||||||
|
List.of(
|
||||||
|
new MemoryColumn<>(
|
||||||
|
"name",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text("record-" + i.id()))),
|
||||||
|
Runnable::run,
|
||||||
|
250);
|
||||||
|
grid =
|
||||||
|
new DataGrid<>(
|
||||||
|
List.of(
|
||||||
|
new ResultColumn("entry", "Entry (fixed)", 140, 100, 300, 0),
|
||||||
|
new ResultColumn("name", "Name", 300, 120, 600, -1),
|
||||||
|
new ResultColumn("type", "Type", 140, 100, 300, -1),
|
||||||
|
new ResultColumn("status", "Status", 260, 100, 600, -1)),
|
||||||
|
item -> {
|
||||||
|
created.incrementAndGet();
|
||||||
|
var name = new TextField("record-" + item.id());
|
||||||
|
editors.put(item.id(), name);
|
||||||
|
var entry = new Label("Record");
|
||||||
|
var type = new Label(item.type());
|
||||||
|
var status = new Label(item.status());
|
||||||
|
return new ResultRow(
|
||||||
|
new HBox(entry, name, type, status),
|
||||||
|
Map.of(
|
||||||
|
"entry", entry, "name", name, "type", type,
|
||||||
|
"status", status),
|
||||||
|
disposed::incrementAndGet);
|
||||||
|
},
|
||||||
|
source);
|
||||||
|
grid.configureGrouping(
|
||||||
|
List.of(
|
||||||
|
GroupColumn.<Item>text("name", i -> "record-" + i.id()),
|
||||||
|
GroupColumn.<Item>text("type", Item::type),
|
||||||
|
GroupColumn.<Item>text("status", Item::status)),
|
||||||
|
true,
|
||||||
|
List.of("type"),
|
||||||
|
true,
|
||||||
|
1000);
|
||||||
|
grid.configureSetups(
|
||||||
|
"native-edges",
|
||||||
|
1,
|
||||||
|
Map.of("entry", "text", "name", "text", "type", "text", "status", "text"),
|
||||||
|
Map.of());
|
||||||
|
grid.configureFilter("name", FilterColumn.text());
|
||||||
|
root =
|
||||||
|
new VBox(
|
||||||
|
8,
|
||||||
|
new Label("Native grid edge verification — fictional records only"),
|
||||||
|
grid);
|
||||||
|
root.setStyle("-fx-padding: 16;");
|
||||||
|
VBox.setVgrow(grid, Priority.ALWAYS);
|
||||||
|
stage = new Stage();
|
||||||
|
stage.setTitle("DataGrid native edge verification");
|
||||||
|
stage.setX(280);
|
||||||
|
stage.setY(160);
|
||||||
|
stage.setScene(new Scene(root, 1000, 760));
|
||||||
|
themes = new ThemeManager();
|
||||||
|
themes.register(stage.getScene());
|
||||||
|
stage.show();
|
||||||
|
stage.toFront();
|
||||||
|
stage.requestFocus();
|
||||||
|
robot = new Robot();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
waitFor(() -> stage.isFocused(), "Native fixture owns focus");
|
||||||
|
fx(grid::loadAsync).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
pause(120);
|
||||||
|
System.out.println(
|
||||||
|
"NATIVE os="
|
||||||
|
+ System.getProperty("os.name")
|
||||||
|
+ " java="
|
||||||
|
+ System.getProperty("java.version")
|
||||||
|
+ " scale="
|
||||||
|
+ fx(stage::getOutputScaleX));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void close() throws Exception {
|
||||||
|
if (stage == null) return;
|
||||||
|
if (pointer != null) {
|
||||||
|
pointer.mouseRelease(java.awt.event.InputEvent.BUTTON1_DOWN_MASK);
|
||||||
|
if (dragDone != null) dragDone.await(3, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
fx(() -> {
|
||||||
|
if (pointer != null) pointer.keyRelease(java.awt.event.KeyEvent.VK_ESCAPE);
|
||||||
|
if (grid != null) grid.close();
|
||||||
|
if (themes != null) themes.close();
|
||||||
|
stage.close();
|
||||||
|
Thread.currentThread().setUncaughtExceptionHandler(previousExceptionHandler);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
assertTrue(fxFailures.isEmpty(), () -> "Unexpected FX exceptions: " + fxFailures);
|
||||||
|
assertEquals(created.get(), disposed.get(), "Close releases all retained rows");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resizePreviewEscapeBoundsAndRelease() throws Exception {
|
||||||
|
var before = setup();
|
||||||
|
long revision = fx(() -> grid.committedRevisionProperty().get());
|
||||||
|
Point2D start = point(fx(() -> header("name").lookup(".column-resize")), .5, .5);
|
||||||
|
press(start);
|
||||||
|
move(start.add(130, 0));
|
||||||
|
pause(120);
|
||||||
|
assertEquals(before, setup(), "Preview is not committed");
|
||||||
|
capture("resize-preview");
|
||||||
|
assertEquals(430, fx(() -> header("name").getWidth()), 2);
|
||||||
|
key(KeyCode.ESCAPE);
|
||||||
|
release();
|
||||||
|
assertEquals(before, setup());
|
||||||
|
assertEquals(revision, fx(() -> grid.committedRevisionProperty().get()));
|
||||||
|
assertEquals(300, fx(() -> header("name").getWidth()), 1);
|
||||||
|
press(point(fx(() -> header("name").lookup(".column-resize")), .5, .5));
|
||||||
|
move(start.subtract(500, 0));
|
||||||
|
release();
|
||||||
|
assertEquals(new ColumnWidth.Explicit(120), width("name"));
|
||||||
|
unchangedSource();
|
||||||
|
System.out.println("PASS native resize preview/Escape/default intent/minimum/release");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void headerReorderFixedInvalidOutsideAndEscape() throws Exception {
|
||||||
|
var original = order();
|
||||||
|
begin(fx(() -> label("name")));
|
||||||
|
move(point(fx(() -> header("status")), .8, .5));
|
||||||
|
pause(120);
|
||||||
|
assertTrue(
|
||||||
|
fx(() -> header("status").getStyleClass().contains("drop-after")),
|
||||||
|
"Insertion marker before release");
|
||||||
|
capture("header-ghost-insertion");
|
||||||
|
release();
|
||||||
|
waitFor(
|
||||||
|
() -> grid.snapshotSetup().columns().getLast().id().equals("name"),
|
||||||
|
"Native reorder commits");
|
||||||
|
assertEquals(List.of("entry", "type", "status", "name"), order());
|
||||||
|
fx(() -> {
|
||||||
|
grid.setColumnOrder(original);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
begin(fx(() -> label("name")));
|
||||||
|
move(point(fx(() -> header("entry")), .1, .5));
|
||||||
|
pause(100);
|
||||||
|
assertTrue(fx(() -> header("entry").getStyleClass().contains("drop-invalid")));
|
||||||
|
capture("fixed-target-rejected");
|
||||||
|
release();
|
||||||
|
assertEquals(original, order());
|
||||||
|
begin(fx(() -> label("entry")));
|
||||||
|
move(point(fx(() -> header("status")), .8, .5));
|
||||||
|
release();
|
||||||
|
assertEquals(original, order());
|
||||||
|
begin(fx(() -> label("name")));
|
||||||
|
move(point(fx(() -> header("status")), .8, .5));
|
||||||
|
key(KeyCode.ESCAPE);
|
||||||
|
release();
|
||||||
|
assertEquals(original, order());
|
||||||
|
begin(fx(() -> label("name")));
|
||||||
|
move(point(fx(() -> root.getChildren().getFirst()), .5, .5));
|
||||||
|
release();
|
||||||
|
assertEquals(original, order());
|
||||||
|
unchangedSource();
|
||||||
|
assertTrue(
|
||||||
|
fx(() ->
|
||||||
|
stage.getScene().getFocusOwner() != null
|
||||||
|
&& stage.getScene().getFocusOwner().getScene() == stage.getScene()),
|
||||||
|
"Focus remains attached");
|
||||||
|
System.out.println(
|
||||||
|
"PASS native reorder/ghost/insertion/fixed source/fixed target/outside/Escape/no"
|
||||||
|
+ " sort");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void groupingAddDuplicateUnmappedChipReorderOutsideEscapeAndRemove() throws Exception {
|
||||||
|
var original = order();
|
||||||
|
begin(fx(() -> label("status")));
|
||||||
|
move(point(fx(this::bar), .8, .5));
|
||||||
|
release();
|
||||||
|
waitFor(() -> grid.groupingColumns().equals(List.of("type", "status")), "Add group");
|
||||||
|
begin(fx(() -> chip("status")));
|
||||||
|
move(point(fx(() -> chip("type")), .1, .5));
|
||||||
|
pause(100);
|
||||||
|
capture("chip-insertion");
|
||||||
|
release();
|
||||||
|
waitFor(() -> grid.groupingColumns().equals(List.of("status", "type")), "Reorder chips");
|
||||||
|
begin(fx(() -> label("status")));
|
||||||
|
move(point(fx(this::bar), .8, .5));
|
||||||
|
pause(80);
|
||||||
|
assertTrue(fx(() -> bar().getStyleClass().contains("drop-invalid")));
|
||||||
|
release();
|
||||||
|
assertEquals(List.of("status", "type"), groups());
|
||||||
|
begin(fx(() -> label("entry")));
|
||||||
|
move(point(fx(this::bar), .8, .5));
|
||||||
|
release();
|
||||||
|
assertEquals(List.of("status", "type"), groups());
|
||||||
|
begin(fx(() -> chip("status")));
|
||||||
|
move(point(fx(() -> header("name")), .5, .5));
|
||||||
|
release();
|
||||||
|
assertEquals(List.of("status", "type"), groups());
|
||||||
|
begin(fx(() -> chip("status")));
|
||||||
|
move(point(fx(this::bar), .9, .5));
|
||||||
|
key(KeyCode.ESCAPE);
|
||||||
|
release();
|
||||||
|
assertEquals(List.of("status", "type"), groups());
|
||||||
|
click(fx(() -> chip("status").getChildren().getLast()));
|
||||||
|
waitFor(() -> grid.groupingColumns().equals(List.of("type")), "Explicit chip removal");
|
||||||
|
assertEquals(original, order());
|
||||||
|
fx(() -> {
|
||||||
|
grid.setGroupingEnabled(false);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
assertFalse(fx(() -> bar().isVisible()));
|
||||||
|
fx(() -> {
|
||||||
|
grid.setGroupingEnabled(true);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
assertEquals(List.of("type"), groups());
|
||||||
|
unchangedSource();
|
||||||
|
System.out.println(
|
||||||
|
"PASS native grouping/chip"
|
||||||
|
+ " reorder/duplicate/unmapped/outside/Escape/removal/disabled capability");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void edgeScrollStopsOutsideAndKeepsHeadersAligned() throws Exception {
|
||||||
|
fx(() -> {
|
||||||
|
grid.setColumnWidth("name", new ColumnWidth.Explicit(600));
|
||||||
|
grid.setColumnWidth("status", new ColumnWidth.Explicit(600));
|
||||||
|
grid.setExpanded(path("A"), true);
|
||||||
|
grid.setExpanded(path("MX"), true);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
pause(100);
|
||||||
|
ScrollPane scroll = fx(() -> (ScrollPane) grid.lookup(".table-scroll"));
|
||||||
|
var original = order();
|
||||||
|
begin(fx(() -> label("name")));
|
||||||
|
Bounds viewport = fx(() -> scroll.localToScreen(scroll.getViewportBounds()));
|
||||||
|
move(new Point2D(viewport.getMaxX() - 10, point(fx(() -> header("type")), .5, .5).getY()));
|
||||||
|
waitFor(() -> scroll.getHvalue() > .1, "Native edge hover scrolls");
|
||||||
|
capture("edge-scroll");
|
||||||
|
// Leave vertically so the last header x remains in the edge zone.
|
||||||
|
// A diagonal exit can mask stale-pointer scrolling by crossing the centre.
|
||||||
|
move(
|
||||||
|
new Point2D(
|
||||||
|
viewport.getMaxX() - 10,
|
||||||
|
point(fx(() -> root.getChildren().getFirst()), .5, .5).getY()));
|
||||||
|
pause(150);
|
||||||
|
double stopped = fx(scroll::getHvalue);
|
||||||
|
pause(250);
|
||||||
|
assertEquals(stopped, fx(scroll::getHvalue), .001, "Leaving header stops scrolling");
|
||||||
|
key(KeyCode.ESCAPE);
|
||||||
|
release();
|
||||||
|
assertEquals(original, order());
|
||||||
|
double headerX =
|
||||||
|
fx(() -> header("type").localToScreen(header("type").getBoundsInLocal()).getMinX());
|
||||||
|
double rowX =
|
||||||
|
fx(() -> {
|
||||||
|
Node field = editors.get(0L).getParent().getChildrenUnmodifiable().get(2);
|
||||||
|
return field.localToScreen(field.getBoundsInLocal()).getMinX();
|
||||||
|
});
|
||||||
|
assertEquals(headerX, rowX, 1, "Header/body alignment");
|
||||||
|
fx(() -> {
|
||||||
|
scroll.setHvalue(0);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
pause(100);
|
||||||
|
begin(fx(() -> label("name")));
|
||||||
|
move(new Point2D(viewport.getMaxX() - 10, point(fx(() -> header("type")), .5, .5).getY()));
|
||||||
|
waitFor(() -> scroll.getHvalue() > .95, "Reach offscreen insertion target");
|
||||||
|
move(point(fx(() -> header("status")), .85, .5));
|
||||||
|
release();
|
||||||
|
assertEquals(List.of("entry", "type", "status", "name"), order());
|
||||||
|
capture("offscreen-drop-committed");
|
||||||
|
unchangedSource();
|
||||||
|
System.out.println(
|
||||||
|
"PASS native edge hover/outside stop/header-body alignment/offscreen drop");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void disclosureFocusDraftsFilterIsolationAndThemes() throws Exception {
|
||||||
|
Node heading =
|
||||||
|
fx(() ->
|
||||||
|
grid.lookupAll(".group-heading").stream()
|
||||||
|
.filter(n -> ((Button) n).getText().contains("Type: A"))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow());
|
||||||
|
click(heading);
|
||||||
|
waitFor(
|
||||||
|
() -> editors.get(0L).getParent().getParent() != null,
|
||||||
|
"Pointer disclosure expands");
|
||||||
|
click(editors.get(0L));
|
||||||
|
key(KeyCode.HOME);
|
||||||
|
key(KeyCode.X);
|
||||||
|
String draft = fx(() -> editors.get(0L).getText());
|
||||||
|
assertTrue(draft.toLowerCase(Locale.ROOT).startsWith("x"));
|
||||||
|
fx(() -> {
|
||||||
|
grid.select(0L);
|
||||||
|
grid.setExpanded(path("A"), false);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
assertNull(fx(() -> grid.selectedElementProperty().get()));
|
||||||
|
assertSame(heading, fx(() -> stage.getScene().getFocusOwner()));
|
||||||
|
key(KeyCode.RIGHT);
|
||||||
|
waitFor(
|
||||||
|
() -> grid.selectedElementProperty().get() != null,
|
||||||
|
"Keyboard disclosure restores selection");
|
||||||
|
assertEquals(draft, fx(() -> editors.get(0L).getText()));
|
||||||
|
click(fx(() -> header("name").lookup(".filter-button")));
|
||||||
|
pause(100);
|
||||||
|
assertEquals(1, queries.get());
|
||||||
|
assertTrue(setup().sort().isEmpty());
|
||||||
|
key(KeyCode.ESCAPE);
|
||||||
|
for (String theme : List.of("light", "dark", "high-contrast")) {
|
||||||
|
fx(() -> {
|
||||||
|
themes.select(theme);
|
||||||
|
grid.setGroupingColumns(List.of("type", "status"));
|
||||||
|
grid.setExpanded(path("A"), true);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
pause(100);
|
||||||
|
capture("nested-" + theme);
|
||||||
|
}
|
||||||
|
unchangedSource();
|
||||||
|
System.out.println(
|
||||||
|
"PASS native disclosure/drafts/hidden selection/focus/filter isolation/nested"
|
||||||
|
+ " themes");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void unchangedSource() throws Exception {
|
||||||
|
assertEquals(1, queries.get());
|
||||||
|
assertEquals(0, disposed.get());
|
||||||
|
assertTrue(setup().sort().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GroupPath path(String value) {
|
||||||
|
return new GroupPath(List.of(new GroupPath.Segment("type", new FilterValue.Text(value))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private HBox header(String id) {
|
||||||
|
return (HBox)
|
||||||
|
grid.lookupAll(".column-cell").stream()
|
||||||
|
.filter(n -> id.equals(n.getUserData()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Node label(String id) {
|
||||||
|
return header(id).getChildren().getFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
private HBox bar() {
|
||||||
|
return (HBox) grid.lookup(".data-grid-grouping");
|
||||||
|
}
|
||||||
|
|
||||||
|
private HBox chip(String id) {
|
||||||
|
return (HBox)
|
||||||
|
bar().getChildren().stream()
|
||||||
|
.filter(n -> id.equals(n.getUserData()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow();
|
||||||
|
}
|
||||||
|
|
||||||
|
private GridSetup setup() throws Exception {
|
||||||
|
return fx(grid::snapshotSetup);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> order() throws Exception {
|
||||||
|
return setup().columns().stream().map(GridSetup.ColumnState::id).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> groups() throws Exception {
|
||||||
|
return fx(grid::groupingColumns);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ColumnWidth width(String id) throws Exception {
|
||||||
|
return setup().columns().stream()
|
||||||
|
.filter(c -> c.id().equals(id))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow()
|
||||||
|
.width();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Point2D point(Node n, double x, double y) throws Exception {
|
||||||
|
return fx(() -> {
|
||||||
|
root.applyCss();
|
||||||
|
for (int pulse = 0; pulse < 3; pulse++) root.layout();
|
||||||
|
return n.localToScreen(
|
||||||
|
n.getBoundsInLocal().getMinX() + n.getBoundsInLocal().getWidth() * x,
|
||||||
|
n.getBoundsInLocal().getMinY() + n.getBoundsInLocal().getHeight() * y);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void focus() {
|
||||||
|
boolean ownedFocus =
|
||||||
|
javafx.stage.Window.getWindows().stream()
|
||||||
|
.anyMatch(window -> window.isFocused() && belongsToFixture(window));
|
||||||
|
assertTrue(ownedFocus, "Stop input if fixture and its owned popups lose focus");
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean belongsToFixture(javafx.stage.Window window) {
|
||||||
|
for (var current = window; current != null; ) {
|
||||||
|
if (current == stage) return true;
|
||||||
|
current =
|
||||||
|
current instanceof javafx.stage.PopupWindow popup
|
||||||
|
? popup.getOwnerWindow()
|
||||||
|
: current instanceof Stage owned ? owned.getOwner() : null;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void press(Point2D p) throws Exception {
|
||||||
|
fx(() -> {
|
||||||
|
focus();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
pointer.mouseMove((int) Math.round(p.getX()), (int) Math.round(p.getY()));
|
||||||
|
pause(60);
|
||||||
|
pointer.mousePress(java.awt.event.InputEvent.BUTTON1_DOWN_MASK);
|
||||||
|
pause(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void begin(Node n) throws Exception {
|
||||||
|
dragDone = new CountDownLatch(1);
|
||||||
|
var completed = dragDone;
|
||||||
|
fx(() -> {
|
||||||
|
n.addEventHandler(DragEvent.DRAG_DONE, event -> completed.countDown());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
Point2D p = point(n, .35, .5);
|
||||||
|
press(p);
|
||||||
|
move(p.add(16, 0));
|
||||||
|
pause(160);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void move(Point2D end) throws Exception {
|
||||||
|
Point2D start = fx(() -> new Point2D(robot.getMouseX(), robot.getMouseY()));
|
||||||
|
for (int i = 1; i <= 12; i++) {
|
||||||
|
Point2D p = start.add(end.subtract(start).multiply(i / 12.0));
|
||||||
|
fx(() -> {
|
||||||
|
focus();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
pointer.mouseMove((int) Math.round(p.getX()), (int) Math.round(p.getY()));
|
||||||
|
pause(18);
|
||||||
|
}
|
||||||
|
pause(70);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void release() throws Exception {
|
||||||
|
pointer.mouseRelease(java.awt.event.InputEvent.BUTTON1_DOWN_MASK);
|
||||||
|
if (dragDone != null) {
|
||||||
|
assertTrue(
|
||||||
|
dragDone.await(3, TimeUnit.SECONDS),
|
||||||
|
"Native drag completion must drain before the next gesture");
|
||||||
|
dragDone = null;
|
||||||
|
fx(() -> null);
|
||||||
|
}
|
||||||
|
pause(140);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void click(Node n) throws Exception {
|
||||||
|
press(point(n, .5, .5));
|
||||||
|
release();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void key(KeyCode code) throws Exception {
|
||||||
|
fx(() -> {
|
||||||
|
focus();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
// Use one native input source for the held pointer and keyboard events.
|
||||||
|
pointer.keyPress(code.getCode());
|
||||||
|
pointer.keyRelease(code.getCode());
|
||||||
|
pause(100);
|
||||||
|
// macOS completes cancellation asynchronously (including its return animation).
|
||||||
|
// Releasing early can clear JavaFX gesture state before the native callback.
|
||||||
|
if (code == KeyCode.ESCAPE && dragDone != null) {
|
||||||
|
assertTrue(
|
||||||
|
dragDone.await(5, TimeUnit.SECONDS),
|
||||||
|
"Escape must finish the native drag before mouse release");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void capture(String name) throws Exception {
|
||||||
|
Path dir = Path.of(System.getProperty("neitzellib.nativeGridOutput", "target/native-grid"));
|
||||||
|
Files.createDirectories(dir);
|
||||||
|
var image =
|
||||||
|
fx(() -> {
|
||||||
|
focus();
|
||||||
|
return robot.getScreenCapture(
|
||||||
|
null,
|
||||||
|
stage.getX(),
|
||||||
|
stage.getY(),
|
||||||
|
stage.getWidth(),
|
||||||
|
stage.getHeight(),
|
||||||
|
false);
|
||||||
|
});
|
||||||
|
int w = (int) image.getWidth(), h = (int) image.getHeight();
|
||||||
|
int[] pixels = new int[w * h];
|
||||||
|
image.getPixelReader()
|
||||||
|
.getPixels(0, 0, w, h, PixelFormat.getIntArgbInstance(), pixels, 0, w);
|
||||||
|
var output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
||||||
|
output.setRGB(0, 0, w, h, pixels, 0, w);
|
||||||
|
ImageIO.write(output, "png", dir.resolve(name + ".png").toFile());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void pause(long ms) throws InterruptedException {
|
||||||
|
Thread.sleep(ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <V> V fx(Callable<V> action) throws Exception {
|
||||||
|
var task = new FutureTask<>(action);
|
||||||
|
Platform.runLater(task);
|
||||||
|
return task.get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void waitFor(BooleanSupplier condition, String message) throws Exception {
|
||||||
|
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(4);
|
||||||
|
while (System.nanoTime() < until) {
|
||||||
|
if (fx(condition::getAsBoolean)) return;
|
||||||
|
pause(30);
|
||||||
|
}
|
||||||
|
assertTrue(fx(condition::getAsBoolean), message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.grid.filter.FilterColumn;
|
||||||
|
import de.neitzel.fx.theme.ThemeManager;
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.*;
|
||||||
|
import javafx.scene.layout.*;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
|
|
||||||
|
/** Manual native qualification surface. No synthetic OS input or real application data. */
|
||||||
|
public final class DataGridNativeProbe {
|
||||||
|
record Item(long id, String name, String type, String status) {}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
CountDownLatch done = new CountDownLatch(1);
|
||||||
|
Platform.startup(() -> {
|
||||||
|
Platform.setImplicitExit(false);
|
||||||
|
AtomicInteger queries = new AtomicInteger(),
|
||||||
|
created = new AtomicInteger(),
|
||||||
|
disposed = new AtomicInteger();
|
||||||
|
AtomicLong started = new AtomicLong();
|
||||||
|
List<Item> items = new ArrayList<>();
|
||||||
|
for (int i = 0; i < 2000; i++)
|
||||||
|
items.add(
|
||||||
|
new Item(
|
||||||
|
i,
|
||||||
|
"record-%04d.example.com.".formatted(i),
|
||||||
|
List.of("A", "CAA", "MX", "NS").get(i % 4),
|
||||||
|
i % 3 == 0 ? "Missing" : "Live"));
|
||||||
|
List<MemoryColumn<Item>> mappings =
|
||||||
|
List.of(
|
||||||
|
new MemoryColumn<>(
|
||||||
|
"entry",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text("Record")),
|
||||||
|
new MemoryColumn<>(
|
||||||
|
"name",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.name())),
|
||||||
|
new MemoryColumn<>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.type())),
|
||||||
|
new MemoryColumn<>(
|
||||||
|
"status",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.status())));
|
||||||
|
var source =
|
||||||
|
new MemoryGridSource<Long, Item>(
|
||||||
|
() -> {
|
||||||
|
queries.incrementAndGet();
|
||||||
|
started.set(System.nanoTime());
|
||||||
|
return items;
|
||||||
|
},
|
||||||
|
Item::id,
|
||||||
|
Long::compare,
|
||||||
|
mappings,
|
||||||
|
Runnable::run,
|
||||||
|
250);
|
||||||
|
var grid =
|
||||||
|
new DataGrid<Long, Item>(
|
||||||
|
List.of(
|
||||||
|
new ResultColumn("entry", "Entry (fixed)", 140, 100, 300, 0),
|
||||||
|
new ResultColumn("name", "Name", 300, 120, 600, -1),
|
||||||
|
new ResultColumn("type", "Type", 140, 80, 300, -1),
|
||||||
|
new ResultColumn("status", "Status", 260, 100, 600, -1)),
|
||||||
|
item -> {
|
||||||
|
created.incrementAndGet();
|
||||||
|
Label entry = new Label("Record");
|
||||||
|
TextField name = new TextField(item.name());
|
||||||
|
name.setAccessibleText("Record name draft " + item.id());
|
||||||
|
Label type = new Label(item.type()),
|
||||||
|
status = new Label(item.status());
|
||||||
|
return new ResultRow(
|
||||||
|
new HBox(entry, name, type, status),
|
||||||
|
Map.of(
|
||||||
|
"entry", entry, "name", name, "type", type,
|
||||||
|
"status", status),
|
||||||
|
disposed::incrementAndGet);
|
||||||
|
},
|
||||||
|
source);
|
||||||
|
grid.configureGrouping(
|
||||||
|
List.of(
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"name",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.name()),
|
||||||
|
GroupColumn::display),
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"type",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.type()),
|
||||||
|
GroupColumn::display),
|
||||||
|
new GroupColumn<Item>(
|
||||||
|
"status",
|
||||||
|
MemoryColumn.Kind.TEXT,
|
||||||
|
i -> new FilterValue.Text(i.status()),
|
||||||
|
GroupColumn::display)),
|
||||||
|
true,
|
||||||
|
List.of("type"),
|
||||||
|
true,
|
||||||
|
1000);
|
||||||
|
grid.configureSetups(
|
||||||
|
"native-grid",
|
||||||
|
1,
|
||||||
|
Map.of(
|
||||||
|
"entry", "text.v1", "name", "text.v1", "type", "text.v1", "status",
|
||||||
|
"text.v1"),
|
||||||
|
Map.of());
|
||||||
|
for (String id : List.of("entry", "name", "type", "status"))
|
||||||
|
grid.configureFilter(id, FilterColumn.text());
|
||||||
|
Label metrics = new Label();
|
||||||
|
metrics.setWrapText(true);
|
||||||
|
metrics.setId("probeMetrics");
|
||||||
|
ThemeManager themes = new ThemeManager();
|
||||||
|
HBox themeControls = new HBox(8);
|
||||||
|
for (String id : List.of("light", "dark", "high-contrast")) {
|
||||||
|
Button button = new Button("Theme " + id);
|
||||||
|
button.setOnAction(e -> themes.select(id));
|
||||||
|
themeControls.getChildren().add(button);
|
||||||
|
}
|
||||||
|
Button close = new Button("Close probe");
|
||||||
|
Button regroup = new Button("Explicit regroup"),
|
||||||
|
select = new Button("Select first record");
|
||||||
|
regroup.setOnAction(e -> grid.regroup());
|
||||||
|
select.setOnAction(e -> grid.select(0L));
|
||||||
|
VBox root =
|
||||||
|
new VBox(
|
||||||
|
10,
|
||||||
|
new Label(
|
||||||
|
"Native DataGrid qualification · fictional records · no"
|
||||||
|
+ " persistence"),
|
||||||
|
new Label(
|
||||||
|
"Entry is fixed and has no grouping mapping. Other columns"
|
||||||
|
+ " group. Draft fields test component retention."),
|
||||||
|
themeControls,
|
||||||
|
new HBox(8, regroup, select, close),
|
||||||
|
grid,
|
||||||
|
metrics);
|
||||||
|
root.setStyle("-fx-padding: 16;");
|
||||||
|
VBox.setVgrow(grid, Priority.ALWAYS);
|
||||||
|
Stage stage = new Stage();
|
||||||
|
close.setOnAction(e -> stage.close());
|
||||||
|
stage.setTitle("DataGrid native qualification");
|
||||||
|
stage.setScene(new Scene(root, 1000, 800));
|
||||||
|
themes.register(stage.getScene());
|
||||||
|
Runnable describe =
|
||||||
|
() -> {
|
||||||
|
GridSetup setup = grid.snapshotSetup();
|
||||||
|
String text =
|
||||||
|
"Order: "
|
||||||
|
+ setup.columns().stream()
|
||||||
|
.map(GridSetup.ColumnState::id)
|
||||||
|
.toList()
|
||||||
|
+ " | widths: "
|
||||||
|
+ setup.columns().stream()
|
||||||
|
.map(c -> c.id() + "=" + c.width())
|
||||||
|
.toList()
|
||||||
|
+ " | groups: "
|
||||||
|
+ grid.groupingColumns()
|
||||||
|
+ " | source queries: "
|
||||||
|
+ queries.get()
|
||||||
|
+ " | created/disposed: "
|
||||||
|
+ created.get()
|
||||||
|
+ "/"
|
||||||
|
+ disposed.get()
|
||||||
|
+ " | window: "
|
||||||
|
+ stage.getX()
|
||||||
|
+ ","
|
||||||
|
+ stage.getY()
|
||||||
|
+ " scale="
|
||||||
|
+ stage.getOutputScaleX()
|
||||||
|
+ " | actionable selection: "
|
||||||
|
+ (grid.selectedElementProperty().get() != null);
|
||||||
|
metrics.setText(text);
|
||||||
|
System.out.println("STATE " + text);
|
||||||
|
};
|
||||||
|
grid.committedRevisionProperty().addListener((o, b, a) -> describe.run());
|
||||||
|
grid.selectedElementProperty().addListener((o, b, a) -> describe.run());
|
||||||
|
grid.stateProperty()
|
||||||
|
.addListener((o, b, a) -> {
|
||||||
|
if (a.phase() == GridCoordinator.Phase.READY)
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
root.applyCss();
|
||||||
|
root.layout();
|
||||||
|
describe.run();
|
||||||
|
System.out.println(
|
||||||
|
"PUBLICATION rows="
|
||||||
|
+ a.result().rows().size()
|
||||||
|
+ " elapsedMs="
|
||||||
|
+ (System.nanoTime() - started.get()) / 1_000_000.0
|
||||||
|
+ " retained="
|
||||||
|
+ (created.get() - disposed.get())
|
||||||
|
+ " scale="
|
||||||
|
+ stage.getOutputScaleX());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
stage.setOnHidden(e -> {
|
||||||
|
grid.close();
|
||||||
|
themes.close();
|
||||||
|
System.out.println(
|
||||||
|
"CLOSE created=" + created.get() + " disposed=" + disposed.get());
|
||||||
|
done.countDown();
|
||||||
|
Platform.runLater(Platform::exit);
|
||||||
|
});
|
||||||
|
stage.show();
|
||||||
|
stage.toFront();
|
||||||
|
grid.load();
|
||||||
|
System.out.println(
|
||||||
|
"NATIVE READY java="
|
||||||
|
+ System.getProperty("java.version")
|
||||||
|
+ " javafx="
|
||||||
|
+ System.getProperty("javafx.version")
|
||||||
|
+ " os="
|
||||||
|
+ System.getProperty("os.name"));
|
||||||
|
});
|
||||||
|
done.await();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
class DataGridScalingTest {
|
||||||
|
record Item(long id) {}
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void toolkit() throws Exception {
|
||||||
|
DataGridGroupingTest.toolkit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void pageCyclesBoundRowsAndCaptureWorkIncludingExplicitlyApprovedAll() throws Exception {
|
||||||
|
var queries = new AtomicInteger();
|
||||||
|
var mappings = new AtomicInteger();
|
||||||
|
var created = new AtomicInteger();
|
||||||
|
var disposed = new AtomicInteger();
|
||||||
|
var approvals = new AtomicInteger();
|
||||||
|
var grid =
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
List<Item> items =
|
||||||
|
java.util.stream.LongStream.range(0, 2000).mapToObj(Item::new).toList();
|
||||||
|
var source =
|
||||||
|
new MemoryGridSource<Long, Item>(
|
||||||
|
() -> {
|
||||||
|
queries.incrementAndGet();
|
||||||
|
return items;
|
||||||
|
},
|
||||||
|
Item::id,
|
||||||
|
Long::compare,
|
||||||
|
List.of(
|
||||||
|
new MemoryColumn<>(
|
||||||
|
"id",
|
||||||
|
MemoryColumn.Kind.INTEGER,
|
||||||
|
i -> new FilterValue.IntegerValue(i.id()))),
|
||||||
|
Runnable::run,
|
||||||
|
250);
|
||||||
|
var value =
|
||||||
|
new DataGrid<Long, Item>(
|
||||||
|
List.of(
|
||||||
|
new ResultColumn("id", "Identifier", 150, 80, 400, -1),
|
||||||
|
new ResultColumn("type", "Type", 150, 80, 400, -1),
|
||||||
|
new ResultColumn("status", "Status", 150, 80, 400, -1)),
|
||||||
|
item -> {
|
||||||
|
created.incrementAndGet();
|
||||||
|
Label label = new Label(Long.toString(item.id()));
|
||||||
|
Label type = new Label("T" + item.id() % 4),
|
||||||
|
status = new Label("S" + item.id() % 3);
|
||||||
|
return new ResultRow(
|
||||||
|
new HBox(label, type, status),
|
||||||
|
Map.of("id", label, "type", type, "status", status),
|
||||||
|
disposed::incrementAndGet);
|
||||||
|
},
|
||||||
|
source);
|
||||||
|
value.configureGrouping(
|
||||||
|
List.of(
|
||||||
|
GroupColumn.<Item>integer(
|
||||||
|
"id",
|
||||||
|
item -> {
|
||||||
|
mappings.incrementAndGet();
|
||||||
|
return item.id();
|
||||||
|
}),
|
||||||
|
GroupColumn.<Item>text(
|
||||||
|
"type",
|
||||||
|
item -> {
|
||||||
|
mappings.incrementAndGet();
|
||||||
|
return "T" + item.id() % 4;
|
||||||
|
}),
|
||||||
|
GroupColumn.<Item>text(
|
||||||
|
"status",
|
||||||
|
item -> {
|
||||||
|
mappings.incrementAndGet();
|
||||||
|
return "S" + item.id() % 3;
|
||||||
|
})),
|
||||||
|
true,
|
||||||
|
List.of("id"),
|
||||||
|
true,
|
||||||
|
1000);
|
||||||
|
value.configureSetups(
|
||||||
|
"scaling",
|
||||||
|
1,
|
||||||
|
Map.of("id", "integer.v1", "type", "text.v1", "status", "text.v1"),
|
||||||
|
Map.of());
|
||||||
|
value.setAllConfirmation((query, count) -> {
|
||||||
|
approvals.incrementAndGet();
|
||||||
|
assertEquals(2000, count);
|
||||||
|
return CompletableFuture.completedFuture(true);
|
||||||
|
});
|
||||||
|
return value;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
int cycle = 0;
|
||||||
|
for (int size : List.of(50, 250, 50, 250, 2000, 50)) {
|
||||||
|
int levels = cycle >= 2 && cycle <= 4 ? 3 : 1;
|
||||||
|
cycle++;
|
||||||
|
var before = DataGridGroupingTest.fx(grid::snapshotSetup);
|
||||||
|
var setup =
|
||||||
|
new GridSetup(
|
||||||
|
2,
|
||||||
|
before.definitionId(),
|
||||||
|
before.definitionVersion(),
|
||||||
|
before.columns(),
|
||||||
|
before.sort(),
|
||||||
|
before.filters(),
|
||||||
|
size == 2000
|
||||||
|
? new PageRequest.All()
|
||||||
|
: new PageRequest.Paged(0, size),
|
||||||
|
new GroupingSetup(
|
||||||
|
levels == 3
|
||||||
|
? List.of("type", "status", "id")
|
||||||
|
: List.of("id"),
|
||||||
|
before.grouping().choices()));
|
||||||
|
int captured = mappings.get();
|
||||||
|
long started = System.nanoTime();
|
||||||
|
DataGridGroupingTest.fx(() -> grid.restoreSetupAsync(setup))
|
||||||
|
.toCompletableFuture()
|
||||||
|
.get(10, TimeUnit.SECONDS);
|
||||||
|
double publicationMs = (System.nanoTime() - started) / 1_000_000.0;
|
||||||
|
assertEquals(size, created.get() - disposed.get());
|
||||||
|
assertEquals(size * 3, mappings.get() - captured);
|
||||||
|
int queried = queries.get(), retired = disposed.get();
|
||||||
|
long regroupStarted = System.nanoTime();
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
grid.regroup();
|
||||||
|
grid.resetExpansion();
|
||||||
|
grid.setColumnWidth("id", new ColumnWidth.Explicit(200));
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
double localMs = (System.nanoTime() - regroupStarted) / 1_000_000.0;
|
||||||
|
assertEquals(queried, queries.get());
|
||||||
|
assertEquals(retired, disposed.get());
|
||||||
|
assertEquals(size * 6, mappings.get() - captured);
|
||||||
|
System.out.printf(
|
||||||
|
Locale.ROOT,
|
||||||
|
"SCALING rows=%d levels=%d publicationMs=%.3f regroupResetResizeMs=%.3f"
|
||||||
|
+ " mappings=%d retained=%d created=%d disposed=%d%n",
|
||||||
|
size,
|
||||||
|
levels,
|
||||||
|
publicationMs,
|
||||||
|
localMs,
|
||||||
|
mappings.get() - captured,
|
||||||
|
created.get() - disposed.get(),
|
||||||
|
created.get(),
|
||||||
|
disposed.get());
|
||||||
|
}
|
||||||
|
assertEquals(1, approvals.get());
|
||||||
|
} finally {
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
grid.close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assertEquals(created.get(), disposed.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,6 +61,29 @@ class DataGridTest {
|
|||||||
source);
|
source);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void viewportUsesAvailableHeightAndGrowsWithGrid() throws Exception {
|
||||||
|
fx(() -> {
|
||||||
|
var g = grid(List.of(new Item(1, "Alpha")), new AtomicInteger());
|
||||||
|
try {
|
||||||
|
var root = new javafx.scene.layout.StackPane(g);
|
||||||
|
new javafx.scene.Scene(root, 800, 400);
|
||||||
|
root.applyCss();
|
||||||
|
root.resize(800, 400);
|
||||||
|
root.layout();
|
||||||
|
var viewport = (javafx.scene.control.ScrollPane) g.lookup(".table-scroll");
|
||||||
|
double before = viewport.getHeight();
|
||||||
|
assertTrue(before > 200, "Viewport should fill the grid above paging controls");
|
||||||
|
root.resize(800, 700);
|
||||||
|
root.layout();
|
||||||
|
assertEquals(300, viewport.getHeight() - before, 1,
|
||||||
|
"Additional height must reach the scrolling body");
|
||||||
|
} finally {
|
||||||
|
g.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void pagingFilteringSelectionAndAllUseCoordinatorWithoutChangingLegacyTable() throws Exception {
|
void pagingFilteringSelectionAndAllUseCoordinatorWithoutChangingLegacyTable() throws Exception {
|
||||||
var ref = new AtomicReference<DataGrid<Long, Item>>();
|
var ref = new AtomicReference<DataGrid<Long, Item>>();
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
|
|
||||||
|
class GridPersistenceAttachmentTest {
|
||||||
|
static class Store implements GridSetupStore {
|
||||||
|
GridSetup value;
|
||||||
|
int revision, writes;
|
||||||
|
boolean unreadable;
|
||||||
|
|
||||||
|
public synchronized Stored load(Key key) {
|
||||||
|
if (unreadable) throw new IllegalArgumentException("Malformed document");
|
||||||
|
return new Stored(value, "" + revision);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized String revision(Key key) {
|
||||||
|
return "" + revision;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized String save(Key key, String expected, GridSetup setup)
|
||||||
|
throws java.io.IOException {
|
||||||
|
if (!expected.equals("" + revision)) throw new Conflict();
|
||||||
|
value = setup;
|
||||||
|
unreadable = false;
|
||||||
|
writes++;
|
||||||
|
return "" + (++revision);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void toolkit() throws Exception {
|
||||||
|
DataGridTest.start();
|
||||||
|
Platform.setImplicitExit(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
record View(
|
||||||
|
DataGrid<Long, DataGridGroupingTest.Item> grid,
|
||||||
|
GridPersistenceAttachment<Long, DataGridGroupingTest.Item> attachment,
|
||||||
|
AtomicInteger queries) {}
|
||||||
|
|
||||||
|
static View view(GridApplicationConfiguration config) throws Exception {
|
||||||
|
return DataGridGroupingTest.fx(() -> {
|
||||||
|
AtomicInteger queries = new AtomicInteger();
|
||||||
|
var grid = DataGridGroupingTest.grid(queries, new AtomicInteger(), new HashMap<>());
|
||||||
|
var attachment = grid.attachPersistence(config, "records");
|
||||||
|
return new View(grid, attachment, queries);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void loadPrecedesQueryAndDetachedViewLeavesItsAcceptedSaveWithTheService() throws Exception {
|
||||||
|
var store = new Store();
|
||||||
|
var config =
|
||||||
|
new GridApplicationConfiguration(
|
||||||
|
"Example",
|
||||||
|
store,
|
||||||
|
Duration.ofHours(1),
|
||||||
|
Executors.newSingleThreadScheduledExecutor(),
|
||||||
|
true);
|
||||||
|
var first = view(config);
|
||||||
|
assertEquals(0, first.queries().get());
|
||||||
|
DataGridGroupingTest.fx(first.attachment()::loadAsync)
|
||||||
|
.toCompletableFuture()
|
||||||
|
.get(5, TimeUnit.SECONDS);
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
first.grid().setColumnWidth("type", new ColumnWidth.Explicit(270));
|
||||||
|
first.grid().setExpanded(DataGridGroupingTest.path("A"), true);
|
||||||
|
first.grid().close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
var second = view(config);
|
||||||
|
DataGridGroupingTest.fx(second.attachment()::loadAsync)
|
||||||
|
.toCompletableFuture()
|
||||||
|
.get(5, TimeUnit.SECONDS);
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
assertEquals(
|
||||||
|
new ColumnWidth.Explicit(270),
|
||||||
|
second.grid().snapshotSetup().columns().getFirst().width());
|
||||||
|
assertTrue(
|
||||||
|
second.grid().snapshotSetup().grouping().choices().stream()
|
||||||
|
.anyMatch(c ->
|
||||||
|
c.path().equals(DataGridGroupingTest.path("A"))
|
||||||
|
&& c.expanded()));
|
||||||
|
assertEquals(1, second.queries().get());
|
||||||
|
second.grid().close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unreadableStartupDoesNotQueryOrOverwriteUntilExplicitResetSucceeds() throws Exception {
|
||||||
|
var store = new Store();
|
||||||
|
store.unreadable = true;
|
||||||
|
var config =
|
||||||
|
new GridApplicationConfiguration(
|
||||||
|
"Example",
|
||||||
|
store,
|
||||||
|
Duration.ofHours(1),
|
||||||
|
Executors.newSingleThreadScheduledExecutor(),
|
||||||
|
true);
|
||||||
|
var view = view(config);
|
||||||
|
assertThrows(
|
||||||
|
ExecutionException.class,
|
||||||
|
() ->
|
||||||
|
DataGridGroupingTest.fx(view.attachment()::loadAsync)
|
||||||
|
.toCompletableFuture()
|
||||||
|
.get(5, TimeUnit.SECONDS));
|
||||||
|
assertEquals(0, view.queries().get());
|
||||||
|
assertEquals(0, store.writes);
|
||||||
|
DataGridGroupingTest.fx(view.attachment()::resetAsync)
|
||||||
|
.toCompletableFuture()
|
||||||
|
.get(5, TimeUnit.SECONDS);
|
||||||
|
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
assertEquals(1, view.queries().get());
|
||||||
|
assertEquals(1, store.writes);
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
view.grid().close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void applicationCloseDuringRestoreCompletesTheOperationWithAVisibleFailure() throws Exception {
|
||||||
|
var config = new GridApplicationConfiguration("Example", new Store());
|
||||||
|
var view = view(config);
|
||||||
|
var guard = new CompletableFuture<Boolean>();
|
||||||
|
var entered = new CountDownLatch(1);
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
view.grid()
|
||||||
|
.setEditGuard(query -> {
|
||||||
|
entered.countDown();
|
||||||
|
return guard;
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
var loading = DataGridGroupingTest.fx(view.attachment()::loadAsync);
|
||||||
|
try {
|
||||||
|
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||||
|
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
guard.complete(true);
|
||||||
|
assertThrows(
|
||||||
|
ExecutionException.class,
|
||||||
|
() -> loading.toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
assertTrue(
|
||||||
|
view.grid().lookupAll(".grid-persistence-status").stream()
|
||||||
|
.map(javafx.scene.control.Label.class::cast)
|
||||||
|
.anyMatch(label -> label.getText().contains("unavailable")));
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
guard.complete(false);
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
view.grid().close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
config.discardAndCloseAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import de.neitzel.grid.ColumnWidth;
|
||||||
|
|
||||||
|
import javafx.event.Event;
|
||||||
|
import javafx.scene.Node;
|
||||||
|
import javafx.scene.input.*;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
/** Handler-level rollback/commit checks; native drag routing is qualified separately. */
|
||||||
|
class ResultHeaderGesturesTest {
|
||||||
|
@BeforeAll
|
||||||
|
static void toolkit() throws Exception {
|
||||||
|
DataGridGroupingTest.toolkit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resizePreviewEscapeBoundsAndReleaseNeverSortOrReplaceRows() throws Exception {
|
||||||
|
var reads = new AtomicInteger();
|
||||||
|
var disposed = new AtomicInteger();
|
||||||
|
var fields = new HashMap<Long, javafx.scene.control.TextField>();
|
||||||
|
var grid =
|
||||||
|
DataGridGroupingTest.fx(() -> DataGridGroupingTest.grid(reads, disposed, fields));
|
||||||
|
DataGridGroupingTest.fx(grid::loadAsync).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||||
|
try {
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
Node handle =
|
||||||
|
grid.lookupAll(".column-resize").stream()
|
||||||
|
.filter(n -> "type".equals(n.getParent().getUserData()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow();
|
||||||
|
HBox cell = (HBox) handle.getParent();
|
||||||
|
var before = grid.snapshotSetup();
|
||||||
|
long revision = grid.committedRevisionProperty().get();
|
||||||
|
Event.fireEvent(handle, mouse(MouseEvent.MOUSE_PRESSED, 100));
|
||||||
|
Event.fireEvent(handle, mouse(MouseEvent.MOUSE_DRAGGED, 5000));
|
||||||
|
assertEquals(400, cell.getPrefWidth());
|
||||||
|
assertEquals(before, grid.snapshotSetup(), "Preview must not be persisted");
|
||||||
|
Event.fireEvent(
|
||||||
|
grid.getScene(),
|
||||||
|
new KeyEvent(
|
||||||
|
KeyEvent.KEY_PRESSED,
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
KeyCode.ESCAPE,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false));
|
||||||
|
assertEquals(150, cell.getPrefWidth());
|
||||||
|
assertEquals(revision, grid.committedRevisionProperty().get());
|
||||||
|
Event.fireEvent(handle, mouse(MouseEvent.MOUSE_RELEASED, 5000));
|
||||||
|
assertEquals(before, grid.snapshotSetup());
|
||||||
|
Event.fireEvent(handle, mouse(MouseEvent.MOUSE_PRESSED, 100));
|
||||||
|
Event.fireEvent(handle, mouse(MouseEvent.MOUSE_DRAGGED, -500));
|
||||||
|
Event.fireEvent(handle, mouse(MouseEvent.MOUSE_RELEASED, -500));
|
||||||
|
Event.fireEvent(handle, mouse(MouseEvent.MOUSE_CLICKED, -500));
|
||||||
|
assertEquals(
|
||||||
|
new ColumnWidth.Explicit(80),
|
||||||
|
grid.snapshotSetup().columns().getFirst().width());
|
||||||
|
assertEquals(revision + 1, grid.committedRevisionProperty().get());
|
||||||
|
assertTrue(grid.snapshotSetup().sort().isEmpty());
|
||||||
|
assertEquals(1, reads.get());
|
||||||
|
assertEquals(0, disposed.get());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
DataGridGroupingTest.fx(() -> {
|
||||||
|
grid.close();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MouseEvent mouse(javafx.event.EventType<MouseEvent> type, double screenX) {
|
||||||
|
return new MouseEvent(
|
||||||
|
type,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
screenX,
|
||||||
|
100,
|
||||||
|
MouseButton.PRIMARY,
|
||||||
|
1,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
type != MouseEvent.MOUSE_RELEASED,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -47,8 +47,7 @@ class TableResultsTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void resultOrderMappingSelectionAndLifetime() throws Exception {
|
void resultOrderMappingSelectionAndLifetime() throws Exception {
|
||||||
fx(
|
fx(() -> {
|
||||||
() -> {
|
|
||||||
Table table = new Table();
|
Table table = new Table();
|
||||||
AtomicInteger disposed = new AtomicInteger();
|
AtomicInteger disposed = new AtomicInteger();
|
||||||
List<ResultRow> views = new ArrayList<>();
|
List<ResultRow> views = new ArrayList<>();
|
||||||
@@ -64,17 +63,13 @@ class TableResultsTest {
|
|||||||
VBox body = (VBox) ((ScrollPane) table.getChildren().get(1)).getContent();
|
VBox body = (VBox) ((ScrollPane) table.getChildren().get(1)).getContent();
|
||||||
assertEquals(
|
assertEquals(
|
||||||
"Z",
|
"Z",
|
||||||
((Label) ((HBox) body.getChildren().get(0)).getChildren().get(0))
|
((Label) ((HBox) body.getChildren().get(0)).getChildren().get(0)).getText());
|
||||||
.getText());
|
|
||||||
renderer.select(2);
|
renderer.select(2);
|
||||||
assertEquals("Z", renderer.selectedElementProperty().get());
|
assertEquals("Z", renderer.selectedElementProperty().get());
|
||||||
renderer.setColumnOrder(List.of("city", "name"));
|
renderer.setColumnOrder(List.of("city", "name"));
|
||||||
assertSame(
|
assertSame(views.get(0).fields().get("city"), views.get(0).root().getChildren().get(0));
|
||||||
views.get(0).fields().get("city"),
|
|
||||||
views.get(0).root().getChildren().get(0));
|
|
||||||
assertInstanceOf(Button.class, views.get(0).root().getChildren().get(2));
|
assertInstanceOf(Button.class, views.get(0).root().getChildren().get(2));
|
||||||
assertEquals(
|
assertEquals(200, renderer.setColumnWidth("city", new ColumnWidth.Explicit(999)));
|
||||||
200, renderer.setColumnWidth("city", new ColumnWidth.Explicit(999)));
|
|
||||||
assertEquals(200, views.get(0).fields().get("city").getPrefWidth());
|
assertEquals(200, views.get(0).fields().get("city").getPrefWidth());
|
||||||
assertThrows(
|
assertThrows(
|
||||||
IllegalArgumentException.class,
|
IllegalArgumentException.class,
|
||||||
@@ -96,8 +91,7 @@ class TableResultsTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void failedReplacementKeepsOldRowsAndReleasesStagedRows() throws Exception {
|
void failedReplacementKeepsOldRowsAndReleasesStagedRows() throws Exception {
|
||||||
fx(
|
fx(() -> {
|
||||||
() -> {
|
|
||||||
AtomicInteger disposed = new AtomicInteger();
|
AtomicInteger disposed = new AtomicInteger();
|
||||||
Table t = new Table();
|
Table t = new Table();
|
||||||
TableResults<Integer, String> r =
|
TableResults<Integer, String> r =
|
||||||
@@ -112,11 +106,7 @@ class TableResultsTest {
|
|||||||
r.select(1);
|
r.select(1);
|
||||||
assertThrows(
|
assertThrows(
|
||||||
IllegalArgumentException.class,
|
IllegalArgumentException.class,
|
||||||
() ->
|
() -> r.show(List.of(new GridRow<>(2, "staged"), new GridRow<>(3, "fail"))));
|
||||||
r.show(
|
|
||||||
List.of(
|
|
||||||
new GridRow<>(2, "staged"),
|
|
||||||
new GridRow<>(3, "fail"))));
|
|
||||||
assertEquals(1, disposed.get());
|
assertEquals(1, disposed.get());
|
||||||
assertEquals("old", r.selectedElementProperty().get());
|
assertEquals("old", r.selectedElementProperty().get());
|
||||||
assertThrows(
|
assertThrows(
|
||||||
@@ -130,8 +120,7 @@ class TableResultsTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void fixedColumnsAndModeAreValidated() throws Exception {
|
void fixedColumnsAndModeAreValidated() throws Exception {
|
||||||
fx(
|
fx(() -> {
|
||||||
() -> {
|
|
||||||
Table t = new Table();
|
Table t = new Table();
|
||||||
var defs =
|
var defs =
|
||||||
List.of(
|
List.of(
|
||||||
@@ -143,18 +132,14 @@ class TableResultsTest {
|
|||||||
() -> r.setColumnOrder(List.of("city", "name")));
|
() -> r.setColumnOrder(List.of("city", "name")));
|
||||||
assertThrows(
|
assertThrows(
|
||||||
IllegalStateException.class,
|
IllegalStateException.class,
|
||||||
() ->
|
() -> t.openResults(defs, s -> row(String.valueOf(s), new AtomicInteger())));
|
||||||
t.openResults(
|
|
||||||
defs,
|
|
||||||
s -> row(String.valueOf(s), new AtomicInteger())));
|
|
||||||
r.close();
|
r.close();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void malformedMappingAndDisposalFailureAreObservable() throws Exception {
|
void malformedMappingAndDisposalFailureAreObservable() throws Exception {
|
||||||
fx(
|
fx(() -> {
|
||||||
() -> {
|
|
||||||
AtomicInteger releases = new AtomicInteger();
|
AtomicInteger releases = new AtomicInteger();
|
||||||
Table table = new Table();
|
Table table = new Table();
|
||||||
TableResults<Integer, String> renderer =
|
TableResults<Integer, String> renderer =
|
||||||
@@ -172,8 +157,7 @@ class TableResultsTest {
|
|||||||
() -> {
|
() -> {
|
||||||
releases.incrementAndGet();
|
releases.incrementAndGet();
|
||||||
if (model.equals("old"))
|
if (model.equals("old"))
|
||||||
throw new IllegalStateException(
|
throw new IllegalStateException("cleanup failed");
|
||||||
"cleanup failed");
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
renderer.show(List.of(new GridRow<>(1, "old")));
|
renderer.show(List.of(new GridRow<>(1, "old")));
|
||||||
@@ -192,4 +176,48 @@ class TableResultsTest {
|
|||||||
assertEquals(3, releases.get());
|
assertEquals(3, releases.get());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void horizontallyScrolledHeadersAlignWithRowsBesideAVerticalScrollbar() throws Exception {
|
||||||
|
fx(() -> {
|
||||||
|
Table table = new Table();
|
||||||
|
List<ResultRow> views = new ArrayList<>();
|
||||||
|
var renderer =
|
||||||
|
table.<Integer, String>openResults(
|
||||||
|
columns(),
|
||||||
|
model -> {
|
||||||
|
var view = row(model, new AtomicInteger());
|
||||||
|
view.root().setMinHeight(35);
|
||||||
|
views.add(view);
|
||||||
|
return view;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
renderer.setColumnWidth("name", new ColumnWidth.Explicit(300));
|
||||||
|
renderer.setColumnWidth("city", new ColumnWidth.Explicit(200));
|
||||||
|
renderer.show(
|
||||||
|
java.util.stream.IntStream.range(0, 30)
|
||||||
|
.mapToObj(i -> new GridRow<>(i, "Row " + i))
|
||||||
|
.toList());
|
||||||
|
var root = new StackPane(table);
|
||||||
|
new javafx.scene.Scene(root, 260, 260);
|
||||||
|
root.resize(260, 260);
|
||||||
|
root.applyCss();
|
||||||
|
root.layout();
|
||||||
|
var scroll = (ScrollPane) table.getChildren().get(1);
|
||||||
|
var header = (ScrollPane) table.getChildren().getFirst();
|
||||||
|
scroll.setHvalue(.7);
|
||||||
|
root.layout();
|
||||||
|
double cellX = header.getContent().lookup(".column-cell").localToScene(0, 0).getX();
|
||||||
|
double rowX = views.getFirst().fields().get("name").localToScene(0, 0).getX();
|
||||||
|
assertEquals(
|
||||||
|
cellX,
|
||||||
|
rowX,
|
||||||
|
1,
|
||||||
|
"Header and row must share pixel offset, including scrollbar and trailing"
|
||||||
|
+ " actions");
|
||||||
|
} finally {
|
||||||
|
renderer.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-1
@@ -2,6 +2,11 @@
|
|||||||
|
|
||||||
This module supplies existing Gson configuration/type adapters and optional DataGrid setup JSON support.
|
This module supplies existing Gson configuration/type adapters and optional DataGrid setup JSON support.
|
||||||
|
|
||||||
`de.neitzel.gson.grid.GridSetupJson` encodes explicit format-version-1 documents with independently versioned filter codecs. It depends on neutral `data-grid` contracts, not JavaFX. See [saved setups](../fx/docs/saved-setups.md) for schema behavior, custom codecs and application-owned storage. The `fx` and `data-grid` modules do not depend on this JSON implementation.
|
`de.neitzel.gson.grid.GridSetupJson` encodes explicit format-version-1 and format-version-2 documents with independently versioned filter codecs. It depends on neutral `data-grid` contracts, not JavaFX. See [saved setups](../fx/docs/saved-setups.md) for schema behavior, custom codecs and application-owned storage. The `fx` and `data-grid` modules do not depend on this JSON implementation.
|
||||||
|
|
||||||
Use the repository's declared Java 25/Maven wrapper baseline. Run the Gson tests and affected data-grid/FX integration tests when changing the saved setup schema.
|
Use the repository's declared Java 25/Maven wrapper baseline. Run the Gson tests and affected data-grid/FX integration tests when changing the saved setup schema.
|
||||||
|
|
||||||
|
`GridSetupFiles.forApplication(name)` creates the optional application service and
|
||||||
|
revision-aware JSON file store. It reuses core application-directory resolution;
|
||||||
|
construction creates no files. FX attachment, failure/conflict recovery and lifecycle
|
||||||
|
are documented in the [layout/persistence guide](../fx/docs/data-grid-layout.md).
|
||||||
|
|||||||
+2
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
@@ -24,6 +24,7 @@
|
|||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<dependency><groupId>de.neitzel.lib</groupId><artifactId>core</artifactId><version>${project.version}</version></dependency>
|
||||||
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package de.neitzel.gson.grid;
|
||||||
|
|
||||||
|
import de.neitzel.core.config.ApplicationDirectories;
|
||||||
|
import de.neitzel.grid.GridApplicationConfiguration;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/** Simple opt-in factory; constructing it does not create directories or read preferences. */
|
||||||
|
public final class GridSetupFiles {
|
||||||
|
private GridSetupFiles() {}
|
||||||
|
|
||||||
|
public static GridApplicationConfiguration forApplication(String application) {
|
||||||
|
return forApplication(
|
||||||
|
application,
|
||||||
|
ApplicationDirectories.configurationDirectory(application).resolve("grids"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static GridApplicationConfiguration forApplication(
|
||||||
|
String application, Path gridDirectory) {
|
||||||
|
return forApplication(application, gridDirectory, new GridSetupJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static GridApplicationConfiguration forApplication(
|
||||||
|
String application, Path gridDirectory, GridSetupJson codecs) {
|
||||||
|
return new GridApplicationConfiguration(
|
||||||
|
application, new JsonGridSetupStore(gridDirectory, codecs));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,7 +26,7 @@ public final class GridSetupJson {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private final Map<String, FilterCodec> codecs = new LinkedHashMap<>();
|
private final Map<String, FilterCodec> codecs = new LinkedHashMap<>();
|
||||||
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
private final Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
|
||||||
|
|
||||||
public GridSetupJson() {
|
public GridSetupJson() {
|
||||||
for (String id :
|
for (String id :
|
||||||
@@ -50,10 +50,10 @@ public final class GridSetupJson {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String encode(GridSetup setup) {
|
public String encode(GridSetup setup) {
|
||||||
if (setup.formatVersion() != 1)
|
if (setup.formatVersion() != 1 && setup.formatVersion() != 2)
|
||||||
throw new IllegalArgumentException("Unsupported setup format version");
|
throw new IllegalArgumentException("Unsupported setup format version");
|
||||||
JsonObject root = new JsonObject();
|
JsonObject root = new JsonObject();
|
||||||
root.addProperty("formatVersion", 1);
|
root.addProperty("formatVersion", setup.formatVersion());
|
||||||
root.addProperty("definitionId", setup.definitionId());
|
root.addProperty("definitionId", setup.definitionId());
|
||||||
root.addProperty("definitionVersion", setup.definitionVersion());
|
root.addProperty("definitionVersion", setup.definitionVersion());
|
||||||
JsonArray columns = new JsonArray();
|
JsonArray columns = new JsonArray();
|
||||||
@@ -97,6 +97,7 @@ public final class GridSetupJson {
|
|||||||
page.addProperty("mode", setup.page() instanceof PageRequest.All ? "all" : "paged");
|
page.addProperty("mode", setup.page() instanceof PageRequest.All ? "all" : "paged");
|
||||||
if (setup.page() instanceof PageRequest.Paged p) page.addProperty("size", p.pageSize());
|
if (setup.page() instanceof PageRequest.Paged p) page.addProperty("size", p.pageSize());
|
||||||
root.add("page", page);
|
root.add("page", page);
|
||||||
|
if (setup.formatVersion() == 2) root.add("grouping", grouping(setup.grouping()));
|
||||||
return gson.toJson(root);
|
return gson.toJson(root);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,6 +108,8 @@ public final class GridSetupJson {
|
|||||||
JsonObject root = object(read(reader));
|
JsonObject root = object(read(reader));
|
||||||
if (reader.peek() != JsonToken.END_DOCUMENT)
|
if (reader.peek() != JsonToken.END_DOCUMENT)
|
||||||
throw new IllegalArgumentException("Trailing JSON content");
|
throw new IllegalArgumentException("Trailing JSON content");
|
||||||
|
int format = integer(root, "formatVersion");
|
||||||
|
if (format == 1)
|
||||||
keys(
|
keys(
|
||||||
root,
|
root,
|
||||||
"formatVersion",
|
"formatVersion",
|
||||||
@@ -116,9 +119,18 @@ public final class GridSetupJson {
|
|||||||
"sort",
|
"sort",
|
||||||
"filters",
|
"filters",
|
||||||
"page");
|
"page");
|
||||||
int format = integer(root, "formatVersion");
|
else if (format == 2)
|
||||||
if (format != 1)
|
keys(
|
||||||
throw new IllegalArgumentException("Unsupported setup format version: " + format);
|
root,
|
||||||
|
"formatVersion",
|
||||||
|
"definitionId",
|
||||||
|
"definitionVersion",
|
||||||
|
"columns",
|
||||||
|
"sort",
|
||||||
|
"filters",
|
||||||
|
"page",
|
||||||
|
"grouping");
|
||||||
|
else throw new IllegalArgumentException("Unsupported setup format version: " + format);
|
||||||
List<GridSetup.ColumnState> columns = new ArrayList<>();
|
List<GridSetup.ColumnState> columns = new ArrayList<>();
|
||||||
for (var entry : array(root, "columns")) {
|
for (var entry : array(root, "columns")) {
|
||||||
var c = object(entry);
|
var c = object(entry);
|
||||||
@@ -184,13 +196,69 @@ public final class GridSetupJson {
|
|||||||
columns,
|
columns,
|
||||||
sort,
|
sort,
|
||||||
filters,
|
filters,
|
||||||
page);
|
page,
|
||||||
|
format == 2 ? grouping(object(required(root, "grouping"))) : null);
|
||||||
} catch (IOException | IllegalStateException | ArithmeticException error) {
|
} catch (IOException | IllegalStateException | ArithmeticException error) {
|
||||||
throw new IllegalArgumentException("Invalid saved setup: " + error.getMessage(), error);
|
throw new IllegalArgumentException("Invalid saved setup: " + error.getMessage(), error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static JsonElement read(JsonReader reader) throws IOException {
|
private static JsonObject grouping(GroupingSetup grouping) {
|
||||||
|
var object = new JsonObject();
|
||||||
|
var columns = new JsonArray();
|
||||||
|
grouping.columns().forEach(columns::add);
|
||||||
|
object.add("columns", columns);
|
||||||
|
var choices = new JsonArray();
|
||||||
|
for (var choice : grouping.choices()) {
|
||||||
|
var item = new JsonObject();
|
||||||
|
item.addProperty("expanded", choice.expanded());
|
||||||
|
var path = new JsonArray();
|
||||||
|
for (var segment : choice.path().segments()) {
|
||||||
|
var value = new JsonObject();
|
||||||
|
value.addProperty("column", segment.columnId());
|
||||||
|
value.add(
|
||||||
|
"value",
|
||||||
|
segment.value() == null
|
||||||
|
? JsonNull.INSTANCE
|
||||||
|
: BuiltIn.value(segment.value()));
|
||||||
|
path.add(value);
|
||||||
|
}
|
||||||
|
item.add("path", path);
|
||||||
|
choices.add(item);
|
||||||
|
}
|
||||||
|
object.add("choices", choices);
|
||||||
|
return object;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GroupingSetup grouping(JsonObject object) {
|
||||||
|
keys(object, "columns", "choices");
|
||||||
|
List<String> columns = new ArrayList<>();
|
||||||
|
for (var column : array(object, "columns")) {
|
||||||
|
if (!column.isJsonPrimitive() || !column.getAsJsonPrimitive().isString())
|
||||||
|
throw new IllegalArgumentException("Grouping column must be text");
|
||||||
|
columns.add(column.getAsString());
|
||||||
|
}
|
||||||
|
List<GroupingSetup.Choice> choices = new ArrayList<>();
|
||||||
|
for (var entry : array(object, "choices")) {
|
||||||
|
var item = object(entry);
|
||||||
|
keys(item, "expanded", "path");
|
||||||
|
List<GroupPath.Segment> path = new ArrayList<>();
|
||||||
|
for (var part : array(item, "path")) {
|
||||||
|
var segment = object(part);
|
||||||
|
keys(segment, "column", "value");
|
||||||
|
path.add(
|
||||||
|
new GroupPath.Segment(
|
||||||
|
string(segment, "column"),
|
||||||
|
segment.get("value").isJsonNull()
|
||||||
|
? null
|
||||||
|
: BuiltIn.value(object(segment.get("value")))));
|
||||||
|
}
|
||||||
|
choices.add(new GroupingSetup.Choice(new GroupPath(path), bool(item, "expanded")));
|
||||||
|
}
|
||||||
|
return new GroupingSetup(columns, choices);
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonElement read(JsonReader reader) throws IOException {
|
||||||
return switch (reader.peek()) {
|
return switch (reader.peek()) {
|
||||||
case BEGIN_OBJECT -> {
|
case BEGIN_OBJECT -> {
|
||||||
reader.beginObject();
|
reader.beginObject();
|
||||||
@@ -223,7 +291,7 @@ public final class GridSetupJson {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void keys(JsonObject o, String... names) {
|
static void keys(JsonObject o, String... names) {
|
||||||
if (!o.keySet().equals(Set.of(names)))
|
if (!o.keySet().equals(Set.of(names)))
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"Expected properties " + Arrays.toString(names) + ", found " + o.keySet());
|
"Expected properties " + Arrays.toString(names) + ", found " + o.keySet());
|
||||||
@@ -236,7 +304,7 @@ public final class GridSetupJson {
|
|||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static JsonObject object(JsonElement v) {
|
static JsonObject object(JsonElement v) {
|
||||||
if (!v.isJsonObject()) throw new IllegalArgumentException("Expected JSON object");
|
if (!v.isJsonObject()) throw new IllegalArgumentException("Expected JSON object");
|
||||||
return v.getAsJsonObject();
|
return v.getAsJsonObject();
|
||||||
}
|
}
|
||||||
@@ -247,7 +315,7 @@ public final class GridSetupJson {
|
|||||||
return v.getAsJsonArray();
|
return v.getAsJsonArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String string(JsonObject o, String name) {
|
static String string(JsonObject o, String name) {
|
||||||
var v = required(o, name);
|
var v = required(o, name);
|
||||||
if (!v.isJsonPrimitive() || !v.getAsJsonPrimitive().isString())
|
if (!v.isJsonPrimitive() || !v.getAsJsonPrimitive().isString())
|
||||||
throw new IllegalArgumentException("Expected string: " + name);
|
throw new IllegalArgumentException("Expected string: " + name);
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
package de.neitzel.gson.grid;
|
||||||
|
|
||||||
|
import com.google.gson.*;
|
||||||
|
import com.google.gson.stream.*;
|
||||||
|
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.channels.FileChannel;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.security.*;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
|
/** Optional file store: safe opaque identities, strict JSON, locked compare-and-atomic-replace. */
|
||||||
|
public final class JsonGridSetupStore implements GridSetupStore {
|
||||||
|
private static final ReentrantLock[] JVM_LOCKS = new ReentrantLock[64];
|
||||||
|
|
||||||
|
static {
|
||||||
|
Arrays.setAll(JVM_LOCKS, i -> new ReentrantLock());
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Path directory;
|
||||||
|
private final GridSetupJson json;
|
||||||
|
|
||||||
|
public JsonGridSetupStore(Path directory, GridSetupJson json) {
|
||||||
|
this.directory = Objects.requireNonNull(directory).toAbsolutePath().normalize();
|
||||||
|
this.json = Objects.requireNonNull(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Path path(Key key) {
|
||||||
|
String identity =
|
||||||
|
key.gridId().length()
|
||||||
|
+ ":"
|
||||||
|
+ key.gridId()
|
||||||
|
+ (key.context() == null
|
||||||
|
? "N"
|
||||||
|
: "S" + key.context().length() + ":" + key.context());
|
||||||
|
return directory.resolve(hash(identity.getBytes(StandardCharsets.UTF_8)) + ".json");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Stored load(Key key) throws IOException {
|
||||||
|
Path path = path(key);
|
||||||
|
if (!Files.exists(path)) return new Stored(null, "absent");
|
||||||
|
byte[] bytes = Files.readAllBytes(path);
|
||||||
|
try (var reader =
|
||||||
|
new JsonReader(new StringReader(new String(bytes, StandardCharsets.UTF_8)))) {
|
||||||
|
reader.setStrictness(Strictness.STRICT);
|
||||||
|
reader.setNestingLimit(80);
|
||||||
|
JsonObject root = GridSetupJson.object(GridSetupJson.read(reader));
|
||||||
|
if (reader.peek() != JsonToken.END_DOCUMENT)
|
||||||
|
throw new IllegalArgumentException("Trailing setup document");
|
||||||
|
GridSetupJson.keys(root, "gridId", "context", "revision", "setup");
|
||||||
|
GridSetupJson.string(root, "revision");
|
||||||
|
String context =
|
||||||
|
root.get("context").isJsonNull() ? null : GridSetupJson.string(root, "context");
|
||||||
|
if (!key.gridId().equals(GridSetupJson.string(root, "gridId"))
|
||||||
|
|| !Objects.equals(key.context(), context))
|
||||||
|
throw new IllegalArgumentException("Stored grid/context identity differs");
|
||||||
|
return new Stored(json.decode(root.get("setup").toString()), hash(bytes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String revision(Key key) throws IOException {
|
||||||
|
Path path = path(key);
|
||||||
|
return Files.exists(path) ? hash(Files.readAllBytes(path)) : "absent";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String save(Key key, String expected, GridSetup setup) throws IOException {
|
||||||
|
// Encode fully before touching the existing document or acquiring its lock.
|
||||||
|
var root = new JsonObject();
|
||||||
|
root.addProperty("gridId", key.gridId());
|
||||||
|
root.addProperty("context", key.context());
|
||||||
|
root.addProperty("revision", UUID.randomUUID().toString());
|
||||||
|
root.add("setup", JsonParser.parseString(json.encode(setup)));
|
||||||
|
byte[] bytes =
|
||||||
|
new GsonBuilder()
|
||||||
|
.setPrettyPrinting()
|
||||||
|
.serializeNulls()
|
||||||
|
.create()
|
||||||
|
.toJson(root)
|
||||||
|
.getBytes(StandardCharsets.UTF_8);
|
||||||
|
Files.createDirectories(directory);
|
||||||
|
Path path = path(key), lock = path.resolveSibling(path.getFileName() + ".lock");
|
||||||
|
ReentrantLock local = JVM_LOCKS[Math.floorMod(path.hashCode(), JVM_LOCKS.length)];
|
||||||
|
local.lock();
|
||||||
|
try (var channel =
|
||||||
|
FileChannel.open(
|
||||||
|
lock, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
||||||
|
var ignored = channel.lock()) {
|
||||||
|
if (!Objects.equals(expected, revision(key))) throw new GridSetupStore.Conflict();
|
||||||
|
Path temporary = Files.createTempFile(directory, ".grid-setup-", ".tmp");
|
||||||
|
try {
|
||||||
|
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||||
|
var buffer = java.nio.ByteBuffer.wrap(bytes);
|
||||||
|
while (buffer.hasRemaining()) output.write(buffer);
|
||||||
|
output.force(true);
|
||||||
|
}
|
||||||
|
Files.move(
|
||||||
|
temporary,
|
||||||
|
path,
|
||||||
|
StandardCopyOption.REPLACE_EXISTING,
|
||||||
|
StandardCopyOption.ATOMIC_MOVE);
|
||||||
|
} finally {
|
||||||
|
Files.deleteIfExists(temporary);
|
||||||
|
}
|
||||||
|
return hash(bytes);
|
||||||
|
} finally {
|
||||||
|
local.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String hash(byte[] bytes) {
|
||||||
|
try {
|
||||||
|
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||||
|
} catch (NoSuchAlgorithmException impossible) {
|
||||||
|
throw new IllegalStateException(impossible);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package de.neitzel.gson.grid;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
class GridFileStoreTest {
|
||||||
|
@TempDir Path directory;
|
||||||
|
|
||||||
|
static GridSetup setup() {
|
||||||
|
return new GridSetup(
|
||||||
|
2,
|
||||||
|
"records",
|
||||||
|
1,
|
||||||
|
List.of(new GridSetup.ColumnState("type", "text", new ColumnWidth.Default())),
|
||||||
|
List.of(),
|
||||||
|
List.of(),
|
||||||
|
new PageRequest.Paged(0, 50),
|
||||||
|
new GroupingSetup(
|
||||||
|
List.of("type"),
|
||||||
|
List.of(
|
||||||
|
new GroupingSetup.Choice(
|
||||||
|
new GroupPath(List.of(new GroupPath.Segment("type", null))),
|
||||||
|
true))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void strictVersionTwoRoundTripKeepsTypedMissingAndRejectsMalformedNewFormat() {
|
||||||
|
var codec = new GridSetupJson();
|
||||||
|
String json = codec.encode(setup());
|
||||||
|
assertEquals(setup(), codec.decode(json));
|
||||||
|
assertThrows(
|
||||||
|
IllegalArgumentException.class,
|
||||||
|
() -> codec.decode(json.replace("\"expanded\": true", "\"expanded\": \"true\"")));
|
||||||
|
assertThrows(
|
||||||
|
IllegalArgumentException.class,
|
||||||
|
() -> codec.decode(json.replace("\"choices\"", "\"unknown\"")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noFilesUntilSaveAndSafeIdentityDoesNotTreatKeysAsPaths() throws Exception {
|
||||||
|
var root = directory.resolve("not-created");
|
||||||
|
var store = new JsonGridSetupStore(root, new GridSetupJson());
|
||||||
|
var key = new GridSetupStore.Key("../../records", "../outside");
|
||||||
|
assertNull(store.load(key).setup());
|
||||||
|
assertFalse(Files.exists(root));
|
||||||
|
String revision = store.save(key, "absent", setup());
|
||||||
|
assertEquals(root, store.path(key).getParent());
|
||||||
|
assertEquals(setup(), store.load(key).setup());
|
||||||
|
assertThrows(GridSetupStore.Conflict.class, () -> store.save(key, "absent", setup()));
|
||||||
|
assertEquals(revision, store.revision(key));
|
||||||
|
assertNotEquals(
|
||||||
|
store.path(new GridSetupStore.Key("a", null)),
|
||||||
|
store.path(new GridSetupStore.Key("a", "null")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void competingProcessesCannotBothReplaceTheSameRevision() throws Exception {
|
||||||
|
var store = new JsonGridSetupStore(directory, new GridSetupJson());
|
||||||
|
var key = new GridSetupStore.Key("records", null);
|
||||||
|
String revision = store.save(key, "absent", setup());
|
||||||
|
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
|
||||||
|
String cp = System.getProperty("java.class.path");
|
||||||
|
var first =
|
||||||
|
new ProcessBuilder(
|
||||||
|
java,
|
||||||
|
"-cp",
|
||||||
|
cp,
|
||||||
|
GridStoreRace.class.getName(),
|
||||||
|
directory.toString(),
|
||||||
|
revision)
|
||||||
|
.redirectErrorStream(true)
|
||||||
|
.start();
|
||||||
|
var second =
|
||||||
|
new ProcessBuilder(
|
||||||
|
java,
|
||||||
|
"-cp",
|
||||||
|
cp,
|
||||||
|
GridStoreRace.class.getName(),
|
||||||
|
directory.toString(),
|
||||||
|
revision)
|
||||||
|
.redirectErrorStream(true)
|
||||||
|
.start();
|
||||||
|
assertTrue(first.waitFor(15, TimeUnit.SECONDS));
|
||||||
|
assertTrue(second.waitFor(15, TimeUnit.SECONDS));
|
||||||
|
var exits = new ArrayList<>(List.of(first.exitValue(), second.exitValue()));
|
||||||
|
Collections.sort(exits);
|
||||||
|
assertEquals(
|
||||||
|
List.of(0, 3),
|
||||||
|
exits,
|
||||||
|
new String(first.getInputStream().readAllBytes())
|
||||||
|
+ new String(second.getInputStream().readAllBytes()));
|
||||||
|
assertEquals(setup(), store.load(key).setup());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package de.neitzel.gson.grid;
|
||||||
|
|
||||||
|
import de.neitzel.grid.*;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/** Separate-process CAS probe, deliberately independent of JUnit scheduling. */
|
||||||
|
public final class GridStoreRace {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
var store = new JsonGridSetupStore(Path.of(args[0]), new GridSetupJson());
|
||||||
|
try {
|
||||||
|
store.save(new GridSetupStore.Key("records", null), args[1], GridFileStoreTest.setup());
|
||||||
|
} catch (GridSetupStore.Conflict expected) {
|
||||||
|
System.exit(3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>injection</artifactId>
|
<artifactId>injection</artifactId>
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>log4j</artifactId>
|
<artifactId>log4j</artifactId>
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>net</artifactId>
|
<artifactId>net</artifactId>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
|
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>quarkus</artifactId>
|
<artifactId>quarkus</artifactId>
|
||||||
|
|||||||
Reference in New Issue
Block a user