Complete multiwindow restore, coordinated shutdown and keyboard docking

This commit is contained in:
2026-11-16 00:54:10 +01:00
parent 853c6c0115
commit 485451de26
55 changed files with 3624 additions and 178 deletions
@@ -11,5 +11,5 @@ public record CloseScope(Kind kind, List<DockableId> dockableIds) {
}
/** The entry point that requested consent. */
public enum Kind { TAB, FLOATING_WINDOW }
public enum Kind { TAB, FLOATING_WINDOW, MAIN_WINDOW, MANAGER_ONLY }
}
@@ -0,0 +1,52 @@
package de.neitzel.fx.docking;
import java.util.List;
import java.util.function.BiFunction;
/** Checks a concrete or area fallback against a detached plan before changing its ID order. */
final class DockCandidatePlacement {
private DockCandidatePlacement() { }
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(), "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 destination exists", null) : firstFailure;
}
static DockFailure affected(DockFailure failure, DockableId id) {
return new DockFailure(failure.code(), id, failure.message(), failure.cause(), failure.messageKey());
}
}
@@ -17,30 +17,45 @@ import java.util.concurrent.CompletionStage;
final class DockCloseCoordinator {
interface Host {
Optional<Dockable> find(DockableId id);
List<DockableId> allDockables();
Optional<List<DockableId>> floatingDockables(DockWindowId id);
Window owner(DockableId id);
void remove(List<DockableId> ids);
CompletionStage<ShutdownDecision> beforeShutdown(CloseScope.Kind kind);
void endManager(CloseScope.Kind kind);
}
private final Host host;
private final ReadOnlyObjectWrapper<CloseScope> scope = new ReadOnlyObjectWrapper<>(this, "closingScope");
private final LinkedHashMap<RequestKey, Pending> queued = new LinkedHashMap<>();
private Running running;
private boolean ended;
DockCloseCoordinator(Host host) { this.host = host; }
ReadOnlyObjectProperty<CloseScope> closingScopeProperty() { return scope.getReadOnlyProperty(); }
CloseScope scope() { return scope.get(); }
boolean coversWindow(DockWindowId id) {
return id != null && running != null && id.equals(running.pending.key.windowId);
return running != null && (global(running.pending.key) || id != null && id.equals(running.pending.key.windowId));
}
CompletionStage<CloseResult> requestTabClose(DockableId id) {
return request(new RequestKey(Objects.requireNonNull(id, "id"), null));
return request(new RequestKey(Objects.requireNonNull(id, "id"), null, CloseScope.Kind.TAB));
}
CompletionStage<CloseResult> requestFloatingWindowClose(DockWindowId id) {
return request(new RequestKey(null, Objects.requireNonNull(id, "id")));
return request(new RequestKey(null, Objects.requireNonNull(id, "id"), CloseScope.Kind.FLOATING_WINDOW));
}
CompletionStage<CloseResult> requestShutdown(CloseScope.Kind kind) {
if (kind != CloseScope.Kind.MAIN_WINDOW && kind != CloseScope.Kind.MANAGER_ONLY) {
throw new IllegalArgumentException("Shutdown requires a manager-wide scope");
}
return request(new RequestKey(null, null, kind));
}
private static boolean global(RequestKey key) {
return key.kind == CloseScope.Kind.MAIN_WINDOW || key.kind == CloseScope.Kind.MANAGER_ONLY;
}
private CompletionStage<CloseResult> request(RequestKey key) {
@@ -67,21 +82,31 @@ final class DockCloseCoordinator {
}
private void begin(Pending pending) {
if (ended) {
completeNoChange(pending);
return;
}
RequestKey key = pending.key;
List<DockableId> ids = key.windowId == null
? host.find(key.tabId).map(ignored -> List.of(key.tabId)).orElse(List.of())
: host.floatingDockables(key.windowId).orElse(List.of());
if (ids.isEmpty()) {
pending.completion.complete(new CloseResult.NoChange());
if (!queued.isEmpty()) Platform.runLater(this::nextQueued);
List<DockableId> ids = switch (key.kind) {
case TAB -> host.find(key.tabId).map(ignored -> List.of(key.tabId)).orElse(List.of());
case FLOATING_WINDOW -> host.floatingDockables(key.windowId).orElse(List.of());
case MAIN_WINDOW, MANAGER_ONLY -> host.allDockables();
};
if (ids.isEmpty() && !global(key)) {
completeNoChange(pending);
return;
}
Running request = new Running(pending, ids.stream().map(id -> host.find(id).orElseThrow()).toList());
running = request;
scope.set(new CloseScope(key.windowId == null ? CloseScope.Kind.TAB : CloseScope.Kind.FLOATING_WINDOW, ids));
scope.set(new CloseScope(key.kind, ids));
askNext(request);
}
private void completeNoChange(Pending pending) {
pending.completion.complete(new CloseResult.NoChange());
if (!queued.isEmpty()) Platform.runLater(this::nextQueued);
}
/** Synchronous answers drain iteratively; asynchronous answers resume on the FX thread. */
private void askNext(Running request) {
request.checking = true;
@@ -125,6 +150,30 @@ final class DockCloseCoordinator {
finish(request, new CloseResult.Vetoed(request.vetoes, request.failures));
return;
}
if (global(request.pending.key)) {
request.saving = true;
try {
CompletionStage<ShutdownDecision> save = Objects.requireNonNull(
host.beforeShutdown(request.pending.key.kind), "Shutdown callback returned no stage");
save.whenComplete((decision, failure) -> onFx(() -> saved(request, decision, failure)));
} catch (RuntimeException failure) {
saved(request, null, failure);
}
} else closeContents(request);
}
private void saved(Running request, ShutdownDecision decision, Throwable failure) {
if (running != request || !request.saving) return;
request.saving = false;
if (failure != null || decision == null) {
Throwable cause = failure == null ? new IllegalStateException("Shutdown callback returned no decision") : failure;
finish(request, new CloseResult.Rejected(new DockFailure(DockFailure.Code.SHUTDOWN_CALLBACK_FAILED,
null, "Before-shutdown callback failed", cause)));
} else if (decision == ShutdownDecision.CANCEL) finish(request, new CloseResult.Canceled());
else closeContents(request);
}
private void closeContents(Running request) {
host.remove(request.dockables.stream().map(Dockable::getId).toList());
List<DockFailure> cleanupFailures = new ArrayList<>();
for (Dockable dockable : request.dockables) {
@@ -136,13 +185,35 @@ final class DockCloseCoordinator {
dockable.getId(), "Closed Dockable resource release failed", cleanup));
}
}
if (global(request.pending.key)) {
try {
host.endManager(request.pending.key.kind);
} catch (RuntimeException cleanup) {
cleanupFailures.add(new DockFailure(DockFailure.Code.CLEANUP_FAILED, null,
"Docking manager resource release failed", cleanup));
}
ended = true;
}
finish(request, new CloseResult.Closed(cleanupFailures));
}
private void finish(Running request, CloseResult result) {
List<Pending> canceledShutdowns = new ArrayList<>();
if (!(result instanceof CloseResult.Closed) && !(result instanceof CloseResult.NoChange)) {
var iterator = queued.entrySet().iterator();
while (iterator.hasNext()) {
Pending pending = iterator.next().getValue();
if (global(pending.key)) {
canceledShutdowns.add(pending);
iterator.remove();
}
}
}
running = null;
scope.set(null);
request.pending.completion.complete(result);
// A waiting global request adopts the refusal; independent windows still advance in FIFO order.
canceledShutdowns.forEach(pending -> pending.completion.complete(result));
if (!queued.isEmpty()) Platform.runLater(this::nextQueued);
}
@@ -151,7 +222,7 @@ final class DockCloseCoordinator {
else Platform.runLater(action);
}
private record RequestKey(DockableId tabId, DockWindowId windowId) { }
private record RequestKey(DockableId tabId, DockWindowId windowId, CloseScope.Kind kind) { }
private static final class Pending {
final RequestKey key;
final CompletableFuture<CloseResult> completion = new CompletableFuture<>();
@@ -166,6 +237,7 @@ final class DockCloseCoordinator {
int index;
boolean awaiting;
boolean checking;
boolean saving;
Running(Pending pending, List<Dockable> dockables) {
this.pending = pending;
this.dockables = dockables;
@@ -72,11 +72,22 @@ final class DockDragController {
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));
close.setOnAction(event -> {
hideMenu(close);
manager.requestTabClose(id).thenAccept(result -> {
if (!(result instanceof CloseResult.Closed) && manager.activeDockable() != null
&& manager.activeDockable().getId().equals(id)) manager.restoreDragFocus(id);
});
});
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())));
pin.setOnAction(event -> {
hideMenu(pin);
currentGroup(id).ifPresent(group -> {
manager.updateGroup(group.id(), DockGroupChanges.builder().mode(group.mode() == DockGroupMode.DOCKED
? DockGroupMode.OVERLAY : DockGroupMode.DOCKED).build());
manager.restoreDragFocus(id);
});
});
ContextMenu menu = new ContextMenu(destinations, splits, close,
new MenuItem(manager.message("dock.action.float")), new MenuItem(manager.message("dock.action.return")), pin);
menu.setOnShowing(event -> {
@@ -144,10 +155,20 @@ final class DockDragController {
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));
item.setOnAction(event -> {
hideMenu(item);
manager.move(id, target);
});
return item;
}
private static void hideMenu(MenuItem item) {
MenuItem root = item;
while (root.getParentMenu() != null) root = root.getParentMenu();
// Close the popup before a workflow transfers focus or retires its owner window.
if (root.getParentPopup() != null) root.getParentPopup().hide();
}
void dispose() {
pane.removeEventFilter(MouseEvent.ANY, mouseHandler);
scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler);
@@ -415,9 +436,32 @@ final class DockDragController {
cancel();
manager.restoreDragFocus(id);
event.consume();
} else if (pressed == null && !event.isControlDown() && !event.isAltDown() && !event.isMetaDown()
&& (event.getCode() == KeyCode.CONTEXT_MENU
|| event.getCode() == KeyCode.F10 && event.isShiftDown())) {
if (showKeyboardMenu()) event.consume();
}
}
private boolean showKeyboardMenu() {
Node focused = scene.getFocusOwner();
for (GroupSurface surface : surfaces.get()) {
TabPane tabs = surface.tabs();
Node strip = headerStrip(tabs);
boolean ownsFocus = focused == tabs;
for (Node current = focused; !ownsFocus && current != null; current = current.getParent()) {
ownsFocus = current == strip;
}
if (!ownsFocus) continue;
Tab selected = tabs.getSelectionModel().getSelectedItem();
Node header = selected == null || strip == null ? null : strip.lookup("#" + selected.getId());
if (header == null || selected.getContextMenu() == null) return false;
if (!selected.getContextMenu().isShowing()) selected.getContextMenu().show(header, Side.BOTTOM, 0, 0);
return true;
}
return false;
}
private void cancel() {
pressed = null;
dragging = false;
@@ -7,7 +7,7 @@ public record DockFailure(Code code, DockableId dockableId, String message, Thro
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,
public enum Code { SHUTDOWN_CALLBACK_FAILED, MANAGER_CLOSED, 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 }
}
@@ -125,6 +125,10 @@ final class DockGroupPane extends TabPane {
@Override protected void layoutChildren() {
super.layoutChildren();
Node strip = ownedSkinChild("tab-header-area");
if (strip != null) {
for (Tab tab : getTabs()) DockTabPresentation.updateHeader(tab, strip.lookup("#" + tab.getId()));
}
Tab selected = getSelectionModel().getSelectedItem();
Node selectedContent = selected == null ? null : selected.getContent();
for (Node wrapper : getChildrenUnmodifiable()) {
@@ -58,6 +58,11 @@ final class DockLayoutCandidate {
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 remove(DockableId id) {
orders.values().forEach(order -> order.remove(id));
selections.replaceAll((group, selected) -> id.equals(selected) ? null : selected);
}
void place(DockableId id, DockGroupId group, int index) {
orders.values().forEach(order -> order.remove(id));
List<DockableId> order = orders.get(group);
@@ -38,7 +38,7 @@ final class DockLayoutTree {
private static final class Split implements Branch {
private Branch first;
private Branch second;
private final SplitPane pane = new SplitPane();
private final SplitPane pane = new DockSplitPane();
private double position = .5;
private boolean dragging;
private boolean collapsedAllocation;
@@ -30,6 +30,13 @@ final class DockOverlayLayer extends Region {
});
}
void resume() {
disposed = false;
if (registeredScene != null) registeredScene.removeEventFilter(MouseEvent.MOUSE_PRESSED, outsidePress);
registeredScene = getScene();
if (registeredScene != null) registeredScene.addEventFilter(MouseEvent.MOUSE_PRESSED, outsidePress);
}
void dispose() {
disposed = true;
if (registeredScene != null) registeredScene.removeEventFilter(MouseEvent.MOUSE_PRESSED, outsidePress);
@@ -20,6 +20,7 @@ public final class DockPane extends Region {
DockingManager manager;
public DockPane() {
sceneProperty().addListener((observable, previous, current) -> DockStyles.install(current));
getStyleClass().add("dock-pane");
getChildren().addAll(surface, overlays);
dropIndicator.getStyleClass().add("dock-drop-indicator");
@@ -20,7 +20,7 @@ final class DockResetPlan {
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);
DockFailure failure = DockCandidatePlacement.place(candidate, dockable, intended == null ? null : DockTarget.area(intended), check);
if (failure != null) {
if (fallback == null) return failure;
fallbackContents.add(dockable);
@@ -28,7 +28,7 @@ final class DockResetPlan {
}
// Home placements establish reference tabs before relative fallback positions are resolved.
for (Dockable dockable : fallbackContents) {
DockFailure failure = place(candidate, dockable, fallback, check);
DockFailure failure = DockCandidatePlacement.place(candidate, dockable, fallback, check);
if (failure != null) return failure;
}
// Relative fallback positions can shift earlier insertions; validate the completed plan too.
@@ -38,52 +38,10 @@ final class DockResetPlan {
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());
if (checked instanceof MoveCheck.Rejected rejected) return DockCandidatePlacement.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());
}
}
@@ -9,13 +9,19 @@ 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,
record DockRestorePreparation(Map<DockableId, Dockable> contents, List<DockableId> missingIds,
boolean layoutAdjusted, RestoreResult.Rejected rejection) {
static DockRestorePreparation resolve(DockLayoutCandidate candidate, DockableResolver resolver, DockTarget fallback,
java.util.function.BiFunction<Dockable, ResolvedDockTarget, MoveCheck> placement) {
return resolve(List.of(candidate), resolver, fallback, placement);
}
static DockRestorePreparation resolve(List<DockLayoutCandidate> candidates, DockableResolver resolver, DockTarget fallback,
java.util.function.BiFunction<Dockable, ResolvedDockTarget, MoveCheck> placement) {
Map<DockableId, Dockable> prepared = new LinkedHashMap<>();
List<DockableId> missing = new ArrayList<>();
var contentNodes = Collections.newSetFromMap(new IdentityHashMap<javafx.scene.Node, Boolean>());
for (DockingManager.Group group : candidate.groups()) {
int index = 0;
for (DockLayoutCandidate candidate : candidates) for (DockingManager.Group group : candidate.groups()) {
for (DockableId id : candidate.tabs(group.id())) {
DockableResolution resolution;
try {
@@ -29,8 +35,9 @@ record DockRestorePreparation(Map<DockableId, Dockable> contents, RestoreResult.
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));
missing.add(id);
candidate.remove(id);
continue;
}
Dockable dockable = ((DockableResolution.Available) resolution).dockable();
if (dockable == null) return rejected(prepared, new DockFailure(DockFailure.Code.DOCKABLE_LOAD_FAILED,
@@ -46,14 +53,39 @@ record DockRestorePreparation(Map<DockableId, Dockable> contents, RestoreResult.
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++));
}
}
List<Dockable> fallbackContents = new ArrayList<>();
for (DockLayoutCandidate candidate : candidates) for (DockingManager.Group group : candidate.groups()) {
for (DockableId id : candidate.tabs(group.id())) {
Dockable dockable = prepared.get(id);
MoveCheck checked = placement.apply(dockable,
new ResolvedDockTarget.Insertion(group.id(), candidate.tabs(group.id()).indexOf(id)));
if (checked instanceof MoveCheck.Rejected rejected) {
DockFailure failure = rejected.failure();
return rejected(prepared, new DockFailure(failure.code(), id, failure.message(), failure.cause(), failure.messageKey()));
if (fallback == null) return rejected(prepared, DockCandidatePlacement.affected(rejected.failure(), id));
candidate.remove(id);
fallbackContents.add(dockable);
}
}
}
return new DockRestorePreparation(Collections.unmodifiableMap(new LinkedHashMap<>(prepared)), null);
// Resolve fallbacks only after every surviving reference tab is known.
for (Dockable dockable : fallbackContents) {
DockFailure failure = DockCandidatePlacement.place(candidates.getFirst(), dockable, fallback, placement);
if (failure != null) return rejected(prepared, failure);
}
// Relative insertions can shift earlier positions, so validate the final plan before installation.
for (DockLayoutCandidate candidate : candidates) 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);
MoveCheck checked = placement.apply(prepared.get(id), new ResolvedDockTarget.Insertion(group.id(), index));
if (checked instanceof MoveCheck.Rejected rejected) {
return rejected(prepared, DockCandidatePlacement.affected(rejected.failure(), id));
}
}
}
return new DockRestorePreparation(Collections.unmodifiableMap(new LinkedHashMap<>(prepared)), List.copyOf(missing),
!missing.isEmpty() || !fallbackContents.isEmpty(), null);
}
static DockRestorePreparation rejected(Map<DockableId, Dockable> prepared, DockFailure primary) {
@@ -68,6 +100,6 @@ record DockRestorePreparation(Map<DockableId, Dockable> contents, RestoreResult.
"Prepared Dockable cleanup failed", failure));
}
}
return new DockRestorePreparation(Map.of(), new RestoreResult.Rejected(primary, cleanup));
return new DockRestorePreparation(Map.of(), List.of(), false, new RestoreResult.Rejected(primary, cleanup));
}
}
@@ -0,0 +1,18 @@
package de.neitzel.fx.docking;
import javafx.scene.Node;
import javafx.scene.control.SplitPane;
/** Exposes stable divider styling as soon as a docking split is laid out. */
final class DockSplitPane extends SplitPane {
@Override protected void layoutChildren() {
for (Node child : getChildrenUnmodifiable()) {
if (child.getStyleClass().contains("split-pane-divider")
&& !child.getStyleClass().contains("dock-divider")) {
child.getStyleClass().add("dock-divider");
child.applyCss();
}
}
super.layoutChildren();
}
}
@@ -0,0 +1,16 @@
package de.neitzel.fx.docking;
import javafx.scene.Scene;
import java.util.Objects;
/** Adds scoped defaults before application styles, without replacing the application's theme. */
final class DockStyles {
private static final String DEFAULTS = Objects.requireNonNull(DockStyles.class.getResource("docking.css")).toExternalForm();
private DockStyles() { }
static void install(Scene scene) {
if (scene != null && !scene.getStylesheets().contains(DEFAULTS)) scene.getStylesheets().addFirst(DEFAULTS);
}
}
@@ -0,0 +1,65 @@
package de.neitzel.fx.docking;
import javafx.beans.InvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding;
import javafx.scene.control.Tab;
/** Keeps icon-only accessibility text separate from the application's visible title. */
final class DockTabPresentation {
private final Tab tab;
private final Dockable dockable;
private final String closeName;
private final StringBinding text;
private final InvalidationListener appearanceChanged = observable -> refreshClass();
private DockTabPresentation(Tab tab, Dockable dockable, String closeName) {
this.tab = tab;
this.dockable = dockable;
this.closeName = closeName;
text = Bindings.createStringBinding(this::headerText,
dockable.titleProperty(), dockable.iconProperty(), dockable.accessibleNameProperty());
tab.textProperty().bind(text);
tab.getStyleClass().add("dock-tab-header");
refreshClass();
dockable.titleProperty().addListener(appearanceChanged);
dockable.iconProperty().addListener(appearanceChanged);
}
static void bind(Tab tab, Dockable dockable, String closeName) {
tab.getProperties().put(DockTabPresentation.class, new DockTabPresentation(tab, dockable, closeName));
}
static void updateHeader(Tab tab, javafx.scene.Node header) {
if (header == null) return;
if (tab.getProperties().get(DockTabPresentation.class) instanceof DockTabPresentation presentation) {
javafx.scene.Node close = header.lookup(".tab-close-button");
if (close != null) close.setAccessibleText(presentation.closeName);
}
}
static void unbind(Tab tab) {
if (tab.getProperties().remove(DockTabPresentation.class) instanceof DockTabPresentation presentation) {
presentation.dockable.titleProperty().removeListener(presentation.appearanceChanged);
presentation.dockable.iconProperty().removeListener(presentation.appearanceChanged);
tab.textProperty().unbind();
presentation.text.dispose();
}
}
private boolean iconOnly() {
return dockable.getIcon() != null && (dockable.getTitle() == null || dockable.getTitle().isBlank());
}
private String headerText() {
if (!iconOnly()) return dockable.getTitle();
String name = dockable.getAccessibleName();
return name == null || name.isBlank() ? dockable.getTitle() : name;
}
private void refreshClass() {
if (iconOnly()) {
if (!tab.getStyleClass().contains("dock-icon-only")) tab.getStyleClass().add("dock-icon-only");
} else tab.getStyleClass().remove("dock-icon-only");
}
}
@@ -21,6 +21,7 @@ public final class Dockable {
@Getter @Setter private CloseCheck closeCheck;
@Getter @Setter private Runnable onClosed;
private final StringProperty title = new SimpleStringProperty(this, "title", "");
private final StringProperty accessibleName = new SimpleStringProperty(this, "accessibleName", "");
private final ObjectProperty<Node> icon = new SimpleObjectProperty<>(this, "icon");
public Dockable(DockableId id, Node content) {
@@ -28,6 +29,11 @@ public final class Dockable {
this.content = Objects.requireNonNull(content, "content");
}
/** Name spoken for an icon-only tab; tabs with visible text use their title. */
public StringProperty accessibleNameProperty() { return accessibleName; }
public String getAccessibleName() { return accessibleName.get(); }
public void setAccessibleName(String value) { accessibleName.set(value); }
public StringProperty titleProperty() { return title; }
public String getTitle() { return title.get(); }
public void setTitle(String value) { title.set(value); }
@@ -21,6 +21,10 @@ public final class DockingManager {
private static final Object ATTACHMENT_KEY = new Object();
private final Stage stage;
private final DockPane pane;
private final javafx.scene.Scene mainScene;
private final MainWindowCloseMode mainWindowCloseMode;
private final java.util.function.Function<ShutdownRequest, java.util.concurrent.CompletionStage<ShutdownDecision>> beforeShutdown;
private boolean disposed;
private final PlacementRule placementRule;
private final DockMessages messages;
private final DockTarget fallbackTarget;
@@ -52,13 +56,29 @@ public final class DockingManager {
private final ReadOnlyObjectWrapper<Dockable> active = new ReadOnlyObjectWrapper<>(this, "activeDockable");
private final ReadOnlyObjectWrapper<DockLayoutView> layout = new ReadOnlyObjectWrapper<>(this, "layout");
private LayoutSnapshot publishedSnapshot;
private final javafx.event.EventHandler<javafx.stage.WindowEvent> mainCloseHandler = event -> {
event.consume();
requestMainWindowClose();
};
private final javafx.event.EventHandler<javafx.stage.WindowEvent> mainShownHandler = event -> {
boolean wasUpdating = updating;
updating = true;
try {
floatingWindows.values().forEach(window -> window.stage.show());
focus(active.get());
} finally { updating = wasUpdating; }
};
private DockingManager(Stage stage, DockPane pane, DockingOptions options) {
this.stage = stage;
this.pane = pane;
this.mainScene = stage.getScene();
this.mainWindowCloseMode = Objects.requireNonNull(options.getMainWindowCloseMode(), "mainWindowCloseMode");
this.beforeShutdown = Objects.requireNonNull(options.getBeforeShutdown(), "beforeShutdown");
this.messages = new DockMessages(options.getResourceBundle());
closing = new DockCloseCoordinator(new DockCloseCoordinator.Host() {
@Override public Optional<Dockable> find(DockableId id) { return findDockable(id); }
@Override public List<DockableId> allDockables() { return List.copyOf(dockables.keySet()); }
@Override public javafx.stage.Window owner(DockableId id) { return DockingManager.this.owner(containing(id)); }
@Override public Optional<List<DockableId>> floatingDockables(DockWindowId id) {
FloatingWindow window = floatingWindows.get(id);
@@ -69,6 +89,11 @@ public final class DockingManager {
.map(tab -> (DockableId) tab.getUserData()).toList());
}
@Override public void remove(List<DockableId> ids) { removeDockables(ids); }
@Override public java.util.concurrent.CompletionStage<ShutdownDecision> beforeShutdown(CloseScope.Kind kind) {
return DockingManager.this.beforeShutdown.apply(new ShutdownRequest(snapshot(),
kind == CloseScope.Kind.MAIN_WINDOW ? ShutdownReason.MAIN_WINDOW : ShutdownReason.MANAGER_ONLY));
}
@Override public void endManager(CloseScope.Kind kind) { releaseManager(kind); }
});
this.placementRule = Objects.requireNonNull(options.getPlacementRule(), "placementRule");
this.fallbackTarget = options.getFallbackTarget();
@@ -78,6 +103,7 @@ public final class DockingManager {
this.floatingWindowCustomizer = Objects.requireNonNull(options.getFloatingWindowCustomizer(), "floatingWindowCustomizer");
DockLayout initial = Objects.requireNonNull(pane.getInitialLayout(), "initialLayout");
validate(initial);
pane.overlays.resume();
addGroup(initial.getCenter(), pane.surface::setCenter);
addEdgeGroup(initial.getLeft(), javafx.geometry.Side.LEFT);
addEdgeGroup(initial.getRight(), javafx.geometry.Side.RIGHT);
@@ -91,7 +117,11 @@ public final class DockingManager {
refreshEmptyGroups();
publish();
initialWindow = snapshot().windows().getFirst();
stage.getScene().focusOwnerProperty().addListener(focusListener);
mainScene.focusOwnerProperty().addListener(focusListener);
stage.addEventHandler(javafx.stage.WindowEvent.WINDOW_SHOWN, mainShownHandler);
if (mainWindowCloseMode == MainWindowCloseMode.AUTOMATIC) {
stage.addEventFilter(javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST, mainCloseHandler);
}
}
public static DockingManager attach(Stage stage, DockPane pane, DockingOptions options) {
@@ -113,6 +143,8 @@ public final class DockingManager {
public ActionResult open(Dockable dockable, DockTarget target) {
requireFxThread();
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
if (globalClosePending()) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "A manager-wide close is pending");
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
Objects.requireNonNull(dockable, "dockable");
if (dockables.containsKey(dockable.getId())) return activate(dockable.getId());
@@ -158,7 +190,7 @@ public final class DockingManager {
event.consume();
requestTabClose(dockable.getId());
});
tab.textProperty().bind(dockable.titleProperty());
DockTabPresentation.bind(tab, dockable, message("dock.action.close"));
tab.graphicProperty().bind(dockable.iconProperty());
tab.setContent(dockable.getContent());
tab.setUserData(dockable.getId());
@@ -168,6 +200,8 @@ public final class DockingManager {
/** 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 (disposed) return new ActionResult.Rejected(managerClosedFailure());
if (globalClosePending()) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "A manager-wide close is pending");
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
Objects.requireNonNull(id, "id");
Objects.requireNonNull(factory, "factory");
@@ -199,6 +233,7 @@ public final class DockingManager {
/** Restores the captured starting arrangement while retaining every live Dockable. */
public ActionResult resetLayout() {
requireFxThread();
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
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,
@@ -232,6 +267,7 @@ public final class DockingManager {
public ActionResult activate(DockableId id) {
requireFxThread();
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
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");
@@ -274,6 +310,7 @@ public final class DockingManager {
/** Requests consent without closing or releasing content while the answer is pending. */
public java.util.concurrent.CompletionStage<CloseResult> requestTabClose(DockableId id) {
requireFxThread();
if (disposed && closing.scope() == null) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.NoChange());
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
return closing.requestTabClose(id);
}
@@ -281,6 +318,7 @@ public final class DockingManager {
/** Requests every contained Dockable's consent before closing a floating window. */
public java.util.concurrent.CompletionStage<CloseResult> requestFloatingWindowClose(DockWindowId id) {
requireFxThread();
if (disposed && closing.scope() == null) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.NoChange());
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
Objects.requireNonNull(id, "id");
if (layout.get().windows().getFirst().id().equals(id)) {
@@ -290,11 +328,64 @@ public final class DockingManager {
return closing.requestFloatingWindowClose(id);
}
/** Collects consent and saves the complete layout before closing this manager's windows. */
public java.util.concurrent.CompletionStage<CloseResult> requestMainWindowClose() {
requireFxThread();
if (disposed && closing.scope() == null) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.NoChange());
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
return closing.requestShutdown(CloseScope.Kind.MAIN_WINDOW);
}
/** Ends this embedded manager while preserving the application's main Stage. */
public java.util.concurrent.CompletionStage<CloseResult> requestManagerClose() {
requireFxThread();
if (disposed && closing.scope() == null) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.NoChange());
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
return closing.requestShutdown(CloseScope.Kind.MANAGER_ONLY);
}
/** Scope remains available until checks and resource release have finished. */
public ReadOnlyObjectProperty<CloseScope> closingScopeProperty() {
return closing.closingScopeProperty();
}
private boolean globalClosePending() {
CloseScope scope = closing.scope();
return scope != null && (scope.kind() == CloseScope.Kind.MAIN_WINDOW || scope.kind() == CloseScope.Kind.MANAGER_ONLY);
}
private DockFailure managerClosedFailure() {
return new DockFailure(DockFailure.Code.MANAGER_CLOSED, null, "The docking manager has ended", null);
}
private void releaseManager(CloseScope.Kind kind) {
if (disposed) return;
disposed = true;
boolean wasUpdating = updating;
updating = true;
try {
drag.dispose();
mainScene.focusOwnerProperty().removeListener(focusListener);
stage.removeEventHandler(javafx.stage.WindowEvent.WINDOW_SHOWN, mainShownHandler);
stage.removeEventFilter(javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST, mainCloseHandler);
floatingWindows.values().forEach(this::disposeFloatingWindow);
floatingWindows.clear();
groupWindows.clear();
tree.clear();
pane.clearAreas();
pane.overlays.dispose();
groups.clear();
edgeAreas.clear();
groupActivationOrder.clear();
previousFocus.clear();
activationOrder.clear();
pane.manager = null;
if (stage.getProperties().get(ATTACHMENT_KEY) == this) stage.getProperties().remove(ATTACHMENT_KEY);
} finally { updating = wasUpdating; }
publish();
if (kind == CloseScope.Kind.MAIN_WINDOW && mainWindowCloseMode == MainWindowCloseMode.AUTOMATIC) stage.hide();
}
private void removeDockables(List<DockableId> ids) {
Dockable previousActive = active.get();
Group previousGroup = previousActive == null ? null : containing(previousActive.getId());
@@ -305,6 +396,7 @@ public final class DockingManager {
if (group == null) continue;
Tab tab = group.tabs.getTabs().get(tabIndex(group, id));
dragFor(group).uninstallTab(tab);
DockTabPresentation.unbind(tab);
tab.textProperty().unbind();
tab.graphicProperty().unbind();
tab.setGraphic(null);
@@ -340,6 +432,7 @@ public final class DockingManager {
if (layoutChanging) return true;
CloseScope scope = closing.scope();
if (scope == null) return false;
if (scope.kind() == CloseScope.Kind.MAIN_WINDOW || scope.kind() == CloseScope.Kind.MANAGER_ONLY) return true;
if (scope.kind() == CloseScope.Kind.FLOATING_WINDOW) {
return group != null && closing.coversWindow(groupWindows.get(group.id));
}
@@ -352,6 +445,7 @@ public final class DockingManager {
/** Resolves a move without mutating content, layout or identity allocation. */
public MoveCheck checkMove(DockableId id, DockTarget target) {
requireFxThread();
if (disposed) return new MoveCheck.Rejected(managerClosedFailure());
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");
@@ -583,6 +677,7 @@ public final class DockingManager {
/** Applies explicitly supplied settings as one validated group change. */
public ActionResult updateGroup(DockGroupId id, DockGroupChanges changes) {
requireFxThread();
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
Objects.requireNonNull(changes, "changes");
Group group = group(Objects.requireNonNull(id, "id"));
@@ -675,6 +770,7 @@ public final class DockingManager {
private ActionResult setGroupCollapsed(DockGroupId id, boolean collapsed, boolean focusHeader) {
requireFxThread();
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
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");
@@ -779,6 +875,7 @@ public final class DockingManager {
/** Prepares fresh content for an empty manager, then installs the validated layout as one change. */
public RestoreResult restore(LayoutSnapshot snapshot, DockableResolver resolver) {
requireFxThread();
if (disposed) return new RestoreResult.Rejected(managerClosedFailure(), List.of());
Objects.requireNonNull(snapshot, "snapshot");
Objects.requireNonNull(resolver, "resolver");
if (layoutChanging) return new RestoreResult.Rejected(layoutChangeFailure(), List.of());
@@ -789,20 +886,48 @@ public final class DockingManager {
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);
List<DockLayoutCandidate> candidates = snapshot.windows().stream().map(this::prepareLayoutCandidate).toList();
java.util.Set<DockGroupId> floatingGroups = candidates.stream().filter(candidate -> !candidate.window.main())
.flatMap(candidate -> candidate.groups().stream()).map(Group::id).collect(java.util.stream.Collectors.toSet());
DockRestorePreparation prepared = DockRestorePreparation.resolve(candidates, resolver, fallbackTarget, (dockable, target) -> {
if (dockable.isMainWindowOnly() && target instanceof ResolvedDockTarget.Insertion insertion
&& floatingGroups.contains(insertion.groupId())) {
return moveRejected(DockFailure.Code.MAIN_WINDOW_ONLY, dockable.getId(), "This Dockable must remain in the main window");
}
return checkPlacement(dockable, target);
});
if (prepared.rejection() != null) return prepared.rejection();
if (prepared.layoutAdjusted()) candidates.forEach(DockLayoutCandidate::normalize);
candidates = candidates.stream().filter(candidate -> candidate.window.main()
|| candidate.groups().stream().anyMatch(group -> !candidate.tabs(group.id).isEmpty())).toList();
if (snapshot.activeDockableId() != null) for (DockLayoutCandidate candidate : candidates) {
candidate.groups().stream().filter(group -> candidate.tabs(group.id).contains(snapshot.activeDockableId())).findFirst()
.ifPresent(group -> candidate.select(group.id, snapshot.activeDockableId()));
}
Map<DockWindowId, FloatingWindow> hosts = new LinkedHashMap<>();
try {
for (DockLayoutCandidate candidate : candidates) if (!candidate.window.main()) {
hosts.put(candidate.window.id(), prepareFloatingWindow(candidate.window.id(),
DockWindowBounds.fit(candidate.window.bounds())));
}
} catch (FloatingPreparationFailure failure) {
hosts.values().forEach(this::disposeFloatingWindow);
return DockRestorePreparation.rejected(prepared.contents(), new DockFailure(
DockFailure.Code.WINDOW_CREATION_FAILED, null, "Floating window preparation failed", failure.getCause())).rejection();
}
initialIntents.clear();
initialIntents.putAll(snapshot.initialIntents());
snapshot.initialIntents().forEach((id, area) -> {
if (prepared.contents().containsKey(id)) initialIntents.put(id, area);
});
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());
snapshot.returnPositions().forEach((id, position) -> {
if (prepared.contents().containsKey(id)) returnTargets.put(id,
new ReturnLocation(position.target(), position.areaId()));
});
installLayoutCandidates(candidates, hosts, prepared.contents(), snapshot.activeDockableId());
return new RestoreResult.Applied(prepared.missingIds());
} finally {
layoutChanging = false;
}
@@ -825,6 +950,11 @@ public final class DockingManager {
private void installLayoutCandidate(DockLayoutCandidate candidate, Map<DockableId, Dockable> contents,
DockableId activeId) {
installLayoutCandidates(List.of(candidate), Map.of(), contents, activeId);
}
private void installLayoutCandidates(List<DockLayoutCandidate> candidates, Map<DockWindowId, FloatingWindow> hosts,
Map<DockableId, Dockable> contents, DockableId activeId) {
Map<DockableId, Dockable> installed = new LinkedHashMap<>(contents);
boolean wasUpdating = updating;
updating = true;
@@ -832,6 +962,7 @@ public final class DockingManager {
for (Group old : groups.values()) {
for (Tab tab : List.copyOf(old.tabs.getTabs())) {
dragFor(old).uninstallTab(tab);
DockTabPresentation.unbind(tab);
tab.textProperty().unbind();
tab.graphicProperty().unbind();
tab.setGraphic(null);
@@ -851,38 +982,49 @@ public final class DockingManager {
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);
floatingWindows.putAll(hosts);
for (DockLayoutCandidate candidate : candidates) {
FloatingWindow host = hosts.get(candidate.window.id());
DockPane destinationPane = host == null ? pane : host.pane;
DockLayoutTree destinationTree = host == null ? tree : host.tree;
DockDragController destinationDrag = host == null ? drag : host.drag;
for (Group group : candidate.groups()) {
groups.put(group.id, group);
if (host != null) groupWindows.put(group.id, host.id);
allocatedGroupIds.add(group.id);
for (DockableId id : candidate.tabs(group.id)) {
Tab tab = prepareTab(installed.get(id));
destinationDrag.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();
}
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());
});
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(destinationPane.surface::setCenter);
else {
javafx.geometry.Side side = javafx.geometry.Side.valueOf(root.placement().name());
DockAreaId areaId = root.branch().aliases().getFirst();
Map<DockAreaId, javafx.geometry.Side> destinationEdges = host == null ? edgeAreas : host.edgeAreas;
root.branch().aliases().forEach(alias -> destinationEdges.put(alias, side));
placements.add(node -> {
destinationPane.setArea(side, node, () -> canResizeEdge(destinationPane, destinationTree,
host == null ? null : host.id, areaId, side), this::publish);
destinationPane.setAreaExtent(side, root.preferredWidth(), root.preferredHeight());
});
}
}
destinationTree.installFrom(candidate.tree, placements);
destinationTree.view().forEach(area -> allocatedAreaIds.add(area.id()));
}
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);
if (stage.isShowing()) hosts.values().forEach(host -> host.stage.show());
focus(active.get());
} finally {
updating = wasUpdating;
@@ -903,11 +1045,16 @@ public final class DockingManager {
}
private boolean canResizeEdge(DockAreaId areaId, javafx.geometry.Side side) {
if (tree.groups(areaId).stream().anyMatch(this::groupClosing)) return false;
return canResizeEdge(pane, tree, null, areaId, side);
}
private boolean canResizeEdge(DockPane ownerPane, DockLayoutTree ownerTree, DockWindowId ownerId,
DockAreaId areaId, javafx.geometry.Side side) {
if (ownerTree.groups(areaId).stream().anyMatch(this::groupClosing)) return false;
for (Group candidate : groups.values()) {
if (groupWindows.containsKey(candidate.id) || !groupClosing(candidate)) continue;
if (contains(pane.surface.getCenter(), ((DockGroupPane) candidate.tabs).surface())) return false;
javafx.geometry.Side otherSide = pane.edgeOf(candidate.tabs);
if (!Objects.equals(groupWindows.get(candidate.id), ownerId) || !groupClosing(candidate)) continue;
if (contains(ownerPane.surface.getCenter(), ((DockGroupPane) candidate.tabs).surface())) return false;
javafx.geometry.Side otherSide = ownerPane.edgeOf(candidate.tabs);
if (side.isHorizontal() && otherSide != null && otherSide.isVertical()) return false;
}
return true;
@@ -923,13 +1070,19 @@ public final class DockingManager {
if (!changingOuterExtent) return !groupClosing(group);
}
if (treeFor(group).geometryAffects(group.id, this::groupClosing)) return false;
if (groupWindows.containsKey(group.id)) return true;
for (var entry : edgeAreas.entrySet()) {
List<Group> areaGroups = tree.groups(entry.getKey());
DockWindowId windowId = groupWindows.get(group.id);
FloatingWindow host = windowId == null ? null : floatingWindows.get(windowId);
DockLayoutTree ownerTree = host == null ? tree : host.tree;
DockPane ownerPane = host == null ? pane : host.pane;
Map<DockAreaId, javafx.geometry.Side> ownerEdges = host == null ? edgeAreas : host.edgeAreas;
for (var entry : ownerEdges.entrySet()) {
List<Group> areaGroups = ownerTree.groups(entry.getKey());
if (!areaGroups.contains(group)) continue;
boolean onlyExpandedGroup = areaGroups.stream().filter(candidate -> candidate != group)
.allMatch(candidate -> !candidate.tabs.isManaged() || ((DockGroupPane) candidate.tabs).isCollapsed());
if (changingOuterExtent || onlyExpandedGroup) return canResizeEdge(entry.getKey(), entry.getValue());
if (changingOuterExtent || onlyExpandedGroup) {
return canResizeEdge(ownerPane, ownerTree, windowId, entry.getKey(), entry.getValue());
}
}
return true;
}
@@ -1035,7 +1188,7 @@ public final class DockingManager {
Stage window = owner(containing(dockable.getId()));
window.getScene().getRoot().applyCss();
window.getScene().getRoot().layout();
if (window != stage && !window.isShowing()) window.show();
if (window != stage && stage.isShowing() && !window.isShowing()) window.show();
if (window.isShowing()) {
window.toFront();
window.requestFocus();
@@ -1103,29 +1256,16 @@ public final class DockingManager {
} finally {
updating = wasUpdating;
}
var areas = tree.view().stream().map(area -> {
javafx.geometry.Side side = edgeAreas.get(area.id());
if (side == null) return area;
double extent = pane.committedExtent(side);
return new DockLayoutView.Area(area.id(), area.groups(), area.root(),
side.isVertical() ? extent : -1, side.isHorizontal() ? extent : -1);
}).toList();
var windows = new java.util.ArrayList<DockLayoutView.Window>();
windows.add(new DockLayoutView.Window(new DockWindowId("main"), true, areas));
windows.add(new DockLayoutView.Window(new DockWindowId("main"), true, layoutAreas(tree, pane, edgeAreas)));
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();
window.id, false, layoutAreas(window.tree, window.pane, window.edgeAreas), window.geometry.bounds())));
List<LayoutSnapshot.Root> mainRoots = snapshotRoots(tree, pane, edgeAreas, false);
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()))));
window.id, false, window.geometry.bounds(), snapshotRoots(window.tree, window.pane, window.edgeAreas,
window.geometry.hasPendingChanges()))));
Map<DockableId, LayoutSnapshot.ReturnPosition> positions = new LinkedHashMap<>();
returnTargets.forEach((id, position) -> positions.put(id,
new LayoutSnapshot.ReturnPosition(position.target, position.areaId)));
@@ -1134,6 +1274,29 @@ public final class DockingManager {
layout.set(new DockLayoutView(windows));
}
private static List<DockLayoutView.Area> layoutAreas(DockLayoutTree tree, DockPane pane,
Map<DockAreaId, javafx.geometry.Side> edges) {
return tree.view().stream().map(area -> {
javafx.geometry.Side side = edges.get(area.id());
if (side == null) return area;
double extent = pane.committedExtent(side);
return new DockLayoutView.Area(area.id(), area.groups(), area.root(),
side.isVertical() ? extent : -1, side.isHorizontal() ? extent : -1);
}).toList();
}
private static List<LayoutSnapshot.Root> snapshotRoots(DockLayoutTree tree, DockPane pane,
Map<DockAreaId, javafx.geometry.Side> edges,
boolean windowResizing) {
return tree.snapshotRoots(edges, windowResizing || 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();
}
private Stage owner(Group group) {
DockWindowId id = group == null ? null : groupWindows.get(group.id);
return id == null ? stage : floatingWindows.get(id).stage;
@@ -1168,6 +1331,24 @@ public final class DockingManager {
}
private Group createFloatingGroup(javafx.geometry.Rectangle2D bounds) {
DockWindowId candidateId;
do { candidateId = new DockWindowId("floating-" + ++nextWindowId); }
while (floatingWindows.containsKey(candidateId) || allocatedAreaIds.contains(new DockAreaId(candidateId.value())));
DockWindowId windowId = candidateId;
FloatingWindow host = prepareFloatingWindow(windowId, bounds);
allocatedAreaIds.add(new DockAreaId(windowId.value()));
DockGroupId groupId;
do { groupId = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(groupId));
DockGroupDefinition definition = new DockGroupDefinition(windowId.value());
definition.setPersistent(false);
Group group = createGroup(groupId, definition);
groupWindows.put(group.id, windowId);
host.tree.addArea(definition, host.pane.surface::setCenter, ignored -> group);
floatingWindows.put(windowId, host);
return group;
}
private FloatingWindow prepareFloatingWindow(DockWindowId windowId, javafx.geometry.Rectangle2D bounds) {
FloatingWindowConfiguration configuration = new FloatingWindowConfiguration();
try {
floatingWindowCustomizer.accept(configuration);
@@ -1176,10 +1357,6 @@ public final class DockingManager {
} catch (RuntimeException failure) {
throw new FloatingPreparationFailure(failure);
}
DockWindowId candidateId;
do { candidateId = new DockWindowId("floating-" + ++nextWindowId); }
while (!allocatedAreaIds.add(new DockAreaId(candidateId.value())));
DockWindowId windowId = candidateId;
DockPane floatingPane = new DockPane();
Stage floatingStage = new Stage();
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
@@ -1191,27 +1368,21 @@ public final class DockingManager {
floatingStage.setTitle(configuration.getTitle());
floatingStage.getIcons().setAll(configuration.getIcons());
floatingStage.getScene().getStylesheets().setAll(configuration.getStylesheets());
DockStyles.install(floatingStage.getScene());
floatingStage.setX(bounds.getMinX());
floatingStage.setY(bounds.getMinY());
floatingStage.setWidth(bounds.getWidth());
floatingStage.setHeight(bounds.getHeight());
DockLayoutTree floatingTree = new DockLayoutTree(this::publish, id -> !groupClosing(group(id)));
DockGroupId groupId;
do { groupId = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(groupId));
DockGroupDefinition definition = new DockGroupDefinition(windowId.value());
definition.setPersistent(false);
Group group = createGroup(groupId, definition);
groupWindows.put(group.id, windowId);
floatingTree.addArea(definition, floatingPane.surface::setCenter, ignored -> group);
DockDragController floatingDrag = new DockDragController(this, floatingPane, () -> groups.values().stream()
.filter(candidate -> windowId.equals(groupWindows.get(candidate.id)))
.map(candidate -> new DockDragController.GroupSurface(candidate.id, candidate.tabs)).toList());
.map(candidate -> new DockDragController.GroupSurface(candidate.id, candidate.tabs,
floatingPane.edgeOf(candidate.tabs))).toList());
DockWindowGeometry geometry = new DockWindowGeometry(floatingStage, this::publish);
floatingWindows.put(windowId, new FloatingWindow(windowId, floatingStage, floatingPane, floatingTree, floatingDrag, geometry, closeHandler));
floatingPane.manager = this;
floatingStage.getProperties().put(ATTACHMENT_KEY, this);
floatingStage.getScene().focusOwnerProperty().addListener(focusListener);
return group;
return new FloatingWindow(windowId, floatingStage, floatingPane, floatingTree, floatingDrag, geometry, closeHandler, new LinkedHashMap<>());
}
private static final class FloatingPreparationFailure extends RuntimeException {
@@ -1220,7 +1391,8 @@ public final class DockingManager {
private record FloatingWindow(DockWindowId id, Stage stage, DockPane pane, DockLayoutTree tree,
DockDragController drag, DockWindowGeometry geometry,
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler) { }
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler,
Map<DockAreaId, javafx.geometry.Side> edgeAreas) { }
private record ReturnLocation(DockTarget target, DockAreaId areaId) { }
private static ActionResult rejected(DockFailure.Code code, DockableId id, String message) {
@@ -7,6 +7,9 @@ import java.util.Optional;
/** Attachment options. Additional policies are introduced with their operations. */
@Getter @Setter
public final class DockingOptions {
private MainWindowCloseMode mainWindowCloseMode = MainWindowCloseMode.AUTOMATIC;
private java.util.function.Function<ShutdownRequest, java.util.concurrent.CompletionStage<ShutdownDecision>> beforeShutdown =
request -> java.util.concurrent.CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
/** 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();
@@ -0,0 +1,4 @@
package de.neitzel.fx.docking;
/** Selects who handles and finally closes the main Stage. */
public enum MainWindowCloseMode { AUTOMATIC, APPLICATION_COORDINATED }
@@ -0,0 +1,4 @@
package de.neitzel.fx.docking;
/** Final application decision after saving or retrying the pre-close snapshot. */
public enum ShutdownDecision { PROCEED, CANCEL }
@@ -0,0 +1,4 @@
package de.neitzel.fx.docking;
/** Distinguishes closing the main window from replacing its embedded manager. */
public enum ShutdownReason { MAIN_WINDOW, MANAGER_ONLY }
@@ -0,0 +1,9 @@
package de.neitzel.fx.docking;
/** Immutable pre-close state passed after every Dockable has consented. */
public record ShutdownRequest(LayoutSnapshot snapshot, ShutdownReason reason) {
public ShutdownRequest {
java.util.Objects.requireNonNull(snapshot, "snapshot");
java.util.Objects.requireNonNull(reason, "reason");
}
}