Complete multiwindow restore, coordinated shutdown and keyboard docking
This commit is contained in:
@@ -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;
|
package de.neitzel.fx.example.docking;
|
||||||
|
|
||||||
import de.neitzel.fx.docking.DockPane;
|
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.DockTarget;
|
||||||
import de.neitzel.fx.docking.Dockable;
|
import de.neitzel.fx.docking.Dockable;
|
||||||
import de.neitzel.fx.docking.DockableId;
|
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.DockingOptions;
|
||||||
import de.neitzel.fx.docking.LayoutSnapshot;
|
import de.neitzel.fx.docking.LayoutSnapshot;
|
||||||
import de.neitzel.fx.docking.RestoreResult;
|
import de.neitzel.fx.docking.RestoreResult;
|
||||||
|
import de.neitzel.fx.docking.ResolvedDockTarget;
|
||||||
import javafx.application.Application;
|
import javafx.application.Application;
|
||||||
import javafx.fxml.FXMLLoader;
|
import javafx.fxml.FXMLLoader;
|
||||||
|
import javafx.geometry.Rectangle2D;
|
||||||
import javafx.scene.Scene;
|
import javafx.scene.Scene;
|
||||||
import javafx.scene.control.Button;
|
import javafx.scene.control.Button;
|
||||||
import javafx.scene.control.CheckBox;
|
import javafx.scene.control.CheckBox;
|
||||||
@@ -18,9 +23,12 @@ import javafx.scene.control.Label;
|
|||||||
import javafx.scene.control.TextArea;
|
import javafx.scene.control.TextArea;
|
||||||
import javafx.scene.control.ToolBar;
|
import javafx.scene.control.ToolBar;
|
||||||
import javafx.scene.layout.BorderPane;
|
import javafx.scene.layout.BorderPane;
|
||||||
|
import javafx.scene.layout.VBox;
|
||||||
import javafx.stage.Stage;
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
/** Keeps layout data in application memory and restores fresh content before showing another workspace. */
|
/** 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 restore = new Button("Restore saved layout");
|
||||||
Button incompatible = new Button("Try incompatible version");
|
Button incompatible = new Button("Try incompatible version");
|
||||||
Button failed = new Button("Simulate load failure");
|
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");
|
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));
|
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())));
|
DOCUMENTS.forEach(document -> manager.open(content(document), DockTarget.area(document.area())));
|
||||||
saved = manager.snapshot();
|
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 -> {
|
capture.setOnAction(event -> {
|
||||||
saved = manager.snapshot();
|
saved = manager.snapshot();
|
||||||
|
updateFloatingActions.run();
|
||||||
status.setText("Captured layout in application memory; document text remains outside the snapshot.");
|
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,
|
incompatible.setOnAction(event -> restoreWindow(new LayoutSnapshot(saved.version() + 1,
|
||||||
saved.windows(), saved.activeDockableId(), saved.returnPositions(), saved.initialIntents()), false, false, status));
|
saved.windows(), saved.activeDockableId(), saved.returnPositions(), saved.initialIntents()), RestoreScenario.NORMAL, false, status));
|
||||||
failed.setOnAction(event -> restoreWindow(saved, true, cleanupFailure.isSelected(), 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.setTitle("NeitzelLib — application-owned layout snapshots");
|
||||||
stage.show();
|
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();
|
Stage target = new Stage();
|
||||||
try {
|
try {
|
||||||
DockPane pane = loadPane();
|
DockPane pane = loadPane();
|
||||||
@@ -67,15 +111,21 @@ public final class SnapshotDockingApp extends Application {
|
|||||||
status.setId("snapshotStatus");
|
status.setId("snapshotStatus");
|
||||||
status.setWrapText(true);
|
status.setWrapText(true);
|
||||||
target.setScene(new Scene(new BorderPane(pane, null, null, status, null), 1000, 650));
|
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 prepared = new AtomicInteger();
|
||||||
AtomicInteger discarded = new AtomicInteger();
|
AtomicInteger discarded = new AtomicInteger();
|
||||||
RestoreResult result = manager.restore(snapshot, id -> {
|
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"));
|
return new DockableResolution.Failed(new IllegalStateException("Demo document source is unavailable"));
|
||||||
}
|
}
|
||||||
Document document = DOCUMENTS.stream().filter(candidate -> candidate.id().equals(id.value())).findFirst().orElseThrow();
|
Document document = DOCUMENTS.stream().filter(candidate -> candidate.id().equals(id.value())).findFirst().orElseThrow();
|
||||||
Dockable content = content(document);
|
Dockable content = content(document);
|
||||||
|
if (scenario == RestoreScenario.PARTIAL_FLOATING && id.value().equals("project")) content.setMainWindowOnly(true);
|
||||||
prepared.incrementAndGet();
|
prepared.incrementAndGet();
|
||||||
content.setOnDiscarded(() -> {
|
content.setOnDiscarded(() -> {
|
||||||
discarded.incrementAndGet();
|
discarded.incrementAndGet();
|
||||||
@@ -85,16 +135,34 @@ public final class SnapshotDockingApp extends Application {
|
|||||||
});
|
});
|
||||||
String message = switch (result) {
|
String message = switch (result) {
|
||||||
case RestoreResult.Applied applied -> "Restored before showing this window; prepared " + prepared.get()
|
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()
|
case RestoreResult.Rejected rejected -> "Fallback layout retained: " + rejected.failure().code()
|
||||||
|
+ (rejected.failure().dockableId() == null ? "" : " (" + rejected.failure().dockableId().value() + ")")
|
||||||
+ "; prepared " + prepared.get() + ", discarded " + discarded.get()
|
+ "; prepared " + prepared.get() + ", discarded " + discarded.get()
|
||||||
+ ", cleanup diagnostics " + rejected.cleanupFailures().size() + "."
|
+ ", cleanup diagnostics " + rejected.cleanupFailures().size() + "."
|
||||||
|
+ " " + manager.describeFailure(rejected.failure())
|
||||||
+ (rejected.failure().cause() == null ? "" : " " + rejected.failure().cause().getMessage());
|
+ (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);
|
status.setText(message);
|
||||||
sourceStatus.setText(message);
|
sourceStatus.setText(message);
|
||||||
target.setTitle(result instanceof RestoreResult.Applied ? "Restored snapshot" : "Unchanged fallback layout");
|
|
||||||
target.show();
|
|
||||||
} catch (java.io.IOException failure) {
|
} catch (java.io.IOException failure) {
|
||||||
target.hide();
|
target.hide();
|
||||||
sourceStatus.setText("Cannot load the workspace FXML: " + failure.getMessage());
|
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"));
|
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) {
|
private static Dockable content(Document document) {
|
||||||
Dockable content = new Dockable(new DockableId(document.id()), new TextArea(document.text()));
|
Dockable content = new Dockable(new DockableId(document.id()), new TextArea(document.text()));
|
||||||
content.setTitle(document.title());
|
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 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>
|
</center>
|
||||||
<right>
|
<right>
|
||||||
<DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true"
|
<DockGroupDefinition destinationId="tools" tabSide="RIGHT" collapsible="true"
|
||||||
mode="OVERLAY" preferredWidth="240"/>
|
mode="OVERLAY" preferredWidth="240" visibleWhenEmpty="false" releaseSpaceWhenEmpty="true"/>
|
||||||
</right>
|
</right>
|
||||||
</DockLayout>
|
</DockLayout>
|
||||||
</initialLayout>
|
</initialLayout>
|
||||||
|
|||||||
+201
@@ -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; }
|
||||||
|
}
|
||||||
+137
@@ -21,6 +21,7 @@ import javafx.scene.control.TabPane;
|
|||||||
import javafx.scene.control.TextArea;
|
import javafx.scene.control.TextArea;
|
||||||
import javafx.stage.Stage;
|
import javafx.stage.Stage;
|
||||||
import javafx.stage.Window;
|
import javafx.stage.Window;
|
||||||
|
import javafx.stage.Screen;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.util.List;
|
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();
|
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) {
|
private static Button button(Parent root, String label) {
|
||||||
return root.lookupAll(".button").stream().filter(Button.class::isInstance).map(Button.class::cast)
|
return root.lookupAll(".button").stream().filter(Button.class::isInstance).map(Button.class::cast)
|
||||||
.filter(button -> button.getText().equals(label)).findFirst().orElseThrow();
|
.filter(button -> button.getText().equals(label)).findFirst().orElseThrow();
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
- [Layout snapshots and empty-workspace restore](docs/docking-snapshots.md), with application-owned storage and loading.
|
- [Layout snapshots and empty-workspace restore](docs/docking-snapshots.md), with application-owned storage and loading.
|
||||||
- [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.
|
||||||
- [Dependency injection](../injection/README.md).
|
- [Dependency injection](../injection/README.md).
|
||||||
|
|
||||||
## Introduction
|
## Introduction
|
||||||
|
|||||||
+3
-2
@@ -95,5 +95,6 @@ Append `fxml` to the launch command for the FXML screen. The classpath separator
|
|||||||
shown is for macOS/Linux; use `;` on Windows. A graphical desktop session is
|
shown is for macOS/Linux; use `;` on Windows. A graphical desktop session is
|
||||||
required. The launch class is ordinary Java and delegates to the Application.
|
required. The launch class is ordinary Java and delegates to the Application.
|
||||||
|
|
||||||
Dockable-owned bars and optional MVVM bindings are a later integration step;
|
The [MVVM docking editor](../../fx-example/docs/docking-mvvm.md) demonstrates
|
||||||
the standalone controls already support ordinary JavaFX property bindings.
|
Dockable-owned bars and optional MVVM bindings alongside a plain JavaFX editor.
|
||||||
|
The standalone controls also support ordinary JavaFX property bindings.
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# Accessible names and translated docking actions
|
||||||
|
|
||||||
|
A Dockable with a visible title uses that title as its accessible tab name.
|
||||||
|
For an icon-only tab, supply an application name:
|
||||||
|
|
||||||
|
```java
|
||||||
|
Dockable project = new Dockable(new DockableId("project"), projectView);
|
||||||
|
project.setIcon(projectIcon);
|
||||||
|
project.setAccessibleName("Project files");
|
||||||
|
```
|
||||||
|
|
||||||
|
`accessibleNameProperty()` is bindable. It names an icon-only tab, whose title
|
||||||
|
is empty or blank; it does not replace the spoken name of a visibly titled tab.
|
||||||
|
The application title and original icon remain unchanged when the tab moves or
|
||||||
|
floats. JavaFX exposes the accessible name as the header's text attribute while
|
||||||
|
the default stylesheet displays only its graphic. An application supplying an
|
||||||
|
icon-only tab must supply a meaningful name; an unnamed icon has no useful
|
||||||
|
spoken label.
|
||||||
|
|
||||||
|
## Translations and placement failures
|
||||||
|
|
||||||
|
Set `DockingOptions.resourceBundle` before attaching the manager. Its String
|
||||||
|
entries are captured at attachment, so replacing the options bundle afterward
|
||||||
|
does not alter an existing manager. Unspecified built-in keys use the library's
|
||||||
|
English defaults. The tab header's close button also uses `dock.action.close`
|
||||||
|
as its accessible action name, including after a transfer into a floating window.
|
||||||
|
Action keys include `dock.action.move`, `split`, `close`,
|
||||||
|
`float`, `return`, and `pin` with the same `dock.action.` prefix. Direction keys
|
||||||
|
are `dock.side.TOP`, `RIGHT`, `BOTTOM`, and `LEFT` with `dock.side.` as the prefix.
|
||||||
|
|
||||||
|
Placement rules can attach an application message key without losing technical
|
||||||
|
diagnostics:
|
||||||
|
|
||||||
|
```java
|
||||||
|
DockFailure failure = new DockFailure(DockFailure.Code.PLACEMENT_REJECTED,
|
||||||
|
dockableId, "Workspace policy prohibits this destination", cause,
|
||||||
|
"workspace.destination.locked");
|
||||||
|
String visibleText = manager.describeFailure(failure);
|
||||||
|
```
|
||||||
|
|
||||||
|
The built-in context menus use the same `describeFailure` method as application
|
||||||
|
commands. An available application key wins. A missing application key falls
|
||||||
|
back to the failure code's default text (`dock.failure.` followed by the enum
|
||||||
|
name), not the technical diagnostic string. Code, key, diagnostic message and
|
||||||
|
cause remain available unchanged on the failure. Existing failures without a
|
||||||
|
key retain their supplied message unless the bundle overrides the code text.
|
||||||
|
|
||||||
|
`dock.action.unavailable` and `dock.action.noChange` are MessageFormat patterns.
|
||||||
|
The former accepts the action name and reason; the latter accepts the action
|
||||||
|
name. Keep those placeholders in translations.
|
||||||
|
|
||||||
|
## Application styles
|
||||||
|
|
||||||
|
A DockPane installs the library's scoped `docking.css` before existing Scene
|
||||||
|
stylesheets. Add your application theme to the Scene as usual. Configure a
|
||||||
|
floating window's stylesheets through `floatingWindowCustomizer` when the same
|
||||||
|
theme should apply there. The floating drag-preview popup inherits its owner's
|
||||||
|
Scene styles; it does not open a separate unthemed application window.
|
||||||
|
|
||||||
|
The tab-header hook is `.dock-tab-header`. An icon-only header additionally has
|
||||||
|
`.dock-icon-only`; keep its graphic-only content display if the visible header
|
||||||
|
should remain an icon. `.dock-drop-indicator` styles the in-window preview;
|
||||||
|
its `:no-change` pseudo-class identifies a drop which retains the placement.
|
||||||
|
The outside-window preview uses `.dock-floating-preview-frame` for fill/stroke
|
||||||
|
and `.dock-floating-preview-label` for the action label.
|
||||||
|
|
||||||
|
```css
|
||||||
|
.dock-tab-header { -fx-background-color: #dce8f1; }
|
||||||
|
.dock-drop-indicator { -fx-fill: rgba(30, 100, 180, 0.2); -fx-stroke: #1e64b4; }
|
||||||
|
.dock-floating-preview-frame { -fx-fill: rgba(30, 100, 180, 0.2); -fx-stroke: #1e64b4; }
|
||||||
|
```
|
||||||
|
|
||||||
|
The application retains control over color contrast and focus visibility when
|
||||||
|
replacing JavaFX's control styles.
|
||||||
|
|
||||||
|
`.dock-divider` styles split dividers from their first layout, and
|
||||||
|
`.dock-area-divider` styles the draggable boundary of an outer area.
|
||||||
|
`.dock-edge-area` is the outer area container. `.dock-group` is its TabPane;
|
||||||
|
`.dock-group:collapsed` identifies a closed rail. `.dock-group-surface` is the
|
||||||
|
space reserved for a group, and `.dock-overlay-layer` contains overlay groups.
|
||||||
|
These hooks are available in both main and floating DockPanes. Default divider
|
||||||
|
colors use JavaFX's looked-up theme colors, so replacing the application's base
|
||||||
|
palette also affects them.
|
||||||
|
|
||||||
|
## Keyboard commands
|
||||||
|
|
||||||
|
Focus the group's TabPane or one of its tab headers, then press **Shift+F10**
|
||||||
|
or the keyboard's **Context Menu** key. Arrow keys select actions and navigate
|
||||||
|
Move/Split submenus; Enter executes the highlighted enabled action. Move,
|
||||||
|
Split, Float, Return, Pin and Close use the manager's normal placement rules and
|
||||||
|
close consent. A successful transfer restores the content focus and keeps its
|
||||||
|
selection. Pinning and a vetoed Close return focus to the surviving content.
|
||||||
|
If the user activates another Dockable while asynchronous consent is pending,
|
||||||
|
a later veto preserves that newer focus choice.
|
||||||
|
An editor's own keyboard context menu remains the editor's responsibility.
|
||||||
|
|
||||||
|
## Runnable exercise
|
||||||
|
|
||||||
|
Launch `de.neitzel.fx.example.docking.KeyboardThemeDockingMain` from `fx-example`.
|
||||||
|
It provides a shared application theme, a named icon-only Project tab and
|
||||||
|
German docking action labels. **Focus active tab strip** places focus at the
|
||||||
|
keyboard entry point; then use Shift+F10, arrows and Enter.
|
||||||
|
|
||||||
|
- Float Notes and immediately type over the selected `cd` in `abcdef`.
|
||||||
|
Return it through the same menu and continue typing at its caret.
|
||||||
|
- Toggle **Block floating**. Compare **Check Float** with the disabled Float
|
||||||
|
menu item. Toggle **Missing translation key** to see the failure-code fallback.
|
||||||
|
- Close Notes with **Allow Notes to close** unchecked to exercise a veto, then
|
||||||
|
enable it and repeat to close the tab.
|
||||||
|
- Use the Project menu to pin/unpin its whole group. Its main-window-only flag
|
||||||
|
keeps Float unavailable. Drag another tab to inspect the themed preview and
|
||||||
|
split/outer dividers in both window types.
|
||||||
|
|
||||||
|
The native keyboard qualification uses the public `javafx.scene.robot.Robot`
|
||||||
|
for the real Shift+F10 chord and `java.awt.Robot` for arrow navigation, Enter
|
||||||
|
and typing. It selects actions
|
||||||
|
by their focused accessible names, then types `1` and `2` without repairing
|
||||||
|
content focus: `abcdef` with
|
||||||
|
`cd` selected becomes `ab1ef`, then `ab12ef`. Qualification on **2026-11-16**
|
||||||
|
used **macOS 27.2, Java 25 (25.0.5.0.3), and JavaFX 27.0.1**. The menu closes
|
||||||
|
before its workflow transfers focus, so a
|
||||||
|
later popup auto-hide cannot restore focus to a retired floating owner.
|
||||||
|
|
||||||
|
`NativeKeyboardDockingTest` permanently uses `@RepeatedTest(3)`: all three
|
||||||
|
independent executions must pass. Run this opt-in test from the NeitzelLib root
|
||||||
|
only with an exclusive desktop; other JavaFX tests or
|
||||||
|
manual app switching can take native focus:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./mvnw -pl fx -am -DskipVersions=true -Dversions.skip=true \
|
||||||
|
-Dtest=NativeKeyboardDockingTest \
|
||||||
|
-Dneitzellib.nativeKeyboardTest=true \
|
||||||
|
-Dsurefire.failIfNoSpecifiedTests=false test
|
||||||
|
```
|
||||||
|
|
||||||
|
`KeyboardDockActionsTest`, `AccessibleDockTabsTest`, `DockingLocalizationTest`
|
||||||
|
and `DockingThemeTest` exercise the public controls/API without native input.
|
||||||
|
The accessible-attribute checks verify JavaFX's exposed names, not a complete
|
||||||
|
screen-reader audit on every operating system.
|
||||||
|
|
||||||
|
During qualification, AWT sometimes delivered F10 without the held Shift flag
|
||||||
|
on this macOS/JDK combination; the public JavaFX event trace exposed that
|
||||||
|
missing modifier before the framework handled it. The test uses the public
|
||||||
|
[JavaFX Robot](https://openjfx.io/javadoc/27/javafx.graphics/javafx/scene/robot/Robot.html)
|
||||||
|
for the chord. Its [macOS backend](https://raw.githubusercontent.com/openjdk/jfx/jfx27/modules/javafx.graphics/src/main/native-glass/mac/GlassRobot.m)
|
||||||
|
posts native accessibility keyboard events, whereas the
|
||||||
|
[JDK 25 AWT backend](https://raw.githubusercontent.com/openjdk/jdk/jdk-25-ga/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobot.m)
|
||||||
|
creates CoreGraphics keyboard events from HID source state. This changes only
|
||||||
|
the test driver; the framework still requires an actual Shift+F10 event. Three
|
||||||
|
independent repetitions must each complete both transfers and exact text
|
||||||
|
assertions. They are not retries after a failure.
|
||||||
@@ -25,8 +25,9 @@ The `CloseDockingMain` launcher in the example module shows a pending close
|
|||||||
without a nested event loop. Choose Close Notes, then Keep open and continue
|
without a nested event loop. Choose Close Notes, then Keep open and continue
|
||||||
editing. Request close again and choose Allow close. Until that decision, Notes
|
editing. Request close again and choose Allow close. Until that decision, Notes
|
||||||
remains open; after approval its resource callback runs. The same demonstration
|
remains open; after approval its resource callback runs. The same demonstration
|
||||||
works through the tab's close control. Main-window shutdown is added by the
|
works through the tab's close control. This example demonstrates individual tab
|
||||||
later lifecycle slices; this example demonstrates individual tab consent.
|
consent; [main-window shutdown](docking-shutdown.md) adds complete-workspace
|
||||||
|
consent, pre-close saving and manager replacement.
|
||||||
|
|
||||||
## Closing a floating window
|
## Closing a floating window
|
||||||
|
|
||||||
@@ -48,8 +49,9 @@ layout is published once. Then every `onClosed` callback runs, even if an earlie
|
|||||||
cleanup fails. `Closed.cleanupFailures()` reports those failures. The scope stays
|
cleanup fails. `Closed.cleanupFailures()` reports those failures. The scope stays
|
||||||
observable until cleanup finishes. Unknown/already closed floating IDs return
|
observable until cleanup finishes. Unknown/already closed floating IDs return
|
||||||
`NoChange`; the main-window ID is rejected by this floating-only entry point.
|
`NoChange`; the main-window ID is rejected by this floating-only entry point.
|
||||||
Main-window and manager shutdown, including the shutdown snapshot callback,
|
Main-window and manager shutdown use the same consent and cleanup guarantees;
|
||||||
belong to the later shutdown slices.
|
the [shutdown guide](docking-shutdown.md) describes their snapshot callback and
|
||||||
|
ownership modes.
|
||||||
|
|
||||||
The example launcher is
|
The example launcher is
|
||||||
`de.neitzel.fx.example.docking.FloatingCloseDockingMain`. It creates First and
|
`de.neitzel.fx.example.docking.FloatingCloseDockingMain`. It creates First and
|
||||||
@@ -68,4 +70,5 @@ are in-memory demonstration snapshots in the log, not filesystem writes.
|
|||||||
The floating window's native close control follows the same sequence.
|
The floating window's native close control follows the same sequence.
|
||||||
|
|
||||||
The demo's main Stage is only a control panel; closing it hides its demonstration
|
The demo's main Stage is only a control panel; closing it hides its demonstration
|
||||||
windows. This is separate from the future application-wide shutdown protocol.
|
windows. For an application-wide Quit command, use the
|
||||||
|
[shutdown workflow](docking-shutdown.md).
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# Quit, save and replace a docking workspace
|
||||||
|
|
||||||
|
`requestMainWindowClose()` asks every Dockable in the manager, including contents
|
||||||
|
in floating windows and collapsed groups. Every close check runs even if an
|
||||||
|
earlier one vetoes. Nothing closes until all checks allow the operation. A veto
|
||||||
|
returns `CloseResult.Vetoed` and skips the shutdown-save callback.
|
||||||
|
|
||||||
|
Configure `DockingOptions.beforeShutdown` before attaching the manager. After
|
||||||
|
unanimous consent, the callback receives a `ShutdownRequest` with the complete
|
||||||
|
immutable pre-close `LayoutSnapshot` and a `ShutdownReason`: `MAIN_WINDOW` or
|
||||||
|
`MANAGER_ONLY`. Application document saving still belongs to the application and
|
||||||
|
its close checks; the snapshot contains arrangement data, not editor text.
|
||||||
|
|
||||||
|
```java
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setBeforeShutdown(request -> saveLayoutWithRetry(request.snapshot()));
|
||||||
|
DockingManager manager = DockingManager.attach(stage, pane, options);
|
||||||
|
```
|
||||||
|
|
||||||
|
Here `saveLayoutWithRetry` is an application function returning a
|
||||||
|
`CompletionStage<ShutdownDecision>`. Keep that stage pending while saving or
|
||||||
|
retrying. The manager leaves all contents and windows open and holds the close
|
||||||
|
scope throughout that wait. Complete with `PROCEED` after a successful save, or
|
||||||
|
`CANCEL` to keep the workspace open. Throwing from the callback or completing its
|
||||||
|
stage exceptionally returns `Rejected` with `SHUTDOWN_CALLBACK_FAILED` and the
|
||||||
|
original cause; it does not close contents. The callback runs on the JavaFX
|
||||||
|
thread, and the returned stage may complete on a worker thread.
|
||||||
|
|
||||||
|
After `PROCEED`, the manager detaches contents and calls every `onClosed` callback.
|
||||||
|
Cleanup failures are reported in `Closed.cleanupFailures()` and do not turn an
|
||||||
|
already completed close into a rollback. The close scope remains active through
|
||||||
|
resource cleanup.
|
||||||
|
|
||||||
|
## Main-window ownership
|
||||||
|
|
||||||
|
The default `MainWindowCloseMode.AUTOMATIC` connects the Stage's close control to
|
||||||
|
the manager and hides the main Stage only after a successful main-window close.
|
||||||
|
Route an application's Quit command through `requestMainWindowClose()` as well.
|
||||||
|
|
||||||
|
With `APPLICATION_COORDINATED`, the application owns its close-request handler
|
||||||
|
and decides when to hide the main Stage after `Closed`. Consume the close event
|
||||||
|
while consent and saving are pending:
|
||||||
|
|
||||||
|
```java
|
||||||
|
stage.setOnCloseRequest(event -> {
|
||||||
|
event.consume();
|
||||||
|
manager.requestMainWindowClose().thenAccept(result -> {
|
||||||
|
if (result instanceof CloseResult.Closed) stage.hide();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Choose the mode before `attach`; changing the original options afterward does
|
||||||
|
not change the attached manager.
|
||||||
|
|
||||||
|
## Replacing the embedded workspace
|
||||||
|
|
||||||
|
`requestManagerClose()` uses the same checks and save workflow with reason
|
||||||
|
`MANAGER_ONLY`. On success it closes Dockables and floating windows, removes the
|
||||||
|
manager's handlers and releases the pane and Stage for another attachment. The
|
||||||
|
main Stage stays open. A veto, cancellation or failed save leaves the current
|
||||||
|
manager usable.
|
||||||
|
|
||||||
|
```java
|
||||||
|
manager.requestManagerClose().thenAccept(result -> {
|
||||||
|
if (result instanceof CloseResult.Closed) {
|
||||||
|
DockingManager replacement = DockingManager.attach(stage, pane, nextOptions);
|
||||||
|
openNewWorkspaceContents(replacement);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
The replacement application creates or loads new contents. Use
|
||||||
|
[`resetLayout()`](../../fx-example/docs/docking-reset.md) when the intention is to
|
||||||
|
rearrange existing editors while retaining their Nodes and unsaved text.
|
||||||
|
|
||||||
|
## Quit during an existing floating-window close
|
||||||
|
|
||||||
|
A main-window request waits behind an already running floating-window close.
|
||||||
|
If the floating close succeeds, Quit asks only the remaining Dockables and then
|
||||||
|
captures their full pre-close snapshot. If it vetoes or fails, the waiting Quit
|
||||||
|
adopts that result without starting new checks or saving. A later explicit Quit
|
||||||
|
starts fresh checks. Repeated requests for the same running workflow share its
|
||||||
|
answer rather than invoking another application prompt.
|
||||||
|
|
||||||
|
The example makes this sequence visible:
|
||||||
|
|
||||||
|
1. Select **Delay Preview window consent** and click **Close Preview window**.
|
||||||
|
Preview stays open while its one consent answer is pending.
|
||||||
|
2. Click **Quit workspace**. The status shows that Quit is waiting; Notes and
|
||||||
|
Project have not been asked and no snapshot has been saved.
|
||||||
|
3. **Allow Preview** closes that independently approved window, then Quit asks
|
||||||
|
Notes and Project and waits at the normal save controls. The snapshot now
|
||||||
|
contains their one remaining main window.
|
||||||
|
4. Alternatively, **Veto Preview** leaves all three contents open and ends the
|
||||||
|
waiting Quit with the same veto. Clicking **Quit workspace** again performs
|
||||||
|
fresh checks and reaches the two-window save workflow.
|
||||||
|
|
||||||
|
The asynchronous consent controls remain usable while Quit waits. The public
|
||||||
|
scope property continues to describe the running floating close until the queue
|
||||||
|
can advance; a pending global save then owns the manager-wide scope.
|
||||||
|
|
||||||
|
## Runnable Quit/Replace example
|
||||||
|
|
||||||
|
`ShutdownDockingMain` loads `ShutdownDocking.fxml`: Notes occupies the center,
|
||||||
|
Project starts collapsed on the left, and Preview is floating. The example uses
|
||||||
|
ordinary JavaFX without MVVM.
|
||||||
|
|
||||||
|
1. Select **Preview vetoes last**, then **Replace workspace**. The log shows all
|
||||||
|
three checks, no snapshot callback and no released contents.
|
||||||
|
2. Clear the veto and request **Quit workspace** or **Replace workspace**. The
|
||||||
|
application displays the pre-close reason and the two-window snapshot.
|
||||||
|
3. **Retry save** fails while **Simulate save failure** is selected. The same
|
||||||
|
pending request retains every editor. Clear that checkbox and retry, or use
|
||||||
|
**Save successfully**, to complete with `PROCEED`.
|
||||||
|
4. **Cancel shutdown**, **Fail asynchronously** and **Throw before saving** show
|
||||||
|
the distinct canceled and rejected paths without losing the current editors.
|
||||||
|
5. **Replace workspace** followed by successful saving attaches fresh contents
|
||||||
|
to the same DockPane. **Next workspace** selects the ownership mode captured
|
||||||
|
by that new attachment. In application-owned mode, a successful Quit leaves
|
||||||
|
**Close application window** available for the caller's final action.
|
||||||
|
|
||||||
|
The example stores the saved snapshot in application-owned memory and deliberately
|
||||||
|
simulates failures; it performs no disk I/O. Connect the same callback to your
|
||||||
|
storage implementation for a real application.
|
||||||
|
|
||||||
|
After building local artifacts, launch from the NeitzelLib root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -cp 'fx-example/target/classes:fx-example/target/libs/*' \
|
||||||
|
de.neitzel.fx.example.docking.ShutdownDockingMain
|
||||||
|
```
|
||||||
|
|
||||||
|
The public workflow tests exercise consent and save ordering, pending saves,
|
||||||
|
both ownership modes, cleanup, captured options and reattachment. Four example
|
||||||
|
integration cases drive the actual Java/FXML controls through veto, retry,
|
||||||
|
cancellation, failures, replacement, both main-close ownership modes and queued
|
||||||
|
Quit after delayed floating consent. The queue cases use ordinary JavaFX turns
|
||||||
|
to verify callback counts, retained editor identity and fresh checks after a
|
||||||
|
veto. All four example scenarios pass without failures, errors or skips.
|
||||||
@@ -50,10 +50,27 @@ adopts it. Contents belonging to this or another live manager receive neither
|
|||||||
`onDiscarded` nor `onClosed` on that rejection. Fresh, unused prepared contents
|
`onDiscarded` nor `onClosed` on that rejection. Fresh, unused prepared contents
|
||||||
remain subject to the discard contract.
|
remain subject to the discard contract.
|
||||||
|
|
||||||
This milestone restores snapshots containing the main window. Floating-window
|
Restore includes the main window and floating hosts with their saved return
|
||||||
data is captured, but restoring floating hosts currently returns
|
destinations. The same window customizer configures new and restored hosts.
|
||||||
`UNSUPPORTED_SNAPSHOT_FEATURE` before invoking the resolver; ticket 14 adds that
|
Prepared floating windows remain hidden until the main Stage is shown; failed
|
||||||
capability. Partial restoration for missing IDs is supplied by ticket 13.
|
preparation never shows them. Customizers and placement checks finish before the
|
||||||
|
layout is installed.
|
||||||
|
Floating bounds outside the available displays are fitted to a current screen,
|
||||||
|
preserving the saved size as far as it fits. Return uses the saved main-window
|
||||||
|
destination, including persistent groups hidden while empty.
|
||||||
|
|
||||||
|
`DockableResolution.Missing` skips that identity and reports it in
|
||||||
|
`RestoreResult.Applied.missingIds()`. Empty split branches dissolve while stable
|
||||||
|
area aliases remain available; configured persistent empty side groups survive.
|
||||||
|
Available contents are checked against the application's current placement rule.
|
||||||
|
If a saved destination is rejected, restore tries the explicitly configured
|
||||||
|
`DockingOptions.fallbackTarget`, such as `DockTarget.area("primary")`. It does not
|
||||||
|
silently choose an arbitrary group. If any available content has no eligible
|
||||||
|
destination, the entire restore is rejected with that ID and all freshly prepared
|
||||||
|
contents are discarded; the live fallback layout remains unchanged.
|
||||||
|
An available Dockable that has become `mainWindowOnly` uses an explicitly
|
||||||
|
configured main-window fallback. Floating hosts emptied by Missing or fallback
|
||||||
|
are omitted entirely, including their customizer calls.
|
||||||
Use [live reset](../../fx-example/docs/docking-reset.md) to rearrange already open
|
Use [live reset](../../fx-example/docs/docking-reset.md) to rearrange already open
|
||||||
contents without replacing their Nodes or losing their unsaved state.
|
contents without replacing their Nodes or losing their unsaved state.
|
||||||
|
|
||||||
@@ -82,6 +99,37 @@ java --enable-native-access=ALL-UNNAMED \
|
|||||||
prepared and discarded content counts, and separate cleanup diagnostics.
|
prepared and discarded content counts, and separate cleanup diagnostics.
|
||||||
5. Enable **Simulate cleanup failure** and repeat the failed load to see cleanup
|
5. Enable **Simulate cleanup failure** and repeat the failed load to see cleanup
|
||||||
diagnostics alongside the unchanged primary failure.
|
diagnostics alongside the unchanged primary failure.
|
||||||
|
6. Choose **Restore without Preview/Project**. The status names both missing IDs;
|
||||||
|
the nested Preview split dissolves and the persistent empty Project side target
|
||||||
|
remains. The original workspace and its unsaved text remain open.
|
||||||
|
7. Choose **Restore with changed rule**. In the supplied starting arrangement,
|
||||||
|
Project is no longer permitted in the tools group and joins Notes in the
|
||||||
|
configured editor fallback, `primary`. The status names that fallback.
|
||||||
|
8. Choose **Reject Project placement**. Project is rejected at both its saved
|
||||||
|
destination and the fallback. The new window retains its empty starting layout;
|
||||||
|
the status identifies Project and reports all four freshly prepared contents
|
||||||
|
discarded. The original workspace remains untouched.
|
||||||
|
9. Choose **Prepare floating snapshot**. Preview and Project become two floating
|
||||||
|
windows; Project's persistent side target hides while empty. The captured
|
||||||
|
snapshot includes their return destinations.
|
||||||
|
10. Choose **Restore saved layout**. A fresh main window and two floating hosts
|
||||||
|
appear. The status reports zero floating windows visible before main-window
|
||||||
|
display and two afterward. Source and restored hosts use the same custom title.
|
||||||
|
11. Choose **Restore off-screen windows**. This changes only the saved floating
|
||||||
|
positions to simulate unavailable monitors. The new hosts fit the available
|
||||||
|
displays. In the new main window, **Return Project** brings the same content
|
||||||
|
back to its preserved target and removes its empty floating host.
|
||||||
|
12. Choose **Restore partial floating**. Preview is missing; Project now requires
|
||||||
|
the main window and uses the configured editor fallback. Only the new main
|
||||||
|
window appears, with three contents. No empty floating hosts are created.
|
||||||
|
13. Choose **Abort floating customizer**. The second floating-window customizer
|
||||||
|
throws. Neither prepared floating host appears, the new main window retains
|
||||||
|
its empty fallback, and all four prepared contents are discarded.
|
||||||
|
|
||||||
|
The display and startup checks run against actual JavaFX windows on the current
|
||||||
|
macOS desktop. Off-screen saved bounds simulate monitor changes; physically
|
||||||
|
disconnecting monitors and Windows/Linux desktop startup have not been qualified
|
||||||
|
by these example tests.
|
||||||
|
|
||||||
The example's **Capture layout** command saves layout data only. Reloaded document
|
The example's **Capture layout** command saves layout data only. Reloaded document
|
||||||
text comes from its application source; document persistence is a separate concern.
|
text comes from its application source; document persistence is a separate concern.
|
||||||
|
|||||||
+5
-2
@@ -41,8 +41,11 @@ The content instance remains owned by the application. A supplied
|
|||||||
the previously focused descendant. See [split groups](docking-splits.md) for
|
the previously focused descendant. See [split groups](docking-splits.md) for
|
||||||
nested layouts and resizing, [group presentation](docking-groups.md) for collapse
|
nested layouts and resizing, [group presentation](docking-groups.md) for collapse
|
||||||
and atomic configuration, [overlay groups](docking-overlays.md) for pinning,
|
and atomic configuration, [overlay groups](docking-overlays.md) for pinning,
|
||||||
and [close consent](docking-close.md) for
|
and [close consent](docking-close.md) for asynchronous close checks.
|
||||||
asynchronous close checks. Restoration is supplied by a later slice.
|
[Snapshot restoration](docking-snapshots.md) prepares fresh contents for an empty
|
||||||
|
manager; [live reset](../../fx-example/docs/docking-reset.md) retains existing
|
||||||
|
editors. [Shutdown and replacement](docking-shutdown.md) cover saving before
|
||||||
|
Quit and attaching a new manager to the same host.
|
||||||
|
|
||||||
## Move and check placement
|
## Move and check placement
|
||||||
|
|
||||||
|
|||||||
@@ -11,5 +11,5 @@ public record CloseScope(Kind kind, List<DockableId> dockableIds) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The entry point that requested consent. */
|
/** The entry point that requested consent. */
|
||||||
public enum Kind { TAB, FLOATING_WINDOW }
|
public enum Kind { TAB, FLOATING_WINDOW, MAIN_WINDOW, MANAGER_ONLY }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.BiFunction;
|
||||||
|
|
||||||
|
/** Checks a concrete or area fallback against a detached plan before changing its ID order. */
|
||||||
|
final class DockCandidatePlacement {
|
||||||
|
private DockCandidatePlacement() { }
|
||||||
|
|
||||||
|
static DockFailure place(DockLayoutCandidate candidate, Dockable dockable, DockTarget target,
|
||||||
|
BiFunction<Dockable, ResolvedDockTarget, MoveCheck> check) {
|
||||||
|
List<DockingManager.Group> destinations = switch (target) {
|
||||||
|
case null -> List.of();
|
||||||
|
case DockTarget.Area area -> candidate.groups(area.id());
|
||||||
|
case DockTarget.Group concrete -> candidate.groups().stream().filter(group -> group.id().equals(concrete.id())).toList();
|
||||||
|
default -> List.of();
|
||||||
|
};
|
||||||
|
DockFailure firstFailure = null;
|
||||||
|
for (DockingManager.Group group : destinations) {
|
||||||
|
List<DockableId> order = candidate.tabs(group.id());
|
||||||
|
int index = order.size();
|
||||||
|
if (target instanceof DockTarget.Group concrete) {
|
||||||
|
DockableId reference = switch (concrete.position()) {
|
||||||
|
case TabPosition.Before before -> before.id();
|
||||||
|
case TabPosition.After after -> after.id();
|
||||||
|
case TabPosition.Append ignored -> null;
|
||||||
|
};
|
||||||
|
if (reference != null) {
|
||||||
|
index = order.indexOf(reference);
|
||||||
|
if (index < 0) return new DockFailure(DockFailure.Code.REFERENCE_TAB_NOT_FOUND,
|
||||||
|
dockable.getId(), "Fallback reference tab is not in its destination", null);
|
||||||
|
if (concrete.position() instanceof TabPosition.After) index++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MoveCheck result = check.apply(dockable, new ResolvedDockTarget.Insertion(group.id(), index));
|
||||||
|
if (result instanceof MoveCheck.Allowed) {
|
||||||
|
candidate.place(dockable.getId(), group.id(), index);
|
||||||
|
candidate.select(group.id(), dockable.getId());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (firstFailure == null && result instanceof MoveCheck.Rejected rejected) {
|
||||||
|
firstFailure = affected(rejected.failure(), dockable.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return firstFailure == null ? new DockFailure(DockFailure.Code.TARGET_NOT_FOUND,
|
||||||
|
dockable.getId(), "No eligible destination exists", null) : firstFailure;
|
||||||
|
}
|
||||||
|
|
||||||
|
static DockFailure affected(DockFailure failure, DockableId id) {
|
||||||
|
return new DockFailure(failure.code(), id, failure.message(), failure.cause(), failure.messageKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,30 +17,45 @@ import java.util.concurrent.CompletionStage;
|
|||||||
final class DockCloseCoordinator {
|
final class DockCloseCoordinator {
|
||||||
interface Host {
|
interface Host {
|
||||||
Optional<Dockable> find(DockableId id);
|
Optional<Dockable> find(DockableId id);
|
||||||
|
List<DockableId> allDockables();
|
||||||
Optional<List<DockableId>> floatingDockables(DockWindowId id);
|
Optional<List<DockableId>> floatingDockables(DockWindowId id);
|
||||||
Window owner(DockableId id);
|
Window owner(DockableId id);
|
||||||
void remove(List<DockableId> ids);
|
void remove(List<DockableId> ids);
|
||||||
|
CompletionStage<ShutdownDecision> beforeShutdown(CloseScope.Kind kind);
|
||||||
|
void endManager(CloseScope.Kind kind);
|
||||||
}
|
}
|
||||||
|
|
||||||
private final Host host;
|
private final Host host;
|
||||||
private final ReadOnlyObjectWrapper<CloseScope> scope = new ReadOnlyObjectWrapper<>(this, "closingScope");
|
private final ReadOnlyObjectWrapper<CloseScope> scope = new ReadOnlyObjectWrapper<>(this, "closingScope");
|
||||||
private final LinkedHashMap<RequestKey, Pending> queued = new LinkedHashMap<>();
|
private final LinkedHashMap<RequestKey, Pending> queued = new LinkedHashMap<>();
|
||||||
private Running running;
|
private Running running;
|
||||||
|
private boolean ended;
|
||||||
|
|
||||||
DockCloseCoordinator(Host host) { this.host = host; }
|
DockCloseCoordinator(Host host) { this.host = host; }
|
||||||
|
|
||||||
ReadOnlyObjectProperty<CloseScope> closingScopeProperty() { return scope.getReadOnlyProperty(); }
|
ReadOnlyObjectProperty<CloseScope> closingScopeProperty() { return scope.getReadOnlyProperty(); }
|
||||||
CloseScope scope() { return scope.get(); }
|
CloseScope scope() { return scope.get(); }
|
||||||
boolean coversWindow(DockWindowId id) {
|
boolean coversWindow(DockWindowId id) {
|
||||||
return id != null && running != null && id.equals(running.pending.key.windowId);
|
return running != null && (global(running.pending.key) || id != null && id.equals(running.pending.key.windowId));
|
||||||
}
|
}
|
||||||
|
|
||||||
CompletionStage<CloseResult> requestTabClose(DockableId id) {
|
CompletionStage<CloseResult> requestTabClose(DockableId id) {
|
||||||
return request(new RequestKey(Objects.requireNonNull(id, "id"), null));
|
return request(new RequestKey(Objects.requireNonNull(id, "id"), null, CloseScope.Kind.TAB));
|
||||||
}
|
}
|
||||||
|
|
||||||
CompletionStage<CloseResult> requestFloatingWindowClose(DockWindowId id) {
|
CompletionStage<CloseResult> requestFloatingWindowClose(DockWindowId id) {
|
||||||
return request(new RequestKey(null, Objects.requireNonNull(id, "id")));
|
return request(new RequestKey(null, Objects.requireNonNull(id, "id"), CloseScope.Kind.FLOATING_WINDOW));
|
||||||
|
}
|
||||||
|
|
||||||
|
CompletionStage<CloseResult> requestShutdown(CloseScope.Kind kind) {
|
||||||
|
if (kind != CloseScope.Kind.MAIN_WINDOW && kind != CloseScope.Kind.MANAGER_ONLY) {
|
||||||
|
throw new IllegalArgumentException("Shutdown requires a manager-wide scope");
|
||||||
|
}
|
||||||
|
return request(new RequestKey(null, null, kind));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean global(RequestKey key) {
|
||||||
|
return key.kind == CloseScope.Kind.MAIN_WINDOW || key.kind == CloseScope.Kind.MANAGER_ONLY;
|
||||||
}
|
}
|
||||||
|
|
||||||
private CompletionStage<CloseResult> request(RequestKey key) {
|
private CompletionStage<CloseResult> request(RequestKey key) {
|
||||||
@@ -67,21 +82,31 @@ final class DockCloseCoordinator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void begin(Pending pending) {
|
private void begin(Pending pending) {
|
||||||
|
if (ended) {
|
||||||
|
completeNoChange(pending);
|
||||||
|
return;
|
||||||
|
}
|
||||||
RequestKey key = pending.key;
|
RequestKey key = pending.key;
|
||||||
List<DockableId> ids = key.windowId == null
|
List<DockableId> ids = switch (key.kind) {
|
||||||
? host.find(key.tabId).map(ignored -> List.of(key.tabId)).orElse(List.of())
|
case TAB -> host.find(key.tabId).map(ignored -> List.of(key.tabId)).orElse(List.of());
|
||||||
: host.floatingDockables(key.windowId).orElse(List.of());
|
case FLOATING_WINDOW -> host.floatingDockables(key.windowId).orElse(List.of());
|
||||||
if (ids.isEmpty()) {
|
case MAIN_WINDOW, MANAGER_ONLY -> host.allDockables();
|
||||||
pending.completion.complete(new CloseResult.NoChange());
|
};
|
||||||
if (!queued.isEmpty()) Platform.runLater(this::nextQueued);
|
if (ids.isEmpty() && !global(key)) {
|
||||||
|
completeNoChange(pending);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Running request = new Running(pending, ids.stream().map(id -> host.find(id).orElseThrow()).toList());
|
Running request = new Running(pending, ids.stream().map(id -> host.find(id).orElseThrow()).toList());
|
||||||
running = request;
|
running = request;
|
||||||
scope.set(new CloseScope(key.windowId == null ? CloseScope.Kind.TAB : CloseScope.Kind.FLOATING_WINDOW, ids));
|
scope.set(new CloseScope(key.kind, ids));
|
||||||
askNext(request);
|
askNext(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void completeNoChange(Pending pending) {
|
||||||
|
pending.completion.complete(new CloseResult.NoChange());
|
||||||
|
if (!queued.isEmpty()) Platform.runLater(this::nextQueued);
|
||||||
|
}
|
||||||
|
|
||||||
/** Synchronous answers drain iteratively; asynchronous answers resume on the FX thread. */
|
/** Synchronous answers drain iteratively; asynchronous answers resume on the FX thread. */
|
||||||
private void askNext(Running request) {
|
private void askNext(Running request) {
|
||||||
request.checking = true;
|
request.checking = true;
|
||||||
@@ -125,6 +150,30 @@ final class DockCloseCoordinator {
|
|||||||
finish(request, new CloseResult.Vetoed(request.vetoes, request.failures));
|
finish(request, new CloseResult.Vetoed(request.vetoes, request.failures));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (global(request.pending.key)) {
|
||||||
|
request.saving = true;
|
||||||
|
try {
|
||||||
|
CompletionStage<ShutdownDecision> save = Objects.requireNonNull(
|
||||||
|
host.beforeShutdown(request.pending.key.kind), "Shutdown callback returned no stage");
|
||||||
|
save.whenComplete((decision, failure) -> onFx(() -> saved(request, decision, failure)));
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
saved(request, null, failure);
|
||||||
|
}
|
||||||
|
} else closeContents(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saved(Running request, ShutdownDecision decision, Throwable failure) {
|
||||||
|
if (running != request || !request.saving) return;
|
||||||
|
request.saving = false;
|
||||||
|
if (failure != null || decision == null) {
|
||||||
|
Throwable cause = failure == null ? new IllegalStateException("Shutdown callback returned no decision") : failure;
|
||||||
|
finish(request, new CloseResult.Rejected(new DockFailure(DockFailure.Code.SHUTDOWN_CALLBACK_FAILED,
|
||||||
|
null, "Before-shutdown callback failed", cause)));
|
||||||
|
} else if (decision == ShutdownDecision.CANCEL) finish(request, new CloseResult.Canceled());
|
||||||
|
else closeContents(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void closeContents(Running request) {
|
||||||
host.remove(request.dockables.stream().map(Dockable::getId).toList());
|
host.remove(request.dockables.stream().map(Dockable::getId).toList());
|
||||||
List<DockFailure> cleanupFailures = new ArrayList<>();
|
List<DockFailure> cleanupFailures = new ArrayList<>();
|
||||||
for (Dockable dockable : request.dockables) {
|
for (Dockable dockable : request.dockables) {
|
||||||
@@ -136,13 +185,35 @@ final class DockCloseCoordinator {
|
|||||||
dockable.getId(), "Closed Dockable resource release failed", cleanup));
|
dockable.getId(), "Closed Dockable resource release failed", cleanup));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (global(request.pending.key)) {
|
||||||
|
try {
|
||||||
|
host.endManager(request.pending.key.kind);
|
||||||
|
} catch (RuntimeException cleanup) {
|
||||||
|
cleanupFailures.add(new DockFailure(DockFailure.Code.CLEANUP_FAILED, null,
|
||||||
|
"Docking manager resource release failed", cleanup));
|
||||||
|
}
|
||||||
|
ended = true;
|
||||||
|
}
|
||||||
finish(request, new CloseResult.Closed(cleanupFailures));
|
finish(request, new CloseResult.Closed(cleanupFailures));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void finish(Running request, CloseResult result) {
|
private void finish(Running request, CloseResult result) {
|
||||||
|
List<Pending> canceledShutdowns = new ArrayList<>();
|
||||||
|
if (!(result instanceof CloseResult.Closed) && !(result instanceof CloseResult.NoChange)) {
|
||||||
|
var iterator = queued.entrySet().iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
Pending pending = iterator.next().getValue();
|
||||||
|
if (global(pending.key)) {
|
||||||
|
canceledShutdowns.add(pending);
|
||||||
|
iterator.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
running = null;
|
running = null;
|
||||||
scope.set(null);
|
scope.set(null);
|
||||||
request.pending.completion.complete(result);
|
request.pending.completion.complete(result);
|
||||||
|
// A waiting global request adopts the refusal; independent windows still advance in FIFO order.
|
||||||
|
canceledShutdowns.forEach(pending -> pending.completion.complete(result));
|
||||||
if (!queued.isEmpty()) Platform.runLater(this::nextQueued);
|
if (!queued.isEmpty()) Platform.runLater(this::nextQueued);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,7 +222,7 @@ final class DockCloseCoordinator {
|
|||||||
else Platform.runLater(action);
|
else Platform.runLater(action);
|
||||||
}
|
}
|
||||||
|
|
||||||
private record RequestKey(DockableId tabId, DockWindowId windowId) { }
|
private record RequestKey(DockableId tabId, DockWindowId windowId, CloseScope.Kind kind) { }
|
||||||
private static final class Pending {
|
private static final class Pending {
|
||||||
final RequestKey key;
|
final RequestKey key;
|
||||||
final CompletableFuture<CloseResult> completion = new CompletableFuture<>();
|
final CompletableFuture<CloseResult> completion = new CompletableFuture<>();
|
||||||
@@ -166,6 +237,7 @@ final class DockCloseCoordinator {
|
|||||||
int index;
|
int index;
|
||||||
boolean awaiting;
|
boolean awaiting;
|
||||||
boolean checking;
|
boolean checking;
|
||||||
|
boolean saving;
|
||||||
Running(Pending pending, List<Dockable> dockables) {
|
Running(Pending pending, List<Dockable> dockables) {
|
||||||
this.pending = pending;
|
this.pending = pending;
|
||||||
this.dockables = dockables;
|
this.dockables = dockables;
|
||||||
|
|||||||
@@ -72,11 +72,22 @@ final class DockDragController {
|
|||||||
Menu destinations = new Menu(manager.message("dock.action.move"));
|
Menu destinations = new Menu(manager.message("dock.action.move"));
|
||||||
Menu splits = new Menu(manager.message("dock.action.split"));
|
Menu splits = new Menu(manager.message("dock.action.split"));
|
||||||
MenuItem close = new MenuItem(manager.message("dock.action.close"));
|
MenuItem close = new MenuItem(manager.message("dock.action.close"));
|
||||||
close.setOnAction(event -> manager.requestTabClose(id));
|
close.setOnAction(event -> {
|
||||||
|
hideMenu(close);
|
||||||
|
manager.requestTabClose(id).thenAccept(result -> {
|
||||||
|
if (!(result instanceof CloseResult.Closed) && manager.activeDockable() != null
|
||||||
|
&& manager.activeDockable().getId().equals(id)) manager.restoreDragFocus(id);
|
||||||
|
});
|
||||||
|
});
|
||||||
javafx.scene.control.CheckMenuItem pin = new javafx.scene.control.CheckMenuItem(manager.message("dock.action.pin"));
|
javafx.scene.control.CheckMenuItem pin = new javafx.scene.control.CheckMenuItem(manager.message("dock.action.pin"));
|
||||||
pin.setOnAction(event -> currentGroup(id).ifPresent(group -> manager.updateGroup(group.id(),
|
pin.setOnAction(event -> {
|
||||||
DockGroupChanges.builder().mode(group.mode() == DockGroupMode.DOCKED
|
hideMenu(pin);
|
||||||
? DockGroupMode.OVERLAY : DockGroupMode.DOCKED).build())));
|
currentGroup(id).ifPresent(group -> {
|
||||||
|
manager.updateGroup(group.id(), DockGroupChanges.builder().mode(group.mode() == DockGroupMode.DOCKED
|
||||||
|
? DockGroupMode.OVERLAY : DockGroupMode.DOCKED).build());
|
||||||
|
manager.restoreDragFocus(id);
|
||||||
|
});
|
||||||
|
});
|
||||||
ContextMenu menu = new ContextMenu(destinations, splits, close,
|
ContextMenu menu = new ContextMenu(destinations, splits, close,
|
||||||
new MenuItem(manager.message("dock.action.float")), new MenuItem(manager.message("dock.action.return")), pin);
|
new MenuItem(manager.message("dock.action.float")), new MenuItem(manager.message("dock.action.return")), pin);
|
||||||
menu.setOnShowing(event -> {
|
menu.setOnShowing(event -> {
|
||||||
@@ -144,10 +155,20 @@ final class DockDragController {
|
|||||||
else if (check instanceof MoveCheck.NoChange) label = manager.message("dock.action.noChange", label);
|
else if (check instanceof MoveCheck.NoChange) label = manager.message("dock.action.noChange", label);
|
||||||
MenuItem item = new MenuItem(label);
|
MenuItem item = new MenuItem(label);
|
||||||
item.setDisable(!(check instanceof MoveCheck.Allowed));
|
item.setDisable(!(check instanceof MoveCheck.Allowed));
|
||||||
item.setOnAction(event -> manager.move(id, target));
|
item.setOnAction(event -> {
|
||||||
|
hideMenu(item);
|
||||||
|
manager.move(id, target);
|
||||||
|
});
|
||||||
return item;
|
return item;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void hideMenu(MenuItem item) {
|
||||||
|
MenuItem root = item;
|
||||||
|
while (root.getParentMenu() != null) root = root.getParentMenu();
|
||||||
|
// Close the popup before a workflow transfers focus or retires its owner window.
|
||||||
|
if (root.getParentPopup() != null) root.getParentPopup().hide();
|
||||||
|
}
|
||||||
|
|
||||||
void dispose() {
|
void dispose() {
|
||||||
pane.removeEventFilter(MouseEvent.ANY, mouseHandler);
|
pane.removeEventFilter(MouseEvent.ANY, mouseHandler);
|
||||||
scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler);
|
scene.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler);
|
||||||
@@ -415,9 +436,32 @@ final class DockDragController {
|
|||||||
cancel();
|
cancel();
|
||||||
manager.restoreDragFocus(id);
|
manager.restoreDragFocus(id);
|
||||||
event.consume();
|
event.consume();
|
||||||
|
} else if (pressed == null && !event.isControlDown() && !event.isAltDown() && !event.isMetaDown()
|
||||||
|
&& (event.getCode() == KeyCode.CONTEXT_MENU
|
||||||
|
|| event.getCode() == KeyCode.F10 && event.isShiftDown())) {
|
||||||
|
if (showKeyboardMenu()) event.consume();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean showKeyboardMenu() {
|
||||||
|
Node focused = scene.getFocusOwner();
|
||||||
|
for (GroupSurface surface : surfaces.get()) {
|
||||||
|
TabPane tabs = surface.tabs();
|
||||||
|
Node strip = headerStrip(tabs);
|
||||||
|
boolean ownsFocus = focused == tabs;
|
||||||
|
for (Node current = focused; !ownsFocus && current != null; current = current.getParent()) {
|
||||||
|
ownsFocus = current == strip;
|
||||||
|
}
|
||||||
|
if (!ownsFocus) continue;
|
||||||
|
Tab selected = tabs.getSelectionModel().getSelectedItem();
|
||||||
|
Node header = selected == null || strip == null ? null : strip.lookup("#" + selected.getId());
|
||||||
|
if (header == null || selected.getContextMenu() == null) return false;
|
||||||
|
if (!selected.getContextMenu().isShowing()) selected.getContextMenu().show(header, Side.BOTTOM, 0, 0);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private void cancel() {
|
private void cancel() {
|
||||||
pressed = null;
|
pressed = null;
|
||||||
dragging = false;
|
dragging = false;
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ public record DockFailure(Code code, DockableId dockableId, String message, Thro
|
|||||||
this(code, dockableId, message, cause, null);
|
this(code, dockableId, message, cause, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum Code { LAYOUT_CHANGE_IN_PROGRESS, RESTORE_REQUIRES_EMPTY_MANAGER, UNSUPPORTED_SNAPSHOT_VERSION, INVALID_SNAPSHOT, UNSUPPORTED_SNAPSHOT_FEATURE, DOCKABLE_LOAD_FAILED, MISSING_DOCKABLE, INVALID_GROUP_CONFIGURATION, COLLAPSE_DISABLED, SPLIT_DISABLED, SPLIT_TOO_SMALL, TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED,
|
public enum Code { SHUTDOWN_CALLBACK_FAILED, MANAGER_CLOSED, LAYOUT_CHANGE_IN_PROGRESS, RESTORE_REQUIRES_EMPTY_MANAGER, UNSUPPORTED_SNAPSHOT_VERSION, INVALID_SNAPSHOT, UNSUPPORTED_SNAPSHOT_FEATURE, DOCKABLE_LOAD_FAILED, MISSING_DOCKABLE, INVALID_GROUP_CONFIGURATION, COLLAPSE_DISABLED, SPLIT_DISABLED, SPLIT_TOO_SMALL, TARGET_NOT_FOUND, REFERENCE_TAB_NOT_FOUND, DOCKABLE_NOT_FOUND, CONTENT_ALREADY_ATTACHED,
|
||||||
PLACEMENT_REJECTED, PLACEMENT_CHECK_FAILED, ID_MISMATCH, FACTORY_FAILED, MAIN_WINDOW_ONLY,
|
PLACEMENT_REJECTED, PLACEMENT_CHECK_FAILED, ID_MISMATCH, FACTORY_FAILED, MAIN_WINDOW_ONLY,
|
||||||
CLOSE_IN_PROGRESS, CLOSE_CHECK_FAILED, CLEANUP_FAILED, INVALID_WINDOW_BOUNDS, WINDOW_CREATION_FAILED }
|
CLOSE_IN_PROGRESS, CLOSE_CHECK_FAILED, CLEANUP_FAILED, INVALID_WINDOW_BOUNDS, WINDOW_CREATION_FAILED }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -125,6 +125,10 @@ final class DockGroupPane extends TabPane {
|
|||||||
|
|
||||||
@Override protected void layoutChildren() {
|
@Override protected void layoutChildren() {
|
||||||
super.layoutChildren();
|
super.layoutChildren();
|
||||||
|
Node strip = ownedSkinChild("tab-header-area");
|
||||||
|
if (strip != null) {
|
||||||
|
for (Tab tab : getTabs()) DockTabPresentation.updateHeader(tab, strip.lookup("#" + tab.getId()));
|
||||||
|
}
|
||||||
Tab selected = getSelectionModel().getSelectedItem();
|
Tab selected = getSelectionModel().getSelectedItem();
|
||||||
Node selectedContent = selected == null ? null : selected.getContent();
|
Node selectedContent = selected == null ? null : selected.getContent();
|
||||||
for (Node wrapper : getChildrenUnmodifiable()) {
|
for (Node wrapper : getChildrenUnmodifiable()) {
|
||||||
|
|||||||
@@ -58,6 +58,11 @@ final class DockLayoutCandidate {
|
|||||||
List<DockableId> tabs(DockGroupId group) { return List.copyOf(orders.get(group)); }
|
List<DockableId> tabs(DockGroupId group) { return List.copyOf(orders.get(group)); }
|
||||||
DockableId selected(DockGroupId group) { return selections.get(group); }
|
DockableId selected(DockGroupId group) { return selections.get(group); }
|
||||||
void select(DockGroupId group, DockableId selected) { selections.put(group, selected); }
|
void select(DockGroupId group, DockableId selected) { selections.put(group, selected); }
|
||||||
|
void remove(DockableId id) {
|
||||||
|
orders.values().forEach(order -> order.remove(id));
|
||||||
|
selections.replaceAll((group, selected) -> id.equals(selected) ? null : selected);
|
||||||
|
}
|
||||||
|
|
||||||
void place(DockableId id, DockGroupId group, int index) {
|
void place(DockableId id, DockGroupId group, int index) {
|
||||||
orders.values().forEach(order -> order.remove(id));
|
orders.values().forEach(order -> order.remove(id));
|
||||||
List<DockableId> order = orders.get(group);
|
List<DockableId> order = orders.get(group);
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ final class DockLayoutTree {
|
|||||||
private static final class Split implements Branch {
|
private static final class Split implements Branch {
|
||||||
private Branch first;
|
private Branch first;
|
||||||
private Branch second;
|
private Branch second;
|
||||||
private final SplitPane pane = new SplitPane();
|
private final SplitPane pane = new DockSplitPane();
|
||||||
private double position = .5;
|
private double position = .5;
|
||||||
private boolean dragging;
|
private boolean dragging;
|
||||||
private boolean collapsedAllocation;
|
private boolean collapsedAllocation;
|
||||||
|
|||||||
@@ -30,6 +30,13 @@ final class DockOverlayLayer extends Region {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void resume() {
|
||||||
|
disposed = false;
|
||||||
|
if (registeredScene != null) registeredScene.removeEventFilter(MouseEvent.MOUSE_PRESSED, outsidePress);
|
||||||
|
registeredScene = getScene();
|
||||||
|
if (registeredScene != null) registeredScene.addEventFilter(MouseEvent.MOUSE_PRESSED, outsidePress);
|
||||||
|
}
|
||||||
|
|
||||||
void dispose() {
|
void dispose() {
|
||||||
disposed = true;
|
disposed = true;
|
||||||
if (registeredScene != null) registeredScene.removeEventFilter(MouseEvent.MOUSE_PRESSED, outsidePress);
|
if (registeredScene != null) registeredScene.removeEventFilter(MouseEvent.MOUSE_PRESSED, outsidePress);
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ public final class DockPane extends Region {
|
|||||||
DockingManager manager;
|
DockingManager manager;
|
||||||
|
|
||||||
public DockPane() {
|
public DockPane() {
|
||||||
|
sceneProperty().addListener((observable, previous, current) -> DockStyles.install(current));
|
||||||
getStyleClass().add("dock-pane");
|
getStyleClass().add("dock-pane");
|
||||||
getChildren().addAll(surface, overlays);
|
getChildren().addAll(surface, overlays);
|
||||||
dropIndicator.getStyleClass().add("dock-drop-indicator");
|
dropIndicator.getStyleClass().add("dock-drop-indicator");
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ final class DockResetPlan {
|
|||||||
List<Dockable> fallbackContents = new ArrayList<>();
|
List<Dockable> fallbackContents = new ArrayList<>();
|
||||||
for (Dockable dockable : contents) {
|
for (Dockable dockable : contents) {
|
||||||
DockAreaId intended = initialIntents.get(dockable.getId());
|
DockAreaId intended = initialIntents.get(dockable.getId());
|
||||||
DockFailure failure = place(candidate, dockable, intended == null ? null : DockTarget.area(intended), check);
|
DockFailure failure = DockCandidatePlacement.place(candidate, dockable, intended == null ? null : DockTarget.area(intended), check);
|
||||||
if (failure != null) {
|
if (failure != null) {
|
||||||
if (fallback == null) return failure;
|
if (fallback == null) return failure;
|
||||||
fallbackContents.add(dockable);
|
fallbackContents.add(dockable);
|
||||||
@@ -28,7 +28,7 @@ final class DockResetPlan {
|
|||||||
}
|
}
|
||||||
// Home placements establish reference tabs before relative fallback positions are resolved.
|
// Home placements establish reference tabs before relative fallback positions are resolved.
|
||||||
for (Dockable dockable : fallbackContents) {
|
for (Dockable dockable : fallbackContents) {
|
||||||
DockFailure failure = place(candidate, dockable, fallback, check);
|
DockFailure failure = DockCandidatePlacement.place(candidate, dockable, fallback, check);
|
||||||
if (failure != null) return failure;
|
if (failure != null) return failure;
|
||||||
}
|
}
|
||||||
// Relative fallback positions can shift earlier insertions; validate the completed plan too.
|
// Relative fallback positions can shift earlier insertions; validate the completed plan too.
|
||||||
@@ -38,52 +38,10 @@ final class DockResetPlan {
|
|||||||
DockableId id = order.get(index);
|
DockableId id = order.get(index);
|
||||||
Dockable dockable = contents.stream().filter(content -> content.getId().equals(id)).findFirst().orElseThrow();
|
Dockable dockable = contents.stream().filter(content -> content.getId().equals(id)).findFirst().orElseThrow();
|
||||||
MoveCheck checked = check.apply(dockable, new ResolvedDockTarget.Insertion(group.id(), index));
|
MoveCheck checked = check.apply(dockable, new ResolvedDockTarget.Insertion(group.id(), index));
|
||||||
if (checked instanceof MoveCheck.Rejected rejected) return affected(rejected.failure(), dockable.getId());
|
if (checked instanceof MoveCheck.Rejected rejected) return DockCandidatePlacement.affected(rejected.failure(), dockable.getId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static DockFailure place(DockLayoutCandidate candidate, Dockable dockable, DockTarget target,
|
|
||||||
BiFunction<Dockable, ResolvedDockTarget, MoveCheck> check) {
|
|
||||||
List<DockingManager.Group> destinations = switch (target) {
|
|
||||||
case null -> List.of();
|
|
||||||
case DockTarget.Area area -> candidate.groups(area.id());
|
|
||||||
case DockTarget.Group concrete -> candidate.groups().stream().filter(group -> group.id().equals(concrete.id())).toList();
|
|
||||||
default -> List.of();
|
|
||||||
};
|
|
||||||
DockFailure firstFailure = null;
|
|
||||||
for (DockingManager.Group group : destinations) {
|
|
||||||
List<DockableId> order = candidate.tabs(group.id());
|
|
||||||
int index = order.size();
|
|
||||||
if (target instanceof DockTarget.Group concrete) {
|
|
||||||
DockableId reference = switch (concrete.position()) {
|
|
||||||
case TabPosition.Before before -> before.id();
|
|
||||||
case TabPosition.After after -> after.id();
|
|
||||||
case TabPosition.Append ignored -> null;
|
|
||||||
};
|
|
||||||
if (reference != null) {
|
|
||||||
index = order.indexOf(reference);
|
|
||||||
if (index < 0) return new DockFailure(DockFailure.Code.REFERENCE_TAB_NOT_FOUND,
|
|
||||||
dockable.getId(), "Reset fallback reference tab is not in its destination", null);
|
|
||||||
if (concrete.position() instanceof TabPosition.After) index++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
MoveCheck result = check.apply(dockable, new ResolvedDockTarget.Insertion(group.id(), index));
|
|
||||||
if (result instanceof MoveCheck.Allowed) {
|
|
||||||
candidate.place(dockable.getId(), group.id(), index);
|
|
||||||
candidate.select(group.id(), dockable.getId());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (firstFailure == null && result instanceof MoveCheck.Rejected rejected) {
|
|
||||||
firstFailure = affected(rejected.failure(), dockable.getId());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return firstFailure == null ? new DockFailure(DockFailure.Code.TARGET_NOT_FOUND,
|
|
||||||
dockable.getId(), "No eligible reset destination exists", null) : firstFailure;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static DockFailure affected(DockFailure failure, DockableId id) {
|
|
||||||
return new DockFailure(failure.code(), id, failure.message(), failure.cause(), failure.messageKey());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,13 +9,19 @@ import java.util.Map;
|
|||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
/** Owns prepared resolver results until they are either installed or discarded exactly once. */
|
/** Owns prepared resolver results until they are either installed or discarded exactly once. */
|
||||||
record DockRestorePreparation(Map<DockableId, Dockable> contents, RestoreResult.Rejected rejection) {
|
record DockRestorePreparation(Map<DockableId, Dockable> contents, List<DockableId> missingIds,
|
||||||
static DockRestorePreparation resolve(DockLayoutCandidate candidate, DockableResolver resolver,
|
boolean layoutAdjusted, RestoreResult.Rejected rejection) {
|
||||||
|
static DockRestorePreparation resolve(DockLayoutCandidate candidate, DockableResolver resolver, DockTarget fallback,
|
||||||
|
java.util.function.BiFunction<Dockable, ResolvedDockTarget, MoveCheck> placement) {
|
||||||
|
return resolve(List.of(candidate), resolver, fallback, placement);
|
||||||
|
}
|
||||||
|
|
||||||
|
static DockRestorePreparation resolve(List<DockLayoutCandidate> candidates, DockableResolver resolver, DockTarget fallback,
|
||||||
java.util.function.BiFunction<Dockable, ResolvedDockTarget, MoveCheck> placement) {
|
java.util.function.BiFunction<Dockable, ResolvedDockTarget, MoveCheck> placement) {
|
||||||
Map<DockableId, Dockable> prepared = new LinkedHashMap<>();
|
Map<DockableId, Dockable> prepared = new LinkedHashMap<>();
|
||||||
|
List<DockableId> missing = new ArrayList<>();
|
||||||
var contentNodes = Collections.newSetFromMap(new IdentityHashMap<javafx.scene.Node, Boolean>());
|
var contentNodes = Collections.newSetFromMap(new IdentityHashMap<javafx.scene.Node, Boolean>());
|
||||||
for (DockingManager.Group group : candidate.groups()) {
|
for (DockLayoutCandidate candidate : candidates) for (DockingManager.Group group : candidate.groups()) {
|
||||||
int index = 0;
|
|
||||||
for (DockableId id : candidate.tabs(group.id())) {
|
for (DockableId id : candidate.tabs(group.id())) {
|
||||||
DockableResolution resolution;
|
DockableResolution resolution;
|
||||||
try {
|
try {
|
||||||
@@ -29,8 +35,9 @@ record DockRestorePreparation(Map<DockableId, Dockable> contents, RestoreResult.
|
|||||||
id, "Dockable loading failed", failed.cause()));
|
id, "Dockable loading failed", failed.cause()));
|
||||||
}
|
}
|
||||||
if (resolution instanceof DockableResolution.Missing) {
|
if (resolution instanceof DockableResolution.Missing) {
|
||||||
return rejected(prepared, new DockFailure(DockFailure.Code.MISSING_DOCKABLE,
|
missing.add(id);
|
||||||
id, "Missing-ID restoration is not available in this milestone", null));
|
candidate.remove(id);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
Dockable dockable = ((DockableResolution.Available) resolution).dockable();
|
Dockable dockable = ((DockableResolution.Available) resolution).dockable();
|
||||||
if (dockable == null) return rejected(prepared, new DockFailure(DockFailure.Code.DOCKABLE_LOAD_FAILED,
|
if (dockable == null) return rejected(prepared, new DockFailure(DockFailure.Code.DOCKABLE_LOAD_FAILED,
|
||||||
@@ -46,14 +53,39 @@ record DockRestorePreparation(Map<DockableId, Dockable> contents, RestoreResult.
|
|||||||
return rejected(prepared, new DockFailure(DockFailure.Code.CONTENT_ALREADY_ATTACHED,
|
return rejected(prepared, new DockFailure(DockFailure.Code.CONTENT_ALREADY_ATTACHED,
|
||||||
id, "Resolved content is attached or shared by another prepared Dockable", null));
|
id, "Resolved content is attached or shared by another prepared Dockable", null));
|
||||||
}
|
}
|
||||||
MoveCheck checked = placement.apply(dockable, new ResolvedDockTarget.Insertion(group.id(), index++));
|
}
|
||||||
|
}
|
||||||
|
List<Dockable> fallbackContents = new ArrayList<>();
|
||||||
|
for (DockLayoutCandidate candidate : candidates) for (DockingManager.Group group : candidate.groups()) {
|
||||||
|
for (DockableId id : candidate.tabs(group.id())) {
|
||||||
|
Dockable dockable = prepared.get(id);
|
||||||
|
MoveCheck checked = placement.apply(dockable,
|
||||||
|
new ResolvedDockTarget.Insertion(group.id(), candidate.tabs(group.id()).indexOf(id)));
|
||||||
if (checked instanceof MoveCheck.Rejected rejected) {
|
if (checked instanceof MoveCheck.Rejected rejected) {
|
||||||
DockFailure failure = rejected.failure();
|
if (fallback == null) return rejected(prepared, DockCandidatePlacement.affected(rejected.failure(), id));
|
||||||
return rejected(prepared, new DockFailure(failure.code(), id, failure.message(), failure.cause(), failure.messageKey()));
|
candidate.remove(id);
|
||||||
|
fallbackContents.add(dockable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new DockRestorePreparation(Collections.unmodifiableMap(new LinkedHashMap<>(prepared)), null);
|
// Resolve fallbacks only after every surviving reference tab is known.
|
||||||
|
for (Dockable dockable : fallbackContents) {
|
||||||
|
DockFailure failure = DockCandidatePlacement.place(candidates.getFirst(), dockable, fallback, placement);
|
||||||
|
if (failure != null) return rejected(prepared, failure);
|
||||||
|
}
|
||||||
|
// Relative insertions can shift earlier positions, so validate the final plan before installation.
|
||||||
|
for (DockLayoutCandidate candidate : candidates) for (DockingManager.Group group : candidate.groups()) {
|
||||||
|
List<DockableId> order = candidate.tabs(group.id());
|
||||||
|
for (int index = 0; index < order.size(); index++) {
|
||||||
|
DockableId id = order.get(index);
|
||||||
|
MoveCheck checked = placement.apply(prepared.get(id), new ResolvedDockTarget.Insertion(group.id(), index));
|
||||||
|
if (checked instanceof MoveCheck.Rejected rejected) {
|
||||||
|
return rejected(prepared, DockCandidatePlacement.affected(rejected.failure(), id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new DockRestorePreparation(Collections.unmodifiableMap(new LinkedHashMap<>(prepared)), List.copyOf(missing),
|
||||||
|
!missing.isEmpty() || !fallbackContents.isEmpty(), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
static DockRestorePreparation rejected(Map<DockableId, Dockable> prepared, DockFailure primary) {
|
static DockRestorePreparation rejected(Map<DockableId, Dockable> prepared, DockFailure primary) {
|
||||||
@@ -68,6 +100,6 @@ record DockRestorePreparation(Map<DockableId, Dockable> contents, RestoreResult.
|
|||||||
"Prepared Dockable cleanup failed", failure));
|
"Prepared Dockable cleanup failed", failure));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new DockRestorePreparation(Map.of(), new RestoreResult.Rejected(primary, cleanup));
|
return new DockRestorePreparation(Map.of(), List.of(), false, new RestoreResult.Rejected(primary, cleanup));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
import javafx.scene.Node;
|
||||||
|
import javafx.scene.control.SplitPane;
|
||||||
|
|
||||||
|
/** Exposes stable divider styling as soon as a docking split is laid out. */
|
||||||
|
final class DockSplitPane extends SplitPane {
|
||||||
|
@Override protected void layoutChildren() {
|
||||||
|
for (Node child : getChildrenUnmodifiable()) {
|
||||||
|
if (child.getStyleClass().contains("split-pane-divider")
|
||||||
|
&& !child.getStyleClass().contains("dock-divider")) {
|
||||||
|
child.getStyleClass().add("dock-divider");
|
||||||
|
child.applyCss();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
super.layoutChildren();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/** Adds scoped defaults before application styles, without replacing the application's theme. */
|
||||||
|
final class DockStyles {
|
||||||
|
private static final String DEFAULTS = Objects.requireNonNull(DockStyles.class.getResource("docking.css")).toExternalForm();
|
||||||
|
|
||||||
|
private DockStyles() { }
|
||||||
|
|
||||||
|
static void install(Scene scene) {
|
||||||
|
if (scene != null && !scene.getStylesheets().contains(DEFAULTS)) scene.getStylesheets().addFirst(DEFAULTS);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
import javafx.beans.InvalidationListener;
|
||||||
|
import javafx.beans.binding.Bindings;
|
||||||
|
import javafx.beans.binding.StringBinding;
|
||||||
|
import javafx.scene.control.Tab;
|
||||||
|
|
||||||
|
/** Keeps icon-only accessibility text separate from the application's visible title. */
|
||||||
|
final class DockTabPresentation {
|
||||||
|
private final Tab tab;
|
||||||
|
private final Dockable dockable;
|
||||||
|
private final String closeName;
|
||||||
|
private final StringBinding text;
|
||||||
|
private final InvalidationListener appearanceChanged = observable -> refreshClass();
|
||||||
|
|
||||||
|
private DockTabPresentation(Tab tab, Dockable dockable, String closeName) {
|
||||||
|
this.tab = tab;
|
||||||
|
this.dockable = dockable;
|
||||||
|
this.closeName = closeName;
|
||||||
|
text = Bindings.createStringBinding(this::headerText,
|
||||||
|
dockable.titleProperty(), dockable.iconProperty(), dockable.accessibleNameProperty());
|
||||||
|
tab.textProperty().bind(text);
|
||||||
|
tab.getStyleClass().add("dock-tab-header");
|
||||||
|
refreshClass();
|
||||||
|
dockable.titleProperty().addListener(appearanceChanged);
|
||||||
|
dockable.iconProperty().addListener(appearanceChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void bind(Tab tab, Dockable dockable, String closeName) {
|
||||||
|
tab.getProperties().put(DockTabPresentation.class, new DockTabPresentation(tab, dockable, closeName));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void updateHeader(Tab tab, javafx.scene.Node header) {
|
||||||
|
if (header == null) return;
|
||||||
|
if (tab.getProperties().get(DockTabPresentation.class) instanceof DockTabPresentation presentation) {
|
||||||
|
javafx.scene.Node close = header.lookup(".tab-close-button");
|
||||||
|
if (close != null) close.setAccessibleText(presentation.closeName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void unbind(Tab tab) {
|
||||||
|
if (tab.getProperties().remove(DockTabPresentation.class) instanceof DockTabPresentation presentation) {
|
||||||
|
presentation.dockable.titleProperty().removeListener(presentation.appearanceChanged);
|
||||||
|
presentation.dockable.iconProperty().removeListener(presentation.appearanceChanged);
|
||||||
|
tab.textProperty().unbind();
|
||||||
|
presentation.text.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean iconOnly() {
|
||||||
|
return dockable.getIcon() != null && (dockable.getTitle() == null || dockable.getTitle().isBlank());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String headerText() {
|
||||||
|
if (!iconOnly()) return dockable.getTitle();
|
||||||
|
String name = dockable.getAccessibleName();
|
||||||
|
return name == null || name.isBlank() ? dockable.getTitle() : name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void refreshClass() {
|
||||||
|
if (iconOnly()) {
|
||||||
|
if (!tab.getStyleClass().contains("dock-icon-only")) tab.getStyleClass().add("dock-icon-only");
|
||||||
|
} else tab.getStyleClass().remove("dock-icon-only");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ public final class Dockable {
|
|||||||
@Getter @Setter private CloseCheck closeCheck;
|
@Getter @Setter private CloseCheck closeCheck;
|
||||||
@Getter @Setter private Runnable onClosed;
|
@Getter @Setter private Runnable onClosed;
|
||||||
private final StringProperty title = new SimpleStringProperty(this, "title", "");
|
private final StringProperty title = new SimpleStringProperty(this, "title", "");
|
||||||
|
private final StringProperty accessibleName = new SimpleStringProperty(this, "accessibleName", "");
|
||||||
private final ObjectProperty<Node> icon = new SimpleObjectProperty<>(this, "icon");
|
private final ObjectProperty<Node> icon = new SimpleObjectProperty<>(this, "icon");
|
||||||
|
|
||||||
public Dockable(DockableId id, Node content) {
|
public Dockable(DockableId id, Node content) {
|
||||||
@@ -28,6 +29,11 @@ public final class Dockable {
|
|||||||
this.content = Objects.requireNonNull(content, "content");
|
this.content = Objects.requireNonNull(content, "content");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Name spoken for an icon-only tab; tabs with visible text use their title. */
|
||||||
|
public StringProperty accessibleNameProperty() { return accessibleName; }
|
||||||
|
public String getAccessibleName() { return accessibleName.get(); }
|
||||||
|
public void setAccessibleName(String value) { accessibleName.set(value); }
|
||||||
|
|
||||||
public StringProperty titleProperty() { return title; }
|
public StringProperty titleProperty() { return title; }
|
||||||
public String getTitle() { return title.get(); }
|
public String getTitle() { return title.get(); }
|
||||||
public void setTitle(String value) { title.set(value); }
|
public void setTitle(String value) { title.set(value); }
|
||||||
|
|||||||
@@ -21,6 +21,10 @@ public final class DockingManager {
|
|||||||
private static final Object ATTACHMENT_KEY = new Object();
|
private static final Object ATTACHMENT_KEY = new Object();
|
||||||
private final Stage stage;
|
private final Stage stage;
|
||||||
private final DockPane pane;
|
private final DockPane pane;
|
||||||
|
private final javafx.scene.Scene mainScene;
|
||||||
|
private final MainWindowCloseMode mainWindowCloseMode;
|
||||||
|
private final java.util.function.Function<ShutdownRequest, java.util.concurrent.CompletionStage<ShutdownDecision>> beforeShutdown;
|
||||||
|
private boolean disposed;
|
||||||
private final PlacementRule placementRule;
|
private final PlacementRule placementRule;
|
||||||
private final DockMessages messages;
|
private final DockMessages messages;
|
||||||
private final DockTarget fallbackTarget;
|
private final DockTarget fallbackTarget;
|
||||||
@@ -52,13 +56,29 @@ public final class DockingManager {
|
|||||||
private final ReadOnlyObjectWrapper<Dockable> active = new ReadOnlyObjectWrapper<>(this, "activeDockable");
|
private final ReadOnlyObjectWrapper<Dockable> active = new ReadOnlyObjectWrapper<>(this, "activeDockable");
|
||||||
private final ReadOnlyObjectWrapper<DockLayoutView> layout = new ReadOnlyObjectWrapper<>(this, "layout");
|
private final ReadOnlyObjectWrapper<DockLayoutView> layout = new ReadOnlyObjectWrapper<>(this, "layout");
|
||||||
private LayoutSnapshot publishedSnapshot;
|
private LayoutSnapshot publishedSnapshot;
|
||||||
|
private final javafx.event.EventHandler<javafx.stage.WindowEvent> mainCloseHandler = event -> {
|
||||||
|
event.consume();
|
||||||
|
requestMainWindowClose();
|
||||||
|
};
|
||||||
|
private final javafx.event.EventHandler<javafx.stage.WindowEvent> mainShownHandler = event -> {
|
||||||
|
boolean wasUpdating = updating;
|
||||||
|
updating = true;
|
||||||
|
try {
|
||||||
|
floatingWindows.values().forEach(window -> window.stage.show());
|
||||||
|
focus(active.get());
|
||||||
|
} finally { updating = wasUpdating; }
|
||||||
|
};
|
||||||
|
|
||||||
private DockingManager(Stage stage, DockPane pane, DockingOptions options) {
|
private DockingManager(Stage stage, DockPane pane, DockingOptions options) {
|
||||||
this.stage = stage;
|
this.stage = stage;
|
||||||
this.pane = pane;
|
this.pane = pane;
|
||||||
|
this.mainScene = stage.getScene();
|
||||||
|
this.mainWindowCloseMode = Objects.requireNonNull(options.getMainWindowCloseMode(), "mainWindowCloseMode");
|
||||||
|
this.beforeShutdown = Objects.requireNonNull(options.getBeforeShutdown(), "beforeShutdown");
|
||||||
this.messages = new DockMessages(options.getResourceBundle());
|
this.messages = new DockMessages(options.getResourceBundle());
|
||||||
closing = new DockCloseCoordinator(new DockCloseCoordinator.Host() {
|
closing = new DockCloseCoordinator(new DockCloseCoordinator.Host() {
|
||||||
@Override public Optional<Dockable> find(DockableId id) { return findDockable(id); }
|
@Override public Optional<Dockable> find(DockableId id) { return findDockable(id); }
|
||||||
|
@Override public List<DockableId> allDockables() { return List.copyOf(dockables.keySet()); }
|
||||||
@Override public javafx.stage.Window owner(DockableId id) { return DockingManager.this.owner(containing(id)); }
|
@Override public javafx.stage.Window owner(DockableId id) { return DockingManager.this.owner(containing(id)); }
|
||||||
@Override public Optional<List<DockableId>> floatingDockables(DockWindowId id) {
|
@Override public Optional<List<DockableId>> floatingDockables(DockWindowId id) {
|
||||||
FloatingWindow window = floatingWindows.get(id);
|
FloatingWindow window = floatingWindows.get(id);
|
||||||
@@ -69,6 +89,11 @@ public final class DockingManager {
|
|||||||
.map(tab -> (DockableId) tab.getUserData()).toList());
|
.map(tab -> (DockableId) tab.getUserData()).toList());
|
||||||
}
|
}
|
||||||
@Override public void remove(List<DockableId> ids) { removeDockables(ids); }
|
@Override public void remove(List<DockableId> ids) { removeDockables(ids); }
|
||||||
|
@Override public java.util.concurrent.CompletionStage<ShutdownDecision> beforeShutdown(CloseScope.Kind kind) {
|
||||||
|
return DockingManager.this.beforeShutdown.apply(new ShutdownRequest(snapshot(),
|
||||||
|
kind == CloseScope.Kind.MAIN_WINDOW ? ShutdownReason.MAIN_WINDOW : ShutdownReason.MANAGER_ONLY));
|
||||||
|
}
|
||||||
|
@Override public void endManager(CloseScope.Kind kind) { releaseManager(kind); }
|
||||||
});
|
});
|
||||||
this.placementRule = Objects.requireNonNull(options.getPlacementRule(), "placementRule");
|
this.placementRule = Objects.requireNonNull(options.getPlacementRule(), "placementRule");
|
||||||
this.fallbackTarget = options.getFallbackTarget();
|
this.fallbackTarget = options.getFallbackTarget();
|
||||||
@@ -78,6 +103,7 @@ public final class DockingManager {
|
|||||||
this.floatingWindowCustomizer = Objects.requireNonNull(options.getFloatingWindowCustomizer(), "floatingWindowCustomizer");
|
this.floatingWindowCustomizer = Objects.requireNonNull(options.getFloatingWindowCustomizer(), "floatingWindowCustomizer");
|
||||||
DockLayout initial = Objects.requireNonNull(pane.getInitialLayout(), "initialLayout");
|
DockLayout initial = Objects.requireNonNull(pane.getInitialLayout(), "initialLayout");
|
||||||
validate(initial);
|
validate(initial);
|
||||||
|
pane.overlays.resume();
|
||||||
addGroup(initial.getCenter(), pane.surface::setCenter);
|
addGroup(initial.getCenter(), pane.surface::setCenter);
|
||||||
addEdgeGroup(initial.getLeft(), javafx.geometry.Side.LEFT);
|
addEdgeGroup(initial.getLeft(), javafx.geometry.Side.LEFT);
|
||||||
addEdgeGroup(initial.getRight(), javafx.geometry.Side.RIGHT);
|
addEdgeGroup(initial.getRight(), javafx.geometry.Side.RIGHT);
|
||||||
@@ -91,7 +117,11 @@ public final class DockingManager {
|
|||||||
refreshEmptyGroups();
|
refreshEmptyGroups();
|
||||||
publish();
|
publish();
|
||||||
initialWindow = snapshot().windows().getFirst();
|
initialWindow = snapshot().windows().getFirst();
|
||||||
stage.getScene().focusOwnerProperty().addListener(focusListener);
|
mainScene.focusOwnerProperty().addListener(focusListener);
|
||||||
|
stage.addEventHandler(javafx.stage.WindowEvent.WINDOW_SHOWN, mainShownHandler);
|
||||||
|
if (mainWindowCloseMode == MainWindowCloseMode.AUTOMATIC) {
|
||||||
|
stage.addEventFilter(javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST, mainCloseHandler);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static DockingManager attach(Stage stage, DockPane pane, DockingOptions options) {
|
public static DockingManager attach(Stage stage, DockPane pane, DockingOptions options) {
|
||||||
@@ -113,6 +143,8 @@ public final class DockingManager {
|
|||||||
|
|
||||||
public ActionResult open(Dockable dockable, DockTarget target) {
|
public ActionResult open(Dockable dockable, DockTarget target) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
|
||||||
|
if (globalClosePending()) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "A manager-wide close is pending");
|
||||||
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
||||||
Objects.requireNonNull(dockable, "dockable");
|
Objects.requireNonNull(dockable, "dockable");
|
||||||
if (dockables.containsKey(dockable.getId())) return activate(dockable.getId());
|
if (dockables.containsKey(dockable.getId())) return activate(dockable.getId());
|
||||||
@@ -158,7 +190,7 @@ public final class DockingManager {
|
|||||||
event.consume();
|
event.consume();
|
||||||
requestTabClose(dockable.getId());
|
requestTabClose(dockable.getId());
|
||||||
});
|
});
|
||||||
tab.textProperty().bind(dockable.titleProperty());
|
DockTabPresentation.bind(tab, dockable, message("dock.action.close"));
|
||||||
tab.graphicProperty().bind(dockable.iconProperty());
|
tab.graphicProperty().bind(dockable.iconProperty());
|
||||||
tab.setContent(dockable.getContent());
|
tab.setContent(dockable.getContent());
|
||||||
tab.setUserData(dockable.getId());
|
tab.setUserData(dockable.getId());
|
||||||
@@ -168,6 +200,8 @@ public final class DockingManager {
|
|||||||
/** Creates content only for a new identity; rejected prepared content is discarded. */
|
/** Creates content only for a new identity; rejected prepared content is discarded. */
|
||||||
public ActionResult open(DockableId id, java.util.function.Supplier<? extends Dockable> factory, DockTarget target) {
|
public ActionResult open(DockableId id, java.util.function.Supplier<? extends Dockable> factory, DockTarget target) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
|
||||||
|
if (globalClosePending()) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null, "A manager-wide close is pending");
|
||||||
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
||||||
Objects.requireNonNull(id, "id");
|
Objects.requireNonNull(id, "id");
|
||||||
Objects.requireNonNull(factory, "factory");
|
Objects.requireNonNull(factory, "factory");
|
||||||
@@ -199,6 +233,7 @@ public final class DockingManager {
|
|||||||
/** Restores the captured starting arrangement while retaining every live Dockable. */
|
/** Restores the captured starting arrangement while retaining every live Dockable. */
|
||||||
public ActionResult resetLayout() {
|
public ActionResult resetLayout() {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
|
||||||
if (layoutChanging) return rejected(DockFailure.Code.LAYOUT_CHANGE_IN_PROGRESS, null,
|
if (layoutChanging) return rejected(DockFailure.Code.LAYOUT_CHANGE_IN_PROGRESS, null,
|
||||||
"A layout replacement is already being prepared");
|
"A layout replacement is already being prepared");
|
||||||
if (closing.scope() != null) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null,
|
if (closing.scope() != null) return rejected(DockFailure.Code.CLOSE_IN_PROGRESS, null,
|
||||||
@@ -232,6 +267,7 @@ public final class DockingManager {
|
|||||||
|
|
||||||
public ActionResult activate(DockableId id) {
|
public ActionResult activate(DockableId id) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
|
||||||
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
||||||
Dockable dockable = dockables.get(id);
|
Dockable dockable = dockables.get(id);
|
||||||
if (dockable == null) return rejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open");
|
if (dockable == null) return rejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open");
|
||||||
@@ -274,6 +310,7 @@ public final class DockingManager {
|
|||||||
/** Requests consent without closing or releasing content while the answer is pending. */
|
/** Requests consent without closing or releasing content while the answer is pending. */
|
||||||
public java.util.concurrent.CompletionStage<CloseResult> requestTabClose(DockableId id) {
|
public java.util.concurrent.CompletionStage<CloseResult> requestTabClose(DockableId id) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed && closing.scope() == null) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.NoChange());
|
||||||
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
|
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
|
||||||
return closing.requestTabClose(id);
|
return closing.requestTabClose(id);
|
||||||
}
|
}
|
||||||
@@ -281,6 +318,7 @@ public final class DockingManager {
|
|||||||
/** Requests every contained Dockable's consent before closing a floating window. */
|
/** Requests every contained Dockable's consent before closing a floating window. */
|
||||||
public java.util.concurrent.CompletionStage<CloseResult> requestFloatingWindowClose(DockWindowId id) {
|
public java.util.concurrent.CompletionStage<CloseResult> requestFloatingWindowClose(DockWindowId id) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed && closing.scope() == null) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.NoChange());
|
||||||
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
|
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
|
||||||
Objects.requireNonNull(id, "id");
|
Objects.requireNonNull(id, "id");
|
||||||
if (layout.get().windows().getFirst().id().equals(id)) {
|
if (layout.get().windows().getFirst().id().equals(id)) {
|
||||||
@@ -290,11 +328,64 @@ public final class DockingManager {
|
|||||||
return closing.requestFloatingWindowClose(id);
|
return closing.requestFloatingWindowClose(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Collects consent and saves the complete layout before closing this manager's windows. */
|
||||||
|
public java.util.concurrent.CompletionStage<CloseResult> requestMainWindowClose() {
|
||||||
|
requireFxThread();
|
||||||
|
if (disposed && closing.scope() == null) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.NoChange());
|
||||||
|
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
|
||||||
|
return closing.requestShutdown(CloseScope.Kind.MAIN_WINDOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ends this embedded manager while preserving the application's main Stage. */
|
||||||
|
public java.util.concurrent.CompletionStage<CloseResult> requestManagerClose() {
|
||||||
|
requireFxThread();
|
||||||
|
if (disposed && closing.scope() == null) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.NoChange());
|
||||||
|
if (layoutChanging) return java.util.concurrent.CompletableFuture.completedFuture(new CloseResult.Rejected(layoutChangeFailure()));
|
||||||
|
return closing.requestShutdown(CloseScope.Kind.MANAGER_ONLY);
|
||||||
|
}
|
||||||
|
|
||||||
/** Scope remains available until checks and resource release have finished. */
|
/** Scope remains available until checks and resource release have finished. */
|
||||||
public ReadOnlyObjectProperty<CloseScope> closingScopeProperty() {
|
public ReadOnlyObjectProperty<CloseScope> closingScopeProperty() {
|
||||||
return closing.closingScopeProperty();
|
return closing.closingScopeProperty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean globalClosePending() {
|
||||||
|
CloseScope scope = closing.scope();
|
||||||
|
return scope != null && (scope.kind() == CloseScope.Kind.MAIN_WINDOW || scope.kind() == CloseScope.Kind.MANAGER_ONLY);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DockFailure managerClosedFailure() {
|
||||||
|
return new DockFailure(DockFailure.Code.MANAGER_CLOSED, null, "The docking manager has ended", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void releaseManager(CloseScope.Kind kind) {
|
||||||
|
if (disposed) return;
|
||||||
|
disposed = true;
|
||||||
|
boolean wasUpdating = updating;
|
||||||
|
updating = true;
|
||||||
|
try {
|
||||||
|
drag.dispose();
|
||||||
|
mainScene.focusOwnerProperty().removeListener(focusListener);
|
||||||
|
stage.removeEventHandler(javafx.stage.WindowEvent.WINDOW_SHOWN, mainShownHandler);
|
||||||
|
stage.removeEventFilter(javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST, mainCloseHandler);
|
||||||
|
floatingWindows.values().forEach(this::disposeFloatingWindow);
|
||||||
|
floatingWindows.clear();
|
||||||
|
groupWindows.clear();
|
||||||
|
tree.clear();
|
||||||
|
pane.clearAreas();
|
||||||
|
pane.overlays.dispose();
|
||||||
|
groups.clear();
|
||||||
|
edgeAreas.clear();
|
||||||
|
groupActivationOrder.clear();
|
||||||
|
previousFocus.clear();
|
||||||
|
activationOrder.clear();
|
||||||
|
pane.manager = null;
|
||||||
|
if (stage.getProperties().get(ATTACHMENT_KEY) == this) stage.getProperties().remove(ATTACHMENT_KEY);
|
||||||
|
} finally { updating = wasUpdating; }
|
||||||
|
publish();
|
||||||
|
if (kind == CloseScope.Kind.MAIN_WINDOW && mainWindowCloseMode == MainWindowCloseMode.AUTOMATIC) stage.hide();
|
||||||
|
}
|
||||||
|
|
||||||
private void removeDockables(List<DockableId> ids) {
|
private void removeDockables(List<DockableId> ids) {
|
||||||
Dockable previousActive = active.get();
|
Dockable previousActive = active.get();
|
||||||
Group previousGroup = previousActive == null ? null : containing(previousActive.getId());
|
Group previousGroup = previousActive == null ? null : containing(previousActive.getId());
|
||||||
@@ -305,6 +396,7 @@ public final class DockingManager {
|
|||||||
if (group == null) continue;
|
if (group == null) continue;
|
||||||
Tab tab = group.tabs.getTabs().get(tabIndex(group, id));
|
Tab tab = group.tabs.getTabs().get(tabIndex(group, id));
|
||||||
dragFor(group).uninstallTab(tab);
|
dragFor(group).uninstallTab(tab);
|
||||||
|
DockTabPresentation.unbind(tab);
|
||||||
tab.textProperty().unbind();
|
tab.textProperty().unbind();
|
||||||
tab.graphicProperty().unbind();
|
tab.graphicProperty().unbind();
|
||||||
tab.setGraphic(null);
|
tab.setGraphic(null);
|
||||||
@@ -340,6 +432,7 @@ public final class DockingManager {
|
|||||||
if (layoutChanging) return true;
|
if (layoutChanging) return true;
|
||||||
CloseScope scope = closing.scope();
|
CloseScope scope = closing.scope();
|
||||||
if (scope == null) return false;
|
if (scope == null) return false;
|
||||||
|
if (scope.kind() == CloseScope.Kind.MAIN_WINDOW || scope.kind() == CloseScope.Kind.MANAGER_ONLY) return true;
|
||||||
if (scope.kind() == CloseScope.Kind.FLOATING_WINDOW) {
|
if (scope.kind() == CloseScope.Kind.FLOATING_WINDOW) {
|
||||||
return group != null && closing.coversWindow(groupWindows.get(group.id));
|
return group != null && closing.coversWindow(groupWindows.get(group.id));
|
||||||
}
|
}
|
||||||
@@ -352,6 +445,7 @@ public final class DockingManager {
|
|||||||
/** Resolves a move without mutating content, layout or identity allocation. */
|
/** Resolves a move without mutating content, layout or identity allocation. */
|
||||||
public MoveCheck checkMove(DockableId id, DockTarget target) {
|
public MoveCheck checkMove(DockableId id, DockTarget target) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed) return new MoveCheck.Rejected(managerClosedFailure());
|
||||||
if (layoutChanging) return new MoveCheck.Rejected(layoutChangeFailure());
|
if (layoutChanging) return new MoveCheck.Rejected(layoutChangeFailure());
|
||||||
if (!dockables.containsKey(id)) return moveRejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open");
|
if (!dockables.containsKey(id)) return moveRejected(DockFailure.Code.DOCKABLE_NOT_FOUND, id, "Dockable is not open");
|
||||||
if (groupClosing(containing(id))) return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "A close request covers this group");
|
if (groupClosing(containing(id))) return moveRejected(DockFailure.Code.CLOSE_IN_PROGRESS, id, "A close request covers this group");
|
||||||
@@ -583,6 +677,7 @@ public final class DockingManager {
|
|||||||
/** Applies explicitly supplied settings as one validated group change. */
|
/** Applies explicitly supplied settings as one validated group change. */
|
||||||
public ActionResult updateGroup(DockGroupId id, DockGroupChanges changes) {
|
public ActionResult updateGroup(DockGroupId id, DockGroupChanges changes) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
|
||||||
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
||||||
Objects.requireNonNull(changes, "changes");
|
Objects.requireNonNull(changes, "changes");
|
||||||
Group group = group(Objects.requireNonNull(id, "id"));
|
Group group = group(Objects.requireNonNull(id, "id"));
|
||||||
@@ -675,6 +770,7 @@ public final class DockingManager {
|
|||||||
|
|
||||||
private ActionResult setGroupCollapsed(DockGroupId id, boolean collapsed, boolean focusHeader) {
|
private ActionResult setGroupCollapsed(DockGroupId id, boolean collapsed, boolean focusHeader) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed) return new ActionResult.Rejected(managerClosedFailure());
|
||||||
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
if (layoutChanging) return new ActionResult.Rejected(layoutChangeFailure());
|
||||||
Group group = group(Objects.requireNonNull(id, "id"));
|
Group group = group(Objects.requireNonNull(id, "id"));
|
||||||
if (group == null) return rejected(DockFailure.Code.TARGET_NOT_FOUND, null, "Group does not exist");
|
if (group == null) return rejected(DockFailure.Code.TARGET_NOT_FOUND, null, "Group does not exist");
|
||||||
@@ -779,6 +875,7 @@ public final class DockingManager {
|
|||||||
/** Prepares fresh content for an empty manager, then installs the validated layout as one change. */
|
/** Prepares fresh content for an empty manager, then installs the validated layout as one change. */
|
||||||
public RestoreResult restore(LayoutSnapshot snapshot, DockableResolver resolver) {
|
public RestoreResult restore(LayoutSnapshot snapshot, DockableResolver resolver) {
|
||||||
requireFxThread();
|
requireFxThread();
|
||||||
|
if (disposed) return new RestoreResult.Rejected(managerClosedFailure(), List.of());
|
||||||
Objects.requireNonNull(snapshot, "snapshot");
|
Objects.requireNonNull(snapshot, "snapshot");
|
||||||
Objects.requireNonNull(resolver, "resolver");
|
Objects.requireNonNull(resolver, "resolver");
|
||||||
if (layoutChanging) return new RestoreResult.Rejected(layoutChangeFailure(), List.of());
|
if (layoutChanging) return new RestoreResult.Rejected(layoutChangeFailure(), List.of());
|
||||||
@@ -789,20 +886,48 @@ public final class DockingManager {
|
|||||||
DockFailure invalid = DockSnapshotValidation.validate(snapshot,
|
DockFailure invalid = DockSnapshotValidation.validate(snapshot,
|
||||||
group -> validate(group.settings().definition(group.originArea()), new java.util.HashSet<>()));
|
group -> validate(group.settings().definition(group.originArea()), new java.util.HashSet<>()));
|
||||||
if (invalid != null) return new RestoreResult.Rejected(invalid, List.of());
|
if (invalid != null) return new RestoreResult.Rejected(invalid, List.of());
|
||||||
if (snapshot.windows().size() != 1) return new RestoreResult.Rejected(new DockFailure(
|
|
||||||
DockFailure.Code.UNSUPPORTED_SNAPSHOT_FEATURE, null, "Floating-window restoration is not available in this milestone", null), List.of());
|
|
||||||
layoutChanging = true;
|
layoutChanging = true;
|
||||||
try {
|
try {
|
||||||
DockLayoutCandidate candidate = prepareLayoutCandidate(snapshot.windows().getFirst());
|
List<DockLayoutCandidate> candidates = snapshot.windows().stream().map(this::prepareLayoutCandidate).toList();
|
||||||
DockRestorePreparation prepared = DockRestorePreparation.resolve(candidate, resolver, this::checkPlacement);
|
java.util.Set<DockGroupId> floatingGroups = candidates.stream().filter(candidate -> !candidate.window.main())
|
||||||
|
.flatMap(candidate -> candidate.groups().stream()).map(Group::id).collect(java.util.stream.Collectors.toSet());
|
||||||
|
DockRestorePreparation prepared = DockRestorePreparation.resolve(candidates, resolver, fallbackTarget, (dockable, target) -> {
|
||||||
|
if (dockable.isMainWindowOnly() && target instanceof ResolvedDockTarget.Insertion insertion
|
||||||
|
&& floatingGroups.contains(insertion.groupId())) {
|
||||||
|
return moveRejected(DockFailure.Code.MAIN_WINDOW_ONLY, dockable.getId(), "This Dockable must remain in the main window");
|
||||||
|
}
|
||||||
|
return checkPlacement(dockable, target);
|
||||||
|
});
|
||||||
if (prepared.rejection() != null) return prepared.rejection();
|
if (prepared.rejection() != null) return prepared.rejection();
|
||||||
|
if (prepared.layoutAdjusted()) candidates.forEach(DockLayoutCandidate::normalize);
|
||||||
|
candidates = candidates.stream().filter(candidate -> candidate.window.main()
|
||||||
|
|| candidate.groups().stream().anyMatch(group -> !candidate.tabs(group.id).isEmpty())).toList();
|
||||||
|
if (snapshot.activeDockableId() != null) for (DockLayoutCandidate candidate : candidates) {
|
||||||
|
candidate.groups().stream().filter(group -> candidate.tabs(group.id).contains(snapshot.activeDockableId())).findFirst()
|
||||||
|
.ifPresent(group -> candidate.select(group.id, snapshot.activeDockableId()));
|
||||||
|
}
|
||||||
|
Map<DockWindowId, FloatingWindow> hosts = new LinkedHashMap<>();
|
||||||
|
try {
|
||||||
|
for (DockLayoutCandidate candidate : candidates) if (!candidate.window.main()) {
|
||||||
|
hosts.put(candidate.window.id(), prepareFloatingWindow(candidate.window.id(),
|
||||||
|
DockWindowBounds.fit(candidate.window.bounds())));
|
||||||
|
}
|
||||||
|
} catch (FloatingPreparationFailure failure) {
|
||||||
|
hosts.values().forEach(this::disposeFloatingWindow);
|
||||||
|
return DockRestorePreparation.rejected(prepared.contents(), new DockFailure(
|
||||||
|
DockFailure.Code.WINDOW_CREATION_FAILED, null, "Floating window preparation failed", failure.getCause())).rejection();
|
||||||
|
}
|
||||||
initialIntents.clear();
|
initialIntents.clear();
|
||||||
initialIntents.putAll(snapshot.initialIntents());
|
snapshot.initialIntents().forEach((id, area) -> {
|
||||||
|
if (prepared.contents().containsKey(id)) initialIntents.put(id, area);
|
||||||
|
});
|
||||||
returnTargets.clear();
|
returnTargets.clear();
|
||||||
snapshot.returnPositions().forEach((id, position) -> returnTargets.put(id,
|
snapshot.returnPositions().forEach((id, position) -> {
|
||||||
new ReturnLocation(position.target(), position.areaId())));
|
if (prepared.contents().containsKey(id)) returnTargets.put(id,
|
||||||
installLayoutCandidate(candidate, prepared.contents(), snapshot.activeDockableId());
|
new ReturnLocation(position.target(), position.areaId()));
|
||||||
return new RestoreResult.Applied(List.of());
|
});
|
||||||
|
installLayoutCandidates(candidates, hosts, prepared.contents(), snapshot.activeDockableId());
|
||||||
|
return new RestoreResult.Applied(prepared.missingIds());
|
||||||
} finally {
|
} finally {
|
||||||
layoutChanging = false;
|
layoutChanging = false;
|
||||||
}
|
}
|
||||||
@@ -825,6 +950,11 @@ public final class DockingManager {
|
|||||||
|
|
||||||
private void installLayoutCandidate(DockLayoutCandidate candidate, Map<DockableId, Dockable> contents,
|
private void installLayoutCandidate(DockLayoutCandidate candidate, Map<DockableId, Dockable> contents,
|
||||||
DockableId activeId) {
|
DockableId activeId) {
|
||||||
|
installLayoutCandidates(List.of(candidate), Map.of(), contents, activeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void installLayoutCandidates(List<DockLayoutCandidate> candidates, Map<DockWindowId, FloatingWindow> hosts,
|
||||||
|
Map<DockableId, Dockable> contents, DockableId activeId) {
|
||||||
Map<DockableId, Dockable> installed = new LinkedHashMap<>(contents);
|
Map<DockableId, Dockable> installed = new LinkedHashMap<>(contents);
|
||||||
boolean wasUpdating = updating;
|
boolean wasUpdating = updating;
|
||||||
updating = true;
|
updating = true;
|
||||||
@@ -832,6 +962,7 @@ public final class DockingManager {
|
|||||||
for (Group old : groups.values()) {
|
for (Group old : groups.values()) {
|
||||||
for (Tab tab : List.copyOf(old.tabs.getTabs())) {
|
for (Tab tab : List.copyOf(old.tabs.getTabs())) {
|
||||||
dragFor(old).uninstallTab(tab);
|
dragFor(old).uninstallTab(tab);
|
||||||
|
DockTabPresentation.unbind(tab);
|
||||||
tab.textProperty().unbind();
|
tab.textProperty().unbind();
|
||||||
tab.graphicProperty().unbind();
|
tab.graphicProperty().unbind();
|
||||||
tab.setGraphic(null);
|
tab.setGraphic(null);
|
||||||
@@ -851,12 +982,19 @@ public final class DockingManager {
|
|||||||
dockables.putAll(installed);
|
dockables.putAll(installed);
|
||||||
previousFocus.keySet().retainAll(installed.keySet());
|
previousFocus.keySet().retainAll(installed.keySet());
|
||||||
activationOrder.keySet().retainAll(installed.keySet());
|
activationOrder.keySet().retainAll(installed.keySet());
|
||||||
|
floatingWindows.putAll(hosts);
|
||||||
|
for (DockLayoutCandidate candidate : candidates) {
|
||||||
|
FloatingWindow host = hosts.get(candidate.window.id());
|
||||||
|
DockPane destinationPane = host == null ? pane : host.pane;
|
||||||
|
DockLayoutTree destinationTree = host == null ? tree : host.tree;
|
||||||
|
DockDragController destinationDrag = host == null ? drag : host.drag;
|
||||||
for (Group group : candidate.groups()) {
|
for (Group group : candidate.groups()) {
|
||||||
groups.put(group.id, group);
|
groups.put(group.id, group);
|
||||||
|
if (host != null) groupWindows.put(group.id, host.id);
|
||||||
allocatedGroupIds.add(group.id);
|
allocatedGroupIds.add(group.id);
|
||||||
for (DockableId id : candidate.tabs(group.id)) {
|
for (DockableId id : candidate.tabs(group.id)) {
|
||||||
Tab tab = prepareTab(installed.get(id));
|
Tab tab = prepareTab(installed.get(id));
|
||||||
drag.installTab(tab, id);
|
destinationDrag.installTab(tab, id);
|
||||||
group.tabs.getTabs().add(tab);
|
group.tabs.getTabs().add(tab);
|
||||||
}
|
}
|
||||||
DockableId selected = candidate.selected(group.id);
|
DockableId selected = candidate.selected(group.id);
|
||||||
@@ -866,23 +1004,27 @@ public final class DockingManager {
|
|||||||
}
|
}
|
||||||
List<java.util.function.Consumer<Node>> placements = new java.util.ArrayList<>();
|
List<java.util.function.Consumer<Node>> placements = new java.util.ArrayList<>();
|
||||||
for (LayoutSnapshot.Root root : candidate.roots()) {
|
for (LayoutSnapshot.Root root : candidate.roots()) {
|
||||||
if (root.placement() == LayoutSnapshot.Placement.CENTER) placements.add(pane.surface::setCenter);
|
if (root.placement() == LayoutSnapshot.Placement.CENTER) placements.add(destinationPane.surface::setCenter);
|
||||||
else {
|
else {
|
||||||
javafx.geometry.Side side = javafx.geometry.Side.valueOf(root.placement().name());
|
javafx.geometry.Side side = javafx.geometry.Side.valueOf(root.placement().name());
|
||||||
DockAreaId areaId = root.branch().aliases().getFirst();
|
DockAreaId areaId = root.branch().aliases().getFirst();
|
||||||
root.branch().aliases().forEach(alias -> edgeAreas.put(alias, side));
|
Map<DockAreaId, javafx.geometry.Side> destinationEdges = host == null ? edgeAreas : host.edgeAreas;
|
||||||
|
root.branch().aliases().forEach(alias -> destinationEdges.put(alias, side));
|
||||||
placements.add(node -> {
|
placements.add(node -> {
|
||||||
pane.setArea(side, node, () -> canResizeEdge(areaId, side), this::publish);
|
destinationPane.setArea(side, node, () -> canResizeEdge(destinationPane, destinationTree,
|
||||||
pane.setAreaExtent(side, root.preferredWidth(), root.preferredHeight());
|
host == null ? null : host.id, areaId, side), this::publish);
|
||||||
|
destinationPane.setAreaExtent(side, root.preferredWidth(), root.preferredHeight());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tree.installFrom(candidate.tree, placements);
|
destinationTree.installFrom(candidate.tree, placements);
|
||||||
tree.view().forEach(area -> allocatedAreaIds.add(area.id()));
|
destinationTree.view().forEach(area -> allocatedAreaIds.add(area.id()));
|
||||||
|
}
|
||||||
refreshEmptyGroups();
|
refreshEmptyGroups();
|
||||||
Dockable desired = activeId == null ? null : installed.get(activeId);
|
Dockable desired = activeId == null ? null : installed.get(activeId);
|
||||||
if (desired != null && !isGroupVisible(containing(activeId))) desired = null;
|
if (desired != null && !isGroupVisible(containing(activeId))) desired = null;
|
||||||
setActive(desired == null ? selectedVisibleFallback() : desired);
|
setActive(desired == null ? selectedVisibleFallback() : desired);
|
||||||
|
if (stage.isShowing()) hosts.values().forEach(host -> host.stage.show());
|
||||||
focus(active.get());
|
focus(active.get());
|
||||||
} finally {
|
} finally {
|
||||||
updating = wasUpdating;
|
updating = wasUpdating;
|
||||||
@@ -903,11 +1045,16 @@ public final class DockingManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private boolean canResizeEdge(DockAreaId areaId, javafx.geometry.Side side) {
|
private boolean canResizeEdge(DockAreaId areaId, javafx.geometry.Side side) {
|
||||||
if (tree.groups(areaId).stream().anyMatch(this::groupClosing)) return false;
|
return canResizeEdge(pane, tree, null, areaId, side);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean canResizeEdge(DockPane ownerPane, DockLayoutTree ownerTree, DockWindowId ownerId,
|
||||||
|
DockAreaId areaId, javafx.geometry.Side side) {
|
||||||
|
if (ownerTree.groups(areaId).stream().anyMatch(this::groupClosing)) return false;
|
||||||
for (Group candidate : groups.values()) {
|
for (Group candidate : groups.values()) {
|
||||||
if (groupWindows.containsKey(candidate.id) || !groupClosing(candidate)) continue;
|
if (!Objects.equals(groupWindows.get(candidate.id), ownerId) || !groupClosing(candidate)) continue;
|
||||||
if (contains(pane.surface.getCenter(), ((DockGroupPane) candidate.tabs).surface())) return false;
|
if (contains(ownerPane.surface.getCenter(), ((DockGroupPane) candidate.tabs).surface())) return false;
|
||||||
javafx.geometry.Side otherSide = pane.edgeOf(candidate.tabs);
|
javafx.geometry.Side otherSide = ownerPane.edgeOf(candidate.tabs);
|
||||||
if (side.isHorizontal() && otherSide != null && otherSide.isVertical()) return false;
|
if (side.isHorizontal() && otherSide != null && otherSide.isVertical()) return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -923,13 +1070,19 @@ public final class DockingManager {
|
|||||||
if (!changingOuterExtent) return !groupClosing(group);
|
if (!changingOuterExtent) return !groupClosing(group);
|
||||||
}
|
}
|
||||||
if (treeFor(group).geometryAffects(group.id, this::groupClosing)) return false;
|
if (treeFor(group).geometryAffects(group.id, this::groupClosing)) return false;
|
||||||
if (groupWindows.containsKey(group.id)) return true;
|
DockWindowId windowId = groupWindows.get(group.id);
|
||||||
for (var entry : edgeAreas.entrySet()) {
|
FloatingWindow host = windowId == null ? null : floatingWindows.get(windowId);
|
||||||
List<Group> areaGroups = tree.groups(entry.getKey());
|
DockLayoutTree ownerTree = host == null ? tree : host.tree;
|
||||||
|
DockPane ownerPane = host == null ? pane : host.pane;
|
||||||
|
Map<DockAreaId, javafx.geometry.Side> ownerEdges = host == null ? edgeAreas : host.edgeAreas;
|
||||||
|
for (var entry : ownerEdges.entrySet()) {
|
||||||
|
List<Group> areaGroups = ownerTree.groups(entry.getKey());
|
||||||
if (!areaGroups.contains(group)) continue;
|
if (!areaGroups.contains(group)) continue;
|
||||||
boolean onlyExpandedGroup = areaGroups.stream().filter(candidate -> candidate != group)
|
boolean onlyExpandedGroup = areaGroups.stream().filter(candidate -> candidate != group)
|
||||||
.allMatch(candidate -> !candidate.tabs.isManaged() || ((DockGroupPane) candidate.tabs).isCollapsed());
|
.allMatch(candidate -> !candidate.tabs.isManaged() || ((DockGroupPane) candidate.tabs).isCollapsed());
|
||||||
if (changingOuterExtent || onlyExpandedGroup) return canResizeEdge(entry.getKey(), entry.getValue());
|
if (changingOuterExtent || onlyExpandedGroup) {
|
||||||
|
return canResizeEdge(ownerPane, ownerTree, windowId, entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -1035,7 +1188,7 @@ public final class DockingManager {
|
|||||||
Stage window = owner(containing(dockable.getId()));
|
Stage window = owner(containing(dockable.getId()));
|
||||||
window.getScene().getRoot().applyCss();
|
window.getScene().getRoot().applyCss();
|
||||||
window.getScene().getRoot().layout();
|
window.getScene().getRoot().layout();
|
||||||
if (window != stage && !window.isShowing()) window.show();
|
if (window != stage && stage.isShowing() && !window.isShowing()) window.show();
|
||||||
if (window.isShowing()) {
|
if (window.isShowing()) {
|
||||||
window.toFront();
|
window.toFront();
|
||||||
window.requestFocus();
|
window.requestFocus();
|
||||||
@@ -1103,29 +1256,16 @@ public final class DockingManager {
|
|||||||
} finally {
|
} finally {
|
||||||
updating = wasUpdating;
|
updating = wasUpdating;
|
||||||
}
|
}
|
||||||
var areas = tree.view().stream().map(area -> {
|
|
||||||
javafx.geometry.Side side = edgeAreas.get(area.id());
|
|
||||||
if (side == null) return area;
|
|
||||||
double extent = pane.committedExtent(side);
|
|
||||||
return new DockLayoutView.Area(area.id(), area.groups(), area.root(),
|
|
||||||
side.isVertical() ? extent : -1, side.isHorizontal() ? extent : -1);
|
|
||||||
}).toList();
|
|
||||||
var windows = new java.util.ArrayList<DockLayoutView.Window>();
|
var windows = new java.util.ArrayList<DockLayoutView.Window>();
|
||||||
windows.add(new DockLayoutView.Window(new DockWindowId("main"), true, areas));
|
windows.add(new DockLayoutView.Window(new DockWindowId("main"), true, layoutAreas(tree, pane, edgeAreas)));
|
||||||
floatingWindows.values().forEach(window -> windows.add(new DockLayoutView.Window(
|
floatingWindows.values().forEach(window -> windows.add(new DockLayoutView.Window(
|
||||||
window.id, false, window.tree.view(), window.geometry.bounds())));
|
window.id, false, layoutAreas(window.tree, window.pane, window.edgeAreas), window.geometry.bounds())));
|
||||||
List<LayoutSnapshot.Root> mainRoots = tree.snapshotRoots(edgeAreas, tree.isResizing() || pane.isResizing()).stream().map(root -> {
|
List<LayoutSnapshot.Root> mainRoots = snapshotRoots(tree, pane, edgeAreas, false);
|
||||||
if (root.placement() == LayoutSnapshot.Placement.CENTER) return root;
|
|
||||||
javafx.geometry.Side side = javafx.geometry.Side.valueOf(root.placement().name());
|
|
||||||
double extent = pane.committedExtent(side);
|
|
||||||
return new LayoutSnapshot.Root(root.placement(), side.isVertical() ? extent : -1,
|
|
||||||
side.isHorizontal() ? extent : -1, root.branch());
|
|
||||||
}).toList();
|
|
||||||
var snapshotWindows = new java.util.ArrayList<LayoutSnapshot.Window>();
|
var snapshotWindows = new java.util.ArrayList<LayoutSnapshot.Window>();
|
||||||
snapshotWindows.add(new LayoutSnapshot.Window(new DockWindowId("main"), true, null, mainRoots));
|
snapshotWindows.add(new LayoutSnapshot.Window(new DockWindowId("main"), true, null, mainRoots));
|
||||||
floatingWindows.values().forEach(window -> snapshotWindows.add(new LayoutSnapshot.Window(
|
floatingWindows.values().forEach(window -> snapshotWindows.add(new LayoutSnapshot.Window(
|
||||||
window.id, false, window.geometry.bounds(), window.tree.snapshotRoots(Map.of(),
|
window.id, false, window.geometry.bounds(), snapshotRoots(window.tree, window.pane, window.edgeAreas,
|
||||||
window.geometry.hasPendingChanges() || window.tree.isResizing() || window.pane.isResizing()))));
|
window.geometry.hasPendingChanges()))));
|
||||||
Map<DockableId, LayoutSnapshot.ReturnPosition> positions = new LinkedHashMap<>();
|
Map<DockableId, LayoutSnapshot.ReturnPosition> positions = new LinkedHashMap<>();
|
||||||
returnTargets.forEach((id, position) -> positions.put(id,
|
returnTargets.forEach((id, position) -> positions.put(id,
|
||||||
new LayoutSnapshot.ReturnPosition(position.target, position.areaId)));
|
new LayoutSnapshot.ReturnPosition(position.target, position.areaId)));
|
||||||
@@ -1134,6 +1274,29 @@ public final class DockingManager {
|
|||||||
layout.set(new DockLayoutView(windows));
|
layout.set(new DockLayoutView(windows));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static List<DockLayoutView.Area> layoutAreas(DockLayoutTree tree, DockPane pane,
|
||||||
|
Map<DockAreaId, javafx.geometry.Side> edges) {
|
||||||
|
return tree.view().stream().map(area -> {
|
||||||
|
javafx.geometry.Side side = edges.get(area.id());
|
||||||
|
if (side == null) return area;
|
||||||
|
double extent = pane.committedExtent(side);
|
||||||
|
return new DockLayoutView.Area(area.id(), area.groups(), area.root(),
|
||||||
|
side.isVertical() ? extent : -1, side.isHorizontal() ? extent : -1);
|
||||||
|
}).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<LayoutSnapshot.Root> snapshotRoots(DockLayoutTree tree, DockPane pane,
|
||||||
|
Map<DockAreaId, javafx.geometry.Side> edges,
|
||||||
|
boolean windowResizing) {
|
||||||
|
return tree.snapshotRoots(edges, windowResizing || tree.isResizing() || pane.isResizing()).stream().map(root -> {
|
||||||
|
if (root.placement() == LayoutSnapshot.Placement.CENTER) return root;
|
||||||
|
javafx.geometry.Side side = javafx.geometry.Side.valueOf(root.placement().name());
|
||||||
|
double extent = pane.committedExtent(side);
|
||||||
|
return new LayoutSnapshot.Root(root.placement(), side.isVertical() ? extent : -1,
|
||||||
|
side.isHorizontal() ? extent : -1, root.branch());
|
||||||
|
}).toList();
|
||||||
|
}
|
||||||
|
|
||||||
private Stage owner(Group group) {
|
private Stage owner(Group group) {
|
||||||
DockWindowId id = group == null ? null : groupWindows.get(group.id);
|
DockWindowId id = group == null ? null : groupWindows.get(group.id);
|
||||||
return id == null ? stage : floatingWindows.get(id).stage;
|
return id == null ? stage : floatingWindows.get(id).stage;
|
||||||
@@ -1168,6 +1331,24 @@ public final class DockingManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Group createFloatingGroup(javafx.geometry.Rectangle2D bounds) {
|
private Group createFloatingGroup(javafx.geometry.Rectangle2D bounds) {
|
||||||
|
DockWindowId candidateId;
|
||||||
|
do { candidateId = new DockWindowId("floating-" + ++nextWindowId); }
|
||||||
|
while (floatingWindows.containsKey(candidateId) || allocatedAreaIds.contains(new DockAreaId(candidateId.value())));
|
||||||
|
DockWindowId windowId = candidateId;
|
||||||
|
FloatingWindow host = prepareFloatingWindow(windowId, bounds);
|
||||||
|
allocatedAreaIds.add(new DockAreaId(windowId.value()));
|
||||||
|
DockGroupId groupId;
|
||||||
|
do { groupId = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(groupId));
|
||||||
|
DockGroupDefinition definition = new DockGroupDefinition(windowId.value());
|
||||||
|
definition.setPersistent(false);
|
||||||
|
Group group = createGroup(groupId, definition);
|
||||||
|
groupWindows.put(group.id, windowId);
|
||||||
|
host.tree.addArea(definition, host.pane.surface::setCenter, ignored -> group);
|
||||||
|
floatingWindows.put(windowId, host);
|
||||||
|
return group;
|
||||||
|
}
|
||||||
|
|
||||||
|
private FloatingWindow prepareFloatingWindow(DockWindowId windowId, javafx.geometry.Rectangle2D bounds) {
|
||||||
FloatingWindowConfiguration configuration = new FloatingWindowConfiguration();
|
FloatingWindowConfiguration configuration = new FloatingWindowConfiguration();
|
||||||
try {
|
try {
|
||||||
floatingWindowCustomizer.accept(configuration);
|
floatingWindowCustomizer.accept(configuration);
|
||||||
@@ -1176,10 +1357,6 @@ public final class DockingManager {
|
|||||||
} catch (RuntimeException failure) {
|
} catch (RuntimeException failure) {
|
||||||
throw new FloatingPreparationFailure(failure);
|
throw new FloatingPreparationFailure(failure);
|
||||||
}
|
}
|
||||||
DockWindowId candidateId;
|
|
||||||
do { candidateId = new DockWindowId("floating-" + ++nextWindowId); }
|
|
||||||
while (!allocatedAreaIds.add(new DockAreaId(candidateId.value())));
|
|
||||||
DockWindowId windowId = candidateId;
|
|
||||||
DockPane floatingPane = new DockPane();
|
DockPane floatingPane = new DockPane();
|
||||||
Stage floatingStage = new Stage();
|
Stage floatingStage = new Stage();
|
||||||
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
|
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
|
||||||
@@ -1191,27 +1368,21 @@ public final class DockingManager {
|
|||||||
floatingStage.setTitle(configuration.getTitle());
|
floatingStage.setTitle(configuration.getTitle());
|
||||||
floatingStage.getIcons().setAll(configuration.getIcons());
|
floatingStage.getIcons().setAll(configuration.getIcons());
|
||||||
floatingStage.getScene().getStylesheets().setAll(configuration.getStylesheets());
|
floatingStage.getScene().getStylesheets().setAll(configuration.getStylesheets());
|
||||||
|
DockStyles.install(floatingStage.getScene());
|
||||||
floatingStage.setX(bounds.getMinX());
|
floatingStage.setX(bounds.getMinX());
|
||||||
floatingStage.setY(bounds.getMinY());
|
floatingStage.setY(bounds.getMinY());
|
||||||
floatingStage.setWidth(bounds.getWidth());
|
floatingStage.setWidth(bounds.getWidth());
|
||||||
floatingStage.setHeight(bounds.getHeight());
|
floatingStage.setHeight(bounds.getHeight());
|
||||||
DockLayoutTree floatingTree = new DockLayoutTree(this::publish, id -> !groupClosing(group(id)));
|
DockLayoutTree floatingTree = new DockLayoutTree(this::publish, id -> !groupClosing(group(id)));
|
||||||
DockGroupId groupId;
|
|
||||||
do { groupId = new DockGroupId("group-" + ++nextGroupId); } while (allocatedGroupIds.contains(groupId));
|
|
||||||
DockGroupDefinition definition = new DockGroupDefinition(windowId.value());
|
|
||||||
definition.setPersistent(false);
|
|
||||||
Group group = createGroup(groupId, definition);
|
|
||||||
groupWindows.put(group.id, windowId);
|
|
||||||
floatingTree.addArea(definition, floatingPane.surface::setCenter, ignored -> group);
|
|
||||||
DockDragController floatingDrag = new DockDragController(this, floatingPane, () -> groups.values().stream()
|
DockDragController floatingDrag = new DockDragController(this, floatingPane, () -> groups.values().stream()
|
||||||
.filter(candidate -> windowId.equals(groupWindows.get(candidate.id)))
|
.filter(candidate -> windowId.equals(groupWindows.get(candidate.id)))
|
||||||
.map(candidate -> new DockDragController.GroupSurface(candidate.id, candidate.tabs)).toList());
|
.map(candidate -> new DockDragController.GroupSurface(candidate.id, candidate.tabs,
|
||||||
|
floatingPane.edgeOf(candidate.tabs))).toList());
|
||||||
DockWindowGeometry geometry = new DockWindowGeometry(floatingStage, this::publish);
|
DockWindowGeometry geometry = new DockWindowGeometry(floatingStage, this::publish);
|
||||||
floatingWindows.put(windowId, new FloatingWindow(windowId, floatingStage, floatingPane, floatingTree, floatingDrag, geometry, closeHandler));
|
|
||||||
floatingPane.manager = this;
|
floatingPane.manager = this;
|
||||||
floatingStage.getProperties().put(ATTACHMENT_KEY, this);
|
floatingStage.getProperties().put(ATTACHMENT_KEY, this);
|
||||||
floatingStage.getScene().focusOwnerProperty().addListener(focusListener);
|
floatingStage.getScene().focusOwnerProperty().addListener(focusListener);
|
||||||
return group;
|
return new FloatingWindow(windowId, floatingStage, floatingPane, floatingTree, floatingDrag, geometry, closeHandler, new LinkedHashMap<>());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class FloatingPreparationFailure extends RuntimeException {
|
private static final class FloatingPreparationFailure extends RuntimeException {
|
||||||
@@ -1220,7 +1391,8 @@ public final class DockingManager {
|
|||||||
|
|
||||||
private record FloatingWindow(DockWindowId id, Stage stage, DockPane pane, DockLayoutTree tree,
|
private record FloatingWindow(DockWindowId id, Stage stage, DockPane pane, DockLayoutTree tree,
|
||||||
DockDragController drag, DockWindowGeometry geometry,
|
DockDragController drag, DockWindowGeometry geometry,
|
||||||
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler) { }
|
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler,
|
||||||
|
Map<DockAreaId, javafx.geometry.Side> edgeAreas) { }
|
||||||
private record ReturnLocation(DockTarget target, DockAreaId areaId) { }
|
private record ReturnLocation(DockTarget target, DockAreaId areaId) { }
|
||||||
|
|
||||||
private static ActionResult rejected(DockFailure.Code code, DockableId id, String message) {
|
private static ActionResult rejected(DockFailure.Code code, DockableId id, String message) {
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ import java.util.Optional;
|
|||||||
/** Attachment options. Additional policies are introduced with their operations. */
|
/** Attachment options. Additional policies are introduced with their operations. */
|
||||||
@Getter @Setter
|
@Getter @Setter
|
||||||
public final class DockingOptions {
|
public final class DockingOptions {
|
||||||
|
private MainWindowCloseMode mainWindowCloseMode = MainWindowCloseMode.AUTOMATIC;
|
||||||
|
private java.util.function.Function<ShutdownRequest, java.util.concurrent.CompletionStage<ShutdownDecision>> beforeShutdown =
|
||||||
|
request -> java.util.concurrent.CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
|
||||||
/** String overrides for built-in labels, failure codes and application message keys; captured at attach. */
|
/** String overrides for built-in labels, failure codes and application message keys; captured at attach. */
|
||||||
private java.util.ResourceBundle resourceBundle;
|
private java.util.ResourceBundle resourceBundle;
|
||||||
private PlacementRule placementRule = (dockable, target) -> Optional.empty();
|
private PlacementRule placementRule = (dockable, target) -> Optional.empty();
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
/** Selects who handles and finally closes the main Stage. */
|
||||||
|
public enum MainWindowCloseMode { AUTOMATIC, APPLICATION_COORDINATED }
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
/** Final application decision after saving or retrying the pre-close snapshot. */
|
||||||
|
public enum ShutdownDecision { PROCEED, CANCEL }
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
/** Distinguishes closing the main window from replacing its embedded manager. */
|
||||||
|
public enum ShutdownReason { MAIN_WINDOW, MANAGER_ONLY }
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
/** Immutable pre-close state passed after every Dockable has consented. */
|
||||||
|
public record ShutdownRequest(LayoutSnapshot snapshot, ShutdownReason reason) {
|
||||||
|
public ShutdownRequest {
|
||||||
|
java.util.Objects.requireNonNull(snapshot, "snapshot");
|
||||||
|
java.util.Objects.requireNonNull(reason, "reason");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,3 +36,6 @@ dock.failure.CLOSE_CHECK_FAILED=The close check failed
|
|||||||
dock.failure.CLEANUP_FAILED=Resource release failed
|
dock.failure.CLEANUP_FAILED=Resource release failed
|
||||||
dock.failure.INVALID_WINDOW_BOUNDS=The window bounds are invalid
|
dock.failure.INVALID_WINDOW_BOUNDS=The window bounds are invalid
|
||||||
dock.failure.WINDOW_CREATION_FAILED=The floating window could not be prepared
|
dock.failure.WINDOW_CREATION_FAILED=The floating window could not be prepared
|
||||||
|
|
||||||
|
dock.failure.SHUTDOWN_CALLBACK_FAILED=The shutdown preparation failed
|
||||||
|
dock.failure.MANAGER_CLOSED=The docking manager has ended
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/* The text remains available to assistive technology while only the supplied icon is drawn. */
|
||||||
|
.dock-icon-only .tab-label {
|
||||||
|
-fx-content-display: graphic-only;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Scope defaults to docking surfaces; application styles are loaded afterward. */
|
||||||
|
.dock-edge-area {
|
||||||
|
-fx-background-color: -fx-background;
|
||||||
|
}
|
||||||
|
.dock-divider, .dock-area-divider {
|
||||||
|
-fx-background-color: -fx-box-border, -fx-inner-border;
|
||||||
|
-fx-background-insets: 0, 1;
|
||||||
|
}
|
||||||
|
.dock-drop-indicator {
|
||||||
|
-fx-fill: rgba(30, 144, 255, 0.18);
|
||||||
|
-fx-stroke: dodgerblue;
|
||||||
|
-fx-stroke-width: 2;
|
||||||
|
}
|
||||||
|
.dock-drop-indicator:no-change {
|
||||||
|
-fx-fill: rgba(100, 100, 100, 0.15);
|
||||||
|
-fx-stroke: gray;
|
||||||
|
}
|
||||||
|
.dock-floating-preview-frame {
|
||||||
|
-fx-fill: rgba(80, 140, 220, 0.16);
|
||||||
|
-fx-stroke: rgb(50, 110, 190);
|
||||||
|
}
|
||||||
|
.dock-floating-preview-label {
|
||||||
|
-fx-background-color: -fx-control-inner-background;
|
||||||
|
-fx-text-fill: -fx-text-base-color;
|
||||||
|
-fx-padding: 4 8;
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.property.SimpleStringProperty;
|
||||||
|
import javafx.scene.AccessibleAttribute;
|
||||||
|
import javafx.scene.Node;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.ContentDisplay;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.control.Labeled;
|
||||||
|
import javafx.scene.control.Tab;
|
||||||
|
import javafx.scene.control.TabPane;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Observes the public accessibility attributes and visible presentation of actual tab headers. */
|
||||||
|
class AccessibleDockTabsTest {
|
||||||
|
@BeforeAll
|
||||||
|
static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start();
|
||||||
|
FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void anIconOnlyTabKeepsItsAccessibleNameWhenBoundRenamedFloatedAndReturned() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
List<Window> existing = List.copyOf(Window.getWindows());
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 760, 480));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
|
Label icon = new Label("▦");
|
||||||
|
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project files"));
|
||||||
|
project.setIcon(icon);
|
||||||
|
SimpleStringProperty name = new SimpleStringProperty("Project files");
|
||||||
|
project.accessibleNameProperty().bind(name);
|
||||||
|
manager.open(project, DockTarget.area("editors"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
assertPresentation(project, icon, "Project files", true);
|
||||||
|
name.set("Project outline");
|
||||||
|
assertPresentation(project, icon, "Project outline", true);
|
||||||
|
manager.move(project.getId(), DockTarget.floating());
|
||||||
|
assertPresentation(project, icon, "Project outline", true);
|
||||||
|
manager.move(project.getId(), DockTarget.returnToMain());
|
||||||
|
assertPresentation(project, icon, "Project outline", true);
|
||||||
|
assertEquals("", project.getTitle());
|
||||||
|
project.setTitle("Visible title");
|
||||||
|
assertPresentation(project, icon, "Visible title", false);
|
||||||
|
assertEquals("Project outline", project.getAccessibleName());
|
||||||
|
} finally {
|
||||||
|
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void theCloseButtonsAccessibleActionNameUsesTheCapturedApplicationBundle() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
var existing = List.copyOf(Window.getWindows());
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 760, 480));
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setResourceBundle(new java.util.ListResourceBundle() {
|
||||||
|
@Override protected Object[][] getContents() {
|
||||||
|
return new Object[][] {{"dock.action.close", "Fermer le document"}};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, options);
|
||||||
|
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
|
||||||
|
notes.setTitle("Notes");
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
for (boolean floating : new boolean[]{false, true}) {
|
||||||
|
if (floating) manager.move(notes.getId(), DockTarget.floating());
|
||||||
|
var root = notes.getContent().getScene().getRoot();
|
||||||
|
root.applyCss(); root.layout();
|
||||||
|
Node close = root.lookup(".dock-tab-header .tab-close-button");
|
||||||
|
assertNotNull(close);
|
||||||
|
assertEquals("Fermer le document", close.queryAccessibleAttribute(AccessibleAttribute.TEXT));
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void assertPresentation(Dockable dockable, Node icon, String name, boolean iconOnly) {
|
||||||
|
var root = dockable.getContent().getScene().getRoot();
|
||||||
|
root.applyCss();
|
||||||
|
root.layout();
|
||||||
|
TabPane tabs = root.lookupAll(".tab-pane").stream().map(TabPane.class::cast)
|
||||||
|
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == dockable.getContent()))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
Tab tab = tabs.getTabs().stream().filter(candidate -> candidate.getContent() == dockable.getContent())
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
Node header = tabs.lookup("#" + tab.getId());
|
||||||
|
assertEquals(name, header.queryAccessibleAttribute(AccessibleAttribute.TEXT));
|
||||||
|
assertSame(icon, tab.getGraphic());
|
||||||
|
Labeled label = (Labeled) header.lookup(".tab-label");
|
||||||
|
assertEquals(iconOnly ? ContentDisplay.GRAPHIC_ONLY : ContentDisplay.LEFT, label.getContentDisplay());
|
||||||
|
assertTrue(header.getStyleClass().contains("dock-tab-header"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionStage;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Overlapping close entry points share consent and serialize global shutdown. */
|
||||||
|
class CoordinatedShutdownTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest @ValueSource(booleans = {false, true})
|
||||||
|
void mainShutdownWaitsForFloatingCloseAndDoesNotRepeatAVetoedRequest(boolean allow) throws Exception {
|
||||||
|
var fixture = new AtomicReference<Fixture>();
|
||||||
|
var consent = new CompletableFuture<CloseConsent>();
|
||||||
|
var floatingResult = new AtomicReference<CompletionStage<CloseResult>>();
|
||||||
|
var mainResult = new AtomicReference<CompletionStage<CloseResult>>();
|
||||||
|
List<String> asked = new ArrayList<>();
|
||||||
|
List<String> closed = new ArrayList<>();
|
||||||
|
List<CloseScope.Kind> scopes = new ArrayList<>();
|
||||||
|
AtomicInteger saves = new AtomicInteger();
|
||||||
|
try {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setBeforeShutdown(request -> {
|
||||||
|
assertTrue(Platform.isFxApplicationThread());
|
||||||
|
assertEquals(ShutdownReason.MAIN_WINDOW, request.reason());
|
||||||
|
assertEquals(allow ? 2 : 3, request.snapshot().windows().size());
|
||||||
|
saves.incrementAndGet();
|
||||||
|
return CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
|
||||||
|
});
|
||||||
|
Fixture f = fixture(options); fixture.set(f);
|
||||||
|
f.manager.closingScopeProperty().addListener((observable, old, current) -> {
|
||||||
|
if (current != null) scopes.add(current.kind());
|
||||||
|
});
|
||||||
|
for (Dockable dockable : List.of(f.mainContent, f.first, f.second)) {
|
||||||
|
dockable.setCloseCheck(request -> {
|
||||||
|
assertTrue(Platform.isFxApplicationThread());
|
||||||
|
assertSame(dockable.getContent().getScene().getWindow(), request.owner());
|
||||||
|
asked.add(dockable.getId().value());
|
||||||
|
return dockable == f.first ? consent : CompletableFuture.completedFuture(CloseConsent.ALLOW);
|
||||||
|
});
|
||||||
|
dockable.setOnClosed(() -> closed.add(dockable.getId().value()));
|
||||||
|
}
|
||||||
|
floatingResult.set(f.manager.requestFloatingWindowClose(f.firstWindow));
|
||||||
|
assertSame(floatingResult.get(), f.manager.requestFloatingWindowClose(f.firstWindow));
|
||||||
|
assertSame(floatingResult.get(), f.manager.requestTabClose(f.first.getId()));
|
||||||
|
mainResult.set(f.manager.requestMainWindowClose());
|
||||||
|
assertSame(mainResult.get(), f.manager.requestMainWindowClose());
|
||||||
|
assertFalse(mainResult.get().toCompletableFuture().isDone());
|
||||||
|
assertEquals(List.of("first"), asked);
|
||||||
|
assertEquals(CloseScope.Kind.FLOATING_WINDOW, f.manager.closingScopeProperty().get().kind());
|
||||||
|
assertEquals(0, saves.get());
|
||||||
|
assertTrue(closed.isEmpty());
|
||||||
|
});
|
||||||
|
CompletableFuture.runAsync(() -> consent.complete(allow ? CloseConsent.ALLOW : CloseConsent.VETO)).get();
|
||||||
|
// The queue continuation is scheduled by the FX-thread completion; drain two ordinary FX turns.
|
||||||
|
FxThread.onFx(() -> { });
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
Fixture f = fixture.get();
|
||||||
|
assertTrue(mainResult.get().toCompletableFuture().isDone(), "The queued shutdown must have settled");
|
||||||
|
if (allow) {
|
||||||
|
assertInstanceOf(CloseResult.Closed.class, floatingResult.get().toCompletableFuture().join());
|
||||||
|
assertInstanceOf(CloseResult.Closed.class, mainResult.get().toCompletableFuture().join());
|
||||||
|
assertEquals(List.of("first", "main", "second"), asked);
|
||||||
|
assertEquals(List.of("first", "main", "second"), closed);
|
||||||
|
assertEquals(1, saves.get());
|
||||||
|
assertFalse(f.stage.isShowing());
|
||||||
|
} else {
|
||||||
|
CloseResult veto = floatingResult.get().toCompletableFuture().join();
|
||||||
|
assertInstanceOf(CloseResult.Vetoed.class, veto);
|
||||||
|
assertEquals(veto, mainResult.get().toCompletableFuture().join());
|
||||||
|
assertEquals(List.of("first"), asked, "A waiting quit must not ask again after the floating veto");
|
||||||
|
assertEquals(List.of(CloseScope.Kind.FLOATING_WINDOW), scopes);
|
||||||
|
assertTrue(closed.isEmpty());
|
||||||
|
assertEquals(0, saves.get());
|
||||||
|
assertEquals(3, f.manager.layout().windows().size());
|
||||||
|
assertTrue(f.stage.isShowing());
|
||||||
|
f.first.setCloseCheck(request -> {
|
||||||
|
asked.add("first"); return CompletableFuture.completedFuture(CloseConsent.ALLOW);
|
||||||
|
});
|
||||||
|
asked.clear();
|
||||||
|
assertInstanceOf(CloseResult.Closed.class, f.manager.requestMainWindowClose().toCompletableFuture().join());
|
||||||
|
assertEquals(List.of("main", "first", "second"), asked, "A new explicit quit gets fresh consent");
|
||||||
|
assertEquals(1, saves.get());
|
||||||
|
}
|
||||||
|
assertNull(f.manager.closingScopeProperty().get());
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
if (fixture.get() != null) FxThread.onFx(fixture.get()::close);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@org.junit.jupiter.api.Test
|
||||||
|
void duplicatesShareTheFinalPublicationAndAQueuedQuitCannotSaveAnEndedManagerAgain() throws Exception {
|
||||||
|
var fixture = new AtomicReference<Fixture>();
|
||||||
|
var save = new CompletableFuture<ShutdownDecision>();
|
||||||
|
var managerResult = new AtomicReference<CompletionStage<CloseResult>>();
|
||||||
|
var queuedQuit = new AtomicReference<CompletionStage<CloseResult>>();
|
||||||
|
List<CompletionStage<CloseResult>> duplicates = new ArrayList<>();
|
||||||
|
List<CompletionStage<CloseResult>> coveredTabs = new ArrayList<>();
|
||||||
|
List<ShutdownReason> saves = new ArrayList<>();
|
||||||
|
try {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setBeforeShutdown(request -> { saves.add(request.reason()); return save; });
|
||||||
|
Fixture f = fixture(options); fixture.set(f);
|
||||||
|
f.manager.layoutProperty().addListener((observable, old, current) -> {
|
||||||
|
boolean empty = current.windows().stream().flatMap(window -> window.areas().stream())
|
||||||
|
.flatMap(area -> area.groups().stream()).allMatch(group -> group.dockableIds().isEmpty());
|
||||||
|
if (empty && f.manager.closingScopeProperty().get() != null) {
|
||||||
|
duplicates.add(f.manager.requestManagerClose());
|
||||||
|
coveredTabs.add(f.manager.requestTabClose(f.first.getId()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
managerResult.set(f.manager.requestManagerClose());
|
||||||
|
queuedQuit.set(f.manager.requestMainWindowClose());
|
||||||
|
assertFalse(queuedQuit.get().toCompletableFuture().isDone());
|
||||||
|
assertEquals(List.of(ShutdownReason.MANAGER_ONLY), saves);
|
||||||
|
});
|
||||||
|
CompletableFuture.runAsync(() -> save.complete(ShutdownDecision.PROCEED)).get();
|
||||||
|
FxThread.onFx(() -> { });
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
Fixture f = fixture.get();
|
||||||
|
assertTrue(managerResult.get().toCompletableFuture().isDone());
|
||||||
|
assertInstanceOf(CloseResult.Closed.class, managerResult.get().toCompletableFuture().join());
|
||||||
|
assertTrue(duplicates.size() >= 2, "Observe both content removal and final area release");
|
||||||
|
duplicates.forEach(answer -> assertSame(managerResult.get(), answer,
|
||||||
|
"A duplicate shares the pending outcome until the scope ends"));
|
||||||
|
coveredTabs.forEach(answer -> assertSame(managerResult.get(), answer));
|
||||||
|
assertTrue(queuedQuit.get().toCompletableFuture().isDone());
|
||||||
|
assertInstanceOf(CloseResult.NoChange.class, queuedQuit.get().toCompletableFuture().join());
|
||||||
|
assertEquals(List.of(ShutdownReason.MANAGER_ONLY), saves, "An ended manager cannot save an empty replacement snapshot");
|
||||||
|
assertTrue(f.stage.isShowing(), "The ended manager no longer owns main-window closure");
|
||||||
|
assertNull(f.manager.closingScopeProperty().get());
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
if (fixture.get() != null) FxThread.onFx(fixture.get()::close);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Fixture fixture(DockingOptions options) {
|
||||||
|
List<Window> existing = List.copyOf(Window.getWindows());
|
||||||
|
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
Stage stage = new Stage(); stage.setScene(new Scene(pane, 700, 500));
|
||||||
|
DockingManager manager = DockingManager.attach(stage, pane, options);
|
||||||
|
Dockable main = new Dockable(new DockableId("main"), new TextArea("Main"));
|
||||||
|
Dockable first = new Dockable(new DockableId("first"), new TextArea("First"));
|
||||||
|
Dockable second = new Dockable(new DockableId("second"), new TextArea("Second"));
|
||||||
|
manager.open(main, DockTarget.area("editors"));
|
||||||
|
manager.open(first, DockTarget.floating());
|
||||||
|
DockWindowId firstWindow = manager.layout().windows().stream().filter(window -> !window.main()).findFirst().orElseThrow().id();
|
||||||
|
manager.open(second, DockTarget.floating());
|
||||||
|
stage.show();
|
||||||
|
return new Fixture(stage, manager, main, first, second, firstWindow, existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Fixture(Stage stage, DockingManager manager, Dockable mainContent, Dockable first,
|
||||||
|
Dockable second, DockWindowId firstWindow, List<Window> existing) {
|
||||||
|
void close() { List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.event.Event;
|
||||||
|
import javafx.geometry.Bounds;
|
||||||
|
import javafx.scene.Node;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.scene.input.*;
|
||||||
|
import javafx.scene.layout.Region;
|
||||||
|
import javafx.scene.paint.Color;
|
||||||
|
import javafx.scene.shape.Rectangle;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class DockingThemeTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start();
|
||||||
|
FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void applicationThemeStylesHeadersAndBothDragPreviewsAcrossWindows() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
var existing = List.copyOf(Window.getWindows());
|
||||||
|
String theme = getClass().getResource("docking-theme.css").toExternalForm();
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 760, 460));
|
||||||
|
main.setX(80); main.setY(100);
|
||||||
|
main.getScene().getStylesheets().add(theme);
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setFloatingWindowCustomizer(configuration -> configuration.getStylesheets().add(theme));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, options);
|
||||||
|
Dockable notes = dockable("Notes"), tools = dockable("Tools");
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
manager.open(tools, DockTarget.area("tools"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
pane.applyCss(); pane.layout();
|
||||||
|
Node source = header(pane, "Notes");
|
||||||
|
assertHeaderColor(source);
|
||||||
|
Bounds from = source.localToScreen(source.getBoundsInLocal());
|
||||||
|
Bounds into = tools.getContent().localToScreen(tools.getContent().getBoundsInLocal());
|
||||||
|
mouse(source, MouseEvent.MOUSE_PRESSED, from.getCenterX(), from.getCenterY(), true);
|
||||||
|
mouse(source, MouseEvent.MOUSE_DRAGGED, into.getCenterX(), into.getCenterY(), true);
|
||||||
|
pane.applyCss();
|
||||||
|
Rectangle marker = (Rectangle) pane.lookup(".dock-drop-indicator");
|
||||||
|
assertTrue(marker.isVisible());
|
||||||
|
assertEquals(Color.web("#123456"), marker.getFill());
|
||||||
|
assertEquals(Color.web("#654321"), marker.getStroke());
|
||||||
|
mouse(source, MouseEvent.MOUSE_DRAGGED, into.getCenterX() + 2, into.getCenterY(), true);
|
||||||
|
pane.applyCss();
|
||||||
|
assertEquals(Color.web("#123456"), marker.getFill(), "Continuous drag preserves the application theme");
|
||||||
|
mouse(source, MouseEvent.MOUSE_DRAGGED, main.getX() + main.getWidth() + 60, main.getY() + 100, true);
|
||||||
|
Window preview = Window.getWindows().stream().filter(window -> window.getScene() != null
|
||||||
|
&& window.getScene().getRoot().lookup(".dock-floating-preview-frame") != null).findFirst().orElseThrow();
|
||||||
|
preview.getScene().getRoot().applyCss();
|
||||||
|
Rectangle frame = (Rectangle) preview.getScene().getRoot().lookup(".dock-floating-preview-frame");
|
||||||
|
assertEquals(Color.web("#234567"), frame.getFill());
|
||||||
|
assertEquals(Color.web("#765432"), frame.getStroke());
|
||||||
|
Event.fireEvent(main.getScene(), new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.ESCAPE,
|
||||||
|
false, false, false, false));
|
||||||
|
assertFalse(preview.isShowing());
|
||||||
|
manager.move(notes.getId(), DockTarget.floating());
|
||||||
|
var floatingRoot = notes.getContent().getScene().getRoot();
|
||||||
|
floatingRoot.applyCss(); floatingRoot.layout();
|
||||||
|
assertHeaderColor(header(floatingRoot, "Notes"));
|
||||||
|
} finally {
|
||||||
|
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
@Test void splitAndOuterDividersAreThemeableBeforeAnyPointerInteraction() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 1000, 600));
|
||||||
|
main.getScene().getStylesheets().add(getClass().getResource("docking-theme.css").toExternalForm());
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
|
Dockable notes = dockable("Notes"), other = dockable("Other");
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
manager.open(other, DockTarget.area("editors"));
|
||||||
|
manager.open(dockable("Tools"), DockTarget.area("tools"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
pane.applyCss(); pane.layout();
|
||||||
|
var group = manager.layout().windows().getFirst().areas().getFirst().groups().getFirst().id();
|
||||||
|
manager.move(other.getId(), DockTarget.split(group, javafx.geometry.Side.BOTTOM));
|
||||||
|
pane.applyCss(); pane.layout();
|
||||||
|
Node split = pane.lookup(".dock-divider");
|
||||||
|
assertNotNull(split, "A split exposes its theme hook before the user points at it");
|
||||||
|
assertEquals(Color.web("#345678"), ((Region) split).getBackground().getFills().getFirst().getFill());
|
||||||
|
Node outer = pane.lookup(".dock-area-divider");
|
||||||
|
assertNotNull(outer);
|
||||||
|
assertEquals(Color.web("#456789"), ((Region) outer).getBackground().getFills().getFirst().getFill());
|
||||||
|
assertFalse(pane.lookupAll(".dock-edge-area").isEmpty());
|
||||||
|
} finally { main.hide(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void assertHeaderColor(Node node) {
|
||||||
|
assertEquals(Color.web("#f1e2c3"), ((Region) node).getBackground().getFills().getFirst().getFill());
|
||||||
|
}
|
||||||
|
private static Dockable dockable(String name) {
|
||||||
|
Dockable result = new Dockable(new DockableId(name), new TextArea(name)); result.setTitle(name); return result;
|
||||||
|
}
|
||||||
|
private static Node header(Node root, String text) {
|
||||||
|
return root.lookupAll(".dock-tab-header").stream()
|
||||||
|
.filter(node -> node.lookup(".tab-label") instanceof Label label && text.equals(label.getText()))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
}
|
||||||
|
private static void mouse(Node source, javafx.event.EventType<MouseEvent> type, double x, double y, boolean down) {
|
||||||
|
var local = source.screenToLocal(x, y);
|
||||||
|
source.fireEvent(new MouseEvent(type, local.getX(), local.getY(), x, y, MouseButton.PRIMARY, 1,
|
||||||
|
false, false, false, false, down, false, false, false, false, false,
|
||||||
|
new PickResult(source, local.getX(), local.getY())));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.scene.Node;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.ContextMenu;
|
||||||
|
import javafx.scene.control.TabPane;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.scene.input.KeyCode;
|
||||||
|
import javafx.scene.input.KeyEvent;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Keyboard events enter through focused public controls and invoke the visible menu. */
|
||||||
|
class KeyboardDockActionsTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start();
|
||||||
|
FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void shiftF10OnTheSelectedTabOpensItsMenuAndFloatRestoresTheEditorFocus() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
var existing = List.copyOf(Window.getWindows());
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 760, 460));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
|
TextArea editor = new TextArea("abcdef");
|
||||||
|
Dockable notes = new Dockable(new DockableId("notes"), editor);
|
||||||
|
notes.setTitle("Notes");
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
pane.applyCss(); pane.layout();
|
||||||
|
editor.selectRange(2, 4);
|
||||||
|
TabPane tabs = (TabPane) pane.lookup(".dock-group");
|
||||||
|
tabs.requestFocus();
|
||||||
|
ContextMenu menu = tabs.getSelectionModel().getSelectedItem().getContextMenu();
|
||||||
|
key(tabs, KeyCode.F10, true);
|
||||||
|
assertTrue(menu.isShowing(), "Shift+F10 opens the selected docking tab's menu");
|
||||||
|
for (int index = 0; index < 4; index++) key(menu.getSkin().getNode(), KeyCode.DOWN, false);
|
||||||
|
key(menu.getSkin().getNode(), KeyCode.ENTER, false);
|
||||||
|
assertNotSame(main, editor.getScene().getWindow());
|
||||||
|
assertSame(editor, editor.getScene().getFocusOwner());
|
||||||
|
assertEquals("cd", editor.getSelectedText());
|
||||||
|
assertSame(notes, manager.activeDockable());
|
||||||
|
} finally {
|
||||||
|
for (Window window : List.copyOf(Window.getWindows())) if (!existing.contains(window)) window.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@org.junit.jupiter.params.ParameterizedTest
|
||||||
|
@org.junit.jupiter.params.provider.ValueSource(strings = {"Pin group", "Close"})
|
||||||
|
void commandsThatKeepContentOpenRestoreItsFocus(String action) throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
DockGroupDefinition tools = new DockGroupDefinition("tools");
|
||||||
|
tools.setCollapsible(true);
|
||||||
|
pane.getInitialLayout().setRight(tools);
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 760, 460));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
|
TextArea editor = new TextArea("Unsaved changes");
|
||||||
|
Dockable notes = new Dockable(new DockableId("notes"), editor);
|
||||||
|
notes.setTitle("Notes");
|
||||||
|
java.util.concurrent.atomic.AtomicInteger checks = new java.util.concurrent.atomic.AtomicInteger();
|
||||||
|
notes.setCloseCheck(request -> {
|
||||||
|
checks.incrementAndGet();
|
||||||
|
return java.util.concurrent.CompletableFuture.completedFuture(CloseConsent.VETO);
|
||||||
|
});
|
||||||
|
manager.open(notes, DockTarget.area("tools"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
pane.applyCss(); pane.layout();
|
||||||
|
TabPane tabs = (TabPane) pane.lookupAll(".dock-group").stream()
|
||||||
|
.filter(node -> ((TabPane) node).getTabs().stream().anyMatch(tab -> tab.getContent() == editor))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
tabs.requestFocus();
|
||||||
|
ContextMenu menu = tabs.getSelectionModel().getSelectedItem().getContextMenu();
|
||||||
|
key(tabs, KeyCode.CONTEXT_MENU, false);
|
||||||
|
assertTrue(menu.isShowing());
|
||||||
|
int count = action.equals("Pin group") ? 6 : 3;
|
||||||
|
for (int index = 0; index < count; index++) key(menu.getSkin().getNode(), KeyCode.DOWN, false);
|
||||||
|
key(menu.getSkin().getNode(), KeyCode.ENTER, false);
|
||||||
|
assertSame(notes, manager.findDockable(notes.getId()).orElseThrow());
|
||||||
|
if (action.equals("Pin group")) assertEquals(DockGroupMode.OVERLAY,
|
||||||
|
manager.layout().windows().getFirst().areas().get(1).groups().getFirst().mode());
|
||||||
|
else assertEquals(1, checks.get(), "Close uses the application's ordinary consent callback");
|
||||||
|
assertSame(editor, editor.getScene().getFocusOwner(), "The surviving editor can receive typing");
|
||||||
|
} finally { main.hide(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void aLateCloseVetoDoesNotTakeFocusBackFromAnotherActivatedEditor() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 760, 460));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
|
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Notes"));
|
||||||
|
notes.setTitle("Notes");
|
||||||
|
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme"));
|
||||||
|
readme.setTitle("Readme");
|
||||||
|
var consent = new java.util.concurrent.CompletableFuture<CloseConsent>();
|
||||||
|
notes.setCloseCheck(request -> consent);
|
||||||
|
manager.open(readme, DockTarget.area("tools"));
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
pane.applyCss(); pane.layout();
|
||||||
|
TabPane tabs = pane.lookupAll(".dock-group").stream().map(TabPane.class::cast)
|
||||||
|
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == notes.getContent()))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
tabs.requestFocus();
|
||||||
|
ContextMenu menu = tabs.getSelectionModel().getSelectedItem().getContextMenu();
|
||||||
|
key(tabs, KeyCode.F10, true);
|
||||||
|
for (int index = 0; index < 3; index++) key(menu.getSkin().getNode(), KeyCode.DOWN, false);
|
||||||
|
key(menu.getSkin().getNode(), KeyCode.ENTER, false);
|
||||||
|
assertNotNull(manager.closingScopeProperty().get());
|
||||||
|
manager.activate(readme.getId());
|
||||||
|
assertSame(readme.getContent(), main.getScene().getFocusOwner());
|
||||||
|
consent.complete(CloseConsent.VETO);
|
||||||
|
assertNull(manager.closingScopeProperty().get());
|
||||||
|
assertSame(readme, manager.activeDockable());
|
||||||
|
assertSame(readme.getContent(), main.getScene().getFocusOwner(),
|
||||||
|
"Completion must respect the user's intervening focus choice");
|
||||||
|
assertTrue(manager.findDockable(notes.getId()).isPresent());
|
||||||
|
} finally { consent.complete(CloseConsent.VETO); main.hide(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@org.junit.jupiter.params.ParameterizedTest
|
||||||
|
@org.junit.jupiter.params.provider.ValueSource(strings = {"Move", "Split"})
|
||||||
|
void submenuNavigationMovesOrSplitsTheSelectedEditor(String action) throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
pane.getInitialLayout().setRight(new DockGroupDefinition("tools"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 1000, 600));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
|
TextArea editor = new TextArea("abcdef");
|
||||||
|
Dockable notes = new Dockable(new DockableId("notes"), editor);
|
||||||
|
notes.setTitle("Notes");
|
||||||
|
Dockable readme = new Dockable(new DockableId("readme"), new TextArea("Readme"));
|
||||||
|
readme.setTitle("Readme");
|
||||||
|
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
|
||||||
|
project.setTitle("Project");
|
||||||
|
manager.open(readme, DockTarget.area("editors"));
|
||||||
|
manager.open(project, DockTarget.area("tools"));
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
pane.applyCss(); pane.layout();
|
||||||
|
editor.selectRange(2, 4);
|
||||||
|
TabPane tabs = pane.lookupAll(".dock-group").stream().map(TabPane.class::cast)
|
||||||
|
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == editor))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
tabs.requestFocus();
|
||||||
|
ContextMenu menu = tabs.getSelectionModel().getSelectedItem().getContextMenu();
|
||||||
|
key(tabs, KeyCode.F10, true);
|
||||||
|
key(menu.getSkin().getNode(), KeyCode.DOWN, false);
|
||||||
|
if (action.equals("Split")) key(menu.getSkin().getNode(), KeyCode.DOWN, false);
|
||||||
|
key(menu.getSkin().getNode(), KeyCode.RIGHT, false);
|
||||||
|
ContextMenu submenu = Window.getWindows().stream()
|
||||||
|
.filter(window -> window instanceof ContextMenu candidate && candidate != menu && candidate.isShowing())
|
||||||
|
.map(ContextMenu.class::cast).findFirst().orElseThrow();
|
||||||
|
if (action.equals("Move")) key(submenu.getSkin().getNode(), KeyCode.DOWN, false);
|
||||||
|
key(submenu.getSkin().getNode(), KeyCode.ENTER, false);
|
||||||
|
if (action.equals("Move")) {
|
||||||
|
var toolGroup = manager.layout().windows().getFirst().areas().get(1).groups().getFirst();
|
||||||
|
assertEquals(List.of(project.getId(), notes.getId()), toolGroup.dockableIds());
|
||||||
|
} else {
|
||||||
|
var editorArea = manager.layout().windows().getFirst().areas().getFirst();
|
||||||
|
assertInstanceOf(DockLayoutView.Split.class, editorArea.root());
|
||||||
|
assertEquals(2, editorArea.groups().size());
|
||||||
|
assertEquals(List.of(notes.getId()), editorArea.groups().getFirst().dockableIds());
|
||||||
|
}
|
||||||
|
assertSame(notes, manager.activeDockable());
|
||||||
|
assertSame(editor, editor.getScene().getFocusOwner());
|
||||||
|
assertEquals("cd", editor.getSelectedText());
|
||||||
|
} finally {
|
||||||
|
for (Window window : List.copyOf(Window.getWindows())) if (window instanceof ContextMenu) window.hide();
|
||||||
|
main.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void contentControlsKeepTheirOwnKeyboardContextMenus() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 760, 460));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
|
TextArea editor = new TextArea("Application editor");
|
||||||
|
ContextMenu editorMenu = new ContextMenu(new javafx.scene.control.MenuItem("Inspect editor"));
|
||||||
|
editor.setContextMenu(editorMenu);
|
||||||
|
java.util.concurrent.atomic.AtomicBoolean receivedShortcut = new java.util.concurrent.atomic.AtomicBoolean();
|
||||||
|
editor.setOnKeyPressed(event -> {
|
||||||
|
if (event.getCode() == KeyCode.F10 && event.isShiftDown()) receivedShortcut.set(true);
|
||||||
|
});
|
||||||
|
Dockable notes = new Dockable(new DockableId("notes"), editor);
|
||||||
|
notes.setTitle("Notes");
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
main.show();
|
||||||
|
try {
|
||||||
|
pane.applyCss(); pane.layout();
|
||||||
|
editor.requestFocus();
|
||||||
|
ContextMenu tabMenu = ((TabPane) pane.lookup(".dock-group"))
|
||||||
|
.getSelectionModel().getSelectedItem().getContextMenu();
|
||||||
|
key(editor, KeyCode.F10, true);
|
||||||
|
assertTrue(receivedShortcut.get(), "Docking does not consume content keyboard shortcuts");
|
||||||
|
assertFalse(tabMenu.isShowing());
|
||||||
|
var bounds = editor.localToScreen(editor.getBoundsInLocal());
|
||||||
|
editor.fireEvent(new javafx.scene.input.ContextMenuEvent(
|
||||||
|
javafx.scene.input.ContextMenuEvent.CONTEXT_MENU_REQUESTED, 4, 4,
|
||||||
|
bounds.getMinX() + 4, bounds.getMinY() + 4, true,
|
||||||
|
new javafx.scene.input.PickResult(editor, 4, 4)));
|
||||||
|
assertTrue(editorMenu.isShowing());
|
||||||
|
assertFalse(tabMenu.isShowing());
|
||||||
|
assertEquals("Inspect editor", editorMenu.getItems().getFirst().getText());
|
||||||
|
} finally { editorMenu.hide(); main.hide(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void key(Node target, KeyCode code, boolean shift) {
|
||||||
|
target.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", code, shift, false, false, false));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.ContextMenu;
|
||||||
|
import javafx.scene.control.TabPane;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.RepeatedTest;
|
||||||
|
import org.junit.jupiter.api.Timeout;
|
||||||
|
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||||
|
|
||||||
|
import java.awt.Robot;
|
||||||
|
import java.awt.event.KeyEvent;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Native keyboard delivery through the actual popup; requires the exclusive desktop slot. */
|
||||||
|
@EnabledIfSystemProperty(named = "neitzellib.nativeKeyboardTest", matches = "true")
|
||||||
|
class NativeKeyboardDockingTest {
|
||||||
|
private static final int[] KEYS = {KeyEvent.VK_DOWN, KeyEvent.VK_ENTER, KeyEvent.VK_1, KeyEvent.VK_2};
|
||||||
|
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start();
|
||||||
|
FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@RepeatedTest(3) @Timeout(25)
|
||||||
|
void shiftF10FloatAndReturnAllowImmediateTypingAtTheOriginalCaret() throws Exception {
|
||||||
|
Robot robot = new Robot();
|
||||||
|
robot.setAutoDelay(25);
|
||||||
|
AtomicReference<Fixture> reference = new AtomicReference<>();
|
||||||
|
AtomicReference<List<Window>> existing = new AtomicReference<>();
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
existing.set(List.copyOf(Window.getWindows()));
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 760, 460));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
||||||
|
TextArea editor = new TextArea("abcdef");
|
||||||
|
Dockable notes = new Dockable(new DockableId("notes"), editor);
|
||||||
|
notes.setTitle("Notes");
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
main.show();
|
||||||
|
manager.activate(notes.getId());
|
||||||
|
editor.selectRange(2, 4);
|
||||||
|
reference.set(new Fixture(main, editor, manager, notes, new javafx.scene.robot.Robot()));
|
||||||
|
});
|
||||||
|
Fixture fixture = reference.get();
|
||||||
|
try {
|
||||||
|
openMenuByNativeKeyboard(robot, fixture, "Float");
|
||||||
|
await(() -> fixture.editor.getScene().getWindow() != fixture.main, "Float was not invoked by the keyboard");
|
||||||
|
typeWithoutFocusRepair(robot, fixture, KeyEvent.VK_1, "ab1ef");
|
||||||
|
openMenuByNativeKeyboard(robot, fixture, "Return to main");
|
||||||
|
await(() -> fixture.editor.getScene().getWindow() == fixture.main, "Return was not invoked by the keyboard");
|
||||||
|
typeWithoutFocusRepair(robot, fixture, KeyEvent.VK_2, "ab12ef");
|
||||||
|
FxThread.onFx(() -> assertSame(fixture.notes, fixture.manager.activeDockable()));
|
||||||
|
} finally {
|
||||||
|
for (int key : KEYS) robot.keyRelease(key);
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
fixture.keyboard.keyRelease(javafx.scene.input.KeyCode.F10);
|
||||||
|
fixture.keyboard.keyRelease(javafx.scene.input.KeyCode.SHIFT);
|
||||||
|
for (Window window : List.copyOf(Window.getWindows())) if (!existing.get().contains(window)) window.hide();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void openMenuByNativeKeyboard(Robot robot, Fixture fixture, String action) throws Exception {
|
||||||
|
AtomicReference<TabPane> selectedTabs = new AtomicReference<>();
|
||||||
|
AtomicReference<ContextMenu> menu = new AtomicReference<>();
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
var root = fixture.editor.getScene().getRoot();
|
||||||
|
root.applyCss(); root.layout();
|
||||||
|
TabPane tabs = root.lookupAll(".dock-group").stream().map(TabPane.class::cast)
|
||||||
|
.filter(candidate -> candidate.getTabs().stream().anyMatch(tab -> tab.getContent() == fixture.editor))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
// Start the command from its tab strip. Never repair content focus after the command.
|
||||||
|
tabs.requestFocus();
|
||||||
|
selectedTabs.set(tabs);
|
||||||
|
menu.set(tabs.getSelectionModel().getSelectedItem().getContextMenu());
|
||||||
|
});
|
||||||
|
await(() -> fixture.editor.getScene().getWindow().isFocused()
|
||||||
|
&& fixture.editor.getScene().getFocusOwner() == selectedTabs.get(), "The tab strip did not receive native focus");
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
try {
|
||||||
|
fixture.keyboard.keyPress(javafx.scene.input.KeyCode.SHIFT);
|
||||||
|
fixture.keyboard.keyPress(javafx.scene.input.KeyCode.F10);
|
||||||
|
} finally {
|
||||||
|
fixture.keyboard.keyRelease(javafx.scene.input.KeyCode.F10);
|
||||||
|
fixture.keyboard.keyRelease(javafx.scene.input.KeyCode.SHIFT);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await(() -> menu.get().isShowing(), "Native Shift+F10 did not open the tab menu");
|
||||||
|
for (int step = 0; step < 7; step++) {
|
||||||
|
AtomicReference<String> selected = new AtomicReference<>();
|
||||||
|
FxThread.onFx(() -> selected.set(focusedAction(menu.get())));
|
||||||
|
if (action.equals(selected.get())) break;
|
||||||
|
press(robot, KeyEvent.VK_DOWN);
|
||||||
|
await(() -> !java.util.Objects.equals(selected.get(), focusedAction(menu.get())),
|
||||||
|
"The arrow key did not move the menu selection");
|
||||||
|
}
|
||||||
|
FxThread.onFx(() -> assertEquals(action, focusedAction(menu.get()),
|
||||||
|
"Enter must execute the visibly focused intended action"));
|
||||||
|
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 void typeWithoutFocusRepair(Robot robot, Fixture fixture, int key, String expected) throws Exception {
|
||||||
|
await(() -> fixture.editor.getScene().getWindow().isFocused()
|
||||||
|
&& fixture.editor.getScene().getFocusOwner() == fixture.editor,
|
||||||
|
"The menu transfer did not restore content/native window focus");
|
||||||
|
press(robot, key);
|
||||||
|
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
|
||||||
|
AtomicReference<String> actual = new AtomicReference<>();
|
||||||
|
do {
|
||||||
|
Thread.sleep(25);
|
||||||
|
FxThread.onFx(() -> actual.set(fixture.editor.getText()));
|
||||||
|
} while (!expected.equals(actual.get()) && System.nanoTime() < deadline);
|
||||||
|
assertEquals(expected, actual.get(), "Native typing continues at the transferred editor caret");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void press(Robot robot, int key) {
|
||||||
|
try { robot.keyPress(key); } finally { robot.keyRelease(key); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void await(BooleanSupplier condition, String failure) throws Exception {
|
||||||
|
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
|
||||||
|
AtomicReference<Boolean> ready = new AtomicReference<>(false);
|
||||||
|
do {
|
||||||
|
Thread.sleep(25);
|
||||||
|
FxThread.onFx(() -> ready.set(condition.getAsBoolean()));
|
||||||
|
} while (!ready.get() && System.nanoTime() < deadline);
|
||||||
|
assertTrue(ready.get(), failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Fixture(Stage main, TextArea editor, DockingManager manager, Dockable notes,
|
||||||
|
javafx.scene.robot.Robot keyboard) { }
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class PartialRestoreTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
|
||||||
|
|
||||||
|
@ParameterizedTest @ValueSource(booleans = {false, true})
|
||||||
|
void missingBranchesNormalizeInBothDirectionsWhilePersistentSideDestinationsRemainReachable(boolean missingLeft) throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockSplitDefinition pair = split("pair", new DockGroupDefinition("middle"), new DockGroupDefinition("right"));
|
||||||
|
DockLayout definition = new DockLayout();
|
||||||
|
definition.setCenter(split("editors", new DockGroupDefinition("left"), pair));
|
||||||
|
DockGroupDefinition tools = new DockGroupDefinition("tools");
|
||||||
|
tools.setVisibleWhenEmpty(false); tools.setReleaseSpaceWhenEmpty(true); definition.setRight(tools);
|
||||||
|
DockGroupDefinition scratch = new DockGroupDefinition("scratch");
|
||||||
|
scratch.setPersistent(false); definition.setTop(scratch);
|
||||||
|
DockingManager original = RestoreValidationTest.manager(definition);
|
||||||
|
for (String[] entry : new String[][]{{"a", "left"}, {"b", "middle"}, {"c", "right"}, {"tool", "tools"}, {"scratch", "scratch"}}) {
|
||||||
|
original.open(new Dockable(new DockableId(entry[0]), new TextArea(entry[0])), DockTarget.area(entry[1]));
|
||||||
|
}
|
||||||
|
LayoutSnapshot saved = original.snapshot();
|
||||||
|
Set<String> missing = missingLeft ? Set.of("a", "tool", "scratch") : Set.of("b", "c", "tool", "scratch");
|
||||||
|
DockLayout starting = new DockLayout(); starting.setCenter(new DockGroupDefinition("start"));
|
||||||
|
DockingManager restored = RestoreValidationTest.manager(starting);
|
||||||
|
RestoreResult.Applied result = assertInstanceOf(RestoreResult.Applied.class, restored.restore(saved, id ->
|
||||||
|
missing.contains(id.value()) ? new DockableResolution.Missing()
|
||||||
|
: new DockableResolution.Available(new Dockable(id, new TextArea("Reloaded " + id.value())))));
|
||||||
|
assertEquals((missingLeft ? List.of("a", "tool", "scratch") : List.of("b", "c", "tool", "scratch"))
|
||||||
|
.stream().map(DockableId::new).toList(), result.missingIds());
|
||||||
|
for (String id : missing) assertTrue(restored.findDockable(new DockableId(id)).isEmpty());
|
||||||
|
LayoutSnapshot.Window window = restored.snapshot().windows().getFirst();
|
||||||
|
assertEquals(2, window.roots().size(), "The nonpersistent empty standalone root disappears");
|
||||||
|
LayoutSnapshot.Branch center = window.roots().stream().filter(root -> root.placement() == LayoutSnapshot.Placement.CENTER)
|
||||||
|
.findFirst().orElseThrow().branch();
|
||||||
|
if (missingLeft) assertInstanceOf(LayoutSnapshot.Split.class, center);
|
||||||
|
else assertInstanceOf(LayoutSnapshot.Group.class, center);
|
||||||
|
DockableId survivor = new DockableId(missingLeft ? "b" : "a");
|
||||||
|
for (String area : List.of("editors", "left", "pair", "middle", "right")) {
|
||||||
|
assertFalse(restored.checkMove(survivor, DockTarget.area(area)) instanceof MoveCheck.Rejected,
|
||||||
|
"Normalized area remains addressable: " + area);
|
||||||
|
}
|
||||||
|
assertInstanceOf(MoveCheck.Allowed.class, restored.checkMove(survivor, DockTarget.area("tools")));
|
||||||
|
assertEquals(DockFailure.Code.TARGET_NOT_FOUND,
|
||||||
|
assertInstanceOf(MoveCheck.Rejected.class, restored.checkMove(survivor, DockTarget.area("scratch"))).failure().code());
|
||||||
|
LayoutSnapshot.Group emptyTools = (LayoutSnapshot.Group) window.roots().stream()
|
||||||
|
.filter(root -> root.placement() == LayoutSnapshot.Placement.RIGHT).findFirst().orElseThrow().branch();
|
||||||
|
assertTrue(emptyTools.tabs().isEmpty());
|
||||||
|
assertTrue(emptyTools.settings().persistent());
|
||||||
|
DockingManager nextStartup = RestoreValidationTest.manager(starting);
|
||||||
|
assertTrue(assertInstanceOf(RestoreResult.Applied.class, nextStartup.restore(restored.snapshot(), id ->
|
||||||
|
new DockableResolution.Available(new Dockable(id, new TextArea("Next startup"))))).missingIds().isEmpty(),
|
||||||
|
"Omitted identities cannot leave invalid references in the next saved snapshot");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockSplitDefinition split(String id, DockLayoutNode first, DockLayoutNode second) {
|
||||||
|
DockSplitDefinition split = new DockSplitDefinition(); split.setDestinationId(id);
|
||||||
|
split.setFirst(first); split.setSecond(second); return split;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class RestoreFallbackTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws InterruptedException { FxThread.start(); }
|
||||||
|
|
||||||
|
@ParameterizedTest @ValueSource(booleans = {false, true})
|
||||||
|
void changedRulesUseTheDesignatedRelativeFallbackAfterEveryIdentityIsResolved(boolean movingFirst) throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
LayoutSnapshot saved = RestoreValidationTest.saved();
|
||||||
|
DockableId moved = new DockableId(movingFirst ? "a" : "b");
|
||||||
|
DockableId anchor = new DockableId(movingFirst ? "b" : "a");
|
||||||
|
DockGroupId receiver = new DockGroupId(movingFirst ? "preview" : "primary");
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setFallbackTarget(DockTarget.group(receiver, TabPosition.before(anchor)));
|
||||||
|
options.setPlacementRule((dockable, target) -> dockable.getId().equals(moved)
|
||||||
|
&& !((ResolvedDockTarget.Insertion) target).groupId().equals(receiver)
|
||||||
|
? Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, moved, "Saved group is no longer allowed", null))
|
||||||
|
: Optional.empty());
|
||||||
|
DockingManager manager = manager(options);
|
||||||
|
List<DockableId> requested = new ArrayList<>();
|
||||||
|
RestoreResult.Applied applied = assertInstanceOf(RestoreResult.Applied.class, manager.restore(saved, id -> {
|
||||||
|
requested.add(id);
|
||||||
|
return new DockableResolution.Available(new Dockable(id, new TextArea("Reloaded " + id.value())));
|
||||||
|
}));
|
||||||
|
assertTrue(applied.missingIds().isEmpty());
|
||||||
|
assertEquals(List.of(new DockableId("a"), new DockableId("b")), requested,
|
||||||
|
"Moving to a later-resolved anchor cannot resolve or construct a Dockable twice");
|
||||||
|
LayoutSnapshot.Group group = assertInstanceOf(LayoutSnapshot.Group.class,
|
||||||
|
manager.snapshot().windows().getFirst().roots().getFirst().branch());
|
||||||
|
assertEquals(List.of(moved, anchor), group.tabs());
|
||||||
|
assertEquals(receiver, group.id());
|
||||||
|
assertEquals(new DockableId("b"), group.selected());
|
||||||
|
assertEquals(new DockableId("b"), manager.activeDockable().getId());
|
||||||
|
assertFalse(manager.checkMove(anchor, DockTarget.area(movingFirst ? "primary" : "preview")) instanceof MoveCheck.Rejected,
|
||||||
|
"The emptied saved destination remains a stable alias of the surviving group");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest @ValueSource(strings = {"absent", "missing", "denied", "throws"})
|
||||||
|
void anUnusableFallbackAbortsTheWholeRestoreAndKeepsCleanupFailuresSeparate(String fallback) throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
LayoutSnapshot saved = RestoreValidationTest.saved();
|
||||||
|
RuntimeException policyFailure = new IllegalStateException("Fallback policy failed");
|
||||||
|
RuntimeException cleanupFailure = new IllegalArgumentException("Cleanup A failed");
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
if (!fallback.equals("absent")) options.setFallbackTarget(DockTarget.area(fallback.equals("missing") ? "unknown" : "primary"));
|
||||||
|
options.setPlacementRule((dockable, target) -> {
|
||||||
|
if (dockable.getId().value().equals("a")) return Optional.empty();
|
||||||
|
if (fallback.equals("throws") && ((ResolvedDockTarget.Insertion) target).groupId().value().equals("primary")) throw policyFailure;
|
||||||
|
return Optional.of(new DockFailure(DockFailure.Code.PLACEMENT_REJECTED, dockable.getId(), "No eligible group", null, "app.no-group"));
|
||||||
|
});
|
||||||
|
DockingManager manager = manager(options);
|
||||||
|
var before = manager.layout(); var beforeSnapshot = manager.snapshot();
|
||||||
|
AtomicInteger discarded = new AtomicInteger();
|
||||||
|
RestoreResult.Rejected rejected = assertInstanceOf(RestoreResult.Rejected.class, manager.restore(saved, id -> {
|
||||||
|
Dockable dockable = new Dockable(id, new TextArea(id.value()));
|
||||||
|
dockable.setOnDiscarded(() -> { discarded.incrementAndGet(); if (id.value().equals("a")) throw cleanupFailure; });
|
||||||
|
return new DockableResolution.Available(dockable);
|
||||||
|
}));
|
||||||
|
assertEquals(new DockableId("b"), rejected.failure().dockableId());
|
||||||
|
assertEquals(switch (fallback) {
|
||||||
|
case "missing" -> DockFailure.Code.TARGET_NOT_FOUND;
|
||||||
|
case "throws" -> DockFailure.Code.PLACEMENT_CHECK_FAILED;
|
||||||
|
default -> DockFailure.Code.PLACEMENT_REJECTED;
|
||||||
|
}, rejected.failure().code());
|
||||||
|
if (fallback.equals("throws")) assertSame(policyFailure, rejected.failure().cause());
|
||||||
|
if (fallback.equals("absent") || fallback.equals("denied")) assertEquals("app.no-group", rejected.failure().messageKey());
|
||||||
|
assertEquals(2, discarded.get());
|
||||||
|
assertEquals(1, rejected.cleanupFailures().size());
|
||||||
|
assertSame(cleanupFailure, rejected.cleanupFailures().getFirst().cause());
|
||||||
|
assertSame(before, manager.layout());
|
||||||
|
assertEquals(beforeSnapshot, manager.snapshot());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockingManager manager(DockingOptions options) {
|
||||||
|
DockLayout initial = new DockLayout(); initial.setCenter(new DockGroupDefinition("start"));
|
||||||
|
DockPane pane = new DockPane(); pane.setInitialLayout(initial);
|
||||||
|
Stage stage = new Stage(); stage.setScene(new Scene(pane, 900, 600));
|
||||||
|
return DockingManager.attach(stage, pane, options);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.geometry.Rectangle2D;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class RestoreFloatingFailureTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void aLaterCustomizerFailureDiscardsAllPreparedContentsAndNeverShowsPreparedHosts() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
List<Window> existing = List.copyOf(Window.getWindows());
|
||||||
|
Stage source = new Stage(); Stage target = new Stage();
|
||||||
|
try {
|
||||||
|
DockingManager original = attach(source, new DockingOptions());
|
||||||
|
for (String name : List.of("first", "second")) {
|
||||||
|
DockableId id = new DockableId(name);
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.open(new Dockable(id, new TextArea(name)), DockTarget.area("editors")));
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.move(id, DockTarget.floating(new Rectangle2D(100, 100, 400, 300))));
|
||||||
|
}
|
||||||
|
LayoutSnapshot saved = original.snapshot();
|
||||||
|
RuntimeException creationFailure = new IllegalStateException("second floating host");
|
||||||
|
RuntimeException cleanupFailure = new IllegalStateException("first prepared content cleanup");
|
||||||
|
AtomicInteger customized = new AtomicInteger();
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setFloatingWindowCustomizer(configuration -> {
|
||||||
|
if (customized.incrementAndGet() == 2) throw creationFailure;
|
||||||
|
});
|
||||||
|
DockingManager restored = attach(target, options);
|
||||||
|
LayoutSnapshot before = restored.snapshot(); var layoutBefore = restored.layout();
|
||||||
|
List<DockableId> discarded = new ArrayList<>(); List<Dockable> prepared = new ArrayList<>();
|
||||||
|
AtomicInteger closed = new AtomicInteger(); AtomicInteger publications = new AtomicInteger();
|
||||||
|
restored.layoutProperty().addListener((observable, old, current) -> publications.incrementAndGet());
|
||||||
|
RestoreResult.Rejected result = assertInstanceOf(RestoreResult.Rejected.class, restored.restore(saved, id -> {
|
||||||
|
Dockable dockable = new Dockable(id, new TextArea("fresh " + id.value()));
|
||||||
|
dockable.setOnClosed(closed::incrementAndGet);
|
||||||
|
dockable.setOnDiscarded(() -> {
|
||||||
|
discarded.add(id);
|
||||||
|
if (id.value().equals("first")) throw cleanupFailure;
|
||||||
|
});
|
||||||
|
prepared.add(dockable); return new DockableResolution.Available(dockable);
|
||||||
|
}));
|
||||||
|
assertEquals(2, customized.get());
|
||||||
|
assertEquals(DockFailure.Code.WINDOW_CREATION_FAILED, result.failure().code());
|
||||||
|
assertSame(creationFailure, result.failure().cause());
|
||||||
|
assertEquals(List.of(new DockableId("first"), new DockableId("second")), discarded);
|
||||||
|
assertEquals(1, result.cleanupFailures().size());
|
||||||
|
assertSame(cleanupFailure, result.cleanupFailures().getFirst().cause());
|
||||||
|
assertEquals(0, closed.get()); assertEquals(0, publications.get());
|
||||||
|
assertSame(before, restored.snapshot()); assertSame(layoutBefore, restored.layout());
|
||||||
|
prepared.forEach(dockable -> {
|
||||||
|
assertNull(dockable.getContent().getParent()); assertNull(dockable.getContent().getScene());
|
||||||
|
});
|
||||||
|
target.show();
|
||||||
|
assertEquals(List.of(target), Window.getWindows().stream().filter(window -> !existing.contains(window)).toList(),
|
||||||
|
"The main shown hook must not resurrect any prepared floating host after failure");
|
||||||
|
} finally {
|
||||||
|
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
|
||||||
|
source.hide(); target.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockingManager attach(Stage stage, DockingOptions options) {
|
||||||
|
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
stage.setScene(new Scene(pane, 700, 500)); return DockingManager.attach(stage, pane, options);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.geometry.Rectangle2D;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class RestoreFloatingFallbackTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest @ValueSource(booleans = {true, false})
|
||||||
|
void changedMainOnlyAndMissingContentsNeverCreateAnEmptyFloatingHost(boolean designatedFallback) throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
List<Window> existing = List.copyOf(Window.getWindows());
|
||||||
|
Stage source = new Stage(); Stage target = new Stage();
|
||||||
|
try {
|
||||||
|
DockingManager original = attach(source, new DockingOptions());
|
||||||
|
DockableId project = new DockableId("project");
|
||||||
|
DockableId preview = new DockableId("preview");
|
||||||
|
for (DockableId id : List.of(project, preview)) {
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.open(new Dockable(id, new TextArea(id.value())), DockTarget.area("editors")));
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.move(id, DockTarget.floating(new Rectangle2D(100, 100, 400, 300))));
|
||||||
|
}
|
||||||
|
LayoutSnapshot saved = original.snapshot();
|
||||||
|
AtomicInteger customized = new AtomicInteger(); AtomicInteger discarded = new AtomicInteger();
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
if (designatedFallback) options.setFallbackTarget(DockTarget.area("editors"));
|
||||||
|
options.setFloatingWindowCustomizer(configuration -> customized.incrementAndGet());
|
||||||
|
DockingManager restored = attach(target, options);
|
||||||
|
LayoutSnapshot before = restored.snapshot();
|
||||||
|
AtomicReference<Dockable> prepared = new AtomicReference<>();
|
||||||
|
RestoreResult result = restored.restore(saved, id -> {
|
||||||
|
if (id.equals(preview)) return new DockableResolution.Missing();
|
||||||
|
Dockable dockable = new Dockable(id, new TextArea("fresh project"));
|
||||||
|
dockable.setMainWindowOnly(true); dockable.setOnDiscarded(discarded::incrementAndGet);
|
||||||
|
prepared.set(dockable); return new DockableResolution.Available(dockable);
|
||||||
|
});
|
||||||
|
assertEquals(0, customized.get(), "Omitted windows are not prepared or customized");
|
||||||
|
assertEquals(1, restored.layout().windows().size());
|
||||||
|
if (designatedFallback) {
|
||||||
|
assertEquals(List.of(preview), assertInstanceOf(RestoreResult.Applied.class, result).missingIds());
|
||||||
|
assertSame(target, prepared.get().getContent().getScene().getWindow());
|
||||||
|
assertSame(prepared.get(), restored.activeDockable());
|
||||||
|
assertEquals(0, discarded.get());
|
||||||
|
} else {
|
||||||
|
DockFailure failure = assertInstanceOf(RestoreResult.Rejected.class, result).failure();
|
||||||
|
assertEquals(DockFailure.Code.MAIN_WINDOW_ONLY, failure.code());
|
||||||
|
assertEquals(project, failure.dockableId());
|
||||||
|
assertSame(before, restored.snapshot());
|
||||||
|
assertNull(prepared.get().getContent().getParent());
|
||||||
|
assertEquals(1, discarded.get());
|
||||||
|
}
|
||||||
|
target.show();
|
||||||
|
assertEquals(1, restored.layout().windows().size());
|
||||||
|
} finally {
|
||||||
|
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
|
||||||
|
source.hide(); target.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockingManager attach(Stage stage, DockingOptions options) {
|
||||||
|
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
stage.setScene(new Scene(pane, 700, 500)); return DockingManager.attach(stage, pane, options);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.geometry.Rectangle2D;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Screen;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class RestoreFloatingGeometryTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void newAndRestoredHostsWaitForMainAndOffscreenFramesFitTheCurrentDisplay() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
List<Window> existing = List.copyOf(Window.getWindows());
|
||||||
|
Stage source = new Stage(); Stage target = new Stage();
|
||||||
|
try {
|
||||||
|
DockingManager original = attach(source);
|
||||||
|
DockableId id = new DockableId("notes");
|
||||||
|
Dockable notes = new Dockable(id, new TextArea("source"));
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.open(notes, DockTarget.area("editors")));
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.move(id, DockTarget.floating(new Rectangle2D(100, 100, 400, 300))));
|
||||||
|
Stage originalHost = (Stage) notes.getContent().getScene().getWindow();
|
||||||
|
assertFalse(originalHost.isShowing(), "New floating hosts also wait for main startup");
|
||||||
|
source.show(); assertTrue(originalHost.isShowing());
|
||||||
|
LayoutSnapshot saved = original.snapshot();
|
||||||
|
var visual = Screen.getPrimary().getVisualBounds();
|
||||||
|
Rectangle2D unavailable = new Rectangle2D(100_000, -100_000, visual.getWidth() + 500, visual.getHeight() + 500);
|
||||||
|
LayoutSnapshot offscreen = new LayoutSnapshot(saved.version(), saved.windows().stream()
|
||||||
|
.map(window -> window.main() ? window : new LayoutSnapshot.Window(window.id(), false, unavailable, window.roots()))
|
||||||
|
.toList(), saved.activeDockableId(), saved.returnPositions(), saved.initialIntents());
|
||||||
|
DockingManager restored = attach(target); AtomicReference<Dockable> fresh = new AtomicReference<>();
|
||||||
|
assertInstanceOf(RestoreResult.Applied.class, restored.restore(offscreen, requested -> {
|
||||||
|
Dockable dockable = new Dockable(requested, new TextArea("loaded")); fresh.set(dockable);
|
||||||
|
return new DockableResolution.Available(dockable);
|
||||||
|
}));
|
||||||
|
Rectangle2D fitted = restored.snapshot().windows().get(1).bounds();
|
||||||
|
assertTrue(visual.contains(fitted), "Committed restored bounds fit an available visual display");
|
||||||
|
assertEquals(visual.getWidth(), fitted.getWidth(), .01);
|
||||||
|
assertEquals(visual.getHeight(), fitted.getHeight(), .01);
|
||||||
|
Stage host = (Stage) fresh.get().getContent().getScene().getWindow();
|
||||||
|
assertFalse(host.isShowing());
|
||||||
|
target.show(); assertTrue(host.isShowing());
|
||||||
|
assertTrue(visual.contains(new Rectangle2D(host.getX(), host.getY(), host.getWidth(), host.getHeight())));
|
||||||
|
} finally {
|
||||||
|
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
|
||||||
|
source.hide(); target.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockingManager attach(Stage stage) {
|
||||||
|
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
stage.setScene(new Scene(pane, 700, 500)); return DockingManager.attach(stage, pane, new DockingOptions());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.geometry.Rectangle2D;
|
||||||
|
import javafx.geometry.Side;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Screen;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Multiwindow startup and return through ordinary snapshot/restore APIs. */
|
||||||
|
class RestoreFloatingLayoutTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void floatingSplitsStayHiddenUntilMainShowAndReturnToTheirEmptyMainArea() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
List<Window> existing = List.copyOf(Window.getWindows());
|
||||||
|
Stage source = new Stage();
|
||||||
|
Stage target = new Stage();
|
||||||
|
try {
|
||||||
|
DockingManager original = attach(source, new DockingOptions());
|
||||||
|
Map<DockableId, Dockable> originals = new LinkedHashMap<>();
|
||||||
|
for (String id : List.of("notes", "preview", "readme")) {
|
||||||
|
Dockable dockable = new Dockable(new DockableId(id), new TextArea("Saved " + id));
|
||||||
|
dockable.setTitle(id);
|
||||||
|
originals.put(dockable.getId(), dockable);
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.open(dockable, DockTarget.area("editors")));
|
||||||
|
}
|
||||||
|
source.show();
|
||||||
|
var screen = Screen.getPrimary().getVisualBounds();
|
||||||
|
DockableId notes = new DockableId("notes");
|
||||||
|
DockableId preview = new DockableId("preview");
|
||||||
|
DockableId readme = new DockableId("readme");
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.move(notes, DockTarget.floating(
|
||||||
|
new Rectangle2D(screen.getMinX() + 80, screen.getMinY() + 80, 400, 400))));
|
||||||
|
DockGroupId notesGroup = groupContaining(original, notes).id();
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.move(preview, DockTarget.split(notesGroup, Side.BOTTOM)));
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.move(readme, DockTarget.floating(
|
||||||
|
new Rectangle2D(screen.getMaxX() - 440, screen.getMinY() + 100, 400, 320))));
|
||||||
|
original.activate(notes);
|
||||||
|
LayoutSnapshot saved = original.snapshot();
|
||||||
|
assertEquals(3, saved.windows().size());
|
||||||
|
assertTrue(saved.returnPositions().keySet().containsAll(List.of(notes, preview, readme)));
|
||||||
|
assertEquals(2, original.layout().windows().stream().filter(window -> !window.main())
|
||||||
|
.filter(window -> window.areas().stream().anyMatch(area -> area.groups().size() == 2))
|
||||||
|
.findFirst().orElseThrow().areas().getFirst().groups().size());
|
||||||
|
|
||||||
|
AtomicInteger customized = new AtomicInteger();
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setFloatingWindowCustomizer(configuration -> {
|
||||||
|
customized.incrementAndGet(); configuration.setTitle("Restored editor window");
|
||||||
|
});
|
||||||
|
DockingManager restored = attach(target, options);
|
||||||
|
Map<DockableId, Dockable> fresh = new LinkedHashMap<>();
|
||||||
|
RestoreResult.Applied result = assertInstanceOf(RestoreResult.Applied.class, restored.restore(saved, id -> {
|
||||||
|
Dockable dockable = new Dockable(id, new TextArea("Loaded " + id.value()));
|
||||||
|
dockable.setTitle(id.value()); fresh.put(id, dockable);
|
||||||
|
return new DockableResolution.Available(dockable);
|
||||||
|
}));
|
||||||
|
assertTrue(result.missingIds().isEmpty());
|
||||||
|
assertEquals(2, customized.get());
|
||||||
|
assertEquals(3, restored.layout().windows().size());
|
||||||
|
for (Dockable dockable : fresh.values()) {
|
||||||
|
assertNotSame(originals.get(dockable.getId()).getContent(), dockable.getContent());
|
||||||
|
Stage floating = (Stage) dockable.getContent().getScene().getWindow();
|
||||||
|
assertNotSame(target, floating);
|
||||||
|
assertFalse(floating.isShowing(), "Restored floating hosts wait for the main Stage");
|
||||||
|
assertEquals("Restored editor window", floating.getTitle());
|
||||||
|
}
|
||||||
|
target.show();
|
||||||
|
for (Dockable dockable : fresh.values()) assertTrue(dockable.getContent().getScene().getWindow().isShowing());
|
||||||
|
assertSame(fresh.get(notes), restored.activeDockable());
|
||||||
|
for (DockableId id : List.of(notes, preview, readme)) {
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, restored.move(id, DockTarget.returnToMain()));
|
||||||
|
assertSame(target, fresh.get(id).getContent().getScene().getWindow());
|
||||||
|
assertEquals("Loaded " + id.value(), ((TextArea) fresh.get(id).getContent()).getText());
|
||||||
|
}
|
||||||
|
assertEquals(1, restored.layout().windows().size());
|
||||||
|
} finally {
|
||||||
|
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
|
||||||
|
source.hide(); target.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockingManager attach(Stage stage, DockingOptions options) {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
stage.setScene(new Scene(pane, 700, 500));
|
||||||
|
return DockingManager.attach(stage, pane, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockLayoutView.Group groupContaining(DockingManager manager, DockableId id) {
|
||||||
|
return manager.layout().windows().stream().flatMap(window -> window.areas().stream())
|
||||||
|
.flatMap(area -> area.groups().stream()).filter(group -> group.dockableIds().contains(id))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.geometry.Rectangle2D;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class RestoreFloatingRootsTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void acceptedFloatingSideRootsKeepTheirPlacementAndCommittedExtentAcrossRepeatedStartup() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
List<Window> existing = List.copyOf(Window.getWindows());
|
||||||
|
Stage source = new Stage(); Stage first = new Stage(); Stage second = new Stage();
|
||||||
|
try {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
DockGroupDefinition tools = new DockGroupDefinition("tools"); tools.setPreferredWidth(220);
|
||||||
|
pane.getInitialLayout().setLeft(tools);
|
||||||
|
source.setScene(new Scene(pane, 800, 600));
|
||||||
|
DockingManager original = DockingManager.attach(source, pane, new DockingOptions());
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.open(new Dockable(new DockableId("editor"), new TextArea("edit")), DockTarget.area("editors")));
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, original.open(new Dockable(new DockableId("project"), new TextArea("project")), DockTarget.area("tools")));
|
||||||
|
LayoutSnapshot saved = original.snapshot();
|
||||||
|
List<LayoutSnapshot.Root> roots = saved.windows().getFirst().roots();
|
||||||
|
LayoutSnapshot floating = new LayoutSnapshot(saved.version(), List.of(
|
||||||
|
new LayoutSnapshot.Window(new DockWindowId("main"), true, null, List.of()),
|
||||||
|
new LayoutSnapshot.Window(new DockWindowId("detached-workspace"), false, new Rectangle2D(100, 100, 800, 600), roots)),
|
||||||
|
saved.activeDockableId(), Map.of(), saved.initialIntents());
|
||||||
|
DockingManager restored = attach(first);
|
||||||
|
assertInstanceOf(RestoreResult.Applied.class, restored.restore(floating, RestoreFloatingRootsTest::load));
|
||||||
|
first.show();
|
||||||
|
LayoutSnapshot exported = restored.snapshot();
|
||||||
|
List<LayoutSnapshot.Root> floatingRoots = exported.windows().get(1).roots();
|
||||||
|
assertEquals(roots.stream().map(LayoutSnapshot.Root::placement).toList(),
|
||||||
|
floatingRoots.stream().map(LayoutSnapshot.Root::placement).toList());
|
||||||
|
LayoutSnapshot.Root left = floatingRoots.stream().filter(root -> root.placement() == LayoutSnapshot.Placement.LEFT).findFirst().orElseThrow();
|
||||||
|
assertEquals(220, left.preferredWidth(), 1);
|
||||||
|
var toolsView = restored.layout().windows().get(1).areas().stream()
|
||||||
|
.filter(area -> area.id().equals(new DockAreaId("tools"))).findFirst().orElseThrow();
|
||||||
|
assertEquals(left.preferredWidth(), toolsView.preferredWidth(), 1);
|
||||||
|
DockingManager restarted = attach(second);
|
||||||
|
assertInstanceOf(RestoreResult.Applied.class, restarted.restore(exported, RestoreFloatingRootsTest::load),
|
||||||
|
"A successful restore must publish a valid snapshot for the next startup");
|
||||||
|
assertEquals(floatingRoots.stream().map(LayoutSnapshot.Root::placement).toList(),
|
||||||
|
restarted.snapshot().windows().get(1).roots().stream().map(LayoutSnapshot.Root::placement).toList());
|
||||||
|
} finally {
|
||||||
|
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
|
||||||
|
source.hide(); first.hide(); second.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void aRestoredSideRootCannotResizeAnAdjacentGroupAwaitingConsent() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
List<Window> existing = List.copyOf(Window.getWindows());
|
||||||
|
Stage source = new Stage(); Stage target = new Stage();
|
||||||
|
try {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
pane.getInitialLayout().setLeft(new DockGroupDefinition("tools"));
|
||||||
|
source.setScene(new Scene(pane, 800, 600));
|
||||||
|
DockingManager original = DockingManager.attach(source, pane, new DockingOptions());
|
||||||
|
original.open(new Dockable(new DockableId("editor"), new TextArea()), DockTarget.area("editors"));
|
||||||
|
original.open(new Dockable(new DockableId("project"), new TextArea()), DockTarget.area("tools"));
|
||||||
|
LayoutSnapshot saved = original.snapshot();
|
||||||
|
LayoutSnapshot floating = new LayoutSnapshot(saved.version(), List.of(
|
||||||
|
new LayoutSnapshot.Window(new DockWindowId("main"), true, null, List.of()),
|
||||||
|
new LayoutSnapshot.Window(new DockWindowId("detached-workspace"), false,
|
||||||
|
new Rectangle2D(100, 100, 800, 600), saved.windows().getFirst().roots())),
|
||||||
|
saved.activeDockableId(), Map.of(), saved.initialIntents());
|
||||||
|
DockingManager restored = attach(target);
|
||||||
|
assertInstanceOf(RestoreResult.Applied.class, restored.restore(floating, RestoreFloatingRootsTest::load));
|
||||||
|
target.show();
|
||||||
|
Dockable editor = restored.findDockable(new DockableId("editor")).orElseThrow();
|
||||||
|
var consent = new java.util.concurrent.CompletableFuture<CloseConsent>();
|
||||||
|
editor.setCloseCheck(request -> consent);
|
||||||
|
restored.requestTabClose(editor.getId());
|
||||||
|
LayoutSnapshot before = restored.snapshot();
|
||||||
|
try {
|
||||||
|
ActionResult.Rejected rejected = assertInstanceOf(ActionResult.Rejected.class,
|
||||||
|
restored.updateGroup(new DockGroupId("tools"), DockGroupChanges.builder().preferredWidth(300).build()));
|
||||||
|
assertEquals(DockFailure.Code.CLOSE_IN_PROGRESS, rejected.failure().code());
|
||||||
|
assertSame(before, restored.snapshot());
|
||||||
|
} finally { consent.complete(CloseConsent.VETO); }
|
||||||
|
assertInstanceOf(ActionResult.Applied.class,
|
||||||
|
restored.updateGroup(new DockGroupId("tools"), DockGroupChanges.builder().preferredWidth(300).build()));
|
||||||
|
} finally {
|
||||||
|
List.copyOf(Window.getWindows()).stream().filter(window -> !existing.contains(window)).forEach(Window::hide);
|
||||||
|
source.hide(); target.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockableResolution load(DockableId id) {
|
||||||
|
return new DockableResolution.Available(new Dockable(id, new TextArea("loaded " + id.value())));
|
||||||
|
}
|
||||||
|
private static DockingManager attach(Stage stage) {
|
||||||
|
DockPane pane = new DockPane(); pane.getInitialLayout().setCenter(new DockGroupDefinition("initial"));
|
||||||
|
stage.setScene(new Scene(pane, 800, 600)); return DockingManager.attach(stage, pane, new DockingOptions());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,323 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.docking.*;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Application shutdown asks all windows before a snapshot or any removal. */
|
||||||
|
class ShutdownDockingTest {
|
||||||
|
@BeforeAll static void startJavaFx() throws Exception {
|
||||||
|
FxThread.start(); FxThread.onFx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void lateVetoLeavesEveryWindowOpenAndSkipsTheShutdownSnapshot() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
DockGroupDefinition tools = new DockGroupDefinition("tools");
|
||||||
|
tools.setCollapsible(true);
|
||||||
|
pane.getInitialLayout().setLeft(tools);
|
||||||
|
Stage stage = new Stage();
|
||||||
|
stage.setScene(new Scene(pane, 700, 500));
|
||||||
|
AtomicInteger saves = new AtomicInteger();
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setBeforeShutdown(request -> {
|
||||||
|
saves.incrementAndGet();
|
||||||
|
return CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
|
||||||
|
});
|
||||||
|
DockingManager manager = DockingManager.attach(stage, pane, options);
|
||||||
|
List<String> asked = new ArrayList<>();
|
||||||
|
AtomicInteger closed = new AtomicInteger();
|
||||||
|
Dockable editor = new Dockable(new DockableId("editor"), new TextArea("Unsaved editor"));
|
||||||
|
Dockable tool = new Dockable(new DockableId("project"), new TextArea("Collapsed project"));
|
||||||
|
Dockable floating = new Dockable(new DockableId("floating"), new TextArea("Unsaved float"));
|
||||||
|
for (Dockable dockable : List.of(editor, tool, floating)) {
|
||||||
|
dockable.setCloseCheck(request -> {
|
||||||
|
assertEquals(CloseScope.Kind.MAIN_WINDOW, request.scope().kind());
|
||||||
|
assertEquals(3, request.scope().dockableIds().size());
|
||||||
|
assertEquals(0, closed.get());
|
||||||
|
assertSame(dockable.getContent().getScene().getWindow(), request.owner());
|
||||||
|
asked.add(dockable.getId().value());
|
||||||
|
return CompletableFuture.completedFuture(dockable == tool ? CloseConsent.VETO : CloseConsent.ALLOW);
|
||||||
|
});
|
||||||
|
dockable.setOnClosed(closed::incrementAndGet);
|
||||||
|
}
|
||||||
|
manager.open(editor, DockTarget.area("editors"));
|
||||||
|
manager.open(tool, DockTarget.area("tools"));
|
||||||
|
manager.open(floating, DockTarget.floating());
|
||||||
|
var toolGroup = manager.layout().windows().getFirst().areas().stream()
|
||||||
|
.filter(area -> area.id().value().equals("tools")).findFirst().orElseThrow().groups().getFirst();
|
||||||
|
manager.setGroupCollapsed(toolGroup.id(), true);
|
||||||
|
stage.show();
|
||||||
|
Stage floated = (Stage) floating.getContent().getScene().getWindow();
|
||||||
|
try {
|
||||||
|
var before = manager.layout();
|
||||||
|
var snapshot = manager.snapshot();
|
||||||
|
var result = manager.requestMainWindowClose().toCompletableFuture().join();
|
||||||
|
assertInstanceOf(CloseResult.Vetoed.class, result);
|
||||||
|
assertEquals(List.of("editor", "project", "floating"), asked);
|
||||||
|
assertEquals(0, saves.get());
|
||||||
|
assertEquals(0, closed.get());
|
||||||
|
assertSame(before, manager.layout());
|
||||||
|
assertSame(snapshot, manager.snapshot());
|
||||||
|
assertTrue(stage.isShowing());
|
||||||
|
assertTrue(floated.isShowing());
|
||||||
|
assertNull(manager.closingScopeProperty().get());
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, manager.move(editor.getId(), DockTarget.area("tools")));
|
||||||
|
} finally { floated.hide(); stage.hide(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
@Test void asynchronousShutdownSaveKeepsEveryContentOpenThenClosesOnTheFxThread() throws Exception {
|
||||||
|
var save = new CompletableFuture<ShutdownDecision>();
|
||||||
|
var fixture = new java.util.concurrent.atomic.AtomicReference<ShutdownFixture>();
|
||||||
|
var outcome = new java.util.concurrent.atomic.AtomicReference<java.util.concurrent.CompletionStage<CloseResult>>();
|
||||||
|
AtomicInteger saves = new AtomicInteger();
|
||||||
|
AtomicInteger closed = new AtomicInteger();
|
||||||
|
try {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setBeforeShutdown(request -> {
|
||||||
|
assertTrue(Platform.isFxApplicationThread());
|
||||||
|
assertEquals(ShutdownReason.MAIN_WINDOW, request.reason());
|
||||||
|
assertEquals(2, request.snapshot().windows().size());
|
||||||
|
assertEquals(2, fixture.get().manager.closingScopeProperty().get().dockableIds().size());
|
||||||
|
assertEquals(0, closed.get());
|
||||||
|
assertTrue(fixture.get().main.isShowing());
|
||||||
|
assertTrue(fixture.get().floating.isShowing());
|
||||||
|
saves.incrementAndGet();
|
||||||
|
return save;
|
||||||
|
});
|
||||||
|
ShutdownFixture f = shutdownFixture(options);
|
||||||
|
fixture.set(f);
|
||||||
|
for (Dockable dockable : List.of(f.notes, f.project)) {
|
||||||
|
dockable.setOnClosed(() -> {
|
||||||
|
assertTrue(Platform.isFxApplicationThread());
|
||||||
|
assertNotNull(f.manager.closingScopeProperty().get(), "Scope includes resource release");
|
||||||
|
assertNull(dockable.getContent().getScene());
|
||||||
|
closed.incrementAndGet();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
var before = f.manager.layout();
|
||||||
|
outcome.set(f.manager.requestMainWindowClose());
|
||||||
|
assertEquals(1, saves.get());
|
||||||
|
assertFalse(outcome.get().toCompletableFuture().isDone());
|
||||||
|
assertEquals(0, closed.get());
|
||||||
|
assertSame(before, f.manager.layout());
|
||||||
|
assertTrue(f.main.isShowing());
|
||||||
|
assertTrue(f.floating.isShowing());
|
||||||
|
assertEquals(CloseScope.Kind.MAIN_WINDOW, f.manager.closingScopeProperty().get().kind());
|
||||||
|
assertInstanceOf(ActionResult.Rejected.class, f.manager.move(f.notes.getId(), DockTarget.area("editors")));
|
||||||
|
assertInstanceOf(ActionResult.Rejected.class, f.manager.open(
|
||||||
|
new Dockable(new DockableId("late"), new TextArea()), DockTarget.floating()));
|
||||||
|
AtomicInteger factories = new AtomicInteger();
|
||||||
|
assertInstanceOf(ActionResult.Rejected.class, f.manager.open(new DockableId("factory"), () -> {
|
||||||
|
factories.incrementAndGet(); return new Dockable(new DockableId("factory"), new TextArea());
|
||||||
|
}, DockTarget.area("editors")));
|
||||||
|
assertEquals(0, factories.get(), "A global close cannot start creating new content");
|
||||||
|
});
|
||||||
|
CompletableFuture.runAsync(() -> save.complete(ShutdownDecision.PROCEED)).get();
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
ShutdownFixture f = fixture.get();
|
||||||
|
assertInstanceOf(CloseResult.Closed.class, outcome.get().toCompletableFuture().join());
|
||||||
|
assertEquals(2, closed.get());
|
||||||
|
assertEquals(1, saves.get());
|
||||||
|
assertFalse(f.main.isShowing());
|
||||||
|
assertFalse(f.floating.isShowing());
|
||||||
|
assertNull(f.manager.closingScopeProperty().get());
|
||||||
|
assertTrue(f.manager.findDockable(f.notes.getId()).isEmpty());
|
||||||
|
assertInstanceOf(ActionResult.Rejected.class, f.manager.open(
|
||||||
|
new Dockable(new DockableId("after-close"), new TextArea()), DockTarget.area("editors")));
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
if (fixture.get() != null) FxThread.onFx(fixture.get()::close);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void managerOnlyCloseReleasesTheSamePaneForANewWorkingOverlayManager() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
List<ShutdownReason> reasons = new ArrayList<>();
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setBeforeShutdown(request -> {
|
||||||
|
reasons.add(request.reason());
|
||||||
|
return CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
|
||||||
|
});
|
||||||
|
ShutdownFixture f = shutdownFixture(options);
|
||||||
|
try {
|
||||||
|
assertInstanceOf(CloseResult.Closed.class, f.manager.requestManagerClose().toCompletableFuture().join());
|
||||||
|
assertEquals(List.of(ShutdownReason.MANAGER_ONLY), reasons);
|
||||||
|
assertTrue(f.main.isShowing());
|
||||||
|
assertFalse(f.floating.isShowing());
|
||||||
|
assertEquals(DockFailure.Code.MANAGER_CLOSED,
|
||||||
|
assertInstanceOf(ActionResult.Rejected.class, f.manager.activate(f.notes.getId())).failure().code());
|
||||||
|
assertInstanceOf(CloseResult.NoChange.class, f.manager.requestMainWindowClose().toCompletableFuture().join());
|
||||||
|
assertTrue(f.main.isShowing(), "An ended manager no longer owns the application's Stage");
|
||||||
|
|
||||||
|
((DockGroupDefinition) f.pane.getInitialLayout().getLeft()).setMode(DockGroupMode.OVERLAY);
|
||||||
|
DockingManager replacement = DockingManager.attach(f.main, f.pane, new DockingOptions());
|
||||||
|
TextArea editor = new TextArea("Replacement editor");
|
||||||
|
TextArea project = new TextArea("Replacement project");
|
||||||
|
replacement.open(new Dockable(new DockableId("new-editor"), editor), DockTarget.area("editors"));
|
||||||
|
replacement.open(new Dockable(new DockableId("new-project"), project), DockTarget.area("tools"));
|
||||||
|
f.pane.applyCss(); f.pane.layout();
|
||||||
|
assertFalse(group(replacement, "tools").collapsed());
|
||||||
|
editor.fireEvent(new javafx.scene.input.MouseEvent(javafx.scene.input.MouseEvent.MOUSE_PRESSED,
|
||||||
|
5, 5, 5, 5, javafx.scene.input.MouseButton.PRIMARY, 1,
|
||||||
|
false, false, false, false, true, false, false, false, false, false,
|
||||||
|
new javafx.scene.input.PickResult(editor, 5, 5)));
|
||||||
|
assertTrue(group(replacement, "tools").collapsed(), "Reattached overlay restores the outside-click handler");
|
||||||
|
f.main.hide(); f.main.show();
|
||||||
|
assertFalse(f.floating.isShowing(), "The ended manager cannot resurrect its old floating Stage");
|
||||||
|
assertInstanceOf(CloseResult.Closed.class, replacement.requestManagerClose().toCompletableFuture().join());
|
||||||
|
assertTrue(f.main.isShowing());
|
||||||
|
} finally { f.close(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@org.junit.jupiter.params.ParameterizedTest
|
||||||
|
@org.junit.jupiter.params.provider.EnumSource(MainWindowCloseMode.class)
|
||||||
|
void mainCloseControlHonorsTheCapturedOwnershipModeAndWaitsForConsent(MainWindowCloseMode mode) throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setMainWindowCloseMode(mode);
|
||||||
|
AtomicInteger saves = new AtomicInteger();
|
||||||
|
options.setBeforeShutdown(request -> {
|
||||||
|
saves.incrementAndGet();
|
||||||
|
return CompletableFuture.completedFuture(ShutdownDecision.PROCEED);
|
||||||
|
});
|
||||||
|
ShutdownFixture f = shutdownFixture(options);
|
||||||
|
options.setMainWindowCloseMode(mode == MainWindowCloseMode.AUTOMATIC
|
||||||
|
? MainWindowCloseMode.APPLICATION_COORDINATED : MainWindowCloseMode.AUTOMATIC);
|
||||||
|
var consent = new CompletableFuture<CloseConsent>();
|
||||||
|
f.notes.setCloseCheck(request -> consent);
|
||||||
|
AtomicInteger applicationEvents = new AtomicInteger();
|
||||||
|
if (mode == MainWindowCloseMode.APPLICATION_COORDINATED) {
|
||||||
|
f.main.setOnCloseRequest(event -> {
|
||||||
|
event.consume(); applicationEvents.incrementAndGet();
|
||||||
|
f.manager.requestMainWindowClose();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
f.main.fireEvent(new javafx.stage.WindowEvent(f.main, javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST));
|
||||||
|
assertTrue(f.main.isShowing(), "The main close control waits for consent");
|
||||||
|
assertTrue(f.floating.isShowing());
|
||||||
|
assertNotNull(f.manager.closingScopeProperty().get());
|
||||||
|
assertEquals(0, saves.get());
|
||||||
|
consent.complete(CloseConsent.VETO);
|
||||||
|
assertTrue(f.main.isShowing());
|
||||||
|
assertTrue(f.floating.isShowing());
|
||||||
|
assertNull(f.manager.closingScopeProperty().get());
|
||||||
|
assertEquals(0, saves.get());
|
||||||
|
f.notes.setCloseCheck(request -> CompletableFuture.completedFuture(CloseConsent.ALLOW));
|
||||||
|
f.main.fireEvent(new javafx.stage.WindowEvent(f.main, javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST));
|
||||||
|
assertFalse(f.floating.isShowing());
|
||||||
|
assertEquals(1, saves.get());
|
||||||
|
assertEquals(mode == MainWindowCloseMode.APPLICATION_COORDINATED, f.main.isShowing());
|
||||||
|
assertEquals(mode == MainWindowCloseMode.APPLICATION_COORDINATED ? 2 : 0, applicationEvents.get());
|
||||||
|
if (mode == MainWindowCloseMode.APPLICATION_COORDINATED) f.main.hide();
|
||||||
|
} finally { f.close(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@org.junit.jupiter.params.ParameterizedTest
|
||||||
|
@org.junit.jupiter.params.provider.ValueSource(strings = {"cancel", "throw", "failed"})
|
||||||
|
void canceledOrFailedShutdownSaveLeavesTheManagerOperational(String fault) throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
RuntimeException failure = new IllegalStateException("Layout storage unavailable");
|
||||||
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setBeforeShutdown(request -> {
|
||||||
|
if (fault.equals("throw")) throw failure;
|
||||||
|
if (fault.equals("failed")) return CompletableFuture.failedFuture(failure);
|
||||||
|
return CompletableFuture.completedFuture(ShutdownDecision.CANCEL);
|
||||||
|
});
|
||||||
|
ShutdownFixture f = shutdownFixture(options);
|
||||||
|
AtomicInteger closed = new AtomicInteger();
|
||||||
|
f.notes.setOnClosed(closed::incrementAndGet);
|
||||||
|
f.project.setOnClosed(closed::incrementAndGet);
|
||||||
|
try {
|
||||||
|
var before = f.manager.layout();
|
||||||
|
var snapshot = f.manager.snapshot();
|
||||||
|
CloseResult result = f.manager.requestMainWindowClose().toCompletableFuture().join();
|
||||||
|
if (fault.equals("cancel")) assertInstanceOf(CloseResult.Canceled.class, result);
|
||||||
|
else {
|
||||||
|
DockFailure diagnostic = assertInstanceOf(CloseResult.Rejected.class, result).failure();
|
||||||
|
assertEquals(DockFailure.Code.SHUTDOWN_CALLBACK_FAILED, diagnostic.code());
|
||||||
|
assertSame(failure, diagnostic.cause());
|
||||||
|
}
|
||||||
|
assertSame(before, f.manager.layout());
|
||||||
|
assertSame(snapshot, f.manager.snapshot());
|
||||||
|
assertEquals(0, closed.get());
|
||||||
|
assertTrue(f.main.isShowing());
|
||||||
|
assertTrue(f.floating.isShowing());
|
||||||
|
assertNull(f.manager.closingScopeProperty().get());
|
||||||
|
assertInstanceOf(ActionResult.Applied.class, f.manager.move(f.notes.getId(), DockTarget.returnToMain()));
|
||||||
|
} finally { f.close(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void shutdownCleanupFailuresStillReleaseEveryDockableAndTheManager() throws Exception {
|
||||||
|
FxThread.onFx(() -> {
|
||||||
|
ShutdownFixture f = shutdownFixture(new DockingOptions());
|
||||||
|
AtomicInteger cleanups = new AtomicInteger();
|
||||||
|
RuntimeException failure = new IllegalStateException("Listener release failed");
|
||||||
|
f.notes.setOnClosed(() -> { cleanups.incrementAndGet(); throw failure; });
|
||||||
|
f.project.setOnClosed(cleanups::incrementAndGet);
|
||||||
|
try {
|
||||||
|
CloseResult.Closed result = assertInstanceOf(CloseResult.Closed.class,
|
||||||
|
f.manager.requestManagerClose().toCompletableFuture().join());
|
||||||
|
assertEquals(2, cleanups.get());
|
||||||
|
assertEquals(1, result.cleanupFailures().size());
|
||||||
|
assertSame(failure, result.cleanupFailures().getFirst().cause());
|
||||||
|
assertFalse(f.floating.isShowing());
|
||||||
|
assertTrue(f.main.isShowing());
|
||||||
|
assertNull(f.manager.closingScopeProperty().get());
|
||||||
|
DockingManager replacement = DockingManager.attach(f.main, f.pane, new DockingOptions());
|
||||||
|
assertInstanceOf(CloseResult.Closed.class, replacement.requestManagerClose().toCompletableFuture().join());
|
||||||
|
assertInstanceOf(CloseResult.NoChange.class, f.manager.requestManagerClose().toCompletableFuture().join());
|
||||||
|
assertEquals(2, cleanups.get());
|
||||||
|
} finally { f.close(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DockLayoutView.Group group(DockingManager manager, String area) {
|
||||||
|
return manager.layout().windows().getFirst().areas().stream().filter(value -> value.id().value().equals(area))
|
||||||
|
.findFirst().orElseThrow().groups().getFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ShutdownFixture shutdownFixture(DockingOptions options) {
|
||||||
|
List<javafx.stage.Window> existing = List.copyOf(javafx.stage.Window.getWindows());
|
||||||
|
DockPane pane = new DockPane();
|
||||||
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
|
DockGroupDefinition tools = new DockGroupDefinition("tools");
|
||||||
|
tools.setCollapsible(true);
|
||||||
|
pane.getInitialLayout().setLeft(tools);
|
||||||
|
Stage main = new Stage();
|
||||||
|
main.setScene(new Scene(pane, 700, 500));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, options);
|
||||||
|
Dockable notes = new Dockable(new DockableId("notes"), new TextArea("Unsaved notes"));
|
||||||
|
Dockable project = new Dockable(new DockableId("project"), new TextArea("Project"));
|
||||||
|
manager.open(notes, DockTarget.area("editors"));
|
||||||
|
manager.open(project, DockTarget.area("tools"));
|
||||||
|
manager.setGroupCollapsed(new DockGroupId("tools"), true);
|
||||||
|
manager.move(notes.getId(), DockTarget.floating());
|
||||||
|
main.show();
|
||||||
|
return new ShutdownFixture(main, (Stage) notes.getContent().getScene().getWindow(), pane, manager, notes, project, existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
private record ShutdownFixture(Stage main, Stage floating, DockPane pane, DockingManager manager,
|
||||||
|
Dockable notes, Dockable project, List<javafx.stage.Window> existing) {
|
||||||
|
void close() {
|
||||||
|
List.copyOf(javafx.stage.Window.getWindows()).stream().filter(window -> !existing.contains(window))
|
||||||
|
.forEach(javafx.stage.Window::hide);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
.dock-tab-header { -fx-background-color: #f1e2c3; }
|
||||||
|
.dock-drop-indicator { -fx-fill: #123456; -fx-stroke: #654321; }
|
||||||
|
.dock-floating-preview-frame { -fx-fill: #234567; -fx-stroke: #765432; }
|
||||||
|
|
||||||
|
.dock-divider { -fx-background-color: #345678; }
|
||||||
|
.dock-area-divider { -fx-background-color: #456789; }
|
||||||
Reference in New Issue
Block a user