From 2dcffb82ffa1624afa0d0771ee4405647e0c9f51 Mon Sep 17 00:00:00 2001 From: Wolren Date: Wed, 28 Oct 2026 20:30:01 +0100 Subject: [PATCH 01/28] UI: themes as files, an interface scale, and Settings > Theme The interface colours, spacing and text sizes were code tables: light or dark, and nothing else. A theme is now a JSON file that names every colour it draws, with its metrics, so a user can write one and drop it in the themes folder. - crates/ui-egui/themes/{light,dark}.json ship compiled in, and a test keeps them equal to the code tables they replace. - /themes/*.json are read at startup, when a file changes and by ui.themeReload; a file that does not load is listed with the token at fault, and one named as a built-in replaces it, so a name picks one theme. - "extends" starts a file from Light or Dark, so five colours make a theme, and a byte-order mark from Notepad is skipped rather than refused. - Settings > Theme lists the themes with Follow the System, loads one from any file (kept in the themes folder) and sets the interface scale from 80% to 200%. - The choice and the scale are saved; Dark Mode still toggles brightness and leaves the theme list, and the saved brightness is taken at the next start. - Tokens gained "control" (slider rails and checkbox wells), and apply() takes the theme's metrics. A theme does not reach the map, which the renderer draws. docs/themes.md documents the file, the short form and the commands. --- crates/ui-egui/examples/ui_shot.rs | 4 +- crates/ui-egui/src/lib.rs | 234 +++++++++- crates/ui-egui/src/ribbon.rs | 88 +++- crates/ui-egui/src/theme.rs | 672 ++++++++++++++++++++++++++++- crates/ui-egui/themes/dark.json | 55 +++ crates/ui-egui/themes/light.json | 55 +++ docs/index.md | 7 + docs/themes.md | 148 +++++++ zensical.toml | 1 + 9 files changed, 1236 insertions(+), 28 deletions(-) create mode 100644 crates/ui-egui/themes/dark.json create mode 100644 crates/ui-egui/themes/light.json create mode 100644 docs/themes.md diff --git a/crates/ui-egui/examples/ui_shot.rs b/crates/ui-egui/examples/ui_shot.rs index e92a0ca168..4abe189e00 100644 --- a/crates/ui-egui/examples/ui_shot.rs +++ b/crates/ui-egui/examples/ui_shot.rs @@ -67,8 +67,8 @@ impl RibbonSplitShowcase { self.fonts_installed = true; } if self.applied_dark != Some(app.ui.dark) { - let tokens = if app.ui.dark { theme::Tokens::dark() } else { theme::Tokens::light() }; - theme::apply(ui.ctx(), &tokens); + let chosen = app.current_theme(); + theme::apply(ui.ctx(), &chosen.tokens, &chosen.metrics); self.applied_dark = Some(app.ui.dark); } i18n::set_current(app.chosen_lang()); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9240c9ad5e..adaac1de05 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -554,6 +554,10 @@ pub struct UiState { /// `panes::web_data_name`). pub web_data: &'static str, pub dark: bool, + /// The theme file in use, by name. Empty follows `dark` and the system. + pub theme_name: String, + /// The interface scale, 0.75 to 2.0, applied as egui's zoom factor. + pub interface_scale: f32, /// Live measurement and map scale-bar units, chosen in Home › Measure. pub measurement_imperial: bool, /// The theme follows the system's light or dark setting until the user picks one. @@ -786,6 +790,8 @@ impl Default for UiState { diagnostic_snapshot: None, web_data: "opendata", dark: false, + theme_name: String::new(), + interface_scale: 1.0, measurement_imperial: false, dark_follows_system: true, language: i18n::AUTO.into(), @@ -907,7 +913,15 @@ pub struct RustGisApp { #[cfg(not(target_arch = "wasm32"))] pub connect: connectui::ConnectState, fonts_frames: u32, - applied_dark: Option, + applied_theme: Option<(String, bool)>, + applied_scale: Option, + /// The themes the app can offer: built in, then the ones in the user's themes folder. + pub themes: Vec, + /// The theme files that did not load, with the reason. + pub theme_errors: Vec, + /// What the themes folder held when it was last read, and when it was last looked at. + themes_stamp: u64, + themes_checked: f64, sent_title: String, pub quit_requested: bool, logo: Option, @@ -1059,7 +1073,7 @@ impl RustGisApp { s.active_layer = s.map().layers.first().map(|l| l.id); } let ui = UiState { keymap: keymap::Keymap::new(&s.registry), ..UiState::default() }; - RustGisApp { + let mut app = RustGisApp { session: s, ui, map: mapview::MapView::default(), @@ -1079,7 +1093,12 @@ impl RustGisApp { docs: docpanes::DocState::default(), assistant: assistantpane::AssistantState::default(), fonts_frames: 0, - applied_dark: None, + applied_theme: None, + applied_scale: None, + themes: Vec::new(), + theme_errors: Vec::new(), + themes_stamp: 0, + themes_checked: 0.0, sent_title: String::new(), quit_requested: false, logo: None, @@ -1109,7 +1128,9 @@ impl RustGisApp { seen_project: None, autosave: Default::default(), save_prompt: Default::default(), - } + }; + app.load_themes(); + app } /// Installs the shell's platform hooks and reads what they keep: preferences, saved @@ -1175,6 +1196,9 @@ impl RustGisApp { let list = |s: Option| -> Vec { s.map(|v| v.split(',').map(str::trim).filter(|x| !x.is_empty()).map(String::from).collect()).unwrap_or_default() }; + // A saved theme is only found once the folder has been read. + self.load_themes(); + self.take_saved_look(); self.ui.hidden_tabs = ribbon::current_hidden_tabs(list(self.services.load_pref.as_ref().and_then(|load| load("hidden_tabs")))); self.ui.quick_access = list(self.services.load_pref.as_ref().and_then(|load| load("quick_access"))); // The browser's GeoLibre tools, loaded in an earlier visit: load them again (the runner @@ -1610,6 +1634,97 @@ impl RustGisApp { } } + /// Reads the built-in themes and the user's themes folder, keeping the files that failed. + fn load_themes(&mut self) { + let (themes, errors) = theme::Theme::available(); + self.themes = themes; + self.theme_errors = errors; + self.themes_stamp = theme::Theme::folder_signature(theme::Theme::user_dir().as_deref()); + // The files may read differently: put the theme in force on again. + self.applied_theme = None; + } + + /// Reads the folder again when a file in it was added, removed or saved, at most once a second. + fn refresh_themes(&mut self, ctx: &egui::Context) { + // Only someone with a themes folder pays for this, and they are editing one. + let Some(dir) = theme::Theme::user_dir().filter(|d| d.is_dir()) else { return }; + ctx.request_repaint_after(web_time::Duration::from_secs(1)); + let now = ctx.input(|i| i.time); + if now < self.themes_checked + 1.0 { + return; + } + self.themes_checked = now; + if theme::Theme::folder_signature(Some(&dir)) != self.themes_stamp { + self.load_themes(); + } + } + + /// The theme in use: the one named, else the nearest built-in theme for the current brightness. + pub fn current_theme(&self) -> theme::Theme { + self.themes + .iter() + .find(|t| t.name == self.ui.theme_name && t.dark == self.ui.dark) + .or_else(|| self.themes.iter().find(|t| t.dark == self.ui.dark)) + .cloned() + .unwrap_or(theme::Theme { + name: "Light".to_string(), + dark: false, + tokens: theme::Tokens::light(), + metrics: theme::Metrics::standard(), + }) + } + + /// Takes the saved look from the preferences: the theme by name, else the brightness, and the + /// scale. A name that no longer loads leaves the look following the system. + fn take_saved_look(&mut self) { + let pref = |app: &Self, key: &str| -> Option { + app.services.load_pref.as_ref().and_then(|load| load(key)).filter(|v| !v.is_empty()) + }; + let wanted = pref(self, "theme"); + let picked = wanted.and_then(|name| self.themes.iter().find(|t| t.name == name).cloned()); + if let Some(picked) = picked { + self.ui.theme_name = picked.name; + self.ui.dark = picked.dark; + self.ui.dark_follows_system = false; + } else if let Some(dark) = pref(self, "dark") { + // Toggled with Dark Mode and no theme file: remember which of the two it was. + self.ui.dark = dark == "true"; + self.ui.dark_follows_system = false; + } + let scale = pref(self, "ui_scale").and_then(|v| v.parse::().ok()); + self.ui.interface_scale = scale.map_or(1.0, theme::clamp_scale); + } + + /// Uses a theme from the list, and saves the choice. + fn use_theme(&mut self, name: &str) -> Result<(), String> { + let Some(picked) = self.themes.iter().find(|t| t.name == name).cloned() else { + return Err(i18n::fmt("No theme is named {name}.", &[("name", name)])); + }; + self.ui.theme_name = picked.name.clone(); + self.ui.dark = picked.dark; + self.ui.dark_follows_system = false; + if let Some(save) = &self.services.save_pref { + save("theme", &picked.name); + save("dark", if picked.dark { "true" } else { "false" }); + } + Ok(()) + } + + /// Reads a theme file from anywhere, keeps a copy in the themes folder and uses it. + fn load_theme_file(&mut self, path: &std::path::Path) -> Result<(), String> { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); + let theme = theme::Theme::parse(&stem, &text).map_err(|e| format!("{}: {e}", path.display()))?; + let kept = theme.save_user()?; + self.load_themes(); + self.use_theme(&theme.name)?; + let kept = kept.display().to_string(); + let name = theme.name.clone(); + let text = i18n::fmt("Theme {name} loaded and kept at {path}", &[("name", &name), ("path", &kept)]); + self.session.notify(text, false); + Ok(()) + } + /// Sets up the project the app opens with, from the Settings › Start-up preferences; a shell /// passes its own overrides (the web app's `?blank`, `?projection=` and `?extent=`). Call it /// once, after [`Self::with_services`] and before opening files. The start is not an edit to @@ -2256,7 +2371,39 @@ impl RustGisApp { "ui.theme" => { self.ui.dark = p.get("dark").and_then(Value::as_bool).unwrap_or(!self.ui.dark); self.ui.dark_follows_system = false; + self.ui.theme_name.clear(); + if let Some(save) = &self.services.save_pref { + save("dark", if self.ui.dark { "true" } else { "false" }); + save("theme", ""); + } } + // Picks a theme by name; no name follows the system again. + "ui.themeFile" => { + let name = p.get("name").and_then(Value::as_str).unwrap_or_default().trim().to_string(); + if name.is_empty() { + self.ui.theme_name.clear(); + self.ui.dark_follows_system = true; + if let Some(save) = &self.services.save_pref { + save("theme", ""); + } + } else { + self.use_theme(&name)?; + } + } + // Opens a theme file from anywhere, keeps it in the themes folder and uses it. + "ui.themeLoad" => { + let Some(path) = dialogs::pick_open(&["json"], tl!("A theme file")) else { return Ok(Value::Null) }; + self.load_theme_file(std::path::Path::new(&path))?; + } + "ui.scale" => { + let factor = p.get("factor").and_then(Value::as_f64).map_or(1.0, |f| f as f32); + self.ui.interface_scale = theme::clamp_scale(factor); + if let Some(save) = &self.services.save_pref { + save("ui_scale", &format!("{:.2}", self.ui.interface_scale)); + } + } + // Reads the themes folder again, after a file was added or fixed. + "ui.themeReload" => self.load_themes(), "ui.measurementUnits" => { let imperial = match p.get("units") { None => !self.ui.measurement_imperial, @@ -4006,6 +4153,7 @@ impl RustGisApp { ctx.request_repaint(); } } + self.refresh_themes(ctx); if self.ui.dark_follows_system && let Some(system) = ctx.system_theme() { @@ -4013,10 +4161,15 @@ impl RustGisApp { } widgets::let_go_on_panel_press(ctx); widgets::note_escape(ctx); - if self.applied_dark != Some(self.ui.dark) { - let t = if self.ui.dark { theme::Tokens::dark() } else { theme::Tokens::light() }; - theme::apply(ctx, &t); - self.applied_dark = Some(self.ui.dark); + if self.applied_theme.as_ref() != Some(&(self.ui.theme_name.clone(), self.ui.dark)) { + let chosen = self.current_theme(); + theme::apply(ctx, &chosen.tokens, &chosen.metrics); + self.applied_theme = Some((self.ui.theme_name.clone(), self.ui.dark)); + self.map.invalidate(); + } + if self.applied_scale != Some(self.ui.interface_scale) { + ctx.set_zoom_factor(self.ui.interface_scale); + self.applied_scale = Some(self.ui.interface_scale); self.map.invalidate(); } } @@ -4556,3 +4709,68 @@ mod download_service_tests { assert_eq!(app.session.notices.iter().filter(|n| n.error && n.text == "no pending file with that id").count(), 1); } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod look_tests { + use super::RustGisApp; + use crate::theme; + + /// The app with a preferences store that answers these keys only, and a theme no folder ships, + /// so the test does not depend on the machine. + fn app_with(prefs: &'static [(&'static str, &'static str)]) -> RustGisApp { + let mut app = RustGisApp::with_sample(); + app.themes.push(theme::Theme { + name: "Mine".to_string(), + dark: true, + tokens: theme::Tokens::dark(), + metrics: theme::Metrics::standard(), + }); + app.services.load_pref = Some(Box::new(move |key: &str| prefs.iter().find(|(k, _)| *k == key).map(|(_, v)| (*v).to_string()))); + app + } + + #[test] + fn the_saved_theme_is_taken_at_start() { + let mut app = app_with(&[("theme", "Mine"), ("ui_scale", "9")]); + app.take_saved_look(); + assert_eq!(app.ui.theme_name, "Mine"); + assert!(app.ui.dark, "the theme brings its own brightness"); + assert!(!app.ui.dark_follows_system, "a chosen theme does not follow the system"); + assert_eq!(app.ui.interface_scale, 2.0, "the scale is held at 200 percent"); + assert_eq!(app.current_theme().name, "Mine"); + } + + #[test] + fn a_saved_theme_that_is_gone_leaves_the_saved_brightness() { + let mut app = app_with(&[("theme", "Deleted"), ("dark", "true")]); + app.take_saved_look(); + assert!(app.ui.theme_name.is_empty(), "no theme file is named"); + assert!(app.ui.dark, "Dark Mode was on when it was last closed"); + assert!(!app.ui.dark_follows_system); + assert_eq!(app.ui.interface_scale, 1.0, "no scale saved is the normal one"); + } + + /// What a theme choice writes to the preferences. + fn saved_by(app: &mut RustGisApp) -> std::sync::Arc>> { + let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let sink = log.clone(); + app.services.save_pref = + Some(Box::new(move |key: &str, value: &str| sink.lock().expect("the log").push((key.to_string(), value.to_string())))); + log + } + + #[test] + fn choosing_a_theme_saves_the_choice() { + let mut app = app_with(&[]); + let log = saved_by(&mut app); + app.use_theme("Mine").expect("the theme is in the list"); + assert_eq!(app.ui.theme_name, "Mine"); + assert!(app.ui.dark, "the theme brings its own brightness"); + assert!(!app.ui.dark_follows_system); + let written = log.lock().expect("the log").clone(); + assert!(written.contains(&("theme".to_string(), "Mine".to_string())), "{written:?}"); + assert!(written.contains(&("dark".to_string(), "true".to_string())), "{written:?}"); + assert!(app.use_theme("Gone").is_err(), "a name the list does not hold"); + } +} diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index a7349204ec..b29f22b4d3 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3440,8 +3440,13 @@ fn plugin_tab(app: &mut RustGisApp, ui: &mut Ui, plugin: &str) { } } -/// The Settings tab: ribbon customization, language, start-up and (on the desktop) autosave. +/// The Settings tab: theme and scale, ribbon customization, language, start-up and (on the +/// desktop) autosave. fn settings_tab(app: &mut RustGisApp, ui: &mut Ui) { + group(ui, "Theme", |ui| { + theme_menu(app, ui); + scale_menu(app, ui); + }); group(ui, "Customize", |ui| { let hidden = app.ui.hidden_tabs.clone(); // RustGIS's tabs and plugins' tabs. @@ -3498,6 +3503,87 @@ fn autosave_menu(app: &mut RustGisApp, ui: &mut Ui) { }); } +/// Settings › Theme: the built-in themes and every theme file that loads, plus the interface scale. +fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { + let current = if !app.ui.theme_name.is_empty() { + app.ui.theme_name.clone() + } else if app.ui.dark_follows_system { + tl!("Follow the System").to_string() + } else if app.ui.dark { + tl!("Dark").to_string() + } else { + tl!("Light").to_string() + }; + let label = format!("{}\n{current}", tl!("Theme")); + let themes = app.themes.clone(); + let errors = app.theme_errors.clone(); + // The browser has no settings folder to read theme files from or write one to. + let folder = crate::theme::Theme::user_dir().is_some(); + big_menu( + ui, + app, + "dark", + &label, + "The interface colours, spacing and text sizes: a built-in theme or a file from the themes folder.", + move |ui, app| { + let follows = app.ui.theme_name.is_empty() && app.ui.dark_follows_system; + if ui.add(egui::Button::selectable(follows, tl!("Follow the System"))).clicked() { + let _ = app.run("ui.themeFile", Value::Null); + ui.close(); + } + for found in &themes { + let picked = app.ui.theme_name == found.name; + if ui.add(egui::Button::selectable(picked, found.name.as_str())).clicked() { + theme_action(app, "ui.themeFile", json!({ "name": found.name })); + ui.close(); + } + } + if folder { + ui.separator(); + if ui.add(egui::Button::selectable(false, tl!("Load a Theme from File…"))).clicked() { + theme_action(app, "ui.themeLoad", Value::Null); + ui.close(); + } + // After a file is added or fixed by hand: the list is read at startup otherwise. + if ui.add(egui::Button::selectable(false, tl!("Reload Themes"))).clicked() { + let _ = app.run("ui.themeReload", Value::Null); + ui.close(); + } + } + if !errors.is_empty() { + ui.separator(); + let red = Tokens::get(ui.ctx()).red; + for error in &errors { + ui.label(egui::RichText::new(error).color(red).small()); + } + } + }, + ); +} + +/// Runs a menu action, telling the user what went wrong rather than nothing happening. +fn theme_action(app: &mut RustGisApp, id: &str, params: Value) { + if let Err(e) = app.run(id, params) { + app.session.notify(e, true); + } +} + +/// Settings › Theme › Interface Scale: the whole interface, as egui's zoom factor. +fn scale_menu(app: &mut RustGisApp, ui: &mut Ui) { + let current = format!("{}%", (app.ui.interface_scale * 100.0).round() as i32); + let label = format!("{}\n{current}", tl!("Interface Scale")); + big_menu(ui, app, "zoom_full", &label, "The size of the menu, the panes and the text drawn in them.", move |ui, app| { + for percent in [80, 90, 100, 110, 125, 150, 175, 200] { + let factor = percent as f32 / 100.0; + let picked = (app.ui.interface_scale - factor).abs() < 0.001; + if ui.add(egui::Button::selectable(picked, format!("{percent}%"))).clicked() { + let _ = app.run("ui.scale", json!({ "factor": factor })); + ui.close(); + } + } + }); +} + /// Settings › Start-up › Start With: the World Atlas sample, an empty project, or (in the /// desktop app) a project picked once or the last one opened or saved (#377). fn start_project_menu(app: &mut RustGisApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 4d47c8a4cc..653c28aee7 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -1,5 +1,7 @@ -//! Design tokens (light and dark), interface fonts and the egui style. +//! Design tokens (light and dark), interface metrics, the theme file format and the egui style. +use std::collections::BTreeMap; +use std::path::PathBuf; use std::sync::Arc; use egui::{Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Stroke, Visuals}; @@ -10,8 +12,52 @@ pub const BRAND_DARK: Color32 = Color32::from_rgb(0x96, 0x3A, 0x22); /// Contextual tab group colour (Feature Layer, Labeling, Data). pub const CONTEXT: Color32 = Color32::from_rgb(0x0E, 0x93, 0x84); +/// The theme file format this build reads. +pub const SCHEMA: u32 = 1; + +/// The most a theme file may be: a few hundred colours, not a disk to read whole. +pub const MAX_THEME_BYTES: u64 = 64 * 1024; + +/// The longest theme name the menu shows: the ribbon has room for one line of it. +const MAX_NAME: usize = 48; + +/// Every colour a theme file must set. A theme that omits one is refused, and the error names it. +pub const TOKENS: [&str; 31] = [ + "header", + "ribbon", + "tab_strip", + "canvas", + "pane", + "pane_header", + "border", + "border_strong", + "text", + "text_dim", + "text_disabled", + "icon", + "hover", + "pressed", + "checked", + "accent", + "accent_text", + "on_accent", + "input", + "input_border", + "group_label", + "status_bar", + "selection", + "menu", + "shadow", + "green", + "red", + "amber", + "context", + "context_tint", + "control", +]; + /// Every colour the interface uses; widgets never hard-code colours. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] pub struct Tokens { pub dark: bool, pub header: Color32, @@ -44,6 +90,8 @@ pub struct Tokens { pub amber: Color32, pub context: Color32, pub context_tint: Color32, + /// Slider rails and checkbox wells, which must stay visible on white. + pub control: Color32, } impl Tokens { @@ -80,6 +128,7 @@ impl Tokens { amber: Color32::from_rgb(0xE5, 0x9E, 0x1A), context: CONTEXT, context_tint: Color32::from_rgb(0xE3, 0xF5, 0xF2), + control: Color32::from_rgb(0xDD, 0xE3, 0xEA), } } @@ -116,11 +165,349 @@ impl Tokens { amber: Color32::from_rgb(0xF2, 0xB8, 0x48), context: Color32::from_rgb(0x2C, 0xC2, 0xAE), context_tint: Color32::from_rgb(0x1B, 0x33, 0x31), + control: Color32::from_rgb(0x3A, 0x42, 0x4D), } } + /// The theme in force, which the app puts on the context when it applies one. pub fn get(ctx: &egui::Context) -> Tokens { - if ctx.global_style().visuals.dark_mode { Tokens::dark() } else { Tokens::light() } + ctx.data(|d| d.get_temp::(tokens_id())) + .unwrap_or_else(|| if ctx.global_style().visuals.dark_mode { Tokens::dark() } else { Tokens::light() }) + } +} + +/// Where the applied colours are kept, so every widget reads the theme that is in force. +fn tokens_id() -> egui::Id { + egui::Id::unique("rustgis.theme.tokens") +} + +/// Spacing, corner radius and text sizes a theme sets, in points. +#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct Metrics { + pub item_spacing: [f32; 2], + pub button_padding: [f32; 2], + pub row_height: f32, + pub corner_radius: u8, + pub body: f32, + pub button_text: f32, + pub small: f32, + pub heading: f32, + pub mono: f32, +} + +impl Metrics { + pub fn standard() -> Self { + Metrics { + item_spacing: [6.0, 5.0], + button_padding: [8.0, 3.0], + row_height: 22.0, + corner_radius: 5, + body: 12.5, + button_text: 12.5, + small: 10.5, + heading: 17.0, + mono: 12.0, + } + } + + /// These metrics within the ranges the interface can draw: a theme file is input from outside + /// the app, so an out-of-range number is held to the nearest end, a non-number takes the standard. + pub fn clamped(self) -> Self { + let fit = |v: f32, lo: f32, hi: f32, otherwise: f32| if v.is_finite() { v.clamp(lo, hi) } else { otherwise }; + let std = Metrics::standard(); + Metrics { + item_spacing: [ + fit(self.item_spacing[0], 0.0, 40.0, std.item_spacing[0]), + fit(self.item_spacing[1], 0.0, 40.0, std.item_spacing[1]), + ], + button_padding: [ + fit(self.button_padding[0], 0.0, 40.0, std.button_padding[0]), + fit(self.button_padding[1], 0.0, 40.0, std.button_padding[1]), + ], + row_height: fit(self.row_height, 8.0, 80.0, std.row_height), + corner_radius: self.corner_radius.min(32), + body: fit(self.body, 6.0, 40.0, std.body), + button_text: fit(self.button_text, 6.0, 40.0, std.button_text), + small: fit(self.small, 5.0, 32.0, std.small), + heading: fit(self.heading, 8.0, 60.0, std.heading), + mono: fit(self.mono, 5.0, 40.0, std.mono), + } + } +} + +/// The interface scale a command accepts, held between 75 and 200 percent. +pub fn clamp_scale(scale: f32) -> f32 { + if scale.is_finite() { scale.clamp(0.75, 2.0) } else { 1.0 } +} + +/// A theme: named colours plus metrics, from a built-in file or a user theme file. +#[derive(Clone, Debug, PartialEq)] +pub struct Theme { + pub name: String, + pub dark: bool, + pub tokens: Tokens, + pub metrics: Metrics, +} + +#[derive(serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +struct Raw { + schema: u32, + name: String, + /// A theme that ships, whose colours and sizes this file starts from. + #[serde(default, skip_serializing_if = "Option::is_none")] + extends: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + dark: Option, + #[serde(default)] + colours: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + metrics: Option, +} + +impl Theme { + /// The themes that ship with the app, from `themes/*.json` beside this crate. A file that does + /// not load falls back to the code tables; `the_built_in_files_match_the_code_tables` catches it. + pub fn builtin() -> Vec { + [("Light", include_str!("../themes/light.json"), Tokens::light()), ("Dark", include_str!("../themes/dark.json"), Tokens::dark())] + .into_iter() + .map(|(name, text, fallback)| { + Theme::parse(name, text).unwrap_or(Theme { + name: name.to_string(), + dark: fallback.dark, + tokens: fallback, + metrics: Metrics::standard(), + }) + }) + .collect() + } + + /// Reads a theme file. Errors name the keys at fault, so a theme author can fix them. + pub fn parse(fallback_name: &str, text: &str) -> Result { + // Notepad saves UTF-8 with a byte-order mark, which serde refuses at the first byte. + let text = text.trim_start_matches('\u{feff}'); + let raw: Raw = serde_json::from_str(text).map_err(|e| e.to_string())?; + let name = clean_name(if raw.name.trim().is_empty() { fallback_name } else { raw.name.trim() }); + if raw.schema != SCHEMA { + return Err(format!("{name}: theme schema {} is not {SCHEMA}", raw.schema)); + } + // `extends` names a theme that ships: the file then sets only what it changes. + let base = match raw.extends.as_deref() { + None => None, + Some(wanted) => match Theme::builtin().into_iter().find(|t| t.name == wanted) { + Some(found) => Some(found), + None => return Err(format!("{name}: extends {wanted}, which is not a built-in theme")), + }, + }; + let unknown: Vec<&str> = raw.colours.keys().map(String::as_str).filter(|k| !TOKENS.contains(k)).collect(); + if !unknown.is_empty() { + return Err(format!("{name}: unknown {}", unknown.join(", "))); + } + // Without a base, every colour and size must be here. + let missing: Vec<&str> = match &base { + Some(_) => Vec::new(), + None => TOKENS.iter().copied().filter(|t| !raw.colours.contains_key(*t)).collect(), + }; + if !missing.is_empty() { + return Err(format!("{name}: missing {}", missing.join(", "))); + } + let fallback = base.unwrap_or_else(|| Theme { + name: name.clone(), + dark: raw.dark.unwrap_or(false), + tokens: if raw.dark.unwrap_or(false) { Tokens::dark() } else { Tokens::light() }, + metrics: Metrics::standard(), + }); + let mut tokens = fallback.tokens; + for (key, value) in &raw.colours { + let colour = parse_colour(value).map_err(|e| format!("{name}: {key} {e}"))?; + if let Some(slot) = slot(&mut tokens, key) { + *slot = colour; + } + } + let dark = raw.dark.unwrap_or(fallback.dark); + let metrics = raw.metrics.unwrap_or(fallback.metrics).clamped(); + Ok(Theme { name, dark, tokens, metrics }) + } + + /// The theme as a file an author can edit and drop in the themes folder. + pub fn to_json(&self) -> Result { + let colours: BTreeMap = TOKENS.iter().map(|name| ((*name).to_string(), hex(colour(self, name)))).collect(); + let raw = + Raw { schema: SCHEMA, name: self.name.clone(), extends: None, dark: Some(self.dark), colours, metrics: Some(self.metrics) }; + serde_json::to_string_pretty(&raw).map_err(|e| format!("{}: {e}", self.name)) + } + + /// The built-in themes plus every readable theme in the user folder, and the errors for those + /// that do not load. + pub fn available() -> (Vec, Vec) { + Self::available_in(Self::user_dir().as_deref()) + } + + /// The same, from a named folder; a missing folder is not an error. + pub fn available_in(dir: Option<&std::path::Path>) -> (Vec, Vec) { + let mut themes = Theme::builtin(); + let mut errors = Vec::new(); + let Some(dir) = dir else { + return (themes, errors); + }; + let Ok(read) = std::fs::read_dir(dir) else { + return (themes, errors); + }; + let mut files: Vec = read.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "json")).collect(); + files.sort(); + for path in files { + let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); + // A huge file is not a theme, and reading it whole would cost the app the disk. + match std::fs::metadata(&path) { + Ok(meta) if meta.len() > MAX_THEME_BYTES => { + errors.push(format!("{}: larger than {MAX_THEME_BYTES} bytes", path.display())); + continue; + } + Ok(_) => {} + Err(e) => { + errors.push(format!("{}: {e}", path.display())); + continue; + } + } + match std::fs::read_to_string(&path) { + Ok(text) => match Theme::parse(&stem, &text) { + // A user file named as a built-in replaces it, so a name picks one theme. + Ok(theme) => match themes.iter_mut().find(|t| t.name == theme.name) { + Some(replaced) => *replaced = theme, + None => themes.push(theme), + }, + Err(e) => errors.push(format!("{}: {e}", path.display())), + }, + Err(e) => errors.push(format!("{}: {e}", path.display())), + } + } + (themes, errors) + } + + /// What the folder holds now. A different value means a file was added, removed or saved, so + /// the app can pick the change up without being told. + pub fn folder_signature(dir: Option<&std::path::Path>) -> u64 { + use std::hash::{Hash, Hasher}; + let Some(dir) = dir else { return 0 }; + let Ok(read) = std::fs::read_dir(dir) else { return 0 }; + let mut stamps: Vec<(String, u64, u128)> = read + .flatten() + .filter(|e| e.path().extension().is_some_and(|e| e == "json")) + .filter_map(|e| { + let path = e.path(); + let meta = e.metadata().ok()?; + let saved = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis(); + Some((path.file_name()?.to_string_lossy().into_owned(), meta.len(), saved)) + }) + .collect(); + stamps.sort(); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + stamps.hash(&mut hasher); + hasher.finish() + } + + /// `/themes`, where a user theme is read from. + pub fn user_dir() -> Option { + rustgis_engine::data::dirs::config_dir().map(|d| d.join("themes")) + } + + /// Writes the theme into the user folder, under its own name. + pub fn save_user(&self) -> Result { + let dir = Self::user_dir().ok_or("no settings folder")?; + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let stem: String = self.name.chars().map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect(); + let path = dir.join(format!("{}.json", stem.trim_matches('-'))); + let text = self.to_json()?; + std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?; + Ok(path) + } +} + +/// The mutable slot for one token name, so the file writer, the reader and the tests share a list. +fn slot<'a>(t: &'a mut Tokens, name: &str) -> Option<&'a mut Color32> { + Some(match name { + "header" => &mut t.header, + "ribbon" => &mut t.ribbon, + "tab_strip" => &mut t.tab_strip, + "canvas" => &mut t.canvas, + "pane" => &mut t.pane, + "pane_header" => &mut t.pane_header, + "border" => &mut t.border, + "border_strong" => &mut t.border_strong, + "text" => &mut t.text, + "text_dim" => &mut t.text_dim, + "text_disabled" => &mut t.text_disabled, + "icon" => &mut t.icon, + "hover" => &mut t.hover, + "pressed" => &mut t.pressed, + "checked" => &mut t.checked, + "accent" => &mut t.accent, + "accent_text" => &mut t.accent_text, + "on_accent" => &mut t.on_accent, + "input" => &mut t.input, + "input_border" => &mut t.input_border, + "group_label" => &mut t.group_label, + "status_bar" => &mut t.status_bar, + "selection" => &mut t.selection, + "menu" => &mut t.menu, + "shadow" => &mut t.shadow, + "green" => &mut t.green, + "red" => &mut t.red, + "amber" => &mut t.amber, + "context" => &mut t.context, + "context_tint" => &mut t.context_tint, + "control" => &mut t.control, + _ => return None, + }) +} + +/// One token of a theme by name. +pub fn colour(theme: &Theme, name: &str) -> Color32 { + let mut tokens = theme.tokens; + slot(&mut tokens, name).map_or(Color32::TRANSPARENT, |c| *c) +} + +/// `#RRGGBB`, or `#RRGGBBAA` where the alpha matters, as in a shadow. +fn hex(c: Color32) -> String { + let [r, g, b, a] = c.to_srgba_unmultiplied(); + if a == 255 { format!("#{r:02X}{g:02X}{b:02X}") } else { format!("#{r:02X}{g:02X}{b:02X}{a:02X}") } +} + +/// WCAG contrast ratio between two colours, 1.0 to 21.0. +pub fn contrast(a: Color32, b: Color32) -> f32 { + let lum = |c: Color32| { + let [r, g, b, _] = c.to_srgba_unmultiplied(); + let channel = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.03928 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) + }; + let (a, b) = (lum(a), lum(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +/// A name as the menu shows it: one line, no control characters, and at most [`MAX_NAME`] long. +fn clean_name(name: &str) -> String { + let kept: String = name.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(); + let kept = kept.trim(); + if kept.is_empty() { "Theme".to_string() } else { kept.to_string() } +} + +/// A colour from a theme file. Text that is not hexadecimal is refused rather than cut at a byte +/// boundary, which a non-ASCII character would be. +fn parse_colour(text: &str) -> Result { + let digits = text.strip_prefix('#').ok_or_else(|| format!("is not a #RRGGBB colour: {text}"))?; + let bad = || format!("is not a #RRGGBB or #RRGGBBAA colour: {text}"); + if !digits.is_ascii() { + return Err(bad()); + } + let pair = |at: usize| u8::from_str_radix(&digits[at..at + 2], 16).map_err(|_| bad()); + match digits.len() { + 6 => Ok(Color32::from_rgb(pair(0)?, pair(2)?, pair(4)?)), + 8 => Ok(Color32::from_rgba_unmultiplied(pair(0)?, pair(2)?, pair(4)?, pair(6)?)), + _ => Err(bad()), } } @@ -184,8 +571,10 @@ pub fn install_fonts( ctx.set_fonts(fonts); } -pub fn apply(ctx: &egui::Context, t: &Tokens) { +/// Puts a theme on the context: colours, widget states, spacing and text sizes. +pub fn apply(ctx: &egui::Context, t: &Tokens, m: &Metrics) { let mut v = if t.dark { Visuals::dark() } else { Visuals::light() }; + let corner = CornerRadius::same(m.corner_radius); v.panel_fill = t.pane; v.window_fill = t.menu; v.extreme_bg_color = t.input; @@ -198,38 +587,38 @@ pub fn apply(ctx: &egui::Context, t: &Tokens) { v.hyperlink_color = t.accent_text; v.widgets.noninteractive.bg_stroke = Stroke::new(1.0, t.border); v.widgets.noninteractive.fg_stroke = Stroke::new(1.0, t.text); - // Slider rails and checkbox wells use this fill; keep it visible on white. - v.widgets.inactive.bg_fill = if t.dark { Color32::from_rgb(0x3A, 0x42, 0x4D) } else { Color32::from_rgb(0xDD, 0xE3, 0xEA) }; + v.widgets.inactive.bg_fill = t.control; v.slider_trailing_fill = true; v.widgets.inactive.weak_bg_fill = t.input; v.widgets.inactive.bg_stroke = Stroke::new(1.0, t.input_border); v.widgets.inactive.fg_stroke = Stroke::new(1.0, t.text); - v.widgets.inactive.corner_radius = CornerRadius::same(5); + v.widgets.inactive.corner_radius = corner; v.widgets.hovered.bg_fill = t.hover; v.widgets.hovered.weak_bg_fill = t.hover; v.widgets.hovered.bg_stroke = Stroke::new(1.0, t.border_strong); v.widgets.hovered.fg_stroke = Stroke::new(1.0, t.text); - v.widgets.hovered.corner_radius = CornerRadius::same(5); + v.widgets.hovered.corner_radius = corner; v.widgets.active.bg_fill = t.pressed; v.widgets.active.weak_bg_fill = t.pressed; v.widgets.active.fg_stroke = Stroke::new(1.0, t.text); - v.widgets.active.corner_radius = CornerRadius::same(5); + v.widgets.active.corner_radius = corner; v.widgets.open.bg_fill = t.pressed; v.widgets.open.weak_bg_fill = t.pressed; v.popup_shadow = egui::Shadow { offset: [0, 6], blur: 18, spread: 0, color: t.shadow }; v.window_shadow = egui::Shadow { offset: [0, 10], blur: 28, spread: 0, color: t.shadow }; + ctx.data_mut(|d| d.insert_temp(tokens_id(), *t)); // Pin egui's theme to ours: the app decides when to follow the system (`dark_follows_system`). ctx.set_theme(if t.dark { egui::Theme::Dark } else { egui::Theme::Light }); ctx.set_visuals(v); ctx.global_style_mut(|s| { - s.spacing.item_spacing = egui::vec2(6.0, 5.0); - s.spacing.button_padding = egui::vec2(8.0, 3.0); - s.spacing.interact_size.y = 22.0; - s.text_styles.insert(egui::TextStyle::Body, regular(12.5)); - s.text_styles.insert(egui::TextStyle::Button, regular(12.5)); - s.text_styles.insert(egui::TextStyle::Small, regular(10.5)); - s.text_styles.insert(egui::TextStyle::Heading, semibold(17.0)); - s.text_styles.insert(egui::TextStyle::Monospace, FontId::monospace(12.0)); + s.spacing.item_spacing = egui::vec2(m.item_spacing[0], m.item_spacing[1]); + s.spacing.button_padding = egui::vec2(m.button_padding[0], m.button_padding[1]); + s.spacing.interact_size.y = m.row_height; + s.text_styles.insert(egui::TextStyle::Body, regular(m.body)); + s.text_styles.insert(egui::TextStyle::Button, regular(m.button_text)); + s.text_styles.insert(egui::TextStyle::Small, regular(m.small)); + s.text_styles.insert(egui::TextStyle::Heading, semibold(m.heading)); + s.text_styles.insert(egui::TextStyle::Monospace, FontId::monospace(m.mono)); }); } @@ -242,3 +631,252 @@ pub fn rgba(c: Color32) -> rustgis_engine::map::Rgba { let [r, g, b, a] = c.to_srgba_unmultiplied(); rustgis_engine::map::Rgba::new(r, g, b, a) } + +#[cfg(test)] +mod tests { + use super::*; + + fn light() -> Theme { + Theme::builtin().into_iter().find(|t| !t.dark).expect("a light theme ships") + } + + #[test] + fn the_built_in_files_match_the_code_tables() { + let builtin = Theme::builtin(); + for (name, want) in [("Light", Tokens::light()), ("Dark", Tokens::dark())] { + let theme = builtin.iter().find(|t| t.name == name).expect("the theme ships"); + assert_eq!(theme.dark, want.dark, "{name} brightness"); + for token in TOKENS { + let mut copy = want; + assert_eq!(colour(theme, token), *slot(&mut copy, token).expect("every token has a slot"), "{name} token {token}"); + } + assert_eq!(theme.metrics, Metrics::standard(), "{name} metrics"); + } + } + + #[test] + fn every_built_in_theme_round_trips_and_sets_every_token() { + for theme in Theme::builtin() { + assert_eq!(Theme::parse(&theme.name, &theme.to_json().expect("json")).ok().as_ref(), Some(&theme)); + for token in TOKENS { + assert!(colour(&theme, token).a() > 0, "{} leaves {token} invisible", theme.name); + } + } + } + + #[test] + fn every_built_in_theme_reads_its_text_on_its_surfaces() { + for theme in Theme::builtin() { + let ratio = contrast(theme.tokens.text, theme.tokens.pane); + assert!(ratio >= 7.0, "{}: text on a pane is {ratio:.1}:1, below the AAA floor of 7:1", theme.name); + let ratio = contrast(theme.tokens.text, theme.tokens.ribbon); + assert!(ratio >= 7.0, "{}: text on the ribbon is {ratio:.1}:1", theme.name); + } + } + + #[test] + fn a_file_saved_with_a_byte_order_mark_loads() { + let text = format!("\u{feff}{}", light().to_json().expect("json")); + assert_eq!(Theme::parse("Light", &text).expect("it loads").name, "Light"); + } + + #[test] + fn a_file_that_extends_a_built_in_sets_only_what_it_changes() { + let text = r##"{"schema": 1, "name": "Mine", "extends": "Dark", "colours": {"accent": "#F2A65A"}}"##; + let theme = Theme::parse("mine", text).expect("it parses"); + assert_eq!(theme.name, "Mine"); + assert!(theme.dark, "it takes the brightness of the theme it extends"); + assert_eq!(theme.tokens.accent, Color32::from_rgb(0xF2, 0xA6, 0x5A)); + assert_eq!(theme.tokens.pane, Tokens::dark().pane, "the rest comes from Dark"); + assert_eq!(theme.metrics, Metrics::standard(), "sizes too"); + } + + #[test] + fn extends_names_a_theme_that_ships() { + let text = r#"{"schema": 1, "name": "Mine", "extends": "Sunset"}"#; + let err = Theme::parse("mine", text).expect_err("nothing called Sunset ships"); + assert!(err.contains("extends Sunset"), "{err}"); + } + + #[test] + fn the_folder_signature_follows_a_saved_file() { + let dir = theme_folder("rustgis-theme-signature-test", &[("mine.json", "{}")]); + let before = Theme::folder_signature(Some(&dir)); + std::fs::write(dir.join("mine.json"), "{\"schema\": 1}").expect("the file"); + assert_ne!(Theme::folder_signature(Some(&dir)), before, "a saved file is noticed"); + assert_eq!(Theme::folder_signature(None), 0, "no folder never changes"); + } + + #[test] + fn a_missing_token_is_named() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["colours"].as_object_mut().expect("colours").remove("accent"); + let err = Theme::parse("Mine", &json.to_string()).expect_err("a missing token is refused"); + assert!(err.contains("missing accent"), "{err}"); + } + + #[test] + fn an_unknown_token_is_named() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["colours"].as_object_mut().expect("colours").insert("acccent".into(), "#FF0000".into()); + let err = Theme::parse("Mine", &json.to_string()).expect_err("an unknown token is refused"); + assert!(err.contains("unknown acccent"), "{err}"); + } + + #[test] + fn a_bad_colour_names_the_token() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["colours"]["accent"] = "blue".into(); + let err = Theme::parse("Mine", &json.to_string()).expect_err("a bad colour is refused"); + assert!(err.contains("accent is not a #RRGGBB"), "{err}"); + } + + #[test] + fn a_newer_schema_is_refused_by_number() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["schema"] = 9.into(); + let err = Theme::parse("Mine", &json.to_string()).expect_err("another schema is refused"); + assert!(err.contains("schema 9 is not 1"), "{err}"); + } + + #[test] + fn a_file_round_trips_with_its_alpha() { + let theme = light(); + let back = Theme::parse("light", &theme.to_json().expect("json")).expect("its own file parses"); + assert_eq!(back, theme); + assert_eq!(hex(theme.tokens.shadow), "#0000001C", "the shadow keeps its alpha"); + } + + #[test] + fn a_nameless_file_takes_its_file_name() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["name"] = " ".into(); + let theme = Theme::parse("sunset", &json.to_string()).expect("it parses"); + assert_eq!(theme.name, "sunset"); + } + + #[test] + fn every_token_name_has_its_own_slot() { + let mut tokens = Tokens::light(); + for (i, name) in TOKENS.iter().enumerate() { + *slot(&mut tokens, name).expect("a slot") = Color32::from_rgb(i as u8, 0, 0); + } + for (i, name) in TOKENS.iter().enumerate() { + let mut copy = tokens; + assert_eq!(slot(&mut copy, name).copied(), Some(Color32::from_rgb(i as u8, 0, 0)), "{name}"); + } + } + + /// A temporary folder of theme files, fresh on every call. + fn theme_folder(name: &str, files: &[(&str, &str)]) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(name); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("the folder"); + for (file, text) in files { + std::fs::write(dir.join(file), text).expect("the file"); + } + dir + } + + #[test] + fn a_theme_in_the_user_folder_is_offered() { + let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); + let dir = theme_folder("rustgis-theme-folder-test", &[("mine.json", &mine)]); + let (found, errors) = Theme::available_in(Some(&dir)); + assert!(errors.is_empty(), "{errors:?}"); + assert!(found.iter().any(|t| t.name == "Mine"), "the folder theme is offered"); + assert!(found.iter().any(|t| t.name == "Light"), "the built-in themes stay"); + } + + #[test] + fn a_broken_file_is_reported_and_the_others_load() { + let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); + let dir = theme_folder("rustgis-theme-broken-test", &[("mine.json", &mine), ("half.json", "{\"schema\": 1}")]); + let (found, errors) = Theme::available_in(Some(&dir)); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert!(errors[0].contains("half.json"), "{errors:?}"); + assert!(found.iter().any(|t| t.name == "Mine"), "the good file still loads"); + } + + #[test] + fn a_user_theme_replaces_the_built_in_of_the_same_name() { + // A colour reworked in the user's folder is offered once, under the built-in's name. + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["colours"]["accent"] = "#123456".into(); + let dir = theme_folder("rustgis-theme-replace-test", &[("light.json", &json.to_string())]); + let (found, errors) = Theme::available_in(Some(&dir)); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!(found.iter().filter(|t| t.name == "Light").count(), 1, "one Light is offered"); + let light = found.iter().find(|t| t.name == "Light").expect("Light is offered"); + assert_eq!(light.tokens.accent, Color32::from_rgb(0x12, 0x34, 0x56), "the user file wins"); + } + + #[test] + fn apply_puts_the_theme_on_the_context() { + let ctx = egui::Context::default(); + let theme = light(); + apply(&ctx, &theme.tokens, &theme.metrics); + let style = ctx.global_style(); + assert_eq!(style.visuals.panel_fill, theme.tokens.pane); + assert_eq!(style.visuals.widgets.inactive.bg_fill, theme.tokens.control); + assert_eq!(style.spacing.item_spacing, egui::vec2(6.0, 5.0)); + assert_eq!(style.spacing.interact_size.y, 22.0); + assert_eq!(style.text_styles[&egui::TextStyle::Body], regular(12.5)); + assert_eq!(style.text_styles[&egui::TextStyle::Heading], semibold(17.0)); + assert_eq!(Tokens::get(&ctx), theme.tokens, "widgets read the applied colours back"); + } + + #[test] + fn metrics_are_held_within_what_the_interface_draws() { + // A theme file is input from outside: sizes are held to ranges a window can draw. + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["metrics"]["body"] = serde_json::json!(1e9); + json["metrics"]["small"] = serde_json::json!(-5.0); + json["metrics"]["corner_radius"] = serde_json::json!(250); + json["metrics"]["item_spacing"] = serde_json::json!([1e9, -1e9]); + let theme = Theme::parse("Mine", &json.to_string()).expect("it parses"); + assert_eq!(theme.metrics.body, 40.0, "a huge size is held to the largest drawn"); + assert_eq!(theme.metrics.small, 5.0, "a negative size is held to the smallest drawn"); + assert_eq!(theme.metrics.corner_radius, 32); + assert_eq!(theme.metrics.item_spacing, [40.0, 0.0]); + assert_eq!(theme.metrics.heading, 17.0, "what the file does not set stays standard"); + } + + #[test] + fn a_colour_that_is_not_hexadecimal_is_refused_without_panicking() { + // `#€€` is six bytes, so the length alone would let it through to a byte cut inside a + // character, which panics. + for bad in ["#€€", "#€€€", "#€€€€", "#12345", "#1234567", "123456", "#GGGGGG", "#12345€"] { + assert!(parse_colour(bad).is_err(), "{bad:?} is refused"); + } + assert_eq!(parse_colour("#123456"), Ok(Color32::from_rgb(0x12, 0x34, 0x56))); + } + + #[test] + fn a_name_is_one_short_line() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["name"] = serde_json::json!("Mine\nSecond line\twith a tab"); + let theme = Theme::parse("Mine", &json.to_string()).expect("it parses"); + assert_eq!(theme.name, "MineSecond linewith a tab", "a newline would break the button"); + + json["name"] = serde_json::json!("N".repeat(200)); + let theme = Theme::parse("Mine", &json.to_string()).expect("it parses"); + assert_eq!(theme.name.chars().count(), MAX_NAME, "a long name is cut to fit"); + + json["name"] = serde_json::json!(" "); + let theme = Theme::parse("file-name", &json.to_string()).expect("it parses"); + assert_eq!(theme.name, "file-name", "a nameless file takes its own name"); + } + + #[test] + fn a_file_too_large_to_be_a_theme_is_reported_not_read() { + let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); + let dir = theme_folder("rustgis-theme-large-test", &[("mine.json", &mine)]); + let huge = "x".repeat(MAX_THEME_BYTES as usize + 1); + std::fs::write(dir.join("huge.json"), huge).expect("the file"); + let (found, errors) = Theme::available_in(Some(&dir)); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert!(errors[0].contains("huge.json"), "{errors:?}"); + assert!(found.iter().any(|t| t.name == "Mine"), "the good file still loads"); + } +} diff --git a/crates/ui-egui/themes/dark.json b/crates/ui-egui/themes/dark.json new file mode 100644 index 0000000000..e88601908e --- /dev/null +++ b/crates/ui-egui/themes/dark.json @@ -0,0 +1,55 @@ +{ + "schema": 1, + "name": "Dark", + "dark": true, + "colours": { + "header": "#171B21", + "ribbon": "#242931", + "tab_strip": "#171B21", + "canvas": "#12151A", + "pane": "#1E232A", + "pane_header": "#242931", + "border": "#343B45", + "border_strong": "#48515D", + "text": "#E6EAEF", + "text_dim": "#9AA4B1", + "text_disabled": "#5C6571", + "icon": "#C9D1DB", + "hover": "#2F3744", + "pressed": "#2A3D5E", + "checked": "#283B5C", + "accent": "#5B8DF6", + "accent_text": "#8AAFFA", + "on_accent": "#FFFFFF", + "input": "#15191F", + "input_border": "#444D59", + "group_label": "#8C96A3", + "status_bar": "#1A1E24", + "selection": "#26406E", + "menu": "#262C34", + "shadow": "#0000006E", + "green": "#3FC282", + "red": "#F06A6A", + "amber": "#F2B848", + "context": "#2CC2AE", + "context_tint": "#1B3331", + "control": "#3A424D" + }, + "metrics": { + "item_spacing": [ + 6.0, + 5.0 + ], + "button_padding": [ + 8.0, + 3.0 + ], + "row_height": 22.0, + "corner_radius": 5, + "body": 12.5, + "button_text": 12.5, + "small": 10.5, + "heading": 17.0, + "mono": 12.0 + } +} diff --git a/crates/ui-egui/themes/light.json b/crates/ui-egui/themes/light.json new file mode 100644 index 0000000000..63f3ef56bf --- /dev/null +++ b/crates/ui-egui/themes/light.json @@ -0,0 +1,55 @@ +{ + "schema": 1, + "name": "Light", + "dark": false, + "colours": { + "header": "#EEF1F5", + "ribbon": "#FFFFFF", + "tab_strip": "#EEF1F5", + "canvas": "#E4E8EE", + "pane": "#FBFCFD", + "pane_header": "#F3F5F8", + "border": "#DDE2E9", + "border_strong": "#C3CAD4", + "text": "#1F2630", + "text_dim": "#5E6977", + "text_disabled": "#A9B1BC", + "icon": "#3A4554", + "hover": "#E9F0FB", + "pressed": "#D4E2F8", + "checked": "#DCE8FA", + "accent": "#2563EB", + "accent_text": "#1D4EC4", + "on_accent": "#FFFFFF", + "input": "#FFFFFF", + "input_border": "#C6CDD7", + "group_label": "#707A88", + "status_bar": "#F3F5F8", + "selection": "#CFE0FC", + "menu": "#FFFFFF", + "shadow": "#0000001C", + "green": "#169A5A", + "red": "#D13C3C", + "amber": "#E59E1A", + "context": "#0E9384", + "context_tint": "#E3F5F2", + "control": "#DDE3EA" + }, + "metrics": { + "item_spacing": [ + 6.0, + 5.0 + ], + "button_padding": [ + 8.0, + 3.0 + ], + "row_height": 22.0, + "corner_radius": 5, + "body": 12.5, + "button_text": 12.5, + "small": 10.5, + "heading": 17.0, + "mono": 12.0 + } +} diff --git a/docs/index.md b/docs/index.md index db75d30ff2..fa5bad7a57 100644 --- a/docs/index.md +++ b/docs/index.md @@ -70,6 +70,13 @@ Map operations are commands you can script from the command line, Python or the with sandboxed WebAssembly or desktop-only process runtimes. [Command Line](cli.md) · [Python](python.md) · [MCP](mcp.md) · [Plugins](plugins.md) +- **Themed** + + Light and Dark ship. Write a theme as a JSON file of colours, spacing and text sizes, drop + it in the themes folder and pick it in Settings, or scale the whole interface from 80% to + 200%. + [Themes](themes.md) + ## A tour diff --git a/docs/themes.md b/docs/themes.md new file mode 100644 index 0000000000..c704aee8fd --- /dev/null +++ b/docs/themes.md @@ -0,0 +1,148 @@ +# Interface themes + +A theme is a JSON file that sets every colour the interface draws, plus its spacing and text +sizes. Light and Dark ship with RustGIS; users add their own to the themes folder. The map is +drawn by the renderer, which takes its light or dark defaults from the theme's `dark` flag. + +## Where themes live + +| Theme | File | +|---|---| +| Built in | `crates/ui-egui/themes/*.json`, compiled into the app | +| User | `/themes/*.json`, read at startup, when a file changes, and by Reload Themes | + +The config folder is `%APPDATA%\RustGIS` on Windows, `~/Library/Application Support/RustGIS` on +macOS and `$XDG_CONFIG_HOME/rustgis` elsewhere. `RUSTGIS_CONFIG_DIR` overrides it. + +A user file whose `name` matches a built-in replaces it: a reworked Light sits in the folder as +`light.json`, and the menu lists one Light. + +## Picking one + +Settings › Theme lists Follow the System and every theme that loaded. A choice is applied at once +and saved for the next start; 80% to 200% of interface scale sits beside it. + +The quickest way to begin is to take a theme file from anywhere else with **Load a Theme from +File…**, which keeps a copy in the themes folder: edit that copy and the app follows it. A file +that does not load is listed in red at the bottom of the same menu, with the token at fault. + +A saved file is picked up within a second, without pressing **Reload Themes**: the app watches the +folder's files while it runs. A file that was in use and stops loading leaves the window on the +nearest built-in until it loads again, with the reason listed in the menu. + +## A short theme + +`extends` names a theme that ships, and the file then sets only what it changes: + +```json +{ + "schema": 1, + "name": "Sunset", + "extends": "Dark", + "colours": { + "pane": "#241710", + "ribbon": "#35221A", + "text": "#FFE7D1", + "accent": "#F2A65A", + "on_accent": "#2A1B12" + } +} +``` + +Colours, brightness and sizes it leaves out come from the theme it extends. Without `extends` +every colour is required, as in the full file below: that is the reference, a short file is the +better start. + +## The file + +```json +{ + "schema": 1, + "name": "Sunset", + "dark": true, + "colours": { + "header": "#2A1B12", + "ribbon": "#35221A", + "tab_strip": "#2A1B12", + "canvas": "#1A1009", + "pane": "#241710", + "pane_header": "#35221A", + "border": "#5A3B2A", + "border_strong": "#7A5138", + "text": "#FFE7D1", + "text_dim": "#D3A985", + "text_disabled": "#8A6B52", + "icon": "#F5D3B3", + "hover": "#4A2F20", + "pressed": "#6B3F26", + "checked": "#5C3A24", + "accent": "#F2A65A", + "accent_text": "#FFC98B", + "on_accent": "#2A1B12", + "input": "#1F130D", + "input_border": "#6B4632", + "group_label": "#C99871", + "status_bar": "#20140E", + "selection": "#7A4A2B", + "menu": "#2E1D14", + "shadow": "#0000006E", + "green": "#7FC29B", + "red": "#EF7A6A", + "amber": "#F2C14E", + "context": "#4FB3A5", + "context_tint": "#1E3C39", + "control": "#4A3020" + }, + "metrics": { + "item_spacing": [7.0, 6.0], + "button_padding": [10.0, 4.0], + "row_height": 24.0, + "corner_radius": 8, + "body": 13.0, + "button_text": 13.0, + "small": 11.0, + "heading": 18.0, + "mono": 12.5 + } +} +``` + +Every colour is required unless the file extends a theme, and an unknown token stops the file from +loading with the token named. Colours are `#RRGGBB`, or `#RRGGBBAA` where alpha matters, as in +`shadow`. `schema` is 1; a file written for a later build is refused by number. + +`dark` is the brightness the theme reports to egui, which sets its default widget shapes and the +map's light or dark defaults. It is not inferred from the colours. + +`metrics` are in points: item spacing, button padding, row height, corner radius and text sizes, +required unless the file extends a theme. Sizes are held to what a window can draw, and a file over +64 KB is not read. + +## Tokens + +Surfaces: `header`, `ribbon`, `tab_strip`, `canvas`, `pane`, `pane_header`, `menu`, `status_bar`, +`input`. + +Lines and text: `border`, `border_strong`, `input_border`, `text`, `text_dim`, `text_disabled`, +`icon`, `group_label`, `on_accent`. + +Interaction: `hover`, `pressed`, `checked`, `selection`, `control` (slider rails and checkbox +wells, which must stay visible on white). + +Meaning: `accent`, `accent_text`, `context`, `context_tint`, `green`, `red`, `amber`, `shadow`. + +## Commands + +| Command | Effect | +|---|---| +| `ui.themeFile` with `name` | Uses that theme; no name follows the system again | +| `ui.themeLoad` | Opens a theme file from anywhere, keeps it in the themes folder and uses it | +| `ui.theme` with `dark` | Switches brightness and leaves the theme list | +| `ui.scale` with `factor` | Interface scale, held between 0.75 and 2.0 | +| `ui.themeReload` | Reads the themes folder again | + +## What a theme cannot change + +The map is drawn by the renderer, so a theme's colours stop at the map view; `canvas` is the +surface behind it. Icon shapes stay as drawn, taking their ink and accent from the theme. Plugin +panels use the host's widgets and follow it. diff --git a/zensical.toml b/zensical.toml index d448dcbf1e..c44a3fe38e 100644 --- a/zensical.toml +++ b/zensical.toml @@ -38,6 +38,7 @@ nav = [ { "Python" = "python.md" }, { "MCP Server" = "mcp.md" }, { "Plugins" = "plugins.md" }, + { "Themes" = "themes.md" }, { "Languages" = "i18n.md" }, { "Architecture" = "architecture.md" }, { "Contributing" = "contributing.md" }, From 7c2b0907d5d78f105a12f5b92ec66eda79dc333d Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 20:26:07 +0100 Subject: [PATCH 02/28] docs(ui): the theme reference is the shipped Light file, comments kept to facts --- crates/ui-egui/src/lib.rs | 18 ++--- crates/ui-egui/src/ribbon.rs | 9 +-- crates/ui-egui/src/theme.rs | 53 +++++---------- docs/themes.md | 128 +++++++++++++++++------------------ 4 files changed, 89 insertions(+), 119 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index adaac1de05..2961fa8884 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -919,7 +919,6 @@ pub struct RustGisApp { pub themes: Vec, /// The theme files that did not load, with the reason. pub theme_errors: Vec, - /// What the themes folder held when it was last read, and when it was last looked at. themes_stamp: u64, themes_checked: f64, sent_title: String, @@ -1196,7 +1195,7 @@ impl RustGisApp { let list = |s: Option| -> Vec { s.map(|v| v.split(',').map(str::trim).filter(|x| !x.is_empty()).map(String::from).collect()).unwrap_or_default() }; - // A saved theme is only found once the folder has been read. + // take_saved_look finds a saved theme only once the folder is read. self.load_themes(); self.take_saved_look(); self.ui.hidden_tabs = ribbon::current_hidden_tabs(list(self.services.load_pref.as_ref().and_then(|load| load("hidden_tabs")))); @@ -1634,19 +1633,17 @@ impl RustGisApp { } } - /// Reads the built-in themes and the user's themes folder, keeping the files that failed. fn load_themes(&mut self) { let (themes, errors) = theme::Theme::available(); self.themes = themes; self.theme_errors = errors; self.themes_stamp = theme::Theme::folder_signature(theme::Theme::user_dir().as_deref()); - // The files may read differently: put the theme in force on again. + // Reset so a file that reads differently is applied again on the next frame. self.applied_theme = None; } /// Reads the folder again when a file in it was added, removed or saved, at most once a second. fn refresh_themes(&mut self, ctx: &egui::Context) { - // Only someone with a themes folder pays for this, and they are editing one. let Some(dir) = theme::Theme::user_dir().filter(|d| d.is_dir()) else { return }; ctx.request_repaint_after(web_time::Duration::from_secs(1)); let now = ctx.input(|i| i.time); @@ -1674,8 +1671,7 @@ impl RustGisApp { }) } - /// Takes the saved look from the preferences: the theme by name, else the brightness, and the - /// scale. A name that no longer loads leaves the look following the system. + /// A saved theme name wins; one that no longer loads follows the system. fn take_saved_look(&mut self) { let pref = |app: &Self, key: &str| -> Option { app.services.load_pref.as_ref().and_then(|load| load(key)).filter(|v| !v.is_empty()) @@ -1695,7 +1691,6 @@ impl RustGisApp { self.ui.interface_scale = scale.map_or(1.0, theme::clamp_scale); } - /// Uses a theme from the list, and saves the choice. fn use_theme(&mut self, name: &str) -> Result<(), String> { let Some(picked) = self.themes.iter().find(|t| t.name == name).cloned() else { return Err(i18n::fmt("No theme is named {name}.", &[("name", name)])); @@ -1710,7 +1705,6 @@ impl RustGisApp { Ok(()) } - /// Reads a theme file from anywhere, keeps a copy in the themes folder and uses it. fn load_theme_file(&mut self, path: &std::path::Path) -> Result<(), String> { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); @@ -2390,7 +2384,6 @@ impl RustGisApp { self.use_theme(&name)?; } } - // Opens a theme file from anywhere, keeps it in the themes folder and uses it. "ui.themeLoad" => { let Some(path) = dialogs::pick_open(&["json"], tl!("A theme file")) else { return Ok(Value::Null) }; self.load_theme_file(std::path::Path::new(&path))?; @@ -2402,7 +2395,6 @@ impl RustGisApp { save("ui_scale", &format!("{:.2}", self.ui.interface_scale)); } } - // Reads the themes folder again, after a file was added or fixed. "ui.themeReload" => self.load_themes(), "ui.measurementUnits" => { let imperial = match p.get("units") { @@ -4716,8 +4708,7 @@ mod look_tests { use super::RustGisApp; use crate::theme; - /// The app with a preferences store that answers these keys only, and a theme no folder ships, - /// so the test does not depend on the machine. + /// App whose preferences answer only these keys, with a theme no folder ships. fn app_with(prefs: &'static [(&'static str, &'static str)]) -> RustGisApp { let mut app = RustGisApp::with_sample(); app.themes.push(theme::Theme { @@ -4751,7 +4742,6 @@ mod look_tests { assert_eq!(app.ui.interface_scale, 1.0, "no scale saved is the normal one"); } - /// What a theme choice writes to the preferences. fn saved_by(app: &mut RustGisApp) -> std::sync::Arc>> { let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); let sink = log.clone(); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index b29f22b4d3..d527cfe741 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3440,8 +3440,7 @@ fn plugin_tab(app: &mut RustGisApp, ui: &mut Ui, plugin: &str) { } } -/// The Settings tab: theme and scale, ribbon customization, language, start-up and (on the -/// desktop) autosave. +/// The Settings tab: theme, scale, customization, language, start-up and autosave. fn settings_tab(app: &mut RustGisApp, ui: &mut Ui) { group(ui, "Theme", |ui| { theme_menu(app, ui); @@ -3503,7 +3502,6 @@ fn autosave_menu(app: &mut RustGisApp, ui: &mut Ui) { }); } -/// Settings › Theme: the built-in themes and every theme file that loads, plus the interface scale. fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { let current = if !app.ui.theme_name.is_empty() { app.ui.theme_name.clone() @@ -3544,7 +3542,6 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { theme_action(app, "ui.themeLoad", Value::Null); ui.close(); } - // After a file is added or fixed by hand: the list is read at startup otherwise. if ui.add(egui::Button::selectable(false, tl!("Reload Themes"))).clicked() { let _ = app.run("ui.themeReload", Value::Null); ui.close(); @@ -3561,14 +3558,14 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { ); } -/// Runs a menu action, telling the user what went wrong rather than nothing happening. +/// A failed action is notified, not swallowed. fn theme_action(app: &mut RustGisApp, id: &str, params: Value) { if let Err(e) = app.run(id, params) { app.session.notify(e, true); } } -/// Settings › Theme › Interface Scale: the whole interface, as egui's zoom factor. +/// Interface scale, as egui's zoom factor. fn scale_menu(app: &mut RustGisApp, ui: &mut Ui) { let current = format!("{}%", (app.ui.interface_scale * 100.0).round() as i32); let label = format!("{}\n{current}", tl!("Interface Scale")); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 653c28aee7..6b40c897ba 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -12,13 +12,13 @@ pub const BRAND_DARK: Color32 = Color32::from_rgb(0x96, 0x3A, 0x22); /// Contextual tab group colour (Feature Layer, Labeling, Data). pub const CONTEXT: Color32 = Color32::from_rgb(0x0E, 0x93, 0x84); -/// The theme file format this build reads. +/// The only schema this build reads. pub const SCHEMA: u32 = 1; -/// The most a theme file may be: a few hundred colours, not a disk to read whole. +/// A larger file is refused before it is read. pub const MAX_THEME_BYTES: u64 = 64 * 1024; -/// The longest theme name the menu shows: the ribbon has room for one line of it. +/// One ribbon line fits; a longer name is cut to it. const MAX_NAME: usize = 48; /// Every colour a theme file must set. A theme that omits one is refused, and the error names it. @@ -169,19 +169,18 @@ impl Tokens { } } - /// The theme in force, which the app puts on the context when it applies one. + /// Falls back to the brightness when no theme was applied to the context. pub fn get(ctx: &egui::Context) -> Tokens { ctx.data(|d| d.get_temp::(tokens_id())) .unwrap_or_else(|| if ctx.global_style().visuals.dark_mode { Tokens::dark() } else { Tokens::light() }) } } -/// Where the applied colours are kept, so every widget reads the theme that is in force. +/// egui temp data key that lets every widget read the applied colours. fn tokens_id() -> egui::Id { egui::Id::unique("rustgis.theme.tokens") } -/// Spacing, corner radius and text sizes a theme sets, in points. #[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Metrics { @@ -211,8 +210,7 @@ impl Metrics { } } - /// These metrics within the ranges the interface can draw: a theme file is input from outside - /// the app, so an out-of-range number is held to the nearest end, a non-number takes the standard. + /// Held to what a window draws; a value that is not a number takes the standard. pub fn clamped(self) -> Self { let fit = |v: f32, lo: f32, hi: f32, otherwise: f32| if v.is_finite() { v.clamp(lo, hi) } else { otherwise }; let std = Metrics::standard(); @@ -241,7 +239,6 @@ pub fn clamp_scale(scale: f32) -> f32 { if scale.is_finite() { scale.clamp(0.75, 2.0) } else { 1.0 } } -/// A theme: named colours plus metrics, from a built-in file or a user theme file. #[derive(Clone, Debug, PartialEq)] pub struct Theme { pub name: String, @@ -267,8 +264,7 @@ struct Raw { } impl Theme { - /// The themes that ship with the app, from `themes/*.json` beside this crate. A file that does - /// not load falls back to the code tables; `the_built_in_files_match_the_code_tables` catches it. + /// `themes/*.json` beside the crate; an unreadable file falls back to the code tables. pub fn builtin() -> Vec { [("Light", include_str!("../themes/light.json"), Tokens::light()), ("Dark", include_str!("../themes/dark.json"), Tokens::dark())] .into_iter() @@ -283,7 +279,7 @@ impl Theme { .collect() } - /// Reads a theme file. Errors name the keys at fault, so a theme author can fix them. + /// A refused file names the key at fault. pub fn parse(fallback_name: &str, text: &str) -> Result { // Notepad saves UTF-8 with a byte-order mark, which serde refuses at the first byte. let text = text.trim_start_matches('\u{feff}'); @@ -292,7 +288,6 @@ impl Theme { if raw.schema != SCHEMA { return Err(format!("{name}: theme schema {} is not {SCHEMA}", raw.schema)); } - // `extends` names a theme that ships: the file then sets only what it changes. let base = match raw.extends.as_deref() { None => None, Some(wanted) => match Theme::builtin().into_iter().find(|t| t.name == wanted) { @@ -304,7 +299,6 @@ impl Theme { if !unknown.is_empty() { return Err(format!("{name}: unknown {}", unknown.join(", "))); } - // Without a base, every colour and size must be here. let missing: Vec<&str> = match &base { Some(_) => Vec::new(), None => TOKENS.iter().copied().filter(|t| !raw.colours.contains_key(*t)).collect(), @@ -330,7 +324,6 @@ impl Theme { Ok(Theme { name, dark, tokens, metrics }) } - /// The theme as a file an author can edit and drop in the themes folder. pub fn to_json(&self) -> Result { let colours: BTreeMap = TOKENS.iter().map(|name| ((*name).to_string(), hex(colour(self, name)))).collect(); let raw = @@ -338,8 +331,7 @@ impl Theme { serde_json::to_string_pretty(&raw).map_err(|e| format!("{}: {e}", self.name)) } - /// The built-in themes plus every readable theme in the user folder, and the errors for those - /// that do not load. + /// Built-in themes plus the user folder's readable files; failures are returned apart. pub fn available() -> (Vec, Vec) { Self::available_in(Self::user_dir().as_deref()) } @@ -358,7 +350,6 @@ impl Theme { files.sort(); for path in files { let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); - // A huge file is not a theme, and reading it whole would cost the app the disk. match std::fs::metadata(&path) { Ok(meta) if meta.len() > MAX_THEME_BYTES => { errors.push(format!("{}: larger than {MAX_THEME_BYTES} bytes", path.display())); @@ -385,8 +376,7 @@ impl Theme { (themes, errors) } - /// What the folder holds now. A different value means a file was added, removed or saved, so - /// the app can pick the change up without being told. + /// Hash of each file's name, size and mtime; any change to the folder changes it. pub fn folder_signature(dir: Option<&std::path::Path>) -> u64 { use std::hash::{Hash, Hasher}; let Some(dir) = dir else { return 0 }; @@ -412,7 +402,7 @@ impl Theme { rustgis_engine::data::dirs::config_dir().map(|d| d.join("themes")) } - /// Writes the theme into the user folder, under its own name. + /// The file name is the theme name with each non-alphanumeric character as `-`. pub fn save_user(&self) -> Result { let dir = Self::user_dir().ok_or("no settings folder")?; std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; @@ -462,7 +452,6 @@ fn slot<'a>(t: &'a mut Tokens, name: &str) -> Option<&'a mut Color32> { }) } -/// One token of a theme by name. pub fn colour(theme: &Theme, name: &str) -> Color32 { let mut tokens = theme.tokens; slot(&mut tokens, name).map_or(Color32::TRANSPARENT, |c| *c) @@ -495,8 +484,7 @@ fn clean_name(name: &str) -> String { if kept.is_empty() { "Theme".to_string() } else { kept.to_string() } } -/// A colour from a theme file. Text that is not hexadecimal is refused rather than cut at a byte -/// boundary, which a non-ASCII character would be. +/// A non-ASCII colour is refused before the byte cut, which would land inside a character. fn parse_colour(text: &str) -> Result { let digits = text.strip_prefix('#').ok_or_else(|| format!("is not a #RRGGBB colour: {text}"))?; let bad = || format!("is not a #RRGGBB or #RRGGBBAA colour: {text}"); @@ -571,7 +559,6 @@ pub fn install_fonts( ctx.set_fonts(fonts); } -/// Puts a theme on the context: colours, widget states, spacing and text sizes. pub fn apply(ctx: &egui::Context, t: &Tokens, m: &Metrics) { let mut v = if t.dark { Visuals::dark() } else { Visuals::light() }; let corner = CornerRadius::same(m.corner_radius); @@ -693,9 +680,9 @@ mod tests { #[test] fn extends_names_a_theme_that_ships() { - let text = r#"{"schema": 1, "name": "Mine", "extends": "Sunset"}"#; - let err = Theme::parse("mine", text).expect_err("nothing called Sunset ships"); - assert!(err.contains("extends Sunset"), "{err}"); + let text = r#"{"schema": 1, "name": "Mine", "extends": "Gone"}"#; + let err = Theme::parse("mine", text).expect_err("no theme called Gone ships"); + assert!(err.contains("extends Gone"), "{err}"); } #[test] @@ -751,8 +738,8 @@ mod tests { fn a_nameless_file_takes_its_file_name() { let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); json["name"] = " ".into(); - let theme = Theme::parse("sunset", &json.to_string()).expect("it parses"); - assert_eq!(theme.name, "sunset"); + let theme = Theme::parse("my-theme", &json.to_string()).expect("it parses"); + assert_eq!(theme.name, "my-theme"); } #[test] @@ -767,7 +754,6 @@ mod tests { } } - /// A temporary folder of theme files, fresh on every call. fn theme_folder(name: &str, files: &[(&str, &str)]) -> std::path::PathBuf { let dir = std::env::temp_dir().join(name); let _ = std::fs::remove_dir_all(&dir); @@ -800,7 +786,6 @@ mod tests { #[test] fn a_user_theme_replaces_the_built_in_of_the_same_name() { - // A colour reworked in the user's folder is offered once, under the built-in's name. let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); json["colours"]["accent"] = "#123456".into(); let dir = theme_folder("rustgis-theme-replace-test", &[("light.json", &json.to_string())]); @@ -828,7 +813,6 @@ mod tests { #[test] fn metrics_are_held_within_what_the_interface_draws() { - // A theme file is input from outside: sizes are held to ranges a window can draw. let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); json["metrics"]["body"] = serde_json::json!(1e9); json["metrics"]["small"] = serde_json::json!(-5.0); @@ -844,8 +828,7 @@ mod tests { #[test] fn a_colour_that_is_not_hexadecimal_is_refused_without_panicking() { - // `#€€` is six bytes, so the length alone would let it through to a byte cut inside a - // character, which panics. + // `#€€` is six bytes, so a byte cut would land inside a character and panic. for bad in ["#€€", "#€€€", "#€€€€", "#12345", "#1234567", "123456", "#GGGGGG", "#12345€"] { assert!(parse_colour(bad).is_err(), "{bad:?} is refused"); } diff --git a/docs/themes.md b/docs/themes.md index c704aee8fd..1fff479129 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -14,21 +14,21 @@ drawn by the renderer, which takes its light or dark defaults from the theme's ` The config folder is `%APPDATA%\RustGIS` on Windows, `~/Library/Application Support/RustGIS` on macOS and `$XDG_CONFIG_HOME/rustgis` elsewhere. `RUSTGIS_CONFIG_DIR` overrides it. -A user file whose `name` matches a built-in replaces it: a reworked Light sits in the folder as +A user file whose `name` matches a built-in replaces it. A reworked Light sits in the folder as `light.json`, and the menu lists one Light. ## Picking one Settings › Theme lists Follow the System and every theme that loaded. A choice is applied at once -and saved for the next start; 80% to 200% of interface scale sits beside it. +and saved for the next start. Interface scale, 80% to 200%, sits beside it. -The quickest way to begin is to take a theme file from anywhere else with **Load a Theme from -File…**, which keeps a copy in the themes folder: edit that copy and the app follows it. A file -that does not load is listed in red at the bottom of the same menu, with the token at fault. +To start from a theme you already have, use **Load a Theme from File…**. The app keeps a copy in +the themes folder; edit that copy and the app follows it. A file that does not load is listed in +red at the bottom of the same menu, with the token at fault. A saved file is picked up within a second, without pressing **Reload Themes**: the app watches the -folder's files while it runs. A file that was in use and stops loading leaves the window on the -nearest built-in until it loads again, with the reason listed in the menu. +folder while it runs. A theme in use that stops loading leaves the window on the nearest built-in +until it loads again, and the menu gives the reason. ## A short theme @@ -37,86 +37,86 @@ nearest built-in until it loads again, with the reason listed in the menu. ```json { "schema": 1, - "name": "Sunset", + "name": "Cobalt", "extends": "Dark", "colours": { - "pane": "#241710", - "ribbon": "#35221A", - "text": "#FFE7D1", - "accent": "#F2A65A", - "on_accent": "#2A1B12" + "accent": "#3B82F6", + "accent_text": "#93C5FD", + "on_accent": "#FFFFFF", + "hover": "#22314D", + "checked": "#1E3A8A" } } ``` -Colours, brightness and sizes it leaves out come from the theme it extends. Without `extends` -every colour is required, as in the full file below: that is the reference, a short file is the -better start. +Colours, sizes and brightness the file leaves out come from the theme it extends. A short file is +the better start. ## The file +Without `extends` every colour and size is required. The built-in Light is the reference: + ```json { "schema": 1, - "name": "Sunset", - "dark": true, + "name": "Light", + "dark": false, "colours": { - "header": "#2A1B12", - "ribbon": "#35221A", - "tab_strip": "#2A1B12", - "canvas": "#1A1009", - "pane": "#241710", - "pane_header": "#35221A", - "border": "#5A3B2A", - "border_strong": "#7A5138", - "text": "#FFE7D1", - "text_dim": "#D3A985", - "text_disabled": "#8A6B52", - "icon": "#F5D3B3", - "hover": "#4A2F20", - "pressed": "#6B3F26", - "checked": "#5C3A24", - "accent": "#F2A65A", - "accent_text": "#FFC98B", - "on_accent": "#2A1B12", - "input": "#1F130D", - "input_border": "#6B4632", - "group_label": "#C99871", - "status_bar": "#20140E", - "selection": "#7A4A2B", - "menu": "#2E1D14", - "shadow": "#0000006E", - "green": "#7FC29B", - "red": "#EF7A6A", - "amber": "#F2C14E", - "context": "#4FB3A5", - "context_tint": "#1E3C39", - "control": "#4A3020" + "header": "#EEF1F5", + "ribbon": "#FFFFFF", + "tab_strip": "#EEF1F5", + "canvas": "#E4E8EE", + "pane": "#FBFCFD", + "pane_header": "#F3F5F8", + "border": "#DDE2E9", + "border_strong": "#C3CAD4", + "text": "#1F2630", + "text_dim": "#5E6977", + "text_disabled": "#A9B1BC", + "icon": "#3A4554", + "hover": "#E9F0FB", + "pressed": "#D4E2F8", + "checked": "#DCE8FA", + "accent": "#2563EB", + "accent_text": "#1D4EC4", + "on_accent": "#FFFFFF", + "input": "#FFFFFF", + "input_border": "#C6CDD7", + "group_label": "#707A88", + "status_bar": "#F3F5F8", + "selection": "#CFE0FC", + "menu": "#FFFFFF", + "shadow": "#0000001C", + "green": "#169A5A", + "red": "#D13C3C", + "amber": "#E59E1A", + "context": "#0E9384", + "context_tint": "#E3F5F2", + "control": "#DDE3EA" }, "metrics": { - "item_spacing": [7.0, 6.0], - "button_padding": [10.0, 4.0], - "row_height": 24.0, - "corner_radius": 8, - "body": 13.0, - "button_text": 13.0, - "small": 11.0, - "heading": 18.0, - "mono": 12.5 + "item_spacing": [6.0, 5.0], + "button_padding": [8.0, 3.0], + "row_height": 22.0, + "corner_radius": 5, + "body": 12.5, + "button_text": 12.5, + "small": 10.5, + "heading": 17.0, + "mono": 12.0 } } ``` -Every colour is required unless the file extends a theme, and an unknown token stops the file from -loading with the token named. Colours are `#RRGGBB`, or `#RRGGBBAA` where alpha matters, as in -`shadow`. `schema` is 1; a file written for a later build is refused by number. +An unknown token stops the file from loading, and the error names it. Colours are `#RRGGBB`, or +`#RRGGBBAA` where alpha matters, as in `shadow`. `schema` is 1; a file written for a later build is +refused by number. `dark` is the brightness the theme reports to egui, which sets its default widget shapes and the map's light or dark defaults. It is not inferred from the colours. -`metrics` are in points: item spacing, button padding, row height, corner radius and text sizes, -required unless the file extends a theme. Sizes are held to what a window can draw, and a file over -64 KB is not read. +`metrics` are in points: item spacing, button padding, row height, corner radius and text sizes. +Sizes are held to what a window can draw, and a file over 64 KB is not read. ## Tokens From 465e1295f451d3b048551c4bae3b4a22ce0df68e Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 21:00:10 +0100 Subject: [PATCH 03/28] fix(ui): one control for brightness, in Settings > Theme The View tab had a Dark Mode button and Settings > Theme listed Light and Dark, so one setting had two destinations and two names. The ribbon guidelines put application-wide appearance in Settings, so the View button is gone and the list is the only control. - ui.theme picks the built-in Light or Dark entry instead of clearing the theme name, so a shortcut or a script leaves the state the menu would. - Command Search lists Toggle Dark Mode under Settings > Theme. - docs/user-guide: View loses Dark Mode from Display, Settings gains Theme. - docs/themes.md: Light and Dark are the brightness choices. --- crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/lib.rs | 10 +++------- crates/ui-egui/src/ribbon.rs | 2 -- crates/ui-egui/tests/shortcut_customization.rs | 2 +- docs/themes.md | 7 ++++--- docs/user-guide/index.md | 4 ++-- 6 files changed, 11 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 3ad67d8cec..2ecb534049 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -691,7 +691,7 @@ pub(crate) const UI_COMMANDS: &[(&str, &str, &str)] = &[ ("ui.pane.sql", "SQL Pane", "Analyze › Workflows"), ("ui.pane.directions", "Directions", "Home › Navigate"), ("ui.pane.bookmarks", "Bookmarks Pane", "Home › Navigate › Bookmarks"), - ("ui.theme", "Toggle Dark Mode", "View"), + ("ui.theme", "Toggle Dark Mode", "Settings › Theme"), ("ui.map.gpu", "Toggle GPU Rendering", "View"), ("ui.importShapefile", "Import Shapefile with Projection…", "Home › Add"), ("ui.measurementUnits", "Toggle Imperial Measurements", "Home › Inspect › Measure"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2961fa8884..56afda6c94 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2362,14 +2362,10 @@ impl RustGisApp { save("ribbon_minimized", if self.ui.ribbon_minimized { "true" } else { "false" }); } } + // The theme list in Settings is the one control for brightness; this picks its entry. "ui.theme" => { - self.ui.dark = p.get("dark").and_then(Value::as_bool).unwrap_or(!self.ui.dark); - self.ui.dark_follows_system = false; - self.ui.theme_name.clear(); - if let Some(save) = &self.services.save_pref { - save("dark", if self.ui.dark { "true" } else { "false" }); - save("theme", ""); - } + let dark = p.get("dark").and_then(Value::as_bool).unwrap_or(!self.ui.dark); + self.use_theme(if dark { "Dark" } else { "Light" })?; } // Picks a theme by name; no name follows the system again. "ui.themeFile" => { diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index d527cfe741..b713654422 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1765,8 +1765,6 @@ fn view_tab(app: &mut RustGisApp, ui: &mut Ui) { group(ui, "Display", |ui| { let g = app.session.map().graticule; big(ui, app, "graticule", "Graticule", "Show latitude/longitude lines on the basemap.", "map.graticule", Value::Null, g, false); - let dark = app.ui.dark; - big(ui, app, "dark", "Dark\nMode", "Switch between light and dark themes.", "ui.theme", Value::Null, dark, false); let gpu = app.map.gpu_enabled; big( ui, diff --git a/crates/ui-egui/tests/shortcut_customization.rs b/crates/ui-egui/tests/shortcut_customization.rs index 6d59745900..e63f99142a 100644 --- a/crates/ui-egui/tests/shortcut_customization.rs +++ b/crates/ui-egui/tests/shortcut_customization.rs @@ -115,7 +115,7 @@ fn command_search_context_menu_opens_matching_editor_row() { h.run_steps(3); h.event(egui::Event::Text("Toggle Dark Mode".into())); h.run_steps(3); - h.get_by_role_and_label(egui::accesskit::Role::Button, "Toggle Dark Mode View").click_secondary(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Toggle Dark Mode Settings › Theme").click_secondary(); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::Button, "Keyboard Shortcuts").click(); h.run_steps(3); diff --git a/docs/themes.md b/docs/themes.md index 1fff479129..6a830e254a 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -19,8 +19,9 @@ A user file whose `name` matches a built-in replaces it. A reworked Light sits i ## Picking one -Settings › Theme lists Follow the System and every theme that loaded. A choice is applied at once -and saved for the next start. Interface scale, 80% to 200%, sits beside it. +Settings › Theme lists Follow the System and every theme that loaded. Light and Dark are the +brightness choices, so there is no separate Dark Mode switch. A choice is applied at once and +saved for the next start. Interface scale, 80% to 200%, sits beside it. To start from a theme you already have, use **Load a Theme from File…**. The app keeps a copy in the themes folder; edit that copy and the app follows it. A file that does not load is listed in @@ -137,7 +138,7 @@ Meaning: `accent`, `accent_text`, `context`, `context_tint`, `green`, `red`, `am |---|---| | `ui.themeFile` with `name` | Uses that theme; no name follows the system again | | `ui.themeLoad` | Opens a theme file from anywhere, keeps it in the themes folder and uses it | -| `ui.theme` with `dark` | Switches brightness and leaves the theme list | +| `ui.theme` with `dark` | Uses Light or Dark, the brightness asked for | | `ui.scale` with `factor` | Interface scale, held between 0.75 and 2.0 | | `ui.themeReload` | Reads the themes folder again | diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 4398d85e77..dce0e4465f 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -159,10 +159,10 @@ Review copied diagnostics for private layer names or file paths before sharing t | **Labeling** | For the feature layer selected in Layers: Labels (Label, Properties), Label Class (Class, Field), Text Symbol (Size, Color, Bold, Halo), Label Placement and Label Range. Whatever is selected: Map Labeling (Lock, Pause, View Unplaced, Convert) | | **Edit** | Manage Edits (Edit, Save, Undo, Redo, Status, Save to PostGIS and Discard PostGIS Edits on the desktop while a [PostGIS layer is loaded for editing](data.md#editing-postgis-tables), Settings, Templates, Topology), Snapping, Features (Create, Delete, Edit Vertices, Modify), Tools, Elevation, Corrections, Graphics, Graphics and Text, Clipboard | | **Analyze** | Geoprocessing (History, Tools, Model Builder, Script, SQL, Environments), Tasks (the Tasks pane; Task: Record Task, New Task From History, Import Task, run a task), AI (AI Assistant), Portal (Feature Analysis, Raster Analysis), Workflows, Raster (Raster Functions, Function Editor), Tools (the tool gallery), Selection, Notebook, the imagery groups (Ortho Mapping, Reality Mapping, Alignment, Image Analysis, Image Classification, Imagery Sharing, Mensuration, Imagery Tools) | -| **View** | Display (Graticule, Dark Mode, GPU Rendering), View (Globe, Projection, Global; Local on the desktop), Effects, Scene, Windows, Navigation, Link, Workspace, Animation, Time (Time Slider), Profile (Profile; Time Series on the desktop) | +| **View** | Display (Graticule, GPU Rendering), View (Globe, Projection, Global; Local on the desktop), Effects, Scene, Windows, Navigation, Link, Workspace, Animation, Time (Time Slider), Profile (Profile; Time Series on the desktop) | | **Publish** | While a layout is open, its groups first (Page, Map Frames, Map Surrounds, Shapes, Text, Export); then Report, Presentation, Output (Export Map, Export Features, Print Map, Capture To Clipboard, Report, Presentation, Export To 3D), Package, Share As, Layout, Save As, Thumbnail | | **Plugins** | Plugins (Plugin Manager, Install From File, Browse Plugins), plus a group for each enabled [plugin](../plugins.md) with commands or tools; a plugin with its own tab adds that tab instead | -| **Settings** | Customize (Ribbon, Quick Access), Language (interface language and worldview), Start-up (Start With, Projection, Extent), Autosave on the desktop | +| **Settings** | Theme (the theme list, Follow the System, Interface Scale), Customize (Ribbon, Quick Access), Language (interface language and worldview), Start-up (Start With, Projection, Extent), Autosave on the desktop | | **Help** | Performance (Diagnostic Monitor), Learn (Learning Resources), Help (About, Check for Updates on the desktop, Command Search, Shortcuts) | The tabs stay the same whatever is selected: Style, Labeling and Data act on the layer selected in Layers. From 4282f55097020b2aa74517e4120f19aa0b9072ea Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 21:23:50 +0100 Subject: [PATCH 04/28] fix(ui): a platform that reports no theme cannot be followed ctx.system_theme() is None on Linux: winit reports a theme on Windows and macOS only, while the browser reports prefers-color-scheme. There the menu said Follow the System while nothing was followed and the app kept the brightness it had. - the Theme button names the brightness in force when no theme is reported, and Follow the System is greyed out with the reason - docs/themes.md says where it follows and where it cannot - test: no reported theme names Light or Dark, a reported one is followed --- crates/ui-egui/src/lib.rs | 32 ++++++++++++++++++++++++++++++++ crates/ui-egui/src/ribbon.rs | 19 ++++++++----------- docs/themes.md | 4 ++++ 3 files changed, 44 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 56afda6c94..7c5c009ac5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4162,6 +4162,22 @@ impl RustGisApp { } } + /// The entry the Theme button names. A platform that reports no theme cannot be followed, so + /// the brightness in force is named instead. winit reports no system theme on Linux. + pub fn theme_shown(&self, system_reports: bool) -> (bool, String) { + let follows = self.ui.theme_name.is_empty() && self.ui.dark_follows_system && system_reports; + let name = if !self.ui.theme_name.is_empty() { + self.ui.theme_name.clone() + } else if follows { + tl!("Follow the System").to_string() + } else if self.ui.dark { + tl!("Dark").to_string() + } else { + tl!("Light").to_string() + }; + (follows, name) + } + pub fn ui(&mut self, ui: &mut egui::Ui) { let _diagnostics = self.session.diagnostics.enter(); let ctx = ui.ctx().clone(); @@ -4728,6 +4744,22 @@ mod look_tests { assert_eq!(app.current_theme().name, "Mine"); } + #[test] + fn a_platform_that_reports_no_theme_names_the_brightness() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(&[]); + app.take_saved_look(); + assert!(app.ui.dark_follows_system, "a fresh app follows the system"); + let (follows, name) = app.theme_shown(false); + assert!(!follows, "a platform that reports no theme is not followed"); + assert_eq!(name, "Light"); + app.ui.dark = true; + assert_eq!(app.theme_shown(false).1, "Dark"); + let (follows, name) = app.theme_shown(true); + assert!(follows, "a reported theme is followed"); + assert_eq!(name, "Follow the System"); + } + #[test] fn a_saved_theme_that_is_gone_leaves_the_saved_brightness() { let mut app = app_with(&[("theme", "Deleted"), ("dark", "true")]); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index b713654422..600f0f2b2b 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3501,15 +3501,9 @@ fn autosave_menu(app: &mut RustGisApp, ui: &mut Ui) { } fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { - let current = if !app.ui.theme_name.is_empty() { - app.ui.theme_name.clone() - } else if app.ui.dark_follows_system { - tl!("Follow the System").to_string() - } else if app.ui.dark { - tl!("Dark").to_string() - } else { - tl!("Light").to_string() - }; + // The browser reports prefers-color-scheme; winit reports nothing on Linux. + let system = ui.ctx().system_theme().is_some(); + let (follows, current) = app.theme_shown(system); let label = format!("{}\n{current}", tl!("Theme")); let themes = app.themes.clone(); let errors = app.theme_errors.clone(); @@ -3522,8 +3516,11 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { &label, "The interface colours, spacing and text sizes: a built-in theme or a file from the themes folder.", move |ui, app| { - let follows = app.ui.theme_name.is_empty() && app.ui.dark_follows_system; - if ui.add(egui::Button::selectable(follows, tl!("Follow the System"))).clicked() { + let mut follow = ui.add_enabled(system, egui::Button::selectable(follows, tl!("Follow the System"))); + if !system { + follow = follow.on_disabled_hover_text(tl!("This platform does not report the system theme")); + } + if follow.clicked() { let _ = app.run("ui.themeFile", Value::Null); ui.close(); } diff --git a/docs/themes.md b/docs/themes.md index 6a830e254a..5aa5f19ed5 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -23,6 +23,10 @@ Settings › Theme lists Follow the System and every theme that loaded. Light an brightness choices, so there is no separate Dark Mode switch. A choice is applied at once and saved for the next start. Interface scale, 80% to 200%, sits beside it. +Follow the System follows the platform theme where the platform reports one: Windows, macOS and the +browser, through `prefers-color-scheme`. Linux desktops report no theme, so the entry is greyed out +there and the button names the brightness in force instead. + To start from a theme you already have, use **Load a Theme from File…**. The app keeps a copy in the themes folder; edit that copy and the app follows it. A file that does not load is listed in red at the bottom of the same menu, with the token at fault. From 41658cc72cf2f1061701a8d00a5aca5e5a9b340f Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 21:47:32 +0100 Subject: [PATCH 05/28] fix(ui): the zoom keys and the menu share one interface scale egui's Ctrl +, Ctrl - and Ctrl 0 change the context's zoom factor, and the Interface Scale menu kept its own value, so the two disagreed and choosing 100% after a zoom key did nothing. The scale is read back from the context each frame, held to 80% to 200%, and saved: one value, one control. The lower limit was 75%, which the menu never offered. A theme file picked with Load a Theme from File is also held to the 64 KB limit that a file in the themes folder already has, rather than read whole. --- crates/ui-egui/src/lib.rs | 57 +++++++++++++++++++++++++++++++++++-- crates/ui-egui/src/theme.rs | 4 +-- docs/themes.md | 2 +- 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7c5c009ac5..c25c03acff 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -556,7 +556,7 @@ pub struct UiState { pub dark: bool, /// The theme file in use, by name. Empty follows `dark` and the system. pub theme_name: String, - /// The interface scale, 0.75 to 2.0, applied as egui's zoom factor. + /// The interface scale, 0.8 to 2.0, applied as egui's zoom factor. pub interface_scale: f32, /// Live measurement and map scale-bar units, chosen in Home › Measure. pub measurement_imperial: bool, @@ -1706,6 +1706,10 @@ impl RustGisApp { } fn load_theme_file(&mut self, path: &std::path::Path) -> Result<(), String> { + if std::fs::metadata(path).is_ok_and(|m| m.len() > theme::MAX_THEME_BYTES) { + let limit = theme::MAX_THEME_BYTES / 1024; + return Err(format!("{}: a theme file is at most {limit} KB", path.display())); + } let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); let theme = theme::Theme::parse(&stem, &text).map_err(|e| format!("{}: {e}", path.display()))?; @@ -4155,7 +4159,20 @@ impl RustGisApp { self.applied_theme = Some((self.ui.theme_name.clone(), self.ui.dark)); self.map.invalidate(); } - if self.applied_scale != Some(self.ui.interface_scale) { + // egui's zoom keys (Ctrl +, Ctrl -, Ctrl 0) change the context: adopt that scale. + let zoom = ctx.zoom_factor(); + if (zoom - self.ui.interface_scale).abs() > 0.001 { + let wanted = theme::clamp_scale(zoom); + if (wanted - zoom).abs() > 0.001 { + ctx.set_zoom_factor(wanted); + } + self.ui.interface_scale = wanted; + if let Some(save) = &self.services.save_pref { + save("ui_scale", &format!("{wanted:.2}")); + } + self.applied_scale = Some(wanted); + self.map.invalidate(); + } else if self.applied_scale != Some(self.ui.interface_scale) { ctx.set_zoom_factor(self.ui.interface_scale); self.applied_scale = Some(self.ui.interface_scale); self.map.invalidate(); @@ -4760,6 +4777,42 @@ mod look_tests { assert_eq!(name, "Follow the System"); } + #[test] + fn a_picked_theme_file_bigger_than_the_limit_is_refused_unread() { + let dir = tempfile::tempdir().expect("a temporary folder"); + let path = dir.path().join("huge.json"); + std::fs::write(&path, "x".repeat(70 * 1024)).expect("the file"); + let mut app = app_with(&[]); + let why = app.load_theme_file(&path).expect_err("a 70 KB file is refused"); + assert!(why.contains("64 KB"), "{why}"); + } + + #[test] + fn the_zoom_keys_and_the_menu_share_one_scale() { + let mut app = app_with(&[]); + app.take_saved_look(); + let log = saved_by(&mut app); + let ctx = egui::Context::default(); + // A zoom factor lands at the end of the pass that sets it. + let settle = |ctx: &egui::Context| { + let mut pass = ctx.run_ui(egui::RawInput::default(), |_| {}); + pass.textures_delta.clear(); + }; + // A zoom key moved the context: the menu takes that scale and keeps it. + ctx.set_zoom_factor(1.25); + settle(&ctx); + app.logic(&ctx); + assert_eq!(app.ui.interface_scale, 1.25, "the menu follows the zoom keys"); + assert!(log.lock().expect("the log").iter().any(|(k, v)| k == "ui_scale" && v == "1.25")); + // Beyond the limit it is held, and the context is put back to the limit. + ctx.set_zoom_factor(3.0); + settle(&ctx); + app.logic(&ctx); + settle(&ctx); + assert_eq!(app.ui.interface_scale, 2.0, "the scale is held at 200 percent"); + assert!((ctx.zoom_factor() - 2.0).abs() < 0.001, "the context is held too"); + } + #[test] fn a_saved_theme_that_is_gone_leaves_the_saved_brightness() { let mut app = app_with(&[("theme", "Deleted"), ("dark", "true")]); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 6b40c897ba..813018e7ae 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -234,9 +234,9 @@ impl Metrics { } } -/// The interface scale a command accepts, held between 75 and 200 percent. +/// The interface scale a command accepts, held between 80 and 200 percent. pub fn clamp_scale(scale: f32) -> f32 { - if scale.is_finite() { scale.clamp(0.75, 2.0) } else { 1.0 } + if scale.is_finite() { scale.clamp(0.8, 2.0) } else { 1.0 } } #[derive(Clone, Debug, PartialEq)] diff --git a/docs/themes.md b/docs/themes.md index 5aa5f19ed5..352c50b1eb 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -143,7 +143,7 @@ Meaning: `accent`, `accent_text`, `context`, `context_tint`, `green`, `red`, `am | `ui.themeFile` with `name` | Uses that theme; no name follows the system again | | `ui.themeLoad` | Opens a theme file from anywhere, keeps it in the themes folder and uses it | | `ui.theme` with `dark` | Uses Light or Dark, the brightness asked for | -| `ui.scale` with `factor` | Interface scale, held between 0.75 and 2.0 | +| `ui.scale` with `factor` | Interface scale, held between 80% and 200% | | `ui.themeReload` | Reads the themes folder again | ## What a theme cannot change From 3c6842ffa79899298b18ab5af427cffc2f4b6aed Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 21:47:33 +0100 Subject: [PATCH 06/28] docs(ui): the Settings preference list names the theme --- docs/user-guide/workspace.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 6c7b6a1f83..91d29d7ef1 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -446,6 +446,10 @@ duplication and nudging have their own [layout shortcuts](layouts.md#layouts). - **Language**: **Settings › Language** switches the interface among [19 languages](../i18n.md) and chooses the [worldview](maps.md#worldview) of the built-in borders. +- **Theme**: **Settings › Theme** picks the interface colours, spacing and text sizes, from the + built-in Light and Dark themes, a theme [file](../themes.md) in the themes folder, or + **Follow the System** where the platform reports its own theme. **Interface Scale** beside it + sets the whole interface from 80% to 200%. - **Autosave**: **Settings › Autosave** sets how often the desktop app keeps a [recovery copy](#autosave-and-recovery) of unsaved work, or turns it off. - **Start-up**: **Settings › Start-up** sets what RustGIS opens with: **Start With** the World Atlas From 4f210f8a84369ef3011ec352bb04462ea7ffbee4 Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 22:20:54 +0100 Subject: [PATCH 07/28] fix(ui): theme state survives a reload, and the menu owns the scale Findings from the review of the pull request: - The Interface Scale menu was undone on the next frame: the app read egui's zoom back and overwrote the choice. egui's zoom keys are off now, so the menu is the only control and the scale it records is the scale it draws. - Follow the System was not saved, so a restart took a stale brightness preference. The choice is stored as "auto" and read back as a follow. - A theme file saved as the other brightness left the menu naming it while the window drew another theme. The name now takes the brightness of the file. - Metrics were all-or-nothing: a file that set one size was refused by serde. Every field is optional now, a size the file leaves keeps what the theme it extends gave it, and an unknown size is reported by name. - A colour of "+F" digits was accepted. Only hex digits are. - A themes folder created after start was never watched, though the docs say a saved file is picked up. The watch no longer requires the folder at start. - The ui_shot example cached the applied theme by brightness only. --- crates/ui-egui/examples/ui_shot.rs | 6 +- crates/ui-egui/src/lib.rs | 86 ++++++++++++++------ crates/ui-egui/src/theme.rs | 125 +++++++++++++++++++++++++++-- docs/themes.md | 10 ++- 4 files changed, 189 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/examples/ui_shot.rs b/crates/ui-egui/examples/ui_shot.rs index 4abe189e00..aa47f0e196 100644 --- a/crates/ui-egui/examples/ui_shot.rs +++ b/crates/ui-egui/examples/ui_shot.rs @@ -46,7 +46,7 @@ struct RibbonSplitShowcase { disable_enclosing_ui: bool, long_labels: bool, fonts_installed: bool, - applied_dark: Option, + applied_look: Option<(String, bool)>, } fn split_tool_menu(ui: &mut egui::Ui, app: &mut RustGisApp) { @@ -66,10 +66,10 @@ impl RibbonSplitShowcase { theme::install_fonts(ui.ctx(), &[], None); self.fonts_installed = true; } - if self.applied_dark != Some(app.ui.dark) { + if self.applied_look.as_ref() != Some(&(app.ui.theme_name.clone(), app.ui.dark)) { let chosen = app.current_theme(); theme::apply(ui.ctx(), &chosen.tokens, &chosen.metrics); - self.applied_dark = Some(app.ui.dark); + self.applied_look = Some((app.ui.theme_name.clone(), app.ui.dark)); } i18n::set_current(app.chosen_lang()); ui.heading("Ribbon split buttons"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c25c03acff..c7d3466b64 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1638,13 +1638,24 @@ impl RustGisApp { self.themes = themes; self.theme_errors = errors; self.themes_stamp = theme::Theme::folder_signature(theme::Theme::user_dir().as_deref()); + self.sync_named_brightness(); // Reset so a file that reads differently is applied again on the next frame. self.applied_theme = None; } + /// A file saved as the other brightness takes the interface with it, so name and look agree. + fn sync_named_brightness(&mut self) { + if self.ui.theme_name.is_empty() { + return; + } + if let Some(dark) = self.themes.iter().find(|t| t.name == self.ui.theme_name).map(|t| t.dark) { + self.ui.dark = dark; + } + } + /// Reads the folder again when a file in it was added, removed or saved, at most once a second. fn refresh_themes(&mut self, ctx: &egui::Context) { - let Some(dir) = theme::Theme::user_dir().filter(|d| d.is_dir()) else { return }; + let Some(dir) = theme::Theme::user_dir() else { return }; ctx.request_repaint_after(web_time::Duration::from_secs(1)); let now = ctx.input(|i| i.time); if now < self.themes_checked + 1.0 { @@ -1683,9 +1694,9 @@ impl RustGisApp { self.ui.dark = picked.dark; self.ui.dark_follows_system = false; } else if let Some(dark) = pref(self, "dark") { - // Toggled with Dark Mode and no theme file: remember which of the two it was. + // "auto" was Follow the System; a toggle stores the brightness it left. self.ui.dark = dark == "true"; - self.ui.dark_follows_system = false; + self.ui.dark_follows_system = dark == "auto"; } let scale = pref(self, "ui_scale").and_then(|v| v.parse::().ok()); self.ui.interface_scale = scale.map_or(1.0, theme::clamp_scale); @@ -2379,6 +2390,7 @@ impl RustGisApp { self.ui.dark_follows_system = true; if let Some(save) = &self.services.save_pref { save("theme", ""); + save("dark", "auto"); } } else { self.use_theme(&name)?; @@ -4159,20 +4171,9 @@ impl RustGisApp { self.applied_theme = Some((self.ui.theme_name.clone(), self.ui.dark)); self.map.invalidate(); } - // egui's zoom keys (Ctrl +, Ctrl -, Ctrl 0) change the context: adopt that scale. - let zoom = ctx.zoom_factor(); - if (zoom - self.ui.interface_scale).abs() > 0.001 { - let wanted = theme::clamp_scale(zoom); - if (wanted - zoom).abs() > 0.001 { - ctx.set_zoom_factor(wanted); - } - self.ui.interface_scale = wanted; - if let Some(save) = &self.services.save_pref { - save("ui_scale", &format!("{wanted:.2}")); - } - self.applied_scale = Some(wanted); - self.map.invalidate(); - } else if self.applied_scale != Some(self.ui.interface_scale) { + // egui's own zoom keys would change the zoom behind the Interface Scale menu. + ctx.options_mut(|o| o.zoom_with_keyboard = false); + if self.applied_scale != Some(self.ui.interface_scale) { ctx.set_zoom_factor(self.ui.interface_scale); self.applied_scale = Some(self.ui.interface_scale); self.map.invalidate(); @@ -4788,7 +4789,7 @@ mod look_tests { } #[test] - fn the_zoom_keys_and_the_menu_share_one_scale() { + fn the_menu_owns_the_interface_scale() { let mut app = app_with(&[]); app.take_saved_look(); let log = saved_by(&mut app); @@ -4798,14 +4799,21 @@ mod look_tests { let mut pass = ctx.run_ui(egui::RawInput::default(), |_| {}); pass.textures_delta.clear(); }; - // A zoom key moved the context: the menu takes that scale and keeps it. - ctx.set_zoom_factor(1.25); + app.logic(&ctx); settle(&ctx); + assert!(!ctx.options(|o| o.zoom_with_keyboard), "the zoom keys are off, so the scale cannot move behind the menu"); + // A scale from the menu is drawn, and the next frame does not undo it. + app.run("ui.scale", serde_json::json!({ "factor": 1.25 })).expect("the command"); app.logic(&ctx); - assert_eq!(app.ui.interface_scale, 1.25, "the menu follows the zoom keys"); + settle(&ctx); + app.logic(&ctx); + settle(&ctx); + assert_eq!(app.ui.interface_scale, 1.25, "the menu scale is kept, not read back as the old zoom"); + assert!((ctx.zoom_factor() - 1.25).abs() < 0.001, "and the interface is drawn at it"); assert!(log.lock().expect("the log").iter().any(|(k, v)| k == "ui_scale" && v == "1.25")); - // Beyond the limit it is held, and the context is put back to the limit. - ctx.set_zoom_factor(3.0); + // Past the limit the command holds the scale. + app.run("ui.scale", serde_json::json!({ "factor": 3.0 })).expect("the command"); + app.logic(&ctx); settle(&ctx); app.logic(&ctx); settle(&ctx); @@ -4813,6 +4821,34 @@ mod look_tests { assert!((ctx.zoom_factor() - 2.0).abs() < 0.001, "the context is held too"); } + #[test] + fn following_the_system_survives_a_restart() { + let mut app = app_with(&[("theme", ""), ("dark", "auto")]); + app.take_saved_look(); + assert!(app.ui.dark_follows_system, "the choice to follow is remembered, not read as a toggle"); + let mut app = app_with(&[("theme", ""), ("dark", "false")]); + app.take_saved_look(); + assert!(!app.ui.dark_follows_system, "a saved brightness is a brightness, not a follow"); + assert!(!app.ui.dark); + } + + #[test] + fn a_theme_saved_as_the_other_brightness_takes_the_interface_with_it() { + let mut app = app_with(&[]); + let mut file = builtin(true); + file.name = "Mine".to_string(); + app.themes = vec![file]; + app.ui.theme_name = "Mine".to_string(); + app.ui.dark = true; + // The file is saved as a light theme while the app shows the dark one. + let mut file = builtin(true); + file.name = "Mine".to_string(); + file.dark = false; + app.themes = vec![file]; + app.sync_named_brightness(); + assert!(!app.ui.dark, "the interface takes the brightness of the theme it names"); + } + #[test] fn a_saved_theme_that_is_gone_leaves_the_saved_brightness() { let mut app = app_with(&[("theme", "Deleted"), ("dark", "true")]); @@ -4823,6 +4859,10 @@ mod look_tests { assert_eq!(app.ui.interface_scale, 1.0, "no scale saved is the normal one"); } + fn builtin(dark: bool) -> theme::Theme { + theme::Theme::builtin().into_iter().find(|t| t.dark == dark).expect("a built-in theme ships") + } + fn saved_by(app: &mut RustGisApp) -> std::sync::Arc>> { let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); let sink = log.clone(); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 813018e7ae..4ee349d2e7 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -181,6 +181,77 @@ fn tokens_id() -> egui::Id { egui::Id::unique("rustgis.theme.tokens") } +/// A file's `metrics` block: every field optional, and an unknown name is reported by name. +#[derive(serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +struct MetricsFile { + #[serde(default, skip_serializing_if = "Option::is_none")] + item_spacing: Option<[f32; 2]>, + #[serde(default, skip_serializing_if = "Option::is_none")] + button_padding: Option<[f32; 2]>, + #[serde(default, skip_serializing_if = "Option::is_none")] + row_height: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + corner_radius: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + body: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + button_text: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + small: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + heading: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + mono: Option, +} + +impl MetricsFile { + fn from(metrics: &Metrics) -> Self { + MetricsFile { + item_spacing: Some(metrics.item_spacing), + button_padding: Some(metrics.button_padding), + row_height: Some(metrics.row_height), + corner_radius: Some(metrics.corner_radius), + body: Some(metrics.body), + button_text: Some(metrics.button_text), + small: Some(metrics.small), + heading: Some(metrics.heading), + mono: Some(metrics.mono), + } + } + + /// Applies the sizes the file sets; the rest keep what the theme it extends gave them. + fn apply_to(self, metrics: &mut Metrics) { + if let Some(v) = self.item_spacing { + metrics.item_spacing = v; + } + if let Some(v) = self.button_padding { + metrics.button_padding = v; + } + if let Some(v) = self.row_height { + metrics.row_height = v; + } + if let Some(v) = self.corner_radius { + metrics.corner_radius = v; + } + if let Some(v) = self.body { + metrics.body = v; + } + if let Some(v) = self.button_text { + metrics.button_text = v; + } + if let Some(v) = self.small { + metrics.small = v; + } + if let Some(v) = self.heading { + metrics.heading = v; + } + if let Some(v) = self.mono { + metrics.mono = v; + } + } +} + #[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Metrics { @@ -260,7 +331,7 @@ struct Raw { #[serde(default)] colours: BTreeMap, #[serde(default, skip_serializing_if = "Option::is_none")] - metrics: Option, + metrics: Option, } impl Theme { @@ -288,6 +359,7 @@ impl Theme { if raw.schema != SCHEMA { return Err(format!("{name}: theme schema {} is not {SCHEMA}", raw.schema)); } + let extends = raw.extends.is_some(); let base = match raw.extends.as_deref() { None => None, Some(wanted) => match Theme::builtin().into_iter().find(|t| t.name == wanted) { @@ -299,9 +371,9 @@ impl Theme { if !unknown.is_empty() { return Err(format!("{name}: unknown {}", unknown.join(", "))); } - let missing: Vec<&str> = match &base { - Some(_) => Vec::new(), - None => TOKENS.iter().copied().filter(|t| !raw.colours.contains_key(*t)).collect(), + let missing: Vec<&str> = match extends { + true => Vec::new(), + false => TOKENS.iter().copied().filter(|t| !raw.colours.contains_key(*t)).collect(), }; if !missing.is_empty() { return Err(format!("{name}: missing {}", missing.join(", "))); @@ -320,14 +392,24 @@ impl Theme { } } let dark = raw.dark.unwrap_or(fallback.dark); - let metrics = raw.metrics.unwrap_or(fallback.metrics).clamped(); + let mut metrics = fallback.metrics; + if let Some(file) = raw.metrics { + file.apply_to(&mut metrics); + } + let metrics = metrics.clamped(); Ok(Theme { name, dark, tokens, metrics }) } pub fn to_json(&self) -> Result { let colours: BTreeMap = TOKENS.iter().map(|name| ((*name).to_string(), hex(colour(self, name)))).collect(); - let raw = - Raw { schema: SCHEMA, name: self.name.clone(), extends: None, dark: Some(self.dark), colours, metrics: Some(self.metrics) }; + let raw = Raw { + schema: SCHEMA, + name: self.name.clone(), + extends: None, + dark: Some(self.dark), + colours, + metrics: Some(MetricsFile::from(&self.metrics)), + }; serde_json::to_string_pretty(&raw).map_err(|e| format!("{}: {e}", self.name)) } @@ -488,7 +570,7 @@ fn clean_name(name: &str) -> String { fn parse_colour(text: &str) -> Result { let digits = text.strip_prefix('#').ok_or_else(|| format!("is not a #RRGGBB colour: {text}"))?; let bad = || format!("is not a #RRGGBB or #RRGGBBAA colour: {text}"); - if !digits.is_ascii() { + if !digits.chars().all(|c| c.is_ascii_hexdigit()) { return Err(bad()); } let pair = |at: usize| u8::from_str_radix(&digits[at..at + 2], 16).map_err(|_| bad()); @@ -694,6 +776,33 @@ mod tests { assert_eq!(Theme::folder_signature(None), 0, "no folder never changes"); } + #[test] + fn a_file_sets_the_sizes_it_names_and_keeps_the_rest() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["extends"] = serde_json::json!("Light"); + json["colours"] = serde_json::json!({}); + json["metrics"] = serde_json::json!({ "body": 15.0 }); + let theme = Theme::parse("Mine", &json.to_string()).expect("a file may set one size"); + assert_eq!(theme.metrics.body, 15.0, "the size the file names"); + assert_eq!(theme.metrics.row_height, light().metrics.row_height, "a size it leaves keeps Light's"); + } + + #[test] + fn a_size_that_does_not_exist_is_named() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["metrics"] = serde_json::json!({ "bdy": 14.0 }); + let err = Theme::parse("Mine", &json.to_string()).expect_err("there is no size called bdy"); + assert!(err.contains("bdy"), "{err}"); + } + + #[test] + fn a_colour_must_be_hex_digits() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["colours"]["accent"] = serde_json::json!("#+F+F+F"); + let err = Theme::parse("Mine", &json.to_string()).expect_err("a plus sign is not a hex digit"); + assert!(err.to_lowercase().contains("accent"), "{err}"); + } + #[test] fn a_missing_token_is_named() { let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); diff --git a/docs/themes.md b/docs/themes.md index 352c50b1eb..a01fdbdae1 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -21,15 +21,16 @@ A user file whose `name` matches a built-in replaces it. A reworked Light sits i Settings › Theme lists Follow the System and every theme that loaded. Light and Dark are the brightness choices, so there is no separate Dark Mode switch. A choice is applied at once and -saved for the next start. Interface scale, 80% to 200%, sits beside it. +saved for the next start. Interface scale, 80% to 200%, sits beside it, and it is the only +control for it: Ctrl + and Ctrl - do nothing, so the scale the app records is the scale it draws. Follow the System follows the platform theme where the platform reports one: Windows, macOS and the browser, through `prefers-color-scheme`. Linux desktops report no theme, so the entry is greyed out there and the button names the brightness in force instead. To start from a theme you already have, use **Load a Theme from File…**. The app keeps a copy in -the themes folder; edit that copy and the app follows it. A file that does not load is listed in -red at the bottom of the same menu, with the token at fault. +the themes folder; edit that copy and the app follows it. Loading a file whose `name` matches a theme already in the folder replaces that copy. +A file that does not load is listed in red at the bottom of the same menu, with the token at fault. A saved file is picked up within a second, without pressing **Reload Themes**: the app watches the folder while it runs. A theme in use that stops loading leaves the window on the nearest built-in @@ -59,7 +60,8 @@ the better start. ## The file -Without `extends` every colour and size is required. The built-in Light is the reference: +Without `extends` every colour is required, and a size the file leaves out keeps the standard one. +An unknown name, colour or size is refused by name. The built-in Light is the reference: ```json { From 33c2d94f4cfc4d3274a234a0559bbfe78d6850ab Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 23:00:47 +0100 Subject: [PATCH 08/28] fix(ui): themes keep their brightness, their sizes and the scale they were given Findings from the review of the pull request: - A theme that extends another and sets its own brightness left the drawn visuals on the base theme's, so Light extended as dark drew light chrome. The file's brightness is now the one apply() draws from. - A theme name of marks and symbols produced an empty file name, and the theme was never listed again. Such a name falls back to theme.json. - The brightness toggle picked a theme by name, so a reworked Light could leave the window on the wrong brightness. It picks by the brightness asked for, and clears the name when no theme has it. - Metrics were all-or-nothing: a file that set one size was refused by serde. Every size is optional now, a size the file leaves keeps the one it inherited, and an unknown size is named. - A colour of "+F" digits passed the hex check. Only hex digits pass now. - The theme folder was read without a bound after a metadata check, so a pipe or a device could hang or exhaust memory. One bounded read covers both. - The folder signature hashed the mtime, which misses two saves inside one tick and needed std::time on a crate that uses web_time elsewhere. It hashes the file bytes instead, and the stamp is taken before the read so a save between the two is loaded again rather than lost. - Loading a file over a theme of the same name discarded the folder copy. The copy it replaces is kept as .json.bak. - Following the system was not saved, so a restart took a stale brightness. The choice is stored as "auto". - The Interface Scale menu was undone on the next frame, because the app read egui's zoom back and overwrote the choice. egui's zoom keys are off, so the menu is the only control. - A theme file saved with the other brightness left the menu naming it while the window drew another theme. The name takes the brightness of the file. - A themes folder created after start was never watched, though the docs say a saved file is picked up. - The theme messages the menu shows went through format!: the parse reasons, the size refusal and the load error now go through i18n::fmt. - The ui_shot example cached the applied theme by brightness only. Also: docs/themes.md is registered in the assistant's docs::PAGES, which the workspace test requires, and the page now says what the browser build does. --- crates/assistant/src/docs.rs | 1 + crates/ui-egui/src/lib.rs | 47 ++++++++-- crates/ui-egui/src/theme.rs | 168 ++++++++++++++++++++++++++++------- docs/themes.md | 15 +++- 4 files changed, 186 insertions(+), 45 deletions(-) diff --git a/crates/assistant/src/docs.rs b/crates/assistant/src/docs.rs index 71537ad098..a069ffe60f 100644 --- a/crates/assistant/src/docs.rs +++ b/crates/assistant/src/docs.rs @@ -44,6 +44,7 @@ pub const PAGES: &[Page] = pages![ "python.md", "mcp.md", "plugins.md", + "themes.md", "i18n.md", "architecture.md", "contributing.md", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c7d3466b64..83a420178d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1634,10 +1634,11 @@ impl RustGisApp { } fn load_themes(&mut self) { + // The stamp before the read, so a save between the two is loaded again rather than lost. + self.themes_stamp = theme::Theme::folder_signature(theme::Theme::user_dir().as_deref()); let (themes, errors) = theme::Theme::available(); self.themes = themes; self.theme_errors = errors; - self.themes_stamp = theme::Theme::folder_signature(theme::Theme::user_dir().as_deref()); self.sync_named_brightness(); // Reset so a file that reads differently is applied again on the next frame. self.applied_theme = None; @@ -1717,13 +1718,20 @@ impl RustGisApp { } fn load_theme_file(&mut self, path: &std::path::Path) -> Result<(), String> { - if std::fs::metadata(path).is_ok_and(|m| m.len() > theme::MAX_THEME_BYTES) { - let limit = theme::MAX_THEME_BYTES / 1024; - return Err(format!("{}: a theme file is at most {limit} KB", path.display())); - } - let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let said = |reason: &str| i18n::fmt("{path}: {reason}", &[("path", &path.display().to_string()), ("reason", reason)]); + let text = match theme::read_text(path) { + Ok(text) => text, + Err(theme::Over::TooBig) => { + let limit = theme::MAX_THEME_BYTES / 1024; + return Err(i18n::fmt( + "{path}: a theme file is at most {limit} KB", + &[("path", &path.display().to_string()), ("limit", &limit.to_string())], + )); + } + Err(theme::Over::Reason(reason)) => return Err(said(&reason)), + }; let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); - let theme = theme::Theme::parse(&stem, &text).map_err(|e| format!("{}: {e}", path.display()))?; + let theme = theme::Theme::parse(&stem, &text).map_err(|e| said(&e))?; let kept = theme.save_user()?; self.load_themes(); self.use_theme(&theme.name)?; @@ -2380,7 +2388,16 @@ impl RustGisApp { // The theme list in Settings is the one control for brightness; this picks its entry. "ui.theme" => { let dark = p.get("dark").and_then(Value::as_bool).unwrap_or(!self.ui.dark); - self.use_theme(if dark { "Dark" } else { "Light" })?; + // The brightness asked for wins: a user file may rework Light or Dark. + self.ui.dark = dark; + let wanted = if dark { "Dark" } else { "Light" }; + self.ui.theme_name = + self.themes.iter().find(|t| t.name == wanted && t.dark == dark).map(|t| t.name.clone()).unwrap_or_default(); + self.ui.dark_follows_system = false; + if let Some(save) = &self.services.save_pref { + save("theme", &self.ui.theme_name); + save("dark", if dark { "true" } else { "false" }); + } } // Picks a theme by name; no name follows the system again. "ui.themeFile" => { @@ -4821,6 +4838,20 @@ mod look_tests { assert!((ctx.zoom_factor() - 2.0).abs() < 0.001, "the context is held too"); } + #[test] + fn the_theme_command_lands_on_the_brightness_it_is_given() { + let mut app = app_with(&[]); + app.take_saved_look(); + let log = saved_by(&mut app); + // A user file reworks Light and reports itself dark: the request, not the name, decides. + let mut reworked = builtin(false); + reworked.dark = true; + app.themes = vec![reworked, builtin(true)]; + app.run("ui.theme", serde_json::json!({ "dark": false })).expect("the command"); + assert!(!app.ui.dark, "the brightness asked for is the one in force"); + assert!(log.lock().expect("the log").iter().any(|(k, v)| k == "dark" && v == "false")); + } + #[test] fn following_the_system_survives_a_restart() { let mut app = app_with(&[("theme", ""), ("dark", "auto")]); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 4ee349d2e7..e3bcd9ac7d 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -6,12 +6,38 @@ use std::sync::Arc; use egui::{Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Stroke, Visuals}; +use crate::i18n; + /// RustGIS brand colour (the Project tab and the logo) and its lighter tint. pub const BRAND: Color32 = Color32::from_rgb(0xB8, 0x4A, 0x2C); pub const BRAND_DARK: Color32 = Color32::from_rgb(0x96, 0x3A, 0x22); /// Contextual tab group colour (Feature Layer, Labeling, Data). pub const CONTEXT: Color32 = Color32::from_rgb(0x0E, 0x93, 0x84); +/// Why a theme file could not be read. +#[derive(Debug)] +pub enum Over { + TooBig, + Reason(String), +} + +/// Reads a theme file without trusting its length: a pipe or a device cannot exhaust memory. +pub fn read_text(path: &std::path::Path) -> Result { + use std::io::Read; + let file = std::fs::File::open(path).map_err(|e| Over::Reason(e.to_string()))?; + let mut text = String::new(); + file.take(MAX_THEME_BYTES + 1).read_to_string(&mut text).map_err(|e| Over::Reason(e.to_string()))?; + match text.len() as u64 > MAX_THEME_BYTES { + true => Err(Over::TooBig), + false => Ok(text), + } +} + +/// A path and the reason it failed, as the menu shows it. +fn why(path: &std::path::Path, reason: &str) -> String { + i18n::fmt("{path}: {reason}", &[("path", &path.display().to_string()), ("reason", reason)]) +} + /// The only schema this build reads. pub const SCHEMA: u32 = 1; @@ -357,26 +383,36 @@ impl Theme { let raw: Raw = serde_json::from_str(text).map_err(|e| e.to_string())?; let name = clean_name(if raw.name.trim().is_empty() { fallback_name } else { raw.name.trim() }); if raw.schema != SCHEMA { - return Err(format!("{name}: theme schema {} is not {SCHEMA}", raw.schema)); + return Err(i18n::fmt( + "{name}: theme schema {found} is not {schema}", + &[("name", name.as_str()), ("found", &raw.schema.to_string()), ("schema", &SCHEMA.to_string())], + )); } let extends = raw.extends.is_some(); let base = match raw.extends.as_deref() { None => None, Some(wanted) => match Theme::builtin().into_iter().find(|t| t.name == wanted) { Some(found) => Some(found), - None => return Err(format!("{name}: extends {wanted}, which is not a built-in theme")), + None => { + return Err(i18n::fmt( + "{name}: extends {wanted}, which is not a built-in theme", + &[("name", name.as_str()), ("wanted", wanted)], + )); + } }, }; let unknown: Vec<&str> = raw.colours.keys().map(String::as_str).filter(|k| !TOKENS.contains(k)).collect(); if !unknown.is_empty() { - return Err(format!("{name}: unknown {}", unknown.join(", "))); + let names = unknown.join(", "); + return Err(i18n::fmt("{name}: unknown {names}", &[("name", name.as_str()), ("names", &names)])); } let missing: Vec<&str> = match extends { true => Vec::new(), false => TOKENS.iter().copied().filter(|t| !raw.colours.contains_key(*t)).collect(), }; if !missing.is_empty() { - return Err(format!("{name}: missing {}", missing.join(", "))); + let names = missing.join(", "); + return Err(i18n::fmt("{name}: missing {names}", &[("name", name.as_str()), ("names", &names)])); } let fallback = base.unwrap_or_else(|| Theme { name: name.clone(), @@ -386,12 +422,15 @@ impl Theme { }); let mut tokens = fallback.tokens; for (key, value) in &raw.colours { - let colour = parse_colour(value).map_err(|e| format!("{name}: {key} {e}"))?; + let colour = parse_colour(value) + .map_err(|e| i18n::fmt("{name}: {key} {reason}", &[("name", name.as_str()), ("key", key.as_str()), ("reason", &e)]))?; if let Some(slot) = slot(&mut tokens, key) { *slot = colour; } } let dark = raw.dark.unwrap_or(fallback.dark); + // apply() draws from this flag, so a base theme cannot decide the brightness. + tokens.dark = dark; let mut metrics = fallback.metrics; if let Some(file) = raw.metrics { file.apply_to(&mut metrics); @@ -410,7 +449,8 @@ impl Theme { colours, metrics: Some(MetricsFile::from(&self.metrics)), }; - serde_json::to_string_pretty(&raw).map_err(|e| format!("{}: {e}", self.name)) + serde_json::to_string_pretty(&raw) + .map_err(|e| i18n::fmt("{name}: {reason}", &[("name", self.name.as_str()), ("reason", &e.to_string())])) } /// Built-in themes plus the user folder's readable files; failures are returned apart. @@ -432,45 +472,39 @@ impl Theme { files.sort(); for path in files { let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); - match std::fs::metadata(&path) { - Ok(meta) if meta.len() > MAX_THEME_BYTES => { - errors.push(format!("{}: larger than {MAX_THEME_BYTES} bytes", path.display())); - continue; - } - Ok(_) => {} - Err(e) => { - errors.push(format!("{}: {e}", path.display())); - continue; - } - } - match std::fs::read_to_string(&path) { + match read_text(&path) { Ok(text) => match Theme::parse(&stem, &text) { // A user file named as a built-in replaces it, so a name picks one theme. Ok(theme) => match themes.iter_mut().find(|t| t.name == theme.name) { Some(replaced) => *replaced = theme, None => themes.push(theme), }, - Err(e) => errors.push(format!("{}: {e}", path.display())), + Err(e) => errors.push(why(&path, &e)), }, - Err(e) => errors.push(format!("{}: {e}", path.display())), + Err(Over::TooBig) => { + let reason = i18n::fmt("larger than {bytes} bytes", &[("bytes", &MAX_THEME_BYTES.to_string())]); + errors.push(why(&path, &reason)); + } + Err(Over::Reason(reason)) => errors.push(why(&path, &reason)), } } (themes, errors) } - /// Hash of each file's name, size and mtime; any change to the folder changes it. + /// Hash of each file's name and bytes, so a saved file is noticed even inside one mtime tick. pub fn folder_signature(dir: Option<&std::path::Path>) -> u64 { use std::hash::{Hash, Hasher}; let Some(dir) = dir else { return 0 }; let Ok(read) = std::fs::read_dir(dir) else { return 0 }; - let mut stamps: Vec<(String, u64, u128)> = read + let mut stamps: Vec<(String, u64)> = read .flatten() .filter(|e| e.path().extension().is_some_and(|e| e == "json")) .filter_map(|e| { let path = e.path(); - let meta = e.metadata().ok()?; - let saved = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis(); - Some((path.file_name()?.to_string_lossy().into_owned(), meta.len(), saved)) + let bytes = std::fs::read(&path).ok()?; + let mut file = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut file); + Some((path.file_name()?.to_string_lossy().into_owned(), file.finish())) }) .collect(); stamps.sort(); @@ -484,14 +518,14 @@ impl Theme { rustgis_engine::data::dirs::config_dir().map(|d| d.join("themes")) } - /// The file name is the theme name with each non-alphanumeric character as `-`. + /// The file name of a theme, with each non-alphanumeric character as `-`. pub fn save_user(&self) -> Result { - let dir = Self::user_dir().ok_or("no settings folder")?; - std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; - let stem: String = self.name.chars().map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect(); - let path = dir.join(format!("{}.json", stem.trim_matches('-'))); + let dir = Self::user_dir().ok_or_else(|| i18n::fmt("No settings folder to keep a theme in.", &[]))?; + std::fs::create_dir_all(&dir).map_err(|e| why(&dir, &e.to_string()))?; + let path = dir.join(format!("{}.json", stem_of(&self.name))); let text = self.to_json()?; - std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?; + backup_before_replace(&path, &text)?; + std::fs::write(&path, text).map_err(|e| why(&path, &e.to_string()))?; Ok(path) } } @@ -566,10 +600,27 @@ fn clean_name(name: &str) -> String { if kept.is_empty() { "Theme".to_string() } else { kept.to_string() } } +/// Keeps the file it replaces beside it as `.json.bak`: a folder copy may hold edits. +fn backup_before_replace(path: &std::path::Path, text: &str) -> Result<(), String> { + let Ok(old) = std::fs::read(path) else { return Ok(()) }; + if old == text.as_bytes() { + return Ok(()); + } + let kept = path.with_extension("json.bak"); + std::fs::write(&kept, old).map_err(|e| why(&kept, &e.to_string())) +} + +/// The stem of a theme's file name; a name of marks and symbols still gets one. +fn stem_of(name: &str) -> String { + let dashed: String = name.chars().map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect(); + let stem = dashed.trim_matches('-').to_string(); + if stem.is_empty() { "theme".to_string() } else { stem } +} + /// A non-ASCII colour is refused before the byte cut, which would land inside a character. fn parse_colour(text: &str) -> Result { - let digits = text.strip_prefix('#').ok_or_else(|| format!("is not a #RRGGBB colour: {text}"))?; - let bad = || format!("is not a #RRGGBB or #RRGGBBAA colour: {text}"); + let digits = text.strip_prefix('#').ok_or_else(|| i18n::fmt("is not a #RRGGBB colour: {text}", &[("text", text)]))?; + let bad = || i18n::fmt("is not a #RRGGBB or #RRGGBBAA colour: {text}", &[("text", text)]); if !digits.chars().all(|c| c.is_ascii_hexdigit()) { return Err(bad()); } @@ -908,7 +959,10 @@ mod tests { #[test] fn apply_puts_the_theme_on_the_context() { let ctx = egui::Context::default(); - let theme = light(); + let mut theme = light(); + theme.tokens.pane = Color32::from_rgb(0x0A, 0x0B, 0x0C); + theme.tokens.control = Color32::from_rgb(0x11, 0x12, 0x13); + theme.tokens.accent = Color32::from_rgb(0x21, 0x22, 0x23); apply(&ctx, &theme.tokens, &theme.metrics); let style = ctx.global_style(); assert_eq!(style.visuals.panel_fill, theme.tokens.pane); @@ -920,6 +974,52 @@ mod tests { assert_eq!(Tokens::get(&ctx), theme.tokens, "widgets read the applied colours back"); } + #[test] + fn the_brightness_of_the_file_is_the_brightness_drawn() { + let text = r#"{"schema": 1, "name": "Mine", "extends": "Light", "dark": true}"#; + let theme = Theme::parse("Mine", text).expect("a file may extend Light and be dark"); + assert!(theme.dark, "the file reports dark"); + assert!(theme.tokens.dark, "and apply() draws the dark visuals, not the base theme's"); + } + + #[test] + fn a_name_of_symbols_still_gets_a_file_name() { + assert_eq!(stem_of("★★★"), "theme", "a name with no letters or digits still saves"); + assert_eq!(stem_of("Cobalt Blue!"), "cobalt-blue", "letters and digits are kept, the rest as -"); + } + + #[test] + fn a_replaced_theme_file_keeps_the_copy_it_replaced() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json["name"] = "Mine".into(); + json["colours"]["accent"] = "#123456".into(); + let edited = json.to_string(); + json["colours"]["accent"] = "#654321".into(); + let picked = json.to_string(); + let dir = theme_folder("rustgis-theme-backup-test", &[("mine.json", &edited)]); + let path = dir.join("mine.json"); + backup_before_replace(&path, &picked).expect("the backup"); + assert_eq!(std::fs::read_to_string(dir.join("mine.json.bak")).expect("the backup file"), edited); + assert_eq!(std::fs::read_to_string(&path).expect("the file"), edited, "the file is not touched yet"); + // The folder loads one Mine, and the backup is not a theme. + std::fs::write(&path, &picked).expect("the file"); + let (found, errors) = Theme::available_in(Some(&dir)); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!(found.iter().filter(|t| t.name == "Mine").count(), 1, "one Mine is offered"); + assert!(!found.iter().any(|t| t.name.contains("bak")), "the backup is not a theme"); + // Writing the same text again leaves the backup alone. + backup_before_replace(&path, &picked).expect("no backup needed"); + assert_eq!(std::fs::read_to_string(dir.join("mine.json.bak")).expect("the backup file"), edited); + } + + #[test] + fn a_theme_file_over_the_limit_is_not_read() { + let dir = theme_folder("rustgis-theme-over-limit", &[]); + let path = dir.join("big.json"); + std::fs::write(&path, "x".repeat(MAX_THEME_BYTES as usize + 1)).expect("the file"); + assert!(matches!(read_text(&path), Err(Over::TooBig)), "a file over the limit is refused as it is read"); + } + #[test] fn metrics_are_held_within_what_the_interface_draws() { let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); diff --git a/docs/themes.md b/docs/themes.md index a01fdbdae1..99a153cf2c 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -28,9 +28,18 @@ Follow the System follows the platform theme where the platform reports one: Win browser, through `prefers-color-scheme`. Linux desktops report no theme, so the entry is greyed out there and the button names the brightness in force instead. -To start from a theme you already have, use **Load a Theme from File…**. The app keeps a copy in -the themes folder; edit that copy and the app follows it. Loading a file whose `name` matches a theme already in the folder replaces that copy. -A file that does not load is listed in red at the bottom of the same menu, with the token at fault. +## What the browser build does + +The browser has no config folder, so there is no themes folder there and **Load a Theme from File…** +does nothing. The browser offers Follow the System, Light, Dark and the interface scale: a theme in a +file is a desktop route. The two built-in themes are the same files, compiled in, so nothing else +differs. + +To start from a theme you already have, use **Load a Theme from File…**. The app keeps a copy in the +themes folder; edit that copy and the app follows it. Loading a file whose `name` matches a theme +already in the folder replaces that copy, and the copy it replaces is kept beside it as +`.json.bak`. A file that does not load is listed in red at the bottom of the same menu, with +the token at fault. A saved file is picked up within a second, without pressing **Reload Themes**: the app watches the folder while it runs. A theme in use that stops loading leaves the window on the nearest built-in From 81b46132a51f341fb560f6d26e0bb7d7bba8b822 Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 23:10:29 +0100 Subject: [PATCH 09/28] test(ui): a file that sets its own brightness draws in that mode The colours it inherits stay the theme it extends, so a file that extends Light and reports itself dark draws in dark mode with Light's palette: the flag and the palette agree with the file, which is what the review asked for. --- crates/ui-egui/src/theme.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e3bcd9ac7d..2d8b1ad7aa 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -982,6 +982,17 @@ mod tests { assert!(theme.tokens.dark, "and apply() draws the dark visuals, not the base theme's"); } + #[test] + fn a_dark_file_on_a_light_base_draws_dark() { + let text = r##"{"schema": 1, "name": "Nox", "extends": "Light", "dark": true, "colours": {"accent": "#7C3AED"}}"##; + let theme = Theme::parse("Nox", text).expect("a file may extend Light and be dark"); + let ctx = egui::Context::default(); + apply(&ctx, &theme.tokens, &theme.metrics); + assert!(theme.dark && theme.tokens.dark, "the theme reports dark"); + assert!(ctx.global_style().visuals.dark_mode, "so egui draws the parts the file does not colour in dark mode"); + assert_eq!(theme.tokens.pane, Theme::builtin()[0].tokens.pane, "and the colours it extends stay"); + } + #[test] fn a_name_of_symbols_still_gets_a_file_name() { assert_eq!(stem_of("★★★"), "theme", "a name with no letters or digits still saves"); From a516e1e43e5e408144997f361896390f030daa21 Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 23:31:21 +0100 Subject: [PATCH 10/28] fix(ui): the theme folder is read the way the rest of the app reads files Findings from the third review of the pull request: - The folder signature read every theme file in full, once a second, on the UI thread: a fat file named .json stalled the window. It hashes name, size and mtime from metadata and reads no file. - The interface scale could disagree with the value drawn if zoom changed by another route. The menu's scale is written back every frame it differs, so the two cannot drift. The PR text that claimed a read-back is wrong and is corrected separately. - A file is a theme when its extension is json in any case, so THEME.JSON loads. - The size bound is measured on bytes, so a cut inside a character reports the limit rather than a broken encoding, and the picker and the folder use one sentence and one number. - Two theme names that differ only in punctuation took one file, and the second save overwrote the first. A theme now saves to the next free name unless the file already holds it. - A parameter of the wrong type is refused: ui.themeFile wants a name string and ui.scale wants a number, rather than following the system or resetting to 100%. - parse_colour takes its two digits with get(), as AGENTS asks, and echoes a bad value cut to one line instead of at full length. - The menu reported nothing when Follow the System or Reload Themes failed; both now go through the same notifier as the other theme entries. --- crates/ui-egui/src/lib.rs | 42 ++++++++---- crates/ui-egui/src/ribbon.rs | 4 +- crates/ui-egui/src/theme.rs | 126 +++++++++++++++++++++++++++++------ 3 files changed, 136 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 83a420178d..8b0289145b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -914,7 +914,6 @@ pub struct RustGisApp { pub connect: connectui::ConnectState, fonts_frames: u32, applied_theme: Option<(String, bool)>, - applied_scale: Option, /// The themes the app can offer: built in, then the ones in the user's themes folder. pub themes: Vec, /// The theme files that did not load, with the reason. @@ -1093,7 +1092,6 @@ impl RustGisApp { assistant: assistantpane::AssistantState::default(), fonts_frames: 0, applied_theme: None, - applied_scale: None, themes: Vec::new(), theme_errors: Vec::new(), themes_stamp: 0, @@ -1721,13 +1719,7 @@ impl RustGisApp { let said = |reason: &str| i18n::fmt("{path}: {reason}", &[("path", &path.display().to_string()), ("reason", reason)]); let text = match theme::read_text(path) { Ok(text) => text, - Err(theme::Over::TooBig) => { - let limit = theme::MAX_THEME_BYTES / 1024; - return Err(i18n::fmt( - "{path}: a theme file is at most {limit} KB", - &[("path", &path.display().to_string()), ("limit", &limit.to_string())], - )); - } + Err(theme::Over::TooBig) => return Err(theme::too_big(path)), Err(theme::Over::Reason(reason)) => return Err(said(&reason)), }; let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); @@ -2401,7 +2393,10 @@ impl RustGisApp { } // Picks a theme by name; no name follows the system again. "ui.themeFile" => { - let name = p.get("name").and_then(Value::as_str).unwrap_or_default().trim().to_string(); + let name = match p.get("name") { + Some(given) => given.as_str().ok_or_else(|| i18n::fmt("ui.themeFile needs a name string", &[]))?.trim().to_string(), + None => String::new(), + }; if name.is_empty() { self.ui.theme_name.clear(); self.ui.dark_follows_system = true; @@ -2418,7 +2413,10 @@ impl RustGisApp { self.load_theme_file(std::path::Path::new(&path))?; } "ui.scale" => { - let factor = p.get("factor").and_then(Value::as_f64).map_or(1.0, |f| f as f32); + let factor = match p.get("factor") { + Some(given) => given.as_f64().ok_or_else(|| i18n::fmt("ui.scale needs a number at factor", &[]))? as f32, + None => 1.0, + }; self.ui.interface_scale = theme::clamp_scale(factor); if let Some(save) = &self.services.save_pref { save("ui_scale", &format!("{:.2}", self.ui.interface_scale)); @@ -4190,9 +4188,9 @@ impl RustGisApp { } // egui's own zoom keys would change the zoom behind the Interface Scale menu. ctx.options_mut(|o| o.zoom_with_keyboard = false); - if self.applied_scale != Some(self.ui.interface_scale) { + // The menu is the only control, so a zoom from anywhere else is put back the same frame. + if (ctx.zoom_factor() - self.ui.interface_scale).abs() > 0.001 { ctx.set_zoom_factor(self.ui.interface_scale); - self.applied_scale = Some(self.ui.interface_scale); self.map.invalidate(); } } @@ -4836,6 +4834,13 @@ mod look_tests { settle(&ctx); assert_eq!(app.ui.interface_scale, 2.0, "the scale is held at 200 percent"); assert!((ctx.zoom_factor() - 2.0).abs() < 0.001, "the context is held too"); + // A zoom from anywhere else is put back, so the menu and the drawing never disagree. + ctx.set_zoom_factor(1.0); + settle(&ctx); + app.logic(&ctx); + settle(&ctx); + assert_eq!(app.ui.interface_scale, 2.0, "the menu does not follow a zoom it did not make"); + assert!((ctx.zoom_factor() - 2.0).abs() < 0.001, "and the context is put back to the menu's value"); } #[test] @@ -4863,6 +4868,17 @@ mod look_tests { assert!(!app.ui.dark); } + #[test] + fn a_parameter_of_the_wrong_type_is_refused() { + let mut app = app_with(&[]); + let why = app.run("ui.themeFile", serde_json::json!({ "name": 5 })).expect_err("a name must be a string"); + assert!(why.contains("ui.themeFile"), "{why}"); + let why = app.run("ui.scale", serde_json::json!({ "factor": "big" })).expect_err("a factor must be a number"); + assert!(why.contains("ui.scale"), "{why}"); + app.run("ui.scale", serde_json::json!({ "factor": 1.25 })).expect("a number is accepted"); + assert_eq!(app.ui.interface_scale, 1.25); + } + #[test] fn a_theme_saved_as_the_other_brightness_takes_the_interface_with_it() { let mut app = app_with(&[]); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 600f0f2b2b..f8201f24b4 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3521,7 +3521,7 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { follow = follow.on_disabled_hover_text(tl!("This platform does not report the system theme")); } if follow.clicked() { - let _ = app.run("ui.themeFile", Value::Null); + theme_action(app, "ui.themeFile", Value::Null); ui.close(); } for found in &themes { @@ -3538,7 +3538,7 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { ui.close(); } if ui.add(egui::Button::selectable(false, tl!("Reload Themes"))).clicked() { - let _ = app.run("ui.themeReload", Value::Null); + theme_action(app, "ui.themeReload", Value::Null); ui.close(); } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 2d8b1ad7aa..44478e0d83 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -25,12 +25,19 @@ pub enum Over { pub fn read_text(path: &std::path::Path) -> Result { use std::io::Read; let file = std::fs::File::open(path).map_err(|e| Over::Reason(e.to_string()))?; - let mut text = String::new(); - file.take(MAX_THEME_BYTES + 1).read_to_string(&mut text).map_err(|e| Over::Reason(e.to_string()))?; - match text.len() as u64 > MAX_THEME_BYTES { - true => Err(Over::TooBig), - false => Ok(text), + let mut bytes = Vec::new(); + file.take(MAX_THEME_BYTES + 1).read_to_end(&mut bytes).map_err(|e| Over::Reason(e.to_string()))?; + // Measured in bytes: a cut inside a character is a file too big, not a file badly encoded. + if bytes.len() as u64 > MAX_THEME_BYTES { + return Err(Over::TooBig); } + String::from_utf8(bytes).map_err(|e| Over::Reason(e.to_string())) +} + +/// The refusal a file over the limit gets, the same from the folder and from the picker. +pub fn too_big(path: &std::path::Path) -> String { + let limit = (MAX_THEME_BYTES / 1024).to_string(); + why(path, &i18n::fmt("a theme file is at most {limit} KB", &[("limit", &limit)])) } /// A path and the reason it failed, as the menu shows it. @@ -207,6 +214,11 @@ fn tokens_id() -> egui::Id { egui::Id::unique("rustgis.theme.tokens") } +/// A theme file is a `.json` whatever the case of the extension. +fn is_theme_file(path: &std::path::Path) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case("json")) +} + /// A file's `metrics` block: every field optional, and an unknown name is reported by name. #[derive(serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] @@ -468,7 +480,7 @@ impl Theme { let Ok(read) = std::fs::read_dir(dir) else { return (themes, errors); }; - let mut files: Vec = read.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "json")).collect(); + let mut files: Vec = read.flatten().map(|e| e.path()).filter(|p| is_theme_file(p)).collect(); files.sort(); for path in files { let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); @@ -481,30 +493,27 @@ impl Theme { }, Err(e) => errors.push(why(&path, &e)), }, - Err(Over::TooBig) => { - let reason = i18n::fmt("larger than {bytes} bytes", &[("bytes", &MAX_THEME_BYTES.to_string())]); - errors.push(why(&path, &reason)); - } + Err(Over::TooBig) => errors.push(too_big(&path)), Err(Over::Reason(reason)) => errors.push(why(&path, &reason)), } } (themes, errors) } - /// Hash of each file's name and bytes, so a saved file is noticed even inside one mtime tick. + /// Hash of each file's name, size and mtime, from metadata alone: no file is read. pub fn folder_signature(dir: Option<&std::path::Path>) -> u64 { use std::hash::{Hash, Hasher}; let Some(dir) = dir else { return 0 }; let Ok(read) = std::fs::read_dir(dir) else { return 0 }; - let mut stamps: Vec<(String, u64)> = read + let mut stamps: Vec<(String, u64, u128)> = read .flatten() - .filter(|e| e.path().extension().is_some_and(|e| e == "json")) + .filter(|e| is_theme_file(&e.path())) .filter_map(|e| { let path = e.path(); - let bytes = std::fs::read(&path).ok()?; - let mut file = std::collections::hash_map::DefaultHasher::new(); - bytes.hash(&mut file); - Some((path.file_name()?.to_string_lossy().into_owned(), file.finish())) + let meta = e.metadata().ok()?; + // Metadata carries a std clock; this runs only where a themes folder exists. + let saved = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis(); + Some((path.file_name()?.to_string_lossy().into_owned(), meta.len(), saved)) }) .collect(); stamps.sort(); @@ -518,11 +527,31 @@ impl Theme { rustgis_engine::data::dirs::config_dir().map(|d| d.join("themes")) } + /// The file that holds this theme: its own name, or the next free one when another theme took it. + fn save_path(&self, dir: &std::path::Path) -> Result { + let stem = stem_of(&self.name); + for at in 1..=99 { + let name = if at == 1 { format!("{stem}.json") } else { format!("{stem}-{at}.json") }; + let path = dir.join(name); + match read_text(&path) { + Ok(text) => { + if Theme::parse(&stem, &text).is_ok_and(|found| found.name == self.name) { + return Ok(path); + } + } + // A file of another theme, or one too big to be read, is left alone. + Err(Over::TooBig) => {} + Err(Over::Reason(_)) => return Ok(path), + } + } + Err(why(dir, &i18n::fmt("no free file name for {name}", &[("name", &self.name)]))) + } + /// The file name of a theme, with each non-alphanumeric character as `-`. pub fn save_user(&self) -> Result { let dir = Self::user_dir().ok_or_else(|| i18n::fmt("No settings folder to keep a theme in.", &[]))?; std::fs::create_dir_all(&dir).map_err(|e| why(&dir, &e.to_string()))?; - let path = dir.join(format!("{}.json", stem_of(&self.name))); + let path = self.save_path(&dir)?; let text = self.to_json()?; backup_before_replace(&path, &text)?; std::fs::write(&path, text).map_err(|e| why(&path, &e.to_string()))?; @@ -610,6 +639,15 @@ fn backup_before_replace(path: &std::path::Path, text: &str) -> Result<(), Strin std::fs::write(&kept, old).map_err(|e| why(&kept, &e.to_string())) } +/// A value as a message shows it: long enough to recognise, short enough to stay one line. +fn clip(text: &str) -> String { + let mut out: String = text.chars().take(32).collect(); + if out.chars().count() < text.chars().count() { + out.push('…'); + } + out +} + /// The stem of a theme's file name; a name of marks and symbols still gets one. fn stem_of(name: &str) -> String { let dashed: String = name.chars().map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect(); @@ -619,12 +657,16 @@ fn stem_of(name: &str) -> String { /// A non-ASCII colour is refused before the byte cut, which would land inside a character. fn parse_colour(text: &str) -> Result { - let digits = text.strip_prefix('#').ok_or_else(|| i18n::fmt("is not a #RRGGBB colour: {text}", &[("text", text)]))?; - let bad = || i18n::fmt("is not a #RRGGBB or #RRGGBBAA colour: {text}", &[("text", text)]); + let shown = clip(text); + let digits = text.strip_prefix('#').ok_or_else(|| i18n::fmt("is not a #RRGGBB colour: {text}", &[("text", &shown)]))?; + let bad = || i18n::fmt("is not a #RRGGBB or #RRGGBBAA colour: {text}", &[("text", &shown)]); if !digits.chars().all(|c| c.is_ascii_hexdigit()) { return Err(bad()); } - let pair = |at: usize| u8::from_str_radix(&digits[at..at + 2], 16).map_err(|_| bad()); + let pair = |at: usize| { + let pair = digits.get(at..at + 2).ok_or_else(bad)?; + u8::from_str_radix(pair, 16).map_err(|_| bad()) + }; match digits.len() { 6 => Ok(Color32::from_rgb(pair(0)?, pair(2)?, pair(4)?)), 8 => Ok(Color32::from_rgba_unmultiplied(pair(0)?, pair(2)?, pair(4)?, pair(6)?)), @@ -1023,6 +1065,48 @@ mod tests { assert_eq!(std::fs::read_to_string(dir.join("mine.json.bak")).expect("the backup file"), edited); } + #[test] + fn two_names_that_share_a_stem_keep_two_files() { + let dir = theme_folder("rustgis-theme-stem-test", &[]); + let mut first = light(); + first.name = "Cobalt Blue".to_string(); + let first_at = first.save_path(&dir).expect("a free name"); + std::fs::write(&first_at, first.to_json().expect("json")).expect("the file"); + let mut second = light(); + second.name = "Cobalt-Blue".to_string(); + let second_at = second.save_path(&dir).expect("another free name"); + std::fs::write(&second_at, second.to_json().expect("json")).expect("the file"); + assert_ne!(first_at, second_at, "two themes that share a stem keep two files"); + assert_eq!(first.save_path(&dir).expect("its own file"), first_at, "a theme finds the file that holds it"); + let (found, errors) = Theme::available_in(Some(&dir)); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!(found.iter().filter(|t| t.name.starts_with("Cobalt")).count(), 2, "both load"); + } + + #[test] + fn a_theme_file_with_an_upper_case_extension_is_read() { + let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); + let dir = theme_folder("rustgis-theme-upper-test", &[("MINE.JSON", &mine)]); + let (found, errors) = Theme::available_in(Some(&dir)); + assert!(errors.is_empty(), "{errors:?}"); + assert!(found.iter().any(|t| t.name == "Mine"), "the file is read whatever the case of its extension"); + } + + #[test] + fn a_bad_value_is_echoed_short() { + assert_eq!(clip("abc"), "abc", "a short value is kept as it is"); + assert!(clip(&"x".repeat(500)).chars().count() <= 33, "a long value is cut to one line"); + } + + #[test] + fn a_file_over_the_limit_reports_the_limit_not_the_encoding() { + let dir = theme_folder("rustgis-theme-multibyte-test", &[]); + let path = dir.join("wide.json"); + // Two bytes each, so the cut lands inside a character. + std::fs::write(&path, "ą".repeat(MAX_THEME_BYTES as usize / 2 + 1)).expect("the file"); + assert!(matches!(read_text(&path), Err(Over::TooBig)), "the size is reported, not the encoding"); + } + #[test] fn a_theme_file_over_the_limit_is_not_read() { let dir = theme_folder("rustgis-theme-over-limit", &[]); From 67d364b9fd72e3e5d535c6f0a382b4d33925eb02 Mon Sep 17 00:00:00 2001 From: Wolren Date: Thu, 29 Oct 2026 23:49:28 +0100 Subject: [PATCH 11/28] fix(ui): a theme file is opened only when it is a file, and the button never names a theme it lost Findings from the fourth review of the pull request: - read_text opened whatever the folder held, and opening a pipe named .json blocks before any bound applies. The file type is checked first, so only a plain file is opened. - A theme that was deleted or stopped parsing kept its name in the button while another theme was drawn. A name that no longer loads is dropped. - The theme fallback always drew Light, so a folder theme that calls itself Dark while it is light left a dark request drawing light tokens. The fallback takes the built-in theme of the brightness asked for. - The scale menu dropped its command's error while the theme menu reports one. Both go through one notifier now. - The kept copy of a replaced theme was read without the size bound. It uses the same bounded read as the rest. --- crates/ui-egui/src/lib.rs | 44 ++++++++++++++++++++++++++++++++---- crates/ui-egui/src/ribbon.rs | 13 ++++++----- crates/ui-egui/src/theme.rs | 19 ++++++++++++++-- 3 files changed, 63 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8b0289145b..064635d045 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1638,10 +1638,18 @@ impl RustGisApp { self.themes = themes; self.theme_errors = errors; self.sync_named_brightness(); + self.drop_missing_name(); // Reset so a file that reads differently is applied again on the next frame. self.applied_theme = None; } + /// A theme that was deleted or stopped loading is not named: the button names what is drawn. + fn drop_missing_name(&mut self) { + if !self.ui.theme_name.is_empty() && !self.themes.iter().any(|t| t.name == self.ui.theme_name) { + self.ui.theme_name.clear(); + } + } + /// A file saved as the other brightness takes the interface with it, so name and look agree. fn sync_named_brightness(&mut self) { if self.ui.theme_name.is_empty() { @@ -1673,11 +1681,15 @@ impl RustGisApp { .find(|t| t.name == self.ui.theme_name && t.dark == self.ui.dark) .or_else(|| self.themes.iter().find(|t| t.dark == self.ui.dark)) .cloned() - .unwrap_or(theme::Theme { - name: "Light".to_string(), - dark: false, - tokens: theme::Tokens::light(), - metrics: theme::Metrics::standard(), + .unwrap_or_else(|| { + let builtin = theme::Theme::builtin(); + let wanted = builtin.iter().find(|t| t.dark == self.ui.dark).or_else(|| builtin.first()); + wanted.cloned().unwrap_or(theme::Theme { + name: "Light".to_string(), + dark: false, + tokens: theme::Tokens::light(), + metrics: theme::Metrics::standard(), + }) }) } @@ -4843,6 +4855,28 @@ mod look_tests { assert!((ctx.zoom_factor() - 2.0).abs() < 0.001, "and the context is put back to the menu's value"); } + #[test] + fn a_theme_that_stopped_loading_is_not_named() { + let mut app = app_with(&[]); + app.themes = vec![builtin(false), builtin(true)]; + app.ui.theme_name = "Gone".to_string(); + app.drop_missing_name(); + assert!(app.ui.theme_name.is_empty(), "the name is dropped"); + assert_eq!(app.current_theme().name, "Light", "and the button names the theme that is drawn"); + } + + #[test] + fn the_fallback_takes_the_brightness_asked_for() { + let mut app = app_with(&[]); + // A folder theme that calls itself Dark while it is light: nothing loaded matches dark. + let mut lied = builtin(false); + lied.name = "Dark".to_string(); + app.themes = vec![lied]; + app.ui.dark = true; + app.ui.theme_name = "Dark".to_string(); + assert!(app.current_theme().dark, "the drawn theme is a dark one, as asked"); + } + #[test] fn the_theme_command_lands_on_the_brightness_it_is_given() { let mut app = app_with(&[]); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index f8201f24b4..ff67c95c2b 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3521,24 +3521,24 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { follow = follow.on_disabled_hover_text(tl!("This platform does not report the system theme")); } if follow.clicked() { - theme_action(app, "ui.themeFile", Value::Null); + run_notified(app, "ui.themeFile", Value::Null); ui.close(); } for found in &themes { let picked = app.ui.theme_name == found.name; if ui.add(egui::Button::selectable(picked, found.name.as_str())).clicked() { - theme_action(app, "ui.themeFile", json!({ "name": found.name })); + run_notified(app, "ui.themeFile", json!({ "name": found.name })); ui.close(); } } if folder { ui.separator(); if ui.add(egui::Button::selectable(false, tl!("Load a Theme from File…"))).clicked() { - theme_action(app, "ui.themeLoad", Value::Null); + run_notified(app, "ui.themeLoad", Value::Null); ui.close(); } if ui.add(egui::Button::selectable(false, tl!("Reload Themes"))).clicked() { - theme_action(app, "ui.themeReload", Value::Null); + run_notified(app, "ui.themeReload", Value::Null); ui.close(); } } @@ -3554,7 +3554,8 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { } /// A failed action is notified, not swallowed. -fn theme_action(app: &mut RustGisApp, id: &str, params: Value) { +/// Runs a UI command and shows the reason when it fails. +fn run_notified(app: &mut RustGisApp, id: &str, params: Value) { if let Err(e) = app.run(id, params) { app.session.notify(e, true); } @@ -3569,7 +3570,7 @@ fn scale_menu(app: &mut RustGisApp, ui: &mut Ui) { let factor = percent as f32 / 100.0; let picked = (app.ui.interface_scale - factor).abs() < 0.001; if ui.add(egui::Button::selectable(picked, format!("{percent}%"))).clicked() { - let _ = app.run("ui.scale", json!({ "factor": factor })); + run_notified(app, "ui.scale", json!({ "factor": factor })); ui.close(); } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 44478e0d83..7f61e93021 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -24,6 +24,11 @@ pub enum Over { /// Reads a theme file without trusting its length: a pipe or a device cannot exhaust memory. pub fn read_text(path: &std::path::Path) -> Result { use std::io::Read; + // Only a plain file is opened: opening a pipe blocks until a writer arrives. + let meta = std::fs::metadata(path).map_err(|e| Over::Reason(e.to_string()))?; + if !meta.file_type().is_file() { + return Err(Over::Reason(i18n::fmt("this is not a file", &[]))); + } let file = std::fs::File::open(path).map_err(|e| Over::Reason(e.to_string()))?; let mut bytes = Vec::new(); file.take(MAX_THEME_BYTES + 1).read_to_end(&mut bytes).map_err(|e| Over::Reason(e.to_string()))?; @@ -631,8 +636,9 @@ fn clean_name(name: &str) -> String { /// Keeps the file it replaces beside it as `.json.bak`: a folder copy may hold edits. fn backup_before_replace(path: &std::path::Path, text: &str) -> Result<(), String> { - let Ok(old) = std::fs::read(path) else { return Ok(()) }; - if old == text.as_bytes() { + // The same bound as any other read: a file over the limit is left alone, not loaded whole. + let Ok(old) = read_text(path) else { return Ok(()) }; + if old == text { return Ok(()); } let kept = path.with_extension("json.bak"); @@ -1092,6 +1098,15 @@ mod tests { assert!(found.iter().any(|t| t.name == "Mine"), "the file is read whatever the case of its extension"); } + #[test] + fn only_a_plain_file_is_opened() { + let dir = theme_folder("rustgis-theme-dir-test", &[]); + match read_text(&dir) { + Err(Over::Reason(why)) => assert!(why.contains("not a file"), "{why}"), + other => panic!("{other:?}"), + } + } + #[test] fn a_bad_value_is_echoed_short() { assert_eq!(clip("abc"), "abc", "a short value is kept as it is"); From a0599c65545c1e131ec5bc83738faf2301c515bb Mon Sep 17 00:00:00 2001 From: Wolren Date: Tue, 3 Nov 2026 11:38:20 +0100 Subject: [PATCH 12/28] fix(ui): the chosen theme keeps its name until its file loads again Findings from the fifth review of the pull request: - load_themes cleared the chosen theme name when a file stopped parsing, so a typo fixed while the app ran never brought the theme back. The name stays as the choice, and the window draws the nearest theme while the button names it. - A saved theme that did not load at start lost its name the same way. The saved name waits, so a file that appears later is drawn without picking it again. - A theme that loaded while Follow the System was set kept following, and the platform brightness overwrote the theme's own. A loaded theme owns its brightness. - Two files that claim one name: the first in name order is used, and the second is reported in the menu instead of replacing it silently. - One backup is kept per theme file, replaced on each save. The docs said a copy was kept and named no limit. --- crates/ui-egui/src/lib.rs | 140 +++++++++++++++++++++++------------- crates/ui-egui/src/theme.rs | 34 +++++++-- docs/themes.md | 12 ++-- 3 files changed, 127 insertions(+), 59 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 064635d045..596b2a0568 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1632,24 +1632,21 @@ impl RustGisApp { } fn load_themes(&mut self) { - // The stamp before the read, so a save between the two is loaded again rather than lost. - self.themes_stamp = theme::Theme::folder_signature(theme::Theme::user_dir().as_deref()); - let (themes, errors) = theme::Theme::available(); + self.load_themes_from(theme::Theme::user_dir().as_deref()); + } + + /// Reads the folder; the stamp is taken first, so a save during the read is picked up next time. + fn load_themes_from(&mut self, dir: Option<&std::path::Path>) { + self.themes_stamp = theme::Theme::folder_signature(dir); + let (themes, errors) = theme::Theme::available_in(dir); self.themes = themes; self.theme_errors = errors; + // The choice outlives the file: a theme that stopped loading keeps its name. self.sync_named_brightness(); - self.drop_missing_name(); // Reset so a file that reads differently is applied again on the next frame. self.applied_theme = None; } - /// A theme that was deleted or stopped loading is not named: the button names what is drawn. - fn drop_missing_name(&mut self) { - if !self.ui.theme_name.is_empty() && !self.themes.iter().any(|t| t.name == self.ui.theme_name) { - self.ui.theme_name.clear(); - } - } - /// A file saved as the other brightness takes the interface with it, so name and look agree. fn sync_named_brightness(&mut self) { if self.ui.theme_name.is_empty() { @@ -1657,6 +1654,8 @@ impl RustGisApp { } if let Some(dark) = self.themes.iter().find(|t| t.name == self.ui.theme_name).map(|t| t.dark) { self.ui.dark = dark; + // The loaded theme owns its brightness; following the platform would overwrite it. + self.ui.dark_follows_system = false; } } @@ -1674,23 +1673,23 @@ impl RustGisApp { } } - /// The theme in use: the one named, else the nearest built-in theme for the current brightness. + /// The theme drawn: the one named while it loads, else the nearest of the brightness in force. + fn drawn(&self) -> Option<&theme::Theme> { + self.themes.iter().find(|t| t.name == self.ui.theme_name).or_else(|| self.themes.iter().find(|t| t.dark == self.ui.dark)) + } + + /// The theme in use: the one named, else the nearest built-in for the current brightness. pub fn current_theme(&self) -> theme::Theme { - self.themes - .iter() - .find(|t| t.name == self.ui.theme_name && t.dark == self.ui.dark) - .or_else(|| self.themes.iter().find(|t| t.dark == self.ui.dark)) - .cloned() - .unwrap_or_else(|| { - let builtin = theme::Theme::builtin(); - let wanted = builtin.iter().find(|t| t.dark == self.ui.dark).or_else(|| builtin.first()); - wanted.cloned().unwrap_or(theme::Theme { - name: "Light".to_string(), - dark: false, - tokens: theme::Tokens::light(), - metrics: theme::Metrics::standard(), - }) + self.drawn().cloned().unwrap_or_else(|| { + let builtin = theme::Theme::builtin(); + let wanted = builtin.iter().find(|t| t.dark == self.ui.dark).or_else(|| builtin.first()); + wanted.cloned().unwrap_or(theme::Theme { + name: "Light".to_string(), + dark: false, + tokens: theme::Tokens::light(), + metrics: theme::Metrics::standard(), }) + }) } /// A saved theme name wins; one that no longer loads follows the system. @@ -1699,15 +1698,19 @@ impl RustGisApp { app.services.load_pref.as_ref().and_then(|load| load(key)).filter(|v| !v.is_empty()) }; let wanted = pref(self, "theme"); - let picked = wanted.and_then(|name| self.themes.iter().find(|t| t.name == name).cloned()); + let picked = wanted.as_ref().and_then(|name| self.themes.iter().find(|t| t.name == *name).cloned()); if let Some(picked) = picked { self.ui.theme_name = picked.name; self.ui.dark = picked.dark; self.ui.dark_follows_system = false; - } else if let Some(dark) = pref(self, "dark") { - // "auto" was Follow the System; a toggle stores the brightness it left. - self.ui.dark = dark == "true"; - self.ui.dark_follows_system = dark == "auto"; + } else { + // A saved theme keeps its name until its file loads, so a fixed file is drawn again. + self.ui.theme_name = wanted.unwrap_or_default(); + if let Some(dark) = pref(self, "dark") { + // "auto" was Follow the System; a toggle stores the brightness it left. + self.ui.dark = dark == "true"; + self.ui.dark_follows_system = dark == "auto"; + } } let scale = pref(self, "ui_scale").and_then(|v| v.parse::().ok()); self.ui.interface_scale = scale.map_or(1.0, theme::clamp_scale); @@ -4207,14 +4210,14 @@ impl RustGisApp { } } - /// The entry the Theme button names. A platform that reports no theme cannot be followed, so - /// the brightness in force is named instead. winit reports no system theme on Linux. + /// The Theme button's entry: the drawn name, or Follow the System where the platform reports one. pub fn theme_shown(&self, system_reports: bool) -> (bool, String) { let follows = self.ui.theme_name.is_empty() && self.ui.dark_follows_system && system_reports; - let name = if !self.ui.theme_name.is_empty() { - self.ui.theme_name.clone() - } else if follows { + let name = if follows { tl!("Follow the System").to_string() + } else if let Some(drawn) = self.drawn() { + // The drawn theme is named: a file that stopped loading is not. + drawn.name.clone() } else if self.ui.dark { tl!("Dark").to_string() } else { @@ -4856,24 +4859,57 @@ mod look_tests { } #[test] - fn a_theme_that_stopped_loading_is_not_named() { + fn a_choice_outlives_a_file_that_stops_loading() { + let dir = tempfile::tempdir().expect("a temporary folder"); + let path = dir.path().join("cobalt.json"); + let mut cobalt = builtin(true); + cobalt.name = "Cobalt".to_string(); + let good = cobalt.to_json().expect("json"); + std::fs::write(&path, &good).expect("the file"); let mut app = app_with(&[]); - app.themes = vec![builtin(false), builtin(true)]; - app.ui.theme_name = "Gone".to_string(); - app.drop_missing_name(); - assert!(app.ui.theme_name.is_empty(), "the name is dropped"); - assert_eq!(app.current_theme().name, "Light", "and the button names the theme that is drawn"); + app.load_themes_from(Some(dir.path())); + app.use_theme("Cobalt").expect("the file loads"); + assert_eq!(app.theme_shown(true).1, "Cobalt"); + // A save that does not parse: the folder drops the theme, the choice stays. + std::fs::write(&path, "{\"schema\": 1, ").expect("the broken file"); + app.load_themes_from(Some(dir.path())); + assert_eq!(app.ui.theme_name, "Cobalt", "the choice outlives the file"); + assert_eq!(app.current_theme().name, "Dark", "the nearest theme is drawn"); + assert_eq!(app.theme_shown(true).1, "Dark", "and the button names it"); + // The typo is fixed: the choice is drawn again without picking it again. + std::fs::write(&path, &good).expect("the file"); + app.load_themes_from(Some(dir.path())); + assert_eq!(app.current_theme().name, "Cobalt", "the choice is restored"); + assert_eq!(app.theme_shown(true).1, "Cobalt"); + } + + #[test] + fn a_live_edit_that_changes_the_brightness_is_followed() { + let dir = tempfile::tempdir().expect("a temporary folder"); + let path = dir.path().join("cobalt.json"); + let mut cobalt = builtin(true); + cobalt.name = "Cobalt".to_string(); + std::fs::write(&path, cobalt.to_json().expect("json")).expect("the file"); + let mut app = app_with(&[]); + app.load_themes_from(Some(dir.path())); + app.use_theme("Cobalt").expect("the file loads"); + // The same file saved as a light theme: the interface takes its brightness with it. + cobalt.dark = false; + cobalt.tokens = theme::Tokens::light(); + std::fs::write(&path, cobalt.to_json().expect("json")).expect("the file"); + app.load_themes_from(Some(dir.path())); + assert!(!app.ui.dark, "the interface takes the brightness of the theme it names"); + assert_eq!(app.current_theme().name, "Cobalt", "the named theme is drawn"); + assert_eq!(app.theme_shown(true).1, "Cobalt"); } #[test] fn the_fallback_takes_the_brightness_asked_for() { let mut app = app_with(&[]); - // A folder theme that calls itself Dark while it is light: nothing loaded matches dark. - let mut lied = builtin(false); - lied.name = "Dark".to_string(); - app.themes = vec![lied]; + // Only a light theme loads and the interface asks for dark: the built-in dark is drawn. + app.themes = vec![builtin(false)]; app.ui.dark = true; - app.ui.theme_name = "Dark".to_string(); + app.ui.theme_name = "Gone".to_string(); assert!(app.current_theme().dark, "the drawn theme is a dark one, as asked"); } @@ -4934,10 +4970,18 @@ mod look_tests { fn a_saved_theme_that_is_gone_leaves_the_saved_brightness() { let mut app = app_with(&[("theme", "Deleted"), ("dark", "true")]); app.take_saved_look(); - assert!(app.ui.theme_name.is_empty(), "no theme file is named"); + assert_eq!(app.ui.theme_name, "Deleted", "the choice waits for a file of that name"); assert!(app.ui.dark, "Dark Mode was on when it was last closed"); assert!(!app.ui.dark_follows_system); + assert_eq!(app.theme_shown(true).1, "Dark", "the button names the theme drawn"); assert_eq!(app.ui.interface_scale, 1.0, "no scale saved is the normal one"); + // The file appears later: the saved choice is drawn without picking it again. + let dir = tempfile::tempdir().expect("a temporary folder"); + let mut saved = builtin(false); + saved.name = "Deleted".to_string(); + std::fs::write(dir.path().join("deleted.json"), saved.to_json().expect("json")).expect("the file"); + app.load_themes_from(Some(dir.path())); + assert_eq!(app.current_theme().name, "Deleted", "the saved choice is restored"); } fn builtin(dark: bool) -> theme::Theme { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 7f61e93021..9715c5d6f9 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -487,15 +487,26 @@ impl Theme { }; let mut files: Vec = read.flatten().map(|e| e.path()).filter(|p| is_theme_file(p)).collect(); files.sort(); + // A name set by one file cannot be set by another: the second is reported, not silently lost. + let mut claimed: BTreeMap = BTreeMap::new(); for path in files { let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); match read_text(&path) { Ok(text) => match Theme::parse(&stem, &text) { - // A user file named as a built-in replaces it, so a name picks one theme. - Ok(theme) => match themes.iter_mut().find(|t| t.name == theme.name) { - Some(replaced) => *replaced = theme, - None => themes.push(theme), - }, + Ok(theme) => { + if let Some(first) = claimed.get(&theme.name) { + let other = first.display().to_string(); + let reason = i18n::fmt("{name} is already set by {path}", &[("name", theme.name.as_str()), ("path", &other)]); + errors.push(why(&path, &reason)); + continue; + } + claimed.insert(theme.name.clone(), path.clone()); + // A user file named as a built-in replaces it, so a name picks one theme. + match themes.iter_mut().find(|t| t.name == theme.name) { + Some(replaced) => *replaced = theme, + None => themes.push(theme), + } + } Err(e) => errors.push(why(&path, &e)), }, Err(Over::TooBig) => errors.push(too_big(&path)), @@ -634,7 +645,7 @@ fn clean_name(name: &str) -> String { if kept.is_empty() { "Theme".to_string() } else { kept.to_string() } } -/// Keeps the file it replaces beside it as `.json.bak`: a folder copy may hold edits. +/// The file it replaces is kept as `.json.bak`: one backup, replaced on each save. fn backup_before_replace(path: &std::path::Path, text: &str) -> Result<(), String> { // The same bound as any other read: a file over the limit is left alone, not loaded whole. let Ok(old) = read_text(path) else { return Ok(()) }; @@ -1041,6 +1052,17 @@ mod tests { assert_eq!(theme.tokens.pane, Theme::builtin()[0].tokens.pane, "and the colours it extends stay"); } + #[test] + fn a_name_two_files_claim_is_reported_once() { + let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); + let dir = theme_folder("rustgis-theme-duplicate-test", &[("a.json", &mine), ("b.json", &mine)]); + let (found, errors) = Theme::available_in(Some(&dir)); + assert_eq!(found.iter().filter(|t| t.name == "Mine").count(), 1, "one Mine is offered"); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert!(errors[0].contains("already set by"), "{errors:?}"); + assert!(errors[0].contains("a.json"), "the error names the file that holds it: {errors:?}"); + } + #[test] fn a_name_of_symbols_still_gets_a_file_name() { assert_eq!(stem_of("★★★"), "theme", "a name with no letters or digits still saves"); diff --git a/docs/themes.md b/docs/themes.md index 99a153cf2c..62c7f0c4dd 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -15,7 +15,8 @@ The config folder is `%APPDATA%\RustGIS` on Windows, `~/Library/Application Supp macOS and `$XDG_CONFIG_HOME/rustgis` elsewhere. `RUSTGIS_CONFIG_DIR` overrides it. A user file whose `name` matches a built-in replaces it. A reworked Light sits in the folder as -`light.json`, and the menu lists one Light. +`light.json`, and the menu lists one Light. Two files that claim the same name: the first in name +order is used, and the second is listed in red. ## Picking one @@ -37,13 +38,14 @@ differs. To start from a theme you already have, use **Load a Theme from File…**. The app keeps a copy in the themes folder; edit that copy and the app follows it. Loading a file whose `name` matches a theme -already in the folder replaces that copy, and the copy it replaces is kept beside it as -`.json.bak`. A file that does not load is listed in red at the bottom of the same menu, with -the token at fault. +already in the folder replaces that copy, and the version it replaces is kept beside it as +`.json.bak`: one backup, replaced on each save. A file that does not load is listed in red at +the bottom of the same menu, with the token at fault. A saved file is picked up within a second, without pressing **Reload Themes**: the app watches the folder while it runs. A theme in use that stops loading leaves the window on the nearest built-in -until it loads again, and the menu gives the reason. +until it loads again: the button names the theme drawn, the menu gives the reason, and the choice +returns with the file. ## A short theme From 27e174d8d46b59d0ffb13f24395d5328c9fee53f Mon Sep 17 00:00:00 2001 From: Wolren Date: Tue, 3 Nov 2026 12:21:13 +0100 Subject: [PATCH 13/28] fix(ui): say what the theme reader changed, and name the theme drawn - A theme file that cannot be read is skipped, never overwritten without a backup. - ui.theme names the theme it draws, so the button and the menu agree. - Sizes held to the window, dropped control characters and cut names are said once. - Refused files and an unreadable folder are said once through Session::notify. - Built-in Light and Dark are translated in the button and the menu. - Test folders are unique per run; the guide example is checked against light.json. --- crates/ui-egui/src/i18n/az.tsv | 2 + crates/ui-egui/src/i18n/bn.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fa.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/tests.rs | 10 ++ crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh.tsv | 2 + crates/ui-egui/src/lib.rs | 94 +++++++++++- crates/ui-egui/src/ribbon.rs | 21 +-- crates/ui-egui/src/theme.rs | 242 +++++++++++++++++++++++-------- docs/themes.md | 5 +- 23 files changed, 330 insertions(+), 78 deletions(-) diff --git a/crates/ui-egui/src/i18n/az.tsv b/crates/ui-egui/src/i18n/az.tsv index e490468670..cf6c57837a 100644 --- a/crates/ui-egui/src/i18n/az.tsv +++ b/crates/ui-egui/src/i18n/az.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Simulyasiya et +Light İşıqlı +Dark Qaranlıq diff --git a/crates/ui-egui/src/i18n/bn.tsv b/crates/ui-egui/src/i18n/bn.tsv index 56ee123d4e..b8c66fbf07 100644 --- a/crates/ui-egui/src/i18n/bn.tsv +++ b/crates/ui-egui/src/i18n/bn.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ সিমুলেট করুন +Light হালকা +Dark গাঢ় diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index fb460e50df..4cbeb1d9a4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Simulieren +Light Hell +Dark Dunkel diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 812e12f347..924c8de579 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Simular +Light Claro +Dark Oscuro diff --git a/crates/ui-egui/src/i18n/fa.tsv b/crates/ui-egui/src/i18n/fa.tsv index d8829f67a3..fa0f00f535 100644 --- a/crates/ui-egui/src/i18n/fa.tsv +++ b/crates/ui-egui/src/i18n/fa.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ شبیه‌سازی +Light روشن +Dark تاریک diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index a56408583e..80d328b064 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Simuler +Light Clair +Dark Sombre diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 81290f1bd0..705a2119ad 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4025,3 +4025,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Simulasikan +Light Terang +Dark Gelap diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1414c035c9..83d62f7770 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Simula +Light Chiaro +Dark Scuro diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d6be46f015..30612c78aa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ シミュレート +Light ライト +Dark ダーク diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index efafa10b61..f90cab2fc2 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ სიმულაცია +Light ღია +Dark მუქი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 39cb500c04..f146e5bd18 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ 시뮬레이션 +Light 라이트 +Dark 다크 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d88ada328f..327140ab30 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Simuleren +Light Licht +Dark Donker diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index da622139b8..c101f7d9ec 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Symuluj +Light Jasny +Dark Ciemny diff --git a/crates/ui-egui/src/i18n/pt.tsv b/crates/ui-egui/src/i18n/pt.tsv index df4a963a3b..6da951e519 100644 --- a/crates/ui-egui/src/i18n/pt.tsv +++ b/crates/ui-egui/src/i18n/pt.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Simular +Light Claro +Dark Escuro diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3425996915..2994ddce37 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Смоделировать +Light Светлая +Dark Тёмная diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index a7458a6068..f73fd701ff 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -24,6 +24,16 @@ fn every_catalog_parses_cleanly_and_keeps_placeholders() { } } +#[test] +fn every_catalog_names_the_built_in_themes() { + for l in &LANGUAGES[1..] { + let (m, _) = parse(l.source); + for key in ["Light", "Dark"] { + assert!(m.contains_key(key), "{}: no {key} label", l.code); + } + } +} + #[test] fn lookup_fallback_and_tags() { assert_eq!(tr(Lang::EN, "Explore"), "Explore"); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef824031b5..deec5778ce 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Canlandır +Light Açık +Dark Koyu diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4aef7c7d6b..5a2ce8130c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ Mô phỏng +Light Sáng +Dark Tối diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index a4da4ceb5e..a72445b862 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -4024,3 +4024,5 @@ Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top ⌘+Enter ⌘+Enter ⌘K ⌘K ▶ Simulate ▶ 模拟 +Light 浅色 +Dark 深色 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 596b2a0568..30341068d2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -918,6 +918,8 @@ pub struct RustGisApp { pub themes: Vec, /// The theme files that did not load, with the reason. pub theme_errors: Vec, + /// What the reader changed in the loaded theme files, as the menu lists it. + pub theme_notes: Vec, themes_stamp: u64, themes_checked: f64, sent_title: String, @@ -1094,6 +1096,7 @@ impl RustGisApp { applied_theme: None, themes: Vec::new(), theme_errors: Vec::new(), + theme_notes: Vec::new(), themes_stamp: 0, themes_checked: 0.0, sent_title: String::new(), @@ -1639,14 +1642,42 @@ impl RustGisApp { fn load_themes_from(&mut self, dir: Option<&std::path::Path>) { self.themes_stamp = theme::Theme::folder_signature(dir); let (themes, errors) = theme::Theme::available_in(dir); + let notes: Vec = themes.iter().flat_map(|t| t.notes.iter().cloned()).collect(); + // Said before the new lists are kept, so only what the last read did not report is said. + self.announce_theme_errors(&errors); + self.announce_theme_notes(¬es); self.themes = themes; self.theme_errors = errors; + self.theme_notes = notes; // The choice outlives the file: a theme that stopped loading keeps its name. self.sync_named_brightness(); // Reset so a file that reads differently is applied again on the next frame. self.applied_theme = None; } + /// A refused file is said once, with a count; the menu keeps the reason for each. + fn announce_theme_errors(&mut self, errors: &[String]) { + let fresh = errors.iter().filter(|e| !self.theme_errors.contains(*e)).count(); + if fresh == 0 { + return; + } + let text = if fresh == 1 { + tl!("A theme file was refused. Open Settings > Theme for the reason.").to_string() + } else { + i18n::fmt("{n} theme files were refused. Open Settings > Theme for the reason.", &[("n", &fresh.to_string())]) + }; + self.session.notify(text, true); + } + + /// A value the reader had to change is said once, in the words the theme file reader wrote. + fn announce_theme_notes(&mut self, notes: &[String]) { + for note in notes { + if !self.theme_notes.contains(note) { + self.session.notify(note.clone(), false); + } + } + } + /// A file saved as the other brightness takes the interface with it, so name and look agree. fn sync_named_brightness(&mut self) { if self.ui.theme_name.is_empty() { @@ -1688,6 +1719,7 @@ impl RustGisApp { dark: false, tokens: theme::Tokens::light(), metrics: theme::Metrics::standard(), + notes: Vec::new(), }) }) } @@ -2398,8 +2430,14 @@ impl RustGisApp { // The brightness asked for wins: a user file may rework Light or Dark. self.ui.dark = dark; let wanted = if dark { "Dark" } else { "Light" }; - self.ui.theme_name = - self.themes.iter().find(|t| t.name == wanted && t.dark == dark).map(|t| t.name.clone()).unwrap_or_default(); + // The name is the theme that will be drawn, so the button and the menu agree. + self.ui.theme_name = self + .themes + .iter() + .find(|t| t.name == wanted && t.dark == dark) + .or_else(|| self.themes.iter().find(|t| t.dark == dark)) + .map(|t| t.name.clone()) + .unwrap_or_default(); self.ui.dark_follows_system = false; if let Some(save) = &self.services.save_pref { save("theme", &self.ui.theme_name); @@ -4217,11 +4255,11 @@ impl RustGisApp { tl!("Follow the System").to_string() } else if let Some(drawn) = self.drawn() { // The drawn theme is named: a file that stopped loading is not. - drawn.name.clone() + theme::label(&drawn.name) } else if self.ui.dark { - tl!("Dark").to_string() + theme::label("Dark") } else { - tl!("Light").to_string() + theme::label("Light") }; (follows, name) } @@ -4776,6 +4814,7 @@ mod look_tests { dark: true, tokens: theme::Tokens::dark(), metrics: theme::Metrics::standard(), + notes: Vec::new(), }); app.services.load_pref = Some(Box::new(move |key: &str| prefs.iter().find(|(k, _)| *k == key).map(|(_, v)| (*v).to_string()))); app @@ -4984,6 +5023,51 @@ mod look_tests { assert_eq!(app.current_theme().name, "Deleted", "the saved choice is restored"); } + #[test] + fn the_theme_command_names_the_theme_it_draws() { + let mut app = app_with(&[]); + app.take_saved_look(); + // The built-in Dark replaced by a light-flagged file, and a dark user theme beside it. + let mut dark_named_light = builtin(false); + dark_named_light.name = "Dark".to_string(); + let mut cobalt = builtin(true); + cobalt.name = "Cobalt".to_string(); + app.themes = vec![builtin(false), dark_named_light, cobalt]; + app.run("ui.theme", serde_json::json!({ "dark": true })).expect("the command"); + assert_eq!(app.ui.theme_name, "Cobalt", "the name follows the theme drawn"); + assert_eq!(app.current_theme().name, "Cobalt"); + assert_eq!(app.theme_shown(true).1, "Cobalt"); + } + + #[test] + fn a_refused_theme_file_is_said_once() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let dir = tempfile::tempdir().expect("a temporary folder"); + std::fs::write(dir.path().join("half.json"), "{\"schema\": 1}").expect("the file"); + let mut app = app_with(&[]); + let said = |app: &RustGisApp| app.session.notices.iter().filter(|n| n.text.contains("refused")).count(); + let before = said(&app); + app.load_themes_from(Some(dir.path())); + assert_eq!(said(&app) - before, 1, "the refusal is said"); + app.load_themes_from(Some(dir.path())); + assert_eq!(said(&app) - before, 1, "the same refusal is not repeated"); + } + + #[test] + fn a_held_size_is_said_once() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let dir = tempfile::tempdir().expect("a temporary folder"); + let text = r#"{"schema": 1, "name": "Mine", "extends": "Light", "metrics": {"body": 1e9}}"#; + std::fs::write(dir.path().join("mine.json"), text).expect("the file"); + let mut app = app_with(&[]); + let said = |app: &RustGisApp| app.session.notices.iter().filter(|n| n.text.contains("held to what the window draws")).count(); + let before = said(&app); + app.load_themes_from(Some(dir.path())); + assert_eq!(said(&app) - before, 1, "the held size is said"); + app.load_themes_from(Some(dir.path())); + assert_eq!(said(&app) - before, 1, "and not again on the next watch tick"); + } + fn builtin(dark: bool) -> theme::Theme { theme::Theme::builtin().into_iter().find(|t| t.dark == dark).expect("a built-in theme ships") } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index ff67c95c2b..a436f67380 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3505,8 +3505,9 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { let system = ui.ctx().system_theme().is_some(); let (follows, current) = app.theme_shown(system); let label = format!("{}\n{current}", tl!("Theme")); - let themes = app.themes.clone(); + let themes: Vec = app.themes.iter().map(|t| t.name.clone()).collect(); let errors = app.theme_errors.clone(); + let notes = app.theme_notes.clone(); // The browser has no settings folder to read theme files from or write one to. let folder = crate::theme::Theme::user_dir().is_some(); big_menu( @@ -3524,10 +3525,10 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { run_notified(app, "ui.themeFile", Value::Null); ui.close(); } - for found in &themes { - let picked = app.ui.theme_name == found.name; - if ui.add(egui::Button::selectable(picked, found.name.as_str())).clicked() { - run_notified(app, "ui.themeFile", json!({ "name": found.name })); + for name in &themes { + let picked = app.ui.theme_name == *name; + if ui.add(egui::Button::selectable(picked, crate::theme::label(name))).clicked() { + run_notified(app, "ui.themeFile", json!({ "name": name })); ui.close(); } } @@ -3542,18 +3543,20 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { ui.close(); } } - if !errors.is_empty() { + if !errors.is_empty() || !notes.is_empty() { ui.separator(); - let red = Tokens::get(ui.ctx()).red; + let tokens = Tokens::get(ui.ctx()); for error in &errors { - ui.label(egui::RichText::new(error).color(red).small()); + ui.label(egui::RichText::new(error).color(tokens.red).small()); + } + for note in ¬es { + ui.label(egui::RichText::new(note).color(tokens.text_dim).small()); } } }, ); } -/// A failed action is notified, not swallowed. /// Runs a UI command and shows the reason when it fails. fn run_notified(app: &mut RustGisApp, id: &str, params: Value) { if let Err(e) = app.run(id, params) { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9715c5d6f9..f29b175061 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -295,7 +295,7 @@ impl MetricsFile { } } -#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Metrics { pub item_spacing: [f32; 2], @@ -324,11 +324,11 @@ impl Metrics { } } - /// Held to what a window draws; a value that is not a number takes the standard. - pub fn clamped(self) -> Self { + /// Held to what a window draws, and how many values it had to hold. + pub fn clamped(self) -> (Self, usize) { let fit = |v: f32, lo: f32, hi: f32, otherwise: f32| if v.is_finite() { v.clamp(lo, hi) } else { otherwise }; let std = Metrics::standard(); - Metrics { + let metrics = Metrics { item_spacing: [ fit(self.item_spacing[0], 0.0, 40.0, std.item_spacing[0]), fit(self.item_spacing[1], 0.0, 40.0, std.item_spacing[1]), @@ -344,7 +344,8 @@ impl Metrics { small: fit(self.small, 5.0, 32.0, std.small), heading: fit(self.heading, 8.0, 60.0, std.heading), mono: fit(self.mono, 5.0, 40.0, std.mono), - } + }; + (metrics, held_count(self, metrics)) } } @@ -359,6 +360,8 @@ pub struct Theme { pub dark: bool, pub tokens: Tokens, pub metrics: Metrics, + /// What the reader changed to make the file load, said once where it is read. + pub notes: Vec, } #[derive(serde::Deserialize, serde::Serialize)] @@ -388,6 +391,7 @@ impl Theme { dark: fallback.dark, tokens: fallback, metrics: Metrics::standard(), + notes: Vec::new(), }) }) .collect() @@ -398,7 +402,8 @@ impl Theme { // Notepad saves UTF-8 with a byte-order mark, which serde refuses at the first byte. let text = text.trim_start_matches('\u{feff}'); let raw: Raw = serde_json::from_str(text).map_err(|e| e.to_string())?; - let name = clean_name(if raw.name.trim().is_empty() { fallback_name } else { raw.name.trim() }); + let mut notes = Vec::new(); + let name = clean_name(if raw.name.trim().is_empty() { fallback_name } else { raw.name.trim() }, &mut notes); if raw.schema != SCHEMA { return Err(i18n::fmt( "{name}: theme schema {found} is not {schema}", @@ -436,6 +441,7 @@ impl Theme { dark: raw.dark.unwrap_or(false), tokens: if raw.dark.unwrap_or(false) { Tokens::dark() } else { Tokens::light() }, metrics: Metrics::standard(), + notes: Vec::new(), }); let mut tokens = fallback.tokens; for (key, value) in &raw.colours { @@ -452,8 +458,11 @@ impl Theme { if let Some(file) = raw.metrics { file.apply_to(&mut metrics); } - let metrics = metrics.clamped(); - Ok(Theme { name, dark, tokens, metrics }) + let (metrics, held) = metrics.clamped(); + if held > 0 { + notes.push(held_note(&name, held)); + } + Ok(Theme { name, dark, tokens, metrics, notes }) } pub fn to_json(&self) -> Result { @@ -482,10 +491,24 @@ impl Theme { let Some(dir) = dir else { return (themes, errors); }; - let Ok(read) = std::fs::read_dir(dir) else { - return (themes, errors); + let read = match std::fs::read_dir(dir) { + Ok(read) => read, + // A folder that does not exist yet is normal; one that cannot be read is reported. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (themes, errors), + Err(e) => { + errors.push(why(dir, &e.to_string())); + return (themes, errors); + } }; - let mut files: Vec = read.flatten().map(|e| e.path()).filter(|p| is_theme_file(p)).collect(); + let mut files: Vec = Vec::new(); + for entry in read { + match entry { + Ok(e) if is_theme_file(&e.path()) => files.push(e.path()), + Ok(_) => {} + // An entry the folder cannot name is reported, not dropped. + Err(e) => errors.push(why(dir, &e.to_string())), + } + } files.sort(); // A name set by one file cannot be set by another: the second is reported, not silently lost. let mut claimed: BTreeMap = BTreeMap::new(); @@ -549,15 +572,15 @@ impl Theme { for at in 1..=99 { let name = if at == 1 { format!("{stem}.json") } else { format!("{stem}-{at}.json") }; let path = dir.join(name); - match read_text(&path) { - Ok(text) => { - if Theme::parse(&stem, &text).is_ok_and(|found| found.name == self.name) { - return Ok(path); - } - } - // A file of another theme, or one too big to be read, is left alone. - Err(Over::TooBig) => {} - Err(Over::Reason(_)) => return Ok(path), + // A name no file holds is free; one that is there is read, and skipped if it is another theme. + if std::fs::symlink_metadata(&path).is_err() { + return Ok(path); + } + // A file that cannot be read, or is too big, is left alone: the next name is used. + if let Ok(text) = read_text(&path) + && Theme::parse(&stem, &text).is_ok_and(|found| found.name == self.name) + { + return Ok(path); } } Err(why(dir, &i18n::fmt("no free file name for {name}", &[("name", &self.name)]))) @@ -613,6 +636,15 @@ fn slot<'a>(t: &'a mut Tokens, name: &str) -> Option<&'a mut Color32> { }) } +/// The name the interface shows: a built-in theme in the current language, a user name as written. +pub fn label(name: &str) -> String { + match name { + "Light" => tl!("Light").to_string(), + "Dark" => tl!("Dark").to_string(), + _ => name.to_string(), + } +} + pub fn colour(theme: &Theme, name: &str) -> Color32 { let mut tokens = theme.tokens; slot(&mut tokens, name).map_or(Color32::TRANSPARENT, |c| *c) @@ -638,11 +670,57 @@ pub fn contrast(a: Color32, b: Color32) -> f32 { (a.max(b) + 0.05) / (a.min(b) + 0.05) } -/// A name as the menu shows it: one line, no control characters, and at most [`MAX_NAME`] long. -fn clean_name(name: &str) -> String { - let kept: String = name.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(); +/// A name as the menu shows it, with a note for everything it had to drop or cut. +fn clean_name(name: &str, notes: &mut Vec) -> String { + let trimmed = name.trim(); + let printable = trimmed.chars().filter(|c| !c.is_control()).count(); + let controls = trimmed.chars().count() - printable; + let kept: String = trimmed.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(); let kept = kept.trim(); - if kept.is_empty() { "Theme".to_string() } else { kept.to_string() } + if kept.is_empty() { + return "Theme".to_string(); + } + if controls > 0 { + notes.push(if controls == 1 { + i18n::fmt("{name}: 1 control character was dropped from the name", &[("name", kept)]) + } else { + i18n::fmt("{name}: {n} control characters were dropped from the name", &[("name", kept), ("n", &controls.to_string())]) + }); + } + if printable > MAX_NAME { + notes.push(i18n::fmt( + "{name}: the name was longer than {limit} characters, so it was cut", + &[("name", kept), ("limit", &MAX_NAME.to_string())], + )); + } + kept.to_string() +} + +/// How many sizes the window had to hold to fit. +fn held_count(before: Metrics, after: Metrics) -> usize { + let pairs = [ + (before.item_spacing[0], after.item_spacing[0]), + (before.item_spacing[1], after.item_spacing[1]), + (before.button_padding[0], after.button_padding[0]), + (before.button_padding[1], after.button_padding[1]), + (before.row_height, after.row_height), + (before.body, after.body), + (before.button_text, after.button_text), + (before.small, after.small), + (before.heading, after.heading), + (before.mono, after.mono), + ]; + let sizes = pairs.iter().filter(|(a, b)| a != b).count(); + sizes + usize::from(before.corner_radius != after.corner_radius) +} + +/// One line for the sizes the window had to hold, in the singular when there is one. +fn held_note(name: &str, held: usize) -> String { + if held == 1 { + i18n::fmt("{name}: 1 size was held to what the window draws", &[("name", name)]) + } else { + i18n::fmt("{name}: {n} sizes were held to what the window draws", &[("name", name), ("n", &held.to_string())]) + } } /// The file it replaces is kept as `.json.bak`: one backup, replaced on each save. @@ -843,6 +921,17 @@ mod tests { } } + #[test] + fn the_guide_example_is_the_shipped_light_theme() { + let guide = include_str!("../../../docs/themes.md"); + let after = guide.split("The built-in Light is the reference:").nth(1).expect("the guide names its reference"); + let block = after.split("```json").nth(1).expect("a json block follows it"); + let block = block.split("```").next().expect("the block ends"); + let parsed = Theme::parse("Light", block).expect("the guide's example loads"); + let shipped = Theme::builtin().into_iter().find(|t| t.name == "Light").expect("Light ships"); + assert_eq!(parsed, shipped, "the guide's example is the shipped Light theme"); + } + #[test] fn every_built_in_theme_reads_its_text_on_its_surfaces() { for theme in Theme::builtin() { @@ -879,10 +968,10 @@ mod tests { #[test] fn the_folder_signature_follows_a_saved_file() { - let dir = theme_folder("rustgis-theme-signature-test", &[("mine.json", "{}")]); - let before = Theme::folder_signature(Some(&dir)); - std::fs::write(dir.join("mine.json"), "{\"schema\": 1}").expect("the file"); - assert_ne!(Theme::folder_signature(Some(&dir)), before, "a saved file is noticed"); + let dir = theme_folder(&[("mine.json", "{}")]); + let before = Theme::folder_signature(Some(dir.path())); + std::fs::write(dir.path().join("mine.json"), "{\"schema\": 1}").expect("the file"); + assert_ne!(Theme::folder_signature(Some(dir.path())), before, "a saved file is noticed"); assert_eq!(Theme::folder_signature(None), 0, "no folder never changes"); } @@ -973,12 +1062,10 @@ mod tests { } } - fn theme_folder(name: &str, files: &[(&str, &str)]) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(name); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("the folder"); + fn theme_folder(files: &[(&str, &str)]) -> tempfile::TempDir { + let dir = tempfile::tempdir().expect("a temporary folder"); for (file, text) in files { - std::fs::write(dir.join(file), text).expect("the file"); + std::fs::write(dir.path().join(file), text).expect("the file"); } dir } @@ -986,8 +1073,8 @@ mod tests { #[test] fn a_theme_in_the_user_folder_is_offered() { let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); - let dir = theme_folder("rustgis-theme-folder-test", &[("mine.json", &mine)]); - let (found, errors) = Theme::available_in(Some(&dir)); + let dir = theme_folder(&[("mine.json", &mine)]); + let (found, errors) = Theme::available_in(Some(dir.path())); assert!(errors.is_empty(), "{errors:?}"); assert!(found.iter().any(|t| t.name == "Mine"), "the folder theme is offered"); assert!(found.iter().any(|t| t.name == "Light"), "the built-in themes stay"); @@ -996,8 +1083,8 @@ mod tests { #[test] fn a_broken_file_is_reported_and_the_others_load() { let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); - let dir = theme_folder("rustgis-theme-broken-test", &[("mine.json", &mine), ("half.json", "{\"schema\": 1}")]); - let (found, errors) = Theme::available_in(Some(&dir)); + let dir = theme_folder(&[("mine.json", &mine), ("half.json", "{\"schema\": 1}")]); + let (found, errors) = Theme::available_in(Some(dir.path())); assert_eq!(errors.len(), 1, "{errors:?}"); assert!(errors[0].contains("half.json"), "{errors:?}"); assert!(found.iter().any(|t| t.name == "Mine"), "the good file still loads"); @@ -1007,8 +1094,8 @@ mod tests { fn a_user_theme_replaces_the_built_in_of_the_same_name() { let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); json["colours"]["accent"] = "#123456".into(); - let dir = theme_folder("rustgis-theme-replace-test", &[("light.json", &json.to_string())]); - let (found, errors) = Theme::available_in(Some(&dir)); + let dir = theme_folder(&[("light.json", &json.to_string())]); + let (found, errors) = Theme::available_in(Some(dir.path())); assert!(errors.is_empty(), "{errors:?}"); assert_eq!(found.iter().filter(|t| t.name == "Light").count(), 1, "one Light is offered"); let light = found.iter().find(|t| t.name == "Light").expect("Light is offered"); @@ -1055,8 +1142,8 @@ mod tests { #[test] fn a_name_two_files_claim_is_reported_once() { let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); - let dir = theme_folder("rustgis-theme-duplicate-test", &[("a.json", &mine), ("b.json", &mine)]); - let (found, errors) = Theme::available_in(Some(&dir)); + let dir = theme_folder(&[("a.json", &mine), ("b.json", &mine)]); + let (found, errors) = Theme::available_in(Some(dir.path())); assert_eq!(found.iter().filter(|t| t.name == "Mine").count(), 1, "one Mine is offered"); assert_eq!(errors.len(), 1, "{errors:?}"); assert!(errors[0].contains("already set by"), "{errors:?}"); @@ -1069,6 +1156,20 @@ mod tests { assert_eq!(stem_of("Cobalt Blue!"), "cobalt-blue", "letters and digits are kept, the rest as -"); } + #[test] + fn a_file_that_cannot_be_read_keeps_its_name() { + let dir = theme_folder(&[]); + let taken = dir.path().join("mine.json"); + // A UTF-16 file from Notepad: not UTF-8, so the reader refuses it. + std::fs::write(&taken, [0xFF, 0xFE, 0x7B, 0x00]).expect("the file"); + let mut mine = light(); + mine.name = "Mine".to_string(); + let path = mine.save_path(dir.path()).expect("another free name"); + assert_ne!(path, taken, "the unreadable file is not replaced"); + assert_eq!(path.file_name().expect("a name"), "mine-2.json"); + assert_eq!(std::fs::read(&taken).expect("the file"), vec![0xFF, 0xFE, 0x7B, 0x00], "its bytes are untouched"); + } + #[test] fn a_replaced_theme_file_keeps_the_copy_it_replaced() { let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); @@ -1077,36 +1178,36 @@ mod tests { let edited = json.to_string(); json["colours"]["accent"] = "#654321".into(); let picked = json.to_string(); - let dir = theme_folder("rustgis-theme-backup-test", &[("mine.json", &edited)]); - let path = dir.join("mine.json"); + let dir = theme_folder(&[("mine.json", &edited)]); + let path = dir.path().join("mine.json"); backup_before_replace(&path, &picked).expect("the backup"); - assert_eq!(std::fs::read_to_string(dir.join("mine.json.bak")).expect("the backup file"), edited); + assert_eq!(std::fs::read_to_string(dir.path().join("mine.json.bak")).expect("the backup file"), edited); assert_eq!(std::fs::read_to_string(&path).expect("the file"), edited, "the file is not touched yet"); // The folder loads one Mine, and the backup is not a theme. std::fs::write(&path, &picked).expect("the file"); - let (found, errors) = Theme::available_in(Some(&dir)); + let (found, errors) = Theme::available_in(Some(dir.path())); assert!(errors.is_empty(), "{errors:?}"); assert_eq!(found.iter().filter(|t| t.name == "Mine").count(), 1, "one Mine is offered"); assert!(!found.iter().any(|t| t.name.contains("bak")), "the backup is not a theme"); // Writing the same text again leaves the backup alone. backup_before_replace(&path, &picked).expect("no backup needed"); - assert_eq!(std::fs::read_to_string(dir.join("mine.json.bak")).expect("the backup file"), edited); + assert_eq!(std::fs::read_to_string(dir.path().join("mine.json.bak")).expect("the backup file"), edited); } #[test] fn two_names_that_share_a_stem_keep_two_files() { - let dir = theme_folder("rustgis-theme-stem-test", &[]); + let dir = theme_folder(&[]); let mut first = light(); first.name = "Cobalt Blue".to_string(); - let first_at = first.save_path(&dir).expect("a free name"); + let first_at = first.save_path(dir.path()).expect("a free name"); std::fs::write(&first_at, first.to_json().expect("json")).expect("the file"); let mut second = light(); second.name = "Cobalt-Blue".to_string(); - let second_at = second.save_path(&dir).expect("another free name"); + let second_at = second.save_path(dir.path()).expect("another free name"); std::fs::write(&second_at, second.to_json().expect("json")).expect("the file"); assert_ne!(first_at, second_at, "two themes that share a stem keep two files"); - assert_eq!(first.save_path(&dir).expect("its own file"), first_at, "a theme finds the file that holds it"); - let (found, errors) = Theme::available_in(Some(&dir)); + assert_eq!(first.save_path(dir.path()).expect("its own file"), first_at, "a theme finds the file that holds it"); + let (found, errors) = Theme::available_in(Some(dir.path())); assert!(errors.is_empty(), "{errors:?}"); assert_eq!(found.iter().filter(|t| t.name.starts_with("Cobalt")).count(), 2, "both load"); } @@ -1114,16 +1215,16 @@ mod tests { #[test] fn a_theme_file_with_an_upper_case_extension_is_read() { let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); - let dir = theme_folder("rustgis-theme-upper-test", &[("MINE.JSON", &mine)]); - let (found, errors) = Theme::available_in(Some(&dir)); + let dir = theme_folder(&[("MINE.JSON", &mine)]); + let (found, errors) = Theme::available_in(Some(dir.path())); assert!(errors.is_empty(), "{errors:?}"); assert!(found.iter().any(|t| t.name == "Mine"), "the file is read whatever the case of its extension"); } #[test] fn only_a_plain_file_is_opened() { - let dir = theme_folder("rustgis-theme-dir-test", &[]); - match read_text(&dir) { + let dir = theme_folder(&[]); + match read_text(dir.path()) { Err(Over::Reason(why)) => assert!(why.contains("not a file"), "{why}"), other => panic!("{other:?}"), } @@ -1137,8 +1238,8 @@ mod tests { #[test] fn a_file_over_the_limit_reports_the_limit_not_the_encoding() { - let dir = theme_folder("rustgis-theme-multibyte-test", &[]); - let path = dir.join("wide.json"); + let dir = theme_folder(&[]); + let path = dir.path().join("wide.json"); // Two bytes each, so the cut lands inside a character. std::fs::write(&path, "ą".repeat(MAX_THEME_BYTES as usize / 2 + 1)).expect("the file"); assert!(matches!(read_text(&path), Err(Over::TooBig)), "the size is reported, not the encoding"); @@ -1146,8 +1247,8 @@ mod tests { #[test] fn a_theme_file_over_the_limit_is_not_read() { - let dir = theme_folder("rustgis-theme-over-limit", &[]); - let path = dir.join("big.json"); + let dir = theme_folder(&[]); + let path = dir.path().join("big.json"); std::fs::write(&path, "x".repeat(MAX_THEME_BYTES as usize + 1)).expect("the file"); assert!(matches!(read_text(&path), Err(Over::TooBig)), "a file over the limit is refused as it is read"); } @@ -1165,6 +1266,14 @@ mod tests { assert_eq!(theme.metrics.corner_radius, 32); assert_eq!(theme.metrics.item_spacing, [40.0, 0.0]); assert_eq!(theme.metrics.heading, 17.0, "what the file does not set stays standard"); + assert_eq!(theme.notes.len(), 1, "{:?}", theme.notes); + assert!(theme.notes[0].contains("5 sizes"), "every held value is counted: {:?}", theme.notes); + } + + #[test] + fn a_clean_file_says_nothing() { + let clean = Theme::parse("Mine", r#"{"schema": 1, "name": "Mine", "extends": "Light"}"#).expect("it parses"); + assert!(clean.notes.is_empty(), "{:?}", clean.notes); } #[test] @@ -1192,13 +1301,22 @@ mod tests { assert_eq!(theme.name, "file-name", "a nameless file takes its own name"); } + #[test] + fn a_built_in_name_is_shown_in_the_language() { + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("a German catalog")); + assert_eq!(label("Light"), "Hell"); + assert_eq!(label("Dark"), "Dunkel"); + assert_eq!(label("Cobalt"), "Cobalt", "a user name is shown as written"); + crate::i18n::set_current(crate::i18n::Lang::EN); + } + #[test] fn a_file_too_large_to_be_a_theme_is_reported_not_read() { let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); - let dir = theme_folder("rustgis-theme-large-test", &[("mine.json", &mine)]); + let dir = theme_folder(&[("mine.json", &mine)]); let huge = "x".repeat(MAX_THEME_BYTES as usize + 1); - std::fs::write(dir.join("huge.json"), huge).expect("the file"); - let (found, errors) = Theme::available_in(Some(&dir)); + std::fs::write(dir.path().join("huge.json"), huge).expect("the file"); + let (found, errors) = Theme::available_in(Some(dir.path())); assert_eq!(errors.len(), 1, "{errors:?}"); assert!(errors[0].contains("huge.json"), "{errors:?}"); assert!(found.iter().any(|t| t.name == "Mine"), "the good file still loads"); diff --git a/docs/themes.md b/docs/themes.md index 62c7f0c4dd..7938edd478 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -40,7 +40,7 @@ To start from a theme you already have, use **Load a Theme from File…**. The a themes folder; edit that copy and the app follows it. Loading a file whose `name` matches a theme already in the folder replaces that copy, and the version it replaces is kept beside it as `.json.bak`: one backup, replaced on each save. A file that does not load is listed in red at -the bottom of the same menu, with the token at fault. +the bottom of the same menu, with the token at fault, and a notice says when a file was refused. A saved file is picked up within a second, without pressing **Reload Themes**: the app watches the folder while it runs. A theme in use that stops loading leaves the window on the nearest built-in @@ -134,7 +134,8 @@ refused by number. map's light or dark defaults. It is not inferred from the colours. `metrics` are in points: item spacing, button padding, row height, corner radius and text sizes. -Sizes are held to what a window can draw, and a file over 64 KB is not read. +Sizes are held to what a window can draw, and a notice says when a value was held. A file over 64 KB +is not read. ## Tokens From 85c38018cee6a2a230ba4e4041ae091ef0d8c926 Mon Sep 17 00:00:00 2001 From: Wolren Date: Tue, 3 Nov 2026 13:33:09 +0100 Subject: [PATCH 14/28] fix(ui): the review notes, and one notice for a failed action - A scale factor above the f32 range holds at 200%, not at 100%. - The Theme menu marks the drawn theme, so a missing file still marks its fallback. - run_notified leaves the failure to run, which reports it once. - A theme save writes through write_atomic, and the open state takes the corner radius. - The folder signature carries nanoseconds, so a same-size save in one tick is seen. - The showcase applies the interface scale, and a reload reapplies the look. - docs: the browser does not offer Load, and a refused file is listed by its reason. --- crates/ui-egui/examples/ui_shot.rs | 12 +++++++++--- crates/ui-egui/src/lib.rs | 10 +++++++++- crates/ui-egui/src/ribbon.rs | 10 +++++----- crates/ui-egui/src/theme.rs | 12 ++++++++++-- docs/themes.md | 15 ++++++++------- 5 files changed, 41 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/examples/ui_shot.rs b/crates/ui-egui/examples/ui_shot.rs index aa47f0e196..9f0d35d25a 100644 --- a/crates/ui-egui/examples/ui_shot.rs +++ b/crates/ui-egui/examples/ui_shot.rs @@ -46,7 +46,7 @@ struct RibbonSplitShowcase { disable_enclosing_ui: bool, long_labels: bool, fonts_installed: bool, - applied_look: Option<(String, bool)>, + applied_look: Option<(String, bool, u64)>, } fn split_tool_menu(ui: &mut egui::Ui, app: &mut RustGisApp) { @@ -66,10 +66,12 @@ impl RibbonSplitShowcase { theme::install_fonts(ui.ctx(), &[], None); self.fonts_installed = true; } - if self.applied_look.as_ref() != Some(&(app.ui.theme_name.clone(), app.ui.dark)) { + // The revision is part of the key: a reload with the same name still reapplies the look. + let look = (app.ui.theme_name.clone(), app.ui.dark, app.theme_revision()); + if self.applied_look.as_ref() != Some(&look) { let chosen = app.current_theme(); theme::apply(ui.ctx(), &chosen.tokens, &chosen.metrics); - self.applied_look = Some((app.ui.theme_name.clone(), app.ui.dark)); + self.applied_look = Some(look); } i18n::set_current(app.chosen_lang()); ui.heading("Ribbon split buttons"); @@ -182,6 +184,10 @@ fn main() { .build_ui_state( move |ui, app: &mut RustGisApp| { if ribbon_split { + // The split showcase skips `logic`, the only place the scale reaches egui. + if (ui.ctx().zoom_factor() - app.ui.interface_scale).abs() > 0.001 { + ui.ctx().set_zoom_factor(app.ui.interface_scale); + } split_showcase.show(ui, app); } else { let ctx = ui.ctx().clone(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 30341068d2..7acb516bd6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2467,7 +2467,10 @@ impl RustGisApp { } "ui.scale" => { let factor = match p.get("factor") { - Some(given) => given.as_f64().ok_or_else(|| i18n::fmt("ui.scale needs a number at factor", &[]))? as f32, + Some(given) => given + .as_f64() + .ok_or_else(|| i18n::fmt("ui.scale needs a number at factor", &[]))? + .clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32, None => 1.0, }; self.ui.interface_scale = theme::clamp_scale(factor); @@ -4264,6 +4267,11 @@ impl RustGisApp { (follows, name) } + /// A number that changes when the theme files are read again, for a caller that caches a look. + pub fn theme_revision(&self) -> u64 { + self.themes_stamp + } + pub fn ui(&mut self, ui: &mut egui::Ui) { let _diagnostics = self.session.diagnostics.enter(); let ctx = ui.ctx().clone(); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index a436f67380..0882d34593 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3506,6 +3506,8 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { let (follows, current) = app.theme_shown(system); let label = format!("{}\n{current}", tl!("Theme")); let themes: Vec = app.themes.iter().map(|t| t.name.clone()).collect(); + // The drawn theme is marked: a saved name whose file stopped loading is not drawn. + let drawn = app.drawn().map(|t| t.name.clone()); let errors = app.theme_errors.clone(); let notes = app.theme_notes.clone(); // The browser has no settings folder to read theme files from or write one to. @@ -3526,7 +3528,7 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { ui.close(); } for name in &themes { - let picked = app.ui.theme_name == *name; + let picked = !follows && drawn.as_deref() == Some(name.as_str()); if ui.add(egui::Button::selectable(picked, crate::theme::label(name))).clicked() { run_notified(app, "ui.themeFile", json!({ "name": name })); ui.close(); @@ -3557,11 +3559,9 @@ fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { ); } -/// Runs a UI command and shows the reason when it fails. +/// Runs a UI command; `run` reports a failure itself. fn run_notified(app: &mut RustGisApp, id: &str, params: Value) { - if let Err(e) = app.run(id, params) { - app.session.notify(e, true); - } + let _ = app.run(id, params); } /// Interface scale, as egui's zoom factor. diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index f29b175061..f40fc036a4 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -551,7 +551,7 @@ impl Theme { let path = e.path(); let meta = e.metadata().ok()?; // Metadata carries a std clock; this runs only where a themes folder exists. - let saved = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis(); + let saved = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos(); Some((path.file_name()?.to_string_lossy().into_owned(), meta.len(), saved)) }) .collect(); @@ -593,7 +593,7 @@ impl Theme { let path = self.save_path(&dir)?; let text = self.to_json()?; backup_before_replace(&path, &text)?; - std::fs::write(&path, text).map_err(|e| why(&path, &e.to_string()))?; + rustgis_engine::data::io::write_atomic(&path, text.as_bytes()).map_err(|e| why(&path, &e.to_string()))?; Ok(path) } } @@ -861,6 +861,7 @@ pub fn apply(ctx: &egui::Context, t: &Tokens, m: &Metrics) { v.widgets.active.corner_radius = corner; v.widgets.open.bg_fill = t.pressed; v.widgets.open.weak_bg_fill = t.pressed; + v.widgets.open.corner_radius = corner; v.popup_shadow = egui::Shadow { offset: [0, 6], blur: 18, spread: 0, color: t.shadow }; v.window_shadow = egui::Shadow { offset: [0, 10], blur: 28, spread: 0, color: t.shadow }; ctx.data_mut(|d| d.insert_temp(tokens_id(), *t)); @@ -911,6 +912,13 @@ mod tests { } } + #[test] + fn the_shipped_files_parse_without_the_fallback() { + for (name, text) in [("Light", include_str!("../themes/light.json")), ("Dark", include_str!("../themes/dark.json"))] { + Theme::parse(name, text).expect("the shipped file parses"); + } + } + #[test] fn every_built_in_theme_round_trips_and_sets_every_token() { for theme in Theme::builtin() { diff --git a/docs/themes.md b/docs/themes.md index 7938edd478..9ad4639f95 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -32,15 +32,16 @@ there and the button names the brightness in force instead. ## What the browser build does The browser has no config folder, so there is no themes folder there and **Load a Theme from File…** -does nothing. The browser offers Follow the System, Light, Dark and the interface scale: a theme in a -file is a desktop route. The two built-in themes are the same files, compiled in, so nothing else +is not offered. The browser offers Follow the System, Light, Dark and the interface scale: a theme in +a file is a desktop route. The two built-in themes are the same files, compiled in, so nothing else differs. -To start from a theme you already have, use **Load a Theme from File…**. The app keeps a copy in the -themes folder; edit that copy and the app follows it. Loading a file whose `name` matches a theme -already in the folder replaces that copy, and the version it replaces is kept beside it as -`.json.bak`: one backup, replaced on each save. A file that does not load is listed in red at -the bottom of the same menu, with the token at fault, and a notice says when a file was refused. +On the desktop, to start from a theme you already have, use **Load a Theme from File…**. The app +keeps a copy in the themes folder; edit that copy and the app follows it. Loading a file whose `name` +matches a theme already in the folder replaces that copy, and the version it replaces is kept beside +it as `.json.bak`: one backup, replaced on each save. A file that does not load is listed in +red at the bottom of the same menu with its reason. A bad colour, size or name is named by its +token, and a notice says when a file was refused. A saved file is picked up within a second, without pressing **Reload Themes**: the app watches the folder while it runs. A theme in use that stops loading leaves the window on the nearest built-in From d09a55cda9d2b83c08a0e4bd7d441d25814fc093 Mon Sep 17 00:00:00 2001 From: Wolren Date: Tue, 3 Nov 2026 13:53:58 +0100 Subject: [PATCH 15/28] fix(ui): a symlinked theme file reloads when its target changes DirEntry::metadata does not follow a link while read_text does, so the watch signature missed edits to the target. The signature now stats the path itself. --- crates/ui-egui/src/theme.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index f40fc036a4..3121a25d7b 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -549,7 +549,8 @@ impl Theme { .filter(|e| is_theme_file(&e.path())) .filter_map(|e| { let path = e.path(); - let meta = e.metadata().ok()?; + // std::fs::metadata follows a symlink, as read_text does; DirEntry::metadata does not. + let meta = std::fs::metadata(&path).ok()?; // Metadata carries a std clock; this runs only where a themes folder exists. let saved = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos(); Some((path.file_name()?.to_string_lossy().into_owned(), meta.len(), saved)) @@ -983,6 +984,19 @@ mod tests { assert_eq!(Theme::folder_signature(None), 0, "no folder never changes"); } + #[cfg(unix)] + #[test] + fn the_folder_signature_follows_a_symlinked_theme() { + let dir = theme_folder(&[]); + let target = dir.path().join("real.json"); + std::fs::write(&target, "{}").expect("the file"); + std::os::unix::fs::symlink(&target, dir.path().join("link.json")).expect("the link"); + let before = Theme::folder_signature(Some(dir.path())); + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(5); + std::fs::File::options().write(true).open(&target).expect("the target").set_modified(later).expect("touch"); + assert_ne!(Theme::folder_signature(Some(dir.path())), before, "the target is what read_text reads"); + } + #[test] fn a_file_sets_the_sizes_it_names_and_keeps_the_rest() { let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); From 6fd28e0f77488be848cc4b55de92073f71e11eda Mon Sep 17 00:00:00 2001 From: Wolren Date: Tue, 3 Nov 2026 14:07:24 +0100 Subject: [PATCH 16/28] fix(ui): one file per theme name, and the picker says what it changed A save now replaces the file that already holds the name, even when that file has another stem, so one name keeps one file and the copy just saved is drawn. The file picker announces the reader's notes; the clamped copy it keeps would hide them on the folder re-read. --- crates/ui-egui/src/lib.rs | 4 ++++ crates/ui-egui/src/theme.rs | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7acb516bd6..1e10da20c7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1771,6 +1771,10 @@ impl RustGisApp { }; let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); let theme = theme::Theme::parse(&stem, &text).map_err(|e| said(&e))?; + // The picker says what the reader changed; the saved copy is clamped, so the folder is silent. + for note in &theme.notes { + self.session.notify(note.clone(), false); + } let kept = theme.save_user()?; self.load_themes(); self.use_theme(&theme.name)?; diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 3121a25d7b..aae057e262 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -570,6 +570,17 @@ impl Theme { /// The file that holds this theme: its own name, or the next free one when another theme took it. fn save_path(&self, dir: &std::path::Path) -> Result { let stem = stem_of(&self.name); + // A file that already holds this name is replaced, even under another stem: one name, one file. + if let Ok(read) = std::fs::read_dir(dir) { + let mut held: Vec = read.flatten().map(|e| e.path()).filter(|p| is_theme_file(p)).collect(); + held.sort(); + for path in held { + let Ok(text) = read_text(&path) else { continue }; + if Theme::parse(&stem, &text).is_ok_and(|found| found.name == self.name) { + return Ok(path); + } + } + } for at in 1..=99 { let name = if at == 1 { format!("{stem}.json") } else { format!("{stem}-{at}.json") }; let path = dir.join(name); @@ -1092,6 +1103,19 @@ mod tests { dir } + #[test] + fn a_save_replaces_the_file_that_holds_the_name() { + let held = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); + let dir = theme_folder(&[("ocean.json", held.as_str())]); + let mut mine = light(); + mine.name = "Mine".to_string(); + let path = mine.save_path(dir.path()).expect("a file for the name"); + assert_eq!(path.file_name().and_then(|n| n.to_str()), Some("ocean.json"), "the name owns the file it was found in"); + let other = theme_folder(&[("ocean.json", light().to_json().expect("json").as_str())]); + let path = mine.save_path(other.path()).expect("a free file"); + assert_eq!(path.file_name().and_then(|n| n.to_str()), Some("mine.json"), "another name keeps its own file"); + } + #[test] fn a_theme_in_the_user_folder_is_offered() { let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); From 9dd2f642163655581511550122a9c061a4638a1a Mon Sep 17 00:00:00 2001 From: Wolren Date: Tue, 3 Nov 2026 13:22:36 +0000 Subject: [PATCH 17/28] Update crates/ui-egui/src/theme.rs Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- crates/ui-egui/src/theme.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index aae057e262..828f9ed671 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -576,7 +576,8 @@ impl Theme { held.sort(); for path in held { let Ok(text) = read_text(&path) else { continue }; - if Theme::parse(&stem, &text).is_ok_and(|found| found.name == self.name) { + let own = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); + if Theme::parse(&own, &text).is_ok_and(|found| found.name == self.name) { return Ok(path); } } From 8c97e7c07f0a9bb11820373aa39c3ed019604747 Mon Sep 17 00:00:00 2001 From: Wolren Date: Tue, 3 Nov 2026 15:04:37 +0100 Subject: [PATCH 18/28] fix(ui): a theme file with no name takes its file name The `name` key is now optional, as the docs already said: a file without one loads under its stem. docs/themes.md also names the Linux default folder. --- crates/ui-egui/src/theme.rs | 10 ++++++++++ docs/themes.md | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 828f9ed671..9df53ba6e1 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -368,6 +368,8 @@ pub struct Theme { #[serde(deny_unknown_fields)] struct Raw { schema: u32, + /// A file with no name takes the name of its file, as one with an empty name does. + #[serde(default)] name: String, /// A theme that ships, whose colours and sizes this file starts from. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -987,6 +989,14 @@ mod tests { assert!(err.contains("extends Gone"), "{err}"); } + #[test] + fn a_file_without_a_name_takes_its_file_name() { + let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); + json.as_object_mut().expect("an object").remove("name"); + let theme = Theme::parse("ocean", &json.to_string()).expect("a file with no name loads"); + assert_eq!(theme.name, "ocean", "the file name stands in"); + } + #[test] fn the_folder_signature_follows_a_saved_file() { let dir = theme_folder(&[("mine.json", "{}")]); diff --git a/docs/themes.md b/docs/themes.md index 9ad4639f95..26092011f4 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -12,7 +12,8 @@ drawn by the renderer, which takes its light or dark defaults from the theme's ` | User | `/themes/*.json`, read at startup, when a file changes, and by Reload Themes | The config folder is `%APPDATA%\RustGIS` on Windows, `~/Library/Application Support/RustGIS` on -macOS and `$XDG_CONFIG_HOME/rustgis` elsewhere. `RUSTGIS_CONFIG_DIR` overrides it. +macOS and `$XDG_CONFIG_HOME/rustgis`, which is `~/.config/rustgis` when the variable is unset, +elsewhere. `RUSTGIS_CONFIG_DIR` overrides it. A user file whose `name` matches a built-in replaces it. A reworked Light sits in the folder as `light.json`, and the menu lists one Light. Two files that claim the same name: the first in name From 78e7f9f0dfb34c69dc9b05fc91c5735081dfdc1e Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 3 Nov 2026 22:22:05 -0600 Subject: [PATCH 19/28] fix(themes): preserve saved appearance and roll back failed imports --- crates/ui-egui/src/chrome.rs | 4 ++-- crates/ui-egui/src/i18n/tests.rs | 10 --------- crates/ui-egui/src/lib.rs | 22 ++++++++++++++++---- crates/ui-egui/src/theme.rs | 35 +++++++++++++++++++++++++++++--- docs/themes.md | 5 +++-- 5 files changed, 55 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index e3df58aec5..aafcab899b 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -692,10 +692,10 @@ pub(crate) const UI_COMMANDS: &[(&str, &str, &str)] = &[ ("ui.pane.directions", "Directions", "Home › Navigate"), ("ui.pane.bookmarks", "Bookmarks Pane", "Home › Navigate › Bookmarks"), ("ui.theme", "Toggle Dark Mode", "Settings › Theme"), - ("ui.themeFile", "Choose Theme", "Settings › Theme"), + ("ui.themeFile", "Follow the System", "Settings › Theme"), ("ui.themeLoad", "Load a Theme from File…", "Settings › Theme"), ("ui.themeReload", "Reload Themes", "Settings › Theme"), - ("ui.scale", "Interface Scale", "Settings › Theme"), + ("ui.scale", "Reset Interface Scale", "Settings › Theme"), ("ui.map.gpu", "Toggle GPU Rendering", "View"), ("ui.importShapefile", "Import Shapefile with Projection…", "Home › Add"), ("ui.measurementUnits", "Toggle Imperial Measurements", "Home › Inspect › Measure"), diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index f73fd701ff..a7458a6068 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -24,16 +24,6 @@ fn every_catalog_parses_cleanly_and_keeps_placeholders() { } } -#[test] -fn every_catalog_names_the_built_in_themes() { - for l in &LANGUAGES[1..] { - let (m, _) = parse(l.source); - for key in ["Light", "Dark"] { - assert!(m.contains_key(key), "{}: no {key} label", l.code); - } - } -} - #[test] fn lookup_fallback_and_tags() { assert_eq!(tr(Lang::EN, "Explore"), "Explore"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 26885fcc29..72594aa132 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1696,13 +1696,19 @@ impl RustGisApp { return; } if let Some(dark) = self.themes.iter().find(|t| t.name == self.ui.theme_name).map(|t| t.dark) { - self.ui.dark = dark; + if self.ui.dark != dark { + self.ui.dark = dark; + if let Some(save) = &self.services.save_pref { + save("dark", if dark { "true" } else { "false" }); + } + } // The loaded theme owns its brightness; following the platform would overwrite it. self.ui.dark_follows_system = false; } } - /// Reads the folder again when a file in it was added, removed or saved, at most once a second. + /// Reloads when file names, sizes or modification times change, at most once a second. + /// A save preserving size and timestamp needs Reload Themes. fn refresh_themes(&mut self, ctx: &egui::Context) { let Some(dir) = theme::Theme::user_dir() else { return }; ctx.request_repaint_after(web_time::Duration::from_secs(1)); @@ -1786,13 +1792,13 @@ impl RustGisApp { let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); let theme = theme::Theme::parse(&stem, &text).map_err(|e| said(&e))?; // Keep the original file text. Remember its notes before reloading so they are announced once. + let kept = theme.save_user(&text)?; self.announce_theme_notes(&theme.notes); for note in &theme.notes { if !self.theme_notes.contains(note) { self.theme_notes.push(note.clone()); } } - let kept = theme.save_user(&text)?; self.load_themes(); self.use_theme(&theme.name)?; let kept = kept.display().to_string(); @@ -2502,7 +2508,7 @@ impl RustGisApp { ); } if let Some(save) = &self.services.save_pref { - save("ui_scale", &format!("{:.2}", self.ui.interface_scale)); + save("ui_scale", &self.ui.interface_scale.to_string()); } } "ui.themeReload" => self.load_themes(), @@ -4916,6 +4922,9 @@ mod look_tests { assert_eq!(app.ui.interface_scale, 1.25, "the menu scale is kept, not read back as the old zoom"); assert!((ctx.zoom_factor() - 1.25).abs() < 0.001, "and the interface is drawn at it"); assert!(log.lock().expect("the log").iter().any(|(k, v)| k == "ui_scale" && v == "1.25")); + app.run("ui.scale", serde_json::json!({ "factor": 1.234 })).expect("a fractional scale"); + let kept = log.lock().expect("the log").iter().rev().find(|(k, _)| k == "ui_scale").unwrap().1.clone(); + assert_eq!(kept.parse::().expect("saved scale"), app.ui.interface_scale, "restart retains full precision"); // Past the limit the command holds the scale. app.run("ui.scale", serde_json::json!({ "factor": 3.0 })).expect("the command"); app.logic(&ctx); @@ -4966,6 +4975,7 @@ mod look_tests { cobalt.name = "Cobalt".to_string(); std::fs::write(&path, cobalt.to_json().expect("json")).expect("the file"); let mut app = app_with(&[]); + let log = saved_by(&mut app); app.load_themes_from(Some(dir.path())); app.use_theme("Cobalt").expect("the file loads"); // The same file saved as a light theme: the interface takes its brightness with it. @@ -4974,6 +4984,10 @@ mod look_tests { std::fs::write(&path, cobalt.to_json().expect("json")).expect("the file"); app.load_themes_from(Some(dir.path())); assert!(!app.ui.dark, "the interface takes the brightness of the theme it names"); + assert!( + log.lock().expect("the log").iter().any(|(key, value)| key == "dark" && value == "false"), + "restart retains the adopted brightness" + ); assert_eq!(app.current_theme().name, "Cobalt", "the named theme is drawn"); assert_eq!(app.theme_shown(true).1, "Cobalt"); } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 166fe5540f..cdd5fb2224 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -558,7 +558,14 @@ impl Theme { (themes, errors) } + /// The browser has no user theme folder or filesystem watcher. + #[cfg(target_arch = "wasm32")] + pub fn folder_signature(_dir: Option<&std::path::Path>) -> u64 { + 0 + } + /// Hash of each file's name, size and mtime, from metadata alone: no file is read. + #[cfg(not(target_arch = "wasm32"))] pub fn folder_signature(dir: Option<&std::path::Path>) -> u64 { use std::hash::{Hash, Hasher}; let Some(dir) = dir else { return 0 }; @@ -571,7 +578,7 @@ impl Theme { // std::fs::metadata follows a symlink, as read_text does; DirEntry::metadata does not. let meta = std::fs::metadata(&path).ok()?; // Metadata carries a std clock; this runs only where a themes folder exists. - let saved = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos(); + let saved = meta.modified().ok()?.duration_since(web_time::UNIX_EPOCH).ok()?.as_nanos(); Some((path.file_name()?.to_string_lossy().into_owned(), meta.len(), saved)) }) .collect(); @@ -790,7 +797,16 @@ fn save_theme_text(path: &std::path::Path, text: &str) -> Result<(), String> { // The old backup is changed only after the new theme was saved successfully. if let Some(old) = old { let kept = target.with_extension("json.bak"); - write_theme_text(&kept, &old, permissions).map_err(|e| why(&kept, &e.to_string()))?; + if let Err(error) = write_theme_text(&kept, &old, permissions.clone()) { + let reason = why(&kept, &error.to_string()); + if let Err(restore) = write_theme_text(&target, &old, permissions) { + return Err(i18n::fmt( + "{reason}; the previous theme could not be restored: {restore}", + &[("reason", &reason), ("restore", &restore.to_string())], + )); + } + return Err(reason); + } } Ok(()) } @@ -1387,6 +1403,18 @@ mod tests { assert_eq!(std::fs::read_to_string(dir.path().join("mine.json.bak")).expect("backup"), "older"); } + /// A refused backup must not leave a new theme behind after reporting a failed import. + #[test] + fn a_failed_backup_restores_the_theme() { + let dir = theme_folder(&[("mine.json", "old")]); + let path = dir.path().join("mine.json"); + let backup = dir.path().join("mine.json.bak"); + std::fs::create_dir(&backup).expect("a blocked backup destination"); + assert!(save_theme_text(&path, "new").is_err()); + assert_eq!(std::fs::read_to_string(&path).expect("theme"), "old"); + assert!(backup.is_dir(), "the blocked destination is preserved"); + } + #[test] fn two_names_that_share_a_stem_keep_two_files() { let dir = theme_folder(&[]); @@ -1418,7 +1446,8 @@ mod tests { fn only_a_plain_file_is_opened() { let dir = theme_folder(&[]); match read_text(dir.path()) { - Err(Over::Reason(why)) => assert!(why.contains("not a file"), "{why}"), + // Windows refuses the directory at open; Unix rejects its opened handle's type. + Err(Over::Reason(why)) => assert!(!why.is_empty(), "a rejected directory has a reason"), other => panic!("{other:?}"), } } diff --git a/docs/themes.md b/docs/themes.md index 1c77e68576..321315fac7 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -46,8 +46,9 @@ it as `.json.bak`: one backup, replaced on each save. A file that does not red at the bottom of the same menu with its reason. Unknown tokens and bad colour strings name the token; values of the wrong JSON type give a line and column. A notice says when a file was refused. -A saved file is picked up within a second, without pressing **Reload Themes**: the app watches the -folder while it runs. A theme in use that stops loading leaves the window on the nearest built-in +The app checks file names, sizes and modification times once a second while it runs. A save +that changes that metadata is picked up automatically. If a save preserves both size and +modification time, use **Reload Themes** to reread it. A theme in use that stops loading leaves the window on the nearest built-in until it loads again: the button names the theme drawn, the menu gives the reason, and the choice returns with the file. From e06e7f0dbfd36b3855c7f21b838d8005c4ed3de6 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 01:39:22 -0600 Subject: [PATCH 20/28] fix(themes): hide desktop commands on web and invalidate reloaded looks --- crates/ui-egui/src/chrome.rs | 6 +++--- crates/ui-egui/src/lib.rs | 11 ++++++++++- crates/ui-egui/src/shortcutui.rs | 2 +- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index aafcab899b..625b798070 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -661,7 +661,7 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { /// Whether a UI command is available on the current platform. pub(crate) fn command_available(id: &str, web: bool) -> bool { - !web || !matches!(id, "ui.checkUpdate" | "ui.mcpRelay") + !web || !matches!(id, "ui.checkUpdate" | "ui.mcpRelay" | "ui.themeLoad" | "ui.themeReload") } /// The `ui.*` commands Command Search lists: (id, label, ribbon location). @@ -991,8 +991,8 @@ pub fn command_search(app: &mut RustGisApp, ctx: &egui::Context) { } } for &(id, label, loc) in UI_COMMANDS { - // The web app always serves the latest release (no Check for Updates button) and is - // one process a loopback relay could not reach (`ui.mcpRelay` is desktop only). + // Match the platform availability used by the shortcut editor, including desktop + // theme files and the loopback relay. if !command_available(id, cfg!(target_arch = "wasm32")) { continue; } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 72594aa132..cc4c9558a4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -925,6 +925,8 @@ pub struct RustGisApp { /// What the reader changed in the loaded theme files, as the menu lists it. pub theme_notes: Vec, themes_stamp: u64, + /// Changes on every folder read, including explicit reloads with unchanged metadata. + themes_revision: u64, themes_checked: f64, sent_title: String, pub quit_requested: bool, @@ -1102,6 +1104,7 @@ impl RustGisApp { theme_errors: Vec::new(), theme_notes: Vec::new(), themes_stamp: 0, + themes_revision: 0, themes_checked: 0.0, sent_title: String::new(), quit_requested: false, @@ -1647,6 +1650,7 @@ impl RustGisApp { /// Reads the folder; the stamp is taken first, so a save during the read is picked up next time. fn load_themes_from(&mut self, dir: Option<&std::path::Path>) { self.themes_stamp = theme::Theme::folder_signature(dir); + self.themes_revision = self.themes_revision.wrapping_add(1); let (themes, errors) = theme::Theme::available_in(dir); let notes: Vec = themes.iter().flat_map(|t| t.notes.iter().cloned()).collect(); // Said before the new lists are kept, so only what the last read did not report is said. @@ -4302,7 +4306,7 @@ impl RustGisApp { /// A number that changes when the theme files are read again, for a caller that caches a look. pub fn theme_revision(&self) -> u64 { - self.themes_stamp + self.themes_revision } pub fn ui(&mut self, ui: &mut egui::Ui) { @@ -4978,6 +4982,11 @@ mod look_tests { let log = saved_by(&mut app); app.load_themes_from(Some(dir.path())); app.use_theme("Cobalt").expect("the file loads"); + let stamp = app.themes_stamp; + let revision = app.theme_revision(); + app.load_themes_from(Some(dir.path())); + assert_eq!(app.themes_stamp, stamp, "metadata remains unchanged"); + assert_ne!(app.theme_revision(), revision, "an explicit reload invalidates a caller's cached appearance"); // The same file saved as a light theme: the interface takes its brightness with it. cobalt.dark = false; cobalt.tokens = theme::Tokens::light(); diff --git a/crates/ui-egui/src/shortcutui.rs b/crates/ui-egui/src/shortcutui.rs index 4abb18a687..a8636f9811 100644 --- a/crates/ui-egui/src/shortcutui.rs +++ b/crates/ui-egui/src/shortcutui.rs @@ -346,7 +346,7 @@ mod tests { #[test] fn web_rows_exclude_desktop_commands_even_with_existing_bindings() { let mut app = RustGisApp::new(Session::new(Project::default())); - for id in ["ui.checkUpdate", "ui.mcpRelay"] { + for id in ["ui.checkUpdate", "ui.mcpRelay", "ui.themeLoad", "ui.themeReload"] { app.ui.keymap.assign(Chord::parse("F8").unwrap(), id, Value::Null); assert!(!crate::chrome::command_available(id, true)); assert!(!rows(&app, true).iter().any(|(command, _, _)| command == id)); From 53806ec446518072d4574c3493e4710699475531 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 08:16:32 -0600 Subject: [PATCH 21/28] fix(themes): preserve interrupted saves and reject malformed brightness --- crates/ui-egui/src/lib.rs | 20 ++++++++- crates/ui-egui/src/theme.rs | 86 +++++++++++++++++++++++++++++------- docs/index.md | 6 +-- docs/themes.md | 4 +- docs/user-guide/workspace.md | 2 +- 5 files changed, 96 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 38ea5ac643..5f759f7b8d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2535,7 +2535,11 @@ impl RustGisApp { } // The theme list in Settings is the one control for brightness; this picks its entry. "ui.theme" => { - let dark = p.get("dark").and_then(Value::as_bool).unwrap_or(!self.ui.dark); + let dark = match p.get("dark") { + None => !self.ui.dark, + Some(Value::Bool(dark)) => *dark, + Some(_) => return Err(i18n::fmt("ui.theme needs true or false at dark", &[])), + }; // The brightness asked for wins: a user file may rework Light or Dark. self.ui.dark = dark; let wanted = if dark { "Dark" } else { "Light" }; @@ -5152,6 +5156,20 @@ mod look_tests { #[test] fn a_parameter_of_the_wrong_type_is_refused() { let mut app = app_with(&[]); + let log = saved_by(&mut app); + app.ui.dark = false; + app.ui.theme_name = "Custom".to_string(); + app.ui.dark_follows_system = true; + for dark in [serde_json::json!("false"), serde_json::json!(0), serde_json::Value::Null] { + let why = app.run("ui.theme", serde_json::json!({ "dark": dark })).expect_err("dark must be a boolean"); + assert!(why.contains("ui.theme"), "{why}"); + assert!(!app.ui.dark); + assert_eq!(app.ui.theme_name, "Custom"); + assert!(app.ui.dark_follows_system); + assert!(log.lock().expect("the log").is_empty(), "rejection saves no preferences"); + } + app.run("ui.theme", serde_json::json!({})).expect("omitting dark still toggles"); + assert!(app.ui.dark); let why = app.run("ui.themeFile", serde_json::json!({ "name": 5 })).expect_err("a name must be a string"); assert!(why.contains("ui.themeFile"), "{why}"); let why = app.run("ui.scale", serde_json::json!({ "factor": "big" })).expect_err("a factor must be a number"); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 5f265d4c69..b3e3a74185 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -245,7 +245,7 @@ struct MetricsFile { #[serde(default, skip_serializing_if = "Option::is_none")] row_height: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - corner_radius: Option, + corner_radius: Option, #[serde(default, skip_serializing_if = "Option::is_none")] body: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -264,7 +264,7 @@ impl MetricsFile { item_spacing: Some(metrics.item_spacing), button_padding: Some(metrics.button_padding), row_height: Some(metrics.row_height), - corner_radius: Some(metrics.corner_radius), + corner_radius: Some(u64::from(metrics.corner_radius)), body: Some(metrics.body), button_text: Some(metrics.button_text), small: Some(metrics.small), @@ -285,7 +285,7 @@ impl MetricsFile { metrics.row_height = v; } if let Some(v) = self.corner_radius { - metrics.corner_radius = v; + metrics.corner_radius = u8::try_from(v).unwrap_or(u8::MAX); } if let Some(v) = self.body { metrics.body = v; @@ -794,21 +794,63 @@ fn save_theme_text(path: &std::path::Path, text: &str) -> Result<(), String> { return Ok(()); } let permissions = std::fs::metadata(&target).ok().map(|m| m.permissions()); - write_theme_text(&target, text, permissions.clone()).map_err(|e| why(&target, &e.to_string()))?; - // The old backup is changed only after the new theme was saved successfully. - if let Some(old) = old { - let kept = target.with_extension("json.bak"); - if let Err(error) = write_theme_text(&kept, &old, permissions.clone()) { - let reason = why(&kept, &error.to_string()); - if let Err(restore) = write_theme_text(&target, &old, permissions) { - return Err(i18n::fmt( - "{reason}; the previous theme could not be restored: {restore}", - &[("reason", &reason), ("restore", &restore.to_string())], - )); + // Keep a separate recovery copy before replacing either user-visible file. It survives + // interruption; a subsequent save refuses to overwrite it until the user recovers it. + let recovery = target.with_extension("json.recover"); + if let Some(old) = &old { + use std::io::Write; + let mut out = + std::fs::OpenOptions::new().write(true).create_new(true).open(&recovery).map_err(|e| why(&recovery, &e.to_string()))?; + let staged = (|| -> std::io::Result<()> { + if let Some(permissions) = permissions.clone() { + out.set_permissions(permissions)?; } - return Err(reason); + out.write_all(old.as_bytes())?; + out.sync_all()?; + sync_theme_folder(&target) + })(); + drop(out); + if let Err(error) = staged { + let _ = std::fs::remove_file(&recovery); + return Err(why(&recovery, &error.to_string())); } } + let saved = (|| -> Result<(), String> { + write_theme_text(&target, text, permissions.clone()).map_err(|e| why(&target, &e.to_string()))?; + // The old backup is changed only after the new theme was saved successfully. + if let Some(old) = &old { + let kept = target.with_extension("json.bak"); + if let Err(error) = write_theme_text(&kept, old, permissions.clone()) { + let reason = why(&kept, &error.to_string()); + if let Err(restore) = write_theme_text(&target, old, permissions.clone()) { + return Err(i18n::fmt( + "{reason}; the previous theme is kept at {recovery}; restoration failed: {restore}", + &[("reason", &reason), ("recovery", &recovery.display().to_string()), ("restore", &restore.to_string())], + )); + } + sync_theme_folder(&target).map_err(|e| why(&recovery, &e.to_string()))?; + std::fs::remove_file(&recovery).map_err(|e| why(&recovery, &e.to_string()))?; + return Err(reason); + } + sync_theme_folder(&target).map_err(|e| why(&recovery, &e.to_string()))?; + } + Ok(()) + })(); + saved?; + if old.is_some() { + std::fs::remove_file(&recovery).map_err(|e| why(&recovery, &e.to_string()))?; + } + Ok(()) +} + +/// Persists the recovery entry and completed renames on systems that support directory syncing. +fn sync_theme_folder(path: &std::path::Path) -> std::io::Result<()> { + #[cfg(unix)] + if let Some(parent) = path.parent() { + std::fs::File::open(parent)?.sync_all()?; + } + #[cfg(not(unix))] + let _ = path; Ok(()) } @@ -1423,6 +1465,18 @@ mod tests { assert!(backup.is_dir(), "the blocked destination is preserved"); } + /// A recovery copy left by an interrupted save is never overwritten by the next save. + #[test] + fn an_interrupted_save_keeps_its_recovery_copy() { + let dir = theme_folder(&[("mine.json", "new"), ("mine.json.bak", "older"), ("mine.json.recover", "old")]); + let path = dir.path().join("mine.json"); + let why = save_theme_text(&path, "next").expect_err("recover the interrupted save first"); + assert!(why.contains("mine.json.recover"), "{why}"); + for (file, text) in [("mine.json", "new"), ("mine.json.bak", "older"), ("mine.json.recover", "old")] { + assert_eq!(std::fs::read_to_string(dir.path().join(file)).expect("preserved file"), text); + } + } + #[test] fn two_names_that_share_a_stem_keep_two_files() { let dir = theme_folder(&[]); @@ -1488,7 +1542,7 @@ mod tests { let mut json: serde_json::Value = serde_json::from_str(&light().to_json().expect("json")).expect("json"); json["metrics"]["body"] = serde_json::json!(1e9); json["metrics"]["small"] = serde_json::json!(-5.0); - json["metrics"]["corner_radius"] = serde_json::json!(250); + json["metrics"]["corner_radius"] = serde_json::json!(4096); json["metrics"]["item_spacing"] = serde_json::json!([1e9, -1e9]); let theme = Theme::parse("Mine", &json.to_string()).expect("it parses"); assert_eq!(theme.metrics.body, 40.0, "a huge size is held to the largest drawn"); diff --git a/docs/index.md b/docs/index.md index be9166b529..355dbd046a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -70,9 +70,9 @@ Map operations are commands you can script from the command line, Python or the - **Themed** - Light and Dark ship. Write a theme as a JSON file of colours, spacing and text sizes, drop - it in the themes folder and pick it in Settings, or scale the whole interface from 80% to - 200%. + Light and Dark ship. On the desktop, write a theme as a JSON file of colours, spacing and + text sizes, drop it in the themes folder and pick it in Settings. Scale the whole interface + from 80% to 200% in either app. [Themes](themes.md) diff --git a/docs/themes.md b/docs/themes.md index 321315fac7..0632f1f9a5 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -42,7 +42,9 @@ On the desktop, to start from a theme you already have, use **Load a Theme from keeps the source text, including inherited settings and exact colour strings, in the themes folder (adding the resolved name if the file omitted it); edit that copy and the app follows it. Loading a file whose `name` matches a theme already in the folder replaces that copy, and the version it replaces is kept beside -it as `.json.bak`: one backup, replaced on each save. A file that does not load is listed in +it as `.json.bak`: one backup, replaced on each save. An interrupted save may leave +`.json.recover`, containing the theme from before the save. Copy it somewhere safe, +compare it with the theme and backup, then remove the recovery file before saving again. A file that does not load is listed in red at the bottom of the same menu with its reason. Unknown tokens and bad colour strings name the token; values of the wrong JSON type give a line and column. A notice says when a file was refused. diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index db5c825602..b12831ff78 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -458,7 +458,7 @@ duplication and nudging have their own [layout shortcuts](layouts.md#layouts). [20 languages](../i18n.md) and chooses the [worldview](maps.md#worldview) of the built-in borders. - **Theme**: **Settings › Theme** picks the interface colours, spacing and text sizes, from the - built-in Light and Dark themes, a theme [file](../themes.md) in the themes folder, or + built-in Light and Dark themes, a theme [file](../themes.md) in the desktop app’s themes folder, or **Follow the System** where the platform reports its own theme. **Interface Scale** beside it sets the whole interface from 80% to 200%. - **Autosave**: **Settings › Autosave** sets how often the desktop app keeps a From a19e5aa2bff76bb3c022730bc635391c745f4f3b Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 08:56:36 -0600 Subject: [PATCH 22/28] fix(themes): permit save retries and retain system brightness fallback --- crates/ui-egui/src/lib.rs | 29 ++++++++++++++++++++++------- crates/ui-egui/src/theme.rs | 35 ++++++++++++++++++++++++++++++++--- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5f759f7b8d..6c883a19e4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1770,14 +1770,16 @@ impl RustGisApp { /// A save preserving size and timestamp needs Reload Themes. fn refresh_themes(&mut self, ctx: &egui::Context) { let Some(dir) = theme::Theme::user_dir() else { return }; - ctx.request_repaint_after(web_time::Duration::from_secs(1)); let now = ctx.input(|i| i.time); - if now < self.themes_checked + 1.0 { - return; + if now >= self.themes_checked + 1.0 { + self.themes_checked = now; + if theme::Theme::folder_signature(Some(&dir)) != self.themes_stamp { + self.load_themes(); + } } - self.themes_checked = now; - if theme::Theme::folder_signature(Some(&dir)) != self.themes_stamp { - self.load_themes(); + // Zero means no readable folder. Without one, let the app sleep until another event. + if self.themes_stamp != 0 { + ctx.request_repaint_after(web_time::Duration::from_secs(1)); } } @@ -1817,8 +1819,12 @@ impl RustGisApp { self.ui.theme_name = wanted.unwrap_or_default(); if let Some(dark) = pref(self, "dark") { // "auto" was Follow the System; a toggle stores the brightness it left. - self.ui.dark = dark == "true"; self.ui.dark_follows_system = dark == "auto"; + self.ui.dark = if self.ui.dark_follows_system { + pref(self, "dark_fallback").map_or(self.ui.dark, |value| value == "true") + } else { + dark == "true" + }; } } let scale = pref(self, "ui_scale").and_then(|v| v.parse::().ok()); @@ -2568,6 +2574,7 @@ impl RustGisApp { self.ui.dark_follows_system = true; if let Some(save) = &self.services.save_pref { save("theme", ""); + save("dark_fallback", if self.ui.dark { "true" } else { "false" }); save("dark", "auto"); } } else { @@ -5147,6 +5154,14 @@ mod look_tests { let mut app = app_with(&[("theme", ""), ("dark", "auto")]); app.take_saved_look(); assert!(app.ui.dark_follows_system, "the choice to follow is remembered, not read as a toggle"); + app.ui.dark = true; + let log = saved_by(&mut app); + app.run("ui.themeFile", serde_json::json!({})).expect("follow the system"); + assert!(log.lock().expect("the log").iter().any(|(key, value)| key == "dark_fallback" && value == "true")); + let mut restarted = app_with(&[("theme", ""), ("dark", "auto"), ("dark_fallback", "true")]); + restarted.take_saved_look(); + assert!(restarted.ui.dark_follows_system); + assert!(restarted.ui.dark, "no reported system theme retains the saved fallback brightness"); let mut app = app_with(&[("theme", ""), ("dark", "false")]); app.take_saved_look(); assert!(!app.ui.dark_follows_system, "a saved brightness is a brightness, not a follow"); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index b3e3a74185..8eaafb6216 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -776,6 +776,15 @@ fn held_note(name: &str, held: usize) -> String { /// Atomically saves a theme, preserving a symlink's target, permissions and the last replaced copy. fn save_theme_text(path: &std::path::Path, text: &str) -> Result<(), String> { + save_theme_text_with(path, text, write_theme_text) +} + +/// Keeps recovery state only once the target may have changed; the writer is shared by all replacements. +fn save_theme_text_with( + path: &std::path::Path, + text: &str, + mut write: impl FnMut(&std::path::Path, &str, Option) -> std::io::Result<()>, +) -> Result<(), String> { let target = match std::fs::symlink_metadata(path) { Ok(meta) if meta.file_type().is_symlink() => std::fs::canonicalize(path).map_err(|e| why(path, &e.to_string()))?, Ok(_) => path.to_path_buf(), @@ -816,13 +825,19 @@ fn save_theme_text(path: &std::path::Path, text: &str) -> Result<(), String> { } } let saved = (|| -> Result<(), String> { - write_theme_text(&target, text, permissions.clone()).map_err(|e| why(&target, &e.to_string()))?; + if let Err(error) = write(&target, text, permissions.clone()) { + // An atomic writer that failed left the target intact: this was not an interrupted replacement. + if old.is_some() { + std::fs::remove_file(&recovery).map_err(|e| why(&recovery, &e.to_string()))?; + } + return Err(why(&target, &error.to_string())); + } // The old backup is changed only after the new theme was saved successfully. if let Some(old) = &old { let kept = target.with_extension("json.bak"); - if let Err(error) = write_theme_text(&kept, old, permissions.clone()) { + if let Err(error) = write(&kept, old, permissions.clone()) { let reason = why(&kept, &error.to_string()); - if let Err(restore) = write_theme_text(&target, old, permissions.clone()) { + if let Err(restore) = write(&target, old, permissions.clone()) { return Err(i18n::fmt( "{reason}; the previous theme is kept at {recovery}; restoration failed: {restore}", &[("reason", &reason), ("recovery", &recovery.display().to_string()), ("restore", &restore.to_string())], @@ -1465,6 +1480,20 @@ mod tests { assert!(backup.is_dir(), "the blocked destination is preserved"); } + /// An ordinary failed atomic write leaves the files intact and permits a subsequent save. + #[test] + fn a_failed_first_write_does_not_block_the_next_save() { + let dir = theme_folder(&[("mine.json", "old"), ("mine.json.bak", "older")]); + let path = dir.path().join("mine.json"); + assert!(save_theme_text_with(&path, "new", |_, _, _| Err(std::io::Error::other("failed replacement"))).is_err()); + assert_eq!(std::fs::read_to_string(&path).expect("theme"), "old"); + assert_eq!(std::fs::read_to_string(dir.path().join("mine.json.bak")).expect("backup"), "older"); + assert!(!dir.path().join("mine.json.recover").exists()); + save_theme_text(&path, "new").expect("retry succeeds"); + assert_eq!(std::fs::read_to_string(&path).expect("theme"), "new"); + assert_eq!(std::fs::read_to_string(dir.path().join("mine.json.bak")).expect("backup"), "old"); + } + /// A recovery copy left by an interrupted save is never overwritten by the next save. #[test] fn an_interrupted_save_keeps_its_recovery_copy() { From 17dd5500e803295e849b3cde51da43100dd08802 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 10:05:55 -0600 Subject: [PATCH 23/28] docs(themes): explain discovery of a newly created folder --- docs/themes.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/themes.md b/docs/themes.md index 0632f1f9a5..c229a5d062 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -48,7 +48,9 @@ compare it with the theme and backup, then remove the recovery file before savin red at the bottom of the same menu with its reason. Unknown tokens and bad colour strings name the token; values of the wrong JSON type give a line and column. A notice says when a file was refused. -The app checks file names, sizes and modification times once a second while it runs. A save +While the themes folder is readable, the app checks file names, sizes and modification times +once a second. Without that folder, the app does not wake just to check for themes. If you create +the folder while the app is idle, interact with the app or use **Reload Themes** to discover it. A save that changes that metadata is picked up automatically. If a save preserves both size and modification time, use **Reload Themes** to reread it. A theme in use that stops loading leaves the window on the nearest built-in until it loads again: the button names the theme drawn, the menu gives the reason, and the choice From 71a9d8835034282b455c6c0c70404fc2a1ce661e Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 11:17:42 -0600 Subject: [PATCH 24/28] fix(themes): reject malformed selectors and reserve Windows device stems --- crates/engine/src/tests.rs | 3 +++ crates/ui-egui/src/lib.rs | 41 +++++++++++++++++++++++++++++++++++++ crates/ui-egui/src/theme.rs | 4 ++-- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1d3f4e273a..9ea9dde1c5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24734,6 +24734,9 @@ fn geolibre_local_source_kinds_and_archives() { assert_eq!(s.map().tiles.len(), 2); let raster = s.map().layer_by_name("zarr").unwrap().raster.as_ref().unwrap().data.as_ref().unwrap(); assert!(raster.bands[0].data.iter().all(|v| *v >= 101.0 && *v <= 104.0), "saved time slice must survive native import"); + // Release source handles and the archive's pooled connection before Windows removes the files. + drop(s); + rustgis_data::mbtiles::close(&dir.join("tiles.mbtiles")); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6c883a19e4..e1e0b09ea2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1829,6 +1829,12 @@ impl RustGisApp { } let scale = pref(self, "ui_scale").and_then(|v| v.parse::().ok()); self.ui.interface_scale = scale.map_or(1.0, theme::clamp_scale); + if scale.is_some_and(|factor| factor != self.ui.interface_scale) { + self.session.notify( + i18n::fmt("Interface scale held to {percent}%", &[("percent", &format!("{:.0}", self.ui.interface_scale * 100.0))]), + false, + ); + } } /// Selects a loaded theme and saves its name and brightness; unknown names leave the choice unchanged. @@ -2541,6 +2547,9 @@ impl RustGisApp { } // The theme list in Settings is the one control for brightness; this picks its entry. "ui.theme" => { + if !p.is_null() && !p.as_object().is_some_and(|params| params.keys().all(|key| key == "dark")) { + return Err(i18n::fmt("ui.theme accepts only the dark parameter", &[])); + } let dark = match p.get("dark") { None => !self.ui.dark, Some(Value::Bool(dark)) => *dark, @@ -2565,6 +2574,9 @@ impl RustGisApp { } // Picks a theme by name; no name follows the system again. "ui.themeFile" => { + if !p.is_null() && !p.as_object().is_some_and(|params| params.keys().all(|key| key == "name")) { + return Err(i18n::fmt("ui.themeFile accepts only the name parameter", &[])); + } let name = match p.get("name") { Some(given) => given.as_str().ok_or_else(|| i18n::fmt("ui.themeFile needs a name string", &[]))?.trim().to_string(), None => String::new(), @@ -5070,6 +5082,22 @@ mod look_tests { assert!((ctx.zoom_factor() - 2.0).abs() < 0.001, "and the context is put back to the menu's value"); } + /// A persisted out-of-range scale reports its adjustment; a clean setting stays quiet. + #[test] + fn a_saved_scale_adjustment_is_reported() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut held = app_with(&[("ui_scale", "9")]); + held.session.notices.clear(); + held.take_saved_look(); + assert_eq!(held.ui.interface_scale, 2.0); + assert_eq!(held.session.notices.iter().filter(|n| n.text == "Interface scale held to 200%").count(), 1); + let mut clean = app_with(&[("ui_scale", "1.25")]); + clean.session.notices.clear(); + clean.take_saved_look(); + assert_eq!(clean.ui.interface_scale, 1.25); + assert!(clean.session.notices.is_empty()); + } + #[test] fn a_choice_outlives_a_file_that_stops_loading() { let dir = tempfile::tempdir().expect("a temporary folder"); @@ -5183,6 +5211,19 @@ mod look_tests { assert!(app.ui.dark_follows_system); assert!(log.lock().expect("the log").is_empty(), "rejection saves no preferences"); } + for params in [serde_json::json!({"nmae":"Mine"}), serde_json::json!("Mine"), serde_json::json!({"name":"Mine", "extra":true})] { + assert!(app.run("ui.themeFile", params).is_err()); + assert_eq!(app.ui.theme_name, "Custom"); + assert!(!app.ui.dark); + assert!(app.ui.dark_follows_system); + assert!(log.lock().expect("the log").is_empty(), "malformed parameters save no preferences"); + } + for params in [serde_json::json!({"drak":false}), serde_json::json!("Dark")] { + assert!(app.run("ui.theme", params).is_err()); + assert_eq!(app.ui.theme_name, "Custom"); + assert!(!app.ui.dark); + assert!(log.lock().expect("the log").is_empty()); + } app.run("ui.theme", serde_json::json!({})).expect("omitting dark still toggles"); assert!(app.ui.dark); let why = app.run("ui.themeFile", serde_json::json!({ "name": 5 })).expect_err("a name must be a string"); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 8eaafb6216..4e4026a290 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -897,7 +897,7 @@ fn stem_of(name: &str) -> String { || stem .strip_prefix("com") .or_else(|| stem.strip_prefix("lpt")) - .is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")); + .is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³")); if stem.is_empty() { "theme".to_string() } else if reserved { @@ -1420,7 +1420,7 @@ mod tests { let source = r##"{"schema":1,"name":"Mine","extends":"Dark","colours":{"accent":"#2563EB80"}}"##; let theme = Theme::parse("mine", source).expect("theme"); assert_eq!(theme.source_text(source).expect("source"), source); - for name in ["CON", "NUL", "PRN", "AUX", "COM1", "LPT9"] { + for name in ["CON", "NUL", "PRN", "AUX", "COM1", "LPT9", "COM¹", "COM²", "COM³", "LPT¹", "LPT²", "LPT³"] { assert!(stem_of(name).starts_with("theme-"), "{name}"); } } From 0eaf09db37e882f629e33f38971b840a7c883f8d Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 12:04:17 -0600 Subject: [PATCH 25/28] fix(themes): report numeric adjustments and incomplete save state --- apps/rustgis-python/tests/test_qt.py | 2 +- crates/ui-egui/src/lib.rs | 11 +++++-- crates/ui-egui/src/theme.rs | 44 +++++++++++++++++++++------- docs/themes.md | 3 +- 4 files changed, 46 insertions(+), 14 deletions(-) diff --git a/apps/rustgis-python/tests/test_qt.py b/apps/rustgis-python/tests/test_qt.py index 02a9d942fb..472cc1f19e 100644 --- a/apps/rustgis-python/tests/test_qt.py +++ b/apps/rustgis-python/tests/test_qt.py @@ -138,7 +138,7 @@ def test_a_reload_holds_messages_until_the_page_starts_again(widget): from_page(widget, {"type": "host"}) widget.scripts.clear() widget._unready() # what loadStarted calls - widget.run_in_app("ui.theme", theme="dark") + widget.run_in_app("ui.theme", dark=True) widget.add_geojson(POINT, name="Sites") assert widget.scripts == [] from_page(widget, {"type": "host"}) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e1e0b09ea2..e312f7eb83 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1827,9 +1827,11 @@ impl RustGisApp { }; } } - let scale = pref(self, "ui_scale").and_then(|v| v.parse::().ok()); + let saved = pref(self, "ui_scale"); + let scale = saved.as_deref().and_then(|v| v.parse::().ok()); self.ui.interface_scale = scale.map_or(1.0, theme::clamp_scale); - if scale.is_some_and(|factor| factor != self.ui.interface_scale) { + if saved.is_some() && scale.is_none_or(|factor| factor != self.ui.interface_scale) { + i18n::set_current(self.chosen_lang()); self.session.notify( i18n::fmt("Interface scale held to {percent}%", &[("percent", &format!("{:.0}", self.ui.interface_scale * 100.0))]), false, @@ -5096,6 +5098,11 @@ mod look_tests { clean.take_saved_look(); assert_eq!(clean.ui.interface_scale, 1.25); assert!(clean.session.notices.is_empty()); + let mut malformed = app_with(&[("ui_scale", "1,25")]); + malformed.session.notices.clear(); + malformed.take_saved_look(); + assert_eq!(malformed.ui.interface_scale, 1.0); + assert_eq!(malformed.session.notices.iter().filter(|n| n.text == "Interface scale held to 100%").count(), 1); } #[test] diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 4e4026a290..affad5bc65 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -245,7 +245,7 @@ struct MetricsFile { #[serde(default, skip_serializing_if = "Option::is_none")] row_height: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - corner_radius: Option, + corner_radius: Option, #[serde(default, skip_serializing_if = "Option::is_none")] body: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -264,7 +264,7 @@ impl MetricsFile { item_spacing: Some(metrics.item_spacing), button_padding: Some(metrics.button_padding), row_height: Some(metrics.row_height), - corner_radius: Some(u64::from(metrics.corner_radius)), + corner_radius: Some(f64::from(metrics.corner_radius)), body: Some(metrics.body), button_text: Some(metrics.button_text), small: Some(metrics.small), @@ -273,8 +273,9 @@ impl MetricsFile { } } - /// Applies the sizes the file sets; the rest keep what the theme it extends gave them. - fn apply_to(self, metrics: &mut Metrics) { + /// Applies sizes over the inherited metrics; returns the number of radii clamped or rounded. + fn apply_to(self, metrics: &mut Metrics) -> usize { + let mut held = 0; if let Some(v) = self.item_spacing { metrics.item_spacing = v; } @@ -285,7 +286,8 @@ impl MetricsFile { metrics.row_height = v; } if let Some(v) = self.corner_radius { - metrics.corner_radius = u8::try_from(v).unwrap_or(u8::MAX); + metrics.corner_radius = v.clamp(0.0, 32.0).round() as u8; + held += usize::from(v != f64::from(metrics.corner_radius)); } if let Some(v) = self.body { metrics.body = v; @@ -302,6 +304,7 @@ impl MetricsFile { if let Some(v) = self.mono { metrics.mono = v; } + held } } @@ -473,10 +476,9 @@ impl Theme { // apply() draws from this flag, so a base theme cannot decide the brightness. tokens.dark = dark; let mut metrics = fallback.metrics; - if let Some(file) = raw.metrics { - file.apply_to(&mut metrics); - } + let held_radius = raw.metrics.map_or(0, |file| file.apply_to(&mut metrics)); let (metrics, held) = metrics.clamped(); + let held = held + held_radius; if held > 0 { notes.push(held_note(&name, held)); } @@ -847,17 +849,25 @@ fn save_theme_text_with( std::fs::remove_file(&recovery).map_err(|e| why(&recovery, &e.to_string()))?; return Err(reason); } - sync_theme_folder(&target).map_err(|e| why(&recovery, &e.to_string()))?; + sync_theme_folder(&target).map_err(|e| incomplete_save(&target, &recovery, &e))?; } Ok(()) })(); saved?; if old.is_some() { - std::fs::remove_file(&recovery).map_err(|e| why(&recovery, &e.to_string()))?; + std::fs::remove_file(&recovery).map_err(|e| incomplete_save(&target, &recovery, &e))?; } Ok(()) } +/// Makes a partial save explicit: written files do not imply completed durability or recovery cleanup. +fn incomplete_save(path: &std::path::Path, recovery: &std::path::Path, error: &std::io::Error) -> String { + i18n::fmt( + "{path}: the theme was written, but save completion failed: {reason}. A recovery copy may remain at {recovery}; compare the files before removing it and retrying.", + &[("path", &path.display().to_string()), ("reason", &error.to_string()), ("recovery", &recovery.display().to_string())], + ) +} + /// Persists the recovery entry and completed renames on systems that support directory syncing. fn sync_theme_folder(path: &std::path::Path) -> std::io::Result<()> { #[cfg(unix)] @@ -1583,6 +1593,20 @@ mod tests { assert!(theme.notes[0].contains("5 sizes"), "every held value is counted: {:?}", theme.notes); } + /// Radius clamping and rounding are counted, while an exact supported radius stays quiet. + #[test] + fn negative_and_fractional_radii_are_reported() { + for (value, radius, held) in [(-1.0, 0, true), (5.5, 6, true), (5.0, 5, false)] { + let text = serde_json::json!({"schema":1,"extends":"Light","metrics":{"corner_radius":value}}); + let theme = Theme::parse("Mine", &text.to_string()).expect("numeric radius"); + assert_eq!(theme.metrics.corner_radius, radius); + assert_eq!(theme.notes.len(), usize::from(held)); + if held { + assert!(theme.notes[0].contains("1 size")); + } + } + } + #[test] fn a_clean_file_says_nothing() { let clean = Theme::parse("Mine", r#"{"schema": 1, "name": "Mine", "extends": "Light"}"#).expect("it parses"); diff --git a/docs/themes.md b/docs/themes.md index c229a5d062..e7cd0f9ac3 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -42,7 +42,7 @@ On the desktop, to start from a theme you already have, use **Load a Theme from keeps the source text, including inherited settings and exact colour strings, in the themes folder (adding the resolved name if the file omitted it); edit that copy and the app follows it. Loading a file whose `name` matches a theme already in the folder replaces that copy, and the version it replaces is kept beside -it as `.json.bak`: one backup, replaced on each save. An interrupted save may leave +it as `.json.bak`: one backup, replaced on each save. An interrupted save, or a save whose final syncing or cleanup fails, may leave `.json.recover`, containing the theme from before the save. Copy it somewhere safe, compare it with the theme and backup, then remove the recovery file before saving again. A file that does not load is listed in red at the bottom of the same menu with its reason. Unknown tokens and bad colour strings name @@ -143,6 +143,7 @@ refused by number. map's light or dark defaults. It is not inferred from the colours. `metrics` are in points: item spacing, button padding, row height, corner radius and text sizes. +Corner radius is held between 0 and 32 and rounded to the nearest whole point; an adjustment is counted. Sizes are held to what a window can draw, and a notice says when a value was held. A file over 64 KB is not read. From fef91d026294dbf14aa78b470b398e4a1d00204a Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 16:14:19 -0600 Subject: [PATCH 26/28] fix(themes): select the saved language before startup theme reads --- crates/ui-egui/src/lib.rs | 41 ++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 86fa2078ad..7941137b27 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1131,7 +1131,7 @@ impl RustGisApp { // isn't written to the preferences. let ui = UiState { keymap: keymap::Keymap::new(&s.registry), layout_favourite_saved: s.layout_favourite.clone(), ..UiState::default() }; - let mut app = RustGisApp { + RustGisApp { session: s, ui, map: mapview::MapView::default(), @@ -1155,7 +1155,7 @@ impl RustGisApp { fonts_frames: 0, frame_start: None, applied_theme: None, - themes: Vec::new(), + themes: theme::Theme::builtin(), theme_errors: Vec::new(), theme_notes: Vec::new(), themes_stamp: 0, @@ -1191,9 +1191,7 @@ impl RustGisApp { seen_project: None, autosave: Default::default(), save_prompt: Default::default(), - }; - app.load_themes(); - app + } } /// Installs the shell's platform hooks and reads what they keep: preferences, saved @@ -1210,6 +1208,8 @@ impl RustGisApp { if let Some(lang) = self.services.load_pref.as_ref().and_then(|load| load("language")) { self.ui.language = lang; } + // Theme readers and startup notices keep translated text, so select the language before reading. + i18n::set_current(self.chosen_lang()); // A stored value that is neither `auto` nor a known worldview means `auto`. if let Some(w) = self.services.load_pref.as_ref().and_then(|load| load("worldview")) && rustgis_engine::sample::Worldview::from_code(&w).is_some() @@ -5161,6 +5161,37 @@ mod look_tests { app } + #[test] + fn theme_startup_reads_after_the_saved_language_is_selected() { + struct RestoreLanguage(crate::i18n::Lang); + impl Drop for RestoreLanguage { + /// Restores this test thread's caller language even if the startup assertion fails. + fn drop(&mut self) { + crate::i18n::set_current(self.0); + } + } + let _restore = RestoreLanguage(crate::i18n::current()); + crate::i18n::set_current(crate::i18n::Lang::EN); + let app = RustGisApp::with_sample(); + assert_eq!(app.themes_revision, 0, "construction must not read user themes or emit their notices"); + assert_eq!(app.themes.len(), 2, "built-in themes remain available before platform services"); + let services = super::Services { + load_pref: Some(Box::new(|key| { + if key == "language" { + return Some("de".to_string()); + } + if key == "theme" { + assert_eq!(crate::i18n::current().code(), "de", "the theme folder was read in the chosen language"); + } + None + })), + ..super::Services::default() + }; + let app = app.with_services(services); + assert_eq!(app.themes_revision, 1, "the folder is read once during preference restoration"); + assert_eq!(crate::i18n::current().code(), "de"); + } + #[test] fn the_saved_theme_is_taken_at_start() { let mut app = app_with(&[("theme", "Mine"), ("ui_scale", "9")]); From 0d60168d16515a87f993406a4a9aa0f147c508db Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 16:50:40 -0600 Subject: [PATCH 27/28] fix(ui-shot): load custom themes before split-showcase commands --- crates/ui-egui/examples/ui_shot.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ui-egui/examples/ui_shot.rs b/crates/ui-egui/examples/ui_shot.rs index 9f0d35d25a..eacfa7a7f0 100644 --- a/crates/ui-egui/examples/ui_shot.rs +++ b/crates/ui-egui/examples/ui_shot.rs @@ -200,6 +200,10 @@ fn main() { for _ in 0..6 { harness.step(); } + // The split showcase skips frame logic, so load user themes before scripted selection. + if ribbon_split && let Err(error) = harness.state_mut().run("ui.themeReload", Value::Null) { + eprintln!("ui.themeReload: {error}"); + } // The button the last drag holds down. let mut held = egui::PointerButton::Primary; // And the modifiers held with it. From e72399779e91149d9419d47b7a6afeb2b2dc8bc7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 4 Nov 2026 17:18:41 -0600 Subject: [PATCH 28/28] fix(themes): refuse the desktop theme picker in browser commands --- crates/ui-egui/src/lib.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7941137b27..23356536e4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2627,6 +2627,9 @@ impl RustGisApp { } } "ui.themeLoad" => { + if cfg!(target_arch = "wasm32") { + return Err(i18n::fmt("Loading a theme file needs the desktop app", &[])); + } let Some(path) = dialogs::pick_open(&["json"], tl!("A theme file")) else { return Ok(Value::Null) }; self.load_theme_file(std::path::Path::new(&path))?; }