editor with write capability

This commit is contained in:
2026-04-04 11:39:04 +01:00
parent fc96e45435
commit a0e19fd143
20 changed files with 1082 additions and 410 deletions
@@ -101,6 +101,11 @@ public enum I18n {
CODE_EDITOR_STATUS_LANGUAGE("codeEditor.status.language"),
CODE_EDITOR_COMMAND_SAVE("codeEditor.command.save"),
CODE_EDITOR_COMMAND_SAVE_ALL("codeEditor.command.saveAll"),
CODE_EDITOR_CLOSE_DIRTY_TITLE("codeEditor.closeDirty.title"),
CODE_EDITOR_CLOSE_DIRTY_MESSAGE("codeEditor.closeDirty.message"),
CODE_EDITOR_CLOSE_DIRTY_SAVE("codeEditor.closeDirty.save"),
CODE_EDITOR_CLOSE_DIRTY_DISCARD("codeEditor.closeDirty.discard"),
CODE_EDITOR_CLOSE_DIRTY_CANCEL("codeEditor.closeDirty.cancel"),
CODE_EDITOR_WARNING_FRONTEND_READ_ONLY("codeEditor.warning.frontendReadOnly"),
CODE_EDITOR_UNSUPPORTED_FILE_TITLE("codeEditor.unsupportedFile.title"),
CODE_EDITOR_UNSUPPORTED_FILE_MESSAGE("codeEditor.unsupportedFile.message"),
@@ -30,6 +30,24 @@ public final class EditorOpenFileSession {
}
}
public void close(final Path path) {
final int index = indexOf(path);
if (index < 0) {
return;
}
final Path normalizedPath = normalize(path);
openFiles.remove(index);
if (openFiles.isEmpty()) {
activePath = null;
return;
}
if (!normalizedPath.equals(activePath)) {
return;
}
final int nextIndex = Math.min(index, openFiles.size() - 1);
activePath = openFiles.get(nextIndex).path();
}
public List<EditorOpenFileBuffer> openFiles() {
return List.copyOf(openFiles);
}
@@ -41,6 +59,10 @@ public final class EditorOpenFileSession {
return find(activePath);
}
public Optional<EditorOpenFileBuffer> file(final Path path) {
return find(normalize(path));
}
public boolean hasDirtyEditableFiles() {
return openFiles.stream().anyMatch(EditorOpenFileBuffer::saveEnabled);
}
@@ -106,7 +106,11 @@ public final class EditorProjectNavigatorPanel extends BorderPane {
}
}
});
treeView.getSelectionModel().selectedItemProperty().addListener((ignored, previous, current) -> {
treeView.setOnMouseClicked(event -> {
if (event.getClickCount() != 2) {
return;
}
final TreeItem<VfsProjectNode> current = treeView.getSelectionModel().getSelectedItem();
if (current == null || current.getValue() == null || current.getValue().directory()) {
return;
}
@@ -4,7 +4,11 @@ import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.*;
@@ -32,6 +36,12 @@ import java.util.Objects;
import java.util.function.IntFunction;
public final class EditorWorkspace extends Workspace {
private static final int CARET_SCROLL_CONTEXT_LINES = 2;
private static final KeyCombination SAVE_SHORTCUT = new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN);
private static final KeyCombination SAVE_ALL_SHORTCUT = new KeyCodeCombination(
KeyCode.S,
KeyCombination.SHORTCUT_DOWN,
KeyCombination.SHIFT_DOWN);
private final BorderPane root = new BorderPane();
private final CodeArea codeArea = new CodeArea();
private final VirtualizedScrollPane<CodeArea> codeScroller = new VirtualizedScrollPane<>(codeArea);
@@ -59,6 +69,8 @@ public final class EditorWorkspace extends Workspace {
List.of());
private boolean syncingEditor;
private boolean applyingPendingLayoutState;
private int activeGuideParagraph = -1;
private boolean pendingCaretContextRestore;
private Runnable stateChangedAction = () -> { };
private ProjectLocalStudioState.EditorLayoutState pendingEditorLayoutState = ProjectLocalStudioState.EditorLayoutState.defaults();
private SplitPane contentSplit;
@@ -81,12 +93,15 @@ public final class EditorWorkspace extends Workspace {
codeArea.textProperty().addListener((ignored, previous, current) -> syncActiveDocumentToVfs(current));
codeArea.caretPositionProperty().addListener((ignored, previous, current) -> {
final int caretOffset = current == null ? 0 : current.intValue();
updateActiveGuides(caretOffset);
updateActiveGuides(caretOffset, codeArea.getCurrentParagraph());
refreshStatusBarCaret();
});
codeArea.estimatedScrollYProperty().addListener((ignored, previous, current) ->
restoreCaretScrollContextIfNeeded(previous, current));
codeArea.getStyleClass().add("editor-workspace-code-area");
codeArea.addEventFilter(KeyEvent.KEY_PRESSED, this::guardInlineHintMutation);
codeArea.addEventFilter(KeyEvent.KEY_TYPED, this::guardInlineHintMutation);
root.addEventFilter(KeyEvent.KEY_PRESSED, this::handleWorkspaceShortcuts);
inlineHintChangeSubscription = codeArea.plainTextChanges().subscribe(change -> {
if (syncingEditor) {
return;
@@ -108,6 +123,7 @@ public final class EditorWorkspace extends Workspace {
notifyStateChanged();
renderSession();
});
tabStrip.setTabCloseAction(this::requestCloseFile);
root.setCenter(buildLayout());
statusBar.showPlaceholder(presentationRegistry.resolve("text"));
@@ -218,16 +234,13 @@ public final class EditorWorkspace extends Workspace {
codeArea.replaceText(inlineHintProjection.displayText());
codeArea.setStyleSpans(0, inlineHintProjection.displayStyles());
codeArea.moveTo(0);
codeArea.requestFollowCaret();
} finally {
syncingEditor = false;
}
activeGuides = scopeGuideModel.resolveActiveGuides(codeArea.getCaretPosition());
activeGuideParagraph = codeArea.getCurrentParagraph();
refreshParagraphGraphics();
Platform.runLater(() -> {
codeArea.moveTo(0);
codeArea.showParagraphAtTop(0);
codeArea.requestFollowCaret();
if (fileBuffer.editable()) {
codeArea.requestFocus();
}
@@ -261,6 +274,7 @@ public final class EditorWorkspace extends Workspace {
final EditorDocumentPresentation presentation = presentationRegistry.resolve("text");
scopeGuideModel = EditorDocumentScopeGuideModel.empty();
activeGuides = EditorDocumentScopeGuideModel.ActiveGuides.empty();
activeGuideParagraph = -1;
refreshParagraphGraphics();
applyPresentationStylesheets(presentation);
syncingEditor = true;
@@ -269,15 +283,9 @@ public final class EditorWorkspace extends Workspace {
codeArea.replaceText("");
codeArea.setStyleSpans(0, inlineHintProjection.displayStyles());
codeArea.moveTo(0);
codeArea.requestFollowCaret();
} finally {
syncingEditor = false;
}
Platform.runLater(() -> {
codeArea.moveTo(0);
codeArea.showParagraphAtTop(0);
codeArea.requestFollowCaret();
});
codeArea.setEditable(false);
EditorDocumentPresentationStyles.applyToCodeArea(codeArea, presentation);
saveButton.setDisable(true);
@@ -295,11 +303,11 @@ public final class EditorWorkspace extends Workspace {
}
private void refreshParagraphGraphics() {
codeArea.setParagraphGraphicFactory(paragraphIndex -> EditorDocumentScopeGuideGraphicFactory.create(
preserveViewport(() -> codeArea.setParagraphGraphicFactory(paragraphIndex -> EditorDocumentScopeGuideGraphicFactory.create(
lineNumberFactory.apply(paragraphIndex),
paragraphIndex,
scopeGuideModel,
activeGuides));
activeGuides)));
}
private VBox buildLayout() {
@@ -346,7 +354,7 @@ public final class EditorWorkspace extends Workspace {
private void configureCommandBar() {
saveButton.textProperty().bind(p.studio.Container.i18n().bind(I18n.CODE_EDITOR_COMMAND_SAVE));
saveAllButton.textProperty().bind(p.studio.Container.i18n().bind(I18n.CODE_EDITOR_COMMAND_SAVE_ALL));
saveButton.getStyleClass().addAll("studio-button", "editor-workspace-command-button");
saveButton.getStyleClass().addAll("studio-button", "studio-button-primary", "editor-workspace-command-button");
saveAllButton.getStyleClass().addAll("studio-button", "studio-button-secondary", "editor-workspace-command-button");
saveButton.setFocusTraversable(false);
saveAllButton.setFocusTraversable(false);
@@ -378,6 +386,7 @@ public final class EditorWorkspace extends Workspace {
final String sourceContent = inlineHintProjection.stripDecorations(content);
final VfsDocumentOpenResult.VfsTextDocument updatedDocument = vfsProjectDocument.updateDocument(activeFile.path(), sourceContent);
openFileSession.open(bufferFrom(updatedDocument));
pendingCaretContextRestore = true;
refreshEditableHighlighting(updatedDocument);
statusBar.showDocumentFormatting(updatedDocument.lineSeparator(), indentationSetup.statusLabel());
tabStrip.showOpenFiles(
@@ -393,7 +402,33 @@ public final class EditorWorkspace extends Workspace {
updatedDocument.content(),
presentation.highlight(updatedDocument.content()),
List.of());
codeArea.setStyleSpans(0, inlineHintProjection.displayStyles());
preserveViewport(() -> codeArea.setStyleSpans(0, inlineHintProjection.displayStyles()));
}
private void preserveViewport(final Runnable action) {
final int caretPosition = codeArea.getCaretPosition();
final double scrollX = codeArea.estimatedScrollXProperty().getValue();
final double scrollY = codeArea.estimatedScrollYProperty().getValue();
action.run();
codeArea.moveTo(Math.max(0, Math.min(caretPosition, codeArea.getLength())));
Platform.runLater(() -> {
codeArea.scrollXToPixel(scrollX);
codeArea.scrollYToPixel(scrollY);
});
}
private void restoreCaretScrollContextIfNeeded(final Number previous, final Number current) {
if (!pendingCaretContextRestore) {
return;
}
final double previousValue = previous == null ? Double.NaN : previous.doubleValue();
final double currentValue = current == null ? Double.NaN : current.doubleValue();
if (!Double.isFinite(previousValue) || !Double.isFinite(currentValue) || Double.compare(previousValue, currentValue) == 0) {
return;
}
pendingCaretContextRestore = false;
Platform.runLater(() -> codeArea.showParagraphAtTop(
Math.max(0, codeArea.getCurrentParagraph() - CARET_SCROLL_CONTEXT_LINES)));
}
private void saveActiveFile() {
@@ -415,6 +450,67 @@ public final class EditorWorkspace extends Workspace {
renderSession();
}
private void requestCloseFile(final Path path) {
final var fileBuffer = openFileSession.file(path).orElse(null);
if (fileBuffer == null) {
return;
}
if (fileBuffer.dirty() && !confirmDirtyFileClose(fileBuffer)) {
return;
}
openFileSession.close(path);
notifyStateChanged();
renderSession();
}
private boolean confirmDirtyFileClose(final EditorOpenFileBuffer fileBuffer) {
final var alert = new Alert(Alert.AlertType.CONFIRMATION);
if (root.getScene() != null) {
alert.initOwner(root.getScene().getWindow());
}
final var saveButtonType = new ButtonType(
p.studio.Container.i18n().text(I18n.CODE_EDITOR_CLOSE_DIRTY_SAVE),
ButtonBar.ButtonData.YES);
final var discardButtonType = new ButtonType(
p.studio.Container.i18n().text(I18n.CODE_EDITOR_CLOSE_DIRTY_DISCARD),
ButtonBar.ButtonData.NO);
final var cancelButtonType = new ButtonType(
p.studio.Container.i18n().text(I18n.CODE_EDITOR_CLOSE_DIRTY_CANCEL),
ButtonBar.ButtonData.CANCEL_CLOSE);
alert.setTitle(p.studio.Container.i18n().text(I18n.CODE_EDITOR_CLOSE_DIRTY_TITLE));
alert.setHeaderText(null);
alert.setContentText(p.studio.Container.i18n().format(
I18n.CODE_EDITOR_CLOSE_DIRTY_MESSAGE,
fileBuffer.tabLabel()));
alert.getButtonTypes().setAll(saveButtonType, discardButtonType, cancelButtonType);
final var result = alert.showAndWait().orElse(cancelButtonType);
if (result == saveButtonType) {
vfsProjectDocument.saveDocument(fileBuffer.path());
return true;
}
if (result == discardButtonType) {
vfsProjectDocument.discardDocument(fileBuffer.path());
return true;
}
return false;
}
private void handleWorkspaceShortcuts(final KeyEvent event) {
if (SAVE_ALL_SHORTCUT.match(event)) {
if (!saveAllButton.isDisabled()) {
saveAllFiles();
}
event.consume();
return;
}
if (SAVE_SHORTCUT.match(event)) {
if (!saveButton.isDisabled()) {
saveActiveFile();
}
event.consume();
}
}
private void reloadOpenFilesFromVfs(final Path activePath) {
final var openPaths = openFileSession.openFiles().stream()
.map(EditorOpenFileBuffer::path)
@@ -433,16 +529,7 @@ public final class EditorWorkspace extends Workspace {
private void refreshCommandSurfaces(final EditorOpenFileBuffer fileBuffer) {
saveButton.setDisable(!fileBuffer.saveEnabled());
saveAllButton.setDisable(!openFileSession.hasDirtyEditableFiles());
final List<EditorWarningStrip.WarningItem> warnings = new ArrayList<>();
if (fileBuffer.frontendDocument() && fileBuffer.readOnly()) {
warnings.add(new EditorWarningStrip.WarningItem(
p.studio.Container.i18n().text(I18n.CODE_EDITOR_WARNING_FRONTEND_READ_ONLY)));
}
if (warnings.isEmpty()) {
warningStrip.clearWarnings();
return;
}
warningStrip.showWarnings(warnings);
warningStrip.clearWarnings();
}
private EditorOpenFileBuffer bufferFrom(final VfsDocumentOpenResult.VfsTextDocument textDocument) {
@@ -483,12 +570,17 @@ public final class EditorWorkspace extends Workspace {
return EditorDocumentScopeGuideModel.from(fileBuffer.content(), analysis.documentSymbols());
}
private void updateActiveGuides(final int caretOffset) {
private void updateActiveGuides(final int caretOffset, final int currentParagraph) {
final EditorDocumentScopeGuideModel.ActiveGuides next = scopeGuideModel.resolveActiveGuides(caretOffset);
if (Objects.equals(activeGuides, next)) {
if (Objects.equals(activeGuides, next) && activeGuideParagraph == currentParagraph) {
return;
}
activeGuides = next;
final boolean paragraphChanged = activeGuideParagraph != currentParagraph;
activeGuideParagraph = currentParagraph;
if (!paragraphChanged) {
return;
}
refreshParagraphGraphics();
}
@@ -92,6 +92,11 @@ codeEditor.status.indentation=Spaces: 4
codeEditor.status.language=Text
codeEditor.command.save=Save
codeEditor.command.saveAll=Save All
codeEditor.closeDirty.title=Unsaved changes
codeEditor.closeDirty.message=Save changes to {0} before closing?
codeEditor.closeDirty.save=Save
codeEditor.closeDirty.discard=Discard
codeEditor.closeDirty.cancel=Cancel
codeEditor.warning.frontendReadOnly=This frontend file is read-only in this wave. It cannot be edited or saved yet.
codeEditor.unsupportedFile.title=Unsupported file
codeEditor.unsupportedFile.message=This file is not supported in this wave: {0}
@@ -598,6 +598,29 @@
-fx-text-fill: #d6dde6;
}
.editor-workspace-tab-container {
-fx-spacing: 8;
-fx-alignment: center-left;
-fx-padding: 0 8 0 12;
}
.editor-workspace-tab-label {
-fx-alignment: center-left;
-fx-font-size: 12px;
}
.editor-workspace-tab-close-chip {
-fx-alignment: center;
-fx-padding: 0;
-fx-cursor: hand;
}
.editor-workspace-tab-close-icon {
-fx-fill: transparent;
-fx-stroke: #d6dde6;
-fx-stroke-width: 1.15;
}
.editor-workspace-tab-button-active {
-fx-background-color: #16283d;
-fx-border-color: #8fc4f2 #516579 #516579 #516579;
@@ -612,12 +635,24 @@
-fx-text-fill: #d9dee5;
}
.editor-workspace-tab-label.editor-workspace-tab-button-read-only {
-fx-text-fill: #d9dee5;
}
.editor-workspace-tab-button-read-only:hover {
-fx-background-color: #2b323d;
-fx-border-color: #5b6878;
-fx-text-fill: #eff4fa;
}
.editor-workspace-tab-label.editor-workspace-tab-button-read-only:hover {
-fx-text-fill: #eff4fa;
}
.editor-workspace-tab-close-chip.editor-workspace-tab-button-read-only .editor-workspace-tab-close-icon {
-fx-stroke: #d9dee5;
}
.editor-workspace-tab-button-read-only.editor-workspace-tab-button-active {
-fx-background-color: #16283d;
-fx-border-color: #8fc4f2 #516579 #516579 #516579;
@@ -626,6 +661,11 @@
-fx-font-weight: bold;
}
.editor-workspace-tab-label.editor-workspace-tab-button-read-only.editor-workspace-tab-button-active {
-fx-text-fill: #ffffff;
-fx-font-weight: bold;
}
.editor-workspace-tab-button-read-only.editor-workspace-tab-button-active:hover {
-fx-background-color: #1c3148;
-fx-border-color: #a7d7ff #5c738b #5c738b #5c738b;
@@ -637,12 +677,24 @@
-fx-text-fill: #e8f6eb;
}
.editor-workspace-tab-label.editor-workspace-tab-button-editable {
-fx-text-fill: #e8f6eb;
}
.editor-workspace-tab-button-editable:hover {
-fx-background-color: #29412f;
-fx-border-color: #6f957a;
-fx-text-fill: #f4fff5;
}
.editor-workspace-tab-label.editor-workspace-tab-button-editable:hover {
-fx-text-fill: #f4fff5;
}
.editor-workspace-tab-close-chip.editor-workspace-tab-button-editable .editor-workspace-tab-close-icon {
-fx-stroke: #e8f6eb;
}
.editor-workspace-tab-button-editable.editor-workspace-tab-button-active {
-fx-background-color: #1d3a2a;
-fx-border-color: #8ad3a2 #587464 #587464 #587464;
@@ -656,6 +708,7 @@
-fx-border-color: #a5efbd #688676 #688676 #688676;
}
.editor-workspace-tab-overflow {
-fx-background-radius: 0;
-fx-border-radius: 0;
@@ -1849,3 +1902,7 @@
-fx-text-fill: #b9cae0;
-fx-font-size: 12px;
}
.editor-workspace-tab-label.editor-workspace-tab-button-editable.editor-workspace-tab-button-active {
-fx-text-fill: #ffffff;
-fx-font-weight: bold;
}
@@ -13,7 +13,7 @@ final class EditorOpenFileSessionTest {
@Test
void openAddsNewFileAndMarksItActive() {
final var session = new EditorOpenFileSession();
final var file = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.READ_ONLY, false, true, "fn main(): void\n");
final var file = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.EDITABLE, false, true, "fn main(): void\n");
session.open(file);
@@ -24,8 +24,8 @@ final class EditorOpenFileSessionTest {
@Test
void openDoesNotDuplicateExistingTab() {
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("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.READ_ONLY, false, true, "b");
final var first = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.EDITABLE, false, true, "a");
final var second = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.EDITABLE, false, true, "b");
session.open(first);
session.open(second);
@@ -38,8 +38,8 @@ final class EditorOpenFileSessionTest {
@Test
void activateSwitchesTheActiveTabWithinTheCurrentSession() {
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("src/other.pbs"), "other.pbs", VfsDocumentAccessMode.READ_ONLY, false, true, "b");
final var first = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.EDITABLE, false, true, "a");
final var second = fileBuffer(Path.of("src/other.pbs"), "other.pbs", VfsDocumentAccessMode.EDITABLE, false, true, "b");
session.open(first);
session.open(second);
@@ -58,20 +58,54 @@ final class EditorOpenFileSessionTest {
}
@Test
void frontendReadOnlyFilesDoNotEnableSaveActions() {
void frontendEditableFilesParticipateInSaveStateWhenDirty() {
final var session = new EditorOpenFileSession();
session.open(fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.READ_ONLY, false, true, "fn main(): void"));
session.open(fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.EDITABLE, true, true, "fn main(): void"));
assertFalse(session.hasSaveableActiveFile());
assertFalse(session.hasDirtyEditableFiles());
assertTrue(session.hasSaveableActiveFile());
assertTrue(session.hasDirtyEditableFiles());
assertTrue(session.activeFile().orElseThrow().frontendDocument());
assertTrue(session.activeFile().orElseThrow().readOnly());
assertTrue(session.activeFile().orElseThrow().editable());
}
@Test
void closeRemovesInactiveTabWithoutChangingTheActiveTab() {
final var session = new EditorOpenFileSession();
final var first = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.EDITABLE, 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.close(first.path());
assertEquals(1, session.openFiles().size());
assertEquals(second.path().toAbsolutePath().normalize(), session.activeFile().orElseThrow().path());
}
@Test
void closePromotesTheNextTabWhenTheActiveTabIsClosed() {
final var session = new EditorOpenFileSession();
final var first = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.EDITABLE, false, true, "a");
final var second = fileBuffer(Path.of("README.md"), "README.md", VfsDocumentAccessMode.EDITABLE, false, false, "b");
final var third = fileBuffer(Path.of("notes.txt"), "notes.txt", VfsDocumentAccessMode.EDITABLE, false, false, "c");
session.open(first);
session.open(second);
session.open(third);
session.activate(second.path());
session.close(second.path());
assertEquals(List.of(
first.path().toAbsolutePath().normalize(),
third.path().toAbsolutePath().normalize()),
session.openFiles().stream().map(EditorOpenFileBuffer::path).toList());
assertEquals(third.path().toAbsolutePath().normalize(), session.activeFile().orElseThrow().path());
}
@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 first = fileBuffer(Path.of("src/main.pbs"), "main.pbs", VfsDocumentAccessMode.EDITABLE, false, true, "a");
final var second = fileBuffer(Path.of("README.md"), "README.md", VfsDocumentAccessMode.EDITABLE, false, false, "b");
session.open(first);