diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/KeyboardThemeDockingApp.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/KeyboardThemeDockingApp.java new file mode 100644 index 0000000..7b2a0e7 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/KeyboardThemeDockingApp.java @@ -0,0 +1,129 @@ +package de.neitzel.fx.example.docking; + +import de.neitzel.fx.control.StatusBar; +import de.neitzel.fx.docking.*; +import javafx.application.Application; +import javafx.geometry.Side; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.layout.BorderPane; +import javafx.scene.layout.VBox; +import javafx.stage.Stage; + +import java.util.List; +import java.util.ListResourceBundle; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** Keyboard menus, icon names, translated policy failures and a shared application theme. */ +public final class KeyboardThemeDockingApp extends Application { + @Override public void start(Stage stage) { + DockPane pane = new DockPane(); + pane.getInitialLayout().setCenter(new DockGroupDefinition("editors")); + DockGroupDefinition tools = new DockGroupDefinition("project"); + tools.setCollapsible(true); + tools.setTabSide(Side.LEFT); + tools.setPreferredWidth(220); + pane.getInitialLayout().setLeft(tools); + + Button focusTabs = new Button("Focus active tab strip"); + Button checkFloat = new Button("Check Float"); + CheckBox blockFloat = new CheckBox("Block floating"); + CheckBox missingKey = new CheckBox("Missing translation key"); + CheckBox allowClose = new CheckBox("Allow Notes to close"); + Label message = new Label("Focus a tab strip, press Shift+F10, then use arrows and Enter."); + message.setWrapText(true); + Label active = new Label(); + StatusBar status = new StatusBar(); + status.getLeftItems().add(message); + status.getRightItems().add(active); + BorderPane shell = new BorderPane(pane); + shell.setTop(new VBox(new ToolBar(focusTabs, checkFloat, blockFloat, missingKey), + new ToolBar(allowClose, new Label("Notes initially vetoes Close. Project is an icon-only tab.")))); + shell.setBottom(status); + String theme = getClass().getResource("KeyboardThemeDocking.css").toExternalForm(); + stage.setScene(new Scene(shell, 1000, 620)); + stage.getScene().getStylesheets().add(theme); + stage.setTitle("NeitzelLib — keyboard, names and application styles"); + + DockingOptions options = new DockingOptions(); + options.setResourceBundle(translations()); + options.setFloatingWindowCustomizer(configuration -> { + configuration.setTitle("Themed floating editor — Shift+F10 to return"); + configuration.getStylesheets().add(theme); + }); + options.setPlacementRule((dockable, target) -> blockFloat.isSelected() + && target instanceof ResolvedDockTarget.Detachment + ? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), + "Demo policy disabled detachment", null, + missingKey.isSelected() ? "demo.unknownKey" : "demo.floatingBlocked")) : Optional.empty()); + DockingManager manager = DockingManager.attach(stage, pane, options); + Dockable notes = editor("notes", "Notes", "abcdef\nMove this tab with its keyboard menu, then keep typing."); + Dockable readme = editor("readme", "Readme", "Move/Split/Float/Return use the same rules as dragging.\n" + + "Toggle Block floating and Missing translation key, then compare Check Float with the tab menu."); + Dockable project = editor("project", "", "Project files\nThis icon-only tab is named for assistive technology."); + project.setIcon(new Label("▦")); + project.setAccessibleName("Project files"); + project.setMainWindowOnly(true); + notes.setCloseCheck(request -> CompletableFuture.completedFuture( + allowClose.isSelected() ? CloseConsent.ALLOW : CloseConsent.VETO)); + notes.setOnClosed(() -> message.setText("Notes closed after consent.")); + manager.open(project, DockTarget.area("project")); + manager.open(readme, DockTarget.area("editors")); + manager.open(notes, DockTarget.area("editors")); + + focusTabs.setOnAction(event -> { + Dockable current = manager.activeDockable(); + if (current == null) return; + current.getContent().getScene().getRoot().lookupAll(".dock-group").stream() + .filter(node -> node instanceof TabPane tabs && tabs.getTabs().stream() + .anyMatch(tab -> tab.getContent() == current.getContent())) + .findFirst().ifPresent(node -> node.requestFocus()); + }); + checkFloat.setOnAction(event -> { + Dockable current = manager.activeDockable(); + if (current == null) return; + MoveCheck result = manager.checkMove(current.getId(), DockTarget.floating()); + message.setText(result instanceof MoveCheck.Rejected rejected + ? manager.describeFailure(rejected.failure()) + " [" + rejected.failure().code() + + "; key=" + rejected.failure().messageKey() + "]" + : "Float is available. Open the tab menu to execute it."); + }); + Runnable refresh = () -> { + Dockable current = manager.activeDockable(); + active.setText(current == null ? "No active tab" : current.getTitle().isBlank() + ? current.getAccessibleName() : current.getTitle()); + }; + manager.activeDockableProperty().addListener((observable, old, current) -> refresh.run()); + refresh.run(); + stage.setOnHidden(event -> { + for (Dockable dockable : List.of(notes, readme, project)) { + Scene scene = dockable.getContent().getScene(); + if (scene != null && scene.getWindow() != stage) scene.getWindow().hide(); + } + }); + stage.show(); + manager.activate(notes.getId()); + ((TextArea) notes.getContent()).selectRange(2, 4); + } + + private static Dockable editor(String id, String title, String text) { + Dockable dockable = new Dockable(new DockableId(id), new TextArea(text)); + dockable.setTitle(title); + return dockable; + } + + private static ListResourceBundle translations() { + return new ListResourceBundle() { + @Override protected Object[][] getContents() { + return new Object[][] { + {"dock.action.move", "Verschieben"}, {"dock.action.split", "Unterteilen"}, + {"dock.action.close", "Schließen"}, {"dock.action.float", "Abkoppeln"}, + {"dock.action.return", "Zurück ins Hauptfenster"}, {"dock.action.pin", "Gruppe anheften"}, + {"dock.failure.PLACEMENT_REJECTED", "Diese Platzierung ist nicht erlaubt"}, + {"demo.floatingBlocked", "Abkoppeln ist in dieser Ansicht gesperrt"} + }; + } + }; + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/KeyboardThemeDockingMain.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/KeyboardThemeDockingMain.java new file mode 100644 index 0000000..08dc3d7 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/KeyboardThemeDockingMain.java @@ -0,0 +1,9 @@ +package de.neitzel.fx.example.docking; + +import javafx.application.Application; + +/** Plain launcher for the keyboard and theme exercise. */ +public final class KeyboardThemeDockingMain { + private KeyboardThemeDockingMain() { } + public static void main(String[] args) { Application.launch(KeyboardThemeDockingApp.class, args); } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/ShutdownDockingApp.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/ShutdownDockingApp.java new file mode 100644 index 0000000..158ddbf --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/ShutdownDockingApp.java @@ -0,0 +1,215 @@ +package de.neitzel.fx.example.docking; + +import de.neitzel.fx.docking.*; +import javafx.application.Application; +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.scene.control.Button; +import javafx.scene.control.CheckBox; +import javafx.scene.control.ComboBox; +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.Stage; +import javafx.util.StringConverter; + +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; + +/** A visible save/retry workflow owns storage decisions while the manager owns close ordering. */ +public final class ShutdownDockingApp extends Application { + private final SimpleObjectProperty> pendingSave = new SimpleObjectProperty<>(); + private final SimpleObjectProperty> pendingConsent = new SimpleObjectProperty<>(); + private final SimpleBooleanProperty shutdownRequested = new SimpleBooleanProperty(); + private final SimpleBooleanProperty ended = new SimpleBooleanProperty(); + private final Label status = new Label(); + private final TextArea history = new TextArea(); + private final CheckBox delayFloating = new CheckBox("Delay Preview window consent"); + private final CheckBox lateVeto = new CheckBox("Preview vetoes last"); + private final CheckBox saveFails = new CheckBox("Simulate save failure"); + private final CheckBox throwShutdown = new CheckBox("Throw before saving"); + private final ComboBox nextOwnership = new ComboBox<>(); + private final Button quit = new Button("Quit workspace"); + private final Button replace = new Button("Replace workspace"); + private final Button applicationClose = new Button("Close application window"); + private DockingManager manager; + private DockPane pane; + private Stage stage; + private MainWindowCloseMode ownership; + private LayoutSnapshot pendingSnapshot; + private LayoutSnapshot savedSnapshot; + private int generation; + private int retries; + + @Override public void start(Stage stage) throws IOException { + this.stage = stage; + pane = FXMLLoader.load(ShutdownDockingApp.class.getResource("ShutdownDocking.fxml")); + status.setId("shutdown-status"); history.setId("shutdown-history"); + history.setEditable(false); history.setPrefRowCount(9); + lateVeto.setId("late-veto"); saveFails.setId("save-fails"); throwShutdown.setId("throw-shutdown"); + saveFails.setSelected(true); + delayFloating.setId("delay-floating-consent"); delayFloating.setSelected(true); + nextOwnership.setId("next-ownership"); + nextOwnership.getItems().setAll(MainWindowCloseMode.values()); + nextOwnership.setValue(MainWindowCloseMode.AUTOMATIC); + nextOwnership.setConverter(new StringConverter<>() { + @Override public String toString(MainWindowCloseMode value) { + return value == MainWindowCloseMode.AUTOMATIC ? "Library closes main" : "Application closes main"; + } + @Override public MainWindowCloseMode fromString(String text) { throw new UnsupportedOperationException("Selection only"); } + }); + quit.setId("quit-workspace"); replace.setId("replace-workspace"); applicationClose.setId("close-application-window"); + applicationClose.setDisable(true); + quit.setOnAction(event -> requestClose(false)); + replace.setOnAction(event -> requestClose(true)); + applicationClose.setOnAction(event -> stage.hide()); + Button retry = saveButton("Retry save", "retry-save", () -> attemptSave(false)); + Button proceed = saveButton("Save successfully", "proceed-save", () -> attemptSave(true)); + Button cancel = saveButton("Cancel shutdown", "cancel-save", () -> finishSave(ShutdownDecision.CANCEL, null)); + Button fail = saveButton("Fail asynchronously", "fail-save", () -> finishSave(null, + new IllegalStateException("Simulated asynchronous storage failure"))); + Button closePreview = new Button("Close Preview window"); closePreview.setId("close-preview-window"); + closePreview.disableProperty().bind(pendingConsent.isNotNull().or(shutdownRequested).or(ended)); + closePreview.setOnAction(event -> requestPreviewClose()); + Button allowPreview = consentButton("Allow Preview", "allow-preview", CloseConsent.ALLOW); + Button vetoPreview = consentButton("Veto Preview", "veto-preview", CloseConsent.VETO); + BorderPane shell = new BorderPane(pane); + shell.setTop(new VBox(new ToolBar(quit, replace, applicationClose), + new ToolBar(lateVeto, saveFails, throwShutdown), + new ToolBar(delayFloating, closePreview, allowPreview, vetoPreview), + new ToolBar(new Label("Next workspace:"), nextOwnership, retry, proceed, cancel, fail), status)); + shell.setBottom(history); + stage.setScene(new Scene(shell, 1100, 640)); + stage.setTitle("NeitzelLib — Quit, save and replace"); + stage.setOnCloseRequest(event -> { + if (ownership == MainWindowCloseMode.APPLICATION_COORDINATED && !ended.get()) { + event.consume(); requestClose(false); + } + }); + attachWorkspace(); + stage.show(); + } + + private Button saveButton(String text, String id, Runnable action) { + Button button = new Button(text); button.setId(id); + button.disableProperty().bind(pendingSave.isNull()); + button.setOnAction(event -> action.run()); return button; + } + + private Button consentButton(String text, String id, CloseConsent answer) { + Button button = new Button(text); button.setId(id); + button.disableProperty().bind(pendingConsent.isNull()); + button.setOnAction(event -> { + CompletableFuture pending = pendingConsent.get(); + if (pending == null) return; + pendingConsent.set(null); pending.complete(answer); + }); + return button; + } + + private void requestPreviewClose() { + var window = manager.layout().windows().stream().filter(candidate -> !candidate.main()) + .filter(candidate -> candidate.areas().stream().flatMap(area -> area.groups().stream()) + .anyMatch(group -> group.dockableIds().contains(new DockableId("preview")))).findFirst(); + if (window.isEmpty()) { status.setText("Preview is not in a floating window."); return; } + manager.requestFloatingWindowClose(window.get().id()).thenAccept(result -> { + log("Preview window: " + result); + if (!shutdownRequested.get()) status.setText("Preview window: " + result); + }); + } + + private void attachWorkspace() { + ownership = nextOwnership.getValue(); + DockingOptions options = new DockingOptions(); + options.setMainWindowCloseMode(ownership); + options.setBeforeShutdown(this::beforeShutdown); + options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("Preview — included in Quit and Replace")); + manager = DockingManager.attach(stage, pane, options); + ended.set(false); shutdownRequested.set(false); + quit.disableProperty().unbind(); replace.disableProperty().unbind(); + var scope = manager.closingScopeProperty(); + var globalBusy = javafx.beans.binding.Bindings.createBooleanBinding(() -> scope.get() != null + && (scope.get().kind() == CloseScope.Kind.MAIN_WINDOW || scope.get().kind() == CloseScope.Kind.MANAGER_ONLY), scope); + quit.disableProperty().bind(globalBusy.or(shutdownRequested).or(ended)); + replace.disableProperty().bind(globalBusy.or(shutdownRequested).or(ended)); + applicationClose.setDisable(true); + generation++; + manager.open(editor("notes", "Notes"), DockTarget.area("editors")); + manager.open(editor("project", "Project"), DockTarget.area("tools")); + manager.setGroupCollapsed(new DockGroupId("tools"), true); + manager.open(editor("preview", "Preview"), DockTarget.floating()); + status.setText("Workspace " + generation + " attached; Project is collapsed, Preview is floating."); + log("Attached workspace " + generation + " with " + ownership); + } + + private Dockable editor(String id, String title) { + TextArea content = new TextArea(title + " in workspace " + generation); content.setId(id + "-content"); + Dockable dockable = new Dockable(new DockableId(id), content); dockable.setTitle(title); + dockable.setCloseCheck(request -> { + log("Checked " + id + " in " + request.scope().kind() + "; all contents remain open."); + if (id.equals("preview") && delayFloating.isSelected() && request.scope().kind() == CloseScope.Kind.FLOATING_WINDOW) { + CompletableFuture answer = new CompletableFuture<>(); pendingConsent.set(answer); + status.setText("Preview consent pending; Quit can wait for this window."); + return answer; + } + boolean veto = id.equals("preview") && lateVeto.isSelected(); + if (veto) status.setText("Late veto from Preview; no content was closed."); + return CompletableFuture.completedFuture(veto ? CloseConsent.VETO : CloseConsent.ALLOW); + }); + dockable.setOnClosed(() -> log("Released " + id)); + return dockable; + } + + private CompletionStage beforeShutdown(ShutdownRequest request) { + if (throwShutdown.isSelected()) throw new IllegalStateException("Simulated synchronous save setup failure"); + pendingSnapshot = request.snapshot(); retries = 0; + log("Snapshot " + request.reason() + ": " + pendingSnapshot.windows().size() + " windows before any content closes."); + status.setText("Save pending: " + request.reason() + ". Retry, save successfully, cancel or fail."); + CompletableFuture decision = new CompletableFuture<>(); pendingSave.set(decision); + return decision; + } + + private void attemptSave(boolean forceSuccess) { + if (pendingSave.get() == null) return; + if (!forceSuccess && saveFails.isSelected()) { + retries++; status.setText("Retry failed (" + retries + "); the same shutdown remains pending."); + log("Retry " + retries + " failed; every window and editor stays open."); return; + } + savedSnapshot = pendingSnapshot; + log("Saved " + savedSnapshot.windows().size() + " windows in application-owned memory."); + finishSave(ShutdownDecision.PROCEED, null); + } + + private void finishSave(ShutdownDecision decision, RuntimeException failure) { + CompletableFuture pending = pendingSave.get(); + if (pending == null) return; + pendingSave.set(null); pendingSnapshot = null; + status.setText(failure == null ? "Save decision: " + decision : "Save failed: " + failure.getMessage()); + if (failure == null) pending.complete(decision); else pending.completeExceptionally(failure); + } + + private void requestClose(boolean replaceWorkspace) { + CloseScope scope = manager.closingScopeProperty().get(); + if (scope != null && scope.kind() == CloseScope.Kind.FLOATING_WINDOW) { + status.setText((replaceWorkspace ? "Replacement" : "Quit") + " waiting for Preview consent."); + } + shutdownRequested.set(true); + CompletionStage request = replaceWorkspace ? manager.requestManagerClose() : manager.requestMainWindowClose(); + request.thenAccept(result -> { + shutdownRequested.set(false); + status.setText(result.toString()); log(result.toString()); + if (result instanceof CloseResult.Closed) { + ended.set(true); + if (replaceWorkspace) attachWorkspace(); + else if (ownership == MainWindowCloseMode.APPLICATION_COORDINATED) applicationClose.setDisable(false); + } + }); + } + + private void log(String message) { history.appendText(message + "\n"); } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/ShutdownDockingMain.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/ShutdownDockingMain.java new file mode 100644 index 0000000..47cd130 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/ShutdownDockingMain.java @@ -0,0 +1,9 @@ +package de.neitzel.fx.example.docking; + +import javafx.application.Application; + +/** Plain launcher for the application-owned shutdown/save workflow. */ +public final class ShutdownDockingMain { + private ShutdownDockingMain() { } + public static void main(String[] args) { Application.launch(ShutdownDockingApp.class, args); } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/SnapshotDockingApp.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/SnapshotDockingApp.java index 3a69aef..1db7c76 100644 --- a/fx-example/src/main/java/de/neitzel/fx/example/docking/SnapshotDockingApp.java +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/SnapshotDockingApp.java @@ -1,6 +1,9 @@ package de.neitzel.fx.example.docking; import de.neitzel.fx.docking.DockPane; +import de.neitzel.fx.docking.ActionResult; +import de.neitzel.fx.docking.DockFailure; +import de.neitzel.fx.docking.DockGroupId; import de.neitzel.fx.docking.DockTarget; import de.neitzel.fx.docking.Dockable; import de.neitzel.fx.docking.DockableId; @@ -9,8 +12,10 @@ import de.neitzel.fx.docking.DockingManager; import de.neitzel.fx.docking.DockingOptions; import de.neitzel.fx.docking.LayoutSnapshot; import de.neitzel.fx.docking.RestoreResult; +import de.neitzel.fx.docking.ResolvedDockTarget; import javafx.application.Application; import javafx.fxml.FXMLLoader; +import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; @@ -18,9 +23,12 @@ 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.Stage; +import javafx.stage.Window; import java.util.List; +import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; /** Keeps layout data in application memory and restores fresh content before showing another workspace. */ @@ -41,25 +49,61 @@ public final class SnapshotDockingApp extends Application { Button restore = new Button("Restore saved layout"); Button incompatible = new Button("Try incompatible version"); Button failed = new Button("Simulate load failure"); + Button missing = new Button("Restore without Preview/Project"); + Button changedRule = new Button("Restore with changed rule"); + Button rejected = new Button("Reject Project placement"); + Button floating = new Button("Prepare floating snapshot"); + Button partialFloating = new Button("Restore partial floating"); + Button offscreen = new Button("Restore off-screen windows"); + Button abortCustomizer = new Button("Abort floating customizer"); CheckBox cleanupFailure = new CheckBox("Simulate cleanup failure"); - stage.setScene(new Scene(new BorderPane(pane, new ToolBar(capture, restore, incompatible, failed, cleanupFailure), + stage.setScene(new Scene(new BorderPane(pane, new VBox(new ToolBar(capture, restore, incompatible, failed, cleanupFailure), + new ToolBar(missing, changedRule, rejected), new ToolBar(floating, offscreen, partialFloating, abortCustomizer)), null, status, null), 1120, 680)); - DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions()); + DockingManager manager = DockingManager.attach(stage, pane, restoreOptions(RestoreScenario.NORMAL)); DOCUMENTS.forEach(document -> manager.open(content(document), DockTarget.area(document.area()))); saved = manager.snapshot(); + Runnable updateFloatingActions = () -> { + long count = saved.windows().stream().filter(window -> !window.main()).count(); + partialFloating.setDisable(count == 0); + offscreen.setDisable(count == 0); + abortCustomizer.setDisable(count < 2); + }; + updateFloatingActions.run(); capture.setOnAction(event -> { saved = manager.snapshot(); + updateFloatingActions.run(); status.setText("Captured layout in application memory; document text remains outside the snapshot."); }); - restore.setOnAction(event -> restoreWindow(saved, false, false, status)); + restore.setOnAction(event -> restoreWindow(saved, RestoreScenario.NORMAL, false, status)); incompatible.setOnAction(event -> restoreWindow(new LayoutSnapshot(saved.version() + 1, - saved.windows(), saved.activeDockableId(), saved.returnPositions(), saved.initialIntents()), false, false, status)); - failed.setOnAction(event -> restoreWindow(saved, true, cleanupFailure.isSelected(), status)); + saved.windows(), saved.activeDockableId(), saved.returnPositions(), saved.initialIntents()), RestoreScenario.NORMAL, false, status)); + failed.setOnAction(event -> restoreWindow(saved, RestoreScenario.LOAD_FAILURE, cleanupFailure.isSelected(), status)); + missing.setOnAction(event -> restoreWindow(saved, RestoreScenario.MISSING_CONTENT, false, status)); + changedRule.setOnAction(event -> restoreWindow(saved, RestoreScenario.PROJECT_FALLBACK, false, status)); + rejected.setOnAction(event -> restoreWindow(saved, RestoreScenario.REJECT_PROJECT, false, status)); + floating.setOnAction(event -> { + for (String id : List.of("preview", "project")) { + ActionResult moved = manager.move(new DockableId(id), DockTarget.floating()); + if (moved instanceof ActionResult.Rejected failure) { + status.setText(manager.describeFailure(failure.failure())); + return; + } + } + saved = manager.snapshot(); + updateFloatingActions.run(); + status.setText("Captured " + saved.windows().stream().filter(window -> !window.main()).count() + + " floating windows; Project retains its tools-area return target."); + }); + partialFloating.setOnAction(event -> restoreWindow(saved, RestoreScenario.PARTIAL_FLOATING, false, status)); + offscreen.setOnAction(event -> restoreWindow(offscreenSnapshot(saved), RestoreScenario.OFFSCREEN, false, status)); + abortCustomizer.setOnAction(event -> restoreWindow(saved, RestoreScenario.ABORT_CUSTOMIZER, false, status)); stage.setTitle("NeitzelLib — application-owned layout snapshots"); stage.show(); } - private static void restoreWindow(LayoutSnapshot snapshot, boolean failLoading, boolean failCleanup, Label sourceStatus) { + private static void restoreWindow(LayoutSnapshot snapshot, RestoreScenario scenario, boolean failCleanup, Label sourceStatus) { + List visibleBefore = List.copyOf(Window.getWindows()); Stage target = new Stage(); try { DockPane pane = loadPane(); @@ -67,15 +111,21 @@ public final class SnapshotDockingApp extends Application { status.setId("snapshotStatus"); status.setWrapText(true); target.setScene(new Scene(new BorderPane(pane, null, null, status, null), 1000, 650)); - DockingManager manager = DockingManager.attach(target, pane, new DockingOptions()); + DockingManager manager = DockingManager.attach(target, pane, restoreOptions(scenario)); AtomicInteger prepared = new AtomicInteger(); AtomicInteger discarded = new AtomicInteger(); RestoreResult result = manager.restore(snapshot, id -> { - if (failLoading && id.value().equals("readme")) { + if ((scenario == RestoreScenario.MISSING_CONTENT + && (id.value().equals("preview") || id.value().equals("project"))) + || scenario == RestoreScenario.PARTIAL_FLOATING && id.value().equals("preview")) { + return new DockableResolution.Missing(); + } + if (scenario == RestoreScenario.LOAD_FAILURE && id.value().equals("readme")) { return new DockableResolution.Failed(new IllegalStateException("Demo document source is unavailable")); } Document document = DOCUMENTS.stream().filter(candidate -> candidate.id().equals(id.value())).findFirst().orElseThrow(); Dockable content = content(document); + if (scenario == RestoreScenario.PARTIAL_FLOATING && id.value().equals("project")) content.setMainWindowOnly(true); prepared.incrementAndGet(); content.setOnDiscarded(() -> { discarded.incrementAndGet(); @@ -85,16 +135,34 @@ public final class SnapshotDockingApp extends Application { }); String message = switch (result) { case RestoreResult.Applied applied -> "Restored before showing this window; prepared " + prepared.get() - + " fresh contents, missing " + applied.missingIds().size() + "."; + + " fresh contents, missing " + applied.missingIds().size() + + (applied.missingIds().isEmpty() ? "." : " " + applied.missingIds().stream().map(DockableId::value).toList() + ".") + + (scenario == RestoreScenario.PROJECT_FALLBACK || scenario == RestoreScenario.PARTIAL_FLOATING + ? " Configured editor fallback (primary)." : "") + + (scenario == RestoreScenario.OFFSCREEN ? " Saved off-screen bounds fitted to available displays." : ""); case RestoreResult.Rejected rejected -> "Fallback layout retained: " + rejected.failure().code() + + (rejected.failure().dockableId() == null ? "" : " (" + rejected.failure().dockableId().value() + ")") + "; prepared " + prepared.get() + ", discarded " + discarded.get() + ", cleanup diagnostics " + rejected.cleanupFailures().size() + "." + + " " + manager.describeFailure(rejected.failure()) + (rejected.failure().cause() == null ? "" : " " + rejected.failure().cause().getMessage()); }; + Button returnProject = new Button("Return Project"); + DockableId projectId = new DockableId("project"); + returnProject.setDisable(manager.findDockable(projectId).isEmpty()); + returnProject.setOnAction(event -> status.setText(switch (manager.move(projectId, DockTarget.returnToMain())) { + case ActionResult.Applied ignored -> "Project returned to its preserved main-window target."; + case ActionResult.NoChange ignored -> "Project is already in the main window."; + case ActionResult.Rejected rejected -> manager.describeFailure(rejected.failure()); + })); + ((BorderPane) target.getScene().getRoot()).setTop(new ToolBar(returnProject)); + target.setTitle(result instanceof RestoreResult.Applied ? "Restored snapshot" : "Unchanged fallback layout"); + long beforeShow = visibleFloatingWindows(visibleBefore, target); + target.show(); + message += " Floating windows before main show: " + beforeShow + "; now: " + + visibleFloatingWindows(visibleBefore, target) + "."; status.setText(message); sourceStatus.setText(message); - target.setTitle(result instanceof RestoreResult.Applied ? "Restored snapshot" : "Unchanged fallback layout"); - target.show(); } catch (java.io.IOException failure) { target.hide(); sourceStatus.setText("Cannot load the workspace FXML: " + failure.getMessage()); @@ -105,6 +173,41 @@ public final class SnapshotDockingApp extends Application { return FXMLLoader.load(SnapshotDockingApp.class.getResource("SnapshotDocking.fxml")); } + private static long visibleFloatingWindows(List previous, Stage main) { + return Window.getWindows().stream().filter(window -> window != main && !previous.contains(window)).count(); + } + + private static LayoutSnapshot offscreenSnapshot(LayoutSnapshot snapshot) { + return new LayoutSnapshot(snapshot.version(), snapshot.windows().stream().map(window -> window.main() ? window + : new LayoutSnapshot.Window(window.id(), false, + new Rectangle2D(-100_000, -100_000, window.bounds().getWidth(), window.bounds().getHeight()), + window.roots())).toList(), snapshot.activeDockableId(), snapshot.returnPositions(), snapshot.initialIntents()); + } + + private static DockingOptions restoreOptions(RestoreScenario scenario) { + DockingOptions options = new DockingOptions(); + AtomicInteger configured = new AtomicInteger(); + options.setFloatingWindowCustomizer(configuration -> { + if (scenario == RestoreScenario.ABORT_CUSTOMIZER && configured.incrementAndGet() == 2) { + throw new IllegalStateException("Demo customizer rejected the second floating window"); + } + configuration.setTitle("Snapshot floating content"); + }); + if (scenario == RestoreScenario.PARTIAL_FLOATING) options.setFallbackTarget(DockTarget.area("primary")); + if (scenario == RestoreScenario.PROJECT_FALLBACK || scenario == RestoreScenario.REJECT_PROJECT) { + options.setFallbackTarget(DockTarget.area("primary")); + DockGroupId tools = new DockGroupId("tools"); + options.setPlacementRule((dockable, destination) -> { + boolean forbidden = dockable.getId().value().equals("project") + && (scenario == RestoreScenario.REJECT_PROJECT + || destination instanceof ResolvedDockTarget.Insertion insertion && insertion.groupId().equals(tools)); + return forbidden ? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, + dockable.getId(), "Project is not allowed in this destination", null)) : Optional.empty(); + }); + } + return options; + } + private static Dockable content(Document document) { Dockable content = new Dockable(new DockableId(document.id()), new TextArea(document.text())); content.setTitle(document.title()); @@ -112,4 +215,8 @@ public final class SnapshotDockingApp extends Application { } private record Document(String id, String area, String title, String text) { } + private enum RestoreScenario { + NORMAL, LOAD_FAILURE, MISSING_CONTENT, PROJECT_FALLBACK, REJECT_PROJECT, + PARTIAL_FLOATING, OFFSCREEN, ABORT_CUSTOMIZER + } } diff --git a/fx-example/src/main/resources/de/neitzel/fx/example/docking/KeyboardThemeDocking.css b/fx-example/src/main/resources/de/neitzel/fx/example/docking/KeyboardThemeDocking.css new file mode 100644 index 0000000..033f28e --- /dev/null +++ b/fx-example/src/main/resources/de/neitzel/fx/example/docking/KeyboardThemeDocking.css @@ -0,0 +1,14 @@ +.dock-pane { + -fx-base: #dce8f1; + -fx-accent: #156b83; + -fx-focus-color: #0c617b; +} +.dock-tab-header { -fx-background-color: #dce8f1; } +.dock-tab-header:selected { -fx-background-color: #faf3dc; } +.dock-tab-header:focused .focus-indicator { -fx-border-color: #0c617b; } +.dock-divider, .dock-area-divider { -fx-background-color: #53869b; } +.dock-edge-area { -fx-background-color: #b9d2dc; } +.dock-drop-indicator { -fx-fill: rgba(15, 120, 130, 0.25); -fx-stroke: #0f7882; } +.dock-drop-indicator:no-change { -fx-fill: rgba(130, 100, 20, 0.2); -fx-stroke: #826414; } +.dock-floating-preview-frame { -fx-fill: rgba(15, 120, 130, 0.25); -fx-stroke: #0f7882; } +.dock-floating-preview-label { -fx-background-color: #faf3dc; -fx-text-fill: #173b4a; } diff --git a/fx-example/src/main/resources/de/neitzel/fx/example/docking/ShutdownDocking.fxml b/fx-example/src/main/resources/de/neitzel/fx/example/docking/ShutdownDocking.fxml new file mode 100644 index 0000000..7843728 --- /dev/null +++ b/fx-example/src/main/resources/de/neitzel/fx/example/docking/ShutdownDocking.fxml @@ -0,0 +1,12 @@ + + + + + + + +
+ +
+
+
diff --git a/fx-example/src/main/resources/de/neitzel/fx/example/docking/SnapshotDocking.fxml b/fx-example/src/main/resources/de/neitzel/fx/example/docking/SnapshotDocking.fxml index 8d12655..ae99c9a 100644 --- a/fx-example/src/main/resources/de/neitzel/fx/example/docking/SnapshotDocking.fxml +++ b/fx-example/src/main/resources/de/neitzel/fx/example/docking/SnapshotDocking.fxml @@ -19,7 +19,7 @@ + mode="OVERLAY" preferredWidth="240" visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/> diff --git a/fx-example/src/test/java/de/neitzel/fx/example/docking/ShutdownDockingExampleTest.java b/fx-example/src/test/java/de/neitzel/fx/example/docking/ShutdownDockingExampleTest.java new file mode 100644 index 0000000..0902cb1 --- /dev/null +++ b/fx-example/src/test/java/de/neitzel/fx/example/docking/ShutdownDockingExampleTest.java @@ -0,0 +1,201 @@ +package de.neitzel.fx.example.docking; + +import de.neitzel.fx.docking.MainWindowCloseMode; +import javafx.application.Platform; +import javafx.scene.Parent; +import javafx.scene.control.Button; +import javafx.scene.control.CheckBox; +import javafx.scene.control.ComboBox; +import javafx.scene.control.Label; +import javafx.scene.control.TextArea; +import javafx.stage.Stage; +import javafx.stage.Window; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; + +class ShutdownDockingExampleTest { + @Test void quitAndReplaceControlsPreserveEditorsThroughVetoRetryCancelAndFailureThenReattach() throws Exception { + onFx(() -> { + Platform.setImplicitExit(false); + List existing = List.copyOf(Window.getWindows()); + Stage stage = new Stage(); + try { + new ShutdownDockingApp().start(stage); + Parent root = stage.getScene().getRoot(); root.applyCss(); root.layout(); + TextArea notes = (TextArea) root.lookup("#notes-content"); + notes.setText("Keep these unsaved notes"); + Label status = (Label) root.lookup("#shutdown-status"); + TextArea history = (TextArea) root.lookup("#shutdown-history"); + CheckBox veto = (CheckBox) root.lookup("#late-veto"); + veto.setSelected(true); + button(root, "replace-workspace").fire(); + assertTrue(status.getText().contains("Vetoed"), status.getText()); + for (String id : List.of("notes", "project", "preview")) assertTrue(history.getText().contains("Checked " + id)); + assertFalse(history.getText().contains("Snapshot MANAGER_ONLY")); + assertEquals("Keep these unsaved notes", notes.getText()); + assertEquals(2, windowsSince(existing).size()); + + veto.setSelected(false); + button(root, "replace-workspace").fire(); + assertTrue(status.getText().contains("Save pending"), status.getText()); + assertTrue(history.getText().contains("Snapshot MANAGER_ONLY: 2 windows")); + button(root, "retry-save").fire(); + assertTrue(status.getText().contains("Retry failed"), status.getText()); + assertSame(notes, root.lookup("#notes-content")); + assertEquals(2, windowsSince(existing).size()); + button(root, "cancel-save").fire(); + assertTrue(status.getText().contains("Canceled"), status.getText()); + + ((CheckBox) root.lookup("#throw-shutdown")).setSelected(true); + button(root, "quit-workspace").fire(); + assertTrue(status.getText().contains("SHUTDOWN_CALLBACK_FAILED"), status.getText()); + ((CheckBox) root.lookup("#throw-shutdown")).setSelected(false); + button(root, "quit-workspace").fire(); + button(root, "fail-save").fire(); + assertTrue(status.getText().contains("SHUTDOWN_CALLBACK_FAILED"), status.getText()); + assertSame(notes, root.lookup("#notes-content")); + assertEquals("Keep these unsaved notes", notes.getText()); + + @SuppressWarnings("unchecked") ComboBox ownership = + (ComboBox) root.lookup("#next-ownership"); + ownership.setValue(MainWindowCloseMode.APPLICATION_COORDINATED); + button(root, "replace-workspace").fire(); + button(root, "proceed-save").fire(); + root.applyCss(); root.layout(); + assertTrue(stage.isShowing()); + assertTrue(status.getText().contains("Workspace 2 attached"), status.getText()); + assertNotSame(notes, root.lookup("#notes-content")); + assertEquals(2, windowsSince(existing).size()); + assertTrue(history.getText().contains("Released preview")); + + button(root, "quit-workspace").fire(); + button(root, "proceed-save").fire(); + assertTrue(stage.isShowing(), "Application-coordinated completion keeps the caller's Stage open"); + assertEquals(List.of(stage), windowsSince(existing)); + assertFalse(button(root, "close-application-window").isDisabled()); + button(root, "close-application-window").fire(); + assertFalse(stage.isShowing()); + } finally { windowsSince(existing).forEach(Window::hide); stage.hide(); } + }); + } + + @Test void automaticMainCloseWaitsForASuccessfulRetryThenHidesEveryWindow() throws Exception { + onFx(() -> { + Platform.setImplicitExit(false); + List existing = List.copyOf(Window.getWindows()); Stage stage = new Stage(); + try { + new ShutdownDockingApp().start(stage); + Parent root = stage.getScene().getRoot(); root.applyCss(); root.layout(); + stage.fireEvent(new javafx.stage.WindowEvent(stage, javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST)); + assertTrue(stage.isShowing()); + assertEquals(2, windowsSince(existing).size()); + button(root, "retry-save").fire(); + assertTrue(((Label) root.lookup("#shutdown-status")).getText().contains("Retry failed")); + assertTrue(stage.isShowing()); + ((CheckBox) root.lookup("#save-fails")).setSelected(false); + button(root, "retry-save").fire(); + assertFalse(stage.isShowing()); + assertTrue(windowsSince(existing).isEmpty()); + TextArea history = (TextArea) root.lookup("#shutdown-history"); + assertTrue(history.getText().contains("Saved 2 windows")); + for (String id : List.of("notes", "project", "preview")) assertTrue(history.getText().contains("Released " + id)); + } finally { windowsSince(existing).forEach(Window::hide); stage.hide(); } + }); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {true, false}) + void quitWaitsForFloatingConsentWithoutRepeatingAVetoedPrompt(boolean allowFloating) throws Exception { + AtomicReference main = new AtomicReference<>(); + AtomicReference floating = new AtomicReference<>(); + AtomicReference