Restore and reset docking layouts transactionally with localized diagnostics

This commit is contained in:
2026-11-15 23:48:27 +01:00
parent fb5603eb76
commit 853c6c0115
39 changed files with 2465 additions and 42 deletions
@@ -69,16 +69,16 @@ final class DockDragController {
String headerId = "dock-tab-" + ++nextHeaderId;
tab.setId(headerId);
headers.put(headerId, id);
Menu destinations = new Menu("Move to");
Menu splits = new Menu("Split");
MenuItem close = new MenuItem("Close");
Menu destinations = new Menu(manager.message("dock.action.move"));
Menu splits = new Menu(manager.message("dock.action.split"));
MenuItem close = new MenuItem(manager.message("dock.action.close"));
close.setOnAction(event -> manager.requestTabClose(id));
javafx.scene.control.CheckMenuItem pin = new javafx.scene.control.CheckMenuItem("Pin group");
javafx.scene.control.CheckMenuItem pin = new javafx.scene.control.CheckMenuItem(manager.message("dock.action.pin"));
pin.setOnAction(event -> currentGroup(id).ifPresent(group -> manager.updateGroup(group.id(),
DockGroupChanges.builder().mode(group.mode() == DockGroupMode.DOCKED
? DockGroupMode.OVERLAY : DockGroupMode.DOCKED).build())));
ContextMenu menu = new ContextMenu(destinations, splits, close,
new MenuItem("Float"), new MenuItem("Return to main"), pin);
new MenuItem(manager.message("dock.action.float")), new MenuItem(manager.message("dock.action.return")), pin);
menu.setOnShowing(event -> {
currentGroup(id).ifPresent(group -> {
pin.setSelected(group.mode() == DockGroupMode.DOCKED);
@@ -86,8 +86,8 @@ final class DockDragController {
});
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()));
menu.getItems().set(3, moveItem(manager.message("dock.action.float"), id, DockTarget.floating()));
menu.getItems().set(4, moveItem(manager.message("dock.action.return"), id, DockTarget.returnToMain()));
});
tab.setContextMenu(menu);
}
@@ -130,12 +130,7 @@ final class DockDragController {
.flatMap(area -> area.groups().stream()).filter(group -> group.dockableIds().contains(id))
.findFirst().ifPresent(group -> {
for (Side side : Side.values()) {
String label = switch (side) {
case TOP -> "Above";
case RIGHT -> "Right";
case BOTTOM -> "Below";
case LEFT -> "Left";
};
String label = manager.message("dock.side." + side.name());
menu.getItems().add(moveItem(label, id, DockTarget.split(group.id(), side)));
}
});
@@ -144,8 +139,9 @@ final class DockDragController {
private MenuItem moveItem(String label, DockableId id, DockTarget target) {
MoveCheck check = manager.checkMove(id, target);
if (check instanceof MoveCheck.Rejected rejected) label += " (" + rejected.failure().message() + ")";
else if (check instanceof MoveCheck.NoChange) label += " (Already here)";
if (check instanceof MoveCheck.Rejected rejected) label = manager.message("dock.action.unavailable", label,
manager.describeFailure(rejected.failure()));
else if (check instanceof MoveCheck.NoChange) label = manager.message("dock.action.noChange", label);
MenuItem item = new MenuItem(label);
item.setDisable(!(check instanceof MoveCheck.Allowed));
item.setOnAction(event -> manager.move(id, target));
@@ -220,7 +216,7 @@ final class DockDragController {
floatingFrame.setFill(javafx.scene.paint.Color.rgb(80, 140, 220, .16));
floatingFrame.setStroke(javafx.scene.paint.Color.rgb(50, 110, 190));
floatingFrame.setStrokeType(javafx.scene.shape.StrokeType.INSIDE);
javafx.scene.control.Label label = new javafx.scene.control.Label("Float");
javafx.scene.control.Label label = new javafx.scene.control.Label(manager.message("dock.action.float"));
label.getStyleClass().add("dock-floating-preview-label");
javafx.scene.layout.StackPane preview = new javafx.scene.layout.StackPane(floatingFrame, label);
preview.getStyleClass().add("dock-floating-preview");
@@ -134,6 +134,7 @@ final class DockEdgeRegion extends Region {
: split.getInsets().getTop() + split.getInsets().getBottom());
}
Side side() { return side; }
boolean isResizing() { return dragging; }
@Override protected double computePrefWidth(double height) {
return side.isVertical() ? displayedExtent() + dividerSize() : content == null ? 0 : content.prefWidth(height);
@@ -1,8 +1,13 @@
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 { INVALID_GROUP_CONFIGURATION, COLLAPSE_DISABLED, SPLIT_DISABLED, SPLIT_TOO_SMALL, TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED,
public record DockFailure(Code code, DockableId dockableId, String message, Throwable cause, String messageKey) {
/** Preserves the direct-message form for failures without an application resource key. */
public DockFailure(Code code, DockableId dockableId, String message, Throwable cause) {
this(code, dockableId, message, cause, null);
}
public enum Code { LAYOUT_CHANGE_IN_PROGRESS, RESTORE_REQUIRES_EMPTY_MANAGER, UNSUPPORTED_SNAPSHOT_VERSION, INVALID_SNAPSHOT, UNSUPPORTED_SNAPSHOT_FEATURE, DOCKABLE_LOAD_FAILED, MISSING_DOCKABLE, 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 }
}
@@ -10,6 +10,8 @@ final class DockGroupSurface extends Region {
private DockPane host;
private double expandedWidth;
private double expandedHeight;
private double committedWidth;
private double committedHeight;
DockGroupSurface(DockGroupPane tabs, DockGroupDefinition definition) {
this.tabs = tabs;
@@ -25,6 +27,14 @@ final class DockGroupSurface extends Region {
double expandedWidth() { return expandedWidth > 0 ? expandedWidth : definition.getPreferredWidth(); }
double expandedHeight() { return expandedHeight > 0 ? expandedHeight : definition.getPreferredHeight(); }
double[] snapshotSize(boolean preserveGeometry) {
if (!preserveGeometry || committedWidth <= 0 || committedHeight <= 0) {
committedWidth = expandedWidth();
committedHeight = expandedHeight();
}
return new double[]{committedWidth, committedHeight};
}
boolean spansEdgeExtent(javafx.geometry.Side side) {
for (Node current = getParent(); current != null && !(current instanceof DockEdgeRegion); current = current.getParent()) {
if (current instanceof javafx.scene.control.SplitPane split
@@ -0,0 +1,66 @@
package de.neitzel.fx.docking;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
/** Detached controls and ID-only placement plans shared by restore and live reset. */
final class DockLayoutCandidate {
final LayoutSnapshot.Window window;
final DockLayoutTree tree;
private final Map<DockGroupId, DockingManager.Group> groups = new LinkedHashMap<>();
private final Map<DockGroupId, List<DockableId>> orders = new LinkedHashMap<>();
private final Map<DockGroupId, DockableId> selections = new LinkedHashMap<>();
DockLayoutCandidate(LayoutSnapshot.Window window, Function<LayoutSnapshot.Group, DockingManager.Group> factory,
Runnable geometryChanged, Predicate<DockGroupId> canResize) {
this.window = window;
tree = new DockLayoutTree(geometryChanged, canResize);
for (LayoutSnapshot.Root root : window.roots()) {
tree.addSnapshot(root.branch(), node -> { }, state -> {
DockingManager.Group group = factory.apply(state);
groups.put(group.id(), group);
orders.put(group.id(), new ArrayList<>(state.tabs()));
selections.put(group.id(), state.selected());
return group;
});
}
}
List<LayoutSnapshot.Root> roots() {
Map<DockAreaId, javafx.geometry.Side> edges = new LinkedHashMap<>();
window.roots().stream().filter(root -> root.placement() != LayoutSnapshot.Placement.CENTER)
.forEach(root -> root.branch().aliases().forEach(alias -> edges.put(alias,
javafx.geometry.Side.valueOf(root.placement().name()))));
return tree.snapshotRoots(edges).stream().map(root -> {
LayoutSnapshot.Root original = window.roots().stream()
.filter(candidate -> candidate.placement() == root.placement()).findFirst().orElseThrow();
return new LayoutSnapshot.Root(root.placement(), original.preferredWidth(), original.preferredHeight(), root.branch());
}).toList();
}
void normalize() {
for (DockGroupId id : List.copyOf(groups.keySet())) {
if (!orders.containsKey(id) || !orders.get(id).isEmpty()) continue;
for (DockGroupId removed : tree.normalize(id, group -> orders.get(group.id()).isEmpty())) {
groups.remove(removed);
orders.remove(removed);
selections.remove(removed);
}
}
}
List<DockingManager.Group> groups() { return List.copyOf(groups.values()); }
List<DockingManager.Group> groups(DockAreaId area) { return tree.groups(area); }
List<DockableId> tabs(DockGroupId group) { return List.copyOf(orders.get(group)); }
DockableId selected(DockGroupId group) { return selections.get(group); }
void select(DockGroupId group, DockableId selected) { selections.put(group, selected); }
void place(DockableId id, DockGroupId group, int index) {
orders.values().forEach(order -> order.remove(id));
List<DockableId> order = orders.get(group);
order.add(Math.max(0, Math.min(order.size(), index)), id);
}
}
@@ -83,6 +83,44 @@ final class DockLayoutTree {
place.accept(branch.node());
}
void addSnapshot(LayoutSnapshot.Branch state, Consumer<Node> place,
java.util.function.Function<LayoutSnapshot.Group, DockingManager.Group> factory) {
Branch branch = buildSnapshot(state, factory);
roots.add(new Root(branch, place));
render(branch);
place.accept(branch.node());
}
private Branch buildSnapshot(LayoutSnapshot.Branch state,
java.util.function.Function<LayoutSnapshot.Group, DockingManager.Group> factory) {
Branch branch;
if (state instanceof LayoutSnapshot.Group group) branch = new Leaf(factory.apply(group));
else {
LayoutSnapshot.Split stateSplit = (LayoutSnapshot.Split) state;
Split split = split(buildSnapshot(stateSplit.first(), factory), buildSnapshot(stateSplit.second(), factory),
stateSplit.orientation());
split.position = stateSplit.position();
branch = split;
}
state.aliases().forEach(alias -> areas.put(alias, branch));
return branch;
}
void clear() {
detach();
roots.clear();
areas.clear();
}
void installFrom(DockLayoutTree candidate, List<Consumer<Node>> placements) {
clear();
areas.putAll(candidate.areas);
for (int i = 0; i < candidate.roots.size(); i++) {
roots.add(new Root(candidate.roots.get(i).branch, placements.get(i)));
}
render();
}
private Branch build(DockLayoutNode definition,
java.util.function.Function<DockGroupDefinition, DockingManager.Group> groupFactory) {
DockAreaId id = new DockAreaId(definition.getDestinationId());
@@ -201,15 +239,19 @@ final class DockLayoutTree {
}
List<DockGroupId> normalize(DockGroupId source) {
return normalize(source, group -> group.tabs().getTabs().isEmpty());
}
List<DockGroupId> normalize(DockGroupId source, java.util.function.Predicate<DockingManager.Group> isEmpty) {
Branch emptied = find(source);
if (!empty(emptied)) return List.of();
if (emptied == null || !empty(emptied, isEmpty)) return List.of();
detach();
List<DockGroupId> removed = new ArrayList<>();
for (var iterator = roots.iterator(); iterator.hasNext();) {
Root root = iterator.next();
boolean affected = includes(root.branch, emptied);
root.branch = normalize(root.branch, emptied, removed);
if (affected && root.branch instanceof Leaf leaf && empty(leaf)
root.branch = normalize(root.branch, emptied, removed, isEmpty);
if (affected && root.branch instanceof Leaf leaf && empty(leaf, isEmpty)
&& !leaf.group.definition().isPersistent()) {
areas.entrySet().removeIf(entry -> entry.getValue() == leaf);
removed.add(leaf.group.id());
@@ -220,12 +262,13 @@ final class DockLayoutTree {
return List.copyOf(removed);
}
private Branch normalize(Branch branch, Branch emptied, List<DockGroupId> removed) {
private Branch normalize(Branch branch, Branch emptied, List<DockGroupId> removed,
java.util.function.Predicate<DockingManager.Group> isEmpty) {
if (!(branch instanceof Split split) || !includes(branch, emptied)) return branch;
split.first = normalize(split.first, emptied, removed);
split.second = normalize(split.second, emptied, removed);
boolean firstEmpty = empty(split.first);
boolean secondEmpty = empty(split.second);
split.first = normalize(split.first, emptied, removed, isEmpty);
split.second = normalize(split.second, emptied, removed, isEmpty);
boolean firstEmpty = empty(split.first, isEmpty);
boolean secondEmpty = empty(split.second, isEmpty);
if (!firstEmpty && !secondEmpty) return split;
Branch survivor = firstEmpty && !secondEmpty ? split.second : split.first;
Branch discarded = survivor == split.first ? split.second : split.first;
@@ -240,8 +283,8 @@ final class DockLayoutTree {
return branch instanceof Split split && (includes(split.first, target) || includes(split.second, target));
}
private static boolean empty(Branch branch) {
return branch.groups().stream().allMatch(group -> group.tabs().getTabs().isEmpty());
private static boolean empty(Branch branch, java.util.function.Predicate<DockingManager.Group> isEmpty) {
return branch.groups().stream().allMatch(isEmpty);
}
/** Reuses the live overlay dimensions when its group starts reserving space again. */
@@ -279,6 +322,43 @@ final class DockLayoutTree {
if (!split.collapsedAllocation) split.pane.setDividerPositions(position);
}
boolean isResizing() { return roots.stream().anyMatch(root -> isResizing(root.branch)); }
private static boolean isResizing(Branch branch) {
return branch instanceof Split split && (split.dragging || isResizing(split.first) || isResizing(split.second));
}
List<LayoutSnapshot.Root> snapshotRoots(Map<DockAreaId, Side> edgeAreas) {
return snapshotRoots(edgeAreas, false);
}
List<LayoutSnapshot.Root> snapshotRoots(Map<DockAreaId, Side> edgeAreas, boolean preserveGeometry) {
return roots.stream().map(root -> {
Side side = edgeAreas.entrySet().stream().filter(entry -> areas.get(entry.getKey()) == root.branch)
.map(Map.Entry::getValue).findFirst().orElse(null);
LayoutSnapshot.Placement placement = side == null ? LayoutSnapshot.Placement.CENTER
: LayoutSnapshot.Placement.valueOf(side.name());
return new LayoutSnapshot.Root(placement, -1, -1, snapshot(root.branch, preserveGeometry));
}).toList();
}
private LayoutSnapshot.Branch snapshot(Branch branch, boolean preserveGeometry) {
List<DockAreaId> aliases = areas.entrySet().stream().filter(entry -> entry.getValue() == branch)
.map(Map.Entry::getKey).toList();
if (branch instanceof Split split) {
return new LayoutSnapshot.Split(aliases, split.pane.getOrientation(), split.position,
snapshot(split.first, preserveGeometry), snapshot(split.second, preserveGeometry));
}
DockingManager.Group group = ((Leaf) branch).group;
DockGroupPane tabs = (DockGroupPane) group.tabs();
Tab selected = tabs.getSelectionModel().getSelectedItem();
double[] size = tabs.surface().snapshotSize(preserveGeometry);
return new LayoutSnapshot.Group(aliases, group.id(), new DockAreaId(group.definition().getDestinationId()),
LayoutSnapshot.GroupSettings.capture(group.definition()), tabs.isCollapsed(),
size[0], size[1],
tabs.getTabs().stream().map(tab -> (DockableId) tab.getUserData()).toList(),
selected == null ? null : (DockableId) selected.getUserData());
}
void captureGeometry() {
for (Root root : roots) allocateCollapsed(root.branch);
for (Root root : roots) captureGeometry(root.branch);
@@ -0,0 +1,47 @@
package de.neitzel.fx.docking;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.ResourceBundle;
/** Captures application wording and keeps presentation separate from diagnostic failures. */
final class DockMessages {
private final ResourceBundle defaults = ResourceBundle.getBundle("de.neitzel.fx.docking.Docking", Locale.ROOT);
private final Map<String, String> overrides;
private final Locale locale;
DockMessages(ResourceBundle resources) {
Map<String, String> captured = new HashMap<>();
if (resources != null) {
for (String key : resources.keySet()) {
if (resources.getObject(key) instanceof String text) captured.put(key, text);
}
}
overrides = Map.copyOf(captured);
locale = resources == null || resources.getLocale() == null ? Locale.ROOT : resources.getLocale();
}
String text(String key) {
if (overrides.containsKey(key)) return overrides.get(key);
return defaults.containsKey(key) ? defaults.getString(key) : defaults.getString("dock.failure.generic");
}
String format(String key, Object... values) {
return new MessageFormat(text(key), locale).format(values);
}
String failure(DockFailure failure) {
Objects.requireNonNull(failure, "failure");
String codeKey = "dock.failure." + failure.code().name();
String applicationKey = failure.messageKey();
if (applicationKey != null && !applicationKey.isBlank()) {
return overrides.getOrDefault(applicationKey, text(codeKey));
}
if (overrides.containsKey(codeKey)) return overrides.get(codeKey);
// Keep the existing direct-message API useful when no localization key was supplied.
return failure.message() == null || failure.message().isBlank() ? text(codeKey) : failure.message();
}
}
@@ -58,6 +58,22 @@ public final class DockPane extends Region {
}
}
void clearAreas() {
surface.setCenter(null);
surface.setLeft(null);
surface.setRight(null);
surface.setTop(null);
surface.setBottom(null);
edgeAreas.clear();
}
void setAreaExtent(Side side, double width, double height) {
DockEdgeRegion area = edgeAreas.get(side);
if (area != null) area.updatePreferredExtent(width > 0 ? width : null, height > 0 ? height : null);
}
boolean isResizing() { return edgeAreas.values().stream().anyMatch(DockEdgeRegion::isResizing); }
double committedExtent(Side side) {
DockEdgeRegion area = edgeAreas.get(side);
return area == null ? -1 : area.committedExtent();
@@ -0,0 +1,89 @@
package de.neitzel.fx.docking;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.function.BiFunction;
/** Plans initial destinations using IDs only; live content is untouched until installation. */
final class DockResetPlan {
private DockResetPlan() { }
static DockFailure prepare(DockLayoutCandidate candidate, List<Dockable> contents,
Map<DockableId, DockAreaId> initialIntents, DockTarget configuredFallback,
BiFunction<Dockable, ResolvedDockTarget, MoveCheck> check) {
DockTarget fallback = configuredFallback;
if (fallback == null && !candidate.window.roots().isEmpty()) {
List<DockAreaId> aliases = candidate.window.roots().getFirst().branch().aliases();
if (!aliases.isEmpty()) fallback = DockTarget.area(aliases.getFirst());
}
List<Dockable> fallbackContents = new ArrayList<>();
for (Dockable dockable : contents) {
DockAreaId intended = initialIntents.get(dockable.getId());
DockFailure failure = place(candidate, dockable, intended == null ? null : DockTarget.area(intended), check);
if (failure != null) {
if (fallback == null) return failure;
fallbackContents.add(dockable);
}
}
// Home placements establish reference tabs before relative fallback positions are resolved.
for (Dockable dockable : fallbackContents) {
DockFailure failure = place(candidate, dockable, fallback, check);
if (failure != null) return failure;
}
// Relative fallback positions can shift earlier insertions; validate the completed plan too.
for (DockingManager.Group group : candidate.groups()) {
List<DockableId> order = candidate.tabs(group.id());
for (int index = 0; index < order.size(); index++) {
DockableId id = order.get(index);
Dockable dockable = contents.stream().filter(content -> content.getId().equals(id)).findFirst().orElseThrow();
MoveCheck checked = check.apply(dockable, new ResolvedDockTarget.Insertion(group.id(), index));
if (checked instanceof MoveCheck.Rejected rejected) return affected(rejected.failure(), dockable.getId());
}
}
return null;
}
private static DockFailure place(DockLayoutCandidate candidate, Dockable dockable, DockTarget target,
BiFunction<Dockable, ResolvedDockTarget, MoveCheck> check) {
List<DockingManager.Group> destinations = switch (target) {
case null -> List.of();
case DockTarget.Area area -> candidate.groups(area.id());
case DockTarget.Group concrete -> candidate.groups().stream().filter(group -> group.id().equals(concrete.id())).toList();
default -> List.of();
};
DockFailure firstFailure = null;
for (DockingManager.Group group : destinations) {
List<DockableId> order = candidate.tabs(group.id());
int index = order.size();
if (target instanceof DockTarget.Group concrete) {
DockableId reference = switch (concrete.position()) {
case TabPosition.Before before -> before.id();
case TabPosition.After after -> after.id();
case TabPosition.Append ignored -> null;
};
if (reference != null) {
index = order.indexOf(reference);
if (index < 0) return new DockFailure(DockFailure.Code.REFERENCE_TAB_NOT_FOUND,
dockable.getId(), "Reset fallback reference tab is not in its destination", null);
if (concrete.position() instanceof TabPosition.After) index++;
}
}
MoveCheck result = check.apply(dockable, new ResolvedDockTarget.Insertion(group.id(), index));
if (result instanceof MoveCheck.Allowed) {
candidate.place(dockable.getId(), group.id(), index);
candidate.select(group.id(), dockable.getId());
return null;
}
if (firstFailure == null && result instanceof MoveCheck.Rejected rejected) {
firstFailure = affected(rejected.failure(), dockable.getId());
}
}
return firstFailure == null ? new DockFailure(DockFailure.Code.TARGET_NOT_FOUND,
dockable.getId(), "No eligible reset destination exists", null) : firstFailure;
}
private static DockFailure affected(DockFailure failure, DockableId id) {
return new DockFailure(failure.code(), id, failure.message(), failure.cause(), failure.messageKey());
}
}
@@ -0,0 +1,73 @@
package de.neitzel.fx.docking;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/** Owns prepared resolver results until they are either installed or discarded exactly once. */
record DockRestorePreparation(Map<DockableId, Dockable> contents, RestoreResult.Rejected rejection) {
static DockRestorePreparation resolve(DockLayoutCandidate candidate, DockableResolver resolver,
java.util.function.BiFunction<Dockable, ResolvedDockTarget, MoveCheck> placement) {
Map<DockableId, Dockable> prepared = new LinkedHashMap<>();
var contentNodes = Collections.newSetFromMap(new IdentityHashMap<javafx.scene.Node, Boolean>());
for (DockingManager.Group group : candidate.groups()) {
int index = 0;
for (DockableId id : candidate.tabs(group.id())) {
DockableResolution resolution;
try {
resolution = Objects.requireNonNull(resolver.resolve(id), "Resolver returned no resolution");
} catch (RuntimeException failure) {
return rejected(prepared, new DockFailure(DockFailure.Code.DOCKABLE_LOAD_FAILED,
id, "Dockable loading failed", failure));
}
if (resolution instanceof DockableResolution.Failed failed) {
return rejected(prepared, new DockFailure(DockFailure.Code.DOCKABLE_LOAD_FAILED,
id, "Dockable loading failed", failed.cause()));
}
if (resolution instanceof DockableResolution.Missing) {
return rejected(prepared, new DockFailure(DockFailure.Code.MISSING_DOCKABLE,
id, "Missing-ID restoration is not available in this milestone", null));
}
Dockable dockable = ((DockableResolution.Available) resolution).dockable();
if (dockable == null) return rejected(prepared, new DockFailure(DockFailure.Code.DOCKABLE_LOAD_FAILED,
id, "Resolver returned an empty available result", null));
if (dockable.getContent().getParent() != null || dockable.getContent().getScene() != null) {
return rejected(prepared, new DockFailure(DockFailure.Code.CONTENT_ALREADY_ATTACHED,
id, "Attached content retains its existing owner", null));
}
prepared.put(id, dockable);
if (!id.equals(dockable.getId())) return rejected(prepared, new DockFailure(
DockFailure.Code.ID_MISMATCH, id, "Resolver returned a different Dockable identity", null));
if (!contentNodes.add(dockable.getContent())) {
return rejected(prepared, new DockFailure(DockFailure.Code.CONTENT_ALREADY_ATTACHED,
id, "Resolved content is attached or shared by another prepared Dockable", null));
}
MoveCheck checked = placement.apply(dockable, new ResolvedDockTarget.Insertion(group.id(), index++));
if (checked instanceof MoveCheck.Rejected rejected) {
DockFailure failure = rejected.failure();
return rejected(prepared, new DockFailure(failure.code(), id, failure.message(), failure.cause(), failure.messageKey()));
}
}
}
return new DockRestorePreparation(Collections.unmodifiableMap(new LinkedHashMap<>(prepared)), null);
}
static DockRestorePreparation rejected(Map<DockableId, Dockable> prepared, DockFailure primary) {
List<DockFailure> cleanup = new ArrayList<>();
var discarded = Collections.newSetFromMap(new IdentityHashMap<Dockable, Boolean>());
for (Dockable dockable : prepared.values()) {
if (!discarded.add(dockable) || dockable.getOnDiscarded() == null) continue;
try {
dockable.getOnDiscarded().run();
} catch (RuntimeException failure) {
cleanup.add(new DockFailure(DockFailure.Code.CLEANUP_FAILED, dockable.getId(),
"Prepared Dockable cleanup failed", failure));
}
}
return new DockRestorePreparation(Map.of(), new RestoreResult.Rejected(primary, cleanup));
}
}
@@ -0,0 +1,91 @@
package de.neitzel.fx.docking;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
/** Checks the complete data graph before any application resolver or live layout is touched. */
final class DockSnapshotValidation {
private DockSnapshotValidation() { }
static DockFailure validate(LayoutSnapshot snapshot, Consumer<LayoutSnapshot.Group> validateSettings) {
if (snapshot.version() != LayoutSnapshot.CURRENT_VERSION) {
return new DockFailure(DockFailure.Code.UNSUPPORTED_SNAPSHOT_VERSION, null,
"Unsupported layout snapshot version: " + snapshot.version(), null);
}
try {
Set<DockWindowId> windows = new HashSet<>();
Set<DockAreaId> aliases = new HashSet<>();
Set<DockGroupId> groups = new HashSet<>();
Set<DockableId> contents = new HashSet<>();
Set<DockableId> selected = new HashSet<>();
int mainWindows = 0;
for (LayoutSnapshot.Window window : snapshot.windows()) {
require(windows.add(Objects.requireNonNull(window.id())), "Duplicate window identity");
if (window.main()) {
mainWindows++;
require(window.id().equals(new DockWindowId("main")) && window.bounds() == null,
"The main window uses its canonical identity and application-owned bounds");
} else {
var bounds = Objects.requireNonNull(window.bounds(), "Floating bounds are required");
require(Double.isFinite(bounds.getMinX()) && Double.isFinite(bounds.getMinY())
&& positive(bounds.getWidth()) && positive(bounds.getHeight()), "Invalid floating bounds");
}
Set<LayoutSnapshot.Placement> placements = new HashSet<>();
for (LayoutSnapshot.Root root : window.roots()) {
require(placements.add(Objects.requireNonNull(root.placement())), "Duplicate root placement");
require(extent(root.preferredWidth()) && extent(root.preferredHeight()), "Invalid root extent");
require(!root.branch().aliases().isEmpty(), "A root requires a stable area alias");
validate(root.branch(), aliases, groups, contents, selected, validateSettings);
}
}
require(mainWindows == 1 && snapshot.windows().getFirst().main(), "Exactly one first main window is required");
require(snapshot.activeDockableId() == null || selected.contains(snapshot.activeDockableId()),
"Active Dockable must be a selected stored Dockable");
snapshot.initialIntents().forEach((id, area) -> {
require(contents.contains(id), "Initial intent refers to an unknown Dockable");
Objects.requireNonNull(area);
});
snapshot.returnPositions().forEach((id, position) -> {
require(contents.contains(id), "Return position refers to an unknown Dockable");
require(position.target() instanceof DockTarget.Area || position.target() instanceof DockTarget.Group,
"A return position must identify an area or group");
Objects.requireNonNull(position.areaId(), "Return area is required");
});
return null;
} catch (RuntimeException invalid) {
return new DockFailure(DockFailure.Code.INVALID_SNAPSHOT, null,
"Invalid layout snapshot: " + invalid.getMessage(), invalid);
}
}
private static void validate(LayoutSnapshot.Branch branch, Set<DockAreaId> aliases, Set<DockGroupId> groups,
Set<DockableId> contents, Set<DockableId> selected,
Consumer<LayoutSnapshot.Group> validateSettings) {
for (DockAreaId alias : branch.aliases()) require(aliases.add(alias), "Duplicate area alias");
if (branch instanceof LayoutSnapshot.Split split) {
Objects.requireNonNull(split.orientation(), "Split orientation is required");
require(Double.isFinite(split.position()) && split.position() > 0 && split.position() < 1,
"Split proportion must lie between zero and one");
validate(split.first(), aliases, groups, contents, selected, validateSettings);
validate(split.second(), aliases, groups, contents, selected, validateSettings);
} else {
LayoutSnapshot.Group group = (LayoutSnapshot.Group) branch;
require(groups.add(Objects.requireNonNull(group.id())), "Duplicate group identity");
Objects.requireNonNull(group.originArea(), "Group origin is required");
validateSettings.accept(group);
require(!group.collapsed() || group.settings().collapsible(), "A noncollapsible group cannot be collapsed");
require(positive(group.expandedWidth()) && positive(group.expandedHeight()), "Invalid remembered group size");
for (DockableId id : group.tabs()) require(contents.add(id), "Duplicate Dockable identity");
require(group.selected() == null || group.tabs().contains(group.selected()), "Selection refers to a missing tab");
if (group.selected() != null) selected.add(group.selected());
}
}
private static boolean positive(double value) { return Double.isFinite(value) && value > 0; }
private static boolean extent(double value) { return value == -1 || positive(value); }
private static void require(boolean condition, String message) {
if (!condition) throw new IllegalArgumentException(message);
}
}
@@ -0,0 +1,8 @@
package de.neitzel.fx.docking;
/** Resolving stored identity distinguishes available content, absence and a technical load failure. */
public sealed interface DockableResolution {
record Available(Dockable dockable) implements DockableResolution { }
record Missing() implements DockableResolution { }
record Failed(Throwable cause) implements DockableResolution { }
}
@@ -0,0 +1,7 @@
package de.neitzel.fx.docking;
/** Prepares fresh application content for a stored Dockable identity. */
@FunctionalInterface
public interface DockableResolver {
DockableResolution resolve(DockableId id);
}
@@ -22,23 +22,28 @@ public final class DockingManager {
private final Stage stage;
private final DockPane pane;
private final PlacementRule placementRule;
private final DockMessages messages;
private final DockTarget fallbackTarget;
private final java.util.function.Consumer<FloatingWindowConfiguration> floatingWindowCustomizer;
private final DockDragController drag;
private final DockCloseCoordinator closing;
private boolean updating;
private boolean layoutChanging;
private final Map<DockGroupId, Group> groups = new LinkedHashMap<>();
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 final java.util.Set<DockAreaId> initialAreaIds = new java.util.HashSet<>();
private final LayoutSnapshot.Window initialWindow;
private long nextGroupId;
private long nextWindowId;
private long nextWindowFocusOrder;
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, DockAreaId> initialIntents = 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<>();
@@ -46,10 +51,12 @@ public final class DockingManager {
private final javafx.beans.value.ChangeListener<Node> focusListener = (observable, old, current) -> rememberFocus(current);
private final ReadOnlyObjectWrapper<Dockable> active = new ReadOnlyObjectWrapper<>(this, "activeDockable");
private final ReadOnlyObjectWrapper<DockLayoutView> layout = new ReadOnlyObjectWrapper<>(this, "layout");
private LayoutSnapshot publishedSnapshot;
private DockingManager(Stage stage, DockPane pane, DockingOptions options) {
this.stage = stage;
this.pane = pane;
this.messages = new DockMessages(options.getResourceBundle());
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 DockingManager.this.owner(containing(id)); }
@@ -77,11 +84,13 @@ public final class DockingManager {
addEdgeGroup(initial.getTop(), javafx.geometry.Side.TOP);
addEdgeGroup(initial.getBottom(), javafx.geometry.Side.BOTTOM);
tree.view().forEach(area -> allocatedAreaIds.add(area.id()));
initialAreaIds.addAll(allocatedAreaIds);
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();
initialWindow = snapshot().windows().getFirst();
stage.getScene().focusOwnerProperty().addListener(focusListener);
}
@@ -104,6 +113,7 @@ public final class DockingManager {
public ActionResult open(Dockable dockable, DockTarget target) {
requireFxThread();
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
Objects.requireNonNull(dockable, "dockable");
if (dockables.containsKey(dockable.getId())) return activate(dockable.getId());
MoveCheck check = resolve(dockable, target);
@@ -120,16 +130,7 @@ public final class DockingManager {
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);
tab.setOnCloseRequest(event -> {
event.consume();
requestTabClose(dockable.getId());
});
tab.textProperty().bind(dockable.titleProperty());
tab.graphicProperty().bind(dockable.iconProperty());
tab.setContent(dockable.getContent());
tab.setUserData(dockable.getId());
Tab tab = prepareTab(dockable);
dragFor(group).installTab(tab, dockable.getId());
dockables.put(dockable.getId(), dockable);
updating = true;
@@ -143,13 +144,31 @@ public final class DockingManager {
}
setActive(dockable);
focus(dockable);
DockAreaId initialArea = target instanceof DockTarget.Area area && initialAreaIds.contains(area.id())
? area.id() : new DockAreaId(group.definition.getDestinationId());
if (initialAreaIds.contains(initialArea)) initialIntents.put(dockable.getId(), initialArea);
publish();
return new ActionResult.Applied();
}
private Tab prepareTab(Dockable dockable) {
Tab tab = new Tab();
tab.setClosable(true);
tab.setOnCloseRequest(event -> {
event.consume();
requestTabClose(dockable.getId());
});
tab.textProperty().bind(dockable.titleProperty());
tab.graphicProperty().bind(dockable.iconProperty());
tab.setContent(dockable.getContent());
tab.setUserData(dockable.getId());
return tab;
}
/** Creates content only for a new identity; rejected prepared content is discarded. */
public ActionResult open(DockableId id, java.util.function.Supplier<? extends Dockable> factory, DockTarget target) {
requireFxThread();
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
Objects.requireNonNull(id, "id");
Objects.requireNonNull(factory, "factory");
if (dockables.containsKey(id)) return activate(id);
@@ -163,6 +182,7 @@ public final class DockingManager {
ActionResult result = id.equals(prepared.getId()) ? open(prepared, target)
: rejected(DockFailure.Code.ID_MISMATCH, id, "Factory returned a different Dockable ID");
if (result instanceof ActionResult.Rejected rejected && !dockables.containsValue(prepared)
&& prepared.getContent().getParent() == null && prepared.getContent().getScene() == null
&& prepared.getOnDiscarded() != null) {
try {
prepared.getOnDiscarded().run();
@@ -170,14 +190,49 @@ public final class DockingManager {
DockFailure failure = rejected.failure();
var cause = new IllegalStateException("Cleanup failed after rejected open", failure.cause());
cause.addSuppressed(cleanup);
return new ActionResult.Rejected(new DockFailure(failure.code(), failure.dockableId(), failure.message(), cause));
return new ActionResult.Rejected(new DockFailure(failure.code(), failure.dockableId(), failure.message(), cause, failure.messageKey()));
}
}
return result;
}
/** Restores the captured starting arrangement while retaining every live Dockable. */
public ActionResult resetLayout() {
requireFxThread();
if (layoutChanging) return rejected(DockFailure.Code.LAYOUT_CHANGE_IN_PROGRESS, null,
"A layout replacement is already being prepared");
if (closing.scope() != null) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null,
"Cannot reset while close consent is pending");
layoutChanging = true;
try {
LayoutSnapshot.Window reset = LayoutSnapshot.remapGroups(initialWindow, original -> {
if (groups.containsKey(original)) return original;
DockGroupId fresh;
do { fresh = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(fresh));
return fresh;
});
DockLayoutCandidate candidate = prepareLayoutCandidate(reset);
Map<DockableId, Dockable> retained = new LinkedHashMap<>(dockables);
DockFailure failure = DockResetPlan.prepare(candidate, List.copyOf(retained.values()),
initialIntents, fallbackTarget, this::checkPlacement);
if (failure != null) return new ActionResult.Rejected(failure);
candidate.normalize();
DockableId activeId = active.get() == null ? null : active.get().getId();
if (activeId != null) {
candidate.groups().stream().filter(group -> candidate.tabs(group.id).contains(activeId))
.findFirst().ifPresent(group -> candidate.select(group.id, activeId));
}
returnTargets.clear();
installLayoutCandidate(candidate, retained, activeId);
return new ActionResult.Applied();
} finally {
layoutChanging = false;
}
}
public ActionResult activate(DockableId id) {
requireFxThread();
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
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))) {
@@ -210,14 +265,23 @@ public final class DockingManager {
public Optional<Dockable> findDockable(DockableId id) { return Optional.ofNullable(dockables.get(id)); }
/** Uses the same captured language settings and fallback as built-in menu rejection text. */
public String describeFailure(DockFailure failure) { return messages.failure(failure); }
String message(String key) { return messages.text(key); }
String message(String key, Object... values) { return messages.format(key, values); }
/** Requests consent without closing or releasing content while the answer is pending. */
public java.util.concurrent.CompletionStage<CloseResult> requestTabClose(DockableId id) {
requireFxThread();
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
return closing.requestTabClose(id);
}
/** Requests every contained Dockable's consent before closing a floating window. */
public java.util.concurrent.CompletionStage<CloseResult> requestFloatingWindowClose(DockWindowId id) {
requireFxThread();
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
Objects.requireNonNull(id, "id");
if (layout.get().windows().getFirst().id().equals(id)) {
return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(
@@ -250,6 +314,7 @@ public final class DockingManager {
previousFocus.remove(id);
activationOrder.remove(id);
returnTargets.remove(id);
initialIntents.remove(id);
normalizeLayout(group.id);
}
} finally {
@@ -272,6 +337,7 @@ public final class DockingManager {
}
private boolean groupClosing(Group group) {
if (layoutChanging) return true;
CloseScope scope = closing.scope();
if (scope == null) return false;
if (scope.kind() == CloseScope.Kind.FLOATING_WINDOW) {
@@ -286,6 +352,7 @@ public final class DockingManager {
/** Resolves a move without mutating content, layout or identity allocation. */
public MoveCheck checkMove(DockableId id, DockTarget target) {
requireFxThread();
if (layoutChanging) return new MoveCheck.Rejected(layoutChangeFailure());
if (!dockables.containsKey(id)) return moveRejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open");
if (groupClosing(containing(id))) return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "A close request covers this group");
MoveCheck check = resolve(dockables.get(id), target);
@@ -516,6 +583,7 @@ public final class DockingManager {
/** Applies explicitly supplied settings as one validated group change. */
public ActionResult updateGroup(DockGroupId id, DockGroupChanges changes) {
requireFxThread();
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
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");
@@ -607,6 +675,7 @@ public final class DockingManager {
private ActionResult setGroupCollapsed(DockGroupId id, boolean collapsed, boolean focusHeader) {
requireFxThread();
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
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");
@@ -707,6 +776,122 @@ public final class DockingManager {
public Dockable activeDockable() { return active.get(); }
public ReadOnlyObjectProperty<Dockable> activeDockableProperty() { return active.getReadOnlyProperty(); }
public DockLayoutView layout() { return layout.get(); }
/** Prepares fresh content for an empty manager, then installs the validated layout as one change. */
public RestoreResult restore(LayoutSnapshot snapshot, DockableResolver resolver) {
requireFxThread();
Objects.requireNonNull(snapshot, "snapshot");
Objects.requireNonNull(resolver, "resolver");
if (layoutChanging) return new RestoreResult.Rejected(layoutChangeFailure(), List.of());
if (closing.scope() != null) return new RestoreResult.Rejected(new DockFailure(
DockFailure.Code.CLOSE_IN_PROGRESS, null, "Cannot restore during close consent", null), List.of());
if (!dockables.isEmpty()) return new RestoreResult.Rejected(new DockFailure(
DockFailure.Code.RESTORE_REQUIRES_EMPTY_MANAGER, null, "Restore requires a manager without open Dockables", null), List.of());
DockFailure invalid = DockSnapshotValidation.validate(snapshot,
group -> validate(group.settings().definition(group.originArea()), new java.util.HashSet<>()));
if (invalid != null) return new RestoreResult.Rejected(invalid, List.of());
if (snapshot.windows().size() != 1) return new RestoreResult.Rejected(new DockFailure(
DockFailure.Code.UNSUPPORTED_SNAPSHOT_FEATURE, null, "Floating-window restoration is not available in this milestone", null), List.of());
layoutChanging = true;
try {
DockLayoutCandidate candidate = prepareLayoutCandidate(snapshot.windows().getFirst());
DockRestorePreparation prepared = DockRestorePreparation.resolve(candidate, resolver, this::checkPlacement);
if (prepared.rejection() != null) return prepared.rejection();
initialIntents.clear();
initialIntents.putAll(snapshot.initialIntents());
returnTargets.clear();
snapshot.returnPositions().forEach((id, position) -> returnTargets.put(id,
new ReturnLocation(position.target(), position.areaId())));
installLayoutCandidate(candidate, prepared.contents(), snapshot.activeDockableId());
return new RestoreResult.Applied(List.of());
} finally {
layoutChanging = false;
}
}
private DockFailure layoutChangeFailure() {
return new DockFailure(DockFailure.Code.LAYOUT_CHANGE_IN_PROGRESS, null,
"A layout replacement is already being prepared", null);
}
private DockLayoutCandidate prepareLayoutCandidate(LayoutSnapshot.Window window) {
return new DockLayoutCandidate(window, state -> {
Group group = createDetachedGroup(state.id(), state.settings().definition(state.originArea()));
DockGroupPane tabs = (DockGroupPane) group.tabs;
tabs.setCollapsed(state.settings().mode() == DockGroupMode.OVERLAY || state.collapsed());
tabs.surface().updatePreferredSize(state.expandedWidth(), state.expandedHeight());
return group;
}, this::publish, id -> !groupClosing(group(id)));
}
private void installLayoutCandidate(DockLayoutCandidate candidate, Map<DockableId, Dockable> contents,
DockableId activeId) {
Map<DockableId, Dockable> installed = new LinkedHashMap<>(contents);
boolean wasUpdating = updating;
updating = true;
try {
for (Group old : groups.values()) {
for (Tab tab : List.copyOf(old.tabs.getTabs())) {
dragFor(old).uninstallTab(tab);
tab.textProperty().unbind();
tab.graphicProperty().unbind();
tab.setGraphic(null);
tab.setContent(null);
}
old.tabs.getTabs().clear();
}
tree.clear();
pane.clearAreas();
floatingWindows.values().forEach(this::disposeFloatingWindow);
floatingWindows.clear();
groupWindows.clear();
groups.clear();
groupActivationOrder.clear();
edgeAreas.clear();
dockables.clear();
dockables.putAll(installed);
previousFocus.keySet().retainAll(installed.keySet());
activationOrder.keySet().retainAll(installed.keySet());
for (Group group : candidate.groups()) {
groups.put(group.id, group);
allocatedGroupIds.add(group.id);
for (DockableId id : candidate.tabs(group.id)) {
Tab tab = prepareTab(installed.get(id));
drag.installTab(tab, id);
group.tabs.getTabs().add(tab);
}
DockableId selected = candidate.selected(group.id);
int index = selected == null ? -1 : tabIndex(group, selected);
if (index >= 0) group.tabs.getSelectionModel().select(index);
else if (!group.tabs.getTabs().isEmpty()) group.tabs.getSelectionModel().selectFirst();
}
List<java.util.function.Consumer<Node>> placements = new java.util.ArrayList<>();
for (LayoutSnapshot.Root root : candidate.roots()) {
if (root.placement() == LayoutSnapshot.Placement.CENTER) placements.add(pane.surface::setCenter);
else {
javafx.geometry.Side side = javafx.geometry.Side.valueOf(root.placement().name());
DockAreaId areaId = root.branch().aliases().getFirst();
root.branch().aliases().forEach(alias -> edgeAreas.put(alias, side));
placements.add(node -> {
pane.setArea(side, node, () -> canResizeEdge(areaId, side), this::publish);
pane.setAreaExtent(side, root.preferredWidth(), root.preferredHeight());
});
}
}
tree.installFrom(candidate.tree, placements);
tree.view().forEach(area -> allocatedAreaIds.add(area.id()));
refreshEmptyGroups();
Dockable desired = activeId == null ? null : installed.get(activeId);
if (desired != null && !isGroupVisible(containing(activeId))) desired = null;
setActive(desired == null ? selectedVisibleFallback() : desired);
focus(active.get());
} finally {
updating = wasUpdating;
}
publish();
}
/** Returns the last completed layout geometry, including during live geometry gestures. */
public LayoutSnapshot snapshot() { return publishedSnapshot; }
public ReadOnlyObjectProperty<DockLayoutView> layoutProperty() { return layout.getReadOnlyProperty(); }
private void addEdgeGroup(DockLayoutNode definition, javafx.geometry.Side side) {
@@ -756,6 +941,13 @@ public final class DockingManager {
}
private Group createGroup(DockGroupId id, DockGroupDefinition definition) {
Group group = createDetachedGroup(id, definition);
allocatedGroupIds.add(id);
groups.put(id, group);
return group;
}
private Group createDetachedGroup(DockGroupId id, DockGroupDefinition definition) {
DockGroupDefinition captured = new DockGroupDefinition(definition.getDestinationId());
captured.setTabSide(definition.getTabSide());
captured.setMode(definition.getMode());
@@ -772,12 +964,10 @@ public final class DockingManager {
tabs.setSide(captured.getTabSide());
((DockGroupPane) tabs).setCollapsed(captured.getMode() == DockGroupMode.OVERLAY);
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 && isGroupVisible(group)) {
if (!updating && groups.get(id) == group && selected != null && isGroupVisible(group)) {
setActive(dockables.get((DockableId) selected.getUserData()));
focus(active.get());
publish();
@@ -815,6 +1005,12 @@ public final class DockingManager {
for (Dockable dockable : dockables.values()) {
if (contains(dockable.getContent(), current) && isGroupVisible(containing(dockable.getId()))) {
previousFocus.put(dockable.getId(), current);
if (active.get() != dockable && !updating && !layoutChanging && publishedSnapshot != null
&& layout.get().windows().stream().flatMap(window -> window.areas().stream())
.flatMap(area -> area.groups().stream()).anyMatch(group -> dockable.getId().equals(group.selectedDockableId()))) {
publishedSnapshot = new LayoutSnapshot(publishedSnapshot.version(), publishedSnapshot.windows(),
dockable.getId(), publishedSnapshot.returnPositions(), publishedSnapshot.initialIntents());
}
setActive(dockable);
return;
}
@@ -918,6 +1114,23 @@ public final class DockingManager {
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())));
List<LayoutSnapshot.Root> mainRoots = tree.snapshotRoots(edgeAreas, tree.isResizing() || pane.isResizing()).stream().map(root -> {
if (root.placement() == LayoutSnapshot.Placement.CENTER) return root;
javafx.geometry.Side side = javafx.geometry.Side.valueOf(root.placement().name());
double extent = pane.committedExtent(side);
return new LayoutSnapshot.Root(root.placement(), side.isVertical() ? extent : -1,
side.isHorizontal() ? extent : -1, root.branch());
}).toList();
var snapshotWindows = new java.util.ArrayList<LayoutSnapshot.Window>();
snapshotWindows.add(new LayoutSnapshot.Window(new DockWindowId("main"), true, null, mainRoots));
floatingWindows.values().forEach(window -> snapshotWindows.add(new LayoutSnapshot.Window(
window.id, false, window.geometry.bounds(), window.tree.snapshotRoots(Map.of(),
window.geometry.hasPendingChanges() || window.tree.isResizing() || window.pane.isResizing()))));
Map<DockableId, LayoutSnapshot.ReturnPosition> positions = new LinkedHashMap<>();
returnTargets.forEach((id, position) -> positions.put(id,
new LayoutSnapshot.ReturnPosition(position.target, position.areaId)));
publishedSnapshot = new LayoutSnapshot(LayoutSnapshot.CURRENT_VERSION, snapshotWindows,
active.get() == null ? null : active.get().getId(), positions, initialIntents);
layout.set(new DockLayoutView(windows));
}
@@ -7,6 +7,8 @@ import java.util.Optional;
/** Attachment options. Additional policies are introduced with their operations. */
@Getter @Setter
public final class DockingOptions {
/** String overrides for built-in labels, failure codes and application message keys; captured at attach. */
private java.util.ResourceBundle resourceBundle;
private PlacementRule placementRule = (dockable, target) -> Optional.empty();
private DockTarget fallbackTarget;
private java.util.function.Consumer<FloatingWindowConfiguration> floatingWindowCustomizer = configuration -> { };
@@ -0,0 +1,72 @@
package de.neitzel.fx.docking;
import javafx.geometry.Orientation;
import javafx.geometry.Rectangle2D;
import javafx.geometry.Side;
import java.util.List;
import java.util.Map;
/** Versioned immutable layout data; document contents and JavaFX Nodes remain application-owned. */
public record LayoutSnapshot(int version, List<Window> windows, DockableId activeDockableId,
Map<DockableId, ReturnPosition> returnPositions,
Map<DockableId, DockAreaId> initialIntents) {
public static final int CURRENT_VERSION = 1;
public LayoutSnapshot {
windows = List.copyOf(windows);
returnPositions = Map.copyOf(returnPositions);
initialIntents = Map.copyOf(initialIntents);
}
static Window remapGroups(Window window, java.util.function.Function<DockGroupId, DockGroupId> remap) {
return new Window(window.id(), window.main(), window.bounds(), window.roots().stream()
.map(root -> new Root(root.placement(), root.preferredWidth(), root.preferredHeight(),
remapGroups(root.branch(), remap))).toList());
}
private static Branch remapGroups(Branch branch, java.util.function.Function<DockGroupId, DockGroupId> remap) {
if (branch instanceof Split split) return new Split(split.aliases(), split.orientation(), split.position(),
remapGroups(split.first(), remap), remapGroups(split.second(), remap));
Group group = (Group) branch;
return new Group(group.aliases(), remap.apply(group.id()), group.originArea(), group.settings(),
group.collapsed(), group.expandedWidth(), group.expandedHeight(), group.tabs(), group.selected());
}
public enum Placement { CENTER, LEFT, RIGHT, TOP, BOTTOM }
public record Window(DockWindowId id, boolean main, Rectangle2D bounds, List<Root> roots) {
public Window { roots = List.copyOf(roots); }
}
public record Root(Placement placement, double preferredWidth, double preferredHeight, Branch branch) { }
public sealed interface Branch {
List<DockAreaId> aliases();
}
public record Split(List<DockAreaId> aliases, Orientation orientation, double position,
Branch first, Branch second) implements Branch {
public Split { aliases = List.copyOf(aliases); }
}
public record Group(List<DockAreaId> aliases, DockGroupId id, DockAreaId originArea,
GroupSettings settings, boolean collapsed, double expandedWidth, double expandedHeight,
List<DockableId> tabs, DockableId selected) implements Branch {
public Group { aliases = List.copyOf(aliases); tabs = List.copyOf(tabs); }
}
public record ReturnPosition(DockTarget target, DockAreaId areaId) { }
public record GroupSettings(Side tabSide, DockGroupMode mode, double preferredWidth, double preferredHeight,
double minimumWidth, double minimumHeight, boolean persistent,
boolean visibleWhenEmpty, boolean releaseSpaceWhenEmpty, boolean collapsible,
SplitDirections splitDirections) {
static GroupSettings capture(DockGroupDefinition definition) {
return new GroupSettings(definition.getTabSide(), definition.getMode(), definition.getPreferredWidth(),
definition.getPreferredHeight(), definition.getMinimumWidth(), definition.getMinimumHeight(),
definition.isPersistent(), definition.isVisibleWhenEmpty(), definition.isReleaseSpaceWhenEmpty(),
definition.isCollapsible(), definition.getSplitDirections());
}
DockGroupDefinition definition(DockAreaId origin) {
DockGroupDefinition definition = new DockGroupDefinition(origin.value());
DockGroupChanges.builder().tabSide(tabSide).mode(mode).preferredWidth(preferredWidth)
.preferredHeight(preferredHeight).minimumWidth(minimumWidth).minimumHeight(minimumHeight)
.persistent(persistent).visibleWhenEmpty(visibleWhenEmpty).releaseSpaceWhenEmpty(releaseSpaceWhenEmpty)
.collapsible(collapsible).splitDirections(splitDirections).build().applyTo(definition);
return definition;
}
}
}
@@ -0,0 +1,13 @@
package de.neitzel.fx.docking;
import java.util.List;
/** An applied restore reports missing identities; rejection separates its cause from cleanup diagnostics. */
public sealed interface RestoreResult {
record Applied(List<DockableId> missingIds) implements RestoreResult {
public Applied { missingIds = List.copyOf(missingIds); }
}
record Rejected(DockFailure failure, List<DockFailure> cleanupFailures) implements RestoreResult {
public Rejected { cleanupFailures = List.copyOf(cleanupFailures); }
}
}