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
@@ -1351,6 +1351,7 @@ public final class DockingManager {
DockPane floatingPane = new DockPane();
Stage floatingStage = new Stage();
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
de.neitzel.fx.theme.ThemeManager.link(floatingStage, stage.getScene());
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler = event -> {
event.consume();
requestFloatingWindowClose(windowId);
@@ -0,0 +1,344 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.fxml.*;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.*;
import java.util.*;
/**
* FXML controller for literal text, exact numeric, missing/present and explicit membership drafts.
*/
public final class BuiltInFilterEditor implements FilterEditor {
@FXML private ComboBox<String> mode, operator;
@FXML private TextField operand, upper, search;
@FXML private CheckBox caseSensitive;
@FXML private VBox comparison, checklistPane, candidates;
@FXML private Label scope, validation, lookupMessage, selectionSummary;
@FXML private Button selectShown, clearShown, more, retry;
private Parent view;
private FilterEditorContext context;
private final ReadOnlyStringWrapper message = new ReadOnlyStringWrapper("");
private final Set<FilterValue> selected = new LinkedHashSet<>();
private boolean missing, closed, configuring, numeric, available;
private long generation;
private int offset;
private FilterCandidates.Context candidateContext;
private FilterCandidates.Session session;
private final List<FilterCandidates.Candidate> shown = new ArrayList<>();
public static BuiltInFilterEditor load(FilterEditorContext context) {
try {
var loader =
new FXMLLoader(
BuiltInFilterEditor.class.getResource("BuiltInFilterEditor.fxml"));
Parent root = loader.load();
BuiltInFilterEditor editor = loader.getController();
editor.view = root;
try {
editor.configure(context);
} catch (RuntimeException error) {
editor.close();
throw error;
}
return editor;
} catch (IOException error) {
throw new IllegalStateException("Cannot load built-in filter FXML", error);
}
}
private void configure(FilterEditorContext context) {
this.context = context;
configuring = true;
numeric = context.configuration().editorId().equals("neitzel.number");
mode.getItems().setAll("Comparison", "Missing", "Present", "Clear filter");
if (numeric)
for (var op : NumericFilter.Operator.values()) operator.getItems().add(op.name());
else for (var op : TextFilter.Operator.values()) operator.getItems().add(op.name());
operator.setValue("EQUALS");
mode.setValue("Comparison");
caseSensitive.setSelected(context.configuration().caseSensitive());
caseSensitive.setVisible(!numeric);
caseSensitive.setManaged(!numeric);
if (context.checklist() != FilterColumn.Checklist.DISABLED) {
var requestedScope =
context.checklist() == FilterColumn.Checklist.CURRENT_PAGE
? FilterCandidates.Scope.CURRENT_PAGE
: FilterCandidates.Scope.SOURCE_WIDE;
candidateContext =
new FilterCandidates.Context(
context.columnId(), requestedScope, context.otherFilters());
available = context.configuration().candidates().scopes().contains(requestedScope);
scope.setText(
available
? (requestedScope == FilterCandidates.Scope.CURRENT_PAGE
? "Current page only — captured when opened"
: "Source-wide — excluding this column's filter")
: "Checklist unavailable: provider does not support "
+ requestedScope
+ ". Use a comparison or supply a capable provider.");
// Keep the unavailable mode visible with an explanation, never substitute a scope.
mode.getItems().add("Checklist");
if (available) {
try {
session = context.configuration().candidates().open(candidateContext);
} catch (RuntimeException error) {
lookupMessage.setText("Lookup failed: " + error.getMessage());
}
}
}
FilterCondition committed = context.committed();
if (committed instanceof TextFilter f && !numeric) {
operator.setValue(f.operator().name());
operand.setText(f.operand());
caseSensitive.setSelected(f.caseSensitive());
} else if (committed instanceof NumericFilter f && numeric) {
operator.setValue(f.operator().name());
operand.setText(format(f.operand()));
if (f.upper() != null) upper.setText(format(f.upper()));
} else if (committed instanceof MissingFilter f)
mode.setValue(f.missing() ? "Missing" : "Present");
else if (committed instanceof ValueFilter f) {
selected.addAll(f.values());
missing = f.includeMissing();
if (!mode.getItems().contains("Checklist"))
throw new IllegalArgumentException(
"Existing checklist requires an enabled candidate provider; clear it"
+ " explicitly or restore the configuration");
mode.setValue("Checklist");
} else if (committed != null)
throw new IllegalArgumentException("Editor cannot restore " + committed.typeId());
else mode.setValue("Clear filter");
validation.textProperty().bind(message);
mode.valueProperty().addListener((o, a, b) -> changed());
operator.valueProperty().addListener((o, a, b) -> changed());
operand.textProperty().addListener((o, a, b) -> changed());
upper.textProperty().addListener((o, a, b) -> changed());
caseSensitive.selectedProperty().addListener((o, a, b) -> changed());
search.textProperty().addListener((o, a, b) -> lookup(false));
selectShown.setOnAction(e -> selectShown(true));
clearShown.setOnAction(e -> selectShown(false));
more.setOnAction(e -> lookup(true));
retry.setOnAction(e -> lookup(false));
configuring = false;
changed();
if (available) lookup(false);
}
private String format(BigDecimal value) {
return value.toPlainString()
.replace(
'.',
DecimalFormatSymbols.getInstance(context.configuration().locale())
.getDecimalSeparator());
}
private BigDecimal number(String text) {
// Grouping deliberately disallowed: malformed grouping must never be silently ignored.
var format =
(DecimalFormat) NumberFormat.getNumberInstance(context.configuration().locale());
format.setGroupingUsed(false);
format.setParseBigDecimal(true);
String input = text.strip();
var position = new ParsePosition(0);
Number parsed = format.parse(input, position);
if (!(parsed instanceof BigDecimal value) || position.getIndex() != input.length())
throw new IllegalArgumentException(
"Enter a finite number for "
+ context.configuration().locale()
+ " without grouping separators");
var config = context.configuration();
if (config.integer()) {
try {
value.longValueExact();
} catch (ArithmeticException error) {
throw new IllegalArgumentException(
"Enter a whole number within the signed 64-bit range");
}
}
if ((config.minimum() != null && value.compareTo(config.minimum()) < 0)
|| (config.maximum() != null && value.compareTo(config.maximum()) > 0))
throw new IllegalArgumentException("Number is outside the configured column range");
return value;
}
public FilterCondition draft() {
if (closed) throw new IllegalStateException("Editor closed");
return switch (mode.getValue()) {
case "Clear filter" -> null;
case "Missing" -> new MissingFilter(context.columnId(), true);
case "Present" -> new MissingFilter(context.columnId(), false);
case "Checklist" -> {
if (!available)
throw new IllegalArgumentException(
"Checklist scope is unavailable; configure a capable provider");
yield new ValueFilter(context.columnId(), selected, missing);
}
case "Comparison" ->
numeric
? new NumericFilter(
context.columnId(),
NumericFilter.Operator.valueOf(operator.getValue()),
number(operand.getText()),
operator.getValue().equals("RANGE")
? number(upper.getText())
: null)
: new TextFilter(
context.columnId(),
TextFilter.Operator.valueOf(operator.getValue()),
operand.getText(),
caseSensitive.isSelected());
default -> throw new IllegalArgumentException("Select a filter mode");
};
}
private void changed() {
if (configuring || closed) return;
boolean comparing = mode.getValue().equals("Comparison"),
checklist = mode.getValue().equals("Checklist");
comparison.setVisible(comparing);
comparison.setManaged(comparing);
checklistPane.setVisible(checklist);
checklistPane.setManaged(checklist);
boolean range = numeric && "RANGE".equals(operator.getValue());
upper.setVisible(range);
upper.setManaged(range);
selectionSummary.setText(
selected.size()
+ " selected values"
+ (missing ? " plus missing" : "")
+ " (including values outside this batch)");
try {
draft();
message.set("");
} catch (RuntimeException error) {
message.set(error.getMessage());
}
}
private void selectShown(boolean select) {
for (var value : shown) {
if (value.value() == null) missing = select;
else if (select) selected.add(value.value());
else selected.remove(value.value());
}
render();
changed();
}
private void render() {
candidates.getChildren().clear();
for (var value : shown) {
var box = new CheckBox(value.label());
box.setSelected(value.value() == null ? missing : selected.contains(value.value()));
box.setOnAction(
e -> {
if (value.value() == null) missing = box.isSelected();
else if (box.isSelected()) selected.add(value.value());
else selected.remove(value.value());
changed();
});
candidates.getChildren().add(box);
}
}
private void lookup(boolean append) {
if (closed || !available) return;
long token = ++generation;
int requestedOffset = append ? offset : 0;
lookupMessage.setText("Loading candidates…");
more.setDisable(true);
retry.setDisable(true);
try {
if (session == null)
session = context.configuration().candidates().open(candidateContext);
session.load(
new FilterCandidates.Request(
candidateContext, search.getText(), requestedOffset, 50))
.whenComplete(
(batch, error) ->
Platform.runLater(
() -> {
if (closed || generation != token) return;
retry.setDisable(false);
if (error != null || batch == null) {
lookupMessage.setText(
"Lookup failed: "
+ (error == null
? "missing batch"
: error.getMessage())
+ ". Selections preserved;"
+ " retry available.");
return;
}
if (!append) shown.clear();
// Count provider rows, not de-duplicated display
// rows, for the next offset.
offset =
Math.addExact(
requestedOffset,
batch.candidates().size());
for (var candidate : batch.candidates())
if (shown.stream()
.noneMatch(
c ->
Objects.equals(
c.value(),
candidate
.value())))
shown.add(candidate);
more.setDisable(
!batch.hasMore()
|| batch.candidates().isEmpty());
lookupMessage.setText(
batch.hasMore()
? "More candidates available"
: "End of candidate results");
render();
changed();
}));
} catch (RuntimeException error) {
retry.setDisable(false);
lookupMessage.setText(
"Lookup failed: " + error.getMessage() + ". Selections preserved.");
}
}
public Parent view() {
return view;
}
public ReadOnlyStringProperty validationMessageProperty() {
return message.getReadOnlyProperty();
}
public boolean nestedPopupShowing() {
return mode.isShowing() || operator.isShowing();
}
public void closeNestedPopup() {
mode.hide();
operator.hide();
}
public void close() {
if (closed) return;
closed = true;
generation++;
closeNestedPopup();
validation.textProperty().unbind();
if (session != null) {
var retired = session;
session = null;
retired.close();
}
}
}
@@ -0,0 +1,66 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.FilterCandidates;
import java.math.BigDecimal;
import java.util.*;
/** Developer configuration. Bounds express the actual numeric domain, without rounding. */
public record FilterColumn(
String editorId,
Locale locale,
boolean caseSensitive,
boolean integer,
BigDecimal minimum,
BigDecimal maximum,
Checklist checklist,
FilterCandidates.Provider candidates) {
public enum Checklist {
INHERIT,
DISABLED,
CURRENT_PAGE,
SOURCE_WIDE
}
public FilterColumn {
Objects.requireNonNull(editorId);
Objects.requireNonNull(locale);
Objects.requireNonNull(checklist);
if (minimum != null && maximum != null && minimum.compareTo(maximum) > 0)
throw new IllegalArgumentException("Reversed numeric domain");
if ((checklist == Checklist.CURRENT_PAGE || checklist == Checklist.SOURCE_WIDE)
&& candidates == null)
throw new IllegalArgumentException(
"Enabled checklist requires a developer-supplied provider");
}
public static FilterColumn text() {
return new FilterColumn(
"neitzel.text",
Locale.getDefault(),
false,
false,
null,
null,
Checklist.INHERIT,
null);
}
public static FilterColumn number(
Locale locale, boolean integer, BigDecimal minimum, BigDecimal maximum) {
return new FilterColumn(
"neitzel.number",
locale,
false,
integer,
minimum,
maximum,
Checklist.INHERIT,
null);
}
public FilterColumn withChecklist(Checklist mode, FilterCandidates.Provider provider) {
return new FilterColumn(
editorId, locale, caseSensitive, integer, minimum, maximum, mode, provider);
}
}
@@ -0,0 +1,25 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.FilterCondition;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.scene.Parent;
/** Fresh per session; controllers own drafts only. Null draft explicitly clears the filter. */
public interface FilterEditor extends AutoCloseable {
Parent view();
ReadOnlyStringProperty validationMessageProperty();
/** Throws an actionable IllegalArgumentException for invalid input; never mutates a query. */
FilterCondition draft();
default boolean nestedPopupShowing() {
return false;
}
default void closeNestedPopup() {}
@Override
void close();
}
@@ -0,0 +1,28 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.*;
import java.util.*;
public record FilterEditorContext(
String columnId,
FilterColumn configuration,
FilterCondition committed,
List<FilterCondition> otherFilters,
FilterColumn.Checklist checklist) {
public FilterEditorContext {
Objects.requireNonNull(columnId);
Objects.requireNonNull(configuration);
Objects.requireNonNull(checklist);
otherFilters = List.copyOf(otherFilters);
if (checklist == FilterColumn.Checklist.INHERIT)
throw new IllegalArgumentException("Resolve checklist default first");
if (checklist != FilterColumn.Checklist.DISABLED && configuration.candidates() == null)
throw new IllegalArgumentException(
"Enabled checklist requires a provider for " + columnId);
if (committed != null && !columnId.equals(committed.columnId()))
throw new IllegalArgumentException("Wrong committed column");
if (otherFilters.stream().anyMatch(c -> c.columnId().equals(columnId)))
throw new IllegalArgumentException("Own filter in candidate context");
}
}
@@ -0,0 +1,77 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.*;
import java.util.*;
import java.util.function.Function;
/** Editor availability never implies evaluation, persistence or adapter support. */
public final class FilterEditors {
public record Registration(
String id,
FilterCapabilities capabilities,
Set<String> conditionTypes,
Function<FilterEditorContext, FilterEditor> factory) {
public Registration {
if (id == null || id.isBlank())
throw new IllegalArgumentException("Missing stable editor ID");
Objects.requireNonNull(capabilities);
conditionTypes = Set.copyOf(conditionTypes);
if (conditionTypes.isEmpty())
throw new IllegalArgumentException("Declare emitted condition types");
Objects.requireNonNull(factory);
}
public void requireEvaluation(String executionId) {
boolean supported =
executionId.equals("local")
? capabilities.localEvaluation()
: capabilities.adapters().contains(executionId);
if (!supported)
throw new UnsupportedOperationException(
"Editor "
+ id
+ " does not declare evaluation for "
+ executionId
+ "; register a compatible filter or change source");
}
public void validate(FilterCondition condition) {
if (condition != null && !conditionTypes.contains(condition.typeId()))
throw new UnsupportedOperationException(
"Editor " + id + " did not declare condition " + condition.typeId());
}
}
private final Map<String, Registration> registrations = new LinkedHashMap<>();
public void register(Registration registration) {
if (registrations.putIfAbsent(registration.id(), registration) != null)
throw new IllegalArgumentException(
"Duplicate editor registration: " + registration.id());
}
public Registration require(String id) {
var registration = registrations.get(id);
if (registration == null)
throw new IllegalArgumentException("Register the missing filter editor: " + id);
return registration;
}
public static FilterEditors builtIns() {
return builtIns(Set.of());
}
/** Application-declared adapter support; every concrete condition is still source-validated. */
public static FilterEditors builtIns(Set<String> adapters) {
var editors = new FilterEditors();
for (String id : List.of("neitzel.text", "neitzel.number"))
editors.register(
new Registration(
id,
new FilterCapabilities(true, true, adapters),
Set.of(id, "neitzel.missing", "neitzel.values"),
BuiltInFilterEditor::load));
return editors;
}
}
@@ -0,0 +1,245 @@
package de.neitzel.fx.grid.filter;
import de.neitzel.grid.FilterCondition;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ChangeListener;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import java.util.*;
import java.util.function.Consumer;
/** One transactional edit session. All methods run on the FX thread; close always rolls back. */
public final class FilterPopup implements AutoCloseable {
public enum Outside {
CANCEL,
ACCEPT
}
public record Options(Outside outside, boolean showOk, boolean showCancel) {
public Options {
Objects.requireNonNull(outside);
}
public static Options defaults() {
return new Options(Outside.CANCEL, true, true);
}
}
private final Node opener;
private final Window owner;
private final FilterEditor editor;
private final Consumer<FilterCondition> validate, commit;
private final Options options;
private final Popup popup = new Popup();
private final Label error = new Label();
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
new ReadOnlyObjectWrapper<>();
private final VBox root;
private boolean closed, reopening;
private final EventHandler<WindowEvent> ownerHidden = e -> close();
private final ChangeListener<Scene> detached =
(o, a, b) -> {
if (a != b) close();
};
public FilterPopup(
Node opener,
FilterEditor editor,
Options options,
Consumer<FilterCondition> validate,
Consumer<FilterCondition> commit) {
requireFx();
this.opener = Objects.requireNonNull(opener);
this.editor = Objects.requireNonNull(editor);
this.options = Objects.requireNonNull(options);
this.validate = Objects.requireNonNull(validate);
this.commit = Objects.requireNonNull(commit);
if (opener.getScene() == null
|| opener.getScene().getWindow() == null
|| !opener.getScene().getWindow().isShowing())
throw new IllegalArgumentException("Filter opener needs a visible owner window");
owner = opener.getScene().getWindow();
Button ok = new Button("OK"),
cancel = new Button("Cancel"),
clear = new Button("Clear filter");
ok.setId("filter-ok");
cancel.setId("filter-cancel");
clear.setId("filter-clear");
ok.setOnAction(e -> accept());
cancel.setOnAction(e -> cancel());
clear.setOnAction(e -> finish(true, true, true));
ok.setVisible(options.showOk());
ok.setManaged(options.showOk());
cancel.setVisible(options.showCancel());
cancel.setManaged(options.showCancel());
HBox actions = new HBox(8, ok, cancel, clear);
actions.getStyleClass().add("filter-actions");
error.setWrapText(true);
error.getStyleClass().add("filter-validation");
root = new VBox(8, editor.view(), error, actions);
root.getStyleClass().addAll("root", "filter-popup");
root.setFocusTraversable(true);
root.getStylesheets().add(FilterPopup.class.getResource("filters.css").toExternalForm());
root.getStylesheets()
.addAll(de.neitzel.fx.theme.ThemeManager.applicationStyles(opener.getScene()));
popup.getContent().add(root);
popup.setAutoHide(true);
popup.setHideOnEscape(false);
popup.setConsumeAutoHidingEvents(false);
popup.setOnAutoHide(e -> outside());
popup.setOnHidden(
e ->
Platform.runLater(
() -> {
if (!closed && !reopening && !popup.isShowing()) close();
}));
root.addEventFilter(
KeyEvent.KEY_PRESSED,
e -> {
if (e.getCode() != KeyCode.ENTER && e.getCode() != KeyCode.ESCAPE) return;
if (nested()) {
if (e.getCode() == KeyCode.ESCAPE) {
hideNested();
e.consume();
}
return;
}
e.consume();
if (e.getCode() == KeyCode.ENTER) accept();
else cancel();
});
owner.addEventHandler(WindowEvent.WINDOW_HIDING, ownerHidden);
opener.sceneProperty().addListener(detached);
}
public void show() {
requireFx();
if (closed) throw new IllegalStateException("Filter session closed");
var bounds = opener.localToScreen(opener.getBoundsInLocal());
if (bounds == null || !owner.isShowing()) {
close();
return;
}
popup.show(opener, bounds.getMinX(), bounds.getMaxY());
Platform.runLater(
() -> {
if (!closed && popup.isShowing()) {
Node field = editor.view().lookup(".text-field");
(field == null || !visible(field) ? root : field).requestFocus();
}
});
}
public boolean isOpen() {
return !closed;
}
public boolean isShowing() {
return popup.isShowing();
}
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
return disposalFailure.getReadOnlyProperty();
}
public String errorMessage() {
return error.getText();
}
public void accept() {
finish(true, true, false);
}
public void cancel() {
finish(false, true, false);
}
/** Used for outside dismissal and an opener re-click; leaves focus with the clicked target. */
public void outside() {
finish(options.outside() == Outside.ACCEPT, false, false);
}
private void finish(boolean accept, boolean focus, boolean clear) {
requireFx();
if (closed) return;
if (accept) {
try {
FilterCondition condition = clear ? null : editor.draft();
validate.accept(condition);
commit.accept(condition);
} catch (RuntimeException invalid) {
error.setText(
Objects.toString(invalid.getMessage(), invalid.getClass().getSimpleName()));
if (!popup.isShowing() && owner.isShowing()) {
reopening = true;
Platform.runLater(
() -> {
if (!closed) show();
reopening = false;
});
}
return;
}
}
close();
if (focus && owner.isShowing() && opener.getScene() != null) opener.requestFocus();
}
private static boolean visible(Node node) {
for (Node current = node; current != null; current = current.getParent())
if (!current.isVisible() || current.isDisabled()) return false;
return true;
}
private List<ComboBoxBase<?>> choosers() {
List<ComboBoxBase<?>> found = new ArrayList<>();
collect(editor.view(), found);
return found;
}
private static void collect(Node node, List<ComboBoxBase<?>> found) {
if (node instanceof ComboBoxBase<?> chooser) found.add(chooser);
if (node instanceof Parent parent)
for (Node child : parent.getChildrenUnmodifiable()) collect(child, found);
}
private boolean nested() {
return editor.nestedPopupShowing() || choosers().stream().anyMatch(ComboBoxBase::isShowing);
}
private void hideNested() {
editor.closeNestedPopup();
choosers().forEach(ComboBoxBase::hide);
}
public void close() {
requireFx();
if (closed) return;
closed = true;
owner.removeEventHandler(WindowEvent.WINDOW_HIDING, ownerHidden);
opener.sceneProperty().removeListener(detached);
popup.setOnAutoHide(null);
popup.setOnHidden(null);
popup.hide();
try {
editor.close();
} catch (RuntimeException failure) {
disposalFailure.set(failure);
} finally {
popup.getContent().clear();
}
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the FX application thread");
}
}
@@ -0,0 +1,34 @@
package de.neitzel.fx.theme;
import java.util.*;
/** A named CSS bundle. Themes contain presentation only; applications own preference storage. */
public record Theme(String id, List<String> stylesheets) {
public Theme {
if (id == null || id.isBlank()) throw new IllegalArgumentException("Missing theme ID");
stylesheets = List.copyOf(stylesheets);
if (stylesheets.isEmpty()) throw new IllegalArgumentException("Missing theme stylesheets");
}
public static Theme light() {
return bundled("light");
}
public static Theme dark() {
return bundled("dark");
}
public static Theme highContrast() {
return bundled("high-contrast");
}
private static Theme bundled(String id) {
return new Theme(id, List.of(resource("theme-base.css"), resource(id + ".css")));
}
private static String resource(String name) {
return Objects.requireNonNull(
Theme.class.getResource(name), "Missing bundled theme: " + name)
.toExternalForm();
}
}
@@ -0,0 +1,317 @@
package de.neitzel.fx.theme;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.beans.value.ChangeListener;
import javafx.collections.ListChangeListener;
import javafx.scene.*;
import javafx.stage.*;
import java.net.URI;
import java.util.*;
import java.util.function.Consumer;
/** Opt-in, application-owned theme lifetime. All operations use the FX application thread. */
public final class ThemeManager implements AutoCloseable {
private static final Object MANAGER = new Object(), OWNER_SCENE = new Object();
private static final String SCOPE = "neitzel-theme";
public record Failure(String message, Throwable cause) {}
private final Map<String, Theme> themes = new LinkedHashMap<>();
private final Map<Scene, Registration> scenes = new LinkedHashMap<>();
private final Map<Window, Registration> automatic = new IdentityHashMap<>();
private final ReadOnlyObjectWrapper<Theme> selected =
new ReadOnlyObjectWrapper<>(Theme.light());
private final ReadOnlyObjectWrapper<Failure> failure = new ReadOnlyObjectWrapper<>();
private Consumer<Scene> installationCheck = scene -> {};
private boolean closed, switching;
private final ListChangeListener<Window> windows =
change -> {
while (change.next()) {
if (change.wasRemoved())
for (var window : change.getRemoved()) {
var r = automatic.remove(window);
if (r != null) r.close();
}
if (change.wasAdded())
for (var window : change.getAddedSubList()) inherit(window);
}
};
public ThemeManager() {
requireFx();
for (var theme : List.of(Theme.light(), Theme.dark(), Theme.highContrast()))
themes.put(theme.id(), theme);
Window.getWindows().addListener(windows);
}
public ReadOnlyObjectProperty<Theme> selectedThemeProperty() {
return selected.getReadOnlyProperty();
}
public ReadOnlyObjectProperty<Failure> failureProperty() {
return failure.getReadOnlyProperty();
}
public List<Theme> themes() {
return List.copyOf(themes.values());
}
public void addTheme(Theme theme) {
check();
if (themes.putIfAbsent(theme.id(), theme) != null)
throw new IllegalArgumentException("Duplicate theme ID: " + theme.id());
}
/**
* Optional application CSS qualification; throwing rolls back a detectable installation
* failure.
*/
public void setInstallationCheck(Consumer<Scene> check) {
check();
installationCheck = Objects.requireNonNull(check);
}
public Registration register(Scene scene) {
check();
Objects.requireNonNull(scene);
if (scenes.containsKey(scene))
throw new IllegalArgumentException("Scene already registered");
if (scene.getProperties().containsKey(MANAGER))
throw new IllegalArgumentException("Scene belongs to another theme manager");
preflight(selected.get());
var registration = new Registration(scene);
var original = List.copyOf(scene.getStylesheets());
try {
registration.install(selected.get());
installationCheck.accept(scene);
scenes.put(scene, registration);
scene.getProperties().put(MANAGER, this);
scene.rootProperty().addListener(registration.rootChanged);
for (var window : List.copyOf(Window.getWindows())) inherit(window);
return registration;
} catch (RuntimeException error) {
registration.unmark(scene.getRoot());
if (!registration.ownerBound) scene.getStylesheets().setAll(original);
failure.set(new Failure("Could not theme scene: " + error.getMessage(), error));
throw error;
}
}
public boolean select(String id) {
check();
if (switching) throw new IllegalStateException("Theme switch already in progress");
var theme = themes.get(id);
if (theme == null) {
failure.set(
new Failure("Theme unavailable: " + id + ". Choose a registered theme.", null));
return false;
}
Map<Registration, List<String>> before = new LinkedHashMap<>();
Map<Registration, List<String>> owned = new LinkedHashMap<>();
switching = true;
try {
preflight(theme);
for (var r : scenes.values()) {
if (!r.ownerBound) {
before.put(r, List.copyOf(r.scene.getStylesheets()));
owned.put(r, r.managed);
}
}
for (var r : List.copyOf(scenes.values())) {
r.install(theme);
installationCheck.accept(r.scene);
}
selected.set(theme);
failure.set(null);
return true;
} catch (RuntimeException error) {
for (var entry : before.entrySet()) {
try {
entry.getKey().scene.getStylesheets().setAll(entry.getValue());
entry.getKey().managed = owned.get(entry.getKey());
entry.getKey().scene.getRoot().applyCss();
} catch (RuntimeException rollback) {
error.addSuppressed(rollback);
}
}
failure.set(
new Failure(
"Could not install theme "
+ id
+ "; retained "
+ selected.get().id()
+ ": "
+ error.getMessage(),
error));
return false;
} finally {
switching = false;
}
}
/** Startup fallback is explicit, and retains an explanation even after Light installs. */
public boolean selectSaved(String id) {
if (select(id)) return true;
var problem = failure.get();
if (select("light"))
failure.set(
new Failure(
"Saved theme unavailable; using light. " + problem.message(),
problem.cause()));
return false;
}
/** Link a library-owned floating window without imposing JavaFX window ownership semantics. */
public static void link(Window child, Scene owner) {
requireFx();
child.getProperties().put(OWNER_SCENE, Objects.requireNonNull(owner));
}
/** Copy application/default CSS to another surface without freezing a selected theme there. */
public static List<String> applicationStyles(Scene scene) {
var manager = (ThemeManager) scene.getProperties().get(MANAGER);
if (manager == null) return List.copyOf(scene.getStylesheets());
var reserved = manager.reserved();
return scene.getStylesheets().stream().filter(s -> !reserved.contains(s)).toList();
}
private Set<String> reserved() {
Set<String> urls = new HashSet<>();
themes.values().forEach(t -> urls.addAll(t.stylesheets()));
return urls;
}
private void inherit(Window window) {
if (closed
|| automatic.containsKey(window)
|| window.getScene() == null
|| scenes.containsKey(window.getScene())) return;
Scene owner = (Scene) window.getProperties().get(OWNER_SCENE);
if (owner == null) {
Window parent =
window instanceof PopupWindow p
? p.getOwnerWindow()
: window instanceof Stage s ? s.getOwner() : null;
if (parent != null) owner = parent.getScene();
}
if (owner != null && owner.getProperties().get(MANAGER) == this) {
try {
automatic.put(window, register(window.getScene()));
} catch (RuntimeException error) {
failure.set(
new Failure("Could not theme new window: " + error.getMessage(), error));
}
}
}
private static void preflight(Theme theme) {
for (String url : theme.stylesheets())
try {
var connection = URI.create(url).toURL().openConnection();
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
try (var stream = connection.getInputStream()) {
stream.read();
}
} catch (Exception error) {
throw new IllegalArgumentException(
"Missing or unreadable theme stylesheet: " + url, error);
}
}
public final class Registration implements AutoCloseable {
private final Scene scene;
private final boolean ownerBound;
private List<String> managed = List.of();
private Parent marked;
private boolean addedClass, disposed;
private final ChangeListener<Parent> rootChanged =
(o, old, next) -> {
unmark(old);
mark(next);
next.applyCss();
};
private Registration(Scene scene) {
this.scene = scene;
// Standard JavaFX Dialogs bind this list to their owner. Never edit the bound target.
this.ownerBound =
scene.getRoot() instanceof javafx.scene.control.DialogPane
&& scene.getWindow() instanceof Stage window
&& window.getOwner() instanceof Stage owner
&& owner.getScene() != null
&& scene.getStylesheets().equals(owner.getScene().getStylesheets());
if (ownerBound
&& ((Stage) ((Stage) scene.getWindow()).getOwner())
.getScene()
.getProperties()
.get(MANAGER)
!= ThemeManager.this)
throw new IllegalArgumentException(
"Register a dialog's owner scene before the dialog");
}
private void mark(Parent root) {
marked = root;
addedClass = !root.getStyleClass().contains(SCOPE);
if (addedClass) root.getStyleClass().add(SCOPE);
}
private void unmark(Parent root) {
if (root == marked && addedClass) root.getStyleClass().remove(SCOPE);
}
private void install(Theme theme) {
if (marked == null) mark(scene.getRoot());
if (ownerBound) {
scene.getRoot().applyCss();
return;
}
var next = new ArrayList<>(scene.getStylesheets());
// Reserved bundle URLs copied from an owner are theme-owned, never application
// overrides.
next.removeIf(reserved()::contains);
int index = 0;
while (index < next.size()
&& (next.get(index).endsWith("/docking.css")
|| next.get(index).endsWith("/filters.css"))) index++;
next.addAll(index, theme.stylesheets());
scene.getStylesheets().setAll(next);
managed = theme.stylesheets();
scene.getRoot().applyCss();
}
public void close() {
requireFx();
if (disposed) return;
disposed = true;
scene.rootProperty().removeListener(rootChanged);
if (!ownerBound) scene.getStylesheets().removeAll(managed);
unmark(scene.getRoot());
scenes.remove(scene);
if (scene.getProperties().get(MANAGER) == ThemeManager.this)
scene.getProperties().remove(MANAGER);
}
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the FX application thread");
}
private void check() {
requireFx();
if (closed) throw new IllegalStateException("Theme manager closed");
}
public void close() {
requireFx();
if (closed) return;
closed = true;
Window.getWindows().removeListener(windows);
for (var r : List.copyOf(scenes.values())) r.close();
automatic.clear();
}
}
@@ -0,0 +1,652 @@
package de.neitzel.fx.view;
import de.neitzel.fx.grid.filter.*;
import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/**
* Local/external data grid coordinator and paging presentation. Construct and use on the FX thread.
* No query runs until load/refresh or an explicit query change, allowing configuration before first
* load. The application owns the source and executor. Closing releases only this grid's requests
* and rows.
*/
public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private final Table table = new Table();
private final TableResults<K, T> renderer;
private final GridCoordinator<K, T> coordinator;
private final ReadOnlyObjectWrapper<GridCoordinator.State<K, T>> state =
new ReadOnlyObjectWrapper<>();
private final Label status = new Label("Not loaded");
private final Button first = new Button("First"),
previous = new Button("Previous"),
next = new Button("Next"),
last = new Button("Last"),
retry = new Button("Retry"),
refresh = new Button("Refresh");
private final ComboBox<String> pageSize = new ComboBox<>();
private final GridQuery initial;
private final List<ResultColumn> columnDefinitions;
private GridDefinition setupDefinition;
private Map<Integer, java.util.function.UnaryOperator<GridSetup>> setupMigrations = Map.of();
private final ReadOnlyObjectWrapper<List<String>> restorationAdjustments =
new ReadOnlyObjectWrapper<>(List.of());
private final Map<String, FilterColumn> filterColumns = new LinkedHashMap<>();
private FilterEditors filterEditors = FilterEditors.builtIns();
private FilterColumn.Checklist defaultChecklist = FilterColumn.Checklist.DISABLED;
private FilterPopup.Options filterPopupOptions = FilterPopup.Options.defaults();
private FilterPopup filterPopup;
private final ReadOnlyObjectWrapper<RuntimeException> filterDisposalFailure =
new ReadOnlyObjectWrapper<>();
private boolean updating, closed;
private long visibleSourceVersion;
private Alert pendingAlert;
private long alertGeneration;
public DataGrid(
List<ResultColumn> columns,
Function<T, ResultRow> rowFactory,
GridSource<K, T> source) {
requireFx();
columnDefinitions = List.copyOf(columns);
Objects.requireNonNull(source);
initial =
new GridQuery(
List.of(),
List.of(),
new PageRequest.Paged(
0, Math.min(50, source.capabilities().maximumPageSize())));
renderer = table.openResults(columns, rowFactory);
coordinator =
new GridCoordinator<>(
source,
Platform::runLater,
this::changed,
result -> renderer.show(result.rows()));
coordinator.setConfirmation(this::confirmAll);
renderer.setOnSortRequest(
id -> {
var q = query();
SortKey.Direction direction =
q.sort().size() == 1
&& q.sort().getFirst().columnId().equals(id)
&& q.sort().getFirst().direction()
== SortKey.Direction.ASCENDING
? SortKey.Direction.DESCENDING
: SortKey.Direction.ASCENDING;
setSort(new SortKey(id, direction));
});
first.setOnAction(e -> first());
previous.setOnAction(e -> previous());
next.setOnAction(e -> next());
last.setOnAction(e -> last());
retry.setOnAction(e -> coordinator.retry());
refresh.setOnAction(e -> refresh());
pageSize.setOnAction(
e -> {
if (updating || pageSize.getValue() == null) return;
setPageRequest(
pageSize.getValue().equals("All")
? new PageRequest.All()
: new PageRequest.Paged(
0, Integer.parseInt(pageSize.getValue())));
});
status.setWrapText(true);
status.getStyleClass().add("data-grid-status");
HBox controls =
new HBox(
8,
first,
previous,
next,
last,
new Label("Rows"),
pageSize,
refresh,
retry);
controls.getStyleClass().add("data-grid-paging");
getStyleClass().add("data-grid");
setSpacing(8);
getChildren().addAll(table, controls, status);
VBox.setVgrow(table, Priority.ALWAYS);
state.set(coordinator.state());
updateControls(coordinator.state());
}
public ReadOnlyObjectProperty<GridCoordinator.State<K, T>> stateProperty() {
return state.getReadOnlyProperty();
}
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
return renderer.selectedKeyProperty();
}
public ReadOnlyObjectProperty<T> selectedElementProperty() {
return renderer.selectedElementProperty();
}
public void select(K key) {
check();
renderer.select(key);
}
public void confirmedDeleted(K key) {
check();
if (Objects.equals(key, selectedKeyProperty().get())) renderer.select(null);
refresh();
}
public void setEditGuard(Function<GridQuery, CompletionStage<Boolean>> guard) {
check();
coordinator.setGuard(guard);
}
public void setAllConfirmation(BiFunction<GridQuery, Long, CompletionStage<Boolean>> handler) {
check();
coordinator.setConfirmation(handler);
}
public void setAllWarningThreshold(long count) {
check();
coordinator.setAllWarningThreshold(count);
}
public void setColumnOrder(List<String> ids) {
check();
closeFilter();
coordinator.cancelRestore();
renderer.setColumnOrder(ids);
}
public double setColumnWidth(String id, ColumnWidth width) {
check();
closeFilter();
coordinator.cancelRestore();
return renderer.setColumnWidth(id, width);
}
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
return renderer.disposalFailureProperty();
}
public void load() {
check();
coordinator.request(query());
}
public void refresh() {
load();
}
public void retry() {
check();
coordinator.retry();
}
public void setSource(GridSource<K, T> source) {
check();
closeFilter();
var q = query();
coordinator.request(source, new GridQuery(q.filters(), q.sort(), firstPage(q.page())));
}
public void setFilters(List<FilterCondition> filters) {
check();
coordinator.validateFilters(filters);
var q = query();
coordinator.request(new GridQuery(filters, q.sort(), firstPage(q.page())));
}
/**
* Definition type IDs are stable schema identifiers, not display labels or Java class names.
*/
public void configureSetups(
String id,
int version,
Map<String, String> types,
Map<Integer, java.util.function.UnaryOperator<GridSetup>> migrations) {
check();
if (!types.keySet().equals(new HashSet<>(renderer.columnOrder())))
throw new IllegalArgumentException("Declare a type for every column");
GridDefinition definition =
new GridDefinition(
id,
version,
columnDefinitions.stream()
.map(
c ->
new GridDefinition.Column(
c.id(),
types.get(c.id()),
c.defaultWidth(),
c.minimumWidth(),
c.maximumWidth(),
c.fixedPosition()))
.toList());
Map<Integer, java.util.function.UnaryOperator<GridSetup>> next = Map.copyOf(migrations);
if (coordinator.isRestoring())
throw new IllegalStateException("Cannot change definition during restoration");
setupDefinition = definition;
setupMigrations = next;
}
/** Snapshots committed settings only; never accepts or cancels an open draft. */
public GridSetup snapshotSetup() {
check();
if (setupDefinition == null)
throw new IllegalStateException("Configure the grid definition before saving");
var committed =
coordinator.state().displayed() == null ? initial : coordinator.state().displayed();
Map<String, String> types = new HashMap<>();
setupDefinition.columns().forEach(c -> types.put(c.id(), c.type()));
return new GridSetup(
1,
setupDefinition.id(),
setupDefinition.version(),
renderer.columnOrder().stream()
.map(
id ->
new GridSetup.ColumnState(
id, types.get(id), renderer.columnWidths().get(id)))
.toList(),
committed.sort(),
committed.filters(),
firstPage(committed.page()));
}
public ReadOnlyObjectProperty<List<String>> restorationAdjustmentsProperty() {
return restorationAdjustments.getReadOnlyProperty();
}
/** Decode through a supplier so parse errors receive the same visible, query-free rollback. */
public void restoreSetup(java.util.function.Supplier<GridSetup> decode) {
check();
try {
restoreSetup(Objects.requireNonNull(decode.get()));
} catch (RuntimeException error) {
coordinator.rejectSetup(error);
}
}
public void restoreSetup(GridSetup saved) {
check();
try {
if (setupDefinition == null)
throw new IllegalStateException("Configure the grid definition before restoring");
var prepared =
setupDefinition.prepare(
saved,
setupMigrations,
coordinator.capabilities(),
condition -> coordinator.validateFilters(List.of(condition)));
var setup = prepared.setup();
Map<String, ColumnWidth> widths = new LinkedHashMap<>();
setup.columns().forEach(c -> widths.put(c.id(), c.width()));
coordinator.restoreSetup(
new GridQuery(setup.filters(), setup.sort(), setup.page()),
this::closeFilter,
result -> {
renderer.show(
result.rows(),
setup.columns().stream().map(GridSetup.ColumnState::id).toList(),
widths);
restorationAdjustments.set(prepared.adjustments());
});
} catch (RuntimeException error) {
coordinator.rejectSetup(error);
}
}
public void setFilterEditors(FilterEditors editors) {
check();
Objects.requireNonNull(editors);
filterColumns.values().forEach(c -> editors.require(c.editorId()));
closeFilter();
filterEditors = editors;
}
public void setDefaultChecklist(FilterColumn.Checklist mode) {
check();
Objects.requireNonNull(mode);
if (mode == FilterColumn.Checklist.INHERIT)
throw new IllegalArgumentException("Grid default cannot inherit");
for (var entry : filterColumns.values())
if (entry.checklist() == FilterColumn.Checklist.INHERIT
&& mode != FilterColumn.Checklist.DISABLED
&& entry.candidates() == null)
throw new IllegalArgumentException(
"Each enabled column needs a candidate provider");
closeFilter();
defaultChecklist = mode;
}
public void setFilterPopupOptions(FilterPopup.Options options) {
check();
closeFilter();
filterPopupOptions = Objects.requireNonNull(options);
}
public void configureFilter(String column, FilterColumn configuration) {
check();
Objects.requireNonNull(configuration);
if (!renderer.columnOrder().contains(column))
throw new IllegalArgumentException("Unknown filter column: " + column);
filterEditors.require(configuration.editorId());
if (configuration.checklist() == FilterColumn.Checklist.INHERIT
&& defaultChecklist != FilterColumn.Checklist.DISABLED
&& configuration.candidates() == null)
throw new IllegalArgumentException("Enabled checklist requires a provider");
closeFilter();
filterColumns.put(column, configuration);
renderer.setFilterActions(filterColumns.keySet(), this::openFilter);
}
private void openFilter(String column, javafx.scene.Node opener) {
check();
if (filterPopup != null && filterPopup.isOpen()) {
filterPopup.outside();
return;
}
var config = filterColumns.get(column);
var registration = filterEditors.require(config.editorId());
var current = query().filters();
var committed =
current.stream().filter(f -> f.columnId().equals(column)).findFirst().orElse(null);
var others = current.stream().filter(f -> !f.columnId().equals(column)).toList();
FilterEditor editor = null;
try {
editor =
registration
.factory()
.apply(
new FilterEditorContext(
column,
config,
committed,
others,
config.checklist() == FilterColumn.Checklist.INHERIT
? defaultChecklist
: config.checklist()));
filterPopup =
new FilterPopup(
opener,
editor,
filterPopupOptions,
condition -> {
registration.validate(condition);
if (condition != null) {
registration.requireEvaluation(coordinator.filterExecutionId());
if (!condition.columnId().equals(column))
throw new IllegalArgumentException(
"Editor returned another column");
coordinator.validateFilters(List.of(condition));
}
},
condition -> {
// Preserve current other-column state, even if it changed while
// this editor was open.
List<FilterCondition> nextFilters =
new ArrayList<>(
query().filters().stream()
.filter(f -> !f.columnId().equals(column))
.toList());
if (condition != null) nextFilters.add(condition);
setFilters(nextFilters);
});
filterPopup
.disposalFailureProperty()
.addListener((o, old, failure) -> filterDisposalFailure.set(failure));
filterPopup.show();
} catch (RuntimeException error) {
if (editor != null) editor.close();
status.setText("Cannot open filter: " + error.getMessage());
}
}
public ReadOnlyObjectProperty<RuntimeException> filterDisposalFailureProperty() {
return filterDisposalFailure.getReadOnlyProperty();
}
private void closeFilter() {
if (filterPopup != null) {
filterPopup.close();
filterPopup = null;
}
}
public void setSort(SortKey sort) {
check();
var q = query();
coordinator.request(
new GridQuery(
q.filters(),
sort == null ? List.of() : List.of(sort),
firstPage(q.page())));
}
public void setPageSize(int size) {
setPageRequest(new PageRequest.Paged(0, size));
}
public void showAll() {
setPageRequest(new PageRequest.All());
}
public void setPageRequest(PageRequest page) {
check();
var q = query();
coordinator.request(new GridQuery(q.filters(), q.sort(), page));
}
public void first() {
check();
if (query().page() instanceof PageRequest.Paged p)
setPageRequest(new PageRequest.Paged(0, p.pageSize()));
}
public void previous() {
check();
if (query().page() instanceof PageRequest.Paged p && p.pageIndex() > 0)
setPageRequest(new PageRequest.Paged(p.pageIndex() - 1, p.pageSize()));
}
public void next() {
check();
if (query().page() instanceof PageRequest.Paged p) {
var s = coordinator.state();
if (s.phase() == GridCoordinator.Phase.READY && !s.result().hasNext()) return;
setPageRequest(new PageRequest.Paged(Math.incrementExact(p.pageIndex()), p.pageSize()));
}
}
public void last() {
check();
var s = coordinator.state();
if (s.phase() == GridCoordinator.Phase.READY
&& s.result().total().isPresent()
&& query().page() instanceof PageRequest.Paged p) {
long count = s.result().total().getAsLong();
if (count > 0)
setPageRequest(new PageRequest.Paged((count - 1) / p.pageSize(), p.pageSize()));
}
}
private GridQuery query() {
if (coordinator.isRestoring())
return coordinator.state().displayed() == null
? initial
: coordinator.state().displayed();
return coordinator.state().requested() == null ? initial : coordinator.state().requested();
}
private static PageRequest firstPage(PageRequest page) {
return page instanceof PageRequest.Paged p ? new PageRequest.Paged(0, p.pageSize()) : page;
}
private void changed(GridCoordinator.State<K, T> value) {
if (pendingAlert != null && value.generation() != alertGeneration) {
pendingAlert.close();
pendingAlert = null;
}
if (!closed) {
pseudoClassStateChanged(
javafx.css.PseudoClass.getPseudoClass("loading"),
value.phase() == GridCoordinator.Phase.LOADING);
pseudoClassStateChanged(
javafx.css.PseudoClass.getPseudoClass("error"),
value.phase() == GridCoordinator.Phase.ERROR);
if (value.displayed() != null)
renderer.setFilteredColumns(
value.displayed().filters().stream()
.map(FilterCondition::columnId)
.collect(java.util.stream.Collectors.toSet()));
if (visibleSourceVersion != value.sourceVersion()) {
visibleSourceVersion = value.sourceVersion();
renderer.select(null);
}
renderer.setRowsInteractive(value.phase() == GridCoordinator.Phase.READY);
updateControls(value);
}
state.set(value);
}
private void updateControls(GridCoordinator.State<K, T> s) {
GridQuery requested = s.requested() == null ? initial : s.requested();
boolean ready = s.phase() == GridCoordinator.Phase.READY;
boolean empty = ready && s.result().rows().isEmpty();
long index = requested.page() instanceof PageRequest.Paged p ? p.pageIndex() : 0;
boolean paged = requested.page() instanceof PageRequest.Paged;
first.setDisable(!paged || index == 0 || empty);
previous.setDisable(first.isDisabled());
next.setDisable(!paged || empty || (ready && !s.result().hasNext()));
last.setDisable(
!paged || empty || !ready || s.result().total().isEmpty() || !s.result().hasNext());
retry.setDisable(s.phase() != GridCoordinator.Phase.ERROR);
updating = true;
try {
int max = coordinator.capabilities().maximumPageSize();
List<String> sizes = new ArrayList<>();
for (int n : new int[] {25, 50, 100, 250}) if (n <= max) sizes.add(Integer.toString(n));
if (requested.page() instanceof PageRequest.Paged p
&& !sizes.contains(Integer.toString(p.pageSize())))
sizes.add(Integer.toString(p.pageSize()));
if (coordinator.capabilities().all()) sizes.add("All");
pageSize.getItems().setAll(sizes);
pageSize.setValue(
requested.page() instanceof PageRequest.All
? "All"
: Integer.toString(((PageRequest.Paged) requested.page()).pageSize()));
} finally {
updating = false;
}
String shown =
s.result() == null
? ""
: " Displayed "
+ pageLabel(s.displayed().page())
+ " ("
+ s.result().rows().size()
+ " rows).";
String message =
switch (s.phase()) {
case IDLE -> "Not loaded";
case GUARD ->
"Waiting for edit approval. Requested "
+ pageLabel(requested.page())
+ "."
+ shown;
case LOADING ->
"Loading "
+ pageLabel(requested.page())
+ ". Previous rows are outdated."
+ shown;
case CONFIRMATION ->
"Waiting for permission to load all matching rows." + shown;
case ERROR ->
"Query failed: "
+ String.valueOf(s.error().getMessage())
+ ". Retry is available; previous rows are outdated."
+ shown;
case CLOSED -> "Closed";
case READY -> {
if (empty) yield "No results";
if (s.result().total().isPresent()) {
long total = s.result().total().getAsLong();
yield requested.page() instanceof PageRequest.Paged p
? "Page "
+ (p.pageIndex() + 1)
+ " of "
+ (total == 0 ? 0 : 1 + (total - 1) / p.pageSize())
+ " — "
+ total
+ " matching rows"
: "All " + total + " matching rows";
}
yield pageLabel(requested.page()) + " — total unknown";
}
};
status.setText(message);
}
private static String pageLabel(PageRequest page) {
return page instanceof PageRequest.Paged p ? "page " + (p.pageIndex() + 1) : "all rows";
}
private CompletionStage<Boolean> confirmAll(GridQuery query, long count) {
CompletableFuture<Boolean> answer = new CompletableFuture<>();
ButtonType proceed = new ButtonType("Continue", ButtonBar.ButtonData.OK_DONE);
Alert alert =
new Alert(
Alert.AlertType.CONFIRMATION,
"Load all "
+ count
+ " matching rows? This may use substantial memory and reduce"
+ " responsiveness.",
proceed,
ButtonType.CANCEL);
alert.setTitle("Load all rows");
alert.setHeaderText("Paging will be disabled");
if (getScene() != null && getScene().getWindow() != null)
alert.initOwner(getScene().getWindow());
pendingAlert = alert;
alertGeneration = coordinator.state().generation();
alert.setOnHidden(
e -> {
if (pendingAlert == alert) pendingAlert = null;
answer.complete(alert.getResult() == proceed);
});
alert.show();
return answer;
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the JavaFX application thread");
}
private void check() {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
}
public void close() {
requireFx();
if (closed) return;
closed = true;
closeFilter();
coordinator.close();
if (pendingAlert != null) {
pendingAlert.close();
pendingAlert = null;
}
renderer.close();
getChildren().clear();
}
}
@@ -6,38 +6,42 @@ import javafx.scene.control.Label;
/**
* Shows each newly added {@link Message} in a dialog when the developer asks.
* <p>
* The library shows nothing until {@link #showNewMessages(ViewModel)} is called. An in-place
*
* <p>The library shows nothing until {@link #showNewMessages(ViewModel)} is called. An in-place
* update of an existing binding failure is not a new Message, so it does not open another dialog.
*/
public final class MessagePopup {
/**
* Prevents instantiation.
*/
private MessagePopup() {
}
/** Prevents instantiation. */
private MessagePopup() {}
/**
* Shows each Message added to {@code viewModel} after this call in a dialog.
* <p>
* The dialog is shown with {@link Dialog#show()}, so the caller is not blocked. Messages
*
* <p>The dialog is shown with {@link Dialog#show()}, so the caller is not blocked. Messages
* already on the ViewModel stay where they are. A later in-place update of a binding failure
* does not open another dialog.
*
* @param viewModel the ViewModel whose new Messages should be shown
*/
public static void showNewMessages(ViewModel viewModel) {
viewModel.whenMessageAdded(MessagePopup::show);
viewModel.whenMessageAdded(message -> show(message, null));
}
/**
* Opens a dialog whose content is the Message text.
* Shows new messages in owned dialogs, allowing theme inheritance from the owner scene.
*
* @param message the notice to show
* @param viewModel the ViewModel whose new Messages should be shown
* @param owner the application window that owns the dialogs
*/
private static void show(Message message) {
public static void showNewMessages(ViewModel viewModel, javafx.stage.Window owner) {
java.util.Objects.requireNonNull(owner);
viewModel.whenMessageAdded(message -> show(message, owner));
}
private static void show(Message message, javafx.stage.Window owner) {
Dialog<Void> dialog = new Dialog<>();
if (owner != null) dialog.initOwner(owner);
dialog.setHeaderText(null);
dialog.getDialogPane().setContent(new Label(message.getText()));
dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
@@ -0,0 +1,24 @@
package de.neitzel.fx.view;
/** Immutable result-column definition. fixedPosition is zero-based, or -1 for movable. */
public record ResultColumn(
String id,
String header,
double defaultWidth,
double minimumWidth,
double maximumWidth,
int fixedPosition) {
public ResultColumn {
if (id == null || id.isBlank() || header == null)
throw new IllegalArgumentException("Invalid column identity/header");
if (!Double.isFinite(minimumWidth)
|| !Double.isFinite(maximumWidth)
|| minimumWidth <= 0
|| maximumWidth < minimumWidth
|| !Double.isFinite(defaultWidth)
|| defaultWidth < minimumWidth
|| defaultWidth > maximumWidth
|| fixedPosition < -1)
throw new IllegalArgumentException("Invalid column width/position");
}
}
@@ -0,0 +1,19 @@
package de.neitzel.fx.view;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import java.util.Map;
import java.util.Objects;
/**
* A freshly bound row with explicit direct-child field mapping and application-owned cleanup.
* Unmapped children are trailing action controls. A factory must return fresh nodes for every call.
*/
public record ResultRow(HBox root, Map<String, Region> fields, Runnable dispose) {
public ResultRow {
Objects.requireNonNull(root);
fields = Map.copyOf(fields);
Objects.requireNonNull(dispose);
}
}
@@ -228,6 +228,27 @@ public class Table extends VBox {
*/
private Class<?> rowType;
/** True once the explicit queried-result rendering path has been selected. */
private boolean resultMode;
/**
* Opens the opt-in queried-result renderer on a fresh Table. Existing FXML/collection behavior
* is unchanged. This must be called on the FX thread before legacy ViewLoader initialization.
* The returned renderer owns rows until closed; its factory supplies mapped, already-bound nodes.
*/
public <K, T> TableResults<K, T> openResults(List<ResultColumn> definitions,
java.util.function.Function<T, ResultRow> factory) {
if (!javafx.application.Platform.isFxApplicationThread()) {
throw new IllegalStateException("Use the JavaFX application thread");
}
if (opened || resultMode) {
throw new IllegalStateException("Table is already open");
}
TableResults<K, T> renderer = new TableResults<>(header, body, List.copyOf(definitions), factory);
resultMode = true;
return renderer;
}
/**
* Creates a Table and prepares its header, scrolling body, and popup.
*/
@@ -327,6 +348,9 @@ public class Table extends VBox {
* @param context the container that creates each Row
*/
void open(Object viewModel, ApplicationContext context) {
if (resultMode) {
return;
}
if (opened) {
return;
}
@@ -0,0 +1,399 @@
package de.neitzel.fx.view;
import de.neitzel.grid.ColumnWidth;
import de.neitzel.grid.GridRow;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.shape.SVGPath;
import java.util.*;
import java.util.function.Function;
/**
* Opt-in presentation of already queried rows. All operations run on the FX thread. This object
* never queries, sorts, filters, or rebinds models. The future grid coordinator owns those
* decisions. Closing releases rows; the Table remains in result mode and cannot be reopened as a
* legacy Table.
*/
public final class TableResults<K, T> implements AutoCloseable {
private final HBox header;
private final VBox body;
private final Function<T, ResultRow> factory;
private final Map<String, ResultColumn> definitions = new LinkedHashMap<>();
private final Map<String, ColumnWidth> widths = new LinkedHashMap<>();
private List<String> order;
private List<Entry<K, T>> entries = List.of();
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
new ReadOnlyObjectWrapper<>();
private boolean closed;
private boolean rowsInteractive = true;
private Set<String> filterColumns = Set.of();
private Set<String> filteredColumns = Set.of();
private java.util.function.BiConsumer<String, Node> filterRequest = (id, node) -> {};
private java.util.function.Consumer<String> sortRequest = id -> {};
private record Entry<K, T>(GridRow<K, T> row, ResultRow view, EventHandler<MouseEvent> click) {}
TableResults(
HBox header, VBox body, List<ResultColumn> columns, Function<T, ResultRow> factory) {
requireFx();
this.header = header;
this.body = body;
this.factory = Objects.requireNonNull(factory);
if (columns.isEmpty())
throw new IllegalArgumentException("At least one column is required");
for (var c : columns) {
if (definitions.putIfAbsent(c.id(), c) != null)
throw new IllegalArgumentException("Duplicate column ID");
widths.put(c.id(), new ColumnWidth.Default());
}
order = List.copyOf(definitions.keySet());
validateOrder(order);
drawHeader();
body.setOnMouseClicked(
e -> {
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
});
}
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
return selectedKey.getReadOnlyProperty();
}
public ReadOnlyObjectProperty<T> selectedElementProperty() {
return selectedElement.getReadOnlyProperty();
}
/** Cleanup failures are exposed separately: they do not roll back an already published page. */
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
return disposalFailure.getReadOnlyProperty();
}
public List<String> columnOrder() {
return order;
}
public Map<String, ColumnWidth> columnWidths() {
return Map.copyOf(widths);
}
/** Marks retained rows unavailable without disabling header/query controls. */
public void setRowsInteractive(boolean interactive) {
checkOpen();
rowsInteractive = interactive;
body.setDisable(!interactive);
markSelection();
}
/** Header requests are delegated to the coordinator, never applied locally. */
public void setOnSortRequest(java.util.function.Consumer<String> handler) {
checkOpen();
sortRequest = Objects.requireNonNull(handler);
}
/** Opt-in filter actions; clicking the icon never issues a sort request. */
public void setFilterActions(
Set<String> columns, java.util.function.BiConsumer<String, Node> handler) {
checkOpen();
if (!definitions.keySet().containsAll(columns))
throw new IllegalArgumentException("Unknown filter column");
filterColumns = Set.copyOf(columns);
filterRequest = Objects.requireNonNull(handler);
drawHeader();
}
/**
* Published filter state; updates existing header controls without recreating an open editor.
*/
public void setFilteredColumns(Set<String> ids) {
checkOpen();
if (filteredColumns.equals(ids)) return;
filteredColumns = Set.copyOf(ids);
for (Node cell : header.getChildren())
if (cell instanceof HBox box)
for (Node child : box.getChildren())
if (child instanceof Button button
&& button.getStyleClass().contains("filter-button"))
markFilter(button, (String) cell.getUserData());
}
private void markFilter(Button button, String id) {
boolean active = filteredColumns.contains(id);
button.pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("filtered"), active);
button.setText(active ? "•" : "");
button.setAccessibleText(
"Filter " + definitions.get(id).header() + (active ? " (active)" : ""));
button.setTooltip(
new Tooltip(
"Filter " + definitions.get(id).header() + (active ? " — active" : "")));
}
/** Retains an off-page key while exposing no loaded selected element. */
public void select(K key) {
checkOpen();
selectedKey.set(key);
markSelection();
}
/**
* Stages fresh rows before replacing the visible page; failed construction preserves the old
* page.
*/
public void show(List<GridRow<K, T>> result) {
show(result, order, widths);
}
/** Stages both fresh rows and complete layout, publishing neither on preparation failure. */
public void show(
List<GridRow<K, T>> result,
List<String> nextOrder,
Map<String, ColumnWidth> nextWidths) {
checkOpen();
nextOrder = List.copyOf(nextOrder);
validateOrder(nextOrder);
nextWidths = Map.copyOf(nextWidths);
if (!nextWidths.keySet().equals(definitions.keySet()))
throw new IllegalArgumentException("Width mapping must match columns");
Map<String, ColumnWidth> preparedWidths = new LinkedHashMap<>();
for (var c : definitions.values()) {
var width = nextWidths.get(c.id());
preparedWidths.put(
c.id(),
width instanceof ColumnWidth.Explicit e
? new ColumnWidth.Explicit(
Math.clamp(e.value(), c.minimumWidth(), c.maximumWidth()))
: width);
}
var nextHeader = headerNodes(nextOrder, preparedWidths);
result = List.copyOf(result);
Set<K> keys = new HashSet<>();
for (var row : result)
if (!keys.add(row.key())) throw new IllegalArgumentException("Duplicate row key");
List<Entry<K, T>> next = new ArrayList<>();
Set<Node> roots = Collections.newSetFromMap(new IdentityHashMap<>());
try {
for (var row : result) {
ResultRow view =
Objects.requireNonNull(
factory.apply(row.model()), "Row factory returned null");
// Never dispose a live row accidentally returned by a faulty factory.
if (view.root().getParent() != null || !roots.add(view.root()))
throw new IllegalArgumentException(
"Row factory must create detached fresh rows");
EventHandler<MouseEvent> click =
e -> {
if (e.getButton() == MouseButton.PRIMARY) select(row.key());
};
next.add(new Entry<>(row, view, click));
validateRow(view);
view.root().getStyleClass().add("result-row");
layoutRow(view, nextOrder, preparedWidths);
view.root().addEventHandler(MouseEvent.MOUSE_CLICKED, click);
}
} catch (RuntimeException failure) {
release(next);
throw failure;
}
var old = entries;
entries = List.copyOf(next);
order = nextOrder;
widths.clear();
widths.putAll(preparedWidths);
header.getChildren().setAll(nextHeader);
body.getChildren().setAll(entries.stream().map(e -> e.view().root()).toList());
markSelection();
release(old);
}
/** Changes header and mapped row order atomically after validating fixed positions. */
public void setColumnOrder(List<String> ids) {
checkOpen();
ids = List.copyOf(ids);
validateOrder(ids);
order = ids;
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
}
/**
* Returns the applied width; explicit widths are clamped to current limits, preserving
* default-vs-explicit intent.
*/
public double setColumnWidth(String id, ColumnWidth width) {
checkOpen();
ResultColumn c = Objects.requireNonNull(definitions.get(id), "Unknown column");
Objects.requireNonNull(width);
double applied =
width instanceof ColumnWidth.Explicit e
? Math.clamp(e.value(), c.minimumWidth(), c.maximumWidth())
: c.defaultWidth();
widths.put(
id,
width instanceof ColumnWidth.Explicit ? new ColumnWidth.Explicit(applied) : width);
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
return applied;
}
private void validateOrder(List<String> ids) {
if (ids.size() != definitions.size() || !new HashSet<>(ids).equals(definitions.keySet()))
throw new IllegalArgumentException("Order must contain each column exactly once");
for (int i = 0; i < ids.size(); i++) {
int fixed = definitions.get(ids.get(i)).fixedPosition();
if (fixed >= 0 && fixed != i)
throw new IllegalArgumentException("Fixed column displaced");
}
}
private void validateRow(ResultRow view) {
if (!view.root().getPadding().equals(javafx.geometry.Insets.EMPTY))
throw new IllegalArgumentException(
"Result row padding must be zero; put padding inside mapped fields");
if (!view.fields().keySet().equals(definitions.keySet()))
throw new IllegalArgumentException("Row mapping must match columns");
Set<Node> nodes = Collections.newSetFromMap(new IdentityHashMap<>());
for (var field : view.fields().values())
if (!nodes.add(field) || field.getParent() != view.root())
throw new IllegalArgumentException(
"Mapped fields must be distinct direct children");
}
private double width(String id) {
return width(id, widths);
}
private double width(String id, Map<String, ColumnWidth> sizes) {
return sizes.get(id) instanceof ColumnWidth.Explicit e
? e.value()
: definitions.get(id).defaultWidth();
}
private void drawHeader() {
header.getChildren().setAll(headerNodes(order, widths));
}
private List<Node> headerNodes(List<String> ordering, Map<String, ColumnWidth> sizes) {
List<Node> nodes = new ArrayList<>();
for (String id : ordering) {
Label label = new Label(definitions.get(id).header());
label.getStyleClass().add("column-header");
HBox cell = new HBox(label);
cell.getStyleClass().add("column-cell");
cell.setUserData(id);
cell.setOnMouseClicked(
event -> {
if (event.getButton() == MouseButton.PRIMARY) sortRequest.accept(id);
});
if (filterColumns.contains(id)) {
SVGPath icon = new SVGPath();
icon.setContent("M0 0 H14 L9 6 V12 L5 14 V6 Z");
icon.getStyleClass().add("filter-icon");
Button button = new Button("", icon);
button.getStyleClass().add("filter-button");
button.setAccessibleText("Filter " + definitions.get(id).header());
button.setTooltip(new Tooltip("Filter " + definitions.get(id).header()));
markFilter(button, id);
button.setOnAction(e -> filterRequest.accept(id, button));
button.addEventHandler(MouseEvent.MOUSE_CLICKED, MouseEvent::consume);
cell.getChildren().add(button);
}
size(cell, width(id, sizes));
nodes.add(cell);
}
return nodes;
}
private static void size(Region region, double width) {
region.setMinWidth(width);
region.setPrefWidth(width);
region.setMaxWidth(width);
}
private void layoutRow(ResultRow view) {
layoutRow(view, order, widths);
}
private void layoutRow(ResultRow view, List<String> ordering, Map<String, ColumnWidth> sizes) {
Set<Region> fields = Collections.newSetFromMap(new IdentityHashMap<>());
fields.addAll(view.fields().values());
List<Node> children = new ArrayList<>();
for (String id : ordering) {
Region field = view.fields().get(id);
size(field, width(id, sizes));
children.add(field);
}
for (Node child : view.root().getChildren())
if (!fields.contains(child)) children.add(child);
view.root().setSpacing(0);
view.root().getChildren().setAll(children);
}
private void markSelection() {
T loaded = null;
for (var e : entries) {
boolean selected = Objects.equals(selectedKey.get(), e.row().key());
e.view()
.root()
.pseudoClassStateChanged(
javafx.css.PseudoClass.getPseudoClass("selected"), selected);
e.view().root().getStyleClass().remove("selected");
if (selected) {
e.view().root().getStyleClass().add("selected");
loaded = e.row().model();
}
}
selectedElement.set(rowsInteractive ? loaded : null);
}
private void release(List<Entry<K, T>> retired) {
RuntimeException aggregate = null;
for (var e : retired) {
e.view().root().removeEventHandler(MouseEvent.MOUSE_CLICKED, e.click());
try {
e.view().dispose().run();
} catch (RuntimeException failure) {
if (aggregate == null) aggregate = new IllegalStateException("Row disposal failed");
aggregate.addSuppressed(failure);
}
}
if (aggregate != null) disposalFailure.set(aggregate);
}
private static void requireFx() {
if (!Platform.isFxApplicationThread())
throw new IllegalStateException("Use the JavaFX application thread");
}
private void checkOpen() {
requireFx();
if (closed) throw new IllegalStateException("Result renderer is closed");
}
@Override
public void close() {
requireFx();
if (closed) return;
closed = true;
var old = entries;
entries = List.of();
body.getChildren().clear();
header.getChildren().clear();
body.setOnMouseClicked(null);
selectedKey.set(null);
selectedElement.set(null);
release(old);
}
}