Add compatible DataGrid, filter editors, themes and JDBC example

This commit is contained in:
2026-11-16 17:29:19 +01:00
parent a35664dabe
commit 889846ca19
102 changed files with 10970 additions and 14 deletions
@@ -0,0 +1,373 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.grid.filter.FilterColumn;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import org.junit.jupiter.api.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class DataGridSetupTest {
@BeforeAll
static void start() throws Exception {
DataGridTest.start();
DataGridTest.fx(() -> Platform.setImplicitExit(false));
}
static class Source implements GridSource<Integer, String> {
List<GridQuery> queries = new ArrayList<>();
List<QueryOptions> options = new ArrayList<>();
List<CompletableFuture<PageResult<Integer, String>>> pending = new ArrayList<>();
public SourceCapabilities capabilities() {
return new SourceCapabilities(true, true, 100);
}
public String filterExecutionId() {
return "local";
}
public void validateFilter(FilterCondition filter) {
if (!(filter instanceof TextFilter))
throw new UnsupportedOperationException("Only text comparisons supported");
}
public QueryExecution<Integer, String> query(GridQuery q) {
return query(q, QueryOptions.defaults());
}
public QueryExecution<Integer, String> query(GridQuery q, QueryOptions o) {
queries.add(q);
options.add(o);
var f = new CompletableFuture<PageResult<Integer, String>>();
pending.add(f);
return new QueryExecution<>() {
public CompletionStage<PageResult<Integer, String>> result() {
return f;
}
public void cancel() {}
};
}
void success(int index, String model) {
pending.get(index)
.complete(
new PageResult<>(
queries.get(index).page(),
List.of(new GridRow<>(9, model)),
OptionalLong.of(1),
false));
}
}
static class Harness {
Source source = new Source();
AtomicInteger disposed = new AtomicInteger();
DataGrid<Integer, String> grid;
Harness() {
grid =
new DataGrid<>(
List.of(
new ResultColumn("a", "A", 100, 50, 200, -1),
new ResultColumn("b", "B", 80, 40, 200, -1)),
value -> {
if (value.equals("bad"))
throw new IllegalArgumentException("Cannot construct row");
var a = new Label(value);
var b = new Label(value);
return new ResultRow(
new HBox(a, b),
Map.of("a", a, "b", b),
disposed::incrementAndGet);
},
source);
grid.configureSetups("items", 1, Map.of("a", "text", "b", "text"), Map.of());
}
GridSetup candidate(PageRequest page) {
return new GridSetup(
1,
"items",
1,
List.of(
new GridSetup.ColumnState("b", "text", new ColumnWidth.Explicit(999)),
new GridSetup.ColumnState("a", "text", new ColumnWidth.Default())),
List.of(new SortKey("b", SortKey.Direction.DESCENDING)),
List.of(new TextFilter("a", TextFilter.Operator.CONTAINS, "v", false)),
page);
}
}
static Harness create() throws Exception {
var ref = new AtomicReference<Harness>();
DataGridTest.fx(() -> ref.set(new Harness()));
return ref.get();
}
static void loaded(Harness h) throws Exception {
DataGridTest.fx(h.grid::load);
DataGridTest.drain();
DataGridTest.fx(() -> h.source.success(0, "old"));
DataGridTest.drain();
}
@Test
void startupRestoreIssuesOneQueryAndPublishesLayoutAndRowsTogether() throws Exception {
var h = create();
var original = new AtomicReference<GridSetup>();
DataGridTest.fx(
() -> {
original.set(h.grid.snapshotSetup());
h.grid.select(9);
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
assertTrue(h.source.queries.isEmpty());
assertEquals(original.get(), h.grid.snapshotSetup());
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(1, h.source.queries.size());
assertEquals(new PageRequest.Paged(0, 25), h.source.queries.getFirst().page());
h.source.success(0, "value");
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
var saved = h.grid.snapshotSetup();
assertEquals(
List.of("b", "a"),
saved.columns().stream().map(GridSetup.ColumnState::id).toList());
assertEquals(new ColumnWidth.Explicit(200), saved.columns().getFirst().width());
assertEquals(1, h.grid.restorationAdjustmentsProperty().get().size());
assertEquals("value", h.grid.selectedElementProperty().get());
h.grid.close();
});
}
@Test
void decodeValidationQueryAndRowConstructionFailuresPreserveCommittedState() throws Exception {
var h = create();
loaded(h);
var before = new AtomicReference<GridSetup>();
DataGridTest.fx(
() -> {
before.set(h.grid.snapshotSetup());
h.grid.restoreSetup(
() -> {
throw new IllegalArgumentException("Malformed JSON");
});
assertEquals(1, h.source.queries.size());
assertEquals(before.get(), h.grid.snapshotSetup());
var invalid = h.candidate(new PageRequest.Paged(0, 25));
h.grid.restoreSetup(
new GridSetup(
1,
"wrong",
1,
invalid.columns(),
invalid.sort(),
invalid.filters(),
invalid.page()));
assertEquals(1, h.source.queries.size());
h.grid.restoreSetup(invalid);
});
DataGridTest.drain();
DataGridTest.fx(
() ->
h.source
.pending
.getLast()
.completeExceptionally(new IllegalStateException("offline")));
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(before.get(), h.grid.snapshotSetup());
assertEquals(GridCoordinator.Phase.ERROR, h.grid.stateProperty().get().phase());
assertEquals(
"old", h.grid.stateProperty().get().result().rows().getFirst().model());
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
});
DataGridTest.drain();
DataGridTest.fx(() -> h.source.success(h.source.queries.size() - 1, "bad"));
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(before.get(), h.grid.snapshotSetup());
assertEquals(0, h.disposed.get());
assertTrue(
h.grid.stateProperty()
.get()
.error()
.getMessage()
.contains("construct"));
h.grid.close();
});
}
@Test
void newerQueryAndLayoutChangesSupersedeRestoreAndLateApproval() throws Exception {
var h = create();
loaded(h);
var guard = new CompletableFuture<Boolean>();
DataGridTest.fx(
() -> {
h.grid.setEditGuard(q -> guard);
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
h.grid.setEditGuard(q -> CompletableFuture.completedFuture(true));
h.grid.setFilters(
List.of(new TextFilter("a", TextFilter.Operator.EQUALS, "new", true)));
guard.complete(true);
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(2, h.source.queries.size());
assertEquals(new PageRequest.Paged(0, 50), h.source.queries.getLast().page());
h.source.success(1, "new");
});
DataGridTest.drain();
DataGridTest.fx(() -> h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25))));
DataGridTest.drain();
DataGridTest.fx(
() -> {
h.grid.setColumnWidth("a", new ColumnWidth.Explicit(150));
h.source.success(2, "late");
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(
"new", h.grid.stateProperty().get().result().rows().getFirst().model());
assertEquals("a", h.grid.snapshotSetup().columns().getFirst().id());
assertEquals(
new ColumnWidth.Explicit(150),
h.grid.snapshotSetup().columns().getFirst().width());
h.grid.close();
});
}
@Test
void allRestoreRequiresFreshConfirmationAndCancelDoesNotInstallLayout() throws Exception {
var h = create();
loaded(h);
var before = new AtomicReference<GridSetup>();
var confirmation = new CompletableFuture<Boolean>();
DataGridTest.fx(
() -> {
before.set(h.grid.snapshotSetup());
h.grid.setAllConfirmation((q, n) -> confirmation);
h.grid.restoreSetup(h.candidate(new PageRequest.All()));
});
DataGridTest.drain();
DataGridTest.fx(
() ->
h.source
.pending
.getLast()
.completeExceptionally(new AllRowsConfirmationRequired(1001)));
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(before.get(), h.grid.snapshotSetup());
confirmation.complete(false);
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertEquals(before.get(), h.grid.snapshotSetup());
h.grid.setAllConfirmation((q, n) -> CompletableFuture.completedFuture(true));
h.grid.restoreSetup(h.candidate(new PageRequest.All()));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertFalse(h.source.options.getLast().allApproved());
h.source
.pending
.getLast()
.completeExceptionally(new AllRowsConfirmationRequired(1001));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertTrue(h.source.options.getLast().allApproved());
h.source.success(h.source.queries.size() - 1, "all");
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertInstanceOf(PageRequest.All.class, h.grid.snapshotSetup().page());
h.grid.close();
});
}
@Test
void savingLeavesDraftOpenAndRestoreCancelsItOnlyAfterGuardAllows() throws Exception {
var h = create();
loaded(h);
var stage = new AtomicReference<Stage>();
var guard = new CompletableFuture<Boolean>();
var popup = new AtomicReference<Window>();
DataGridTest.fx(
() -> {
h.grid.configureFilter("a", FilterColumn.text());
var window = new Stage();
window.setScene(new Scene(h.grid, 600, 400));
window.show();
stage.set(window);
((Button) h.grid.lookup(".filter-button")).fire();
popup.set(
Window.getWindows().stream()
.filter(
w ->
w != window
&& w.getScene()
.getRoot()
.lookup("#filter-ok")
!= null)
.findFirst()
.orElseThrow());
h.grid.snapshotSetup();
assertTrue(popup.get().isShowing());
h.grid.setEditGuard(q -> guard);
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertTrue(popup.get().isShowing());
guard.complete(false);
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertTrue(popup.get().isShowing());
h.grid.setEditGuard(q -> CompletableFuture.completedFuture(true));
h.grid.restoreSetup(h.candidate(new PageRequest.Paged(0, 25)));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertFalse(popup.get().isShowing());
assertEquals(2, h.source.queries.size());
h.grid.close();
stage.get().close();
});
}
}
@@ -0,0 +1,213 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import org.junit.jupiter.api.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class DataGridTest {
record Item(long id, String text) {}
@BeforeAll
static void start() throws Exception {
CountDownLatch ready = new CountDownLatch(1);
try {
Platform.startup(ready::countDown);
} catch (IllegalStateException running) {
ready.countDown();
}
assertTrue(ready.await(10, TimeUnit.SECONDS));
}
static void fx(Runnable code) throws Exception {
FutureTask<Void> task = new FutureTask<>(code, null);
Platform.runLater(task);
task.get(10, TimeUnit.SECONDS);
}
static void drain() throws Exception {
for (int i = 0; i < 4; i++) fx(() -> {});
}
static DataGrid<Long, Item> grid(List<Item> items, AtomicInteger disposed) {
var source =
new MemoryGridSource<Long, Item>(
() -> items,
Item::id,
Long::compare,
List.of(
new MemoryColumn<>(
"text",
MemoryColumn.Kind.TEXT,
i -> new FilterValue.Text(i.text()))),
Runnable::run,
250);
return new DataGrid<>(
List.of(new ResultColumn("text", "Text", 120, 50, 300, -1)),
i -> {
Label label = new Label(i.text());
return new ResultRow(
new HBox(label), Map.of("text", label), disposed::incrementAndGet);
},
source);
}
@Test
void pagingFilteringSelectionAndAllUseCoordinatorWithoutChangingLegacyTable() throws Exception {
var ref = new AtomicReference<DataGrid<Long, Item>>();
AtomicInteger disposed = new AtomicInteger();
var items =
new ArrayList<>(
List.of(new Item(1, "Zulu"), new Item(2, "Alpha"), new Item(3, "Beta")));
fx(
() -> {
ref.set(grid(items, disposed));
assertEquals(
GridCoordinator.Phase.IDLE, ref.get().stateProperty().get().phase());
ref.get().setPageSize(1);
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(1, g.stateProperty().get().result().rows().size());
g.select(1L);
assertEquals("Zulu", g.selectedElementProperty().get().text());
g.next();
assertNull(g.selectedElementProperty().get());
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(1L, g.selectedKeyProperty().get());
assertNull(g.selectedElementProperty().get());
g.setSort(new SortKey("text", SortKey.Direction.ASCENDING));
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(
"Alpha",
g.stateProperty().get().result().rows().getFirst().model().text());
assertEquals(
0,
((PageRequest.Paged) g.stateProperty().get().requested().page())
.pageIndex());
g.setAllWarningThreshold(1);
g.setAllConfirmation((q, count) -> CompletableFuture.completedFuture(false));
g.showAll();
});
drain();
fx(
() -> {
var g = ref.get();
assertInstanceOf(
PageRequest.Paged.class, g.stateProperty().get().requested().page());
g.setAllConfirmation((q, count) -> CompletableFuture.completedFuture(true));
g.showAll();
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(3, g.stateProperty().get().result().rows().size());
assertEquals("Zulu", g.selectedElementProperty().get().text());
g.setFilters(
List.of(
new TextFilter(
"text", TextFilter.Operator.EQUALS, "alpha", false)));
});
drain();
fx(
() -> {
var g = ref.get();
assertEquals(1, g.stateProperty().get().result().rows().size());
assertNull(g.selectedElementProperty().get());
g.close();
assertEquals(GridCoordinator.Phase.CLOSED, g.stateProperty().get().phase());
assertTrue(disposed.get() > 0);
assertThrows(IllegalStateException.class, g::load);
});
}
@Test
void pendingGuardDoesNotPublishAfterGridCloses() throws Exception {
var ref = new AtomicReference<DataGrid<Long, Item>>();
var guard = new CompletableFuture<Boolean>();
fx(
() -> {
ref.set(grid(List.of(new Item(1, "a")), new AtomicInteger()));
ref.get().setEditGuard(q -> guard);
ref.get().load();
ref.get().close();
});
guard.complete(true);
drain();
fx(
() ->
assertEquals(
GridCoordinator.Phase.CLOSED,
ref.get().stateProperty().get().phase()));
}
@Test
void successfulSourceReplacementClearsSelectionAndPublishesOnFx() throws Exception {
var ref = new AtomicReference<DataGrid<Long, Item>>();
fx(
() -> {
ref.set(grid(List.of(new Item(1, "old")), new AtomicInteger()));
ref.get().load();
});
drain();
fx(
() -> {
var replacement =
new MemoryGridSource<Long, Item>(
() -> List.of(new Item(1, "new")),
Item::id,
Long::compare,
List.of(
new MemoryColumn<>(
"text",
MemoryColumn.Kind.TEXT,
i -> new FilterValue.Text(i.text()))),
Runnable::run,
250);
ref.get().select(1L);
ref.get()
.stateProperty()
.addListener(
(obs, old, value) ->
assertTrue(Platform.isFxApplicationThread()));
ref.get().setSource(replacement);
});
drain();
fx(
() -> {
assertNull(ref.get().selectedKeyProperty().get());
assertNull(ref.get().selectedElementProperty().get());
assertEquals(
"new",
ref.get()
.stateProperty()
.get()
.result()
.rows()
.getFirst()
.model()
.text());
ref.get().close();
});
}
}
@@ -0,0 +1,494 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import org.junit.jupiter.api.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class FilterEditorsTest {
@BeforeAll
static void start() throws Exception {
DataGridTest.start();
DataGridTest.fx(() -> javafx.application.Platform.setImplicitExit(false));
}
static <T extends Node> T node(FilterEditor e, String id, Class<T> type) {
return type.cast(e.view().lookup("#" + id));
}
@SuppressWarnings("unchecked")
static void choice(FilterEditor e, String id, String value) {
((ComboBox<String>) e.view().lookup("#" + id)).setValue(value);
}
static FilterEditorContext context(FilterColumn config, FilterCondition committed) {
return new FilterEditorContext(
"x",
config,
committed,
List.of(),
config.checklist() == FilterColumn.Checklist.INHERIT
? FilterColumn.Checklist.DISABLED
: config.checklist());
}
@Test
void realFxmlPreservesLiteralTextAndExactLocaleNumbers() throws Exception {
DataGridTest.fx(
() -> {
try (var editor =
BuiltInFilterEditor.load(context(FilterColumn.text(), null))) {
choice(editor, "mode", "Comparison");
node(editor, "operand", TextField.class).setText(" %_ ");
assertEquals(
new TextFilter("x", TextFilter.Operator.EQUALS, " %_ ", false),
editor.draft());
node(editor, "operand", TextField.class).setText("");
assertNotNull(editor.draft());
choice(editor, "operator", "CONTAINS");
assertThrows(IllegalArgumentException.class, editor::draft);
assertFalse(editor.validationMessageProperty().get().isBlank());
choice(editor, "mode", "Missing");
assertEquals(new MissingFilter("x", true), editor.draft());
choice(editor, "mode", "Clear filter");
assertNull(editor.draft());
}
var config =
FilterColumn.number(
Locale.GERMANY,
false,
new BigDecimal("-100"),
new BigDecimal("100"));
try (var editor =
BuiltInFilterEditor.load(
context(
config,
new NumericFilter(
"x",
NumericFilter.Operator.EQUALS,
new BigDecimal("1.20"),
null)))) {
assertEquals("1,20", node(editor, "operand", TextField.class).getText());
assertEquals(
new BigDecimal("1.20"), ((NumericFilter) editor.draft()).operand());
for (String invalid :
List.of("NaN", "Infinity", "1.234,50", "101", "bad")) {
node(editor, "operand", TextField.class).setText(invalid);
assertThrows(IllegalArgumentException.class, editor::draft);
}
node(editor, "operand", TextField.class).setText("2");
choice(editor, "operator", "RANGE");
node(editor, "upper", TextField.class).setText("1");
assertThrows(IllegalArgumentException.class, editor::draft);
}
try (var editor =
BuiltInFilterEditor.load(
context(
FilterColumn.number(
Locale.US,
true,
BigDecimal.ZERO,
BigDecimal.valueOf(Integer.MAX_VALUE)),
null))) {
choice(editor, "mode", "Comparison");
for (String invalid : List.of("1.5", "2147483648", "9223372036854775808")) {
node(editor, "operand", TextField.class).setText(invalid);
assertThrows(IllegalArgumentException.class, editor::draft);
}
}
});
}
@Test
void lookupRacesFailuresAndSearchNeverEraseOffBatchSelections() throws Exception {
var pending = new ArrayList<CompletableFuture<FilterCandidates.Batch>>();
AtomicInteger disposed = new AtomicInteger();
FilterCandidates.Provider provider =
new FilterCandidates.Provider() {
public Set<FilterCandidates.Scope> scopes() {
return Set.of(FilterCandidates.Scope.CURRENT_PAGE);
}
public FilterCandidates.Session open(FilterCandidates.Context c) {
return new FilterCandidates.Session() {
public CompletionStage<FilterCandidates.Batch> load(
FilterCandidates.Request r) {
var f = new CompletableFuture<FilterCandidates.Batch>();
pending.add(f);
return f;
}
public void close() {
disposed.incrementAndGet();
}
};
}
};
var ref = new AtomicReference<BuiltInFilterEditor>();
DataGridTest.fx(
() -> {
ref.set(
BuiltInFilterEditor.load(
context(
FilterColumn.text()
.withChecklist(
FilterColumn.Checklist.CURRENT_PAGE,
provider),
new ValueFilter(
"x",
Set.of(new FilterValue.Text("off-page")),
true))));
node(ref.get(), "search", TextField.class).setText("b");
pending.get(1)
.complete(
new FilterCandidates.Batch(
List.of(
new FilterCandidates.Candidate(
new FilterValue.Text("b"), "B")),
false));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
pending.getFirst()
.complete(
new FilterCandidates.Batch(
List.of(
new FilterCandidates.Candidate(
new FilterValue.Text("old"), "Old")),
false));
node(ref.get(), "selectShown", Button.class).fire();
assertEquals(
Set.of(new FilterValue.Text("off-page"), new FilterValue.Text("b")),
((ValueFilter) ref.get().draft()).values());
node(ref.get(), "search", TextField.class).setText("fail");
pending.getLast().completeExceptionally(new IllegalStateException("offline"));
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
assertTrue(
node(ref.get(), "lookupMessage", Label.class)
.getText()
.contains("offline"));
assertEquals(2, ((ValueFilter) ref.get().draft()).values().size());
node(ref.get(), "retry", Button.class).fire();
ref.get().close();
pending.getLast().complete(new FilterCandidates.Batch(List.of(), false));
assertEquals(1, disposed.get());
});
DataGridTest.drain();
}
@Test
void configurationAndCapabilitiesFailVisiblyWithoutFallback() throws Exception {
DataGridTest.fx(
() -> {
assertThrows(
IllegalArgumentException.class,
() ->
FilterColumn.text()
.withChecklist(
FilterColumn.Checklist.CURRENT_PAGE, null));
var config =
FilterColumn.text()
.withChecklist(
FilterColumn.Checklist.SOURCE_WIDE,
FilterCandidates.currentPage(List::of));
try (var e = BuiltInFilterEditor.load(context(config, null))) {
choice(e, "mode", "Checklist");
assertThrows(IllegalArgumentException.class, e::draft);
assertTrue(node(e, "scope", Label.class).getText().contains("unavailable"));
choice(e, "mode", "Comparison");
assertNotNull(e.draft());
}
var registry = FilterEditors.builtIns();
assertThrows(IllegalArgumentException.class, () -> registry.require("absent"));
assertThrows(
UnsupportedOperationException.class,
() ->
registry.require("neitzel.text")
.requireEvaluation("jdbc-unknown"));
assertTrue(registry.require("neitzel.text").capabilities().persistence());
assertThrows(
UnsupportedOperationException.class,
() ->
registry.require("neitzel.text")
.validate(
new NumericFilter(
"x",
NumericFilter.Operator.EQUALS,
BigDecimal.ONE,
null)));
});
}
@Test
void popupDraftValidationDismissalNestedEscapeAndOwnerCleanup() throws Exception {
AtomicReference<FilterCondition> committed =
new AtomicReference<>(
new TextFilter("x", TextFilter.Operator.EQUALS, "old", false));
DataGridTest.fx(
() -> {
Stage stage = new Stage();
Button opener = new Button("Filter");
stage.setScene(new Scene(new VBox(opener), 500, 400));
stage.show();
try {
var editor =
BuiltInFilterEditor.load(
context(FilterColumn.text(), committed.get()));
var popup =
new FilterPopup(
opener,
editor,
new FilterPopup.Options(
FilterPopup.Outside.ACCEPT, false, false),
c -> {
if (c instanceof TextFilter f
&& f.operand().equals("unsupported"))
throw new UnsupportedOperationException(
"Unsupported source semantics");
},
committed::set);
popup.show();
node(editor, "operand", TextField.class).setText("unsupported");
popup.outside();
assertTrue(popup.isOpen());
assertTrue(popup.errorMessage().contains("Unsupported"));
assertEquals("old", ((TextFilter) committed.get()).operand());
node(editor, "operand", TextField.class).setText("new");
ComboBox<?> chooser = node(editor, "operator", ComboBox.class);
chooser.show();
javafx.event.Event.fireEvent(
editor.view(),
new KeyEvent(
KeyEvent.KEY_PRESSED,
"",
"",
KeyCode.ESCAPE,
false,
false,
false,
false));
assertFalse(chooser.isShowing());
assertTrue(popup.isOpen());
javafx.event.Event.fireEvent(
editor.view(),
new KeyEvent(
KeyEvent.KEY_PRESSED,
"",
"",
KeyCode.ENTER,
false,
false,
false,
false));
assertFalse(popup.isOpen());
assertEquals("new", ((TextFilter) committed.get()).operand());
var second =
BuiltInFilterEditor.load(
context(FilterColumn.text(), committed.get()));
var cancel =
new FilterPopup(
opener,
second,
FilterPopup.Options.defaults(),
c -> {},
committed::set);
cancel.show();
node(second, "operand", TextField.class).setText("discard");
cancel.outside();
assertEquals("new", ((TextFilter) committed.get()).operand());
var third =
BuiltInFilterEditor.load(
context(FilterColumn.text(), committed.get()));
var disposed =
new FilterPopup(
opener,
third,
FilterPopup.Options.defaults(),
c -> {},
committed::set);
disposed.show();
stage.close();
assertFalse(disposed.isOpen());
assertThrows(IllegalStateException.class, third::draft);
} finally {
stage.close();
}
});
DataGridTest.drain();
}
public record Prefix(String columnId, String operand) implements FilterCondition {
public String typeId() {
return "test.prefix";
}
}
public static final class CustomEditor implements FilterEditor {
@javafx.fxml.FXML private TextField value;
private Parent root;
private String column;
private final javafx.beans.property.ReadOnlyStringWrapper message =
new javafx.beans.property.ReadOnlyStringWrapper("");
static CustomEditor load(FilterEditorContext context) {
try {
var loader =
new javafx.fxml.FXMLLoader(
FilterEditorsTest.class.getResource("CustomFilterEditor.fxml"));
var editor = new CustomEditor();
loader.setController(editor);
editor.root = loader.load();
editor.column = context.columnId();
editor.value.setText(context.committed() instanceof Prefix f ? f.operand() : "a");
return editor;
} catch (java.io.IOException failure) {
throw new IllegalStateException(failure);
}
}
public Parent view() {
return root;
}
public javafx.beans.property.ReadOnlyStringProperty validationMessageProperty() {
return message.getReadOnlyProperty();
}
public FilterCondition draft() {
return new Prefix(column, value.getText());
}
public void close() {}
}
@Test
void customFxmlRegistrationAndHeaderActionRespectActualSourceCapabilities() throws Exception {
var ref = new AtomicReference<DataGrid<Long, String>>();
var window = new AtomicReference<Stage>();
DataGridTest.fx(
() -> {
var source =
new MemoryGridSource<Long, String>(
() -> List.of("alpha", "beta"),
s -> (long) s.length(),
Long::compare,
List.of(
new MemoryColumn<>(
"text",
MemoryColumn.Kind.TEXT,
FilterValue.Text::new,
Map.of(
"test.prefix",
c ->
v ->
v
instanceof
FilterValue
.Text
t
&& t.value()
.startsWith(
((Prefix)
c)
.operand())))),
Runnable::run,
50);
var grid =
new DataGrid<Long, String>(
List.of(new ResultColumn("text", "Text", 200, 50, 300, -1)),
value -> {
var label = new Label(value);
return new ResultRow(
new HBox(label), Map.of("text", label), () -> {});
},
source);
var registry = new FilterEditors();
registry.register(
new FilterEditors.Registration(
"test.prefix",
new FilterCapabilities(true, false, Set.of()),
Set.of("test.prefix"),
CustomEditor::load));
grid.setFilterEditors(registry);
grid.configureFilter(
"text",
new FilterColumn(
"test.prefix",
Locale.US,
false,
false,
null,
null,
FilterColumn.Checklist.DISABLED,
null));
Stage stage = new Stage();
stage.setScene(new Scene(grid, 500, 400));
stage.show();
window.set(stage);
ref.set(grid);
grid.load();
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
var grid = ref.get();
var before = grid.stateProperty().get().generation();
((Button) grid.lookup(".filter-button")).fire();
assertEquals(
before,
grid.stateProperty().get().generation()); // Opener must not sort.
Parent popup =
javafx.stage.Window.getWindows().stream()
.map(w -> w.getScene().getRoot())
.filter(root -> root.lookup("#filter-ok") != null)
.findFirst()
.orElseThrow();
((Button) popup.lookup("#filter-ok")).fire();
});
DataGridTest.drain();
DataGridTest.fx(
() -> {
var grid = ref.get();
assertEquals(
List.of(new Prefix("text", "a")),
grid.stateProperty().get().displayed().filters());
assertEquals(
"alpha", grid.stateProperty().get().result().rows().getFirst().model());
long generation = grid.stateProperty().get().generation();
assertThrows(
UnsupportedOperationException.class,
() ->
grid.setFilters(
List.of(
new FilterCondition() {
public String columnId() {
return "text";
}
public String typeId() {
return "unknown";
}
})));
assertEquals(generation, grid.stateProperty().get().generation());
grid.close();
window.get().close();
});
}
}
@@ -0,0 +1,350 @@
package de.neitzel.fx.view;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
/**
* Explicit desktop acceptance probe, not part of unattended Surefire execution. Uses native OS
* input.
*/
public final class FilterPopupNativeProbe {
private static Stage stage;
private static Button opener;
private static TextField outside;
private static BuiltInFilterEditor editor;
private static DatePicker date;
private static FilterPopup popup;
private static FilterCondition committed =
new NumericFilter("x", NumericFilter.Operator.EQUALS, BigDecimal.TEN, null);
private static FilterPopup.Options options = FilterPopup.Options.defaults();
private static Robot robot;
private static <T> T fx(Callable<T> work) throws Exception {
var task = new FutureTask<>(work);
Platform.runLater(task);
return task.get(10, TimeUnit.SECONDS);
}
private static void settle() throws Exception {
Thread.sleep(350);
fx(() -> null);
}
private static void click(Node node) throws Exception {
double[] point =
fx(
() -> {
var b = node.localToScreen(node.getBoundsInLocal());
return new double[] {b.getCenterX(), b.getCenterY()};
});
robot.mouseMove((int) point[0], (int) point[1]);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
settle();
}
private static void key(int code) throws Exception {
robot.keyPress(code);
robot.keyRelease(code);
settle();
}
private static TextField operand() {
return (TextField) editor.view().lookup("#operand");
}
private static void check(boolean value, String message) {
if (!value) throw new AssertionError(message);
System.out.println("PASS " + message);
}
private static void open() {
if (popup != null && popup.isOpen()) {
popup.outside();
return;
}
editor =
BuiltInFilterEditor.load(
new FilterEditorContext(
"x",
FilterColumn.number(Locale.US, true, null, null),
committed,
List.of(),
FilterColumn.Checklist.DISABLED));
date = new DatePicker();
date.setAccessibleText("Nested date chooser probe");
VBox content = new VBox(8, editor.view(), date);
FilterEditor wrapped =
new FilterEditor() {
public Parent view() {
return content;
}
public FilterCondition draft() {
return editor.draft();
}
public ReadOnlyStringProperty validationMessageProperty() {
return editor.validationMessageProperty();
}
public void close() {
date.hide();
editor.close();
}
};
popup = new FilterPopup(opener, wrapped, options, c -> {}, c -> committed = c);
popup.show();
}
private static Region spacer() {
Region spacer = new Region();
spacer.setPrefHeight(300);
return spacer;
}
public static void main(String[] args) throws Exception {
try {
DataGridTest.start();
fx(
() -> {
Platform.setImplicitExit(false);
stage = new Stage();
opener = new Button("Filter");
opener.setOnAction(e -> open());
outside = new TextField();
outside.setPromptText("Outside target");
VBox root =
new VBox(
20,
new Label("Native filter popup qualification"),
opener,
spacer(),
outside);
root.setStyle("-fx-padding: 24;");
stage.setScene(new Scene(root, 650, 600));
stage.setTitle("DataGrid native filter qualification");
stage.show();
stage.toFront();
stage.requestFocus();
return null;
});
if (Arrays.asList(args).contains("--manual")) {
var finished = new CountDownLatch(1);
fx(
() -> {
CheckBox acceptOutside = new CheckBox("Accept on outside click");
CheckBox showActions = new CheckBox("Show OK / Cancel");
showActions.setSelected(true);
Runnable configure =
() ->
options =
new FilterPopup.Options(
acceptOutside.isSelected()
? FilterPopup.Outside.ACCEPT
: FilterPopup.Outside.CANCEL,
showActions.isSelected(),
showActions.isSelected());
acceptOutside.setOnAction(e -> configure.run());
showActions.setOnAction(e -> configure.run());
((VBox) stage.getScene().getRoot())
.getChildren()
.addAll(acceptOutside, showActions);
stage.setOnHidden(e -> finished.countDown());
return null;
});
System.out.println("MANUAL PROBE READY; close its window to finish");
finished.await();
return;
}
robot = new Robot();
robot.setAutoDelay(100);
settle();
click(opener);
check(
fx(() -> popup != null && popup.isShowing()),
"native opener click and anchored placement");
click(operand());
key(KeyEvent.VK_END);
key(KeyEvent.VK_2);
key(KeyEvent.VK_ENTER);
check(
fx(
() ->
!popup.isOpen()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("102"))),
"native typing and Enter commit");
check(fx(() -> opener.isFocused()), "explicit acceptance returns focus to opener");
click(opener);
fx(
() -> {
operand().setText("44");
return null;
});
key(KeyEvent.VK_ESCAPE);
check(
fx(
() ->
!popup.isOpen()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("102"))),
"Escape rollback and fresh reopen");
click(opener);
fx(
() -> {
operand().setText("55");
return null;
});
click(outside);
check(
fx(
() ->
!popup.isOpen()
&& outside.isFocused()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("102"))),
"outside Cancel preserves filter and clicked target focus");
fx(
() -> {
options = new FilterPopup.Options(FilterPopup.Outside.ACCEPT, false, false);
return null;
});
click(opener);
fx(
() -> {
operand().setText("66");
return null;
});
click(outside);
check(
fx(
() ->
!popup.isOpen()
&& outside.isFocused()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("66"))),
"outside Accept with hidden OK/Cancel");
click(opener);
fx(
() -> {
operand().setText("bad");
return null;
});
click(outside);
settle();
check(
fx(
() ->
popup.isShowing()
&& !popup.errorMessage().isBlank()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("66"))),
"invalid outside Accept reopens with error and retains committed filter");
fx(
() -> {
operand().setText("77");
return null;
});
key(KeyEvent.VK_ENTER);
check(
fx(
() ->
!popup.isOpen()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("77"))),
"Enter works without action buttons");
click(opener);
fx(
() -> {
operand().setText("88");
return null;
});
click(opener);
check(
fx(
() ->
!popup.isOpen()
&& ((NumericFilter) committed)
.operand()
.equals(new BigDecimal("88"))),
"opener re-click follows outside policy without reopening");
click(opener);
ComboBox<?> combo = fx(() -> (ComboBox<?>) editor.view().lookup("#operator"));
click(combo);
check(fx(combo::isShowing), "native nested ComboBox opens");
key(KeyEvent.VK_ESCAPE);
check(
fx(() -> !combo.isShowing() && popup.isShowing()),
"first Escape closes nested ComboBox only");
click(combo);
key(KeyEvent.VK_DOWN);
key(KeyEvent.VK_ENTER);
check(
fx(() -> !combo.isShowing() && popup.isOpen()),
"nested ComboBox selection does not accept parent");
Node arrow = fx(() -> date.lookup(".arrow-button"));
click(arrow);
check(fx(date::isShowing), "native nested DatePicker opens");
key(KeyEvent.VK_ESCAPE);
check(
fx(() -> !date.isShowing() && popup.isOpen()),
"first Escape closes nested DatePicker only");
key(KeyEvent.VK_ESCAPE);
check(fx(() -> !popup.isOpen()), "second Escape cancels parent");
click(opener);
new ProcessBuilder("osascript", "-e", "tell application \"Finder\" to activate")
.start()
.waitFor();
settle();
check(fx(() -> !popup.isOpen()), "other-application dismissal");
fx(
() -> {
stage.toFront();
stage.requestFocus();
return null;
});
settle();
click(opener);
fx(
() -> {
stage.close();
return null;
});
settle();
check(fx(() -> !popup.isOpen()), "owner disposal cancels and releases editor");
System.out.println("NATIVE MATRIX PASSED");
} catch (Throwable failure) {
failure.printStackTrace();
System.exit(1);
} finally {
if (stage != null)
fx(
() -> {
stage.close();
return null;
});
Platform.exit();
}
}
}
@@ -0,0 +1,195 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import org.junit.jupiter.api.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
class TableResultsTest {
@BeforeAll
static void start() throws Exception {
CountDownLatch started = new CountDownLatch(1);
try {
Platform.startup(started::countDown);
} catch (IllegalStateException e) {
started.countDown();
}
assertTrue(started.await(10, TimeUnit.SECONDS));
}
static void fx(Runnable r) throws Exception {
FutureTask<Void> task = new FutureTask<>(r, null);
Platform.runLater(task);
task.get(10, TimeUnit.SECONDS);
}
static List<ResultColumn> columns() {
return List.of(
new ResultColumn("name", "Name", 120, 60, 300, -1),
new ResultColumn("city", "City", 100, 50, 200, -1));
}
static ResultRow row(String model, AtomicInteger disposed) {
Label name = new Label(model), city = new Label("City");
Button action = new Button("Edit");
HBox root = new HBox(name, city, action);
return new ResultRow(root, Map.of("name", name, "city", city), disposed::incrementAndGet);
}
@Test
void resultOrderMappingSelectionAndLifetime() throws Exception {
fx(
() -> {
Table table = new Table();
AtomicInteger disposed = new AtomicInteger();
List<ResultRow> views = new ArrayList<>();
TableResults<Integer, String> renderer =
table.openResults(
columns(),
s -> {
var v = row(s, disposed);
views.add(v);
return v;
});
renderer.show(List.of(new GridRow<>(2, "Z"), new GridRow<>(1, "A")));
VBox body = (VBox) ((ScrollPane) table.getChildren().get(1)).getContent();
assertEquals(
"Z",
((Label) ((HBox) body.getChildren().get(0)).getChildren().get(0))
.getText());
renderer.select(2);
assertEquals("Z", renderer.selectedElementProperty().get());
renderer.setColumnOrder(List.of("city", "name"));
assertSame(
views.get(0).fields().get("city"),
views.get(0).root().getChildren().get(0));
assertInstanceOf(Button.class, views.get(0).root().getChildren().get(2));
assertEquals(
200, renderer.setColumnWidth("city", new ColumnWidth.Explicit(999)));
assertEquals(200, views.get(0).fields().get("city").getPrefWidth());
assertThrows(
IllegalArgumentException.class,
() -> renderer.setColumnOrder(List.of("name", "name")));
renderer.show(List.of(new GridRow<>(1, "New A")));
assertEquals(2, disposed.get());
assertEquals(2, renderer.selectedKeyProperty().get());
assertNull(renderer.selectedElementProperty().get());
renderer.show(List.of(new GridRow<>(2, "New Z")));
assertEquals("New Z", renderer.selectedElementProperty().get());
assertEquals(3, disposed.get());
renderer.close();
renderer.close();
assertEquals(4, disposed.get());
assertTrue(body.getChildren().isEmpty());
assertThrows(IllegalStateException.class, () -> renderer.show(List.of()));
});
}
@Test
void failedReplacementKeepsOldRowsAndReleasesStagedRows() throws Exception {
fx(
() -> {
AtomicInteger disposed = new AtomicInteger();
Table t = new Table();
TableResults<Integer, String> r =
t.openResults(
columns(),
s -> {
if (s.equals("fail"))
throw new IllegalArgumentException("factory failure");
return row(s, disposed);
});
r.show(List.of(new GridRow<>(1, "old")));
r.select(1);
assertThrows(
IllegalArgumentException.class,
() ->
r.show(
List.of(
new GridRow<>(2, "staged"),
new GridRow<>(3, "fail"))));
assertEquals(1, disposed.get());
assertEquals("old", r.selectedElementProperty().get());
assertThrows(
IllegalArgumentException.class,
() -> r.show(List.of(new GridRow<>(2, "a"), new GridRow<>(2, "b"))));
assertEquals(1, disposed.get());
r.close();
assertEquals(2, disposed.get());
});
}
@Test
void fixedColumnsAndModeAreValidated() throws Exception {
fx(
() -> {
Table t = new Table();
var defs =
List.of(
new ResultColumn("name", "Name", 120, 60, 300, 0),
new ResultColumn("city", "City", 100, 50, 200, -1));
var r = t.openResults(defs, s -> row(String.valueOf(s), new AtomicInteger()));
assertThrows(
IllegalArgumentException.class,
() -> r.setColumnOrder(List.of("city", "name")));
assertThrows(
IllegalStateException.class,
() ->
t.openResults(
defs,
s -> row(String.valueOf(s), new AtomicInteger())));
r.close();
});
}
@Test
void malformedMappingAndDisposalFailureAreObservable() throws Exception {
fx(
() -> {
AtomicInteger releases = new AtomicInteger();
Table table = new Table();
TableResults<Integer, String> renderer =
table.openResults(
columns(),
model -> {
Label name = new Label(model);
Label city = new Label("City");
HBox root = new HBox(name, city);
return new ResultRow(
root,
model.equals("invalid")
? Map.of("name", name)
: Map.of("name", name, "city", city),
() -> {
releases.incrementAndGet();
if (model.equals("old"))
throw new IllegalStateException(
"cleanup failed");
});
});
renderer.show(List.of(new GridRow<>(1, "old")));
renderer.select(1);
assertThrows(
IllegalArgumentException.class,
() -> renderer.show(List.of(new GridRow<>(2, "invalid"))));
assertEquals("old", renderer.selectedElementProperty().get());
assertEquals(1, releases.get());
renderer.show(List.of(new GridRow<>(3, "new")));
assertEquals(2, releases.get());
assertNotNull(renderer.disposalFailureProperty().get());
renderer.select(3);
assertEquals("new", renderer.selectedElementProperty().get());
renderer.close();
assertEquals(3, releases.get());
});
}
}
@@ -0,0 +1,266 @@
package de.neitzel.fx.view;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.docking.*;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.fx.theme.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import org.junit.jupiter.api.*;
import java.util.*;
class ThemeManagerTest {
private static final java.util.Queue<Throwable> uncaught =
new java.util.concurrent.ConcurrentLinkedQueue<>();
private static Thread.UncaughtExceptionHandler previousHandler;
@BeforeEach
void captureFxErrors() throws Exception {
DataGridTest.fx(
() -> {
previousHandler = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread()
.setUncaughtExceptionHandler((thread, error) -> uncaught.add(error));
});
}
@AfterEach
void verifyFxErrors() throws Exception {
DataGridTest.fx(() -> Thread.currentThread().setUncaughtExceptionHandler(previousHandler));
var errors = new java.util.ArrayList<>(uncaught);
uncaught.clear();
assertTrue(errors.isEmpty(), "Uncaught FX errors: " + errors);
}
@BeforeAll
static void start() throws Exception {
DataGridTest.start();
DataGridTest.fx(() -> Platform.setImplicitExit(false));
}
@Test
void optInSwitchPreservesApplicationStylesAndCloseRemovesOnlyOwnedStyles() throws Exception {
DataGridTest.fx(
() -> {
Button button = new Button("Unchanged unless opted in");
Scene scene = new Scene(new VBox(button));
String app =
getClass().getResource("shared-theme-override.css").toExternalForm();
scene.getStylesheets().add(app);
assertFalse(scene.getRoot().getStyleClass().contains("neitzel-theme"));
var manager = new ThemeManager();
var registration = manager.register(scene);
assertEquals(app, scene.getStylesheets().getLast());
for (String id : List.of("dark", "high-contrast", "light")) {
assertTrue(manager.select(id));
scene.getRoot().applyCss();
assertEquals(app, scene.getStylesheets().getLast());
assertEquals(3, scene.getStylesheets().size());
assertEquals(
9,
button.getBackground()
.getFills()
.getFirst()
.getRadii()
.getTopLeftHorizontalRadius(),
0.01);
}
var old = scene.getRoot();
scene.setRoot(new VBox(new Label("Replacement root")));
assertFalse(old.getStyleClass().contains("neitzel-theme"));
assertTrue(scene.getRoot().getStyleClass().contains("neitzel-theme"));
registration.close();
assertEquals(List.of(app), scene.getStylesheets());
assertFalse(scene.getRoot().getStyleClass().contains("neitzel-theme"));
manager.close();
manager.close();
});
}
@Test
void missingThemeAndDetectablePartialInstallationRollBackEveryScene() throws Exception {
DataGridTest.fx(
() -> {
var manager = new ThemeManager();
Scene one = new Scene(new VBox()), two = new Scene(new VBox());
manager.register(one);
manager.register(two);
manager.select("dark");
var oldOne = List.copyOf(one.getStylesheets());
var oldTwo = List.copyOf(two.getStylesheets());
manager.addTheme(
new Theme("missing", List.of("file:/missing/neitzel-theme.css")));
assertFalse(manager.select("missing"));
assertEquals("dark", manager.selectedThemeProperty().get().id());
assertEquals(oldOne, one.getStylesheets());
manager.setInstallationCheck(
s -> {
if (s == two)
throw new IllegalArgumentException(
"Application CSS check failed");
});
assertFalse(manager.select("light"));
assertEquals(oldOne, one.getStylesheets());
assertEquals(oldTwo, two.getStylesheets());
assertEquals("dark", manager.selectedThemeProperty().get().id());
assertTrue(manager.failureProperty().get().message().contains("retained dark"));
manager.setInstallationCheck(s -> {});
assertFalse(manager.selectSaved("deleted-user-theme"));
assertEquals("light", manager.selectedThemeProperty().get().id());
assertTrue(manager.failureProperty().get().message().contains("using light"));
manager.close();
});
}
@Test
void filterDraftNestedChooserDialogAndFutureOwnedWindowFollowLiveTheme() throws Exception {
DataGridTest.fx(
() -> {
Stage stage = new Stage();
Button opener = new Button("Filter");
stage.setScene(new Scene(new VBox(opener), 500, 400));
var manager = new ThemeManager();
manager.register(stage.getScene());
stage.show();
var editor =
BuiltInFilterEditor.load(
new FilterEditorContext(
"x",
FilterColumn.text(),
new TextFilter(
"x",
TextFilter.Operator.EQUALS,
"unfinished",
false),
List.of(),
FilterColumn.Checklist.DISABLED));
var popup =
new FilterPopup(
opener,
editor,
FilterPopup.Options.defaults(),
c -> {},
c -> {});
popup.show();
Alert alert =
new Alert(Alert.AlertType.INFORMATION, "Owned dialog", ButtonType.OK);
alert.initOwner(stage);
try {
manager.select("dark");
assertTrue(popup.isOpen());
assertEquals(
"unfinished",
((TextField) editor.view().lookup("#operand")).getText());
assertTrue(
editor.view()
.getScene()
.getStylesheets()
.containsAll(Theme.dark().stylesheets()));
assertFalse(
editor.view()
.getStylesheets()
.contains(Theme.light().stylesheets().getLast()));
ComboBox<?> chooser = (ComboBox<?>) editor.view().lookup("#operator");
chooser.show();
var nested =
Window.getWindows().stream()
.filter(
w ->
w instanceof PopupWindow p
&& p.getOwnerWindow()
== editor.view()
.getScene()
.getWindow())
.toList();
assertFalse(nested.isEmpty());
manager.select("high-contrast");
for (var w : nested)
assertTrue(
w.getScene()
.getStylesheets()
.containsAll(Theme.highContrast().stylesheets()));
chooser.hide();
popup.close();
alert.show();
assertTrue(
alert.getDialogPane()
.getScene()
.getStylesheets()
.containsAll(Theme.highContrast().stylesheets()));
manager.select("dark");
assertTrue(
alert.getDialogPane()
.getScene()
.getStylesheets()
.containsAll(Theme.dark().stylesheets()));
manager.select("high-contrast");
Stage future = new Stage();
future.initOwner(stage);
future.setScene(new Scene(new VBox(new Label("Future"))));
future.show();
assertTrue(
future.getScene()
.getStylesheets()
.containsAll(Theme.highContrast().stylesheets()));
future.close();
assertFalse(
future.getScene()
.getStylesheets()
.contains(Theme.highContrast().stylesheets().getLast()));
} finally {
alert.close();
popup.close();
stage.close();
manager.close();
}
});
}
@Test
void dockingFloatingWindowsInheritWithoutChangingWindowOwnership() throws Exception {
DataGridTest.fx(
() -> {
Stage stage = new Stage();
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
stage.setScene(new Scene(pane, 600, 400));
var themes = new ThemeManager();
themes.register(stage.getScene());
themes.select("dark");
var docking = DockingManager.attach(stage, pane, new DockingOptions());
Dockable item =
new Dockable(new DockableId("example"), new TextArea("Keep this edit"));
docking.open(item, DockTarget.area("editors"));
stage.show();
try {
docking.move(item.getId(), DockTarget.floating());
Scene floating = item.getContent().getScene();
assertTrue(
floating.getStylesheets().containsAll(Theme.dark().stylesheets()));
themes.select("high-contrast");
assertTrue(
floating.getStylesheets()
.containsAll(Theme.highContrast().stylesheets()));
assertEquals("Keep this edit", ((TextArea) item.getContent()).getText());
} finally {
for (var w : List.copyOf(Window.getWindows()))
if (w != stage
&& w.getScene() != null
&& w.getScene()
.getStylesheets()
.contains(Theme.highContrast().stylesheets().getLast()))
w.hide();
stage.hide();
themes.close();
}
});
}
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1"><TextField fx:id="value" accessibleText="Custom prefix"/></VBox>
@@ -0,0 +1 @@
.neitzel-theme .button { -fx-background-radius: 9; }