mgui-core 0.7.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! 应用级基础服务(0.7):设置、最近文件、崩溃诊断。
//!
//! 这些服务刻意不碰 Widget/Element/RO,也不引入 serde/平台 API:
//! 用可审计的纯文本格式落盘,便于 Agent replay 与人工核对。时间由调用方注入,
//! 框架不读墙钟,保证同一脚本两遍 trace 可逐字节比较。

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

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
}

fn read_lines(path: &Path) -> std::io::Result<Vec<String>> {
    match std::fs::read_to_string(path) {
        Ok(text) => Ok(text.lines().map(str::to_string).collect()),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
        Err(err) => Err(err),
    }
}

/// 键值设置。同名 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
    }

    pub fn load(&mut self, path: &Path) -> std::io::Result<()> {
        self.values.clear();
        for line in read_lines(path)? {
            if let Some((key, value)) = split_unescaped_once(&line, '=') {
                self.values.insert(unescape(key), unescape(value));
            }
        }
        self.dirty = false;
        Ok(())
    }

    pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut lines: Vec<_> = self.values.iter().collect();
        lines.sort_by_key(|(key, _)| key.as_str());
        let text: String =
            lines.into_iter().map(|(key, value)| format!("{}={}\n", escape(key), escape(value))).collect();
        std::fs::write(path, text)?;
        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(&mut self, path: &Path) -> std::io::Result<()> {
        self.paths.clear();
        for line in read_lines(path)? {
            if !line.trim().is_empty() {
                self.paths.push(PathBuf::from(unescape(&line)));
            }
        }
        self.paths.truncate(self.limit);
        self.dirty = false;
        Ok(())
    }

    pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let text: String = self.paths.iter().map(|p| format!("{}\n", escape(&p.to_string_lossy()))).collect();
        std::fs::write(path, text)?;
        self.dirty = false;
        Ok(())
    }
}

/// 应用级服务集合。目录由应用给出;框架只负责 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")
    }

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

    pub fn save(&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(())
    }
}

/// 一条崩溃/错误诊断记录。`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(&mut self, path: &Path) -> std::io::Result<()> {
        self.records.clear();
        for line in read_lines(path)? {
            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));
            }
        }
        Ok(())
    }

    pub fn save(&self, path: &Path) -> std::io::Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let text: String = self
            .records
            .iter()
            .map(|r| format!("{}\t{}\t{}\n", escape(&r.scene), escape(&r.summary), escape(&r.detail)))
            .collect();
        std::fs::write(path, text)
    }
}

#[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 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();
    }
}