Release NeitzelLib 1.0.1 with declarative DataGrid controls and saved setups

This commit is contained in:
2026-11-18 08:31:03 +01:00
parent 91d9cdccaa
commit 257e0edb28
66 changed files with 6378 additions and 273 deletions
@@ -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);
}
@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
void pagingFilteringSelectionAndAllUseCoordinatorWithoutChangingLegacyTable() throws Exception {
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,149 +47,177 @@ class TableResultsTest {
@Test
void resultOrderMappingSelectionAndLifetime() throws Exception {
fx(
() -> {
Table table = new Table();
AtomicInteger disposed = new AtomicInteger();
List<ResultRow> views = new ArrayList<>();
TableResults<Integer, String> renderer =
table.openResults(
columns(),
s -> {
var v = row(s, disposed);
views.add(v);
return v;
});
renderer.show(List.of(new GridRow<>(2, "Z"), new GridRow<>(1, "A")));
VBox body = (VBox) ((ScrollPane) table.getChildren().get(1)).getContent();
assertEquals(
"Z",
((Label) ((HBox) body.getChildren().get(0)).getChildren().get(0))
.getText());
renderer.select(2);
assertEquals("Z", renderer.selectedElementProperty().get());
renderer.setColumnOrder(List.of("city", "name"));
assertSame(
views.get(0).fields().get("city"),
views.get(0).root().getChildren().get(0));
assertInstanceOf(Button.class, views.get(0).root().getChildren().get(2));
assertEquals(
200, renderer.setColumnWidth("city", new ColumnWidth.Explicit(999)));
assertEquals(200, views.get(0).fields().get("city").getPrefWidth());
assertThrows(
IllegalArgumentException.class,
() -> renderer.setColumnOrder(List.of("name", "name")));
renderer.show(List.of(new GridRow<>(1, "New A")));
assertEquals(2, disposed.get());
assertEquals(2, renderer.selectedKeyProperty().get());
assertNull(renderer.selectedElementProperty().get());
renderer.show(List.of(new GridRow<>(2, "New Z")));
assertEquals("New Z", renderer.selectedElementProperty().get());
assertEquals(3, disposed.get());
renderer.close();
renderer.close();
assertEquals(4, disposed.get());
assertTrue(body.getChildren().isEmpty());
assertThrows(IllegalStateException.class, () -> renderer.show(List.of()));
});
fx(() -> {
Table table = new Table();
AtomicInteger disposed = new AtomicInteger();
List<ResultRow> views = new ArrayList<>();
TableResults<Integer, String> renderer =
table.openResults(
columns(),
s -> {
var v = row(s, disposed);
views.add(v);
return v;
});
renderer.show(List.of(new GridRow<>(2, "Z"), new GridRow<>(1, "A")));
VBox body = (VBox) ((ScrollPane) table.getChildren().get(1)).getContent();
assertEquals(
"Z",
((Label) ((HBox) body.getChildren().get(0)).getChildren().get(0)).getText());
renderer.select(2);
assertEquals("Z", renderer.selectedElementProperty().get());
renderer.setColumnOrder(List.of("city", "name"));
assertSame(views.get(0).fields().get("city"), views.get(0).root().getChildren().get(0));
assertInstanceOf(Button.class, views.get(0).root().getChildren().get(2));
assertEquals(200, renderer.setColumnWidth("city", new ColumnWidth.Explicit(999)));
assertEquals(200, views.get(0).fields().get("city").getPrefWidth());
assertThrows(
IllegalArgumentException.class,
() -> renderer.setColumnOrder(List.of("name", "name")));
renderer.show(List.of(new GridRow<>(1, "New A")));
assertEquals(2, disposed.get());
assertEquals(2, renderer.selectedKeyProperty().get());
assertNull(renderer.selectedElementProperty().get());
renderer.show(List.of(new GridRow<>(2, "New Z")));
assertEquals("New Z", renderer.selectedElementProperty().get());
assertEquals(3, disposed.get());
renderer.close();
renderer.close();
assertEquals(4, disposed.get());
assertTrue(body.getChildren().isEmpty());
assertThrows(IllegalStateException.class, () -> renderer.show(List.of()));
});
}
@Test
void failedReplacementKeepsOldRowsAndReleasesStagedRows() throws Exception {
fx(
() -> {
AtomicInteger disposed = new AtomicInteger();
Table t = new Table();
TableResults<Integer, String> r =
t.openResults(
columns(),
s -> {
if (s.equals("fail"))
throw new IllegalArgumentException("factory failure");
return row(s, disposed);
});
r.show(List.of(new GridRow<>(1, "old")));
r.select(1);
assertThrows(
IllegalArgumentException.class,
() ->
r.show(
List.of(
new GridRow<>(2, "staged"),
new GridRow<>(3, "fail"))));
assertEquals(1, disposed.get());
assertEquals("old", r.selectedElementProperty().get());
assertThrows(
IllegalArgumentException.class,
() -> r.show(List.of(new GridRow<>(2, "a"), new GridRow<>(2, "b"))));
assertEquals(1, disposed.get());
r.close();
assertEquals(2, disposed.get());
});
fx(() -> {
AtomicInteger disposed = new AtomicInteger();
Table t = new Table();
TableResults<Integer, String> r =
t.openResults(
columns(),
s -> {
if (s.equals("fail"))
throw new IllegalArgumentException("factory failure");
return row(s, disposed);
});
r.show(List.of(new GridRow<>(1, "old")));
r.select(1);
assertThrows(
IllegalArgumentException.class,
() -> r.show(List.of(new GridRow<>(2, "staged"), new GridRow<>(3, "fail"))));
assertEquals(1, disposed.get());
assertEquals("old", r.selectedElementProperty().get());
assertThrows(
IllegalArgumentException.class,
() -> r.show(List.of(new GridRow<>(2, "a"), new GridRow<>(2, "b"))));
assertEquals(1, disposed.get());
r.close();
assertEquals(2, disposed.get());
});
}
@Test
void fixedColumnsAndModeAreValidated() throws Exception {
fx(
() -> {
Table t = new Table();
var defs =
List.of(
new ResultColumn("name", "Name", 120, 60, 300, 0),
new ResultColumn("city", "City", 100, 50, 200, -1));
var r = t.openResults(defs, s -> row(String.valueOf(s), new AtomicInteger()));
assertThrows(
IllegalArgumentException.class,
() -> r.setColumnOrder(List.of("city", "name")));
assertThrows(
IllegalStateException.class,
() ->
t.openResults(
defs,
s -> row(String.valueOf(s), new AtomicInteger())));
r.close();
});
fx(() -> {
Table t = new Table();
var defs =
List.of(
new ResultColumn("name", "Name", 120, 60, 300, 0),
new ResultColumn("city", "City", 100, 50, 200, -1));
var r = t.openResults(defs, s -> row(String.valueOf(s), new AtomicInteger()));
assertThrows(
IllegalArgumentException.class,
() -> r.setColumnOrder(List.of("city", "name")));
assertThrows(
IllegalStateException.class,
() -> t.openResults(defs, s -> row(String.valueOf(s), new AtomicInteger())));
r.close();
});
}
@Test
void malformedMappingAndDisposalFailureAreObservable() throws Exception {
fx(
() -> {
AtomicInteger releases = new AtomicInteger();
Table table = new Table();
TableResults<Integer, String> renderer =
table.openResults(
columns(),
model -> {
Label name = new Label(model);
Label city = new Label("City");
HBox root = new HBox(name, city);
return new ResultRow(
root,
model.equals("invalid")
? Map.of("name", name)
: Map.of("name", name, "city", city),
() -> {
releases.incrementAndGet();
if (model.equals("old"))
throw new IllegalStateException(
"cleanup failed");
});
});
renderer.show(List.of(new GridRow<>(1, "old")));
renderer.select(1);
assertThrows(
IllegalArgumentException.class,
() -> renderer.show(List.of(new GridRow<>(2, "invalid"))));
assertEquals("old", renderer.selectedElementProperty().get());
assertEquals(1, releases.get());
renderer.show(List.of(new GridRow<>(3, "new")));
assertEquals(2, releases.get());
assertNotNull(renderer.disposalFailureProperty().get());
renderer.select(3);
assertEquals("new", renderer.selectedElementProperty().get());
renderer.close();
assertEquals(3, releases.get());
});
fx(() -> {
AtomicInteger releases = new AtomicInteger();
Table table = new Table();
TableResults<Integer, String> renderer =
table.openResults(
columns(),
model -> {
Label name = new Label(model);
Label city = new Label("City");
HBox root = new HBox(name, city);
return new ResultRow(
root,
model.equals("invalid")
? Map.of("name", name)
: Map.of("name", name, "city", city),
() -> {
releases.incrementAndGet();
if (model.equals("old"))
throw new IllegalStateException("cleanup failed");
});
});
renderer.show(List.of(new GridRow<>(1, "old")));
renderer.select(1);
assertThrows(
IllegalArgumentException.class,
() -> renderer.show(List.of(new GridRow<>(2, "invalid"))));
assertEquals("old", renderer.selectedElementProperty().get());
assertEquals(1, releases.get());
renderer.show(List.of(new GridRow<>(3, "new")));
assertEquals(2, releases.get());
assertNotNull(renderer.disposalFailureProperty().get());
renderer.select(3);
assertEquals("new", renderer.selectedElementProperty().get());
renderer.close();
assertEquals(3, releases.get());
});
}
@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();
}
});
}
}