дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 17:21:13 +02:00
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-<parent>-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 <[email protected]>
Цей коміт міститься в:
1 джерело
7c3b40b1c4
коміт
4e8a392fed
18 files changed
+543
-26
No files matched your search
@@ -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));
|
||||
|
||||
@@ -1907,6 +1907,11 @@ export const commands = {
|
||||
* `background` (`#rrggbb`) paints it until its page has loaded.
|
||||
*/
|
||||
windowOpenDiff: (diff: DiffLaunch_Deserialize, background: string | null) => typedError<null, IdeError>(__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<null, IdeError>(__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-<parent>` 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) >`). */
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Lightweight editor window (`editor-<parent>-<n>`): 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<EditorReadyResult, "label">) {
|
||||
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<boolean> {
|
||||
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 (
|
||||
<main className={clsx(styles.window, os === "linux" && styles.edge)}>
|
||||
{ownTitleBar && <TitleBar minimal dialog title={title} />}
|
||||
{error ? (
|
||||
<div className={styles.error} role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : !path ? (
|
||||
<div className={styles.loading} role="status">
|
||||
<Spinner />
|
||||
<T>Loading…</T>
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.body}>
|
||||
<EditorArea />
|
||||
</div>
|
||||
)}
|
||||
<OverlayHost />
|
||||
<WindowResizeHandles />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -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<boolean> {
|
||||
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;
|
||||
|
||||
@@ -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<typeof Messages>()),
|
||||
ask: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const mod = await original<typeof import("@/platform/ipc")>();
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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<typeof setTimeout> | undefined;
|
||||
private saving: Promise<void> = 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;
|
||||
|
||||
@@ -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<void> {
|
||||
const parent = getCurrentWindow();
|
||||
let off: (() => void) | undefined;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(tx("Timed out opening the editor window"))), READY_MS);
|
||||
void parent
|
||||
.listen<EditorReadyResult>(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?.();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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"]) {
|
||||
|
||||
@@ -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 (`<kind>-<parent>-<n>`); the others have one (`<kind>-<parent>`). */
|
||||
const MULTIPLE: ReadonlySet<AuxKind> = new Set(["comparison", "diff"]);
|
||||
const KINDS: readonly AuxKind[] = ["settings", "comparison", "diff", "deployment"];
|
||||
const MULTIPLE: ReadonlySet<AuxKind> = 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;
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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": "无法打开编辑器窗口"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача