Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 611a829ea7 feat(editor): load or keep a file that changed on disk with unsaved edits
When a file changes on disk while its buffer has unsaved changes, the editor keeps them and
autosave leaves the file alone. The backend reported that with a fixed English notification and
no way to take the disk version except discarding the changes by hand. It now sends
DocDiskConflict, and the editor shows a localized prompt with Load Changes from Disk, which
drops the buffer's changes and reads the file again (doc_reload_from_disk), and Keep Editor
Changes.
2026-11-20 14:09:59 +08:00
12 змінених файлів з 119 додано та 22 видалено

No files matched your search

+6
Переглянути файл
@@ -92,6 +92,12 @@ pub enum IdeEvent {
/// Text version when this transition occurred, including when it was saved.
version: u32,
},
/// An open document's file changed on disk while the buffer had unsaved changes. The buffer
/// keeps them (autosave leaves the file alone); the UI offers to load the disk version.
DocDiskConflict {
doc: DocId,
path: String,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
id: u32,
+8
Переглянути файл
@@ -70,6 +70,13 @@ pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
/// Load Changes from Disk: discards the buffer's unsaved changes and reads its file again.
#[command(trust = always)]
pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.discard_and_reload(doc)).await
}
/// An automatic save: `false` (nothing written) when the file changed on disk after the
/// buffer was edited, which only an explicit save overwrites.
#[command(trust = always)]
@@ -120,6 +127,7 @@ ide_command::domain!(
doc_edit,
doc_open,
doc_open_untitled,
doc_reload_from_disk,
doc_save,
doc_autosave,
doc_save_all,
+5 -3
Переглянути файл
@@ -1,6 +1,6 @@
use super::*;
use crate::{HostConfig, Project};
use ide_core::{IdeEvent, TextChange, event::NotifyLevel};
use ide_core::{IdeEvent, TextChange};
use parking_lot::Mutex;
use std::{path::Path, sync::Arc};
@@ -57,7 +57,9 @@ impl Fixture {
self.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::DocPatched { .. } | IdeEvent::DocDirty { .. } | IdeEvent::Notify { .. }))
.filter(|e| {
matches!(e, IdeEvent::DocPatched { .. } | IdeEvent::DocDirty { .. } | IdeEvent::DocDiskConflict { .. })
})
.cloned()
.collect()
}
@@ -110,7 +112,7 @@ async fn dirty_document_keeps_edits_and_warns_once() {
let loaded = f.project.documents.snapshot(original.id).unwrap();
assert_eq!(loaded.text, "local original\n");
assert!(loaded.dirty);
assert!(matches!(f.document_events().as_slice(), [IdeEvent::Notify { level: NotifyLevel::Warning, .. }]));
assert!(matches!(f.document_events().as_slice(), [IdeEvent::DocDiskConflict { .. }]));
f.events.lock().clear();
f.sync().await;
assert!(f.document_events().is_empty());
+1
Переглянути файл
@@ -191,6 +191,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
| IdeEvent::ExcludedDirsChanged { .. }
| IdeEvent::DocPatched { .. }
| IdeEvent::DocDirty { .. }
| IdeEvent::DocDiskConflict { .. }
| IdeEvent::WorkspaceEditApplied { .. }
| IdeEvent::DocLanguage { .. }
| IdeEvent::Diagnostics { .. }
+20 -12
Переглянути файл
@@ -1,7 +1,6 @@
use crate::editorconfig::{EditorConfig, EditorConfigProps};
use crate::file_defaults::FileDefaults;
use ide_core::error::ErrorKind;
use ide_core::event::NotifyLevel;
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
use parking_lot::{Mutex, ReentrantMutex, RwLock};
@@ -1138,6 +1137,24 @@ impl Documents {
})
}
/// Load Changes from Disk: drops the buffer's unsaved changes and reads its file again in
/// the buffer's encoding, after the file changed on disk (`IdeEvent::DocDiskConflict`).
pub fn discard_and_reload(&self, doc: DocId) -> IdeResult<()> {
self.with_doc(doc, |st| {
if st.uri.is_some() || st.binary {
return Err(IdeError::invalid("only a file's text can be reloaded from disk"));
}
let loaded = Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?;
st.has_bom = loaded.has_bom;
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
self.replace_locked(doc, st, &loaded.text)?;
self.set_dirty(doc, st, false);
Ok(())
})
}
/// The URI of a virtual document, or `None` for a file-backed one.
pub fn virtual_uri(&self, doc: DocId) -> IdeResult<Option<String>> {
self.with_doc(doc, |st| Ok(st.uri.clone()))
@@ -1250,7 +1267,7 @@ impl Documents {
}
/// Re-reads from disk after an external change. Clean documents reload
/// silently; dirty ones are left alone and reported via `IdeEvent::Notify`.
/// silently; dirty ones are left alone and reported via `IdeEvent::DocDiskConflict`.
/// Changes matching our own last save are ignored.
pub fn on_disk_changed(&self, paths: &[PathBuf]) {
self.reload_from_disk(paths, false, false);
@@ -1289,16 +1306,7 @@ impl Documents {
st.disk_mtime = mtime;
st.disk_len = meta.len();
st.disk_conflict = true;
let name = st.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: format!("{name} changed on disk"),
body: Some(format!(
"{} was modified externally but has unsaved changes in the editor. \
Saving explicitly will overwrite the external changes; autosave leaves the file alone.",
st.path.display()
)),
});
self.sink.emit(IdeEvent::DocDiskConflict { doc: id, path: st.path.to_string_lossy().into_owned() });
return Ok(());
}
let loaded = if force_clean {
+20 -5
Переглянути файл
@@ -1,5 +1,4 @@
use ide_core::error::ErrorKind;
use ide_core::event::NotifyLevel;
use ide_core::{ChangeSet, DocId, IdeEvent, LanguageId, Pos, Range, SharedSink, TextChange, TextEdit};
use ide_text::{AppliedChange, LineEnding};
use ide_workspace::documents::DocumentObserver;
@@ -565,15 +564,31 @@ fn external_changes() {
fs::write(&path, "something else\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(id).unwrap().text, "// alpha\nBETA\ngamma\n");
let warnings =
f.events.lock().iter().filter(|e| matches!(e, IdeEvent::Notify { level: NotifyLevel::Warning, .. })).count();
let warnings = f
.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::DocDiskConflict { path: p, .. } if *p == path.to_string_lossy()))
.count();
assert_eq!(warnings, 1);
// The same disk state is reported only once.
f.docs.on_disk_changed(std::slice::from_ref(&path));
let warnings =
f.events.lock().iter().filter(|e| matches!(e, IdeEvent::Notify { level: NotifyLevel::Warning, .. })).count();
let warnings = f
.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::DocDiskConflict { path: p, .. } if *p == path.to_string_lossy()))
.count();
assert_eq!(warnings, 1);
// Load Changes from Disk drops the buffer's changes; autosave writes again afterwards.
f.docs.discard_and_reload(id).unwrap();
let reloaded = f.docs.snapshot(id).unwrap();
assert_eq!((reloaded.text.as_str(), reloaded.dirty), ("something else\n", false));
f.docs.edit(id, reloaded.version, change(0, 0, "# ")).unwrap();
assert!(f.docs.autosave(id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "# something else\n");
// Unknown paths are ignored.
f.docs.on_disk_changed(&[f.root.join("other.txt")]);
}
+1
Переглянути файл
@@ -215,6 +215,7 @@ doc_open_untitled always project_host bin
doc_open_virtual always project_host bindings async
doc_outline always project_host bindings async
doc_python_facts always project_host bindings async
doc_reload_from_disk always project_host bindings async
doc_save always project_host bindings async
doc_save_all always project_host bindings async
doc_save_as always project_host bindings async
+7
Переглянути файл
@@ -533,6 +533,8 @@ export const commands = {
docOutline: (doc: DocId) => typedError<OutlineItem[], IdeError>(__TAURI_INVOKE("doc_outline", { doc })),
/** Python class facts for the inheritance inspections: tree-sitter, no language server. */
docPythonFacts: (doc: DocId) => typedError<PythonFacts, IdeError>(__TAURI_INVOKE("doc_python_facts", { doc })),
/** Load Changes from Disk: discards the buffer's unsaved changes and reads its file again. */
docReloadFromDisk: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_reload_from_disk", { doc })),
docSave: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_save", { doc })),
docSaveAll: () => typedError<null, IdeError>(__TAURI_INVOKE("doc_save_all")),
/**
@@ -7033,6 +7035,11 @@ workspaceEdit?: boolean } |
{ type: "docDirty"; doc: DocId; dirty: boolean;
/** Text version when this transition occurred, including when it was saved. */
version: number } |
/**
* An open document's file changed on disk while the buffer had unsaved changes. The buffer
* keeps them (autosave leaves the file alone); the UI offers to load the disk version.
*/
{ type: "docDiskConflict"; doc: DocId; path: string } |
/** A complete workspace edit can be undone as one operation. */
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
/**
+6
Переглянути файл
@@ -77,6 +77,10 @@ export interface DocBackend {
onDirty(handler: (e: DocDirtyEvent) => void): () => void;
/** Files changed on disk (used to refresh nothing but closed-file state). */
onFsChanged?(handler: (e: { removed: string[] }) => void): () => void;
/** A file changed on disk while its buffer had unsaved changes, which the buffer kept. */
onDiskConflict?(handler: (e: { doc: DocId; path: string }) => void): () => void;
/** Load Changes from Disk: drops the buffer's unsaved changes and reads its file again. */
reloadDiscarding?(doc: DocId): Promise<void>;
/**
* Every OpenIDEA window lost focus to another application. Also seen while focus is in a frame
* (a plugin's web view), which hides the window's own `blur`.
@@ -112,6 +116,8 @@ export const ipcBackend: DocBackend = {
onPatched: (h) => onIdeEvent("docPatched", (e) => h(e)),
onDirty: (h) => onIdeEvent("docDirty", (e) => h(e)),
onFsChanged: (h) => onIdeEvent("fsChanged", (e) => h(e)),
onDiskConflict: (h) => onIdeEvent("docDiskConflict", (e) => h(e)),
reloadDiscarding: async (doc) => void (await call(commands.docReloadFromDisk(doc))),
onApplicationDeactivated: (h) => {
if (!isTauri()) return () => {};
const listener = getCurrentWebviewWindow().listen("ide://application-deactivated", () => h());
+35
Переглянути файл
@@ -466,6 +466,8 @@ export class EditorController implements SlotHost {
if (prevRoot) this.projectTransition = this.restoreSession(prevRoot);
if (this.manager.backend.onFsChanged)
this.disposers.push(this.manager.backend.onFsChanged((e) => this.onFilesRemoved(e.removed)));
if (this.manager.backend.onDiskConflict)
this.disposers.push(this.manager.backend.onDiskConflict((e) => this.onDiskConflict(e.path)));
const onWindowBlur = () => {
if (this.autoSave() && !this.closeSession) {
void this.manager.saveAll("auto");
@@ -1765,6 +1767,39 @@ export class EditorController implements SlotHost {
});
}
/** Reload from Disk: re-reads the open, unmodified documents of `paths`. */
/**
* A file changed on disk while its buffer had unsaved changes: the buffer keeps them (autosave
* leaves the file alone) until the user loads the disk version or saves over it.
*/
private onDiskConflict(path: string) {
const key = `disk-conflict:${path}`;
notifications().notify({
level: "warning",
key,
sticky: true,
title: tx`${basename(path)} changed on disk`,
body: tx(
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.",
),
actions: [
{
label: tx("Load Changes from Disk"),
run: () => {
const doc = this.manager.get(path)?.getMeta().doc;
if (doc === undefined || !this.manager.backend.reloadDiscarding) return;
this.manager.backend.reloadDiscarding(doc).catch((e: unknown) =>
notifications().notify({
level: "error",
title: tx("Cannot reload from disk"),
body: e instanceof Error ? e.message : String(e),
}),
);
},
},
{ label: tx("Keep Editor Changes"), run: () => {} },
],
});
}
async reloadFromDisk(paths: string[]) {
for (const path of paths) {
const model = this.manager.get(path);
+5 -1
Переглянути файл
@@ -2732,5 +2732,9 @@
"Presentation": "Presentation",
"Code Assistance": "Code Assistance",
"Managed version {version} in {location}": "Managed version {version} in {location}",
"Managed in {location}": "Managed in {location}"
"Managed in {location}": "Managed in {location}",
"{name} changed on disk": "{name} changed on disk",
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.": "The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.",
"Load Changes from Disk": "Load Changes from Disk",
"Keep Editor Changes": "Keep Editor Changes"
}
+5 -1
Переглянути файл
@@ -9098,5 +9098,9 @@
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。",
"github-username": "GitHub 用户名",
"Managed version {version} in {location}": "版本 {version} 由 {location} 管理",
"Managed in {location}": "由 {location} 管理"
"Managed in {location}": "由 {location} 管理",
"{name} changed on disk": "{name} 已在磁盘上更改",
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.": "该文件在 IDE 外被修改,而编辑器中还有未保存的更改。保存会保留编辑器中的版本并覆盖该文件。",
"Load Changes from Disk": "从磁盘加载更改",
"Keep Editor Changes": "保留编辑器中的更改"
}