From c709844c042c58aba41a888b2f6c0549762daece Mon Sep 17 00:00:00 2001 From: Muu Date: Sun, 29 Nov 2026 10:35:25 +0800 Subject: [PATCH] feat(editor): add Save As for existing files (#6534) File > Save As opens the existing Copy dialog for the active file with Open copy in editor forced on. A single-file copy of an open editor uses the new doc_copy_as, which writes the current buffer with its encoding, BOM and line endings and refuses a target that is open in another editor. Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- crates/ide-host/src/menu.rs | 1 + crates/ide-host/src/ops/doc.rs | 15 +++ crates/ide-host/src/ops/doc/tests.rs | 30 ++++++ crates/ide-workspace/src/documents.rs | 52 ++++++++-- crates/ide-workspace/tests/documents.rs | 60 ++++++++++++ docs/en/guide/editor.mdx | 2 + docs/en/reference/shortcuts.mdx | 1 + docs/zh/guide/editor.mdx | 2 + docs/zh/reference/shortcuts.mdx | 1 + src-tauri/tests/commands.snap | 1 + src/bindings.ts | 2 + src/editor/core/backend.ts | 13 +++ src/editor/core/controller.test.ts | 24 +++++ src/editor/core/controller.ts | 8 ++ src/editor/core/index.ts | 1 + src/features/app/__tests__/menuBridge.test.ts | 1 + .../project-tree/FileRefactorDialogs.tsx | 20 +++- src/features/project-tree/actions.ts | 18 +++- src/features/project-tree/operations.test.ts | 98 ++++++++++++++++++- src/features/project-tree/operations.ts | 37 ++++++- src/features/vim/__tests__/rc.test.ts | 1 + src/platform/i18n.test.ts | 1 + src/platform/ideaActions.ts | 1 + src/platform/keymaps/ideaParity.test.ts | 1 + src/platform/keymaps/intellij-macos.ts | 1 + src/platform/keymaps/intellij-windows.ts | 1 + src/platform/keymaps/vscode-macos.ts | 1 + src/platform/locales/en.json | 1 + src/platform/locales/text/zh-TW.json | 1 + src/platform/locales/zh-TW.json | 1 + src/platform/locales/zh.json | 1 + src/workbench/contributions.ts | 2 + src/workbench/pathChooser.test.tsx | 16 +++ 33 files changed, 396 insertions(+), 20 deletions(-) diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs index b327bb24b8..1d7b31d0f8 100644 --- a/crates/ide-host/src/menu.rs +++ b/crates/ide-host/src/menu.rs @@ -236,6 +236,7 @@ pub fn spec(os: Os) -> Vec { act("remote.stopBackend", "Stop Remote Backend"), act("remote.reloadEnvironment", "Reload Environment"), SEP, + act("file.saveAs", "Save As…"), act("file.save", "Save All"), act("file.reloadAllFromDisk", "Reload All from Disk"), sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]), diff --git a/crates/ide-host/src/ops/doc.rs b/crates/ide-host/src/ops/doc.rs index 0cd3118a12..b515315e44 100644 --- a/crates/ide-host/src/ops/doc.rs +++ b/crates/ide-host/src/ops/doc.rs @@ -56,6 +56,20 @@ pub async fn doc_save_as(host: &Host, window: &str, doc: DocId, path: PathBuf) - .await } +/// Copies the current buffer, including unsaved edits, without changing the source; false for the source itself. +#[command(trust = always)] +pub async fn doc_copy_as(host: &Host, window: &str, doc: DocId, path: PathBuf) -> IdeResult { + let project = host.project(window)?; + host.blocking(move || { + let copied = project.documents.copy_as(doc, &path)?; + if let Some(dir) = path.parent().filter(|_| project.light) { + project.watch_light_dir(dir); + } + Ok(copied) + }) + .await +} + /// Applies a CodeMirror change set; returns the new version. Rejects with /// `outOfSync` when `base_version` is stale; the UI then calls `doc_snapshot`. #[command(trust = always, desktop_body = async)] @@ -141,6 +155,7 @@ mod tests; ide_command::domain!( doc: doc_close, + doc_copy_as, doc_edit, doc_open, doc_open_untitled, diff --git a/crates/ide-host/src/ops/doc/tests.rs b/crates/ide-host/src/ops/doc/tests.rs index 17cdf7408f..ce96a5d830 100644 --- a/crates/ide-host/src/ops/doc/tests.rs +++ b/crates/ide-host/src/ops/doc/tests.rs @@ -111,6 +111,36 @@ async fn dirty_document_keeps_edits_and_warns_once() { assert!(f.document_events().is_empty()); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn save_as_copies_the_current_buffer_and_leaves_the_source_on_disk() { + let f = Fixture::new(); + let original = f.open(&f.path).await; + doc_edit( + &f.host, + "main", + original.id, + original.version, + ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "local ".into() }] }, + ) + .await + .unwrap(); + let target = f.outside.with_extension("copy.txt"); + std::fs::write(&target, "old\n").unwrap(); + + assert!(doc_copy_as(&f.host, "main", original.id, target.clone()).await.unwrap()); + + assert_eq!(std::fs::read_to_string(&f.path).unwrap(), "original\n"); + assert_eq!(std::fs::read_to_string(&target).unwrap(), "local original\n"); + let source = f.project.documents.snapshot(original.id).unwrap(); + assert_eq!(source.path, f.path); + assert_eq!(source.text, "local original\n"); + assert!(source.dirty); + let copy = f.open(&target).await; + assert_ne!(copy.id, original.id); + assert_eq!(copy.text, "local original\n"); + assert!(!copy.dirty); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn deleted_document_keeps_its_buffer_and_other_documents_still_reload() { let f = Fixture::new(); diff --git a/crates/ide-workspace/src/documents.rs b/crates/ide-workspace/src/documents.rs index cceab6e24c..68117c9f75 100644 --- a/crates/ide-workspace/src/documents.rs +++ b/crates/ide-workspace/src/documents.rs @@ -1065,6 +1065,19 @@ impl Documents { } } + /// Writes the current buffer with its encoding, BOM, line ending and file-type conversion. + fn write_to(st: &DocState, target: &Path) -> IdeResult { + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent)?; + } + let text = st.doc.text_for_save(); + if st.native_to_ascii { + ide_vfs::save_properties_text(target, &text) + } else { + ide_vfs::save_text(target, &text, &st.encoding, st.has_bom) + } + } + /// Save As for an untitled buffer: writes it to `target` (creating missing /// parent folders) and turns it into a regular file document — the buffer /// keeps its identity (undo history, version), the registry is re-keyed and @@ -1090,15 +1103,7 @@ impl Documents { if st.uri.is_none() || !is_untitled(&st.path) { return Err(IdeError::invalid("only an untitled document can be saved to a new path")); } - let text = st.doc.text_for_save(); - if let Some(parent) = target.parent() { - std::fs::create_dir_all(parent)?; - } - let mtime = if st.native_to_ascii { - ide_vfs::save_properties_text(&target, &text)? - } else { - ide_vfs::save_text(&target, &text, &st.encoding, st.has_bom)? - }; + let mtime = Self::write_to(st, &target)?; // Re-key the registry before anyone opens the new path in parallel. let keys = keys_for(&target); { @@ -1148,6 +1153,35 @@ impl Documents { }) } + /// Copies the current buffer without changing the source; another open target is never overwritten. + pub fn copy_as(&self, doc: DocId, target: &Path) -> IdeResult { + // Keep the operation lock across the target check and write so opening cannot race the copy. + let _operation = self.operations.lock(); + if is_untitled(target) { + return Err(IdeError::invalid("cannot copy over an untitled buffer")); + } + let target = absolute(target); + { + let reg = self.registry.lock(); + match Self::lookup(®, &target) { + Some(other) if other != doc => { + return Err(IdeError::invalid(format!("{} is already open", target.display()))); + } + Some(_) => return Ok(false), + None => {} + } + } + let slot = self.slot(doc)?; + let st = slot.lock(); + if st.closed { + return Err(IdeError::not_found(format!("document {doc} is not open"))); + } + if st.uri.is_some() || ide_vfs::is_archive_path(&st.path) { + return Err(IdeError::invalid("only a file document can be copied to a new path")); + } + Self::write_to(&st, &target).map(|_| true) + } + pub fn has_unsaved_changes(&self) -> bool { self.registry.lock().docs.values().any(|entry| entry.slot.lock().dirty) } diff --git a/crates/ide-workspace/tests/documents.rs b/crates/ide-workspace/tests/documents.rs index 8a4863efb7..0606e46361 100644 --- a/crates/ide-workspace/tests/documents.rs +++ b/crates/ide-workspace/tests/documents.rs @@ -1285,6 +1285,66 @@ fn untitled_buffers_are_editable_and_saved_to_a_chosen_path() { assert!(f.docs.snapshot(info.id).is_err()); } +#[test] +fn save_as_copies_dirty_file_without_saving_or_retargeting_source() { + let f = fixture(); + let source = f.root.join("source.txt"); + fs::write(&source, "saved\n").unwrap(); + let info = f.docs.open(&source).unwrap(); + let version = f.docs.edit(info.id, info.version, change(0, 0, "dirty ")).unwrap(); + assert!(f.docs.is_dirty(info.id).unwrap()); + f.rec.log.lock().clear(); + + let target = f.root.join("nested/copy.txt"); + f.docs.copy_as(info.id, &target).unwrap(); + + assert_eq!(fs::read_to_string(&source).unwrap(), "saved\n"); + assert_eq!(fs::read_to_string(&target).unwrap(), "dirty saved\n"); + let after = f.docs.snapshot(info.id).unwrap(); + assert_eq!(after.id, info.id); + assert_eq!(after.path, source); + assert_eq!(after.version, version); + assert_eq!(after.text, "dirty saved\n"); + assert!(after.dirty); + assert_eq!(f.docs.by_path(&source), Some(info.id)); + assert_eq!(f.docs.by_path(&target), None, "the copy is opened through the normal document service"); + assert!(!f.rec.log.lock().iter().any(|entry| entry.starts_with("save "))); + + let copy = f.docs.open(&target).unwrap(); + assert_ne!(copy.id, info.id); + assert_eq!(copy.text, "dirty saved\n"); + assert!(!copy.dirty); + assert!(f.docs.is_dirty(info.id).unwrap()); +} + +#[test] +fn save_as_same_path_is_a_noop_and_copy_failures_leave_the_source_unchanged() { + let f = fixture(); + let source = f.root.join("source.txt"); + fs::write(&source, "saved\n").unwrap(); + let info = f.docs.open(&source).unwrap(); + f.docs.edit(info.id, info.version, change(0, 0, "dirty ")).unwrap(); + fs::create_dir(f.root.join("sub")).unwrap(); + + // A different spelling of the source must not write its dirty buffer to disk. + assert!(!f.docs.copy_as(info.id, &f.root.join("sub/../source.txt")).unwrap()); + assert_eq!(fs::read_to_string(&source).unwrap(), "saved\n"); + assert!(f.docs.is_dirty(info.id).unwrap()); + + let blocked = f.root.join("blocked"); + fs::write(&blocked, "not a directory").unwrap(); + assert!(f.docs.copy_as(info.id, &blocked.join("copy.txt")).is_err()); + assert_eq!(fs::read_to_string(&source).unwrap(), "saved\n"); + assert!(f.docs.is_dirty(info.id).unwrap()); + + let taken = f.root.join("taken.txt"); + fs::write(&taken, "taken\n").unwrap(); + let other = f.docs.open(&taken).unwrap(); + assert!(f.docs.copy_as(info.id, &taken).is_err()); + assert_eq!(fs::read_to_string(&taken).unwrap(), "taken\n"); + assert_eq!(f.docs.snapshot(other.id).unwrap().text, "taken\n"); +} + #[test] fn save_as_rejects_paths_opened_elsewhere_and_reuses_free_names() { let f = fixture(); diff --git a/docs/en/guide/editor.mdx b/docs/en/guide/editor.mdx index f21d160771..91cc2153fd 100644 --- a/docs/en/guide/editor.mdx +++ b/docs/en/guide/editor.mdx @@ -182,6 +182,8 @@ With tabs placed left or right, the tab column is as wide as its longest name, u As in IntelliJ IDEA, there is no per-file save: files are saved when you switch to another application or to the built-in terminal, and **File › Save All** (`⌘S` / `Ctrl+S`) saves everything at once. **Settings › Appearance & Behavior › System Settings**, section **Autosave**, can also save after the IDE has been idle for a while. +**File › Save As…** (`⇧⌘S` / `Ctrl+Shift+S`) opens the Copy dialog for the current file. The copy includes unsaved edits; the copy operation itself does not save or retarget the original tab, buffer or file. Choose a destination and optionally select **Open copy in editor** to open the copy in a new active tab. + If you keep typing during a save, edits not included in that write stay marked as unsaved. Changes made outside the IDE are picked up when you switch back to its window. **Reload from Disk** (`⌥⌘Y` / `Ctrl+Alt+Y`) reloads the current file now. diff --git a/docs/en/reference/shortcuts.mdx b/docs/en/reference/shortcuts.mdx index 44862f67ff..0a2efdb89c 100644 --- a/docs/en/reference/shortcuts.mdx +++ b/docs/en/reference/shortcuts.mdx @@ -192,6 +192,7 @@ Some shortcuts depend on where the focus is. For example `⌘N` / `Alt+Insert` i | --------------------------------- | ------------ | ----------------------- | | Settings… | `⌘,` | `Ctrl+Alt+S` | | Project Structure… | `⌘;` | `Ctrl+Alt+Shift+S` | +| Save As… | `⇧⌘S` | `Ctrl+Shift+S` | | Save All | `⌘S` | `Ctrl+S` | | New Scratch File… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` | | Quick Preview (Project) | `Space` | `Space` | diff --git a/docs/zh/guide/editor.mdx b/docs/zh/guide/editor.mdx index b167d0148a..34d588f6dc 100644 --- a/docs/zh/guide/editor.mdx +++ b/docs/zh/guide/editor.mdx @@ -180,6 +180,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 和 IntelliJ IDEA 一样,这里没有逐个文件保存的概念:切换到其他应用或内置终端时文件会自动保存,**文件 › 全部保存**(`⌘S` / `Ctrl+S`)立即保存所有文件。**设置 › 外观与行为 › 系统设置** 的 **自动保存** 一节还可以设置在 IDE 空闲一段时间后保存。 +**文件 › 另存为…**(`⇧⌘S` / `Ctrl+Shift+S`)为当前文件打开“复制”对话框。副本包含未保存的编辑;复制操作本身不会保存或改变原标签页、缓冲区和磁盘文件。选择目标位置,并可勾选**在编辑器中打开副本**,在新的活动标签页中打开副本。 + 如果在保存期间继续编辑,未写入磁盘的改动仍会标记为未保存。 在 IDE 之外修改的文件,会在切回 IDE 窗口时同步。**从磁盘重新加载**(`⌥⌘Y` / `Ctrl+Alt+Y`)立即重新加载当前文件。 diff --git a/docs/zh/reference/shortcuts.mdx b/docs/zh/reference/shortcuts.mdx index 9f2712d56d..55f306691c 100644 --- a/docs/zh/reference/shortcuts.mdx +++ b/docs/zh/reference/shortcuts.mdx @@ -192,6 +192,7 @@ macOS 符号:`⌘` Command、`⌥` Option、`⌃` Control、`⇧` Shift、`↵ | ---------------------- | ------------ | ----------------------- | | 设置… | `⌘,` | `Ctrl+Alt+S` | | 项目结构… | `⌘;` | `Ctrl+Alt+Shift+S` | +| 另存为… | `⇧⌘S` | `Ctrl+Shift+S` | | 全部保存 | `⌘S` | `Ctrl+S` | | 新建临时文件… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` | | 快速预览(项目) | `Space` | `Space` | diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 2371b8ecdc..1d120d3893 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -241,6 +241,7 @@ deploy_upload trusted project_host bin diff_external_tool always desktop bindings async doc_autosave always project_host bindings async doc_close always project_host bindings async +doc_copy_as always project_host bindings async doc_edit always project_host bindings async doc_flutter_outline always project_host bindings async doc_folding always project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index d54086f15c..9b2fa4f48f 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -582,6 +582,8 @@ export const commands = { */ docAutosave: (doc: DocId) => typedError(__TAURI_INVOKE("doc_autosave", { doc })), docClose: (doc: DocId) => typedError(__TAURI_INVOKE("doc_close", { doc })), + /** Copies the current buffer, including unsaved edits, without changing the source; false for the source itself. */ + docCopyAs: (doc: DocId, path: string) => typedError(__TAURI_INVOKE("doc_copy_as", { doc, path })), /** * Applies a CodeMirror change set; returns the new version. Rejects with * `outOfSync` when `base_version` is stale; the UI then calls `doc_snapshot`. diff --git a/src/editor/core/backend.ts b/src/editor/core/backend.ts index 955e0433d1..b4ddd73bb8 100644 --- a/src/editor/core/backend.ts +++ b/src/editor/core/backend.ts @@ -49,6 +49,8 @@ export interface DocBackend { openUntitled(name: string | null): Promise; /** Save As for an untitled buffer: writes it to `path` and re-keys the document. */ saveAs(doc: DocId, path: string): Promise; + /** Copies a real file's current buffer to `path`; `false` when it already names the source. */ + copyAs(doc: DocId, path: string): Promise; close(doc: DocId): Promise; edit(doc: DocId, baseVersion: number, changes: TextChange[]): Promise; save(doc: DocId): Promise; @@ -100,6 +102,7 @@ export const ipcBackend: DocBackend = { openVirtual: (uri) => call(commands.docOpenVirtual(uri)), openUntitled: (name) => call(commands.docOpenUntitled(name)), saveAs: (doc, path) => call(commands.docSaveAs(doc, path)), + copyAs: (doc, path) => call(commands.docCopyAs(doc, path)), close: async (doc) => void (await call(commands.docClose(doc))), edit: (doc, baseVersion, changes) => call(commands.docEdit(doc, baseVersion, { changes })), save: async (doc) => void (await call(commands.docSave(doc))), @@ -588,6 +591,16 @@ export function createMemoryBackend(files: Record = {}): MemoryB setDirty(d, before); return info(d); }, + async copyAs(doc, path) { + const d = get(doc); + if (d.uri) + throw new IpcError({ kind: "invalidInput", message: "only a file document can be copied to a new path" }); + if (byPath.get(path) === doc) return false; + if (byPath.has(path)) throw new IpcError({ kind: "invalidInput", message: `${path} is already open` }); + store.set(path, d.text); + savedBoms.set(path, d.hasBom); + return true; + }, edit(doc, baseVersion, changes) { return delay(() => { const d = get(doc); diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts index 3e7c26a3f5..b670bd9481 100644 --- a/src/editor/core/controller.test.ts +++ b/src/editor/core/controller.test.ts @@ -129,6 +129,30 @@ describe("EditorController", () => { expect(useProjectViewLead.getState().lead).toBeNull(); }); + it("copies an open file's unsaved buffer without saving or retargeting its source", async () => { + const backend = createMemoryBackend({ "/p/source.txt": "saved\n" }); + ctrl = new EditorController(backend); + ctrl.start(); + expect(await ctrl.copyAs("/p/not-open.txt", "/p/not-open-copy.txt")).toBeNull(); + + await ctrl.openFile("/p/source.txt", { focus: false }); + const sourceTab = useTabs.getState().panes[useTabs.getState().activePane]!.active!; + const slot = ctrl.slotFor(sourceTab)!; + slot.dispatchLocal({ + changes: { from: 0, to: slot.currentState().doc.length, insert: "dirty\n" }, + userEvent: "input.type", + }); + await vi.waitFor(() => expect(slot.model.getMeta().dirty).toBe(true)); + const save = vi.spyOn(backend, "save"); + + expect(await ctrl.copyAs("/p/source.txt", "/p/copy.txt")).toBe(true); + expect(save).not.toHaveBeenCalled(); + expect(backend.files.get("/p/source.txt")).toBe("saved\n"); + expect(backend.files.get("/p/copy.txt")).toBe("dirty\n"); + expect(ctrl.manager.get("/p/source.txt")?.getMeta()).toMatchObject({ path: "/p/source.txt", dirty: true }); + expect(ctrl.manager.get("/p/copy.txt")).toBeUndefined(); + }); + it("goes back to the line a stand-in view shows (Markdown Preview only), not the hidden caret", async () => { const text = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n"); ctrl = new EditorController(createMemoryBackend({ "/p/a.md": text, "/p/b.md": "b\n" })); diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index ce0bbd1736..e403f059f1 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -2416,6 +2416,14 @@ export class EditorController implements SlotHost { return this.activeSlot?.model.path ?? this.activeTabOf()?.input.path ?? null; } + /** Copies an open file's current buffer without saving it; null when no editor document owns `path`. */ + async copyAs(path: string, target: string): Promise { + const model = this.manager.get(path); + if (!model || model.closed || model.virtual || isUntitledUri(path)) return null; + await model.sync.whenIdle(); + return this.manager.backend.copyAs(model.doc, target); + } + activeCursor() { const slot = this.activeSlot; if (!slot) return null; diff --git a/src/editor/core/index.ts b/src/editor/core/index.ts index 128a280e69..97104ac2b8 100644 --- a/src/editor/core/index.ts +++ b/src/editor/core/index.ts @@ -51,6 +51,7 @@ export function activate(): void | (() => void) { activePath: () => ctrl.activePath(), activeCursor: () => ctrl.activeCursor(), saveAll: (opts) => ctrl.saveAll(opts), + copyAs: (path, target) => ctrl.copyAs(path, target), dirtyDocumentIds: () => [...ctrl.manager.byId.values()].filter((m) => m.getMeta().dirty).map((m) => m.doc), untitledDirtyDocumentIds: () => [...ctrl.manager.byId.values()].filter((m) => isUntitledUri(m.path) && m.getMeta().dirty).map((m) => m.doc), diff --git a/src/features/app/__tests__/menuBridge.test.ts b/src/features/app/__tests__/menuBridge.test.ts index bf8a011083..4823cb18c3 100644 --- a/src/features/app/__tests__/menuBridge.test.ts +++ b/src/features/app/__tests__/menuBridge.test.ts @@ -265,6 +265,7 @@ describe("menu config", () => { it("carries keymap shortcuts as native accelerators", () => { const mac = buildMenuConfig("macos"); expect(mac.accelerators["file.save"]).toBe("Meta+S"); + expect(mac.accelerators["file.saveAs"]).toBe("Shift+Meta+S"); expect(mac.accelerators["navigate.gotoFile"]).toBe("Shift+Meta+O"); expect(mac.accelerators["build.compileFile"]).toBe("Shift+Meta+F9"); expect(mac.accelerators["navigate.searchEverywhere"]).toBeUndefined(); diff --git a/src/features/project-tree/FileRefactorDialogs.tsx b/src/features/project-tree/FileRefactorDialogs.tsx index 269bc39aad..3c6dd68c59 100644 --- a/src/features/project-tree/FileRefactorDialogs.tsx +++ b/src/features/project-tree/FileRefactorDialogs.tsx @@ -51,6 +51,8 @@ export type FileRefactorRequest = target: string; /** The single copied item is a folder. */ dir?: boolean; + /** Save As always opens the copy without changing the remembered Copy option. */ + forceOpenInEditor?: boolean; /** Copies into `target` (`name`: the single item's new name); false keeps the dialog open. */ copy: (target: string, name: string | null, openInEditor: boolean) => Promise; }; @@ -433,6 +435,7 @@ function CopyDialog({ request }: { request: Extract taken.has(fold(n)), !!request.dir) : ""; }); const [openInEditor, setOpenInEditor] = useState(() => { + if (request.forceOpenInEditor) return true; try { return localStorage.getItem(COPY_OPEN_KEY) === "true"; } catch { @@ -465,10 +468,12 @@ function CopyDialog({ request }: { request: Extract { if (busy || browsing || error) return; - try { - localStorage.setItem(COPY_OPEN_KEY, String(openInEditor)); - } catch { - /* storage unavailable */ + if (!request.forceOpenInEditor) { + try { + localStorage.setItem(COPY_OPEN_KEY, String(openInEditor)); + } catch { + /* storage unavailable */ + } } setBusy(true); const ok = await request.copy(dest, single ? name : null, openInEditor && !request.dir); @@ -484,7 +489,12 @@ function CopyDialog({ request }: { request: Extract + ) } buttons={[ diff --git a/src/features/project-tree/actions.ts b/src/features/project-tree/actions.ts index ebbeb28786..2c6b35a790 100644 --- a/src/features/project-tree/actions.ts +++ b/src/features/project-tree/actions.ts @@ -1,10 +1,11 @@ /** Actions of the project view (Find Action, keymap, other features via `executeAction`). */ -import { activeEditor } from "@/editor/api"; +import { activeEditor, focusedCellEditor } from "@/editor/api"; import { executeAction, getAction, registerActions, type Action } from "@/platform/actions"; import { getContext } from "@/platform/context"; import { FILE_COLOR_NAMES } from "@/platform/fileColors"; import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fileManager"; import { dirname, useProject } from "@/platform/project"; +import { isUntitledUri } from "@/platform/virtualDocs"; import { showContextMenu, type MenuItem } from "@/ui"; import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions"; import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions"; @@ -415,6 +416,21 @@ export function registerProjectActions(): () => void { if (path) openCopyDialog(nodesFrom(path)); }, }, + { + id: "file.saveAs", + title: "Save As…", + category: "File", + keywords: ["save", "copy file"], + when: "textEditorActive", + enabled: () => { + const editor = activeEditor(); + return !!editor && !editor.ctx.virtual && !isUntitledUri(editor.ctx.path) && !focusedCellEditor(); + }, + run: () => { + const path = activeEditor()?.ctx.path; + if (path) openCopyDialog(nodesFrom(path), { forceOpenInEditor: true }); + }, + }, { id: "navigate.showFilePath", title: "File Path", diff --git a/src/features/project-tree/operations.test.ts b/src/features/project-tree/operations.test.ts index 7b43941a26..d93335d3fd 100644 --- a/src/features/project-tree/operations.test.ts +++ b/src/features/project-tree/operations.test.ts @@ -5,6 +5,7 @@ import { checkEditingName, copySelection, importExternal, + openCopyDialog, paste, refreshOsClipboard, revealablePath, @@ -16,7 +17,11 @@ import { IpcError } from "@/platform/ipc"; import { closeFileRefactorDialog, pendingFileRefactorDialog } from "./FileRefactorDialogs"; import { useRemote } from "@/platform/remote"; import { usePlatform } from "@/platform/platformInfo"; -import { provideNotificationService } from "@/workbench/contributions"; +import { provideEditorService, provideNotificationService, type EditorService } from "@/workbench/contributions"; +import { getAction } from "@/platform/actions"; +import { getContext } from "@/platform/context"; +import { useEditorRegistry } from "@/editor/api"; +import { registerProjectActions } from "./actions"; import { MemoryFs, setProjectFsForTests } from "./fs"; import { initProjectTree, loadDir, setClipboard, setSelection, useProjectTree } from "./store"; import { setOsClipboardForTests } from "./clipboard"; @@ -598,6 +603,97 @@ describe("project clipboard ownership", () => { }); }); +describe("Copy dialog buffer copies and Save As", () => { + let disposeActions: () => void; + let copyAs: ReturnType; + let openFile: ReturnType; + + beforeEach(async () => { + fs = new MemoryFs({ "/p/source.txt": "saved\n", "/p/other.txt": "other\n", "/p/target": null }, "/p"); + setProjectFsForTests(fs, "/p"); + initProjectTree("/p", "p"); + await loadDir("/p"); + provideNotificationService({ notify }); + notify.mockClear(); + copyAs = vi.fn(async () => true); + openFile = vi.fn(async () => {}); + provideEditorService({ copyAs, openFile, activePath: () => "/p/source.txt" } as unknown as EditorService); + disposeActions = registerProjectActions(); + }); + + afterEach(() => { + disposeActions(); + closeFileRefactorDialog(); + provideEditorService(undefined as unknown as EditorService); + useEditorRegistry.setState({ active: null }); + setProjectFsForTests(null); + initProjectTree(null); + vi.restoreAllMocks(); + }); + + it("copies one open file through its document buffer and opens the copy on request", async () => { + const filesystemCopy = vi.spyOn(fs, "copy"); + openCopyDialog([node("/p/source.txt")]); + const request = pendingFileRefactorDialog(); + expect(request).toMatchObject({ kind: "copy", paths: ["/p/source.txt"], target: "/p" }); + if (request?.kind !== "copy") throw new Error("no copy dialog"); + + expect(await request.copy("/p/target", "source copy.txt", true)).toBe(true); + expect(copyAs).toHaveBeenCalledExactlyOnceWith("/p/source.txt", "/p/target/source copy.txt"); + expect(filesystemCopy).not.toHaveBeenCalled(); + expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/target/source copy.txt", { focus: true }); + }); + + it("keeps the filesystem copy path when the source is not open", async () => { + copyAs.mockResolvedValue(null); + const filesystemCopy = vi.spyOn(fs, "copy"); + openCopyDialog([node("/p/source.txt")]); + const request = pendingFileRefactorDialog(); + if (request?.kind !== "copy") throw new Error("no copy dialog"); + + expect(await request.copy("/p/target", "source copy.txt", false)).toBe(true); + expect(copyAs).toHaveBeenCalledExactlyOnceWith("/p/source.txt", "/p/target/source copy.txt"); + expect(filesystemCopy).toHaveBeenCalledExactlyOnceWith("/p/source.txt", "/p/target/source copy.txt"); + expect(openFile).not.toHaveBeenCalled(); + }); + + it("reports a buffer copy failure without falling back to stale disk contents", async () => { + copyAs.mockRejectedValue(new Error("disk full")); + const filesystemCopy = vi.spyOn(fs, "copy"); + openCopyDialog([node("/p/source.txt")]); + const request = pendingFileRefactorDialog(); + if (request?.kind !== "copy") throw new Error("no copy dialog"); + + expect(await request.copy("/p/target", "source copy.txt", false)).toBe(false); + expect(filesystemCopy).not.toHaveBeenCalled(); + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ level: "error", title: "Some items could not be copied", body: "disk full" }), + ); + }); + + it("opens the same Copy dialog for Save As and F5 using the active editor's file", async () => { + setSelection(new Set(["/p/other.txt"]), "/p/other.txt"); + useEditorRegistry.setState({ active: { ctx: { path: "/p/source.txt" } } as never }); + + await getAction("file.saveAs")!.run({ ctx: getContext() }); + expect(pendingFileRefactorDialog()).toMatchObject({ + kind: "copy", + paths: ["/p/source.txt"], + target: "/p", + forceOpenInEditor: true, + }); + closeFileRefactorDialog(); + + await getAction("project.copyElement")!.run({ ctx: { ...getContext(), projectViewFocus: false } }); + expect(pendingFileRefactorDialog()).toMatchObject({ + kind: "copy", + paths: ["/p/source.txt"], + target: "/p", + forceOpenInEditor: false, + }); + }); +}); + describe("revealablePath", () => { const platform = usePlatform.getState(); afterEach(() => { diff --git a/src/features/project-tree/operations.ts b/src/features/project-tree/operations.ts index 1fa008ca0d..992af98c55 100644 --- a/src/features/project-tree/operations.ts +++ b/src/features/project-tree/operations.ts @@ -22,6 +22,7 @@ import { beginLocalImport, projectFs } from "./fs"; import { renameCopiedJavaType } from "./javaCopy"; import { javaPackageAt, pastedJavaClass, withJavaPackage } from "./javaPaste"; import { currentRoots } from "@/platform/projectRoots"; +import { notifyFileOperation } from "@/platform/fileOps"; import { IpcError, isCancelled, isTauri } from "@/platform/ipc"; import { MEMBER_PREFIX, type ProjectNode } from "./model"; import { @@ -223,12 +224,12 @@ export function openMoveDialog(nodes: ProjectNode[] = selectedNodes(), target?: } /** Copy… (F5): IDEA's Copy dialog for the selection, into the folder it is in. */ -export function openCopyDialog(nodes: ProjectNode[] = selectedNodes()) { +export function openCopyDialog(nodes: ProjectNode[] = selectedNodes(), options: { forceOpenInEditor?: boolean } = {}) { const copyable = nodes.filter((n) => !n.root && !n.group); const paths = topLevelPaths(copyable); if (!paths.length) return; const single = paths.length === 1 && copyable.some((n) => n.path === paths[0] && n.dir); - openCopyDialogFor(paths, parentOf(paths[0]!), single); + openCopyDialogFor(paths, parentOf(paths[0]!), single, options.forceOpenInEditor); } function openMoveDialogFor(paths: string[], target?: string, dir?: boolean, done?: () => void) { @@ -763,7 +764,7 @@ function sameFiles(files: string[], paths: string[] | undefined): boolean { return key(files) === key(paths); } -function openCopyDialogFor(paths: string[], target: string, dir?: boolean) { +function openCopyDialogFor(paths: string[], target: string, dir?: boolean, forceOpenInEditor = false) { if (!paths.length) return; void loadDir(target); openFileRefactorDialog({ @@ -771,14 +772,42 @@ function openCopyDialogFor(paths: string[], target: string, dir?: boolean) { paths, target, dir, + forceOpenInEditor, copy: async (to, name, openInEditor) => { - const first = await transfer(paths, to, "copy", name ?? undefined); + const first = await copyDialogPaths(paths, to, name, dir); if (typeof first === "string" && openInEditor) void openFile(first, { focus: true }); return !!first; }, }); } +/** A single open file is copied from its document buffer; closed files keep the filesystem copy path. */ +async function copyDialogPaths( + paths: string[], + target: string, + name: string | null, + dir?: boolean, +): Promise { + const source = !dir && paths.length === 1 ? paths[0]! : null; + if (!source) return transfer(paths, target, "copy", name ?? undefined); + const to = joinPath(target, name ?? nameOf(source)); + try { + const copied = await maybeEditorService()?.copyAs?.(source, to); + if (copied === undefined || copied === null) return transfer(paths, target, "copy", name ?? undefined); + if (!copied) return false; + notifyFileOperation({ kind: "created", paths: [to] }); + // Preserve the Copy dialog's Java class rename for buffer-backed copies too. + await renameCopiedJavaType(source, to).catch(() => undefined); + await loadDir(target, true); + expandFolder(target); + revealPath(to, false); + return to; + } catch (e) { + fail("Some items could not be copied", e); + return false; + } +} + type ConflictChoice = "overwrite" | "skip" | "copy"; /** diff --git a/src/features/vim/__tests__/rc.test.ts b/src/features/vim/__tests__/rc.test.ts index dd9c95cd82..2e941803dd 100644 --- a/src/features/vim/__tests__/rc.test.ts +++ b/src/features/vim/__tests__/rc.test.ts @@ -191,6 +191,7 @@ describe(":action ids", () => { expect(resolveActionId("GotoDeclaration")).toBe("navigate.declaration"); expect(resolveActionId("ReformatCode")).toBe("code.reformat"); expect(resolveActionId("FindInPath")).toBe("find.inPath"); + expect(resolveActionId("SaveAs")).toBe("file.saveAs"); expect(resolveActionId("code.commentLine")).toBe("code.commentLine"); }); diff --git a/src/platform/i18n.test.ts b/src/platform/i18n.test.ts index 7000d5b758..ededaf2f0a 100644 --- a/src/platform/i18n.test.ts +++ b/src/platform/i18n.test.ts @@ -259,6 +259,7 @@ describe("t / locales", () => { it("lists keys by prefix", () => { const keys = keysWithPrefix("menu."); expect(keys).toContain("menu.file.save"); + expect(keys).toContain("menu.file.saveAs"); expect(keys.every((k) => k.startsWith("menu."))).toBe(true); }); }); diff --git a/src/platform/ideaActions.ts b/src/platform/ideaActions.ts index 462dcee6b4..cf77ac14d9 100644 --- a/src/platform/ideaActions.ts +++ b/src/platform/ideaActions.ts @@ -103,6 +103,7 @@ export const IDEA_ACTIONS: Readonly> = { "Debugger.RemoveAllBreakpoints": "debug.removeAllBreakpoints", "Debugger.RemoveAllBreakpointsInFile": "debug.removeAllBreakpointsInFile", ToggleBreakpointEnabled: "debug.toggleBreakpointEnabled", + SaveAs: "file.saveAs", SaveAll: "file.save", ShowSettings: "file.settings", NewScratchFile: "file.newScratchFile", diff --git a/src/platform/keymaps/ideaParity.test.ts b/src/platform/keymaps/ideaParity.test.ts index c6fa151d4e..f0f8853061 100644 --- a/src/platform/keymaps/ideaParity.test.ts +++ b/src/platform/keymaps/ideaParity.test.ts @@ -152,6 +152,7 @@ describe("IDEA keymap parity", () => { ["workbench.stopBackgroundProcesses", ["Meta+Shift+F2"], ["Ctrl+Shift+F2"]], ["navigate.back", ["Meta+[", "Meta+Alt+Left", "Button4", "SwipeRight"], ["Ctrl+Alt+Left", "Button4"]], ["navigate.forward", ["Meta+]", "Meta+Alt+Right", "Button5", "SwipeLeft"], ["Ctrl+Alt+Right", "Button5"]], + ["file.saveAs", ["Meta+Shift+S"], ["Ctrl+Shift+S"]], ["file.projectStructure", ["Meta+;"], ["Ctrl+Alt+Shift+S"]], ["build.compileFile", ["Meta+Shift+F9"], ["Ctrl+Shift+F9"]], ["build.buildModule", [], []], diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index ee5a22c6c1..d8a26123e6 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -229,6 +229,7 @@ export const intellijMacos: Record = { "refactor.pushMembersDown": [], // File / editor tabs + "file.saveAs": ["Meta+Shift+S"], "file.save": ["Meta+S"], "file.settings": ["Meta+,"], "file.projectStructure": ["Meta+;"], diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index ac081f0085..12d52d10cf 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -230,6 +230,7 @@ export const intellijWindows: Record = { "refactor.pushMembersDown": [], // File / editor tabs + "file.saveAs": ["Ctrl+Shift+S"], "file.save": ["Ctrl+S"], "file.settings": ["Ctrl+Alt+S"], "file.projectStructure": ["Ctrl+Alt+Shift+S"], diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index ddba4d5aaf..bbbf3eed81 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -223,6 +223,7 @@ export const vscodeMacos: Record = { // File / editor tabs "file.save": ["Meta+S"], + "file.saveAs": ["Meta+Shift+S"], "file.newUntitled": ["Meta+N"], "file.new": [], "file.settings": ["Meta+,"], diff --git a/src/platform/locales/en.json b/src/platform/locales/en.json index 11f7315e78..3931a9a7e4 100644 --- a/src/platform/locales/en.json +++ b/src/platform/locales/en.json @@ -236,6 +236,7 @@ "menu.window.previousTab": "Previous Project Tab", "menu.project.attach": "Attach Project…", "menu.file.openProject": "Open…", + "menu.file.saveAs": "Save As…", "menu.file.save": "Save All", "menu.file.projectStructure": "Project Structure…", "menu.file.settings": "Settings…", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 7fccfc4113..1407a68b76 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -2790,6 +2790,7 @@ "Save": "儲存", "Save All": "全部儲存", "Save As": "另存為", + "Save As…": "另存為…", "Save Files": "儲存檔案", "Save files if the IDE is idle for": "IDE 空閒以下時長時儲存檔案", "Save files when switching to a different application or a built-in terminal": "切換到其他應用程式或內建終端機時儲存檔案", diff --git a/src/platform/locales/zh-TW.json b/src/platform/locales/zh-TW.json index c8f87ec183..4106274287 100644 --- a/src/platform/locales/zh-TW.json +++ b/src/platform/locales/zh-TW.json @@ -232,6 +232,7 @@ "menu.window.previousTab": "上一個專案分頁", "menu.project.attach": "附加專案…", "menu.file.openProject": "開啟…", + "menu.file.saveAs": "另存為…", "menu.file.save": "全部儲存", "menu.file.projectStructure": "專案結構…", "menu.file.settings": "設定…", diff --git a/src/platform/locales/zh.json b/src/platform/locales/zh.json index 18c8abef4a..d085f02283 100644 --- a/src/platform/locales/zh.json +++ b/src/platform/locales/zh.json @@ -236,6 +236,7 @@ "menu.window.previousTab": "上一个项目标签页", "menu.project.attach": "附加项目…", "menu.file.openProject": "打开…", + "menu.file.saveAs": "另存为…", "menu.file.save": "全部保存", "menu.file.projectStructure": "项目结构…", "menu.file.settings": "设置…", diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index f5d8661831..cfcbb2b14e 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -841,6 +841,8 @@ export interface EditorService { activeCursor(): { doc: number; path: string; line: number; col: number; offset: number } | null; /** Save all dirty documents; rejects with the failures once every save was tried. */ saveAll(opts?: { skipUntitled?: boolean }): Promise; + /** Copies an open file's current buffer to `target`; null when `path` is not open in an editor. */ + copyAs?(path: string, target: string): Promise; /** Doc ids of untitled buffers with unsaved changes (they follow the window, not a project). */ untitledDirtyDocumentIds?(): number[]; /** Includes local edits not yet acknowledged by the backend. */ diff --git a/src/workbench/pathChooser.test.tsx b/src/workbench/pathChooser.test.tsx index 991455387b..c4507f1b1c 100644 --- a/src/workbench/pathChooser.test.tsx +++ b/src/workbench/pathChooser.test.tsx @@ -159,6 +159,22 @@ describe("choosePath in a remote window", () => { expect(mocks.confirm).not.toHaveBeenCalled(); }); + it("does not accept an existing save destination when overwrite is declined", async () => { + mocks.confirm.mockResolvedValueOnce(false); + let result!: Promise; + act(() => { + result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/pom.xml" }); + }); + await dialog().findByText("runner"); + fireEvent.click(dialog().getByRole("button", { name: "OK" })); + await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce()); + expect(mocks.nativeSave).not.toHaveBeenCalled(); + expect(screen.getByRole("dialog")).toBeTruthy(); + + fireEvent.click(dialog().getByRole("button", { name: "Cancel" })); + await expect(result).resolves.toBeNull(); + }); + it("asks before accepting an existing save destination", async () => { mocks.confirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true); let result!: Promise;