mgui-core 0.8.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! 应用级基础服务(0.7):设置、最近文件、崩溃诊断。
//!
//! 这些服务刻意不碰 Widget/Element/RO,也不引入 serde/平台 API:
//! 用可审计的纯文本格式落盘,便于 Agent replay 与人工核对。时间由调用方注入,
//! 框架不读墙钟,保证同一脚本两遍 trace 可逐字节比较。

use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};

use crate::persistence::{
    self, read_with_recovery, write_with_backup, AcquireError, FileOutcome, OwnerLease, SchemaState,
};

fn escape(value: &str) -> String {
    value.replace('\\', "\\\\").replace('\t', "\\t").replace('\n', "\\n").replace('\r', "\\r").replace('=', "\\=")
}

fn unescape(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    let mut chars = value.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('t') => out.push('\t'),
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some('\\') => out.push('\\'),
            Some('=') => out.push('='),
            Some(other) => {
                out.push('\\');
                out.push(other);
            }
            None => out.push('\\'),
        }
    }
    out
}

/// 按分隔符切分,但忽略被反斜杠转义的分隔符。`SettingsStore` 的 key/value
/// 都会转义 `=`,不能再用 `split_once('=')` 直接切。
fn split_unescaped_once(value: &str, separator: char) -> Option<(&str, &str)> {
    let mut escaped = false;
    for (index, ch) in value.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if ch == '\\' {
            escaped = true;
            continue;
        }
        if ch == separator {
            return Some((&value[..index], &value[index + ch.len_utf8()..]));
        }
    }
    None
}

/// 键值设置。同名 key 后写覆盖前写;空值等于删除。
#[derive(Debug, Clone, Default)]
pub struct SettingsStore {
    values: HashMap<String, String>,
    dirty: bool,
}

impl SettingsStore {
    pub fn get(&self, key: &str) -> Option<&str> {
        self.values.get(key).map(String::as_str)
    }

    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
        let key = key.into();
        let value = value.into();
        if value.is_empty() {
            self.values.remove(&key);
        } else {
            self.values.insert(key, value);
        }
        self.dirty = true;
    }

    pub fn remove(&mut self, key: &str) {
        if self.values.remove(key).is_some() {
            self.dirty = true;
        }
    }

    pub fn len(&self) -> usize {
        self.values.len()
    }

    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// 供展示/调试读取当前键值;顺序未定义,调用方需要稳定顺序时自行排序。
    pub fn entries(&self) -> impl Iterator<Item = (&str, &str)> {
        self.values.iter().map(|(key, value)| (key.as_str(), value.as_str()))
    }

    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// 从纯文本解析(0.7 格式),供鲁棒加载与直接注入两种路径共用。
    pub fn load_from_text(&mut self, text: &str) {
        self.values.clear();
        for line in text.lines() {
            if let Some((key, value)) = split_unescaped_once(line, '=') {
                self.values.insert(unescape(key), unescape(value));
            }
        }
        self.dirty = false;
    }

    /// 保持 0.7 签名:内部走「校验 → 备份回退 → 原子替换」鲁棒层。
    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
        let (text, _) = read_with_recovery(path)?;
        self.load_from_text(&text);
        Ok(())
    }

    /// 序列化为 0.7 纯文本格式。
    pub fn to_text(&self) -> String {
        let mut lines: Vec<_> = self.values.iter().collect();
        lines.sort_by_key(|(key, _)| key.as_str());
        lines.into_iter().map(|(key, value)| format!("{}={}\n", escape(key), escape(value))).collect()
    }

    /// 保持 0.7 签名:内部走备份 + 原子写。
    pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
        write_with_backup(path, self.to_text().as_bytes())?;
        self.dirty = false;
        Ok(())
    }
}

/// 最近文件列表;最新在最前,重复 push 会前移而不新增。
#[derive(Debug, Clone)]
pub struct RecentFiles {
    paths: Vec<PathBuf>,
    limit: usize,
    dirty: bool,
}

impl RecentFiles {
    pub fn new(limit: usize) -> Self {
        Self { paths: Vec::new(), limit: limit.max(1), dirty: false }
    }

    pub fn push(&mut self, path: impl Into<PathBuf>) {
        let path = path.into();
        self.paths.retain(|existing| existing != &path);
        self.paths.insert(0, path);
        self.paths.truncate(self.limit);
        self.dirty = true;
    }

    pub fn remove(&mut self, path: &Path) {
        let before = self.paths.len();
        self.paths.retain(|existing| existing != path);
        self.dirty |= self.paths.len() != before;
    }

    pub fn clear(&mut self) {
        if !self.paths.is_empty() {
            self.dirty = true;
        }
        self.paths.clear();
    }

    pub fn iter(&self) -> impl Iterator<Item = &PathBuf> {
        self.paths.iter()
    }

    pub fn len(&self) -> usize {
        self.paths.len()
    }

    pub fn is_empty(&self) -> bool {
        self.paths.is_empty()
    }

    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    pub fn load_from_text(&mut self, text: &str) {
        self.paths.clear();
        for line in text.lines() {
            if !line.trim().is_empty() {
                self.paths.push(PathBuf::from(unescape(line)));
            }
        }
        self.paths.truncate(self.limit);
        self.dirty = false;
    }

    /// 保持 0.7 签名:内部走鲁棒加载层。
    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
        let (text, _) = read_with_recovery(path)?;
        self.load_from_text(&text);
        Ok(())
    }

    pub fn to_text(&self) -> String {
        self.paths.iter().map(|p| format!("{}\n", escape(&p.to_string_lossy()))).collect()
    }

    /// 保持 0.7 签名:内部走备份 + 原子写。
    pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
        write_with_backup(path, self.to_text().as_bytes())?;
        self.dirty = false;
        Ok(())
    }
}

/// 三个持久化文件的确定性加载结果。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LoadReport {
    pub settings: FileOutcome,
    pub recent_files: FileOutcome,
    pub crashes: FileOutcome,
}

/// 应用级服务集合。目录由应用给出;框架只负责 load/save,不自动选择用户目录。
#[derive(Debug, Clone)]
pub struct AppServices {
    pub dir: PathBuf,
    pub settings: SettingsStore,
    pub recent_files: RecentFiles,
    pub crashes: CrashDiagnostics,
}

impl AppServices {
    pub fn new(dir: impl Into<PathBuf>) -> Self {
        Self {
            dir: dir.into(),
            settings: SettingsStore::default(),
            recent_files: RecentFiles::new(32),
            crashes: CrashDiagnostics::new(64),
        }
    }

    pub fn settings_path(&self) -> PathBuf {
        self.dir.join("settings.txt")
    }

    pub fn recent_files_path(&self) -> PathBuf {
        self.dir.join("recent_files.txt")
    }

    pub fn crashes_path(&self) -> PathBuf {
        self.dir.join("crashes.txt")
    }

    /// 保持 0.7 签名的加载入口。
    pub fn load(&mut self) -> std::io::Result<()> {
        let _ = self.load_with_report()?;
        Ok(())
    }

    /// 0.8 入口:加载并返回每个文件的确定性结果(含损坏回退标记)。
    /// IO 不可用时该字段记为 `IoUnavailable`,不误报为损坏。
    pub fn load_with_report(&mut self) -> std::io::Result<LoadReport> {
        let load = |path: PathBuf, outcome: &mut FileOutcome| -> Option<String> {
            match read_with_recovery(&path) {
                Ok((text, result)) => {
                    *outcome = result;
                    Some(text)
                }
                Err(_) => {
                    *outcome = FileOutcome::IoUnavailable;
                    None
                }
            }
        };
        let mut report = LoadReport::default();
        if let Some(text) = load(self.settings_path(), &mut report.settings) {
            self.settings.load_from_text(&text);
        }
        if let Some(text) = load(self.recent_files_path(), &mut report.recent_files) {
            self.recent_files.load_from_text(&text);
        }
        if let Some(text) = load(self.crashes_path(), &mut report.crashes) {
            self.crashes.load_from_text(&text);
        }
        Ok(report)
    }

    /// 保持 0.7 签名的保存入口:写纯文本 + schema sidecar,不强制 owner。
    /// 多窗口场景应改用 `save_with_owner` 以避免并发覆盖。
    pub fn save(&mut self) -> std::io::Result<()> {
        self.save_text()?;
        persistence::write_schema(&self.dir)
    }

    /// 0.8 入口:写入前校验 owner 租约仍有效,防止丢租约后的旧窗口覆盖新数据。
    pub fn save_with_owner(&mut self, owner: &OwnerLease) -> std::io::Result<()> {
        if !owner.is_current() {
            return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "owner lease is no longer current"));
        }
        self.save()
    }

    fn save_text(&mut self) -> std::io::Result<()> {
        self.settings.save(&self.settings_path())?;
        self.recent_files.save(&self.recent_files_path())?;
        self.crashes.save(&self.crashes_path())?;
        Ok(())
    }

    pub fn schema_state(&self) -> SchemaState {
        persistence::read_schema(&self.dir)
    }

    pub fn try_acquire_owner(&self) -> Result<OwnerLease, AcquireError> {
        persistence::try_acquire_owner(&self.dir)
    }

    /// 损坏文件恢复后回写主文件,让下一轮读取不再走备份路径。
    pub fn heal_after_recovery(&mut self, report: &LoadReport) -> std::io::Result<()> {
        if report.settings == FileOutcome::RecoveredFromBackup {
            write_with_backup(&self.settings_path(), self.settings.to_text().as_bytes())?;
        }
        if report.recent_files == FileOutcome::RecoveredFromBackup {
            write_with_backup(&self.recent_files_path(), self.recent_files.to_text().as_bytes())?;
        }
        if report.crashes == FileOutcome::RecoveredFromBackup {
            write_with_backup(&self.crashes_path(), self.crashes.to_text().as_bytes())?;
        }
        Ok(())
    }
}

/// 一条崩溃/错误诊断记录。`scene` 由应用注入,`summary/detail` 来自 `ErrorReport`。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CrashRecord {
    pub scene: String,
    pub summary: String,
    pub detail: String,
}

/// 有界崩溃日志。只记录 ErrorBoundary 已进入 `Dead` 的错误,不重复记录 Recovering。
#[derive(Debug, Clone)]
pub struct CrashDiagnostics {
    records: VecDeque<CrashRecord>,
    limit: usize,
}

impl CrashDiagnostics {
    pub fn new(limit: usize) -> Self {
        Self { records: VecDeque::new(), limit: limit.max(1) }
    }

    pub fn record(&mut self, scene: impl Into<String>, summary: impl Into<String>, detail: impl Into<String>) {
        self.records.push_back(CrashRecord { scene: scene.into(), summary: summary.into(), detail: detail.into() });
        while self.records.len() > self.limit {
            self.records.pop_front();
        }
    }

    pub fn records(&self) -> impl Iterator<Item = &CrashRecord> {
        self.records.iter()
    }

    pub fn len(&self) -> usize {
        self.records.len()
    }

    pub fn is_empty(&self) -> bool {
        self.records.is_empty()
    }

    pub fn clear(&mut self) {
        self.records.clear();
    }

    pub fn load_from_text(&mut self, text: &str) {
        self.records.clear();
        for line in text.lines() {
            let mut parts = line.split('\t');
            if let (Some(scene), Some(summary), Some(detail)) = (parts.next(), parts.next(), parts.next()) {
                self.record(unescape(scene), unescape(summary), unescape(detail));
            }
        }
    }

    /// 保持 0.7 签名:内部走鲁棒加载层。
    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
        let (text, _) = read_with_recovery(path)?;
        self.load_from_text(&text);
        Ok(())
    }

    pub fn to_text(&self) -> String {
        self.records
            .iter()
            .map(|r| format!("{}\t{}\t{}\n", escape(&r.scene), escape(&r.summary), escape(&r.detail)))
            .collect()
    }

    /// 保持 0.7 签名:内部走备份 + 原子写。
    pub fn save(&self, path: &Path) -> std::io::Result<()> {
        write_with_backup(path, self.to_text().as_bytes())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn settings_round_trip_escapes_and_sorted_output() {
        let mut store = SettingsStore::default();
        store.set("theme", "dark");
        store.set("note", "a\nb\\c\t=");
        store.set("a=b", "value");
        assert_eq!(store.get("theme"), Some("dark"));
        let path = std::env::temp_dir().join(format!("mgui-settings-{}.txt", std::process::id()));
        store.save(&path).unwrap();
        let mut loaded = SettingsStore::default();
        loaded.load(&path).unwrap();
        assert_eq!(loaded.get("note"), Some("a\nb\\c\t="));
        assert_eq!(loaded.get("a=b"), Some("value"));
        let mut entries: Vec<_> = loaded.entries().collect();
        entries.sort_by_key(|(key, _)| *key);
        assert_eq!(entries, vec![("a=b", "value"), ("note", "a\nb\\c\t="), ("theme", "dark")]);
        assert!(!loaded.is_dirty());
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn recent_files_dedup_and_bound() {
        let mut recent = RecentFiles::new(2);
        recent.push("a.rs");
        recent.push("b.rs");
        recent.push("a.rs");
        assert_eq!(recent.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>(), ["a.rs", "b.rs"]);
        recent.push("c.rs");
        assert_eq!(recent.len(), 2);
        assert_eq!(recent.iter().next().unwrap().to_string_lossy(), "c.rs");
    }

    #[test]
    fn app_services_bundle_round_trip() {
        let dir = std::env::temp_dir().join(format!("mgui-app-services-{}", std::process::id()));
        let mut services = AppServices::new(&dir);
        services.settings.set("theme", "dark");
        services.recent_files.push("a.rs");
        services.crashes.record("scene", "summary", "detail");
        services.save().unwrap();
        let mut loaded = AppServices::new(&dir);
        loaded.load().unwrap();
        assert_eq!(loaded.settings.get("theme"), Some("dark"));
        assert_eq!(loaded.recent_files.len(), 1);
        assert_eq!(loaded.crashes.len(), 1);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn schema_marker_written_after_save() {
        let dir = std::env::temp_dir().join(format!("mgui-schema-app-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut services = AppServices::new(&dir);
        assert_eq!(services.schema_state(), SchemaState::Legacy);
        services.save().unwrap();
        assert_eq!(services.schema_state(), SchemaState::Current);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn corrupted_settings_recover_from_backup_and_heal() {
        let dir = std::env::temp_dir().join(format!("mgui-recover-app-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut services = AppServices::new(&dir);
        services.settings.set("theme", "dark");
        services.save().unwrap();
        // 第二次保存产生含 theme=dark 的备份,再写一份新值作为主文件。
        services.settings.set("theme", "light");
        services.save().unwrap();
        // 模拟半写主文件:校验和不再匹配。
        std::fs::write(services.settings_path(), "theme=corrupt").unwrap();

        let mut loaded = AppServices::new(&dir);
        let report = loaded.load_with_report().unwrap();
        assert_eq!(report.settings, FileOutcome::RecoveredFromBackup);
        assert_eq!(loaded.settings.get("theme"), Some("dark"));
        loaded.heal_after_recovery(&report).unwrap();
        let mut again = AppServices::new(&dir);
        assert_eq!(again.load_with_report().unwrap().settings, FileOutcome::Loaded);
        assert_eq!(again.settings.get("theme"), Some("dark"));
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn owner_contest_blocks_second_window_and_stale_lease() {
        let dir = std::env::temp_dir().join(format!("mgui-owner-app-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let services = AppServices::new(&dir);
        let owner = services.try_acquire_owner().unwrap();
        assert!(matches!(services.try_acquire_owner(), Err(AcquireError::Contested)));

        let mut writer = AppServices::new(&dir);
        writer.settings.set("theme", "dark");
        writer.save_with_owner(&owner).unwrap();
        assert_eq!(writer.schema_state(), SchemaState::Current);

        // 主动释放后旧租约失效,再保存必须被拒绝。
        let mut owner = owner;
        owner.release().unwrap();
        assert_eq!(writer.save_with_owner(&owner).unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn legacy_files_without_checksum_still_load() {
        let dir = std::env::temp_dir().join(format!("mgui-legacy-app-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("settings.txt"), "theme=dark\n").unwrap();
        let mut services = AppServices::new(&dir);
        let report = services.load_with_report().unwrap();
        assert_eq!(report.settings, FileOutcome::LegacyLoaded);
        assert_eq!(services.settings.get("theme"), Some("dark"));
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn crash_diagnostics_are_bounded_and_round_trip() {
        let mut log = CrashDiagnostics::new(2);
        log.record("a", "one", "detail one");
        log.record("b", "two", "detail\ttwo=2");
        log.record("c", "three", "detail\tthree=3");
        assert_eq!(log.len(), 2);
        let path = std::env::temp_dir().join(format!("mgui-crash-{}.txt", std::process::id()));
        log.save(&path).unwrap();
        let mut loaded = CrashDiagnostics::new(2);
        loaded.load(&path).unwrap();
        assert_eq!(loaded.records().map(|r| r.scene.as_str()).collect::<Vec<_>>(), ["b", "c"]);
        assert_eq!(loaded.records().nth(1).unwrap().detail, "detail\tthree=3");
        std::fs::remove_file(path).unwrap();
    }
}