studio session persistent

This commit is contained in:
2026-04-04 06:57:33 +01:00
parent d1722b23a3
commit a824b2185f
24 changed files with 1612 additions and 26 deletions
@@ -112,6 +112,26 @@ public abstract class WorkspaceDockPane extends TitledPane {
return split;
}
public final DockState captureDockState() {
final double preferredExpandedDivider = lastExpandedDividerPosition != null
? lastExpandedDividerPosition
: currentDivider();
return new DockState(isExpanded(), preferredExpandedDivider);
}
public final void restoreDockState(final DockState dockState) {
if (dockState == null) {
return;
}
lastExpandedDividerPosition = dockState.dividerPosition();
setExpanded(dockState.expanded());
if (dockState.expanded()) {
setDivider(clampExpandedDivider(dockState.dividerPosition()));
} else if (dockSplit != null) {
applyCollapsedDivider();
}
}
protected final void setDockContent(final Node content) {
setContent(Objects.requireNonNull(content, "content"));
}
@@ -227,4 +247,7 @@ public abstract class WorkspaceDockPane extends TitledPane {
node.setManaged(!disabled);
}));
}
public record DockState(boolean expanded, double dividerPosition) {
}
}
@@ -6,6 +6,7 @@ import java.util.Objects;
public final class ProjectStudioPaths {
private static final String STUDIO_DIR = ".studio";
private static final String ACTIVITIES_FILE = "activities.json";
private static final String STATE_FILE = "state.json";
private ProjectStudioPaths() {
}
@@ -24,4 +25,11 @@ public final class ProjectStudioPaths {
.toAbsolutePath()
.normalize();
}
public static Path statePath(ProjectReference projectReference) {
return studioRoot(projectReference)
.resolve(STATE_FILE)
.toAbsolutePath()
.normalize();
}
}
@@ -1,6 +1,8 @@
package p.studio.projectsessions;
import p.studio.lsp.LspService;
import p.studio.projectstate.ProjectLocalStudioState;
import p.studio.projectstate.ProjectLocalStudioStateService;
import p.studio.projects.ProjectReference;
import p.studio.vfs.VfsProjectDocument;
@@ -10,15 +12,33 @@ public final class StudioProjectSession implements AutoCloseable {
private final ProjectReference projectReference;
private final LspService prometeuLspService;
private final VfsProjectDocument vfsProjectDocument;
private final ProjectLocalStudioStateService projectLocalStudioStateService;
private ProjectLocalStudioState projectLocalStudioState;
private boolean closed;
public StudioProjectSession(
final ProjectReference projectReference,
final LspService prometeuLspService,
final VfsProjectDocument vfsProjectDocument) {
this(
projectReference,
prometeuLspService,
vfsProjectDocument,
new ProjectLocalStudioStateService(),
ProjectLocalStudioState.defaults());
}
StudioProjectSession(
final ProjectReference projectReference,
final LspService prometeuLspService,
final VfsProjectDocument vfsProjectDocument,
final ProjectLocalStudioStateService projectLocalStudioStateService,
final ProjectLocalStudioState projectLocalStudioState) {
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.prometeuLspService = Objects.requireNonNull(prometeuLspService, "prometeuLspService");
this.vfsProjectDocument = Objects.requireNonNull(vfsProjectDocument, "vfsProjectDocument");
this.projectLocalStudioStateService = Objects.requireNonNull(projectLocalStudioStateService, "projectLocalStudioStateService");
this.projectLocalStudioState = Objects.requireNonNull(projectLocalStudioState, "projectLocalStudioState");
}
public ProjectReference projectReference() {
@@ -33,13 +53,50 @@ public final class StudioProjectSession implements AutoCloseable {
return prometeuLspService;
}
public ProjectLocalStudioState projectLocalStudioState() {
return projectLocalStudioState;
}
public void replaceProjectLocalStudioState(final ProjectLocalStudioState nextProjectLocalStudioState) {
this.projectLocalStudioState = Objects.requireNonNull(nextProjectLocalStudioState, "nextProjectLocalStudioState");
}
public void saveProjectLocalStudioState() {
projectLocalStudioStateService.save(projectReference, projectLocalStudioState);
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
prometeuLspService.close();
vfsProjectDocument.close();
RuntimeException failure = null;
try {
saveProjectLocalStudioState();
} catch (RuntimeException runtimeException) {
failure = runtimeException;
}
try {
prometeuLspService.close();
} catch (RuntimeException runtimeException) {
if (failure == null) {
failure = runtimeException;
} else {
failure.addSuppressed(runtimeException);
}
}
try {
vfsProjectDocument.close();
} catch (RuntimeException runtimeException) {
if (failure == null) {
failure = runtimeException;
} else {
failure.addSuppressed(runtimeException);
}
}
if (failure != null) {
throw failure;
}
}
}
@@ -2,6 +2,7 @@ package p.studio.projectsessions;
import p.studio.lsp.messages.LspProjectContext;
import p.studio.lsp.LspServiceFactory;
import p.studio.projectstate.ProjectLocalStudioStateService;
import p.studio.projects.ProjectReference;
import p.studio.vfs.VfsProjectDocument;
import p.studio.vfs.ProjectDocumentVfsFactory;
@@ -11,12 +12,21 @@ import java.util.Objects;
public final class StudioProjectSessionFactory {
private final LspServiceFactory lspServiceFactory;
private final ProjectDocumentVfsFactory projectDocumentVfsFactory;
private final ProjectLocalStudioStateService projectLocalStudioStateService;
public StudioProjectSessionFactory(
final LspServiceFactory lspServiceFactory,
final ProjectDocumentVfsFactory projectDocumentVfsFactory) {
this(lspServiceFactory, projectDocumentVfsFactory, new ProjectLocalStudioStateService());
}
StudioProjectSessionFactory(
final LspServiceFactory lspServiceFactory,
final ProjectDocumentVfsFactory projectDocumentVfsFactory,
final ProjectLocalStudioStateService projectLocalStudioStateService) {
this.lspServiceFactory = Objects.requireNonNull(lspServiceFactory, "prometeuLspServiceFactory");
this.projectDocumentVfsFactory = Objects.requireNonNull(projectDocumentVfsFactory, "projectDocumentVfsFactory");
this.projectLocalStudioStateService = Objects.requireNonNull(projectLocalStudioStateService, "projectLocalStudioStateService");
}
public StudioProjectSession open(final ProjectReference projectReference) {
@@ -25,7 +35,9 @@ public final class StudioProjectSessionFactory {
return new StudioProjectSession(
target,
lspServiceFactory.open(lspProjectContext(target), vfsProjectDocument),
vfsProjectDocument);
vfsProjectDocument,
projectLocalStudioStateService,
projectLocalStudioStateService.load(target));
}
private LspProjectContext lspProjectContext(final ProjectReference projectReference) {
@@ -0,0 +1,228 @@
package p.studio.projectstate;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public record ProjectLocalStudioState(
int version,
ProjectLocalSetup projectLocalSetup,
ShellLayout shellLayout,
OpenShellState openShellState,
EditorRestorationState editorRestoration) {
public static final int CURRENT_VERSION = 1;
public ProjectLocalStudioState {
version = version <= 0 ? CURRENT_VERSION : version;
projectLocalSetup = projectLocalSetup == null ? ProjectLocalSetup.defaults() : projectLocalSetup.normalize();
shellLayout = shellLayout == null ? ShellLayout.defaults() : shellLayout.normalize();
openShellState = openShellState == null ? OpenShellState.defaults() : openShellState.normalize();
editorRestoration = editorRestoration == null ? EditorRestorationState.defaults() : editorRestoration.normalize();
}
public static ProjectLocalStudioState defaults() {
return new ProjectLocalStudioState(
CURRENT_VERSION,
ProjectLocalSetup.defaults(),
ShellLayout.defaults(),
OpenShellState.defaults(),
EditorRestorationState.defaults());
}
public ProjectLocalStudioState withShellLayout(final ShellLayout nextShellLayout) {
return new ProjectLocalStudioState(version, projectLocalSetup, nextShellLayout, openShellState, editorRestoration);
}
public ProjectLocalStudioState withOpenShellState(final OpenShellState nextOpenShellState) {
return new ProjectLocalStudioState(version, projectLocalSetup, shellLayout, nextOpenShellState, editorRestoration);
}
public ProjectLocalStudioState withEditorRestoration(final EditorRestorationState nextEditorRestoration) {
return new ProjectLocalStudioState(version, projectLocalSetup, shellLayout, openShellState, nextEditorRestoration);
}
public ProjectLocalStudioState withProjectLocalSetup(final ProjectLocalSetup nextProjectLocalSetup) {
return new ProjectLocalStudioState(version, nextProjectLocalSetup, shellLayout, openShellState, editorRestoration);
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record ProjectLocalSetup(String prometeuRuntimePath) {
public ProjectLocalSetup {
prometeuRuntimePath = normalizeText(prometeuRuntimePath);
}
public static ProjectLocalSetup defaults() {
return new ProjectLocalSetup(null);
}
private ProjectLocalSetup normalize() {
return new ProjectLocalSetup(prometeuRuntimePath);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record ShellLayout(EditorLayoutState editorLayout, AssetsLayoutState assetsLayout) {
public ShellLayout {
editorLayout = editorLayout == null ? EditorLayoutState.defaults() : editorLayout.normalize();
assetsLayout = assetsLayout == null ? AssetsLayoutState.defaults() : assetsLayout.normalize();
}
public static ShellLayout defaults() {
return new ShellLayout(EditorLayoutState.defaults(), AssetsLayoutState.defaults());
}
private ShellLayout normalize() {
return new ShellLayout(editorLayout, assetsLayout);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record AssetsLayoutState(List<Double> contentSplitDividers) {
public AssetsLayoutState {
contentSplitDividers = normalizeDividerPositions(contentSplitDividers);
}
public static AssetsLayoutState defaults() {
return new AssetsLayoutState(List.of());
}
private AssetsLayoutState normalize() {
return new AssetsLayoutState(contentSplitDividers);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record OpenShellState(String selectedWorkspaceId) {
public OpenShellState {
selectedWorkspaceId = normalizeText(selectedWorkspaceId);
}
public static OpenShellState defaults() {
return new OpenShellState(null);
}
private OpenShellState normalize() {
return new OpenShellState(selectedWorkspaceId);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record EditorLayoutState(
List<Double> contentSplitDividers,
List<Double> leftColumnDividers,
List<Double> rightColumnDividers,
DockPanelState outlinePanel,
DockPanelState helperPanel,
List<String> navigatorExpandedPaths) {
public EditorLayoutState {
contentSplitDividers = normalizeDividerPositions(contentSplitDividers);
leftColumnDividers = normalizeDividerPositions(leftColumnDividers);
rightColumnDividers = normalizeDividerPositions(rightColumnDividers);
outlinePanel = outlinePanel == null ? DockPanelState.defaults() : outlinePanel.normalize();
helperPanel = helperPanel == null ? DockPanelState.defaults() : helperPanel.normalize();
navigatorExpandedPaths = normalizePaths(navigatorExpandedPaths);
}
public static EditorLayoutState defaults() {
return new EditorLayoutState(
List.of(),
List.of(),
List.of(),
DockPanelState.defaults(),
DockPanelState.defaults(),
List.of());
}
private EditorLayoutState normalize() {
return new EditorLayoutState(
contentSplitDividers,
leftColumnDividers,
rightColumnDividers,
outlinePanel,
helperPanel,
navigatorExpandedPaths);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record DockPanelState(boolean expanded, Double dividerPosition) {
public DockPanelState {
dividerPosition = normalizeDividerPosition(dividerPosition);
}
public static DockPanelState defaults() {
return new DockPanelState(true, null);
}
private DockPanelState normalize() {
return new DockPanelState(expanded, dividerPosition);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record EditorRestorationState(List<String> openTabPaths, String activeTabPath) {
public EditorRestorationState {
openTabPaths = normalizePaths(openTabPaths);
activeTabPath = normalizeText(activeTabPath);
if (activeTabPath != null && !openTabPaths.contains(activeTabPath)) {
final List<String> expanded = new ArrayList<>(openTabPaths);
expanded.add(activeTabPath);
openTabPaths = List.copyOf(expanded);
}
}
public static EditorRestorationState defaults() {
return new EditorRestorationState(List.of(), null);
}
private EditorRestorationState normalize() {
return new EditorRestorationState(openTabPaths, activeTabPath);
}
}
private static String normalizeText(final String value) {
if (value == null) {
return null;
}
final String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
private static List<String> normalizePaths(final List<String> values) {
if (values == null || values.isEmpty()) {
return List.of();
}
final LinkedHashSet<String> normalized = new LinkedHashSet<>();
for (final String value : values) {
final String text = normalizeText(value);
if (text != null) {
normalized.add(text);
}
}
return List.copyOf(normalized);
}
private static List<Double> normalizeDividerPositions(final List<Double> values) {
if (values == null || values.isEmpty()) {
return List.of();
}
final List<Double> normalized = new ArrayList<>();
for (final Double value : values) {
if (value == null || value.isNaN() || value.isInfinite()) {
continue;
}
normalized.add(Math.max(0.0d, Math.min(1.0d, value)));
}
return List.copyOf(normalized);
}
private static Double normalizeDividerPosition(final Double value) {
if (value == null || value.isNaN() || value.isInfinite()) {
return null;
}
return Math.max(0.0d, Math.min(1.0d, value));
}
}
@@ -0,0 +1,45 @@
package p.studio.projectstate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import p.studio.projects.ProjectReference;
import p.studio.projects.ProjectStudioPaths;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
public class ProjectLocalStudioStateService {
private static final ObjectMapper MAPPER = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT);
public ProjectLocalStudioState load(final ProjectReference projectReference) {
final Path statePath = ProjectStudioPaths.statePath(projectReference);
if (!Files.isRegularFile(statePath)) {
return ProjectLocalStudioState.defaults();
}
try {
final ProjectLocalStudioState loaded = MAPPER.readValue(statePath.toFile(), ProjectLocalStudioState.class);
if (loaded == null || loaded.version() != ProjectLocalStudioState.CURRENT_VERSION) {
return ProjectLocalStudioState.defaults();
}
return loaded;
} catch (IOException | RuntimeException ignored) {
return ProjectLocalStudioState.defaults();
}
}
public void save(final ProjectReference projectReference, final ProjectLocalStudioState state) {
final Path statePath = ProjectStudioPaths.statePath(projectReference);
final ProjectLocalStudioState normalized = Objects.requireNonNull(state, "state");
try {
Files.createDirectories(statePath.getParent());
MAPPER.writeValue(statePath.toFile(), normalized);
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
}
@@ -4,6 +4,7 @@ import javafx.scene.layout.BorderPane;
import p.studio.Container;
import p.studio.controls.shell.*;
import p.studio.lsp.events.StudioWorkspaceSelectedEvent;
import p.studio.projectstate.ProjectLocalStudioState;
import p.studio.projects.ProjectReference;
import p.studio.projectsessions.StudioProjectSession;
import p.studio.utilities.i18n.I18n;
@@ -19,23 +20,36 @@ public final class MainView extends BorderPane {
private final WorkspaceHost host = new WorkspaceHost();
private final ProjectReference projectReference;
private final StudioProjectSession projectSession;
private final AssetWorkspace assetWorkspace;
private final EditorWorkspace editorWorkspace;
private final StudioWorkspaceRailControl<WorkspaceId> workspaceRail;
private boolean initializing;
private boolean workspaceLifecycleInitialized;
public MainView(final StudioProjectSession projectSession) {
initializing = true;
this.projectSession = projectSession;
this.projectReference = projectSession.projectReference();
final ProjectLocalStudioState persistedState = projectSession.projectLocalStudioState();
final var menuBar = new StudioShellMenuBarControl();
final var runSurface = new StudioRunSurfaceControl();
setTop(new StudioShellTopBarControl(menuBar));
host.register(new AssetWorkspace(projectReference));
host.register(new EditorWorkspace(
assetWorkspace = new AssetWorkspace(projectReference);
host.register(assetWorkspace);
editorWorkspace = new EditorWorkspace(
projectReference,
projectSession.projectDocumentVfs(),
projectSession.prometeuLspService()));
projectSession.prometeuLspService());
host.register(editorWorkspace);
assetWorkspace.restoreProjectLocalState(persistedState);
editorWorkspace.restoreProjectLocalState(persistedState);
assetWorkspace.setStateChangedAction(this::persistProjectLocalState);
editorWorkspace.setStateChangedAction(this::persistProjectLocalState);
// host.register(new PlaceholderWorkspace(WorkspaceId.DEBUG, I18n.WORKSPACE_DEBUG, "Debug"));
host.register(new ShipperWorkspace(projectReference));
final var workspaceRail = new StudioWorkspaceRailControl<>(
workspaceRail = new StudioWorkspaceRailControl<>(
List.of(
new StudioWorkspaceRailItem<>(WorkspaceId.ASSETS, "📦", Container.i18n().bind(I18n.WORKSPACE_ASSETS)),
new StudioWorkspaceRailItem<>(WorkspaceId.EDITOR, "📝", Container.i18n().bind(I18n.WORKSPACE_CODE)),
@@ -50,9 +64,11 @@ public final class MainView extends BorderPane {
Container.i18n().bind(I18n.SHELL_ACTIVITY),
new StudioActivityFeedControl(projectReference)));
// default
workspaceRail.select(WorkspaceId.ASSETS);
loadWorkspace(WorkspaceId.ASSETS);
final WorkspaceId initialWorkspace = restoreInitialWorkspace(persistedState.openShellState());
workspaceRail.select(initialWorkspace);
loadWorkspace(initialWorkspace);
workspaceLifecycleInitialized = true;
initializing = false;
}
public ProjectReference projectReference() {
@@ -63,8 +79,43 @@ public final class MainView extends BorderPane {
return projectSession;
}
public void persistProjectLocalState() {
if (initializing) {
return;
}
final WorkspaceId selectedWorkspace = host.getCurrentWorkspaceId() == null ? WorkspaceId.ASSETS : host.getCurrentWorkspaceId();
final ProjectLocalStudioState current = projectSession.projectLocalStudioState();
projectSession.replaceProjectLocalStudioState(
current.withOpenShellState(new ProjectLocalStudioState.OpenShellState(selectedWorkspace.name()))
.withShellLayout(new ProjectLocalStudioState.ShellLayout(
editorWorkspace.captureLayoutState(),
assetWorkspace.captureLayoutState()))
.withEditorRestoration(editorWorkspace.captureRestorationState()));
}
public void reapplyProjectLocalLayout() {
assetWorkspace.reapplyPendingLayoutState();
editorWorkspace.reapplyPendingLayoutState();
}
private void loadWorkspace(WorkspaceId workspaceId) {
host.change(workspaceId);
if (workspaceLifecycleInitialized) {
persistProjectLocalState();
projectSession.saveProjectLocalStudioState();
}
Container.eventBus().publish(new StudioWorkspaceSelectedEvent(workspaceId));
}
private WorkspaceId restoreInitialWorkspace(final ProjectLocalStudioState.OpenShellState openShellState) {
if (openShellState.selectedWorkspaceId() == null) {
return WorkspaceId.ASSETS;
}
try {
return WorkspaceId.valueOf(openShellState.selectedWorkspaceId());
} catch (IllegalArgumentException ignored) {
return WorkspaceId.ASSETS;
}
}
}
@@ -146,7 +146,8 @@ public final class StudioWindowCoordinator {
private void finishProjectOpen(StudioProjectSession projectSession, Stage loadingStage) {
final ProjectReference projectReference = projectSession.projectReference();
final Stage projectStage = new Stage();
final Scene scene = new Scene(new MainView(projectSession), PROJECT_WIDTH, PROJECT_HEIGHT);
final MainView mainView = new MainView(projectSession);
final Scene scene = new Scene(mainView, PROJECT_WIDTH, PROJECT_HEIGHT);
scene.getStylesheets().add(Container.theme().getDefaultTheme());
projectStage.setTitle(Container.i18n().format(I18n.APP_PROJECT_TITLE, projectReference.name()));
@@ -169,6 +170,7 @@ public final class StudioWindowCoordinator {
loadingStage.close();
projectStage.show();
projectStage.toFront();
Platform.runLater(mainView::reapplyProjectLocalLayout);
}
private void failProjectOpen(
@@ -9,6 +9,7 @@ import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.projectstate.ProjectLocalStudioState;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.Workspace;
@@ -27,6 +28,10 @@ public final class AssetWorkspace extends Workspace {
private final AssetListControl assetListControl;
private final AssetDetailsControl detailsControl;
private final AssetLogsPane logsPane;
private SplitPane splitPane;
private Runnable stateChangedAction = () -> { };
private ProjectLocalStudioState.AssetsLayoutState pendingAssetsLayoutState = ProjectLocalStudioState.AssetsLayoutState.defaults();
private boolean applyingPendingLayoutState;
public AssetWorkspace(final ProjectReference projectReference) {
super(projectReference);
@@ -55,6 +60,8 @@ public final class AssetWorkspace extends Workspace {
@Override
public void load() {
reapplyPendingLayoutState();
schedulePendingLayoutReapply();
workspaceEventBus.publish(new StudioAssetsRefreshRequestedEvent());
}
@@ -67,6 +74,37 @@ public final class AssetWorkspace extends Workspace {
return List.of(assetListControl, detailsControl, logsPane);
}
public void setStateChangedAction(final Runnable stateChangedAction) {
this.stateChangedAction = java.util.Objects.requireNonNull(stateChangedAction, "stateChangedAction");
}
public void restoreProjectLocalState(final ProjectLocalStudioState projectLocalStudioState) {
pendingAssetsLayoutState = projectLocalStudioState.shellLayout().assetsLayout();
reapplyPendingLayoutState();
schedulePendingLayoutReapply();
}
public void reapplyPendingLayoutState() {
if (splitPane == null || pendingAssetsLayoutState.contentSplitDividers().isEmpty()) {
return;
}
applyingPendingLayoutState = true;
splitPane.setDividerPositions(pendingAssetsLayoutState.contentSplitDividers().stream()
.mapToDouble(Double::doubleValue)
.toArray());
javafx.application.Platform.runLater(() -> applyingPendingLayoutState = false);
}
public ProjectLocalStudioState.AssetsLayoutState captureLayoutState() {
if (splitPane == null || splitPane.getDividers().isEmpty()) {
return ProjectLocalStudioState.AssetsLayoutState.defaults();
}
return new ProjectLocalStudioState.AssetsLayoutState(
splitPane.getDividers().stream()
.map(SplitPane.Divider::getPosition)
.toList());
}
private VBox buildLayout() {
final var topProgress = createTopProgressBox();
final var actionBar = createActionBar();
@@ -144,10 +182,37 @@ public final class AssetWorkspace extends Workspace {
}
private SplitPane createAssetSplitPane() {
final var splitPane = new SplitPane(assetListControl, detailsControl);
splitPane = new SplitPane(assetListControl, detailsControl);
splitPane.setDividerPositions(0.34);
splitPane.getStyleClass().add("assets-workspace-split");
splitPane.getDividers().forEach(divider ->
divider.positionProperty().addListener((ignored, previous, current) -> {
if (applyingPendingLayoutState) {
return;
}
pendingAssetsLayoutState = captureLayoutState();
stateChangedAction.run();
}));
VBox.setVgrow(splitPane, Priority.ALWAYS);
return splitPane;
}
private void schedulePendingLayoutReapply() {
if (splitPane == null) {
return;
}
if (splitPane.getWidth() > 0) {
javafx.application.Platform.runLater(this::reapplyPendingLayoutState);
return;
}
final javafx.beans.value.ChangeListener<Number>[] listenerRef = new javafx.beans.value.ChangeListener[1];
listenerRef[0] = (ignored, previous, current) -> {
if (current == null || current.doubleValue() <= 0) {
return;
}
splitPane.widthProperty().removeListener(listenerRef[0]);
javafx.application.Platform.runLater(this::reapplyPendingLayoutState);
};
splitPane.widthProperty().addListener(listenerRef[0]);
}
}
@@ -1,5 +1,7 @@
package p.studio.workspaces.editor;
import p.studio.projectstate.ProjectLocalStudioState;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -51,6 +53,19 @@ public final class EditorOpenFileSession {
return openFiles.isEmpty();
}
public void clear() {
openFiles.clear();
activePath = null;
}
public ProjectLocalStudioState.EditorRestorationState restorationState() {
return new ProjectLocalStudioState.EditorRestorationState(
openFiles.stream()
.map(buffer -> buffer.path().toString())
.toList(),
activePath == null ? null : activePath.toString());
}
private Optional<EditorOpenFileBuffer> find(final Path path) {
final int index = indexOf(path);
if (index < 0) {
@@ -19,7 +19,9 @@ import p.studio.vfs.messages.VfsProjectNode;
import p.studio.vfs.messages.VfsProjectSnapshot;
import java.nio.file.Path;
import java.util.LinkedHashSet;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -34,6 +36,7 @@ public final class EditorProjectNavigatorPanel extends BorderPane {
private Runnable revealActiveFileAction = () -> { };
private Runnable refreshAction = () -> { };
private Consumer<VfsProjectNode> fileSelectionAction = node -> { };
private Set<Path> preferredExpandedPaths = Set.of();
public EditorProjectNavigatorPanel() {
getStyleClass().addAll("editor-workspace-panel", "editor-workspace-navigator-panel");
@@ -129,13 +132,42 @@ public final class EditorProjectNavigatorPanel extends BorderPane {
public void setSnapshot(final VfsProjectSnapshot snapshot) {
final var currentSelection = selectedPath();
final var expandedPaths = captureExpandedPaths(treeView.getRoot());
final var expandedPaths = mergeExpandedPaths();
final var rootItem = buildTreeItem(Objects.requireNonNull(snapshot, "snapshot").rootNode(), expandedPaths, true);
treeView.setRoot(rootItem);
restoreSelection(rootItem, currentSelection);
showEmptyState(false);
}
public List<String> expandedPathStrings() {
return captureExpandedPaths(treeView.getRoot()).stream()
.map(Path::toString)
.toList();
}
public void restoreExpandedPaths(final List<String> expandedPaths) {
final LinkedHashSet<Path> restored = new LinkedHashSet<>();
if (expandedPaths != null) {
for (final String expandedPath : expandedPaths) {
if (expandedPath == null || expandedPath.isBlank()) {
continue;
}
try {
restored.add(Path.of(expandedPath).toAbsolutePath().normalize());
} catch (RuntimeException ignored) {
// Ignore malformed persisted paths and continue with the remaining ones.
}
}
}
preferredExpandedPaths = Set.copyOf(restored);
final TreeItem<VfsProjectNode> rootItem = treeView.getRoot();
if (rootItem != null) {
final var currentSelection = selectedPath();
treeView.setRoot(buildTreeItem(rootItem.getValue(), preferredExpandedPaths, true));
restoreSelection(treeView.getRoot(), currentSelection);
}
}
public void revealPath(final Path path) {
final var normalizedPath = Objects.requireNonNull(path, "path").toAbsolutePath().normalize();
final var rootItem = treeView.getRoot();
@@ -180,6 +212,12 @@ public final class EditorProjectNavigatorPanel extends BorderPane {
item.getChildren().forEach(child -> collectExpandedPaths(child, expandedPaths));
}
private Set<Path> mergeExpandedPaths() {
final LinkedHashSet<Path> merged = new LinkedHashSet<>(preferredExpandedPaths);
merged.addAll(captureExpandedPaths(treeView.getRoot()));
return Set.copyOf(merged);
}
private Optional<Path> selectedPath() {
return Optional.ofNullable(treeView.getSelectionModel().getSelectedItem())
.map(TreeItem::getValue)
@@ -15,6 +15,7 @@ import org.reactfx.Subscription;
import p.studio.lsp.LspService;
import p.studio.lsp.messages.LspAnalyzeDocumentRequest;
import p.studio.lsp.messages.LspAnalyzeDocumentResult;
import p.studio.projectstate.ProjectLocalStudioState;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.vfs.VfsProjectDocument;
@@ -55,6 +56,12 @@ public final class EditorWorkspace extends Workspace {
presentationRegistry.resolve("text").highlight(""),
List.of());
private boolean syncingEditor;
private boolean applyingPendingLayoutState;
private Runnable stateChangedAction = () -> { };
private ProjectLocalStudioState.EditorLayoutState pendingEditorLayoutState = ProjectLocalStudioState.EditorLayoutState.defaults();
private SplitPane contentSplit;
private SplitPane leftColumnSplit;
private SplitPane rightColumnSplit;
public EditorWorkspace(
final ProjectReference projectReference,
@@ -91,6 +98,7 @@ public final class EditorWorkspace extends Workspace {
navigatorPanel.setFileSelectionAction(this::openNode);
tabStrip.setTabSelectionAction(path -> {
openFileSession.activate(path);
notifyStateChanged();
renderSession();
});
@@ -104,6 +112,8 @@ public final class EditorWorkspace extends Workspace {
@Override
public void load() {
applyEditorLayoutState(pendingEditorLayoutState);
schedulePendingLayoutReapply();
refreshNavigator();
}
@@ -114,6 +124,36 @@ public final class EditorWorkspace extends Workspace {
public CodeArea codeArea() { return codeArea; }
public void setStateChangedAction(final Runnable stateChangedAction) {
this.stateChangedAction = Objects.requireNonNull(stateChangedAction, "stateChangedAction");
}
public void restoreProjectLocalState(final ProjectLocalStudioState projectLocalStudioState) {
final ProjectLocalStudioState state = Objects.requireNonNull(projectLocalStudioState, "projectLocalStudioState");
pendingEditorLayoutState = state.shellLayout().editorLayout();
reapplyPendingLayoutState();
schedulePendingLayoutReapply();
restoreEditorState(state.editorRestoration());
}
public void reapplyPendingLayoutState() {
applyEditorLayoutState(pendingEditorLayoutState);
}
public ProjectLocalStudioState.EditorLayoutState captureLayoutState() {
return new ProjectLocalStudioState.EditorLayoutState(
dividerPositions(contentSplit),
dividerPositions(leftColumnSplit),
dividerPositions(rightColumnSplit),
dockPanelState(outlinePanel),
dockPanelState(helperPanel),
navigatorPanel.expandedPathStrings());
}
public ProjectLocalStudioState.EditorRestorationState captureRestorationState() {
return openFileSession.restorationState();
}
private void refreshNavigator() {
navigatorPanel.setSnapshot(vfsProjectDocument.refresh());
}
@@ -129,6 +169,7 @@ public final class EditorWorkspace extends Workspace {
private void openFile(final VfsDocumentOpenResult.VfsTextDocument textDocument) {
openFileSession.open(bufferFrom(textDocument));
notifyStateChanged();
renderSession();
}
@@ -254,19 +295,23 @@ public final class EditorWorkspace extends Workspace {
}
private VBox buildLayout() {
final var content = new SplitPane(buildLeftColumn(), buildRightColumn());
content.setDividerPositions(0.30);
content.getStyleClass().add("editor-workspace-split");
contentSplit = new SplitPane(buildLeftColumn(), buildRightColumn());
contentSplit.setDividerPositions(0.30);
contentSplit.getStyleClass().add("editor-workspace-split");
observeStatefulSplitPane(contentSplit);
final var layout = new VBox(12, buildCommandBar(), content, statusBar);
final var layout = new VBox(12, buildCommandBar(), contentSplit, statusBar);
layout.getStyleClass().add("editor-workspace-layout");
VBox.setVgrow(content, Priority.ALWAYS);
VBox.setVgrow(contentSplit, Priority.ALWAYS);
return layout;
}
private SplitPane buildLeftColumn() {
final var leftColumn = outlinePanel.createBottomDockLayout(navigatorPanel, "editor-workspace-left-split");
leftColumnSplit = outlinePanel.createBottomDockLayout(navigatorPanel, "editor-workspace-left-split");
final var leftColumn = leftColumnSplit;
leftColumn.getStyleClass().add("editor-workspace-left-column");
observeStatefulSplitPane(leftColumnSplit);
observeDockPane(outlinePanel);
return leftColumn;
}
@@ -284,7 +329,10 @@ public final class EditorWorkspace extends Workspace {
}
private SplitPane buildRightColumn() {
return helperPanel.createBottomDockLayout(buildCenterColumn(), "editor-workspace-right-split");
rightColumnSplit = helperPanel.createBottomDockLayout(buildCenterColumn(), "editor-workspace-right-split");
observeStatefulSplitPane(rightColumnSplit);
observeDockPane(helperPanel);
return rightColumnSplit;
}
private void configureCommandBar() {
@@ -454,4 +502,134 @@ public final class EditorWorkspace extends Workspace {
codeArea.moveTo(inlineHintProjection.clampCaret(caret, true));
}
}
private void restoreEditorState(final ProjectLocalStudioState.EditorRestorationState editorRestorationState) {
openFileSession.clear();
for (final String pathText : editorRestorationState.openTabPaths()) {
tryRestoreOpenFile(pathText);
}
if (editorRestorationState.activeTabPath() != null) {
try {
openFileSession.activate(Path.of(editorRestorationState.activeTabPath()));
} catch (RuntimeException ignored) {
// Fall back to the currently active restored tab.
}
}
renderSession();
}
private void tryRestoreOpenFile(final String pathText) {
try {
final Path path = Path.of(pathText).toAbsolutePath().normalize();
final VfsDocumentOpenResult result = vfsProjectDocument.openDocument(path);
if (result instanceof VfsDocumentOpenResult.VfsTextDocument textDocument) {
openFileSession.open(bufferFrom(textDocument));
}
} catch (RuntimeException ignored) {
// Invalid or unavailable persisted tabs are skipped and the editor falls back to the remaining state.
}
}
private List<Double> dividerPositions(final SplitPane splitPane) {
if (splitPane == null || splitPane.getDividers().isEmpty()) {
return List.of();
}
return splitPane.getDividers().stream()
.map(SplitPane.Divider::getPosition)
.toList();
}
private void applyDividerPositions(final SplitPane splitPane, final List<Double> positions) {
if (splitPane == null || positions == null || positions.isEmpty()) {
return;
}
final double[] values = positions.stream().mapToDouble(Double::doubleValue).toArray();
splitPane.setDividerPositions(values);
}
private ProjectLocalStudioState.DockPanelState dockPanelState(final p.studio.controls.WorkspaceDockPane dockPane) {
final p.studio.controls.WorkspaceDockPane.DockState state = dockPane.captureDockState();
return new ProjectLocalStudioState.DockPanelState(state.expanded(), state.dividerPosition());
}
private void restoreDockPanelState(
final p.studio.controls.WorkspaceDockPane dockPane,
final ProjectLocalStudioState.DockPanelState dockPanelState) {
if (dockPanelState == null) {
return;
}
final double dividerPosition = dockPanelState.dividerPosition() == null
? dockPane.captureDockState().dividerPosition()
: dockPanelState.dividerPosition();
dockPane.restoreDockState(new p.studio.controls.WorkspaceDockPane.DockState(
dockPanelState.expanded(),
dividerPosition));
}
private void observeStatefulSplitPane(final SplitPane splitPane) {
splitPane.getDividers().forEach(divider ->
divider.positionProperty().addListener((ignored, previous, current) -> {
if (applyingPendingLayoutState) {
return;
}
notifyStateChanged();
}));
splitPane.getDividers().addListener((javafx.collections.ListChangeListener<? super SplitPane.Divider>) change -> {
while (change.next()) {
if (change.wasAdded()) {
change.getAddedSubList().forEach(divider ->
divider.positionProperty().addListener((ignored, previous, current) -> {
if (applyingPendingLayoutState) {
return;
}
notifyStateChanged();
}));
}
}
});
}
private void observeDockPane(final p.studio.controls.WorkspaceDockPane dockPane) {
dockPane.expandedProperty().addListener((ignored, previous, current) -> {
if (applyingPendingLayoutState) {
return;
}
notifyStateChanged();
});
}
private void notifyStateChanged() {
pendingEditorLayoutState = captureLayoutState();
stateChangedAction.run();
}
private void schedulePendingLayoutReapply() {
if (contentSplit == null) {
return;
}
if (contentSplit.getWidth() > 0) {
Platform.runLater(this::reapplyPendingLayoutState);
return;
}
final javafx.beans.value.ChangeListener<Number>[] listenerRef = new javafx.beans.value.ChangeListener[1];
listenerRef[0] = (ignored, previous, current) -> {
if (current == null || current.doubleValue() <= 0) {
return;
}
contentSplit.widthProperty().removeListener(listenerRef[0]);
Platform.runLater(this::reapplyPendingLayoutState);
};
contentSplit.widthProperty().addListener(listenerRef[0]);
}
private void applyEditorLayoutState(final ProjectLocalStudioState.EditorLayoutState editorLayoutState) {
applyingPendingLayoutState = true;
applyDividerPositions(contentSplit, editorLayoutState.contentSplitDividers());
applyDividerPositions(leftColumnSplit, editorLayoutState.leftColumnDividers());
applyDividerPositions(rightColumnSplit, editorLayoutState.rightColumnDividers());
restoreDockPanelState(outlinePanel, editorLayoutState.outlinePanel());
restoreDockPanelState(helperPanel, editorLayoutState.helperPanel());
navigatorPanel.restoreExpandedPaths(editorLayoutState.navigatorExpandedPaths());
Platform.runLater(() -> applyingPendingLayoutState = false);
}
}
@@ -4,6 +4,8 @@ import org.junit.jupiter.api.Test;
import p.studio.lsp.messages.LspProjectContext;
import p.studio.lsp.LspService;
import p.studio.lsp.LspServiceFactory;
import p.studio.projectstate.ProjectLocalStudioState;
import p.studio.projectstate.ProjectLocalStudioStateService;
import p.studio.lsp.dtos.LspSessionStateDTO;
import p.studio.lsp.messages.LspAnalyzeDocumentRequest;
import p.studio.lsp.messages.LspAnalyzeDocumentResult;
@@ -27,7 +29,8 @@ final class StudioProjectSessionFactoryTest {
void openCreatesProjectSessionBackedByProjectScopedVfs() {
final RecordingLspFactory lspFactory = new RecordingLspFactory();
final RecordingVfsFactory vfsFactory = new RecordingVfsFactory();
final StudioProjectSessionFactory sessionFactory = new StudioProjectSessionFactory(lspFactory, vfsFactory);
final RecordingProjectLocalStudioStateService stateService = new RecordingProjectLocalStudioStateService();
final StudioProjectSessionFactory sessionFactory = new StudioProjectSessionFactory(lspFactory, vfsFactory, stateService);
final ProjectReference projectReference = new ProjectReference(
"Example",
"1.0.0",
@@ -46,6 +49,24 @@ final class StudioProjectSessionFactoryTest {
assertEquals("Example", lspFactory.capturedContext.projectName());
assertEquals("pbs", lspFactory.capturedContext.languageId());
assertSame(vfsFactory.vfs, lspFactory.capturedVfs);
assertSame(stateService.loadedState, session.projectLocalStudioState());
assertSame(projectReference, stateService.loadedProjectReference);
}
private static final class RecordingProjectLocalStudioStateService extends ProjectLocalStudioStateService {
private ProjectReference loadedProjectReference;
private final ProjectLocalStudioState loadedState = new ProjectLocalStudioState(
ProjectLocalStudioState.CURRENT_VERSION,
new ProjectLocalStudioState.ProjectLocalSetup("/opt/prometeu"),
ProjectLocalStudioState.ShellLayout.defaults(),
new ProjectLocalStudioState.OpenShellState("EDITOR"),
ProjectLocalStudioState.EditorRestorationState.defaults());
@Override
public ProjectLocalStudioState load(final ProjectReference projectReference) {
this.loadedProjectReference = projectReference;
return loadedState;
}
}
private static final class RecordingVfsFactory implements ProjectDocumentVfsFactory {
@@ -3,6 +3,8 @@ package p.studio.projectsessions;
import org.junit.jupiter.api.Test;
import p.studio.lsp.messages.LspProjectContext;
import p.studio.lsp.LspService;
import p.studio.projectstate.ProjectLocalStudioState;
import p.studio.projectstate.ProjectLocalStudioStateService;
import p.studio.lsp.dtos.LspSessionStateDTO;
import p.studio.lsp.messages.LspAnalyzeDocumentRequest;
import p.studio.lsp.messages.LspAnalyzeDocumentResult;
@@ -24,19 +26,60 @@ final class StudioProjectSessionTest {
void closeDelegatesToUnderlyingServicesOnlyOnce() {
final CountingVfsProjectDocument vfs = new CountingVfsProjectDocument();
final CountingPrometeuLspService lsp = new CountingPrometeuLspService(vfs);
final StudioProjectSession session = new StudioProjectSession(projectReference(), lsp, vfs);
final RecordingProjectLocalStudioStateService stateService = new RecordingProjectLocalStudioStateService();
final StudioProjectSession session = new StudioProjectSession(
projectReference(),
lsp,
vfs,
stateService,
ProjectLocalStudioState.defaults());
session.close();
session.close();
assertEquals(1, lsp.closeCalls);
assertEquals(1, vfs.closeCalls);
assertEquals(1, stateService.saveCalls);
assertEquals(projectReference(), stateService.savedProjectReference);
}
@Test
void replaceProjectLocalStudioStateUpdatesTheSavedSnapshot() {
final CountingVfsProjectDocument vfs = new CountingVfsProjectDocument();
final CountingPrometeuLspService lsp = new CountingPrometeuLspService(vfs);
final RecordingProjectLocalStudioStateService stateService = new RecordingProjectLocalStudioStateService();
final StudioProjectSession session = new StudioProjectSession(
projectReference(),
lsp,
vfs,
stateService,
ProjectLocalStudioState.defaults());
final ProjectLocalStudioState nextState = ProjectLocalStudioState.defaults()
.withProjectLocalSetup(new ProjectLocalStudioState.ProjectLocalSetup("/opt/prometeu/runtime"));
session.replaceProjectLocalStudioState(nextState);
session.close();
assertEquals("/opt/prometeu/runtime", stateService.savedState.projectLocalSetup().prometeuRuntimePath());
}
private ProjectReference projectReference() {
return new ProjectReference("Example", "1.0.0", "pbs", 1, Path.of("/tmp/example"));
}
private static final class RecordingProjectLocalStudioStateService extends ProjectLocalStudioStateService {
private int saveCalls;
private ProjectReference savedProjectReference;
private ProjectLocalStudioState savedState;
@Override
public void save(final ProjectReference projectReference, final ProjectLocalStudioState state) {
saveCalls++;
savedProjectReference = projectReference;
savedState = state;
}
}
private static final class CountingVfsProjectDocument implements VfsProjectDocument {
private int closeCalls;
@@ -0,0 +1,83 @@
package p.studio.projectstate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.projects.ProjectReference;
import p.studio.projects.ProjectStudioPaths;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
final class ProjectLocalStudioStateServiceTest {
@TempDir
Path tempDir;
@Test
void savesAndLoadsSingleFileProjectLocalStudioState() {
final ProjectLocalStudioStateService service = new ProjectLocalStudioStateService();
final ProjectReference project = project("main");
final ProjectLocalStudioState state = new ProjectLocalStudioState(
ProjectLocalStudioState.CURRENT_VERSION,
new ProjectLocalStudioState.ProjectLocalSetup("/opt/prometeu/runtime"),
new ProjectLocalStudioState.ShellLayout(
new ProjectLocalStudioState.EditorLayoutState(
List.of(0.25d),
List.of(0.80d),
List.of(0.70d),
new ProjectLocalStudioState.DockPanelState(true, 0.80d),
new ProjectLocalStudioState.DockPanelState(false, 0.70d),
List.of(
project.rootPath().resolve("src").toString(),
project.rootPath().resolve("src/game").toString())),
new ProjectLocalStudioState.AssetsLayoutState(List.of(0.42d))),
new ProjectLocalStudioState.OpenShellState("EDITOR"),
new ProjectLocalStudioState.EditorRestorationState(
List.of(
project.rootPath().resolve("src/main.pbs").toString(),
project.rootPath().resolve("README.md").toString()),
project.rootPath().resolve("src/main.pbs").toString()));
service.save(project, state);
assertTrue(Files.isRegularFile(ProjectStudioPaths.statePath(project)));
assertEquals(state, service.load(project));
}
@Test
void malformedStateFallsBackToDefaults() throws Exception {
final ProjectLocalStudioStateService service = new ProjectLocalStudioStateService();
final ProjectReference project = project("main");
Files.createDirectories(ProjectStudioPaths.studioRoot(project));
Files.writeString(ProjectStudioPaths.statePath(project), "{ not valid json");
assertEquals(ProjectLocalStudioState.defaults(), service.load(project));
}
@Test
void unsupportedVersionFallsBackToDefaults() throws Exception {
final ProjectLocalStudioStateService service = new ProjectLocalStudioStateService();
final ProjectReference project = project("main");
Files.createDirectories(ProjectStudioPaths.studioRoot(project));
Files.writeString(
ProjectStudioPaths.statePath(project),
"""
{
"version": 99,
"projectLocalSetup": {
"prometeuRuntimePath": "/opt/legacy/runtime"
}
}
""");
assertEquals(ProjectLocalStudioState.defaults(), service.load(project));
}
private ProjectReference project(final String name) {
final Path projectRoot = tempDir.resolve(name);
return new ProjectReference("Main", "1.0.0", "pbs", 1, projectRoot);
}
}
@@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test;
import p.studio.vfs.messages.VfsDocumentAccessMode;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -67,6 +68,24 @@ final class EditorOpenFileSessionTest {
assertTrue(session.activeFile().orElseThrow().readOnly());
}
@Test
void exportsRestorationStateFromOpenTabsAndActiveTab() {
final var session = new EditorOpenFileSession();
final var first = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.READ_ONLY, false, true, "a");
final var second = fileBuffer(Path.of("README.md"), "README.md", VfsDocumentAccessMode.EDITABLE, false, false, "b");
session.open(first);
session.open(second);
session.activate(first.path());
final var restorationState = session.restorationState();
assertEquals(List.of(
first.path().toAbsolutePath().normalize().toString(),
second.path().toAbsolutePath().normalize().toString()), restorationState.openTabPaths());
assertEquals(first.path().toAbsolutePath().normalize().toString(), restorationState.activeTabPath());
}
private EditorOpenFileBuffer fileBuffer(
final Path path,
final String tabLabel,