Restore and reset docking layouts transactionally with localized diagnostics

This commit is contained in:
2026-11-15 23:48:27 +01:00
parent fb5603eb76
commit 853c6c0115
39 changed files with 2465 additions and 42 deletions
@@ -0,0 +1,72 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.ActionResult;
import de.neitzel.fx.docking.DockFailure;
import de.neitzel.fx.docking.DockGroupId;
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.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.Optional;
/** Demonstrates reset with live editors and atomic rejection under changed placement rules. */
public final class ResetDockingApp extends Application {
@Override public void start(Stage stage) throws Exception {
DockPane pane = FXMLLoader.load(DockingApp.class.getResource("Docking.fxml"));
Button rearrange = new Button("Rearrange");
Button reset = new Button("Reset layout");
reset.setId("resetLayout");
CheckBox allowProject = new CheckBox("Allow Project placement");
allowProject.setSelected(true);
Label status = new Label("Edit Notes, rearrange, then reset. Disable Project placement to see a rejected reset.");
stage.setScene(new Scene(new BorderPane(pane, new ToolBar(rearrange, reset, allowProject),
null, status, null), 1000, 600));
DockingOptions options = new DockingOptions();
options.setPlacementRule((dockable, destination) -> allowProject.isSelected() || !dockable.getId().value().equals("project")
? Optional.empty() : Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED,
dockable.getId(), "Project placement is disabled", null)));
DockingManager manager = DockingManager.attach(stage, pane, options);
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("These unsaved edits survive reset."));
notes.setTitle("Notes");
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme stays open."));
readme.setTitle("Readme");
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project tools"));
project.setTitle("Project");
manager.open(notes, DockTarget.area("editors"));
manager.open(readme, DockTarget.area("editors"));
manager.open(project, DockTarget.area("tools"));
rearrange.setOnAction(event -> {
ActionResult moved = manager.move(project.getId(), DockTarget.area("editors"));
if (moved instanceof ActionResult.Rejected) { report(status, moved); return; }
manager.move(readme.getId(), DockTarget.split(new DockGroupId("editors"), Side.BOTTOM));
manager.move(notes.getId(), DockTarget.floating());
manager.setGroupCollapsed(new DockGroupId("tools"), true);
status.setText("Notes is floating, Readme is split and Project moved. Reset restores the starting arrangement.");
});
reset.setOnAction(event -> report(status, manager.resetLayout()));
stage.setTitle("NeitzelLib — reset without losing edits");
stage.show();
}
private static void report(Label status, ActionResult result) {
status.setText(switch (result) {
case ActionResult.Applied ignored -> "Starting layout restored; all document contents remain open.";
case ActionResult.NoChange ignored -> "The layout already has its starting arrangement.";
case ActionResult.Rejected rejected -> "Layout unchanged: " + rejected.failure().message();
});
}
}
@@ -0,0 +1,10 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain classpath launcher for the reset example. */
public final class ResetDockingMain {
private ResetDockingMain() { }
public static void main(String[] args) { Application.launch(ResetDockingApp.class, args); }
}
@@ -0,0 +1,115 @@
package de.neitzel.fx.example.docking;
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.DockableResolution;
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 javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/** Keeps layout data in application memory and restores fresh content before showing another workspace. */
public final class SnapshotDockingApp extends Application {
private static final List<Document> DOCUMENTS = List.of(
new Document("notes", "primary", "Notes", "Notes loaded from the application document source."),
new Document("readme", "secondary", "Readme", "The saved layout contains identities, not this text."),
new Document("preview", "preview", "Preview", "Preview belongs to a nested editor split."),
new Document("project", "tools", "Project", "Project is a temporary overlay."));
private LayoutSnapshot saved;
@Override public void start(Stage stage) throws Exception {
DockPane pane = loadPane();
Label status = new Label("Rearrange the workspace, capture its layout, then restore into a fresh window.");
status.setId("snapshotStatus");
status.setWrapText(true);
Button capture = new Button("Capture layout");
Button restore = new Button("Restore saved layout");
Button incompatible = new Button("Try incompatible version");
Button failed = new Button("Simulate load failure");
CheckBox cleanupFailure = new CheckBox("Simulate cleanup failure");
stage.setScene(new Scene(new BorderPane(pane, new ToolBar(capture, restore, incompatible, failed, cleanupFailure),
null, status, null), 1120, 680));
DockingManager manager = DockingManager.attach(stage, pane, new DockingOptions());
DOCUMENTS.forEach(document -> manager.open(content(document), DockTarget.area(document.area())));
saved = manager.snapshot();
capture.setOnAction(event -> {
saved = manager.snapshot();
status.setText("Captured layout in application memory; document text remains outside the snapshot.");
});
restore.setOnAction(event -> restoreWindow(saved, false, 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));
stage.setTitle("NeitzelLib — application-owned layout snapshots");
stage.show();
}
private static void restoreWindow(LayoutSnapshot snapshot, boolean failLoading, boolean failCleanup, Label sourceStatus) {
Stage target = new Stage();
try {
DockPane pane = loadPane();
Label status = new Label();
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());
AtomicInteger prepared = new AtomicInteger();
AtomicInteger discarded = new AtomicInteger();
RestoreResult result = manager.restore(snapshot, id -> {
if (failLoading && 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);
prepared.incrementAndGet();
content.setOnDiscarded(() -> {
discarded.incrementAndGet();
if (failCleanup) throw new IllegalStateException("Demo cleanup could not finish");
});
return new DockableResolution.Available(content);
});
String message = switch (result) {
case RestoreResult.Applied applied -> "Restored before showing this window; prepared " + prepared.get()
+ " fresh contents, missing " + applied.missingIds().size() + ".";
case RestoreResult.Rejected rejected -> "Fallback layout retained: " + rejected.failure().code()
+ "; prepared " + prepared.get() + ", discarded " + discarded.get()
+ ", cleanup diagnostics " + rejected.cleanupFailures().size() + "."
+ (rejected.failure().cause() == null ? "" : " " + rejected.failure().cause().getMessage());
};
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());
}
}
private static DockPane loadPane() throws java.io.IOException {
return FXMLLoader.load(SnapshotDockingApp.class.getResource("SnapshotDocking.fxml"));
}
private static Dockable content(Document document) {
Dockable content = new Dockable(new DockableId(document.id()), new TextArea(document.text()));
content.setTitle(document.title());
return content;
}
private record Document(String id, String area, String title, String text) { }
}
@@ -0,0 +1,9 @@
package de.neitzel.fx.example.docking;
import javafx.application.Application;
/** Plain classpath launcher for the snapshot example. */
public final class SnapshotDockingMain {
private SnapshotDockingMain() { }
public static void main(String[] args) { Application.launch(SnapshotDockingApp.class, args); }
}
@@ -0,0 +1,26 @@
<?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?>
<?import de.neitzel.fx.docking.DockSplitDefinition?>
<DockPane xmlns:fx="http://javafx.com/fxml/1">
<initialLayout>
<DockLayout>
<center>
<DockSplitDefinition destinationId="editors" orientation="HORIZONTAL" position="0.55">
<first><DockGroupDefinition destinationId="primary"/></first>
<second>
<DockSplitDefinition destinationId="auxiliary" orientation="VERTICAL" position="0.6">
<first><DockGroupDefinition destinationId="secondary"/></first>
<second><DockGroupDefinition destinationId="preview"/></second>
</DockSplitDefinition>
</second>
</DockSplitDefinition>
</center>
<right>
<DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true"
mode="OVERLAY" preferredWidth="240"/>
</right>
</DockLayout>
</initialLayout>
</DockPane>
@@ -0,0 +1,87 @@
package de.neitzel.fx.example.docking;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TabPane;
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.*;
/** Exercises the visible reset and rule controls of the actual runnable application. */
class ResetDockingExampleTest {
@Test
void resetButtonReportsRejectionThenReturnsTheSameUnsavedEditor() throws Exception {
onFx(() -> {
Platform.setImplicitExit(false);
List<Window> existing = List.copyOf(Window.getWindows());
Stage stage = new Stage();
try {
new ResetDockingApp().start(stage);
Parent root = stage.getScene().getRoot();
root.applyCss();
root.layout();
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("Still editing; nothing saved");
notes.selectRange(0, 5);
button(root, "Rearrange").fire();
Window floating = notes.getScene().getWindow();
assertNotSame(stage, floating);
CheckBox allowProject = (CheckBox) root.lookup(".check-box");
allowProject.setSelected(false);
button(root, "Reset layout").fire();
assertSame(floating, notes.getScene().getWindow());
assertTrue(floating.isShowing());
assertTrue(root.lookupAll(".label").stream().filter(Label.class::isInstance).map(Label.class::cast)
.anyMatch(label -> label.getText().startsWith("Layout unchanged:")));
allowProject.setSelected(true);
button(root, "Reset layout").fire();
assertSame(stage, notes.getScene().getWindow());
assertFalse(floating.isShowing());
assertEquals("Still editing; nothing saved", notes.getText());
assertEquals("Still", notes.getSelectedText());
assertTrue(root.lookupAll(".label").stream().filter(Label.class::isInstance).map(Label.class::cast)
.anyMatch(label -> label.getText().startsWith("Starting layout restored")));
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
private static Button button(Parent root, String text) {
return root.lookupAll(".button").stream().filter(Button.class::isInstance).map(Button.class::cast)
.filter(button -> button.getText().equals(text)).findFirst().orElseThrow();
}
private static void onFx(FxAction action) throws Exception {
CountDownLatch started = new CountDownLatch(1);
try { Platform.startup(started::countDown); }
catch (IllegalStateException alreadyStarted) { 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(10, TimeUnit.SECONDS));
if (failure.get() != null) fail("Reset docking example failed", failure.get());
}
@FunctionalInterface
private interface FxAction { void run() throws Exception; }
}
@@ -0,0 +1,141 @@
package de.neitzel.fx.example.docking;
import de.neitzel.fx.docking.DockGroupMode;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockableResolution;
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 javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TabPane;
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.*;
/** Loads the snapshot application's real FXML before restoring fresh content into an empty manager. */
class SnapshotDockingExampleTest {
@Test
void fxmlRoundTripRestoresNestedStructureAndKeepsTheOverlayCollapsedBeforeShow() throws Exception {
onFx(() -> {
Platform.setImplicitExit(false);
Fixture source = fixture();
for (String area : List.of("primary", "secondary", "preview", "tools")) {
Dockable dockable = new Dockable(new DockableId(area), new TextArea("Original " + area));
source.manager().open(dockable, DockTarget.area(area));
}
LayoutSnapshot snapshot = source.manager().snapshot();
LayoutSnapshot.Split center = assertInstanceOf(LayoutSnapshot.Split.class,
snapshot.windows().getFirst().roots().getFirst().branch());
assertInstanceOf(LayoutSnapshot.Split.class, center.second());
Fixture target = fixture();
var result = target.manager().restore(snapshot, id ->
new DockableResolution.Available(new Dockable(id, new TextArea("Reloaded " + id.value()))));
assertInstanceOf(RestoreResult.Applied.class, result);
assertFalse(target.stage().isShowing(), "The application restores before showing the new main window");
assertEquals(4, target.manager().layout().windows().getFirst().areas().stream()
.flatMap(area -> area.groups().stream()).distinct().mapToLong(group -> group.dockableIds().size()).sum());
var tools = target.manager().layout().windows().getFirst().areas().stream()
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow().groups().getFirst();
assertEquals(DockGroupMode.OVERLAY, tools.mode());
assertTrue(tools.collapsed());
TextArea original = (TextArea) source.manager().findDockable(new DockableId("primary")).orElseThrow().getContent();
TextArea restored = (TextArea) target.manager().findDockable(new DockableId("primary")).orElseThrow().getContent();
assertNotSame(original, restored);
assertEquals("Reloaded primary", restored.getText(), "Document loading belongs to the resolver, not the layout snapshot");
});
}
private static Fixture fixture() throws Exception {
var resource = DockingApp.class.getResource("SnapshotDocking.fxml");
assertNotNull(resource, "The snapshot example supplies its real FXML layout");
DockPane pane = FXMLLoader.load(resource);
Stage stage = new Stage();
stage.setScene(new Scene(pane, 1000, 650));
return new Fixture(stage, DockingManager.attach(stage, pane, new DockingOptions()));
}
@Test
void applicationButtonsShowFreshRestoreFallbackAndSeparateCleanupDiagnostics() 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");
button(root, "Capture layout").fire();
button(root, "Restore saved layout").fire();
assertTrue(status.getText().contains("prepared 4 fresh contents"), status.getText());
Stage restored = Window.getWindows().stream().filter(Stage.class::isInstance).map(Stage.class::cast)
.filter(stage -> stage.getTitle().equals("Restored snapshot")).findFirst().orElseThrow();
assertEquals(4, tabCount(restored.getScene().getRoot()));
assertEquals(4, tabCount(root), "Restoring another workspace leaves the original editor Nodes in place");
button(root, "Try incompatible version").fire();
assertTrue(status.getText().contains("UNSUPPORTED_SNAPSHOT_VERSION"), status.getText());
assertTrue(status.getText().contains("prepared 0, discarded 0"), status.getText());
button(root, "Simulate load failure").fire();
assertTrue(status.getText().contains("DOCKABLE_LOAD_FAILED"), status.getText());
assertTrue(status.getText().contains("prepared 1, discarded 1, cleanup diagnostics 0"), status.getText());
((CheckBox) root.lookup(".check-box")).setSelected(true);
button(root, "Simulate load failure").fire();
assertTrue(status.getText().contains("prepared 1, discarded 1, cleanup diagnostics 1"), status.getText());
assertTrue(status.getText().contains("Demo document source is unavailable"), status.getText());
Window.getWindows().stream().filter(Stage.class::isInstance).map(Stage.class::cast)
.filter(stage -> stage.getTitle().equals("Unchanged fallback layout"))
.forEach(stage -> assertEquals(0, tabCount(stage.getScene().getRoot())));
} finally {
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
}
});
}
private static int tabCount(Parent root) {
return root.lookupAll(".tab-pane").stream().map(TabPane.class::cast).mapToInt(tabs -> tabs.getTabs().size()).sum();
}
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();
}
private static void onFx(FxAction action) throws Exception {
CountDownLatch started = new CountDownLatch(1);
try { Platform.startup(started::countDown); }
catch (IllegalStateException alreadyStarted) { 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(10, TimeUnit.SECONDS));
if (failure.get() != null) fail("Snapshot docking example failed", failure.get());
}
private record Fixture(Stage stage, DockingManager manager) { }
@FunctionalInterface private interface FxAction { void run() throws Exception; }
}