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
}
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),
}
}
#[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(())
}
}
#[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(())
}
}
#[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(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CrashRecord {
pub scene: String,
pub summary: String,
pub detail: String,
}
#[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();
}
}