Skip to main content

mgui_core/
app_services.rs

1//! 应用级基础服务(0.7):设置、最近文件、崩溃诊断。
2//!
3//! 这些服务刻意不碰 Widget/Element/RO,也不引入 serde/平台 API:
4//! 用可审计的纯文本格式落盘,便于 Agent replay 与人工核对。时间由调用方注入,
5//! 框架不读墙钟,保证同一脚本两遍 trace 可逐字节比较。
6
7use std::collections::{HashMap, VecDeque};
8use std::path::{Path, PathBuf};
9
10use crate::persistence::{
11    self, read_with_recovery, write_with_backup, AcquireError, FileOutcome, OwnerLease, SchemaState,
12};
13
14fn escape(value: &str) -> String {
15    value.replace('\\', "\\\\").replace('\t', "\\t").replace('\n', "\\n").replace('\r', "\\r").replace('=', "\\=")
16}
17
18fn unescape(value: &str) -> String {
19    let mut out = String::with_capacity(value.len());
20    let mut chars = value.chars();
21    while let Some(c) = chars.next() {
22        if c != '\\' {
23            out.push(c);
24            continue;
25        }
26        match chars.next() {
27            Some('t') => out.push('\t'),
28            Some('n') => out.push('\n'),
29            Some('r') => out.push('\r'),
30            Some('\\') => out.push('\\'),
31            Some('=') => out.push('='),
32            Some(other) => {
33                out.push('\\');
34                out.push(other);
35            }
36            None => out.push('\\'),
37        }
38    }
39    out
40}
41
42/// 按分隔符切分,但忽略被反斜杠转义的分隔符。`SettingsStore` 的 key/value
43/// 都会转义 `=`,不能再用 `split_once('=')` 直接切。
44fn split_unescaped_once(value: &str, separator: char) -> Option<(&str, &str)> {
45    let mut escaped = false;
46    for (index, ch) in value.char_indices() {
47        if escaped {
48            escaped = false;
49            continue;
50        }
51        if ch == '\\' {
52            escaped = true;
53            continue;
54        }
55        if ch == separator {
56            return Some((&value[..index], &value[index + ch.len_utf8()..]));
57        }
58    }
59    None
60}
61
62/// 键值设置。同名 key 后写覆盖前写;空值等于删除。
63#[derive(Debug, Clone, Default)]
64pub struct SettingsStore {
65    values: HashMap<String, String>,
66    dirty: bool,
67}
68
69impl SettingsStore {
70    pub fn get(&self, key: &str) -> Option<&str> {
71        self.values.get(key).map(String::as_str)
72    }
73
74    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
75        let key = key.into();
76        let value = value.into();
77        if value.is_empty() {
78            self.values.remove(&key);
79        } else {
80            self.values.insert(key, value);
81        }
82        self.dirty = true;
83    }
84
85    pub fn remove(&mut self, key: &str) {
86        if self.values.remove(key).is_some() {
87            self.dirty = true;
88        }
89    }
90
91    pub fn len(&self) -> usize {
92        self.values.len()
93    }
94
95    pub fn is_empty(&self) -> bool {
96        self.values.is_empty()
97    }
98
99    /// 供展示/调试读取当前键值;顺序未定义,调用方需要稳定顺序时自行排序。
100    pub fn entries(&self) -> impl Iterator<Item = (&str, &str)> {
101        self.values.iter().map(|(key, value)| (key.as_str(), value.as_str()))
102    }
103
104    pub fn is_dirty(&self) -> bool {
105        self.dirty
106    }
107
108    /// 从纯文本解析(0.7 格式),供鲁棒加载与直接注入两种路径共用。
109    pub fn load_from_text(&mut self, text: &str) {
110        self.values.clear();
111        for line in text.lines() {
112            if let Some((key, value)) = split_unescaped_once(line, '=') {
113                self.values.insert(unescape(key), unescape(value));
114            }
115        }
116        self.dirty = false;
117    }
118
119    /// 保持 0.7 签名:内部走「校验 → 备份回退 → 原子替换」鲁棒层。
120    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
121        let (text, _) = read_with_recovery(path)?;
122        self.load_from_text(&text);
123        Ok(())
124    }
125
126    /// 序列化为 0.7 纯文本格式。
127    pub fn to_text(&self) -> String {
128        let mut lines: Vec<_> = self.values.iter().collect();
129        lines.sort_by_key(|(key, _)| key.as_str());
130        lines.into_iter().map(|(key, value)| format!("{}={}\n", escape(key), escape(value))).collect()
131    }
132
133    /// 保持 0.7 签名:内部走备份 + 原子写。
134    pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
135        write_with_backup(path, self.to_text().as_bytes())?;
136        self.dirty = false;
137        Ok(())
138    }
139}
140
141/// 最近文件列表;最新在最前,重复 push 会前移而不新增。
142#[derive(Debug, Clone)]
143pub struct RecentFiles {
144    paths: Vec<PathBuf>,
145    limit: usize,
146    dirty: bool,
147}
148
149impl RecentFiles {
150    pub fn new(limit: usize) -> Self {
151        Self { paths: Vec::new(), limit: limit.max(1), dirty: false }
152    }
153
154    pub fn push(&mut self, path: impl Into<PathBuf>) {
155        let path = path.into();
156        self.paths.retain(|existing| existing != &path);
157        self.paths.insert(0, path);
158        self.paths.truncate(self.limit);
159        self.dirty = true;
160    }
161
162    pub fn remove(&mut self, path: &Path) {
163        let before = self.paths.len();
164        self.paths.retain(|existing| existing != path);
165        self.dirty |= self.paths.len() != before;
166    }
167
168    pub fn clear(&mut self) {
169        if !self.paths.is_empty() {
170            self.dirty = true;
171        }
172        self.paths.clear();
173    }
174
175    pub fn iter(&self) -> impl Iterator<Item = &PathBuf> {
176        self.paths.iter()
177    }
178
179    pub fn len(&self) -> usize {
180        self.paths.len()
181    }
182
183    pub fn is_empty(&self) -> bool {
184        self.paths.is_empty()
185    }
186
187    pub fn is_dirty(&self) -> bool {
188        self.dirty
189    }
190
191    pub fn load_from_text(&mut self, text: &str) {
192        self.paths.clear();
193        for line in text.lines() {
194            if !line.trim().is_empty() {
195                self.paths.push(PathBuf::from(unescape(line)));
196            }
197        }
198        self.paths.truncate(self.limit);
199        self.dirty = false;
200    }
201
202    /// 保持 0.7 签名:内部走鲁棒加载层。
203    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
204        let (text, _) = read_with_recovery(path)?;
205        self.load_from_text(&text);
206        Ok(())
207    }
208
209    pub fn to_text(&self) -> String {
210        self.paths.iter().map(|p| format!("{}\n", escape(&p.to_string_lossy()))).collect()
211    }
212
213    /// 保持 0.7 签名:内部走备份 + 原子写。
214    pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
215        write_with_backup(path, self.to_text().as_bytes())?;
216        self.dirty = false;
217        Ok(())
218    }
219}
220
221/// 三个持久化文件的确定性加载结果。
222#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
223pub struct LoadReport {
224    pub settings: FileOutcome,
225    pub recent_files: FileOutcome,
226    pub crashes: FileOutcome,
227}
228
229/// 应用级服务集合。目录由应用给出;框架只负责 load/save,不自动选择用户目录。
230#[derive(Debug, Clone)]
231pub struct AppServices {
232    pub dir: PathBuf,
233    pub settings: SettingsStore,
234    pub recent_files: RecentFiles,
235    pub crashes: CrashDiagnostics,
236}
237
238impl AppServices {
239    pub fn new(dir: impl Into<PathBuf>) -> Self {
240        Self {
241            dir: dir.into(),
242            settings: SettingsStore::default(),
243            recent_files: RecentFiles::new(32),
244            crashes: CrashDiagnostics::new(64),
245        }
246    }
247
248    pub fn settings_path(&self) -> PathBuf {
249        self.dir.join("settings.txt")
250    }
251
252    pub fn recent_files_path(&self) -> PathBuf {
253        self.dir.join("recent_files.txt")
254    }
255
256    pub fn crashes_path(&self) -> PathBuf {
257        self.dir.join("crashes.txt")
258    }
259
260    /// 保持 0.7 签名的加载入口。
261    pub fn load(&mut self) -> std::io::Result<()> {
262        let _ = self.load_with_report()?;
263        Ok(())
264    }
265
266    /// 0.8 入口:加载并返回每个文件的确定性结果(含损坏回退标记)。
267    /// IO 不可用时该字段记为 `IoUnavailable`,不误报为损坏。
268    pub fn load_with_report(&mut self) -> std::io::Result<LoadReport> {
269        let load = |path: PathBuf, outcome: &mut FileOutcome| -> Option<String> {
270            match read_with_recovery(&path) {
271                Ok((text, result)) => {
272                    *outcome = result;
273                    Some(text)
274                }
275                Err(_) => {
276                    *outcome = FileOutcome::IoUnavailable;
277                    None
278                }
279            }
280        };
281        let mut report = LoadReport::default();
282        if let Some(text) = load(self.settings_path(), &mut report.settings) {
283            self.settings.load_from_text(&text);
284        }
285        if let Some(text) = load(self.recent_files_path(), &mut report.recent_files) {
286            self.recent_files.load_from_text(&text);
287        }
288        if let Some(text) = load(self.crashes_path(), &mut report.crashes) {
289            self.crashes.load_from_text(&text);
290        }
291        Ok(report)
292    }
293
294    /// 保持 0.7 签名的保存入口:写纯文本 + schema sidecar,不强制 owner。
295    /// 多窗口场景应改用 `save_with_owner` 以避免并发覆盖。
296    pub fn save(&mut self) -> std::io::Result<()> {
297        self.save_text()?;
298        persistence::write_schema(&self.dir)
299    }
300
301    /// 0.8 入口:写入前校验 owner 租约仍有效,防止丢租约后的旧窗口覆盖新数据。
302    pub fn save_with_owner(&mut self, owner: &OwnerLease) -> std::io::Result<()> {
303        if !owner.is_current() {
304            return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "owner lease is no longer current"));
305        }
306        self.save()
307    }
308
309    fn save_text(&mut self) -> std::io::Result<()> {
310        self.settings.save(&self.settings_path())?;
311        self.recent_files.save(&self.recent_files_path())?;
312        self.crashes.save(&self.crashes_path())?;
313        Ok(())
314    }
315
316    pub fn schema_state(&self) -> SchemaState {
317        persistence::read_schema(&self.dir)
318    }
319
320    pub fn try_acquire_owner(&self) -> Result<OwnerLease, AcquireError> {
321        persistence::try_acquire_owner(&self.dir)
322    }
323
324    /// 损坏文件恢复后回写主文件,让下一轮读取不再走备份路径。
325    pub fn heal_after_recovery(&mut self, report: &LoadReport) -> std::io::Result<()> {
326        if report.settings == FileOutcome::RecoveredFromBackup {
327            write_with_backup(&self.settings_path(), self.settings.to_text().as_bytes())?;
328        }
329        if report.recent_files == FileOutcome::RecoveredFromBackup {
330            write_with_backup(&self.recent_files_path(), self.recent_files.to_text().as_bytes())?;
331        }
332        if report.crashes == FileOutcome::RecoveredFromBackup {
333            write_with_backup(&self.crashes_path(), self.crashes.to_text().as_bytes())?;
334        }
335        Ok(())
336    }
337}
338
339/// 一条崩溃/错误诊断记录。`scene` 由应用注入,`summary/detail` 来自 `ErrorReport`。
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct CrashRecord {
342    pub scene: String,
343    pub summary: String,
344    pub detail: String,
345}
346
347/// 有界崩溃日志。只记录 ErrorBoundary 已进入 `Dead` 的错误,不重复记录 Recovering。
348#[derive(Debug, Clone)]
349pub struct CrashDiagnostics {
350    records: VecDeque<CrashRecord>,
351    limit: usize,
352}
353
354impl CrashDiagnostics {
355    pub fn new(limit: usize) -> Self {
356        Self { records: VecDeque::new(), limit: limit.max(1) }
357    }
358
359    pub fn record(&mut self, scene: impl Into<String>, summary: impl Into<String>, detail: impl Into<String>) {
360        self.records.push_back(CrashRecord { scene: scene.into(), summary: summary.into(), detail: detail.into() });
361        while self.records.len() > self.limit {
362            self.records.pop_front();
363        }
364    }
365
366    pub fn records(&self) -> impl Iterator<Item = &CrashRecord> {
367        self.records.iter()
368    }
369
370    pub fn len(&self) -> usize {
371        self.records.len()
372    }
373
374    pub fn is_empty(&self) -> bool {
375        self.records.is_empty()
376    }
377
378    pub fn clear(&mut self) {
379        self.records.clear();
380    }
381
382    pub fn load_from_text(&mut self, text: &str) {
383        self.records.clear();
384        for line in text.lines() {
385            let mut parts = line.split('\t');
386            if let (Some(scene), Some(summary), Some(detail)) = (parts.next(), parts.next(), parts.next()) {
387                self.record(unescape(scene), unescape(summary), unescape(detail));
388            }
389        }
390    }
391
392    /// 保持 0.7 签名:内部走鲁棒加载层。
393    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
394        let (text, _) = read_with_recovery(path)?;
395        self.load_from_text(&text);
396        Ok(())
397    }
398
399    pub fn to_text(&self) -> String {
400        self.records
401            .iter()
402            .map(|r| format!("{}\t{}\t{}\n", escape(&r.scene), escape(&r.summary), escape(&r.detail)))
403            .collect()
404    }
405
406    /// 保持 0.7 签名:内部走备份 + 原子写。
407    pub fn save(&self, path: &Path) -> std::io::Result<()> {
408        write_with_backup(path, self.to_text().as_bytes())
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn settings_round_trip_escapes_and_sorted_output() {
418        let mut store = SettingsStore::default();
419        store.set("theme", "dark");
420        store.set("note", "a\nb\\c\t=");
421        store.set("a=b", "value");
422        assert_eq!(store.get("theme"), Some("dark"));
423        let path = std::env::temp_dir().join(format!("mgui-settings-{}.txt", std::process::id()));
424        store.save(&path).unwrap();
425        let mut loaded = SettingsStore::default();
426        loaded.load(&path).unwrap();
427        assert_eq!(loaded.get("note"), Some("a\nb\\c\t="));
428        assert_eq!(loaded.get("a=b"), Some("value"));
429        let mut entries: Vec<_> = loaded.entries().collect();
430        entries.sort_by_key(|(key, _)| *key);
431        assert_eq!(entries, vec![("a=b", "value"), ("note", "a\nb\\c\t="), ("theme", "dark")]);
432        assert!(!loaded.is_dirty());
433        std::fs::remove_file(path).unwrap();
434    }
435
436    #[test]
437    fn recent_files_dedup_and_bound() {
438        let mut recent = RecentFiles::new(2);
439        recent.push("a.rs");
440        recent.push("b.rs");
441        recent.push("a.rs");
442        assert_eq!(recent.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>(), ["a.rs", "b.rs"]);
443        recent.push("c.rs");
444        assert_eq!(recent.len(), 2);
445        assert_eq!(recent.iter().next().unwrap().to_string_lossy(), "c.rs");
446    }
447
448    #[test]
449    fn app_services_bundle_round_trip() {
450        let dir = std::env::temp_dir().join(format!("mgui-app-services-{}", std::process::id()));
451        let mut services = AppServices::new(&dir);
452        services.settings.set("theme", "dark");
453        services.recent_files.push("a.rs");
454        services.crashes.record("scene", "summary", "detail");
455        services.save().unwrap();
456        let mut loaded = AppServices::new(&dir);
457        loaded.load().unwrap();
458        assert_eq!(loaded.settings.get("theme"), Some("dark"));
459        assert_eq!(loaded.recent_files.len(), 1);
460        assert_eq!(loaded.crashes.len(), 1);
461        std::fs::remove_dir_all(dir).unwrap();
462    }
463
464    #[test]
465    fn schema_marker_written_after_save() {
466        let dir = std::env::temp_dir().join(format!("mgui-schema-app-{}", std::process::id()));
467        let _ = std::fs::remove_dir_all(&dir);
468        let mut services = AppServices::new(&dir);
469        assert_eq!(services.schema_state(), SchemaState::Legacy);
470        services.save().unwrap();
471        assert_eq!(services.schema_state(), SchemaState::Current);
472        std::fs::remove_dir_all(dir).unwrap();
473    }
474
475    #[test]
476    fn corrupted_settings_recover_from_backup_and_heal() {
477        let dir = std::env::temp_dir().join(format!("mgui-recover-app-{}", std::process::id()));
478        let _ = std::fs::remove_dir_all(&dir);
479        let mut services = AppServices::new(&dir);
480        services.settings.set("theme", "dark");
481        services.save().unwrap();
482        // 第二次保存产生含 theme=dark 的备份,再写一份新值作为主文件。
483        services.settings.set("theme", "light");
484        services.save().unwrap();
485        // 模拟半写主文件:校验和不再匹配。
486        std::fs::write(services.settings_path(), "theme=corrupt").unwrap();
487
488        let mut loaded = AppServices::new(&dir);
489        let report = loaded.load_with_report().unwrap();
490        assert_eq!(report.settings, FileOutcome::RecoveredFromBackup);
491        assert_eq!(loaded.settings.get("theme"), Some("dark"));
492        loaded.heal_after_recovery(&report).unwrap();
493        let mut again = AppServices::new(&dir);
494        assert_eq!(again.load_with_report().unwrap().settings, FileOutcome::Loaded);
495        assert_eq!(again.settings.get("theme"), Some("dark"));
496        std::fs::remove_dir_all(dir).unwrap();
497    }
498
499    #[test]
500    fn owner_contest_blocks_second_window_and_stale_lease() {
501        let dir = std::env::temp_dir().join(format!("mgui-owner-app-{}", std::process::id()));
502        let _ = std::fs::remove_dir_all(&dir);
503        let services = AppServices::new(&dir);
504        let owner = services.try_acquire_owner().unwrap();
505        assert!(matches!(services.try_acquire_owner(), Err(AcquireError::Contested)));
506
507        let mut writer = AppServices::new(&dir);
508        writer.settings.set("theme", "dark");
509        writer.save_with_owner(&owner).unwrap();
510        assert_eq!(writer.schema_state(), SchemaState::Current);
511
512        // 主动释放后旧租约失效,再保存必须被拒绝。
513        let mut owner = owner;
514        owner.release().unwrap();
515        assert_eq!(writer.save_with_owner(&owner).unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
516        std::fs::remove_dir_all(dir).unwrap();
517    }
518
519    #[test]
520    fn legacy_files_without_checksum_still_load() {
521        let dir = std::env::temp_dir().join(format!("mgui-legacy-app-{}", std::process::id()));
522        let _ = std::fs::remove_dir_all(&dir);
523        std::fs::create_dir_all(&dir).unwrap();
524        std::fs::write(dir.join("settings.txt"), "theme=dark\n").unwrap();
525        let mut services = AppServices::new(&dir);
526        let report = services.load_with_report().unwrap();
527        assert_eq!(report.settings, FileOutcome::LegacyLoaded);
528        assert_eq!(services.settings.get("theme"), Some("dark"));
529        std::fs::remove_dir_all(dir).unwrap();
530    }
531
532    #[test]
533    fn crash_diagnostics_are_bounded_and_round_trip() {
534        let mut log = CrashDiagnostics::new(2);
535        log.record("a", "one", "detail one");
536        log.record("b", "two", "detail\ttwo=2");
537        log.record("c", "three", "detail\tthree=3");
538        assert_eq!(log.len(), 2);
539        let path = std::env::temp_dir().join(format!("mgui-crash-{}.txt", std::process::id()));
540        log.save(&path).unwrap();
541        let mut loaded = CrashDiagnostics::new(2);
542        loaded.load(&path).unwrap();
543        assert_eq!(loaded.records().map(|r| r.scene.as_str()).collect::<Vec<_>>(), ["b", "c"]);
544        assert_eq!(loaded.records().nth(1).unwrap().detail, "detail\tthree=3");
545        std::fs::remove_file(path).unwrap();
546    }
547}