feat(fx): add collapsible groups and managed floating windows

This commit is contained in:
2026-11-15 22:26:05 +01:00
parent 1a3aea6e09
commit f6539bdd29
34 changed files with 3062 additions and 48 deletions
@@ -60,10 +60,13 @@ final class DockDragController {
Menu splits = new Menu("Split");
MenuItem close = new MenuItem("Close");
close.setOnAction(event -> manager.requestTabClose(id));
ContextMenu menu = new ContextMenu(destinations, splits, close);
ContextMenu menu = new ContextMenu(destinations, splits, close,
new MenuItem("Float"), new MenuItem("Return to main"));
menu.setOnShowing(event -> {
populateDestinations(destinations, id);
populateSplits(splits, id);
menu.getItems().set(3, moveItem("Float", id, DockTarget.floating()));
menu.getItems().set(4, moveItem("Return to main", id, DockTarget.returnToMain()));
});
tab.setContextMenu(menu);
}
@@ -34,7 +34,7 @@ final class DockEdgeRegion extends Region {
divider.setCursor(side.isVertical() ? Cursor.H_RESIZE : Cursor.V_RESIZE);
divider.setOnMousePressed(event -> {
if (event.getButton() != MouseButton.PRIMARY) return;
if (!canResize.getAsBoolean()) {
if (DockGroupPane.allCollapsed(content) || !canResize.getAsBoolean()) {
event.consume();
return;
}
@@ -100,37 +100,59 @@ final class DockEdgeRegion extends Region {
requestLayout();
}
boolean changesPreferredExtent(Double width, Double height) {
Double requested = side.isVertical() ? width : height;
return requested != null && Double.compare(requested, committedExtent) != 0;
}
void updatePreferredExtent(Double width, Double height) {
Double requested = side.isVertical() ? width : height;
if (requested == null) return;
extent = requested;
committedExtent = requested;
requestLayout();
}
double committedExtent() { return committedExtent; }
Side side() { return side; }
@Override protected double computePrefWidth(double height) {
return side.isVertical() ? extent + DIVIDER_SIZE : content == null ? 0 : content.prefWidth(height);
return side.isVertical() ? displayedExtent() + dividerSize() : content == null ? 0 : content.prefWidth(height);
}
@Override protected double computePrefHeight(double width) {
return side.isHorizontal() ? extent + DIVIDER_SIZE : content == null ? 0 : content.prefHeight(width);
return side.isHorizontal() ? displayedExtent() + dividerSize() : content == null ? 0 : content.prefHeight(width);
}
@Override protected double computeMinWidth(double height) {
return content == null ? 0 : content.minWidth(height) + (side.isVertical() ? DIVIDER_SIZE : 0);
return content == null ? 0 : content.minWidth(height) + (side.isVertical() ? dividerSize() : 0);
}
@Override protected double computeMinHeight(double width) {
return content == null ? 0 : content.minHeight(width) + (side.isHorizontal() ? DIVIDER_SIZE : 0);
return content == null ? 0 : content.minHeight(width) + (side.isHorizontal() ? dividerSize() : 0);
}
private double dividerSize() { return DockGroupPane.allCollapsed(content) ? 0 : DIVIDER_SIZE; }
private double displayedExtent() {
return DockGroupPane.allCollapsed(content)
? side.isVertical() ? content.prefWidth(-1) : content.prefHeight(-1) : extent;
}
@Override protected void layoutChildren() {
if (content == null) return;
double dividerSize = dividerSize();
divider.setVisible(dividerSize > 0);
double width = getWidth();
double height = getHeight();
if (side.isVertical()) {
content.resizeRelocate(side == Side.RIGHT ? DIVIDER_SIZE : 0, 0,
Math.max(0, width - DIVIDER_SIZE), height);
divider.resizeRelocate(side == Side.RIGHT ? 0 : width - DIVIDER_SIZE, 0, DIVIDER_SIZE, height);
content.resizeRelocate(side == Side.RIGHT ? dividerSize : 0, 0,
Math.max(0, width - dividerSize), height);
divider.resizeRelocate(side == Side.RIGHT ? 0 : width - dividerSize, 0, dividerSize, height);
} else {
content.resizeRelocate(0, side == Side.BOTTOM ? DIVIDER_SIZE : 0,
width, Math.max(0, height - DIVIDER_SIZE));
divider.resizeRelocate(0, side == Side.BOTTOM ? 0 : height - DIVIDER_SIZE, width, DIVIDER_SIZE);
content.resizeRelocate(0, side == Side.BOTTOM ? dividerSize : 0,
width, Math.max(0, height - dividerSize));
divider.resizeRelocate(0, side == Side.BOTTOM ? 0 : height - dividerSize, width, dividerSize);
}
}
}
@@ -2,7 +2,7 @@ package de.neitzel.fx.docking;
/** Machine-readable rejection with optional affected identity and technical cause. */
public record DockFailure(Code code, DockableId dockableId, String message, Throwable cause) {
public enum Code { SPLIT_DISABLED, SPLIT_TOO_SMALL, TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED,
PLACEMENT_REJECTED, PLACEMENT_CHECK_FAILED, ID_MISMATCH, FACTORY_FAILED,
CLOSE_IN_PROGRESS, CLOSE_CHECK_FAILED, CLEANUP_FAILED }
public enum Code { INVALID_GROUP_CONFIGURATION, COLLAPSE_DISABLED, SPLIT_DISABLED, SPLIT_TOO_SMALL, TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED,
PLACEMENT_REJECTED, PLACEMENT_CHECK_FAILED, ID_MISMATCH, FACTORY_FAILED, MAIN_WINDOW_ONLY,
CLOSE_IN_PROGRESS, CLOSE_CHECK_FAILED, CLEANUP_FAILED, INVALID_WINDOW_BOUNDS, WINDOW_CREATION_FAILED }
}
@@ -0,0 +1,64 @@
package de.neitzel.fx.docking;
import javafx.geometry.Side;
import lombok.Builder;
import lombok.Value;
import java.util.Objects;
/** Immutable partial update: null getters mean unspecified, while false is an explicit value. */
@Value @Builder
public class DockGroupChanges {
Side tabSide;
Double preferredWidth;
Double preferredHeight;
Double minimumWidth;
Double minimumHeight;
Boolean persistent;
Boolean visibleWhenEmpty;
Boolean releaseSpaceWhenEmpty;
Boolean collapsible;
SplitDirections splitDirections;
/** Builder accepts primitive dimensions/flags and requires non-null enum settings. */
public static class DockGroupChangesBuilder {
public DockGroupChangesBuilder tabSide(Side value) { tabSide = Objects.requireNonNull(value); return this; }
public DockGroupChangesBuilder preferredWidth(double value) { preferredWidth = value; return this; }
public DockGroupChangesBuilder preferredHeight(double value) { preferredHeight = value; return this; }
public DockGroupChangesBuilder minimumWidth(double value) { minimumWidth = value; return this; }
public DockGroupChangesBuilder minimumHeight(double value) { minimumHeight = value; return this; }
public DockGroupChangesBuilder persistent(boolean value) { persistent = value; return this; }
public DockGroupChangesBuilder visibleWhenEmpty(boolean value) { visibleWhenEmpty = value; return this; }
public DockGroupChangesBuilder releaseSpaceWhenEmpty(boolean value) { releaseSpaceWhenEmpty = value; return this; }
public DockGroupChangesBuilder collapsible(boolean value) { collapsible = value; return this; }
public DockGroupChangesBuilder splitDirections(SplitDirections value) { splitDirections = Objects.requireNonNull(value); return this; }
}
DockGroupChanges resolved(DockGroupDefinition current) {
return builder()
.tabSide(tabSide == null ? current.getTabSide() : tabSide)
.preferredWidth(preferredWidth == null ? current.getPreferredWidth() : preferredWidth)
.preferredHeight(preferredHeight == null ? current.getPreferredHeight() : preferredHeight)
.minimumWidth(minimumWidth == null ? current.getMinimumWidth() : minimumWidth)
.minimumHeight(minimumHeight == null ? current.getMinimumHeight() : minimumHeight)
.persistent(persistent == null ? current.isPersistent() : persistent)
.visibleWhenEmpty(visibleWhenEmpty == null ? current.isVisibleWhenEmpty() : visibleWhenEmpty)
.releaseSpaceWhenEmpty(releaseSpaceWhenEmpty == null ? current.isReleaseSpaceWhenEmpty() : releaseSpaceWhenEmpty)
.collapsible(collapsible == null ? current.isCollapsible() : collapsible)
.splitDirections(splitDirections == null ? current.getSplitDirections() : splitDirections)
.build();
}
void applyTo(DockGroupDefinition target) {
if (tabSide != null) target.setTabSide(tabSide);
if (preferredWidth != null) target.setPreferredWidth(preferredWidth);
if (preferredHeight != null) target.setPreferredHeight(preferredHeight);
if (minimumWidth != null) target.setMinimumWidth(minimumWidth);
if (minimumHeight != null) target.setMinimumHeight(minimumHeight);
if (persistent != null) target.setPersistent(persistent);
if (visibleWhenEmpty != null) target.setVisibleWhenEmpty(visibleWhenEmpty);
if (releaseSpaceWhenEmpty != null) target.setReleaseSpaceWhenEmpty(releaseSpaceWhenEmpty);
if (collapsible != null) target.setCollapsible(collapsible);
if (splitDirections != null) target.setSplitDirections(splitDirections);
}
}
@@ -14,6 +14,7 @@ public final class DockGroupDefinition implements DockLayoutNode {
private double minimumWidth = 80;
private double minimumHeight = 80;
private boolean persistent = true;
private boolean collapsible;
private boolean visibleWhenEmpty = true;
private boolean releaseSpaceWhenEmpty;
private SplitDirections splitDirections = SplitDirections.ALL;
@@ -0,0 +1,128 @@
package de.neitzel.fx.docking;
import javafx.scene.Node;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TabPane;
import javafx.scene.control.Tab;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Region;
/** Keeps the same tab headers and live content while exposing only the header rail. */
final class DockGroupPane extends TabPane {
private final DockGroupDefinition definition;
private boolean collapsed;
DockGroupPane(DockGroupDefinition definition) {
this.definition = definition;
getStyleClass().add("dock-group");
}
boolean isCollapsed() { return collapsed; }
void setCollapsed(boolean collapsed) {
this.collapsed = collapsed;
pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("collapsed"), collapsed);
requestLayout();
}
void installHeaderActions(java.util.function.Consumer<Tab> activate, Runnable collapse) {
addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ESCAPE && !collapsed && definition.isCollapsible()) {
collapse.run();
event.consume();
}
});
Tab[] pressed = {null};
boolean[] selected = {false};
boolean[] wasCollapsed = {false};
addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
if (event.getButton() != MouseButton.PRIMARY) return;
pressed[0] = headerTab(event.getPickResult().getIntersectedNode());
selected[0] = pressed[0] != null && getSelectionModel().getSelectedItem() == pressed[0];
wasCollapsed[0] = collapsed;
});
addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
if (event.getButton() != MouseButton.PRIMARY || !event.isStillSincePress()) return;
Tab clicked = headerTab(event.getPickResult().getIntersectedNode());
if (clicked == null || clicked != pressed[0]) return;
pressed[0] = null;
if (wasCollapsed[0]) activate.accept(clicked);
else if (selected[0] && definition.isCollapsible()) collapse.run();
});
}
private Tab headerTab(Node target) {
for (Node current = target; current != null && current != this; current = current.getParent()) {
if (current.getStyleClass().contains("tab-close-button")) return null;
if (current instanceof TabPane) return null;
for (Tab tab : getTabs()) {
if (tab.getId() != null && tab.getId().equals(current.getId())) return tab;
}
}
return null;
}
void focusSelectedHeader() {
Tab selected = getSelectionModel().getSelectedItem();
Node strip = ownedSkinChild("tab-header-area");
Node header = selected == null || strip == null ? null : strip.lookup("#" + selected.getId());
if (header != null) {
header.setFocusTraversable(true);
header.requestFocus();
}
}
static boolean allCollapsed(Node node) {
if (node instanceof DockGroupPane group) return group.isCollapsed();
return node instanceof SplitPane split && !split.getItems().isEmpty()
&& split.getItems().stream().allMatch(DockGroupPane::allCollapsed);
}
private double headerExtent() {
Node header = ownedSkinChild("tab-header-area");
return header instanceof Region region ? Math.max(24, region.prefHeight(-1)) : 28;
}
private double headerLength() {
Node header = ownedSkinChild("tab-header-area");
return header instanceof Region region ? Math.max(24, region.prefWidth(-1)) : Math.max(24, getTabs().size() * 32);
}
@Override protected double computePrefWidth(double height) {
return collapsed ? getSide().isVertical() ? headerExtent() : headerLength() : definition.getPreferredWidth();
}
@Override protected double computePrefHeight(double width) {
return collapsed ? getSide().isHorizontal() ? headerExtent() : headerLength() : definition.getPreferredHeight();
}
@Override protected double computeMinWidth(double height) {
return collapsed ? getSide().isVertical() ? headerExtent() : headerLength() : definition.getMinimumWidth();
}
@Override protected double computeMinHeight(double width) {
return collapsed ? getSide().isHorizontal() ? headerExtent() : headerLength() : definition.getMinimumHeight();
}
private Node ownedSkinChild(String styleClass) {
return getChildrenUnmodifiable().stream().filter(node -> node.getStyleClass().contains(styleClass))
.findFirst().orElse(null);
}
private boolean containsSelectedContent(Node wrapper, Node selectedContent) {
for (Node current = selectedContent; current != null && current != this; current = current.getParent()) {
if (current == wrapper) return true;
}
return false;
}
@Override protected void layoutChildren() {
super.layoutChildren();
Tab selected = getSelectionModel().getSelectedItem();
Node selectedContent = selected == null ? null : selected.getContent();
for (Node wrapper : getChildrenUnmodifiable()) {
if (wrapper.getStyleClass().contains("tab-content-area")) {
wrapper.setVisible(!collapsed && containsSelectedContent(wrapper, selectedContent));
}
}
}
}
@@ -30,7 +30,8 @@ final class DockLayoutTree {
Tab selected = group.tabs().getSelectionModel().getSelectedItem();
return new DockLayoutView.Group(group.id(), group.tabs().getSide(),
group.tabs().getTabs().stream().map(tab -> (DockableId) tab.getUserData()).toList(),
selected == null ? null : (DockableId) selected.getUserData());
selected == null ? null : (DockableId) selected.getUserData(),
group.tabs() instanceof DockGroupPane pane && pane.isCollapsed());
}
}
@@ -40,6 +41,7 @@ final class DockLayoutTree {
private final SplitPane pane = new SplitPane();
private double position = .5;
private boolean dragging;
private boolean collapsedAllocation;
Split(Branch first, Branch second, Orientation orientation) {
this.first = first;
this.second = second;
@@ -127,6 +129,10 @@ final class DockLayoutTree {
}
boolean geometryEvent = event.getEventType() == MouseEvent.MOUSE_PRESSED
|| event.getEventType() == MouseEvent.MOUSE_DRAGGED || event.getEventType() == MouseEvent.MOUSE_RELEASED;
if (geometryEvent && split.collapsedAllocation) {
event.consume();
return;
}
if (geometryEvent && split.groups().stream().anyMatch(group -> !canResize.test(group.id()))) {
if (split.dragging) split.pane.setDividerPositions(split.position);
split.dragging = false;
@@ -156,6 +162,24 @@ final class DockLayoutTree {
return null;
}
boolean geometryAffects(DockGroupId id, java.util.function.Predicate<DockingManager.Group> protectedGroup) {
for (Root root : roots) {
Branch affected = geometryBranch(root.branch, null, id);
if (affected != null) return affected.groups().stream().anyMatch(protectedGroup);
}
return false;
}
private static Branch geometryBranch(Branch branch, Branch parent, DockGroupId id) {
if (branch instanceof Leaf leaf) {
if (!leaf.group.id().equals(id)) return null;
return parent == null ? leaf : parent;
}
Split split = (Split) branch;
Branch found = geometryBranch(split.first, split, id);
return found == null ? geometryBranch(split.second, split, id) : found;
}
boolean normalizationAffects(DockGroupId source, DockGroupId destination,
java.util.function.Predicate<DockingManager.Group> protectedGroup) {
if (find(source).groups().getFirst().tabs().getTabs().size() != 1) return false;
@@ -221,12 +245,44 @@ final class DockLayoutTree {
}
void captureGeometry() {
for (Root root : roots) allocateCollapsed(root.branch);
for (Root root : roots) captureGeometry(root.branch);
}
private static void allocateCollapsed(Branch branch) {
if (!(branch instanceof Split split)) return;
boolean firstCollapsed = DockGroupPane.allCollapsed(split.first.node());
boolean secondCollapsed = DockGroupPane.allCollapsed(split.second.node());
boolean allocate = firstCollapsed || secondCollapsed;
SplitPane.setResizableWithParent(split.first.node(), !firstCollapsed);
SplitPane.setResizableWithParent(split.second.node(), !secondCollapsed);
if (allocate) {
split.collapsedAllocation = true;
split.dragging = false;
boolean horizontal = split.pane.getOrientation() == Orientation.HORIZONTAL;
double span = horizontal ? split.pane.getWidth() : split.pane.getHeight();
double firstExtent = horizontal ? split.first.node().minWidth(-1) : split.first.node().minHeight(-1);
double secondExtent = horizontal ? split.second.node().minWidth(-1) : split.second.node().minHeight(-1);
if (span > 0) {
double position = firstCollapsed && secondCollapsed ? firstExtent / (firstExtent + secondExtent)
: firstCollapsed ? (firstExtent + 4) / span : 1 - (secondExtent + 4) / span;
split.pane.setDividerPositions(Math.max(0, Math.min(1, position)));
}
} else if (split.collapsedAllocation) {
split.collapsedAllocation = false;
split.pane.setDividerPositions(split.position);
}
split.pane.layout();
for (Node node : split.pane.lookupAll(".split-pane-divider")) {
if (divider(node, split.pane) == node) node.setVisible(!allocate);
}
allocateCollapsed(split.first);
allocateCollapsed(split.second);
}
private static void captureGeometry(Branch branch) {
if (branch instanceof Split split) {
if (!split.dragging && split.pane.getWidth() > 0 && split.pane.getHeight() > 0
if (!split.dragging && !split.collapsedAllocation && split.pane.getWidth() > 0 && split.pane.getHeight() > 0
&& !split.pane.getDividers().isEmpty()) {
split.position = split.pane.getDividers().getFirst().getPosition();
}
@@ -1,13 +1,16 @@
package de.neitzel.fx.docking;
import javafx.geometry.Side;
import javafx.geometry.Rectangle2D;
import java.util.List;
/** Immutable overview published after a completed layout change. */
public record DockLayoutView(List<Window> windows) {
public DockLayoutView { windows = List.copyOf(windows); }
public record Window(DockWindowId id, boolean main, List<Area> areas) {
/** Last committed floating-window bounds; main-window geometry belongs to the application. */
public record Window(DockWindowId id, boolean main, List<Area> areas, Rectangle2D bounds) {
public Window { areas = List.copyOf(areas); }
public Window(DockWindowId id, boolean main, List<Area> areas) { this(id, main, areas, null); }
}
/** Preferred side content extent; -1 means that dimension follows the available space. */
public record Area(DockAreaId id, List<Group> groups, LayoutNode root,
@@ -24,7 +27,10 @@ public record DockLayoutView(List<Window> windows) {
public record Split(javafx.geometry.Orientation orientation, double position,
LayoutNode first, LayoutNode second) implements LayoutNode { }
public record Group(DockGroupId id, Side tabSide, List<DockableId> dockableIds,
DockableId selectedDockableId) implements LayoutNode {
DockableId selectedDockableId, boolean collapsed) implements LayoutNode {
public Group { dockableIds = List.copyOf(dockableIds); }
public Group(DockGroupId id, Side tabSide, List<DockableId> dockableIds, DockableId selectedDockableId) {
this(id, tabSide, dockableIds, selectedDockableId, false);
}
}
}
@@ -10,6 +10,13 @@ public sealed interface DockTarget {
static DockTarget group(DockGroupId id, TabPosition position) { return new Group(id, position); }
static DockTarget group(DockGroupId id) { return group(id, TabPosition.append()); }
static DockTarget split(DockGroupId id, Side side) { return new Split(id, side); }
static DockTarget floating() { return new Floating(null); }
static DockTarget floating(javafx.geometry.Rectangle2D bounds) {
return new Floating(Objects.requireNonNull(bounds, "bounds"));
}
static DockTarget returnToMain() { return new ReturnToMain(); }
record Floating(javafx.geometry.Rectangle2D bounds) implements DockTarget { }
record ReturnToMain() implements DockTarget { }
record Split(DockGroupId id, Side side) implements DockTarget {
public Split { Objects.requireNonNull(id, "id"); Objects.requireNonNull(side, "side"); }
}
@@ -0,0 +1,39 @@
package de.neitzel.fx.docking;
import javafx.geometry.Rectangle2D;
import javafx.stage.Screen;
import javafx.stage.Stage;
/** Fits requested floating frames to the visible part of an available screen. */
final class DockWindowBounds {
private DockWindowBounds() { }
static Rectangle2D defaults(Stage main) {
Rectangle2D screen = Screen.getPrimary().getVisualBounds();
double x = Double.isFinite(main.getX()) ? main.getX() + 40 : screen.getMinX() + 40;
double y = Double.isFinite(main.getY()) ? main.getY() + 40 : screen.getMinY() + 40;
return new Rectangle2D(x, y, 600, 400);
}
static boolean valid(Rectangle2D bounds) {
return Double.isFinite(bounds.getMinX()) && Double.isFinite(bounds.getMinY())
&& Double.isFinite(bounds.getWidth()) && Double.isFinite(bounds.getHeight())
&& bounds.getWidth() > 0 && bounds.getHeight() > 0;
}
static Rectangle2D fit(Rectangle2D requested) {
Rectangle2D screen = Screen.getScreensForRectangle(requested).stream()
.max(java.util.Comparator.comparingDouble(candidate -> overlap(requested, candidate.getVisualBounds())))
.orElse(Screen.getPrimary()).getVisualBounds();
double width = Math.min(requested.getWidth(), screen.getWidth());
double height = Math.min(requested.getHeight(), screen.getHeight());
double x = Math.clamp(requested.getMinX(), screen.getMinX(), screen.getMaxX() - width);
double y = Math.clamp(requested.getMinY(), screen.getMinY(), screen.getMaxY() - height);
return new Rectangle2D(x, y, width, height);
}
private static double overlap(Rectangle2D first, Rectangle2D second) {
return Math.max(0, Math.min(first.getMaxX(), second.getMaxX()) - Math.max(first.getMinX(), second.getMinX()))
* Math.max(0, Math.min(first.getMaxY(), second.getMaxY()) - Math.max(first.getMinY(), second.getMinY()));
}
}
@@ -0,0 +1,105 @@
package de.neitzel.fx.docking;
import javafx.animation.AnimationTimer;
import javafx.beans.InvalidationListener;
import javafx.geometry.Rectangle2D;
import javafx.stage.Stage;
import java.util.Objects;
/** Commits floating geometry only after native mouse buttons are released. */
final class DockWindowGeometry {
private final Stage stage;
private final Runnable onCommitted;
private final InvalidationListener geometryChanged = observable -> changed();
private final InvalidationListener visibilityChanged = observable -> watch();
private final AnimationTimer timer = new AnimationTimer() {
@Override public void handle(long now) {
if (captureIfReady()) onCommitted.run();
}
};
private Rectangle2D bounds;
private boolean dirty;
private boolean running;
private boolean disposed;
DockWindowGeometry(Stage stage, Runnable onCommitted) {
this.stage = Objects.requireNonNull(stage, "stage");
this.onCommitted = Objects.requireNonNull(onCommitted, "onCommitted");
bounds = current();
stage.xProperty().addListener(geometryChanged);
stage.yProperty().addListener(geometryChanged);
stage.widthProperty().addListener(geometryChanged);
stage.heightProperty().addListener(geometryChanged);
stage.showingProperty().addListener(visibilityChanged);
stage.focusedProperty().addListener(visibilityChanged);
}
Rectangle2D bounds() { return bounds; }
/** Includes an unfinished gesture that has returned to its original frame size. */
boolean hasPendingChanges() { return dirty; }
/**
* Completes pending geometry for a manager publication without invoking its callback.
* A gesture returning to the same frame still completes, because child split positions may have changed.
*/
boolean captureIfReady() {
if (disposed) return false;
Rectangle2D current = current();
if (current == null) return false;
if (current.equals(bounds) && !dirty) {
stop();
return false;
}
NativeMouseButtons.State buttons = NativeMouseButtons.state();
if (buttons != NativeMouseButtons.State.UP) {
if (buttons == NativeMouseButtons.State.UNKNOWN) stop();
return false;
}
bounds = current;
dirty = false;
stop();
return true;
}
private Rectangle2D current() {
double x = stage.getX();
double y = stage.getY();
double width = stage.getWidth();
double height = stage.getHeight();
return Double.isFinite(x) && Double.isFinite(y) && Double.isFinite(width) && Double.isFinite(height)
&& width > 0 && height > 0 ? new Rectangle2D(x, y, width, height) : null;
}
private void changed() {
dirty = true;
watch();
}
private void watch() {
if (!disposed && dirty && stage.isShowing()) {
if (!running) {
running = true;
timer.start();
}
} else stop();
}
private void stop() {
running = false;
timer.stop();
}
void dispose() {
if (disposed) return;
disposed = true;
stop();
stage.xProperty().removeListener(geometryChanged);
stage.yProperty().removeListener(geometryChanged);
stage.widthProperty().removeListener(geometryChanged);
stage.heightProperty().removeListener(geometryChanged);
stage.showingProperty().removeListener(visibilityChanged);
stage.focusedProperty().removeListener(visibilityChanged);
}
}
@@ -13,6 +13,7 @@ import java.util.Objects;
/** Existing live content with stable identity and bindable tab presentation. */
public final class Dockable {
@Getter @Setter private boolean mainWindowOnly;
@Getter private final DockableId id;
@Getter private final Node content;
@Getter @Setter private Supplier<? extends Node> focusTarget;
@@ -22,6 +22,8 @@ public final class DockingManager {
private final Stage stage;
private final DockPane pane;
private final PlacementRule placementRule;
private final DockTarget fallbackTarget;
private final java.util.function.Consumer<FloatingWindowConfiguration> floatingWindowCustomizer;
private final DockDragController drag;
private final DockCloseCoordinator closing;
private boolean updating;
@@ -29,7 +31,13 @@ public final class DockingManager {
private final Map<DockGroupId, Long> groupActivationOrder = new LinkedHashMap<>();
private final DockLayoutTree tree = new DockLayoutTree(this::publish, id -> !groupClosing(group(id)));
private final Map<DockAreaId, javafx.geometry.Side> edgeAreas = new LinkedHashMap<>();
private final java.util.Set<DockGroupId> allocatedGroupIds = new java.util.HashSet<>();
private final java.util.Set<DockAreaId> allocatedAreaIds = new java.util.HashSet<>();
private long nextGroupId;
private long nextWindowId;
private final Map<DockWindowId, FloatingWindow> floatingWindows = new LinkedHashMap<>();
private final Map<DockGroupId, DockWindowId> groupWindows = new LinkedHashMap<>();
private final Map<DockableId, ReturnLocation> returnTargets = new LinkedHashMap<>();
private final Map<DockableId, Dockable> dockables = new LinkedHashMap<>();
private final Map<DockableId, Node> previousFocus = new LinkedHashMap<>();
private final Map<DockableId, Long> activationOrder = new LinkedHashMap<>();
@@ -43,10 +51,15 @@ public final class DockingManager {
this.pane = pane;
closing = new DockCloseCoordinator(new DockCloseCoordinator.Host() {
@Override public Optional<Dockable> find(DockableId id) { return findDockable(id); }
@Override public javafx.stage.Window owner(DockableId id) { return stage; }
@Override public javafx.stage.Window owner(DockableId id) { return DockingManager.this.owner(containing(id)); }
@Override public void remove(DockableId id) { removeDockable(id); }
});
this.placementRule = Objects.requireNonNull(options.getPlacementRule(), "placementRule");
this.fallbackTarget = options.getFallbackTarget();
if (fallbackTarget != null && !(fallbackTarget instanceof DockTarget.Area) && !(fallbackTarget instanceof DockTarget.Group)) {
throw new IllegalArgumentException("The return fallback must identify an existing main-window area or group");
}
this.floatingWindowCustomizer = Objects.requireNonNull(options.getFloatingWindowCustomizer(), "floatingWindowCustomizer");
DockLayout initial = Objects.requireNonNull(pane.getInitialLayout(), "initialLayout");
validate(initial);
addGroup(initial.getCenter(), pane.surface::setCenter);
@@ -54,7 +67,9 @@ public final class DockingManager {
addEdgeGroup(initial.getRight(), javafx.geometry.Side.RIGHT);
addEdgeGroup(initial.getTop(), javafx.geometry.Side.TOP);
addEdgeGroup(initial.getBottom(), javafx.geometry.Side.BOTTOM);
tree.view().forEach(area -> allocatedAreaIds.add(area.id()));
drag = new DockDragController(this, pane, () -> groups.values().stream()
.filter(group -> !groupWindows.containsKey(group.id))
.map(group -> new DockDragController.GroupSurface(group.id, group.tabs, pane.edgeOf(group.tabs))).toList());
refreshEmptyGroups();
publish();
@@ -88,7 +103,13 @@ public final class DockingManager {
if (dockable.getContent().getParent() != null || dockable.getContent().getScene() != null) {
return rejected(DockFailure.Code.CONTENT_ALREADY_ATTACHED, dockable.getId(), "Content already belongs to a scene graph");
}
Group group = receiver(destination);
Group group;
try {
group = receiver(destination);
} catch (FloatingPreparationFailure failure) {
return new ActionResult.Rejected(new DockFailure(DockFailure.Code.WINDOW_CREATION_FAILED,
dockable.getId(), "Floating window configuration failed", failure.getCause()));
}
int insertionIndex = destination instanceof ResolvedDockTarget.Insertion insertion ? insertion.index() : 0;
Tab tab = new Tab();
tab.setClosable(true);
@@ -100,13 +121,14 @@ public final class DockingManager {
tab.graphicProperty().bind(dockable.iconProperty());
tab.setContent(dockable.getContent());
tab.setUserData(dockable.getId());
drag.installTab(tab, dockable.getId());
dragFor(group).installTab(tab, dockable.getId());
dockables.put(dockable.getId(), dockable);
updating = true;
try {
group.tabs.getTabs().add(insertionIndex, tab);
group.tabs.getSelectionModel().select(tab);
refreshEmptyGroups();
revealGroup(group);
} finally {
updating = false;
}
@@ -149,9 +171,14 @@ public final class DockingManager {
requireFxThread();
Dockable dockable = dockables.get(id);
if (dockable == null) return rejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open");
if (((DockGroupPane) containing(id).tabs).isCollapsed() && !canChangeGroupGeometry(containing(id))) {
return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "Opening this group would resize a group awaiting close consent");
}
boolean revealed = revealGroup(containing(id));
Node target = focusTarget(dockable);
boolean changed = active.get() != dockable || stage.getScene().getFocusOwner() != target
|| (stage.isShowing() && !stage.isFocused());
Stage window = owner(containing(id));
boolean changed = revealed || active.get() != dockable || window.getScene().getFocusOwner() != target
|| (window.isShowing() && !window.isFocused());
for (Group group : groups.values()) {
for (Tab tab : group.tabs.getTabs()) {
if (id.equals(tab.getUserData())) {
@@ -166,7 +193,7 @@ public final class DockingManager {
}
}
setActive(dockable);
if (stage.isShowing()) stage.toFront();
if (window.isShowing()) window.toFront();
focus(dockable);
if (changed) publish();
return changed ? new ActionResult.Applied() : new ActionResult.NoChange();
@@ -191,7 +218,7 @@ public final class DockingManager {
boolean wasActive = active.get() == dockables.get(id);
updating = true;
try {
drag.uninstallTab(tab);
dragFor(group).uninstallTab(tab);
tab.textProperty().unbind();
tab.graphicProperty().unbind();
tab.setGraphic(null);
@@ -200,6 +227,7 @@ public final class DockingManager {
dockables.remove(id);
previousFocus.remove(id);
activationOrder.remove(id);
returnTargets.remove(id);
normalizeLayout(group.id);
} finally {
updating = false;
@@ -207,7 +235,8 @@ public final class DockingManager {
if (wasActive) {
Tab selected = group.tabs.getSelectionModel().getSelectedItem();
if (selected == null) {
selected = groups.values().stream().map(candidate -> candidate.tabs.getSelectionModel().getSelectedItem())
selected = groups.values().stream().filter(this::isGroupVisible)
.map(candidate -> candidate.tabs.getSelectionModel().getSelectedItem())
.filter(Objects::nonNull)
.max(java.util.Comparator.comparingLong(candidate ->
activationOrder.getOrDefault((DockableId) candidate.getUserData(), 0L)))
@@ -238,11 +267,19 @@ public final class DockingManager {
DockGroupId destination = switch (allowed.destination()) {
case ResolvedDockTarget.Insertion insertion -> insertion.groupId();
case ResolvedDockTarget.Split split -> split.groupId();
case ResolvedDockTarget.Detachment ignored -> null;
};
if (tree.normalizationAffects(containing(id).id, destination, this::groupClosing)) {
if (treeFor(containing(id)).normalizationAffects(containing(id).id, destination, this::groupClosing)) {
return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id,
"Removing this tab would resize a group covered by a close request");
}
Group source = containing(id);
if (source.tabs.getTabs().size() == 1 && !source.id.equals(destination)
&& (source.definition.isReleaseSpaceWhenEmpty() || !source.definition.isPersistent())
&& !canChangeGroupGeometry(source)) {
return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id,
"Emptying this group would resize a group awaiting close consent");
}
}
return check;
}
@@ -254,17 +291,37 @@ public final class DockingManager {
if (check instanceof MoveCheck.NoChange) return new ActionResult.NoChange();
var destination = ((MoveCheck.Allowed) check).destination();
Group source = containing(id);
Group receiver = receiver(destination);
Group receiver;
try {
receiver = receiver(destination);
} catch (FloatingPreparationFailure failure) {
return new ActionResult.Rejected(new DockFailure(DockFailure.Code.WINDOW_CREATION_FAILED,
id, "Floating window configuration failed", failure.getCause()));
}
if (!groupWindows.containsKey(source.id) && groupWindows.containsKey(receiver.id)) {
int index = tabIndex(source, id);
TabPosition position = index + 1 < source.tabs.getTabs().size()
? TabPosition.before((DockableId) source.tabs.getTabs().get(index + 1).getUserData())
: index > 0 ? TabPosition.after((DockableId) source.tabs.getTabs().get(index - 1).getUserData())
: TabPosition.append();
returnTargets.put(id, new ReturnLocation(DockTarget.group(source.id, position),
new DockAreaId(source.definition.getDestinationId())));
}
DockDragController sourceDrag = dragFor(source);
DockDragController receiverDrag = dragFor(receiver);
int insertionIndex = destination instanceof ResolvedDockTarget.Insertion insertion ? insertion.index() : 0;
Tab tab = source.tabs.getTabs().get(tabIndex(source, id));
updating = true;
try {
tab.setContent(null);
if (sourceDrag != receiverDrag) sourceDrag.uninstallTab(tab);
source.tabs.getTabs().remove(tab);
receiver.tabs.getTabs().add(insertionIndex, tab);
if (sourceDrag != receiverDrag) receiverDrag.installTab(tab, id);
tab.setContent(dockables.get(id).getContent());
receiver.tabs.getSelectionModel().select(tab);
normalizeLayout(source.id);
revealGroup(receiver);
} finally {
updating = false;
}
@@ -277,11 +334,40 @@ public final class DockingManager {
private MoveCheck resolve(Dockable dockable, DockTarget target) {
DockableId id = dockable.getId();
Objects.requireNonNull(target, "target");
if (target instanceof DockTarget.Floating floating) {
javafx.geometry.Rectangle2D bounds = floating.bounds() == null
? DockWindowBounds.defaults(stage)
: floating.bounds();
if (!DockWindowBounds.valid(bounds)) return moveRejected(DockFailure.Code.INVALID_WINDOW_BOUNDS, id,
"Floating bounds must be finite with positive dimensions");
return checkPlacement(dockable, new ResolvedDockTarget.Detachment(DockWindowBounds.fit(bounds)));
}
if (target instanceof DockTarget.ReturnToMain) {
Group source = containing(id);
if (source != null && !groupWindows.containsKey(source.id)) return new MoveCheck.NoChange();
ReturnLocation remembered = returnTargets.get(id);
if (remembered != null) {
MoveCheck result = resolveMainTarget(dockable, remembered.target());
if (!(result instanceof MoveCheck.Rejected)) return result;
if (((MoveCheck.Rejected) result).failure().code() == DockFailure.Code.TARGET_NOT_FOUND) {
MoveCheck areaResult = resolveMainTarget(dockable, DockTarget.area(remembered.areaId()));
if (!(areaResult instanceof MoveCheck.Rejected)) return areaResult;
}
}
if (fallbackTarget != null) return resolveMainTarget(dockable, fallbackTarget);
List<DockLayoutView.Area> mainAreas = tree.view();
return mainAreas.isEmpty() ? moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "No main-window destination")
: resolveMainTarget(dockable, DockTarget.area(mainAreas.getFirst().id()));
}
if (target instanceof DockTarget.Split split) {
Group receiver = group(split.id());
if (receiver == null) return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "Destination does not exist");
if (groupClosing(receiver)) return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "A close request covers this group");
if (containing(id) == receiver && receiver.tabs.getTabs().size() == 1) return new MoveCheck.NoChange();
if (((DockGroupPane) receiver.tabs).isCollapsed() && !canChangeGroupGeometry(receiver)) {
return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id,
"Opening this group would resize a group awaiting close consent");
}
if (!receiver.definition.getSplitDirections().allows(split.side())) {
return moveRejected(DockFailure.Code.SPLIT_DISABLED, id, "Splitting is disabled in this direction");
}
@@ -296,7 +382,9 @@ public final class DockingManager {
return checkPlacement(dockable, new ResolvedDockTarget.Split(receiver.id, split.side()));
}
if (target instanceof DockTarget.Area area) {
List<Group> candidates = tree.groups(area.id()).stream().sorted(java.util.Comparator
List<Group> candidates = java.util.stream.Stream.concat(java.util.stream.Stream.of(tree),
floatingWindows.values().stream().map(FloatingWindow::tree))
.flatMap(candidate -> candidate.groups(area.id()).stream()).sorted(java.util.Comparator
.comparingLong((Group candidate) -> groupActivationOrder.getOrDefault(candidate.id, 0L)).reversed()).toList();
MoveCheck rejected = moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "Destination does not exist");
for (Group candidate : candidates) {
@@ -328,12 +416,37 @@ public final class DockingManager {
if (index > oldIndex) index--;
if (index == oldIndex) return new MoveCheck.NoChange();
}
if (((DockGroupPane) receiver.tabs).isCollapsed() && !canChangeGroupGeometry(receiver)) {
return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id,
"Opening this group would resize a group awaiting close consent");
}
var resolved = new ResolvedDockTarget.Insertion(receiver.id, index);
return checkPlacement(dockable, resolved);
}
private MoveCheck resolveMainTarget(Dockable dockable, DockTarget target) {
MoveCheck result = resolve(dockable, target);
if (result instanceof MoveCheck.NoChange && groupWindows.containsKey(containing(dockable.getId()).id)) {
return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, dockable.getId(), "The return destination is not in the main window");
}
if (result instanceof MoveCheck.Allowed allowed
&& allowed.destination() instanceof ResolvedDockTarget.Insertion insertion
&& groupWindows.containsKey(insertion.groupId())) {
return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, dockable.getId(), "The return destination is not in the main window");
}
return result;
}
private MoveCheck checkPlacement(Dockable dockable, ResolvedDockTarget resolved) {
DockableId id = dockable.getId();
boolean floating = switch (resolved) {
case ResolvedDockTarget.Detachment ignored -> true;
case ResolvedDockTarget.Insertion insertion -> groupWindows.containsKey(insertion.groupId());
case ResolvedDockTarget.Split split -> groupWindows.containsKey(split.groupId());
};
if (dockable.isMainWindowOnly() && floating) {
return moveRejected(DockFailure.Code.MAIN_WINDOW_ONLY, id, "This Dockable must remain in the main window");
}
try {
Optional<DockFailure> failure = Objects.requireNonNull(placementRule.check(dockable, resolved), "Placement rule result");
if (failure.isPresent()) return new MoveCheck.Rejected(failure.get());
@@ -345,11 +458,134 @@ public final class DockingManager {
}
private void normalizeLayout(DockGroupId source) {
for (DockGroupId id : tree.normalize(source)) {
DockWindowId ownerId = groupWindows.get(source);
for (DockGroupId id : treeFor(group(source)).normalize(source)) {
groups.remove(id);
groupWindows.remove(id);
groupActivationOrder.remove(id);
}
refreshEmptyGroups();
if (ownerId != null && groups.values().stream().filter(group -> ownerId.equals(groupWindows.get(group.id)))
.allMatch(group -> group.tabs.getTabs().isEmpty())) {
FloatingWindow empty = floatingWindows.remove(ownerId);
empty.drag.dispose();
empty.geometry.dispose();
empty.stage.getScene().focusOwnerProperty().removeListener(focusListener);
empty.stage.hide();
empty.pane.manager = null;
empty.stage.getProperties().remove(ATTACHMENT_KEY);
var remaining = groups.keySet().stream().filter(id -> ownerId.equals(groupWindows.get(id))).toList();
remaining.forEach(id -> { groups.remove(id); groupWindows.remove(id); groupActivationOrder.remove(id); });
}
}
/** Applies explicitly supplied settings as one validated group change. */
public ActionResult updateGroup(DockGroupId id, DockGroupChanges changes) {
requireFxThread();
Objects.requireNonNull(changes, "changes");
Group group = group(Objects.requireNonNull(id, "id"));
if (group == null) return rejected(DockFailure.Code.TARGET_NOT_FOUND, null, "Group does not exist");
if (groupClosing(group)) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "A close request covers this group");
DockGroupChanges resolved = changes.resolved(group.definition);
DockGroupDefinition candidate = new DockGroupDefinition(group.definition.getDestinationId());
resolved.applyTo(candidate);
try {
validate(candidate, new java.util.HashSet<>());
} catch (IllegalArgumentException failure) {
return rejected(DockFailure.Code.INVALID_GROUP_CONFIGURATION, null, failure.getMessage());
}
DockEdgeRegion extentOwner = null;
for (Node ancestor = group.tabs.getParent(); ancestor != null; ancestor = ancestor.getParent()) {
if (ancestor instanceof DockEdgeRegion edge) {
extentOwner = edge;
break;
}
}
boolean changesExtent = extentOwner != null
&& extentOwner.changesPreferredExtent(changes.getPreferredWidth(), changes.getPreferredHeight());
if (!changesExtent && resolved.equals(DockGroupChanges.builder().build().resolved(group.definition))) {
return new ActionResult.NoChange();
}
DockGroupDefinition existing = group.definition;
boolean changesGeometry = changesExtent || existing.getTabSide() != candidate.getTabSide()
|| existing.getPreferredWidth() != candidate.getPreferredWidth()
|| existing.getPreferredHeight() != candidate.getPreferredHeight()
|| existing.getMinimumWidth() != candidate.getMinimumWidth()
|| existing.getMinimumHeight() != candidate.getMinimumHeight()
|| (group.tabs.getTabs().isEmpty() && (existing.isVisibleWhenEmpty() != candidate.isVisibleWhenEmpty()
|| existing.isReleaseSpaceWhenEmpty() != candidate.isReleaseSpaceWhenEmpty()))
|| (((DockGroupPane) group.tabs).isCollapsed() && !candidate.isCollapsible());
if (changesGeometry && !canChangeGroupGeometry(group, true)) {
return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "The group change would resize content covered by a close request");
}
boolean wasUpdating = updating;
updating = true;
try {
resolved.applyTo(group.definition);
group.tabs.setSide(candidate.getTabSide());
group.tabs.requestLayout();
if (extentOwner != null) {
extentOwner.updatePreferredExtent(changes.getPreferredWidth(), changes.getPreferredHeight());
}
if (!candidate.isCollapsible() && revealGroup(group)) {
Tab selected = group.tabs.getSelectionModel().getSelectedItem();
if (selected != null) {
setActive(dockables.get((DockableId) selected.getUserData()));
focus(active.get());
}
}
refreshEmptyGroups();
} finally {
updating = wasUpdating;
}
publish();
return new ActionResult.Applied();
}
public ActionResult setGroupCollapsed(DockGroupId id, boolean collapsed) {
requireFxThread();
Group group = group(Objects.requireNonNull(id, "id"));
if (group == null) return rejected(DockFailure.Code.TARGET_NOT_FOUND, null, "Group does not exist");
if (groupClosing(group)) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "A close request covers this group");
if (collapsed && !group.definition.isCollapsible()) {
return rejected(DockFailure.Code.COLLAPSE_DISABLED, null, "This group cannot be collapsed");
}
DockGroupPane tabs = (DockGroupPane) group.tabs;
if (tabs.isCollapsed() == collapsed) return new ActionResult.NoChange();
if (!canChangeGroupGeometry(group)) {
return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "The group change would resize content covered by a close request");
}
tabs.setCollapsed(collapsed);
if (collapsed) {
if (active.get() != null && containing(active.get().getId()) == group) setActive(selectedVisibleFallback());
tabs.focusSelectedHeader();
} else {
Tab selected = tabs.getSelectionModel().getSelectedItem();
if (selected != null) {
setActive(dockables.get((DockableId) selected.getUserData()));
focus(active.get());
}
}
publish();
return new ActionResult.Applied();
}
private boolean revealGroup(Group group) {
DockGroupPane tabs = (DockGroupPane) group.tabs;
if (!tabs.isCollapsed()) return false;
tabs.setCollapsed(false);
return true;
}
private boolean isGroupVisible(Group group) {
return group.tabs.isVisible() && !((DockGroupPane) group.tabs).isCollapsed();
}
private Dockable selectedVisibleFallback() {
return groups.values().stream().filter(this::isGroupVisible)
.map(candidate -> candidate.tabs.getSelectionModel().getSelectedItem()).filter(Objects::nonNull)
.max(java.util.Comparator.comparingLong(tab -> activationOrder.getOrDefault((DockableId) tab.getUserData(), 0L)))
.map(tab -> dockables.get((DockableId) tab.getUserData())).orElse(null);
}
private void refreshEmptyGroups() {
@@ -389,7 +625,35 @@ public final class DockingManager {
edgeAreas.put(new DockAreaId(definition.getDestinationId()), side);
DockAreaId areaId = new DockAreaId(definition.getDestinationId());
addGroup(definition, node -> pane.setArea(side, node,
() -> tree.groups(areaId).stream().noneMatch(this::groupClosing), this::publish));
() -> canResizeEdge(areaId, side), this::publish));
}
private boolean canResizeEdge(DockAreaId areaId, javafx.geometry.Side side) {
if (tree.groups(areaId).stream().anyMatch(this::groupClosing)) return false;
for (Group candidate : groups.values()) {
if (groupWindows.containsKey(candidate.id) || !groupClosing(candidate)) continue;
if (contains(pane.surface.getCenter(), candidate.tabs)) return false;
javafx.geometry.Side otherSide = pane.edgeOf(candidate.tabs);
if (side.isHorizontal() && otherSide != null && otherSide.isVertical()) return false;
}
return true;
}
private boolean canChangeGroupGeometry(Group group) {
return canChangeGroupGeometry(group, false);
}
private boolean canChangeGroupGeometry(Group group, boolean changingOuterExtent) {
if (treeFor(group).geometryAffects(group.id, this::groupClosing)) return false;
if (groupWindows.containsKey(group.id)) return true;
for (var entry : edgeAreas.entrySet()) {
List<Group> areaGroups = tree.groups(entry.getKey());
if (!areaGroups.contains(group)) continue;
boolean onlyExpandedGroup = areaGroups.stream().filter(candidate -> candidate != group)
.allMatch(candidate -> !candidate.tabs.isManaged() || ((DockGroupPane) candidate.tabs).isCollapsed());
if (changingOuterExtent || onlyExpandedGroup) return canResizeEdge(entry.getKey(), entry.getValue());
}
return true;
}
private void addGroup(DockLayoutNode definition, java.util.function.Consumer<javafx.scene.Node> place) {
@@ -407,16 +671,18 @@ public final class DockingManager {
captured.setMinimumHeight(definition.getMinimumHeight());
captured.setSplitDirections(definition.getSplitDirections());
captured.setPersistent(definition.isPersistent());
captured.setCollapsible(definition.isCollapsible());
captured.setVisibleWhenEmpty(definition.isVisibleWhenEmpty());
captured.setReleaseSpaceWhenEmpty(definition.isReleaseSpaceWhenEmpty());
TabPane tabs = new TabPane();
TabPane tabs = new DockGroupPane(captured);
tabs.setSide(captured.getTabSide());
tabs.setPrefSize(captured.getPreferredWidth(), captured.getPreferredHeight());
tabs.setMinSize(captured.getMinimumWidth(), captured.getMinimumHeight());
Group group = new Group(id, tabs, captured);
allocatedGroupIds.add(id);
groups.put(id, group);
((DockGroupPane) tabs).installHeaderActions(tab -> activate((DockableId) tab.getUserData()),
() -> setGroupCollapsed(id, true));
tabs.getSelectionModel().selectedItemProperty().addListener((observable, old, selected) -> {
if (!updating && selected != null) {
if (!updating && selected != null && isGroupVisible(group)) {
setActive(dockables.get((DockableId) selected.getUserData()));
focus(active.get());
publish();
@@ -427,12 +693,15 @@ public final class DockingManager {
private Group receiver(ResolvedDockTarget destination) {
if (destination instanceof ResolvedDockTarget.Insertion insertion) return group(insertion.groupId());
if (destination instanceof ResolvedDockTarget.Detachment detachment) return createFloatingGroup(detachment.bounds());
ResolvedDockTarget.Split split = (ResolvedDockTarget.Split) destination;
Group target = group(split.groupId());
DockGroupId id;
do { id = new DockGroupId("group-" + ++nextGroupId); } while (groups.containsKey(id));
do { id = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(id));
Group added = createGroup(id, target.definition);
tree.split(target, added, split.side());
DockWindowId window = groupWindows.get(target.id);
if (window != null) groupWindows.put(added.id, window);
treeFor(target).split(target, added, split.side());
return added;
}
@@ -449,7 +718,7 @@ public final class DockingManager {
private void rememberFocus(Node current) {
if (current == null) return;
for (Dockable dockable : dockables.values()) {
if (contains(dockable.getContent(), current)) {
if (contains(dockable.getContent(), current) && isGroupVisible(containing(dockable.getId()))) {
previousFocus.put(dockable.getId(), current);
setActive(dockable);
return;
@@ -472,7 +741,14 @@ public final class DockingManager {
private void focus(Dockable dockable) {
if (dockable == null) return;
pane.applyCss();
Stage window = owner(containing(dockable.getId()));
window.getScene().getRoot().applyCss();
window.getScene().getRoot().layout();
if (window != stage && !window.isShowing()) window.show();
if (window.isShowing()) {
window.toFront();
window.requestFocus();
}
Node target = focusTarget(dockable);
target.requestFocus();
}
@@ -524,6 +800,12 @@ public final class DockingManager {
stage.getScene().getRoot().applyCss();
stage.getScene().getRoot().layout();
tree.captureGeometry();
for (FloatingWindow window : floatingWindows.values()) {
window.pane.applyCss();
window.pane.layout();
window.geometry.captureIfReady();
if (!window.geometry.hasPendingChanges()) window.tree.captureGeometry();
}
} finally {
updating = wasUpdating;
}
@@ -534,9 +816,78 @@ public final class DockingManager {
return new DockLayoutView.Area(area.id(), area.groups(), area.root(),
side.isVertical() ? extent : -1, side.isHorizontal() ? extent : -1);
}).toList();
layout.set(new DockLayoutView(List.of(new DockLayoutView.Window(new DockWindowId("main"), true, areas))));
var windows = new java.util.ArrayList<DockLayoutView.Window>();
windows.add(new DockLayoutView.Window(new DockWindowId("main"), true, areas));
floatingWindows.values().forEach(window -> windows.add(new DockLayoutView.Window(
window.id, false, window.tree.view(), window.geometry.bounds())));
layout.set(new DockLayoutView(windows));
}
private Stage owner(Group group) {
DockWindowId id = group == null ? null : groupWindows.get(group.id);
return id == null ? stage : floatingWindows.get(id).stage;
}
private DockLayoutTree treeFor(Group group) {
DockWindowId id = groupWindows.get(group.id);
return id == null ? tree : floatingWindows.get(id).tree;
}
private DockDragController dragFor(Group group) {
DockWindowId id = groupWindows.get(group.id);
return id == null ? drag : floatingWindows.get(id).drag;
}
private Group createFloatingGroup(javafx.geometry.Rectangle2D bounds) {
FloatingWindowConfiguration configuration = new FloatingWindowConfiguration();
try {
floatingWindowCustomizer.accept(configuration);
configuration.getIcons().forEach(Objects::requireNonNull);
configuration.getStylesheets().forEach(Objects::requireNonNull);
} catch (RuntimeException failure) {
throw new FloatingPreparationFailure(failure);
}
DockWindowId candidateId;
do { candidateId = new DockWindowId("floating-" + ++nextWindowId); }
while (!allocatedAreaIds.add(new DockAreaId(candidateId.value())));
DockWindowId windowId = candidateId;
DockPane floatingPane = new DockPane();
Stage floatingStage = new Stage();
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
floatingStage.setTitle(configuration.getTitle());
floatingStage.getIcons().setAll(configuration.getIcons());
floatingStage.getScene().getStylesheets().setAll(configuration.getStylesheets());
floatingStage.setX(bounds.getMinX());
floatingStage.setY(bounds.getMinY());
floatingStage.setWidth(bounds.getWidth());
floatingStage.setHeight(bounds.getHeight());
DockLayoutTree floatingTree = new DockLayoutTree(this::publish, id -> !groupClosing(group(id)));
DockGroupId groupId;
do { groupId = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(groupId));
DockGroupDefinition definition = new DockGroupDefinition(windowId.value());
definition.setPersistent(false);
Group group = createGroup(groupId, definition);
groupWindows.put(group.id, windowId);
floatingTree.addArea(definition, floatingPane.surface::setCenter, ignored -> group);
DockDragController floatingDrag = new DockDragController(this, floatingPane, () -> groups.values().stream()
.filter(candidate -> windowId.equals(groupWindows.get(candidate.id)))
.map(candidate -> new DockDragController.GroupSurface(candidate.id, candidate.tabs)).toList());
DockWindowGeometry geometry = new DockWindowGeometry(floatingStage, this::publish);
floatingWindows.put(windowId, new FloatingWindow(windowId, floatingStage, floatingPane, floatingTree, floatingDrag, geometry));
floatingPane.manager = this;
floatingStage.getProperties().put(ATTACHMENT_KEY, this);
floatingStage.getScene().focusOwnerProperty().addListener(focusListener);
return group;
}
private static final class FloatingPreparationFailure extends RuntimeException {
FloatingPreparationFailure(RuntimeException cause) { super(cause); }
}
private record FloatingWindow(DockWindowId id, Stage stage, DockPane pane, DockLayoutTree tree,
DockDragController drag, DockWindowGeometry geometry) { }
private record ReturnLocation(DockTarget target, DockAreaId areaId) { }
private static ActionResult rejected(DockFailure.Code code, DockableId id, String message) {
return new ActionResult.Rejected(new DockFailure(code, id, message, null));
}
@@ -8,4 +8,6 @@ import java.util.Optional;
@Getter @Setter
public final class DockingOptions {
private PlacementRule placementRule = (dockable, target) -> Optional.empty();
private DockTarget fallbackTarget;
private java.util.function.Consumer<FloatingWindowConfiguration> floatingWindowCustomizer = configuration -> { };
}
@@ -0,0 +1,15 @@
package de.neitzel.fx.docking;
import javafx.scene.image.Image;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/** Appearance supplied before a managed window appears; its Stage and Scene remain manager-owned. */
public final class FloatingWindowConfiguration {
@Getter @Setter private String title = "Docking";
@Getter private final List<Image> icons = new ArrayList<>();
@Getter private final List<String> stylesheets = new ArrayList<>();
}
@@ -0,0 +1,176 @@
package de.neitzel.fx.docking;
import lombok.extern.slf4j.Slf4j;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
/** Narrow, read-only native mouse state. Unknown input state never means release. */
@Slf4j
final class NativeMouseButtons {
enum State { DOWN, UP, UNKNOWN }
@FunctionalInterface private interface Query { State sample() throws Throwable; }
private static boolean failed;
private NativeMouseButtons() { }
private static final class Backend {
private static final Query QUERY = create();
}
/** Called on the JavaFX thread by floating-window geometry trackers. */
static State state() {
if (failed || Backend.QUERY == null) return State.UNKNOWN;
try {
return Backend.QUERY.sample();
} catch (Throwable failure) {
if (failure instanceof Error error) throw error;
failed = true;
log.warn("Native mouse state failed; floating-window geometry remains at its last committed bounds", failure);
return State.UNKNOWN;
}
}
private static Query create() {
try {
String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
if (os.contains("mac")) return mac();
if (os.contains("win")) return windows();
if (os.contains("linux") && !present("WAYLAND_DISPLAY")
&& !"wayland".equalsIgnoreCase(System.getenv("XDG_SESSION_TYPE"))
&& !"wayland".equalsIgnoreCase(System.getenv("GDK_BACKEND")) && present("DISPLAY")) return x11();
log.warn("Native mouse-state observation is unavailable for this desktop backend; floating-window bounds remain committed");
} catch (RuntimeException | LinkageError failure) {
log.warn("Native mouse-state observation is unavailable; enable native access for the library module. Floating-window bounds remain committed", failure);
} catch (Throwable failure) {
if (failure instanceof Error error) throw error;
log.warn("Native mouse-state initialization failed; floating-window bounds remain committed", failure);
}
return null;
}
private static boolean present(String name) {
String value = System.getenv(name);
return value != null && !value.isBlank();
}
private static Query mac() {
Linker linker = Linker.nativeLinker();
if (!ValueLayout.JAVA_BOOLEAN.equals(linker.canonicalLayouts().get("bool"))) {
throw new IllegalStateException("Unsupported CoreGraphics bool ABI");
}
// The String overload also loads frameworks supplied only by the macOS dyld cache.
SymbolLookup library = SymbolLookup.libraryLookup(
"/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics", Arena.global());
MethodHandle button = linker.downcallHandle(library.findOrThrow("CGEventSourceButtonState"),
FunctionDescriptor.of(ValueLayout.JAVA_BOOLEAN, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
return () -> {
// Combined-session state includes accessibility and posted input; check both primary mappings and middle.
for (int number = 0; number <= 2; number++) {
if ((boolean) button.invokeExact(0, number)) return State.DOWN;
}
return State.UP;
};
}
private static Query windows() {
Linker linker = Linker.nativeLinker();
SymbolLookup library = SymbolLookup.libraryLookup("user32.dll", Arena.global());
MethodHandle button = linker.downcallHandle(library.findOrThrow("GetAsyncKeyState"),
FunctionDescriptor.of(ValueLayout.JAVA_SHORT, ValueLayout.JAVA_INT));
MethodHandle foreground = linker.downcallHandle(library.findOrThrow("GetForegroundWindow"),
FunctionDescriptor.of(ValueLayout.ADDRESS));
MethodHandle owner = linker.downcallHandle(library.findOrThrow("GetWindowThreadProcessId"),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
return () -> {
// Physical buttons, including swapped primary buttons and the two extra buttons.
for (int key : new int[] {1, 2, 4, 5, 6}) {
if ((short) button.invokeExact(key) < 0) return State.DOWN;
}
// A zero key state can mean inaccessible input. Accept up only for our foreground process.
MemorySegment window = (MemorySegment) foreground.invokeExact();
if (window.equals(MemorySegment.NULL)) return State.UNKNOWN;
try (Arena arena = Arena.ofConfined()) {
MemorySegment process = arena.allocate(ValueLayout.JAVA_INT);
int thread = (int) owner.invokeExact(window, process);
return thread != 0 && Integer.toUnsignedLong(process.get(ValueLayout.JAVA_INT, 0)) == ProcessHandle.current().pid()
? State.UP : State.UNKNOWN;
}
};
}
/** Both shutdown and sampling hold this monitor before accessing the display. */
private static final class X11ConnectionState {
private boolean closed;
}
private static Query x11() throws Throwable {
Linker linker = Linker.nativeLinker();
if (!ValueLayout.JAVA_LONG.equals(linker.canonicalLayouts().get("long"))) {
throw new IllegalStateException("Unsupported X11 Window ABI");
}
SymbolLookup library = SymbolLookup.libraryLookup("libX11.so.6", Arena.global());
MethodHandle open = linker.downcallHandle(library.findOrThrow("XOpenDisplay"),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS));
MethodHandle root = linker.downcallHandle(library.findOrThrow("XDefaultRootWindow"),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
MethodHandle query = linker.downcallHandle(library.findOrThrow("XQueryPointer"),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.JAVA_LONG,
ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.ADDRESS,
ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
MethodHandle close = linker.downcallHandle(library.findOrThrow("XCloseDisplay"),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS));
X11ConnectionState connection = new X11ConnectionState();
MemorySegment display = (MemorySegment) open.invokeExact(MemorySegment.NULL);
if (display.equals(MemorySegment.NULL)) throw new IllegalStateException("Cannot open the X11 display");
try {
long rootWindow = (long) root.invokeExact(display);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
synchronized (connection) {
if (connection.closed) return;
connection.closed = true;
try { int ignored = (int) close.invokeExact(display); }
catch (Throwable failure) {
if (failure instanceof Error error) throw error;
log.debug("Closing native mouse-state X11 connection failed", failure);
}
}
}, "docking-mouse-state-cleanup"));
return () -> {
synchronized (connection) {
if (connection.closed) return State.UNKNOWN;
try (Arena arena = Arena.ofConfined()) {
MemorySegment rootResult = arena.allocate(ValueLayout.JAVA_LONG);
MemorySegment child = arena.allocate(ValueLayout.JAVA_LONG);
MemorySegment rootX = arena.allocate(ValueLayout.JAVA_INT);
MemorySegment rootY = arena.allocate(ValueLayout.JAVA_INT);
MemorySegment windowX = arena.allocate(ValueLayout.JAVA_INT);
MemorySegment windowY = arena.allocate(ValueLayout.JAVA_INT);
MemorySegment mask = arena.allocate(ValueLayout.JAVA_INT);
int valid = (int) query.invokeExact(display, rootWindow, rootResult, child,
rootX, rootY, windowX, windowY, mask);
if (valid == 0) return State.UNKNOWN;
return (mask.get(ValueLayout.JAVA_INT, 0) & 0x1f00) != 0 ? State.DOWN : State.UP;
}
}
};
} catch (Throwable failure) {
synchronized (connection) {
if (!connection.closed) {
connection.closed = true;
try { int ignored = (int) close.invokeExact(display); }
catch (Throwable cleanup) {
if (cleanup != failure) failure.addSuppressed(cleanup);
}
}
}
throw failure;
}
}
}
@@ -2,6 +2,7 @@ package de.neitzel.fx.docking;
/** Concrete placement checked against the current layout, without allocating IDs. */
public sealed interface ResolvedDockTarget {
record Detachment(javafx.geometry.Rectangle2D bounds) implements ResolvedDockTarget { }
record Split(DockGroupId groupId, javafx.geometry.Side side) implements ResolvedDockTarget { }
record Insertion(DockGroupId groupId, int index) implements ResolvedDockTarget { }
}