From af5a4278fdd312b9176f87788178839fa87a93a1 Mon Sep 17 00:00:00 2001 From: Konrad Neitzel Date: Sun, 15 Nov 2026 20:20:50 +0100 Subject: [PATCH] feat(fx): move live tabs with checked destinations and drag previews --- .../fx/example/docking/DockingApp.java | 18 +- fx/README.md | 2 +- fx/docs/docking-drag.md | 28 ++ fx/docs/docking.md | 58 +++- .../fx/docking/DockDragController.java | 202 ++++++++++++ .../de/neitzel/fx/docking/DockFailure.java | 3 +- .../java/de/neitzel/fx/docking/DockPane.java | 26 ++ .../de/neitzel/fx/docking/DockTarget.java | 8 + .../java/de/neitzel/fx/docking/Dockable.java | 1 + .../de/neitzel/fx/docking/DockingManager.java | 141 +++++++- .../de/neitzel/fx/docking/DockingOptions.java | 6 + .../java/de/neitzel/fx/docking/MoveCheck.java | 8 + .../de/neitzel/fx/docking/PlacementRule.java | 10 + .../fx/docking/ResolvedDockTarget.java | 6 + .../de/neitzel/fx/docking/TabPosition.java | 17 + .../fx/view/ActivateDockingWindowTest.java | 34 +- .../de/neitzel/fx/view/MoveDockablesTest.java | 215 ++++++++++++ .../fx/view/MoveTabsByGestureTest.java | 311 ++++++++++++++++++ 18 files changed, 1077 insertions(+), 17 deletions(-) create mode 100644 fx/docs/docking-drag.md create mode 100644 fx/src/main/java/de/neitzel/fx/docking/DockDragController.java create mode 100644 fx/src/main/java/de/neitzel/fx/docking/MoveCheck.java create mode 100644 fx/src/main/java/de/neitzel/fx/docking/PlacementRule.java create mode 100644 fx/src/main/java/de/neitzel/fx/docking/ResolvedDockTarget.java create mode 100644 fx/src/main/java/de/neitzel/fx/docking/TabPosition.java create mode 100644 fx/src/test/java/de/neitzel/fx/view/MoveDockablesTest.java create mode 100644 fx/src/test/java/de/neitzel/fx/view/MoveTabsByGestureTest.java diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/DockingApp.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/DockingApp.java index 1e96f6c..b3ac064 100644 --- a/fx-example/src/main/java/de/neitzel/fx/example/docking/DockingApp.java +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/DockingApp.java @@ -1,6 +1,7 @@ package de.neitzel.fx.example.docking; import de.neitzel.fx.docking.DockGroupDefinition; +import de.neitzel.fx.docking.ActionResult; import de.neitzel.fx.docking.DockLayout; import de.neitzel.fx.docking.DockPane; import de.neitzel.fx.docking.DockTarget; @@ -15,6 +16,7 @@ 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; @@ -25,8 +27,12 @@ public final class DockingApp extends Application { DockPane pane = getParameters().getRaw().contains("--fxml") ? FXMLLoader.load(DockingApp.class.getResource("Docking.fxml")) : initialPane(); Button activate = new Button("Activate Notes"); + Button toTools = new Button("Move Notes to tools"); + Button toEditors = new Button("Move Notes to editors"); + Label status = new Label("Drag a tab or use its context menu to move it."); BorderPane shell = new BorderPane(pane); - shell.setTop(activate); + shell.setTop(new ToolBar(activate, toTools, toEditors)); + shell.setBottom(status); stage.setScene(new Scene(shell, 900, 600)); DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); DockableId notesId = new DockableId("notes"); @@ -42,11 +48,21 @@ public final class DockingApp extends Application { project.setIcon(new Label("▦")); manager.open(project, DockTarget.area("tools")); activate.setOnAction(event -> manager.activate(notesId)); + toTools.setOnAction(event -> report(status, manager.move(notesId, DockTarget.area("tools")))); + toEditors.setOnAction(event -> report(status, manager.move(notesId, DockTarget.area("editors")))); stage.setTitle("NeitzelLib docking — Java or ordinary FXML"); stage.show(); manager.activate(notesId); } + 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.Rejected rejected -> rejected.failure().message(); + }); + } + private static DockPane initialPane() { DockLayout layout = new DockLayout(); layout.setCenter(new DockGroupDefinition("editors")); diff --git a/fx/README.md b/fx/README.md index cc61dbb..fbf0543 100644 --- a/fx/README.md +++ b/fx/README.md @@ -9,7 +9,7 @@ - [Generated ViewModel classes and registries](docs/generated-viewmodels.md). - [Bounded integer spinners](docs/integer-spinners.md) and [system tray support](docs/tray-support.md). - [Standalone toolbar and status bar](docs/bars.md), usable without MVVM. -- [Docking: opening 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. - [Dependency injection](../injection/README.md). ## Introduction diff --git a/fx/docs/docking-drag.md b/fx/docs/docking-drag.md new file mode 100644 index 0000000..5cfee84 --- /dev/null +++ b/fx/docs/docking-drag.md @@ -0,0 +1,28 @@ +# Moving tabs in the main window + +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 +the same group. The tab's text/icon bindings and its live content stay intact. +All four tab sides are supported. + +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. + +Every tab also provides a **Move to** context submenu. It lists the currently +available groups and the selected content's current title. Rejected targets +are disabled with their reason; selecting an enabled item invokes the same +manager move operation and rechecks the destination. + +The preview is mouse-transparent and has CSS class `dock-drop-indicator`. +Its `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. Splitting, floating, cross-window pointer +delivery and edge overlays 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. diff --git a/fx/docs/docking.md b/fx/docs/docking.md index ef4128d..a553a0a 100644 --- a/fx/docs/docking.md +++ b/fx/docs/docking.md @@ -11,8 +11,8 @@ to a `DockPane`, and embed that pane in your main Stage's Scene. Then call `DockingManager.attach(stage, pane, new DockingOptions())`. Attachment is allowed before showing the Stage. A pane and main Stage can each have one active manager. The initial definition is captured; later changes to the definition do not alter -the attached layout. `DockingOptions` currently has no policy fields in this -first implementation slice. +the attached layout. The manager also captures the placement rule from +`DockingOptions`; replacing that option later does not replace the live policy. A Dockable consists of a stable `DockableId` and the existing content Node. Use `open(dockable, DockTarget.area("editors"))` to open it. Opening an ID that @@ -36,14 +36,60 @@ destinations are included. A selected-tab change publishes its completed state. application actions. Moving keyboard focus to a global button preserves it. `activate(id)` selects the Dockable and requests focus within its content. -The content instance remains owned by the application. Future docking slices -extend this API with movement, splits, close consent and restoration. +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. Future slices add splits, close consent +and restoration. + +## Move and check placement + +The [pointer and context-menu guide](docking-drag.md) describes drag previews, +relative insertion and cancellation in the main window. + +`move(id, target)` transfers the same content instance to a named area or a +concrete group. An area's default insertion position is the end. Group targets +also accept `TabPosition.before(id)` and `after(id)` for exact ordering. + +```java +var destination = DockTarget.group(toolsGroupId, TabPosition.before(projectId)); +MoveCheck check = manager.checkMove(notesId, destination); +if (check instanceof MoveCheck.Allowed) { + ActionResult result = manager.move(notesId, destination); + // Handle Applied, NoChange or Rejected in application presentation code. +} +``` + +The check reports the currently resolved insertion, no change or a rejection. +It does not mutate the layout. Execution resolves and checks again, so menus +must handle a later rejection. Missing groups and missing reference tabs have +distinct failure codes. One successful move publishes its completed layout +once and selects, activates and focuses the destination content. + +Set `DockingOptions.setPlacementRule` before attachment to supply a policy. +It receives the Dockable and concrete proposed destination, returning an empty +Optional to permit it or a DockFailure to reject it. The rule must be +side-effect-free. Opening and moving use the same policy; a thrown policy +exception becomes a diagnostic rejection without a layout change. + +## Lazy content and rejected opens + +`open(id, factory, target)` calls the factory on the FX thread only when the +ID is not already open. Reopening an ID activates its existing content, even +when the caller specifies a different destination. Use move to change placement. + +If the manager-created content is rejected, its `onDiscarded` callback releases +resources exactly once for that preparation. A directly supplied Dockable +stays with the caller on rejection. A failed discard is reported through the +original rejection: its diagnostic cause retains any original cause and lists +the cleanup exception as a suppressed exception. Moving does not discard content. +Factory load failures and mismatched IDs are rejected with diagnostics; a +factory cannot discard an instance that is already open. ## Java and FXML example The `fx-example` module includes `de.neitzel.fx.example.docking.DockingMain`. Its Java-built layout and `--fxml` variant open the same editor and right-side -tool groups. It demonstrates unsaved editor text, tab selection and a global -Activate Notes action without MVVM. Build the reactor with Java 25, then launch +tool groups. It demonstrates unsaved editor text, tab selection, activation and +movement without MVVM. Build the reactor with Java 25, then launch that main class using the example's runtime dependencies; no Designer build is required. diff --git a/fx/src/main/java/de/neitzel/fx/docking/DockDragController.java b/fx/src/main/java/de/neitzel/fx/docking/DockDragController.java new file mode 100644 index 0000000..f555232 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/docking/DockDragController.java @@ -0,0 +1,202 @@ +package de.neitzel.fx.docking; + +import javafx.event.EventHandler; +import javafx.geometry.Bounds; +import javafx.geometry.BoundingBox; +import javafx.geometry.Side; +import javafx.scene.Node; +import javafx.scene.Scene; +import javafx.scene.control.Tab; +import javafx.scene.control.TabPane; +import javafx.scene.control.ContextMenu; +import javafx.scene.control.Menu; +import javafx.scene.control.MenuItem; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyEvent; +import javafx.scene.input.MouseButton; +import javafx.scene.input.MouseEvent; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +/** Translates pointer gestures on tab headers into ordinary checked manager moves. */ +final class DockDragController { + record GroupSurface(DockGroupId id, TabPane tabs) { } + private record Proposal(DockTarget target, Bounds marker) { } + private record Header(DockableId id, Bounds bounds) { } + + private final DockingManager manager; + private final DockPane pane; + private final Scene scene; + private final Supplier> surfaces; + private final Map headers = new HashMap<>(); + private final EventHandler mouseHandler = this::mouse; + private final EventHandler keyHandler = this::key; + private DockableId pressed; + private double startX; + private double startY; + private boolean dragging; + private long nextHeaderId; + + DockDragController(DockingManager manager, DockPane pane, Supplier> surfaces) { + this.manager = manager; + this.pane = pane; + this.scene = pane.getScene(); + this.surfaces = surfaces; + pane.addEventFilter(MouseEvent.ANY, mouseHandler); + scene.addEventFilter(KeyEvent.KEY_PRESSED, keyHandler); + } + + void installTab(Tab tab, DockableId id) { + String headerId = "dock-tab-" + ++nextHeaderId; + tab.setId(headerId); + headers.put(headerId, id); + Menu destinations = new Menu("Move to"); + ContextMenu menu = new ContextMenu(destinations); + menu.setOnShowing(event -> populateDestinations(destinations, id)); + tab.setContextMenu(menu); + } + + private void populateDestinations(Menu menu, DockableId id) { + menu.getItems().clear(); + for (DockLayoutView.Window window : manager.layout().windows()) { + for (DockLayoutView.Area area : window.areas()) { + for (DockLayoutView.Group group : area.groups()) { + DockTarget target = DockTarget.group(group.id()); + MoveCheck check = manager.checkMove(id, target); + String selectedTitle = group.selectedDockableId() == null ? "" : manager + .findDockable(group.selectedDockableId()).map(Dockable::getTitle).orElse(""); + String label = group.id().value() + (selectedTitle.isBlank() ? "" : " — " + selectedTitle); + if (check instanceof MoveCheck.Rejected rejected) { + label += " (" + rejected.failure().message() + ")"; + } else if (check instanceof MoveCheck.NoChange) { + label += " (Already here)"; + } + MenuItem item = new MenuItem(label); + item.setDisable(!(check instanceof MoveCheck.Allowed)); + item.setOnAction(event -> manager.move(id, target)); + menu.getItems().add(item); + } + } + } + } + + void dispose() { + pane.removeEventFilter(MouseEvent.ANY, mouseHandler); + scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler); + headers.clear(); + cancel(); + } + + private void mouse(MouseEvent event) { + if (event.getEventType() == MouseEvent.MOUSE_PRESSED && event.getButton() == MouseButton.PRIMARY) { + cancel(); + for (Node node = event.getPickResult().getIntersectedNode(); node != null; node = node.getParent()) { + DockableId id = headers.get(node.getId()); + if (id != null) { + pressed = id; + startX = event.getScreenX(); + startY = event.getScreenY(); + break; + } + } + } else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED && pressed != null) { + dragging |= Math.hypot(event.getScreenX() - startX, event.getScreenY() - startY) >= 5; + if (dragging) { + preview(event.getScreenX(), event.getScreenY()); + event.consume(); + } + } else if (event.getEventType() == MouseEvent.MOUSE_RELEASED && pressed != null) { + DockableId id = pressed; + boolean apply = dragging; + cancel(); + if (apply) { + Proposal proposal = proposal(event.getScreenX(), event.getScreenY()); + if (proposal != null) manager.move(id, proposal.target()); + event.consume(); + } + } + } + + private void preview(double screenX, double screenY) { + Proposal proposal = proposal(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; + } + } + pane.hideDropIndicator(); + } + + private Proposal proposal(double screenX, double screenY) { + for (GroupSurface group : surfaces.get()) { + Bounds bounds = group.tabs().localToScreen(group.tabs().getBoundsInLocal()); + if (bounds == null || !bounds.contains(screenX, screenY)) continue; + Node strip = group.tabs().lookup(".tab-header-area"); + Bounds stripBounds = strip == null ? null : strip.localToScreen(strip.getBoundsInLocal()); + if (stripBounds != null && stripBounds.contains(screenX, screenY)) { + Proposal insertion = insertion(group, screenX, screenY); + if (insertion != null) return insertion; + } + return new Proposal(DockTarget.group(group.id()), bounds); + } + return null; + } + + private Proposal insertion(GroupSurface group, double x, double y) { + List
visible = group.tabs().getTabs().stream().map(tab -> { + Node node = group.tabs().lookup("#" + tab.getId()); + Bounds bounds = node == null ? null : node.localToScreen(node.getBoundsInLocal()); + return bounds == null ? null : new Header((DockableId) tab.getUserData(), bounds); + }).filter(java.util.Objects::nonNull).toList(); + if (visible.isEmpty()) return null; + Side side = group.tabs().getSide(); + boolean horizontal = side.isHorizontal(); + double direction = 1; + if (visible.size() > 1) { + double difference = center(visible.get(1).bounds(), horizontal) + - center(visible.getFirst().bounds(), horizontal); + if (difference != 0) direction = Math.signum(difference); + } + double coordinate = horizontal ? x : y; + for (Header header : visible) { + if (coordinate * direction < center(header.bounds(), horizontal) * direction) { + return new Proposal(DockTarget.group(group.id(), TabPosition.before(header.id())), + insertionMarker(header.bounds(), horizontal, direction < 0)); + } + } + Header last = visible.getLast(); + return new Proposal(DockTarget.group(group.id(), TabPosition.after(last.id())), + insertionMarker(last.bounds(), horizontal, direction > 0)); + } + + private static double center(Bounds bounds, boolean horizontal) { + return horizontal ? bounds.getCenterX() : bounds.getCenterY(); + } + + private static Bounds insertionMarker(Bounds bounds, boolean horizontal, boolean trailing) { + if (horizontal) { + double x = trailing ? bounds.getMaxX() : bounds.getMinX(); + return new BoundingBox(x - 1, bounds.getMinY(), 2, bounds.getHeight()); + } + double y = trailing ? bounds.getMaxY() : bounds.getMinY(); + return new BoundingBox(bounds.getMinX(), y - 1, bounds.getWidth(), 2); + } + + private void key(KeyEvent event) { + if (pressed != null && event.getCode() == KeyCode.ESCAPE) { + cancel(); + event.consume(); + } + } + + private void cancel() { + pressed = null; + dragging = false; + pane.hideDropIndicator(); + } +} diff --git a/fx/src/main/java/de/neitzel/fx/docking/DockFailure.java b/fx/src/main/java/de/neitzel/fx/docking/DockFailure.java index 0955f88..96349a9 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/DockFailure.java +++ b/fx/src/main/java/de/neitzel/fx/docking/DockFailure.java @@ -2,5 +2,6 @@ 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 { TARGET_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED } + public enum Code { TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED, + PLACEMENT_REJECTED, PLACEMENT_CHECK_FAILED, ID_MISMATCH, FACTORY_FAILED } } diff --git a/fx/src/main/java/de/neitzel/fx/docking/DockPane.java b/fx/src/main/java/de/neitzel/fx/docking/DockPane.java index 459c1c9..072b2a2 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/DockPane.java +++ b/fx/src/main/java/de/neitzel/fx/docking/DockPane.java @@ -2,6 +2,9 @@ package de.neitzel.fx.docking; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Region; +import javafx.geometry.Bounds; +import javafx.scene.paint.Color; +import javafx.scene.shape.Rectangle; import lombok.Getter; import lombok.Setter; @@ -9,11 +12,34 @@ import lombok.Setter; public final class DockPane extends Region { @Getter @Setter private DockLayout initialLayout = new DockLayout(); final BorderPane surface = new BorderPane(); + private final Rectangle dropIndicator = new Rectangle(); DockingManager manager; public DockPane() { getStyleClass().add("dock-pane"); getChildren().add(surface); + dropIndicator.getStyleClass().add("dock-drop-indicator"); + dropIndicator.setManaged(false); + dropIndicator.setMouseTransparent(true); + dropIndicator.setVisible(false); + dropIndicator.setStrokeWidth(2); + getChildren().add(dropIndicator); + } + + void showDropIndicator(Bounds screenBounds, boolean noChange) { + Bounds local = screenToLocal(screenBounds); + dropIndicator.setX(local.getMinX()); + dropIndicator.setY(local.getMinY()); + dropIndicator.setWidth(local.getWidth()); + dropIndicator.setHeight(local.getHeight()); + dropIndicator.setFill(noChange ? Color.rgb(100, 100, 100, .15) : Color.rgb(30, 144, 255, .18)); + dropIndicator.setStroke(noChange ? Color.GRAY : Color.DODGERBLUE); + dropIndicator.pseudoClassStateChanged(javafx.css.PseudoClass.getPseudoClass("no-change"), noChange); + dropIndicator.setVisible(true); + } + + void hideDropIndicator() { + dropIndicator.setVisible(false); } @Override protected void layoutChildren() { surface.resizeRelocate(0, 0, getWidth(), getHeight()); } diff --git a/fx/src/main/java/de/neitzel/fx/docking/DockTarget.java b/fx/src/main/java/de/neitzel/fx/docking/DockTarget.java index b02a85e..d8baf41 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/DockTarget.java +++ b/fx/src/main/java/de/neitzel/fx/docking/DockTarget.java @@ -6,7 +6,15 @@ import java.util.Objects; public sealed interface DockTarget { static DockTarget area(String id) { return new Area(new DockAreaId(id)); } static DockTarget area(DockAreaId id) { return new Area(id); } + static DockTarget group(DockGroupId id, TabPosition position) { return new Group(id, position); } + static DockTarget group(DockGroupId id) { return group(id, TabPosition.append()); } record Area(DockAreaId id) implements DockTarget { public Area { Objects.requireNonNull(id, "id"); } } + record Group(DockGroupId id, TabPosition position) implements DockTarget { + public Group { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(position, "position"); + } + } } diff --git a/fx/src/main/java/de/neitzel/fx/docking/Dockable.java b/fx/src/main/java/de/neitzel/fx/docking/Dockable.java index d4c2af5..b470328 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/Dockable.java +++ b/fx/src/main/java/de/neitzel/fx/docking/Dockable.java @@ -16,6 +16,7 @@ public final class Dockable { @Getter private final DockableId id; @Getter private final Node content; @Getter @Setter private Supplier focusTarget; + @Getter @Setter private Runnable onDiscarded; private final StringProperty title = new SimpleStringProperty(this, "title", ""); private final ObjectProperty icon = new SimpleObjectProperty<>(this, "icon"); 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 fd8106d..b28d6a3 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java +++ b/fx/src/main/java/de/neitzel/fx/docking/DockingManager.java @@ -19,6 +19,8 @@ public final class DockingManager { private static final Object ATTACHMENT_KEY = new Object(); private final Stage stage; private final DockPane pane; + private final PlacementRule placementRule; + private final DockDragController drag; private boolean updating; private final Map groups = new LinkedHashMap<>(); private final Map dockables = new LinkedHashMap<>(); @@ -27,9 +29,10 @@ public final class DockingManager { private final ReadOnlyObjectWrapper active = new ReadOnlyObjectWrapper<>(this, "activeDockable"); private final ReadOnlyObjectWrapper layout = new ReadOnlyObjectWrapper<>(this, "layout"); - private DockingManager(Stage stage, DockPane pane) { + private DockingManager(Stage stage, DockPane pane, DockingOptions options) { this.stage = stage; this.pane = pane; + this.placementRule = Objects.requireNonNull(options.getPlacementRule(), "placementRule"); DockLayout initial = Objects.requireNonNull(pane.getInitialLayout(), "initialLayout"); validate(initial); addGroup(initial.getCenter(), pane.surface::setCenter); @@ -37,6 +40,8 @@ public final class DockingManager { addGroup(initial.getRight(), pane.surface::setRight); addGroup(initial.getTop(), pane.surface::setTop); addGroup(initial.getBottom(), pane.surface::setBottom); + drag = new DockDragController(this, pane, () -> groups.values().stream() + .map(group -> new DockDragController.GroupSurface(group.id, group.tabs)).toList()); publish(); stage.getScene().focusOwnerProperty().addListener(focusListener); } @@ -52,7 +57,7 @@ public final class DockingManager { if (pane.manager != null || stage.getProperties().containsKey(ATTACHMENT_KEY)) { throw new IllegalStateException("DockPane or main Stage already has a docking manager"); } - DockingManager manager = new DockingManager(stage, pane); + DockingManager manager = new DockingManager(stage, pane, options); pane.manager = manager; stage.getProperties().put(ATTACHMENT_KEY, manager); return manager; @@ -62,9 +67,10 @@ public final class DockingManager { requireFxThread(); Objects.requireNonNull(dockable, "dockable"); if (dockables.containsKey(dockable.getId())) return activate(dockable.getId()); - Objects.requireNonNull(target, "target"); - Group group = groups.get(((DockTarget.Area) target).id()); - if (group == null) return rejected(DockFailure.Code.TARGET_NOT_FOUND, dockable.getId(), "Destination does not exist"); + MoveCheck check = resolve(dockable, target); + if (check instanceof MoveCheck.Rejected rejected) return new ActionResult.Rejected(rejected.failure()); + var destination = (ResolvedDockTarget.Insertion) ((MoveCheck.Allowed) check).destination(); + Group group = group(destination.groupId()); 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"); } @@ -74,10 +80,11 @@ public final class DockingManager { tab.graphicProperty().bind(dockable.iconProperty()); tab.setContent(dockable.getContent()); tab.setUserData(dockable.getId()); + drag.installTab(tab, dockable.getId()); dockables.put(dockable.getId(), dockable); updating = true; try { - group.tabs.getTabs().add(tab); + group.tabs.getTabs().add(destination.index(), tab); group.tabs.getSelectionModel().select(tab); } finally { updating = false; @@ -88,6 +95,35 @@ public final class DockingManager { return new ActionResult.Applied(); } + /** Creates content only for a new identity; rejected prepared content is discarded. */ + public ActionResult open(DockableId id, java.util.function.Supplier factory, DockTarget target) { + requireFxThread(); + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(factory, "factory"); + if (dockables.containsKey(id)) return activate(id); + Dockable prepared; + try { + prepared = Objects.requireNonNull(factory.get(), "Factory returned no Dockable"); + } catch (RuntimeException failure) { + return new ActionResult.Rejected(new DockFailure(DockFailure.Code.FACTORY_FAILED, + id, "Dockable creation failed", failure)); + } + ActionResult result = id.equals(prepared.getId()) ? open(prepared, target) + : rejected(DockFailure.Code.ID_MISMATCH, id, "Factory returned a different Dockable ID"); + if (result instanceof ActionResult.Rejected rejected && !dockables.containsValue(prepared) + && prepared.getOnDiscarded() != null) { + try { + prepared.getOnDiscarded().run(); + } catch (RuntimeException cleanup) { + DockFailure failure = rejected.failure(); + var cause = new IllegalStateException("Cleanup failed after rejected open", failure.cause()); + cause.addSuppressed(cleanup); + return new ActionResult.Rejected(new DockFailure(failure.code(), failure.dockableId(), failure.message(), cause)); + } + } + return result; + } + public ActionResult activate(DockableId id) { requireFxThread(); Dockable dockable = dockables.get(id); @@ -116,6 +152,99 @@ public final class DockingManager { } public Optional findDockable(DockableId id) { return Optional.ofNullable(dockables.get(id)); } + + /** Resolves a move without mutating content, layout or identity allocation. */ + public MoveCheck checkMove(DockableId id, DockTarget target) { + requireFxThread(); + if (!dockables.containsKey(id)) return moveRejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open"); + return resolve(dockables.get(id), target); + } + + /** Moves the live content, selecting it only after the complete transfer. */ + public ActionResult move(DockableId id, DockTarget target) { + MoveCheck check = checkMove(id, target); + if (check instanceof MoveCheck.Rejected rejected) return new ActionResult.Rejected(rejected.failure()); + if (check instanceof MoveCheck.NoChange) return new ActionResult.NoChange(); + var destination = (ResolvedDockTarget.Insertion) ((MoveCheck.Allowed) check).destination(); + Group source = containing(id); + Group receiver = group(destination.groupId()); + Tab tab = source.tabs.getTabs().get(tabIndex(source, id)); + updating = true; + try { + tab.setContent(null); + source.tabs.getTabs().remove(tab); + receiver.tabs.getTabs().add(destination.index(), tab); + tab.setContent(dockables.get(id).getContent()); + receiver.tabs.getSelectionModel().select(tab); + } finally { + updating = false; + } + active.set(dockables.get(id)); + focus(active.get()); + publish(); + return new ActionResult.Applied(); + } + + private MoveCheck resolve(Dockable dockable, DockTarget target) { + DockableId id = dockable.getId(); + Objects.requireNonNull(target, "target"); + Group receiver; + TabPosition position; + if (target instanceof DockTarget.Area area) { + receiver = groups.get(area.id()); + position = TabPosition.append(); + } else { + DockTarget.Group concrete = (DockTarget.Group) target; + receiver = group(concrete.id()); + position = concrete.position(); + } + if (receiver == null) return moveRejected(DockFailure.Code.TARGET_NOT_FOUND, id, "Destination does not exist"); + int index = receiver.tabs.getTabs().size(); + DockableId reference = switch (position) { + case TabPosition.Before before -> before.id(); + case TabPosition.After after -> after.id(); + case TabPosition.Append ignored -> null; + }; + if (reference != null) { + index = tabIndex(receiver, reference); + if (index < 0) return moveRejected(DockFailure.Code.REFERENCE_TAB_NOT_FOUND, id, "Reference tab is not in the destination"); + if (position instanceof TabPosition.After) index++; + } + Group source = containing(id); + if (source == receiver) { + int oldIndex = tabIndex(source, id); + if (index > oldIndex) index--; + if (index == oldIndex) return new MoveCheck.NoChange(); + } + var resolved = new ResolvedDockTarget.Insertion(receiver.id, index); + try { + Optional failure = Objects.requireNonNull(placementRule.check(dockable, resolved), "Placement rule result"); + if (failure.isPresent()) return new MoveCheck.Rejected(failure.get()); + } catch (RuntimeException failure) { + return new MoveCheck.Rejected(new DockFailure(DockFailure.Code.PLACEMENT_CHECK_FAILED, + id, "Placement check failed", failure)); + } + return new MoveCheck.Allowed(resolved); + } + + private Group group(DockGroupId id) { + return groups.values().stream().filter(group -> group.id.equals(id)).findFirst().orElse(null); + } + + private Group containing(DockableId id) { + return groups.values().stream().filter(group -> tabIndex(group, id) >= 0).findFirst().orElse(null); + } + + private static int tabIndex(Group group, DockableId id) { + for (int i = 0; i < group.tabs.getTabs().size(); i++) { + if (id.equals(group.tabs.getTabs().get(i).getUserData())) return i; + } + return -1; + } + + private static MoveCheck moveRejected(DockFailure.Code code, DockableId id, String message) { + return new MoveCheck.Rejected(new DockFailure(code, id, message, null)); + } public Dockable activeDockable() { return active.get(); } public ReadOnlyObjectProperty activeDockableProperty() { return active.getReadOnlyProperty(); } public DockLayoutView layout() { return layout.get(); } diff --git a/fx/src/main/java/de/neitzel/fx/docking/DockingOptions.java b/fx/src/main/java/de/neitzel/fx/docking/DockingOptions.java index c13f5a8..b6e3778 100644 --- a/fx/src/main/java/de/neitzel/fx/docking/DockingOptions.java +++ b/fx/src/main/java/de/neitzel/fx/docking/DockingOptions.java @@ -1,5 +1,11 @@ package de.neitzel.fx.docking; +import lombok.Getter; +import lombok.Setter; +import java.util.Optional; + /** Attachment options. Additional policies are introduced with their operations. */ +@Getter @Setter public final class DockingOptions { + private PlacementRule placementRule = (dockable, target) -> Optional.empty(); } diff --git a/fx/src/main/java/de/neitzel/fx/docking/MoveCheck.java b/fx/src/main/java/de/neitzel/fx/docking/MoveCheck.java new file mode 100644 index 0000000..90215f4 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/docking/MoveCheck.java @@ -0,0 +1,8 @@ +package de.neitzel.fx.docking; + +/** Side-effect-free result of checking a proposed move. */ +public sealed interface MoveCheck { + record Allowed(ResolvedDockTarget destination) implements MoveCheck { } + record NoChange() implements MoveCheck { } + record Rejected(DockFailure failure) implements MoveCheck { } +} diff --git a/fx/src/main/java/de/neitzel/fx/docking/PlacementRule.java b/fx/src/main/java/de/neitzel/fx/docking/PlacementRule.java new file mode 100644 index 0000000..41197d7 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/docking/PlacementRule.java @@ -0,0 +1,10 @@ +package de.neitzel.fx.docking; + +import java.util.Optional; + +/** Application placement policy; evaluating it must not change the layout. */ +@FunctionalInterface +public interface PlacementRule { + /** Empty permits placement; a failure rejects it with an application explanation. */ + Optional check(Dockable dockable, ResolvedDockTarget destination); +} diff --git a/fx/src/main/java/de/neitzel/fx/docking/ResolvedDockTarget.java b/fx/src/main/java/de/neitzel/fx/docking/ResolvedDockTarget.java new file mode 100644 index 0000000..01b9c29 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/docking/ResolvedDockTarget.java @@ -0,0 +1,6 @@ +package de.neitzel.fx.docking; + +/** Concrete placement checked against the current layout, without allocating IDs. */ +public sealed interface ResolvedDockTarget { + record Insertion(DockGroupId groupId, int index) implements ResolvedDockTarget { } +} diff --git a/fx/src/main/java/de/neitzel/fx/docking/TabPosition.java b/fx/src/main/java/de/neitzel/fx/docking/TabPosition.java new file mode 100644 index 0000000..7ef9908 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/docking/TabPosition.java @@ -0,0 +1,17 @@ +package de.neitzel.fx.docking; + +import java.util.Objects; + +/** Stable relative insertion position in a tab group. */ +public sealed interface TabPosition { + static TabPosition append() { return new Append(); } + static TabPosition before(DockableId id) { return new Before(id); } + static TabPosition after(DockableId id) { return new After(id); } + record Append() implements TabPosition { } + record Before(DockableId id) implements TabPosition { + public Before { Objects.requireNonNull(id, "id"); } + } + record After(DockableId id) implements TabPosition { + public After { Objects.requireNonNull(id, "id"); } + } +} diff --git a/fx/src/test/java/de/neitzel/fx/view/ActivateDockingWindowTest.java b/fx/src/test/java/de/neitzel/fx/view/ActivateDockingWindowTest.java index 2831c62..4c70bea 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ActivateDockingWindowTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ActivateDockingWindowTest.java @@ -9,10 +9,14 @@ 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.animation.AnimationTimer; import javafx.application.Platform; import javafx.beans.value.ChangeListener; +import javafx.geometry.Bounds; import javafx.scene.Scene; import javafx.scene.control.TextArea; +import javafx.scene.input.MouseButton; +import javafx.scene.robot.Robot; import javafx.stage.Stage; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -78,16 +82,42 @@ class ActivateDockingWindowTest { ChangeListener listener = (observable, old, current) -> { if (current) focused.countDown(); }; + AnimationTimer clickAfterDisplay = new AnimationTimer() { + private int pulses; + + @Override + public void handle(long now) { + if (++pulses < 2) return; + stop(); + Bounds bounds = stage.getScene().getRoot().localToScreen( + stage.getScene().getRoot().getBoundsInLocal()); + Robot robot = new Robot(); + robot.mouseMove(bounds.getCenterX(), bounds.getCenterY()); + robot.mouseClick(MouseButton.PRIMARY); + if (stage.isFocused()) focused.countDown(); + } + }; FxThread.onFx(() -> { stage.focusedProperty().addListener(listener); + stage.setAlwaysOnTop(true); stage.toFront(); stage.requestFocus(); - if (stage.isFocused()) focused.countDown(); + stage.getScene().getRoot().applyCss(); + stage.getScene().getRoot().layout(); + clickAfterDisplay.start(); }); try { + // A native click activates the application even if the previous test or + // another application owned desktop focus. RequestFocus alone cannot + // establish that precondition reliably on macOS. Two pulses allow the + // newly shown native window to display before the Robot sends input. assertTrue(focused.await(5, TimeUnit.SECONDS), "Desktop did not focus the requested window"); } finally { - FxThread.onFx(() -> stage.focusedProperty().removeListener(listener)); + FxThread.onFx(() -> { + clickAfterDisplay.stop(); + stage.focusedProperty().removeListener(listener); + stage.setAlwaysOnTop(false); + }); } } diff --git a/fx/src/test/java/de/neitzel/fx/view/MoveDockablesTest.java b/fx/src/test/java/de/neitzel/fx/view/MoveDockablesTest.java new file mode 100644 index 0000000..b7b26d9 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/MoveDockablesTest.java @@ -0,0 +1,215 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.docking.*; +import javafx.scene.Scene; +import javafx.scene.control.TextArea; +import javafx.stage.Stage; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +/** Placement commands retain live contents and publish completed moves. */ +class MoveDockablesTest { + @BeforeAll static void start() throws InterruptedException { FxThread.start(); } + + @Test void anUnchangedPositionNeedsNoNewPlacementPermission() throws Exception { + FxThread.onFx(() -> { + DockPane pane = new DockPane(); + pane.getInitialLayout().setCenter(new DockGroupDefinition("editors")); + Stage stage = new Stage(); + stage.setScene(new Scene(pane)); + var allowed = new java.util.concurrent.atomic.AtomicBoolean(true); + DockingOptions options = new DockingOptions(); + options.setPlacementRule((dockable, destination) -> allowed.get() ? java.util.Optional.empty() + : java.util.Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, + dockable.getId(), "No new placements", null))); + DockingManager manager = DockingManager.attach(stage, pane, options); + Dockable dockable = new Dockable(new DockableId("notes"), new TextArea("Draft")); + manager.open(dockable, DockTarget.area("editors")); + DockLayoutView before = manager.layout(); + allowed.set(false); + assertInstanceOf(MoveCheck.NoChange.class, manager.checkMove(dockable.getId(), DockTarget.area("editors"))); + assertInstanceOf(ActionResult.NoChange.class, manager.move(dockable.getId(), DockTarget.area("editors"))); + assertSame(before, manager.layout()); + }); + } + + @Test void anIncorrectFactoryCannotDiscardAlreadyOpenContent() throws Exception { + FxThread.onFx(() -> { + DockPane pane = new DockPane(); + pane.getInitialLayout().setCenter(new DockGroupDefinition("editors")); + Stage stage = new Stage(); + stage.setScene(new Scene(pane)); + DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); + Dockable existing = new Dockable(new DockableId("existing"), new TextArea("Unsaved")); + AtomicInteger discards = new AtomicInteger(); + existing.setOnDiscarded(discards::incrementAndGet); + manager.open(existing, DockTarget.area("editors")); + assertInstanceOf(ActionResult.Rejected.class, manager.open(new DockableId("wrong"), + () -> existing, DockTarget.area("editors"))); + assertEquals(0, discards.get()); + assertSame(existing, manager.findDockable(existing.getId()).orElseThrow()); + }); + } + + @Test void aFailedFactoryReportsTheCauseWithoutOpeningContent() throws Exception { + FxThread.onFx(() -> { + DockPane pane = new DockPane(); + pane.getInitialLayout().setCenter(new DockGroupDefinition("editors")); + Stage stage = new Stage(); + stage.setScene(new Scene(pane)); + DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); + DockableId id = new DockableId("failed"); + RuntimeException failure = new IllegalStateException("Load failed"); + ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class, + manager.open(id, () -> { throw failure; }, DockTarget.area("editors"))); + assertSame(failure, rejected.failure().cause()); + assertEquals(id, rejected.failure().dockableId()); + assertTrue(manager.findDockable(id).isEmpty()); + }); + } + + @Test void aFactoryCannotOpenADifferentIdentityThanRequested() throws Exception { + FxThread.onFx(() -> { + DockPane pane = new DockPane(); + pane.getInitialLayout().setCenter(new DockGroupDefinition("editors")); + Stage stage = new Stage(); + stage.setScene(new Scene(pane)); + DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); + DockLayoutView before = manager.layout(); + DockableId requested = new DockableId("requested"); + Dockable wrong = new Dockable(new DockableId("wrong"), new TextArea("Draft")); + AtomicInteger discarded = new AtomicInteger(); + wrong.setOnDiscarded(discarded::incrementAndGet); + ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class, + manager.open(requested, () -> wrong, DockTarget.area("editors"))); + assertEquals(requested, rejected.failure().dockableId()); + assertSame(before, manager.layout()); + assertTrue(manager.findDockable(wrong.getId()).isEmpty()); + assertEquals(1, discarded.get()); + }); + } + + @Test void cleanupFailureIsReportedAlongsideThePlacementRejection() throws Exception { + FxThread.onFx(() -> { + DockPane pane = new DockPane(); + pane.getInitialLayout().setCenter(new DockGroupDefinition("editors")); + Stage stage = new Stage(); + stage.setScene(new Scene(pane)); + DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); + RuntimeException cleanup = new IllegalStateException("Listener release failed"); + Dockable prepared = new Dockable(new DockableId("notes"), new TextArea("Draft")); + prepared.setOnDiscarded(() -> { throw cleanup; }); + ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class, + manager.open(prepared.getId(), () -> prepared, DockTarget.area("missing"))); + assertEquals(DockFailure.Code.TARGET_NOT_FOUND, rejected.failure().code()); + assertSame(cleanup, rejected.failure().cause().getSuppressed()[0]); + assertTrue(manager.findDockable(prepared.getId()).isEmpty()); + }); + } + + @Test void rejectedFactoryContentIsDiscardedButPreparedContentRemainsWithItsCaller() throws Exception { + FxThread.onFx(() -> { + DockLayout initial = new DockLayout(); + initial.setCenter(new DockGroupDefinition("editors")); + DockPane pane = new DockPane(); + pane.setInitialLayout(initial); + Stage stage = new Stage(); + stage.setScene(new Scene(pane)); + DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); + AtomicInteger factories = new AtomicInteger(); + AtomicInteger discards = new AtomicInteger(); + DockableId notesId = new DockableId("notes"); + Dockable notes = new Dockable(notesId, new TextArea("Unsaved")); + notes.setOnDiscarded(discards::incrementAndGet); + assertInstanceOf(ActionResult.Rejected.class, manager.open(notesId, () -> { + factories.incrementAndGet(); + assertTrue(javafx.application.Platform.isFxApplicationThread()); + return notes; + }, DockTarget.area("missing"))); + assertEquals(1, factories.get()); + assertEquals(1, discards.get()); + assertTrue(manager.findDockable(notesId).isEmpty()); + Dockable prepared = new Dockable(new DockableId("prepared"), new TextArea("Draft")); + prepared.setOnDiscarded(discards::incrementAndGet); + assertInstanceOf(ActionResult.Rejected.class, manager.open(prepared, DockTarget.area("missing"))); + assertEquals(1, discards.get()); + manager.open(prepared, DockTarget.area("editors")); + manager.open(prepared.getId(), () -> { throw new AssertionError("Already open"); }, DockTarget.area("missing")); + assertSame(prepared, manager.findDockable(prepared.getId()).orElseThrow()); + assertEquals(1, discards.get()); + }); + } + + @Test void checksAreSideEffectFreeAndExecutionRechecksTheCapturedRule() throws Exception { + FxThread.onFx(() -> { + DockLayout initial = new DockLayout(); + initial.setCenter(new DockGroupDefinition("editors")); + initial.setRight(new DockGroupDefinition("tools")); + DockPane pane = new DockPane(); + pane.setInitialLayout(initial); + Stage stage = new Stage(); + stage.setScene(new Scene(pane)); + var allowed = new java.util.concurrent.atomic.AtomicBoolean(true); + DockingOptions options = new DockingOptions(); + options.setPlacementRule((dockable, target) -> allowed.get() ? java.util.Optional.empty() + : java.util.Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, + dockable.getId(), "Editor must remain here", null))); + DockingManager manager = DockingManager.attach(stage, pane, options); + Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Draft")); + manager.open(notes, DockTarget.area("editors")); + DockLayoutView before = manager.layout(); + assertInstanceOf(MoveCheck.Allowed.class, manager.checkMove(notes.getId(), DockTarget.area("tools"))); + assertSame(before, manager.layout()); + allowed.set(false); + options.setPlacementRule((dockable, target) -> java.util.Optional.empty()); + ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class, + manager.move(notes.getId(), DockTarget.area("tools"))); + assertEquals(DockFailure.Code.PLACEMENT_REJECTED, rejected.failure().code()); + assertSame(before, manager.layout()); + assertEquals(DockFailure.Code.TARGET_NOT_FOUND, assertInstanceOf(MoveCheck.Rejected.class, + manager.checkMove(notes.getId(), DockTarget.group(new DockGroupId("gone")))).failure().code()); + assertEquals(DockFailure.Code.REFERENCE_TAB_NOT_FOUND, assertInstanceOf(MoveCheck.Rejected.class, + manager.checkMove(notes.getId(), DockTarget.group(new DockGroupId("tools"), + TabPosition.after(new DockableId("gone"))))).failure().code()); + }); + } + + @Test void movesTheSameEditorBeforeAnotherTabAndPublishesOnce() throws Exception { + FxThread.onFx(() -> { + DockLayout initial = new DockLayout(); + initial.setCenter(new DockGroupDefinition("editors")); + initial.setRight(new DockGroupDefinition("tools")); + DockPane pane = new DockPane(); + pane.setInitialLayout(initial); + Stage stage = new Stage(); + stage.setScene(new Scene(pane, 800, 500)); + DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); + TextArea text = new TextArea("Unsaved notes"); + Dockable notes = new Dockable(new DockableId("notes"), text); + Dockable project = new Dockable(new DockableId("project"), new TextArea("Project")); + manager.open(notes, DockTarget.area("editors")); + manager.open(project, DockTarget.area("tools")); + text.selectRange(2, 7); + AtomicInteger changes = new AtomicInteger(); + manager.layoutProperty().addListener((observable, before, after) -> changes.incrementAndGet()); + var target = DockTarget.group(new DockGroupId("tools"), TabPosition.before(project.getId())); + assertInstanceOf(MoveCheck.Allowed.class, manager.checkMove(notes.getId(), target)); + assertEquals(0, changes.get()); + assertInstanceOf(ActionResult.Applied.class, manager.move(notes.getId(), target)); + assertEquals(1, changes.get()); + assertEquals(List.of(notes.getId(), project.getId()), manager.layout().windows().getFirst() + .areas().get(1).groups().getFirst().dockableIds()); + assertSame(text, manager.findDockable(notes.getId()).orElseThrow().getContent()); + assertEquals("Unsaved notes", text.getText()); + assertEquals(2, text.getSelection().getStart()); + assertEquals(7, text.getSelection().getEnd()); + assertSame(notes, manager.activeDockable()); + assertInstanceOf(MoveCheck.NoChange.class, manager.checkMove(notes.getId(), target)); + }); + } +} diff --git a/fx/src/test/java/de/neitzel/fx/view/MoveTabsByGestureTest.java b/fx/src/test/java/de/neitzel/fx/view/MoveTabsByGestureTest.java new file mode 100644 index 0000000..3112478 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/MoveTabsByGestureTest.java @@ -0,0 +1,311 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.docking.DockGroupDefinition; +import de.neitzel.fx.docking.DockLayout; +import de.neitzel.fx.docking.DockPane; +import de.neitzel.fx.docking.DockTarget; +import de.neitzel.fx.docking.Dockable; +import de.neitzel.fx.docking.DockableId; +import de.neitzel.fx.docking.DockingManager; +import de.neitzel.fx.docking.DockingOptions; +import javafx.application.Platform; +import javafx.geometry.Bounds; +import javafx.geometry.Side; +import javafx.scene.Node; +import javafx.scene.Scene; +import javafx.scene.control.Label; +import javafx.scene.control.TextArea; +import javafx.scene.control.ContextMenu; +import javafx.scene.control.Menu; +import javafx.scene.control.MenuItem; +import javafx.scene.control.TabPane; +import de.neitzel.fx.docking.DockFailure; +import javafx.scene.input.MouseButton; +import javafx.scene.input.MouseEvent; +import javafx.scene.input.PickResult; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyEvent; +import javafx.scene.layout.BorderPane; +import javafx.stage.Stage; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** User gestures operate on visible tab headers and the public docking state. */ +class MoveTabsByGestureTest { + @BeforeAll + static void startJavaFx() throws Exception { + FxThread.start(); + FxThread.onFx(() -> Platform.setImplicitExit(false)); + } + + @Test + void draggingAHeaderIntoAnotherGroupsContentAppendsItsLiveEditor() throws Exception { + FxThread.onFx(() -> { + DockLayout initial = new DockLayout(); + initial.setCenter(new DockGroupDefinition("editors")); + initial.setRight(new DockGroupDefinition("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()); + TextArea notes = new TextArea("Unsaved notes"); + Dockable editor = new Dockable(new DockableId("notes"), notes); + editor.setTitle("Notes"); + TextArea project = new TextArea("Project"); + Dockable tools = new Dockable(new DockableId("project"), project); + tools.setTitle("Project"); + manager.open(editor, DockTarget.area("editors")); + manager.open(tools, DockTarget.area("tools")); + stage.show(); + try { + pane.applyCss(); + pane.layout(); + Node header = header(pane, "Notes"); + Bounds from = header.localToScreen(header.getBoundsInLocal()); + Bounds into = project.localToScreen(project.getBoundsInLocal()); + mouse(header, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true); + mouse(header, MouseEvent.MOUSE_DRAGGED, into.getCenterX(), into.getCenterY(), true); + mouse(header, MouseEvent.MOUSE_RELEASED, into.getCenterX(), into.getCenterY(), false); + + assertEquals(List.of(tools.getId(), editor.getId()), manager.layout().windows().getFirst() + .areas().get(1).groups().getFirst().dockableIds()); + assertSame(notes, manager.findDockable(editor.getId()).orElseThrow().getContent()); + assertEquals("Unsaved notes", notes.getText()); + assertSame(editor, manager.activeDockable()); + } finally { + stage.hide(); + } + }); + } + + @ParameterizedTest + @EnumSource(Side.class) + void stripMarkerPreviewsTheInsertionPositionInEveryOrientation(Side side) throws Exception { + FxThread.onFx(() -> { + DockGroupDefinition group = new DockGroupDefinition("editors"); + group.setTabSide(side); + DockLayout initial = new DockLayout(); + initial.setCenter(group); + 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()); + for (String name : List.of("Alpha", "Beta", "Notes")) { + Dockable dockable = new Dockable(new DockableId(name), new TextArea(name)); + dockable.setTitle(name); + manager.open(dockable, DockTarget.area("editors")); + } + stage.show(); + try { + pane.applyCss(); + pane.layout(); + Node notes = header(pane, "Notes"); + Bounds from = notes.localToScreen(notes.getBoundsInLocal()); + Node alpha = header(pane, "Alpha"); + Bounds first = alpha.localToScreen(alpha.getBoundsInLocal()); + Node beta = header(pane, "Beta"); + Bounds second = beta.localToScreen(beta.getBoundsInLocal()); + boolean horizontal = side.isHorizontal(); + double direction = Math.signum(horizontal ? second.getCenterX() - first.getCenterX() + : second.getCenterY() - first.getCenterY()); + double x = first.getCenterX() - (horizontal ? direction * first.getWidth() / 3 : 0); + double y = first.getCenterY() - (horizontal ? 0 : direction * first.getHeight() / 3); + mouse(notes, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true); + mouse(notes, MouseEvent.MOUSE_DRAGGED, x, y, true); + + Node marker = pane.lookup(".dock-drop-indicator"); + assertNotNull(marker); + assertTrue(marker.isVisible()); + assertTrue(marker.isMouseTransparent()); + assertEquals(List.of(new DockableId("Alpha"), new DockableId("Beta"), new DockableId("Notes")), + manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().dockableIds()); + mouse(notes, MouseEvent.MOUSE_RELEASED, x, y, false); + assertEquals(List.of(new DockableId("Notes"), new DockableId("Alpha"), new DockableId("Beta")), + manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().dockableIds()); + assertFalse(marker.isVisible()); + } finally { + stage.hide(); + } + }); + } + + @Test + void escapeAndInvalidManagedWindowDropsPreservePlacement() throws Exception { + FxThread.onFx(() -> { + DockLayout initial = new DockLayout(); + initial.setCenter(new DockGroupDefinition("editors")); + initial.setRight(new DockGroupDefinition("tools")); + DockPane pane = new DockPane(); + pane.setInitialLayout(initial); + Label global = new Label("Global status outside the docking area"); + BorderPane shell = new BorderPane(pane); + shell.setTop(global); + Stage stage = new Stage(); + stage.setScene(new Scene(shell, 900, 500)); + DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); + TextArea notes = new TextArea("Keep this draft"); + Dockable editor = new Dockable(new DockableId("notes"), notes); + editor.setTitle("Notes"); + TextArea project = new TextArea("Project"); + Dockable tools = new Dockable(new DockableId("project"), project); + tools.setTitle("Project"); + manager.open(editor, DockTarget.area("editors")); + manager.open(tools, DockTarget.area("tools")); + stage.show(); + try { + shell.applyCss(); + shell.layout(); + Node header = header(pane, "Notes"); + Bounds from = header.localToScreen(header.getBoundsInLocal()); + Bounds into = project.localToScreen(project.getBoundsInLocal()); + var original = manager.layout(); + mouse(header, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true); + mouse(header, MouseEvent.MOUSE_DRAGGED, into.getCenterX(), into.getCenterY(), true); + javafx.event.Event.fireEvent(stage.getScene(), new KeyEvent(KeyEvent.KEY_PRESSED, + "", "", KeyCode.ESCAPE, false, false, false, false)); + mouse(header, MouseEvent.MOUSE_RELEASED, into.getCenterX(), into.getCenterY(), false); + assertEquals(original, manager.layout()); + assertFalse(pane.lookup(".dock-drop-indicator").isVisible()); + + Bounds invalid = global.localToScreen(global.getBoundsInLocal()); + mouse(header, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true); + mouse(header, MouseEvent.MOUSE_DRAGGED, invalid.getCenterX(), invalid.getCenterY(), true); + mouse(header, MouseEvent.MOUSE_RELEASED, invalid.getCenterX(), invalid.getCenterY(), false); + assertEquals(original, manager.layout()); + assertFalse(pane.lookup(".dock-drop-indicator").isVisible()); + assertEquals("Keep this draft", notes.getText()); + } finally { + stage.hide(); + } + }); + } + + @Test + void moveMenuUsesCurrentTitlesAndExplainsRejectedDestinations() throws Exception { + FxThread.onFx(() -> { + DockLayout initial = new DockLayout(); + initial.setCenter(new DockGroupDefinition("editors")); + initial.setRight(new DockGroupDefinition("tools")); + DockPane pane = new DockPane(); + pane.setInitialLayout(initial); + Stage stage = new Stage(); + stage.setScene(new Scene(pane, 900, 500)); + AtomicBoolean allowed = new AtomicBoolean(true); + DockingOptions options = new DockingOptions(); + options.setPlacementRule((dockable, target) -> allowed.get() ? Optional.empty() + : Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, + dockable.getId(), "Tools are locked", null))); + DockingManager manager = DockingManager.attach(stage, pane, options); + TextArea notes = new TextArea("Notes"); + Dockable editor = new Dockable(new DockableId("notes"), notes); + editor.setTitle("Notes"); + Dockable project = new Dockable(new DockableId("project"), new TextArea("Project")); + project.setTitle("Project"); + manager.open(editor, DockTarget.area("editors")); + manager.open(project, DockTarget.area("tools")); + stage.show(); + ContextMenu menu = null; + try { + pane.applyCss(); + pane.layout(); + var tab = pane.lookupAll(".tab-pane").stream().map(TabPane.class::cast) + .flatMap(tabs -> tabs.getTabs().stream()).filter(item -> item.getContent() == notes) + .findFirst().orElseThrow(); + menu = tab.getContextMenu(); + assertNotNull(menu); + project.setTitle("Changed files"); + allowed.set(false); + menu.show(stage, stage.getX() + 80, stage.getY() + 80); + Menu destinations = (Menu) menu.getItems().getFirst(); + MenuItem tools = destinations.getItems().stream() + .filter(item -> item.getText().contains("tools")).findFirst().orElseThrow(); + assertTrue(tools.getText().contains("Changed files")); + assertTrue(tools.getText().contains("Tools are locked")); + assertTrue(tools.isDisable()); + menu.hide(); + allowed.set(true); + menu.show(stage, stage.getX() + 80, stage.getY() + 80); + tools = destinations.getItems().stream() + .filter(item -> item.getText().contains("tools")).findFirst().orElseThrow(); + assertFalse(tools.isDisable()); + tools.fire(); + assertEquals(List.of(project.getId(), editor.getId()), manager.layout().windows().getFirst() + .areas().get(1).groups().getFirst().dockableIds()); + } finally { + if (menu != null) menu.hide(); + stage.hide(); + } + }); + } + + @ParameterizedTest + @EnumSource(Side.class) + void aDropBeforeTheOnlyTargetTabUsesVisualLeadingEdge(Side side) throws Exception { + FxThread.onFx(() -> { + DockLayout initial = new DockLayout(); + initial.setCenter(new DockGroupDefinition("editors")); + DockGroupDefinition tools = new DockGroupDefinition("tools"); + tools.setTabSide(side); + 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("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(); + Node source = header(pane, "Notes"); + Bounds from = source.localToScreen(source.getBoundsInLocal()); + Node target = header(pane, "Project"); + Bounds into = target.localToScreen(target.getBoundsInLocal()); + double x = into.getCenterX() - (side.isHorizontal() ? into.getWidth() / 3 : 0); + double y = into.getCenterY() - (side.isHorizontal() ? 0 : into.getHeight() / 3); + mouse(source, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true); + mouse(source, MouseEvent.MOUSE_DRAGGED, x, y, true); + mouse(source, MouseEvent.MOUSE_RELEASED, x, y, false); + assertEquals(List.of(notes.getId(), project.getId()), manager.layout().windows().getFirst() + .areas().get(1).groups().getFirst().dockableIds()); + } finally { + stage.hide(); + } + }); + } + + private static Node header(DockPane pane, String title) { + return pane.lookupAll(".tab").stream().filter(node -> { + Node label = node.lookup(".tab-label"); + return label instanceof Label text && title.equals(text.getText()); + }).findFirst().orElseThrow(); + } + + private static void mouse(Node source, javafx.event.EventType 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()))); + } +}