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
+1
View File
@@ -15,6 +15,7 @@
- [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.
- [Quit, save and replace a workspace](docs/docking-shutdown.md), with global consent, retry and main-window ownership.
- [Dependency injection](../injection/README.md).
## Introduction
+3 -2
View File
@@ -95,5 +95,6 @@ Append `fxml` to the launch command for the FXML screen. The classpath separator
shown is for macOS/Linux; use `;` on Windows. A graphical desktop session is
required. The launch class is ordinary Java and delegates to the Application.
Dockable-owned bars and optional MVVM bindings are a later integration step;
the standalone controls already support ordinary JavaFX property bindings.
The [MVVM docking editor](../../fx-example/docs/docking-mvvm.md) demonstrates
Dockable-owned bars and optional MVVM bindings alongside a plain JavaFX editor.
The standalone controls also support ordinary JavaFX property bindings.
+151
View File
@@ -0,0 +1,151 @@
# Accessible names and translated docking actions
A Dockable with a visible title uses that title as its accessible tab name.
For an icon-only tab, supply an application name:
```java
Dockable project = new Dockable(new DockableId("project"), projectView);
project.setIcon(projectIcon);
project.setAccessibleName("Project files");
```
`accessibleNameProperty()` is bindable. It names an icon-only tab, whose title
is empty or blank; it does not replace the spoken name of a visibly titled tab.
The application title and original icon remain unchanged when the tab moves or
floats. JavaFX exposes the accessible name as the header's text attribute while
the default stylesheet displays only its graphic. An application supplying an
icon-only tab must supply a meaningful name; an unnamed icon has no useful
spoken label.
## Translations and placement failures
Set `DockingOptions.resourceBundle` before attaching the manager. Its String
entries are captured at attachment, so replacing the options bundle afterward
does not alter an existing manager. Unspecified built-in keys use the library's
English defaults. The tab header's close button also uses `dock.action.close`
as its accessible action name, including after a transfer into a floating window.
Action keys include `dock.action.move`, `split`, `close`,
`float`, `return`, and `pin` with the same `dock.action.` prefix. Direction keys
are `dock.side.TOP`, `RIGHT`, `BOTTOM`, and `LEFT` with `dock.side.` as the prefix.
Placement rules can attach an application message key without losing technical
diagnostics:
```java
DockFailure failure = new DockFailure(DockFailure.Code.PLACEMENT_REJECTED,
dockableId, "Workspace policy prohibits this destination", cause,
"workspace.destination.locked");
String visibleText = manager.describeFailure(failure);
```
The built-in context menus use the same `describeFailure` method as application
commands. An available application key wins. A missing application key falls
back to the failure code's default text (`dock.failure.` followed by the enum
name), not the technical diagnostic string. Code, key, diagnostic message and
cause remain available unchanged on the failure. Existing failures without a
key retain their supplied message unless the bundle overrides the code text.
`dock.action.unavailable` and `dock.action.noChange` are MessageFormat patterns.
The former accepts the action name and reason; the latter accepts the action
name. Keep those placeholders in translations.
## Application styles
A DockPane installs the library's scoped `docking.css` before existing Scene
stylesheets. Add your application theme to the Scene as usual. Configure a
floating window's stylesheets through `floatingWindowCustomizer` when the same
theme should apply there. The floating drag-preview popup inherits its owner's
Scene styles; it does not open a separate unthemed application window.
The tab-header hook is `.dock-tab-header`. An icon-only header additionally has
`.dock-icon-only`; keep its graphic-only content display if the visible header
should remain an icon. `.dock-drop-indicator` styles the in-window preview;
its `:no-change` pseudo-class identifies a drop which retains the placement.
The outside-window preview uses `.dock-floating-preview-frame` for fill/stroke
and `.dock-floating-preview-label` for the action label.
```css
.dock-tab-header { -fx-background-color: #dce8f1; }
.dock-drop-indicator { -fx-fill: rgba(30, 100, 180, 0.2); -fx-stroke: #1e64b4; }
.dock-floating-preview-frame { -fx-fill: rgba(30, 100, 180, 0.2); -fx-stroke: #1e64b4; }
```
The application retains control over color contrast and focus visibility when
replacing JavaFX's control styles.
`.dock-divider` styles split dividers from their first layout, and
`.dock-area-divider` styles the draggable boundary of an outer area.
`.dock-edge-area` is the outer area container. `.dock-group` is its TabPane;
`.dock-group:collapsed` identifies a closed rail. `.dock-group-surface` is the
space reserved for a group, and `.dock-overlay-layer` contains overlay groups.
These hooks are available in both main and floating DockPanes. Default divider
colors use JavaFX's looked-up theme colors, so replacing the application's base
palette also affects them.
## Keyboard commands
Focus the group's TabPane or one of its tab headers, then press **Shift+F10**
or the keyboard's **Context Menu** key. Arrow keys select actions and navigate
Move/Split submenus; Enter executes the highlighted enabled action. Move,
Split, Float, Return, Pin and Close use the manager's normal placement rules and
close consent. A successful transfer restores the content focus and keeps its
selection. Pinning and a vetoed Close return focus to the surviving content.
If the user activates another Dockable while asynchronous consent is pending,
a later veto preserves that newer focus choice.
An editor's own keyboard context menu remains the editor's responsibility.
## Runnable exercise
Launch `de.neitzel.fx.example.docking.KeyboardThemeDockingMain` from `fx-example`.
It provides a shared application theme, a named icon-only Project tab and
German docking action labels. **Focus active tab strip** places focus at the
keyboard entry point; then use Shift+F10, arrows and Enter.
- Float Notes and immediately type over the selected `cd` in `abcdef`.
Return it through the same menu and continue typing at its caret.
- Toggle **Block floating**. Compare **Check Float** with the disabled Float
menu item. Toggle **Missing translation key** to see the failure-code fallback.
- Close Notes with **Allow Notes to close** unchecked to exercise a veto, then
enable it and repeat to close the tab.
- Use the Project menu to pin/unpin its whole group. Its main-window-only flag
keeps Float unavailable. Drag another tab to inspect the themed preview and
split/outer dividers in both window types.
The native keyboard qualification uses the public `javafx.scene.robot.Robot`
for the real Shift+F10 chord and `java.awt.Robot` for arrow navigation, Enter
and typing. It selects actions
by their focused accessible names, then types `1` and `2` without repairing
content focus: `abcdef` with
`cd` selected becomes `ab1ef`, then `ab12ef`. Qualification on **2026-11-16**
used **macOS 27.2, Java 25 (25.0.5.0.3), and JavaFX 27.0.1**. The menu closes
before its workflow transfers focus, so a
later popup auto-hide cannot restore focus to a retired floating owner.
`NativeKeyboardDockingTest` permanently uses `@RepeatedTest(3)`: all three
independent executions must pass. Run this opt-in test from the NeitzelLib root
only with an exclusive desktop; other JavaFX tests or
manual app switching can take native focus:
```sh
./mvnw -pl fx -am -DskipVersions=true -Dversions.skip=true \
-Dtest=NativeKeyboardDockingTest \
-Dneitzellib.nativeKeyboardTest=true \
-Dsurefire.failIfNoSpecifiedTests=false test
```
`KeyboardDockActionsTest`, `AccessibleDockTabsTest`, `DockingLocalizationTest`
and `DockingThemeTest` exercise the public controls/API without native input.
The accessible-attribute checks verify JavaFX's exposed names, not a complete
screen-reader audit on every operating system.
During qualification, AWT sometimes delivered F10 without the held Shift flag
on this macOS/JDK combination; the public JavaFX event trace exposed that
missing modifier before the framework handled it. The test uses the public
[JavaFX Robot](https://openjfx.io/javadoc/27/javafx.graphics/javafx/scene/robot/Robot.html)
for the chord. Its [macOS backend](https://raw.githubusercontent.com/openjdk/jfx/jfx27/modules/javafx.graphics/src/main/native-glass/mac/GlassRobot.m)
posts native accessibility keyboard events, whereas the
[JDK 25 AWT backend](https://raw.githubusercontent.com/openjdk/jdk/jdk-25-ga/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobot.m)
creates CoreGraphics keyboard events from HID source state. This changes only
the test driver; the framework still requires an actual Shift+F10 event. Three
independent repetitions must each complete both transfers and exact text
assertions. They are not retries after a failure.
+8 -5
View File
@@ -25,8 +25,9 @@ The `CloseDockingMain` launcher in the example module shows a pending close
without a nested event loop. Choose Close Notes, then Keep open and continue
editing. Request close again and choose Allow close. Until that decision, Notes
remains open; after approval its resource callback runs. The same demonstration
works through the tab's close control. Main-window shutdown is added by the
later lifecycle slices; this example demonstrates individual tab consent.
works through the tab's close control. This example demonstrates individual tab
consent; [main-window shutdown](docking-shutdown.md) adds complete-workspace
consent, pre-close saving and manager replacement.
## Closing a floating window
@@ -48,8 +49,9 @@ layout is published once. Then every `onClosed` callback runs, even if an earlie
cleanup fails. `Closed.cleanupFailures()` reports those failures. The scope stays
observable until cleanup finishes. Unknown/already closed floating IDs return
`NoChange`; the main-window ID is rejected by this floating-only entry point.
Main-window and manager shutdown, including the shutdown snapshot callback,
belong to the later shutdown slices.
Main-window and manager shutdown use the same consent and cleanup guarantees;
the [shutdown guide](docking-shutdown.md) describes their snapshot callback and
ownership modes.
The example launcher is
`de.neitzel.fx.example.docking.FloatingCloseDockingMain`. It creates First and
@@ -68,4 +70,5 @@ are in-memory demonstration snapshots in the log, not filesystem writes.
The floating window's native close control follows the same sequence.
The demo's main Stage is only a control panel; closing it hides its demonstration
windows. This is separate from the future application-wide shutdown protocol.
windows. For an application-wide Quit command, use the
[shutdown workflow](docking-shutdown.md).
+140
View File
@@ -0,0 +1,140 @@
# Quit, save and replace a docking workspace
`requestMainWindowClose()` asks every Dockable in the manager, including contents
in floating windows and collapsed groups. Every close check runs even if an
earlier one vetoes. Nothing closes until all checks allow the operation. A veto
returns `CloseResult.Vetoed` and skips the shutdown-save callback.
Configure `DockingOptions.beforeShutdown` before attaching the manager. After
unanimous consent, the callback receives a `ShutdownRequest` with the complete
immutable pre-close `LayoutSnapshot` and a `ShutdownReason`: `MAIN_WINDOW` or
`MANAGER_ONLY`. Application document saving still belongs to the application and
its close checks; the snapshot contains arrangement data, not editor text.
```java
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(request -> saveLayoutWithRetry(request.snapshot()));
DockingManager manager = DockingManager.attach(stage, pane, options);
```
Here `saveLayoutWithRetry` is an application function returning a
`CompletionStage<ShutdownDecision>`. Keep that stage pending while saving or
retrying. The manager leaves all contents and windows open and holds the close
scope throughout that wait. Complete with `PROCEED` after a successful save, or
`CANCEL` to keep the workspace open. Throwing from the callback or completing its
stage exceptionally returns `Rejected` with `SHUTDOWN_CALLBACK_FAILED` and the
original cause; it does not close contents. The callback runs on the JavaFX
thread, and the returned stage may complete on a worker thread.
After `PROCEED`, the manager detaches contents and calls every `onClosed` callback.
Cleanup failures are reported in `Closed.cleanupFailures()` and do not turn an
already completed close into a rollback. The close scope remains active through
resource cleanup.
## Main-window ownership
The default `MainWindowCloseMode.AUTOMATIC` connects the Stage's close control to
the manager and hides the main Stage only after a successful main-window close.
Route an application's Quit command through `requestMainWindowClose()` as well.
With `APPLICATION_COORDINATED`, the application owns its close-request handler
and decides when to hide the main Stage after `Closed`. Consume the close event
while consent and saving are pending:
```java
stage.setOnCloseRequest(event -> {
event.consume();
manager.requestMainWindowClose().thenAccept(result -> {
if (result instanceof CloseResult.Closed) stage.hide();
});
});
```
Choose the mode before `attach`; changing the original options afterward does
not change the attached manager.
## Replacing the embedded workspace
`requestManagerClose()` uses the same checks and save workflow with reason
`MANAGER_ONLY`. On success it closes Dockables and floating windows, removes the
manager's handlers and releases the pane and Stage for another attachment. The
main Stage stays open. A veto, cancellation or failed save leaves the current
manager usable.
```java
manager.requestManagerClose().thenAccept(result -> {
if (result instanceof CloseResult.Closed) {
DockingManager replacement = DockingManager.attach(stage, pane, nextOptions);
openNewWorkspaceContents(replacement);
}
});
```
The replacement application creates or loads new contents. Use
[`resetLayout()`](../../fx-example/docs/docking-reset.md) when the intention is to
rearrange existing editors while retaining their Nodes and unsaved text.
## Quit during an existing floating-window close
A main-window request waits behind an already running floating-window close.
If the floating close succeeds, Quit asks only the remaining Dockables and then
captures their full pre-close snapshot. If it vetoes or fails, the waiting Quit
adopts that result without starting new checks or saving. A later explicit Quit
starts fresh checks. Repeated requests for the same running workflow share its
answer rather than invoking another application prompt.
The example makes this sequence visible:
1. Select **Delay Preview window consent** and click **Close Preview window**.
Preview stays open while its one consent answer is pending.
2. Click **Quit workspace**. The status shows that Quit is waiting; Notes and
Project have not been asked and no snapshot has been saved.
3. **Allow Preview** closes that independently approved window, then Quit asks
Notes and Project and waits at the normal save controls. The snapshot now
contains their one remaining main window.
4. Alternatively, **Veto Preview** leaves all three contents open and ends the
waiting Quit with the same veto. Clicking **Quit workspace** again performs
fresh checks and reaches the two-window save workflow.
The asynchronous consent controls remain usable while Quit waits. The public
scope property continues to describe the running floating close until the queue
can advance; a pending global save then owns the manager-wide scope.
## Runnable Quit/Replace example
`ShutdownDockingMain` loads `ShutdownDocking.fxml`: Notes occupies the center,
Project starts collapsed on the left, and Preview is floating. The example uses
ordinary JavaFX without MVVM.
1. Select **Preview vetoes last**, then **Replace workspace**. The log shows all
three checks, no snapshot callback and no released contents.
2. Clear the veto and request **Quit workspace** or **Replace workspace**. The
application displays the pre-close reason and the two-window snapshot.
3. **Retry save** fails while **Simulate save failure** is selected. The same
pending request retains every editor. Clear that checkbox and retry, or use
**Save successfully**, to complete with `PROCEED`.
4. **Cancel shutdown**, **Fail asynchronously** and **Throw before saving** show
the distinct canceled and rejected paths without losing the current editors.
5. **Replace workspace** followed by successful saving attaches fresh contents
to the same DockPane. **Next workspace** selects the ownership mode captured
by that new attachment. In application-owned mode, a successful Quit leaves
**Close application window** available for the caller's final action.
The example stores the saved snapshot in application-owned memory and deliberately
simulates failures; it performs no disk I/O. Connect the same callback to your
storage implementation for a real application.
After building local artifacts, launch from the NeitzelLib root:
```bash
java -cp 'fx-example/target/classes:fx-example/target/libs/*' \
de.neitzel.fx.example.docking.ShutdownDockingMain
```
The public workflow tests exercise consent and save ordering, pending saves,
both ownership modes, cleanup, captured options and reattachment. Four example
integration cases drive the actual Java/FXML controls through veto, retry,
cancellation, failures, replacement, both main-close ownership modes and queued
Quit after delayed floating consent. The queue cases use ordinary JavaFX turns
to verify callback counts, retained editor identity and fresh checks after a
veto. All four example scenarios pass without failures, errors or skips.
+52 -4
View File
@@ -50,10 +50,27 @@ 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.
Restore includes the main window and floating hosts with their saved return
destinations. The same window customizer configures new and restored hosts.
Prepared floating windows remain hidden until the main Stage is shown; failed
preparation never shows them. Customizers and placement checks finish before the
layout is installed.
Floating bounds outside the available displays are fitted to a current screen,
preserving the saved size as far as it fits. Return uses the saved main-window
destination, including persistent groups hidden while empty.
`DockableResolution.Missing` skips that identity and reports it in
`RestoreResult.Applied.missingIds()`. Empty split branches dissolve while stable
area aliases remain available; configured persistent empty side groups survive.
Available contents are checked against the application's current placement rule.
If a saved destination is rejected, restore tries the explicitly configured
`DockingOptions.fallbackTarget`, such as `DockTarget.area("primary")`. It does not
silently choose an arbitrary group. If any available content has no eligible
destination, the entire restore is rejected with that ID and all freshly prepared
contents are discarded; the live fallback layout remains unchanged.
An available Dockable that has become `mainWindowOnly` uses an explicitly
configured main-window fallback. Floating hosts emptied by Missing or fallback
are omitted entirely, including their customizer calls.
Use [live reset](../../fx-example/docs/docking-reset.md) to rearrange already open
contents without replacing their Nodes or losing their unsaved state.
@@ -82,6 +99,37 @@ java --enable-native-access=ALL-UNNAMED \
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.
6. Choose **Restore without Preview/Project**. The status names both missing IDs;
the nested Preview split dissolves and the persistent empty Project side target
remains. The original workspace and its unsaved text remain open.
7. Choose **Restore with changed rule**. In the supplied starting arrangement,
Project is no longer permitted in the tools group and joins Notes in the
configured editor fallback, `primary`. The status names that fallback.
8. Choose **Reject Project placement**. Project is rejected at both its saved
destination and the fallback. The new window retains its empty starting layout;
the status identifies Project and reports all four freshly prepared contents
discarded. The original workspace remains untouched.
9. Choose **Prepare floating snapshot**. Preview and Project become two floating
windows; Project's persistent side target hides while empty. The captured
snapshot includes their return destinations.
10. Choose **Restore saved layout**. A fresh main window and two floating hosts
appear. The status reports zero floating windows visible before main-window
display and two afterward. Source and restored hosts use the same custom title.
11. Choose **Restore off-screen windows**. This changes only the saved floating
positions to simulate unavailable monitors. The new hosts fit the available
displays. In the new main window, **Return Project** brings the same content
back to its preserved target and removes its empty floating host.
12. Choose **Restore partial floating**. Preview is missing; Project now requires
the main window and uses the configured editor fallback. Only the new main
window appears, with three contents. No empty floating hosts are created.
13. Choose **Abort floating customizer**. The second floating-window customizer
throws. Neither prepared floating host appears, the new main window retains
its empty fallback, and all four prepared contents are discarded.
The display and startup checks run against actual JavaFX windows on the current
macOS desktop. Off-screen saved bounds simulate monitor changes; physically
disconnecting monitors and Windows/Linux desktop startup have not been qualified
by these example tests.
The example's **Capture layout** command saves layout data only. Reloaded document
text comes from its application source; document persistence is a separate concern.
+5 -2
View File
@@ -41,8 +41,11 @@ The content instance remains owned by the application. A supplied
the previously focused descendant. See [split groups](docking-splits.md) for
nested layouts and resizing, [group presentation](docking-groups.md) for collapse
and atomic configuration, [overlay groups](docking-overlays.md) for pinning,
and [close consent](docking-close.md) for
asynchronous close checks. Restoration is supplied by a later slice.
and [close consent](docking-close.md) for asynchronous close checks.
[Snapshot restoration](docking-snapshots.md) prepares fresh contents for an empty
manager; [live reset](../../fx-example/docs/docking-reset.md) retains existing
editors. [Shutdown and replacement](docking-shutdown.md) cover saving before
Quit and attaching a new manager to the same host.
## Move and check placement
@@ -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");
}
}
@@ -36,3 +36,6 @@ 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
dock.failure.SHUTDOWN_CALLBACK_FAILED=The shutdown preparation failed
dock.failure.MANAGER_CLOSED=The docking manager has ended
@@ -0,0 +1,31 @@
/* The text remains available to assistive technology while only the supplied icon is drawn. */
.dock-icon-only .tab-label {
-fx-content-display: graphic-only;
}
/* Scope defaults to docking surfaces; application styles are loaded afterward. */
.dock-edge-area {
-fx-background-color: -fx-background;
}
.dock-divider, .dock-area-divider {
-fx-background-color: -fx-box-border, -fx-inner-border;
-fx-background-insets: 0, 1;
}
.dock-drop-indicator {
-fx-fill: rgba(30, 144, 255, 0.18);
-fx-stroke: dodgerblue;
-fx-stroke-width: 2;
}
.dock-drop-indicator:no-change {
-fx-fill: rgba(100, 100, 100, 0.15);
-fx-stroke: gray;
}
.dock-floating-preview-frame {
-fx-fill: rgba(80, 140, 220, 0.16);
-fx-stroke: rgb(50, 110, 190);
}
.dock-floating-preview-label {
-fx-background-color: -fx-control-inner-background;
-fx-text-fill: -fx-text-base-color;
-fx-padding: 4 8;
}
@@ -0,0 +1,115 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.AccessibleAttribute;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.Labeled;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
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.List;
import static org.junit.jupiter.api.Assertions.*;
/** Observes the public accessibility attributes and visible presentation of actual tab headers. */
class AccessibleDockTabsTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void anIconOnlyTabKeepsItsAccessibleNameWhenBoundRenamedFloatedAndReturned() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 480));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Label icon = new Label("▦");
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project files"));
project.setIcon(icon);
SimpleStringProperty name = new SimpleStringProperty("Project files");
project.accessibleNameProperty().bind(name);
manager.open(project, DockTarget.area("editors"));
main.show();
try {
assertPresentation(project, icon, "Project files", true);
name.set("Project outline");
assertPresentation(project, icon, "Project outline", true);
manager.move(project.getId(), DockTarget.floating());
assertPresentation(project, icon, "Project outline", true);
manager.move(project.getId(), DockTarget.returnToMain());
assertPresentation(project, icon, "Project outline", true);
assertEquals("", project.getTitle());
project.setTitle("Visible title");
assertPresentation(project, icon, "Visible title", false);
assertEquals("Project outline", project.getAccessibleName());
} finally {
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
}
});
}
@Test void theCloseButtonsAccessibleActionNameUsesTheCapturedApplicationBundle() throws Exception {
FxThread.onFx(() -> {
var existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 480));
DockingOptions options = new DockingOptions();
options.setResourceBundle(new java.util.ListResourceBundle() {
@Override protected Object[][] getContents() {
return new Object[][] {{"dock.action.close", "Fermer le document"}};
}
});
DockingManager manager = DockingManager.attach(main, pane, options);
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("editors"));
main.show();
try {
for (boolean floating : new boolean[]{false, true}) {
if (floating) manager.move(notes.getId(), DockTarget.floating());
var root = notes.getContent().getScene().getRoot();
root.applyCss(); root.layout();
Node close = root.lookup(".dock-tab-header .tab-close-button");
assertNotNull(close);
assertEquals("Fermer le document", close.queryAccessibleAttribute(AccessibleAttribute.TEXT));
}
} finally {
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
}
});
}
private static void assertPresentation(Dockable dockable, Node icon, String name, boolean iconOnly) {
var root = dockable.getContent().getScene().getRoot();
root.applyCss();
root.layout();
TabPane tabs = root.lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == dockable.getContent()))
.findFirst().orElseThrow();
Tab tab = tabs.getTabs().stream().filter(candidate -> candidate.getContent() == dockable.getContent())
.findFirst().orElseThrow();
Node header = tabs.lookup("#" + tab.getId());
assertEquals(name, header.queryAccessibleAttribute(AccessibleAttribute.TEXT));
assertSame(icon, tab.getGraphic());
Labeled label = (Labeled) header.lookup(".tab-label");
assertEquals(iconOnly ? ContentDisplay.GRAPHIC_ONLY : ContentDisplay.LEFT, label.getContentDisplay());
assertTrue(header.getStyleClass().contains("dock-tab-header"));
}
}
@@ -0,0 +1,176 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.Window;
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.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
/** Overlapping close entry points share consent and serialize global shutdown. */
class CoordinatedShutdownTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@ParameterizedTest @ValueSource(booleans = {false, true})
void mainShutdownWaitsForFloatingCloseAndDoesNotRepeatAVetoedRequest(boolean allow) throws Exception {
var fixture = new AtomicReference<Fixture>();
var consent = new CompletableFuture<CloseConsent>();
var floatingResult = new AtomicReference<CompletionStage<CloseResult>>();
var mainResult = new AtomicReference<CompletionStage<CloseResult>>();
List<String> asked = new ArrayList<>();
List<String> closed = new ArrayList<>();
List<CloseScope.Kind> scopes = new ArrayList<>();
AtomicInteger saves = new AtomicInteger();
try {
FxThread.onFx(() -> {
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(request -> {
assertTrue(Platform.isFxApplicationThread());
assertEquals(ShutdownReason.MAIN_WINDOW, request.reason());
assertEquals(allow ? 2 : 3, request.snapshot().windows().size());
saves.incrementAndGet();
return CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
});
Fixture f = fixture(options); fixture.set(f);
f.manager.closingScopeProperty().addListener((observable, old, current) -> {
if (current != null) scopes.add(current.kind());
});
for (Dockable dockable : List.of(f.mainContent, f.first, f.second)) {
dockable.setCloseCheck(request -> {
assertTrue(Platform.isFxApplicationThread());
assertSame(dockable.getContent().getScene().getWindow(), request.owner());
asked.add(dockable.getId().value());
return dockable == f.first ? consent : CompletableFuture.completedFuture(CloseConsent.ALLOW);
});
dockable.setOnClosed(() -> closed.add(dockable.getId().value()));
}
floatingResult.set(f.manager.requestFloatingWindowClose(f.firstWindow));
assertSame(floatingResult.get(), f.manager.requestFloatingWindowClose(f.firstWindow));
assertSame(floatingResult.get(), f.manager.requestTabClose(f.first.getId()));
mainResult.set(f.manager.requestMainWindowClose());
assertSame(mainResult.get(), f.manager.requestMainWindowClose());
assertFalse(mainResult.get().toCompletableFuture().isDone());
assertEquals(List.of("first"), asked);
assertEquals(CloseScope.Kind.FLOATING_WINDOW, f.manager.closingScopeProperty().get().kind());
assertEquals(0, saves.get());
assertTrue(closed.isEmpty());
});
CompletableFuture.runAsync(() -> consent.complete(allow ? CloseConsent.ALLOW : CloseConsent.VETO)).get();
// The queue continuation is scheduled by the FX-thread completion; drain two ordinary FX turns.
FxThread.onFx(() -> { });
FxThread.onFx(() -> {
Fixture f = fixture.get();
assertTrue(mainResult.get().toCompletableFuture().isDone(), "The queued shutdown must have settled");
if (allow) {
assertInstanceOf(CloseResult.Closed.class, floatingResult.get().toCompletableFuture().join());
assertInstanceOf(CloseResult.Closed.class, mainResult.get().toCompletableFuture().join());
assertEquals(List.of("first", "main", "second"), asked);
assertEquals(List.of("first", "main", "second"), closed);
assertEquals(1, saves.get());
assertFalse(f.stage.isShowing());
} else {
CloseResult veto = floatingResult.get().toCompletableFuture().join();
assertInstanceOf(CloseResult.Vetoed.class, veto);
assertEquals(veto, mainResult.get().toCompletableFuture().join());
assertEquals(List.of("first"), asked, "A waiting quit must not ask again after the floating veto");
assertEquals(List.of(CloseScope.Kind.FLOATING_WINDOW), scopes);
assertTrue(closed.isEmpty());
assertEquals(0, saves.get());
assertEquals(3, f.manager.layout().windows().size());
assertTrue(f.stage.isShowing());
f.first.setCloseCheck(request -> {
asked.add("first"); return CompletableFuture.completedFuture(CloseConsent.ALLOW);
});
asked.clear();
assertInstanceOf(CloseResult.Closed.class, f.manager.requestMainWindowClose().toCompletableFuture().join());
assertEquals(List.of("main", "first", "second"), asked, "A new explicit quit gets fresh consent");
assertEquals(1, saves.get());
}
assertNull(f.manager.closingScopeProperty().get());
});
} finally {
if (fixture.get() != null) FxThread.onFx(fixture.get()::close);
}
}
@org.junit.jupiter.api.Test
void duplicatesShareTheFinalPublicationAndAQueuedQuitCannotSaveAnEndedManagerAgain() throws Exception {
var fixture = new AtomicReference<Fixture>();
var save = new CompletableFuture<ShutdownDecision>();
var managerResult = new AtomicReference<CompletionStage<CloseResult>>();
var queuedQuit = new AtomicReference<CompletionStage<CloseResult>>();
List<CompletionStage<CloseResult>> duplicates = new ArrayList<>();
List<CompletionStage<CloseResult>> coveredTabs = new ArrayList<>();
List<ShutdownReason> saves = new ArrayList<>();
try {
FxThread.onFx(() -> {
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(request -> { saves.add(request.reason()); return save; });
Fixture f = fixture(options); fixture.set(f);
f.manager.layoutProperty().addListener((observable, old, current) -> {
boolean empty = current.windows().stream().flatMap(window -> window.areas().stream())
.flatMap(area -> area.groups().stream()).allMatch(group -> group.dockableIds().isEmpty());
if (empty && f.manager.closingScopeProperty().get() != null) {
duplicates.add(f.manager.requestManagerClose());
coveredTabs.add(f.manager.requestTabClose(f.first.getId()));
}
});
managerResult.set(f.manager.requestManagerClose());
queuedQuit.set(f.manager.requestMainWindowClose());
assertFalse(queuedQuit.get().toCompletableFuture().isDone());
assertEquals(List.of(ShutdownReason.MANAGER_ONLY), saves);
});
CompletableFuture.runAsync(() -> save.complete(ShutdownDecision.PROCEED)).get();
FxThread.onFx(() -> { });
FxThread.onFx(() -> {
Fixture f = fixture.get();
assertTrue(managerResult.get().toCompletableFuture().isDone());
assertInstanceOf(CloseResult.Closed.class, managerResult.get().toCompletableFuture().join());
assertTrue(duplicates.size() >= 2, "Observe both content removal and final area release");
duplicates.forEach(answer -> assertSame(managerResult.get(), answer,
"A duplicate shares the pending outcome until the scope ends"));
coveredTabs.forEach(answer -> assertSame(managerResult.get(), answer));
assertTrue(queuedQuit.get().toCompletableFuture().isDone());
assertInstanceOf(CloseResult.NoChange.class, queuedQuit.get().toCompletableFuture().join());
assertEquals(List.of(ShutdownReason.MANAGER_ONLY), saves, "An ended manager cannot save an empty replacement snapshot");
assertTrue(f.stage.isShowing(), "The ended manager no longer owns main-window closure");
assertNull(f.manager.closingScopeProperty().get());
});
} finally {
if (fixture.get() != null) FxThread.onFx(fixture.get()::close);
}
}
private static Fixture fixture(DockingOptions options) {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage stage = new Stage(); stage.setScene(new Scene(pane, 700, 500));
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable main = new Dockable(new DockableId("main"), new TextArea("Main"));
Dockable first = new Dockable(new DockableId("first"), new TextArea("First"));
Dockable second = new Dockable(new DockableId("second"), new TextArea("Second"));
manager.open(main, DockTarget.area("editors"));
manager.open(first, DockTarget.floating());
DockWindowId firstWindow = manager.layout().windows().stream().filter(window -> !window.main()).findFirst().orElseThrow().id();
manager.open(second, DockTarget.floating());
stage.show();
return new Fixture(stage, manager, main, first, second, firstWindow, existing);
}
private record Fixture(Stage stage, DockingManager manager, Dockable mainContent, Dockable first,
Dockable second, DockWindowId firstWindow, List<Window> existing) {
void close() { List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide); }
}
}
@@ -0,0 +1,129 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.input.*;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class DockingThemeTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test void applicationThemeStylesHeadersAndBothDragPreviewsAcrossWindows() throws Exception {
FxThread.onFx(() -> {
var existing = List.copyOf(Window.getWindows());
String theme = getClass().getResource("docking-theme.css").toExternalForm();
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 460));
main.setX(80); main.setY(100);
main.getScene().getStylesheets().add(theme);
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> configuration.getStylesheets().add(theme));
DockingManager manager = DockingManager.attach(main, pane, options);
Dockable notes = dockable("Notes"), tools = dockable("Tools");
manager.open(notes, DockTarget.area("editors"));
manager.open(tools, DockTarget.area("tools"));
main.show();
try {
pane.applyCss(); pane.layout();
Node source = header(pane, "Notes");
assertHeaderColor(source);
Bounds from = source.localToScreen(source.getBoundsInLocal());
Bounds into = tools.getContent().localToScreen(tools.getContent().getBoundsInLocal());
mouse(source, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true);
mouse(source, MouseEvent.MOUSE_DRAGGED, into.getCenterX(), into.getCenterY(), true);
pane.applyCss();
Rectangle marker = (Rectangle) pane.lookup(".dock-drop-indicator");
assertTrue(marker.isVisible());
assertEquals(Color.web("#123456"), marker.getFill());
assertEquals(Color.web("#654321"), marker.getStroke());
mouse(source, MouseEvent.MOUSE_DRAGGED, into.getCenterX() + 2, into.getCenterY(), true);
pane.applyCss();
assertEquals(Color.web("#123456"), marker.getFill(), "Continuous drag preserves the application theme");
mouse(source, MouseEvent.MOUSE_DRAGGED, main.getX() + main.getWidth() + 60, main.getY() + 100, true);
Window preview = Window.getWindows().stream().filter(window -> window.getScene() != null
&& window.getScene().getRoot().lookup(".dock-floating-preview-frame") != null).findFirst().orElseThrow();
preview.getScene().getRoot().applyCss();
Rectangle frame = (Rectangle) preview.getScene().getRoot().lookup(".dock-floating-preview-frame");
assertEquals(Color.web("#234567"), frame.getFill());
assertEquals(Color.web("#765432"), frame.getStroke());
Event.fireEvent(main.getScene(), new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.ESCAPE,
false, false, false, false));
assertFalse(preview.isShowing());
manager.move(notes.getId(), DockTarget.floating());
var floatingRoot = notes.getContent().getScene().getRoot();
floatingRoot.applyCss(); floatingRoot.layout();
assertHeaderColor(header(floatingRoot, "Notes"));
} finally {
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
}
});
}
@Test void splitAndOuterDividersAreThemeableBeforeAnyPointerInteraction() throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
Stage main = new Stage();
main.setScene(new Scene(pane, 1000, 600));
main.getScene().getStylesheets().add(getClass().getResource("docking-theme.css").toExternalForm());
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable notes = dockable("Notes"), other = dockable("Other");
manager.open(notes, DockTarget.area("editors"));
manager.open(other, DockTarget.area("editors"));
manager.open(dockable("Tools"), DockTarget.area("tools"));
main.show();
try {
pane.applyCss(); pane.layout();
var group = manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().id();
manager.move(other.getId(), DockTarget.split(group, javafx.geometry.Side.BOTTOM));
pane.applyCss(); pane.layout();
Node split = pane.lookup(".dock-divider");
assertNotNull(split, "A split exposes its theme hook before the user points at it");
assertEquals(Color.web("#345678"), ((Region) split).getBackground().getFills().getFirst().getFill());
Node outer = pane.lookup(".dock-area-divider");
assertNotNull(outer);
assertEquals(Color.web("#456789"), ((Region) outer).getBackground().getFills().getFirst().getFill());
assertFalse(pane.lookupAll(".dock-edge-area").isEmpty());
} finally { main.hide(); }
});
}
private static void assertHeaderColor(Node node) {
assertEquals(Color.web("#f1e2c3"), ((Region) node).getBackground().getFills().getFirst().getFill());
}
private static Dockable dockable(String name) {
Dockable result = new Dockable(new DockableId(name), new TextArea(name)); result.setTitle(name); return result;
}
private static Node header(Node root, String text) {
return root.lookupAll(".dock-tab-header").stream()
.filter(node -> node.lookup(".tab-label") instanceof Label label && text.equals(label.getText()))
.findFirst().orElseThrow();
}
private static void mouse(Node source, javafx.event.EventType<MouseEvent> type, double x, double y, boolean down) {
var local = source.screenToLocal(x, y);
source.fireEvent(new MouseEvent(type, local.getX(), local.getY(), x, y, MouseButton.PRIMARY, 1,
false, false, false, false, down, false, false, false, false, false,
new PickResult(source, local.getX(), local.getY())));
}
}
@@ -0,0 +1,241 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/** Keyboard events enter through focused public controls and invoke the visible menu. */
class KeyboardDockActionsTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test void shiftF10OnTheSelectedTabOpensItsMenuAndFloatRestoresTheEditorFocus() throws Exception {
FxThread.onFx(() -> {
var existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 460));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea editor = new TextArea("abcdef");
Dockable notes = new Dockable(new DockableId("notes"), editor);
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("editors"));
main.show();
try {
pane.applyCss(); pane.layout();
editor.selectRange(2, 4);
TabPane tabs = (TabPane) pane.lookup(".dock-group");
tabs.requestFocus();
ContextMenu menu = tabs.getSelectionModel().getSelectedItem().getContextMenu();
key(tabs, KeyCode.F10, true);
assertTrue(menu.isShowing(), "Shift+F10 opens the selected docking tab's menu");
for (int index = 0; index < 4; index++) key(menu.getSkin().getNode(), KeyCode.DOWN, false);
key(menu.getSkin().getNode(), KeyCode.ENTER, false);
assertNotSame(main, editor.getScene().getWindow());
assertSame(editor, editor.getScene().getFocusOwner());
assertEquals("cd", editor.getSelectedText());
assertSame(notes, manager.activeDockable());
} finally {
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
}
});
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = {"Pin group", "Close"})
void commandsThatKeepContentOpenRestoreItsFocus(String action) throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setCollapsible(true);
pane.getInitialLayout().setRight(tools);
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 460));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea editor = new TextArea("Unsaved changes");
Dockable notes = new Dockable(new DockableId("notes"), editor);
notes.setTitle("Notes");
java.util.concurrent.atomic.AtomicInteger checks = new java.util.concurrent.atomic.AtomicInteger();
notes.setCloseCheck(request -> {
checks.incrementAndGet();
return java.util.concurrent.CompletableFuture.completedFuture(CloseConsent.VETO);
});
manager.open(notes, DockTarget.area("tools"));
main.show();
try {
pane.applyCss(); pane.layout();
TabPane tabs = (TabPane) pane.lookupAll(".dock-group").stream()
.filter(node -> ((TabPane) node).getTabs().stream().anyMatch(tab -> tab.getContent() == editor))
.findFirst().orElseThrow();
tabs.requestFocus();
ContextMenu menu = tabs.getSelectionModel().getSelectedItem().getContextMenu();
key(tabs, KeyCode.CONTEXT_MENU, false);
assertTrue(menu.isShowing());
int count = action.equals("Pin group") ? 6 : 3;
for (int index = 0; index < count; index++) key(menu.getSkin().getNode(), KeyCode.DOWN, false);
key(menu.getSkin().getNode(), KeyCode.ENTER, false);
assertSame(notes, manager.findDockable(notes.getId()).orElseThrow());
if (action.equals("Pin group")) assertEquals(DockGroupMode.OVERLAY,
manager.layout().windows().getFirst().areas().get(1).groups().getFirst().mode());
else assertEquals(1, checks.get(), "Close uses the application's ordinary consent callback");
assertSame(editor, editor.getScene().getFocusOwner(), "The surviving editor can receive typing");
} finally { main.hide(); }
});
}
@Test void aLateCloseVetoDoesNotTakeFocusBackFromAnotherActivatedEditor() throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 460));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
notes.setTitle("Notes");
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme"));
readme.setTitle("Readme");
var consent = new java.util.concurrent.CompletableFuture<CloseConsent>();
notes.setCloseCheck(request -> consent);
manager.open(readme, DockTarget.area("tools"));
manager.open(notes, DockTarget.area("editors"));
main.show();
try {
pane.applyCss(); pane.layout();
TabPane tabs = pane.lookupAll(".dock-group").stream().map(TabPane.class::cast)
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == notes.getContent()))
.findFirst().orElseThrow();
tabs.requestFocus();
ContextMenu menu = tabs.getSelectionModel().getSelectedItem().getContextMenu();
key(tabs, KeyCode.F10, true);
for (int index = 0; index < 3; index++) key(menu.getSkin().getNode(), KeyCode.DOWN, false);
key(menu.getSkin().getNode(), KeyCode.ENTER, false);
assertNotNull(manager.closingScopeProperty().get());
manager.activate(readme.getId());
assertSame(readme.getContent(), main.getScene().getFocusOwner());
consent.complete(CloseConsent.VETO);
assertNull(manager.closingScopeProperty().get());
assertSame(readme, manager.activeDockable());
assertSame(readme.getContent(), main.getScene().getFocusOwner(),
"Completion must respect the user's intervening focus choice");
assertTrue(manager.findDockable(notes.getId()).isPresent());
} finally { consent.complete(CloseConsent.VETO); main.hide(); }
});
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = {"Move", "Split"})
void submenuNavigationMovesOrSplitsTheSelectedEditor(String action) throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
Stage main = new Stage();
main.setScene(new Scene(pane, 1000, 600));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea editor = new TextArea("abcdef");
Dockable notes = new Dockable(new DockableId("notes"), editor);
notes.setTitle("Notes");
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme"));
readme.setTitle("Readme");
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
project.setTitle("Project");
manager.open(readme, DockTarget.area("editors"));
manager.open(project, DockTarget.area("tools"));
manager.open(notes, DockTarget.area("editors"));
main.show();
try {
pane.applyCss(); pane.layout();
editor.selectRange(2, 4);
TabPane tabs = pane.lookupAll(".dock-group").stream().map(TabPane.class::cast)
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == editor))
.findFirst().orElseThrow();
tabs.requestFocus();
ContextMenu menu = tabs.getSelectionModel().getSelectedItem().getContextMenu();
key(tabs, KeyCode.F10, true);
key(menu.getSkin().getNode(), KeyCode.DOWN, false);
if (action.equals("Split")) key(menu.getSkin().getNode(), KeyCode.DOWN, false);
key(menu.getSkin().getNode(), KeyCode.RIGHT, false);
ContextMenu submenu = Window.getWindows().stream()
.filter(window -> window instanceof ContextMenu candidate && candidate != menu && candidate.isShowing())
.map(ContextMenu.class::cast).findFirst().orElseThrow();
if (action.equals("Move")) key(submenu.getSkin().getNode(), KeyCode.DOWN, false);
key(submenu.getSkin().getNode(), KeyCode.ENTER, false);
if (action.equals("Move")) {
var toolGroup = manager.layout().windows().getFirst().areas().get(1).groups().getFirst();
assertEquals(List.of(project.getId(), notes.getId()), toolGroup.dockableIds());
} else {
var editorArea = manager.layout().windows().getFirst().areas().getFirst();
assertInstanceOf(DockLayoutView.Split.class, editorArea.root());
assertEquals(2, editorArea.groups().size());
assertEquals(List.of(notes.getId()), editorArea.groups().getFirst().dockableIds());
}
assertSame(notes, manager.activeDockable());
assertSame(editor, editor.getScene().getFocusOwner());
assertEquals("cd", editor.getSelectedText());
} finally {
for (Window window : List.copyOf(Window.getWindows())) if (window instanceof ContextMenu) window.hide();
main.hide();
}
});
}
@Test void contentControlsKeepTheirOwnKeyboardContextMenus() throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 460));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea editor = new TextArea("Application editor");
ContextMenu editorMenu = new ContextMenu(new javafx.scene.control.MenuItem("Inspect editor"));
editor.setContextMenu(editorMenu);
java.util.concurrent.atomic.AtomicBoolean receivedShortcut = new java.util.concurrent.atomic.AtomicBoolean();
editor.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.F10 && event.isShiftDown()) receivedShortcut.set(true);
});
Dockable notes = new Dockable(new DockableId("notes"), editor);
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("editors"));
main.show();
try {
pane.applyCss(); pane.layout();
editor.requestFocus();
ContextMenu tabMenu = ((TabPane) pane.lookup(".dock-group"))
.getSelectionModel().getSelectedItem().getContextMenu();
key(editor, KeyCode.F10, true);
assertTrue(receivedShortcut.get(), "Docking does not consume content keyboard shortcuts");
assertFalse(tabMenu.isShowing());
var bounds = editor.localToScreen(editor.getBoundsInLocal());
editor.fireEvent(new javafx.scene.input.ContextMenuEvent(
javafx.scene.input.ContextMenuEvent.CONTEXT_MENU_REQUESTED, 4, 4,
bounds.getMinX() + 4, bounds.getMinY() + 4, true,
new javafx.scene.input.PickResult(editor, 4, 4)));
assertTrue(editorMenu.isShowing());
assertFalse(tabMenu.isShowing());
assertEquals("Inspect editor", editorMenu.getItems().getFirst().getText());
} finally { editorMenu.hide(); main.hide(); }
});
}
private static void key(Node target, KeyCode code, boolean shift) {
target.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", code, shift, false, false, false));
}
}
@@ -0,0 +1,150 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import static org.junit.jupiter.api.Assertions.*;
/** Native keyboard delivery through the actual popup; requires the exclusive desktop slot. */
@EnabledIfSystemProperty(named = "neitzellib.nativeKeyboardTest", matches = "true")
class NativeKeyboardDockingTest {
private static final int[] KEYS = {KeyEvent.VK_DOWN, KeyEvent.VK_ENTER, KeyEvent.VK_1, KeyEvent.VK_2};
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@RepeatedTest(3) @Timeout(25)
void shiftF10FloatAndReturnAllowImmediateTypingAtTheOriginalCaret() throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(25);
AtomicReference<Fixture> reference = new AtomicReference<>();
AtomicReference<List<Window>> existing = new AtomicReference<>();
FxThread.onFx(() -> {
existing.set(List.copyOf(Window.getWindows()));
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 460));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea editor = new TextArea("abcdef");
Dockable notes = new Dockable(new DockableId("notes"), editor);
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("editors"));
main.show();
manager.activate(notes.getId());
editor.selectRange(2, 4);
reference.set(new Fixture(main, editor, manager, notes, new javafx.scene.robot.Robot()));
});
Fixture fixture = reference.get();
try {
openMenuByNativeKeyboard(robot, fixture, "Float");
await(() -> fixture.editor.getScene().getWindow() != fixture.main, "Float was not invoked by the keyboard");
typeWithoutFocusRepair(robot, fixture, KeyEvent.VK_1, "ab1ef");
openMenuByNativeKeyboard(robot, fixture, "Return to main");
await(() -> fixture.editor.getScene().getWindow() == fixture.main, "Return was not invoked by the keyboard");
typeWithoutFocusRepair(robot, fixture, KeyEvent.VK_2, "ab12ef");
FxThread.onFx(() -> assertSame(fixture.notes, fixture.manager.activeDockable()));
} finally {
for (int key : KEYS) robot.keyRelease(key);
FxThread.onFx(() -> {
fixture.keyboard.keyRelease(javafx.scene.input.KeyCode.F10);
fixture.keyboard.keyRelease(javafx.scene.input.KeyCode.SHIFT);
for (Window window : List.copyOf(Window.getWindows())) if (!existing.get().contains(window)) window.hide();
});
}
}
private static void openMenuByNativeKeyboard(Robot robot, Fixture fixture, String action) throws Exception {
AtomicReference<TabPane> selectedTabs = new AtomicReference<>();
AtomicReference<ContextMenu> menu = new AtomicReference<>();
FxThread.onFx(() -> {
var root = fixture.editor.getScene().getRoot();
root.applyCss(); root.layout();
TabPane tabs = root.lookupAll(".dock-group").stream().map(TabPane.class::cast)
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == fixture.editor))
.findFirst().orElseThrow();
// Start the command from its tab strip. Never repair content focus after the command.
tabs.requestFocus();
selectedTabs.set(tabs);
menu.set(tabs.getSelectionModel().getSelectedItem().getContextMenu());
});
await(() -> fixture.editor.getScene().getWindow().isFocused()
&& fixture.editor.getScene().getFocusOwner() == selectedTabs.get(), "The tab strip did not receive native focus");
FxThread.onFx(() -> {
try {
fixture.keyboard.keyPress(javafx.scene.input.KeyCode.SHIFT);
fixture.keyboard.keyPress(javafx.scene.input.KeyCode.F10);
} finally {
fixture.keyboard.keyRelease(javafx.scene.input.KeyCode.F10);
fixture.keyboard.keyRelease(javafx.scene.input.KeyCode.SHIFT);
}
});
await(() -> menu.get().isShowing(), "Native Shift+F10 did not open the tab menu");
for (int step = 0; step < 7; step++) {
AtomicReference<String> selected = new AtomicReference<>();
FxThread.onFx(() -> selected.set(focusedAction(menu.get())));
if (action.equals(selected.get())) break;
press(robot, KeyEvent.VK_DOWN);
await(() -> !java.util.Objects.equals(selected.get(), focusedAction(menu.get())),
"The arrow key did not move the menu selection");
}
FxThread.onFx(() -> assertEquals(action, focusedAction(menu.get()),
"Enter must execute the visibly focused intended action"));
press(robot, KeyEvent.VK_ENTER);
}
private static String focusedAction(ContextMenu menu) {
return menu.getSkin().getNode().lookupAll(".menu-item:focused").stream()
.map(node -> (String) node.queryAccessibleAttribute(javafx.scene.AccessibleAttribute.TEXT))
.findFirst().orElse(null);
}
private static void typeWithoutFocusRepair(Robot robot, Fixture fixture, int key, String expected) throws Exception {
await(() -> fixture.editor.getScene().getWindow().isFocused()
&& fixture.editor.getScene().getFocusOwner() == fixture.editor,
"The menu transfer did not restore content/native window focus");
press(robot, key);
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
AtomicReference<String> actual = new AtomicReference<>();
do {
Thread.sleep(25);
FxThread.onFx(() -> actual.set(fixture.editor.getText()));
} while (!expected.equals(actual.get()) && System.nanoTime() < deadline);
assertEquals(expected, actual.get(), "Native typing continues at the transferred editor caret");
}
private static void press(Robot robot, int key) {
try { robot.keyPress(key); } finally { robot.keyRelease(key); }
}
private static void await(BooleanSupplier condition, String failure) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
AtomicReference<Boolean> ready = new AtomicReference<>(false);
do {
Thread.sleep(25);
FxThread.onFx(() -> ready.set(condition.getAsBoolean()));
} while (!ready.get() && System.nanoTime() < deadline);
assertTrue(ready.get(), failure);
}
private record Fixture(Stage main, TextArea editor, DockingManager manager, Dockable notes,
javafx.scene.robot.Robot keyboard) { }
}
@@ -0,0 +1,69 @@
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.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class PartialRestoreTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@ParameterizedTest @ValueSource(booleans = {false, true})
void missingBranchesNormalizeInBothDirectionsWhilePersistentSideDestinationsRemainReachable(boolean missingLeft) throws Exception {
FxThread.onFx(() -> {
DockSplitDefinition pair = split("pair", new DockGroupDefinition("middle"), new DockGroupDefinition("right"));
DockLayout definition = new DockLayout();
definition.setCenter(split("editors", new DockGroupDefinition("left"), pair));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setVisibleWhenEmpty(false); tools.setReleaseSpaceWhenEmpty(true); definition.setRight(tools);
DockGroupDefinition scratch = new DockGroupDefinition("scratch");
scratch.setPersistent(false); definition.setTop(scratch);
DockingManager original = RestoreValidationTest.manager(definition);
for (String[] entry : new String[][]{{"a", "left"}, {"b", "middle"}, {"c", "right"}, {"tool", "tools"}, {"scratch", "scratch"}}) {
original.open(new Dockable(new DockableId(entry[0]), new TextArea(entry[0])), DockTarget.area(entry[1]));
}
LayoutSnapshot saved = original.snapshot();
Set<String> missing = missingLeft ? Set.of("a", "tool", "scratch") : Set.of("b", "c", "tool", "scratch");
DockLayout starting = new DockLayout(); starting.setCenter(new DockGroupDefinition("start"));
DockingManager restored = RestoreValidationTest.manager(starting);
RestoreResult.Applied result = assertInstanceOf(RestoreResult.Applied.class, restored.restore(saved, id ->
missing.contains(id.value()) ? new DockableResolution.Missing()
: new DockableResolution.Available(new Dockable(id, new TextArea("Reloaded " + id.value())))));
assertEquals((missingLeft ? List.of("a", "tool", "scratch") : List.of("b", "c", "tool", "scratch"))
.stream().map(DockableId::new).toList(), result.missingIds());
for (String id : missing) assertTrue(restored.findDockable(new DockableId(id)).isEmpty());
LayoutSnapshot.Window window = restored.snapshot().windows().getFirst();
assertEquals(2, window.roots().size(), "The nonpersistent empty standalone root disappears");
LayoutSnapshot.Branch center = window.roots().stream().filter(root -> root.placement() == LayoutSnapshot.Placement.CENTER)
.findFirst().orElseThrow().branch();
if (missingLeft) assertInstanceOf(LayoutSnapshot.Split.class, center);
else assertInstanceOf(LayoutSnapshot.Group.class, center);
DockableId survivor = new DockableId(missingLeft ? "b" : "a");
for (String area : List.of("editors", "left", "pair", "middle", "right")) {
assertFalse(restored.checkMove(survivor, DockTarget.area(area)) instanceof MoveCheck.Rejected,
"Normalized area remains addressable: " + area);
}
assertInstanceOf(MoveCheck.Allowed.class, restored.checkMove(survivor, DockTarget.area("tools")));
assertEquals(DockFailure.Code.TARGET_NOT_FOUND,
assertInstanceOf(MoveCheck.Rejected.class, restored.checkMove(survivor, DockTarget.area("scratch"))).failure().code());
LayoutSnapshot.Group emptyTools = (LayoutSnapshot.Group) window.roots().stream()
.filter(root -> root.placement() == LayoutSnapshot.Placement.RIGHT).findFirst().orElseThrow().branch();
assertTrue(emptyTools.tabs().isEmpty());
assertTrue(emptyTools.settings().persistent());
DockingManager nextStartup = RestoreValidationTest.manager(starting);
assertTrue(assertInstanceOf(RestoreResult.Applied.class, nextStartup.restore(restored.snapshot(), id ->
new DockableResolution.Available(new Dockable(id, new TextArea("Next startup"))))).missingIds().isEmpty(),
"Omitted identities cannot leave invalid references in the next saved snapshot");
});
}
private static DockSplitDefinition split(String id, DockLayoutNode first, DockLayoutNode second) {
DockSplitDefinition split = new DockSplitDefinition(); split.setDestinationId(id);
split.setFirst(first); split.setSecond(second); return split;
}
}
@@ -0,0 +1,95 @@
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.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class RestoreFallbackTest {
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
@ParameterizedTest @ValueSource(booleans = {false, true})
void changedRulesUseTheDesignatedRelativeFallbackAfterEveryIdentityIsResolved(boolean movingFirst) throws Exception {
FxThread.onFx(() -> {
LayoutSnapshot saved = RestoreValidationTest.saved();
DockableId moved = new DockableId(movingFirst ? "a" : "b");
DockableId anchor = new DockableId(movingFirst ? "b" : "a");
DockGroupId receiver = new DockGroupId(movingFirst ? "preview" : "primary");
DockingOptions options = new DockingOptions();
options.setFallbackTarget(DockTarget.group(receiver, TabPosition.before(anchor)));
options.setPlacementRule((dockable, target) -> dockable.getId().equals(moved)
&& !((ResolvedDockTarget.Insertion) target).groupId().equals(receiver)
? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, moved, "Saved group is no longer allowed", null))
: Optional.empty());
DockingManager manager = manager(options);
List<DockableId> requested = new ArrayList<>();
RestoreResult.Applied applied = assertInstanceOf(RestoreResult.Applied.class, manager.restore(saved, id -> {
requested.add(id);
return new DockableResolution.Available(new Dockable(id, new TextArea("Reloaded " + id.value())));
}));
assertTrue(applied.missingIds().isEmpty());
assertEquals(List.of(new DockableId("a"), new DockableId("b")), requested,
"Moving to a later-resolved anchor cannot resolve or construct a Dockable twice");
LayoutSnapshot.Group group = assertInstanceOf(LayoutSnapshot.Group.class,
manager.snapshot().windows().getFirst().roots().getFirst().branch());
assertEquals(List.of(moved, anchor), group.tabs());
assertEquals(receiver, group.id());
assertEquals(new DockableId("b"), group.selected());
assertEquals(new DockableId("b"), manager.activeDockable().getId());
assertFalse(manager.checkMove(anchor, DockTarget.area(movingFirst ? "primary" : "preview")) instanceof MoveCheck.Rejected,
"The emptied saved destination remains a stable alias of the surviving group");
});
}
@ParameterizedTest @ValueSource(strings = {"absent", "missing", "denied", "throws"})
void anUnusableFallbackAbortsTheWholeRestoreAndKeepsCleanupFailuresSeparate(String fallback) throws Exception {
FxThread.onFx(() -> {
LayoutSnapshot saved = RestoreValidationTest.saved();
RuntimeException policyFailure = new IllegalStateException("Fallback policy failed");
RuntimeException cleanupFailure = new IllegalArgumentException("Cleanup A failed");
DockingOptions options = new DockingOptions();
if (!fallback.equals("absent")) options.setFallbackTarget(DockTarget.area(fallback.equals("missing") ? "unknown" : "primary"));
options.setPlacementRule((dockable, target) -> {
if (dockable.getId().value().equals("a")) return Optional.empty();
if (fallback.equals("throws") && ((ResolvedDockTarget.Insertion) target).groupId().value().equals("primary")) throw policyFailure;
return Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), "No eligible group", null, "app.no-group"));
});
DockingManager manager = manager(options);
var before = manager.layout(); var beforeSnapshot = manager.snapshot();
AtomicInteger discarded = new AtomicInteger();
RestoreResult.Rejected rejected = assertInstanceOf(RestoreResult.Rejected.class, manager.restore(saved, id -> {
Dockable dockable = new Dockable(id, new TextArea(id.value()));
dockable.setOnDiscarded(() -> { discarded.incrementAndGet(); if (id.value().equals("a")) throw cleanupFailure; });
return new DockableResolution.Available(dockable);
}));
assertEquals(new DockableId("b"), rejected.failure().dockableId());
assertEquals(switch (fallback) {
case "missing" -> DockFailure.Code.TARGET_NOT_FOUND;
case "throws" -> DockFailure.Code.PLACEMENT_CHECK_FAILED;
default -> DockFailure.Code.PLACEMENT_REJECTED;
}, rejected.failure().code());
if (fallback.equals("throws")) assertSame(policyFailure, rejected.failure().cause());
if (fallback.equals("absent") || fallback.equals("denied")) assertEquals("app.no-group", rejected.failure().messageKey());
assertEquals(2, discarded.get());
assertEquals(1, rejected.cleanupFailures().size());
assertSame(cleanupFailure, rejected.cleanupFailures().getFirst().cause());
assertSame(before, manager.layout());
assertEquals(beforeSnapshot, manager.snapshot());
});
}
private static DockingManager manager(DockingOptions options) {
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));
return DockingManager.attach(stage, pane, options);
}
}
@@ -0,0 +1,82 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
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.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class RestoreFloatingFailureTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test void aLaterCustomizerFailureDiscardsAllPreparedContentsAndNeverShowsPreparedHosts() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage source = new Stage(); Stage target = new Stage();
try {
DockingManager original = attach(source, new DockingOptions());
for (String name : List.of("first", "second")) {
DockableId id = new DockableId(name);
assertInstanceOf(ActionResult.Applied.class, original.open(new Dockable(id, new TextArea(name)), DockTarget.area("editors")));
assertInstanceOf(ActionResult.Applied.class, original.move(id, DockTarget.floating(new Rectangle2D(100, 100, 400, 300))));
}
LayoutSnapshot saved = original.snapshot();
RuntimeException creationFailure = new IllegalStateException("second floating host");
RuntimeException cleanupFailure = new IllegalStateException("first prepared content cleanup");
AtomicInteger customized = new AtomicInteger();
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> {
if (customized.incrementAndGet() == 2) throw creationFailure;
});
DockingManager restored = attach(target, options);
LayoutSnapshot before = restored.snapshot(); var layoutBefore = restored.layout();
List<DockableId> discarded = new ArrayList<>(); List<Dockable> prepared = new ArrayList<>();
AtomicInteger closed = new AtomicInteger(); AtomicInteger publications = new AtomicInteger();
restored.layoutProperty().addListener((observable, old, current) -> publications.incrementAndGet());
RestoreResult.Rejected result = assertInstanceOf(RestoreResult.Rejected.class, restored.restore(saved, id -> {
Dockable dockable = new Dockable(id, new TextArea("fresh " + id.value()));
dockable.setOnClosed(closed::incrementAndGet);
dockable.setOnDiscarded(() -> {
discarded.add(id);
if (id.value().equals("first")) throw cleanupFailure;
});
prepared.add(dockable); return new DockableResolution.Available(dockable);
}));
assertEquals(2, customized.get());
assertEquals(DockFailure.Code.WINDOW_CREATION_FAILED, result.failure().code());
assertSame(creationFailure, result.failure().cause());
assertEquals(List.of(new DockableId("first"), new DockableId("second")), discarded);
assertEquals(1, result.cleanupFailures().size());
assertSame(cleanupFailure, result.cleanupFailures().getFirst().cause());
assertEquals(0, closed.get()); assertEquals(0, publications.get());
assertSame(before, restored.snapshot()); assertSame(layoutBefore, restored.layout());
prepared.forEach(dockable -> {
assertNull(dockable.getContent().getParent()); assertNull(dockable.getContent().getScene());
});
target.show();
assertEquals(List.of(target), Window.getWindows().stream().filter(window -> !existing.contains(window)).toList(),
"The main shown hook must not resurrect any prepared floating host after failure");
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
source.hide(); target.hide();
}
});
}
private static DockingManager attach(Stage stage, DockingOptions options) {
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
stage.setScene(new Scene(pane, 700, 500)); return DockingManager.attach(stage, pane, options);
}
}
@@ -0,0 +1,80 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.Window;
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 java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class RestoreFloatingFallbackTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@ParameterizedTest @ValueSource(booleans = {true, false})
void changedMainOnlyAndMissingContentsNeverCreateAnEmptyFloatingHost(boolean designatedFallback) throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage source = new Stage(); Stage target = new Stage();
try {
DockingManager original = attach(source, new DockingOptions());
DockableId project = new DockableId("project");
DockableId preview = new DockableId("preview");
for (DockableId id : List.of(project, preview)) {
assertInstanceOf(ActionResult.Applied.class, original.open(new Dockable(id, new TextArea(id.value())), DockTarget.area("editors")));
assertInstanceOf(ActionResult.Applied.class, original.move(id, DockTarget.floating(new Rectangle2D(100, 100, 400, 300))));
}
LayoutSnapshot saved = original.snapshot();
AtomicInteger customized = new AtomicInteger(); AtomicInteger discarded = new AtomicInteger();
DockingOptions options = new DockingOptions();
if (designatedFallback) options.setFallbackTarget(DockTarget.area("editors"));
options.setFloatingWindowCustomizer(configuration -> customized.incrementAndGet());
DockingManager restored = attach(target, options);
LayoutSnapshot before = restored.snapshot();
AtomicReference<Dockable> prepared = new AtomicReference<>();
RestoreResult result = restored.restore(saved, id -> {
if (id.equals(preview)) return new DockableResolution.Missing();
Dockable dockable = new Dockable(id, new TextArea("fresh project"));
dockable.setMainWindowOnly(true); dockable.setOnDiscarded(discarded::incrementAndGet);
prepared.set(dockable); return new DockableResolution.Available(dockable);
});
assertEquals(0, customized.get(), "Omitted windows are not prepared or customized");
assertEquals(1, restored.layout().windows().size());
if (designatedFallback) {
assertEquals(List.of(preview), assertInstanceOf(RestoreResult.Applied.class, result).missingIds());
assertSame(target, prepared.get().getContent().getScene().getWindow());
assertSame(prepared.get(), restored.activeDockable());
assertEquals(0, discarded.get());
} else {
DockFailure failure = assertInstanceOf(RestoreResult.Rejected.class, result).failure();
assertEquals(DockFailure.Code.MAIN_WINDOW_ONLY, failure.code());
assertEquals(project, failure.dockableId());
assertSame(before, restored.snapshot());
assertNull(prepared.get().getContent().getParent());
assertEquals(1, discarded.get());
}
target.show();
assertEquals(1, restored.layout().windows().size());
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
source.hide(); target.hide();
}
});
}
private static DockingManager attach(Stage stage, DockingOptions options) {
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
stage.setScene(new Scene(pane, 700, 500)); return DockingManager.attach(stage, pane, options);
}
}
@@ -0,0 +1,67 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class RestoreFloatingGeometryTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test void newAndRestoredHostsWaitForMainAndOffscreenFramesFitTheCurrentDisplay() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage source = new Stage(); Stage target = new Stage();
try {
DockingManager original = attach(source);
DockableId id = new DockableId("notes");
Dockable notes = new Dockable(id, new TextArea("source"));
assertInstanceOf(ActionResult.Applied.class, original.open(notes, DockTarget.area("editors")));
assertInstanceOf(ActionResult.Applied.class, original.move(id, DockTarget.floating(new Rectangle2D(100, 100, 400, 300))));
Stage originalHost = (Stage) notes.getContent().getScene().getWindow();
assertFalse(originalHost.isShowing(), "New floating hosts also wait for main startup");
source.show(); assertTrue(originalHost.isShowing());
LayoutSnapshot saved = original.snapshot();
var visual = Screen.getPrimary().getVisualBounds();
Rectangle2D unavailable = new Rectangle2D(100_000, -100_000, visual.getWidth() + 500, visual.getHeight() + 500);
LayoutSnapshot offscreen = new LayoutSnapshot(saved.version(), saved.windows().stream()
.map(window -> window.main() ? window : new LayoutSnapshot.Window(window.id(), false, unavailable, window.roots()))
.toList(), saved.activeDockableId(), saved.returnPositions(), saved.initialIntents());
DockingManager restored = attach(target); AtomicReference<Dockable> fresh = new AtomicReference<>();
assertInstanceOf(RestoreResult.Applied.class, restored.restore(offscreen, requested -> {
Dockable dockable = new Dockable(requested, new TextArea("loaded")); fresh.set(dockable);
return new DockableResolution.Available(dockable);
}));
Rectangle2D fitted = restored.snapshot().windows().get(1).bounds();
assertTrue(visual.contains(fitted), "Committed restored bounds fit an available visual display");
assertEquals(visual.getWidth(), fitted.getWidth(), .01);
assertEquals(visual.getHeight(), fitted.getHeight(), .01);
Stage host = (Stage) fresh.get().getContent().getScene().getWindow();
assertFalse(host.isShowing());
target.show(); assertTrue(host.isShowing());
assertTrue(visual.contains(new Rectangle2D(host.getX(), host.getY(), host.getWidth(), host.getHeight())));
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
source.hide(); target.hide();
}
});
}
private static DockingManager attach(Stage stage) {
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
stage.setScene(new Scene(pane, 700, 500)); return DockingManager.attach(stage, pane, new DockingOptions());
}
}
@@ -0,0 +1,109 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.Window;
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 java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
/** Multiwindow startup and return through ordinary snapshot/restore APIs. */
class RestoreFloatingLayoutTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test void floatingSplitsStayHiddenUntilMainShowAndReturnToTheirEmptyMainArea() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage source = new Stage();
Stage target = new Stage();
try {
DockingManager original = attach(source, new DockingOptions());
Map<DockableId, Dockable> originals = new LinkedHashMap<>();
for (String id : List.of("notes", "preview", "readme")) {
Dockable dockable = new Dockable(new DockableId(id), new TextArea("Saved " + id));
dockable.setTitle(id);
originals.put(dockable.getId(), dockable);
assertInstanceOf(ActionResult.Applied.class, original.open(dockable, DockTarget.area("editors")));
}
source.show();
var screen = Screen.getPrimary().getVisualBounds();
DockableId notes = new DockableId("notes");
DockableId preview = new DockableId("preview");
DockableId readme = new DockableId("readme");
assertInstanceOf(ActionResult.Applied.class, original.move(notes, DockTarget.floating(
new Rectangle2D(screen.getMinX() + 80, screen.getMinY() + 80, 400, 400))));
DockGroupId notesGroup = groupContaining(original, notes).id();
assertInstanceOf(ActionResult.Applied.class, original.move(preview, DockTarget.split(notesGroup, Side.BOTTOM)));
assertInstanceOf(ActionResult.Applied.class, original.move(readme, DockTarget.floating(
new Rectangle2D(screen.getMaxX() - 440, screen.getMinY() + 100, 400, 320))));
original.activate(notes);
LayoutSnapshot saved = original.snapshot();
assertEquals(3, saved.windows().size());
assertTrue(saved.returnPositions().keySet().containsAll(List.of(notes, preview, readme)));
assertEquals(2, original.layout().windows().stream().filter(window -> !window.main())
.filter(window -> window.areas().stream().anyMatch(area -> area.groups().size() == 2))
.findFirst().orElseThrow().areas().getFirst().groups().size());
AtomicInteger customized = new AtomicInteger();
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> {
customized.incrementAndGet(); configuration.setTitle("Restored editor window");
});
DockingManager restored = attach(target, options);
Map<DockableId, Dockable> fresh = new LinkedHashMap<>();
RestoreResult.Applied result = assertInstanceOf(RestoreResult.Applied.class, restored.restore(saved, id -> {
Dockable dockable = new Dockable(id, new TextArea("Loaded " + id.value()));
dockable.setTitle(id.value()); fresh.put(id, dockable);
return new DockableResolution.Available(dockable);
}));
assertTrue(result.missingIds().isEmpty());
assertEquals(2, customized.get());
assertEquals(3, restored.layout().windows().size());
for (Dockable dockable : fresh.values()) {
assertNotSame(originals.get(dockable.getId()).getContent(), dockable.getContent());
Stage floating = (Stage) dockable.getContent().getScene().getWindow();
assertNotSame(target, floating);
assertFalse(floating.isShowing(), "Restored floating hosts wait for the main Stage");
assertEquals("Restored editor window", floating.getTitle());
}
target.show();
for (Dockable dockable : fresh.values()) assertTrue(dockable.getContent().getScene().getWindow().isShowing());
assertSame(fresh.get(notes), restored.activeDockable());
for (DockableId id : List.of(notes, preview, readme)) {
assertInstanceOf(ActionResult.Applied.class, restored.move(id, DockTarget.returnToMain()));
assertSame(target, fresh.get(id).getContent().getScene().getWindow());
assertEquals("Loaded " + id.value(), ((TextArea) fresh.get(id).getContent()).getText());
}
assertEquals(1, restored.layout().windows().size());
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
source.hide(); target.hide();
}
});
}
private static DockingManager attach(Stage stage, DockingOptions options) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
stage.setScene(new Scene(pane, 700, 500));
return DockingManager.attach(stage, pane, options);
}
private static DockLayoutView.Group groupContaining(DockingManager manager, DockableId id) {
return manager.layout().windows().stream().flatMap(window -> window.areas().stream())
.flatMap(area -> area.groups().stream()).filter(group -> group.dockableIds().contains(id))
.findFirst().orElseThrow();
}
}
@@ -0,0 +1,114 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
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.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class RestoreFloatingRootsTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test void acceptedFloatingSideRootsKeepTheirPlacementAndCommittedExtentAcrossRepeatedStartup() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage source = new Stage(); Stage first = new Stage(); Stage second = new Stage();
try {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools"); tools.setPreferredWidth(220);
pane.getInitialLayout().setLeft(tools);
source.setScene(new Scene(pane, 800, 600));
DockingManager original = DockingManager.attach(source, pane, new DockingOptions());
assertInstanceOf(ActionResult.Applied.class, original.open(new Dockable(new DockableId("editor"), new TextArea("edit")), DockTarget.area("editors")));
assertInstanceOf(ActionResult.Applied.class, original.open(new Dockable(new DockableId("project"), new TextArea("project")), DockTarget.area("tools")));
LayoutSnapshot saved = original.snapshot();
List<LayoutSnapshot.Root> roots = saved.windows().getFirst().roots();
LayoutSnapshot floating = new LayoutSnapshot(saved.version(), List.of(
new LayoutSnapshot.Window(new DockWindowId("main"), true, null, List.of()),
new LayoutSnapshot.Window(new DockWindowId("detached-workspace"), false, new Rectangle2D(100, 100, 800, 600), roots)),
saved.activeDockableId(), Map.of(), saved.initialIntents());
DockingManager restored = attach(first);
assertInstanceOf(RestoreResult.Applied.class, restored.restore(floating, RestoreFloatingRootsTest::load));
first.show();
LayoutSnapshot exported = restored.snapshot();
List<LayoutSnapshot.Root> floatingRoots = exported.windows().get(1).roots();
assertEquals(roots.stream().map(LayoutSnapshot.Root::placement).toList(),
floatingRoots.stream().map(LayoutSnapshot.Root::placement).toList());
LayoutSnapshot.Root left = floatingRoots.stream().filter(root -> root.placement() == LayoutSnapshot.Placement.LEFT).findFirst().orElseThrow();
assertEquals(220, left.preferredWidth(), 1);
var toolsView = restored.layout().windows().get(1).areas().stream()
.filter(area -> area.id().equals(new DockAreaId("tools"))).findFirst().orElseThrow();
assertEquals(left.preferredWidth(), toolsView.preferredWidth(), 1);
DockingManager restarted = attach(second);
assertInstanceOf(RestoreResult.Applied.class, restarted.restore(exported, RestoreFloatingRootsTest::load),
"A successful restore must publish a valid snapshot for the next startup");
assertEquals(floatingRoots.stream().map(LayoutSnapshot.Root::placement).toList(),
restarted.snapshot().windows().get(1).roots().stream().map(LayoutSnapshot.Root::placement).toList());
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
source.hide(); first.hide(); second.hide();
}
});
}
@Test void aRestoredSideRootCannotResizeAnAdjacentGroupAwaitingConsent() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
Stage source = new Stage(); Stage target = new Stage();
try {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
pane.getInitialLayout().setLeft(new DockGroupDefinition("tools"));
source.setScene(new Scene(pane, 800, 600));
DockingManager original = DockingManager.attach(source, pane, new DockingOptions());
original.open(new Dockable(new DockableId("editor"), new TextArea()), DockTarget.area("editors"));
original.open(new Dockable(new DockableId("project"), new TextArea()), DockTarget.area("tools"));
LayoutSnapshot saved = original.snapshot();
LayoutSnapshot floating = new LayoutSnapshot(saved.version(), List.of(
new LayoutSnapshot.Window(new DockWindowId("main"), true, null, List.of()),
new LayoutSnapshot.Window(new DockWindowId("detached-workspace"), false,
new Rectangle2D(100, 100, 800, 600), saved.windows().getFirst().roots())),
saved.activeDockableId(), Map.of(), saved.initialIntents());
DockingManager restored = attach(target);
assertInstanceOf(RestoreResult.Applied.class, restored.restore(floating, RestoreFloatingRootsTest::load));
target.show();
Dockable editor = restored.findDockable(new DockableId("editor")).orElseThrow();
var consent = new java.util.concurrent.CompletableFuture<CloseConsent>();
editor.setCloseCheck(request -> consent);
restored.requestTabClose(editor.getId());
LayoutSnapshot before = restored.snapshot();
try {
ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class,
restored.updateGroup(new DockGroupId("tools"), DockGroupChanges.builder().preferredWidth(300).build()));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, rejected.failure().code());
assertSame(before, restored.snapshot());
} finally { consent.complete(CloseConsent.VETO); }
assertInstanceOf(ActionResult.Applied.class,
restored.updateGroup(new DockGroupId("tools"), DockGroupChanges.builder().preferredWidth(300).build()));
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
source.hide(); target.hide();
}
});
}
private static DockableResolution load(DockableId id) {
return new DockableResolution.Available(new Dockable(id, new TextArea("loaded " + id.value())));
}
private static DockingManager attach(Stage stage) {
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("initial"));
stage.setScene(new Scene(pane, 800, 600)); return DockingManager.attach(stage, pane, new DockingOptions());
}
}
@@ -0,0 +1,323 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
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.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
/** Application shutdown asks all windows before a snapshot or any removal. */
class ShutdownDockingTest {
@BeforeAll static void startJavaFx() throws Exception {
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test void lateVetoLeavesEveryWindowOpenAndSkipsTheShutdownSnapshot() throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setCollapsible(true);
pane.getInitialLayout().setLeft(tools);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 700, 500));
AtomicInteger saves = new AtomicInteger();
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(request -> {
saves.incrementAndGet();
return CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
});
DockingManager manager = DockingManager.attach(stage, pane, options);
List<String> asked = new ArrayList<>();
AtomicInteger closed = new AtomicInteger();
Dockable editor = new Dockable(new DockableId("editor"), new TextArea("Unsaved editor"));
Dockable tool = new Dockable(new DockableId("project"), new TextArea("Collapsed project"));
Dockable floating = new Dockable(new DockableId("floating"), new TextArea("Unsaved float"));
for (Dockable dockable : List.of(editor, tool, floating)) {
dockable.setCloseCheck(request -> {
assertEquals(CloseScope.Kind.MAIN_WINDOW, request.scope().kind());
assertEquals(3, request.scope().dockableIds().size());
assertEquals(0, closed.get());
assertSame(dockable.getContent().getScene().getWindow(), request.owner());
asked.add(dockable.getId().value());
return CompletableFuture.completedFuture(dockable == tool ? CloseConsent.VETO : CloseConsent.ALLOW);
});
dockable.setOnClosed(closed::incrementAndGet);
}
manager.open(editor, DockTarget.area("editors"));
manager.open(tool, DockTarget.area("tools"));
manager.open(floating, DockTarget.floating());
var toolGroup = manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow().groups().getFirst();
manager.setGroupCollapsed(toolGroup.id(), true);
stage.show();
Stage floated = (Stage) floating.getContent().getScene().getWindow();
try {
var before = manager.layout();
var snapshot = manager.snapshot();
var result = manager.requestMainWindowClose().toCompletableFuture().join();
assertInstanceOf(CloseResult.Vetoed.class, result);
assertEquals(List.of("editor", "project", "floating"), asked);
assertEquals(0, saves.get());
assertEquals(0, closed.get());
assertSame(before, manager.layout());
assertSame(snapshot, manager.snapshot());
assertTrue(stage.isShowing());
assertTrue(floated.isShowing());
assertNull(manager.closingScopeProperty().get());
assertInstanceOf(ActionResult.Applied.class, manager.move(editor.getId(), DockTarget.area("tools")));
} finally { floated.hide(); stage.hide(); }
});
}
@Test void asynchronousShutdownSaveKeepsEveryContentOpenThenClosesOnTheFxThread() throws Exception {
var save = new CompletableFuture<ShutdownDecision>();
var fixture = new java.util.concurrent.atomic.AtomicReference<ShutdownFixture>();
var outcome = new java.util.concurrent.atomic.AtomicReference<java.util.concurrent.CompletionStage<CloseResult>>();
AtomicInteger saves = new AtomicInteger();
AtomicInteger closed = new AtomicInteger();
try {
FxThread.onFx(() -> {
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(request -> {
assertTrue(Platform.isFxApplicationThread());
assertEquals(ShutdownReason.MAIN_WINDOW, request.reason());
assertEquals(2, request.snapshot().windows().size());
assertEquals(2, fixture.get().manager.closingScopeProperty().get().dockableIds().size());
assertEquals(0, closed.get());
assertTrue(fixture.get().main.isShowing());
assertTrue(fixture.get().floating.isShowing());
saves.incrementAndGet();
return save;
});
ShutdownFixture f = shutdownFixture(options);
fixture.set(f);
for (Dockable dockable : List.of(f.notes, f.project)) {
dockable.setOnClosed(() -> {
assertTrue(Platform.isFxApplicationThread());
assertNotNull(f.manager.closingScopeProperty().get(), "Scope includes resource release");
assertNull(dockable.getContent().getScene());
closed.incrementAndGet();
});
}
var before = f.manager.layout();
outcome.set(f.manager.requestMainWindowClose());
assertEquals(1, saves.get());
assertFalse(outcome.get().toCompletableFuture().isDone());
assertEquals(0, closed.get());
assertSame(before, f.manager.layout());
assertTrue(f.main.isShowing());
assertTrue(f.floating.isShowing());
assertEquals(CloseScope.Kind.MAIN_WINDOW, f.manager.closingScopeProperty().get().kind());
assertInstanceOf(ActionResult.Rejected.class, f.manager.move(f.notes.getId(), DockTarget.area("editors")));
assertInstanceOf(ActionResult.Rejected.class, f.manager.open(
new Dockable(new DockableId("late"), new TextArea()), DockTarget.floating()));
AtomicInteger factories = new AtomicInteger();
assertInstanceOf(ActionResult.Rejected.class, f.manager.open(new DockableId("factory"), () -> {
factories.incrementAndGet(); return new Dockable(new DockableId("factory"), new TextArea());
}, DockTarget.area("editors")));
assertEquals(0, factories.get(), "A global close cannot start creating new content");
});
CompletableFuture.runAsync(() -> save.complete(ShutdownDecision.PROCEED)).get();
FxThread.onFx(() -> {
ShutdownFixture f = fixture.get();
assertInstanceOf(CloseResult.Closed.class, outcome.get().toCompletableFuture().join());
assertEquals(2, closed.get());
assertEquals(1, saves.get());
assertFalse(f.main.isShowing());
assertFalse(f.floating.isShowing());
assertNull(f.manager.closingScopeProperty().get());
assertTrue(f.manager.findDockable(f.notes.getId()).isEmpty());
assertInstanceOf(ActionResult.Rejected.class, f.manager.open(
new Dockable(new DockableId("after-close"), new TextArea()), DockTarget.area("editors")));
});
} finally {
if (fixture.get() != null) FxThread.onFx(fixture.get()::close);
}
}
@Test void managerOnlyCloseReleasesTheSamePaneForANewWorkingOverlayManager() throws Exception {
FxThread.onFx(() -> {
List<ShutdownReason> reasons = new ArrayList<>();
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(request -> {
reasons.add(request.reason());
return CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
});
ShutdownFixture f = shutdownFixture(options);
try {
assertInstanceOf(CloseResult.Closed.class, f.manager.requestManagerClose().toCompletableFuture().join());
assertEquals(List.of(ShutdownReason.MANAGER_ONLY), reasons);
assertTrue(f.main.isShowing());
assertFalse(f.floating.isShowing());
assertEquals(DockFailure.Code.MANAGER_CLOSED,
assertInstanceOf(ActionResult.Rejected.class, f.manager.activate(f.notes.getId())).failure().code());
assertInstanceOf(CloseResult.NoChange.class, f.manager.requestMainWindowClose().toCompletableFuture().join());
assertTrue(f.main.isShowing(), "An ended manager no longer owns the application's Stage");
((DockGroupDefinition) f.pane.getInitialLayout().getLeft()).setMode(DockGroupMode.OVERLAY);
DockingManager replacement = DockingManager.attach(f.main, f.pane, new DockingOptions());
TextArea editor = new TextArea("Replacement editor");
TextArea project = new TextArea("Replacement project");
replacement.open(new Dockable(new DockableId("new-editor"), editor), DockTarget.area("editors"));
replacement.open(new Dockable(new DockableId("new-project"), project), DockTarget.area("tools"));
f.pane.applyCss(); f.pane.layout();
assertFalse(group(replacement, "tools").collapsed());
editor.fireEvent(new javafx.scene.input.MouseEvent(javafx.scene.input.MouseEvent.MOUSE_PRESSED,
5, 5, 5, 5, javafx.scene.input.MouseButton.PRIMARY, 1,
false, false, false, false, true, false, false, false, false, false,
new javafx.scene.input.PickResult(editor, 5, 5)));
assertTrue(group(replacement, "tools").collapsed(), "Reattached overlay restores the outside-click handler");
f.main.hide(); f.main.show();
assertFalse(f.floating.isShowing(), "The ended manager cannot resurrect its old floating Stage");
assertInstanceOf(CloseResult.Closed.class, replacement.requestManagerClose().toCompletableFuture().join());
assertTrue(f.main.isShowing());
} finally { f.close(); }
});
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(MainWindowCloseMode.class)
void mainCloseControlHonorsTheCapturedOwnershipModeAndWaitsForConsent(MainWindowCloseMode mode) throws Exception {
FxThread.onFx(() -> {
DockingOptions options = new DockingOptions();
options.setMainWindowCloseMode(mode);
AtomicInteger saves = new AtomicInteger();
options.setBeforeShutdown(request -> {
saves.incrementAndGet();
return CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
});
ShutdownFixture f = shutdownFixture(options);
options.setMainWindowCloseMode(mode == MainWindowCloseMode.AUTOMATIC
? MainWindowCloseMode.APPLICATION_COORDINATED : MainWindowCloseMode.AUTOMATIC);
var consent = new CompletableFuture<CloseConsent>();
f.notes.setCloseCheck(request -> consent);
AtomicInteger applicationEvents = new AtomicInteger();
if (mode == MainWindowCloseMode.APPLICATION_COORDINATED) {
f.main.setOnCloseRequest(event -> {
event.consume(); applicationEvents.incrementAndGet();
f.manager.requestMainWindowClose();
});
}
try {
f.main.fireEvent(new javafx.stage.WindowEvent(f.main, javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST));
assertTrue(f.main.isShowing(), "The main close control waits for consent");
assertTrue(f.floating.isShowing());
assertNotNull(f.manager.closingScopeProperty().get());
assertEquals(0, saves.get());
consent.complete(CloseConsent.VETO);
assertTrue(f.main.isShowing());
assertTrue(f.floating.isShowing());
assertNull(f.manager.closingScopeProperty().get());
assertEquals(0, saves.get());
f.notes.setCloseCheck(request -> CompletableFuture.completedFuture(CloseConsent.ALLOW));
f.main.fireEvent(new javafx.stage.WindowEvent(f.main, javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST));
assertFalse(f.floating.isShowing());
assertEquals(1, saves.get());
assertEquals(mode == MainWindowCloseMode.APPLICATION_COORDINATED, f.main.isShowing());
assertEquals(mode == MainWindowCloseMode.APPLICATION_COORDINATED ? 2 : 0, applicationEvents.get());
if (mode == MainWindowCloseMode.APPLICATION_COORDINATED) f.main.hide();
} finally { f.close(); }
});
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = {"cancel", "throw", "failed"})
void canceledOrFailedShutdownSaveLeavesTheManagerOperational(String fault) throws Exception {
FxThread.onFx(() -> {
RuntimeException failure = new IllegalStateException("Layout storage unavailable");
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(request -> {
if (fault.equals("throw")) throw failure;
if (fault.equals("failed")) return CompletableFuture.failedFuture(failure);
return CompletableFuture.completedFuture(ShutdownDecision.CANCEL);
});
ShutdownFixture f = shutdownFixture(options);
AtomicInteger closed = new AtomicInteger();
f.notes.setOnClosed(closed::incrementAndGet);
f.project.setOnClosed(closed::incrementAndGet);
try {
var before = f.manager.layout();
var snapshot = f.manager.snapshot();
CloseResult result = f.manager.requestMainWindowClose().toCompletableFuture().join();
if (fault.equals("cancel")) assertInstanceOf(CloseResult.Canceled.class, result);
else {
DockFailure diagnostic = assertInstanceOf(CloseResult.Rejected.class, result).failure();
assertEquals(DockFailure.Code.SHUTDOWN_CALLBACK_FAILED, diagnostic.code());
assertSame(failure, diagnostic.cause());
}
assertSame(before, f.manager.layout());
assertSame(snapshot, f.manager.snapshot());
assertEquals(0, closed.get());
assertTrue(f.main.isShowing());
assertTrue(f.floating.isShowing());
assertNull(f.manager.closingScopeProperty().get());
assertInstanceOf(ActionResult.Applied.class, f.manager.move(f.notes.getId(), DockTarget.returnToMain()));
} finally { f.close(); }
});
}
@Test void shutdownCleanupFailuresStillReleaseEveryDockableAndTheManager() throws Exception {
FxThread.onFx(() -> {
ShutdownFixture f = shutdownFixture(new DockingOptions());
AtomicInteger cleanups = new AtomicInteger();
RuntimeException failure = new IllegalStateException("Listener release failed");
f.notes.setOnClosed(() -> { cleanups.incrementAndGet(); throw failure; });
f.project.setOnClosed(cleanups::incrementAndGet);
try {
CloseResult.Closed result = assertInstanceOf(CloseResult.Closed.class,
f.manager.requestManagerClose().toCompletableFuture().join());
assertEquals(2, cleanups.get());
assertEquals(1, result.cleanupFailures().size());
assertSame(failure, result.cleanupFailures().getFirst().cause());
assertFalse(f.floating.isShowing());
assertTrue(f.main.isShowing());
assertNull(f.manager.closingScopeProperty().get());
DockingManager replacement = DockingManager.attach(f.main, f.pane, new DockingOptions());
assertInstanceOf(CloseResult.Closed.class, replacement.requestManagerClose().toCompletableFuture().join());
assertInstanceOf(CloseResult.NoChange.class, f.manager.requestManagerClose().toCompletableFuture().join());
assertEquals(2, cleanups.get());
} finally { f.close(); }
});
}
private static DockLayoutView.Group group(DockingManager manager, String area) {
return manager.layout().windows().getFirst().areas().stream().filter(value -> value.id().value().equals(area))
.findFirst().orElseThrow().groups().getFirst();
}
private static ShutdownFixture shutdownFixture(DockingOptions options) {
List<javafx.stage.Window> existing = List.copyOf(javafx.stage.Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setCollapsible(true);
pane.getInitialLayout().setLeft(tools);
Stage main = new Stage();
main.setScene(new Scene(pane, 700, 500));
DockingManager manager = DockingManager.attach(main, pane, options);
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Unsaved notes"));
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
manager.open(notes, DockTarget.area("editors"));
manager.open(project, DockTarget.area("tools"));
manager.setGroupCollapsed(new DockGroupId("tools"), true);
manager.move(notes.getId(), DockTarget.floating());
main.show();
return new ShutdownFixture(main, (Stage) notes.getContent().getScene().getWindow(), pane, manager, notes, project, existing);
}
private record ShutdownFixture(Stage main, Stage floating, DockPane pane, DockingManager manager,
Dockable notes, Dockable project, List<javafx.stage.Window> existing) {
void close() {
List.copyOf(javafx.stage.Window.getWindows()).stream().filter(window -> !existing.contains(window))
.forEach(javafx.stage.Window::hide);
}
}
}
@@ -0,0 +1,6 @@
.dock-tab-header { -fx-background-color: #f1e2c3; }
.dock-drop-indicator { -fx-fill: #123456; -fx-stroke: #654321; }
.dock-floating-preview-frame { -fx-fill: #234567; -fx-stroke: #765432; }
.dock-divider { -fx-background-color: #345678; }
.dock-area-divider { -fx-background-color: #456789; }