дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 06:12:33 +02:00
fix(editor): update the status bar when a file's encoding or line ending changes (#6882)
When another program rewrote a clean open file in a different encoding or line ending, Documents::reload_from_disk re-detected and stored the new values but nothing sent them to the editor's DocMeta, so the status bar kept the old encoding and line separator until the tab was reopened; Load Changes from Disk had the same gap for the BOM. Adds IdeEvent::DocEncoding (modelled on DocLanguage): both reload paths emit it through one helper only when the encoding, BOM or line ending changed, and the DocumentManager updates the meta. Co-authored-by: audichuang <[email protected]>
Цей коміт міститься в:
1 джерело
61dbb2f863
коміт
3d3ed6e120
9 files changed
+133
No files matched your search
@@ -174,6 +174,15 @@ pub enum IdeEvent {
|
||||
/// See `DocumentInfo::ui_mode`.
|
||||
ui_mode: Option<String>,
|
||||
},
|
||||
/// A reload from disk changed an open document's encoding, BOM or line ending (the file
|
||||
/// was rewritten by another program), which the editor only learns when it opens.
|
||||
DocEncoding {
|
||||
doc: DocId,
|
||||
encoding: String,
|
||||
has_bom: bool,
|
||||
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
|
||||
line_ending: String,
|
||||
},
|
||||
/// Full replacement of diagnostics for one file from one producer.
|
||||
Diagnostics {
|
||||
path: crate::IpcPath,
|
||||
|
||||
@@ -375,6 +375,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
|
||||
| IdeEvent::DocDiskConflict { .. }
|
||||
| IdeEvent::WorkspaceEditApplied { .. }
|
||||
| IdeEvent::DocLanguage { .. }
|
||||
| IdeEvent::DocEncoding { .. }
|
||||
| IdeEvent::Diagnostics { .. }
|
||||
| IdeEvent::Task { .. }
|
||||
| IdeEvent::IndexState { .. }
|
||||
|
||||
@@ -36,6 +36,15 @@ impl LineEnding {
|
||||
}
|
||||
}
|
||||
|
||||
/// The serialized form (`serde(rename_all = "camelCase")`) the frontend's `LineEnding` uses.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Lf => "lf",
|
||||
Self::CrLf => "crLf",
|
||||
Self::Cr => "cr",
|
||||
}
|
||||
}
|
||||
|
||||
/// The dominant line ending of `text`; ties and text without any line
|
||||
/// break resolve to [`LineEnding::Lf`].
|
||||
pub fn detect(text: &str) -> Self {
|
||||
|
||||
@@ -1406,6 +1406,24 @@ impl Documents {
|
||||
ids.into_iter().filter_map(|id| saved(id).ok().flatten()).collect()
|
||||
}
|
||||
|
||||
/// The encoding, BOM and line ending the editor shows for a document.
|
||||
fn encoding_state(st: &DocState) -> (String, bool, LineEnding) {
|
||||
(st.encoding.clone(), st.has_bom, st.doc.line_ending())
|
||||
}
|
||||
|
||||
/// The editor reads these at open; no reply carries a change made by a reload back, so
|
||||
/// tell it when `before` no longer holds.
|
||||
fn announce_encoding(&self, doc: DocId, st: &DocState, before: (String, bool, LineEnding)) {
|
||||
if before != Self::encoding_state(st) {
|
||||
self.sink.emit(IdeEvent::DocEncoding {
|
||||
doc,
|
||||
encoding: st.encoding.clone(),
|
||||
has_bom: st.has_bom,
|
||||
line_ending: st.doc.line_ending().name().to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
@@ -1413,12 +1431,14 @@ impl Documents {
|
||||
if st.uri.is_some() || st.binary {
|
||||
return Err(IdeError::invalid("only a file's text can be reloaded from disk"));
|
||||
}
|
||||
let before = Self::encoding_state(st);
|
||||
let loaded = Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?;
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.encoding_unsaved = false;
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
st.synced(loaded.mtime_ms);
|
||||
self.set_dirty(doc, st, false);
|
||||
self.announce_encoding(doc, st, before);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -1603,6 +1623,7 @@ impl Documents {
|
||||
self.disk_conflict(id, st, &meta);
|
||||
return Ok(());
|
||||
}
|
||||
let before = Self::encoding_state(st);
|
||||
st.encoding = loaded.encoding;
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.large = loaded.large;
|
||||
@@ -1610,6 +1631,7 @@ impl Documents {
|
||||
st.doc.set_line_ending(ec_eol.unwrap_or_else(|| LineEnding::detect(&loaded.text)));
|
||||
self.replace_locked(id, st, &loaded.text)?;
|
||||
st.synced(loaded.mtime_ms);
|
||||
self.announce_encoding(id, st, before);
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = result {
|
||||
|
||||
@@ -812,6 +812,58 @@ fn external_changes_redetect_an_encoding_the_user_never_chose() {
|
||||
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("wide", "utf-16le"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_reload_tells_the_editor_the_new_encoding_and_line_ending() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("plain.txt");
|
||||
fs::write(&path, "a\r\nb\r\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
fs::write(&path, ide_vfs::encode("a\nb\n", "utf-16le", true).unwrap()).unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let seen: Vec<_> = f
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::DocEncoding { doc, encoding, has_bom, line_ending } if *doc == info.id => {
|
||||
Some((encoding.clone(), *has_bom, line_ending.clone()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(seen, [("utf-16le".to_owned(), true, "lf".to_owned())]);
|
||||
|
||||
// A reload that changes none of them stays quiet.
|
||||
fs::write(&path, ide_vfs::encode("a\nb\nc\n", "utf-16le", true).unwrap()).unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "a\nb\nc\n");
|
||||
let count = f.events.lock().iter().filter(|e| matches!(e, IdeEvent::DocEncoding { .. })).count();
|
||||
assert_eq!(count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_changes_from_disk_tells_the_editor_a_new_bom() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("plain.txt");
|
||||
fs::write(&path, "text").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.replace_all(info.id, "edited").unwrap();
|
||||
fs::write(&path, b"\xEF\xBB\xBFtext").unwrap();
|
||||
f.docs.discard_and_reload(info.id).unwrap();
|
||||
let seen: Vec<_> = f
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::DocEncoding { doc, encoding, has_bom, .. } if *doc == info.id => {
|
||||
Some((encoding.clone(), *has_bom))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(seen, [("utf-8".to_owned(), true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_bom_is_added_and_removed_on_save() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -9465,6 +9465,13 @@ byAgent: boolean } |
|
||||
{ type: "docLanguage"; doc: DocId; language: LanguageId;
|
||||
/** See `DocumentInfo::ui_mode`. */
|
||||
uiMode: string | null } |
|
||||
/**
|
||||
* A reload from disk changed an open document's encoding, BOM or line ending (the file
|
||||
* was rewritten by another program), which the editor only learns when it opens.
|
||||
*/
|
||||
{ type: "docEncoding"; doc: DocId; encoding: string; hasBom: boolean;
|
||||
/** A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`. */
|
||||
lineEnding: string } |
|
||||
/** Full replacement of diagnostics for one file from one producer. */
|
||||
{ type: "diagnostics"; path: IpcPath; source: string; items: Diagnostic[] } |
|
||||
/** Progress of a background task; `fraction` is `None` when indeterminate. */
|
||||
|
||||
@@ -95,6 +95,10 @@ export interface DocBackend {
|
||||
* Type), or its own mode (`DocumentInfo.uiMode`).
|
||||
*/
|
||||
onLanguage?(handler: (e: { doc: DocId; language: string; uiMode: string | null }) => void): () => void;
|
||||
/** A reload from disk changed an open document's encoding, BOM or line ending. */
|
||||
onEncoding?(
|
||||
handler: (e: { doc: DocId; encoding: string; hasBom: boolean; lineEnding: LineEnding }) => void,
|
||||
): () => void;
|
||||
}
|
||||
|
||||
export const ipcBackend: DocBackend = {
|
||||
@@ -130,6 +134,7 @@ export const ipcBackend: DocBackend = {
|
||||
return () => void listener.then((unlisten) => unlisten());
|
||||
},
|
||||
onLanguage: (h) => onIdeEvent("docLanguage", (e) => h(e)),
|
||||
onEncoding: (h) => onIdeEvent("docEncoding", (e) => h({ ...e, lineEnding: e.lineEnding as LineEnding })),
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -624,6 +624,29 @@ describe("DocumentManager + slots", () => {
|
||||
expect(slot.currentState().facet(languageFacet)?.name).not.toBe("angular");
|
||||
});
|
||||
|
||||
it("follows the encoding and line ending a reload from disk changed", async () => {
|
||||
const { backend, manager } = setup({ "/p/a.txt": "abc" });
|
||||
let handler: Parameters<NonNullable<typeof backend.onEncoding>>[0] = () => {};
|
||||
backend.onEncoding = (h) => {
|
||||
handler = h;
|
||||
return () => {};
|
||||
};
|
||||
manager.stop();
|
||||
manager.start();
|
||||
const model = await manager.acquire("/p/a.txt");
|
||||
try {
|
||||
handler({ doc: model.doc, encoding: "utf-16le", hasBom: true, lineEnding: "crLf" });
|
||||
expect(useDocMeta.getState()["/p/a.txt"]).toMatchObject({
|
||||
encoding: "utf-16le",
|
||||
hasBom: true,
|
||||
lineEnding: "crLf",
|
||||
});
|
||||
} finally {
|
||||
manager.releaseProjectDocuments();
|
||||
manager.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["ts", "mts", "cts"])("loads Angular inline templates for .%s documents", async (ext) => {
|
||||
const path = `/p/src/app.${ext}`;
|
||||
const { manager } = setup({
|
||||
|
||||
@@ -914,6 +914,11 @@ export class DocumentManager {
|
||||
this.backend.onPatched((e) => this.modelsOf(e.doc).forEach((m) => m.sync.remote(e))),
|
||||
this.backend.onLanguage?.((e) => this.modelsOf(e.doc).forEach((m) => m.setLanguage(e.language, e.uiMode))) ??
|
||||
(() => {}),
|
||||
this.backend.onEncoding?.((e) =>
|
||||
this.modelsOf(e.doc).forEach((m) =>
|
||||
m.setMeta({ encoding: e.encoding, hasBom: e.hasBom, lineEnding: e.lineEnding }),
|
||||
),
|
||||
) ?? (() => {}),
|
||||
this.backend.onDirty((e) => this.modelsOf(e.doc).forEach((m) => m.onBackendDirty(e))),
|
||||
);
|
||||
let prev = useEditorRegistry.getState().contributions;
|
||||
|
||||
Reference in new issue
Заблокувати користувача