feat(fx): add resizable split groups and asynchronous tab close

This commit is contained in:
2026-11-15 21:07:15 +01:00
parent af5a4278fd
commit 1a3aea6e09
40 changed files with 2724 additions and 93 deletions
+6
View File
@@ -75,6 +75,12 @@ Changing a JavaBean setter directly after loading does not notify controls. All
## Automated regression coverage ## Automated regression coverage
The standalone `de.neitzel.fx.example.docking.CloseDockingMain` launcher shows
an editor waiting for an asynchronous close decision. Choose Close Notes, then
Keep open to continue editing or Allow close to release its content. The tab
close control and context menu use the same consent callback. See the
[tab-close guide](../fx/docs/docking-close.md) for the library contract.
`src/test/java/de/neitzel/fx/example/DeskLoadsTest.java` loads the real Desk FXML on JavaFX and checks initial values, all binding directions, derived/computed text, conversion failures and recovery, child messages, Table edits/removal, message severities and boolean/enum write-back. It also demonstrates that a direct bean setter leaves controls unchanged and that another simple View reuses the same Model's ViewModel. `src/test/java/de/neitzel/fx/example/DeskLoadsTest.java` loads the real Desk FXML on JavaFX and checks initial values, all binding directions, derived/computed text, conversion failures and recovery, child messages, Table edits/removal, message severities and boolean/enum write-back. It also demonstrates that a direct bean setter leaves controls unchanged and that another simple View reuses the same Model's ViewModel.
Run the reactor tests without installing artifacts with: Run the reactor tests without installing artifacts with:
@@ -0,0 +1,70 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.CloseConsent;
import de.neitzel.fx.docking.CloseResult;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.concurrent.CompletableFuture;
/** Demonstrates a pending close decision while the editor remains open. */
public final class CloseDockingApp extends Application {
@Override
public void start(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Label notice = new Label("Close Notes, then allow the close or keep the editor open.");
Button close = new Button("Close Notes");
Button allow = new Button("Allow close");
Button veto = new Button("Keep open");
var pending = new SimpleObjectProperty<CompletableFuture<CloseConsent>>();
allow.disableProperty().bind(pending.isNull());
veto.disableProperty().bind(pending.isNull());
BorderPane shell = new BorderPane(pane);
shell.setTop(new ToolBar(close, allow, veto));
shell.setBottom(notice);
stage.setScene(new Scene(shell, 760, 420));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
Dockable editor = new Dockable(new DockableId("notes"), new TextArea("Edit these notes before closing."));
editor.setTitle("Notes");
editor.setCloseCheck(request -> {
notice.setText("Notes remains open while you decide.");
CompletableFuture<CloseConsent> answer = new CompletableFuture<>();
pending.set(answer);
return answer;
});
editor.setOnClosed(() -> {
close.setDisable(true);
notice.setText("Notes closed. Its resources can now be released.");
});
manager.open(editor, DockTarget.area("editors"));
close.setOnAction(event -> manager.requestTabClose(editor.getId()).thenAcceptAsync(result -> {
if (result instanceof CloseResult.Vetoed) notice.setText("Close canceled. Notes remains editable.");
}, Platform::runLater));
allow.setOnAction(event -> answer(pending, CloseConsent.ALLOW));
veto.setOnAction(event -> answer(pending, CloseConsent.VETO));
stage.setTitle("NeitzelLib — asynchronous tab close");
stage.show();
}
private static void answer(SimpleObjectProperty<CompletableFuture<CloseConsent>> pending, CloseConsent consent) {
CompletableFuture<CloseConsent> answer = pending.get();
pending.set(null);
if (answer != null) answer.complete(consent);
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain Java launcher for the asynchronous close example. */
public final class CloseDockingMain {
private CloseDockingMain() { }
public static void main(String[] args) {
Application.launch(CloseDockingApp.class, args);
}
}
@@ -1,6 +1,9 @@
package de.neitzel.fx.example.docking; package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.DockGroupDefinition; import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockSplitDefinition;
import de.neitzel.fx.docking.SplitDirections;
import javafx.geometry.Orientation;
import de.neitzel.fx.docking.ActionResult; import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockLayout; import de.neitzel.fx.docking.DockLayout;
import de.neitzel.fx.docking.DockPane; import de.neitzel.fx.docking.DockPane;
@@ -24,14 +27,17 @@ import javafx.stage.Stage;
public final class DockingApp extends Application { public final class DockingApp extends Application {
@Override @Override
public void start(Stage stage) throws Exception { public void start(Stage stage) throws Exception {
boolean splits = getParameters().getRaw().contains("--splits");
DockPane pane = getParameters().getRaw().contains("--fxml") DockPane pane = getParameters().getRaw().contains("--fxml")
? FXMLLoader.load(DockingApp.class.getResource("Docking.fxml")) : initialPane(); ? FXMLLoader.load(DockingApp.class.getResource(splits ? "SplitDocking.fxml" : "Docking.fxml"))
: initialPane(splits);
Button activate = new Button("Activate Notes"); Button activate = new Button("Activate Notes");
Button toTools = new Button("Move Notes to tools"); Button toTools = new Button("Move Notes to tools");
Button toEditors = new Button("Move Notes to editors"); Button toEditors = new Button("Move Notes to editors");
Label status = new Label("Drag a tab or use its context menu to move it."); Button splitNotes = new Button("Split Notes right");
Label status = new Label("Drag a tab to an edge to split; drag dividers to resize.");
BorderPane shell = new BorderPane(pane); BorderPane shell = new BorderPane(pane);
shell.setTop(new ToolBar(activate, toTools, toEditors)); shell.setTop(new ToolBar(activate, toTools, toEditors, splitNotes));
shell.setBottom(status); shell.setBottom(status);
stage.setScene(new Scene(shell, 900, 600)); stage.setScene(new Scene(shell, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
@@ -42,7 +48,12 @@ public final class DockingApp extends Application {
manager.open(editor, DockTarget.area("editors")); manager.open(editor, DockTarget.area("editors"));
Dockable other = new Dockable(new DockableId("readme"), new TextArea("Readme")); Dockable other = new Dockable(new DockableId("readme"), new TextArea("Readme"));
other.setTitle("Readme"); other.setTitle("Readme");
manager.open(other, DockTarget.area("editors")); manager.open(other, DockTarget.area(splits ? "preview" : "editors"));
if (splits) {
Dockable output = new Dockable(new DockableId("output"), new TextArea("Build output"));
output.setTitle("Output");
manager.open(output, DockTarget.area("output"));
}
Dockable project = new Dockable(new DockableId("project"), new Label("Project files")); Dockable project = new Dockable(new DockableId("project"), new Label("Project files"));
project.setTitle("Project"); project.setTitle("Project");
project.setIcon(new Label("▦")); project.setIcon(new Label("▦"));
@@ -50,6 +61,10 @@ public final class DockingApp extends Application {
activate.setOnAction(event -> manager.activate(notesId)); activate.setOnAction(event -> manager.activate(notesId));
toTools.setOnAction(event -> report(status, manager.move(notesId, DockTarget.area("tools")))); toTools.setOnAction(event -> report(status, manager.move(notesId, DockTarget.area("tools"))));
toEditors.setOnAction(event -> report(status, manager.move(notesId, DockTarget.area("editors")))); toEditors.setOnAction(event -> report(status, manager.move(notesId, DockTarget.area("editors"))));
splitNotes.setOnAction(event -> manager.layout().windows().stream()
.flatMap(window -> window.areas().stream()).flatMap(area -> area.groups().stream())
.filter(group -> group.dockableIds().contains(notesId)).findFirst()
.ifPresent(group -> report(status, manager.move(notesId, DockTarget.split(group.id(), Side.RIGHT)))));
stage.setTitle("NeitzelLib docking — Java or ordinary FXML"); stage.setTitle("NeitzelLib docking — Java or ordinary FXML");
stage.show(); stage.show();
manager.activate(notesId); manager.activate(notesId);
@@ -63,12 +78,28 @@ public final class DockingApp extends Application {
}); });
} }
private static DockPane initialPane() { private static DockPane initialPane(boolean splits) {
DockLayout layout = new DockLayout(); DockLayout layout = new DockLayout();
layout.setCenter(new DockGroupDefinition("editors")); if (splits) {
DockSplitDefinition secondary = new DockSplitDefinition();
secondary.setDestinationId("secondary");
secondary.setOrientation(Orientation.VERTICAL);
secondary.setFirst(new DockGroupDefinition("preview"));
secondary.setSecond(new DockGroupDefinition("output"));
DockSplitDefinition editors = new DockSplitDefinition();
editors.setDestinationId("editors");
editors.setFirst(new DockGroupDefinition("primary"));
editors.setSecond(secondary);
layout.setCenter(editors);
} else {
layout.setCenter(new DockGroupDefinition("editors"));
}
DockGroupDefinition tools = new DockGroupDefinition("tools"); DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT); tools.setTabSide(Side.RIGHT);
tools.setPreferredWidth(200); tools.setPreferredWidth(200);
tools.setSplitDirections(SplitDirections.VERTICAL);
tools.setVisibleWhenEmpty(false);
tools.setReleaseSpaceWhenEmpty(true);
layout.setRight(tools); layout.setRight(tools);
DockPane pane = new DockPane(); DockPane pane = new DockPane();
pane.setInitialLayout(layout); pane.setInitialLayout(layout);
@@ -6,7 +6,8 @@
<initialLayout> <initialLayout>
<DockLayout> <DockLayout>
<center><DockGroupDefinition destinationId="editors"/></center> <center><DockGroupDefinition destinationId="editors"/></center>
<right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" preferredWidth="200"/></right> <right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" preferredWidth="200" splitDirections="VERTICAL"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></right>
</DockLayout> </DockLayout>
</initialLayout> </initialLayout>
</DockPane> </DockPane>
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.DockPane?>
<?import de.neitzel.fx.docking.DockLayout?>
<?import de.neitzel.fx.docking.DockGroupDefinition?>
<?import de.neitzel.fx.docking.DockSplitDefinition?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center>
<DockSplitDefinition destinationId="editors" orientation="HORIZONTAL">
<first><DockGroupDefinition destinationId="primary"/></first>
<second>
<DockSplitDefinition destinationId="secondary" orientation="VERTICAL">
<first><DockGroupDefinition destinationId="preview"/></first>
<second><DockGroupDefinition destinationId="output"/></second>
</DockSplitDefinition>
</second>
</DockSplitDefinition>
</center>
<right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" preferredWidth="200" splitDirections="VERTICAL"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></right>
</DockLayout>
</initialLayout>
</DockPane>
@@ -0,0 +1,47 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
/** Checks the example resource through the same ordinary FXML/public manager path as clients. */
class SplitDockingExampleTest {
@Test
void theNestedFxmlExampleOpensEachNamedDestinationWithoutMvvm() throws InterruptedException {
CountDownLatch started = new CountDownLatch(1);
try { Platform.startup(started::countDown); }
catch (IllegalStateException alreadyStarted) { started.countDown(); }
assertTrue(started.await(10, TimeUnit.SECONDS));
CountDownLatch done = new CountDownLatch(1);
AtomicReference<Throwable> failure = new AtomicReference<>();
Platform.runLater(() -> {
try {
DockPane pane = FXMLLoader.load(DockingApp.class.getResource("SplitDocking.fxml"));
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
for (String target : new String[]{"primary", "preview", "output", "tools"}) {
assertInstanceOf(ActionResult.Applied.class,
manager.open(new Dockable(new DockableId(target), new TextArea(target)), DockTarget.area(target)));
}
DockLayoutView.Area editors = manager.layout().windows().getFirst().areas().getFirst();
assertEquals(3, editors.groups().size());
assertInstanceOf(DockLayoutView.Split.class,
assertInstanceOf(DockLayoutView.Split.class, editors.root()).second());
} catch (Throwable thrown) { failure.set(thrown); }
finally { done.countDown(); }
});
assertTrue(done.await(10, TimeUnit.SECONDS));
if (failure.get() != null) fail("Nested docking example failed", failure.get());
}
}
+1
View File
@@ -10,6 +10,7 @@
- [Bounded integer spinners](docs/integer-spinners.md) and [system tray support](docs/tray-support.md). - [Bounded integer spinners](docs/integer-spinners.md) and [system tray support](docs/tray-support.md).
- [Standalone toolbar and status bar](docs/bars.md), usable without MVVM. - [Standalone toolbar and status bar](docs/bars.md), usable without MVVM.
- [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples. - [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples.
- [Asynchronous tab close](docs/docking-close.md), including consent and resource release.
- [Dependency injection](../injection/README.md). - [Dependency injection](../injection/README.md).
## Introduction ## Introduction
+29
View File
@@ -0,0 +1,29 @@
# Asynchronous tab close
Use `Dockable.setCloseCheck` to supply a `CompletionStage<CloseConsent>`.
The callback receives the request scope and the JavaFX window hosting the
content. It can show a nonblocking confirmation or await a save. Return ALLOW
to close or VETO to keep the content available. A failed check is reported as
a veto with its cause. The manager resumes completion on the FX thread.
The tab's close control, context-menu action and `requestTabClose(id)` use the
same workflow. No tab content is removed while consent is pending. Repeated
requests covering that tab share the pending outcome and do not repeat prompts.
`closingScopeProperty()` reports affected IDs until the request and resource
release finish. Conflicting structural operations return `CLOSE_IN_PROGRESS`;
application prompts and content input can continue.
`setOnClosed` releases resources after an actual close. It is separate from
`setOnDiscarded`, which releases factory-prepared content that never opened.
Moving or vetoing a close calls neither close cleanup nor unused-content cleanup.
A cleanup exception is reported in `CloseResult.Closed.cleanupFailures()`;
it does not undo a completed close. Closing the active tab selects its group's
replacement or the most recently active visible Dockable, or clears the active
value if none is visible.
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. Window-wide shutdown is added by the
later lifecycle slices; this example demonstrates individual tab consent.
+17 -2
View File
@@ -5,6 +5,18 @@ a tab strip inserts at the displayed marker, including when reordering within
the same group. The tab's text/icon bindings and its live content stay intact. the same group. The tab's text/icon bindings and its live content stay intact.
All four tab sides are supported. All four tab sides are supported.
Dropping near a content edge creates an adjacent group and previews the half
that will receive the tab. The target group's allowed split directions,
minimum dimensions and application placement rule determine whether the split
is available. A rejected edge split falls back to joining that group. Moving
the sole tab to its own group's edge is an explicit no-change operation.
The tab strip always retains its insertion behavior.
Persistent empty groups remain drop destinations. When they release their
space, a narrow drop indicator appears at their configured outer edge during
the gesture. Their content remains hidden until a tab is actually placed there.
An invisible group that keeps its space accepts drops in its reserved area.
The move preview uses the same `checkMove` rules as an application command. The move preview uses the same `checkMove` rules as an application command.
Placement is checked again on release. A rejected location has no marker; Placement is checked again on release. A rejected location has no marker;
a move that would leave the tab where it is uses a muted marker. Escape a move that would leave the tab where it is uses a muted marker. Escape
@@ -15,13 +27,16 @@ Every tab also provides a **Move to** context submenu. It lists the currently
available groups and the selected content's current title. Rejected targets available groups and the selected content's current title. Rejected targets
are disabled with their reason; selecting an enabled item invokes the same are disabled with their reason; selecting an enabled item invokes the same
manager move operation and rechecks the destination. manager move operation and rechecks the destination.
The **Split** submenu offers the four directions for the tab's current group,
with unavailable directions disabled and explained. These explicit commands
request a split without the pointer gesture's join fallback.
The preview is mouse-transparent and has CSS class `dock-drop-indicator`. The preview is mouse-transparent and has CSS class `dock-drop-indicator`.
Its `no-change` pseudo-class identifies a preview that leaves the current Its `no-change` pseudo-class identifies a preview that leaves the current
placement intact. Applications may style its fill and stroke using JavaFX CSS. placement intact. Applications may style its fill and stroke using JavaFX CSS.
This slice covers the main window. Splitting, floating, cross-window pointer This slice covers the main window. Floating and cross-window pointer delivery
delivery and edge overlays extend these gestures in their respective tickets. extend these gestures in their respective tickets.
The gesture regression tests fire JavaFX events at visible tab headers and The gesture regression tests fire JavaFX events at visible tab headers and
observe the public manager state. Those tests do not by themselves establish observe the public manager state. Those tests do not by themselves establish
native mouse delivery across windows; that has a separate desktop acceptance native mouse delivery across windows; that has a separate desktop acceptance
+80
View File
@@ -0,0 +1,80 @@
# Split groups and predefined destinations
A `DockGroupDefinition` is one named group. A `DockSplitDefinition` is a named
binary branch with `first`, `second`, an `Orientation` and an initial `position`
between zero and one. Either branch can itself be a split. Both definitions
implement `DockLayoutNode`, so Java and ordinary FXML describe the same tree.
Each initial destination name must be unique across the complete layout.
Move an open Dockable with `DockTarget.split(groupId, Side.RIGHT)` (or another
side). The manager checks the target and application placement policy before
allocating a new group identity. `SplitDirections` permits `ALL`, `NONE`,
`HORIZONTAL` (left/right), or `VERTICAL` (top/bottom). The new group starts with
the target's tab presentation, size constraints and splitting policy. The two
groups can subsequently be configured independently.
Group minimum dimensions default to 80 pixels each and are configurable through
`minimumWidth` and `minimumHeight`. Splitting requires both minima plus the
divider to fit. A dynamic split starts evenly. A drop near a disabled or
ineligible edge falls back to tab insertion when insertion is allowed; an
explicit API split request returns its rejection instead. Dropping a group's
only tab on its own edge makes no change.
When either branch loses its last Dockable, that split dissolves and its sibling
fills the area. Nested splits inside the surviving branch remain. The emptied
concrete group ID no longer resolves. The predefined area ID remains usable and
now names the surviving group or branch. An area containing multiple groups
chooses the most recently active eligible group, then the first eligible group
in visual order. Callers can still name a concrete group to control placement
precisely. Initially empty branches elsewhere in the layout are unaffected by
an unrelated move.
`DockLayoutView.Area.groups()` lists its leaf groups in visual order. `root()`
exposes the immutable hierarchy as `DockLayoutView.Group` and
`DockLayoutView.Split`, including the published divider proportion. Named nested
destinations appear as areas as well; one concrete group can consequently be
reachable through several area IDs.
Groups are persistent by default. Outside an emptied split, an empty persistent
group keeps its destination and initial space. Set `visibleWhenEmpty=false` to
hide its empty content, and `releaseSpaceWhenEmpty=true` to give that space back.
Releasing space also hides the empty content, regardless of `visibleWhenEmpty`.
An empty side destination remains available as a narrow drop target at that
edge; a hidden group that retains its space accepts drops in its reserved bounds.
The last occupied side extent is retained when content returns. A root with
`persistent=false` disappears after its last Dockable leaves, including its
destination IDs. These settings are captured at attachment and inherited by a
newly split group.
Run `DockingMain --splits` for a Java-defined nested editor layout, or
`DockingMain --splits --fxml` for its ordinary FXML equivalent. The explicit
split button, tab context menu and edge drops share the same split checks.
Move the Project tab away to release the tool area, then drag it back to the
right edge to fill its persistent target again. The ordinary `--fxml` mode and
Java default still start with one editor group.
The split tests exercise both emptied-branch directions, nested ordinary FXML,
minimum-size and direction rejections, and area fallback after a placement
policy changes. The companion docking example demonstrates these interactions
through public operations.
## Resize boundaries
Both split dividers and the inner boundaries of predefined side areas are
draggable. Horizontal resizing uses the left/right cursor; vertical resizing
uses the up/down cursor. The content follows the pointer while group minima
remain in force. A boundary covered by a pending close request cannot resize;
unrelated areas remain available.
The read-only layout keeps its previously published geometry during the drag.
Releasing the pointer publishes the completed size or proportion once.
`Area.preferredWidth()` holds a left/right area's remembered content width;
`preferredHeight()` holds a top/bottom area's remembered content height. The
other dimension is `-1`, meaning it follows the available space. The five-pixel
outer divider is separate from the content extent. A side area's remembered
extent survives replacement of its split branch and temporary hiding.
The surrounding region has style class `dock-edge-area`; its resize handle has
`dock-area-divider`. The ordinary JavaFX `split-pane-divider` style class applies
to split dividers. These handles do not replace or recreate the application
content when resizing.
+3 -2
View File
@@ -38,8 +38,9 @@ application actions. Moving keyboard focus to a global button preserves it.
`activate(id)` selects the Dockable and requests focus within its content. `activate(id)` selects the Dockable and requests focus within its content.
The content instance remains owned by the application. A supplied The content instance remains owned by the application. A supplied
`setFocusTarget` chooses a Node within the content; otherwise the manager tries `setFocusTarget` chooses a Node within the content; otherwise the manager tries
the previously focused descendant. Future slices add splits, close consent the previously focused descendant. See [split groups](docking-splits.md) for
and restoration. nested layouts and resizing and [close consent](docking-close.md) for asynchronous
close checks. Restoration is supplied by a later slice.
## Move and check placement ## Move and check placement
@@ -0,0 +1,15 @@
package de.neitzel.fx.docking;
import java.util.concurrent.CompletionStage;
/** Application consent callback, invoked on the JavaFX Application Thread. */
@FunctionalInterface
public interface CloseCheck {
/**
* Asks whether the content can close, without closing it.
*
* @param request affected scope and owning window
* @return eventual consent; background saves may complete it from another thread
*/
CompletionStage<CloseConsent> check(CloseRequest request);
}
@@ -0,0 +1,4 @@
package de.neitzel.fx.docking;
/** A Dockable's answer after any application prompt or save has finished. */
public enum CloseConsent { ALLOW, VETO }
@@ -0,0 +1,13 @@
package de.neitzel.fx.docking;
import javafx.stage.Window;
import java.util.Objects;
/** Consent context, including the actual hosting window to use as dialog owner. */
public record CloseRequest(CloseScope scope, Window owner) {
public CloseRequest {
Objects.requireNonNull(scope, "scope");
Objects.requireNonNull(owner, "owner");
}
}
@@ -0,0 +1,23 @@
package de.neitzel.fx.docking;
import java.util.List;
/** Final close outcome, kept separate from consent and resource-release errors. */
public sealed interface CloseResult {
record Closed(List<DockFailure> cleanupFailures) implements CloseResult {
public Closed { cleanupFailures = List.copyOf(cleanupFailures); }
}
record NoChange() implements CloseResult { }
record Vetoed(List<DockableId> vetoingIds, List<DockFailure> checkFailures) implements CloseResult {
public Vetoed {
vetoingIds = List.copyOf(vetoingIds);
checkFailures = List.copyOf(checkFailures);
}
}
record Canceled() implements CloseResult { }
record Rejected(DockFailure failure) implements CloseResult { }
}
@@ -0,0 +1,15 @@
package de.neitzel.fx.docking;
import java.util.List;
import java.util.Objects;
/** Immutable description of the Dockables covered by the running close request. */
public record CloseScope(Kind kind, List<DockableId> dockableIds) {
public CloseScope {
Objects.requireNonNull(kind, "kind");
dockableIds = List.copyOf(dockableIds);
}
/** The entry point that requested consent. */
public enum Kind { TAB }
}
@@ -0,0 +1,129 @@
package de.neitzel.fx.docking;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.stage.Window;
import java.util.List;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/** Keeps consent, live-layout removal and application resource release in order. */
final class DockCloseCoordinator {
interface Host {
Optional<Dockable> find(DockableId id);
Window owner(DockableId id);
void remove(DockableId id);
}
private final Host host;
private final ReadOnlyObjectWrapper<CloseScope> scope = new ReadOnlyObjectWrapper<>(this, "closingScope");
private CompletableFuture<CloseResult> completion;
private CompletionStage<CloseResult> outcome;
private final LinkedHashMap<DockableId, CompletableFuture<CloseResult>> queued = new LinkedHashMap<>();
DockCloseCoordinator(Host host) {
this.host = host;
}
ReadOnlyObjectProperty<CloseScope> closingScopeProperty() {
return scope.getReadOnlyProperty();
}
CloseScope scope() {
return scope.get();
}
CompletionStage<CloseResult> requestTabClose(DockableId id) {
if (!Platform.isFxApplicationThread()) {
throw new IllegalStateException("Docking operations require the JavaFX Application Thread");
}
Objects.requireNonNull(id, "id");
if (completion != null) {
if (scope.get().dockableIds().contains(id)) return outcome;
return enqueue(id);
}
if (!queued.isEmpty()) {
CompletionStage<CloseResult> result = enqueue(id);
Platform.runLater(this::nextQueued);
return result;
}
return begin(id);
}
private CompletionStage<CloseResult> enqueue(DockableId id) {
return queued.computeIfAbsent(id, ignored -> new CompletableFuture<>()).minimalCompletionStage();
}
private void nextQueued() {
if (completion != null || queued.isEmpty()) return;
var next = queued.pollFirstEntry();
begin(next.getKey()).whenComplete((result, failure) -> {
if (failure != null) next.getValue().completeExceptionally(failure);
else next.getValue().complete(result);
});
if (completion == null && !queued.isEmpty()) Platform.runLater(this::nextQueued);
}
private CompletionStage<CloseResult> begin(DockableId id) {
Dockable dockable = host.find(id).orElse(null);
if (dockable == null) return CompletableFuture.completedFuture(new CloseResult.NoChange());
CompletableFuture<CloseResult> request = new CompletableFuture<>();
CompletionStage<CloseResult> result = request.minimalCompletionStage();
completion = request;
outcome = result;
scope.set(new CloseScope(CloseScope.Kind.TAB, List.of(id)));
try {
CompletionStage<CloseConsent> answer = dockable.getCloseCheck() == null
? CompletableFuture.completedFuture(CloseConsent.ALLOW)
: Objects.requireNonNull(dockable.getCloseCheck().check(new CloseRequest(scope.get(), host.owner(id))),
"Close check returned no stage");
answer.whenComplete((consent, failure) -> onFx(() -> answered(request, dockable, consent, failure)));
} catch (RuntimeException failure) {
answered(request, dockable, null, failure);
}
return result;
}
private void answered(CompletableFuture<CloseResult> request, Dockable dockable,
CloseConsent consent, Throwable failure) {
if (completion != request) return;
if (failure != null || consent == null) {
Throwable cause = failure == null ? new IllegalStateException("Close check returned no consent") : failure;
DockFailure checkFailure = new DockFailure(DockFailure.Code.CLOSE_CHECK_FAILED,
dockable.getId(), "Close consent check failed", cause);
finish(request, new CloseResult.Vetoed(List.of(dockable.getId()), List.of(checkFailure)));
} else if (consent == CloseConsent.VETO) {
finish(request, new CloseResult.Vetoed(List.of(dockable.getId()), List.of()));
} else {
host.remove(dockable.getId());
List<DockFailure> cleanupFailures = List.of();
if (dockable.getOnClosed() != null) {
try {
dockable.getOnClosed().run();
} catch (RuntimeException cleanup) {
cleanupFailures = List.of(new DockFailure(DockFailure.Code.CLEANUP_FAILED,
dockable.getId(), "Closed Dockable resource release failed", cleanup));
}
}
finish(request, new CloseResult.Closed(cleanupFailures));
}
}
private void finish(CompletableFuture<CloseResult> request, CloseResult result) {
completion = null;
outcome = null;
scope.set(null);
request.complete(result);
if (!queued.isEmpty()) Platform.runLater(this::nextQueued);
}
private static void onFx(Runnable action) {
if (Platform.isFxApplicationThread()) action.run();
else Platform.runLater(action);
}
}
@@ -17,13 +17,16 @@ import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent; import javafx.scene.input.MouseEvent;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Supplier; import java.util.function.Supplier;
/** Translates pointer gestures on tab headers into ordinary checked manager moves. */ /** Translates pointer gestures on tab headers into ordinary checked manager moves. */
final class DockDragController { final class DockDragController {
record GroupSurface(DockGroupId id, TabPane tabs) { } record GroupSurface(DockGroupId id, TabPane tabs, Side edge) {
GroupSurface(DockGroupId id, TabPane tabs) { this(id, tabs, null); }
}
private record Proposal(DockTarget target, Bounds marker) { } private record Proposal(DockTarget target, Bounds marker) { }
private record Header(DockableId id, Bounds bounds) { } private record Header(DockableId id, Bounds bounds) { }
@@ -54,35 +57,72 @@ final class DockDragController {
tab.setId(headerId); tab.setId(headerId);
headers.put(headerId, id); headers.put(headerId, id);
Menu destinations = new Menu("Move to"); Menu destinations = new Menu("Move to");
ContextMenu menu = new ContextMenu(destinations); Menu splits = new Menu("Split");
menu.setOnShowing(event -> populateDestinations(destinations, id)); MenuItem close = new MenuItem("Close");
close.setOnAction(event -> manager.requestTabClose(id));
ContextMenu menu = new ContextMenu(destinations, splits, close);
menu.setOnShowing(event -> {
populateDestinations(destinations, id);
populateSplits(splits, id);
});
tab.setContextMenu(menu); tab.setContextMenu(menu);
} }
void uninstallTab(Tab tab) {
DockableId removed = headers.remove(tab.getId());
if (removed != null && removed.equals(pressed)) cancel();
if (tab.getContextMenu() != null) {
tab.getContextMenu().hide();
tab.getContextMenu().setOnShowing(null);
tab.setContextMenu(null);
}
}
private void populateDestinations(Menu menu, DockableId id) { private void populateDestinations(Menu menu, DockableId id) {
menu.getItems().clear(); menu.getItems().clear();
var visited = new HashSet<DockGroupId>();
for (DockLayoutView.Window window : manager.layout().windows()) { for (DockLayoutView.Window window : manager.layout().windows()) {
for (DockLayoutView.Area area : window.areas()) { for (DockLayoutView.Area area : window.areas()) {
for (DockLayoutView.Group group : area.groups()) { for (DockLayoutView.Group group : area.groups()) {
if (!visited.add(group.id())) continue;
DockTarget target = DockTarget.group(group.id()); DockTarget target = DockTarget.group(group.id());
MoveCheck check = manager.checkMove(id, target);
String selectedTitle = group.selectedDockableId() == null ? "" : manager String selectedTitle = group.selectedDockableId() == null ? "" : manager
.findDockable(group.selectedDockableId()).map(Dockable::getTitle).orElse(""); .findDockable(group.selectedDockableId()).map(Dockable::getTitle).orElse("");
String label = group.id().value() + (selectedTitle.isBlank() ? "" : " — " + selectedTitle); String label = group.id().value() + (selectedTitle.isBlank() ? "" : " — " + selectedTitle);
if (check instanceof MoveCheck.Rejected rejected) { menu.getItems().add(moveItem(label, id, target));
label += " (" + rejected.failure().message() + ")";
} else if (check instanceof MoveCheck.NoChange) {
label += " (Already here)";
}
MenuItem item = new MenuItem(label);
item.setDisable(!(check instanceof MoveCheck.Allowed));
item.setOnAction(event -> manager.move(id, target));
menu.getItems().add(item);
} }
} }
} }
} }
private void populateSplits(Menu menu, DockableId id) {
menu.getItems().clear();
manager.layout().windows().stream().flatMap(window -> window.areas().stream())
.flatMap(area -> area.groups().stream()).filter(group -> group.dockableIds().contains(id))
.findFirst().ifPresent(group -> {
for (Side side : Side.values()) {
String label = switch (side) {
case TOP -> "Above";
case RIGHT -> "Right";
case BOTTOM -> "Below";
case LEFT -> "Left";
};
menu.getItems().add(moveItem(label, id, DockTarget.split(group.id(), side)));
}
});
menu.setDisable(menu.getItems().isEmpty());
}
private MenuItem moveItem(String label, DockableId id, DockTarget target) {
MoveCheck check = manager.checkMove(id, target);
if (check instanceof MoveCheck.Rejected rejected) label += " (" + rejected.failure().message() + ")";
else if (check instanceof MoveCheck.NoChange) label += " (Already here)";
MenuItem item = new MenuItem(label);
item.setDisable(!(check instanceof MoveCheck.Allowed));
item.setOnAction(event -> manager.move(id, target));
return item;
}
void dispose() { void dispose() {
pane.removeEventFilter(MouseEvent.ANY, mouseHandler); pane.removeEventFilter(MouseEvent.ANY, mouseHandler);
scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler); scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler);
@@ -113,7 +153,7 @@ final class DockDragController {
boolean apply = dragging; boolean apply = dragging;
cancel(); cancel();
if (apply) { if (apply) {
Proposal proposal = proposal(event.getScreenX(), event.getScreenY()); Proposal proposal = proposal(id, event.getScreenX(), event.getScreenY());
if (proposal != null) manager.move(id, proposal.target()); if (proposal != null) manager.move(id, proposal.target());
event.consume(); event.consume();
} }
@@ -121,7 +161,7 @@ final class DockDragController {
} }
private void preview(double screenX, double screenY) { private void preview(double screenX, double screenY) {
Proposal proposal = proposal(screenX, screenY); Proposal proposal = proposal(pressed, screenX, screenY);
if (proposal != null) { if (proposal != null) {
MoveCheck check = manager.checkMove(pressed, proposal.target()); MoveCheck check = manager.checkMove(pressed, proposal.target());
if (!(check instanceof MoveCheck.Rejected)) { if (!(check instanceof MoveCheck.Rejected)) {
@@ -132,8 +172,16 @@ final class DockDragController {
pane.hideDropIndicator(); pane.hideDropIndicator();
} }
private Proposal proposal(double screenX, double screenY) { private Proposal proposal(DockableId id, double screenX, double screenY) {
for (GroupSurface group : surfaces.get()) { List<GroupSurface> groups = surfaces.get();
for (GroupSurface group : groups) {
if (hidden(group) && (group.edge() != null || group.tabs().isManaged())) {
Proposal empty = emptyProposal(group, screenX, screenY);
if (empty != null) return empty;
}
}
for (GroupSurface group : groups) {
if (hidden(group)) continue;
Bounds bounds = group.tabs().localToScreen(group.tabs().getBoundsInLocal()); Bounds bounds = group.tabs().localToScreen(group.tabs().getBoundsInLocal());
if (bounds == null || !bounds.contains(screenX, screenY)) continue; if (bounds == null || !bounds.contains(screenX, screenY)) continue;
Node strip = group.tabs().lookup(".tab-header-area"); Node strip = group.tabs().lookup(".tab-header-area");
@@ -142,11 +190,86 @@ final class DockDragController {
Proposal insertion = insertion(group, screenX, screenY); Proposal insertion = insertion(group, screenX, screenY);
if (insertion != null) return insertion; if (insertion != null) return insertion;
} }
Bounds content = contentBounds(bounds, stripBounds, group.tabs().getSide());
Side edge = edgeAt(content, screenX, screenY);
if (edge != null) {
DockTarget target = DockTarget.split(group.id(), edge);
MoveCheck split = manager.checkMove(id, target);
if (split instanceof MoveCheck.Allowed) return new Proposal(target, half(content, edge));
if (split instanceof MoveCheck.NoChange) return new Proposal(target, bounds);
}
return new Proposal(DockTarget.group(group.id()), bounds); return new Proposal(DockTarget.group(group.id()), bounds);
} }
for (GroupSurface group : groups) {
if (hidden(group) && group.edge() == null && !group.tabs().isManaged()) {
Proposal empty = emptyProposal(group, screenX, screenY);
if (empty != null) return empty;
}
}
return null; return null;
} }
private static boolean hidden(GroupSurface group) {
return !group.tabs().isVisible() || !group.tabs().isManaged();
}
private Proposal emptyProposal(GroupSurface group, double x, double y) {
Bounds bounds = group.tabs().isManaged()
? group.tabs().localToScreen(group.tabs().getBoundsInLocal())
: pane.localToScreen(pane.getBoundsInLocal());
if (bounds == null) return null;
if (!group.tabs().isManaged() && group.edge() != null) {
double width = Math.min(20, bounds.getWidth());
double height = Math.min(20, bounds.getHeight());
bounds = switch (group.edge()) {
case LEFT -> new BoundingBox(bounds.getMinX(), bounds.getMinY(), width, bounds.getHeight());
case RIGHT -> new BoundingBox(bounds.getMaxX() - width, bounds.getMinY(), width, bounds.getHeight());
case TOP -> new BoundingBox(bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), height);
case BOTTOM -> new BoundingBox(bounds.getMinX(), bounds.getMaxY() - height, bounds.getWidth(), height);
};
}
return bounds.contains(x, y) ? new Proposal(DockTarget.group(group.id()), bounds) : null;
}
private static Bounds contentBounds(Bounds group, Bounds strip, Side side) {
if (strip == null) return group;
double left = side == Side.LEFT ? Math.max(group.getMinX(), strip.getMaxX()) : group.getMinX();
double top = side == Side.TOP ? Math.max(group.getMinY(), strip.getMaxY()) : group.getMinY();
double right = side == Side.RIGHT ? Math.min(group.getMaxX(), strip.getMinX()) : group.getMaxX();
double bottom = side == Side.BOTTOM ? Math.min(group.getMaxY(), strip.getMinY()) : group.getMaxY();
return new BoundingBox(left, top, Math.max(0, right - left), Math.max(0, bottom - top));
}
private static Side edgeAt(Bounds content, double x, double y) {
if (!content.contains(x, y) || content.getWidth() <= 0 || content.getHeight() <= 0) return null;
double horizontal = Math.min(40, content.getWidth() / 5);
double vertical = Math.min(40, content.getHeight() / 5);
double best = 1;
Side selected = null;
for (Side side : Side.values()) {
double distance = switch (side) {
case LEFT -> (x - content.getMinX()) / horizontal;
case RIGHT -> (content.getMaxX() - x) / horizontal;
case TOP -> (y - content.getMinY()) / vertical;
case BOTTOM -> (content.getMaxY() - y) / vertical;
};
if (distance < best) {
best = distance;
selected = side;
}
}
return selected;
}
private static Bounds half(Bounds bounds, Side side) {
return switch (side) {
case LEFT -> new BoundingBox(bounds.getMinX(), bounds.getMinY(), bounds.getWidth() / 2, bounds.getHeight());
case RIGHT -> new BoundingBox(bounds.getCenterX(), bounds.getMinY(), bounds.getWidth() / 2, bounds.getHeight());
case TOP -> new BoundingBox(bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), bounds.getHeight() / 2);
case BOTTOM -> new BoundingBox(bounds.getMinX(), bounds.getCenterY(), bounds.getWidth(), bounds.getHeight() / 2);
};
}
private Proposal insertion(GroupSurface group, double x, double y) { private Proposal insertion(GroupSurface group, double x, double y) {
List<Header> visible = group.tabs().getTabs().stream().map(tab -> { List<Header> visible = group.tabs().getTabs().stream().map(tab -> {
Node node = group.tabs().lookup("#" + tab.getId()); Node node = group.tabs().lookup("#" + tab.getId());
@@ -0,0 +1,136 @@
package de.neitzel.fx.docking;
import javafx.geometry.Side;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Region;
import java.util.function.DoubleSupplier;
import java.util.function.BooleanSupplier;
/** Retains a side area's extent while its split branch is replaced or hidden. */
final class DockEdgeRegion extends Region {
private static final double DIVIDER_SIZE = 5;
private final Side side;
private final Region divider = new Region();
private final DoubleSupplier maximum;
private final Runnable completed;
private final BooleanSupplier canResize;
private Node content;
private double extent = -1;
private double committedExtent = -1;
private double pressedAt;
private double pressedExtent;
private boolean dragging;
DockEdgeRegion(Side side, DoubleSupplier maximum, BooleanSupplier canResize, Runnable completed) {
this.side = side;
this.maximum = maximum;
this.completed = completed;
this.canResize = canResize;
getStyleClass().add("dock-edge-area");
divider.getStyleClass().add("dock-area-divider");
divider.setCursor(side.isVertical() ? Cursor.H_RESIZE : Cursor.V_RESIZE);
divider.setOnMousePressed(event -> {
if (event.getButton() != MouseButton.PRIMARY) return;
if (!canResize.getAsBoolean()) {
event.consume();
return;
}
dragging = true;
pressedAt = side.isVertical() ? event.getScreenX() : event.getScreenY();
pressedExtent = Math.max(0, (side.isVertical() ? getWidth() : getHeight()) - DIVIDER_SIZE);
event.consume();
});
divider.setOnMouseDragged(event -> {
if (!dragging || content == null) return;
if (!canResize.getAsBoolean()) {
cancelResize();
event.consume();
return;
}
double current = side.isVertical() ? event.getScreenX() : event.getScreenY();
double direction = side == Side.LEFT || side == Side.TOP ? 1 : -1;
double minimum = side.isVertical() ? content.minWidth(-1) : content.minHeight(-1);
extent = Math.max(minimum, Math.min(maximum.getAsDouble() - DIVIDER_SIZE,
pressedExtent + direction * (current - pressedAt)));
requestLayout();
event.consume();
});
divider.setOnMouseReleased(event -> {
if (!dragging) return;
if (!canResize.getAsBoolean()) {
cancelResize();
event.consume();
return;
}
dragging = false;
if (Double.compare(committedExtent, extent) != 0) {
committedExtent = extent;
completed.run();
}
event.consume();
});
}
private void cancelResize() {
dragging = false;
extent = committedExtent;
requestLayout();
}
void setContent(Node content) {
managedProperty().unbind();
visibleProperty().unbind();
this.content = content;
getChildren().clear();
if (content == null) {
setManaged(false);
setVisible(false);
return;
}
if (extent < 0) {
extent = side.isVertical() ? content.prefWidth(-1) : content.prefHeight(-1);
committedExtent = extent;
}
getChildren().addAll(content, divider);
managedProperty().bind(content.managedProperty());
visibleProperty().bind(content.visibleProperty());
requestLayout();
}
double committedExtent() { return committedExtent; }
Side side() { return side; }
@Override protected double computePrefWidth(double height) {
return side.isVertical() ? extent + DIVIDER_SIZE : content == null ? 0 : content.prefWidth(height);
}
@Override protected double computePrefHeight(double width) {
return side.isHorizontal() ? extent + DIVIDER_SIZE : content == null ? 0 : content.prefHeight(width);
}
@Override protected double computeMinWidth(double height) {
return content == null ? 0 : content.minWidth(height) + (side.isVertical() ? DIVIDER_SIZE : 0);
}
@Override protected double computeMinHeight(double width) {
return content == null ? 0 : content.minHeight(width) + (side.isHorizontal() ? DIVIDER_SIZE : 0);
}
@Override protected void layoutChildren() {
if (content == null) return;
double width = getWidth();
double height = getHeight();
if (side.isVertical()) {
content.resizeRelocate(side == Side.RIGHT ? DIVIDER_SIZE : 0, 0,
Math.max(0, width - DIVIDER_SIZE), height);
divider.resizeRelocate(side == Side.RIGHT ? 0 : width - DIVIDER_SIZE, 0, DIVIDER_SIZE, height);
} else {
content.resizeRelocate(0, side == Side.BOTTOM ? DIVIDER_SIZE : 0,
width, Math.max(0, height - DIVIDER_SIZE));
divider.resizeRelocate(0, side == Side.BOTTOM ? 0 : height - DIVIDER_SIZE, width, DIVIDER_SIZE);
}
}
}
@@ -2,6 +2,7 @@ package de.neitzel.fx.docking;
/** Machine-readable rejection with optional affected identity and technical cause. */ /** Machine-readable rejection with optional affected identity and technical cause. */
public record DockFailure(Code code, DockableId dockableId, String message, Throwable cause) { public record DockFailure(Code code, DockableId dockableId, String message, Throwable cause) {
public enum Code { TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED, public enum Code { SPLIT_DISABLED, SPLIT_TOO_SMALL, TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED,
PLACEMENT_REJECTED, PLACEMENT_CHECK_FAILED, ID_MISMATCH, FACTORY_FAILED } PLACEMENT_REJECTED, PLACEMENT_CHECK_FAILED, ID_MISMATCH, FACTORY_FAILED,
CLOSE_IN_PROGRESS, CLOSE_CHECK_FAILED, CLEANUP_FAILED }
} }
@@ -6,11 +6,17 @@ import lombok.Setter;
/** JavaBean definition of a named initial tab group, usable in ordinary FXML. */ /** JavaBean definition of a named initial tab group, usable in ordinary FXML. */
@Getter @Setter @Getter @Setter
public final class DockGroupDefinition { public final class DockGroupDefinition implements DockLayoutNode {
private String destinationId; private String destinationId;
private Side tabSide = Side.TOP; private Side tabSide = Side.TOP;
private double preferredWidth = 200; private double preferredWidth = 200;
private double preferredHeight = 150; private double preferredHeight = 150;
private double minimumWidth = 80;
private double minimumHeight = 80;
private boolean persistent = true;
private boolean visibleWhenEmpty = true;
private boolean releaseSpaceWhenEmpty;
private SplitDirections splitDirections = SplitDirections.ALL;
/** Creates a definition for FXML configuration. */ /** Creates a definition for FXML configuration. */
public DockGroupDefinition() { } public DockGroupDefinition() { }
@@ -6,9 +6,9 @@ import lombok.Setter;
/** Initial named destinations surrounding a central group. */ /** Initial named destinations surrounding a central group. */
@Getter @Setter @Getter @Setter
public final class DockLayout { public final class DockLayout {
private DockGroupDefinition center; private DockLayoutNode center;
private DockGroupDefinition left; private DockLayoutNode left;
private DockGroupDefinition right; private DockLayoutNode right;
private DockGroupDefinition top; private DockLayoutNode top;
private DockGroupDefinition bottom; private DockLayoutNode bottom;
} }
@@ -0,0 +1,7 @@
package de.neitzel.fx.docking;
/** A named initial destination, containing either a group or a binary split. */
public sealed interface DockLayoutNode permits DockGroupDefinition, DockSplitDefinition {
String getDestinationId();
void setDestinationId(String id);
}
@@ -0,0 +1,303 @@
package de.neitzel.fx.docking;
import javafx.geometry.Orientation;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.Cursor;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/** Owns the visual split hierarchy and the stable predefined destinations into it. */
final class DockLayoutTree {
private sealed interface Branch permits Leaf, Split {
Node node();
List<DockingManager.Group> groups();
DockLayoutView.LayoutNode view();
}
private record Leaf(DockingManager.Group group) implements Branch {
@Override public Node node() { return group.tabs(); }
@Override public List<DockingManager.Group> groups() { return List.of(group); }
@Override public DockLayoutView.LayoutNode view() {
Tab selected = group.tabs().getSelectionModel().getSelectedItem();
return new DockLayoutView.Group(group.id(), group.tabs().getSide(),
group.tabs().getTabs().stream().map(tab -> (DockableId) tab.getUserData()).toList(),
selected == null ? null : (DockableId) selected.getUserData());
}
}
private static final class Split implements Branch {
private Branch first;
private Branch second;
private final SplitPane pane = new SplitPane();
private double position = .5;
private boolean dragging;
Split(Branch first, Branch second, Orientation orientation) {
this.first = first;
this.second = second;
pane.setOrientation(orientation);
}
@Override public Node node() { return pane; }
@Override public List<DockingManager.Group> groups() {
var groups = new ArrayList<>(first.groups());
groups.addAll(second.groups());
return List.copyOf(groups);
}
@Override public DockLayoutView.LayoutNode view() {
return new DockLayoutView.Split(pane.getOrientation(), position, first.view(), second.view());
}
}
private static final class Root {
private Branch branch;
private final Consumer<Node> place;
Root(Branch branch, Consumer<Node> place) { this.branch = branch; this.place = place; }
}
private final Runnable geometryChanged;
private final java.util.function.Predicate<DockGroupId> canResize;
DockLayoutTree(Runnable geometryChanged, java.util.function.Predicate<DockGroupId> canResize) {
this.geometryChanged = geometryChanged;
this.canResize = canResize;
}
private final Map<DockAreaId, Branch> areas = new LinkedHashMap<>();
private final List<Root> roots = new ArrayList<>();
void addArea(DockLayoutNode definition, Consumer<Node> place,
java.util.function.Function<DockGroupDefinition, DockingManager.Group> groupFactory) {
Branch branch = build(definition, groupFactory);
roots.add(new Root(branch, place));
render(branch);
place.accept(branch.node());
}
private Branch build(DockLayoutNode definition,
java.util.function.Function<DockGroupDefinition, DockingManager.Group> groupFactory) {
DockAreaId id = new DockAreaId(definition.getDestinationId());
areas.put(id, null);
Branch branch;
if (definition instanceof DockGroupDefinition group) {
branch = new Leaf(groupFactory.apply(group));
} else {
DockSplitDefinition splitDefinition = (DockSplitDefinition) definition;
Split split = split(build(splitDefinition.getFirst(), groupFactory),
build(splitDefinition.getSecond(), groupFactory), splitDefinition.getOrientation());
split.position = splitDefinition.getPosition();
branch = split;
}
areas.put(id, branch);
return branch;
}
List<DockingManager.Group> groups(DockAreaId id) {
Branch branch = areas.get(id);
return branch == null ? List.of() : branch.groups();
}
void split(DockingManager.Group target, DockingManager.Group added, Side side) {
Branch old = find(target.id());
Branch leaf = new Leaf(added);
Split split = side == Side.LEFT || side == Side.TOP
? split(leaf, old, side.isVertical() ? Orientation.HORIZONTAL : Orientation.VERTICAL)
: split(old, leaf, side.isVertical() ? Orientation.HORIZONTAL : Orientation.VERTICAL);
detach();
replace(old, split);
render();
}
private Split split(Branch first, Branch second, Orientation orientation) {
Split split = new Split(first, second, orientation);
split.pane.getStyleClass().add("dock-split");
split.pane.addEventFilter(MouseEvent.ANY, event -> {
Node divider = divider(event.getPickResult().getIntersectedNode(), split.pane);
if (divider == null && !split.dragging) return;
if (divider != null) {
divider.setCursor(orientation == Orientation.HORIZONTAL ? Cursor.H_RESIZE : Cursor.V_RESIZE);
if (!divider.getStyleClass().contains("dock-divider")) divider.getStyleClass().add("dock-divider");
}
boolean geometryEvent = event.getEventType() == MouseEvent.MOUSE_PRESSED
|| event.getEventType() == MouseEvent.MOUSE_DRAGGED || event.getEventType() == MouseEvent.MOUSE_RELEASED;
if (geometryEvent && split.groups().stream().anyMatch(group -> !canResize.test(group.id()))) {
if (split.dragging) split.pane.setDividerPositions(split.position);
split.dragging = false;
event.consume();
return;
}
if (event.getEventType() == MouseEvent.MOUSE_PRESSED && event.getButton() == MouseButton.PRIMARY) {
split.dragging = true;
} else if (event.getEventType() == MouseEvent.MOUSE_RELEASED && split.dragging) {
split.dragging = false;
double position = split.pane.getDividers().getFirst().getPosition();
if (Double.compare(split.position, position) != 0) {
split.position = position;
geometryChanged.run();
}
}
});
return split;
}
private static Node divider(Node node, SplitPane pane) {
Node divider = null;
for (Node current = node; current != null; current = current.getParent()) {
if (current instanceof SplitPane) return current == pane ? divider : null;
if (current.getStyleClass().contains("split-pane-divider")) divider = current;
}
return null;
}
boolean normalizationAffects(DockGroupId source, DockGroupId destination,
java.util.function.Predicate<DockingManager.Group> protectedGroup) {
if (find(source).groups().getFirst().tabs().getTabs().size() != 1) return false;
return roots.stream().anyMatch(root -> normalizationAffects(root.branch, source, destination, protectedGroup));
}
private static boolean normalizationAffects(Branch branch, DockGroupId source, DockGroupId destination,
java.util.function.Predicate<DockingManager.Group> protectedGroup) {
if (!(branch instanceof Split split) || find(branch, source) == null) return false;
if ((emptyAfterMove(split.first, source, destination) || emptyAfterMove(split.second, source, destination))
&& split.groups().stream().anyMatch(protectedGroup)) return true;
return normalizationAffects(split.first, source, destination, protectedGroup)
|| normalizationAffects(split.second, source, destination, protectedGroup);
}
private static boolean emptyAfterMove(Branch branch, DockGroupId source, DockGroupId destination) {
return branch.groups().stream().allMatch(group -> group.tabs().getTabs().size()
- (group.id().equals(source) ? 1 : 0) + (group.id().equals(destination) ? 1 : 0) == 0);
}
List<DockGroupId> normalize(DockGroupId source) {
Branch emptied = find(source);
if (!empty(emptied)) return List.of();
detach();
List<DockGroupId> removed = new ArrayList<>();
for (var iterator = roots.iterator(); iterator.hasNext();) {
Root root = iterator.next();
boolean affected = includes(root.branch, emptied);
root.branch = normalize(root.branch, emptied, removed);
if (affected && root.branch instanceof Leaf leaf && empty(leaf)
&& !leaf.group.definition().isPersistent()) {
areas.entrySet().removeIf(entry -> entry.getValue() == leaf);
removed.add(leaf.group.id());
iterator.remove();
}
}
render();
return List.copyOf(removed);
}
private Branch normalize(Branch branch, Branch emptied, List<DockGroupId> removed) {
if (!(branch instanceof Split split) || !includes(branch, emptied)) return branch;
split.first = normalize(split.first, emptied, removed);
split.second = normalize(split.second, emptied, removed);
boolean firstEmpty = empty(split.first);
boolean secondEmpty = empty(split.second);
if (!firstEmpty && !secondEmpty) return split;
Branch survivor = firstEmpty && !secondEmpty ? split.second : split.first;
Branch discarded = survivor == split.first ? split.second : split.first;
discarded.groups().forEach(group -> removed.add(group.id()));
areas.replaceAll((id, destination) -> destination == split || includes(discarded, destination)
? survivor : destination);
return survivor;
}
private static boolean includes(Branch branch, Branch target) {
if (branch == target) return true;
return branch instanceof Split split && (includes(split.first, target) || includes(split.second, target));
}
private static boolean empty(Branch branch) {
return branch.groups().stream().allMatch(group -> group.tabs().getTabs().isEmpty());
}
void captureGeometry() {
for (Root root : roots) captureGeometry(root.branch);
}
private static void captureGeometry(Branch branch) {
if (branch instanceof Split split) {
if (!split.dragging && split.pane.getWidth() > 0 && split.pane.getHeight() > 0
&& !split.pane.getDividers().isEmpty()) {
split.position = split.pane.getDividers().getFirst().getPosition();
}
captureGeometry(split.first);
captureGeometry(split.second);
}
}
List<DockLayoutView.Area> view() {
return areas.entrySet().stream().map(entry -> new DockLayoutView.Area(entry.getKey(),
entry.getValue().groups().stream().map(group -> (DockLayoutView.Group) new Leaf(group).view()).toList(),
entry.getValue().view())).toList();
}
private Branch find(DockGroupId id) {
for (Root root : roots) {
Branch found = find(root.branch, id);
if (found != null) return found;
}
throw new IllegalArgumentException("Group is not in the layout: " + id);
}
private static Branch find(Branch branch, DockGroupId id) {
if (branch instanceof Leaf leaf) return leaf.group.id().equals(id) ? leaf : null;
Split split = (Split) branch;
Branch found = find(split.first, id);
return found == null ? find(split.second, id) : found;
}
private void replace(Branch old, Branch replacement) {
for (Root root : roots) root.branch = replace(root.branch, old, replacement);
areas.replaceAll((id, branch) -> branch == old ? replacement : branch);
}
private static Branch replace(Branch branch, Branch old, Branch replacement) {
if (branch == old) return replacement;
if (branch instanceof Split split) {
split.first = replace(split.first, old, replacement);
split.second = replace(split.second, old, replacement);
}
return branch;
}
private void detach() {
for (Root root : roots) {
root.place.accept(null);
detach(root.branch);
}
}
private static void detach(Branch branch) {
if (branch instanceof Split split) {
split.pane.getItems().clear();
detach(split.first);
detach(split.second);
}
}
private void render() {
for (Root root : roots) {
render(root.branch);
root.place.accept(root.branch.node());
}
}
private static void render(Branch branch) {
if (branch instanceof Split split) {
render(split.first);
render(split.second);
split.pane.getItems().setAll(split.first.node(), split.second.node());
split.pane.setDividerPositions(split.position);
}
}
}
@@ -9,11 +9,22 @@ public record DockLayoutView(List<Window> windows) {
public record Window(DockWindowId id, boolean main, List<Area> areas) { public record Window(DockWindowId id, boolean main, List<Area> areas) {
public Window { areas = List.copyOf(areas); } public Window { areas = List.copyOf(areas); }
} }
public record Area(DockAreaId id, List<Group> groups) { /** Preferred side content extent; -1 means that dimension follows the available space. */
public record Area(DockAreaId id, List<Group> groups, LayoutNode root,
double preferredWidth, double preferredHeight) {
public Area { groups = List.copyOf(groups); } public Area { groups = List.copyOf(groups); }
public Area(DockAreaId id, List<Group> groups, LayoutNode root) {
this(id, groups, root, -1, -1);
}
public Area(DockAreaId id, List<Group> groups) {
this(id, groups, groups.isEmpty() ? null : groups.getFirst());
}
} }
public sealed interface LayoutNode { }
public record Split(javafx.geometry.Orientation orientation, double position,
LayoutNode first, LayoutNode second) implements LayoutNode { }
public record Group(DockGroupId id, Side tabSide, List<DockableId> dockableIds, public record Group(DockGroupId id, Side tabSide, List<DockableId> dockableIds,
DockableId selectedDockableId) { DockableId selectedDockableId) implements LayoutNode {
public Group { dockableIds = List.copyOf(dockableIds); } public Group { dockableIds = List.copyOf(dockableIds); }
} }
} }
@@ -3,6 +3,8 @@ package de.neitzel.fx.docking;
import javafx.scene.layout.BorderPane; import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Region; import javafx.scene.layout.Region;
import javafx.geometry.Bounds; import javafx.geometry.Bounds;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.paint.Color; import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle; import javafx.scene.shape.Rectangle;
import lombok.Getter; import lombok.Getter;
@@ -13,6 +15,7 @@ public final class DockPane extends Region {
@Getter @Setter private DockLayout initialLayout = new DockLayout(); @Getter @Setter private DockLayout initialLayout = new DockLayout();
final BorderPane surface = new BorderPane(); final BorderPane surface = new BorderPane();
private final Rectangle dropIndicator = new Rectangle(); private final Rectangle dropIndicator = new Rectangle();
private final java.util.Map<Side, DockEdgeRegion> edgeAreas = new java.util.EnumMap<>(Side.class);
DockingManager manager; DockingManager manager;
public DockPane() { public DockPane() {
@@ -42,6 +45,50 @@ public final class DockPane extends Region {
dropIndicator.setVisible(false); dropIndicator.setVisible(false);
} }
void setArea(Side side, Node content, java.util.function.BooleanSupplier canResize, Runnable completed) {
DockEdgeRegion area = edgeAreas.computeIfAbsent(side,
edge -> new DockEdgeRegion(edge, () -> availableExtent(edge), canResize, completed));
area.setContent(content);
switch (side) {
case LEFT -> surface.setLeft(area);
case RIGHT -> surface.setRight(area);
case TOP -> surface.setTop(area);
case BOTTOM -> surface.setBottom(area);
}
}
double committedExtent(Side side) {
DockEdgeRegion area = edgeAreas.get(side);
return area == null ? -1 : area.committedExtent();
}
Side edgeOf(Node node) {
for (Node current = node; current != null; current = current.getParent()) {
if (current instanceof DockEdgeRegion edge) return edge.side();
}
return null;
}
private double availableExtent(Side side) {
boolean horizontal = side.isVertical();
double available = horizontal ? getWidth() : getHeight();
for (var entry : edgeAreas.entrySet()) {
if (entry.getKey() != side && entry.getKey().isVertical() == horizontal && entry.getValue().isManaged()) {
available -= horizontal ? entry.getValue().getWidth() : entry.getValue().getHeight();
}
}
Node center = surface.getCenter();
double remainingMinimum = center == null || !center.isManaged() ? 0
: horizontal ? center.minWidth(-1) : center.minHeight(-1);
if (!horizontal) {
for (Side edge : new Side[]{Side.LEFT, Side.RIGHT}) {
DockEdgeRegion area = edgeAreas.get(edge);
if (area != null && area.isManaged()) remainingMinimum = Math.max(remainingMinimum, area.minHeight(-1));
}
}
return available - remainingMinimum;
}
@Override protected void layoutChildren() { surface.resizeRelocate(0, 0, getWidth(), getHeight()); } @Override protected void layoutChildren() { surface.resizeRelocate(0, 0, getWidth(), getHeight()); }
@Override protected double computePrefWidth(double height) { return surface.prefWidth(height); } @Override protected double computePrefWidth(double height) { return surface.prefWidth(height); }
@Override protected double computePrefHeight(double width) { return surface.prefHeight(width); } @Override protected double computePrefHeight(double width) { return surface.prefHeight(width); }
@@ -0,0 +1,15 @@
package de.neitzel.fx.docking;
import javafx.geometry.Orientation;
import lombok.Getter;
import lombok.Setter;
/** Java/FXML definition of two adjacent groups or nested branches. */
@Getter @Setter
public final class DockSplitDefinition implements DockLayoutNode {
private String destinationId;
private Orientation orientation = Orientation.HORIZONTAL;
private double position = .5;
private DockLayoutNode first;
private DockLayoutNode second;
}
@@ -1,6 +1,7 @@
package de.neitzel.fx.docking; package de.neitzel.fx.docking;
import java.util.Objects; import java.util.Objects;
import javafx.geometry.Side;
/** A destination for a Dockable. */ /** A destination for a Dockable. */
public sealed interface DockTarget { public sealed interface DockTarget {
@@ -8,6 +9,10 @@ public sealed interface DockTarget {
static DockTarget area(DockAreaId id) { return new Area(id); } static DockTarget area(DockAreaId id) { return new Area(id); }
static DockTarget group(DockGroupId id, TabPosition position) { return new Group(id, position); } static DockTarget group(DockGroupId id, TabPosition position) { return new Group(id, position); }
static DockTarget group(DockGroupId id) { return group(id, TabPosition.append()); } static DockTarget group(DockGroupId id) { return group(id, TabPosition.append()); }
static DockTarget split(DockGroupId id, Side side) { return new Split(id, side); }
record Split(DockGroupId id, Side side) implements DockTarget {
public Split { Objects.requireNonNull(id, "id"); Objects.requireNonNull(side, "side"); }
}
record Area(DockAreaId id) implements DockTarget { record Area(DockAreaId id) implements DockTarget {
public Area { Objects.requireNonNull(id, "id"); } public Area { Objects.requireNonNull(id, "id"); }
} }
@@ -17,6 +17,8 @@ public final class Dockable {
@Getter private final Node content; @Getter private final Node content;
@Getter @Setter private Supplier<? extends Node> focusTarget; @Getter @Setter private Supplier<? extends Node> focusTarget;
@Getter @Setter private Runnable onDiscarded; @Getter @Setter private Runnable onDiscarded;
@Getter @Setter private CloseCheck closeCheck;
@Getter @Setter private Runnable onClosed;
private final StringProperty title = new SimpleStringProperty(this, "title", ""); private final StringProperty title = new SimpleStringProperty(this, "title", "");
private final ObjectProperty<Node> icon = new SimpleObjectProperty<>(this, "icon"); private final ObjectProperty<Node> icon = new SimpleObjectProperty<>(this, "icon");
@@ -7,6 +7,7 @@ import javafx.scene.Node;
import javafx.scene.control.Tab; import javafx.scene.control.Tab;
import javafx.scene.control.TabPane; import javafx.scene.control.TabPane;
import javafx.stage.Stage; import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@@ -15,16 +16,24 @@ import java.util.Objects;
import java.util.Optional; import java.util.Optional;
/** Owns the live tab groups of one embedded docking area. */ /** Owns the live tab groups of one embedded docking area. */
@Slf4j
public final class DockingManager { public final class DockingManager {
private static final Object ATTACHMENT_KEY = new Object(); private static final Object ATTACHMENT_KEY = new Object();
private final Stage stage; private final Stage stage;
private final DockPane pane; private final DockPane pane;
private final PlacementRule placementRule; private final PlacementRule placementRule;
private final DockDragController drag; private final DockDragController drag;
private final DockCloseCoordinator closing;
private boolean updating; private boolean updating;
private final Map<DockAreaId, Group> groups = new LinkedHashMap<>(); private final Map<DockGroupId, Group> groups = new LinkedHashMap<>();
private final Map<DockGroupId, Long> groupActivationOrder = new LinkedHashMap<>();
private final DockLayoutTree tree = new DockLayoutTree(this::publish, id -> !groupClosing(group(id)));
private final Map<DockAreaId, javafx.geometry.Side> edgeAreas = new LinkedHashMap<>();
private long nextGroupId;
private final Map<DockableId, Dockable> dockables = new LinkedHashMap<>(); private final Map<DockableId, Dockable> dockables = new LinkedHashMap<>();
private final Map<DockableId, Node> previousFocus = new LinkedHashMap<>(); private final Map<DockableId, Node> previousFocus = new LinkedHashMap<>();
private final Map<DockableId, Long> activationOrder = new LinkedHashMap<>();
private long nextActivation;
private final javafx.beans.value.ChangeListener<Node> focusListener = (observable, old, current) -> rememberFocus(current); private final javafx.beans.value.ChangeListener<Node> focusListener = (observable, old, current) -> rememberFocus(current);
private final ReadOnlyObjectWrapper<Dockable> active = new ReadOnlyObjectWrapper<>(this, "activeDockable"); private final ReadOnlyObjectWrapper<Dockable> active = new ReadOnlyObjectWrapper<>(this, "activeDockable");
private final ReadOnlyObjectWrapper<DockLayoutView> layout = new ReadOnlyObjectWrapper<>(this, "layout"); private final ReadOnlyObjectWrapper<DockLayoutView> layout = new ReadOnlyObjectWrapper<>(this, "layout");
@@ -32,16 +41,22 @@ public final class DockingManager {
private DockingManager(Stage stage, DockPane pane, DockingOptions options) { private DockingManager(Stage stage, DockPane pane, DockingOptions options) {
this.stage = stage; this.stage = stage;
this.pane = pane; this.pane = pane;
closing = new DockCloseCoordinator(new DockCloseCoordinator.Host() {
@Override public Optional<Dockable> find(DockableId id) { return findDockable(id); }
@Override public javafx.stage.Window owner(DockableId id) { return stage; }
@Override public void remove(DockableId id) { removeDockable(id); }
});
this.placementRule = Objects.requireNonNull(options.getPlacementRule(), "placementRule"); this.placementRule = Objects.requireNonNull(options.getPlacementRule(), "placementRule");
DockLayout initial = Objects.requireNonNull(pane.getInitialLayout(), "initialLayout"); DockLayout initial = Objects.requireNonNull(pane.getInitialLayout(), "initialLayout");
validate(initial); validate(initial);
addGroup(initial.getCenter(), pane.surface::setCenter); addGroup(initial.getCenter(), pane.surface::setCenter);
addGroup(initial.getLeft(), pane.surface::setLeft); addEdgeGroup(initial.getLeft(), javafx.geometry.Side.LEFT);
addGroup(initial.getRight(), pane.surface::setRight); addEdgeGroup(initial.getRight(), javafx.geometry.Side.RIGHT);
addGroup(initial.getTop(), pane.surface::setTop); addEdgeGroup(initial.getTop(), javafx.geometry.Side.TOP);
addGroup(initial.getBottom(), pane.surface::setBottom); addEdgeGroup(initial.getBottom(), javafx.geometry.Side.BOTTOM);
drag = new DockDragController(this, pane, () -> groups.values().stream() drag = new DockDragController(this, pane, () -> groups.values().stream()
.map(group -> new DockDragController.GroupSurface(group.id, group.tabs)).toList()); .map(group -> new DockDragController.GroupSurface(group.id, group.tabs, pane.edgeOf(group.tabs))).toList());
refreshEmptyGroups();
publish(); publish();
stage.getScene().focusOwnerProperty().addListener(focusListener); stage.getScene().focusOwnerProperty().addListener(focusListener);
} }
@@ -69,13 +84,18 @@ public final class DockingManager {
if (dockables.containsKey(dockable.getId())) return activate(dockable.getId()); if (dockables.containsKey(dockable.getId())) return activate(dockable.getId());
MoveCheck check = resolve(dockable, target); MoveCheck check = resolve(dockable, target);
if (check instanceof MoveCheck.Rejected rejected) return new ActionResult.Rejected(rejected.failure()); if (check instanceof MoveCheck.Rejected rejected) return new ActionResult.Rejected(rejected.failure());
var destination = (ResolvedDockTarget.Insertion) ((MoveCheck.Allowed) check).destination(); var destination = ((MoveCheck.Allowed) check).destination();
Group group = group(destination.groupId());
if (dockable.getContent().getParent() != null || dockable.getContent().getScene() != null) { if (dockable.getContent().getParent() != null || dockable.getContent().getScene() != null) {
return rejected(DockFailure.Code.CONTENT_ALREADY_ATTACHED, dockable.getId(), "Content already belongs to a scene graph"); return rejected(DockFailure.Code.CONTENT_ALREADY_ATTACHED, dockable.getId(), "Content already belongs to a scene graph");
} }
Group group = receiver(destination);
int insertionIndex = destination instanceof ResolvedDockTarget.Insertion insertion ? insertion.index() : 0;
Tab tab = new Tab(); Tab tab = new Tab();
tab.setClosable(false); tab.setClosable(true);
tab.setOnCloseRequest(event -> {
event.consume();
requestTabClose(dockable.getId());
});
tab.textProperty().bind(dockable.titleProperty()); tab.textProperty().bind(dockable.titleProperty());
tab.graphicProperty().bind(dockable.iconProperty()); tab.graphicProperty().bind(dockable.iconProperty());
tab.setContent(dockable.getContent()); tab.setContent(dockable.getContent());
@@ -84,12 +104,13 @@ public final class DockingManager {
dockables.put(dockable.getId(), dockable); dockables.put(dockable.getId(), dockable);
updating = true; updating = true;
try { try {
group.tabs.getTabs().add(destination.index(), tab); group.tabs.getTabs().add(insertionIndex, tab);
group.tabs.getSelectionModel().select(tab); group.tabs.getSelectionModel().select(tab);
refreshEmptyGroups();
} finally { } finally {
updating = false; updating = false;
} }
active.set(dockable); setActive(dockable);
focus(dockable); focus(dockable);
publish(); publish();
return new ActionResult.Applied(); return new ActionResult.Applied();
@@ -144,7 +165,7 @@ public final class DockingManager {
} }
} }
} }
active.set(dockable); setActive(dockable);
if (stage.isShowing()) stage.toFront(); if (stage.isShowing()) stage.toFront();
focus(dockable); focus(dockable);
if (changed) publish(); if (changed) publish();
@@ -153,11 +174,77 @@ public final class DockingManager {
public Optional<Dockable> findDockable(DockableId id) { return Optional.ofNullable(dockables.get(id)); } public Optional<Dockable> findDockable(DockableId id) { return Optional.ofNullable(dockables.get(id)); }
/** Requests consent without closing or releasing content while the answer is pending. */
public java.util.concurrent.CompletionStage<CloseResult> requestTabClose(DockableId id) {
return closing.requestTabClose(id);
}
/** Scope remains available until checks and resource release have finished. */
public ReadOnlyObjectProperty<CloseScope> closingScopeProperty() {
return closing.closingScopeProperty();
}
private void removeDockable(DockableId id) {
Group group = containing(id);
if (group == null) return;
Tab tab = group.tabs.getTabs().get(tabIndex(group, id));
boolean wasActive = active.get() == dockables.get(id);
updating = true;
try {
drag.uninstallTab(tab);
tab.textProperty().unbind();
tab.graphicProperty().unbind();
tab.setGraphic(null);
tab.setContent(null);
group.tabs.getTabs().remove(tab);
dockables.remove(id);
previousFocus.remove(id);
activationOrder.remove(id);
normalizeLayout(group.id);
} finally {
updating = false;
}
if (wasActive) {
Tab selected = group.tabs.getSelectionModel().getSelectedItem();
if (selected == null) {
selected = groups.values().stream().map(candidate -> candidate.tabs.getSelectionModel().getSelectedItem())
.filter(Objects::nonNull)
.max(java.util.Comparator.comparingLong(candidate ->
activationOrder.getOrDefault((DockableId) candidate.getUserData(), 0L)))
.orElse(null);
}
setActive(selected == null ? null : dockables.get((DockableId) selected.getUserData()));
focus(active.get());
}
publish();
}
private boolean groupClosing(Group group) {
CloseScope scope = closing.scope();
if (scope == null) return false;
for (DockableId id : scope.dockableIds()) {
if (!dockables.containsKey(id) || (group != null && tabIndex(group, id) >= 0)) return true;
}
return false;
}
/** Resolves a move without mutating content, layout or identity allocation. */ /** Resolves a move without mutating content, layout or identity allocation. */
public MoveCheck checkMove(DockableId id, DockTarget target) { public MoveCheck checkMove(DockableId id, DockTarget target) {
requireFxThread(); requireFxThread();
if (!dockables.containsKey(id)) return moveRejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open"); if (!dockables.containsKey(id)) return moveRejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open");
return resolve(dockables.get(id), target); if (groupClosing(containing(id))) return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "A close request covers this group");
MoveCheck check = resolve(dockables.get(id), target);
if (check instanceof MoveCheck.Allowed allowed) {
DockGroupId destination = switch (allowed.destination()) {
case ResolvedDockTarget.Insertion insertion -> insertion.groupId();
case ResolvedDockTarget.Split split -> split.groupId();
};
if (tree.normalizationAffects(containing(id).id, destination, this::groupClosing)) {
return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id,
"Removing this tab would resize a group covered by a close request");
}
}
return check;
} }
/** Moves the live content, selecting it only after the complete transfer. */ /** Moves the live content, selecting it only after the complete transfer. */
@@ -165,21 +252,23 @@ public final class DockingManager {
MoveCheck check = checkMove(id, target); MoveCheck check = checkMove(id, target);
if (check instanceof MoveCheck.Rejected rejected) return new ActionResult.Rejected(rejected.failure()); if (check instanceof MoveCheck.Rejected rejected) return new ActionResult.Rejected(rejected.failure());
if (check instanceof MoveCheck.NoChange) return new ActionResult.NoChange(); if (check instanceof MoveCheck.NoChange) return new ActionResult.NoChange();
var destination = (ResolvedDockTarget.Insertion) ((MoveCheck.Allowed) check).destination(); var destination = ((MoveCheck.Allowed) check).destination();
Group source = containing(id); Group source = containing(id);
Group receiver = group(destination.groupId()); Group receiver = receiver(destination);
int insertionIndex = destination instanceof ResolvedDockTarget.Insertion insertion ? insertion.index() : 0;
Tab tab = source.tabs.getTabs().get(tabIndex(source, id)); Tab tab = source.tabs.getTabs().get(tabIndex(source, id));
updating = true; updating = true;
try { try {
tab.setContent(null); tab.setContent(null);
source.tabs.getTabs().remove(tab); source.tabs.getTabs().remove(tab);
receiver.tabs.getTabs().add(destination.index(), tab); receiver.tabs.getTabs().add(insertionIndex, tab);
tab.setContent(dockables.get(id).getContent()); tab.setContent(dockables.get(id).getContent());
receiver.tabs.getSelectionModel().select(tab); receiver.tabs.getSelectionModel().select(tab);
normalizeLayout(source.id);
} finally { } finally {
updating = false; updating = false;
} }
active.set(dockables.get(id)); setActive(dockables.get(id));
focus(active.get()); focus(active.get());
publish(); publish();
return new ActionResult.Applied(); return new ActionResult.Applied();
@@ -188,17 +277,40 @@ public final class DockingManager {
private MoveCheck resolve(Dockable dockable, DockTarget target) { private MoveCheck resolve(Dockable dockable, DockTarget target) {
DockableId id = dockable.getId(); DockableId id = dockable.getId();
Objects.requireNonNull(target, "target"); Objects.requireNonNull(target, "target");
Group receiver; if (target instanceof DockTarget.Split split) {
TabPosition position; Group receiver = group(split.id());
if (target instanceof DockTarget.Area area) { if (receiver == null) return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "Destination does not exist");
receiver = groups.get(area.id()); if (groupClosing(receiver)) return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "A close request covers this group");
position = TabPosition.append(); if (containing(id) == receiver && receiver.tabs.getTabs().size() == 1) return new MoveCheck.NoChange();
} else { if (!receiver.definition.getSplitDirections().allows(split.side())) {
DockTarget.Group concrete = (DockTarget.Group) target; return moveRejected(DockFailure.Code.SPLIT_DISABLED, id, "Splitting is disabled in this direction");
receiver = group(concrete.id()); }
position = concrete.position(); double available = split.side().isVertical() ? receiver.tabs.getWidth() : receiver.tabs.getHeight();
if (available <= 0) available = split.side().isVertical()
? receiver.definition.getPreferredWidth() : receiver.definition.getPreferredHeight();
double minimum = split.side().isVertical()
? receiver.definition.getMinimumWidth() : receiver.definition.getMinimumHeight();
if (available - 8 < minimum * 2) {
return moveRejected(DockFailure.Code.SPLIT_TOO_SMALL, id, "Both group minima do not fit beside the divider");
}
return checkPlacement(dockable, new ResolvedDockTarget.Split(receiver.id, split.side()));
} }
if (target instanceof DockTarget.Area area) {
List<Group> candidates = tree.groups(area.id()).stream().sorted(java.util.Comparator
.comparingLong((Group candidate) -> groupActivationOrder.getOrDefault(candidate.id, 0L)).reversed()).toList();
MoveCheck rejected = moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "Destination does not exist");
for (Group candidate : candidates) {
MoveCheck result = resolve(dockable, DockTarget.group(candidate.id));
if (!(result instanceof MoveCheck.Rejected)) return result;
if (candidate == candidates.getFirst()) rejected = result;
}
return rejected;
}
DockTarget.Group concrete = (DockTarget.Group) target;
Group receiver = group(concrete.id());
TabPosition position = concrete.position();
if (receiver == null) return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "Destination does not exist"); if (receiver == null) return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "Destination does not exist");
if (groupClosing(receiver)) return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "A close request covers this group");
int index = receiver.tabs.getTabs().size(); int index = receiver.tabs.getTabs().size();
DockableId reference = switch (position) { DockableId reference = switch (position) {
case TabPosition.Before before -> before.id(); case TabPosition.Before before -> before.id();
@@ -217,6 +329,11 @@ public final class DockingManager {
if (index == oldIndex) return new MoveCheck.NoChange(); if (index == oldIndex) return new MoveCheck.NoChange();
} }
var resolved = new ResolvedDockTarget.Insertion(receiver.id, index); var resolved = new ResolvedDockTarget.Insertion(receiver.id, index);
return checkPlacement(dockable, resolved);
}
private MoveCheck checkPlacement(Dockable dockable, ResolvedDockTarget resolved) {
DockableId id = dockable.getId();
try { try {
Optional<DockFailure> failure = Objects.requireNonNull(placementRule.check(dockable, resolved), "Placement rule result"); Optional<DockFailure> failure = Objects.requireNonNull(placementRule.check(dockable, resolved), "Placement rule result");
if (failure.isPresent()) return new MoveCheck.Rejected(failure.get()); if (failure.isPresent()) return new MoveCheck.Rejected(failure.get());
@@ -227,8 +344,25 @@ public final class DockingManager {
return new MoveCheck.Allowed(resolved); return new MoveCheck.Allowed(resolved);
} }
private void normalizeLayout(DockGroupId source) {
for (DockGroupId id : tree.normalize(source)) {
groups.remove(id);
groupActivationOrder.remove(id);
}
refreshEmptyGroups();
}
private void refreshEmptyGroups() {
for (Group group : groups.values()) {
boolean occupied = !group.tabs.getTabs().isEmpty();
group.tabs.setVisible(occupied || (group.definition.isVisibleWhenEmpty()
&& !group.definition.isReleaseSpaceWhenEmpty()));
group.tabs.setManaged(occupied || !group.definition.isReleaseSpaceWhenEmpty());
}
}
private Group group(DockGroupId id) { private Group group(DockGroupId id) {
return groups.values().stream().filter(group -> group.id.equals(id)).findFirst().orElse(null); return groups.get(id);
} }
private Group containing(DockableId id) { private Group containing(DockableId id) {
@@ -250,23 +384,66 @@ public final class DockingManager {
public DockLayoutView layout() { return layout.get(); } public DockLayoutView layout() { return layout.get(); }
public ReadOnlyObjectProperty<DockLayoutView> layoutProperty() { return layout.getReadOnlyProperty(); } public ReadOnlyObjectProperty<DockLayoutView> layoutProperty() { return layout.getReadOnlyProperty(); }
private void addGroup(DockGroupDefinition definition, java.util.function.Consumer<javafx.scene.Node> place) { private void addEdgeGroup(DockLayoutNode definition, javafx.geometry.Side side) {
if (definition == null) return; if (definition == null) return;
DockAreaId area = new DockAreaId(definition.getDestinationId()); edgeAreas.put(new DockAreaId(definition.getDestinationId()), side);
if (groups.containsKey(area)) throw new IllegalArgumentException("Duplicate destination: " + area.value()); DockAreaId areaId = new DockAreaId(definition.getDestinationId());
addGroup(definition, node -> pane.setArea(side, node,
() -> tree.groups(areaId).stream().noneMatch(this::groupClosing), this::publish));
}
private void addGroup(DockLayoutNode definition, java.util.function.Consumer<javafx.scene.Node> place) {
if (definition == null) return;
tree.addArea(definition, place,
group -> createGroup(new DockGroupId(group.getDestinationId()), group));
}
private Group createGroup(DockGroupId id, DockGroupDefinition definition) {
DockGroupDefinition captured = new DockGroupDefinition(definition.getDestinationId());
captured.setTabSide(definition.getTabSide());
captured.setPreferredWidth(definition.getPreferredWidth());
captured.setPreferredHeight(definition.getPreferredHeight());
captured.setMinimumWidth(definition.getMinimumWidth());
captured.setMinimumHeight(definition.getMinimumHeight());
captured.setSplitDirections(definition.getSplitDirections());
captured.setPersistent(definition.isPersistent());
captured.setVisibleWhenEmpty(definition.isVisibleWhenEmpty());
captured.setReleaseSpaceWhenEmpty(definition.isReleaseSpaceWhenEmpty());
TabPane tabs = new TabPane(); TabPane tabs = new TabPane();
tabs.setSide(Objects.requireNonNull(definition.getTabSide(), "tabSide")); tabs.setSide(captured.getTabSide());
tabs.setPrefSize(definition.getPreferredWidth(), definition.getPreferredHeight()); tabs.setPrefSize(captured.getPreferredWidth(), captured.getPreferredHeight());
Group group = new Group(new DockGroupId(area.value()), tabs); tabs.setMinSize(captured.getMinimumWidth(), captured.getMinimumHeight());
groups.put(area, group); Group group = new Group(id, tabs, captured);
groups.put(id, group);
tabs.getSelectionModel().selectedItemProperty().addListener((observable, old, selected) -> { tabs.getSelectionModel().selectedItemProperty().addListener((observable, old, selected) -> {
if (!updating && selected != null) { if (!updating && selected != null) {
active.set(dockables.get((DockableId) selected.getUserData())); setActive(dockables.get((DockableId) selected.getUserData()));
focus(active.get()); focus(active.get());
publish(); publish();
} }
}); });
place.accept(tabs); return group;
}
private Group receiver(ResolvedDockTarget destination) {
if (destination instanceof ResolvedDockTarget.Insertion insertion) return group(insertion.groupId());
ResolvedDockTarget.Split split = (ResolvedDockTarget.Split) destination;
Group target = group(split.groupId());
DockGroupId id;
do { id = new DockGroupId("group-" + ++nextGroupId); } while (groups.containsKey(id));
Group added = createGroup(id, target.definition);
tree.split(target, added, split.side());
return added;
}
private void setActive(Dockable dockable) {
if (dockable != null) {
long order = ++nextActivation;
activationOrder.put(dockable.getId(), order);
Group group = containing(dockable.getId());
if (group != null) groupActivationOrder.put(group.id, order);
}
active.set(dockable);
} }
private void rememberFocus(Node current) { private void rememberFocus(Node current) {
@@ -274,14 +451,21 @@ public final class DockingManager {
for (Dockable dockable : dockables.values()) { for (Dockable dockable : dockables.values()) {
if (contains(dockable.getContent(), current)) { if (contains(dockable.getContent(), current)) {
previousFocus.put(dockable.getId(), current); previousFocus.put(dockable.getId(), current);
active.set(dockable); setActive(dockable);
return; return;
} }
} }
} }
private Node focusTarget(Dockable dockable) { private Node focusTarget(Dockable dockable) {
Node target = dockable.getFocusTarget() == null ? previousFocus.get(dockable.getId()) : dockable.getFocusTarget().get(); Node target = previousFocus.get(dockable.getId());
if (dockable.getFocusTarget() != null) {
try {
target = dockable.getFocusTarget().get();
} catch (RuntimeException failure) {
log.warn("Cannot resolve focus target for Dockable {}; using its content focus", dockable.getId(), failure);
}
}
if (target == null || !contains(dockable.getContent(), target)) return dockable.getContent(); if (target == null || !contains(dockable.getContent(), target)) return dockable.getContent();
return target; return target;
} }
@@ -302,26 +486,53 @@ public final class DockingManager {
private static void validate(DockLayout initial) { private static void validate(DockLayout initial) {
var destinations = new java.util.HashSet<DockAreaId>(); var destinations = new java.util.HashSet<DockAreaId>();
for (DockGroupDefinition definition : new DockGroupDefinition[]{initial.getCenter(), initial.getLeft(), for (DockLayoutNode definition : new DockLayoutNode[]{initial.getCenter(), initial.getLeft(),
initial.getRight(), initial.getTop(), initial.getBottom()}) { initial.getRight(), initial.getTop(), initial.getBottom()}) {
if (definition == null) continue; if (definition != null) validate(definition, destinations);
DockAreaId id = new DockAreaId(definition.getDestinationId()); }
if (!destinations.add(id)) throw new IllegalArgumentException("Duplicate destination: " + id.value()); }
if (definition.getTabSide() == null) throw new IllegalArgumentException("Tab side is required");
if (!Double.isFinite(definition.getPreferredWidth()) || definition.getPreferredWidth() <= 0 private static void validate(DockLayoutNode definition, java.util.Set<DockAreaId> destinations) {
|| !Double.isFinite(definition.getPreferredHeight()) || definition.getPreferredHeight() <= 0) { if (definition == null) throw new IllegalArgumentException("A split needs two branches");
DockAreaId id = new DockAreaId(definition.getDestinationId());
if (!destinations.add(id)) throw new IllegalArgumentException("Duplicate destination: " + id.value());
if (definition instanceof DockSplitDefinition split) {
if (split.getOrientation() == null || !Double.isFinite(split.getPosition())
|| split.getPosition() <= 0 || split.getPosition() >= 1) {
throw new IllegalArgumentException("A split needs an orientation and a position between zero and one");
}
validate(split.getFirst(), destinations);
validate(split.getSecond(), destinations);
} else {
DockGroupDefinition group = (DockGroupDefinition) definition;
if (group.getSplitDirections() == null || !Double.isFinite(group.getMinimumWidth())
|| group.getMinimumWidth() < 0 || !Double.isFinite(group.getMinimumHeight()) || group.getMinimumHeight() < 0) {
throw new IllegalArgumentException("Group minimum dimensions must be nonnegative and finite, with split directions");
}
if (group.getTabSide() == null) throw new IllegalArgumentException("Tab side is required");
if (!Double.isFinite(group.getPreferredWidth()) || group.getPreferredWidth() <= 0
|| !Double.isFinite(group.getPreferredHeight()) || group.getPreferredHeight() <= 0) {
throw new IllegalArgumentException("Group preferred dimensions must be positive and finite"); throw new IllegalArgumentException("Group preferred dimensions must be positive and finite");
} }
} }
} }
private void publish() { private void publish() {
List<DockLayoutView.Area> areas = groups.entrySet().stream().map(entry -> { boolean wasUpdating = updating;
Group group = entry.getValue(); updating = true;
List<DockableId> ids = group.tabs.getTabs().stream().map(tab -> (DockableId) tab.getUserData()).toList(); try {
Tab selected = group.tabs.getSelectionModel().getSelectedItem(); stage.getScene().getRoot().applyCss();
return new DockLayoutView.Area(entry.getKey(), List.of(new DockLayoutView.Group(group.id, stage.getScene().getRoot().layout();
group.tabs.getSide(), ids, selected == null ? null : (DockableId) selected.getUserData()))); tree.captureGeometry();
} 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(); }).toList();
layout.set(new DockLayoutView(List.of(new DockLayoutView.Window(new DockWindowId("main"), true, areas)))); layout.set(new DockLayoutView(List.of(new DockLayoutView.Window(new DockWindowId("main"), true, areas))));
} }
@@ -334,5 +545,5 @@ public final class DockingManager {
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("Docking operations require the JavaFX Application Thread"); if (!Platform.isFxApplicationThread()) throw new IllegalStateException("Docking operations require the JavaFX Application Thread");
} }
private record Group(DockGroupId id, TabPane tabs) { } record Group(DockGroupId id, TabPane tabs, DockGroupDefinition definition) { }
} }
@@ -2,5 +2,6 @@ package de.neitzel.fx.docking;
/** Concrete placement checked against the current layout, without allocating IDs. */ /** Concrete placement checked against the current layout, without allocating IDs. */
public sealed interface ResolvedDockTarget { public sealed interface ResolvedDockTarget {
record Split(DockGroupId groupId, javafx.geometry.Side side) implements ResolvedDockTarget { }
record Insertion(DockGroupId groupId, int index) implements ResolvedDockTarget { } record Insertion(DockGroupId groupId, int index) implements ResolvedDockTarget { }
} }
@@ -0,0 +1,13 @@
package de.neitzel.fx.docking;
import javafx.geometry.Side;
/** Directions in which a target group permits an adjacent split. */
public enum SplitDirections {
NONE, HORIZONTAL, VERTICAL, ALL;
public boolean allows(Side side) {
return this == ALL || (this == HORIZONTAL && side.isVertical())
|| (this == VERTICAL && side.isHorizontal());
}
}
@@ -84,11 +84,18 @@ class ActivateDockingWindowTest {
}; };
AnimationTimer clickAfterDisplay = new AnimationTimer() { AnimationTimer clickAfterDisplay = new AnimationTimer() {
private int pulses; private int pulses;
private long lastClick;
@Override @Override
public void handle(long now) { public void handle(long now) {
if (stage.isFocused()) {
focused.countDown();
stop();
return;
}
if (++pulses < 2) return; if (++pulses < 2) return;
stop(); if (now - lastClick < 250_000_000) return;
lastClick = now;
Bounds bounds = stage.getScene().getRoot().localToScreen( Bounds bounds = stage.getScene().getRoot().localToScreen(
stage.getScene().getRoot().getBoundsInLocal()); stage.getScene().getRoot().getBoundsInLocal());
Robot robot = new Robot(); Robot robot = new Robot();
@@ -109,8 +116,9 @@ class ActivateDockingWindowTest {
try { try {
// A native click activates the application even if the previous test or // A native click activates the application even if the previous test or
// another application owned desktop focus. RequestFocus alone cannot // another application owned desktop focus. RequestFocus alone cannot
// establish that precondition reliably on macOS. Two pulses allow the // establish that precondition reliably on macOS. FX pulses do not
// newly shown native window to display before the Robot sends input. // guarantee that the native compositor has displayed the window;
// retry only this focus precondition within the bounded wait.
assertTrue(focused.await(5, TimeUnit.SECONDS), "Desktop did not focus the requested window"); assertTrue(focused.await(5, TimeUnit.SECONDS), "Desktop did not focus the requested window");
} finally { } finally {
FxThread.onFx(() -> { FxThread.onFx(() -> {
@@ -0,0 +1,321 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.CloseConsent;
import de.neitzel.fx.docking.CloseRequest;
import de.neitzel.fx.docking.CloseResult;
import de.neitzel.fx.docking.CloseScope;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockLayout;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockFailure;
import de.neitzel.fx.docking.MoveCheck;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.event.Event;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Consent and resource lifecycle are tested through the public manager API. */
class CloseDockableTest {
@BeforeAll
static void startJavaFx() throws InterruptedException {
FxThread.start();
}
@Test
void duplicateRequestsAwaitOneConsentAndReleaseOnlyAfterActualClose() throws Exception {
CompletableFuture<CloseConsent> consent = new CompletableFuture<>();
AtomicReference<Fixture> fixture = new AtomicReference<>();
AtomicReference<CompletionStage<CloseResult>> first = new AtomicReference<>();
AtomicReference<CompletionStage<CloseResult>> duplicate = new AtomicReference<>();
AtomicReference<CloseRequest> request = new AtomicReference<>();
AtomicInteger checks = new AtomicInteger();
AtomicInteger released = new AtomicInteger();
FxThread.onFx(() -> {
Fixture window = window();
fixture.set(window);
window.editor().setCloseCheck(context -> {
checks.incrementAndGet();
request.set(context);
assertTrue(Platform.isFxApplicationThread());
return consent;
});
window.editor().setOnClosed(() -> {
assertTrue(Platform.isFxApplicationThread());
released.incrementAndGet();
});
first.set(window.manager().requestTabClose(window.editor().getId()));
duplicate.set(window.manager().requestTabClose(window.editor().getId()));
assertEquals(1, checks.get());
assertEquals(0, released.get());
assertFalse(first.get().toCompletableFuture().isDone());
assertTrue(window.manager().findDockable(window.editor().getId()).isPresent());
assertEquals(CloseScope.Kind.TAB, request.get().scope().kind());
assertEquals(List.of(window.editor().getId()), request.get().scope().dockableIds());
assertSame(window.stage(), request.get().owner());
assertEquals(request.get().scope(), window.manager().closingScopeProperty().get());
});
consent.complete(CloseConsent.ALLOW);
assertInstanceOf(CloseResult.Closed.class, first.get().toCompletableFuture().get(5, TimeUnit.SECONDS));
assertEquals(first.get().toCompletableFuture().get(), duplicate.get().toCompletableFuture().get());
FxThread.onFx(() -> {
assertEquals(1, released.get());
assertTrue(fixture.get().manager().findDockable(fixture.get().editor().getId()).isEmpty());
assertNull(fixture.get().manager().closingScopeProperty().get());
});
}
@Test
void anotherTabWaitsForTheCurrentConsentEvenWhenItVetoes() throws Exception {
CompletableFuture<CloseConsent> notesConsent = new CompletableFuture<>();
CompletableFuture<CloseConsent> projectConsent = new CompletableFuture<>();
CompletableFuture<Void> projectStarted = new CompletableFuture<>();
AtomicReference<Fixture> fixture = new AtomicReference<>();
AtomicReference<CompletionStage<CloseResult>> notesResult = new AtomicReference<>();
AtomicReference<CompletionStage<CloseResult>> projectResult = new AtomicReference<>();
AtomicReference<CompletionStage<CloseResult>> projectDuplicate = new AtomicReference<>();
AtomicInteger projectChecks = new AtomicInteger();
DockableId projectId = new DockableId("project");
FxThread.onFx(() -> {
Fixture window = window();
fixture.set(window);
window.editor().setCloseCheck(request -> notesConsent);
Dockable project = new Dockable(projectId, new TextArea("Project"));
project.setCloseCheck(request -> {
projectChecks.incrementAndGet();
projectStarted.complete(null);
return projectConsent;
});
window.manager().open(project, DockTarget.area("tools"));
notesResult.set(window.manager().requestTabClose(window.editor().getId()));
projectResult.set(window.manager().requestTabClose(projectId));
projectDuplicate.set(window.manager().requestTabClose(projectId));
assertEquals(0, projectChecks.get());
assertFalse(projectResult.get().toCompletableFuture().isDone());
});
notesConsent.complete(CloseConsent.VETO);
assertInstanceOf(CloseResult.Vetoed.class, notesResult.get().toCompletableFuture().get(5, TimeUnit.SECONDS));
projectStarted.get(5, TimeUnit.SECONDS);
FxThread.onFx(() -> {
assertEquals(1, projectChecks.get());
assertEquals(List.of(projectId), fixture.get().manager().closingScopeProperty().get().dockableIds());
assertTrue(fixture.get().manager().findDockable(fixture.get().editor().getId()).isPresent());
});
projectConsent.complete(CloseConsent.ALLOW);
assertInstanceOf(CloseResult.Closed.class, projectResult.get().toCompletableFuture().get(5, TimeUnit.SECONDS));
assertEquals(projectResult.get().toCompletableFuture().get(), projectDuplicate.get().toCompletableFuture().get());
}
@Test
void closingActiveContentFallsBackToTheMostRecentlyActiveVisibleDockable() throws Exception {
FxThread.onFx(() -> {
Fixture window = window();
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
Dockable console = new Dockable(new DockableId("console"), new TextArea("Console"));
window.manager().open(project, DockTarget.area("tools"));
window.manager().open(console, DockTarget.area("console"));
window.manager().activate(project.getId());
window.manager().activate(window.editor().getId());
assertInstanceOf(CloseResult.Closed.class,
window.manager().requestTabClose(window.editor().getId()).toCompletableFuture().getNow(null));
assertSame(project, window.manager().activeDockable());
});
}
@Test
void tabCloseControlAndContextMenuBothWaitForConsent() throws Exception {
FxThread.onFx(() -> {
Fixture window = window();
AtomicInteger checks = new AtomicInteger();
AtomicReference<CompletableFuture<CloseConsent>> answer = new AtomicReference<>();
window.editor().setCloseCheck(request -> {
checks.incrementAndGet();
CompletableFuture<CloseConsent> pending = new CompletableFuture<>();
answer.set(pending);
return pending;
});
window.pane().applyCss();
Tab tab = window.pane().lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.flatMap(tabs -> tabs.getTabs().stream())
.filter(item -> item.getContent() == window.editor().getContent()).findFirst().orElseThrow();
assertTrue(tab.isClosable());
Event.fireEvent(tab, new Event(Tab.TAB_CLOSE_REQUEST_EVENT));
assertEquals(1, checks.get());
assertTrue(window.manager().findDockable(window.editor().getId()).isPresent());
answer.get().complete(CloseConsent.VETO);
assertTrue(window.manager().findDockable(window.editor().getId()).isPresent());
MenuItem close = tab.getContextMenu().getItems().stream()
.filter(item -> "Close".equals(item.getText())).findFirst().orElse(null);
assertNotNull(close);
close.fire();
assertEquals(2, checks.get());
assertTrue(window.manager().findDockable(window.editor().getId()).isPresent());
answer.get().complete(CloseConsent.ALLOW);
assertTrue(window.manager().findDockable(window.editor().getId()).isEmpty());
});
}
@Test
void failedChecksVetoWithoutReleasingAndALaterRequestCanClose() throws Exception {
FxThread.onFx(() -> {
Fixture window = window();
AtomicInteger released = new AtomicInteger();
AtomicInteger discarded = new AtomicInteger();
window.editor().setOnClosed(released::incrementAndGet);
window.editor().setOnDiscarded(discarded::incrementAndGet);
IllegalStateException failure = new IllegalStateException("Save failed");
window.editor().setCloseCheck(request -> CompletableFuture.failedFuture(failure));
var result = window.manager().requestTabClose(window.editor().getId()).toCompletableFuture().getNow(null);
CloseResult.Vetoed veto = assertInstanceOf(CloseResult.Vetoed.class, result);
assertEquals(List.of(window.editor().getId()), veto.vetoingIds());
assertSame(failure, veto.checkFailures().getFirst().cause());
assertEquals(DockFailure.Code.CLOSE_CHECK_FAILED, veto.checkFailures().getFirst().code());
assertTrue(window.manager().findDockable(window.editor().getId()).isPresent());
assertNull(window.manager().closingScopeProperty().get());
assertEquals(0, released.get());
assertEquals(0, discarded.get());
window.editor().setCloseCheck(request -> { throw failure; });
assertInstanceOf(CloseResult.Vetoed.class,
window.manager().requestTabClose(window.editor().getId()).toCompletableFuture().getNow(null));
window.editor().setCloseCheck(request -> CompletableFuture.completedFuture(CloseConsent.ALLOW));
assertInstanceOf(CloseResult.Closed.class,
window.manager().requestTabClose(window.editor().getId()).toCompletableFuture().getNow(null));
assertEquals(1, released.get());
assertEquals(0, discarded.get());
});
}
@Test
void cleanupFailureReportsAnActualCloseAndKeepsScopeThroughRelease() throws Exception {
FxThread.onFx(() -> {
Fixture window = window();
IllegalStateException cleanup = new IllegalStateException("Release failed");
window.editor().setOnClosed(() -> {
assertTrue(window.manager().findDockable(window.editor().getId()).isEmpty());
assertEquals(List.of(window.editor().getId()), window.manager().closingScopeProperty().get().dockableIds());
Dockable duringRelease = new Dockable(new DockableId("during-release"), new TextArea());
ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class,
window.manager().open(duringRelease, DockTarget.area("tools")));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, rejected.failure().code());
throw cleanup;
});
CloseResult.Closed result = assertInstanceOf(CloseResult.Closed.class,
window.manager().requestTabClose(window.editor().getId()).toCompletableFuture().getNow(null));
assertEquals(DockFailure.Code.CLEANUP_FAILED, result.cleanupFailures().getFirst().code());
assertSame(cleanup, result.cleanupFailures().getFirst().cause());
assertNull(window.manager().activeDockable());
assertNull(window.manager().closingScopeProperty().get());
assertInstanceOf(CloseResult.NoChange.class,
window.manager().requestTabClose(window.editor().getId()).toCompletableFuture().getNow(null));
});
}
@Test
void pendingConsentProtectsItsGroupWhileUnrelatedGroupsRemainUsable() throws Exception {
FxThread.onFx(() -> {
Fixture window = window();
CompletableFuture<CloseConsent> consent = new CompletableFuture<>();
window.editor().setCloseCheck(request -> consent);
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
window.manager().open(project, DockTarget.area("tools"));
window.manager().requestTabClose(window.editor().getId());
ActionResult.Rejected move = assertInstanceOf(ActionResult.Rejected.class,
window.manager().move(window.editor().getId(), DockTarget.area("tools")));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, move.failure().code());
MoveCheck.Rejected inbound = assertInstanceOf(MoveCheck.Rejected.class,
window.manager().checkMove(project.getId(), DockTarget.area("editors")));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, inbound.failure().code());
Dockable prepared = new Dockable(new DockableId("new-editor"), new TextArea());
assertInstanceOf(ActionResult.Rejected.class, window.manager().open(prepared, DockTarget.area("editors")));
assertInstanceOf(ActionResult.Applied.class, window.manager().move(project.getId(), DockTarget.area("console")));
consent.complete(CloseConsent.VETO);
assertInstanceOf(ActionResult.Applied.class, window.manager().move(window.editor().getId(), DockTarget.area("tools")));
});
}
@Test
void closingActiveTabPrefersItsGroupsNewSelection() throws Exception {
FxThread.onFx(() -> {
Fixture window = window();
Dockable second = new Dockable(new DockableId("second"), new TextArea("Second"));
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
window.manager().open(second, DockTarget.area("editors"));
window.manager().open(project, DockTarget.area("tools"));
window.manager().activate(window.editor().getId());
assertInstanceOf(CloseResult.Closed.class,
window.manager().requestTabClose(window.editor().getId()).toCompletableFuture().getNow(null));
assertSame(second, window.manager().activeDockable());
});
}
@Test
void aFailingReplacementFocusTargetCannotStrandAnActualClose() throws Exception {
AtomicReference<Fixture> fixture = new AtomicReference<>();
AtomicReference<CompletionStage<CloseResult>> result = new AtomicReference<>();
AtomicReference<Dockable> replacement = new AtomicReference<>();
AtomicInteger released = new AtomicInteger();
FxThread.onFx(() -> {
Fixture window = window();
fixture.set(window);
Dockable second = new Dockable(new DockableId("second"), new TextArea("Second"));
replacement.set(second);
window.manager().open(second, DockTarget.area("editors"));
window.manager().activate(window.editor().getId());
second.setFocusTarget(() -> { throw new IllegalStateException("Focus target unavailable"); });
window.editor().setOnClosed(released::incrementAndGet);
result.set(window.manager().requestTabClose(window.editor().getId()));
});
assertInstanceOf(CloseResult.Closed.class, result.get().toCompletableFuture().get(5, TimeUnit.SECONDS));
FxThread.onFx(() -> {
assertEquals(1, released.get());
assertSame(replacement.get(), fixture.get().manager().activeDockable());
assertTrue(fixture.get().manager().findDockable(fixture.get().editor().getId()).isEmpty());
assertNull(fixture.get().manager().closingScopeProperty().get());
});
}
private static Fixture window() {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
initial.setLeft(new DockGroupDefinition("console"));
initial.setRight(new DockGroupDefinition("tools"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
Dockable editor = new Dockable(new DockableId("notes"), new TextArea("Unsaved notes"));
editor.setTitle("Notes");
manager.open(editor, DockTarget.area("editors"));
return new Fixture(stage, pane, manager, editor);
}
private record Fixture(Stage stage, DockPane pane, DockingManager manager, Dockable editor) { }
}
@@ -0,0 +1,170 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockLayout;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.application.Platform;
import javafx.geometry.Side;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.PickResult;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The public surface follows a boundary drag before publishing its finished layout. */
class OuterDockResizeTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@ParameterizedTest
@EnumSource(Side.class)
void sideBoundaryResizesLiveAndPublishesOnceOnRelease(Side side) throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
DockGroupDefinition editors = new DockGroupDefinition("editors");
editors.setMinimumWidth(180);
editors.setMinimumHeight(120);
initial.setCenter(editors);
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setMinimumWidth(140);
tools.setMinimumHeight(100);
switch (side) {
case LEFT -> initial.setLeft(tools);
case RIGHT -> initial.setRight(tools);
case TOP -> initial.setTop(tools);
case BOTTOM -> initial.setBottom(tools);
}
if (side.isHorizontal()) {
DockGroupDefinition navigation = new DockGroupDefinition("navigation");
navigation.setMinimumHeight(260);
initial.setLeft(navigation);
}
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 650));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
TextArea project = new TextArea("Project");
TextArea notes = new TextArea("Notes");
Dockable dockable = new Dockable(new DockableId("project"), project);
manager.open(new Dockable(new DockableId("notes"), notes), DockTarget.area("editors"));
manager.open(dockable, DockTarget.area("tools"));
stage.show();
try {
pane.applyCss();
pane.layout();
Node divider = tabPane(pane, project).getParent().lookup(".dock-area-divider");
assertNotNull(divider, "A predefined side area needs a draggable boundary");
assertEquals(side.isVertical() ? Cursor.H_RESIZE : Cursor.V_RESIZE, divider.getCursor());
var origin = divider.localToScreen(divider.getBoundsInLocal());
double oldSize = side.isVertical() ? project.getWidth() : project.getHeight();
var before = manager.layout();
AtomicInteger publications = new AtomicInteger();
manager.layoutProperty().addListener((observable, old, value) -> publications.incrementAndGet());
double dx = side == Side.LEFT ? 40 : side == Side.RIGHT ? -40 : 0;
double dy = side == Side.TOP ? 40 : side == Side.BOTTOM ? -40 : 0;
mouse(divider, MouseEvent.MOUSE_PRESSED, origin.getCenterX(), origin.getCenterY(), true);
mouse(divider, MouseEvent.MOUSE_DRAGGED, origin.getCenterX() + dx, origin.getCenterY() + dy, true);
pane.layout();
assertTrue((side.isVertical() ? project.getWidth() : project.getHeight()) > oldSize + 30);
assertSame(before, manager.layout());
assertEquals(0, publications.get());
mouse(divider, MouseEvent.MOUSE_RELEASED, origin.getCenterX() + dx, origin.getCenterY() + dy, false);
assertNotSame(before, manager.layout());
assertEquals(1, publications.get());
var beforeArea = before.windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow();
var afterArea = manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow();
assertEquals(40, side.isVertical()
? afterArea.preferredWidth() - beforeArea.preferredWidth()
: afterArea.preferredHeight() - beforeArea.preferredHeight(), .1);
assertSame(project, manager.findDockable(dockable.getId()).orElseThrow().getContent());
var consent = new java.util.concurrent.CompletableFuture<de.neitzel.fx.docking.CloseConsent>();
dockable.setCloseCheck(request -> consent);
var closing = manager.requestTabClose(dockable.getId());
var protectedLayout = manager.layout();
var protectedBoundary = divider.localToScreen(divider.getBoundsInLocal());
double protectedSize = side.isVertical() ? project.getWidth() : project.getHeight();
mouse(divider, MouseEvent.MOUSE_PRESSED, protectedBoundary.getCenterX(), protectedBoundary.getCenterY(), true);
mouse(divider, MouseEvent.MOUSE_DRAGGED, protectedBoundary.getCenterX() + dx,
protectedBoundary.getCenterY() + dy, true);
pane.layout();
mouse(divider, MouseEvent.MOUSE_RELEASED, protectedBoundary.getCenterX() + dx,
protectedBoundary.getCenterY() + dy, false);
assertEquals(protectedSize, side.isVertical() ? project.getWidth() : project.getHeight(), .1);
assertSame(protectedLayout, manager.layout());
consent.complete(de.neitzel.fx.docking.CloseConsent.VETO);
assertTrue(closing.toCompletableFuture().isDone());
for (int direction : new int[]{1, -1}) {
var boundary = divider.localToScreen(divider.getBoundsInLocal());
mouse(divider, MouseEvent.MOUSE_PRESSED, boundary.getCenterX(), boundary.getCenterY(), true);
mouse(divider, MouseEvent.MOUSE_DRAGGED, boundary.getCenterX() + dx * direction * 100,
boundary.getCenterY() + dy * direction * 100, true);
pane.layout();
var toolsPane = tabPane(pane, project);
var editorPane = tabPane(pane, notes);
assertTrue((side.isVertical() ? toolsPane.getWidth() : toolsPane.getHeight())
>= (side.isVertical() ? tools.getMinimumWidth() : tools.getMinimumHeight()) - .1);
assertTrue((side.isVertical() ? editorPane.getWidth() : editorPane.getHeight())
>= (side.isVertical() ? editors.getMinimumWidth() : 260) - .1,
"Resizing must retain the minimum of the entire middle row");
var available = pane.localToScene(pane.getLayoutBounds());
var editorBounds = editorPane.localToScene(editorPane.getLayoutBounds());
var toolsBounds = toolsPane.localToScene(toolsPane.getLayoutBounds());
assertTrue(editorBounds.getMaxX() <= available.getMaxX() + 1
&& editorBounds.getMaxY() <= available.getMaxY() + 1
&& toolsBounds.getMaxX() <= available.getMaxX() + 1
&& toolsBounds.getMaxY() <= available.getMaxY() + 1,
"The remaining area must stay inside the docking pane");
mouse(divider, MouseEvent.MOUSE_RELEASED, boundary.getCenterX() + dx * direction * 100,
boundary.getCenterY() + dy * direction * 100, false);
var finished = manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow();
assertEquals(side.isVertical() ? toolsPane.getWidth() : toolsPane.getHeight(),
side.isVertical() ? finished.preferredWidth() : finished.preferredHeight(), 1,
"Published geometry must match the clamped visible size");
}
} finally {
stage.hide();
}
});
}
private static javafx.scene.control.TabPane tabPane(DockPane pane, Node content) {
return pane.lookupAll(".tab-pane").stream().map(javafx.scene.control.TabPane.class::cast)
.filter(tabs -> tabs.getTabs().stream().anyMatch(tab -> tab.getContent() == content))
.findFirst().orElseThrow();
}
private static void mouse(Node source, javafx.event.EventType<MouseEvent> type,
double screenX, double screenY, boolean down) {
var local = source.screenToLocal(screenX, screenY);
source.fireEvent(new MouseEvent(type, local.getX(), local.getY(), screenX, screenY,
MouseButton.PRIMARY, 1, false, false, false, false,
down, false, false, false, false, false,
new PickResult(source, local.getX(), local.getY())));
}
}
@@ -0,0 +1,314 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockLayout;
import de.neitzel.fx.docking.DockLayoutView;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import de.neitzel.fx.docking.DockFailure;
import de.neitzel.fx.docking.ResolvedDockTarget;
import de.neitzel.fx.docking.SplitDirections;
import javafx.application.Platform;
import javafx.geometry.Bounds;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TabPane;
import javafx.scene.control.Menu;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.PickResult;
import javafx.stage.Stage;
import javafx.fxml.FXMLLoader;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertFalse;
/** Split gestures are observed through visible controls and the public layout. */
class SplitDockGroupsByGestureTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@ParameterizedTest
@EnumSource(Side.class)
void anEdgeDropCreatesThePreviewedAdjacentGroup(Side edge) throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 500));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
TextArea notes = new TextArea("Unsaved notes");
Dockable editor = new Dockable(new DockableId("notes"), notes);
editor.setTitle("Notes");
TextArea project = new TextArea("Project");
Dockable tools = new Dockable(new DockableId("project"), project);
tools.setTitle("Project");
manager.open(editor, DockTarget.area("editors"));
manager.open(tools, DockTarget.area("editors"));
stage.show();
try {
pane.applyCss();
pane.layout();
Node header = header(pane, "Notes");
Bounds from = header.localToScreen(header.getBoundsInLocal());
Bounds into = project.localToScreen(project.getBoundsInLocal());
double x = edge == Side.LEFT ? into.getMinX() + 8
: edge == Side.RIGHT ? into.getMaxX() - 8 : into.getCenterX();
double y = edge == Side.TOP ? into.getMinY() + 8
: edge == Side.BOTTOM ? into.getMaxY() - 8 : into.getCenterY();
mouse(header, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true);
mouse(header, MouseEvent.MOUSE_DRAGGED, x, y, true);
assertTrue(pane.lookup(".dock-drop-indicator").isVisible());
assertEquals(1, manager.layout().windows().getFirst().areas().getFirst().groups().size());
mouse(header, MouseEvent.MOUSE_RELEASED, x, y, false);
DockLayoutView.Area area = manager.layout().windows().getFirst().areas().getFirst();
assertInstanceOf(DockLayoutView.Split.class, area.root());
assertEquals(2, area.groups().size());
boolean before = edge == Side.TOP || edge == Side.LEFT;
assertEquals(List.of(editor.getId()), area.groups().get(before ? 0 : 1).dockableIds());
assertSame(notes, manager.findDockable(editor.getId()).orElseThrow().getContent());
assertEquals("Unsaved notes", notes.getText());
} finally {
stage.hide();
}
});
}
@Test
void splitMenuExplainsRejectedDirectionsAndUsesTheSameMoveOperation() throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 500));
AtomicBoolean allowed = new AtomicBoolean(false);
DockingOptions options = new DockingOptions();
options.setPlacementRule((dockable, target) -> target instanceof ResolvedDockTarget.Split && !allowed.get()
? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), "No splits today", null))
: Optional.empty());
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("editors"));
manager.open(new Dockable(new DockableId("project"), new TextArea("Project")), DockTarget.area("editors"));
stage.show();
ContextMenu context = null;
try {
pane.applyCss();
pane.layout();
context = ((TabPane) pane.lookup(".tab-pane")).getTabs().getFirst().getContextMenu();
context.show(stage, stage.getX() + 80, stage.getY() + 80);
Menu splits = context.getItems().stream().filter(item -> "Split".equals(item.getText()))
.map(Menu.class::cast).findFirst().orElse(null);
assertNotNull(splits);
MenuItem right = splits.getItems().stream().filter(item -> item.getText().startsWith("Right"))
.findFirst().orElseThrow();
assertTrue(right.isDisable());
assertTrue(right.getText().contains("No splits today"));
context.hide();
allowed.set(true);
context.show(stage, stage.getX() + 80, stage.getY() + 80);
right = splits.getItems().stream().filter(item -> item.getText().startsWith("Right"))
.findFirst().orElseThrow();
assertFalse(right.isDisable());
right.fire();
assertInstanceOf(DockLayoutView.Split.class, manager.layout().windows().getFirst().areas().getFirst().root());
} finally {
if (context != null) context.hide();
stage.hide();
}
});
}
@ParameterizedTest
@ValueSource(strings = {"directions", "minimum", "placement"})
void aRejectedEdgeSplitFallsBackToJoiningTheTargetGroup(String restriction) throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
DockGroupDefinition editors = new DockGroupDefinition("editors");
if (restriction.equals("directions")) editors.setSplitDirections(SplitDirections.VERTICAL);
if (restriction.equals("minimum")) editors.setMinimumWidth(400);
initial.setCenter(editors);
initial.setLeft(new DockGroupDefinition("tools"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 500));
DockingOptions options = new DockingOptions();
if (restriction.equals("placement")) options.setPlacementRule((dockable, target) ->
target instanceof ResolvedDockTarget.Split ? Optional.of(new DockFailure(
DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), "No split", null)) : Optional.empty());
DockingManager manager = DockingManager.attach(stage, pane, options);
TextArea content = new TextArea("Editor");
Dockable editor = new Dockable(new DockableId("editor"), content);
manager.open(editor, DockTarget.area("editors"));
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("tools"));
stage.show();
try {
pane.applyCss();
pane.layout();
Node header = header(pane, "Notes");
Bounds from = header.localToScreen(header.getBoundsInLocal());
Bounds target = content.localToScreen(content.getBoundsInLocal());
double x = target.getMaxX() - 8;
double y = target.getCenterY();
mouse(header, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true);
mouse(header, MouseEvent.MOUSE_DRAGGED, x, y, true);
assertTrue(pane.lookup(".dock-drop-indicator").isVisible());
mouse(header, MouseEvent.MOUSE_RELEASED, x, y, false);
DockLayoutView.Area area = manager.layout().windows().getFirst().areas().stream()
.filter(candidate -> candidate.id().value().equals("editors")).findFirst().orElseThrow();
assertInstanceOf(DockLayoutView.Group.class, area.root());
assertEquals(List.of(editor.getId(), notes.getId()), area.groups().getFirst().dockableIds());
} finally { stage.hide(); }
});
}
@Test
void aSoleTabDroppedAtItsOwnEdgeIsAnExplicitNoChange() throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 500));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
TextArea content = new TextArea("Unsaved notes");
Dockable notes = new Dockable(new DockableId("notes"), content);
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("editors"));
stage.show();
try {
pane.applyCss();
pane.layout();
DockLayoutView before = manager.layout();
Node header = header(pane, "Notes");
Bounds from = header.localToScreen(header.getBoundsInLocal());
Bounds target = content.localToScreen(content.getBoundsInLocal());
mouse(header, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true);
mouse(header, MouseEvent.MOUSE_DRAGGED, target.getMaxX() - 8, target.getCenterY(), true);
Node marker = pane.lookup(".dock-drop-indicator");
assertTrue(marker.isVisible());
assertTrue(marker.getPseudoClassStates().contains(javafx.css.PseudoClass.getPseudoClass("no-change")));
mouse(header, MouseEvent.MOUSE_RELEASED, target.getMaxX() - 8, target.getCenterY(), false);
assertEquals(before, manager.layout());
assertSame(content, manager.findDockable(notes.getId()).orElseThrow().getContent());
} finally { stage.hide(); }
});
}
@ParameterizedTest
@CsvSource({"LEFT,true", "RIGHT,true", "TOP,true", "BOTTOM,true",
"LEFT,false", "RIGHT,false", "TOP,false", "BOTTOM,false"})
void aPersistentGroupRemainsAnInvisibleDropTargetAndRestoresItsExtent(Side edge, boolean releaseSpace) throws Exception {
FxThread.onFx(() -> {
String property = edge.name().toLowerCase(java.util.Locale.ROOT);
String fxml = """
<?import de.neitzel.fx.docking.*?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout><DockLayout>
<center><DockGroupDefinition destinationId="editors"/></center>
<%s><DockGroupDefinition destinationId="tools" persistent="true"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="%s"/></%s>
</DockLayout></initialLayout>
</DockPane>
""".formatted(property, releaseSpace, property);
DockPane pane = new FXMLLoader().load(new ByteArrayInputStream(fxml.getBytes(StandardCharsets.UTF_8)));
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 500));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
manager.open(new Dockable(new DockableId("project"), new TextArea("Project")), DockTarget.area("editors"));
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
notes.setTitle("Notes");
manager.open(notes, DockTarget.area("tools"));
stage.show();
try {
pane.applyCss();
pane.layout();
TabPane empty = pane.lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.filter(tabs -> tabs.getTabs().stream().anyMatch(tab -> tab.getContent() == notes.getContent()))
.findFirst().orElseThrow();
double occupiedExtent = edge.isVertical() ? empty.getWidth() : empty.getHeight();
manager.move(notes.getId(), DockTarget.area("editors"));
pane.applyCss();
pane.layout();
assertFalse(empty.isVisible());
assertEquals(!releaseSpace, empty.isManaged());
Node header = header(pane, "Notes");
Bounds from = header.localToScreen(header.getBoundsInLocal());
Bounds target = releaseSpace ? pane.localToScreen(pane.getBoundsInLocal())
: empty.localToScreen(empty.getBoundsInLocal());
double x = !releaseSpace ? target.getCenterX() : edge == Side.LEFT ? target.getMinX() + 8
: edge == Side.RIGHT ? target.getMaxX() - 8 : target.getCenterX();
double y = !releaseSpace ? target.getCenterY() : edge == Side.TOP ? target.getMinY() + 8
: edge == Side.BOTTOM ? target.getMaxY() - 8 : target.getCenterY();
mouse(header, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true);
mouse(header, MouseEvent.MOUSE_DRAGGED, x, y, true);
assertTrue(pane.lookup(".dock-drop-indicator").isVisible());
assertFalse(empty.isVisible());
assertEquals(!releaseSpace, empty.isManaged());
mouse(header, MouseEvent.MOUSE_RELEASED, x, y, false);
DockLayoutView.Area tools = manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow();
assertEquals(List.of(notes.getId()), tools.groups().getFirst().dockableIds());
assertTrue(empty.isVisible());
assertTrue(empty.isManaged());
pane.applyCss();
pane.layout();
assertEquals(occupiedExtent, edge.isVertical() ? empty.getWidth() : empty.getHeight(), 1.0);
} finally { stage.hide(); }
});
}
private static Node header(DockPane pane, String title) {
return pane.lookupAll(".tab").stream().filter(node -> {
Node label = node.lookup(".tab-label");
return label instanceof Label text && title.equals(text.getText());
}).findFirst().orElseThrow();
}
private static void mouse(Node source, javafx.event.EventType<MouseEvent> type,
double screenX, double screenY, boolean down) {
var local = source.screenToLocal(screenX, screenY);
source.fireEvent(new MouseEvent(type, local.getX(), local.getY(), screenX, screenY,
MouseButton.PRIMARY, 1, false, false, false, false,
down, false, false, false, false, false,
new PickResult(source, local.getX(), local.getY())));
}
}
@@ -0,0 +1,392 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/** A split displays two groups while preserving the same live Dockables. */
class SplitDockGroupsTest {
@BeforeAll
static void startJavaFx() throws InterruptedException { FxThread.start(); }
@Test
void splittingAnEditorCreatesAnAdjacentGroupWithTheSameContent() throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
TextArea notes = new TextArea("Unsaved notes");
Dockable moved = new Dockable(new DockableId("notes"), notes);
Dockable remaining = new Dockable(new DockableId("readme"), new TextArea("Readme"));
manager.open(moved, DockTarget.area("editors"));
manager.open(remaining, DockTarget.area("editors"));
pane.resize(800, 500);
pane.applyCss();
pane.layout();
DockGroupId original = manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().id();
assertInstanceOf(ActionResult.Applied.class, manager.move(moved.getId(), DockTarget.split(original, Side.RIGHT)));
var groups = manager.layout().windows().getFirst().areas().getFirst().groups();
assertEquals(2, groups.size());
assertEquals(List.of(remaining.getId()), groups.getFirst().dockableIds());
assertEquals(List.of(moved.getId()), groups.getLast().dockableIds());
assertSame(notes, manager.findDockable(moved.getId()).orElseThrow().getContent());
assertSame(moved, manager.activeDockable());
});
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(booleans = {false, true})
void emptyingEitherBranchDissolvesTheSplitAndPreservesTheArea(boolean emptyOriginal) throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
DockingManager manager = fixture.manager();
DockGroupId original = manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().id();
manager.move(fixture.notes(), DockTarget.split(original, Side.RIGHT));
DockGroupId added = manager.layout().windows().getFirst().areas().getFirst().groups().getLast().id();
DockGroupId survivor = emptyOriginal ? added : original;
DockGroupId removed = emptyOriginal ? original : added;
DockableId moved = emptyOriginal ? fixture.readme() : fixture.notes();
var changes = new java.util.ArrayList<DockLayoutView>();
manager.layoutProperty().addListener((observable, old, current) -> changes.add(current));
assertInstanceOf(ActionResult.Applied.class, manager.move(moved, DockTarget.group(survivor)));
assertEquals(1, changes.size());
var area = manager.layout().windows().getFirst().areas().getFirst();
assertEquals(1, area.groups().size());
assertEquals(survivor, area.groups().getFirst().id());
assertInstanceOf(DockLayoutView.Group.class, area.root());
assertInstanceOf(MoveCheck.Rejected.class, manager.checkMove(moved, DockTarget.group(removed)));
Dockable next = new Dockable(new DockableId("next"), new TextArea());
assertInstanceOf(ActionResult.Applied.class, manager.open(next, DockTarget.area("editors")));
assertEquals(3, manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().dockableIds().size());
});
}
@Test
void nestedFxmlSplitsSurviveWhenTheirSiblingBecomesEmpty() throws Exception {
FxThread.onFx(() -> {
DockPane pane = javafx.fxml.FXMLLoader.load(getClass().getResource("docking-nested-splits.fxml"));
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
for (String area : List.of("one", "two", "three")) {
manager.open(new Dockable(new DockableId(area), new TextArea(area)), DockTarget.area(area));
}
manager.move(new DockableId("one"), DockTarget.area("two"));
var editorArea = manager.layout().windows().getFirst().areas().getFirst();
assertEquals(new DockAreaId("editors"), editorArea.id());
assertEquals(2, editorArea.groups().size());
DockLayoutView.Split remaining = assertInstanceOf(DockLayoutView.Split.class, editorArea.root());
assertEquals(javafx.geometry.Orientation.VERTICAL, remaining.orientation());
assertEquals(.3, remaining.position(), .001);
assertInstanceOf(MoveCheck.Rejected.class, manager.checkMove(new DockableId("one"),
DockTarget.group(new DockGroupId("one"))));
assertFalse(manager.checkMove(new DockableId("three"), DockTarget.area("one")) instanceof MoveCheck.Rejected);
});
}
@Test
void areaTargetsPreferTheMostRecentlyActiveEligibleGroup() throws Exception {
FxThread.onFx(() -> {
var rejectedGroup = new java.util.concurrent.atomic.AtomicReference<DockGroupId>();
DockingOptions options = new DockingOptions();
options.setPlacementRule((dockable, destination) -> destination instanceof ResolvedDockTarget.Insertion insertion
&& insertion.groupId().equals(rejectedGroup.get())
? java.util.Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED,
dockable.getId(), "Use another group", null)) : java.util.Optional.empty());
Fixture fixture = fixture(options);
DockingManager manager = fixture.manager();
DockGroupId original = manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().id();
manager.move(fixture.notes(), DockTarget.split(original, Side.RIGHT));
DockGroupId right = manager.layout().windows().getFirst().areas().getFirst().groups().getLast().id();
Dockable third = new Dockable(new DockableId("third"), new TextArea());
manager.open(third, DockTarget.area("editors"));
assertEquals(List.of(fixture.notes(), third.getId()), manager.layout().windows().getFirst()
.areas().getFirst().groups().getLast().dockableIds());
rejectedGroup.set(right);
Dockable fourth = new Dockable(new DockableId("fourth"), new TextArea());
assertInstanceOf(ActionResult.Applied.class, manager.open(fourth, DockTarget.area("editors")));
assertEquals(List.of(fixture.readme(), fourth.getId()), manager.layout().windows().getFirst()
.areas().getFirst().groups().getFirst().dockableIds());
});
}
@Test
void splitDirectionsAndBothMinimumSizesAreCheckedBeforeCreatingAGroup() throws Exception {
FxThread.onFx(() -> {
DockPane pane = javafx.fxml.FXMLLoader.load(getClass().getResource("docking-split-policy.fxml"));
Stage stage = new Stage();
stage.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
DockableId notes = new DockableId("notes");
manager.open(new Dockable(notes, new TextArea()), DockTarget.area("editors"));
manager.open(new Dockable(new DockableId("readme"), new TextArea()), DockTarget.area("editors"));
pane.resize(800, 500);
pane.applyCss();
pane.layout();
DockGroupId original = manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().id();
var before = manager.layout();
assertInstanceOf(MoveCheck.Rejected.class, manager.checkMove(notes, DockTarget.split(original, Side.RIGHT)));
assertInstanceOf(ActionResult.Rejected.class, manager.move(notes, DockTarget.split(original, Side.BOTTOM)));
assertEquals(before, manager.layout());
pane.resize(800, 900);
pane.layout();
assertInstanceOf(ActionResult.Applied.class, manager.move(notes, DockTarget.split(original, Side.TOP)));
DockLayoutView.Split split = assertInstanceOf(DockLayoutView.Split.class,
manager.layout().windows().getFirst().areas().getFirst().root());
assertEquals(.5, split.position());
});
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(value = Side.class, names = {"RIGHT", "BOTTOM"})
void dividerGesturesPublishOnlyTheirCompletedGeometry(Side side) throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
DockingManager manager = fixture.manager();
DockGroupId original = manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().id();
manager.move(fixture.notes(), DockTarget.split(original, side));
fixture.pane().applyCss();
fixture.pane().layout();
javafx.scene.control.SplitPane split = (javafx.scene.control.SplitPane) fixture.pane().lookup(".split-pane");
javafx.scene.Node divider = split.lookup(".split-pane-divider");
assertNotNull(divider);
var changes = new java.util.ArrayList<DockLayoutView>();
manager.layoutProperty().addListener((observable, old, current) -> changes.add(current));
divider.fireEvent(dividerMouse(javafx.scene.input.MouseEvent.MOUSE_PRESSED, divider));
assertEquals(side == Side.RIGHT ? javafx.scene.Cursor.H_RESIZE : javafx.scene.Cursor.V_RESIZE, divider.getCursor());
split.setDividerPositions(.7);
fixture.pane().layout();
assertEquals(.5, ((DockLayoutView.Split) manager.layout().windows().getFirst().areas().getFirst().root()).position());
assertTrue(changes.isEmpty());
divider.fireEvent(dividerMouse(javafx.scene.input.MouseEvent.MOUSE_RELEASED, divider));
assertEquals(1, changes.size());
assertEquals(.7, ((DockLayoutView.Split) changes.getFirst().windows().getFirst().areas().getFirst().root()).position(), .02);
});
}
@Test
void movingOneTabDoesNotDissolveAnUnrelatedInitiallyEmptySplit() throws Exception {
FxThread.onFx(() -> {
DockPane pane = javafx.fxml.FXMLLoader.load(getClass().getResource("docking-nested-splits.fxml"));
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
manager.open(new Dockable(new DockableId("one"), new TextArea()), DockTarget.area("one"));
manager.open(new Dockable(new DockableId("moving"), new TextArea()), DockTarget.area("one"));
manager.open(new Dockable(new DockableId("two"), new TextArea()), DockTarget.area("two"));
assertInstanceOf(ActionResult.Applied.class, manager.move(new DockableId("moving"), DockTarget.area("two")));
DockLayoutView.Split root = assertInstanceOf(DockLayoutView.Split.class,
manager.layout().windows().getFirst().areas().getFirst().root());
assertInstanceOf(DockLayoutView.Split.class, root.second());
assertInstanceOf(ActionResult.Applied.class,
manager.open(new Dockable(new DockableId("three"), new TextArea()),
DockTarget.group(new DockGroupId("three"))));
});
}
@Test
void aNonpersistentRootDisappearsOnlyAfterItsLastContentLeaves() throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition temporary = new DockGroupDefinition("temporary");
temporary.setPersistent(false);
initial.setLeft(temporary);
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
DockableId id = new DockableId("notes");
assertInstanceOf(ActionResult.Applied.class,
manager.open(new Dockable(id, new TextArea()), DockTarget.area("temporary")));
assertInstanceOf(ActionResult.Applied.class, manager.move(id, DockTarget.area("editors")));
assertEquals(List.of(new DockAreaId("editors")), manager.layout().windows().getFirst().areas().stream()
.map(DockLayoutView.Area::id).toList());
MoveCheck.Rejected missing = assertInstanceOf(MoveCheck.Rejected.class,
manager.checkMove(id, DockTarget.area("temporary")));
assertEquals(DockFailure.Code.TARGET_NOT_FOUND, missing.failure().code());
});
}
@Test
void releasingEmptySpaceHidesTheGroupEvenWithDefaultEmptyVisibility() throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setReleaseSpaceWhenEmpty(true);
initial.setRight(tools);
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea());
manager.open(notes, DockTarget.area("tools"));
pane.resize(800, 500);
pane.applyCss();
pane.layout();
javafx.scene.control.TabPane tabs = pane.lookupAll(".tab-pane").stream()
.map(javafx.scene.control.TabPane.class::cast)
.filter(candidate -> !candidate.getTabs().isEmpty()).findFirst().orElseThrow();
double width = tabs.getWidth();
manager.move(notes.getId(), DockTarget.area("editors"));
pane.layout();
assertFalse(tabs.isManaged());
assertFalse(tabs.isVisible(), "A released area must not remain painted over its replacement");
manager.move(notes.getId(), DockTarget.area("tools"));
pane.layout();
assertTrue(tabs.isVisible());
assertTrue(tabs.isManaged());
assertEquals(width, tabs.getWidth(), 1);
});
}
@Test
void thePublishedInitialSplitHonorsItsMinimumAdjustedGeometry() throws Exception {
FxThread.onFx(() -> {
DockGroupDefinition first = new DockGroupDefinition("first");
first.setMinimumWidth(200);
DockSplitDefinition split = new DockSplitDefinition();
split.setDestinationId("editors");
split.setFirst(first);
split.setSecond(new DockGroupDefinition("second"));
split.setPosition(.1);
DockLayout initial = new DockLayout();
initial.setCenter(split);
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 500, 400));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
DockLayoutView.Split view = assertInstanceOf(DockLayoutView.Split.class,
manager.layout().windows().getFirst().areas().getFirst().root());
assertTrue(view.position() >= .4 && view.position() < .5,
"Published geometry must describe the minimum-adjusted layout");
javafx.scene.control.SplitPane surface = (javafx.scene.control.SplitPane) pane.lookup(".split-pane");
assertEquals(surface.getDividers().getFirst().getPosition(), view.position(), .001);
});
}
@Test
void emptyingASiblingCannotResizeAGroupWhoseCloseConsentIsPending() throws Exception {
FxThread.onFx(() -> {
DockSplitDefinition split = new DockSplitDefinition();
split.setDestinationId("editors");
split.setFirst(new DockGroupDefinition("pending"));
split.setSecond(new DockGroupDefinition("sibling"));
DockLayout initial = new DockLayout();
initial.setCenter(split);
initial.setRight(new DockGroupDefinition("tools"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
var consent = new java.util.concurrent.CompletableFuture<CloseConsent>();
Dockable pending = new Dockable(new DockableId("pending"), new TextArea());
pending.setCloseCheck(request -> consent);
manager.open(pending, DockTarget.area("pending"));
DockableId last = new DockableId("last");
DockableId extra = new DockableId("extra");
manager.open(new Dockable(last, new TextArea()), DockTarget.area("sibling"));
manager.open(new Dockable(extra, new TextArea()), DockTarget.area("sibling"));
var close = manager.requestTabClose(pending.getId());
assertInstanceOf(ActionResult.Applied.class, manager.move(extra, DockTarget.area("tools")),
"Moving a non-last sibling tab does not affect the pending group");
DockLayoutView before = manager.layout();
MoveCheck.Rejected check = assertInstanceOf(MoveCheck.Rejected.class,
manager.checkMove(last, DockTarget.area("tools")));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, check.failure().code());
ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class,
manager.move(last, DockTarget.area("tools")));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, rejected.failure().code());
assertEquals(before, manager.layout());
consent.complete(CloseConsent.VETO);
assertInstanceOf(CloseResult.Vetoed.class, close.toCompletableFuture().join());
assertInstanceOf(ActionResult.Applied.class, manager.move(last, DockTarget.area("tools")));
assertInstanceOf(DockLayoutView.Group.class,
manager.layout().windows().getFirst().areas().getFirst().root());
});
}
@Test
void anUnrelatedPendingCloseDoesNotCaptureANestedDividerGesture() throws Exception {
FxThread.onFx(() -> {
DockPane pane = javafx.fxml.FXMLLoader.load(getClass().getResource("docking-nested-splits.fxml"));
Stage stage = new Stage();
stage.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
var consent = new java.util.concurrent.CompletableFuture<CloseConsent>();
for (String area : List.of("one", "two", "three")) {
Dockable dockable = new Dockable(new DockableId(area), new TextArea(area));
if (area.equals("one")) dockable.setCloseCheck(request -> consent);
manager.open(dockable, DockTarget.area(area));
}
var close = manager.requestTabClose(new DockableId("one"));
try {
javafx.scene.control.SplitPane nested = pane.lookupAll(".split-pane").stream()
.map(javafx.scene.control.SplitPane.class::cast)
.filter(candidate -> candidate.getOrientation() == javafx.geometry.Orientation.VERTICAL)
.findFirst().orElseThrow();
javafx.scene.Node divider = nested.lookup(".split-pane-divider");
var changes = new java.util.ArrayList<DockLayoutView>();
manager.layoutProperty().addListener((observable, old, current) -> changes.add(current));
divider.fireEvent(dividerMouse(javafx.scene.input.MouseEvent.MOUSE_PRESSED, divider));
nested.setDividerPositions(.7);
pane.layout();
assertTrue(changes.isEmpty());
divider.fireEvent(dividerMouse(javafx.scene.input.MouseEvent.MOUSE_RELEASED, divider));
assertEquals(1, changes.size(), "Only the owning nested split handles its divider");
assertEquals(javafx.scene.Cursor.V_RESIZE, divider.getCursor());
DockLayoutView.Split root = (DockLayoutView.Split) manager.layout().windows().getFirst().areas().getFirst().root();
assertEquals(.4, root.position(), .01);
assertEquals(.7, ((DockLayoutView.Split) root.second()).position(), .02);
assertFalse(close.toCompletableFuture().isDone());
} finally {
consent.complete(CloseConsent.VETO);
}
});
}
private static javafx.scene.input.MouseEvent dividerMouse(javafx.event.EventType<javafx.scene.input.MouseEvent> type,
javafx.scene.Node divider) {
return new javafx.scene.input.MouseEvent(type, 0, 0, 0, 0, javafx.scene.input.MouseButton.PRIMARY, 1,
false, false, false, false, type != javafx.scene.input.MouseEvent.MOUSE_RELEASED,
false, false, false, false, false, new javafx.scene.input.PickResult(divider, 0, 0));
}
private static Fixture fixture() { return fixture(new DockingOptions()); }
private static Fixture fixture(DockingOptions options) {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(stage, pane, options);
DockableId notes = new DockableId("notes");
DockableId readme = new DockableId("readme");
manager.open(new Dockable(notes, new TextArea("Unsaved notes")), DockTarget.area("editors"));
manager.open(new Dockable(readme, new TextArea("Readme")), DockTarget.area("editors"));
pane.resize(800, 500);
pane.applyCss();
pane.layout();
return new Fixture(manager, pane, notes, readme);
}
private record Fixture(DockingManager manager, DockPane pane, DockableId notes, DockableId readme) { }
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.*?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center>
<DockSplitDefinition destinationId="editors" orientation="HORIZONTAL" position="0.4">
<first><DockGroupDefinition destinationId="one"/></first>
<second>
<DockSplitDefinition destinationId="remaining" orientation="VERTICAL" position="0.3">
<first><DockGroupDefinition destinationId="two"/></first>
<second><DockGroupDefinition destinationId="three"/></second>
</DockSplitDefinition>
</second>
</DockSplitDefinition>
</center>
</DockLayout>
</initialLayout>
</DockPane>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.*?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center><DockGroupDefinition destinationId="editors" splitDirections="VERTICAL"
minimumWidth="100" minimumHeight="300"/></center>
</DockLayout>
</initialLayout>
</DockPane>