diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/NativeDragDockingApp.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/NativeDragDockingApp.java new file mode 100644 index 0000000..f803c50 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/NativeDragDockingApp.java @@ -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."); + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/NativeDragDockingMain.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/NativeDragDockingMain.java new file mode 100644 index 0000000..2444e24 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/NativeDragDockingMain.java @@ -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); + } +} diff --git a/fx/README.md b/fx/README.md index b2e698c..2da7d09 100644 --- a/fx/README.md +++ b/fx/README.md @@ -11,6 +11,7 @@ - [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. - [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. - [Dependency injection](../injection/README.md). diff --git a/fx/docs/docking-drag.md b/fx/docs/docking-drag.md index 6714c22..067f9a3 100644 --- a/fx/docs/docking-drag.md +++ b/fx/docs/docking-drag.md @@ -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 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. 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 -cancels a pending gesture. Releasing over another part of the managed window, -outside the docking groups, leaves the Dockable in place. +cancels a pending gesture. Releasing over another part of a managed window, +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 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. 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. -This slice covers the main window. Floating and cross-window pointer delivery -extend these gestures in their respective tickets. -The gesture regression tests fire JavaFX events at visible tab headers and -observe the public manager state. Those tests do not by themselves establish -native mouse delivery across windows; that has a separate desktop acceptance -sequence. +## Window routing and input delivery + +The interaction uses ordinary JavaFX mouse pressed/dragged/released events and +their screen coordinates to resolve a destination across the same manager's +main and floating windows. It does not start the JavaFX Dragboard protocol or +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. diff --git a/fx/docs/docking-floating.md b/fx/docs/docking-floating.md index 8b5036b..5c24d19 100644 --- a/fx/docs/docking-floating.md +++ b/fx/docs/docking-floating.md @@ -43,7 +43,8 @@ module for a desktop demonstration: 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 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) 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 (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. +transfers on that environment. Cross-window pointer dragging has its separate +[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: diff --git a/fx/src/main/java/de/neitzel/fx/docking/DockDragController.java b/fx/src/main/java/de/neitzel/fx/docking/DockDragController.java index 392c680..91f91a6 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/DockDragController.java +++ b/fx/src/main/java/de/neitzel/fx/docking/DockDragController.java @@ -15,6 +15,7 @@ import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; +import javafx.stage.Stage; import java.util.HashMap; import java.util.HashSet; @@ -29,10 +30,13 @@ final class DockDragController { } private record Proposal(DockTarget target, Bounds marker) { } private record Header(DockableId id, Bounds bounds) { } + private record Destination(DockDragController controller, Proposal proposal) { } private final DockingManager manager; private final DockPane pane; private final Scene scene; + private final Stage window; + private final javafx.beans.value.ChangeListener windowFocus; private final Supplier> surfaces; private final Map headers = new HashMap<>(); private final EventHandler mouseHandler = this::mouse; @@ -42,11 +46,20 @@ final class DockDragController { private double startY; private boolean dragging; private long nextHeaderId; + private long frontOrder; + private javafx.stage.Popup floatingPreview; + private javafx.scene.shape.Rectangle floatingFrame; DockDragController(DockingManager manager, DockPane pane, Supplier> surfaces) { this.manager = manager; this.pane = pane; 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; pane.addEventFilter(MouseEvent.ANY, mouseHandler); scene.addEventFilter(KeyEvent.KEY_PRESSED, keyHandler); @@ -142,8 +155,15 @@ final class DockDragController { void dispose() { pane.removeEventFilter(MouseEvent.ANY, mouseHandler); scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler); + window.focusedProperty().removeListener(windowFocus); headers.clear(); cancel(); + if (floatingPreview != null) { + floatingPreview.getScene().removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler); + floatingPreview.getContent().clear(); + floatingPreview = null; + floatingFrame = null; + } } private void mouse(MouseEvent event) { @@ -169,23 +189,83 @@ final class DockDragController { boolean apply = dragging; cancel(); if (apply) { - Proposal proposal = proposal(id, event.getScreenX(), event.getScreenY()); - if (proposal != null) manager.move(id, proposal.target()); + Destination destination = destination(id, event.getScreenX(), event.getScreenY()); + 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(); } } } private void preview(double screenX, double screenY) { - Proposal proposal = proposal(pressed, screenX, screenY); - if (proposal != null) { - MoveCheck check = manager.checkMove(pressed, proposal.target()); - if (!(check instanceof MoveCheck.Rejected)) { - pane.showDropIndicator(proposal.marker(), check instanceof MoveCheck.NoChange); - return; + Destination destination = destination(pressed, screenX, screenY); + Proposal proposal = destination == null ? null : destination.proposal(); + MoveCheck check = proposal == null ? null : manager.checkMove(pressed, proposal.target()); + boolean accepted = check != null && !(check instanceof MoveCheck.Rejected); + boolean floating = accepted && destination.controller() == null; + 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(); + 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) { @@ -335,7 +415,9 @@ final class DockDragController { private void key(KeyEvent event) { if (pressed != null && event.getCode() == KeyCode.ESCAPE) { + DockableId id = pressed; cancel(); + manager.restoreDragFocus(id); event.consume(); } } @@ -343,6 +425,6 @@ final class DockDragController { private void cancel() { pressed = null; dragging = false; - pane.hideDropIndicator(); + hidePreviews(); } } diff --git a/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java b/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java index 67fd767..3b6e23f 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java +++ b/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java @@ -35,6 +35,7 @@ public final class DockingManager { private final java.util.Set allocatedAreaIds = new java.util.HashSet<>(); private long nextGroupId; private long nextWindowId; + private long nextWindowFocusOrder; private final Map floatingWindows = new LinkedHashMap<>(); private final Map groupWindows = new LinkedHashMap<>(); private final Map returnTargets = new LinkedHashMap<>(); @@ -341,8 +342,8 @@ public final class DockingManager { 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); + receiver.tabs.getTabs().add(insertionIndex, tab); tab.setContent(dockables.get(id).getContent()); receiver.tabs.getSelectionModel().select(tab); normalizeLayout(source.id); @@ -935,6 +936,24 @@ public final class DockingManager { 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 dragControllers() { + var controllers = new java.util.ArrayList(); + 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) { FloatingWindowConfiguration configuration = new FloatingWindowConfiguration(); try { diff --git a/fx/src/test/java/de/neitzel/fx/view/NativeDockDragTest.java b/fx/src/test/java/de/neitzel/fx/view/NativeDockDragTest.java new file mode 100644 index 0000000..a22a292 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/NativeDockDragTest.java @@ -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