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
10fn escape(value: &str) -> String {
11    value.replace('\\', "\\\\").replace('\t', "\\t").replace('\n', "\\n").replace('\r', "\\r").replace('=', "\\=")
12}
13
14fn unescape(value: &str) -> String {
15    let mut out = String::with_capacity(value.len());
16    let mut chars = value.chars();
17    while let Some(c) = chars.next() {
18        if c != '\\' {
19            out.push(c);
20            continue;
21        }
22        match chars.next() {
23            Some('t') => out.push('\t'),
24            Some('n') => out.push('\n'),
25            Some('r') => out.push('\r'),
26            Some('\\') => out.push('\\'),
27            Some('=') => out.push('='),
28            Some(other) => {
29                out.push('\\');
30                out.push(other);
31            }
32            None => out.push('\\'),
33        }
34    }
35    out
36}
37
38/// 按分隔符切分,但忽略被反斜杠转义的分隔符。`SettingsStore` 的 key/value
39/// 都会转义 `=`,不能再用 `split_once('=')` 直接切。
40fn split_unescaped_once(value: &str, separator: char) -> Option<(&str, &str)> {
41    let mut escaped = false;
42    for (index, ch) in value.char_indices() {
43        if escaped {
44            escaped = false;
45            continue;
46        }
47        if ch == '\\' {
48            escaped = true;
49            continue;
50        }
51        if ch == separator {
52            return Some((&value[..index], &value[index + ch.len_utf8()..]));
53        }
54    }
55    None
56}
57
58fn read_lines(path: &Path) -> std::io::Result<Vec<String>> {
59    match std::fs::read_to_string(path) {
60        Ok(text) => Ok(text.lines().map(str::to_string).collect()),
61        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
62        Err(err) => Err(err),
63    }
64}
65
66/// 键值设置。同名 key 后写覆盖前写;空值等于删除。
67#[derive(Debug, Clone, Default)]
68pub struct SettingsStore {
69    values: HashMap<String, String>,
70    dirty: bool,
71}
72
73impl SettingsStore {
74    pub fn get(&self, key: &str) -> Option<&str> {
75        self.values.get(key).map(String::as_str)
76    }
77
78    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
79        let key = key.into();
80        let value = value.into();
81        if value.is_empty() {
82            self.values.remove(&key);
83        } else {
84            self.values.insert(key, value);
85        }
86        self.dirty = true;
87    }
88
89    pub fn remove(&mut self, key: &str) {
90        if self.values.remove(key).is_some() {
91            self.dirty = true;
92        }
93    }
94
95    pub fn len(&self) -> usize {
96        self.values.len()
97    }
98
99    pub fn is_empty(&self) -> bool {
100        self.values.is_empty()
101    }
102
103    /// 供展示/调试读取当前键值;顺序未定义,调用方需要稳定顺序时自行排序。
104    pub fn entries(&self) -> impl Iterator<Item = (&str, &str)> {
105        self.values.iter().map(|(key, value)| (key.as_str(), value.as_str()))
106    }
107
108    pub fn is_dirty(&self) -> bool {
109        self.dirty
110    }
111
112    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
113        self.values.clear();
114        for line in read_lines(path)? {
115            if let Some((key, value)) = split_unescaped_once(&line, '=') {
116                self.values.insert(unescape(key), unescape(value));
117            }
118        }
119        self.dirty = false;
120        Ok(())
121    }
122
123    pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
124        if let Some(parent) = path.parent() {
125            std::fs::create_dir_all(parent)?;
126        }
127        let mut lines: Vec<_> = self.values.iter().collect();
128        lines.sort_by_key(|(key, _)| key.as_str());
129        let text: String =
130            lines.into_iter().map(|(key, value)| format!("{}={}\n", escape(key), escape(value))).collect();
131        std::fs::write(path, text)?;
132        self.dirty = false;
133        Ok(())
134    }
135}
136
137/// 最近文件列表;最新在最前,重复 push 会前移而不新增。
138#[derive(Debug, Clone)]
139pub struct RecentFiles {
140    paths: Vec<PathBuf>,
141    limit: usize,
142    dirty: bool,
143}
144
145impl RecentFiles {
146    pub fn new(limit: usize) -> Self {
147        Self { paths: Vec::new(), limit: limit.max(1), dirty: false }
148    }
149
150    pub fn push(&mut self, path: impl Into<PathBuf>) {
151        let path = path.into();
152        self.paths.retain(|existing| existing != &path);
153        self.paths.insert(0, path);
154        self.paths.truncate(self.limit);
155        self.dirty = true;
156    }
157
158    pub fn remove(&mut self, path: &Path) {
159        let before = self.paths.len();
160        self.paths.retain(|existing| existing != path);
161        self.dirty |= self.paths.len() != before;
162    }
163
164    pub fn clear(&mut self) {
165        if !self.paths.is_empty() {
166            self.dirty = true;
167        }
168        self.paths.clear();
169    }
170
171    pub fn iter(&self) -> impl Iterator<Item = &PathBuf> {
172        self.paths.iter()
173    }
174
175    pub fn len(&self) -> usize {
176        self.paths.len()
177    }
178
179    pub fn is_empty(&self) -> bool {
180        self.paths.is_empty()
181    }
182
183    pub fn is_dirty(&self) -> bool {
184        self.dirty
185    }
186
187    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
188        self.paths.clear();
189        for line in read_lines(path)? {
190            if !line.trim().is_empty() {
191                self.paths.push(PathBuf::from(unescape(&line)));
192            }
193        }
194        self.paths.truncate(self.limit);
195        self.dirty = false;
196        Ok(())
197    }
198
199    pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
200        if let Some(parent) = path.parent() {
201            std::fs::create_dir_all(parent)?;
202        }
203        let text: String = self.paths.iter().map(|p| format!("{}\n", escape(&p.to_string_lossy()))).collect();
204        std::fs::write(path, text)?;
205        self.dirty = false;
206        Ok(())
207    }
208}
209
210/// 应用级服务集合。目录由应用给出;框架只负责 load/save,不自动选择用户目录。
211#[derive(Debug, Clone)]
212pub struct AppServices {
213    pub dir: PathBuf,
214    pub settings: SettingsStore,
215    pub recent_files: RecentFiles,
216    pub crashes: CrashDiagnostics,
217}
218
219impl AppServices {
220    pub fn new(dir: impl Into<PathBuf>) -> Self {
221        Self {
222            dir: dir.into(),
223            settings: SettingsStore::default(),
224            recent_files: RecentFiles::new(32),
225            crashes: CrashDiagnostics::new(64),
226        }
227    }
228
229    pub fn settings_path(&self) -> PathBuf {
230        self.dir.join("settings.txt")
231    }
232
233    pub fn recent_files_path(&self) -> PathBuf {
234        self.dir.join("recent_files.txt")
235    }
236
237    pub fn crashes_path(&self) -> PathBuf {
238        self.dir.join("crashes.txt")
239    }
240
241    pub fn load(&mut self) -> std::io::Result<()> {
242        self.settings.load(&self.settings_path())?;
243        self.recent_files.load(&self.recent_files_path())?;
244        self.crashes.load(&self.crashes_path())?;
245        Ok(())
246    }
247
248    pub fn save(&mut self) -> std::io::Result<()> {
249        self.settings.save(&self.settings_path())?;
250        self.recent_files.save(&self.recent_files_path())?;
251        self.crashes.save(&self.crashes_path())?;
252        Ok(())
253    }
254}
255
256/// 一条崩溃/错误诊断记录。`scene` 由应用注入,`summary/detail` 来自 `ErrorReport`。
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct CrashRecord {
259    pub scene: String,
260    pub summary: String,
261    pub detail: String,
262}
263
264/// 有界崩溃日志。只记录 ErrorBoundary 已进入 `Dead` 的错误,不重复记录 Recovering。
265#[derive(Debug, Clone)]
266pub struct CrashDiagnostics {
267    records: VecDeque<CrashRecord>,
268    limit: usize,
269}
270
271impl CrashDiagnostics {
272    pub fn new(limit: usize) -> Self {
273        Self { records: VecDeque::new(), limit: limit.max(1) }
274    }
275
276    pub fn record(&mut self, scene: impl Into<String>, summary: impl Into<String>, detail: impl Into<String>) {
277        self.records.push_back(CrashRecord { scene: scene.into(), summary: summary.into(), detail: detail.into() });
278        while self.records.len() > self.limit {
279            self.records.pop_front();
280        }
281    }
282
283    pub fn records(&self) -> impl Iterator<Item = &CrashRecord> {
284        self.records.iter()
285    }
286
287    pub fn len(&self) -> usize {
288        self.records.len()
289    }
290
291    pub fn is_empty(&self) -> bool {
292        self.records.is_empty()
293    }
294
295    pub fn clear(&mut self) {
296        self.records.clear();
297    }
298
299    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
300        self.records.clear();
301        for line in read_lines(path)? {
302            let mut parts = line.split('\t');
303            if let (Some(scene), Some(summary), Some(detail)) = (parts.next(), parts.next(), parts.next()) {
304                self.record(unescape(scene), unescape(summary), unescape(detail));
305            }
306        }
307        Ok(())
308    }
309
310    pub fn save(&self, path: &Path) -> std::io::Result<()> {
311        if let Some(parent) = path.parent() {
312            std::fs::create_dir_all(parent)?;
313        }
314        let text: String = self
315            .records
316            .iter()
317            .map(|r| format!("{}\t{}\t{}\n", escape(&r.scene), escape(&r.summary), escape(&r.detail)))
318            .collect();
319        std::fs::write(path, text)
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn settings_round_trip_escapes_and_sorted_output() {
329        let mut store = SettingsStore::default();
330        store.set("theme", "dark");
331        store.set("note", "a\nb\\c\t=");
332        store.set("a=b", "value");
333        assert_eq!(store.get("theme"), Some("dark"));
334        let path = std::env::temp_dir().join(format!("mgui-settings-{}.txt", std::process::id()));
335        store.save(&path).unwrap();
336        let mut loaded = SettingsStore::default();
337        loaded.load(&path).unwrap();
338        assert_eq!(loaded.get("note"), Some("a\nb\\c\t="));
339        assert_eq!(loaded.get("a=b"), Some("value"));
340        let mut entries: Vec<_> = loaded.entries().collect();
341        entries.sort_by_key(|(key, _)| *key);
342        assert_eq!(entries, vec![("a=b", "value"), ("note", "a\nb\\c\t="), ("theme", "dark")]);
343        assert!(!loaded.is_dirty());
344        std::fs::remove_file(path).unwrap();
345    }
346
347    #[test]
348    fn recent_files_dedup_and_bound() {
349        let mut recent = RecentFiles::new(2);
350        recent.push("a.rs");
351        recent.push("b.rs");
352        recent.push("a.rs");
353        assert_eq!(recent.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>(), ["a.rs", "b.rs"]);
354        recent.push("c.rs");
355        assert_eq!(recent.len(), 2);
356        assert_eq!(recent.iter().next().unwrap().to_string_lossy(), "c.rs");
357    }
358
359    #[test]
360    fn app_services_bundle_round_trip() {
361        let dir = std::env::temp_dir().join(format!("mgui-app-services-{}", std::process::id()));
362        let mut services = AppServices::new(&dir);
363        services.settings.set("theme", "dark");
364        services.recent_files.push("a.rs");
365        services.crashes.record("scene", "summary", "detail");
366        services.save().unwrap();
367        let mut loaded = AppServices::new(&dir);
368        loaded.load().unwrap();
369        assert_eq!(loaded.settings.get("theme"), Some("dark"));
370        assert_eq!(loaded.recent_files.len(), 1);
371        assert_eq!(loaded.crashes.len(), 1);
372        std::fs::remove_dir_all(dir).unwrap();
373    }
374
375    #[test]
376    fn crash_diagnostics_are_bounded_and_round_trip() {
377        let mut log = CrashDiagnostics::new(2);
378        log.record("a", "one", "detail one");
379        log.record("b", "two", "detail\ttwo=2");
380        log.record("c", "three", "detail\tthree=3");
381        assert_eq!(log.len(), 2);
382        let path = std::env::temp_dir().join(format!("mgui-crash-{}.txt", std::process::id()));
383        log.save(&path).unwrap();
384        let mut loaded = CrashDiagnostics::new(2);
385        loaded.load(&path).unwrap();
386        assert_eq!(loaded.records().map(|r| r.scene.as_str()).collect::<Vec<_>>(), ["b", "c"]);
387        assert_eq!(loaded.records().nth(1).unwrap().detail, "detail\tthree=3");
388        std::fs::remove_file(path).unwrap();
389    }
390}