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 <[email protected]>
Цей коміт міститься в:
Muuтаmuutot authored and GitHub committed 2026-11-29 10:35:25 +08:00
1 джерело 2cce84ad2c
коміт c709844c04
33 files changed
+396 -20

No files matched your search

+1
Переглянути файл
@@ -236,6 +236,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
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")]),
+15
Переглянути файл
@@ -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<bool> {
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,
+30
Переглянути файл
@@ -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();
+43 -9
Переглянути файл
@@ -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<f64> {
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<bool> {
// 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(&reg, &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)
}
+60
Переглянути файл
@@ -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();
+2
Переглянути файл
@@ -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.
+1
Переглянути файл
@@ -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` |
+2
Переглянути файл
@@ -180,6 +180,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
和 IntelliJ IDEA 一样,这里没有逐个文件保存的概念:切换到其他应用或内置终端时文件会自动保存,**文件 › 全部保存**(`⌘S` / `Ctrl+S`)立即保存所有文件。**设置 › 外观与行为 › 系统设置** 的 **自动保存** 一节还可以设置在 IDE 空闲一段时间后保存。
**文件 › 另存为…**(`⇧⌘S` / `Ctrl+Shift+S`)为当前文件打开“复制”对话框。副本包含未保存的编辑;复制操作本身不会保存或改变原标签页、缓冲区和磁盘文件。选择目标位置,并可勾选**在编辑器中打开副本**,在新的活动标签页中打开副本。
如果在保存期间继续编辑,未写入磁盘的改动仍会标记为未保存。
在 IDE 之外修改的文件,会在切回 IDE 窗口时同步。**从磁盘重新加载**(`⌥⌘Y` / `Ctrl+Alt+Y`)立即重新加载当前文件。
+1
Переглянути файл
@@ -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` |
+1
Переглянути файл
@@ -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
+2
Переглянути файл
@@ -582,6 +582,8 @@ export const commands = {
*/
docAutosave: (doc: DocId) => typedError<boolean, IdeError>(__TAURI_INVOKE("doc_autosave", { doc })),
docClose: (doc: DocId) => typedError<null, IdeError>(__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<boolean, IdeError>(__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`.
+13
Переглянути файл
@@ -49,6 +49,8 @@ export interface DocBackend {
openUntitled(name: string | null): Promise<DocumentInfo>;
/** Save As for an untitled buffer: writes it to `path` and re-keys the document. */
saveAs(doc: DocId, path: string): Promise<DocumentInfo>;
/** Copies a real file's current buffer to `path`; `false` when it already names the source. */
copyAs(doc: DocId, path: string): Promise<boolean>;
close(doc: DocId): Promise<void>;
edit(doc: DocId, baseVersion: number, changes: TextChange[]): Promise<number>;
save(doc: DocId): Promise<void>;
@@ -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<string, string> = {}): 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);
+24
Переглянути файл
@@ -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" }));
+8
Переглянути файл
@@ -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<boolean | null> {
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;
+1
Переглянути файл
@@ -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),
+1
Переглянути файл
@@ -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();
+15 -5
Переглянути файл
@@ -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<boolean>;
};
@@ -433,6 +435,7 @@ function CopyDialog({ request }: { request: Extract<FileRefactorRequest, { kind:
return single ? uniqueName(own, (n) => 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<FileRefactorRequest, { kind:
: tx`Copy ${count} items`;
const submit = async () => {
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<FileRefactorRequest, { kind:
footerStart={
single &&
!request.dir && (
<Checkbox label="Open copy in editor" checked={openInEditor} disabled={busy} onChange={setOpenInEditor} />
<Checkbox
label="Open copy in editor"
checked={openInEditor}
disabled={busy || request.forceOpenInEditor}
onChange={setOpenInEditor}
/>
)
}
buttons={[
+17 -1
Переглянути файл
@@ -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",
+97 -1
Переглянути файл
@@ -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<typeof vi.fn>;
let openFile: ReturnType<typeof vi.fn>;
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(() => {
+33 -4
Переглянути файл
@@ -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<string | boolean> {
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";
/**
+1
Переглянути файл
@@ -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");
});
+1
Переглянути файл
@@ -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);
});
});
+1
Переглянути файл
@@ -103,6 +103,7 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
"Debugger.RemoveAllBreakpoints": "debug.removeAllBreakpoints",
"Debugger.RemoveAllBreakpointsInFile": "debug.removeAllBreakpointsInFile",
ToggleBreakpointEnabled: "debug.toggleBreakpointEnabled",
SaveAs: "file.saveAs",
SaveAll: "file.save",
ShowSettings: "file.settings",
NewScratchFile: "file.newScratchFile",
+1
Переглянути файл
@@ -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", [], []],
+1
Переглянути файл
@@ -229,6 +229,7 @@ export const intellijMacos: Record<string, string[]> = {
"refactor.pushMembersDown": [],
// File / editor tabs
"file.saveAs": ["Meta+Shift+S"],
"file.save": ["Meta+S"],
"file.settings": ["Meta+,"],
"file.projectStructure": ["Meta+;"],
+1
Переглянути файл
@@ -230,6 +230,7 @@ export const intellijWindows: Record<string, string[]> = {
"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"],
+1
Переглянути файл
@@ -223,6 +223,7 @@ export const vscodeMacos: Record<string, string[]> = {
// File / editor tabs
"file.save": ["Meta+S"],
"file.saveAs": ["Meta+Shift+S"],
"file.newUntitled": ["Meta+N"],
"file.new": [],
"file.settings": ["Meta+,"],
+1
Переглянути файл
@@ -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…",
+1
Переглянути файл
@@ -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": "切換到其他應用程式或內建終端機時儲存檔案",
+1
Переглянути файл
@@ -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": "設定…",
+1
Переглянути файл
@@ -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": "设置…",
+2
Переглянути файл
@@ -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<void>;
/** Copies an open file's current buffer to `target`; null when `path` is not open in an editor. */
copyAs?(path: string, target: string): Promise<boolean | null>;
/** 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. */
+16
Переглянути файл
@@ -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<string | null>;
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<string | null>;