Add complete Java and FXML docking workspace with application persistence

This commit is contained in:
2026-11-16 01:13:01 +01:00
parent d8e9aa027e
commit 01af6c6a0c
17 changed files with 1236 additions and 3 deletions
+1 -1
View File
@@ -44,7 +44,7 @@ Some encryption classes that use format-preserving-encryption.
### fx ### fx
JavaFX library that binds an FXML view to an ordinary Java model. See [fx/README.md](fx/README.md). JavaFX docking, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md).
### injection ### injection
+6 -1
View File
@@ -11,6 +11,11 @@ The [live reset example](docs/docking-reset.md) restores the starting arrangemen
without replacing editors, and demonstrates an atomic rejection under changed placement rules. without replacing editors, and demonstrates an atomic rejection under changed placement rules.
The [snapshot example](../fx/docs/docking-snapshots.md) restores a saved arrangement The [snapshot example](../fx/docs/docking-snapshots.md) restores a saved arrangement
into a fresh workspace before it is shown, with load and cleanup diagnostics. into a fresh workspace before it is shown, with load and cleanup diagnostics.
The [Quit/Replace example](../fx/docs/docking-shutdown.md) holds every window open
while saving or retrying, and can attach a fresh manager to the same main window.
The [complete workspace](../fx/docs/docking-workspace.md) combines Java/FXML startup,
plain or optional MVVM editors, real application-owned JSON storage, floating-window
restoration, reset and all-consent shutdown with Retry/Cancel and manager replacement.
## Build and run ## Build and run
@@ -95,7 +100,7 @@ Run the reactor tests without installing artifacts with:
./mvnw -pl fx-example -am clean verify ./mvnw -pl fx-example -am clean verify
``` ```
Inspect Surefire XML reports; a successful Maven exit alone is insufficient with the current parent configuration. JavaFX tests need a usable graphical environment. See the Designer integration section below for the optional preview setup; ordinary application tests do not require the Designer. Inspect Surefire XML reports for test totals, failures and skips. JavaFX tests need a usable graphical environment. See the Designer integration section below for the optional preview setup; ordinary application tests do not require the Designer.
## Open the example in NeitzelFXDesigner ## Open the example in NeitzelFXDesigner
+5
View File
@@ -26,6 +26,11 @@
<artifactId>fx</artifactId> <artifactId>fx</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>gson</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId> <artifactId>slf4j-simple</artifactId>
@@ -0,0 +1,242 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.*;
import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
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.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** Application-owned persistence, editor resources and save decisions around an independent docking manager. */
public final class ReferenceWorkspace implements AutoCloseable {
private final Stage stage;
private final WorkspaceStore store;
private final boolean mvvm;
private final DockPane pane;
private final ExecutorService storage = Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().name("workspace-storage").factory());
private final Map<DockableId, WorkspaceEditor> editors = new LinkedHashMap<>();
private final Label status = identified(new Label(), "workspaceStatus");
private final Label active = identified(new Label(), "activeLabel");
private final TextArea events = identified(new TextArea(), "workspaceEvents");
private final CheckBox veto = check("Readme vetoes close", "vetoReadme");
private final CheckBox saveFailure = check("Simulate save failure", "saveFailure");
private final CheckBox skipReadme = check("Readme missing on reload", "skipReadme");
private final CheckBox mainOnly = check("Project main window only", "projectMainOnly");
private final CheckBox blockProject = check("Project cannot use original group", "blockProject");
private final CheckBox fallback = check("Allow designated editor fallback", "allowFallback");
private final SimpleObjectProperty<CompletableFuture<ShutdownDecision>> pending = new SimpleObjectProperty<>();
private DockingManager manager;
private LayoutSnapshot pendingLayout;
private StoredWorkspace lastSaved;
private boolean saving;
private boolean closeRequested;
private boolean closed;
public ReferenceWorkspace(Stage stage, boolean fxml, boolean mvvm, WorkspaceStore store,
Optional<StoredWorkspace> saved) throws IOException {
this.stage = stage; this.store = store; this.mvvm = mvvm; pane = WorkspaceView.create(fxml);
fallback.setSelected(true);
ToolBar tools = identified(new ToolBar(
button("Save workspace", "saveWorkspace", () -> save(null)),
button("Reload saved", "reloadWorkspace", this::reload),
button("Reset layout", "resetLayout", () -> report(manager.resetLayout())),
button("Replace workspace", "replaceWorkspace", () -> requestClose(true)),
button("Quit", "quitWorkspace", () -> requestClose(false))), "globalTools");
ToolBar placement = new ToolBar(
button("Float active", "floatActive", () -> moveActive(DockTarget.floating())),
button("Return active", "returnActive", () -> moveActive(DockTarget.returnToMain())),
button("Split active right", "splitActive", this::splitActive),
button("Project", "showProject", () -> report(manager.activate(new DockableId("project")))),
button("Changed files", "showChanges", () -> report(manager.activate(new DockableId("changes")))),
button("Clear active editor", "clearActive", this::clearActive));
Button retry = button("Save / Retry", "retrySave", () -> save(pending.get()));
Button cancel = button("Cancel close", "cancelSave", this::cancelSave);
retry.disableProperty().bind(pending.isNull()); cancel.disableProperty().bind(pending.isNull());
TitledPane scenarios = new TitledPane("Restore and close scenarios", new VBox(
new ToolBar(skipReadme, mainOnly, blockProject), new ToolBar(fallback, veto, saveFailure)));
scenarios.setExpanded(false); scenarios.setId("workspaceScenarios");
events.setEditable(false); events.setPrefRowCount(4);
StatusBar globalStatus = identified(new StatusBar(), "globalStatus");
globalStatus.getLeftItems().add(status); globalStatus.getRightItems().add(active);
BorderPane shell = new BorderPane(pane);
shell.setTop(new VBox(tools, placement, scenarios, new ToolBar(retry, cancel)));
shell.setBottom(new VBox(events, globalStatus));
stage.setTitle("NeitzelLib — Reference workspace" + (mvvm ? " (MVVM Notes)" : " (plain JavaFX)"));
stage.setScene(new Scene(shell, 1180, 780));
attach(saved); stage.show();
}
private void attach(Optional<StoredWorkspace> saved) {
DockingOptions options = new DockingOptions();
options.setBeforeShutdown(this::beforeShutdown);
options.setFallbackTarget(fallback.isSelected() ? DockTarget.area("editors") : null);
options.setFloatingWindowCustomizer(configuration -> configuration.setTitle("Reference workspace — floating"));
options.setPlacementRule((dockable, target) -> blockProject.isSelected() && dockable.getId().value().equals("project")
&& target instanceof ResolvedDockTarget.Insertion insertion && insertion.groupId().value().equals("project")
? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), "Project group disabled by application", null))
: Optional.empty());
manager = DockingManager.attach(stage, pane, options);
active.textProperty().unbind();
active.textProperty().bind(javafx.beans.binding.Bindings.createStringBinding(() -> {
Dockable selected = manager.activeDockableProperty().get();
return "Active: " + (selected == null ? "none" : selected.getId().value());
}, manager.activeDockableProperty()));
if (saved.isPresent()) {
lastSaved = saved.get();
RestoreResult result = manager.restore(lastSaved.layout(), id -> resolve(id, lastSaved));
report(result);
if (result instanceof RestoreResult.Applied) { log("Restored workspace before showing new windows"); return; }
log("Restore rejected atomically; opening initial layout");
defaults();
status.setText("Restore rejected: " + ((RestoreResult.Rejected) result).failure().code()
+ "; opened initial workspace. See events for details.");
return;
}
defaults();
}
private void defaults() {
manager.open(editor("readme", new StoredWorkspace.Document("Readme", "Drag a tab, resize groups, or open its keyboard menu with Shift+F10.")), DockTarget.area("editors"));
manager.open(editor("notes", new StoredWorkspace.Document("Notes", "Write notes here. Unsaved text survives move, float and reset.")), DockTarget.area("editors"));
manager.open(tool("project"), DockTarget.area("project"));
manager.open(tool("changes"), DockTarget.area("changes"));
manager.activate(new DockableId("notes"));
status.setText("Workspace ready; " + store.getFile());
}
private DockableResolution resolve(DockableId id, StoredWorkspace saved) {
if (id.value().equals("readme") && skipReadme.isSelected()) return new DockableResolution.Missing();
if (id.value().equals("project") || id.value().equals("changes")) return new DockableResolution.Available(tool(id.value()));
StoredWorkspace.Document document = saved.documents().get(id);
return document == null ? new DockableResolution.Missing() : new DockableResolution.Available(editor(id.value(), document));
}
private Dockable editor(String id, StoredWorkspace.Document document) {
WorkspaceEditor editor = new WorkspaceEditor(id, document, mvvm && id.equals("notes"));
editors.put(editor.getDockable().getId(), editor);
lifecycle(editor.getDockable(), () -> { editors.remove(editor.getDockable().getId(), editor); editor.close(); });
return editor.getDockable();
}
private Dockable tool(String id) {
ListView<String> content = new ListView<>(); content.setId(id + "Content");
content.getItems().addAll(id.equals("project") ? new String[]{"Notes", "Readme", "Workspace layout"}
: new String[]{"Application owns document state", "Save workspace stores current text"});
Dockable dockable = new Dockable(new DockableId(id), content);
dockable.setIcon(new Label(id.equals("project") ? "P" : "Δ"));
dockable.setAccessibleName(id.equals("project") ? "Project" : "Changed files");
dockable.setFocusTarget(() -> content); dockable.setMainWindowOnly(id.equals("project") && mainOnly.isSelected());
lifecycle(dockable, () -> { }); return dockable;
}
private void lifecycle(Dockable dockable, Runnable cleanup) {
dockable.setCloseCheck(request -> {
log("Checked " + dockable.getId().value() + " — " + request.scope().kind());
return CompletableFuture.completedFuture(dockable.getId().value().equals("readme") && veto.isSelected()
? CloseConsent.VETO : CloseConsent.ALLOW);
});
dockable.setOnClosed(() -> { cleanup.run(); log("Closed " + dockable.getId().value()); });
dockable.setOnDiscarded(() -> { cleanup.run(); log("Discarded " + dockable.getId().value()); });
}
private CompletionStage<ShutdownDecision> beforeShutdown(ShutdownRequest request) {
pendingLayout = request.snapshot();
CompletableFuture<ShutdownDecision> decision = new CompletableFuture<>(); pending.set(decision);
status.setText("Save pending — Save / Retry or Cancel close"); log("All consent obtained; save pending " + request.reason());
return decision;
}
private StoredWorkspace capture(LayoutSnapshot layout) {
Map<DockableId, StoredWorkspace.Document> documents = new LinkedHashMap<>();
editors.forEach((id, editor) -> documents.put(id, editor.document()));
return new StoredWorkspace(StoredWorkspace.CURRENT_VERSION, layout, documents);
}
private void save(CompletableFuture<ShutdownDecision> decision) {
if (saving || closed) return;
if (decision == null && pending.get() != null) { status.setText("Use Save / Retry for the pending close"); return; }
StoredWorkspace snapshot = capture(decision == null ? manager.snapshot() : pendingLayout);
if (saveFailure.isSelected()) { status.setText("Save failed (simulated); retry or cancel keeps every editor open"); return; }
saving = true; status.setText("Saving workspace…");
CompletableFuture.runAsync(() -> {
try { store.save(snapshot); } catch (IOException failure) { throw new java.util.concurrent.CompletionException(failure); }
}, storage).whenComplete((unused, failure) -> Platform.runLater(() -> {
saving = false;
if (closed || decision != null && pending.get() != decision) return;
if (failure != null) { status.setText("Save failed: " + failure.getCause().getMessage() + "; retry or cancel"); return; }
lastSaved = snapshot;
if (!capture(snapshot.layout()).documents().equals(snapshot.documents())) {
status.setText("Text changed while saving; save again before closing"); return;
}
editors.values().forEach(WorkspaceEditor::checkpoint);
status.setText("Saved workspace to " + store.getFile()); log("Saved " + snapshot.layout().windows().size() + " windows");
if (decision != null) { pending.set(null); pendingLayout = null; decision.complete(ShutdownDecision.PROCEED); }
}));
}
private void cancelSave() {
CompletableFuture<ShutdownDecision> decision = pending.get();
if (decision == null) return;
pending.set(null); pendingLayout = null; decision.complete(ShutdownDecision.CANCEL);
}
private void requestClose(boolean replace) {
if (closeRequested) return;
closeRequested = true;
CompletionStage<CloseResult> result = replace ? manager.requestManagerClose() : manager.requestMainWindowClose();
result.thenAccept(answer -> {
closeRequested = false;
report(answer);
if (answer instanceof CloseResult.Closed) {
active.textProperty().unbind();
if (replace) { attach(Optional.ofNullable(lastSaved)); log("Reattached workspace to the same Stage and DockPane"); }
else close();
}
});
}
private void reload() {
if (lastSaved == null) { status.setText("Save a workspace first; Reload uses that immutable saved state"); return; }
// The same consent and save protocol protects existing content before replacement.
requestClose(true);
}
private void moveActive(DockTarget target) {
Dockable selected = manager.activeDockableProperty().get();
if (selected != null) report(manager.move(selected.getId(), target));
}
private void splitActive() {
Dockable selected = manager.activeDockableProperty().get(); if (selected == null) return;
manager.layout().windows().stream().flatMap(window -> window.areas().stream()).flatMap(area -> area.groups().stream())
.filter(group -> group.dockableIds().contains(selected.getId())).findFirst()
.ifPresent(group -> report(manager.move(selected.getId(), DockTarget.split(group.id(), Side.RIGHT))));
}
private void clearActive() {
Dockable selected = manager.activeDockableProperty().get();
if (selected != null && editors.containsKey(selected.getId())) editors.get(selected.getId()).getInput().clear();
}
private void report(Object result) { status.setText(result.toString()); log(result.toString()); }
private void log(String text) { events.appendText(text + "\n"); }
private static Button button(String title, String id, Runnable action) {
Button button = identified(new Button(title), id); button.setOnAction(event -> action.run()); return button;
}
private static CheckBox check(String title, String id) { return identified(new CheckBox(title), id); }
private static <T extends javafx.scene.Node> T identified(T node, String id) { node.setId(id); return node; }
/** Stops application I/O and bindings; it does not bypass the manager's consent protocol. */
@Override public void close() {
if (closed) return; closed = true; storage.shutdown();
active.textProperty().unbind(); editors.values().forEach(WorkspaceEditor::close);
}
}
@@ -0,0 +1,40 @@
package de.neitzel.fx.example.docking.workspace;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.nio.file.Path;
import java.util.Optional;
/** Reads application data off the FX thread, then restores before showing any workspace windows. */
public final class ReferenceWorkspaceApp extends Application {
private ReferenceWorkspace workspace;
private volatile boolean stopped;
@Override public void start(Stage stage) {
String location = getParameters().getNamed().get("store");
if (location == null || location.isBlank()) {
stage.setScene(new Scene(new Label("Supply --store=/absolute/path/workspace.json; optional: java, mvvm"), 720, 100));
stage.show(); return;
}
WorkspaceStore store = new WorkspaceStore(Path.of(location));
boolean fxml = !getParameters().getUnnamed().contains("java");
boolean mvvm = getParameters().getUnnamed().contains("mvvm");
Thread.ofVirtual().name("workspace-startup").start(() -> {
try {
Optional<StoredWorkspace> saved = store.read();
Platform.runLater(() -> {
if (stopped) return;
try { workspace = new ReferenceWorkspace(stage, fxml, mvvm, store, saved); }
catch (Exception failure) { showFailure(stage, failure); }
});
} catch (Exception failure) { Platform.runLater(() -> { if (!stopped) showFailure(stage, failure); }); }
});
}
private void showFailure(Stage stage, Exception failure) {
stage.setScene(new Scene(new Label("Workspace was not loaded: " + failure.getMessage()
+ "\nThe existing file has not been changed."), 850, 120)); stage.show();
}
@Override public void stop() { stopped = true; if (workspace != null) workspace.close(); }
}
@@ -0,0 +1,9 @@
package de.neitzel.fx.example.docking.workspace;
import javafx.application.Application;
/** Launcher: --store=/absolute/path/workspace.json [java] [mvvm]. */
public final class ReferenceWorkspaceMain {
private ReferenceWorkspaceMain() { }
public static void main(String[] args) { Application.launch(ReferenceWorkspaceApp.class, args); }
}
@@ -0,0 +1,25 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.LayoutSnapshot;
import java.util.Map;
import java.util.Objects;
/** Application data: document contents are stored separately from the library's layout snapshot. */
public record StoredWorkspace(int version, LayoutSnapshot layout, Map<DockableId, Document> documents) {
public static final int CURRENT_VERSION = 1;
public StoredWorkspace {
Objects.requireNonNull(layout, "layout");
documents = Map.copyOf(documents);
}
/** Text documents have no dependency on their plain-JavaFX or optional MVVM presentation. */
public record Document(String title, String text) {
public Document {
Objects.requireNonNull(title, "title");
Objects.requireNonNull(text, "text");
}
}
}
@@ -0,0 +1,65 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.example.docking.mvvm.MvvmEditor;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import lombok.Getter;
/** Application-owned editor resources. Moving content never rebuilds this adapter. */
final class WorkspaceEditor implements AutoCloseable {
@Getter private final Dockable dockable;
@Getter private final TextArea input;
private final String title;
private final MvvmEditor mvvm;
private final StringBinding titleBinding;
private final StringBinding countBinding;
private final Label count;
private final Button clear;
private String saved;
private boolean released;
WorkspaceEditor(String id, StoredWorkspace.Document document, boolean useMvvm) {
title = document.title(); saved = document.text();
if (useMvvm) {
mvvm = new MvvmEditor(id); dockable = mvvm.getDockable();
input = (TextArea) mvvm.getView().getRoot().lookup("#text");
input.setText(saved); mvvm.checkpoint();
mvvm.getView().getRoot().lookup("#localTools").setId(id + "LocalTools");
mvvm.getView().getRoot().lookup("#localStatus").setId(id + "LocalStatus");
titleBinding = null; countBinding = null; count = null; clear = null;
} else {
mvvm = null; input = new TextArea(saved);
clear = new Button("Clear " + title); clear.setOnAction(event -> input.clear());
ToolBar local = new ToolBar(clear); local.setId(id + "LocalTools");
count = new Label(); countBinding = Bindings.createStringBinding(() -> input.getLength() + " characters", input.textProperty());
count.textProperty().bind(countBinding);
StatusBar status = new StatusBar(); status.setId(id + "LocalStatus"); status.getLeftItems().add(count);
BorderPane root = new BorderPane(input); root.setTop(local); root.setBottom(status);
dockable = new Dockable(new DockableId(id), root);
titleBinding = Bindings.createStringBinding(() -> title + (input.getText().equals(saved) ? "" : " *"), input.textProperty());
dockable.titleProperty().bind(titleBinding);
}
input.setId(id + "Text"); dockable.setFocusTarget(() -> input);
}
StoredWorkspace.Document document() { return new StoredWorkspace.Document(title, input.getText()); }
void checkpoint() {
saved = input.getText();
if (mvvm != null) mvvm.checkpoint(); else titleBinding.invalidate();
}
@Override public void close() {
if (released) return; released = true;
if (mvvm != null) mvvm.close();
else {
dockable.titleProperty().unbind(); titleBinding.dispose();
count.textProperty().unbind(); countBinding.dispose(); clear.setOnAction(null);
}
}
}
@@ -0,0 +1,92 @@
package de.neitzel.fx.example.docking.workspace;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import de.neitzel.fx.docking.DockAreaId;
import de.neitzel.fx.docking.DockGroupId;
import de.neitzel.fx.docking.DockTarget;
import de.neitzel.fx.docking.DockWindowId;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.LayoutSnapshot;
import de.neitzel.fx.docking.TabPosition;
import javafx.geometry.Rectangle2D;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.function.Function;
/** The example's explicit JSON shape; no adapter is registered in the fx library. */
final class WorkspaceJson {
private WorkspaceJson() { }
static Gson create() {
return new GsonBuilder().setPrettyPrinting().enableComplexMapKeySerialization()
.registerTypeAdapter(DockableId.class, new Identifier<>(DockableId::value, DockableId::new))
.registerTypeAdapter(DockAreaId.class, new Identifier<>(DockAreaId::value, DockAreaId::new))
.registerTypeAdapter(DockGroupId.class, new Identifier<>(DockGroupId::value, DockGroupId::new))
.registerTypeAdapter(DockWindowId.class, new Identifier<>(DockWindowId::value, DockWindowId::new))
.registerTypeAdapter(Rectangle2D.class, new Bounds())
.registerTypeAdapter(LayoutSnapshot.Branch.class, new Tagged<LayoutSnapshot.Branch>(Map.of(
"group", LayoutSnapshot.Group.class, "split", LayoutSnapshot.Split.class)))
.registerTypeAdapter(DockTarget.class, new Tagged<DockTarget>(Map.of(
"area", DockTarget.Area.class, "group", DockTarget.Group.class)))
.registerTypeAdapter(TabPosition.class, new Tagged<TabPosition>(Map.of(
"append", TabPosition.Append.class, "before", TabPosition.Before.class, "after", TabPosition.After.class)))
.create();
}
private record Identifier<T>(Function<T, String> print, Function<String, T> parse)
implements JsonSerializer<T>, JsonDeserializer<T> {
@Override public JsonElement serialize(T value, Type type, JsonSerializationContext context) {
return new JsonPrimitive(print.apply(value));
}
@Override public T deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
if (!json.isJsonPrimitive() || !json.getAsJsonPrimitive().isString()) {
throw new JsonParseException("An identity must be a string");
}
return parse.apply(json.getAsString());
}
}
private record Tagged<T>(Map<String, Class<? extends T>> variants)
implements JsonSerializer<T>, JsonDeserializer<T> {
@Override public JsonElement serialize(T value, Type type, JsonSerializationContext context) {
var variant = variants.entrySet().stream().filter(entry -> entry.getValue() == value.getClass())
.findFirst().orElseThrow(() -> new JsonParseException("Unsupported stored layout value"));
JsonObject object = context.serialize(value, variant.getValue()).getAsJsonObject();
object.addProperty("kind", variant.getKey());
return object;
}
@Override public T deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
JsonObject object = json.getAsJsonObject();
JsonElement kind = object.get("kind");
Class<? extends T> variant = kind == null ? null : variants.get(kind.getAsString());
if (variant == null) throw new JsonParseException("Unknown stored layout kind: " + kind);
return context.deserialize(json, variant);
}
}
private static final class Bounds implements JsonSerializer<Rectangle2D>, JsonDeserializer<Rectangle2D> {
@Override public JsonElement serialize(Rectangle2D value, Type type, JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.addProperty("x", value.getMinX());
object.addProperty("y", value.getMinY());
object.addProperty("width", value.getWidth());
object.addProperty("height", value.getHeight());
return object;
}
@Override public Rectangle2D deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
JsonObject object = json.getAsJsonObject();
return new Rectangle2D(object.get("x").getAsDouble(), object.get("y").getAsDouble(),
object.get("width").getAsDouble(), object.get("height").getAsDouble());
}
}
}
@@ -0,0 +1,62 @@
package de.neitzel.fx.example.docking.workspace;
import lombok.Getter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Files;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.Optional;
/** Application-owned storage used by the reference workspace; it is not a library serialization API. */
public final class WorkspaceStore {
private static final com.google.gson.Gson JSON = WorkspaceJson.create();
@Getter private final Path file;
public WorkspaceStore(Path file) {
this.file = Objects.requireNonNull(file, "file").toAbsolutePath().normalize();
if (this.file.getFileName() == null) throw new IllegalArgumentException("A workspace file name is required");
}
public Optional<StoredWorkspace> read() throws IOException {
if (!Files.exists(file)) return Optional.empty();
try (var input = Files.newBufferedReader(file)) {
StoredWorkspace workspace = JSON.fromJson(input, StoredWorkspace.class);
if (workspace == null) throw new IOException("Workspace file contains no workspace");
requireSupportedVersion(workspace);
return Optional.of(workspace);
} catch (RuntimeException invalid) {
throw new IOException("Cannot read workspace data", invalid);
}
}
public void save(StoredWorkspace workspace) throws IOException {
Objects.requireNonNull(workspace, "workspace");
requireSupportedVersion(workspace);
String json;
try { json = JSON.toJson(workspace); }
catch (RuntimeException invalid) { throw new IOException("Cannot encode workspace data", invalid); }
Files.createDirectories(file.getParent());
Path prepared = Files.createTempFile(file.getParent(), file.getFileName() + ".", ".pending");
try {
Files.writeString(prepared, json);
try {
Files.move(prepared, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException unsupported) {
Files.move(prepared, file, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException failure) {
try { Files.deleteIfExists(prepared); }
catch (IOException cleanup) { failure.addSuppressed(cleanup); }
throw failure;
}
}
private static void requireSupportedVersion(StoredWorkspace workspace) throws IOException {
if (workspace.version() != StoredWorkspace.CURRENT_VERSION) {
throw new IOException("Unsupported application workspace version: " + workspace.version());
}
}
}
@@ -0,0 +1,26 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.docking.*;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Side;
import java.io.IOException;
/** Equivalent ordinary FXML and Java definitions; neither requires MVVM. */
final class WorkspaceView {
private WorkspaceView() { }
static DockPane create(boolean fxml) throws IOException {
if (fxml) return FXMLLoader.load(WorkspaceView.class.getResource("ReferenceWorkspace.fxml"));
DockLayout layout = new DockLayout();
layout.setCenter(new DockGroupDefinition("editors"));
layout.setLeft(side("project", Side.LEFT, 240));
DockGroupDefinition changes = side("changes", Side.RIGHT, 220); changes.setMode(DockGroupMode.OVERLAY);
layout.setRight(changes);
DockGroupDefinition bottom = side("bottom", Side.TOP, 200); bottom.setPreferredHeight(160);
layout.setBottom(bottom);
DockPane pane = new DockPane(); pane.setId("workspaceDock"); pane.setInitialLayout(layout); return pane;
}
private static DockGroupDefinition side(String id, Side side, double width) {
DockGroupDefinition group = new DockGroupDefinition(id); group.setTabSide(side); group.setPreferredWidth(width);
group.setCollapsible(true); group.setVisibleWhenEmpty(false); group.setReleaseSpaceWhenEmpty(true); return group;
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.docking.*?>
<DockPane id="workspaceDock" xmlns:fx="http://javafx.com/fxml/1">
<initialLayout><DockLayout>
<center><DockGroupDefinition destinationId="editors"/></center>
<left><DockGroupDefinition destinationId="project" tabSide="LEFT" collapsible="true"
preferredWidth="240" visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></left>
<right><DockGroupDefinition destinationId="changes" tabSide="RIGHT" collapsible="true" mode="OVERLAY"
preferredWidth="220" visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></right>
<bottom><DockGroupDefinition destinationId="bottom" collapsible="true" preferredHeight="160"
visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/></bottom>
</DockLayout></initialLayout>
</DockPane>
@@ -0,0 +1,239 @@
package de.neitzel.fx.example.docking.workspace;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import de.neitzel.fx.docking.DockableId;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.io.TempDir;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Rectangle;
import javax.imageio.ImageIO;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.*;
import static de.neitzel.fx.example.docking.workspace.ReferenceWorkspaceTest.onFx;
/** Actual application controls plus OS input; requires an exclusive interactive desktop. */
@EnabledIfSystemProperty(named = "neitzellib.nativeWorkspaceTest", matches = "true")
class NativeReferenceWorkspaceTest {
@TempDir Path directory;
private static final int[] KEYS = {KeyEvent.VK_DOWN, KeyEvent.VK_ENTER, KeyEvent.VK_1, KeyEvent.VK_2};
@Test @Timeout(35)
void actualDragTypingAndKeyboardReturnKeepTheEditorUntilEveryCloseAnswer() throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(20);
Point pointer = MouseInfo.getPointerInfo().getLocation();
AtomicReference<Fixture> fixture = new AtomicReference<>();
AtomicReference<List<Window>> existingWindows = new AtomicReference<>();
AtomicReference<ReferenceWorkspace> application = new AtomicReference<>();
var watchdog = Executors.newSingleThreadScheduledExecutor();
watchdog.schedule(() -> robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK), 30, TimeUnit.SECONDS);
try {
onFx(() -> {
javafx.application.Platform.setImplicitExit(false);
List<Window> existing = List.copyOf(Window.getWindows()); existingWindows.set(existing);
Stage main = new Stage();
ReferenceWorkspace app = new ReferenceWorkspace(main, true, false,
new WorkspaceStore(directory.resolve("workspace.json")), Optional.empty());
application.set(app);
var screen = Screen.getPrimary().getVisualBounds();
main.setX(screen.getMinX() + 40); main.setY(screen.getMinY() + 40);
main.setWidth(720); main.setHeight(560);
Parent root = main.getScene().getRoot(); root.applyCss(); root.layout();
TextArea notes = (TextArea) root.lookup("#notesText"); assertNotNull(notes);
notes.setText("abcdef"); notes.selectRange(2, 4);
fixture.set(new Fixture(main, notes, new javafx.scene.robot.Robot()));
});
Fixture f = fixture.get();
await(() -> f.main.isFocused(), "The application main window must have native focus before the gesture");
Point outside = value(() -> {
var bounds = Screen.getPrimary().getVisualBounds();
Point target = new Point((int) bounds.getMaxX() - 80, (int) bounds.getMinY() + 160);
assertTrue(target.x > f.main.getX() + f.main.getWidth(), "Fixture must leave desktop space for floating");
return target;
});
drag(robot, value(() -> headerPoint(f.notes)), outside);
await(() -> f.notes.getScene().getWindow() != f.main, "Native drop outside must float Notes");
type(robot, f.notes, KeyEvent.VK_1, "ab1ef");
captureRequestedScreenshot(robot, f);
command(robot, f, "Return to main");
await(() -> f.notes.getScene().getWindow() == f.main, "The native keyboard menu must return Notes");
type(robot, f.notes, KeyEvent.VK_2, "ab12ef");
onFx(() -> assertSame(f.notes, f.main.getScene().lookup("#notesText")));
Parent root = value(() -> f.main.getScene().getRoot());
TextArea events = value(() -> (TextArea) root.lookup("#workspaceEvents"));
onFx(() -> {
((TitledPane) root.lookup("#workspaceScenarios")).setExpanded(true);
root.applyCss(); root.layout();
((CheckBox) root.lookup("#vetoReadme")).fire();
((Button) root.lookup("#quitWorkspace")).fire();
});
await(() -> events.getText().contains("Checked changes"), "Quit must ask every Dockable despite Readme's veto");
onFx(() -> {
assertAllCheckedBeforeAnyClosed(events.getText());
assertFalse(events.getText().contains("Closed "));
assertTrue(f.main.isShowing());
assertSame(f.notes, root.lookup("#notesText"));
assertNotNull(root.lookup("#readmeText"));
((CheckBox) root.lookup("#vetoReadme")).fire();
((CheckBox) root.lookup("#saveFailure")).fire();
((Button) root.lookup("#quitWorkspace")).fire();
});
await(() -> events.getText().contains("All consent obtained; save pending"), "Unanimous consent must reach the application's save phase");
onFx(() -> {
assertEquals(8, events.getText().lines().filter(line -> line.startsWith("Checked ")).count(),
"The vetoed attempt and the fresh attempt must each ask all four Dockables");
assertTrue(f.main.isShowing()); assertSame(f.notes, root.lookup("#notesText"));
assertFalse(events.getText().contains("Closed "));
((Button) root.lookup("#retrySave")).fire();
assertTrue(((Label) root.lookup("#workspaceStatus")).getText().startsWith("Save failed"));
assertFalse(events.getText().contains("Closed "), "Save failure must keep every Dockable open");
((CheckBox) root.lookup("#saveFailure")).fire();
((Button) root.lookup("#retrySave")).fire();
});
await(() -> !f.main.isShowing(), "Successful save must complete Quit");
onFx(() -> {
String log = events.getText();
assertAllCheckedBeforeAnyClosed(log);
assertEquals(4, log.lines().filter(line -> line.startsWith("Closed ")).count());
assertTrue(log.lastIndexOf("Checked ") < log.indexOf("All consent obtained; save pending"));
assertTrue(log.indexOf("Saved ") < log.indexOf("Closed "), "Persist before releasing editor resources");
});
StoredWorkspace saved = new WorkspaceStore(directory.resolve("workspace.json")).read().orElseThrow();
assertEquals("ab12ef", saved.documents().get(new DockableId("notes")).text());
} finally {
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
for (int key : KEYS) robot.keyRelease(key);
robot.mouseMove(pointer.x, pointer.y);
watchdog.shutdownNow();
if (existingWindows.get() != null) onFx(() -> {
if (fixture.get() != null) {
fixture.get().keyboard.keyRelease(javafx.scene.input.KeyCode.F10);
fixture.get().keyboard.keyRelease(javafx.scene.input.KeyCode.SHIFT);
}
try { if (application.get() != null) application.get().close(); }
finally { List.copyOf(Window.getWindows()).stream().filter(w -> !existingWindows.get().contains(w)).forEach(Window::hide); }
});
}
}
private static void captureRequestedScreenshot(Robot robot, Fixture fixture) throws Exception {
String output = System.getProperty("neitzellib.workspaceScreenshot");
if (output == null || output.isBlank()) return;
Rectangle frame = value(() -> {
Window floating = fixture.notes.getScene().getWindow();
double x = Math.min(fixture.main.getX(), floating.getX());
double y = Math.min(fixture.main.getY(), floating.getY());
double right = Math.max(fixture.main.getX() + fixture.main.getWidth(), floating.getX() + floating.getWidth());
double bottom = Math.max(fixture.main.getY() + fixture.main.getHeight(), floating.getY() + floating.getHeight());
return new Rectangle((int) Math.floor(x), (int) Math.floor(y), (int) Math.ceil(right - x), (int) Math.ceil(bottom - y));
});
ImageIO.write(robot.createScreenCapture(frame), "png", Path.of(output).toFile());
}
private static void assertAllCheckedBeforeAnyClosed(String log) {
for (String id : List.of("notes", "readme", "project", "changes")) {
int checked = log.indexOf("Checked " + id + " — MAIN_WINDOW");
assertTrue(checked >= 0, "Missing application consent for " + id);
assertTrue(log.indexOf("Closed ") < 0 || checked < log.indexOf("Closed "));
}
}
private static void command(Robot robot, Fixture f, String action) throws Exception {
AtomicReference<TabPane> strip = new AtomicReference<>();
AtomicReference<ContextMenu> menu = new AtomicReference<>();
onFx(() -> {
var root = f.notes.getScene().getRoot(); root.applyCss(); root.layout();
TabPane tabs = owningTabs(f.notes); tabs.requestFocus(); strip.set(tabs);
menu.set(tabs.getSelectionModel().getSelectedItem().getContextMenu());
});
await(() -> f.notes.getScene().getWindow().isFocused() && f.notes.getScene().getFocusOwner() == strip.get(),
"The header must have native focus before Shift+F10");
onFx(() -> {
try { f.keyboard.keyPress(javafx.scene.input.KeyCode.SHIFT); f.keyboard.keyPress(javafx.scene.input.KeyCode.F10); }
finally { f.keyboard.keyRelease(javafx.scene.input.KeyCode.F10); f.keyboard.keyRelease(javafx.scene.input.KeyCode.SHIFT); }
});
await(() -> menu.get().isShowing(), "Native Shift+F10 must open the menu");
for (int step = 0; step < 8; step++) {
String current = value(() -> focusedAction(menu.get()));
if (action.equals(current)) break;
press(robot, KeyEvent.VK_DOWN);
await(() -> !java.util.Objects.equals(current, focusedAction(menu.get())), "Arrow must change the focused action");
}
onFx(() -> assertEquals(action, focusedAction(menu.get())));
press(robot, KeyEvent.VK_ENTER);
}
private static String focusedAction(ContextMenu menu) {
return menu.getSkin().getNode().lookupAll(".menu-item:focused").stream()
.map(node -> (String) node.queryAccessibleAttribute(javafx.scene.AccessibleAttribute.TEXT))
.findFirst().orElse(null);
}
private static TabPane owningTabs(Node content) {
Node current = content;
while (current != null && !(current instanceof TabPane)) current = current.getParent();
return assertInstanceOf(TabPane.class, current);
}
private static Point headerPoint(TextArea notes) {
TabPane tabs = owningTabs(notes);
Node header = tabs.lookup("#" + tabs.getSelectionModel().getSelectedItem().getId());
assertNotNull(header);
Bounds bounds = header.localToScreen(header.getBoundsInLocal());
return new Point((int) bounds.getCenterX(), (int) bounds.getCenterY());
}
private static void drag(Robot robot, Point from, Point to) throws Exception {
robot.mouseMove(from.x, from.y); Thread.sleep(100);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
try {
for (int step = 1; step <= 16; step++) {
robot.mouseMove(from.x + (to.x - from.x) * step / 16, from.y + (to.y - from.y) * step / 16);
Thread.sleep(25);
}
} finally { robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); }
}
private static void type(Robot robot, TextArea notes, int key, String expected) throws Exception {
await(() -> notes.getScene().getWindow().isFocused() && notes.getScene().getFocusOwner() == notes,
"Transfer must restore native/content focus without a click");
press(robot, key);
await(() -> expected.equals(notes.getText()), "Actual typing must preserve the selection/caret: " + expected);
}
private static void press(Robot robot, int key) {
try { robot.keyPress(key); } finally { robot.keyRelease(key); }
}
private static <T> T value(Supplier<T> action) throws Exception {
AtomicReference<T> result = new AtomicReference<>(); onFx(() -> result.set(action.get())); return result.get();
}
private static void await(BooleanSupplier condition, String message) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(4);
boolean ready;
do { Thread.sleep(25); ready = value(condition::getAsBoolean); } while (!ready && System.nanoTime() < deadline);
assertTrue(ready, message);
}
private record Fixture(Stage main, TextArea notes, javafx.scene.robot.Robot keyboard) { }
}
@@ -0,0 +1,195 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.docking.DockPane;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class ReferenceWorkspaceTest {
@TempDir Path directory;
@ParameterizedTest @ValueSource(booleans = {false, true})
void javaAndFxmlWorkspacesRetainEditorAndLocalBarsAcrossFloatReturnAndReset(boolean fxml) throws Exception {
onFx(() -> {
Platform.setImplicitExit(false);
List<Window> existing = List.copyOf(Window.getWindows());
Stage stage = new Stage();
try (ReferenceWorkspace app = new ReferenceWorkspace(stage, fxml, false,
new WorkspaceStore(directory.resolve("workspace.json")), Optional.empty())) {
Parent root = stage.getScene().getRoot(); root.applyCss(); root.layout();
assertInstanceOf(DockPane.class, root.lookup("#workspaceDock"));
ToolBar global = (ToolBar) root.lookup("#globalTools"); assertNotNull(global);
TextArea notes = (TextArea) root.lookup("#notesText"); assertNotNull(notes);
notes.setText("Unsaved workspace text"); notes.selectRange(2, 9);
Object local = root.lookup("#notesLocalTools"); assertNotNull(local);
button(root, "floatActive").fire();
Stage floating = (Stage) Window.getWindows().stream().filter(w -> !existing.contains(w) && w != stage)
.findFirst().orElseThrow();
assertSame(notes, floating.getScene().getRoot().lookup("#notesText"));
assertSame(local, floating.getScene().getRoot().lookup("#notesLocalTools"));
assertSame(global, root.lookup("#globalTools"));
button(root, "returnActive").fire();
assertSame(notes, root.lookup("#notesText"));
button(root, "splitActive").fire();
button(root, "resetLayout").fire();
assertSame(notes, root.lookup("#notesText"));
assertEquals("Unsaved workspace text", notes.getText());
assertEquals(2, notes.getSelection().getStart()); assertEquals(9, notes.getSelection().getEnd());
} finally { Window.getWindows().stream().filter(w -> !existing.contains(w)).toList().forEach(Window::hide); }
});
}
@org.junit.jupiter.api.Test
void saveRetryCancelAndRepeatedReplaceProtectTextThenRestoreFromTheRealFile() throws Exception {
AtomicReference<Stage> stageRef = new AtomicReference<>();
AtomicReference<ReferenceWorkspace> appRef = new AtomicReference<>();
AtomicReference<TextArea> original = new AtomicReference<>();
WorkspaceStore store = new WorkspaceStore(directory.resolve("saved/workspace.json"));
try {
onFx(() -> {
Platform.setImplicitExit(false);
Stage stage = new Stage(); stageRef.set(stage);
appRef.set(new ReferenceWorkspace(stage, true, false, store, Optional.empty()));
Parent root = stage.getScene().getRoot(); root.applyCss(); root.layout();
TextArea notes = (TextArea) root.lookup("#notesText"); original.set(notes);
notes.setText("Unsaved Ω, survives retry and cancellation");
((javafx.scene.control.CheckBox) root.lookup("#vetoReadme")).setSelected(true);
button(root, "replaceWorkspace").fire();
String history = ((TextArea) root.lookup("#workspaceEvents")).getText();
for (String id : List.of("readme", "notes", "project", "changes")) assertTrue(history.contains("Checked " + id));
assertFalse(history.contains("Closed ")); assertFalse(history.contains("All consent obtained"));
((javafx.scene.control.CheckBox) root.lookup("#vetoReadme")).setSelected(false);
((javafx.scene.control.CheckBox) root.lookup("#saveFailure")).setSelected(true);
button(root, "replaceWorkspace").fire(); button(root, "retrySave").fire();
assertTrue(label(root).contains("Save failed")); assertSame(notes, root.lookup("#notesText"));
button(root, "cancelSave").fire(); assertTrue(label(root).contains("Canceled"));
assertSame(notes, root.lookup("#notesText"));
((javafx.scene.control.CheckBox) root.lookup("#saveFailure")).setSelected(false);
button(root, "replaceWorkspace").fire(); button(root, "replaceWorkspace").fire();
button(root, "retrySave").fire();
});
awaitFx(() -> ((TextArea) stageRef.get().getScene().getRoot().lookup("#workspaceEvents")).getText().contains("Reattached workspace"));
onFx(() -> {
Parent root = stageRef.get().getScene().getRoot(); root.applyCss(); root.layout();
TextArea restored = (TextArea) root.lookup("#notesText");
assertNotSame(original.get(), restored);
assertEquals(original.get().getText(), restored.getText());
assertTrue(label(root).contains("Applied"), "A repeated Replace must not run a second attachment: " + label(root));
assertEquals(1, ((TextArea) root.lookup("#workspaceEvents")).getText().lines().filter(line -> line.startsWith("Reattached")).count());
});
StoredWorkspace saved = store.read().orElseThrow();
assertEquals("Unsaved Ω, survives retry and cancellation", saved.documents().get(new de.neitzel.fx.docking.DockableId("notes")).text());
} finally {
onFx(() -> { if (appRef.get() != null) appRef.get().close(); if (stageRef.get() != null) stageRef.get().hide(); });
}
}
@org.junit.jupiter.api.Test
void savedFloatingMvvmEditorRestoresBeforeShowAndMissingReadmeIsReportedOnReplacement() throws Exception {
WorkspaceStore store = new WorkspaceStore(directory.resolve("mvvm.json"));
AtomicReference<Stage> stageRef = new AtomicReference<>();
AtomicReference<ReferenceWorkspace> appRef = new AtomicReference<>();
AtomicReference<List<Window>> initial = new AtomicReference<>();
AtomicReference<TextArea> original = new AtomicReference<>();
try {
onFx(() -> {
Platform.setImplicitExit(false); initial.set(List.copyOf(Window.getWindows()));
Stage stage = new Stage(); stageRef.set(stage);
appRef.set(new ReferenceWorkspace(stage, true, true, store, Optional.empty()));
Parent root = stage.getScene().getRoot(); root.applyCss(); root.layout();
TextArea notes = (TextArea) root.lookup("#notesText"); original.set(notes);
notes.setText("MVVM notes saved in a floating host"); notes.selectRange(5, 10);
button(root, "floatActive").fire();
Stage floating = (Stage) Window.getWindows().stream().filter(w -> !initial.get().contains(w) && w != stage).findFirst().orElseThrow();
assertSame(notes, floating.getScene().getRoot().lookup("#notesText"));
button(root, "saveWorkspace").fire();
});
awaitFx(() -> label(stageRef.get().getScene().getRoot()).startsWith("Saved workspace"));
StoredWorkspace saved = store.read().orElseThrow();
assertEquals(2, saved.layout().windows().size());
onFx(() -> {
appRef.get().close(); Window.getWindows().stream().filter(w -> !initial.get().contains(w)).toList().forEach(Window::hide);
Stage stage = new Stage(); stageRef.set(stage);
appRef.set(new ReferenceWorkspace(stage, true, true, store, Optional.of(saved)));
Parent root = stage.getScene().getRoot(); root.applyCss(); root.layout();
Stage floating = (Stage) Window.getWindows().stream().filter(w -> !initial.get().contains(w) && w != stage).findFirst().orElseThrow();
TextArea notes = (TextArea) floating.getScene().getRoot().lookup("#notesText");
assertNotSame(original.get(), notes); assertEquals(original.get().getText(), notes.getText());
notes.selectRange(5, 10); button(root, "returnActive").fire();
assertSame(notes, root.lookup("#notesText")); assertEquals(5, notes.getSelection().getStart());
button(root, "clearActive").fire(); assertEquals("", notes.getText());
assertTrue(root.lookupAll(".tab").stream().anyMatch(n -> n.lookupAll(".tab-label").stream()
.filter(javafx.scene.control.Label.class::isInstance).map(javafx.scene.control.Label.class::cast)
.anyMatch(l -> l.getText().equals("Notes *"))), "MVVM title still follows the edited model");
((javafx.scene.control.CheckBox) root.lookup("#skipReadme")).setSelected(true);
((javafx.scene.control.CheckBox) root.lookup("#blockProject")).setSelected(true);
button(root, "replaceWorkspace").fire(); button(root, "retrySave").fire();
});
awaitFx(() -> ((TextArea) stageRef.get().getScene().getRoot().lookup("#workspaceEvents")).getText().contains("Reattached workspace"));
onFx(() -> {
Parent root = stageRef.get().getScene().getRoot(); root.applyCss(); root.layout();
assertTrue(label(root).contains("readme"), label(root));
assertFalse(root.lookupAll(".tab-label").stream().filter(javafx.scene.control.Label.class::isInstance)
.map(javafx.scene.control.Label.class::cast).anyMatch(l -> l.getText().startsWith("Readme")));
assertNotNull(root.lookup("#notesText"));
});
} finally { onFx(() -> {
if (appRef.get() != null) appRef.get().close();
if (initial.get() != null) Window.getWindows().stream().filter(w -> !initial.get().contains(w)).toList().forEach(Window::hide);
}); }
}
@org.junit.jupiter.api.Test
void rejectedSnapshotLeavesAVisibleDiagnosticWhenTheInitialWorkspaceIsOpened() throws Exception {
onFx(() -> {
Platform.setImplicitExit(false);
Stage stage = new Stage();
var invalid = new de.neitzel.fx.docking.LayoutSnapshot(999, List.of(), null, java.util.Map.of(), java.util.Map.of());
var saved = new StoredWorkspace(StoredWorkspace.CURRENT_VERSION, invalid, java.util.Map.of());
try (ReferenceWorkspace app = new ReferenceWorkspace(stage, true, false,
new WorkspaceStore(directory.resolve("rejected.json")), Optional.of(saved))) {
Parent root = stage.getScene().getRoot(); root.applyCss(); root.layout();
assertNotNull(root.lookup("#notesText"), "The initial arrangement remains usable after rejection");
assertTrue(label(root).contains("UNSUPPORTED_SNAPSHOT_VERSION"), label(root));
assertTrue(label(root).contains("initial workspace"), label(root));
} finally { stage.hide(); }
});
}
private static String label(Parent root) { return ((javafx.scene.control.Label) root.lookup("#workspaceStatus")).getText(); }
private static void awaitFx(java.util.function.BooleanSupplier condition) throws Exception {
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (System.nanoTime() < end) {
java.util.concurrent.atomic.AtomicBoolean done = new java.util.concurrent.atomic.AtomicBoolean();
onFx(() -> done.set(condition.getAsBoolean()));
if (done.get()) return;
Thread.sleep(25);
}
fail("Application did not complete its asynchronous operation");
}
static Button button(Parent root, String id) { return (Button) root.lookup("#" + id); }
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 e) { failure.set(e); } finally { done.countDown(); } });
assertTrue(done.await(20, TimeUnit.SECONDS));
if (failure.get() != null) fail("Reference workspace failed", failure.get());
}
@FunctionalInterface interface FxAction { void run() throws Exception; }
}
@@ -0,0 +1,110 @@
package de.neitzel.fx.example.docking.workspace;
import de.neitzel.fx.docking.*;
import javafx.geometry.Orientation;
import javafx.geometry.Rectangle2D;
import javafx.geometry.Side;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
/** Exercises the example's actual file boundary without JavaFX Nodes or a running toolkit. */
class WorkspaceStoreTest {
@TempDir Path directory;
@Test
void fileRoundTripKeepsDocumentTextAndTheCompleteTypedLayoutGraph() throws Exception {
WorkspaceStore store = new WorkspaceStore(directory.resolve("state/workspace.json"));
assertTrue(store.read().isEmpty());
StoredWorkspace workspace = workspace();
store.save(workspace);
assertEquals(workspace, new WorkspaceStore(store.getFile()).read().orElseThrow());
String json = Files.readString(store.getFile());
assertTrue(json.contains("Unsaved text"));
assertFalse(json.contains("javafx.scene"), "Persistence stores application data, not live controls");
}
@Test
void failedReplacementPreservesExistingDataCleansPreparationAndAllowsRetry() throws Exception {
Path state = Files.createDirectory(directory.resolve("state"));
Path destination = Files.createDirectory(state.resolve("workspace.json"));
Path existing = destination.resolve("existing-document.txt");
Files.writeString(existing, "Existing application data");
WorkspaceStore store = new WorkspaceStore(destination);
assertThrows(IOException.class, () -> store.save(workspace()));
assertEquals("Existing application data", Files.readString(existing));
try (var files = Files.list(state)) {
assertEquals(List.of(destination), files.toList(), "A failed replacement must remove its prepared file");
}
Files.delete(existing);
Files.delete(destination);
store.save(workspace());
assertEquals(workspace(), new WorkspaceStore(destination).read().orElseThrow());
}
@Test
void invalidInputAndUnsupportedSaveNeverRewriteExistingFile() throws Exception {
WorkspaceStore store = new WorkspaceStore(directory.resolve("workspace.json"));
StoredWorkspace original = workspace();
store.save(original);
byte[] savedBytes = Files.readAllBytes(store.getFile());
StoredWorkspace future = new StoredWorkspace(999, original.layout(), original.documents());
assertThrows(IOException.class, () -> store.save(future));
assertArrayEquals(savedBytes, Files.readAllBytes(store.getFile()));
assertEquals(original, store.read().orElseThrow());
String unsupported = Files.readString(store.getFile()).replaceFirst("\"version\"\\s*:\\s*1", "\"version\": 999");
for (String invalid : List.of("{", unsupported)) {
Files.writeString(store.getFile(), invalid);
assertThrows(IOException.class, store::read);
assertEquals(invalid, Files.readString(store.getFile()), "Reading invalid data must preserve it for recovery");
}
}
private static StoredWorkspace workspace() {
var notes = new DockableId("notes");
var before = new DockableId("before");
var after = new DockableId("after");
var appended = new DockableId("appended");
var settings = new LayoutSnapshot.GroupSettings(Side.TOP, DockGroupMode.DOCKED,
240, 180, 80, 80, true, true, false, true, SplitDirections.ALL);
var editor = group("primary", settings, List.of(notes), notes);
var secondary = group("secondary", settings, List.of(), null);
var split = new LayoutSnapshot.Split(List.of(new DockAreaId("editors")), Orientation.HORIZONTAL,
.37, editor, secondary);
var overlaySettings = new LayoutSnapshot.GroupSettings(Side.LEFT, DockGroupMode.OVERLAY,
210, 160, 80, 80, true, false, true, true, SplitDirections.VERTICAL);
var main = new LayoutSnapshot.Window(new DockWindowId("main"), true, null, List.of(
new LayoutSnapshot.Root(LayoutSnapshot.Placement.CENTER, -1, -1, split),
new LayoutSnapshot.Root(LayoutSnapshot.Placement.LEFT, 210, -1, group("project", overlaySettings, List.of(), null))));
var floating = new LayoutSnapshot.Window(new DockWindowId("floating-7"), false,
new Rectangle2D(-900, 123, 640, 420), List.of(new LayoutSnapshot.Root(
LayoutSnapshot.Placement.CENTER, -1, -1, group("floating-area", settings, List.of(before, after, appended), before))));
var layout = new LayoutSnapshot(LayoutSnapshot.CURRENT_VERSION, List.of(main, floating), before,
Map.of(notes, new LayoutSnapshot.ReturnPosition(DockTarget.area("editors"), new DockAreaId("editors")),
before, new LayoutSnapshot.ReturnPosition(DockTarget.group(editor.id(), TabPosition.before(notes)), new DockAreaId("editors")),
after, new LayoutSnapshot.ReturnPosition(DockTarget.group(editor.id(), TabPosition.after(notes)), new DockAreaId("editors")),
appended, new LayoutSnapshot.ReturnPosition(DockTarget.group(editor.id()), new DockAreaId("editors"))),
Map.of(notes, new DockAreaId("primary"), before, new DockAreaId("secondary")));
return new StoredWorkspace(StoredWorkspace.CURRENT_VERSION, layout, Map.of(
notes, new StoredWorkspace.Document("Notes", "Unsaved text\nÄnderung: \"quoted\" and λ"),
before, new StoredWorkspace.Document("Before", "Before document"),
after, new StoredWorkspace.Document("After", "After document"),
appended, new StoredWorkspace.Document("Appended", "Appended document")));
}
private static LayoutSnapshot.Group group(String id, LayoutSnapshot.GroupSettings settings,
List<DockableId> tabs, DockableId selected) {
return new LayoutSnapshot.Group(List.of(new DockAreaId(id)), new DockGroupId(id), new DockAreaId(id),
settings, settings.mode() == DockGroupMode.OVERLAY, 317.5, 248.25, tabs, selected);
}
}
+3 -1
View File
@@ -16,11 +16,13 @@
- [Live reset](../fx-example/docs/docking-reset.md), retaining existing contents and unsaved edits. - [Live reset](../fx-example/docs/docking-reset.md), retaining existing contents and unsaved edits.
- [Asynchronous tab close](docs/docking-close.md), including consent and resource release. - [Asynchronous tab close](docs/docking-close.md), including consent and resource release.
- [Quit, save and replace a workspace](docs/docking-shutdown.md), with global consent, retry and main-window ownership. - [Quit, save and replace a workspace](docs/docking-shutdown.md), with global consent, retry and main-window ownership.
- [Complete docking workspace](docs/docking-workspace.md), combining Java/FXML startup, application storage and shutdown.
- [Keyboard access, translations and themes](docs/docking-accessibility.md).
- [Dependency injection](../injection/README.md). - [Dependency injection](../injection/README.md).
## Introduction ## Introduction
`fx` binds an FXML view to an ordinary Java model. The model stays a JavaBean. The library builds one view model for that instance, loads the view, and applies the binding elements declared in the FXML. `fx` includes docking and standalone bars for ordinary JavaFX applications; these controls do not require MVVM initialization. Its optional MVVM functionality binds an FXML view to an ordinary Java model. The model stays a JavaBean. The library builds one view model for that instance, loads the view, and applies the binding elements declared in the FXML.
You write the model, the FXML, and, where a screen needs them, a controller, reusable components, and converters. The library creates the view model. The [injection](../injection/README.md) container creates the controller, each component, and each converter. You write the model, the FXML, and, where a screen needs them, a controller, reusable components, and converters. The library creates the view model. The [injection](../injection/README.md) container creates the controller, each component, and each converter.
+103
View File
@@ -0,0 +1,103 @@
# Reference docking workspace
The `fx-example` package `de.neitzel.fx.example.docking.workspace` combines the
public docking workflows in one application. `ReferenceWorkspace` builds the
same initial layout from Java or ordinary FXML. The default editors use plain
JavaFX; optional MVVM changes the Notes editor adapter, not the docking API.
## Build and launch
From the NeitzelLib checkout with Java 25, build without installing over local
runtime artifacts:
```sh
./mvnw -pl fx-example -am -DskipVersions=true -Dversions.skip=true package
workspace_dir="$(mktemp -d)"
java --enable-native-access=ALL-UNNAMED \
-cp 'fx-example/target/classes:fx-example/target/libs/*' \
de.neitzel.fx.example.docking.workspace.ReferenceWorkspaceMain \
--store="$workspace_dir/workspace.json"
```
The default loads ordinary FXML and uses plain JavaFX editors. Append `java` to
construct the same layout in Java, or `mvvm` to use the optional MVVM Notes
adapter; both arguments can be combined. The explicit `--store` path determines
the only workspace file the example reads or replaces. Restart with that same
path to restore the saved arrangement and document text. Malformed or unsupported
application data produces an explanatory window and leaves the file unchanged.
## Follow the application boundary
The constructor receives a Stage, the Java/FXML and MVVM choices, a
`WorkspaceStore`, and optional previously loaded `StoredWorkspace` data. The
application loads file data before constructing the workspace, attaches its
DockingManager on the JavaFX thread, and restores into the empty manager before
showing the main Stage. Floating windows prepared by restore appear after it.
The library's `LayoutSnapshot` describes arrangement and identities. The
example's `StoredWorkspace` adds a separate map of document titles and text.
`WorkspaceJson` defines the application's versioned JSON representation;
`WorkspaceStore` writes a temporary file and replaces the selected workspace
file. None of those serialization types belong to the `fx` API. The example
adds Gson as its own dependency; docking does not require it.
| Part | Responsibility |
| --- | --- |
| `ReferenceWorkspace` | Layout startup, real controls, editor creation, diagnostics and shutdown callbacks |
| `StoredWorkspace` | Immutable application data: layout plus independent document records |
| `WorkspaceStore` | Reading and replacing the selected application file |
| `WorkspaceJson` | Application-specific tags and adapters for layout values |
| `DockingManager` | Placement, windows, groups, focus, consent and completed layout publication |
## Exercise the combined workflows
The initial workspace has central editors, Project on the left, Changes in a
right overlay, and a persistent empty bottom destination. Global toolbar and
status controls remain outside the DockPane; each editor keeps its own local
bar when moved. Drag tab headers to move, split or float content, drag dividers
to resize, and use the tab context menu to return floating content. Click an
active side symbol to collapse its whole group; another symbol reopens that
group with the selected content. Reset rearranges the current editor Nodes and
keeps their unsaved text.
The application's placement and missing-document controls make restoration
outcomes visible in its status and event log. Missing IDs permit partial
restoration. A changed placement rule uses only the configured eligible
fallback; an unresolvable placement rejects the whole preparation. The example
reports that failure and opens fresh default content in the initial layout. A close veto leaves every affected
editor and floating window open and prevents the shutdown-save callback.
Quit and manager replacement use the same all-consent workflow. Only after
every Dockable allows closing does the application receive the complete
pre-close snapshot. A failed file save keeps that workflow pending so Retry
can try again or Cancel can leave the workspace open. The manager's close scope
covers the save wait. On successful manager replacement the Stage remains open,
old application resources are released and a fresh manager attaches to the same
DockPane. Restoration creates fresh editor adapters from the newly saved data.
**Reload saved** uses this same save-before-replacement workflow, so it protects
current edits instead of silently reverting them to an older file.
## Ownership, threading and lifetime
Read and write files outside the JavaFX thread. Capture document text and call
manager operations on that thread, then pass immutable data to the I/O worker.
Consent and save stages can finish asynchronously; the library resumes close
processing on the JavaFX thread. Do not block that thread waiting for a future.
The application owns editor resources. Moving, floating, returning and resetting
retain the same content Node and do not call cleanup callbacks. Actual close
calls `onClosed`; a failed factory or restore preparation calls `onDiscarded`
for newly adopted, unused content. An already attached foreign Node stays with
its existing owner. A callback failure is diagnostic and does not stop other
required cleanup.
Optional MVVM uses an already loaded View root with ordinary docking callbacks.
The example releases its own bindings/listeners. It does not promise eviction
of the existing MVVM identity cache or a general LoadedView disposal mechanism;
see [MVVM lifetime](architecture.md) and the [editor integration](../../fx-example/docs/docking-mvvm.md).
The FXML path is ordinary FXMLLoader input. Designer authoring, transfers between
independent managers/processes and JavaFX Dragboard interoperability are outside
this implementation. Native input has to be qualified on each target desktop;
see the [drag](docking-drag.md) and [keyboard](docking-accessibility.md) guides for
the executed platform checks.