feat(fx): add collapsible groups and managed floating windows

This commit is contained in:
2026-11-15 22:26:05 +01:00
parent 1a3aea6e09
commit f6539bdd29
34 changed files with 3062 additions and 48 deletions
@@ -1,6 +1,8 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockGroupChanges;
import de.neitzel.fx.docking.DockLayoutView;
import de.neitzel.fx.docking.DockSplitDefinition;
import de.neitzel.fx.docking.SplitDirections;
import javafx.geometry.Orientation;
@@ -35,9 +37,11 @@ public final class DockingApp extends Application {
Button toTools = new Button("Move Notes to tools");
Button toEditors = new Button("Move Notes to editors");
Button splitNotes = new Button("Split Notes right");
Button toggleTools = new Button("Toggle tools");
Button widenTools = new Button("Tools width 260");
Label status = new Label("Drag a tab to an edge to split; drag dividers to resize.");
BorderPane shell = new BorderPane(pane);
shell.setTop(new ToolBar(activate, toTools, toEditors, splitNotes));
shell.setTop(new ToolBar(activate, toTools, toEditors, splitNotes, toggleTools, widenTools));
shell.setBottom(status);
stage.setScene(new Scene(shell, 900, 600));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
@@ -54,6 +58,10 @@ public final class DockingApp extends Application {
output.setTitle("Output");
manager.open(output, DockTarget.area("output"));
}
Dockable changes = new Dockable(new DockableId("changes"), new TextArea("Changed files"));
changes.setTitle("Changed files");
changes.setIcon(new Label("Δ"));
manager.open(changes, DockTarget.area("tools"));
Dockable project = new Dockable(new DockableId("project"), new Label("Project files"));
project.setTitle("Project");
project.setIcon(new Label("▦"));
@@ -65,6 +73,10 @@ public final class DockingApp extends Application {
.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)))));
toggleTools.setOnAction(event -> toolsGroup(manager).ifPresent(group ->
report(status, manager.setGroupCollapsed(group.id(), !group.collapsed()))));
widenTools.setOnAction(event -> toolsGroup(manager).ifPresent(group ->
report(status, manager.updateGroup(group.id(), DockGroupChanges.builder().preferredWidth(260).build()))));
stage.setTitle("NeitzelLib docking — Java or ordinary FXML");
stage.show();
manager.activate(notesId);
@@ -72,12 +84,18 @@ public final class DockingApp extends Application {
private static void report(Label status, ActionResult result) {
status.setText(switch (result) {
case ActionResult.Applied ignored -> "Notes moved.";
case ActionResult.NoChange ignored -> "Notes is already at that position.";
case ActionResult.Applied ignored -> "Layout updated.";
case ActionResult.NoChange ignored -> "The layout already has that state.";
case ActionResult.Rejected rejected -> rejected.failure().message();
});
}
private static java.util.Optional<DockLayoutView.Group> toolsGroup(DockingManager manager) {
return manager.layout().windows().stream().flatMap(window -> window.areas().stream())
.filter(area -> area.id().value().equals("tools"))
.flatMap(area -> area.groups().stream()).findFirst();
}
private static DockPane initialPane(boolean splits) {
DockLayout layout = new DockLayout();
if (splits) {
@@ -96,6 +114,7 @@ public final class DockingApp extends Application {
}
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT);
tools.setCollapsible(true);
tools.setPreferredWidth(200);
tools.setSplitDirections(SplitDirections.VERTICAL);
tools.setVisibleWhenEmpty(false);
@@ -0,0 +1,89 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.ActionResult;
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 de.neitzel.fx.docking.MoveCheck;
import javafx.application.Application;
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;
/** Demonstrates live editor transfers between the main window and floating windows. */
public final class FloatingDockingApp extends Application {
@Override
public void start(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
pane.getInitialLayout().setLeft(new DockGroupDefinition("project"));
Label notice = new Label("Edit Notes and select a word before moving it. Project stays in the main window.");
BorderPane shell = new BorderPane(pane);
shell.setBottom(notice);
stage.setScene(new Scene(shell, 1040, 560));
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("NeitzelLib — floating editor"));
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable notes = editor("notes", "Notes", "Unsaved notes travel with this editor.\nSelect a word, float the tab, and continue typing.");
Dockable readme = editor("readme", "Readme", "A second editor can share a floating window with Notes.");
Dockable project = editor("project", "Project", "This panel is restricted to the main window.\nIts Float menu command is disabled.");
project.setMainWindowOnly(true);
manager.open(project, DockTarget.area("project"));
manager.open(readme, DockTarget.area("editors"));
manager.open(notes, DockTarget.area("editors"));
Button floatNotes = new Button("Float Notes");
Button floatReadme = new Button("Float Readme");
Button join = new Button("Join Readme");
Button returnNotes = new Button("Return Notes");
Button returnReadme = new Button("Return Readme");
shell.setTop(new ToolBar(floatNotes, floatReadme, join, returnNotes, returnReadme));
floatNotes.setOnAction(event -> move(manager, notes, DockTarget.floating(), notice));
floatReadme.setOnAction(event -> move(manager, readme, DockTarget.floating(), notice));
join.setOnAction(event -> {
DockTarget target = floatingGroup(manager, readme.getId());
if (target != null) move(manager, notes, target, notice);
});
returnNotes.setOnAction(event -> move(manager, notes, DockTarget.returnToMain(), notice));
returnReadme.setOnAction(event -> move(manager, readme, DockTarget.returnToMain(), notice));
Runnable refresh = () -> {
floatNotes.setDisable(!(manager.checkMove(notes.getId(), DockTarget.floating()) instanceof MoveCheck.Allowed));
floatReadme.setDisable(!(manager.checkMove(readme.getId(), DockTarget.floating()) instanceof MoveCheck.Allowed));
returnNotes.setDisable(!(manager.checkMove(notes.getId(), DockTarget.returnToMain()) instanceof MoveCheck.Allowed));
returnReadme.setDisable(!(manager.checkMove(readme.getId(), DockTarget.returnToMain()) instanceof MoveCheck.Allowed));
DockTarget target = floatingGroup(manager, readme.getId());
join.setDisable(target == null || !(manager.checkMove(notes.getId(), target) instanceof MoveCheck.Allowed));
};
manager.layoutProperty().addListener((observable, old, current) -> refresh.run());
refresh.run();
stage.setTitle("NeitzelLib — floating windows");
stage.show();
}
private static Dockable editor(String id, String title, String text) {
Dockable editor = new Dockable(new DockableId(id), new TextArea(text));
editor.setTitle(title);
return editor;
}
private static DockTarget floatingGroup(DockingManager manager, DockableId id) {
return manager.layout().windows().stream().filter(window -> !window.main())
.flatMap(window -> window.areas().stream()).flatMap(area -> area.groups().stream())
.filter(group -> group.dockableIds().contains(id)).findFirst()
.map(group -> DockTarget.group(group.id())).orElse(null);
}
private static void move(DockingManager manager, Dockable editor, DockTarget target, Label notice) {
ActionResult result = manager.move(editor.getId(), target);
notice.setText(result instanceof ActionResult.Rejected rejected ? rejected.failure().message()
: editor.getTitle() + " moved. Continue editing in its destination window.");
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain Java launcher for the floating editor example. */
public final class FloatingDockingMain {
private FloatingDockingMain() { }
public static void main(String[] args) {
Application.launch(FloatingDockingApp.class, args);
}
}
@@ -6,7 +6,7 @@
<initialLayout>
<DockLayout>
<center><DockGroupDefinition destinationId="editors"/></center>
<right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" preferredWidth="200" splitDirections="VERTICAL"
<right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true" preferredWidth="200" splitDirections="VERTICAL"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></right>
</DockLayout>
</initialLayout>
@@ -17,7 +17,7 @@
</second>
</DockSplitDefinition>
</center>
<right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" preferredWidth="200" splitDirections="VERTICAL"
<right><DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true" preferredWidth="200" splitDirections="VERTICAL"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></right>
</DockLayout>
</initialLayout>
+128
View File
@@ -0,0 +1,128 @@
# Floating editors
A tab's **Float** command moves its live content into a manager-owned window.
**Return to main** returns it to its last eligible main-window position, or the
configured fallback. Both commands also appear on floating tabs. The tab's
text, selection and content instance survive the transfer, and the destination
receives keyboard focus.
If neither destination is eligible, Return is rejected and the editor stays
in its floating window.
Application commands use the same path:
```java
manager.move(editorId, DockTarget.floating());
manager.move(editorId, DockTarget.floating(new Rectangle2D(100, 100, 640, 480)));
manager.move(editorId, DockTarget.returnToMain());
```
Use `checkMove` to enable a command and explain a rejected destination. The tab
menu does this whenever it opens; checking a destination does not create a
window. Set `dockable.setMainWindowOnly(true)` for content that must remain in
the main window. Its Float command is disabled with the rejection reason.
A floating window's groups remain destinations in the **Move to** menu, so
editors can share a window. Moving its final tab elsewhere removes the empty
window without closing that Dockable. Floating windows also support the
ordinary split commands.
`DockingOptions.setFloatingWindowCustomizer` supplies a configuration bean for
the title, icons and stylesheets before display. The manager continues to own
window placement and lifecycle.
Run `de.neitzel.fx.example.docking.FloatingDockingMain` from the `fx-example`
module for a desktop demonstration:
1. Edit Notes and select a word.
2. Float Notes, then Float Readme to create two windows.
3. Choose Join Readme to move Notes into the second window; the empty first
window disappears. Continue typing without clicking the editor again.
4. In that shared floating window, open Notes' tab menu and choose **Split →
Right** to place the editors beside each other. Resize their divider.
5. Return Notes and Readme to the main window.
6. Open Project's tab menu to inspect the disabled Float command.
The buttons and tab menus use the same manager operations. This example covers
command-based transfers. Native drag-and-drop between windows and the full
multi-tab window-close workflow are supplied by their subsequent tickets.
## Native keyboard qualification
`FloatingNativeFocusTest` sends actual AWT Robot key presses to the focused OS
window. It types into Notes in the main window, uses **Float**, moves Notes
through **Move to** into another floating window, then uses **Return to main**.
After those transfers it never clicks or explicitly repairs focus. It observes
the destination's native window and Scene focus, then verifies the exact text
sequence `1` → `12` → `123` → `1234`; the other editor remains unchanged.
This sequence passed on macOS 27.2 with Java 25 and JavaFX 27.0.1 on 2026-11-15
(one native test, zero failures, errors or skips). It qualifies command/menu
transfers on that environment; native cross-window pointer dragging and other
OS environments need their own qualification.
Run only with an exclusive desktop slot, since the test posts real keystrokes:
```sh
./mvnw -pl fx -am -Dtest=FloatingNativeFocusTest \
-Dneitzellib.nativeFocusTest=true \
-Dsurefire.failIfNoSpecifiedTests=false test
```
Without the opt-in property this test is explicitly skipped. Its fixture uses
digit keys on the active keyboard layout. It releases the keys and hides its
windows in `finally`; it does not move the pointer.
## Committed native window geometry
A floating `DockLayoutView.Window` exposes its last committed screen rectangle
as `bounds()`. Main-window bounds are `null`: the application owns its geometry.
Geometry property changes are collected while a native mouse button remains
down, including a pause in a titlebar drag or border resize. Publication resumes
when the native query observes release. A timeout alone cannot identify this
boundary because the user can pause with the button held.
The same boundary covers nested split ratios: a selection or other unrelated
publication during native resizing retains both the previous frame and its
committed split geometry. Native regression coverage shrinks a floating window
with unequal group minima, verifies that the live divider clamps while the
published ratio stays unchanged, then verifies the new frame and ratio after
release.
The implementation uses Java 25's Foreign Function and Memory API and existing
OS libraries, without an additional native-access dependency. Enable native
access for the module containing this library; for classpath applications use
`--enable-native-access=ALL-UNNAMED` (and `javafx.graphics` when JavaFX is on the
module path). A denied native call is treated as unknown state, never as release.
Backend boundaries are explicit:
- macOS uses combined-session CoreGraphics state for left, right and middle
buttons, covering either primary-button mapping. The native paused-gesture
behavior has been observed on macOS with Java 25 / JavaFX 27.
- Windows queries the five physical mouse buttons. An all-up result is accepted
only while this process owns the foreground window, because the API can also
return zero for inaccessible input. This backend requires native validation
on Windows before claiming equivalent coverage.
- X11 queries the pointer mask on a separate display connection. Its logical
state can lag frozen device processing; this backend requires X11 validation.
- Wayland sessions, unavailable libraries, denied native access and unrecognized
backends retain the last committed bounds and log the limitation. They do not
silently use a timer to claim a completed native gesture. XWayland sessions
are also conservatively excluded until independently verified.
This is mouse-state observation, not a general native window-manager gesture
API. Touch/keyboard-driven native geometry and delayed OS notifications need
separate validation. Global button state may defer publication when an
unrelated mouse button is held.
The opt-in native regression moves the real pointer and must run with an
exclusive desktop slot:
```sh
./mvnw -pl fx -am -Dtest=FloatingWindowGeometryTest \
-Dneitzellib.nativeGeometryTest=true \
-Dsurefire.failIfNoSpecifiedTests=false test
```
Without that property, the native pointer case is explicitly skipped. Ordinary
public initial-bounds verification still runs. The native case includes a
watchdog and restores the pointer in `finally`.
+52
View File
@@ -0,0 +1,52 @@
# Collapsible tab groups
A group shares its content size, tab side, minimum dimensions, splitting policy
and empty-space behavior across its tabs. Enable `collapsible` on an initial
`DockGroupDefinition` in Java or ordinary FXML. It defaults to `false`, so an
editor area keeps its content space and rejects collapse requests unless the
application explicitly enables them.
Clicking the selected visible tool tab collapses the group to its header rail.
The same headers and icons remain available. Clicking any collapsed tab opens
the group at its remembered size and selects that tab. Within a split, the
collapsed leaf keeps only its rail extent and its sibling receives the released
space. `Split.position()` retains the remembered expanded proportion during
that temporary allocation; reopening restores it. The split divider is hidden
while a branch is collapsed. Escape inside an open
collapsible group also collapses it. Keyboard focus returns to the selected
header; the active Dockable falls back to the most recently active visible
selected content, or becomes null. Other collapsed groups stay closed.
`setGroupCollapsed(groupId, boolean)` supplies the same state transition.
`activate(dockableId)` opens the Dockable's group before focusing its content.
A drag preview does not open a collapsed group: only the successful drop does;
Escape cancels the preview without changing the layout.
```java
manager.updateGroup(toolsId, DockGroupChanges.builder()
.preferredWidth(260)
.tabSide(Side.RIGHT)
.collapsible(false)
.build());
```
Only explicitly supplied settings change. In particular, `false` is a supplied
value, not an omitted setting. The manager validates the resulting definition
before applying anything, publishes one completed layout state, and returns a
rejection without partial changes for invalid dimensions. An empty or identical
patch returns `NoChange`. Disabling collapse opens a collapsed group as part of
the update. A missing group returns `TARGET_NOT_FOUND`; a pending close protects
its group from changes. Geometry changes also protect neighboring content that
would be resized while its close consent is pending; unrelated policy updates
remain possible. The initial definition supplied at attachment remains
independent of live updates.
`DockGroupChanges` covers tab side, preferred/minimum width and height,
persistence, empty visibility, empty-space release, collapsibility and split
directions. Each new split receives its own copy of its target's settings.
Overlay display is provided by the subsequent overlay slice.
Run `DockingMain` (or `--fxml`) and select Project. Click it again to collapse,
then click Changed files to reopen the same group. The toolbar also exposes
explicit collapse/open and shared-width updates. The `--splits` variants retain
these group actions in the nested editor demonstration.
+3 -2
View File
@@ -39,8 +39,9 @@ application actions. Moving keyboard focus to a global button preserves it.
The content instance remains owned by the application. A supplied
`setFocusTarget` chooses a Node within the content; otherwise the manager tries
the previously focused descendant. See [split groups](docking-splits.md) for
nested layouts and resizing and [close consent](docking-close.md) for asynchronous
close checks. Restoration is supplied by a later slice.
nested layouts and resizing, [group presentation](docking-groups.md) for
collapse and atomic configuration, and [close consent](docking-close.md) for
asynchronous close checks. Restoration is supplied by a later slice.
## Move and check placement
@@ -60,10 +60,13 @@ final class DockDragController {
Menu splits = new Menu("Split");
MenuItem close = new MenuItem("Close");
close.setOnAction(event -> manager.requestTabClose(id));
ContextMenu menu = new ContextMenu(destinations, splits, close);
ContextMenu menu = new ContextMenu(destinations, splits, close,
new MenuItem("Float"), new MenuItem("Return to main"));
menu.setOnShowing(event -> {
populateDestinations(destinations, id);
populateSplits(splits, id);
menu.getItems().set(3, moveItem("Float", id, DockTarget.floating()));
menu.getItems().set(4, moveItem("Return to main", id, DockTarget.returnToMain()));
});
tab.setContextMenu(menu);
}
@@ -34,7 +34,7 @@ final class DockEdgeRegion extends Region {
divider.setCursor(side.isVertical() ? Cursor.H_RESIZE : Cursor.V_RESIZE);
divider.setOnMousePressed(event -> {
if (event.getButton() != MouseButton.PRIMARY) return;
if (!canResize.getAsBoolean()) {
if (DockGroupPane.allCollapsed(content) || !canResize.getAsBoolean()) {
event.consume();
return;
}
@@ -100,37 +100,59 @@ final class DockEdgeRegion extends Region {
requestLayout();
}
boolean changesPreferredExtent(Double width, Double height) {
Double requested = side.isVertical() ? width : height;
return requested != null && Double.compare(requested, committedExtent) != 0;
}
void updatePreferredExtent(Double width, Double height) {
Double requested = side.isVertical() ? width : height;
if (requested == null) return;
extent = requested;
committedExtent = requested;
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);
return side.isVertical() ? displayedExtent() + dividerSize() : content == null ? 0 : content.prefWidth(height);
}
@Override protected double computePrefHeight(double width) {
return side.isHorizontal() ? extent + DIVIDER_SIZE : content == null ? 0 : content.prefHeight(width);
return side.isHorizontal() ? displayedExtent() + dividerSize() : content == null ? 0 : content.prefHeight(width);
}
@Override protected double computeMinWidth(double height) {
return content == null ? 0 : content.minWidth(height) + (side.isVertical() ? DIVIDER_SIZE : 0);
return content == null ? 0 : content.minWidth(height) + (side.isVertical() ? dividerSize() : 0);
}
@Override protected double computeMinHeight(double width) {
return content == null ? 0 : content.minHeight(width) + (side.isHorizontal() ? DIVIDER_SIZE : 0);
return content == null ? 0 : content.minHeight(width) + (side.isHorizontal() ? dividerSize() : 0);
}
private double dividerSize() { return DockGroupPane.allCollapsed(content) ? 0 : DIVIDER_SIZE; }
private double displayedExtent() {
return DockGroupPane.allCollapsed(content)
? side.isVertical() ? content.prefWidth(-1) : content.prefHeight(-1) : extent;
}
@Override protected void layoutChildren() {
if (content == null) return;
double dividerSize = dividerSize();
divider.setVisible(dividerSize > 0);
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);
content.resizeRelocate(side == Side.RIGHT ? dividerSize : 0, 0,
Math.max(0, width - dividerSize), height);
divider.resizeRelocate(side == Side.RIGHT ? 0 : width - dividerSize, 0, dividerSize, 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);
content.resizeRelocate(0, side == Side.BOTTOM ? dividerSize : 0,
width, Math.max(0, height - dividerSize));
divider.resizeRelocate(0, side == Side.BOTTOM ? 0 : height - dividerSize, width, dividerSize);
}
}
}
@@ -2,7 +2,7 @@ package de.neitzel.fx.docking;
/** Machine-readable rejection with optional affected identity and technical cause. */
public record DockFailure(Code code, DockableId dockableId, String message, Throwable cause) {
public enum Code { 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,
CLOSE_IN_PROGRESS, CLOSE_CHECK_FAILED, CLEANUP_FAILED }
public enum Code { INVALID_GROUP_CONFIGURATION, COLLAPSE_DISABLED, SPLIT_DISABLED, SPLIT_TOO_SMALL, TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED,
PLACEMENT_REJECTED, PLACEMENT_CHECK_FAILED, ID_MISMATCH, FACTORY_FAILED, MAIN_WINDOW_ONLY,
CLOSE_IN_PROGRESS, CLOSE_CHECK_FAILED, CLEANUP_FAILED, INVALID_WINDOW_BOUNDS, WINDOW_CREATION_FAILED }
}
@@ -0,0 +1,64 @@
package de.neitzel.fx.docking;
import javafx.geometry.Side;
import lombok.Builder;
import lombok.Value;
import java.util.Objects;
/** Immutable partial update: null getters mean unspecified, while false is an explicit value. */
@Value @Builder
public class DockGroupChanges {
Side tabSide;
Double preferredWidth;
Double preferredHeight;
Double minimumWidth;
Double minimumHeight;
Boolean persistent;
Boolean visibleWhenEmpty;
Boolean releaseSpaceWhenEmpty;
Boolean collapsible;
SplitDirections splitDirections;
/** Builder accepts primitive dimensions/flags and requires non-null enum settings. */
public static class DockGroupChangesBuilder {
public DockGroupChangesBuilder tabSide(Side value) { tabSide = Objects.requireNonNull(value); return this; }
public DockGroupChangesBuilder preferredWidth(double value) { preferredWidth = value; return this; }
public DockGroupChangesBuilder preferredHeight(double value) { preferredHeight = value; return this; }
public DockGroupChangesBuilder minimumWidth(double value) { minimumWidth = value; return this; }
public DockGroupChangesBuilder minimumHeight(double value) { minimumHeight = value; return this; }
public DockGroupChangesBuilder persistent(boolean value) { persistent = value; return this; }
public DockGroupChangesBuilder visibleWhenEmpty(boolean value) { visibleWhenEmpty = value; return this; }
public DockGroupChangesBuilder releaseSpaceWhenEmpty(boolean value) { releaseSpaceWhenEmpty = value; return this; }
public DockGroupChangesBuilder collapsible(boolean value) { collapsible = value; return this; }
public DockGroupChangesBuilder splitDirections(SplitDirections value) { splitDirections = Objects.requireNonNull(value); return this; }
}
DockGroupChanges resolved(DockGroupDefinition current) {
return builder()
.tabSide(tabSide == null ? current.getTabSide() : tabSide)
.preferredWidth(preferredWidth == null ? current.getPreferredWidth() : preferredWidth)
.preferredHeight(preferredHeight == null ? current.getPreferredHeight() : preferredHeight)
.minimumWidth(minimumWidth == null ? current.getMinimumWidth() : minimumWidth)
.minimumHeight(minimumHeight == null ? current.getMinimumHeight() : minimumHeight)
.persistent(persistent == null ? current.isPersistent() : persistent)
.visibleWhenEmpty(visibleWhenEmpty == null ? current.isVisibleWhenEmpty() : visibleWhenEmpty)
.releaseSpaceWhenEmpty(releaseSpaceWhenEmpty == null ? current.isReleaseSpaceWhenEmpty() : releaseSpaceWhenEmpty)
.collapsible(collapsible == null ? current.isCollapsible() : collapsible)
.splitDirections(splitDirections == null ? current.getSplitDirections() : splitDirections)
.build();
}
void applyTo(DockGroupDefinition target) {
if (tabSide != null) target.setTabSide(tabSide);
if (preferredWidth != null) target.setPreferredWidth(preferredWidth);
if (preferredHeight != null) target.setPreferredHeight(preferredHeight);
if (minimumWidth != null) target.setMinimumWidth(minimumWidth);
if (minimumHeight != null) target.setMinimumHeight(minimumHeight);
if (persistent != null) target.setPersistent(persistent);
if (visibleWhenEmpty != null) target.setVisibleWhenEmpty(visibleWhenEmpty);
if (releaseSpaceWhenEmpty != null) target.setReleaseSpaceWhenEmpty(releaseSpaceWhenEmpty);
if (collapsible != null) target.setCollapsible(collapsible);
if (splitDirections != null) target.setSplitDirections(splitDirections);
}
}
@@ -14,6 +14,7 @@ public final class DockGroupDefinition implements DockLayoutNode {
private double minimumWidth = 80;
private double minimumHeight = 80;
private boolean persistent = true;
private boolean collapsible;
private boolean visibleWhenEmpty = true;
private boolean releaseSpaceWhenEmpty;
private SplitDirections splitDirections = SplitDirections.ALL;
@@ -0,0 +1,128 @@
package de.neitzel.fx.docking;
import javafx.scene.Node;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TabPane;
import javafx.scene.control.Tab;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Region;
/** Keeps the same tab headers and live content while exposing only the header rail. */
final class DockGroupPane extends TabPane {
private final DockGroupDefinition definition;
private boolean collapsed;
DockGroupPane(DockGroupDefinition definition) {
this.definition = definition;
getStyleClass().add("dock-group");
}
boolean isCollapsed() { return collapsed; }
void setCollapsed(boolean collapsed) {
this.collapsed = collapsed;
pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("collapsed"), collapsed);
requestLayout();
}
void installHeaderActions(java.util.function.Consumer<Tab> activate, Runnable collapse) {
addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ESCAPE && !collapsed && definition.isCollapsible()) {
collapse.run();
event.consume();
}
});
Tab[] pressed = {null};
boolean[] selected = {false};
boolean[] wasCollapsed = {false};
addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
if (event.getButton() != MouseButton.PRIMARY) return;
pressed[0] = headerTab(event.getPickResult().getIntersectedNode());
selected[0] = pressed[0] != null && getSelectionModel().getSelectedItem() == pressed[0];
wasCollapsed[0] = collapsed;
});
addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
if (event.getButton() != MouseButton.PRIMARY || !event.isStillSincePress()) return;
Tab clicked = headerTab(event.getPickResult().getIntersectedNode());
if (clicked == null || clicked != pressed[0]) return;
pressed[0] = null;
if (wasCollapsed[0]) activate.accept(clicked);
else if (selected[0] && definition.isCollapsible()) collapse.run();
});
}
private Tab headerTab(Node target) {
for (Node current = target; current != null && current != this; current = current.getParent()) {
if (current.getStyleClass().contains("tab-close-button")) return null;
if (current instanceof TabPane) return null;
for (Tab tab : getTabs()) {
if (tab.getId() != null && tab.getId().equals(current.getId())) return tab;
}
}
return null;
}
void focusSelectedHeader() {
Tab selected = getSelectionModel().getSelectedItem();
Node strip = ownedSkinChild("tab-header-area");
Node header = selected == null || strip == null ? null : strip.lookup("#" + selected.getId());
if (header != null) {
header.setFocusTraversable(true);
header.requestFocus();
}
}
static boolean allCollapsed(Node node) {
if (node instanceof DockGroupPane group) return group.isCollapsed();
return node instanceof SplitPane split && !split.getItems().isEmpty()
&& split.getItems().stream().allMatch(DockGroupPane::allCollapsed);
}
private double headerExtent() {
Node header = ownedSkinChild("tab-header-area");
return header instanceof Region region ? Math.max(24, region.prefHeight(-1)) : 28;
}
private double headerLength() {
Node header = ownedSkinChild("tab-header-area");
return header instanceof Region region ? Math.max(24, region.prefWidth(-1)) : Math.max(24, getTabs().size() * 32);
}
@Override protected double computePrefWidth(double height) {
return collapsed ? getSide().isVertical() ? headerExtent() : headerLength() : definition.getPreferredWidth();
}
@Override protected double computePrefHeight(double width) {
return collapsed ? getSide().isHorizontal() ? headerExtent() : headerLength() : definition.getPreferredHeight();
}
@Override protected double computeMinWidth(double height) {
return collapsed ? getSide().isVertical() ? headerExtent() : headerLength() : definition.getMinimumWidth();
}
@Override protected double computeMinHeight(double width) {
return collapsed ? getSide().isHorizontal() ? headerExtent() : headerLength() : definition.getMinimumHeight();
}
private Node ownedSkinChild(String styleClass) {
return getChildrenUnmodifiable().stream().filter(node -> node.getStyleClass().contains(styleClass))
.findFirst().orElse(null);
}
private boolean containsSelectedContent(Node wrapper, Node selectedContent) {
for (Node current = selectedContent; current != null && current != this; current = current.getParent()) {
if (current == wrapper) return true;
}
return false;
}
@Override protected void layoutChildren() {
super.layoutChildren();
Tab selected = getSelectionModel().getSelectedItem();
Node selectedContent = selected == null ? null : selected.getContent();
for (Node wrapper : getChildrenUnmodifiable()) {
if (wrapper.getStyleClass().contains("tab-content-area")) {
wrapper.setVisible(!collapsed && containsSelectedContent(wrapper, selectedContent));
}
}
}
}
@@ -30,7 +30,8 @@ final class DockLayoutTree {
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());
selected == null ? null : (DockableId) selected.getUserData(),
group.tabs() instanceof DockGroupPane pane && pane.isCollapsed());
}
}
@@ -40,6 +41,7 @@ final class DockLayoutTree {
private final SplitPane pane = new SplitPane();
private double position = .5;
private boolean dragging;
private boolean collapsedAllocation;
Split(Branch first, Branch second, Orientation orientation) {
this.first = first;
this.second = second;
@@ -127,6 +129,10 @@ final class DockLayoutTree {
}
boolean geometryEvent = event.getEventType() == MouseEvent.MOUSE_PRESSED
|| event.getEventType() == MouseEvent.MOUSE_DRAGGED || event.getEventType() == MouseEvent.MOUSE_RELEASED;
if (geometryEvent && split.collapsedAllocation) {
event.consume();
return;
}
if (geometryEvent && split.groups().stream().anyMatch(group -> !canResize.test(group.id()))) {
if (split.dragging) split.pane.setDividerPositions(split.position);
split.dragging = false;
@@ -156,6 +162,24 @@ final class DockLayoutTree {
return null;
}
boolean geometryAffects(DockGroupId id, java.util.function.Predicate<DockingManager.Group> protectedGroup) {
for (Root root : roots) {
Branch affected = geometryBranch(root.branch, null, id);
if (affected != null) return affected.groups().stream().anyMatch(protectedGroup);
}
return false;
}
private static Branch geometryBranch(Branch branch, Branch parent, DockGroupId id) {
if (branch instanceof Leaf leaf) {
if (!leaf.group.id().equals(id)) return null;
return parent == null ? leaf : parent;
}
Split split = (Split) branch;
Branch found = geometryBranch(split.first, split, id);
return found == null ? geometryBranch(split.second, split, id) : found;
}
boolean normalizationAffects(DockGroupId source, DockGroupId destination,
java.util.function.Predicate<DockingManager.Group> protectedGroup) {
if (find(source).groups().getFirst().tabs().getTabs().size() != 1) return false;
@@ -221,12 +245,44 @@ final class DockLayoutTree {
}
void captureGeometry() {
for (Root root : roots) allocateCollapsed(root.branch);
for (Root root : roots) captureGeometry(root.branch);
}
private static void allocateCollapsed(Branch branch) {
if (!(branch instanceof Split split)) return;
boolean firstCollapsed = DockGroupPane.allCollapsed(split.first.node());
boolean secondCollapsed = DockGroupPane.allCollapsed(split.second.node());
boolean allocate = firstCollapsed || secondCollapsed;
SplitPane.setResizableWithParent(split.first.node(), !firstCollapsed);
SplitPane.setResizableWithParent(split.second.node(), !secondCollapsed);
if (allocate) {
split.collapsedAllocation = true;
split.dragging = false;
boolean horizontal = split.pane.getOrientation() == Orientation.HORIZONTAL;
double span = horizontal ? split.pane.getWidth() : split.pane.getHeight();
double firstExtent = horizontal ? split.first.node().minWidth(-1) : split.first.node().minHeight(-1);
double secondExtent = horizontal ? split.second.node().minWidth(-1) : split.second.node().minHeight(-1);
if (span > 0) {
double position = firstCollapsed && secondCollapsed ? firstExtent / (firstExtent + secondExtent)
: firstCollapsed ? (firstExtent + 4) / span : 1 - (secondExtent + 4) / span;
split.pane.setDividerPositions(Math.max(0, Math.min(1, position)));
}
} else if (split.collapsedAllocation) {
split.collapsedAllocation = false;
split.pane.setDividerPositions(split.position);
}
split.pane.layout();
for (Node node : split.pane.lookupAll(".split-pane-divider")) {
if (divider(node, split.pane) == node) node.setVisible(!allocate);
}
allocateCollapsed(split.first);
allocateCollapsed(split.second);
}
private static void captureGeometry(Branch branch) {
if (branch instanceof Split split) {
if (!split.dragging && split.pane.getWidth() > 0 && split.pane.getHeight() > 0
if (!split.dragging && !split.collapsedAllocation && split.pane.getWidth() > 0 && split.pane.getHeight() > 0
&& !split.pane.getDividers().isEmpty()) {
split.position = split.pane.getDividers().getFirst().getPosition();
}
@@ -1,13 +1,16 @@
package de.neitzel.fx.docking;
import javafx.geometry.Side;
import javafx.geometry.Rectangle2D;
import java.util.List;
/** Immutable overview published after a completed layout change. */
public record DockLayoutView(List<Window> windows) {
public DockLayoutView { windows = List.copyOf(windows); }
public record Window(DockWindowId id, boolean main, List<Area> areas) {
/** Last committed floating-window bounds; main-window geometry belongs to the application. */
public record Window(DockWindowId id, boolean main, List<Area> areas, Rectangle2D bounds) {
public Window { areas = List.copyOf(areas); }
public Window(DockWindowId id, boolean main, List<Area> areas) { this(id, main, areas, null); }
}
/** Preferred side content extent; -1 means that dimension follows the available space. */
public record Area(DockAreaId id, List<Group> groups, LayoutNode root,
@@ -24,7 +27,10 @@ public record DockLayoutView(List<Window> windows) {
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,
DockableId selectedDockableId) implements LayoutNode {
DockableId selectedDockableId, boolean collapsed) implements LayoutNode {
public Group { dockableIds = List.copyOf(dockableIds); }
public Group(DockGroupId id, Side tabSide, List<DockableId> dockableIds, DockableId selectedDockableId) {
this(id, tabSide, dockableIds, selectedDockableId, false);
}
}
}
@@ -10,6 +10,13 @@ public sealed interface DockTarget {
static DockTarget group(DockGroupId id, TabPosition position) { return new Group(id, position); }
static DockTarget group(DockGroupId id) { return group(id, TabPosition.append()); }
static DockTarget split(DockGroupId id, Side side) { return new Split(id, side); }
static DockTarget floating() { return new Floating(null); }
static DockTarget floating(javafx.geometry.Rectangle2D bounds) {
return new Floating(Objects.requireNonNull(bounds, "bounds"));
}
static DockTarget returnToMain() { return new ReturnToMain(); }
record Floating(javafx.geometry.Rectangle2D bounds) implements DockTarget { }
record ReturnToMain() implements DockTarget { }
record Split(DockGroupId id, Side side) implements DockTarget {
public Split { Objects.requireNonNull(id, "id"); Objects.requireNonNull(side, "side"); }
}
@@ -0,0 +1,39 @@
package de.neitzel.fx.docking;
import javafx.geometry.Rectangle2D;
import javafx.stage.Screen;
import javafx.stage.Stage;
/** Fits requested floating frames to the visible part of an available screen. */
final class DockWindowBounds {
private DockWindowBounds() { }
static Rectangle2D defaults(Stage main) {
Rectangle2D screen = Screen.getPrimary().getVisualBounds();
double x = Double.isFinite(main.getX()) ? main.getX() + 40 : screen.getMinX() + 40;
double y = Double.isFinite(main.getY()) ? main.getY() + 40 : screen.getMinY() + 40;
return new Rectangle2D(x, y, 600, 400);
}
static boolean valid(Rectangle2D bounds) {
return Double.isFinite(bounds.getMinX()) && Double.isFinite(bounds.getMinY())
&& Double.isFinite(bounds.getWidth()) && Double.isFinite(bounds.getHeight())
&& bounds.getWidth() > 0 && bounds.getHeight() > 0;
}
static Rectangle2D fit(Rectangle2D requested) {
Rectangle2D screen = Screen.getScreensForRectangle(requested).stream()
.max(java.util.Comparator.comparingDouble(candidate -> overlap(requested, candidate.getVisualBounds())))
.orElse(Screen.getPrimary()).getVisualBounds();
double width = Math.min(requested.getWidth(), screen.getWidth());
double height = Math.min(requested.getHeight(), screen.getHeight());
double x = Math.clamp(requested.getMinX(), screen.getMinX(), screen.getMaxX() - width);
double y = Math.clamp(requested.getMinY(), screen.getMinY(), screen.getMaxY() - height);
return new Rectangle2D(x, y, width, height);
}
private static double overlap(Rectangle2D first, Rectangle2D second) {
return Math.max(0, Math.min(first.getMaxX(), second.getMaxX()) - Math.max(first.getMinX(), second.getMinX()))
* Math.max(0, Math.min(first.getMaxY(), second.getMaxY()) - Math.max(first.getMinY(), second.getMinY()));
}
}
@@ -0,0 +1,105 @@
package de.neitzel.fx.docking;
import javafx.animation.AnimationTimer;
import javafx.beans.InvalidationListener;
import javafx.geometry.Rectangle2D;
import javafx.stage.Stage;
import java.util.Objects;
/** Commits floating geometry only after native mouse buttons are released. */
final class DockWindowGeometry {
private final Stage stage;
private final Runnable onCommitted;
private final InvalidationListener geometryChanged = observable -> changed();
private final InvalidationListener visibilityChanged = observable -> watch();
private final AnimationTimer timer = new AnimationTimer() {
@Override public void handle(long now) {
if (captureIfReady()) onCommitted.run();
}
};
private Rectangle2D bounds;
private boolean dirty;
private boolean running;
private boolean disposed;
DockWindowGeometry(Stage stage, Runnable onCommitted) {
this.stage = Objects.requireNonNull(stage, "stage");
this.onCommitted = Objects.requireNonNull(onCommitted, "onCommitted");
bounds = current();
stage.xProperty().addListener(geometryChanged);
stage.yProperty().addListener(geometryChanged);
stage.widthProperty().addListener(geometryChanged);
stage.heightProperty().addListener(geometryChanged);
stage.showingProperty().addListener(visibilityChanged);
stage.focusedProperty().addListener(visibilityChanged);
}
Rectangle2D bounds() { return bounds; }
/** Includes an unfinished gesture that has returned to its original frame size. */
boolean hasPendingChanges() { return dirty; }
/**
* Completes pending geometry for a manager publication without invoking its callback.
* A gesture returning to the same frame still completes, because child split positions may have changed.
*/
boolean captureIfReady() {
if (disposed) return false;
Rectangle2D current = current();
if (current == null) return false;
if (current.equals(bounds) && !dirty) {
stop();
return false;
}
NativeMouseButtons.State buttons = NativeMouseButtons.state();
if (buttons != NativeMouseButtons.State.UP) {
if (buttons == NativeMouseButtons.State.UNKNOWN) stop();
return false;
}
bounds = current;
dirty = false;
stop();
return true;
}
private Rectangle2D current() {
double x = stage.getX();
double y = stage.getY();
double width = stage.getWidth();
double height = stage.getHeight();
return Double.isFinite(x) && Double.isFinite(y) && Double.isFinite(width) && Double.isFinite(height)
&& width > 0 && height > 0 ? new Rectangle2D(x, y, width, height) : null;
}
private void changed() {
dirty = true;
watch();
}
private void watch() {
if (!disposed && dirty && stage.isShowing()) {
if (!running) {
running = true;
timer.start();
}
} else stop();
}
private void stop() {
running = false;
timer.stop();
}
void dispose() {
if (disposed) return;
disposed = true;
stop();
stage.xProperty().removeListener(geometryChanged);
stage.yProperty().removeListener(geometryChanged);
stage.widthProperty().removeListener(geometryChanged);
stage.heightProperty().removeListener(geometryChanged);
stage.showingProperty().removeListener(visibilityChanged);
stage.focusedProperty().removeListener(visibilityChanged);
}
}
@@ -13,6 +13,7 @@ import java.util.Objects;
/** Existing live content with stable identity and bindable tab presentation. */
public final class Dockable {
@Getter @Setter private boolean mainWindowOnly;
@Getter private final DockableId id;
@Getter private final Node content;
@Getter @Setter private Supplier<? extends Node> focusTarget;
@@ -22,6 +22,8 @@ public final class DockingManager {
private final Stage stage;
private final DockPane pane;
private final PlacementRule placementRule;
private final DockTarget fallbackTarget;
private final java.util.function.Consumer<FloatingWindowConfiguration> floatingWindowCustomizer;
private final DockDragController drag;
private final DockCloseCoordinator closing;
private boolean updating;
@@ -29,7 +31,13 @@ public final class DockingManager {
private final Map<DockGroupId, Long> groupActivationOrder = new LinkedHashMap<>();
private final DockLayoutTree tree = new DockLayoutTree(this::publish, id -> !groupClosing(group(id)));
private final Map<DockAreaId, javafx.geometry.Side> edgeAreas = new LinkedHashMap<>();
private final java.util.Set<DockGroupId> allocatedGroupIds = new java.util.HashSet<>();
private final java.util.Set<DockAreaId> allocatedAreaIds = new java.util.HashSet<>();
private long nextGroupId;
private long nextWindowId;
private final Map<DockWindowId, FloatingWindow> floatingWindows = new LinkedHashMap<>();
private final Map<DockGroupId, DockWindowId> groupWindows = new LinkedHashMap<>();
private final Map<DockableId, ReturnLocation> returnTargets = new LinkedHashMap<>();
private final Map<DockableId, Dockable> dockables = new LinkedHashMap<>();
private final Map<DockableId, Node> previousFocus = new LinkedHashMap<>();
private final Map<DockableId, Long> activationOrder = new LinkedHashMap<>();
@@ -43,10 +51,15 @@ public final class DockingManager {
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 javafx.stage.Window owner(DockableId id) { return DockingManager.this.owner(containing(id)); }
@Override public void remove(DockableId id) { removeDockable(id); }
});
this.placementRule = Objects.requireNonNull(options.getPlacementRule(), "placementRule");
this.fallbackTarget = options.getFallbackTarget();
if (fallbackTarget != null && !(fallbackTarget instanceof DockTarget.Area) && !(fallbackTarget instanceof DockTarget.Group)) {
throw new IllegalArgumentException("The return fallback must identify an existing main-window area or group");
}
this.floatingWindowCustomizer = Objects.requireNonNull(options.getFloatingWindowCustomizer(), "floatingWindowCustomizer");
DockLayout initial = Objects.requireNonNull(pane.getInitialLayout(), "initialLayout");
validate(initial);
addGroup(initial.getCenter(), pane.surface::setCenter);
@@ -54,7 +67,9 @@ public final class DockingManager {
addEdgeGroup(initial.getRight(), javafx.geometry.Side.RIGHT);
addEdgeGroup(initial.getTop(), javafx.geometry.Side.TOP);
addEdgeGroup(initial.getBottom(), javafx.geometry.Side.BOTTOM);
tree.view().forEach(area -> allocatedAreaIds.add(area.id()));
drag = new DockDragController(this, pane, () -> groups.values().stream()
.filter(group -> !groupWindows.containsKey(group.id))
.map(group -> new DockDragController.GroupSurface(group.id, group.tabs, pane.edgeOf(group.tabs))).toList());
refreshEmptyGroups();
publish();
@@ -88,7 +103,13 @@ public final class DockingManager {
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");
}
Group group = receiver(destination);
Group group;
try {
group = receiver(destination);
} catch (FloatingPreparationFailure failure) {
return new ActionResult.Rejected(new DockFailure(DockFailure.Code.WINDOW_CREATION_FAILED,
dockable.getId(), "Floating window configuration failed", failure.getCause()));
}
int insertionIndex = destination instanceof ResolvedDockTarget.Insertion insertion ? insertion.index() : 0;
Tab tab = new Tab();
tab.setClosable(true);
@@ -100,13 +121,14 @@ public final class DockingManager {
tab.graphicProperty().bind(dockable.iconProperty());
tab.setContent(dockable.getContent());
tab.setUserData(dockable.getId());
drag.installTab(tab, dockable.getId());
dragFor(group).installTab(tab, dockable.getId());
dockables.put(dockable.getId(), dockable);
updating = true;
try {
group.tabs.getTabs().add(insertionIndex, tab);
group.tabs.getSelectionModel().select(tab);
refreshEmptyGroups();
revealGroup(group);
} finally {
updating = false;
}
@@ -149,9 +171,14 @@ public final class DockingManager {
requireFxThread();
Dockable dockable = dockables.get(id);
if (dockable == null) return rejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open");
if (((DockGroupPane) containing(id).tabs).isCollapsed() && !canChangeGroupGeometry(containing(id))) {
return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "Opening this group would resize a group awaiting close consent");
}
boolean revealed = revealGroup(containing(id));
Node target = focusTarget(dockable);
boolean changed = active.get() != dockable || stage.getScene().getFocusOwner() != target
|| (stage.isShowing() && !stage.isFocused());
Stage window = owner(containing(id));
boolean changed = revealed || active.get() != dockable || window.getScene().getFocusOwner() != target
|| (window.isShowing() && !window.isFocused());
for (Group group : groups.values()) {
for (Tab tab : group.tabs.getTabs()) {
if (id.equals(tab.getUserData())) {
@@ -166,7 +193,7 @@ public final class DockingManager {
}
}
setActive(dockable);
if (stage.isShowing()) stage.toFront();
if (window.isShowing()) window.toFront();
focus(dockable);
if (changed) publish();
return changed ? new ActionResult.Applied() : new ActionResult.NoChange();
@@ -191,7 +218,7 @@ public final class DockingManager {
boolean wasActive = active.get() == dockables.get(id);
updating = true;
try {
drag.uninstallTab(tab);
dragFor(group).uninstallTab(tab);
tab.textProperty().unbind();
tab.graphicProperty().unbind();
tab.setGraphic(null);
@@ -200,6 +227,7 @@ public final class DockingManager {
dockables.remove(id);
previousFocus.remove(id);
activationOrder.remove(id);
returnTargets.remove(id);
normalizeLayout(group.id);
} finally {
updating = false;
@@ -207,7 +235,8 @@ public final class DockingManager {
if (wasActive) {
Tab selected = group.tabs.getSelectionModel().getSelectedItem();
if (selected == null) {
selected = groups.values().stream().map(candidate -> candidate.tabs.getSelectionModel().getSelectedItem())
selected = groups.values().stream().filter(this::isGroupVisible)
.map(candidate -> candidate.tabs.getSelectionModel().getSelectedItem())
.filter(Objects::nonNull)
.max(java.util.Comparator.comparingLong(candidate ->
activationOrder.getOrDefault((DockableId) candidate.getUserData(), 0L)))
@@ -238,11 +267,19 @@ public final class DockingManager {
DockGroupId destination = switch (allowed.destination()) {
case ResolvedDockTarget.Insertion insertion -> insertion.groupId();
case ResolvedDockTarget.Split split -> split.groupId();
case ResolvedDockTarget.Detachment ignored -> null;
};
if (tree.normalizationAffects(containing(id).id, destination, this::groupClosing)) {
if (treeFor(containing(id)).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");
}
Group source = containing(id);
if (source.tabs.getTabs().size() == 1 && !source.id.equals(destination)
&& (source.definition.isReleaseSpaceWhenEmpty() || !source.definition.isPersistent())
&& !canChangeGroupGeometry(source)) {
return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id,
"Emptying this group would resize a group awaiting close consent");
}
}
return check;
}
@@ -254,17 +291,37 @@ public final class DockingManager {
if (check instanceof MoveCheck.NoChange) return new ActionResult.NoChange();
var destination = ((MoveCheck.Allowed) check).destination();
Group source = containing(id);
Group receiver = receiver(destination);
Group receiver;
try {
receiver = receiver(destination);
} catch (FloatingPreparationFailure failure) {
return new ActionResult.Rejected(new DockFailure(DockFailure.Code.WINDOW_CREATION_FAILED,
id, "Floating window configuration failed", failure.getCause()));
}
if (!groupWindows.containsKey(source.id) && groupWindows.containsKey(receiver.id)) {
int index = tabIndex(source, id);
TabPosition position = index + 1 < source.tabs.getTabs().size()
? TabPosition.before((DockableId) source.tabs.getTabs().get(index + 1).getUserData())
: index > 0 ? TabPosition.after((DockableId) source.tabs.getTabs().get(index - 1).getUserData())
: TabPosition.append();
returnTargets.put(id, new ReturnLocation(DockTarget.group(source.id, position),
new DockAreaId(source.definition.getDestinationId())));
}
DockDragController sourceDrag = dragFor(source);
DockDragController receiverDrag = dragFor(receiver);
int insertionIndex = destination instanceof ResolvedDockTarget.Insertion insertion ? insertion.index() : 0;
Tab tab = source.tabs.getTabs().get(tabIndex(source, id));
updating = true;
try {
tab.setContent(null);
if (sourceDrag != receiverDrag) sourceDrag.uninstallTab(tab);
source.tabs.getTabs().remove(tab);
receiver.tabs.getTabs().add(insertionIndex, tab);
if (sourceDrag != receiverDrag) receiverDrag.installTab(tab, id);
tab.setContent(dockables.get(id).getContent());
receiver.tabs.getSelectionModel().select(tab);
normalizeLayout(source.id);
revealGroup(receiver);
} finally {
updating = false;
}
@@ -277,11 +334,40 @@ public final class DockingManager {
private MoveCheck resolve(Dockable dockable, DockTarget target) {
DockableId id = dockable.getId();
Objects.requireNonNull(target, "target");
if (target instanceof DockTarget.Floating floating) {
javafx.geometry.Rectangle2D bounds = floating.bounds() == null
? DockWindowBounds.defaults(stage)
: floating.bounds();
if (!DockWindowBounds.valid(bounds)) return moveRejected(DockFailure.Code.INVALID_WINDOW_BOUNDS, id,
"Floating bounds must be finite with positive dimensions");
return checkPlacement(dockable, new ResolvedDockTarget.Detachment(DockWindowBounds.fit(bounds)));
}
if (target instanceof DockTarget.ReturnToMain) {
Group source = containing(id);
if (source != null && !groupWindows.containsKey(source.id)) return new MoveCheck.NoChange();
ReturnLocation remembered = returnTargets.get(id);
if (remembered != null) {
MoveCheck result = resolveMainTarget(dockable, remembered.target());
if (!(result instanceof MoveCheck.Rejected)) return result;
if (((MoveCheck.Rejected) result).failure().code() == DockFailure.Code.TARGET_NOT_FOUND) {
MoveCheck areaResult = resolveMainTarget(dockable, DockTarget.area(remembered.areaId()));
if (!(areaResult instanceof MoveCheck.Rejected)) return areaResult;
}
}
if (fallbackTarget != null) return resolveMainTarget(dockable, fallbackTarget);
List<DockLayoutView.Area> mainAreas = tree.view();
return mainAreas.isEmpty() ? moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "No main-window destination")
: resolveMainTarget(dockable, DockTarget.area(mainAreas.getFirst().id()));
}
if (target instanceof DockTarget.Split split) {
Group receiver = group(split.id());
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");
if (containing(id) == receiver && receiver.tabs.getTabs().size() == 1) return new MoveCheck.NoChange();
if (((DockGroupPane) receiver.tabs).isCollapsed() && !canChangeGroupGeometry(receiver)) {
return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id,
"Opening this group would resize a group awaiting close consent");
}
if (!receiver.definition.getSplitDirections().allows(split.side())) {
return moveRejected(DockFailure.Code.SPLIT_DISABLED, id, "Splitting is disabled in this direction");
}
@@ -296,7 +382,9 @@ public final class DockingManager {
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
List<Group> candidates = java.util.stream.Stream.concat(java.util.stream.Stream.of(tree),
floatingWindows.values().stream().map(FloatingWindow::tree))
.flatMap(candidate -> candidate.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) {
@@ -328,12 +416,37 @@ public final class DockingManager {
if (index > oldIndex) index--;
if (index == oldIndex) return new MoveCheck.NoChange();
}
if (((DockGroupPane) receiver.tabs).isCollapsed() && !canChangeGroupGeometry(receiver)) {
return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id,
"Opening this group would resize a group awaiting close consent");
}
var resolved = new ResolvedDockTarget.Insertion(receiver.id, index);
return checkPlacement(dockable, resolved);
}
private MoveCheck resolveMainTarget(Dockable dockable, DockTarget target) {
MoveCheck result = resolve(dockable, target);
if (result instanceof MoveCheck.NoChange && groupWindows.containsKey(containing(dockable.getId()).id)) {
return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, dockable.getId(), "The return destination is not in the main window");
}
if (result instanceof MoveCheck.Allowed allowed
&& allowed.destination() instanceof ResolvedDockTarget.Insertion insertion
&& groupWindows.containsKey(insertion.groupId())) {
return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, dockable.getId(), "The return destination is not in the main window");
}
return result;
}
private MoveCheck checkPlacement(Dockable dockable, ResolvedDockTarget resolved) {
DockableId id = dockable.getId();
boolean floating = switch (resolved) {
case ResolvedDockTarget.Detachment ignored -> true;
case ResolvedDockTarget.Insertion insertion -> groupWindows.containsKey(insertion.groupId());
case ResolvedDockTarget.Split split -> groupWindows.containsKey(split.groupId());
};
if (dockable.isMainWindowOnly() && floating) {
return moveRejected(DockFailure.Code.MAIN_WINDOW_ONLY, id, "This Dockable must remain in the main window");
}
try {
Optional<DockFailure> failure = Objects.requireNonNull(placementRule.check(dockable, resolved), "Placement rule result");
if (failure.isPresent()) return new MoveCheck.Rejected(failure.get());
@@ -345,11 +458,134 @@ public final class DockingManager {
}
private void normalizeLayout(DockGroupId source) {
for (DockGroupId id : tree.normalize(source)) {
DockWindowId ownerId = groupWindows.get(source);
for (DockGroupId id : treeFor(group(source)).normalize(source)) {
groups.remove(id);
groupWindows.remove(id);
groupActivationOrder.remove(id);
}
refreshEmptyGroups();
if (ownerId != null && groups.values().stream().filter(group -> ownerId.equals(groupWindows.get(group.id)))
.allMatch(group -> group.tabs.getTabs().isEmpty())) {
FloatingWindow empty = floatingWindows.remove(ownerId);
empty.drag.dispose();
empty.geometry.dispose();
empty.stage.getScene().focusOwnerProperty().removeListener(focusListener);
empty.stage.hide();
empty.pane.manager = null;
empty.stage.getProperties().remove(ATTACHMENT_KEY);
var remaining = groups.keySet().stream().filter(id -> ownerId.equals(groupWindows.get(id))).toList();
remaining.forEach(id -> { groups.remove(id); groupWindows.remove(id); groupActivationOrder.remove(id); });
}
}
/** Applies explicitly supplied settings as one validated group change. */
public ActionResult updateGroup(DockGroupId id, DockGroupChanges changes) {
requireFxThread();
Objects.requireNonNull(changes, "changes");
Group group = group(Objects.requireNonNull(id, "id"));
if (group == null) return rejected(DockFailure.Code.TARGET_NOT_FOUND, null, "Group does not exist");
if (groupClosing(group)) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "A close request covers this group");
DockGroupChanges resolved = changes.resolved(group.definition);
DockGroupDefinition candidate = new DockGroupDefinition(group.definition.getDestinationId());
resolved.applyTo(candidate);
try {
validate(candidate, new java.util.HashSet<>());
} catch (IllegalArgumentException failure) {
return rejected(DockFailure.Code.INVALID_GROUP_CONFIGURATION, null, failure.getMessage());
}
DockEdgeRegion extentOwner = null;
for (Node ancestor = group.tabs.getParent(); ancestor != null; ancestor = ancestor.getParent()) {
if (ancestor instanceof DockEdgeRegion edge) {
extentOwner = edge;
break;
}
}
boolean changesExtent = extentOwner != null
&& extentOwner.changesPreferredExtent(changes.getPreferredWidth(), changes.getPreferredHeight());
if (!changesExtent && resolved.equals(DockGroupChanges.builder().build().resolved(group.definition))) {
return new ActionResult.NoChange();
}
DockGroupDefinition existing = group.definition;
boolean changesGeometry = changesExtent || existing.getTabSide() != candidate.getTabSide()
|| existing.getPreferredWidth() != candidate.getPreferredWidth()
|| existing.getPreferredHeight() != candidate.getPreferredHeight()
|| existing.getMinimumWidth() != candidate.getMinimumWidth()
|| existing.getMinimumHeight() != candidate.getMinimumHeight()
|| (group.tabs.getTabs().isEmpty() && (existing.isVisibleWhenEmpty() != candidate.isVisibleWhenEmpty()
|| existing.isReleaseSpaceWhenEmpty() != candidate.isReleaseSpaceWhenEmpty()))
|| (((DockGroupPane) group.tabs).isCollapsed() && !candidate.isCollapsible());
if (changesGeometry && !canChangeGroupGeometry(group, true)) {
return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "The group change would resize content covered by a close request");
}
boolean wasUpdating = updating;
updating = true;
try {
resolved.applyTo(group.definition);
group.tabs.setSide(candidate.getTabSide());
group.tabs.requestLayout();
if (extentOwner != null) {
extentOwner.updatePreferredExtent(changes.getPreferredWidth(), changes.getPreferredHeight());
}
if (!candidate.isCollapsible() && revealGroup(group)) {
Tab selected = group.tabs.getSelectionModel().getSelectedItem();
if (selected != null) {
setActive(dockables.get((DockableId) selected.getUserData()));
focus(active.get());
}
}
refreshEmptyGroups();
} finally {
updating = wasUpdating;
}
publish();
return new ActionResult.Applied();
}
public ActionResult setGroupCollapsed(DockGroupId id, boolean collapsed) {
requireFxThread();
Group group = group(Objects.requireNonNull(id, "id"));
if (group == null) return rejected(DockFailure.Code.TARGET_NOT_FOUND, null, "Group does not exist");
if (groupClosing(group)) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "A close request covers this group");
if (collapsed && !group.definition.isCollapsible()) {
return rejected(DockFailure.Code.COLLAPSE_DISABLED, null, "This group cannot be collapsed");
}
DockGroupPane tabs = (DockGroupPane) group.tabs;
if (tabs.isCollapsed() == collapsed) return new ActionResult.NoChange();
if (!canChangeGroupGeometry(group)) {
return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "The group change would resize content covered by a close request");
}
tabs.setCollapsed(collapsed);
if (collapsed) {
if (active.get() != null && containing(active.get().getId()) == group) setActive(selectedVisibleFallback());
tabs.focusSelectedHeader();
} else {
Tab selected = tabs.getSelectionModel().getSelectedItem();
if (selected != null) {
setActive(dockables.get((DockableId) selected.getUserData()));
focus(active.get());
}
}
publish();
return new ActionResult.Applied();
}
private boolean revealGroup(Group group) {
DockGroupPane tabs = (DockGroupPane) group.tabs;
if (!tabs.isCollapsed()) return false;
tabs.setCollapsed(false);
return true;
}
private boolean isGroupVisible(Group group) {
return group.tabs.isVisible() && !((DockGroupPane) group.tabs).isCollapsed();
}
private Dockable selectedVisibleFallback() {
return groups.values().stream().filter(this::isGroupVisible)
.map(candidate -> candidate.tabs.getSelectionModel().getSelectedItem()).filter(Objects::nonNull)
.max(java.util.Comparator.comparingLong(tab -> activationOrder.getOrDefault((DockableId) tab.getUserData(), 0L)))
.map(tab -> dockables.get((DockableId) tab.getUserData())).orElse(null);
}
private void refreshEmptyGroups() {
@@ -389,7 +625,35 @@ public final class DockingManager {
edgeAreas.put(new DockAreaId(definition.getDestinationId()), side);
DockAreaId areaId = new DockAreaId(definition.getDestinationId());
addGroup(definition, node -> pane.setArea(side, node,
() -> tree.groups(areaId).stream().noneMatch(this::groupClosing), this::publish));
() -> canResizeEdge(areaId, side), this::publish));
}
private boolean canResizeEdge(DockAreaId areaId, javafx.geometry.Side side) {
if (tree.groups(areaId).stream().anyMatch(this::groupClosing)) return false;
for (Group candidate : groups.values()) {
if (groupWindows.containsKey(candidate.id) || !groupClosing(candidate)) continue;
if (contains(pane.surface.getCenter(), candidate.tabs)) return false;
javafx.geometry.Side otherSide = pane.edgeOf(candidate.tabs);
if (side.isHorizontal() && otherSide != null && otherSide.isVertical()) return false;
}
return true;
}
private boolean canChangeGroupGeometry(Group group) {
return canChangeGroupGeometry(group, false);
}
private boolean canChangeGroupGeometry(Group group, boolean changingOuterExtent) {
if (treeFor(group).geometryAffects(group.id, this::groupClosing)) return false;
if (groupWindows.containsKey(group.id)) return true;
for (var entry : edgeAreas.entrySet()) {
List<Group> areaGroups = tree.groups(entry.getKey());
if (!areaGroups.contains(group)) continue;
boolean onlyExpandedGroup = areaGroups.stream().filter(candidate -> candidate != group)
.allMatch(candidate -> !candidate.tabs.isManaged() || ((DockGroupPane) candidate.tabs).isCollapsed());
if (changingOuterExtent || onlyExpandedGroup) return canResizeEdge(entry.getKey(), entry.getValue());
}
return true;
}
private void addGroup(DockLayoutNode definition, java.util.function.Consumer<javafx.scene.Node> place) {
@@ -407,16 +671,18 @@ public final class DockingManager {
captured.setMinimumHeight(definition.getMinimumHeight());
captured.setSplitDirections(definition.getSplitDirections());
captured.setPersistent(definition.isPersistent());
captured.setCollapsible(definition.isCollapsible());
captured.setVisibleWhenEmpty(definition.isVisibleWhenEmpty());
captured.setReleaseSpaceWhenEmpty(definition.isReleaseSpaceWhenEmpty());
TabPane tabs = new TabPane();
TabPane tabs = new DockGroupPane(captured);
tabs.setSide(captured.getTabSide());
tabs.setPrefSize(captured.getPreferredWidth(), captured.getPreferredHeight());
tabs.setMinSize(captured.getMinimumWidth(), captured.getMinimumHeight());
Group group = new Group(id, tabs, captured);
allocatedGroupIds.add(id);
groups.put(id, group);
((DockGroupPane) tabs).installHeaderActions(tab -> activate((DockableId) tab.getUserData()),
() -> setGroupCollapsed(id, true));
tabs.getSelectionModel().selectedItemProperty().addListener((observable, old, selected) -> {
if (!updating && selected != null) {
if (!updating && selected != null && isGroupVisible(group)) {
setActive(dockables.get((DockableId) selected.getUserData()));
focus(active.get());
publish();
@@ -427,12 +693,15 @@ public final class DockingManager {
private Group receiver(ResolvedDockTarget destination) {
if (destination instanceof ResolvedDockTarget.Insertion insertion) return group(insertion.groupId());
if (destination instanceof ResolvedDockTarget.Detachment detachment) return createFloatingGroup(detachment.bounds());
ResolvedDockTarget.Split split = (ResolvedDockTarget.Split) destination;
Group target = group(split.groupId());
DockGroupId id;
do { id = new DockGroupId("group-" + ++nextGroupId); } while (groups.containsKey(id));
do { id = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(id));
Group added = createGroup(id, target.definition);
tree.split(target, added, split.side());
DockWindowId window = groupWindows.get(target.id);
if (window != null) groupWindows.put(added.id, window);
treeFor(target).split(target, added, split.side());
return added;
}
@@ -449,7 +718,7 @@ public final class DockingManager {
private void rememberFocus(Node current) {
if (current == null) return;
for (Dockable dockable : dockables.values()) {
if (contains(dockable.getContent(), current)) {
if (contains(dockable.getContent(), current) && isGroupVisible(containing(dockable.getId()))) {
previousFocus.put(dockable.getId(), current);
setActive(dockable);
return;
@@ -472,7 +741,14 @@ public final class DockingManager {
private void focus(Dockable dockable) {
if (dockable == null) return;
pane.applyCss();
Stage window = owner(containing(dockable.getId()));
window.getScene().getRoot().applyCss();
window.getScene().getRoot().layout();
if (window != stage && !window.isShowing()) window.show();
if (window.isShowing()) {
window.toFront();
window.requestFocus();
}
Node target = focusTarget(dockable);
target.requestFocus();
}
@@ -524,6 +800,12 @@ public final class DockingManager {
stage.getScene().getRoot().applyCss();
stage.getScene().getRoot().layout();
tree.captureGeometry();
for (FloatingWindow window : floatingWindows.values()) {
window.pane.applyCss();
window.pane.layout();
window.geometry.captureIfReady();
if (!window.geometry.hasPendingChanges()) window.tree.captureGeometry();
}
} finally {
updating = wasUpdating;
}
@@ -534,9 +816,78 @@ public final class DockingManager {
return new DockLayoutView.Area(area.id(), area.groups(), area.root(),
side.isVertical() ? extent : -1, side.isHorizontal() ? extent : -1);
}).toList();
layout.set(new DockLayoutView(List.of(new DockLayoutView.Window(new DockWindowId("main"), true, areas))));
var windows = new java.util.ArrayList<DockLayoutView.Window>();
windows.add(new DockLayoutView.Window(new DockWindowId("main"), true, areas));
floatingWindows.values().forEach(window -> windows.add(new DockLayoutView.Window(
window.id, false, window.tree.view(), window.geometry.bounds())));
layout.set(new DockLayoutView(windows));
}
private Stage owner(Group group) {
DockWindowId id = group == null ? null : groupWindows.get(group.id);
return id == null ? stage : floatingWindows.get(id).stage;
}
private DockLayoutTree treeFor(Group group) {
DockWindowId id = groupWindows.get(group.id);
return id == null ? tree : floatingWindows.get(id).tree;
}
private DockDragController dragFor(Group group) {
DockWindowId id = groupWindows.get(group.id);
return id == null ? drag : floatingWindows.get(id).drag;
}
private Group createFloatingGroup(javafx.geometry.Rectangle2D bounds) {
FloatingWindowConfiguration configuration = new FloatingWindowConfiguration();
try {
floatingWindowCustomizer.accept(configuration);
configuration.getIcons().forEach(Objects::requireNonNull);
configuration.getStylesheets().forEach(Objects::requireNonNull);
} catch (RuntimeException failure) {
throw new FloatingPreparationFailure(failure);
}
DockWindowId candidateId;
do { candidateId = new DockWindowId("floating-" + ++nextWindowId); }
while (!allocatedAreaIds.add(new DockAreaId(candidateId.value())));
DockWindowId windowId = candidateId;
DockPane floatingPane = new DockPane();
Stage floatingStage = new Stage();
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
floatingStage.setTitle(configuration.getTitle());
floatingStage.getIcons().setAll(configuration.getIcons());
floatingStage.getScene().getStylesheets().setAll(configuration.getStylesheets());
floatingStage.setX(bounds.getMinX());
floatingStage.setY(bounds.getMinY());
floatingStage.setWidth(bounds.getWidth());
floatingStage.setHeight(bounds.getHeight());
DockLayoutTree floatingTree = new DockLayoutTree(this::publish, id -> !groupClosing(group(id)));
DockGroupId groupId;
do { groupId = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(groupId));
DockGroupDefinition definition = new DockGroupDefinition(windowId.value());
definition.setPersistent(false);
Group group = createGroup(groupId, definition);
groupWindows.put(group.id, windowId);
floatingTree.addArea(definition, floatingPane.surface::setCenter, ignored -> group);
DockDragController floatingDrag = new DockDragController(this, floatingPane, () -> groups.values().stream()
.filter(candidate -> windowId.equals(groupWindows.get(candidate.id)))
.map(candidate -> new DockDragController.GroupSurface(candidate.id, candidate.tabs)).toList());
DockWindowGeometry geometry = new DockWindowGeometry(floatingStage, this::publish);
floatingWindows.put(windowId, new FloatingWindow(windowId, floatingStage, floatingPane, floatingTree, floatingDrag, geometry));
floatingPane.manager = this;
floatingStage.getProperties().put(ATTACHMENT_KEY, this);
floatingStage.getScene().focusOwnerProperty().addListener(focusListener);
return group;
}
private static final class FloatingPreparationFailure extends RuntimeException {
FloatingPreparationFailure(RuntimeException cause) { super(cause); }
}
private record FloatingWindow(DockWindowId id, Stage stage, DockPane pane, DockLayoutTree tree,
DockDragController drag, DockWindowGeometry geometry) { }
private record ReturnLocation(DockTarget target, DockAreaId areaId) { }
private static ActionResult rejected(DockFailure.Code code, DockableId id, String message) {
return new ActionResult.Rejected(new DockFailure(code, id, message, null));
}
@@ -8,4 +8,6 @@ import java.util.Optional;
@Getter @Setter
public final class DockingOptions {
private PlacementRule placementRule = (dockable, target) -> Optional.empty();
private DockTarget fallbackTarget;
private java.util.function.Consumer<FloatingWindowConfiguration> floatingWindowCustomizer = configuration -> { };
}
@@ -0,0 +1,15 @@
package de.neitzel.fx.docking;
import javafx.scene.image.Image;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/** Appearance supplied before a managed window appears; its Stage and Scene remain manager-owned. */
public final class FloatingWindowConfiguration {
@Getter @Setter private String title = "Docking";
@Getter private final List<Image> icons = new ArrayList<>();
@Getter private final List<String> stylesheets = new ArrayList<>();
}
@@ -0,0 +1,176 @@
package de.neitzel.fx.docking;
import lombok.extern.slf4j.Slf4j;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
/** Narrow, read-only native mouse state. Unknown input state never means release. */
@Slf4j
final class NativeMouseButtons {
enum State { DOWN, UP, UNKNOWN }
@FunctionalInterface private interface Query { State sample() throws Throwable; }
private static boolean failed;
private NativeMouseButtons() { }
private static final class Backend {
private static final Query QUERY = create();
}
/** Called on the JavaFX thread by floating-window geometry trackers. */
static State state() {
if (failed || Backend.QUERY == null) return State.UNKNOWN;
try {
return Backend.QUERY.sample();
} catch (Throwable failure) {
if (failure instanceof Error error) throw error;
failed = true;
log.warn("Native mouse state failed; floating-window geometry remains at its last committed bounds", failure);
return State.UNKNOWN;
}
}
private static Query create() {
try {
String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
if (os.contains("mac")) return mac();
if (os.contains("win")) return windows();
if (os.contains("linux") && !present("WAYLAND_DISPLAY")
&& !"wayland".equalsIgnoreCase(System.getenv("XDG_SESSION_TYPE"))
&& !"wayland".equalsIgnoreCase(System.getenv("GDK_BACKEND")) && present("DISPLAY")) return x11();
log.warn("Native mouse-state observation is unavailable for this desktop backend; floating-window bounds remain committed");
} catch (RuntimeException | LinkageError failure) {
log.warn("Native mouse-state observation is unavailable; enable native access for the library module. Floating-window bounds remain committed", failure);
} catch (Throwable failure) {
if (failure instanceof Error error) throw error;
log.warn("Native mouse-state initialization failed; floating-window bounds remain committed", failure);
}
return null;
}
private static boolean present(String name) {
String value = System.getenv(name);
return value != null && !value.isBlank();
}
private static Query mac() {
Linker linker = Linker.nativeLinker();
if (!ValueLayout.JAVA_BOOLEAN.equals(linker.canonicalLayouts().get("bool"))) {
throw new IllegalStateException("Unsupported CoreGraphics bool ABI");
}
// The String overload also loads frameworks supplied only by the macOS dyld cache.
SymbolLookup library = SymbolLookup.libraryLookup(
"/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics", Arena.global());
MethodHandle button = linker.downcallHandle(library.findOrThrow("CGEventSourceButtonState"),
FunctionDescriptor.of(ValueLayout.JAVA_BOOLEAN, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
return () -> {
// Combined-session state includes accessibility and posted input; check both primary mappings and middle.
for (int number = 0; number <= 2; number++) {
if ((boolean) button.invokeExact(0, number)) return State.DOWN;
}
return State.UP;
};
}
private static Query windows() {
Linker linker = Linker.nativeLinker();
SymbolLookup library = SymbolLookup.libraryLookup("user32.dll", Arena.global());
MethodHandle button = linker.downcallHandle(library.findOrThrow("GetAsyncKeyState"),
FunctionDescriptor.of(ValueLayout.JAVA_SHORT, ValueLayout.JAVA_INT));
MethodHandle foreground = linker.downcallHandle(library.findOrThrow("GetForegroundWindow"),
FunctionDescriptor.of(ValueLayout.ADDRESS));
MethodHandle owner = linker.downcallHandle(library.findOrThrow("GetWindowThreadProcessId"),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
return () -> {
// Physical buttons, including swapped primary buttons and the two extra buttons.
for (int key : new int[] {1, 2, 4, 5, 6}) {
if ((short) button.invokeExact(key) < 0) return State.DOWN;
}
// A zero key state can mean inaccessible input. Accept up only for our foreground process.
MemorySegment window = (MemorySegment) foreground.invokeExact();
if (window.equals(MemorySegment.NULL)) return State.UNKNOWN;
try (Arena arena = Arena.ofConfined()) {
MemorySegment process = arena.allocate(ValueLayout.JAVA_INT);
int thread = (int) owner.invokeExact(window, process);
return thread != 0 && Integer.toUnsignedLong(process.get(ValueLayout.JAVA_INT, 0)) == ProcessHandle.current().pid()
? State.UP : State.UNKNOWN;
}
};
}
/** Both shutdown and sampling hold this monitor before accessing the display. */
private static final class X11ConnectionState {
private boolean closed;
}
private static Query x11() throws Throwable {
Linker linker = Linker.nativeLinker();
if (!ValueLayout.JAVA_LONG.equals(linker.canonicalLayouts().get("long"))) {
throw new IllegalStateException("Unsupported X11 Window ABI");
}
SymbolLookup library = SymbolLookup.libraryLookup("libX11.so.6", Arena.global());
MethodHandle open = linker.downcallHandle(library.findOrThrow("XOpenDisplay"),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS));
MethodHandle root = linker.downcallHandle(library.findOrThrow("XDefaultRootWindow"),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
MethodHandle query = linker.downcallHandle(library.findOrThrow("XQueryPointer"),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.JAVA_LONG,
ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.ADDRESS,
ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
MethodHandle close = linker.downcallHandle(library.findOrThrow("XCloseDisplay"),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS));
X11ConnectionState connection = new X11ConnectionState();
MemorySegment display = (MemorySegment) open.invokeExact(MemorySegment.NULL);
if (display.equals(MemorySegment.NULL)) throw new IllegalStateException("Cannot open the X11 display");
try {
long rootWindow = (long) root.invokeExact(display);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
synchronized (connection) {
if (connection.closed) return;
connection.closed = true;
try { int ignored = (int) close.invokeExact(display); }
catch (Throwable failure) {
if (failure instanceof Error error) throw error;
log.debug("Closing native mouse-state X11 connection failed", failure);
}
}
}, "docking-mouse-state-cleanup"));
return () -> {
synchronized (connection) {
if (connection.closed) return State.UNKNOWN;
try (Arena arena = Arena.ofConfined()) {
MemorySegment rootResult = arena.allocate(ValueLayout.JAVA_LONG);
MemorySegment child = arena.allocate(ValueLayout.JAVA_LONG);
MemorySegment rootX = arena.allocate(ValueLayout.JAVA_INT);
MemorySegment rootY = arena.allocate(ValueLayout.JAVA_INT);
MemorySegment windowX = arena.allocate(ValueLayout.JAVA_INT);
MemorySegment windowY = arena.allocate(ValueLayout.JAVA_INT);
MemorySegment mask = arena.allocate(ValueLayout.JAVA_INT);
int valid = (int) query.invokeExact(display, rootWindow, rootResult, child,
rootX, rootY, windowX, windowY, mask);
if (valid == 0) return State.UNKNOWN;
return (mask.get(ValueLayout.JAVA_INT, 0) & 0x1f00) != 0 ? State.DOWN : State.UP;
}
}
};
} catch (Throwable failure) {
synchronized (connection) {
if (!connection.closed) {
connection.closed = true;
try { int ignored = (int) close.invokeExact(display); }
catch (Throwable cleanup) {
if (cleanup != failure) failure.addSuppressed(cleanup);
}
}
}
throw failure;
}
}
}
@@ -2,6 +2,7 @@ package de.neitzel.fx.docking;
/** Concrete placement checked against the current layout, without allocating IDs. */
public sealed interface ResolvedDockTarget {
record Detachment(javafx.geometry.Rectangle2D bounds) implements ResolvedDockTarget { }
record Split(DockGroupId groupId, javafx.geometry.Side side) implements ResolvedDockTarget { }
record Insertion(DockGroupId groupId, int index) implements ResolvedDockTarget { }
}
@@ -0,0 +1,434 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** Group presentation is exercised through public operations and the rendered JavaFX surface. */
class CollapseDockGroupsTest {
@BeforeAll
static void startJavaFx() throws InterruptedException { FxThread.start(); }
@Test
void collapsingAnEdgeGroupKeepsItsHeadersAndReleasesItsContentSpace() throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT);
tools.setCollapsible(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());
manager.open(new Dockable(new DockableId("editor"), new TextArea()), DockTarget.area("editors"));
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
project.setTitle("Project");
project.setIcon(new Label("P"));
manager.open(project, DockTarget.area("tools"));
TabPane tabs = pane.lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == project.getContent()))
.findFirst().orElseThrow();
double expandedWidth = tabs.getWidth();
assertInstanceOf(ActionResult.Applied.class, manager.setGroupCollapsed(new DockGroupId("tools"), true));
DockLayoutView.Group group = manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().equals(new DockAreaId("tools"))).findFirst().orElseThrow().groups().getFirst();
assertTrue(group.collapsed());
assertTrue(tabs.lookup(".tab-header-area").isVisible());
assertFalse(tabs.lookup(".tab-content-area").isVisible());
assertTrue(tabs.getWidth() < expandedWidth / 2, "The whole group releases its content width");
assertEquals(new DockableId("editor"), manager.activeDockable().getId());
assertInstanceOf(ActionResult.Applied.class, manager.setGroupCollapsed(new DockGroupId("tools"), false));
assertSame(project.getContent(), pane.getScene().getFocusOwner(),
"Reopening the same selected tab restores keyboard focus into its content");
assertTrue(visibleThroughParents(project.getContent()));
});
}
@Test
void clickingProjectThenChangedFilesCollapsesAndReopensTheSharedGroup() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
TabPane tabs = fixture.tabs();
double width = tabs.getWidth();
javafx.scene.Node projectHeader = header(tabs, fixture.project().getId());
click(projectHeader);
assertTrue(group(fixture.manager()).collapsed());
assertFalse(visibleThroughParents(fixture.project().getContent()), "The selected tab content is hidden, not just the first tab");
assertSame(projectHeader, fixture.pane().getScene().getFocusOwner());
assertEquals(new DockableId("editor"), fixture.manager().activeDockable().getId());
click(header(tabs, fixture.changes().getId()));
assertFalse(group(fixture.manager()).collapsed());
assertSame(fixture.changes(), fixture.manager().activeDockable());
assertTrue(visibleThroughParents(fixture.changes().getContent()));
assertSame(fixture.changes().getContent(), tabs.getSelectionModel().getSelectedItem().getContent());
assertEquals(width, tabs.getWidth(), 1);
});
}
@Test
void aGroupUpdateAppliesOnlyExplicitSettingsTogetherIncludingFalse() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
DockingManager manager = fixture.manager();
DockGroupId tools = new DockGroupId("tools");
assertInstanceOf(ActionResult.Rejected.class,
manager.setGroupCollapsed(new DockGroupId("editors"), true));
manager.setGroupCollapsed(tools, true);
var changes = new java.util.ArrayList<DockLayoutView>();
manager.layoutProperty().addListener((observable, old, current) -> changes.add(current));
assertInstanceOf(ActionResult.Applied.class, manager.updateGroup(tools, DockGroupChanges.builder()
.preferredWidth(260.0).tabSide(Side.LEFT).collapsible(false).build()));
assertEquals(1, changes.size());
assertFalse(group(manager).collapsed());
assertEquals(Side.LEFT, group(manager).tabSide());
assertEquals(260, fixture.tabs().getWidth(), 1);
assertEquals(150, fixture.tabs().prefHeight(-1), "Unspecified dimensions are retained");
ActionResult.Rejected disabled = assertInstanceOf(ActionResult.Rejected.class,
manager.setGroupCollapsed(tools, true));
assertEquals(DockFailure.Code.COLLAPSE_DISABLED, disabled.failure().code());
DockLayoutView beforeInvalid = manager.layout();
assertInstanceOf(ActionResult.Rejected.class, manager.updateGroup(tools, DockGroupChanges.builder()
.tabSide(Side.BOTTOM).preferredWidth(-1.0).build()));
assertEquals(beforeInvalid, manager.layout());
assertEquals(Side.LEFT, fixture.tabs().getSide());
assertEquals(1, changes.size());
assertInstanceOf(ActionResult.NoChange.class, manager.updateGroup(tools, DockGroupChanges.builder().build()));
});
}
@Test
void escapeReturnsFocusToTheSymbolAndActivationReopensTheRequestedTab() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
var changes = new java.util.ArrayList<DockLayoutView>();
fixture.manager().layoutProperty().addListener((observable, old, current) -> changes.add(current));
fixture.project().getContent().fireEvent(new javafx.scene.input.KeyEvent(
javafx.scene.input.KeyEvent.KEY_PRESSED, "", "", javafx.scene.input.KeyCode.ESCAPE,
false, false, false, false));
assertTrue(group(fixture.manager()).collapsed());
assertEquals(1, changes.size());
assertSame(header(fixture.tabs(), fixture.project().getId()), fixture.pane().getScene().getFocusOwner());
assertEquals(new DockableId("editor"), fixture.manager().activeDockable().getId());
assertInstanceOf(ActionResult.Applied.class, fixture.manager().activate(fixture.changes().getId()));
assertFalse(group(fixture.manager()).collapsed());
assertSame(fixture.changes(), fixture.manager().activeDockable());
assertTrue(visibleThroughParents(fixture.changes().getContent()));
assertEquals(2, changes.size());
});
}
@Test
void closingTheLastVisibleContentDoesNotActivateACollapsedGroup() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
fixture.manager().setGroupCollapsed(new DockGroupId("tools"), true);
assertEquals(new DockableId("editor"), fixture.manager().activeDockable().getId());
var closed = fixture.manager().requestTabClose(new DockableId("editor"));
assertInstanceOf(CloseResult.Closed.class, closed.toCompletableFuture().join());
assertNull(fixture.manager().activeDockable());
assertTrue(group(fixture.manager()).collapsed());
});
}
@Test
void aPendingCenterCloseProtectsItsGeometryFromToolGroupChanges() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
DockingManager manager = fixture.manager();
var consent = new java.util.concurrent.CompletableFuture<CloseConsent>();
Dockable editor = manager.findDockable(new DockableId("editor")).orElseThrow();
editor.setCloseCheck(request -> consent);
manager.requestTabClose(editor.getId());
DockGroupId tools = new DockGroupId("tools");
try {
DockLayoutView before = manager.layout();
ActionResult.Rejected collapse = assertInstanceOf(ActionResult.Rejected.class,
manager.setGroupCollapsed(tools, true));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, collapse.failure().code());
ActionResult.Rejected resize = assertInstanceOf(ActionResult.Rejected.class,
manager.updateGroup(tools, DockGroupChanges.builder().preferredWidth(300).build()));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, resize.failure().code());
assertEquals(before, manager.layout());
assertInstanceOf(ActionResult.Applied.class,
manager.updateGroup(tools, DockGroupChanges.builder().splitDirections(SplitDirections.NONE).build()),
"Non-geometric settings remain independent of a neighboring close");
} finally {
consent.complete(CloseConsent.VETO);
}
assertInstanceOf(ActionResult.Applied.class, manager.setGroupCollapsed(tools, true));
assertInstanceOf(ActionResult.Applied.class,
manager.updateGroup(tools, DockGroupChanges.builder().preferredWidth(300).build()));
var secondConsent = new java.util.concurrent.CompletableFuture<CloseConsent>();
editor.setCloseCheck(request -> secondConsent);
manager.requestTabClose(editor.getId());
try {
assertInstanceOf(ActionResult.NoChange.class,
manager.move(fixture.project().getId(), DockTarget.group(tools)),
"A move that leaves a collapsed group unchanged remains allowed");
ActionResult.Rejected activation = assertInstanceOf(ActionResult.Rejected.class,
manager.activate(fixture.project().getId()));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, activation.failure().code());
assertTrue(group(manager).collapsed());
} finally {
secondConsent.complete(CloseConsent.VETO);
}
manager.setGroupCollapsed(tools, false);
assertEquals(300, fixture.tabs().getWidth(), 1);
});
}
@Test
void splitGroupsInheritSettingsAndSubsequentUpdatesRemainIndependent() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
DockingManager manager = fixture.manager();
DockGroupId original = new DockGroupId("tools");
manager.updateGroup(original, DockGroupChanges.builder().preferredWidth(260)
.minimumHeight(180).splitDirections(SplitDirections.VERTICAL).build());
assertInstanceOf(ActionResult.Applied.class,
manager.move(fixture.project().getId(), DockTarget.split(original, Side.BOTTOM)));
var area = manager.layout().windows().getFirst().areas().stream()
.filter(candidate -> candidate.id().equals(new DockAreaId("tools"))).findFirst().orElseThrow();
DockGroupId added = area.groups().getLast().id();
assertInstanceOf(ActionResult.Applied.class, manager.setGroupCollapsed(added, true));
manager.updateGroup(original, DockGroupChanges.builder().collapsible(false)
.minimumHeight(20).splitDirections(SplitDirections.ALL).build());
MoveCheck.Rejected direction = assertInstanceOf(MoveCheck.Rejected.class,
manager.checkMove(new DockableId("editor"), DockTarget.split(added, Side.RIGHT)));
assertEquals(DockFailure.Code.SPLIT_DISABLED, direction.failure().code());
MoveCheck.Rejected minimum = assertInstanceOf(MoveCheck.Rejected.class,
manager.checkMove(new DockableId("editor"), DockTarget.split(added, Side.TOP)));
assertEquals(DockFailure.Code.SPLIT_TOO_SMALL, minimum.failure().code());
assertInstanceOf(MoveCheck.Allowed.class,
manager.checkMove(new DockableId("editor"), DockTarget.split(original, Side.TOP)));
assertInstanceOf(ActionResult.Applied.class,
manager.move(fixture.changes().getId(), DockTarget.group(added)));
ActionResult.Rejected stale = assertInstanceOf(ActionResult.Rejected.class,
manager.updateGroup(original, DockGroupChanges.builder().collapsible(true).build()));
assertEquals(DockFailure.Code.TARGET_NOT_FOUND, stale.failure().code());
});
}
@Test
void collapsingASplitLeafGivesItsContentSpaceToItsSiblingAndRestoresTheDivider() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
DockingManager manager = fixture.manager();
DockGroupId first = new DockGroupId("tools");
manager.move(fixture.project().getId(), DockTarget.split(first, Side.BOTTOM));
TabPane second = fixture.pane().lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.filter(candidate -> candidate.getTabs().stream()
.anyMatch(tab -> tab.getContent() == fixture.project().getContent())).findFirst().orElseThrow();
double firstHeight = fixture.tabs().getHeight();
double secondHeight = second.getHeight();
DockLayoutView.Split before = (DockLayoutView.Split) manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().equals(new DockAreaId("tools"))).findFirst().orElseThrow().root();
assertInstanceOf(ActionResult.Applied.class, manager.setGroupCollapsed(first, true));
assertTrue(fixture.tabs().getHeight() < firstHeight - 60,
"The collapsed leaf retains only its header rail along the split axis");
assertTrue(second.getHeight() > secondHeight + 60, "The sibling receives the released content space");
DockLayoutView.Split collapsed = (DockLayoutView.Split) manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().equals(new DockAreaId("tools"))).findFirst().orElseThrow().root();
assertEquals(before.position(), collapsed.position(), .001, "Published state remembers the expanded proportion");
assertInstanceOf(ActionResult.Applied.class, manager.setGroupCollapsed(first, false));
assertEquals(firstHeight, fixture.tabs().getHeight(), 2);
assertEquals(secondHeight, second.getHeight(), 2);
});
}
@Test
void anExplicitWidthIsComparedWithTheLiveDividerExtentAndProtectedAsGeometry() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
DockingManager manager = fixture.manager();
DockGroupId tools = new DockGroupId("tools");
dragRightBoundary(fixture, 100);
assertEquals(300, fixture.tabs().getWidth(), 1);
assertInstanceOf(ActionResult.Applied.class,
manager.updateGroup(tools, DockGroupChanges.builder().preferredWidth(200).build()),
"An explicit initial width still changes the user's resized live width");
assertEquals(200, fixture.tabs().getWidth(), 1);
dragRightBoundary(fixture, 100);
var consent = new java.util.concurrent.CompletableFuture<CloseConsent>();
Dockable editor = manager.findDockable(new DockableId("editor")).orElseThrow();
editor.setCloseCheck(request -> consent);
manager.requestTabClose(editor.getId());
try {
DockLayoutView before = manager.layout();
ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class,
manager.updateGroup(tools, DockGroupChanges.builder()
.preferredWidth(200).splitDirections(SplitDirections.NONE).build()));
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, rejected.failure().code());
assertEquals(before, manager.layout());
assertEquals(300, fixture.tabs().getWidth(), 1);
} finally {
consent.complete(CloseConsent.VETO);
}
assertInstanceOf(ActionResult.Applied.class,
manager.updateGroup(tools, DockGroupChanges.builder().preferredWidth(200).build()));
assertEquals(200, fixture.tabs().getWidth(), 1);
assertInstanceOf(ActionResult.NoChange.class,
manager.updateGroup(tools, DockGroupChanges.builder().preferredWidth(200).build()));
});
}
@Test
void anOrdinaryWindowResizeKeepsACollapsedRailFixedAndGivesSpaceToItsSibling() throws Exception {
var fixtureRef = new java.util.concurrent.atomic.AtomicReference<Fixture>();
var siblingRef = new java.util.concurrent.atomic.AtomicReference<TabPane>();
var resized = new java.util.concurrent.CountDownLatch(1);
double[] before = new double[3];
try {
FxThread.onFx(() -> {
javafx.application.Platform.setImplicitExit(false);
Fixture fixture = fixture();
fixtureRef.set(fixture);
Stage stage = (Stage) fixture.pane().getScene().getWindow();
stage.show();
fixture.manager().move(fixture.project().getId(),
DockTarget.split(new DockGroupId("tools"), Side.BOTTOM));
TabPane sibling = fixture.pane().lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.filter(candidate -> candidate.getTabs().stream()
.anyMatch(tab -> tab.getContent() == fixture.project().getContent())).findFirst().orElseThrow();
siblingRef.set(sibling);
fixture.manager().setGroupCollapsed(new DockGroupId("tools"), true);
before[0] = fixture.tabs().getHeight();
before[1] = sibling.getHeight();
before[2] = stage.getScene().getHeight();
stage.getScene().heightProperty().addListener((observable, old, current) -> {
if (current.doubleValue() > before[2] + 60) resized.countDown();
});
stage.setHeight(stage.getHeight() + 120);
});
assertTrue(resized.await(5, java.util.concurrent.TimeUnit.SECONDS), "The native window resize reaches the Scene");
FxThread.onFx(() -> {
Fixture fixture = fixtureRef.get();
fixture.pane().layout();
assertEquals(before[0], fixture.tabs().getHeight(), 2,
"Resizing a window does not expand the collapsed header rail");
double addedHeight = fixture.pane().getScene().getHeight() - before[2];
assertEquals(before[1] + addedHeight, siblingRef.get().getHeight(), 2);
assertTrue(group(fixture.manager()).collapsed());
});
} finally {
if (fixtureRef.get() != null) FxThread.onFx(() -> ((Stage) fixtureRef.get().pane().getScene().getWindow()).hide());
}
}
@Test
void onlyTheSelectedOwnedContentIsVisibleAndNestedApplicationTabsRemainUntouched() throws Exception {
FxThread.onFx(() -> {
Fixture fixture = fixture();
DockingManager manager = fixture.manager();
manager.activate(fixture.changes().getId());
assertTrue(visibleThroughParents(fixture.changes().getContent()));
assertFalse(visibleThroughParents(fixture.project().getContent()),
"Selecting an earlier tab must not also show the newest tab");
TabPane applicationTabs = new TabPane(
new javafx.scene.control.Tab("Application first", new TextArea("First")),
new javafx.scene.control.Tab("Application second", new TextArea("Second")));
applicationTabs.setStyle("-fx-font-size: 40px;");
Dockable application = new Dockable(new DockableId("application"), applicationTabs);
application.setTitle("Application");
manager.open(application, DockTarget.area("tools"));
var nestedVisibility = applicationTabs.getChildrenUnmodifiable().stream()
.filter(node -> node.getStyleClass().contains("tab-content-area"))
.collect(java.util.stream.Collectors.toMap(node -> node, javafx.scene.Node::isVisible));
assertEquals(2, nestedVisibility.size());
manager.activate(fixture.changes().getId());
assertFalse(visibleThroughParents(applicationTabs));
manager.setGroupCollapsed(new DockGroupId("tools"), true);
assertFalse(visibleThroughParents(fixture.changes().getContent()));
assertFalse(visibleThroughParents(fixture.project().getContent()));
assertFalse(visibleThroughParents(applicationTabs));
assertTrue(fixture.tabs().getWidth() < 50, "The rail uses its own header, not the application's large-font header");
nestedVisibility.forEach((node, visible) -> assertEquals(visible, node.isVisible()));
manager.setGroupCollapsed(new DockGroupId("tools"), false);
assertTrue(visibleThroughParents(fixture.changes().getContent()));
assertFalse(visibleThroughParents(fixture.project().getContent()));
assertFalse(visibleThroughParents(applicationTabs));
nestedVisibility.forEach((node, visible) -> assertEquals(visible, node.isVisible()));
});
}
private static void dragRightBoundary(Fixture fixture, double pixels) {
javafx.scene.Node divider = fixture.pane().lookup(".dock-area-divider");
for (var type : java.util.List.of(javafx.scene.input.MouseEvent.MOUSE_PRESSED,
javafx.scene.input.MouseEvent.MOUSE_DRAGGED, javafx.scene.input.MouseEvent.MOUSE_RELEASED)) {
double screenX = type == javafx.scene.input.MouseEvent.MOUSE_PRESSED ? 0 : -pixels;
divider.fireEvent(new javafx.scene.input.MouseEvent(type, 0, 0, screenX, 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)));
fixture.pane().layout();
}
}
private static DockLayoutView.Group group(DockingManager manager) {
return manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().equals(new DockAreaId("tools"))).findFirst().orElseThrow().groups().getFirst();
}
private static javafx.scene.Node header(TabPane tabs, DockableId id) {
var tab = tabs.getTabs().stream().filter(candidate -> id.equals(candidate.getUserData())).findFirst().orElseThrow();
return tabs.lookup("#" + tab.getId());
}
private static boolean visibleThroughParents(javafx.scene.Node node) {
for (javafx.scene.Node current = node; current != null; current = current.getParent()) {
if (!current.isVisible()) return false;
}
return true;
}
private static void click(javafx.scene.Node header) {
for (var type : java.util.List.of(javafx.scene.input.MouseEvent.MOUSE_PRESSED,
javafx.scene.input.MouseEvent.MOUSE_RELEASED, javafx.scene.input.MouseEvent.MOUSE_CLICKED)) {
header.fireEvent(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_PRESSED, false, false, false, false, true,
new javafx.scene.input.PickResult(header, 0, 0)));
}
}
private static Fixture fixture() {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setTabSide(Side.RIGHT);
tools.setCollapsible(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());
manager.open(new Dockable(new DockableId("editor"), new TextArea()), DockTarget.area("editors"));
Dockable changes = new Dockable(new DockableId("changes"), new TextArea("Changed files"));
changes.setTitle("Changed files");
changes.setIcon(new Label("C"));
manager.open(changes, DockTarget.area("tools"));
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
project.setTitle("Project");
project.setIcon(new Label("P"));
manager.open(project, DockTarget.area("tools"));
TabPane tabs = pane.lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == project.getContent()))
.findFirst().orElseThrow();
return new Fixture(manager, pane, tabs, project, changes);
}
private record Fixture(DockingManager manager, DockPane pane, TabPane tabs, Dockable project, Dockable changes) { }
}
@@ -0,0 +1,135 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockGroupId;
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 javafx.application.Platform;
import javafx.geometry.Bounds;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
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 static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** A collapsed tool rail is a destination without opening merely for a preview. */
class CollapsedDockDropTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@ParameterizedTest
@EnumSource(value = Side.class, names = {"LEFT", "RIGHT"})
void aPreviewAndEscapeKeepTheRailCollapsedButDroppingOpensItsRememberedWidth(Side side) throws Exception {
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setCollapsible(true);
tools.setTabSide(side);
tools.setPreferredWidth(240);
if (side == Side.LEFT) initial.setLeft(tools);
else initial.setRight(tools);
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());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Unsaved notes"));
notes.setTitle("Notes");
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
project.setTitle("Project");
manager.open(notes, DockTarget.area("editors"));
manager.open(project, DockTarget.area("tools"));
stage.show();
try {
pane.applyCss();
pane.layout();
TabPane target = tabs(pane, project.getId());
double expandedWidth = target.getWidth();
manager.setGroupCollapsed(new DockGroupId("tools"), true);
pane.applyCss();
pane.layout();
DockLayoutView collapsed = manager.layout();
assertTrue(group(manager).collapsed());
assertTrue(target.getWidth() < expandedWidth / 2);
Node sourceHeader = header(tabs(pane, notes.getId()), notes.getId());
Node targetHeader = header(target, project.getId());
Bounds from = sourceHeader.localToScreen(sourceHeader.getBoundsInLocal());
Bounds into = targetHeader.localToScreen(targetHeader.getBoundsInLocal());
mouse(sourceHeader, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true);
mouse(sourceHeader, MouseEvent.MOUSE_DRAGGED, into.getCenterX(), into.getCenterY(), true);
assertTrue(pane.lookup(".dock-drop-indicator").isVisible());
assertEquals(collapsed, manager.layout());
assertTrue(group(manager).collapsed());
assertFalse(target.lookup(".tab-content-area").isVisible());
stage.getScene().getRoot().fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.ESCAPE,
false, false, false, false));
assertFalse(pane.lookup(".dock-drop-indicator").isVisible());
mouse(sourceHeader, MouseEvent.MOUSE_RELEASED, into.getCenterX(), into.getCenterY(), false);
assertEquals(collapsed, manager.layout());
assertTrue(group(manager).collapsed());
mouse(sourceHeader, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true);
mouse(sourceHeader, MouseEvent.MOUSE_DRAGGED, into.getCenterX(), into.getCenterY(), true);
mouse(sourceHeader, MouseEvent.MOUSE_RELEASED, into.getCenterX(), into.getCenterY(), false);
pane.applyCss();
pane.layout();
assertFalse(group(manager).collapsed());
assertEquals(notes.getId(), group(manager).selectedDockableId());
assertSame(notes, manager.activeDockable());
assertSame(notes.getContent(), target.getSelectionModel().getSelectedItem().getContent());
assertEquals(expandedWidth, target.getWidth(), 1);
assertTrue(target.lookup(".tab-content-area").isVisible());
assertTrue(notes.getContent().isVisible());
} finally { stage.hide(); }
});
}
private static DockLayoutView.Group group(DockingManager manager) {
return manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow().groups().getFirst();
}
private static TabPane tabs(DockPane pane, DockableId id) {
return pane.lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.filter(tabs -> tabs.getTabs().stream().anyMatch(tab -> id.equals(tab.getUserData())))
.findFirst().orElseThrow();
}
private static Node header(TabPane tabs, DockableId id) {
return tabs.lookup("#" + tabs.getTabs().stream().filter(tab -> id.equals(tab.getUserData()))
.findFirst().orElseThrow().getId());
}
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,425 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.ActionResult;
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 de.neitzel.fx.docking.MoveCheck;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.IndexRange;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
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.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Window moves retain application content and can be inspected without creating a window. */
class FloatDockablesTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void failedWindowCustomizationLeavesLiveContentUntouchedAndDiscardsOnlyFactoryContent() throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
RuntimeException cause = new IllegalStateException("Window customization failed");
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> { throw cause; });
DockingManager manager = DockingManager.attach(main, pane, options);
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Unsaved"));
manager.open(notes, DockTarget.area("editors"));
var layout = manager.layout();
var windows = List.copyOf(Window.getWindows());
assertInstanceOf(MoveCheck.Allowed.class, manager.checkMove(notes.getId(), DockTarget.floating()));
var moved = assertInstanceOf(ActionResult.Rejected.class, manager.move(notes.getId(), DockTarget.floating()));
assertSame(cause, moved.failure().cause());
assertSame(layout, manager.layout());
assertSame(main, notes.getContent().getScene().getWindow());
var discarded = new java.util.concurrent.atomic.AtomicInteger();
var id = new DockableId("prepared");
var opened = manager.open(id, () -> {
Dockable prepared = new Dockable(id, new TextArea("Prepared"));
prepared.setOnDiscarded(discarded::incrementAndGet);
return prepared;
}, DockTarget.floating());
assertInstanceOf(ActionResult.Rejected.class, opened);
assertEquals(1, discarded.get());
assertTrue(manager.findDockable(id).isEmpty());
assertSame(layout, manager.layout());
assertEquals(windows, List.copyOf(Window.getWindows()));
});
}
@Test
void floatingGroupsCanSplitAndRejoinWithoutReplacingOrClosingTheirContents() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable first = new Dockable(new DockableId("first"), new TextArea("First unsaved"));
Dockable second = new Dockable(new DockableId("second"), new TextArea("Second unsaved"));
var closed = new java.util.concurrent.atomic.AtomicInteger();
first.setOnClosed(closed::incrementAndGet);
second.setOnClosed(closed::incrementAndGet);
main.show();
try {
manager.open(first, DockTarget.floating());
var group = manager.layout().windows().getLast().areas().getFirst().groups().getFirst().id();
manager.open(second, DockTarget.group(group));
Window owner = first.getContent().getScene().getWindow();
assertInstanceOf(ActionResult.Applied.class,
manager.move(second.getId(), DockTarget.split(group, javafx.geometry.Side.RIGHT)));
var area = manager.layout().windows().getLast().areas().getFirst();
assertInstanceOf(de.neitzel.fx.docking.DockLayoutView.Split.class, area.root());
assertEquals(2, area.groups().size());
assertSame(owner, second.getContent().getScene().getWindow());
assertInstanceOf(ActionResult.Applied.class, manager.move(second.getId(), DockTarget.group(group)));
var joined = manager.layout().windows().getLast().areas().getFirst();
assertEquals(1, joined.groups().size());
assertEquals(List.of(first.getId(), second.getId()), joined.groups().getFirst().dockableIds());
assertSame(first.getContent(), manager.findDockable(first.getId()).orElseThrow().getContent());
assertEquals("Second unsaved", ((TextArea) second.getContent()).getText());
assertEquals(0, closed.get());
} finally {
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
}
});
}
@Test
void invalidFloatingGeometryIsRejectedWithoutAllocatingAWindow() throws Exception {
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Unsaved"));
manager.open(notes, DockTarget.area("editors"));
var before = manager.layout();
for (Rectangle2D bounds : List.of(new Rectangle2D(0, 0, 0, 100),
new Rectangle2D(Double.NaN, 0, 100, 100),
new Rectangle2D(0, 0, Double.POSITIVE_INFINITY, 100))) {
var rejected = assertInstanceOf(MoveCheck.Rejected.class,
manager.checkMove(notes.getId(), DockTarget.floating(bounds)));
assertEquals(de.neitzel.fx.docking.DockFailure.Code.INVALID_WINDOW_BOUNDS, rejected.failure().code());
assertInstanceOf(ActionResult.Rejected.class, manager.move(notes.getId(), DockTarget.floating(bounds)));
assertSame(before, manager.layout());
assertSame(main, notes.getContent().getScene().getWindow());
}
});
}
@Test
void checkedDetachmentAndReturnKeepTheLiveEditorAndSelection() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea notes = new TextArea("Edited without saving");
Dockable editor = new Dockable(new DockableId("notes"), notes);
editor.setTitle("Notes");
manager.open(editor, DockTarget.area("editors"));
main.show();
try {
notes.selectRange(2, 8);
var before = manager.layout();
int windows = Window.getWindows().size();
DockTarget floating = DockTarget.floating(new Rectangle2D(150, 150, 520, 360));
assertInstanceOf(MoveCheck.Allowed.class, manager.checkMove(editor.getId(), floating));
assertSame(before, manager.layout());
assertEquals(windows, Window.getWindows().size());
assertInstanceOf(ActionResult.Applied.class, manager.move(editor.getId(), floating));
Window detached = notes.getScene().getWindow();
assertNotSame(main, detached);
assertTrue(detached.isShowing());
assertEquals(2, manager.layout().windows().size());
assertEquals("Edited without saving", notes.getText());
assertEquals(new IndexRange(2, 8), notes.getSelection());
assertSame(editor, manager.activeDockable());
assertSame(notes, manager.findDockable(editor.getId()).orElseThrow().getContent());
assertInstanceOf(ActionResult.Applied.class, manager.move(editor.getId(), DockTarget.returnToMain()));
assertSame(main, notes.getScene().getWindow());
assertFalse(detached.isShowing());
assertEquals(1, manager.layout().windows().size());
assertEquals(new IndexRange(2, 8), notes.getSelection());
assertEquals("Edited without saving", notes.getText());
} finally {
for (Window window : List.copyOf(Window.getWindows())) {
if (!existing.contains(window)) window.hide();
}
}
});
}
@Test
void mainWindowOnlyContentCannotCreateOrEnterAFloatingWindow() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
project.setMainWindowOnly(true);
manager.open(notes, DockTarget.area("editors"));
manager.open(project, DockTarget.area("editors"));
main.show();
try {
var before = manager.layout();
assertInstanceOf(MoveCheck.Rejected.class, manager.checkMove(project.getId(), DockTarget.floating()));
assertInstanceOf(ActionResult.Rejected.class, manager.move(project.getId(), DockTarget.floating()));
assertSame(before, manager.layout());
assertEquals(1, manager.layout().windows().size());
assertInstanceOf(ActionResult.Applied.class, manager.move(notes.getId(), DockTarget.floating()));
var floatingGroup = manager.layout().windows().stream().filter(window -> !window.main())
.findFirst().orElseThrow().areas().getFirst().groups().getFirst();
var target = DockTarget.group(floatingGroup.id());
assertInstanceOf(MoveCheck.Rejected.class, manager.checkMove(project.getId(), target));
assertInstanceOf(ActionResult.Rejected.class, manager.move(project.getId(), target));
assertSame(main, project.getContent().getScene().getWindow());
Dockable another = new Dockable(new DockableId("another-project"), new TextArea("Another project"));
another.setMainWindowOnly(true);
assertInstanceOf(ActionResult.Rejected.class, manager.open(another, DockTarget.floating()));
assertTrue(manager.findDockable(another.getId()).isEmpty());
} finally {
for (Window window : List.copyOf(Window.getWindows())) {
if (!existing.contains(window)) window.hide();
}
}
});
}
@Test
void floatingCustomizationAndLiveContentAreReadyBeforeTheWindowAppears() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
var icon = new javafx.scene.image.WritableImage(1, 1);
String stylesheet = getClass().getResource("floating-window.css").toExternalForm();
var customized = new java.util.concurrent.atomic.AtomicInteger();
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> {
customized.incrementAndGet();
assertTrue(Window.getWindows().stream().allMatch(window -> existing.contains(window) || window == main));
configuration.setTitle("Floating editor");
configuration.getIcons().add(icon);
configuration.getStylesheets().add(stylesheet);
});
DockingManager manager = DockingManager.attach(main, pane, options);
TextArea notes = new TextArea("Edited without saving");
Dockable editor = new Dockable(new DockableId("notes"), notes);
manager.open(editor, DockTarget.area("editors"));
main.show();
var appearedWithContent = new java.util.concurrent.atomic.AtomicBoolean();
javafx.collections.ListChangeListener<Window> shown = change -> {
while (change.next()) {
for (Window window : change.getAddedSubList()) {
if (window != main && !existing.contains(window)) {
appearedWithContent.set(notes.getScene() == window.getScene());
}
}
}
};
Window.getWindows().addListener(shown);
try {
assertInstanceOf(MoveCheck.Allowed.class, manager.checkMove(editor.getId(), DockTarget.floating()));
assertEquals(0, customized.get());
assertInstanceOf(ActionResult.Applied.class, manager.move(editor.getId(), DockTarget.floating()));
Stage floating = (Stage) notes.getScene().getWindow();
assertEquals(1, customized.get());
assertEquals("Floating editor", floating.getTitle());
assertEquals(List.of(icon), floating.getIcons());
assertEquals(List.of(stylesheet), floating.getScene().getStylesheets());
assertTrue(appearedWithContent.get(), "A floating window must appear with its prepared content");
} finally {
Window.getWindows().removeListener(shown);
for (Window window : List.copyOf(Window.getWindows())) {
if (!existing.contains(window)) window.hide();
}
}
});
}
@Test
void returningUsesThePreviousRelativeTabPosition() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme"));
manager.open(notes, DockTarget.area("editors"));
manager.open(readme, DockTarget.area("editors"));
main.show();
try {
manager.move(notes.getId(), DockTarget.floating());
manager.move(notes.getId(), DockTarget.returnToMain());
assertEquals(List.of(notes.getId(), readme.getId()), manager.layout().windows().getFirst()
.areas().getFirst().groups().getFirst().dockableIds());
} finally {
for (Window window : List.copyOf(Window.getWindows())) {
if (!existing.contains(window)) window.hide();
}
}
});
}
@Test
void returningFindsTheOriginalAreaAfterItsConcreteSplitGroupDisappears() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setPreferredWidth(400);
pane.getInitialLayout().setRight(tools);
Stage main = new Stage();
main.setScene(new Scene(pane, 1000, 600));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
Dockable anchor = new Dockable(new DockableId("anchor"), new TextArea("Anchor"));
manager.open(anchor, DockTarget.area("tools"));
manager.open(notes, DockTarget.area("tools"));
main.show();
try {
assertInstanceOf(ActionResult.Applied.class, manager.move(notes.getId(),
DockTarget.split(new de.neitzel.fx.docking.DockGroupId("tools"), javafx.geometry.Side.BOTTOM)));
manager.move(notes.getId(), DockTarget.floating());
assertEquals(1, manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow().groups().size());
assertInstanceOf(ActionResult.Applied.class, manager.move(notes.getId(), DockTarget.returnToMain()));
var returned = manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow();
assertEquals(List.of(anchor.getId(), notes.getId()), returned.groups().getFirst().dockableIds());
} finally {
for (Window window : List.copyOf(Window.getWindows())) {
if (!existing.contains(window)) window.hide();
}
}
});
}
@Test
void returnUsesTheCapturedFallbackAndKeepsFloatingWhenNeitherTargetAcceptsIt() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
pane.getInitialLayout().setLeft(new DockGroupDefinition("return-place"));
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
Stage main = new Stage();
main.setScene(new Scene(pane, 1000, 600));
var allowTools = new java.util.concurrent.atomic.AtomicBoolean(true);
var allowFallback = new java.util.concurrent.atomic.AtomicBoolean(true);
DockingOptions options = new DockingOptions();
options.setFallbackTarget(DockTarget.area("return-place"));
options.setPlacementRule((dockable, destination) -> {
if (destination instanceof de.neitzel.fx.docking.ResolvedDockTarget.Insertion insertion
&& ((!allowTools.get() && insertion.groupId().value().equals("tools"))
|| (!allowFallback.get() && insertion.groupId().value().equals("return-place")))) {
return java.util.Optional.of(new de.neitzel.fx.docking.DockFailure(
de.neitzel.fx.docking.DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), "Destination disabled", null));
}
return java.util.Optional.empty();
});
DockingManager manager = DockingManager.attach(main, pane, options);
options.setFallbackTarget(DockTarget.area("editors"));
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
manager.open(notes, DockTarget.area("tools"));
main.show();
try {
manager.move(notes.getId(), DockTarget.floating());
allowTools.set(false);
assertInstanceOf(ActionResult.Applied.class, manager.move(notes.getId(), DockTarget.returnToMain()));
var fallback = manager.layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("return-place")).findFirst().orElseThrow();
assertEquals(List.of(notes.getId()), fallback.groups().getFirst().dockableIds());
manager.move(notes.getId(), DockTarget.floating());
allowFallback.set(false);
var before = manager.layout();
Window floating = notes.getContent().getScene().getWindow();
assertInstanceOf(MoveCheck.Rejected.class, manager.checkMove(notes.getId(), DockTarget.returnToMain()));
assertInstanceOf(ActionResult.Rejected.class, manager.move(notes.getId(), DockTarget.returnToMain()));
assertSame(before, manager.layout());
assertSame(floating, notes.getContent().getScene().getWindow());
assertTrue(floating.isShowing());
} finally {
for (Window window : List.copyOf(Window.getWindows())) {
if (!existing.contains(window)) window.hide();
}
}
});
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(booleans = {false, true})
void aMoveCheckFitsRequestedFloatingBoundsToAnAvailableScreen(boolean tinyFrame) throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
manager.open(notes, DockTarget.area("editors"));
main.show();
try {
Rectangle2D available = javafx.stage.Screen.getPrimary().getVisualBounds();
Rectangle2D requested = tinyFrame ? new Rectangle2D(available.getMaxX() - 1, available.getMaxY() - 1, 1, 1)
: new Rectangle2D(available.getMinX() - 10000, available.getMinY() - 10000,
available.getWidth() + 100, available.getHeight() + 100);
MoveCheck.Allowed allowed = assertInstanceOf(MoveCheck.Allowed.class,
manager.checkMove(notes.getId(), DockTarget.floating(requested)));
var target = assertInstanceOf(de.neitzel.fx.docking.ResolvedDockTarget.Detachment.class, allowed.destination());
assertEquals(tinyFrame ? requested : available, target.bounds());
assertInstanceOf(ActionResult.Applied.class, manager.move(notes.getId(), DockTarget.floating(requested)));
Window floating = notes.getContent().getScene().getWindow();
assertTrue(floating.getX() >= available.getMinX() - 1);
assertTrue(floating.getY() >= available.getMinY() - 1);
assertTrue(floating.getX() + floating.getWidth() <= available.getMaxX() + 1);
assertTrue(floating.getY() + floating.getHeight() <= available.getMaxY() + 1);
} finally {
for (Window window : List.copyOf(Window.getWindows())) {
if (!existing.contains(window)) window.hide();
}
}
});
}
}
@@ -0,0 +1,156 @@
package de.neitzel.fx.view;
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.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Real keyboard input after tab-menu transfers; run only with an exclusive desktop slot. */
@EnabledIfSystemProperty(named = "neitzellib.nativeFocusTest", matches = "true")
class FloatingNativeFocusTest {
private static final int[] DIGITS = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4};
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
@Timeout(20)
void nativeTypingContinuesWithoutClicksAfterFloatCrossWindowMoveAndReturn() throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(20);
Fixture fixture = fixture();
AtomicReference<Stage> firstFloating = new AtomicReference<>();
try {
typeIntoFocusedNotes(robot, fixture, KeyEvent.VK_1, "1");
FxThread.onFx(() -> {
command(fixture.notes, "Float", null);
firstFloating.set((Stage) fixture.notes.getScene().getWindow());
assertNotSame(fixture.main, firstFloating.get());
assertNotSame(fixture.other, firstFloating.get());
});
typeIntoFocusedNotes(robot, fixture, KeyEvent.VK_2, "12");
FxThread.onFx(() -> {
command(fixture.notes, "Move to", "Readme");
assertSame(fixture.other, fixture.notes.getScene().getWindow());
assertFalse(firstFloating.get().isShowing(), "The emptied source window is removed");
});
typeIntoFocusedNotes(robot, fixture, KeyEvent.VK_3, "123");
FxThread.onFx(() -> {
command(fixture.notes, "Return to main", null);
assertSame(fixture.main, fixture.notes.getScene().getWindow());
});
typeIntoFocusedNotes(robot, fixture, KeyEvent.VK_4, "1234");
FxThread.onFx(() -> {
assertEquals("untouched", fixture.readme.getText());
assertSame(fixture.notes, fixture.manager.findDockable(new DockableId("notes")).orElseThrow().getContent());
assertEquals(new DockableId("notes"), fixture.manager.activeDockable().getId());
});
} finally {
for (int key : DIGITS) robot.keyRelease(key);
FxThread.onFx(() -> {
if (firstFloating.get() != null) firstFloating.get().hide();
fixture.other.hide();
fixture.main.hide();
});
}
}
private static void typeIntoFocusedNotes(Robot robot, Fixture fixture, int key, String expected) throws Exception {
// Observe focus only. Do not repair it with a click, activate(), or requestFocus().
await(() -> fixture.notes.getScene().getWindow().isFocused()
&& fixture.notes.getScene().getFocusOwner() == fixture.notes, "Transferred editor did not receive native window focus");
try { robot.keyPress(key); }
finally { robot.keyRelease(key); }
await(() -> expected.equals(fixture.notes.getText()), "Native input did not reach the transferred editor: " + expected);
FxThread.onFx(() -> {
assertEquals(expected, fixture.notes.getText());
assertEquals("untouched", fixture.readme.getText());
assertSame(fixture.notes, fixture.notes.getScene().getFocusOwner());
});
}
private static void await(BooleanSupplier condition, String failure) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
AtomicReference<Boolean> ready = new AtomicReference<>(false);
do {
Thread.sleep(25);
FxThread.onFx(() -> ready.set(condition.getAsBoolean()));
} while (!ready.get() && System.nanoTime() < deadline);
assertTrue(ready.get(), failure);
}
private static void command(TextArea content, String label, String childTitle) {
ContextMenu menu = content.getScene().getRoot().lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.flatMap(tabs -> tabs.getTabs().stream()).filter(tab -> tab.getContent() == content)
.findFirst().orElseThrow().getContextMenu();
Stage owner = (Stage) content.getScene().getWindow();
menu.show(owner, owner.getX() + 60, owner.getY() + 60);
try {
MenuItem action = menu.getItems().stream().filter(item -> item.getText().equals(label)).findFirst().orElseThrow();
if (childTitle != null) action = ((Menu) action).getItems().stream()
.filter(item -> item.getText().contains(childTitle)).findFirst().orElseThrow();
assertFalse(action.isDisable());
menu.hide();
action.fire();
} finally { menu.hide(); }
}
private static Fixture fixture() throws Exception {
AtomicReference<Fixture> result = new AtomicReference<>();
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea notes = new TextArea();
TextArea readme = new TextArea("untouched");
Dockable editor = new Dockable(new DockableId("notes"), notes);
editor.setTitle("Notes");
Dockable other = new Dockable(new DockableId("readme"), readme);
other.setTitle("Readme");
manager.open(editor, DockTarget.area("editors"));
manager.open(other, DockTarget.area("editors"));
main.show();
manager.move(other.getId(), DockTarget.floating());
Stage floating = (Stage) readme.getScene().getWindow();
manager.activate(editor.getId()); // Initial setup only; all later focus must follow the transfer itself.
result.set(new Fixture(main, floating, manager, notes, readme));
});
return result.get();
}
private record Fixture(Stage main, Stage other, DockingManager manager, TextArea notes, TextArea readme) { }
}
@@ -0,0 +1,137 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockAreaId;
import de.neitzel.fx.docking.DockFailure;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockGroupId;
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.MoveCheck;
import javafx.application.Platform;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** Manager ownership and destination identity remain stable when windows and groups change. */
class FloatingOwnershipTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void aFloatingWindowCannotBeAttachedToASecondManager() throws Exception {
FxThread.onFx(() -> {
try (Fixture fixture = fixture("editors", null)) {
Dockable notes = fixture.open("notes", "editors");
assertInstanceOf(ActionResult.Applied.class, fixture.manager.move(notes.getId(), DockTarget.floating()));
Stage floating = (Stage) notes.getContent().getScene().getWindow();
DockPane floatingPane = assertInstanceOf(DockPane.class, floating.getScene().getRoot());
DockLayoutView before = fixture.manager.layout();
assertThrows(IllegalStateException.class,
() -> DockingManager.attach(floating, floatingPane, new DockingOptions()));
assertSame(before, fixture.manager.layout());
assertSame(floating, notes.getContent().getScene().getWindow());
assertSame(notes, fixture.manager.findDockable(notes.getId()).orElseThrow());
assertInstanceOf(ActionResult.Applied.class,
fixture.manager.move(notes.getId(), DockTarget.returnToMain()));
assertSame(fixture.main, notes.getContent().getScene().getWindow());
}
});
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void aRetiredConcreteGroupIdNeverTargetsANewFloatingOrSplitGroup(boolean floating) throws Exception {
FxThread.onFx(() -> {
DockGroupDefinition temporary = new DockGroupDefinition("group-1");
temporary.setPersistent(false);
try (Fixture fixture = fixture("editors", temporary)) {
Dockable anchor = fixture.open("anchor", "editors");
Dockable notes = fixture.open("notes", "group-1");
DockGroupId retired = new DockGroupId("group-1");
assertInstanceOf(ActionResult.Applied.class,
fixture.manager.move(notes.getId(), DockTarget.area("editors")));
assertMissingGroup(fixture.manager, anchor.getId(), retired);
DockTarget destination = floating ? DockTarget.floating()
: DockTarget.split(new DockGroupId("editors"), Side.RIGHT);
assertInstanceOf(ActionResult.Applied.class, fixture.manager.move(notes.getId(), destination));
DockGroupId allocated = fixture.manager.layout().windows().stream()
.flatMap(window -> window.areas().stream()).flatMap(area -> area.groups().stream())
.filter(group -> group.dockableIds().contains(notes.getId())).findFirst().orElseThrow().id();
assertNotEquals(retired, allocated, "A stale concrete destination must not acquire a new meaning");
assertMissingGroup(fixture.manager, anchor.getId(), retired);
}
});
}
@Test
void aGeneratedFloatingAreaDoesNotShadowAnInitialAreaWithTheSameName() throws Exception {
FxThread.onFx(() -> {
try (Fixture fixture = fixture("floating-1", null)) {
Dockable notes = fixture.open("notes", "floating-1");
assertInstanceOf(ActionResult.Applied.class, fixture.manager.move(notes.getId(), DockTarget.floating()));
DockLayoutView.Window floating = fixture.manager.layout().windows().stream()
.filter(window -> !window.main()).findFirst().orElseThrow();
assertNotEquals(new DockAreaId("floating-1"), floating.areas().getFirst().id());
Dockable readme = fixture.open("readme", "floating-1");
assertSame(fixture.main, readme.getContent().getScene().getWindow(),
"The application's original area target must still select the main window");
}
});
}
private static void assertMissingGroup(DockingManager manager, DockableId id, DockGroupId group) {
MoveCheck.Rejected rejected = assertInstanceOf(MoveCheck.Rejected.class,
manager.checkMove(id, DockTarget.group(group)));
assertEquals(DockFailure.Code.TARGET_NOT_FOUND, rejected.failure().code());
}
private static Fixture fixture(String centerId, DockGroupDefinition right) {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition(centerId));
pane.getInitialLayout().setRight(right);
Stage main = new Stage();
main.setScene(new Scene(pane, 900, 600));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
main.show();
return new Fixture(main, manager, existing);
}
private record Fixture(Stage main, DockingManager manager, List<Window> existing) implements AutoCloseable {
Dockable open(String id, String area) {
Dockable dockable = new Dockable(new DockableId(id), new TextArea(id));
assertInstanceOf(ActionResult.Applied.class, manager.open(dockable, DockTarget.area(area)));
return dockable;
}
@Override public void close() {
for (Window window : List.copyOf(Window.getWindows())) {
if (!existing.contains(window)) window.hide();
}
}
}
}
@@ -0,0 +1,201 @@
package de.neitzel.fx.view;
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.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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;
/** Floating commands are exercised through visible tab menus and public layout state. */
class FloatingTabsByMenuTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void tabMenusFloatAndReturnTheSameEditorWithoutLosingItsSelection() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 420));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea content = new TextArea("Unsaved notes survive a transfer");
Dockable notes = new Dockable(new DockableId("notes"), content);
notes.setTitle("Notes");
AtomicInteger closed = new AtomicInteger();
notes.setOnClosed(closed::incrementAndGet);
manager.open(notes, DockTarget.area("editors"));
main.show();
ContextMenu menu = null;
try {
pane.applyCss();
pane.layout();
content.selectRange(8, 13);
menu = tab(content).getContextMenu();
menu.show(main, main.getX() + 80, main.getY() + 80);
MenuItem floatItem = item(menu, "Float");
assertFalse(floatItem.isDisable());
assertEquals(1, manager.layout().windows().size(), "Opening a menu must not create a window");
menu.hide();
floatItem.fire();
assertEquals(2, manager.layout().windows().size());
Window floating = content.getScene().getWindow();
assertNotSame(main, floating);
assertTrue(floating.isShowing());
assertSame(content, manager.findDockable(notes.getId()).orElseThrow().getContent());
assertEquals("Unsaved notes survive a transfer", content.getText());
assertEquals("notes", content.getSelectedText());
assertSame(content, content.getScene().getFocusOwner());
menu = tab(content).getContextMenu();
menu.show(floating, floating.getX() + 80, floating.getY() + 80);
MenuItem returnItem = item(menu, "Return to main");
assertFalse(returnItem.isDisable());
menu.hide();
returnItem.fire();
assertEquals(1, manager.layout().windows().size());
assertFalse(floating.isShowing());
assertSame(main, content.getScene().getWindow());
assertEquals("notes", content.getSelectedText());
assertSame(content, main.getScene().getFocusOwner());
assertSame(notes, manager.activeDockable());
assertEquals(0, closed.get(), "Moving an editor must not close its resources");
} finally {
if (menu != null) menu.hide();
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
@Test
void theMoveMenuOffersAnotherFloatingWindowsGroup() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 420));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea notesContent = new TextArea("Unsaved notes");
TextArea readmeContent = new TextArea("Readme");
Dockable notes = new Dockable(new DockableId("notes"), notesContent);
notes.setTitle("Notes");
Dockable readme = new Dockable(new DockableId("readme"), readmeContent);
readme.setTitle("Readme");
manager.open(notes, DockTarget.area("editors"));
manager.open(readme, DockTarget.area("editors"));
main.show();
ContextMenu menu = null;
try {
manager.move(notes.getId(), DockTarget.floating());
manager.move(readme.getId(), DockTarget.floating());
Window source = notesContent.getScene().getWindow();
Window destination = readmeContent.getScene().getWindow();
notesContent.selectRange(8, 13);
menu = tab(notesContent).getContextMenu();
menu.show(source, source.getX() + 80, source.getY() + 80);
Menu destinations = (Menu) item(menu, "Move to");
MenuItem readmeTarget = destinations.getItems().stream()
.filter(candidate -> candidate.getText().contains("Readme")).findFirst().orElseThrow();
assertFalse(readmeTarget.isDisable());
menu.hide();
readmeTarget.fire();
assertFalse(source.isShowing());
assertEquals(2, manager.layout().windows().size());
assertSame(destination, notesContent.getScene().getWindow());
assertEquals("notes", notesContent.getSelectedText());
assertSame(notesContent, destination.getScene().getFocusOwner());
assertSame(notes, manager.activeDockable());
} finally {
if (menu != null) menu.hide();
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
@Test
void aMainWindowOnlyTabExplainsItsDisabledFloatingCommands() throws Exception {
FxThread.onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 760, 420));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea projectContent = new TextArea("Project");
Dockable project = new Dockable(new DockableId("project"), projectContent);
project.setTitle("Project");
project.setMainWindowOnly(true);
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme"));
readme.setTitle("Readme");
manager.open(project, DockTarget.area("editors"));
manager.open(readme, DockTarget.area("editors"));
main.show();
ContextMenu menu = null;
try {
manager.move(readme.getId(), DockTarget.floating());
pane.applyCss();
pane.layout();
var before = manager.layout();
menu = tab(projectContent).getContextMenu();
menu.show(main, main.getX() + 80, main.getY() + 80);
MenuItem floatItem = item(menu, "Float");
assertTrue(floatItem.isDisable());
assertTrue(floatItem.getText().contains("main window"));
Menu destinations = (Menu) item(menu, "Move to");
MenuItem floatingTarget = destinations.getItems().stream()
.filter(candidate -> candidate.getText().contains("Readme")).findFirst().orElseThrow();
assertTrue(floatingTarget.isDisable());
assertTrue(floatingTarget.getText().contains("main window"));
assertEquals(before, manager.layout(), "Opening the menu only checks destinations");
assertSame(main, projectContent.getScene().getWindow());
} finally {
if (menu != null) menu.hide();
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
private static Tab tab(TextArea content) {
return content.getScene().getRoot().lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.flatMap(tabs -> tabs.getTabs().stream()).filter(tab -> tab.getContent() == content)
.findFirst().orElseThrow();
}
private static MenuItem item(ContextMenu menu, String label) {
MenuItem item = menu.getItems().stream().filter(candidate -> candidate.getText().startsWith(label))
.findFirst().orElse(null);
assertNotNull(item, "Expected tab command: " + label);
return item;
}
}
@@ -0,0 +1,234 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockGroupChanges;
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 javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.SplitPane;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Public geometry observations; native pointer movement requires an exclusive desktop opt-in. */
class FloatingWindowGeometryTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void theLayoutExposesFloatingBoundsAndLeavesMainWindowGeometryToTheApplication() throws Exception {
Fixture fixture = fixture();
try {
FxThread.onFx(() -> {
assertNull(fixture.manager.layout().windows().stream().filter(DockLayoutView.Window::main)
.findFirst().orElseThrow().bounds());
assertEquals(actual(fixture.floating), published(fixture.manager));
});
} finally { FxThread.onFx(fixture::close); }
}
@Test
@EnabledIfSystemProperty(named = "neitzellib.nativeGeometryTest", matches = "true")
void nativeTitlebarAndBorderGesturesPublishOnlyAfterReleaseEvenWithAHeldPause() throws Exception {
Fixture fixture = fixture();
Robot robot = new Robot();
robot.setAutoDelay(15);
Point original = MouseInfo.getPointerInfo().getLocation();
var watchdog = Executors.newSingleThreadScheduledExecutor();
watchdog.schedule(() -> {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseMove(original.x, original.y);
}, 15, TimeUnit.SECONDS);
try {
Thread.sleep(400);
FxThread.onFx(fixture.committed::clear);
for (boolean border : List.of(false, true)) {
AtomicReference<Rectangle2D> before = new AtomicReference<>();
AtomicReference<Point> start = new AtomicReference<>();
FxThread.onFx(() -> {
before.set(published(fixture.manager));
Rectangle2D frame = actual(fixture.floating);
double titleHeight = fixture.floating.getScene().getRoot().localToScreen(0, 0).getY() - frame.getMinY();
start.set(border ? new Point((int) frame.getMaxX() - 1, (int) frame.getMaxY() - 1)
: new Point((int) (frame.getMinX() + frame.getWidth() / 2),
(int) (frame.getMinY() + titleHeight / 2)));
});
robot.mouseMove(start.get().x, start.get().y);
Thread.sleep(100);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
try {
for (int step = 1; step <= 8; step++) {
robot.mouseMove(start.get().x + step * 8, start.get().y + step * 5);
Thread.sleep(35);
}
Thread.sleep(600);
FxThread.onFx(() -> {
assertFalse(before.get().equals(actual(fixture.floating)), "Native gesture must change the real frame");
assertEquals(before.get(), published(fixture.manager), "A held pause is not gesture completion");
});
robot.mouseMove(start.get().x + 88, start.get().y + 55);
Thread.sleep(100);
} finally {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
awaitPublishedFrame(fixture, before.get());
}
FxThread.onFx(() -> assertEquals(2, fixture.committed.size(), "One completed publication per native gesture"));
} finally {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseMove(original.x, original.y);
watchdog.shutdownNow();
FxThread.onFx(fixture::close);
}
}
private static void awaitPublishedFrame(Fixture fixture, Rectangle2D previous) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
AtomicReference<Boolean> complete = new AtomicReference<>(false);
do {
Thread.sleep(25);
FxThread.onFx(() -> complete.set(!published(fixture.manager).equals(previous)
&& published(fixture.manager).equals(actual(fixture.floating))));
} while (!complete.get() && System.nanoTime() < deadline);
assertTrue(complete.get(), "Released native geometry must reach the public layout");
}
@Test
@EnabledIfSystemProperty(named = "neitzellib.nativeGeometryTest", matches = "true")
void anotherPublicationKeepsSplitGeometryCommittedDuringNativeResize() throws Exception {
Fixture fixture = fixture();
Robot robot = new Robot();
robot.setAutoDelay(15);
Point original = MouseInfo.getPointerInfo().getLocation();
var watchdog = Executors.newSingleThreadScheduledExecutor();
watchdog.schedule(() -> {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseMove(original.x, original.y);
}, 15, TimeUnit.SECONDS);
AtomicReference<Rectangle2D> before = new AtomicReference<>();
AtomicReference<Double> ratio = new AtomicReference<>();
AtomicReference<Point> start = new AtomicReference<>();
try {
FxThread.onFx(() -> {
fixture.floating.setWidth(760);
var window = fixture.manager.layout().windows().stream().filter(candidate -> !candidate.main()).findFirst().orElseThrow();
var group = window.areas().getFirst().groups().getFirst().id();
Dockable anchor = new Dockable(new DockableId("anchor"), new TextArea("Anchor"));
fixture.manager.open(anchor, DockTarget.group(group));
fixture.manager.move(anchor.getId(), DockTarget.split(group, Side.RIGHT));
fixture.manager.updateGroup(group, DockGroupChanges.builder().minimumWidth(320).build());
});
Thread.sleep(400);
FxThread.onFx(() -> {
before.set(published(fixture.manager));
ratio.set(publishedSplit(fixture.manager).position());
Rectangle2D frame = actual(fixture.floating);
start.set(new Point((int) frame.getMaxX() - 1, (int) frame.getMaxY() - 1));
});
robot.mouseMove(start.get().x, start.get().y);
Thread.sleep(100);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
try {
for (int step = 1; step <= 10; step++) {
robot.mouseMove(start.get().x - step * 34, start.get().y);
Thread.sleep(35);
}
Thread.sleep(600);
FxThread.onFx(() -> {
SplitPane split = (SplitPane) fixture.floating.getScene().getRoot().lookup(".dock-split");
double live = split.getDividers().getFirst().getPosition();
assertTrue(Math.abs(live - ratio.get()) > .03,
"Unequal minima must change the live split ratio: prior=" + ratio.get() + ", live=" + live
+ ", prior frame=" + before.get() + ", actual=" + actual(fixture.floating)
+ ", split width=" + split.getWidth() + ", first minimum=" + split.getItems().getFirst().minWidth(-1));
assertEquals(before.get(), published(fixture.manager));
fixture.manager.activate(new DockableId("notes"));
assertEquals(before.get(), published(fixture.manager), "Selection publication must retain committed bounds");
assertEquals(ratio.get(), publishedSplit(fixture.manager).position(), 1e-9,
"Selection publication must retain committed split geometry during the same native gesture");
});
} finally { robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); }
awaitPublishedFrame(fixture, before.get());
FxThread.onFx(() -> {
SplitPane split = (SplitPane) fixture.floating.getScene().getRoot().lookup(".dock-split");
assertTrue(Math.abs(publishedSplit(fixture.manager).position() - ratio.get()) > .03);
assertEquals(split.getDividers().getFirst().getPosition(), publishedSplit(fixture.manager).position(), 1e-9);
});
} finally {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseMove(original.x, original.y);
watchdog.shutdownNow();
FxThread.onFx(fixture::close);
}
}
private static DockLayoutView.Split publishedSplit(DockingManager manager) {
var area = manager.layout().windows().stream().filter(window -> !window.main()).findFirst().orElseThrow().areas().getFirst();
return assertInstanceOf(DockLayoutView.Split.class, area.root());
}
private static Fixture fixture() throws Exception {
AtomicReference<Fixture> result = new AtomicReference<>();
FxThread.onFx(() -> {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
Stage main = new Stage();
main.setScene(new Scene(pane, 800, 500));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Unsaved notes"));
manager.open(notes, DockTarget.area("editors"));
main.show();
manager.move(notes.getId(), DockTarget.floating(new Rectangle2D(200, 180, 540, 360)));
Stage floating = (Stage) notes.getContent().getScene().getWindow();
List<Rectangle2D> committed = new ArrayList<>();
manager.layoutProperty().addListener((observable, old, current) -> {
Rectangle2D prior = old.windows().stream().filter(window -> !window.main()).findFirst().orElseThrow().bounds();
Rectangle2D next = current.windows().stream().filter(window -> !window.main()).findFirst().orElseThrow().bounds();
if (!java.util.Objects.equals(prior, next)) committed.add(next);
});
result.set(new Fixture(main, floating, manager, committed));
});
return result.get();
}
private static Rectangle2D published(DockingManager manager) {
return manager.layout().windows().stream().filter(window -> !window.main()).findFirst().orElseThrow().bounds();
}
private static Rectangle2D actual(Stage stage) {
return new Rectangle2D(stage.getX(), stage.getY(), stage.getWidth(), stage.getHeight());
}
private record Fixture(Stage main, Stage floating, DockingManager manager, List<Rectangle2D> committed) {
void close() { floating.hide(); main.hide(); }
}
}
@@ -118,6 +118,19 @@ class OuterDockResizeTest {
assertSame(protectedLayout, manager.layout());
consent.complete(de.neitzel.fx.docking.CloseConsent.VETO);
assertTrue(closing.toCompletableFuture().isDone());
var centerConsent = new java.util.concurrent.CompletableFuture<de.neitzel.fx.docking.CloseConsent>();
var centerDockable = manager.findDockable(new DockableId("notes")).orElseThrow();
centerDockable.setCloseCheck(request -> centerConsent);
manager.requestTabClose(centerDockable.getId());
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,
"A side resize must protect the dependent center area too");
centerConsent.complete(de.neitzel.fx.docking.CloseConsent.VETO);
for (int direction : new int[]{1, -1}) {
var boundary = divider.localToScreen(divider.getBoundsInLocal());
mouse(divider, MouseEvent.MOUSE_PRESSED, boundary.getCenterX(), boundary.getCenterY(), true);
@@ -0,0 +1 @@
.dock-pane { -fx-background-color: #f4f4f4; }