From 4e8a392fedf0d43388c396401803e148c41e109d Mon Sep 17 00:00:00 2001 From: Gabriel Gondim <52431033+GGVidal@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:36:35 -0300 Subject: [PATCH] feat(editor): Open in New Window uses a lightweight editor window (#4368) Open in New Window on a project file's tab now opens an editor-only window (editor--n) instead of a second project workbench. It shares the parent's documents and language servers; unsaved text, caret and selection move with the tab, and the source tab is removed only after the new window reports ready. Files outside the project keep opening a full window. Review changes: closing the window settles only its own unsaved files (the project window's guard also asked to terminate running processes); Escape no longer closes it; error messages go through the text catalog; the window has its own stylesheet. Closes #4117 Co-authored-by: GGVidal <52431033+GGVidal@users.noreply.github.com> --- src-tauri/capabilities/default.json | 2 +- src-tauri/capabilities/e2e.json | 2 +- src-tauri/src/commands/window.rs | 15 ++ src-tauri/src/windows.rs | 63 +++++++- src-tauri/tests/commands.snap | 1 + src/auxiliaryBoot.ts | 5 + src/bindings.ts | 32 ++++ src/editor/core/EditorWindow.module.css | 40 +++++ src/editor/core/EditorWindow.tsx | 193 +++++++++++++++++++++++ src/editor/core/controller.ts | 37 ++++- src/editor/core/detachTab.test.ts | 64 +++++++- src/editor/core/model/document.ts | 12 +- src/editor/core/openLightweightEditor.ts | 32 ++++ src/editorWindowBoot.ts | 24 +++ src/platform/auxWindow.test.ts | 17 +- src/platform/auxWindow.ts | 16 +- src/platform/locales/text/en.json | 7 +- src/platform/locales/text/zh.json | 7 +- 18 files changed, 543 insertions(+), 26 deletions(-) create mode 100644 src/editor/core/EditorWindow.module.css create mode 100644 src/editor/core/EditorWindow.tsx create mode 100644 src/editor/core/openLightweightEditor.ts create mode 100644 src/editorWindowBoot.ts diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 53075fe96..cdfcf6c43 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -2,7 +2,7 @@ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", "description": "Capability for the main window", - "windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "deployment-*"], + "windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"], "permissions": [ "core:default", "core:window:allow-start-dragging", diff --git a/src-tauri/capabilities/e2e.json b/src-tauri/capabilities/e2e.json index 78f820bc1..3bfe73eca 100644 --- a/src-tauri/capabilities/e2e.json +++ b/src-tauri/capabilities/e2e.json @@ -2,6 +2,6 @@ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "e2e-bridge", "description": "Debug-only automation bridge", - "windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "deployment-*"], + "windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"], "permissions": ["mcp-bridge:default"] } diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index cea01c06a..f43cb1284 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -123,6 +123,20 @@ pub async fn window_open_diff( windows::open_diff_window(&app, &window, diff, background) } +/// Opens a lightweight editor window for `editor` next to this project window ("Open in New Window"). +/// `background` (`#rrggbb`) paints it until its page has loaded. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub async fn window_open_editor( + app: AppHandle, + window: WebviewWindow, + editor: windows::EditorLaunch, + background: Option, +) -> IdeResult<()> { + windows::open_editor_window(&app, &window, editor, background) +} + /// Opens this window's Sync with Deployed window comparing `paths` with `server` (or hands them /// to the open one). `background` (`#rrggbb`) paints a new window until its page has loaded. #[desktop_command(trust = always)] @@ -928,6 +942,7 @@ ide_command::desktop_domain!( window_open_comparison, window_open_deployment, window_open_diff, + window_open_editor, window_open_file_in_new_window, window_open_files, window_open_project, diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 837546faa..1e07982ba 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -41,6 +41,8 @@ const COMPARISON_SIZE: (f64, f64) = (1100.0, 720.0); const COMPARISON_MIN_SIZE: (f64, f64) = (640.0, 360.0); const DIFF_SIZE: (f64, f64) = (1100.0, 720.0); const DIFF_MIN_SIZE: (f64, f64) = (640.0, 360.0); +const EDITOR_SIZE: (f64, f64) = (1100.0, 720.0); +const EDITOR_MIN_SIZE: (f64, f64) = (640.0, 360.0); const DEPLOYMENT_SIZE: (f64, f64) = (1400.0, 900.0); const DEPLOYMENT_MIN_SIZE: (f64, f64) = (800.0, 500.0); @@ -77,6 +79,24 @@ pub struct Launch { /// Deployment windows: the server and local selection to compare. #[serde(default)] pub deployment: Option, + /// Editor windows: the file to show (Open in New Window → lightweight aux editor). + #[serde(default)] + pub editor: Option>, +} + +/// A file opened in a lightweight editor window, with optional caret / selection (0-based). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct EditorLaunch { + pub path: ide_core::IpcPath, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub column: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_column: Option, } /// Local files to compare with a deployment server (Sync with Deployed). @@ -352,11 +372,13 @@ pub enum AuxKind { Settings, Comparison, Diff, + Editor, Deployment, } impl AuxKind { - const ALL: [AuxKind; 4] = [AuxKind::Settings, AuxKind::Comparison, AuxKind::Diff, AuxKind::Deployment]; + const ALL: [AuxKind; 5] = + [AuxKind::Settings, AuxKind::Comparison, AuxKind::Diff, AuxKind::Editor, AuxKind::Deployment]; /// Label prefix, and the key of the one remembered geometry shared by every window of the kind. pub fn name(self) -> &'static str { @@ -364,13 +386,14 @@ impl AuxKind { AuxKind::Settings => "settings", AuxKind::Comparison => "comparison", AuxKind::Diff => "diff", + AuxKind::Editor => "editor", AuxKind::Deployment => "deployment", } } /// Several per project window (`--`), else one (`-`). fn multiple(self) -> bool { - matches!(self, AuxKind::Comparison | AuxKind::Diff) + matches!(self, AuxKind::Comparison | AuxKind::Diff | AuxKind::Editor) } /// Shows the project's documents: gets its parent's events and edits made in sibling windows, @@ -394,6 +417,7 @@ impl AuxKind { AuxKind::Settings => SETTINGS_MIN_SIZE, AuxKind::Comparison => COMPARISON_MIN_SIZE, AuxKind::Diff => DIFF_MIN_SIZE, + AuxKind::Editor => EDITOR_MIN_SIZE, AuxKind::Deployment => DEPLOYMENT_MIN_SIZE, } } @@ -403,6 +427,7 @@ impl AuxKind { AuxKind::Settings => SETTINGS_SIZE, AuxKind::Comparison => COMPARISON_SIZE, AuxKind::Diff => DIFF_SIZE, + AuxKind::Editor => EDITOR_SIZE, AuxKind::Deployment => DEPLOYMENT_SIZE, } } @@ -1735,6 +1760,28 @@ pub fn open_diff_window( ) } +/// Opens a lightweight editor window for `editor.path` ("Open in New Window"), sharing the +/// parent's project documents and language servers. +pub fn open_editor_window( + app: &AppHandle, + parent: &WebviewWindow, + editor: EditorLaunch, + background: Option, +) -> IdeResult<()> { + open_auxiliary_window( + app, + parent, + AuxWindow { + kind: AuxKind::Editor, + title: "Editor", + size: AuxKind::Editor.default_size(), + min_size: AuxKind::Editor.min_size(), + launch: Launch { editor: Some(Box::new(editor)), ..Default::default() }, + background, + }, + ) +} + /// Opens (or focuses and hands over to) the project window's Sync with Deployed window: local /// files next to their copies on a deployment server, like IDEA's. pub fn open_deployment_window( @@ -2651,14 +2698,24 @@ mod tests { assert_eq!(auxiliary("settings-main"), Some((AuxKind::Settings, "main"))); assert_eq!(auxiliary("comparison-project-2-14"), Some((AuxKind::Comparison, "project-2"))); assert_eq!(auxiliary("diff-project-2-3"), Some((AuxKind::Diff, "project-2"))); + assert_eq!(auxiliary("editor-project-2-3"), Some((AuxKind::Editor, "project-2"))); assert_eq!(auxiliary("deployment-project-2"), Some((AuxKind::Deployment, "project-2"))); for label in ["main", "project-1", "comparison-main", "comparison-main-x", "settings-", "settingsmain"] { assert_eq!(auxiliary(label), None, "{label}"); } assert_eq!(state_key("comparison-main-3"), "comparison"); assert_eq!(state_key("diff-main-3"), "diff"); + assert_eq!(state_key("editor-main-3"), "editor"); assert_eq!(state_key("project-3"), "project-3"); - let labels = ["comparison-main-0", "diff-main-1", "project-2", "main", "settings-main", "deployment-project-2"]; + let labels = [ + "comparison-main-0", + "diff-main-1", + "editor-main-2", + "project-2", + "main", + "settings-main", + "deployment-project-2", + ]; assert_eq!(sorted_labels(labels.into_iter().filter(|l| auxiliary_parent(l).is_none())), ["main", "project-2"]); } diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 66a8a8057..b082fc1cf 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -723,6 +723,7 @@ window_new always desktop bin window_open_comparison always desktop bindings async window_open_deployment always desktop bindings async window_open_diff always desktop bindings async +window_open_editor always desktop bindings async window_open_file_in_new_window always desktop bindings async window_open_files always desktop bindings async window_open_project always desktop bindings async diff --git a/src/auxiliaryBoot.ts b/src/auxiliaryBoot.ts index dab682b00..0575f3587 100644 --- a/src/auxiliaryBoot.ts +++ b/src/auxiliaryBoot.ts @@ -20,6 +20,11 @@ export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string } mountWindowRoot(bootDiffWindow(aux.parent)); return; } + case "editor": { + const { bootEditorWindow } = await import("./editorWindowBoot"); + mountWindowRoot(bootEditorWindow(aux.parent)); + return; + } case "deployment": { const { bootDeploymentWindow } = await import("./deploymentWindowBoot"); mountWindowRoot(bootDeploymentWindow(aux.parent)); diff --git a/src/bindings.ts b/src/bindings.ts index e47b4fcc0..772f0d76b 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1907,6 +1907,11 @@ export const commands = { * `background` (`#rrggbb`) paints it until its page has loaded. */ windowOpenDiff: (diff: DiffLaunch_Deserialize, background: string | null) => typedError(__TAURI_INVOKE("window_open_diff", { diff, background })), + /** + * Opens a lightweight editor window for `editor` next to this project window ("Open in New Window"). + * `background` (`#rrggbb`) paints it until its page has loaded. + */ + windowOpenEditor: (editor: EditorLaunch_Deserialize, background: string | null) => typedError(__TAURI_INVOKE("window_open_editor", { editor, background })), /** * Detaches an editor tab: opens `file` in a forced new window (`project`, None * for LightEdit, decided by the caller), bypassing the focus-an-existing-window @@ -1977,6 +1982,8 @@ export const commands = { diffBeforeFiles: boolean, /** Deployment windows: the server and local selection to compare. */ deployment: DeploymentLaunch | null, + /** Editor windows: the file to show (Open in New Window → lightweight aux editor). */ + editor: EditorLaunch_Serialize | null, } | null>("window_take_launch"), /** * Local bootstrap snapshot for a `settings-` window, avoiding a sequential @@ -5464,6 +5471,27 @@ export type EditorGeneralSettings = { richTextCopy?: boolean, }; +/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */ +export type EditorLaunch = EditorLaunch_Serialize | EditorLaunch_Deserialize; + +/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */ +export type EditorLaunch_Deserialize = { + path: IpcPath, + line?: number | null, + column?: number | null, + endLine?: number | null, + endColumn?: number | null, +}; + +/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */ +export type EditorLaunch_Serialize = { + path: IpcPath, + line?: number | null, + column?: number | null, + endLine?: number | null, + endColumn?: number | null, +}; + export type EditorSettings = EditorSettings_Serialize | EditorSettings_Deserialize; export type EditorSettings_Deserialize = { @@ -7780,6 +7808,8 @@ export type Launch_Deserialize = { diffBeforeFiles?: boolean, /** Deployment windows: the server and local selection to compare. */ deployment?: DeploymentLaunch | null, + /** Editor windows: the file to show (Open in New Window → lightweight aux editor). */ + editor?: EditorLaunch_Deserialize | null, }; /** What a freshly opened window should do once its frontend is up. */ @@ -7809,6 +7839,8 @@ export type Launch_Serialize = { diffBeforeFiles: boolean, /** Deployment windows: the server and local selection to compare. */ deployment: DeploymentLaunch | null, + /** Editor windows: the file to show (Open in New Window → lightweight aux editor). */ + editor: EditorLaunch_Serialize | null, }; /** One SDK or library with its source folders (`< Python 3.12 (.venv) >`). */ diff --git a/src/editor/core/EditorWindow.module.css b/src/editor/core/EditorWindow.module.css new file mode 100644 index 000000000..519d80c25 --- /dev/null +++ b/src/editor/core/EditorWindow.module.css @@ -0,0 +1,40 @@ +.window { + display: flex; + flex-direction: column; + height: 100%; + min-height: 0; + background: var(--bg-app); + color: var(--fg); +} +/* Linux: frameless X11 windows have no shadow, so mark the edge in CSS. */ +.edge { + position: relative; +} +.edge::after { + content: ""; + position: absolute; + inset: 0; + z-index: 1; + pointer-events: none; + box-shadow: inset 0 0 0 1px var(--border-window); +} +.loading { + display: flex; + flex: 1; + align-items: center; + justify-content: center; + gap: var(--space-2); + color: var(--fg-muted); +} +.body { + display: flex; + flex-direction: column; + flex: 1; + min-height: 0; + overflow: hidden; +} +.error { + padding: var(--space-4); + color: var(--danger); + font-size: var(--fs-small); +} diff --git a/src/editor/core/EditorWindow.tsx b/src/editor/core/EditorWindow.tsx new file mode 100644 index 000000000..f1d0aaf83 --- /dev/null +++ b/src/editor/core/EditorWindow.tsx @@ -0,0 +1,193 @@ +/** + * Lightweight editor window (`editor--`): one project file in a window of its own + * ("Open in New Window" without a second workbench). + */ +import clsx from "clsx"; +import { create } from "zustand"; +import { emitTo } from "@tauri-apps/api/event"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import { AUX_CLOSED, EDITOR_READY, type AuxCloseResult, type EditorReadyResult } from "@/platform/auxWindow"; +import { setContext } from "@/platform/context"; +import { t, tx } from "@/platform/i18n"; +import { isImeKey } from "@/platform/ime"; +import { commands, type EditorLaunch } from "@/platform/ipc"; +import { basename, useProject } from "@/platform/project"; +import { restoreRemote } from "@/platform/remote"; +import { usePlatform } from "@/platform/platformInfo"; +import { Spinner, T, isPopupOpen } from "@/ui"; +import { editorService, notifications } from "@/workbench/contributions"; +import { EditorArea } from "@/workbench/EditorArea"; +import { OverlayHost } from "@/workbench/OverlayHost"; +import { TitleBar } from "@/workbench/TitleBar"; +import { WindowResizeHandles } from "@/workbench/WindowResizeHandles"; +import { useApplyTheme } from "@/workbench/theme"; +import { ask } from "@/workbench/messages"; +import { editorController } from "./controller"; +import type { DocModel } from "./model/document"; +import styles from "./EditorWindow.module.css"; + +const useEditorWindow = create<{ + path: string | null; + title: string; + error: string | null; +}>(() => ({ path: null, title: "", error: null })); + +function showCaption(caption: string) { + if (useEditorWindow.getState().title === caption) return; + useEditorWindow.setState({ title: caption }); + void getCurrentWindow() + .setTitle(caption) + .catch(() => {}); +} + +async function reportReady(parent: string, result: Omit) { + const payload: EditorReadyResult = { label: getCurrentWindow().label, ...result }; + await emitTo(parent, EDITOR_READY, payload).catch((error) => + console.warn("cannot report editor window ready", error), + ); +} + +/** + * Settles this window's unsaved files before it closes. Only its own documents count: the project + * window keeps its processes and any copy of the same file it still has open. + */ +async function settleUnsaved(models: DocModel[], project: string | null): Promise { + const dirty = models.filter((model) => model.getMeta().dirty); + if (dirty.length === 0) return true; + if (useProject.getState().settings?.files?.autoSave !== false) { + await Promise.all(dirty.map((model) => model.save("auto"))); + return true; + } + const answer = await ask({ + title: t("app.unsaved.title"), + body: t("app.unsaved.body", { count: dirty.length, project: project ?? t("app.title.default") }), + buttons: [ + { id: "discard", label: t("app.unsaved.discard") }, + { id: "save", label: t("app.unsaved.save"), primary: true }, + ], + icon: "warning", + }); + if (answer.button === "save") await Promise.all(dirty.map((model) => model.save("explicit"))); + return answer.button === "save" || answer.button === "discard"; +} + +/** Loads the launch's file into this window's editor. */ +export function activateEditorWindow(parent: string): () => void { + let projectName: string | null = null; + const native = getCurrentWindow(); + let disposed = false; + let closing = false; + let stopClose: (() => void) | undefined; + void native + .onCloseRequested(async (event) => { + if (closing) { + event.preventDefault(); + return; + } + closing = true; + const models = [...editorController().manager.byId.values()]; + let closed = false; + try { + await Promise.all(models.map((model) => model.sync.whenIdle())); + closed = await settleUnsaved(models, projectName); + if (closed) { + for (const model of models) model.dispose(); + await Promise.all( + models.map((model) => + commands.docClose(model.doc).catch((error) => console.warn("cannot release editor document", error)), + ), + ); + } + } catch (error) { + notifications().notify({ level: "error", title: tx("Could not close editor"), body: String(error) }); + } finally { + if (!closed) event.preventDefault(); + const result: AuxCloseResult = { + label: native.label, + closed, + documents: closed ? models.map((model) => model.doc) : [], + }; + await emitTo(parent, AUX_CLOSED, result).catch((error) => + console.warn("cannot report editor window close", error), + ); + closing = false; + } + }) + .then((off) => { + if (disposed) off(); + else stopClose = off; + }); + const onCloseShortcut = (event: KeyboardEvent) => { + if (isImeKey(event) || isPopupOpen()) return; + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "w") { + event.preventDefault(); + event.stopImmediatePropagation(); + void native.close(); + } + }; + window.addEventListener("keydown", onCloseShortcut, true); + void (async () => { + let path = ""; + try { + await restoreRemote(); + const launch = (await commands.windowTakeLaunch())?.editor as EditorLaunch | null | undefined; + if (!launch?.path) throw new Error(tx("Missing editor request")); + path = launch.path; + const project = await commands.projectCurrent(); + if (!project) throw new Error(tx("The editor’s project is no longer open")); + projectName = project.name; + // Settings only: restoring the project's editor session here would overwrite the main window's tabs. + useProject.setState({ settings: project.settings }); + setContext("projectOpen", true); + const selection = + launch.line != null && launch.column != null + ? { + line: launch.line, + col: launch.column, + ...(launch.endLine != null ? { endLine: launch.endLine, endCol: launch.endColumn ?? 0 } : {}), + } + : undefined; + await editorService().openFile(path, { focus: true, selection }); + useEditorWindow.setState({ path }); + showCaption(`${project.name} — ${basename(path)}`); + await reportReady(parent, { path, ok: true }); + } catch (error) { + const message = String(error); + useEditorWindow.setState({ error: message }); + await reportReady(parent, { path, ok: false, error: message }); + } + })(); + return () => { + disposed = true; + stopClose?.(); + window.removeEventListener("keydown", onCloseShortcut, true); + }; +} + +export function EditorWindow() { + useApplyTheme(); + const { path, title, error } = useEditorWindow(); + const os = usePlatform((s) => s.os); + const ownTitleBar = usePlatform((s) => s.overlayTitleBar || s.framelessTitleBar); + return ( +
+ {ownTitleBar && } + {error ? ( +
+ {error} +
+ ) : !path ? ( +
+ + Loading… +
+ ) : ( +
+ +
+ )} + + +
+ ); +} diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 3f78c781a..e0871e21a 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -47,7 +47,9 @@ import { useDistractionFree } from "@/workbench/distractionFree"; import { restoreMaximizedToolWindow } from "@/workbench/toolwindows/store"; import { ask, confirm } from "@/workbench/messages"; import { t, tx } from "@/platform/i18n"; -import { call, commands } from "@/platform/ipc"; +import { call, commands, isTauri } from "@/platform/ipc"; +import { openLightweightEditor } from "./openLightweightEditor"; +import { windowBackgroundHex } from "@/workbench/theme"; import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog"; import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs"; import { isRemoteWindow } from "@/platform/remote"; @@ -1856,7 +1858,7 @@ export class EditorController implements SlotHost { changeSplitOrientation(paneId: string) { this.apply((s) => changeSplitOrientation(s, paneId)); } - /** Save or resolve the dirty guard, open the window, then remove the original tab. */ + /** Open a lightweight aux editor (or a full window outside the project), then remove the original tab. */ async detachTab(paneId: string, tabId: string): Promise { const tab = useTabs.getState().panes[paneId]?.tabs.find((t) => t.id === tabId); const path = tab?.input.path; @@ -1873,9 +1875,40 @@ export class EditorController implements SlotHost { const project = useProject.getState().project; const inProject = !!project && (project.workspace?.projects ?? [project.root]).some((root) => isSameOrInside(path, root)); + const light = inProject && isTextTab(tab) && isTauri(); return this.removeGuarded((s) => (s.panes[paneId] ? closeTab(s, paneId, tabId) : s), { beforeRemove: async () => { if (!useTabs.getState().panes[paneId]?.tabs.some((t) => t.id === tabId)) return false; + if (light) { + const slot = await this.ensureSlot(tabId); + if (!slot) return false; + const state = slot.currentState(); + const main = state.selection.main; + const from = state.doc.lineAt(main.from); + const to = state.doc.lineAt(main.to); + try { + await openLightweightEditor( + { + path, + line: from.number - 1, + column: main.from - from.from, + endLine: to.number - 1, + endColumn: main.to - to.from, + }, + windowBackgroundHex(), + ); + slot.model.handoffRelease = true; + return true; + } catch (e) { + notifications().notify({ + level: "error", + title: t("app.window.openFailed", { name: basename(path) }), + body: e instanceof Error ? e.message : String(e), + key: `app.open:${path}`, + }); + return false; + } + } if (isTextTab(tab)) { const slot = await this.ensureSlot(tabId); if (!slot) return false; diff --git a/src/editor/core/detachTab.test.ts b/src/editor/core/detachTab.test.ts index 7786c23db..5bddb5ef9 100644 --- a/src/editor/core/detachTab.test.ts +++ b/src/editor/core/detachTab.test.ts @@ -8,12 +8,18 @@ import * as contributions from "@/workbench/contributions"; import { ask } from "@/workbench/messages"; import type * as Messages from "@/workbench/messages"; import { registerEditorKind, type EditorDocumentLifecycle } from "@/workbench/contributions"; +import * as light from "./openLightweightEditor"; vi.mock("@/workbench/messages", async (original) => ({ ...(await original()), ask: vi.fn(), })); +vi.mock("@/platform/ipc", async (original) => { + const mod = await original(); + return { ...mod, isTauri: () => true }; +}); + const notify = vi.fn(); let ctrl: EditorController; let unregister: (() => void) | undefined; @@ -33,6 +39,7 @@ beforeEach(() => { status: "ok", data: { kind: "opened", label: "second" }, }); + vi.spyOn(light, "openLightweightEditor").mockResolvedValue(); }); afterEach(() => { ctrl?.stop(); @@ -44,7 +51,45 @@ afterEach(() => { }); describe("detachTab", () => { - it.each([false, true])("waits for text save before opening and closing, autosave=%s", async (autoSave) => { + it("moves a project file to a lightweight editor without saving first", async () => { + useProject.setState({ + project: { root: "/p", workspace: { projects: ["/p"] } } as never, + settings: { files: { autoSave: false } } as never, + }); + const backend = createMemoryBackend({ [path]: "original\n" }); + const save = vi.spyOn(backend, "save"); + ctrl = new EditorController(backend); + ctrl.start(); + await ctrl.openFile(path, { focus: false }); + const [pane, id] = current(); + ctrl.slotFor(id)!.dispatchLocal({ changes: { from: 0, to: 8, insert: "edited" } }); + expect(await ctrl.detachTab(pane, id)).toBe(true); + expect(hasTab(id)).toBe(false); + expect(save).not.toHaveBeenCalled(); + expect(commands.windowOpenFileInNewWindow).not.toHaveBeenCalled(); + expect(light.openLightweightEditor).toHaveBeenCalledWith( + expect.objectContaining({ path, line: expect.any(Number), column: expect.any(Number) }), + null, + ); + await vi.waitFor(() => expect(ctrl.manager.get(path)).toBeUndefined()); + }); + + it("keeps the tab when the lightweight editor fails to open", async () => { + useProject.setState({ + project: { root: "/p", workspace: { projects: ["/p"] } } as never, + settings: { files: { autoSave: false } } as never, + }); + ctrl = new EditorController(createMemoryBackend({ [path]: "original\n" })); + ctrl.start(); + await ctrl.openFile(path, { focus: false }); + const [pane, id] = current(); + vi.mocked(light.openLightweightEditor).mockRejectedValue(new Error("window failed")); + expect(await ctrl.detachTab(pane, id)).toBe(false); + expect(hasTab(id)).toBe(true); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "window failed" })); + }); + + it.each([false, true])("waits for text save before opening a full window, autosave=%s", async (autoSave) => { useProject.setState({ settings: { files: { autoSave } } as never }); const backend = createMemoryBackend({ [path]: "original\n" }); ctrl = new EditorController(backend); @@ -69,6 +114,7 @@ describe("detachTab", () => { const result = ctrl.detachTab(pane, id); await vi.waitFor(() => expect(save).toHaveBeenCalled()); expect(commands.windowOpenFileInNewWindow).not.toHaveBeenCalled(); + expect(light.openLightweightEditor).not.toHaveBeenCalled(); expect(hasTab(id)).toBe(true); finish(); expect(await result).toBe(true); @@ -168,15 +214,21 @@ describe("detachTab", () => { ); it.each([ - ["C:\\project\\a.ts", ["C:/project"], "C:/project"], - ["C:\\other\\a.ts", ["C:/project", "C:/other"], "C:/project"], - ["C:\\project-other\\a.ts", ["C:/project"], null], - ])("routes %s by workspace containment", async (file, projects, expected) => { + ["C:\\project\\a.ts", ["C:/project"], true], + ["C:\\other\\a.ts", ["C:/project", "C:/other"], true], + ["C:\\project-other\\a.ts", ["C:/project"], false], + ])("routes %s by workspace containment", async (file, projects, lightPath) => { useProject.setState({ project: { root: "C:/project", workspace: { projects } } as never }); ctrl = new EditorController(createMemoryBackend({ [file]: "text\n" })); ctrl.start(); await ctrl.openFile(file, { focus: false }); expect(await ctrl.detachTab(...current())).toBe(true); - expect(commands.windowOpenFileInNewWindow).toHaveBeenCalledWith(expected, file); + if (lightPath) { + expect(light.openLightweightEditor).toHaveBeenCalledWith(expect.objectContaining({ path: file }), null); + expect(commands.windowOpenFileInNewWindow).not.toHaveBeenCalled(); + } else { + expect(commands.windowOpenFileInNewWindow).toHaveBeenCalledWith(null, file); + expect(light.openLightweightEditor).not.toHaveBeenCalled(); + } }); }); diff --git a/src/editor/core/model/document.ts b/src/editor/core/model/document.ts index d2601a11d..645a7c465 100644 --- a/src/editor/core/model/document.ts +++ b/src/editor/core/model/document.ts @@ -254,6 +254,11 @@ export class DocModel { /** Bumped by every change (local or remote). */ changeCounter = 0; closed = false; + /** + * Tab moved to an auxiliary editor window that already holds this document: + * release must drop the local model and backend ref without autosave / keep-dirty. + */ + handoffRelease = false; private refreshTimer: ReturnType | undefined; private saving: Promise = Promise.resolve(); private meta: DocMeta; @@ -895,8 +900,10 @@ export class DocumentManager { // Defer so that "close tab + reopen in split" in one tick keeps the model. queueMicrotask(async () => { if (model.inUse() || model.closed) return; + const handoff = model.handoffRelease; + model.handoffRelease = false; const files = this.settings()?.files; - if (files?.autoSave !== false && model.getMeta().dirty) { + if (!handoff && files?.autoSave !== false && model.getMeta().dirty) { try { await model.save("auto"); } catch (e) { @@ -906,7 +913,8 @@ export class DocumentManager { // As in IDEA, a file whose changes are not saved (autosave off, or a failed save) stays // open without a tab: reopening shows the changes, and Save All and the exit check still // cover them. An untitled buffer was asked about when its tab closed. - if (model.getMeta().dirty && !isUntitledUri(model.path)) return; + // Handoff to an aux editor: the sibling window already references the same document. + if (!handoff && model.getMeta().dirty && !isUntitledUri(model.path)) return; if (model.inUse()) return; await model.sync.whenIdle(); if (model.inUse()) return; diff --git a/src/editor/core/openLightweightEditor.ts b/src/editor/core/openLightweightEditor.ts new file mode 100644 index 000000000..e419f636d --- /dev/null +++ b/src/editor/core/openLightweightEditor.ts @@ -0,0 +1,32 @@ +import { getCurrentWindow } from "@tauri-apps/api/window"; +import { EDITOR_READY, type EditorReadyResult } from "@/platform/auxWindow"; +import { tx } from "@/platform/i18n"; +import { call, commands, type EditorLaunch } from "@/platform/ipc"; + +const READY_MS = 30_000; + +/** Opens a project-file aux editor and resolves once it has taken over the document. */ +export async function openLightweightEditor(launch: EditorLaunch, background: string | null): Promise { + const parent = getCurrentWindow(); + let off: (() => void) | undefined; + let timer: ReturnType | undefined; + try { + await new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error(tx("Timed out opening the editor window"))), READY_MS); + void parent + .listen(EDITOR_READY, ({ payload }) => { + if (payload.path && payload.path !== launch.path) return; + if (payload.ok) resolve(); + else reject(new Error(payload.error || tx("Could not open the editor window"))); + }) + .then((unlisten) => { + off = unlisten; + return call(commands.windowOpenEditor(launch, background)); + }) + .catch(reject); + }); + } finally { + if (timer) clearTimeout(timer); + off?.(); + } +} diff --git a/src/editorWindowBoot.ts b/src/editorWindowBoot.ts new file mode 100644 index 000000000..af38b2a25 --- /dev/null +++ b/src/editorWindowBoot.ts @@ -0,0 +1,24 @@ +import type { ComponentType } from "react"; +import { activate as editor } from "./editor/core"; +import { activateEditorWindow, EditorWindow } from "./editor/core/EditorWindow"; +import { installLocaleSync } from "./features/app/locale"; +import { installMenuBridge } from "./features/app/menuBridge"; +import { trackRuntimeSettings } from "./features/settings/runtime"; +import { installKeyboardDispatcher } from "./platform/keymap"; +import { activateList } from "./windowBoot"; + +/** + * Lightweight editor window of project window `parent`: one file, sharing the + * parent's documents and language servers, with no workbench chrome. + */ +export function bootEditorWindow(parent: string): ComponentType { + activateList("editor window", [ + ["locale", installLocaleSync], + ["settings", trackRuntimeSettings], + ["menu", installMenuBridge], + ["editor", editor], + ["editorWindow", () => activateEditorWindow(parent)], + ]); + installKeyboardDispatcher(); + return EditorWindow; +} diff --git a/src/platform/auxWindow.test.ts b/src/platform/auxWindow.test.ts index 32974ef76..c4b0043ee 100644 --- a/src/platform/auxWindow.test.ts +++ b/src/platform/auxWindow.test.ts @@ -11,15 +11,20 @@ describe("auxiliaryWindow", () => { expect(auxiliaryWindow("comparison-project-2-14")).toEqual({ kind: "comparison", parent: "project-2" }); expect(auxiliaryWindow("diff-main-0")).toEqual({ kind: "diff", parent: "main" }); expect(auxiliaryWindow("diff-project-2-14")).toEqual({ kind: "diff", parent: "project-2" }); + expect(auxiliaryWindow("editor-main-0")).toEqual({ kind: "editor", parent: "main" }); + expect(auxiliaryWindow("editor-project-2-14")).toEqual({ kind: "editor", parent: "project-2" }); expect(auxiliaryWindow("deployment-project-2")).toEqual({ kind: "deployment", parent: "project-2" }); }); - it.each(["settings", "comparison", "diff", "deployment"])("grants %s windows permission to close", (kind) => { - expect(capability.windows).toContain(`${kind}-*`); - expect(bridgeCapability.windows).toContain(`${kind}-*`); - expect(capability.permissions).toContain("core:window:allow-close"); - expect(capability.permissions).toContain("core:window:allow-destroy"); - }); + it.each(["settings", "comparison", "diff", "editor", "deployment"])( + "grants %s windows permission to close", + (kind) => { + expect(capability.windows).toContain(`${kind}-*`); + expect(bridgeCapability.windows).toContain(`${kind}-*`); + expect(capability.permissions).toContain("core:window:allow-close"); + expect(capability.permissions).toContain("core:window:allow-destroy"); + }, + ); it("leaves project windows and malformed labels alone", () => { for (const label of ["", "main", "project-1", "settings-", "comparison-main", "comparison-main-x"]) { diff --git a/src/platform/auxWindow.ts b/src/platform/auxWindow.ts index df690f56c..2a37e2823 100644 --- a/src/platform/auxWindow.ts +++ b/src/platform/auxWindow.ts @@ -8,15 +8,25 @@ import { getAllWindows, getCurrentWindow } from "@tauri-apps/api/window"; import { TauriEvent } from "@tauri-apps/api/event"; import { isTauri } from "./ipc"; -export type AuxKind = "settings" | "comparison" | "diff" | "deployment"; +export type AuxKind = "settings" | "comparison" | "diff" | "editor" | "deployment"; /** Kinds with several windows per parent (`--`); the others have one (`-`). */ -const MULTIPLE: ReadonlySet = new Set(["comparison", "diff"]); -const KINDS: readonly AuxKind[] = ["settings", "comparison", "diff", "deployment"]; +const MULTIPLE: ReadonlySet = new Set(["comparison", "diff", "editor"]); +const KINDS: readonly AuxKind[] = ["settings", "comparison", "diff", "editor", "deployment"]; /** An auxiliary window reports to its parent whether it closed, and which documents it released. */ export const AUX_CLOSED = "openidea://auxiliary/closed"; +/** Lightweight editor window reports that it opened (or failed to open) the moved file. */ +export const EDITOR_READY = "openidea://editor/ready"; + +export interface EditorReadyResult { + label: string; + path: string; + ok: boolean; + error?: string; +} + export interface AuxCloseResult { label: string; closed: boolean; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 9bb44c636..a8ae9befb 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2535,5 +2535,10 @@ "60 FPS": "60 FPS", "30 FPS": "30 FPS", "15 FPS": "15 FPS", - "10 FPS": "10 FPS" + "10 FPS": "10 FPS", + "Could not close editor": "Could not close editor", + "Missing editor request": "Missing editor request", + "The editor’s project is no longer open": "The editor’s project is no longer open", + "Timed out opening the editor window": "Timed out opening the editor window", + "Could not open the editor window": "Could not open the editor window" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index acb89d7ef..02c500803 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8909,5 +8909,10 @@ "60 FPS": "60 帧/秒", "30 FPS": "30 帧/秒", "15 FPS": "15 帧/秒", - "10 FPS": "10 帧/秒" + "10 FPS": "10 帧/秒", + "Could not close editor": "无法关闭编辑器", + "Missing editor request": "缺少编辑器请求", + "The editor’s project is no longer open": "编辑器所属的项目已关闭", + "Timed out opening the editor window": "打开编辑器窗口超时", + "Could not open the editor window": "无法打开编辑器窗口" }