Support native docking drags across windows with retained input focus

This commit is contained in:
2026-11-15 23:38:26 +01:00
parent bff6257dfe
commit fb5603eb76
8 changed files with 662 additions and 23 deletions
@@ -0,0 +1,120 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockGroupDefinition;
import de.neitzel.fx.docking.DockGroupMode;
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.geometry.Rectangle2D;
import javafx.geometry.Side;
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.scene.layout.VBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
import java.util.List;
/** A desktop exercise for live tab transfers, selection preservation and invalid destinations. */
public final class NativeDragDockingApp extends Application {
@Override
public void start(Stage stage) {
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition projectGroup = new DockGroupDefinition("project");
projectGroup.setTabSide(Side.LEFT);
projectGroup.setCollapsible(true);
projectGroup.setMode(DockGroupMode.OVERLAY);
projectGroup.setPreferredWidth(240);
pane.getInitialLayout().setLeft(projectGroup);
Button showProject = new Button("Show Project");
Button floatReadme = new Button("Separate Readme window");
Button returnNotes = new Button("Return Notes");
Button returnReadme = new Button("Return Readme");
ToolBar toolbar = new ToolBar(showProject, floatReadme, returnNotes, returnReadme,
new Label("Toolbar: no drop destination"));
Label active = new Label();
Label hint = new Label("Drag Notes' tab; then keep typing without clicking. Escape cancels a drag.");
Label count = new Label();
StatusBar status = new StatusBar();
status.getLeftItems().add(active);
status.getRightItems().add(count);
BorderPane shell = new BorderPane(pane);
shell.setTop(toolbar);
hint.setWrapText(true);
shell.setBottom(new VBox(hint, status));
Rectangle2D screen = Screen.getPrimary().getVisualBounds();
double mainWidth = Math.min(920, screen.getWidth() * .60);
stage.setScene(new Scene(shell, mainWidth, Math.min(560, screen.getHeight() - 120)));
stage.setX(screen.getMinX() + 24);
stage.setY(screen.getMinY() + 70);
stage.setTitle("NeitzelLib — drag tabs between windows");
DockingOptions options = new DockingOptions();
options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("NeitzelLib — floating drop destination"));
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable notes = editor("notes", "Notes", "abcdef\nSelect a word, move this tab, then type without an extra click.");
Dockable readme = editor("readme", "Readme", "This floating editor is a destination.\nDrop Notes onto its tab strip or content area.");
Dockable project = editor("project", "Project", "Project stays in the main window.\nDragging it outside or into a floating window is rejected.");
project.setIcon(new Label("▦"));
project.setMainWindowOnly(true);
manager.open(project, DockTarget.area("project"));
manager.open(readme, DockTarget.area("editors"));
manager.open(notes, DockTarget.area("editors"));
manager.setGroupCollapsed(new de.neitzel.fx.docking.DockGroupId("project"), true);
Rectangle2D destination = new Rectangle2D(screen.getMinX() + mainWidth + 48,
screen.getMinY() + 100, Math.min(500, screen.getWidth() * .34), 400);
floatReadme.setOnAction(event -> move(manager, readme, DockTarget.floating(destination), hint));
returnNotes.setOnAction(event -> move(manager, notes, DockTarget.returnToMain(), hint));
returnReadme.setOnAction(event -> move(manager, readme, DockTarget.returnToMain(), hint));
showProject.setOnAction(event -> manager.activate(project.getId()));
Runnable refresh = () -> {
Dockable current = manager.activeDockable();
active.setText("Active: " + (current == null ? "none" : current.getTitle()));
count.setText(manager.layout().windows().size() + " windows");
floatReadme.setDisable(!(manager.checkMove(readme.getId(), DockTarget.floating(destination)) 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));
showProject.setDisable(manager.findDockable(project.getId()).isEmpty());
};
manager.layoutProperty().addListener((observable, previous, current) -> refresh.run());
manager.activeDockableProperty().addListener((observable, previous, current) -> refresh.run());
stage.setOnHidden(event -> {
for (Dockable document : List.of(notes, readme, project)) {
if (document.getContent().getScene() != null && document.getContent().getScene().getWindow() != stage) {
document.getContent().getScene().getWindow().hide();
}
}
});
stage.show();
manager.move(readme.getId(), DockTarget.floating(destination));
manager.activate(notes.getId());
((TextArea) notes.getContent()).selectRange(2, 4);
refresh.run();
}
private static Dockable editor(String id, String title, String text) {
Dockable result = new Dockable(new DockableId(id), new TextArea(text));
result.setTitle(title);
return result;
}
private static void move(DockingManager manager, Dockable editor, DockTarget destination, Label hint) {
ActionResult result = manager.move(editor.getId(), destination);
hint.setText(result instanceof ActionResult.Rejected rejected ? rejected.failure().message()
: editor.getTitle() + " is ready. Continue typing without another click.");
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain Java launcher for native cross-window tab dragging. */
public final class NativeDragDockingMain {
private NativeDragDockingMain() { }
public static void main(String[] args) {
Application.launch(NativeDragDockingApp.class, args);
}
}
+1
View File
@@ -11,6 +11,7 @@
- [Standalone toolbar and status bar](docs/bars.md), usable without MVVM. - [Standalone toolbar and status bar](docs/bars.md), usable without MVVM.
- [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples. - [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples.
- [Optional MVVM docking integration](../fx-example/docs/docking-mvvm.md), with local and global bars. - [Optional MVVM docking integration](../fx-example/docs/docking-mvvm.md), with local and global bars.
- [Dragging between windows](docs/docking-drag.md), with native pointer and keyboard qualification.
- [Asynchronous tab close](docs/docking-close.md), including consent and resource release. - [Asynchronous tab close](docs/docking-close.md), including consent and resource release.
- [Dependency injection](../injection/README.md). - [Dependency injection](../injection/README.md).
+92 -10
View File
@@ -1,4 +1,4 @@
# Moving tabs in the main window # Moving tabs within and between windows
Drag a tab header to another group's content area to append it. Dropping on Drag a tab header to another group's content area to append it. Dropping on
a tab strip inserts at the displayed marker, including when reordering within a tab strip inserts at the displayed marker, including when reordering within
@@ -20,8 +20,12 @@ An invisible group that keeps its space accepts drops in its reserved area.
The move preview uses the same `checkMove` rules as an application command. The move preview uses the same `checkMove` rules as an application command.
Placement is checked again on release. A rejected location has no marker; Placement is checked again on release. A rejected location has no marker;
a move that would leave the tab where it is uses a muted marker. Escape a move that would leave the tab where it is uses a muted marker. Escape
cancels a pending gesture. Releasing over another part of the managed window, cancels a pending gesture. Releasing over another part of a managed window,
outside the docking groups, leaves the Dockable in place. including its global toolbar, status area or title bar, leaves the Dockable in
place. That invalid managed-window location does not create a floating window.
Releasing outside every managed window creates a new floating window when the
same placement rules permit it. Main-window-only Dockables have no floating
destination.
Every tab also provides a **Move to** context submenu. It lists the currently Every tab also provides a **Move to** context submenu. It lists the currently
available groups and the selected content's current title. Rejected targets available groups and the selected content's current title. Rejected targets
@@ -32,12 +36,90 @@ with unavailable directions disabled and explained. These explicit commands
request a split without the pointer gesture's join fallback. request a split without the pointer gesture's join fallback.
The preview is mouse-transparent and has CSS class `dock-drop-indicator`. The preview is mouse-transparent and has CSS class `dock-drop-indicator`.
Its `no-change` pseudo-class identifies a preview that leaves the current A floating preview uses `dock-floating-preview`, with a
`dock-floating-preview-frame` and `dock-floating-preview-label`.
Its bounds are fitted to a visible screen before display; it does not allocate
a managed window. The in-window indicator's `no-change` pseudo-class identifies a preview that leaves the current
placement intact. Applications may style its fill and stroke using JavaFX CSS. placement intact. Applications may style its fill and stroke using JavaFX CSS.
This slice covers the main window. Floating and cross-window pointer delivery ## Window routing and input delivery
extend these gestures in their respective tickets.
The gesture regression tests fire JavaFX events at visible tab headers and The interaction uses ordinary JavaFX mouse pressed/dragged/released events and
observe the public manager state. Those tests do not by themselves establish their screen coordinates to resolve a destination across the same manager's
native mouse delivery across windows; that has a separate desktop acceptance main and floating windows. It does not start the JavaFX Dragboard protocol or
sequence. exchange serialized content between applications. The original Node remains
live throughout the transfer; empty source groups and floating windows are
removed as part of the completed operation.
Insertion markers appear on tab strips; split previews show the receiving half
of a content area. A muted marker means no placement change. A floating preview
shows the proposed new window outside managed windows. Invalid destinations
have no accepted placement preview. Previewing a collapsed overlay rail does
not open it; a successful drop opens the group in its remembered mode and
shared size and selects the incoming tab. The previous overlay in that window
collapses. Escape clears the gesture and preview without changing layout or
content visibility.
The gesture regression tests that fire JavaFX events at visible tab headers
verify destination rules and public layout state. They do not establish native
mouse delivery across windows. `NativeDockDragTest` exercises real AWT Robot
mouse gestures and keyboard input on a desktop. It checks Main → new Floating
→ Main and Floating → Floating, preview without commit, invalid managed-window
drops, Escape for both in-window and floating previews, main-window-only rejection,
and a cross-window drop into a collapsed overlay. After each transfer, it types without a focus-repair click
and verifies the exact text at the retained selection/caret. Scene focus or
`focusedProperty` alone is not its acceptance criterion.
On 2026-11-15 these three native scenarios passed on macOS 27.2, Java 25 and
JavaFX 27.0.1, with zero failures, errors or skips. They retained the original
editor Nodes and selection/caret, and delivered actual text without a repair
click, including after invalid drops and cancellation. The overlay scenario
retained its configured 240-pixel group width and opened only on successful drop.
Other operating systems have not been qualified by this run.
The native test is opt-in because it moves the desktop pointer and sends real
keystrokes. Run it with exclusive access to the desktop and no parallel JavaFX
GUI tests:
```sh
./mvnw -pl fx -am -Dtest=NativeDockDragTest \
-Dneitzellib.nativeDragTest=true \
-Dsurefire.failIfNoSpecifiedTests=false test
```
It releases held keys/buttons, restores the pointer and closes its windows in
cleanup. Without the opt-in flag it is explicitly skipped. Execution results
qualify the tested OS/JDK/JavaFX combination; synthetic-event tests and a green
compile do not establish native delivery on other platforms.
## Desktop demonstration
Launch `de.neitzel.fx.example.docking.NativeDragDockingMain` from `fx-example`.
It starts Notes in the main window, Readme in a separate floating window and a
collapsed Project overlay at the left. Project is restricted to the main
window. The main toolbar and status area are deliberately invalid drop targets.
No MVVM setup is required.
1. Notes starts with `cd` selected in `abcdef`. Drag its tab onto Readme's content
area, release, and type `X` without clicking the content. The first line
becomes `abXef`; Readme remains unchanged.
2. Drag Notes onto the main editor area and type `Y` immediately. The text
becomes `abXYef`. Move Readme back into its own window with **Separate Readme
window** whenever another floating destination is needed.
3. Drag Notes outside all managed windows. Inspect the floating preview, then
release to create its own window. Type immediately at the existing caret.
4. Drag Notes from that floating window onto the main toolbar or status area.
Release: placement stays unchanged. Repeat toward a valid target but press
Escape before releasing: the preview disappears and the tab stays put.
5. Drop on a tab-strip insertion marker to reorder tabs. Drop near a content
edge to split, or drag the sole tab toward its own group edge to inspect the
muted no-change preview. Unavailable splits fall back to joining the group.
6. Drag Notes onto the collapsed Project rail. It stays collapsed during the
preview, then opens after a successful drop with the same overlay mode and
remembered width. Continue typing without another click.
7. Show Project and try to drag its tab outside managed windows or into Readme's
floating window. The main-window-only restriction rejects those destinations.
The buttons are setup/recovery commands; dragging uses the same move checks and
live contents. Closing the demonstration's main Stage hides its floating
windows; application-wide shutdown coordination is supplied by its own slice.
+5 -3
View File
@@ -43,7 +43,8 @@ module for a desktop demonstration:
6. Open Project's tab menu to inspect the disabled Float command. 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 The buttons and tab menus use the same manager operations. This example covers
command-based transfers. Native drag-and-drop between windows is supplied by its subsequent ticket. command-based transfers. The [dragging guide](docking-drag.md) covers native
mouse gestures between windows and their keyboard-focus qualification.
The [floating-window close guide](docking-close.md#closing-a-floating-window) The [floating-window close guide](docking-close.md#closing-a-floating-window)
describes shared consent for all tabs in a window. describes shared consent for all tabs in a window.
@@ -58,8 +59,9 @@ 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 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 (one native test, zero failures, errors or skips). It qualifies command/menu
transfers on that environment; native cross-window pointer dragging and other transfers on that environment. Cross-window pointer dragging has its separate
OS environments need their own qualification. [desktop qualification](docking-drag.md#window-routing-and-input-delivery);
other OS environments have not been qualified.
Run only with an exclusive desktop slot, since the test posts real keystrokes: Run only with an exclusive desktop slot, since the test posts real keystrokes:
@@ -15,6 +15,7 @@ import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent; import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton; import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent; import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@@ -29,10 +30,13 @@ final class DockDragController {
} }
private record Proposal(DockTarget target, Bounds marker) { } private record Proposal(DockTarget target, Bounds marker) { }
private record Header(DockableId id, Bounds bounds) { } private record Header(DockableId id, Bounds bounds) { }
private record Destination(DockDragController controller, Proposal proposal) { }
private final DockingManager manager; private final DockingManager manager;
private final DockPane pane; private final DockPane pane;
private final Scene scene; private final Scene scene;
private final Stage window;
private final javafx.beans.value.ChangeListener<Boolean> windowFocus;
private final Supplier<List<GroupSurface>> surfaces; private final Supplier<List<GroupSurface>> surfaces;
private final Map<String, DockableId> headers = new HashMap<>(); private final Map<String, DockableId> headers = new HashMap<>();
private final EventHandler<MouseEvent> mouseHandler = this::mouse; private final EventHandler<MouseEvent> mouseHandler = this::mouse;
@@ -42,11 +46,20 @@ final class DockDragController {
private double startY; private double startY;
private boolean dragging; private boolean dragging;
private long nextHeaderId; private long nextHeaderId;
private long frontOrder;
private javafx.stage.Popup floatingPreview;
private javafx.scene.shape.Rectangle floatingFrame;
DockDragController(DockingManager manager, DockPane pane, Supplier<List<GroupSurface>> surfaces) { DockDragController(DockingManager manager, DockPane pane, Supplier<List<GroupSurface>> surfaces) {
this.manager = manager; this.manager = manager;
this.pane = pane; this.pane = pane;
this.scene = pane.getScene(); this.scene = pane.getScene();
this.window = (Stage) scene.getWindow();
frontOrder = manager.nextWindowFocusOrder();
windowFocus = (observable, old, focused) -> {
if (focused) frontOrder = manager.nextWindowFocusOrder();
};
window.focusedProperty().addListener(windowFocus);
this.surfaces = surfaces; this.surfaces = surfaces;
pane.addEventFilter(MouseEvent.ANY, mouseHandler); pane.addEventFilter(MouseEvent.ANY, mouseHandler);
scene.addEventFilter(KeyEvent.KEY_PRESSED, keyHandler); scene.addEventFilter(KeyEvent.KEY_PRESSED, keyHandler);
@@ -142,8 +155,15 @@ final class DockDragController {
void dispose() { void dispose() {
pane.removeEventFilter(MouseEvent.ANY, mouseHandler); pane.removeEventFilter(MouseEvent.ANY, mouseHandler);
scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler); scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler);
window.focusedProperty().removeListener(windowFocus);
headers.clear(); headers.clear();
cancel(); cancel();
if (floatingPreview != null) {
floatingPreview.getScene().removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler);
floatingPreview.getContent().clear();
floatingPreview = null;
floatingFrame = null;
}
} }
private void mouse(MouseEvent event) { private void mouse(MouseEvent event) {
@@ -169,23 +189,83 @@ final class DockDragController {
boolean apply = dragging; boolean apply = dragging;
cancel(); cancel();
if (apply) { if (apply) {
Proposal proposal = proposal(id, event.getScreenX(), event.getScreenY()); Destination destination = destination(id, event.getScreenX(), event.getScreenY());
if (proposal != null) manager.move(id, proposal.target()); if (destination != null && destination.proposal() != null) {
if (!(manager.move(id, destination.proposal().target()) instanceof ActionResult.Applied)) manager.restoreDragFocus(id);
} else manager.restoreDragFocus(id);
event.consume(); event.consume();
} }
} }
} }
private void preview(double screenX, double screenY) { private void preview(double screenX, double screenY) {
Proposal proposal = proposal(pressed, screenX, screenY); Destination destination = destination(pressed, screenX, screenY);
if (proposal != null) { Proposal proposal = destination == null ? null : destination.proposal();
MoveCheck check = manager.checkMove(pressed, proposal.target()); MoveCheck check = proposal == null ? null : manager.checkMove(pressed, proposal.target());
if (!(check instanceof MoveCheck.Rejected)) { boolean accepted = check != null && !(check instanceof MoveCheck.Rejected);
pane.showDropIndicator(proposal.marker(), check instanceof MoveCheck.NoChange); boolean floating = accepted && destination.controller() == null;
return; hidePreviews(floating);
if (floating) showFloatingPreview(proposal.marker());
else if (accepted) destination.controller().pane.showDropIndicator(proposal.marker(), check instanceof MoveCheck.NoChange);
}
private void showFloatingPreview(Bounds bounds) {
if (floatingPreview == null) {
floatingPreview = new javafx.stage.Popup();
floatingPreview.setAutoFix(false);
floatingPreview.setAutoHide(false);
floatingPreview.setHideOnEscape(false);
floatingFrame = new javafx.scene.shape.Rectangle();
floatingFrame.getStyleClass().add("dock-floating-preview-frame");
floatingFrame.setFill(javafx.scene.paint.Color.rgb(80, 140, 220, .16));
floatingFrame.setStroke(javafx.scene.paint.Color.rgb(50, 110, 190));
floatingFrame.setStrokeType(javafx.scene.shape.StrokeType.INSIDE);
javafx.scene.control.Label label = new javafx.scene.control.Label("Float");
label.getStyleClass().add("dock-floating-preview-label");
javafx.scene.layout.StackPane preview = new javafx.scene.layout.StackPane(floatingFrame, label);
preview.getStyleClass().add("dock-floating-preview");
preview.setMouseTransparent(true);
floatingPreview.getContent().add(preview);
floatingPreview.getScene().addEventFilter(KeyEvent.KEY_PRESSED, keyHandler);
}
floatingFrame.setWidth(bounds.getWidth());
floatingFrame.setHeight(bounds.getHeight());
if (!floatingPreview.isShowing()) floatingPreview.show(window, bounds.getMinX(), bounds.getMinY());
else {
floatingPreview.setAnchorX(bounds.getMinX());
floatingPreview.setAnchorY(bounds.getMinY());
}
}
long frontOrder() { return frontOrder; }
private Destination destination(DockableId id, double x, double y) {
for (DockDragController controller : manager.dragControllers()) {
Stage candidate = controller.window;
if (candidate.isShowing() && x >= candidate.getX() && x <= candidate.getX() + candidate.getWidth()
&& y >= candidate.getY() && y <= candidate.getY() + candidate.getHeight()) {
return new Destination(controller, controller.proposal(id, x, y));
} }
} }
DockTarget target = DockTarget.floating(new javafx.geometry.Rectangle2D(x - 100, y - 20, 600, 400));
MoveCheck check = manager.checkMove(id, target);
if (check instanceof MoveCheck.Allowed allowed && allowed.destination() instanceof ResolvedDockTarget.Detachment floating) {
var bounds = floating.bounds();
return new Destination(null, new Proposal(DockTarget.floating(bounds), new BoundingBox(
bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), bounds.getHeight())));
}
return null;
}
private void hidePreviews() { hidePreviews(false); }
private void hidePreviews(boolean keepFloatingPreview) {
pane.hideDropIndicator(); pane.hideDropIndicator();
if (!keepFloatingPreview && floatingPreview != null) floatingPreview.hide();
manager.dragControllers().forEach(controller -> {
controller.pane.hideDropIndicator();
if (controller != this && controller.floatingPreview != null) controller.floatingPreview.hide();
});
} }
private Proposal proposal(DockableId id, double screenX, double screenY) { private Proposal proposal(DockableId id, double screenX, double screenY) {
@@ -335,7 +415,9 @@ final class DockDragController {
private void key(KeyEvent event) { private void key(KeyEvent event) {
if (pressed != null && event.getCode() == KeyCode.ESCAPE) { if (pressed != null && event.getCode() == KeyCode.ESCAPE) {
DockableId id = pressed;
cancel(); cancel();
manager.restoreDragFocus(id);
event.consume(); event.consume();
} }
} }
@@ -343,6 +425,6 @@ final class DockDragController {
private void cancel() { private void cancel() {
pressed = null; pressed = null;
dragging = false; dragging = false;
pane.hideDropIndicator(); hidePreviews();
} }
} }
@@ -35,6 +35,7 @@ public final class DockingManager {
private final java.util.Set<DockAreaId> allocatedAreaIds = new java.util.HashSet<>(); private final java.util.Set<DockAreaId> allocatedAreaIds = new java.util.HashSet<>();
private long nextGroupId; private long nextGroupId;
private long nextWindowId; private long nextWindowId;
private long nextWindowFocusOrder;
private final Map<DockWindowId, FloatingWindow> floatingWindows = new LinkedHashMap<>(); private final Map<DockWindowId, FloatingWindow> floatingWindows = new LinkedHashMap<>();
private final Map<DockGroupId, DockWindowId> groupWindows = new LinkedHashMap<>(); private final Map<DockGroupId, DockWindowId> groupWindows = new LinkedHashMap<>();
private final Map<DockableId, ReturnLocation> returnTargets = new LinkedHashMap<>(); private final Map<DockableId, ReturnLocation> returnTargets = new LinkedHashMap<>();
@@ -341,8 +342,8 @@ public final class DockingManager {
tab.setContent(null); tab.setContent(null);
if (sourceDrag != receiverDrag) sourceDrag.uninstallTab(tab); if (sourceDrag != receiverDrag) sourceDrag.uninstallTab(tab);
source.tabs.getTabs().remove(tab); source.tabs.getTabs().remove(tab);
receiver.tabs.getTabs().add(insertionIndex, tab);
if (sourceDrag != receiverDrag) receiverDrag.installTab(tab, id); if (sourceDrag != receiverDrag) receiverDrag.installTab(tab, id);
receiver.tabs.getTabs().add(insertionIndex, tab);
tab.setContent(dockables.get(id).getContent()); tab.setContent(dockables.get(id).getContent());
receiver.tabs.getSelectionModel().select(tab); receiver.tabs.getSelectionModel().select(tab);
normalizeLayout(source.id); normalizeLayout(source.id);
@@ -935,6 +936,24 @@ public final class DockingManager {
return id == null ? drag : floatingWindows.get(id).drag; return id == null ? drag : floatingWindows.get(id).drag;
} }
long nextWindowFocusOrder() { return ++nextWindowFocusOrder; }
void restoreDragFocus(DockableId id) {
Dockable dockable = dockables.get(id);
Group group = containing(id);
if (dockable == null || group == null) return;
if (isGroupVisible(group)) focus(dockable);
else ((DockGroupPane) group.tabs).focusSelectedHeader();
}
List<DockDragController> dragControllers() {
var controllers = new java.util.ArrayList<DockDragController>();
if (drag != null) controllers.add(drag);
floatingWindows.values().forEach(window -> controllers.add(window.drag));
controllers.sort(java.util.Comparator.comparingLong(DockDragController::frontOrder).reversed());
return controllers;
}
private Group createFloatingGroup(javafx.geometry.Rectangle2D bounds) { private Group createFloatingGroup(javafx.geometry.Rectangle2D bounds) {
FloatingWindowConfiguration configuration = new FloatingWindowConfiguration(); FloatingWindowConfiguration configuration = new FloatingWindowConfiguration();
try { try {
@@ -0,0 +1,321 @@
package de.neitzel.fx.view;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
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.awt.event.KeyEvent;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.*;
/** Desktop gestures and actual text delivery; no synthesized JavaFX input events. */
@EnabledIfSystemProperty(named = "neitzellib.nativeDragTest", matches = "true")
class NativeDockDragTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
@Timeout(25)
void draggingOutsideAndBackPreservesTheEditorAndNativeTypingAtItsSelection() throws Exception {
Fixture f = 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), 20, TimeUnit.SECONDS);
try {
await(() -> f.main.isFocused(), "Initial main window must be focused");
Point outside = onFx(() -> {
var screen = Screen.getPrimary().getVisualBounds();
return new Point((int) screen.getMaxX() - 100, (int) (screen.getMinY() + 180));
});
var initial = onFx(f.manager::layout);
drag(robot, onFx(() -> headerPoint(f.notes)), outside, () -> FxThread.onFx(() -> {
assertTrue(floatingPreviewVisible(), "Outside a managed window the proposed floating bounds must be visible");
assertSame(initial, f.manager.layout(), "A floating preview cannot allocate a managed window");
}));
await(() -> f.notes.getScene().getWindow() != f.main, "Dropping outside must create a floating window");
Window floating = onFx(() -> f.notes.getScene().getWindow());
type(robot, f.notes, KeyEvent.VK_X, "abxef");
Point mainTarget = onFx(() -> center(f.pane));
drag(robot, onFx(() -> headerPoint(f.notes)), mainTarget);
await(() -> f.notes.getScene().getWindow() == f.main, "Dropping into the main area must return the editor");
type(robot, f.notes, KeyEvent.VK_Y, "abxyef");
FxThread.onFx(() -> {
assertFalse(floating.isShowing(), "The empty source window disappears");
assertSame(f.notes, f.manager.findDockable(new DockableId("notes")).orElseThrow().getContent());
assertEquals(1, f.manager.layout().windows().size());
});
var returned = onFx(f.manager::layout);
drag(robot, onFx(() -> headerPoint(f.notes)), outside, () -> {
FxThread.onFx(() -> assertTrue(floatingPreviewVisible()));
try { robot.keyPress(KeyEvent.VK_ESCAPE); }
finally { robot.keyRelease(KeyEvent.VK_ESCAPE); }
await(() -> !floatingPreviewVisible(), "Escape must hide the floating preview");
});
FxThread.onFx(() -> assertSame(returned, f.manager.layout()));
type(robot, f.notes, KeyEvent.VK_Z, "abxyzef");
FxThread.onFx(() -> f.manager.findDockable(new DockableId("notes")).orElseThrow().setMainWindowOnly(true));
drag(robot, onFx(() -> headerPoint(f.notes)), outside,
() -> FxThread.onFx(() -> assertFalse(floatingPreviewVisible(), "Main-window-only content has no floating preview")));
FxThread.onFx(() -> assertSame(returned, f.manager.layout(), "Main-window-only cannot leave the main window"));
type(robot, f.notes, KeyEvent.VK_A, "abxyzaef");
} finally {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
for (int key : new int[]{KeyEvent.VK_ESCAPE, KeyEvent.VK_X, KeyEvent.VK_Y, KeyEvent.VK_Z, KeyEvent.VK_A}) robot.keyRelease(key);
robot.mouseMove(original.x, original.y);
watchdog.shutdownNow();
FxThread.onFx(f::close);
}
}
private static boolean floatingPreviewVisible() {
return Window.getWindows().stream().filter(Window::isShowing).anyMatch(window ->
window.getScene() != null && window.getScene().lookup(".dock-floating-preview") != null);
}
private static void drag(Robot robot, Point from, Point to) throws Exception {
drag(robot, from, to, () -> { });
}
@Test
@Timeout(30)
void nativeCrossWindowPreviewInvalidDropAndEscapePreserveTypingWithoutExtraClicks() throws Exception {
Fixture f = fixture();
Robot robot = new Robot();
robot.setAutoDelay(15);
Point original = MouseInfo.getPointerInfo().getLocation();
AtomicReference<TextArea> readme = new AtomicReference<>();
AtomicReference<Window> source = new AtomicReference<>();
AtomicReference<Window> target = new AtomicReference<>();
FxThread.onFx(() -> {
var screen = Screen.getPrimary().getVisualBounds();
TextArea other = new TextArea("untouched");
Dockable document = new Dockable(new DockableId("readme"), other);
document.setTitle("Readme");
f.manager.open(document, DockTarget.floating(new javafx.geometry.Rectangle2D(
screen.getMaxX() - 430, screen.getMinY() + 50, 400, 320)));
f.manager.move(new DockableId("notes"), DockTarget.floating(new javafx.geometry.Rectangle2D(
screen.getMinX() + 50, screen.getMinY() + 50, 360, 300)));
readme.set(other);
target.set(other.getScene().getWindow());
source.set(f.notes.getScene().getWindow());
f.notes.selectRange(2, 4);
});
var watchdog = Executors.newSingleThreadScheduledExecutor();
watchdog.schedule(() -> robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK), 25, TimeUnit.SECONDS);
try {
await(() -> source.get().isFocused(), "The initial source window must have focus");
var before = onFx(f.manager::layout);
drag(robot, onFx(() -> headerPoint(f.notes)), onFx(() -> center(readme.get())), () -> FxThread.onFx(() -> {
assertTrue(target.get().getScene().getRoot().lookup(".dock-drop-indicator").isVisible());
assertSame(before, f.manager.layout(), "A native preview does not commit a move");
assertSame(source.get(), f.notes.getScene().getWindow());
}));
await(() -> f.notes.getScene().getWindow() == target.get(), "Native drop must join the other floating window");
type(robot, f.notes, KeyEvent.VK_X, "abxef");
FxThread.onFx(() -> assertFalse(source.get().isShowing()));
var joined = onFx(f.manager::layout);
drag(robot, onFx(() -> headerPoint(f.notes)), onFx(() -> center(f.main.getScene().lookup("#invalidTarget"))));
FxThread.onFx(() -> assertSame(joined, f.manager.layout(), "Invalid managed-window space cannot float or move content"));
type(robot, f.notes, KeyEvent.VK_Y, "abxyef");
drag(robot, onFx(() -> headerPoint(f.notes)), onFx(() -> center(f.pane)), () -> {
FxThread.onFx(() -> assertTrue(f.pane.lookup(".dock-drop-indicator").isVisible()));
try { robot.keyPress(KeyEvent.VK_ESCAPE); }
finally { robot.keyRelease(KeyEvent.VK_ESCAPE); }
await(() -> !f.pane.lookup(".dock-drop-indicator").isVisible(), "Escape must remove the native drag preview");
});
FxThread.onFx(() -> assertSame(joined, f.manager.layout(), "Escape must leave the completed layout untouched"));
type(robot, f.notes, KeyEvent.VK_Z, "abxyzef");
FxThread.onFx(() -> assertEquals("untouched", readme.get().getText()));
} finally {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
for (int key : new int[]{KeyEvent.VK_ESCAPE, KeyEvent.VK_X, KeyEvent.VK_Y, KeyEvent.VK_Z}) robot.keyRelease(key);
robot.mouseMove(original.x, original.y);
watchdog.shutdownNow();
FxThread.onFx(f::close);
}
}
@Test
@Timeout(25)
void nativeFloatingDropIntoCollapsedOverlayOpensOnlyAtCommitAndRetainsGroupSize() throws Exception {
Fixture f = fixture();
Robot robot = new Robot();
robot.setAutoDelay(15);
Point original = MouseInfo.getPointerInfo().getLocation();
AtomicReference<TextArea> project = new AtomicReference<>();
AtomicReference<Window> source = new AtomicReference<>();
FxThread.onFx(() -> {
TextArea content = new TextArea("Project");
Dockable tool = new Dockable(new DockableId("project"), content);
tool.setTitle("Project");
f.manager.open(tool, DockTarget.area("tools"));
f.manager.setGroupCollapsed(toolGroup(f.manager).id(), true);
var screen = Screen.getPrimary().getVisualBounds();
f.manager.move(new DockableId("notes"), DockTarget.floating(new javafx.geometry.Rectangle2D(
screen.getMaxX() - 430, screen.getMinY() + 50, 400, 320)));
project.set(content);
source.set(f.notes.getScene().getWindow());
f.notes.selectRange(2, 4);
});
var watchdog = Executors.newSingleThreadScheduledExecutor();
watchdog.schedule(() -> robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK), 20, TimeUnit.SECONDS);
try {
await(() -> source.get().isFocused(), "The initial floating source must be focused");
var initial = onFx(f.manager::layout);
drag(robot, onFx(() -> headerPoint(f.notes)), onFx(() -> headerPoint(project.get())), () -> FxThread.onFx(() -> {
assertTrue(f.pane.lookup(".dock-drop-indicator").isVisible());
assertTrue(toolGroup(f.manager).collapsed());
assertSame(initial, f.manager.layout(), "The native preview must not expand an overlay");
}));
await(() -> f.notes.getScene().getWindow() == f.main, "The successful drop must move into the main overlay");
type(robot, f.notes, KeyEvent.VK_X, "abxef");
FxThread.onFx(() -> {
assertFalse(source.get().isShowing());
assertFalse(toolGroup(f.manager).collapsed());
assertEquals(DockGroupMode.OVERLAY, toolGroup(f.manager).mode());
assertEquals(new DockableId("notes"), toolGroup(f.manager).selectedDockableId());
assertEquals(240, owningTabs(f.notes).getWidth(), 1);
assertSame(f.notes, f.manager.findDockable(new DockableId("notes")).orElseThrow().getContent());
assertEquals("Project", project.get().getText());
});
} finally {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.keyRelease(KeyEvent.VK_X);
robot.mouseMove(original.x, original.y);
watchdog.shutdownNow();
FxThread.onFx(f::close);
}
}
private static DockLayoutView.Group toolGroup(DockingManager manager) {
return manager.layout().windows().getFirst().areas().stream().filter(area -> area.id().value().equals("tools"))
.findFirst().orElseThrow().groups().getFirst();
}
private static void drag(Robot robot, Point from, Point to, HeldCheck held) throws Exception {
robot.mouseMove(from.x, from.y);
Thread.sleep(100);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
try {
for (int step = 1; step <= 16; step++) {
robot.mouseMove(from.x + (to.x - from.x) * step / 16, from.y + (to.y - from.y) * step / 16);
Thread.sleep(25);
}
Thread.sleep(100);
held.run();
} finally { robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); }
}
private static void type(Robot robot, TextArea input, int key, String expected) throws Exception {
await(() -> input.getScene().getWindow().isFocused() && input.getScene().getFocusOwner() == input,
"The drop must focus the transferred editor without another click");
try { robot.keyPress(key); }
finally { robot.keyRelease(key); }
await(() -> expected.equals(input.getText()), "Native typing must use the retained selection/caret: " + expected);
}
private static Point headerPoint(TextArea content) {
TabPane tabs = owningTabs(content);
var tab = tabs.getTabs().stream().filter(candidate -> candidate.getContent() == content).findFirst().orElseThrow();
Node header = tabs.lookup("#" + tab.getId());
assertNotNull(header, "The transferred tab must retain an addressable docking header");
return center(header);
}
private static TabPane owningTabs(TextArea content) {
return content.getScene().getRoot().lookupAll(".tab-pane").stream()
.map(TabPane.class::cast).filter(candidate -> candidate.getTabs().stream()
.anyMatch(tab -> tab.getContent() == content)).findFirst().orElseThrow();
}
private static Point center(Node node) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
return new Point((int) bounds.getCenterX(), (int) bounds.getCenterY());
}
private static <T> T onFx(Supplier<T> action) throws Exception {
AtomicReference<T> result = new AtomicReference<>();
FxThread.onFx(() -> result.set(action.get()));
return result.get();
}
private static void await(BooleanSupplier condition, String message) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
boolean ready;
do {
Thread.sleep(25);
ready = onFx(condition::getAsBoolean);
} while (!ready && System.nanoTime() < deadline);
assertTrue(ready, message);
}
private static Fixture fixture() throws Exception {
return onFx(() -> {
List<Window> existing = List.copyOf(Window.getWindows());
DockPane pane = new DockPane();
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
DockGroupDefinition tools = new DockGroupDefinition("tools");
tools.setCollapsible(true);
tools.setMode(DockGroupMode.OVERLAY);
tools.setTabSide(javafx.geometry.Side.LEFT);
tools.setPreferredWidth(240);
pane.getInitialLayout().setLeft(tools);
Stage main = new Stage();
Label status = new Label("An invalid drop target inside the managed window");
status.setId("invalidTarget");
status.setMinHeight(30);
main.setScene(new Scene(new BorderPane(pane, new Label("Workspace"), null, status, null), 600, 440));
var screen = Screen.getPrimary().getVisualBounds();
main.setX(screen.getMinX() + 40);
main.setY(screen.getMinY() + 40);
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea notes = new TextArea("abcdef");
Dockable editor = new Dockable(new DockableId("notes"), notes);
editor.setTitle("Notes");
manager.open(editor, DockTarget.area("editors"));
main.show();
manager.activate(editor.getId());
notes.selectRange(2, 4);
return new Fixture(main, pane, manager, notes, existing);
});
}
private record Fixture(Stage main, DockPane pane, DockingManager manager, TextArea notes, List<Window> existing) {
void close() {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
}
@FunctionalInterface
private interface HeldCheck { void run() throws Exception; }
}