Complete multiwindow restore, coordinated shutdown and keyboard docking

This commit is contained in:
2026-11-16 00:54:10 +01:00
parent 853c6c0115
commit 485451de26
55 changed files with 3624 additions and 178 deletions
@@ -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"}
};
}
};
}
}
@@ -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); }
}
@@ -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<CompletableFuture<ShutdownDecision>> pendingSave = new SimpleObjectProperty<>();
private final SimpleObjectProperty<CompletableFuture<CloseConsent>> 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<MainWindowCloseMode> 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<CloseConsent> 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<CloseConsent> 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<ShutdownDecision> 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<ShutdownDecision> 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<ShutdownDecision> 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<CloseResult> 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"); }
}
@@ -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); }
}
@@ -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<Window> 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<Window> 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
}
}
@@ -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; }
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.DockPane?>
<?import de.neitzel.fx.docking.DockLayout?>
<?import de.neitzel.fx.docking.DockGroupDefinition?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center><DockGroupDefinition destinationId="editors"/></center>
<left><DockGroupDefinition destinationId="tools" tabSide="LEFT" collapsible="true" preferredWidth="220"/></left>
</DockLayout>
</initialLayout>
</DockPane>
@@ -19,7 +19,7 @@
</center>
<right>
<DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true"
mode="OVERLAY" preferredWidth="240"/>
mode="OVERLAY" preferredWidth="240" visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/>
</right>
</DockLayout>
</initialLayout>
@@ -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<Window> 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<MainWindowCloseMode> ownership =
(ComboBox<MainWindowCloseMode>) 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<Window> 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<Stage> main = new AtomicReference<>();
AtomicReference<Stage> floating = new AtomicReference<>();
AtomicReference<TextArea> originalNotes = new AtomicReference<>();
AtomicReference<List<Window>> initialWindows = new AtomicReference<>();
try {
onFx(() -> {
Platform.setImplicitExit(false);
List<Window> existing = List.copyOf(Window.getWindows()); initialWindows.set(existing);
Stage stage = new Stage(); main.set(stage);
new ShutdownDockingApp().start(stage);
Parent root = stage.getScene().getRoot(); root.applyCss(); root.layout();
TextArea history = (TextArea) root.lookup("#shutdown-history");
Label status = (Label) root.lookup("#shutdown-status");
TextArea notes = (TextArea) root.lookup("#notes-content"); notes.setText("Still editing while consent waits");
originalNotes.set(notes);
Stage preview = (Stage) windowsSince(existing).stream().filter(window -> window != stage).findFirst().orElseThrow();
floating.set(preview);
((CheckBox) root.lookup("#delay-floating-consent")).setSelected(true);
button(root, "close-preview-window").fire();
assertTrue(status.getText().contains("Preview consent pending"), status.getText());
assertEquals(1, history.getText().lines().filter(line -> line.startsWith("Checked preview")).count());
assertFalse(button(root, "quit-workspace").isDisabled(), "Quit can wait behind a running floating close");
button(root, "quit-workspace").fire();
assertTrue(status.getText().contains("Quit waiting"), status.getText());
assertFalse(history.getText().contains("Snapshot MAIN_WINDOW"));
assertFalse(history.getText().contains("Checked notes"));
assertTrue(preview.isShowing()); assertTrue(stage.isShowing());
});
onFx(() -> button(main.get().getScene().getRoot(), allowFloating ? "allow-preview" : "veto-preview").fire());
// A queued manager request starts in a subsequent ordinary FX turn.
onFx(() -> { });
onFx(() -> {
Stage stage = main.get(); Stage preview = floating.get();
Parent root = stage.getScene().getRoot();
TextArea history = (TextArea) root.lookup("#shutdown-history");
Label status = (Label) root.lookup("#shutdown-status");
TextArea notes = originalNotes.get();
assertEquals(1, history.getText().lines().filter(line -> line.startsWith("Checked preview")).count(),
"The queued Quit does not ask the already handled floating editor again");
if (allowFloating) {
assertFalse(preview.isShowing());
assertTrue(status.getText().contains("Save pending"), status.getText());
assertTrue(history.getText().contains("Snapshot MAIN_WINDOW: 1 windows"));
assertTrue(history.getText().contains("Checked notes"));
assertTrue(history.getText().contains("Checked project"));
} else {
assertTrue(preview.isShowing());
assertTrue(status.getText().contains("Vetoed"), status.getText());
assertFalse(history.getText().contains("Snapshot MAIN_WINDOW"));
assertFalse(history.getText().contains("Checked notes"));
assertFalse(history.getText().contains("Released "));
assertFalse(button(root, "quit-workspace").isDisabled());
button(root, "quit-workspace").fire();
assertEquals(2, history.getText().lines().filter(line -> line.startsWith("Checked preview")).count(),
"A new explicit Quit performs fresh checks after the earlier veto");
assertTrue(history.getText().contains("Snapshot MAIN_WINDOW: 2 windows"));
}
assertEquals("Still editing while consent waits", notes.getText());
button(root, "cancel-save").fire();
assertTrue(stage.isShowing()); assertTrue(status.getText().contains("Canceled"));
assertSame(notes, root.lookup("#notes-content"));
});
} finally {
if (initialWindows.get() != null) onFx(() -> {
windowsSince(initialWindows.get()).forEach(Window::hide);
if (main.get() != null) main.get().hide();
});
}
}
private static Button button(Parent root, String id) { return (Button) root.lookup("#" + id); }
private static List<Window> windowsSince(List<Window> existing) {
return Window.getWindows().stream().filter(window -> !existing.contains(window)).toList();
}
private static void onFx(FxAction action) throws Exception {
CountDownLatch started = new CountDownLatch(1);
try { Platform.startup(started::countDown); } catch (IllegalStateException running) { started.countDown(); }
assertTrue(started.await(10, TimeUnit.SECONDS));
CountDownLatch done = new CountDownLatch(1); AtomicReference<Throwable> failure = new AtomicReference<>();
Platform.runLater(() -> {
try { action.run(); } catch (Throwable thrown) { failure.set(thrown); } finally { done.countDown(); }
});
assertTrue(done.await(15, TimeUnit.SECONDS));
if (failure.get() != null) fail("Shutdown application failed", failure.get());
}
@FunctionalInterface private interface FxAction { void run() throws Exception; }
}
@@ -21,6 +21,7 @@ import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.stage.Screen;
import org.junit.jupiter.api.Test;
import java.util.List;
@@ -115,6 +116,142 @@ class SnapshotDockingExampleTest {
return root.lookupAll(".tab-pane").stream().map(TabPane.class::cast).mapToInt(tabs -> tabs.getTabs().size()).sum();
}
@Test
void partialRestoreShowsMissingIdsNamedFallbackAndAtomicPlacementRejection() throws Exception {
onFx(() -> {
Platform.setImplicitExit(false);
List<Window> existing = List.copyOf(Window.getWindows());
Stage source = new Stage();
try {
new SnapshotDockingApp().start(source);
Parent root = source.getScene().getRoot();
root.applyCss();
root.layout();
Label status = (Label) root.lookup("#snapshotStatus");
TextArea notes = root.lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.flatMap(tabs -> tabs.getTabs().stream()).filter(tab -> tab.getText().equals("Notes"))
.map(tab -> (TextArea) tab.getContent()).findFirst().orElseThrow();
notes.setText("Unsaved original remains open");
button(root, "Restore without Preview/Project").fire();
assertTrue(status.getText().contains("missing 2"), status.getText());
assertTrue(status.getText().contains("preview") && status.getText().contains("project"), status.getText());
Stage partial = latestResultWindow(source, existing);
assertEquals(2, tabCount(partial.getScene().getRoot()));
assertEquals(3, partial.getScene().getRoot().lookupAll(".tab-pane").size(),
"The persistent empty tools group remains beside the two populated editor groups");
assertEquals(1, partial.getScene().getRoot().lookupAll(".dock-split").size(),
"The missing Preview dissolves the nested split");
partial.hide();
button(root, "Restore with changed rule").fire();
Stage fallback = latestResultWindow(source, existing);
assertTrue(status.getText().contains("editor fallback (primary)"), status.getText());
assertTrue(fallback.getScene().getRoot().lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.anyMatch(tabs -> tabs.getTabs().stream().anyMatch(tab -> tab.getText().equals("Notes"))
&& tabs.getTabs().stream().anyMatch(tab -> tab.getText().equals("Project"))));
fallback.hide();
button(root, "Reject Project placement").fire();
Stage rejected = latestResultWindow(source, existing);
assertEquals(0, tabCount(rejected.getScene().getRoot()));
assertTrue(status.getText().contains("PLACEMENT_REJECTED"), status.getText());
assertTrue(status.getText().contains("project"), status.getText());
assertTrue(status.getText().contains("prepared 4, discarded 4"), status.getText());
assertEquals("Unsaved original remains open", notes.getText());
assertEquals(4, tabCount(root));
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
private static Stage latestResultWindow(Stage source, List<Window> existing) {
return Window.getWindows().stream().filter(window -> window != source && !existing.contains(window))
.filter(Stage.class::isInstance).map(Stage.class::cast).reduce((first, second) -> second).orElseThrow();
}
@Test
void floatingStartupFitsDisplaysReturnsProjectAndOmitsOrAbortsPreparedHosts() throws Exception {
onFx(() -> {
Platform.setImplicitExit(false);
List<Window> existing = List.copyOf(Window.getWindows());
Stage source = new Stage();
try {
new SnapshotDockingApp().start(source);
Parent root = source.getScene().getRoot();
root.applyCss();
root.layout();
Label status = (Label) root.lookup("#snapshotStatus");
assertTrue(button(root, "Restore off-screen windows").isDisabled());
assertTrue(button(root, "Abort floating customizer").isDisabled());
button(root, "Prepare floating snapshot").fire();
assertTrue(status.getText().contains("2 floating windows"), status.getText());
assertFalse(root.lookupAll(".tab-pane").stream().map(TabPane.class::cast)
.filter(tabs -> tabs.getTabs().isEmpty()).findFirst().orElseThrow().isVisible(),
"The persistent Project return target is hidden while empty");
List<Window> beforeOrdinaryRestore = List.copyOf(Window.getWindows());
button(root, "Restore saved layout").fire();
List<Stage> ordinary = newStages(beforeOrdinaryRestore);
assertEquals(3, ordinary.size());
assertTrue(status.getText().contains("Floating windows before main show: 0; now: 2"), status.getText());
ordinary.forEach(Window::hide);
List<Window> beforePartial = List.copyOf(Window.getWindows());
button(root, "Restore partial floating").fire();
List<Stage> partial = newStages(beforePartial);
assertEquals(1, partial.size(), "Missing Preview and main-only Project leave no floating hosts");
assertEquals(3, tabCount(partial.getFirst().getScene().getRoot()));
assertTrue(status.getText().contains("missing 1 [preview]"), status.getText());
assertSame(partial.getFirst(), document(partial.getFirst().getScene().getRoot(), "Project").getScene().getWindow());
partial.forEach(Window::hide);
List<Window> beforeRestore = List.copyOf(Window.getWindows());
button(root, "Restore off-screen windows").fire();
List<Stage> restored = newStages(beforeRestore);
assertEquals(3, restored.size(), "One main window and two floating hosts appear after startup");
Stage main = restored.stream().filter(stage -> stage.getTitle().equals("Restored snapshot")).findFirst().orElseThrow();
assertTrue(status.getText().contains("Floating windows before main show: 0; now: 2"), status.getText());
for (Stage floating : restored.stream().filter(stage -> stage != main).toList()) {
assertEquals("Snapshot floating content", floating.getTitle());
assertTrue(Screen.getScreens().stream().anyMatch(screen -> {
var bounds = screen.getVisualBounds();
return floating.getX() >= bounds.getMinX() - 2 && floating.getY() >= bounds.getMinY() - 2
&& floating.getX() + floating.getWidth() <= bounds.getMaxX() + 2
&& floating.getY() + floating.getHeight() <= bounds.getMaxY() + 2;
}), "The restored floating frame must fit an available display");
}
Stage projectHost = restored.stream().filter(stage -> stage != main)
.filter(stage -> document(stage.getScene().getRoot(), "Project") != null).findFirst().orElseThrow();
TextArea project = document(projectHost.getScene().getRoot(), "Project");
button(main.getScene().getRoot(), "Return Project").fire();
assertSame(main, project.getScene().getWindow());
assertFalse(projectHost.isShowing());
assertTrue(((Label) main.getScene().getRoot().lookup("#snapshotStatus")).getText().contains("preserved main-window target"));
restored.forEach(Window::hide);
List<Window> beforeFailure = List.copyOf(Window.getWindows());
button(root, "Abort floating customizer").fire();
List<Stage> failed = newStages(beforeFailure);
assertEquals(1, failed.size(), "Neither the first prepared floating host nor the failed second one may appear");
assertEquals(0, tabCount(failed.getFirst().getScene().getRoot()));
assertTrue(status.getText().contains("WINDOW_CREATION_FAILED"), status.getText());
assertTrue(status.getText().contains("prepared 4, discarded 4"), status.getText());
assertTrue(status.getText().contains("Floating windows before main show: 0; now: 0"), status.getText());
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
private static List<Stage> newStages(List<Window> existing) {
return Window.getWindows().stream().filter(window -> !existing.contains(window))
.filter(Stage.class::isInstance).map(Stage.class::cast).toList();
}
private static TextArea document(Parent root, String title) {
return root.lookupAll(".tab-pane").stream().map(TabPane.class::cast).flatMap(tabs -> tabs.getTabs().stream())
.filter(tab -> tab.getText().equals(title)).map(tab -> (TextArea) tab.getContent()).findFirst().orElse(null);
}
private static Button button(Parent root, String label) {
return root.lookupAll(".button").stream().filter(Button.class::isInstance).map(Button.class::cast)
.filter(button -> button.getText().equals(label)).findFirst().orElseThrow();