Add compatible DataGrid, filter editors, themes and JDBC example
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?import javafx.scene.control.*?>
|
||||
<?import javafx.scene.layout.*?>
|
||||
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.grid.filter.BuiltInFilterEditor" spacing="8" prefWidth="330" styleClass="filter-editor">
|
||||
<Label text="Filter mode" labelFor="$mode"/>
|
||||
<ComboBox fx:id="mode" maxWidth="Infinity"/>
|
||||
<VBox fx:id="comparison" spacing="8">
|
||||
<Label text="Comparison" labelFor="$operator"/>
|
||||
<ComboBox fx:id="operator" maxWidth="Infinity"/>
|
||||
<TextField fx:id="operand" promptText="Value" accessibleText="Filter value"/>
|
||||
<TextField fx:id="upper" promptText="Inclusive upper value" accessibleText="Inclusive upper value"/>
|
||||
<CheckBox fx:id="caseSensitive" text="Case sensitive"/>
|
||||
</VBox>
|
||||
<VBox fx:id="checklistPane" spacing="8">
|
||||
<Label fx:id="scope" wrapText="true"/>
|
||||
<TextField fx:id="search" promptText="Search candidates" accessibleText="Search candidates"/>
|
||||
<HBox spacing="8"><Button fx:id="selectShown" text="Select all shown"/><Button fx:id="clearShown" text="Uncheck shown"/></HBox>
|
||||
<ScrollPane fitToWidth="true" prefViewportHeight="140"><content><VBox fx:id="candidates" spacing="4"/></content></ScrollPane>
|
||||
<Label fx:id="selectionSummary" wrapText="true"/>
|
||||
<Label fx:id="lookupMessage" wrapText="true"/>
|
||||
<HBox spacing="8"><Button fx:id="more" text="More"/><Button fx:id="retry" text="Retry lookup"/></HBox>
|
||||
</VBox>
|
||||
<Label fx:id="validation" wrapText="true" styleClass="filter-validation"/>
|
||||
</VBox>
|
||||
@@ -0,0 +1,9 @@
|
||||
.filter-popup {
|
||||
-fx-padding: 14;
|
||||
-fx-background-color: -fx-control-inner-background;
|
||||
-fx-border-color: -fx-box-border;
|
||||
-fx-border-width: 1;
|
||||
}
|
||||
.filter-validation { -fx-font-weight: bold; }
|
||||
.filter-button { -fx-padding: 4; }
|
||||
.filter-icon { -fx-fill: -fx-text-base-color; }
|
||||
@@ -0,0 +1,13 @@
|
||||
.neitzel-theme {
|
||||
-nl-surface: #151b24;
|
||||
-nl-raised: #242e3d;
|
||||
-nl-text: #f2f5fa;
|
||||
-nl-muted: #c0cad8;
|
||||
-nl-selection: #385e87;
|
||||
-nl-selection-text: #ffffff;
|
||||
-nl-focus: #8dccff;
|
||||
-nl-error: #ffb4b4;
|
||||
-nl-warning: #ffe09a;
|
||||
-nl-border: #91a4bc;
|
||||
-nl-hover: #34445b;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
.neitzel-theme {
|
||||
-nl-surface: #080a0d;
|
||||
-nl-raised: #111820;
|
||||
-nl-text: #ffffff;
|
||||
-nl-muted: #e4eaf2;
|
||||
-nl-selection: #143e68;
|
||||
-nl-selection-text: #ffffff;
|
||||
-nl-focus: #ffdf00;
|
||||
-nl-error: #ffc2bd;
|
||||
-nl-warning: #ffe09a;
|
||||
-nl-border: #e4eaf2;
|
||||
-nl-hover: #24374b;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
.neitzel-theme {
|
||||
-nl-surface: #ffffff;
|
||||
-nl-raised: #eef2f7;
|
||||
-nl-text: #172033;
|
||||
-nl-muted: #4b5563;
|
||||
-nl-selection: #164e8a;
|
||||
-nl-selection-text: #ffffff;
|
||||
-nl-focus: #005fcc;
|
||||
-nl-error: #a61b1b;
|
||||
-nl-warning: #704300;
|
||||
-nl-border: #65758b;
|
||||
-nl-hover: #dce7f5;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/* Opt-in scope. Geometry is identical in all bundled palettes. */
|
||||
.neitzel-theme, .neitzel-theme .root {
|
||||
-fx-font-family: "System";
|
||||
-fx-font-size: 13px;
|
||||
-fx-base: -nl-raised;
|
||||
-fx-background: -nl-surface;
|
||||
-fx-control-inner-background: -nl-surface;
|
||||
-fx-control-inner-background-alt: -nl-raised;
|
||||
-fx-text-base-color: -nl-text;
|
||||
-fx-text-background-color: -nl-text;
|
||||
-fx-text-inner-color: -nl-text;
|
||||
-fx-accent: -nl-selection;
|
||||
-fx-selection-bar: -nl-selection;
|
||||
-fx-selection-bar-non-focused: -nl-selection;
|
||||
-fx-selection-bar-text: -nl-selection-text;
|
||||
-fx-focus-color: -nl-focus;
|
||||
-fx-faint-focus-color: transparent;
|
||||
-fx-box-border: -nl-border;
|
||||
-fx-inner-border: -nl-raised;
|
||||
-fx-mark-color: -nl-text;
|
||||
-fx-background-color: -nl-surface;
|
||||
}
|
||||
.neitzel-theme .label, .neitzel-theme .check-box, .neitzel-theme .radio-button { -fx-text-fill: -nl-text; }
|
||||
.neitzel-theme .button, .neitzel-theme .toggle-button, .neitzel-theme .combo-box-base, .neitzel-theme .menu-button {
|
||||
-fx-background-color: -nl-raised; -fx-text-fill: -nl-text;
|
||||
-fx-border-color: -nl-border; -fx-border-width: 2; -fx-background-radius: 3; -fx-border-radius: 3;
|
||||
-fx-padding: 4 8;
|
||||
}
|
||||
.neitzel-theme .button:hover, .neitzel-theme .toggle-button:hover, .neitzel-theme .combo-box-base:hover { -fx-background-color: -nl-hover; }
|
||||
.neitzel-theme .button:focused, .neitzel-theme .toggle-button:focused, .neitzel-theme .combo-box-base:focused,
|
||||
.neitzel-theme .text-input:focused, .neitzel-theme .table-view:focused, .neitzel-theme .list-view:focused { -fx-border-color: -nl-focus; }
|
||||
.neitzel-theme .text-input {
|
||||
-fx-text-fill: -nl-text; -fx-prompt-text-fill: -nl-muted; -fx-background-color: -nl-surface;
|
||||
-fx-border-color: -nl-border; -fx-border-width: 2; -fx-padding: 4 6;
|
||||
-fx-highlight-fill: -nl-selection; -fx-highlight-text-fill: -nl-selection-text;
|
||||
}
|
||||
.neitzel-theme .text-area .content { -fx-background-color: -nl-surface; }
|
||||
.neitzel-theme .text-input:invalid { -fx-border-color: -nl-error; -fx-border-style: dashed; }
|
||||
.neitzel-theme .button:disabled, .neitzel-theme .text-input:disabled, .neitzel-theme .combo-box-base:disabled,
|
||||
.neitzel-theme .check-box:disabled, .neitzel-theme .radio-button:disabled { -fx-opacity: 1; -fx-text-fill: -nl-muted; -fx-border-style: dashed; }
|
||||
.neitzel-theme .label:disabled { -fx-opacity: 1; -fx-text-fill: -nl-muted; }
|
||||
.neitzel-theme .table:disabled, .neitzel-theme .data-grid:disabled { -fx-opacity: 1; }
|
||||
.neitzel-theme .table-row-cell, .neitzel-theme .list-cell, .neitzel-theme .tree-cell, .neitzel-theme .table-cell {
|
||||
-fx-background-color: -nl-surface; -fx-text-fill: -nl-text;
|
||||
}
|
||||
.neitzel-theme .table-row-cell:odd { -fx-background-color: -nl-raised; }
|
||||
.neitzel-theme .table-row-cell:odd .table-cell { -fx-background-color: transparent; }
|
||||
.neitzel-theme .table-row-cell:selected, .neitzel-theme .table-row-cell:selected .table-cell,
|
||||
.neitzel-theme .list-cell:selected, .neitzel-theme .tree-cell:selected {
|
||||
-fx-background-color: -nl-selection; -fx-text-fill: -nl-selection-text;
|
||||
}
|
||||
.neitzel-theme .list-cell:filled:hover, .neitzel-theme .tree-cell:filled:hover { -fx-background-color: -nl-hover; -fx-text-fill: -nl-text; }
|
||||
.neitzel-theme .list-cell:filled:selected, .neitzel-theme .tree-cell:filled:selected { -fx-background-color: -nl-selection; -fx-text-fill: -nl-selection-text; }
|
||||
.neitzel-theme .table-row-cell:selected:focused, .neitzel-theme .list-cell:selected:focused { -fx-border-color: -nl-focus; -fx-border-width: 2; }
|
||||
.neitzel-theme .table-view, .neitzel-theme .list-view, .neitzel-theme .tree-view { -fx-background-color: -nl-surface; -fx-border-color: -nl-border; -fx-border-width: 2; }
|
||||
.neitzel-theme .table-header, .neitzel-theme .column-cell, .neitzel-theme .column-header, .neitzel-theme .column-header-background { -fx-background-color: -nl-raised; }
|
||||
.neitzel-theme .table .selected, .neitzel-theme .result-row:selected { -fx-background-color: -nl-selection; }
|
||||
.neitzel-theme .table .selected .label, .neitzel-theme .result-row:selected .label { -fx-text-fill: -nl-selection-text; }
|
||||
.neitzel-theme .result-row { -fx-padding: 0; -fx-border-color: transparent; -fx-border-width: 0; }
|
||||
.neitzel-theme .result-row:disabled { -fx-opacity: 1; }
|
||||
.neitzel-theme .result-row:disabled .label { -fx-text-fill: -nl-muted; }
|
||||
.neitzel-theme .filter-button { -fx-padding: 4; }
|
||||
.neitzel-theme .filter-icon { -fx-fill: -nl-text; }
|
||||
.neitzel-theme .filter-button:filtered, .neitzel-theme .column-opener.filtered { -fx-border-style: segments(3, 2); -fx-border-color: -nl-focus; }
|
||||
.neitzel-theme .filter-validation, .neitzel-theme .theme-error { -fx-text-fill: -nl-error; -fx-font-weight: bold; }
|
||||
.neitzel-theme .theme-warning { -fx-text-fill: -nl-warning; }
|
||||
.neitzel-theme .data-grid-status { -fx-text-fill: -nl-text; }
|
||||
.neitzel-theme .data-grid:error .data-grid-status { -fx-text-fill: -nl-error; -fx-font-weight: bold; }
|
||||
.neitzel-theme .data-grid:loading .data-grid-status { -fx-font-style: italic; }
|
||||
.neitzel-theme .filter-popup, .neitzel-theme .context-menu, .neitzel-theme .dialog-pane, .neitzel-theme .tooltip { -fx-background-color: -nl-surface; -fx-border-color: -nl-border; -fx-border-width: 2; }
|
||||
.neitzel-theme .menu-item .label { -fx-text-fill: -nl-text; }
|
||||
.neitzel-theme .menu-item:focused { -fx-background-color: -nl-selection; }
|
||||
.neitzel-theme .menu-item:focused .label { -fx-text-fill: -nl-selection-text; }
|
||||
.neitzel-theme .dock-drop-indicator, .neitzel-theme .dock-floating-preview-frame { -fx-fill: transparent; -fx-stroke: -nl-focus; -fx-stroke-width: 2; }
|
||||
.neitzel-theme .dock-drop-indicator:no-change { -fx-stroke: -nl-muted; -fx-stroke-dash-array: 4 3; }
|
||||
.neitzel-theme .dock-divider, .neitzel-theme .dock-area-divider { -fx-background-color: -nl-border; }
|
||||
|
||||
.neitzel-theme .result-row:selected:disabled .label { -fx-text-fill: -nl-selection-text; }
|
||||
.neitzel-theme.tooltip, .neitzel-theme .tooltip { -fx-text-fill: -nl-text; -fx-background-color: -nl-surface; }
|
||||
.neitzel-theme .progress-indicator { -fx-progress-color: -nl-focus; }
|
||||
.neitzel-theme .progress-bar .bar { -fx-background-color: -nl-focus; }
|
||||
.neitzel-theme .combo-box-base > .list-cell, .neitzel-theme .combo-box-base > .list-cell:filled:selected {
|
||||
-fx-background-color: transparent; -fx-text-fill: -nl-text;
|
||||
}
|
||||
.neitzel-theme .column-cell { -fx-alignment: center-left; -fx-spacing: 6; -fx-padding: 4 6; }
|
||||
.neitzel-theme .check-box .box, .neitzel-theme .radio-button .radio {
|
||||
-fx-background-color: -nl-raised; -fx-border-color: -nl-border; -fx-border-width: 2; -fx-padding: 3;
|
||||
}
|
||||
.neitzel-theme .radio-button .radio { -fx-border-radius: 100; -fx-background-radius: 100; }
|
||||
.neitzel-theme .check-box:focused .box, .neitzel-theme .radio-button:focused .radio { -fx-border-color: -nl-focus; }
|
||||
.neitzel-theme .check-box:selected .mark, .neitzel-theme .radio-button:selected .dot { -fx-background-color: -nl-text; }
|
||||
.neitzel-theme .combo-box-base > .list-cell, .neitzel-theme .combo-box-base > .list-cell:filled:selected { -fx-border-width: 0; }
|
||||
.neitzel-theme .column-header-row { -fx-background-color: -nl-raised; }
|
||||
.neitzel-theme .column-popup { -fx-background-color: -nl-surface; -fx-border-color: -nl-border; -fx-border-width: 2; -fx-padding: 8; }
|
||||
@@ -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; }
|
||||
Reference in New Issue
Block a user