Release NeitzelLib 1.0.2 with saved HTML viewing and row selection

Supply default selection colors through the row container’s user-agent stylesheet so JavaFX can style large result sets within the existing materialization test timeout.
This commit is contained in:
2026-11-22 20:11:22 +01:00
parent 32f8d28159
commit b2e0724611
36 changed files with 1287 additions and 49 deletions
@@ -0,0 +1,45 @@
package de.neitzel.fx.control;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream;
/** WebView does not decode WebP. Convert embedded images once per preparation, without changing the file. */
final class EmbeddedImages {
private static final Pattern WEBP = Pattern.compile("data:image/webp;base64,[A-Za-z0-9+/=]+", Pattern.CASE_INSENSITIVE);
private static final long MAX_PIXELS = 16 * 1024 * 1024;
private final Map<String, String> converted = new HashMap<>();
private int remainingBytes = 64 * 1024 * 1024;
String adapt(String value) {
if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException();
return WEBP.matcher(value).replaceAll(match -> java.util.regex.Matcher.quoteReplacement(
converted.computeIfAbsent(match.group(), this::png)));
}
private String png(String value) {
if (remainingBytes <= 0) return value;
try (var input = new MemoryCacheImageInputStream(new ByteArrayInputStream(
Base64.getDecoder().decode(value.substring(value.indexOf(',') + 1))))) {
var readers = ImageIO.getImageReaders(input);
if (!readers.hasNext()) return value;
var reader = readers.next();
try {
reader.setInput(input, true, true);
if ((long) reader.getWidth(0) * reader.getHeight(0) > MAX_PIXELS) return value;
var image = reader.read(0);
var output = new ByteArrayOutputStream();
if (!ImageIO.write(image, "png", output)) return value;
if ((long) output.size() * 4 / 3 > remainingBytes) return value;
remainingBytes -= (output.size() + 2) / 3 * 4;
return "data:image/png;base64," + Base64.getEncoder().encodeToString(output.toByteArray());
} finally { reader.dispose(); }
} catch (IOException | IllegalArgumentException invalid) { return value; }
}
}
@@ -0,0 +1,67 @@
package de.neitzel.fx.control;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import org.jsoup.Jsoup;
/** Immutable prepared HTML, shareable between viewers without sharing external-image permission.
* Preparation performs no network requests and may be expensive; call it off the FX thread.
*/
@lombok.RequiredArgsConstructor(access = lombok.AccessLevel.PACKAGE)
public final class HtmlDocument {
private static final int MAX_BYTES = 32 * 1024 * 1024;
private final String offlineHtml;
private final String externalImagesHtml;
private final boolean hasExternalImages;
/** Reads at most 32 MiB, detects the saved character encoding, and never modifies the file. */
public static HtmlDocument read(Path file) throws IOException {
Objects.requireNonNull(file, "file");
try (var input = Files.newInputStream(file)) {
byte[] bytes = input.readNBytes(MAX_BYTES + 1);
if (bytes.length > MAX_BYTES) throw new IOException("HTML exceeds the 32 MiB preview limit.");
return HtmlPresentation.prepare(Jsoup.parse(new ByteArrayInputStream(bytes), null, ""));
}
}
public static HtmlDocument parse(String html) { return parse(html, null); }
/** An optional HTTP(S) source address resolves relative images; it is never fetched. */
public static HtmlDocument parse(String html, URI source) {
Objects.requireNonNull(html, "html");
if (source != null && httpUri(source.toString()) == null) {
throw new IllegalArgumentException("HTML source must be an HTTP(S) address.");
}
if (html.length() > MAX_BYTES || html.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) {
throw new IllegalArgumentException("HTML exceeds the 32 MiB preview limit.");
}
return HtmlPresentation.prepare(Jsoup.parse(html, source == null ? "" : source.toASCIIString()));
}
public boolean hasExternalImages() { return hasExternalImages; }
String offlineHtml() { return offlineHtml; }
String externalImagesHtml() { return externalImagesHtml; }
static URI imageUri(String value, URI base) {
if (value.isBlank()) return null;
try {
URI uri = new URI(value.startsWith("//") ? "https:" + value : value);
if (!uri.isAbsolute() && base != null) uri = base.resolve(uri);
return httpUri(uri.toString());
} catch (URISyntaxException invalid) { return null; }
}
static URI httpUri(String value) {
try {
URI uri = new URI(value.strip());
return uri.getHost() != null && ("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme()))
? uri : null;
} catch (URISyntaxException invalid) { return null; }
}
}
@@ -0,0 +1,170 @@
package de.neitzel.fx.control;
import com.helger.css.decl.CSSDeclaration;
import com.helger.css.decl.CSSExpressionMemberTermURI;
import com.helger.css.decl.CSSFontFaceRule;
import com.helger.css.decl.ICSSTopLevelRule;
import com.helger.css.decl.visit.CSSVisitor;
import com.helger.css.decl.visit.DefaultCSSUrlVisitor;
import com.helger.css.reader.CSSReader;
import com.helger.css.reader.CSSReaderSettings;
import com.helger.css.reader.errorhandler.CollectingCSSParseErrorHandler;
import com.helger.css.handler.DoNothingCSSParseExceptionCallback;
import com.helger.css.writer.CSSWriter;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Pattern;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Safelist;
/** Presentation preserves saved CSS; text indexing deliberately uses the simpler reader markup. */
final class HtmlPresentation {
private static final Safelist SAFE = Safelist.relaxed()
.addTags("div", "main", "header", "footer", "nav", "aside", "section", "article", "figure",
"figcaption", "small", "mark", "s", "style", "picture", "details", "summary", "time",
"form", "fieldset", "legend", "label", "input", "button", "select", "option")
.addAttributes(":all", "class", "id", "style", "hidden", "dir", "lang")
.addAttributes("input", "type", "value", "placeholder", "checked", "disabled")
.addAttributes("button", "type", "disabled")
.addAttributes("option", "value", "selected")
.addAttributes("style", "media", "type")
.removeAttributes("a", "href")
.addProtocols("img", "src", "data");
private static final Pattern IMAGE = Pattern.compile(
"data:image/(?:png|jpeg|gif|webp|svg\\+xml)(?:;[^,]*)?,.+", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
static HtmlDocument prepare(Document source) {
checkCancelled();
var images = new EmbeddedImages();
for (var style : source.select("style")) {
String css = images.adapt(style.data());
style.empty().appendChild(new DataNode(css));
}
for (var element : source.select("[style]")) element.attr("style", images.adapt(element.attr("style")));
var baseElement = source.selectFirst("base[href]");
URI base = HtmlDocument.httpUri(baseElement == null ? source.baseUri() : baseElement.attr("href"));
// Export inline SVG as an isolated image too, keeping page logos and icons without active SVG DOM.
for (var svg : source.select("svg").stream()
.filter(svg -> svg.parents().stream().noneMatch(parent -> parent.tagName().equals("svg"))).toList()) {
svg.attr("xmlns", "http://www.w3.org/2000/svg");
var image = new org.jsoup.nodes.Element("img");
image.attributes().addAll(svg.attributes());
image.attr("src", "data:image/svg+xml;base64," + Base64.getEncoder()
.encodeToString(svg.outerHtml().getBytes(StandardCharsets.UTF_8)));
svg.replaceWith(image);
}
source.select("script, template, noscript, iframe, object, embed, link, meta, base").remove();
// Cleaner handles the body only. Keep saved styles in their original order, ahead of body styles.
var headStyles = source.head().select("style").stream().map(style -> style.clone()).toList();
// Embedded SVG remains an image, never active inline SVG markup (SVG secure image mode).
for (var image : source.select("img[src]")) {
String value = images.adapt(image.attr("src").strip());
image.attr("src", value);
if (IMAGE.matcher(value).matches()) continue;
var remote = HtmlDocument.imageUri(value, base);
if (remote == null) image.removeAttr("src");
else image.attr("src", remote.toASCIIString());
}
var safelist = new Safelist(SAFE);
for (var element : source.getAllElements()) {
checkCancelled();
// Saved custom-element wrappers are inert with JavaScript disabled, but their CSS still matters.
if (element.tagName().contains("-")) safelist.addTags(element.tagName());
for (var attribute : element.attributes()) {
if (presentationAttribute(attribute.getKey())) safelist.addAttributes(":all", attribute.getKey());
}
}
var clean = new Cleaner(safelist).clean(source);
copyAttributes(source.selectFirst("html"), clean.selectFirst("html"));
copyAttributes(source.body(), clean.body());
clean.title(source.title());
for (var style : headStyles) {
var saved = clean.head().appendElement("style");
if (style.hasAttr("media")) saved.attr("media", style.attr("media"));
saved.appendChild(new DataNode(style.data()));
}
var online = render(clean.clone(), base, true);
var offline = render(clean, base, false);
return new HtmlDocument(offline.html(), online.html(), online.external());
}
private static void copyAttributes(org.jsoup.nodes.Element source, org.jsoup.nodes.Element target) {
for (String name : new String[]{"class", "id", "style", "hidden", "dir", "lang"}) {
if (source.hasAttr(name)) target.attr(name, source.attr(name));
}
for (var attribute : source.attributes()) {
if (presentationAttribute(attribute.getKey())) target.attr(attribute.getKey(), attribute.getValue());
}
}
private static boolean presentationAttribute(String name) {
return name.startsWith("data-") || name.startsWith("aria-") || name.equals("role");
}
private record Rendered(String html, boolean external) {}
private static Rendered render(Document document, URI base, boolean externalImages) {
boolean[] external = {false};
for (var image : document.select("img[src]")) {
if (HtmlDocument.httpUri(image.attr("src")) != null) {
external[0] = true;
if (!externalImages) image.removeAttr("src");
}
}
for (var style : document.select("style")) {
String saved = style.data();
style.empty().appendChild(new DataNode(css(saved, base, externalImages, external)));
}
for (var element : document.select("[style]")) {
// Parse an attribute as a rule, so URL handling is identical for both kinds of saved CSS.
String sheet = css("x{" + element.attr("style") + "}", base, externalImages, external);
int start = sheet.indexOf('{'), end = sheet.lastIndexOf('}');
element.attr("style", start >= 0 && end > start ? sheet.substring(start + 1, end) : "");
}
document.head().prependElement("meta").attr("http-equiv", "Content-Security-Policy")
.attr("content", policy(externalImages));
document.head().prependElement("meta").attr("charset", "UTF-8");
document.head().appendElement("meta").attr("name", "viewport").attr("content", "width=device-width, initial-scale=1");
document.outputSettings().prettyPrint(false);
return new Rendered("<!doctype html>" + document.outerHtml(), external[0]);
}
private static String css(String source, URI base, boolean allowExternal, boolean[] external) {
checkCancelled();
var errors = new CollectingCSSParseErrorHandler();
var settings = new CSSReaderSettings().setCustomErrorHandler(errors)
.setCustomExceptionHandler(new DoNothingCSSParseExceptionCallback());
var sheet = CSSReader.readFromStringReader(source, settings);
// Keep unsupported author CSS: the document CSP still enforces the resource boundary.
if (sheet == null || errors.hasParseErrors()) return source;
sheet.removeAllImportRules();
CSSVisitor.visitCSSUrl(sheet, new DefaultCSSUrlVisitor() {
@Override public void onUrlDeclaration(ICSSTopLevelRule rule, CSSDeclaration declaration,
CSSExpressionMemberTermURI term) {
String value = term.getURIString();
if (value.regionMatches(true, 0, "data:", 0, 5) || value.startsWith("#")) return;
URI remote = HtmlDocument.imageUri(value, base);
boolean image = !(rule instanceof CSSFontFaceRule);
if (remote != null && image) external[0] = true;
term.setURIString(remote != null && image && allowExternal ? remote.toASCIIString() : "data:,");
}
});
// A stylesheet's escaped strings must not terminate its HTML raw-text container.
return new CSSWriter().getCSSAsString(sheet).replaceAll("(?i)</style", "<\\\\/style");
}
static String policy(boolean externalImages) {
return "default-src 'none'; img-src data:" + (externalImages ? " https: http:" : "")
+ "; style-src 'unsafe-inline'; font-src data:; script-src 'none'; frame-src 'none';"
+ " object-src 'none'; connect-src 'none'; form-action 'none'; base-uri 'none'";
}
private static void checkCancelled() {
if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException();
}
private HtmlPresentation() {}
}
@@ -0,0 +1,192 @@
package de.neitzel.fx.control;
import java.net.URI;
import java.nio.file.Path;
import java.util.Objects;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
/** Saved HTML viewer with offline defaults, isolated SVG images and per-document image permission.
* All instance methods must be called on the FX thread. Constructing the control performs no I/O.
* Loading a replacement, clearing or closing cancels pending work and revokes permission.
*/
public final class HtmlViewer extends BorderPane implements AutoCloseable {
private final WebView browser = new WebView();
private final ReadOnlyBooleanWrapper preparing = new ReadOnlyBooleanWrapper();
private final ReadOnlyBooleanWrapper loading = new ReadOnlyBooleanWrapper(this, "loading");
private final ReadOnlyObjectWrapper<Throwable> error = new ReadOnlyObjectWrapper<>(this, "error");
private final ReadOnlyBooleanWrapper externalImagesAvailable = new ReadOnlyBooleanWrapper(this, "externalImagesAvailable");
private final ReadOnlyBooleanWrapper externalImagesAllowed = new ReadOnlyBooleanWrapper(this, "externalImagesAllowed");
private final BooleanProperty mediaButtonVisible = new SimpleBooleanProperty(this, "mediaButtonVisible", true);
private final StringProperty mediaLoadText = new SimpleStringProperty(this, "mediaLoadText", "Load external media");
private final StringProperty mediaReloadText = new SimpleStringProperty(this, "mediaReloadText", "Reload external media");
private final StringProperty mediaTooltipText = new SimpleStringProperty(this, "mediaTooltipText", "Loads external images for this viewer only and contacts their servers.");
private final StringProperty noExternalMediaText = new SimpleStringProperty(this, "noExternalMediaText", "No resolvable external image addresses found.");
private HtmlDocument document;
private Task<HtmlDocument> pending;
private long generation;
private boolean closed;
public HtmlViewer() {
getStyleClass().add("html-viewer");
browser.setContextMenuEnabled(false);
browser.getEngine().setJavaScriptEnabled(false);
loading.bind(preparing.or(browser.getEngine().getLoadWorker().runningProperty()));
browser.getEngine().getLoadWorker().stateProperty().addListener((property, old, state) -> {
if (state == Worker.State.FAILED && !preparing.get() && !closed) {
error.set(browser.getEngine().getLoadWorker().getException());
}
});
var media = new Button();
media.getStyleClass().add("html-viewer-media-load");
media.textProperty().bind(Bindings.when(externalImagesAllowed).then(mediaReloadText).otherwise(mediaLoadText));
media.disableProperty().bind(loading.or(externalImagesAvailable.not()));
var tooltip = new Tooltip();
tooltip.textProperty().bind(Bindings.when(externalImagesAvailable).then(mediaTooltipText).otherwise(noExternalMediaText));
media.setTooltip(tooltip);
media.setOnAction(event -> loadExternalImages());
var toolbar = new HBox(media);
toolbar.setPadding(new Insets(8, 10, 5, 10));
toolbar.visibleProperty().bind(mediaButtonVisible);
toolbar.managedProperty().bind(mediaButtonVisible);
setTop(toolbar);
var progress = new ProgressIndicator();
progress.setMaxSize(36, 36);
progress.visibleProperty().bind(loading);
progress.managedProperty().bind(loading);
var failure = new Label();
failure.setWrapText(true);
failure.textProperty().bind(error.map(problem -> Objects.toString(problem.getMessage(), problem.getClass().getSimpleName())));
failure.visibleProperty().bind(error.isNotNull());
failure.managedProperty().bind(failure.visibleProperty());
setCenter(new StackPane(browser, progress, failure));
}
/** Prepare a file on an owned virtual thread, then display it offline. */
public void load(Path file) {
Objects.requireNonNull(file, "file");
prepare(() -> HtmlDocument.read(file));
}
public void loadHtml(String html) { loadHtml(html, null); }
/** Prepare HTML off the FX thread; source is an optional HTTP(S) base, never a URL to fetch. */
public void loadHtml(String html, URI source) {
Objects.requireNonNull(html, "html");
prepare(() -> HtmlDocument.parse(html, source));
}
/** Display an immutable document already prepared by the caller. Permission starts revoked. */
public void display(HtmlDocument value) {
requireOpen();
Objects.requireNonNull(value, "document");
clear();
show(value);
}
private void show(HtmlDocument value) {
document = value;
externalImagesAvailable.set(value.hasExternalImages());
browser.getEngine().loadContent(value.offlineHtml());
}
@FunctionalInterface private interface Preparation { HtmlDocument run() throws Exception; }
private void prepare(Preparation work) {
requireOpen();
clear();
long request = generation;
preparing.set(true);
var task = new Task<HtmlDocument>() {
@Override protected HtmlDocument call() throws Exception { return work.run(); }
};
pending = task;
task.setOnSucceeded(event -> {
if (closed || request != generation) return;
pending = null;
show(task.getValue());
preparing.set(false);
});
task.setOnFailed(event -> {
if (closed || request != generation) return;
pending = null;
error.set(task.getException());
preparing.set(false);
});
Thread.ofVirtual().name("html-viewer-prepare").start(task);
}
/** Explicitly grants HTTP(S) image requests for the currently displayed document only. */
public void loadExternalImages() {
requireOpen();
if (document == null || !externalImagesAvailable.get()) return;
error.set(null);
externalImagesAllowed.set(true);
browser.getEngine().loadContent(document.externalImagesHtml());
}
public void clear() {
requireOpen();
generation++;
if (pending != null) { pending.cancel(true); pending = null; }
preparing.set(false);
document = null;
externalImagesAvailable.set(false);
externalImagesAllowed.set(false);
error.set(null);
browser.getEngine().getLoadWorker().cancel();
browser.getEngine().load(null);
}
@Override public void close() {
requireFxThread();
if (closed) return;
clear();
closed = true;
}
private void requireOpen() {
requireFxThread();
if (closed) throw new IllegalStateException("HtmlViewer is closed.");
}
private static void requireFxThread() {
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("HtmlViewer requires the JavaFX application thread.");
}
public ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); }
public boolean isLoading() { return loading.get(); }
public ReadOnlyObjectProperty<Throwable> errorProperty() { return error.getReadOnlyProperty(); }
public Throwable getError() { return error.get(); }
public ReadOnlyBooleanProperty externalImagesAvailableProperty() { return externalImagesAvailable.getReadOnlyProperty(); }
public boolean isExternalImagesAvailable() { return externalImagesAvailable.get(); }
public ReadOnlyBooleanProperty externalImagesAllowedProperty() { return externalImagesAllowed.getReadOnlyProperty(); }
public boolean isExternalImagesAllowed() { return externalImagesAllowed.get(); }
public BooleanProperty mediaButtonVisibleProperty() { return mediaButtonVisible; }
public boolean isMediaButtonVisible() { return mediaButtonVisible.get(); }
public void setMediaButtonVisible(boolean value) { mediaButtonVisible.set(value); }
public StringProperty mediaLoadTextProperty() { return mediaLoadText; }
public String getMediaLoadText() { return mediaLoadText.get(); }
public void setMediaLoadText(String value) { mediaLoadText.set(value); }
public StringProperty mediaReloadTextProperty() { return mediaReloadText; }
public String getMediaReloadText() { return mediaReloadText.get(); }
public void setMediaReloadText(String value) { mediaReloadText.set(value); }
public StringProperty mediaTooltipTextProperty() { return mediaTooltipText; }
public String getMediaTooltipText() { return mediaTooltipText.get(); }
public void setMediaTooltipText(String value) { mediaTooltipText.set(value); }
public StringProperty noExternalMediaTextProperty() { return noExternalMediaText; }
public String getNoExternalMediaText() { return noExternalMediaText.get(); }
public void setNoExternalMediaText(String value) { noExternalMediaText.set(value); }
}
@@ -88,11 +88,26 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this);
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ReadOnlyListWrapper<K> selectedKeys = new ReadOnlyListWrapper<>(
FXCollections.emptyObservableList());
private final ReadOnlyListWrapper<T> selectedElements = new ReadOnlyListWrapper<>(
FXCollections.emptyObservableList());
private final ObjectProperty<RowSelectionMode> selectionMode =
new SimpleObjectProperty<>(this, "selectionMode", RowSelectionMode.SINGLE) {
@Override public void set(RowSelectionMode value) {
requireFx();
if (closed) throw new IllegalStateException("Grid is closed");
super.set(Objects.requireNonNull(value));
}
};
/** Creates a query-free FXML control. Columns are visible before a source is attached. */
public DataGrid() {
requireFx();
getStyleClass().add("data-grid");
selectionMode.addListener((property, old, mode) -> {
if (renderer != null) renderer.setSelectionMode(mode);
});
setSpacing(8);
getChildren().addAll(declaration.preview(), status);
}
@@ -258,6 +273,9 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
new PageRequest.Paged(
0, Math.min(50, source.capabilities().maximumPageSize())));
renderer = table.openResults(columns, rowFactory);
renderer.setSelectionMode(getSelectionMode());
selectedKeys.bind(renderer.selectedKeysProperty());
selectedElements.bind(renderer.selectedElementsProperty());
renderer.enableColumnSeparators();
selectedKey.bind(renderer.selectedKeyProperty());
selectedElement.bind(renderer.selectedElementProperty());
@@ -351,6 +369,21 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
return selectedElement.getReadOnlyProperty();
}
public ObjectProperty<RowSelectionMode> selectionModeProperty() { return selectionMode; }
public RowSelectionMode getSelectionMode() { return selectionMode.get(); }
public void setSelectionMode(RowSelectionMode mode) { selectionMode.set(mode); }
public ReadOnlyListProperty<K> selectedKeysProperty() { return selectedKeys.getReadOnlyProperty(); }
public ReadOnlyListProperty<T> selectedElementsProperty() { return selectedElements.getReadOnlyProperty(); }
public void selectKeys(Collection<? extends K> keys) {
check();
renderer.selectKeys(keys);
}
public void select(K key) {
check();
renderer.select(key);
@@ -358,7 +391,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
public void confirmedDeleted(K key) {
check();
if (Objects.equals(key, selectedKeyProperty().get())) renderer.select(null);
renderer.deselect(key);
refresh();
}
@@ -1229,6 +1262,10 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
if (renderer != null) renderer.close();
selectedKey.unbind();
selectedElement.unbind();
selectedKeys.unbind();
selectedElements.unbind();
selectedKeys.set(FXCollections.emptyObservableList());
selectedElements.set(FXCollections.emptyObservableList());
selectedKey.set(null);
selectedElement.set(null);
getChildren().clear();
@@ -0,0 +1,6 @@
package de.neitzel.fx.view;
/** Configures row selection independently of querying and saved grid layouts. */
public enum RowSelectionMode {
NONE, SINGLE, MULTIPLE
}
@@ -137,7 +137,15 @@ public class Table extends VBox {
/**
* The Rows currently showing.
*/
private final VBox body = new VBox();
private final VBox body = new VBox() {
private static final String SELECTION_CSS =
Table.class.getResource("result-selection.css").toExternalForm();
@Override
public String getUserAgentStylesheet() {
return SELECTION_CSS;
}
};
/**
* The column popup.
@@ -4,6 +4,7 @@ import de.neitzel.grid.*;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.collections.*;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Button;
@@ -11,6 +12,8 @@ import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
@@ -35,6 +38,14 @@ public final class TableResults<K, T> implements AutoCloseable {
private List<Entry<K, T>> entries = List.of();
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
private final ObservableList<K> selectedKeys = FXCollections.observableArrayList();
private final ObservableList<T> selectedElements = FXCollections.observableArrayList();
private final ReadOnlyListWrapper<K> keysView = new ReadOnlyListWrapper<>(
FXCollections.unmodifiableObservableList(selectedKeys));
private final ReadOnlyListWrapper<T> elementsView = new ReadOnlyListWrapper<>(
FXCollections.unmodifiableObservableList(selectedElements));
private RowSelectionMode selectionMode = RowSelectionMode.SINGLE;
private K anchor;
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
new ReadOnlyObjectWrapper<>();
private boolean closed;
@@ -59,7 +70,8 @@ public final class TableResults<K, T> implements AutoCloseable {
private final ResultHeaderGestures gestures;
private final ResultScrollAlignment scrollAlignment;
private record Entry<K, T>(GridRow<K, T> row, ResultRow view, EventHandler<MouseEvent> click) {}
private record Entry<K, T>(GridRow<K, T> row, ResultRow view,
EventHandler<MouseEvent> click, EventHandler<KeyEvent> key) {}
TableResults(
HBox header,
@@ -104,6 +116,20 @@ public final class TableResults<K, T> implements AutoCloseable {
return selectedElement.getReadOnlyProperty();
}
public ReadOnlyListProperty<K> selectedKeysProperty() { return keysView.getReadOnlyProperty(); }
/** Only selected models currently visible and interactive are actionable. */
public ReadOnlyListProperty<T> selectedElementsProperty() { return elementsView.getReadOnlyProperty(); }
public RowSelectionMode getSelectionMode() { return selectionMode; }
public void setSelectionMode(RowSelectionMode mode) {
checkOpen();
selectionMode = Objects.requireNonNull(mode);
if (mode == RowSelectionMode.NONE) select(null);
else if (mode == RowSelectionMode.SINGLE && selectedKeys.size() > 1) select(selectedKey.get());
}
/** Cleanup failures are exposed separately: they do not roll back an already published page. */
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
return disposalFailure.getReadOnlyProperty();
@@ -193,10 +219,81 @@ public final class TableResults<K, T> implements AutoCloseable {
/** Retains an off-page key while exposing no loaded selected element. */
public void select(K key) {
checkOpen();
selectedKey.set(key);
selectKeys(key == null ? List.of() : List.of(key));
}
/** Replaces selection, retaining off-page identities. The last key is the lead. */
public void selectKeys(Collection<? extends K> keys) {
checkOpen();
var next = new LinkedHashSet<K>();
keys.forEach(key -> next.add(Objects.requireNonNull(key)));
if (selectionMode == RowSelectionMode.NONE) next.clear();
if (selectionMode == RowSelectionMode.SINGLE && next.size() > 1)
throw new IllegalArgumentException("Multiple selection is disabled");
selectedKeys.setAll(next);
selectedKey.set(next.isEmpty() ? null : next.getLast());
anchor = selectedKey.get();
markSelection();
}
public void deselect(K key) {
checkOpen();
var remaining = new ArrayList<>(selectedKeys);
remaining.remove(key);
selectKeys(remaining);
}
private List<K> visibleKeys() {
var byRoot = new IdentityHashMap<Node, K>();
entries.forEach(e -> byRoot.put(e.view().root(), e.row().key()));
return body.getChildren().stream().filter(byRoot::containsKey).map(byRoot::get).toList();
}
private void choose(K key, boolean shortcut, boolean shift) {
if (!rowsInteractive || selectionMode == RowSelectionMode.NONE) return;
if (selectionMode == RowSelectionMode.SINGLE) { select(key); return; }
K previousAnchor = anchor;
var next = new LinkedHashSet<K>();
if (shortcut) next.addAll(selectedKeys);
var visible = visibleKeys();
int start = visible.indexOf(anchor), end = visible.indexOf(key);
if (shift && start >= 0 && end >= 0) {
next.addAll(visible.subList(Math.min(start, end), Math.max(start, end) + 1));
next.remove(key);
next.add(key);
} else if (!shortcut || !next.remove(key)) next.add(key);
selectKeys(next);
anchor = shift && previousAnchor != null ? previousAnchor : key;
}
private void keyPressed(K key, KeyEvent event) {
// Embedded editors retain their own keyboard behavior.
if (event.getTarget() != event.getSource() || !rowsInteractive
|| selectionMode == RowSelectionMode.NONE) return;
var visible = visibleKeys();
int index = visible.indexOf(key);
if (event.getCode() == KeyCode.A && event.isShortcutDown()
&& selectionMode == RowSelectionMode.MULTIPLE) selectKeys(visible);
else if (event.getCode() == KeyCode.ESCAPE) select(null);
else if (event.getCode() == KeyCode.SPACE) choose(key, event.isShortcutDown(), event.isShiftDown());
else {
int next = switch (event.getCode()) {
case UP -> Math.max(0, index - 1);
case DOWN -> Math.min(visible.size() - 1, index + 1);
case HOME -> 0;
case END -> visible.size() - 1;
default -> -1;
};
if (next < 0 || visible.isEmpty()) return;
K target = visible.get(next);
if (!event.isShortcutDown() || event.isShiftDown())
choose(target, event.isShortcutDown(), event.isShiftDown());
entries.stream().filter(e -> Objects.equals(e.row().key(), target))
.findFirst().ifPresent(e -> e.view().root().requestFocus());
}
event.consume();
}
/**
* Stages fresh rows before replacing the visible page; failed construction preserves the old
* page.
@@ -258,13 +355,20 @@ public final class TableResults<K, T> implements AutoCloseable {
"Row factory must create detached fresh rows");
EventHandler<MouseEvent> click =
e -> {
if (e.getButton() == MouseButton.PRIMARY) select(row.key());
if (e.getButton() == MouseButton.PRIMARY)
choose(row.key(), e.isShortcutDown(), e.isShiftDown());
if (e.getButton() == MouseButton.PRIMARY
&& (e.getTarget() == view.root() || e.getTarget() instanceof Label))
view.root().requestFocus();
};
next.add(new Entry<>(row, view, click));
EventHandler<KeyEvent> key = e -> keyPressed(row.key(), e);
next.add(new Entry<>(row, view, click, key));
validateRow(view);
view.root().getStyleClass().add("result-row");
layoutRow(view, nextOrder, preparedWidths);
view.root().addEventHandler(MouseEvent.MOUSE_CLICKED, click);
view.root().setFocusTraversable(true);
view.root().addEventHandler(KeyEvent.KEY_PRESSED, key);
}
} catch (RuntimeException failure) {
release(next);
@@ -445,8 +549,10 @@ public final class TableResults<K, T> implements AutoCloseable {
private void markSelection() {
T loaded = null;
List<T> actionable = new ArrayList<>();
Set<K> keys = new HashSet<>(selectedKeys);
for (var e : entries) {
boolean selected = Objects.equals(selectedKey.get(), e.row().key());
boolean selected = keys.contains(e.row().key());
e.view()
.root()
.pseudoClassStateChanged(
@@ -454,10 +560,14 @@ public final class TableResults<K, T> implements AutoCloseable {
e.view().root().getStyleClass().remove("selected");
if (selected) {
e.view().root().getStyleClass().add("selected");
if (e.view().root().getParent() == body) loaded = e.row().model();
if (rowsInteractive && e.view().root().getParent() == body) {
actionable.add(e.row().model());
if (Objects.equals(selectedKey.get(), e.row().key())) loaded = e.row().model();
}
}
}
selectedElement.set(rowsInteractive ? loaded : null);
selectedElements.setAll(actionable);
}
public void setOnLayoutCommitted(Runnable handler) {
@@ -774,6 +884,7 @@ public final class TableResults<K, T> implements AutoCloseable {
RuntimeException aggregate = null;
for (var e : retired) {
e.view().root().removeEventHandler(MouseEvent.MOUSE_CLICKED, e.click());
e.view().root().removeEventHandler(KeyEvent.KEY_PRESSED, e.key());
try {
e.view().dispose().run();
} catch (RuntimeException failure) {
@@ -806,6 +917,9 @@ public final class TableResults<K, T> implements AutoCloseable {
body.setOnMouseClicked(null);
selectedKey.set(null);
selectedElement.set(null);
selectedKeys.clear();
selectedElements.clear();
anchor = null;
captured = GroupProjection.capture(List.of(), List.of());
groupTree = List.of();
disclosure.clear();