From 0cc2738238bd4b7b29493d09123710d15b7353ba Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 13 Nov 2026 15:30:02 +0100 Subject: [PATCH] Persist Midra application options in platform config directory --- AGENTS.md | 3 +- Cargo.lock | 1 + crates/midra-layout/Cargo.toml | 1 + crates/midra-layout/src/gui.rs | 29 +++ crates/midra-layout/src/main.rs | 4 +- crates/midra-layout/src/menu_ui.rs | 46 +++++ crates/midra-layout/src/project_ui.rs | 9 + crates/midra-layout/src/settings.rs | 179 ++++++++++++++++++ crates/midra-layout/src/theme.rs | 3 +- .../midra-layout-settings-v1.example.json | 7 + docs/interfaces/midra-layout-settings.md | 51 +++++ docs/midra-layout.md | 27 ++- 12 files changed, 355 insertions(+), 5 deletions(-) create mode 100644 crates/midra-layout/src/settings.rs create mode 100644 docs/interfaces/midra-layout-settings-v1.example.json create mode 100644 docs/interfaces/midra-layout-settings.md diff --git a/AGENTS.md b/AGENTS.md index 2e28d96..46acef6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -110,7 +110,8 @@ with quick-start examples and links to detailed documentation in `docs/`. - Version breaking changes explicitly; provide a tested migration or a clear unsupported-version error rather than silently interpreting incompatible data. - Midra Layout's JSON project and SVG geometry contracts are in - `docs/interfaces/midra-layout.md`. + `docs/interfaces/midra-layout.md`; per-user application settings are in + `docs/interfaces/midra-layout-settings.md`. ## Commit every task diff --git a/Cargo.lock b/Cargo.lock index 2628c4c..022652b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2396,6 +2396,7 @@ name = "midra-layout" version = "0.3.0" dependencies = [ "base64 0.22.1", + "directories", "eframe", "image", "rfd", diff --git a/crates/midra-layout/Cargo.toml b/crates/midra-layout/Cargo.toml index 5edd3e9..cdea0a5 100644 --- a/crates/midra-layout/Cargo.toml +++ b/crates/midra-layout/Cargo.toml @@ -16,3 +16,4 @@ serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["float_roundtrip"] } base64 = "0.22" tempfile = "3" +directories = "6" diff --git a/crates/midra-layout/src/gui.rs b/crates/midra-layout/src/gui.rs index 4369693..12e7f6c 100644 --- a/crates/midra-layout/src/gui.rs +++ b/crates/midra-layout/src/gui.rs @@ -10,6 +10,7 @@ use midra_layout::import::{DetectedShape, ImportDocument, parse_svg, parse_value use midra_layout::{AlignTarget, Alignment, Corner, Geometry, Layout, ResizeHandle, ResizeMode}; pub struct Editor { + settings: settings::Store, layout: Layout, files: project_ui::FileUi, corner: Corner, @@ -166,6 +167,7 @@ impl Paste { impl Default for Editor { fn default() -> Self { let mut this = Self { + settings: settings::Store::default(), layout: Layout::default(), files: project_ui::FileUi::default(), corner: Corner::TopRight, @@ -214,6 +216,33 @@ fn bounds(g: Geometry) -> String { ) } impl Editor { + pub(super) fn with_saved_settings(ctx: &egui::Context) -> Self { + let (store, saved) = settings::Store::open(); + Self::with_settings(ctx, store, saved) + } + fn with_settings( + ctx: &egui::Context, + store: settings::Store, + saved: settings::Settings, + ) -> Self { + saved.theme.apply(ctx); + Self { + settings: store, + keep_aspect_ratio: saved.keep_aspect_ratio, + show_pattern: saved.show_source_pattern, + show_toolbar_icon_names: saved.show_toolbar_icon_names, + ..Self::default() + } + } + fn application_settings(&self, ctx: &egui::Context) -> settings::Settings { + settings::Settings { + theme: theme::Theme::current(ctx), + keep_aspect_ratio: self.keep_aspect_ratio, + show_source_pattern: self.show_pattern, + show_toolbar_icon_names: self.show_toolbar_icon_names, + ..Default::default() + } + } fn load_reference(&mut self, ctx: &egui::Context, file: &egui::DroppedFile) { match super::reference::Reference::load(ctx, file) { Ok(reference) => { diff --git a/crates/midra-layout/src/main.rs b/crates/midra-layout/src/main.rs index df28cf3..2b64e51 100644 --- a/crates/midra-layout/src/main.rs +++ b/crates/midra-layout/src/main.rs @@ -29,14 +29,14 @@ fn main() -> eframe::Result { style.visuals.widgets.inactive.bg_stroke = Stroke::new(1.0_f32, LINE); style.spacing.item_spacing = Vec2::new(12.0, 10.0); cc.egui_ctx.set_style(style); - theme::Theme::Midra.apply(&cc.egui_ctx); - Ok(Box::new(gui::Editor::default())) + Ok(Box::new(gui::Editor::with_saved_settings(&cc.egui_ctx))) }), ) } mod gui; mod reference; +mod settings; mod theme; /// Draw in local logical points; viewport artwork alone uses a fitted scale. diff --git a/crates/midra-layout/src/menu_ui.rs b/crates/midra-layout/src/menu_ui.rs index 98efaaa..a3f0413 100644 --- a/crates/midra-layout/src/menu_ui.rs +++ b/crates/midra-layout/src/menu_ui.rs @@ -40,6 +40,7 @@ impl Editor { } } pub(super) fn viewport_options_menu(&mut self, ui: &mut egui::Ui) { + let before = self.application_settings(ui.ctx()); let current = theme::Theme::current(ui.ctx()); ui.menu_button(format!("Theme: {}", current.name()), |ui| { for choice in theme::Theme::ALL { @@ -62,6 +63,21 @@ impl Editor { &mut self.show_pattern, "Show source-coordinate test pattern in viewport", ); + let after = self.application_settings(ui.ctx()); + if before != after { + self.settings.save(&after); + } + if let Some(path) = &self.settings.path { + ui.separator(); + ui.label("Options save automatically") + .on_hover_text(path.display().to_string()); + } + if let Some(error) = &self.settings.error { + ui.colored_label(ui.visuals().error_fg_color, error); + if self.settings.can_retry() && ui.button("Retry saving options").clicked() { + self.settings.save(&after); + } + } } pub(super) fn fit_screen(&mut self) { self.zoom = 1.0; @@ -209,6 +225,36 @@ mod tests { frame(app, ctx, vec![mouse(pos, false)]); } #[test] + fn options_are_saved_and_restored_in_a_fresh_editor() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + let (store, saved) = settings::Store::at(path.clone()); + let ctx = egui::Context::default(); + let mut app = Editor::with_settings(&ctx, store, saved); + click_label(&mut app, &ctx, "Menu"); + click_label(&mut app, &ctx, "Options"); + for label in [ + "Show toolbar icon names", + "Keep aspect ratio when resizing", + "Show source-coordinate test pattern in viewport", + ] { + click_label(&mut app, &ctx, label); + } + click_label(&mut app, &ctx, "Theme: Midra Dark"); + click_label(&mut app, &ctx, "Corporate Light"); + let (store, saved) = settings::Store::at(path); + assert!(store.error.is_none()); + let fresh_ctx = egui::Context::default(); + let restored = Editor::with_settings(&fresh_ctx, store, saved); + assert!(restored.show_toolbar_icon_names); + assert!(!restored.keep_aspect_ratio); + assert!(restored.show_pattern); + assert_eq!( + theme::Theme::current(&fresh_ctx), + theme::Theme::CorporateLight + ); + } + #[test] fn theme_menu_switches_chrome_without_changing_document() { let mut app = Editor::default(); let ctx = egui::Context::default(); diff --git a/crates/midra-layout/src/project_ui.rs b/crates/midra-layout/src/project_ui.rs index 2d1b8b3..d3aaaad 100644 --- a/crates/midra-layout/src/project_ui.rs +++ b/crates/midra-layout/src/project_ui.rs @@ -48,6 +48,7 @@ impl Editor { let e = project.editor; // Replace only after both the document and embedded image are ready. *self = Self { + settings: std::mem::take(&mut self.settings), layout, reference, corner: e.position_corner, @@ -219,7 +220,15 @@ mod tests { edit_content: true, ..Default::default() }; + let settings_dir = tempfile::tempdir().unwrap(); + let settings_path = settings_dir.path().join("settings.json"); + restored.settings = settings::Store::at(settings_path.clone()).0; restored.install_project(&ctx, project.clone()).unwrap(); + assert_eq!(restored.settings.path.as_ref(), Some(&settings_path)); + assert!( + !settings_path.exists(), + "opening a project must not save application defaults" + ); assert_eq!(restored.project(), project); assert!(!restored.edit_content); assert_eq!(restored.reference.as_ref().unwrap().bytes, original_bytes); diff --git a/crates/midra-layout/src/settings.rs b/crates/midra-layout/src/settings.rs new file mode 100644 index 0000000..b6f1a59 --- /dev/null +++ b/crates/midra-layout/src/settings.rs @@ -0,0 +1,179 @@ +//! Per-user application defaults. Contract: docs/interfaces/midra-layout-settings.md. +use crate::theme::Theme; +use serde::{Deserialize, Serialize}; +use std::{io::Read, path::PathBuf}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Settings { + pub version: u32, + pub theme: Theme, + pub show_toolbar_icon_names: bool, + pub keep_aspect_ratio: bool, + pub show_source_pattern: bool, +} +impl Default for Settings { + fn default() -> Self { + Self { + version: 1, + theme: Theme::Midra, + show_toolbar_icon_names: false, + keep_aspect_ratio: true, + show_source_pattern: false, + } + } +} + +/// No filesystem access from Default: headless editor tests stay isolated. +#[derive(Default)] +pub struct Store { + pub path: Option, + pub error: Option, + writable: bool, +} +impl Store { + pub fn open() -> (Self, Settings) { + match directories::ProjectDirs::from("org", "beffroi", "midra-layout") { + Some(dirs) => Self::at(dirs.config_dir().join("settings.json")), + None => ( + Self { + error: Some( + "Cannot locate your configuration directory; options will not be saved." + .into(), + ), + ..Self::default() + }, + Settings::default(), + ), + } + } + pub(super) fn at(path: PathBuf) -> (Self, Settings) { + let mut store = Self { + path: Some(path.clone()), + error: None, + writable: true, + }; + match Self::read(&path) { + Ok(settings) => (store, settings), + Err(e) => { + store.writable = false; + store.error = Some(format!( + "Could not load {}: {e}. Using defaults. Repair or move this file and restart to enable saving; the original file is kept.", + path.display() + )); + (store, Settings::default()) + } + } + } + fn read(path: &std::path::Path) -> Result { + let file = match std::fs::File::open(path) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Settings::default()), + Err(e) => return Err(e.to_string()), + }; + let mut text = String::new(); + file.take(65_537) + .read_to_string(&mut text) + .map_err(|e| e.to_string())?; + if text.len() > 65_536 { + return Err("settings exceed 64 KiB".into()); + } + let settings: Settings = serde_json::from_str(&text).map_err(|e| e.to_string())?; + if settings.version != 1 { + return Err(format!("unsupported settings version {}", settings.version)); + } + Ok(settings) + } + pub fn save(&mut self, settings: &Settings) { + if !self.writable { + return; + } + let Some(path) = &self.path else { + return; + }; + let result = (|| { + let parent = path + .parent() + .ok_or("Settings path has no parent directory")?; + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + let text = serde_json::to_string_pretty(settings).map_err(|e| e.to_string())? + "\n"; + midra_layout::project::write_file(path, text.as_bytes(), true) + })(); + self.error = result.err().map(|e| { + format!( + "Could not save {}: {e}. Your options still apply for this session.", + path.display() + ) + }); + } + pub fn can_retry(&self) -> bool { + self.writable && self.error.is_some() + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn missing_settings_and_changed_options_roundtrip_without_temp_files() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("app/settings.json"); + let (mut store, mut settings) = Store::at(path.clone()); + assert_eq!(settings, Settings::default()); + assert!(!path.exists()); + settings.theme = Theme::CorporateLight; + settings.show_toolbar_icon_names = true; + settings.keep_aspect_ratio = false; + settings.show_source_pattern = true; + store.save(&settings); + assert!(store.error.is_none()); + assert_eq!(Store::at(path.clone()).1, settings); + settings.theme = Theme::FoxifiedDark; + store.save(&settings); + assert_eq!(Store::at(path.clone()).1, settings); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + } + #[test] + fn invalid_or_future_settings_are_preserved_and_writes_can_be_retried() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + for text in [ + "broken".to_string(), + serde_json::to_string(&Settings { + version: 2, + ..Default::default() + }) + .unwrap(), + "x".repeat(65_537), + ] { + std::fs::write(&path, &text).unwrap(); + let (mut store, settings) = Store::at(path.clone()); + assert_eq!(settings, Settings::default()); + assert!(store.error.is_some()); + store.save(&settings); + assert_eq!(std::fs::read_to_string(&path).unwrap(), text); + } + let blocker = dir.path().join("blocked"); + let (mut store, settings) = Store::at(blocker.join("settings.json")); + std::fs::write(&blocker, "occupied").unwrap(); + store.save(&settings); + assert!(store.can_retry()); + assert_eq!(std::fs::read_to_string(&blocker).unwrap(), "occupied"); + std::fs::remove_file(&blocker).unwrap(); + store.save(&settings); + assert!(store.error.is_none()); + assert_eq!(Store::at(blocker.join("settings.json")).1, settings); + } + #[test] + fn documented_settings_match_defaults() { + let example = + include_str!("../../../docs/interfaces/midra-layout-settings-v1.example.json"); + assert_eq!( + serde_json::from_str::(example).unwrap(), + Settings::default() + ); + } +} diff --git a/crates/midra-layout/src/theme.rs b/crates/midra-layout/src/theme.rs index e131e50..31ddd1e 100644 --- a/crates/midra-layout/src/theme.rs +++ b/crates/midra-layout/src/theme.rs @@ -1,7 +1,8 @@ //! Application palettes adapted from SOTV's song database; see docs/midra-layout.md. use super::*; -#[derive(Clone, Copy, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum Theme { #[default] Midra, diff --git a/docs/interfaces/midra-layout-settings-v1.example.json b/docs/interfaces/midra-layout-settings-v1.example.json new file mode 100644 index 0000000..51c3b0c --- /dev/null +++ b/docs/interfaces/midra-layout-settings-v1.example.json @@ -0,0 +1,7 @@ +{ + "version": 1, + "theme": "midra", + "show_toolbar_icon_names": false, + "keep_aspect_ratio": true, + "show_source_pattern": false +} diff --git a/docs/interfaces/midra-layout-settings.md b/docs/interfaces/midra-layout-settings.md new file mode 100644 index 0000000..206501e --- /dev/null +++ b/docs/interfaces/midra-layout-settings.md @@ -0,0 +1,51 @@ +# Midra Layout application settings, version 1 + +Implementation: `crates/midra-layout/src/settings.rs`. This per-user JSON file is +independent of the [project JSON and SVG contracts](midra-layout.md). +[Complete default example](midra-layout-settings-v1.example.json). + +The `directories` 6 crate resolves `ProjectDirs::from("org", "beffroi", "midra-layout")`. +The filename is `settings.json` beneath `config_dir()`: + +| Platform | Location | +| --- | --- | +| Linux | `$XDG_CONFIG_HOME/midra-layout/settings.json`, otherwise `~/.config/midra-layout/settings.json` | +| Windows | `%APPDATA%\beffroi\midra-layout\config\settings.json` (Roaming AppData) | +| macOS | `~/Library/Application Support/org.beffroi.midra-layout/settings.json` | + +UTF-8, pretty-printed JSON with a trailing newline; maximum input size 64 KiB. +Every field is required, unknown fields are rejected, and unknown versions or +unknown theme names are rejected. There are no numeric coordinates or units. + +| Field | Values / default | +| --- | --- | +| `version` | Integer `1` | +| `theme` | `"midra"` (default), `"foxified_dark"`, `"corporate_light"` | +| `show_toolbar_icon_names` | Boolean; default false | +| `keep_aspect_ratio` | Boolean; default true | +| `show_source_pattern` | Boolean; default false | + +Loaded once at startup before the editor appears. Explicit Options changes save +all four current preferences immediately. The directory is created lazily; +missing files do not trigger a write until the user changes an option. Writes +use a temporary file in the same directory, file sync and atomic replacement. +Multiple application instances use last-successful-write wins; no merging or +live reloading is performed. + +Project JSON v1/v2 remains unchanged. Opening a project can restore its embedded +caption, aspect-ratio and source-preview preferences for that document; it never +writes application settings. Theme remains global. Editing an option afterward +saves all currently active preferences as the next startup defaults. + +Invalid/unreadable settings fall back to defaults, report the failure in Options, +and disable writes for that run to preserve the original file. Repair/move the +file and restart to recover. A write failure retains in-memory preferences and +the previous destination where atomic publication failed; Options offers a retry. +Failure to locate a configuration directory also disables persistence with an +Options error. Tests use temporary directories and never touch user settings. + +No layer geometry, source crops, camera state, project paths, image bytes, device +addresses or clipboard contents are stored. No settings are exported to SVG. +Breaking or additive schema changes under this strict contract require a version +bump, updated documentation/examples/tests, and either an explicit migration or +an actionable unsupported-version error. diff --git a/docs/midra-layout.md b/docs/midra-layout.md index e3d9e0b..2afcb5f 100644 --- a/docs/midra-layout.md +++ b/docs/midra-layout.md @@ -437,7 +437,7 @@ project; older projects open with captions off. **Foxified Dark**, and **Corporate Light**. Switching updates toolbar, inspector, dialogs, fields and menus immediately. Reference images, source test patterns, and the dark screen canvas retain their colors; selected layers remain gold. -Theme choice applies to the current application session, survives opening other +Theme choice is saved automatically per user, survives restarts and opening other projects, and is not included in project JSON or SVG exports. The additional palettes are adapted from the sibling `SOTV_Websites` project's @@ -447,3 +447,28 @@ The additional palettes are adapted from the sibling `SOTV_Websites` project's peach text and orange accent. Corporate preserves its neutral light surfaces; muted text, warnings and accent colors are darkened for readable contrast. Action fills are adapted for readable button text in both themes. + +### Saved application options + +Options save automatically when changed: theme, toolbar icon names, aspect-ratio +lock and source-coordinate preview. No separate Apply or Save is needed. +The `directories` crate selects the OS configuration directory: + +- Linux: `$XDG_CONFIG_HOME/midra-layout/settings.json`, or + `~/.config/midra-layout/settings.json` when XDG_CONFIG_HOME is unset. +- Windows: `%APPDATA%\beffroi\midra-layout\config\settings.json`. +- macOS: `~/Library/Application Support/org.beffroi.midra-layout/settings.json`. + +Hover **Options save automatically** in Options to see the actual path. These are +startup defaults. Existing project files still restore their saved aspect-ratio, +caption and source-preview settings for the open document, without rewriting the +application defaults. A subsequent explicit Options change saves the current set +of options as the new defaults. Theme always remains an application preference. + +Missing settings use defaults; the file is created on the first option change. +Unreadable, malformed or unsupported settings use defaults and show an Options +error; the original file is preserved and saving is disabled until the file is +repaired or moved and the application restarted. Write failures keep options +active in memory and offer **Retry saving options**. No project data, images or +clipboard contents are stored here. The [settings interface](interfaces/midra-layout-settings.md) +documents the file and compatibility rules.