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
+2
View File
@@ -12,6 +12,8 @@
- [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples.
- [Optional MVVM docking integration](../fx-example/docs/docking-mvvm.md), with local and global bars.
- [Dragging between windows](docs/docking-drag.md), with native pointer and keyboard qualification.
- [Layout snapshots and empty-workspace restore](docs/docking-snapshots.md), with application-owned storage and loading.
- [Live reset](../fx-example/docs/docking-reset.md), retaining existing contents and unsaved edits.
- [Asynchronous tab close](docs/docking-close.md), including consent and resource release.
- [Dependency injection](../injection/README.md).
+87
View File
@@ -0,0 +1,87 @@
# Application-owned layout snapshots
`DockingManager.snapshot()` returns immutable, versioned layout data from the
last completed publication. It contains window IDs and committed bounds,
canonical root placement, nested splits and proportions, stable area aliases,
group configuration, tab order and selection, and the active Dockable ID.
Remembered expanded dimensions are separate from preferred group settings, so
collapsed and overlaid groups can retain their effective size. Return positions
and initial placement intentions are also data.
A snapshot contains no JavaFX Nodes, controllers, ViewModels or document text.
The application chooses serialization, storage, migration and document loading.
Reading a snapshot does not commit an unfinished resize gesture.
Invoke manager operations on the JavaFX application thread; pass the immutable
snapshot to application storage separately.
## Restore before showing a fresh workspace
Load a `DockPane` using Java or ordinary FXML, attach it to the new main Stage,
and restore while its manager contains no Dockables. The captured initial layout
is the fallback if validation or content preparation fails.
```java
DockingManager manager = DockingManager.attach(stage, pane, options);
RestoreResult result = manager.restore(saved, id -> {
try {
return new DockableResolution.Available(loadDocument(id));
} catch (DocumentLoadException failure) {
return new DockableResolution.Failed(failure);
}
});
stage.show();
```
Here `loadDocument` and `DocumentLoadException` are application code. A successful
resolver returns a fresh, unattached Dockable with the requested ID. Group and tab
order determine preparation order. Restore validates the snapshot and all
prepared contents before installing them, then publishes the completed layout.
Docked groups retain their collapsed state. Temporary overlays restore collapsed
while retaining overlay mode and remembered size.
`RestoreResult.Rejected` separates the primary `DockFailure` from cleanup
diagnostics. For example, `DockableResolution.Failed(cause)` produces
`DOCKABLE_LOAD_FAILED`. Already prepared available contents receive `onDiscarded`
once; a cleanup failure is reported separately and does not replace the original
cause. A rejected restore keeps the previous empty layout intact. It never uses
normal close consent or `onClosed` to discard unused prepared content.
An already attached resolver or factory result is rejected before the manager
adopts it. Contents belonging to this or another live manager receive neither
`onDiscarded` nor `onClosed` on that rejection. Fresh, unused prepared contents
remain subject to the discard contract.
This milestone restores snapshots containing the main window. Floating-window
data is captured, but restoring floating hosts currently returns
`UNSUPPORTED_SNAPSHOT_FEATURE` before invoking the resolver; ticket 14 adds that
capability. Partial restoration for missing IDs is supplied by ticket 13.
Use [live reset](../../fx-example/docs/docking-reset.md) to rearrange already open
contents without replacing their Nodes or losing their unsaved state.
## Runnable Java/FXML example
`SnapshotDockingMain` loads `SnapshotDocking.fxml`, which declares nested editor
splits and a right-hand overlay. The application retains the snapshot in memory
and creates a new empty workspace for each restoration attempt. Fresh TextAreas
come from the example's separate document source.
Build from the repository root using Java 25 without installing runtime artifacts:
```sh
./mvnw -pl fx-example -am package
java --enable-native-access=ALL-UNNAMED \
-cp 'fx-example/target/classes:fx/target/classes:fx-example/target/libs/*' \
de.neitzel.fx.example.docking.SnapshotDockingMain
```
1. Resize the editor splits, select tabs and open Project. Choose **Capture layout**.
2. Choose **Restore saved layout**. A new window restores the arrangement before
it is shown; Project starts collapsed. The original window remains usable.
3. Choose **Try incompatible version**. The new window retains its initial empty
fallback, and the status reports that no content was prepared.
4. Choose **Simulate load failure**. The status reports the original load cause,
prepared and discarded content counts, and separate cleanup diagnostics.
5. Enable **Simulate cleanup failure** and repeat the failed load to see cleanup
diagnostics alongside the unchanged primary failure.
The example's **Capture layout** command saves layout data only. Reloaded document
text comes from its application source; document persistence is a separate concern.
@@ -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); }
}
}
@@ -0,0 +1,38 @@
dock.action.move=Move to
dock.action.split=Split
dock.action.close=Close
dock.action.float=Float
dock.action.return=Return to main
dock.action.pin=Pin group
dock.side.TOP=Above
dock.side.RIGHT=Right
dock.side.BOTTOM=Below
dock.side.LEFT=Left
dock.action.unavailable={0} ({1})
dock.action.noChange={0} (Already here)
dock.failure.generic=The operation cannot be completed
dock.failure.LAYOUT_CHANGE_IN_PROGRESS=A layout change is in progress
dock.failure.RESTORE_REQUIRES_EMPTY_MANAGER=Restore requires an empty manager
dock.failure.UNSUPPORTED_SNAPSHOT_VERSION=This snapshot version is not supported
dock.failure.INVALID_SNAPSHOT=The snapshot is invalid
dock.failure.UNSUPPORTED_SNAPSHOT_FEATURE=This snapshot feature is not supported
dock.failure.DOCKABLE_LOAD_FAILED=The content could not be loaded
dock.failure.MISSING_DOCKABLE=The requested content is unavailable
dock.failure.INVALID_GROUP_CONFIGURATION=The group settings are incompatible
dock.failure.COLLAPSE_DISABLED=This group cannot collapse
dock.failure.SPLIT_DISABLED=This group cannot split in that direction
dock.failure.SPLIT_TOO_SMALL=There is not enough space to split this group
dock.failure.TARGET_NOT_FOUND=The destination is unavailable
dock.failure.REFERENCE_TAB_NOT_FOUND=The reference tab is unavailable
dock.failure.DOCKABLE_NOT_FOUND=The content is not open
dock.failure.CONTENT_ALREADY_ATTACHED=The content already belongs to a view
dock.failure.PLACEMENT_REJECTED=This placement is not allowed
dock.failure.PLACEMENT_CHECK_FAILED=The placement check failed
dock.failure.ID_MISMATCH=The created content has a different identity
dock.failure.FACTORY_FAILED=The content could not be created
dock.failure.MAIN_WINDOW_ONLY=This content must remain in the main window
dock.failure.CLOSE_IN_PROGRESS=A close decision is pending
dock.failure.CLOSE_CHECK_FAILED=The close check failed
dock.failure.CLEANUP_FAILED=Resource release failed
dock.failure.INVALID_WINDOW_BOUNDS=The window bounds are invalid
dock.failure.WINDOW_CREATION_FAILED=The floating window could not be prepared
@@ -0,0 +1,84 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ListResourceBundle;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
/** Application and built-in menus share localization while diagnostics retain original data. */
class DockingLocalizationTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void builtInMenusAndApplicationsResolveTheSamePlacementMessage(boolean knownKey) throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage stage = new Stage();
stage.setScene(new Scene(pane, 700, 450));
DockingOptions options = new DockingOptions();
options.setResourceBundle(new ListResourceBundle() {
@Override protected Object[][] getContents() {
return new Object[][] {
{"dock.action.move", "Verschieben"}, {"dock.action.float", "Abkoppeln"},
{"dock.failure.PLACEMENT_REJECTED", "Platzierung nicht erlaubt"},
{"application.onlyMain", "Nur im Hauptbereich"}
};
}
});
String key = knownKey ? "application.onlyMain" : "application.missing";
RuntimeException cause = new IllegalStateException("Diagnostic context");
DockFailure denial = new DockFailure(DockFailure.Code.PLACEMENT_REJECTED,
new DockableId("notes"), "Original diagnostic text", cause, key);
options.setPlacementRule((dockable, target) -> target instanceof ResolvedDockTarget.Detachment
? Optional.of(denial) : Optional.empty());
DockingManager manager = DockingManager.attach(stage, pane, options);
options.setResourceBundle(null);
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Unsaved"));
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("editors"));
stage.show();
ContextMenu menu = null;
try {
pane.applyCss();
pane.layout();
TabPane tabs = (TabPane) pane.lookup(".tab-pane");
menu = tabs.getTabs().getFirst().getContextMenu();
menu.show(tabs, Side.BOTTOM, 0, 0);
String expected = knownKey ? "Nur im Hauptbereich" : "Platzierung nicht erlaubt";
assertEquals("Verschieben", menu.getItems().getFirst().getText());
assertEquals("Close", menu.getItems().get(2).getText(), "Unspecified labels retain their default");
assertEquals("Abkoppeln (" + expected + ")", menu.getItems().get(3).getText());
assertTrue(menu.getItems().get(3).isDisable());
DockFailure checked = assertInstanceOf(MoveCheck.Rejected.class,
manager.checkMove(notes.getId(), DockTarget.floating())).failure();
assertEquals(expected, manager.describeFailure(checked));
assertSame(denial, checked);
assertEquals(key, checked.messageKey());
assertEquals("Original diagnostic text", checked.message());
assertSame(cause, checked.cause());
assertEquals(DockFailure.Code.PLACEMENT_REJECTED, checked.code());
} finally {
if (menu != null) menu.hide();
stage.hide();
}
});
}
}
@@ -0,0 +1,51 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Node;
import javafx.scene.control.TextArea;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class PreparedDockableOwnershipTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@ParameterizedTest @ValueSource(booleans = {false, true})
void rejectingAnAlreadyOpenedForeignDockableNeverDiscardsItsLiveResources(boolean restore) throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout(); initial.setCenter(new DockGroupDefinition("start"));
DockingManager foreign = RestoreValidationTest.manager(initial);
var model = new SimpleStringProperty("Live document");
TextArea editor = new TextArea(); editor.textProperty().bindBidirectional(model);
Dockable live = new Dockable(new DockableId("a"), editor);
AtomicInteger discarded = new AtomicInteger(); AtomicInteger closed = new AtomicInteger();
live.setOnDiscarded(() -> { discarded.incrementAndGet(); editor.textProperty().unbindBidirectional(model); });
live.setOnClosed(closed::incrementAndGet);
foreign.open(live, DockTarget.area("start"));
Node parent = editor.getParent(); var original = foreign.layout();
DockingManager recipient = RestoreValidationTest.manager(initial);
DockFailure failure;
if (restore) {
failure = assertInstanceOf(RestoreResult.Rejected.class, recipient.restore(RestoreValidationTest.saved(),
id -> new DockableResolution.Available(live))).failure();
} else {
failure = assertInstanceOf(ActionResult.Rejected.class, recipient.open(live.getId(), () -> live,
DockTarget.area("start"))).failure();
}
assertEquals(DockFailure.Code.CONTENT_ALREADY_ATTACHED, failure.code());
assertEquals(0, discarded.get(), "A resolver or factory cannot transfer content already owned by another manager");
assertEquals(0, closed.get());
assertSame(original, foreign.layout());
assertSame(parent, editor.getParent());
assertSame(live, foreign.findDockable(live.getId()).orElseThrow());
model.set("Updated after rejection");
assertEquals("Updated after rejection", editor.getText());
editor.appendText(" and edited");
assertEquals(editor.getText(), model.get(), "The live editor retains both directions of its model binding");
assertTrue(recipient.findDockable(live.getId()).isEmpty());
});
}
}
@@ -0,0 +1,341 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.CloseConsent;
import de.neitzel.fx.docking.DockGroupChanges;
import de.neitzel.fx.docking.DockFailure;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockGroupId;
import de.neitzel.fx.docking.DockGroupMode;
import de.neitzel.fx.docking.DockLayout;
import de.neitzel.fx.docking.DockLayoutView;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockSplitDefinition;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import de.neitzel.fx.docking.ResolvedDockTarget;
import de.neitzel.fx.docking.MoveCheck;
import de.neitzel.fx.docking.TabPosition;
import javafx.application.Platform;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.IndexRange;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
/** Reset returns live contents to the captured initial arrangement through the public API. */
class ResetDockingLayoutTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void resetKeepsLiveEditsAndRestoresTheCapturedDefinitionsInOnePublication() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockGroupDefinition editors = new DockGroupDefinition("editors");
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setCollapsible(true);
tools.setTabSide(Side.RIGHT);
tools.setPreferredWidth(240);
DockLayout initial = new DockLayout();
initial.setCenter(editors);
initial.setRight(tools);
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage main = new Stage();
main.setScene(new Scene(pane, 1000, 600));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea text = new TextArea("Unsaved document");
Dockable notes = new Dockable(new DockableId("notes"), text);
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme"));
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
AtomicInteger released = new AtomicInteger();
notes.setOnClosed(released::incrementAndGet);
notes.setOnDiscarded(released::incrementAndGet);
manager.open(notes, DockTarget.area("editors"));
manager.open(readme, DockTarget.area("editors"));
manager.open(project, DockTarget.area("tools"));
main.show();
try {
editors.setTabSide(Side.LEFT);
tools.setPreferredWidth(390);
tools.setMode(DockGroupMode.OVERLAY);
initial.setLeft(new DockGroupDefinition("late-area"));
assertInstanceOf(ActionResult.Applied.class,
manager.move(notes.getId(), DockTarget.split(new DockGroupId("editors"), Side.RIGHT)));
manager.move(notes.getId(), DockTarget.floating());
Window floating = text.getScene().getWindow();
manager.move(project.getId(), DockTarget.area("editors"));
manager.updateGroup(new DockGroupId("tools"), DockGroupChanges.builder()
.mode(DockGroupMode.OVERLAY).preferredWidth(330).build());
manager.setGroupCollapsed(new DockGroupId("tools"), true);
text.setText("Still unsaved");
text.selectRange(0, 5);
List<DockLayoutView> publications = new ArrayList<>();
manager.layoutProperty().addListener((observable, old, current) -> publications.add(current));
assertInstanceOf(ActionResult.Applied.class, manager.resetLayout());
assertEquals(1, publications.size());
assertEquals(1, manager.layout().windows().size());
assertFalse(floating.isShowing());
assertSame(main, text.getScene().getWindow());
assertSame(text, manager.findDockable(notes.getId()).orElseThrow().getContent());
assertEquals("Still unsaved", text.getText());
assertEquals(new IndexRange(0, 5), text.getSelection());
assertEquals(0, released.get(), "Reset moves content without closing or discarding it");
DockLayoutView.Area resetEditors = area(manager, "editors");
DockLayoutView.Area resetTools = area(manager, "tools");
assertEquals(1, resetEditors.groups().size());
assertEquals(List.of(notes.getId(), readme.getId()), resetEditors.groups().getFirst().dockableIds());
assertEquals(Side.TOP, resetEditors.groups().getFirst().tabSide());
assertEquals(List.of(project.getId()), resetTools.groups().getFirst().dockableIds());
assertEquals(Side.RIGHT, resetTools.groups().getFirst().tabSide());
assertEquals(DockGroupMode.DOCKED, resetTools.groups().getFirst().mode());
assertFalse(resetTools.groups().getFirst().collapsed());
assertEquals(240, resetTools.preferredWidth(), 1);
assertTrue(manager.layout().windows().getFirst().areas().stream()
.noneMatch(candidate -> candidate.id().value().equals("late-area")));
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
private static DockLayoutView.Area area(DockingManager manager, String id) {
return manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals(id)).findFirst().orElseThrow();
}
@Test
void aRejectedResetKeepsAllWindowsContentsSelectionAndTheCommittedSnapshot() throws Exception {
FxThread.onFx(() -> {
AtomicBoolean reject = new AtomicBoolean();
DockingOptions options = new DockingOptions();
options.setPlacementRule((dockable, destination) -> reject.get() && dockable.getId().value().equals("project")
? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(),
"Project is locked", null, "application.project.locked"))
: Optional.empty());
Fixture fixture = fixture(options);
DockingManager manager = fixture.manager();
Dockable notes = open(manager, "notes", "editors");
Dockable project = open(manager, "project", "tools");
fixture.stage().show();
manager.move(notes.getId(), DockTarget.floating());
Window floating = notes.getContent().getScene().getWindow();
try {
TextArea text = (TextArea) notes.getContent();
text.setText("Unsaved notes");
text.selectRange(2, 8);
var layout = manager.layout();
var snapshot = manager.snapshot();
var active = manager.activeDockable();
var parent = text.getParent();
AtomicInteger publications = new AtomicInteger();
manager.layoutProperty().addListener((observable, old, current) -> publications.incrementAndGet());
reject.set(true);
ActionResult.Rejected result = assertInstanceOf(ActionResult.Rejected.class, manager.resetLayout());
assertEquals(project.getId(), result.failure().dockableId());
assertEquals(DockFailure.Code.PLACEMENT_REJECTED, result.failure().code());
assertEquals("application.project.locked", result.failure().messageKey());
assertSame(layout, manager.layout());
assertSame(snapshot, manager.snapshot());
assertSame(active, manager.activeDockable());
assertSame(parent, text.getParent());
assertSame(floating, text.getScene().getWindow());
assertTrue(floating.isShowing());
assertEquals("Unsaved notes", text.getText());
assertEquals(new IndexRange(2, 8), text.getSelection());
assertEquals(0, publications.get());
reject.set(false);
assertInstanceOf(ActionResult.Applied.class, manager.resetLayout(), "A rejection must release the transaction guard");
} finally { floating.hide(); fixture.stage().hide(); }
});
}
@Test
void resetUsesAnEligibleFallbackForARejectedHomeAndInitiallyFloatingContent() throws Exception {
FxThread.onFx(() -> {
AtomicBoolean rejectHome = new AtomicBoolean();
DockingOptions options = new DockingOptions();
options.setFallbackTarget(DockTarget.area("editors"));
options.setPlacementRule((dockable, destination) -> rejectHome.get()
&& destination instanceof ResolvedDockTarget.Insertion insertion
&& insertion.groupId().equals(new DockGroupId("tools"))
? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), "Tools are locked", null))
: Optional.empty());
Fixture fixture = fixture(options);
DockingManager manager = fixture.manager();
Dockable project = open(manager, "project", "tools");
Dockable detached = new Dockable(new DockableId("detached"), new TextArea("First opened floating"));
fixture.stage().show();
manager.open(detached, DockTarget.floating());
Window floating = detached.getContent().getScene().getWindow();
try {
rejectHome.set(true);
assertInstanceOf(ActionResult.Applied.class, manager.resetLayout());
assertEquals(List.of(project.getId(), detached.getId()), area(manager, "editors").groups().getFirst().dockableIds());
assertTrue(area(manager, "tools").groups().getFirst().dockableIds().isEmpty(), "The persistent initial target survives empty");
assertSame(fixture.stage(), detached.getContent().getScene().getWindow());
assertFalse(floating.isShowing());
} finally { floating.hide(); fixture.stage().hide(); }
});
}
@Test
void resetSelectsTheRetainedActiveEditorInItsFinalGroup() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture(new DockingOptions());
DockingManager manager = fixture.manager();
Dockable first = open(manager, "first", "editors");
open(manager, "second", "editors");
fixture.stage().show();
try {
manager.activate(first.getId());
assertInstanceOf(ActionResult.Applied.class, manager.resetLayout());
assertSame(first, manager.activeDockable());
assertEquals(first.getId(), area(manager, "editors").groups().getFirst().selectedDockableId(),
"The active content must be the visible selected editor after reset");
} finally { fixture.stage().hide(); }
});
}
private static Dockable open(DockingManager manager, String id, String area) {
Dockable dockable = new Dockable(new DockableId(id), new TextArea(id));
assertInstanceOf(ActionResult.Applied.class, manager.open(dockable, DockTarget.area(area)));
return dockable;
}
@Test
void aRelativeFallbackCanReferToAnEditorOpenedAfterTheFloatingContent() throws Exception {
FxThread.onFx(() -> {
DockingOptions options = new DockingOptions();
DockableId anchor = new DockableId("anchor");
options.setFallbackTarget(DockTarget.group(new DockGroupId("editors"), TabPosition.before(anchor)));
Fixture fixture = fixture(options);
Dockable first = new Dockable(new DockableId("floating-first"), new TextArea("First"));
fixture.stage().show();
fixture.manager().open(first, DockTarget.floating());
Window floating = first.getContent().getScene().getWindow();
try {
open(fixture.manager(), anchor.value(), "editors");
assertInstanceOf(ActionResult.Applied.class, fixture.manager().resetLayout());
assertEquals(List.of(first.getId(), anchor), area(fixture.manager(), "editors").groups().getFirst().dockableIds());
assertFalse(floating.isShowing());
} finally { floating.hide(); fixture.stage().hide(); }
});
}
@Test
void restoringAnInitialAreaDoesNotReviveItsRetiredConcreteGroupId() throws Exception {
FxThread.onFx(() -> {
DockSplitDefinition split = new DockSplitDefinition();
split.setDestinationId("editors");
split.setFirst(new DockGroupDefinition("primary"));
split.setSecond(new DockGroupDefinition("secondary"));
DockLayout initial = new DockLayout();
initial.setCenter(split);
Fixture fixture = fixture(initial, new DockingOptions());
DockingManager manager = fixture.manager();
Dockable first = open(manager, "first", "primary");
Dockable second = open(manager, "second", "secondary");
fixture.stage().show();
try {
manager.move(first.getId(), DockTarget.area("secondary"));
assertInstanceOf(MoveCheck.Rejected.class, manager.checkMove(second.getId(), DockTarget.group(new DockGroupId("primary"))));
assertInstanceOf(ActionResult.Applied.class, manager.resetLayout());
assertEquals(List.of(first.getId()), area(manager, "primary").groups().getFirst().dockableIds());
assertNotEquals(new DockGroupId("primary"), area(manager, "primary").groups().getFirst().id());
assertEquals(DockFailure.Code.TARGET_NOT_FOUND, assertInstanceOf(MoveCheck.Rejected.class,
manager.checkMove(second.getId(), DockTarget.group(new DockGroupId("primary")))).failure().code());
} finally { fixture.stage().hide(); }
});
}
@Test
void resetCannotReplaceTheLayoutWhileAnAsynchronousCloseIsPending() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture(new DockingOptions());
Dockable notes = open(fixture.manager(), "notes", "editors");
CompletableFuture<CloseConsent> consent = new CompletableFuture<>();
notes.setCloseCheck(request -> consent);
fixture.stage().show();
try {
fixture.manager().requestTabClose(notes.getId());
var snapshot = fixture.manager().snapshot();
ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class, fixture.manager().resetLayout());
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, rejected.failure().code());
assertSame(snapshot, fixture.manager().snapshot());
assertSame(notes, fixture.manager().findDockable(notes.getId()).orElseThrow());
} finally { consent.complete(CloseConsent.VETO); fixture.stage().hide(); }
});
}
@Test
void aPlacementCallbackCannotMoveContentDuringResetPreparation() throws Exception {
FxThread.onFx(() -> {
AtomicBoolean resetting = new AtomicBoolean();
AtomicReference<DockingManager> owner = new AtomicReference<>();
AtomicReference<ActionResult> reentrant = new AtomicReference<>();
DockingOptions options = new DockingOptions();
options.setPlacementRule((dockable, destination) -> {
if (resetting.compareAndSet(true, false)) reentrant.set(owner.get().move(dockable.getId(), DockTarget.area("tools")));
return Optional.empty();
});
Fixture fixture = fixture(options);
owner.set(fixture.manager());
Dockable notes = open(fixture.manager(), "notes", "editors");
fixture.manager().move(notes.getId(), DockTarget.area("tools"));
fixture.stage().show();
try {
AtomicInteger publications = new AtomicInteger();
fixture.manager().layoutProperty().addListener((observable, old, current) -> publications.incrementAndGet());
resetting.set(true);
assertInstanceOf(ActionResult.Applied.class, fixture.manager().resetLayout());
assertEquals(DockFailure.Code.LAYOUT_CHANGE_IN_PROGRESS,
assertInstanceOf(ActionResult.Rejected.class, reentrant.get()).failure().code());
assertEquals(List.of(notes.getId()), area(fixture.manager(), "editors").groups().getFirst().dockableIds());
assertEquals(1, publications.get());
} finally { fixture.stage().hide(); }
});
}
private static Fixture fixture(DockingOptions options) {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT);
tools.setCollapsible(true);
initial.setRight(tools);
return fixture(initial, options);
}
private static Fixture fixture(DockLayout initial, DockingOptions options) {
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 600));
return new Fixture(stage, DockingManager.attach(stage, pane, options));
}
private record Fixture(Stage stage, DockingManager manager) { }
}
@@ -0,0 +1,69 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class RestoreContentValidationTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@ParameterizedTest @ValueSource(strings = {"wrong-id", "attached", "shared-node", "policy-reject", "policy-throw"})
void preparedContentAndPlacementsAreCheckedBeforeAnyLayoutMutation(String fault) throws Exception {
FxThread.onFx(() -> {
LayoutSnapshot saved = RestoreValidationTest.saved();
RuntimeException policyFailure = new IllegalStateException("Placement service failed");
DockingOptions options = new DockingOptions();
options.setPlacementRule((dockable, target) -> {
if (dockable.getId().value().equals("b")) {
if (fault.equals("policy-throw")) throw policyFailure;
if (fault.equals("policy-reject")) return Optional.of(new DockFailure(
DockFailure.Code.PLACEMENT_REJECTED, null, "Destination is no longer allowed", null, "app.restore.blocked"));
}
return Optional.empty();
});
DockLayout initial = new DockLayout(); initial.setCenter(new DockGroupDefinition("start"));
DockPane pane = new DockPane(); pane.setInitialLayout(initial);
Stage stage = new Stage(); stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, options);
var before = manager.layout(); var snapshotBefore = manager.snapshot();
TextArea shared = new TextArea("Existing content");
StackPane foreignParent = new StackPane();
if (fault.equals("attached")) foreignParent.getChildren().add(shared);
List<Dockable> prepared = new ArrayList<>();
AtomicInteger discards = new AtomicInteger();
RestoreResult.Rejected result = assertInstanceOf(RestoreResult.Rejected.class,
manager.restore(saved, id -> {
Dockable dockable = new Dockable(fault.equals("wrong-id") ? new DockableId("wrong") : id,
fault.equals("shared-node") || fault.equals("attached") ? shared : new TextArea("Fresh " + id.value()));
dockable.setOnDiscarded(discards::incrementAndGet);
prepared.add(dockable);
return new DockableResolution.Available(dockable);
}));
assertEquals(switch (fault) {
case "wrong-id" -> DockFailure.Code.ID_MISMATCH;
case "attached", "shared-node" -> DockFailure.Code.CONTENT_ALREADY_ATTACHED;
case "policy-reject" -> DockFailure.Code.PLACEMENT_REJECTED;
default -> DockFailure.Code.PLACEMENT_CHECK_FAILED;
}, result.failure().code());
assertNotNull(result.failure().dockableId());
if (fault.equals("policy-reject")) assertEquals("app.restore.blocked", result.failure().messageKey());
if (fault.equals("policy-throw")) assertSame(policyFailure, result.failure().cause());
assertEquals(fault.equals("attached") ? 0 : prepared.size(), discards.get());
assertSame(before, manager.layout());
assertEquals(snapshotBefore, manager.snapshot());
if (fault.equals("attached")) assertSame(foreignParent, shared.getParent());
else for (Dockable dockable : prepared) assertNull(dockable.getContent().getParent());
});
}
}
@@ -0,0 +1,90 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class RestoreDockingLayoutTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@Test
void aFreshManagerRestoresNestedGroupsSelectionAndOverlayModeBeforeItsWindowIsShown() throws Exception {
FxThread.onFx(() -> {
DockSplitDefinition editors = new DockSplitDefinition();
editors.setDestinationId("editors");
editors.setPosition(.35);
editors.setFirst(new DockGroupDefinition("primary"));
editors.setSecond(new DockGroupDefinition("preview"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT);
tools.setCollapsible(true);
tools.setMode(DockGroupMode.OVERLAY);
tools.setPreferredWidth(240);
DockLayout definition = new DockLayout();
definition.setCenter(editors);
definition.setRight(tools);
DockingManager original = manager(definition);
original.open(new Dockable(new DockableId("a"), new TextArea("Original A")), DockTarget.area("primary"));
original.open(new Dockable(new DockableId("b"), new TextArea("Original B")), DockTarget.area("primary"));
original.open(new Dockable(new DockableId("preview"), new TextArea("Preview")), DockTarget.area("preview"));
original.activate(new DockableId("a"));
original.open(new Dockable(new DockableId("project"), new TextArea("Project")), DockTarget.area("tools"));
LayoutSnapshot saved = original.snapshot();
DockLayout fallback = new DockLayout();
fallback.setCenter(new DockGroupDefinition("fallback"));
DockingManager restored = manager(fallback);
Map<DockableId, Dockable> reloaded = new LinkedHashMap<>();
var publications = new java.util.ArrayList<DockLayoutView>();
restored.layoutProperty().addListener((observable, old, current) -> {
publications.add(current);
assertEquals(4, countTabs(restored.snapshot()));
});
RestoreResult.Applied result = assertInstanceOf(RestoreResult.Applied.class,
restored.restore(saved, id -> {
Dockable dockable = new Dockable(id, new TextArea("Reloaded " + id.value()));
reloaded.put(id, dockable);
return new DockableResolution.Available(dockable);
}));
assertTrue(result.missingIds().isEmpty());
assertEquals(1, publications.size());
assertEquals(List.of(new DockableId("a"), new DockableId("b"), new DockableId("preview"), new DockableId("project")),
List.copyOf(reloaded.keySet()));
LayoutSnapshot.Window window = restored.snapshot().windows().getFirst();
LayoutSnapshot.Split center = assertInstanceOf(LayoutSnapshot.Split.class,
window.roots().stream().filter(root -> root.placement() == LayoutSnapshot.Placement.CENTER).findFirst().orElseThrow().branch());
assertEquals(((LayoutSnapshot.Split) saved.windows().getFirst().roots().getFirst().branch()).position(), center.position(), .01);
assertEquals(new DockableId("a"), ((LayoutSnapshot.Group) center.first()).selected());
LayoutSnapshot.Group overlay = (LayoutSnapshot.Group) window.roots().stream()
.filter(root -> root.placement() == LayoutSnapshot.Placement.RIGHT).findFirst().orElseThrow().branch();
assertEquals(DockGroupMode.OVERLAY, overlay.settings().mode());
assertTrue(overlay.collapsed(), "A temporary overlay never opens automatically after restore");
assertEquals(240, overlay.expandedWidth(), 1);
assertInstanceOf(MoveCheck.NoChange.class, restored.checkMove(new DockableId("preview"), DockTarget.area("preview")));
assertSame(reloaded.get(new DockableId("a")), restored.findDockable(new DockableId("a")).orElseThrow());
assertFalse(reloaded.get(new DockableId("a")).getContent().getScene().getWindow().isShowing());
});
}
private static int countTabs(LayoutSnapshot snapshot) {
return snapshot.windows().stream().flatMap(window -> window.roots().stream())
.mapToInt(root -> countTabs(root.branch())).sum();
}
private static int countTabs(LayoutSnapshot.Branch branch) {
return branch instanceof LayoutSnapshot.Group group ? group.tabs().size()
: countTabs(((LayoutSnapshot.Split) branch).first()) + countTabs(((LayoutSnapshot.Split) branch).second());
}
private static DockingManager manager(DockLayout initial) {
DockPane pane = new DockPane(); pane.setInitialLayout(initial);
Stage stage = new Stage(); stage.setScene(new Scene(pane, 900, 600));
return DockingManager.attach(stage, pane, new DockingOptions());
}
}
@@ -0,0 +1,80 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.scene.control.TextArea;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class RestoreFailureTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@ParameterizedTest @ValueSource(booleans = {false, true})
void aLoadFailureDiscardsEveryPreparedContentOnceAndSeparatesCleanupDiagnostics(boolean throwsFailure) throws Exception {
FxThread.onFx(() -> {
LayoutSnapshot saved = threeDockables();
DockLayout initial = new DockLayout(); initial.setCenter(new DockGroupDefinition("start"));
DockingManager manager = RestoreValidationTest.manager(initial);
var before = manager.layout();
var beforeSnapshot = manager.snapshot();
RuntimeException loadFailure = new IllegalStateException("Document cannot be loaded");
RuntimeException cleanupFailure = new IllegalArgumentException("Cleanup A failed");
List<DockableId> requested = new ArrayList<>();
List<Dockable> prepared = new ArrayList<>();
AtomicInteger discardedA = new AtomicInteger();
AtomicInteger discardedC = new AtomicInteger();
AtomicInteger publications = new AtomicInteger();
manager.layoutProperty().addListener((observable, old, current) -> publications.incrementAndGet());
RestoreResult.Rejected result = assertInstanceOf(RestoreResult.Rejected.class,
manager.restore(saved, id -> {
requested.add(id);
if (id.value().equals("b")) {
if (throwsFailure) throw loadFailure;
return new DockableResolution.Failed(loadFailure);
}
Dockable dockable = new Dockable(id, new TextArea("Prepared " + id.value()));
dockable.setOnDiscarded(() -> {
if (id.value().equals("a")) { discardedA.incrementAndGet(); throw cleanupFailure; }
discardedC.incrementAndGet();
});
prepared.add(dockable);
return new DockableResolution.Available(dockable);
}));
assertEquals(List.of(new DockableId("a"), new DockableId("c"), new DockableId("b")), requested);
assertEquals(DockFailure.Code.DOCKABLE_LOAD_FAILED, result.failure().code());
assertEquals(new DockableId("b"), result.failure().dockableId());
assertSame(loadFailure, result.failure().cause());
assertEquals(1, discardedA.get());
assertEquals(1, discardedC.get(), "Cleanup continues after an earlier callback fails");
assertEquals(1, result.cleanupFailures().size());
assertEquals(DockFailure.Code.CLEANUP_FAILED, result.cleanupFailures().getFirst().code());
assertSame(cleanupFailure, result.cleanupFailures().getFirst().cause());
assertSame(before, manager.layout());
assertEquals(beforeSnapshot, manager.snapshot());
assertEquals(0, publications.get());
for (Dockable dockable : prepared) {
assertNull(dockable.getContent().getParent());
assertNull(dockable.getContent().getScene());
assertTrue(manager.findDockable(dockable.getId()).isEmpty());
}
});
}
static LayoutSnapshot threeDockables() {
LayoutSnapshot saved = RestoreValidationTest.saved();
var window = saved.windows().getFirst(); var root = window.roots().getFirst();
var split = (LayoutSnapshot.Split) root.branch(); var first = (LayoutSnapshot.Group) split.first();
var withThird = new LayoutSnapshot.Group(first.aliases(), first.id(), first.originArea(), first.settings(),
first.collapsed(), first.expandedWidth(), first.expandedHeight(),
List.of(new DockableId("a"), new DockableId("c")), first.selected());
return new LayoutSnapshot(saved.version(), List.of(new LayoutSnapshot.Window(window.id(), true, null,
List.of(new LayoutSnapshot.Root(root.placement(), root.preferredWidth(), root.preferredHeight(),
new LayoutSnapshot.Split(split.aliases(), split.orientation(), split.position(), withThird, split.second()))))),
saved.activeDockableId(), saved.returnPositions(), saved.initialIntents());
}
}
@@ -0,0 +1,84 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class RestoreValidationTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@ParameterizedTest
@ValueSource(strings = {"version", "duplicate-root", "duplicate-tab", "unknown-selection", "invalid-size", "invalid-split", "null-side", "null-mode", "null-split-policy", "not-empty"})
void invalidInputIsRejectedBeforeResolvingAndLeavesTheStartingLayoutUsable(String fault) throws Exception {
FxThread.onFx(() -> {
LayoutSnapshot saved = saved();
DockLayout initial = new DockLayout(); initial.setCenter(new DockGroupDefinition("start"));
DockingManager manager = manager(initial);
if (fault.equals("not-empty")) manager.open(new Dockable(new DockableId("live"), new TextArea("Live edits")), DockTarget.area("start"));
LayoutSnapshot invalid = invalid(saved, fault);
var before = manager.layout();
var snapshotBefore = manager.snapshot();
AtomicInteger calls = new AtomicInteger();
RestoreResult.Rejected result = assertInstanceOf(RestoreResult.Rejected.class,
manager.restore(invalid, id -> {
calls.incrementAndGet();
return new DockableResolution.Available(new Dockable(id, new TextArea("Unexpected loading")));
}));
assertEquals(fault.equals("version") ? DockFailure.Code.UNSUPPORTED_SNAPSHOT_VERSION
: fault.equals("not-empty") ? DockFailure.Code.RESTORE_REQUIRES_EMPTY_MANAGER
: DockFailure.Code.INVALID_SNAPSHOT, result.failure().code());
assertEquals(0, calls.get());
assertTrue(result.cleanupFailures().isEmpty());
assertSame(before, manager.layout());
assertEquals(snapshotBefore, manager.snapshot());
assertInstanceOf(ActionResult.Applied.class, manager.open(new Dockable(new DockableId("recovery"),
new TextArea("Fallback remains usable")), DockTarget.area("start")));
});
}
private static LayoutSnapshot invalid(LayoutSnapshot saved, String fault) {
var window = saved.windows().getFirst();
var root = window.roots().getFirst();
var split = (LayoutSnapshot.Split) root.branch();
var group = (LayoutSnapshot.Group) split.first();
var settings = group.settings();
var changedSettings = new LayoutSnapshot.GroupSettings(fault.equals("null-side") ? null : settings.tabSide(),
fault.equals("null-mode") ? null : settings.mode(), settings.preferredWidth(), settings.preferredHeight(),
settings.minimumWidth(), settings.minimumHeight(), settings.persistent(), settings.visibleWhenEmpty(),
settings.releaseSpaceWhenEmpty(), settings.collapsible(), fault.equals("null-split-policy") ? null : settings.splitDirections());
LayoutSnapshot.Branch first = new LayoutSnapshot.Group(group.aliases(), group.id(), group.originArea(),
changedSettings, group.collapsed(), fault.equals("invalid-size") ? Double.NaN : group.expandedWidth(),
group.expandedHeight(), fault.equals("duplicate-tab") ? List.of(group.tabs().getFirst(), group.tabs().getFirst()) : group.tabs(),
fault.equals("unknown-selection") ? new DockableId("missing") : group.selected());
var changedRoot = new LayoutSnapshot.Root(root.placement(), root.preferredWidth(), root.preferredHeight(),
new LayoutSnapshot.Split(split.aliases(), split.orientation(), fault.equals("invalid-split") ? 1.2 : split.position(), first, split.second()));
var changedWindow = new LayoutSnapshot.Window(window.id(), window.main(), window.bounds(),
fault.equals("duplicate-root") ? List.of(changedRoot, changedRoot) : List.of(changedRoot));
return new LayoutSnapshot(fault.equals("version") ? 99 : saved.version(), List.of(changedWindow),
saved.activeDockableId(), saved.returnPositions(), saved.initialIntents());
}
static LayoutSnapshot saved() {
DockSplitDefinition split = new DockSplitDefinition(); split.setDestinationId("editors");
split.setFirst(new DockGroupDefinition("primary")); split.setSecond(new DockGroupDefinition("preview"));
DockLayout initial = new DockLayout(); initial.setCenter(split);
DockingManager manager = manager(initial);
manager.open(new Dockable(new DockableId("a"), new TextArea("A")), DockTarget.area("primary"));
manager.open(new Dockable(new DockableId("b"), new TextArea("B")), DockTarget.area("preview"));
return manager.snapshot();
}
static DockingManager manager(DockLayout initial) {
DockPane pane = new DockPane(); pane.setInitialLayout(initial);
Stage stage = new Stage(); stage.setScene(new Scene(pane, 900, 600));
return DockingManager.attach(stage, pane, new DockingOptions());
}
}
@@ -0,0 +1,71 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockLayout;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockSplitDefinition;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
/** Focus between already-selected visible contents must update saved active identity too. */
class SnapshotFocusTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void focusBetweenSelectedGroupsUpdatesTheSnapshotWithoutChangingItsGeometry() throws Exception {
AtomicReference<Fixture> fixture = new AtomicReference<>();
FxThread.onFx(() -> {
DockSplitDefinition split = new DockSplitDefinition();
split.setDestinationId("editors");
split.setFirst(new DockGroupDefinition("first"));
split.setSecond(new DockGroupDefinition("second"));
DockLayout initial = new DockLayout();
initial.setCenter(split);
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
Dockable first = new Dockable(new DockableId("first"), new TextArea("First editor"));
Dockable second = new Dockable(new DockableId("second"), new TextArea("Second editor"));
manager.open(first, DockTarget.area("first"));
manager.open(second, DockTarget.area("second"));
stage.show();
pane.applyCss();
pane.layout();
fixture.set(new Fixture(stage, manager, first, second));
});
try {
FxThread.onFx(() -> {
Fixture current = fixture.get();
current.manager().activate(current.first().getId());
assertSame(current.first().getContent(), current.stage().getScene().getFocusOwner());
var committed = current.manager().snapshot();
current.second().getContent().requestFocus();
assertSame(current.second().getContent(), current.stage().getScene().getFocusOwner());
assertSame(current.second(), current.manager().activeDockable());
assertEquals(current.second().getId(), current.manager().snapshot().activeDockableId(),
"A focus-only change must not leave the saved active identity stale");
assertEquals(committed.windows(), current.manager().snapshot().windows());
});
} finally { FxThread.onFx(() -> fixture.get().stage().hide()); }
}
private record Fixture(Stage stage, DockingManager manager, Dockable first, Dockable second) { }
}
@@ -0,0 +1,66 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.PickResult;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class SnapshotGeometryTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@Test
void aSelectionPublicationDuringResizeRetainsCommittedSnapshotSizesUntilRelease() throws Exception {
FxThread.onFx(() -> {
javafx.application.Platform.setImplicitExit(false);
DockLayout initial = new DockLayout(); initial.setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT); tools.setPreferredWidth(240); initial.setRight(tools);
DockPane pane = new DockPane(); pane.setInitialLayout(initial);
Stage stage = new Stage(); stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
manager.open(new Dockable(new DockableId("editor"), new TextArea("Editor")), DockTarget.area("editors"));
TextArea first = new TextArea("First");
manager.open(new Dockable(new DockableId("a"), first), DockTarget.area("tools"));
manager.open(new Dockable(new DockableId("b"), new TextArea("Second")), DockTarget.area("tools"));
manager.activate(new DockableId("a"));
stage.show();
try {
Node divider = pane.lookup(".dock-area-divider");
LayoutSnapshot before = manager.snapshot();
mouse(divider, MouseEvent.MOUSE_PRESSED, 0);
mouse(divider, MouseEvent.MOUSE_DRAGGED, -80);
pane.layout();
assertSame(before, manager.snapshot(), "A snapshot read cannot capture live resize geometry");
manager.activate(new DockableId("b"));
assertEquals(new DockableId("b"), group(manager.snapshot()).selected());
assertEquals(240, group(manager.snapshot()).expandedWidth(), 1,
"Selection publication cannot commit the still-dragged group width");
assertEquals(240, root(manager.snapshot()).preferredWidth(), 1);
mouse(divider, MouseEvent.MOUSE_RELEASED, -80);
assertEquals(320, group(manager.snapshot()).expandedWidth(), 1);
assertEquals(320, root(manager.snapshot()).preferredWidth(), 1);
assertEquals(320, manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow().preferredWidth(), 1);
} finally { stage.hide(); }
});
}
private static LayoutSnapshot.Root root(LayoutSnapshot snapshot) {
return snapshot.windows().getFirst().roots().stream()
.filter(root -> root.placement() == LayoutSnapshot.Placement.RIGHT).findFirst().orElseThrow();
}
private static LayoutSnapshot.Group group(LayoutSnapshot snapshot) { return (LayoutSnapshot.Group) root(snapshot).branch(); }
private static void mouse(Node node, javafx.event.EventType<MouseEvent> type, double screenX) {
node.fireEvent(new MouseEvent(type, 0, 0, screenX, 0, MouseButton.PRIMARY, 1,
false, false, false, false, type != MouseEvent.MOUSE_RELEASED, false, false,
false, false, false, new PickResult(node, 0, 0)));
}
}
@@ -0,0 +1,66 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** Persistence reads the completed public layout without retaining live JavaFX content. */
class SnapshotLayoutTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@Test
void snapshotKeepsCanonicalAliasesSettingsTabOrderAndSelectionAsImmutableVersionedData() throws Exception {
FxThread.onFx(() -> {
DockSplitDefinition editors = new DockSplitDefinition();
editors.setDestinationId("editors");
editors.setFirst(new DockGroupDefinition("primary"));
editors.setSecond(new DockGroupDefinition("preview"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT);
tools.setCollapsible(true);
tools.setMode(DockGroupMode.OVERLAY);
tools.setPreferredWidth(240);
DockLayout initial = new DockLayout();
initial.setCenter(editors);
initial.setRight(tools);
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
manager.open(new Dockable(new DockableId("a"), new TextArea("Unsaved A")), DockTarget.area("primary"));
manager.open(new Dockable(new DockableId("b"), new TextArea("Unsaved B")), DockTarget.area("preview"));
manager.move(new DockableId("b"), DockTarget.area("primary"));
manager.open(new Dockable(new DockableId("project"), new TextArea("Project")), DockTarget.area("tools"));
LayoutSnapshot snapshot = manager.snapshot();
assertEquals(1, snapshot.version());
assertEquals(1, snapshot.windows().size());
assertEquals(2, snapshot.windows().getFirst().roots().size(), "Aliases do not duplicate their canonical branch");
LayoutSnapshot.Group center = assertInstanceOf(LayoutSnapshot.Group.class,
snapshot.windows().getFirst().roots().stream()
.filter(root -> root.placement() == LayoutSnapshot.Placement.CENTER).findFirst().orElseThrow().branch());
assertEquals(java.util.Set.of(new DockAreaId("editors"), new DockAreaId("primary"), new DockAreaId("preview")),
java.util.Set.copyOf(center.aliases()));
assertEquals(java.util.List.of(new DockableId("a"), new DockableId("b")), center.tabs());
assertEquals(new DockableId("b"), center.selected());
LayoutSnapshot.Group side = assertInstanceOf(LayoutSnapshot.Group.class,
snapshot.windows().getFirst().roots().stream()
.filter(root -> root.placement() == LayoutSnapshot.Placement.RIGHT).findFirst().orElseThrow().branch());
assertEquals(DockGroupMode.OVERLAY, side.settings().mode());
assertEquals(240, side.expandedWidth(), 1);
assertFalse(side.collapsed());
assertEquals(new DockableId("project"), snapshot.activeDockableId());
assertThrows(UnsupportedOperationException.class, () -> center.tabs().clear());
assertThrows(UnsupportedOperationException.class, () -> snapshot.windows().clear());
manager.activate(new DockableId("a"));
assertEquals(new DockableId("b"), center.selected(), "Earlier snapshots never observe later selections");
assertNotEquals(snapshot, manager.snapshot());
});
}
}