diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3a339e7551..379e0698f5 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -15,6 +15,7 @@ of use. | File | Author / source | Licence | |---|---|---| +| Interface themes (`crates/ui-egui/themes/light.json`, `dark.json`) | The RustGIS project | Apache-2.0 | | Sample data (`countries`, `countries_chn`, `cities`, `rivers`, `lakes` GeoJSON), embedded at build time from [rustgis-assets](https://github.com/opengeos/rustgis-assets/tree/main/data) | Natural Earth 1:110m, attributes trimmed; `countries_chn` is Natural Earth's China point of view (1:10m, simplified) | Public domain | | QGIS screenshot (`qgis-world-atlas.webp` in [rustgis-assets](https://github.com/opengeos/rustgis-assets/tree/main/images)), on the [RustGIS and QGIS](docs/comparison/qgis.md) page | Taken by the RustGIS project: [QGIS](https://qgis.org) 4.2 showing the Natural Earth sample data above | QGIS is GPL-2.0-or-later; the data is public domain | | QGIS test corpus (`crates/map/testdata/qgis/generated/`: styles, projects and their sample data) | Dominik Strebel ([@pick2510](https://github.com/pick2510)) for the RustGIS project: written by [QGIS](https://qgis.org) 4.2.3 through its API, from `generate.py` there; the data is made up | Apache-2.0 | 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/assistant/src/docs.rs b/crates/assistant/src/docs.rs index 952cc7405a..1e31c31979 100644 --- a/crates/assistant/src/docs.rs +++ b/crates/assistant/src/docs.rs @@ -45,6 +45,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/Cargo.toml b/crates/ui-egui/Cargo.toml index 5e506be506..525a8a623a 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -37,7 +37,7 @@ rfd = { workspace = true } # Stopping an agent on this computer with every process it started: its process group, by the # system call (as the plugins crate does). [target.'cfg(unix)'.dependencies] -rustix = { version = "1.1", features = ["process"] } +rustix = { version = "1.1", features = ["process", "fs"] } [dev-dependencies] tempfile = "3" diff --git a/crates/ui-egui/examples/ui_shot.rs b/crates/ui-egui/examples/ui_shot.rs index e92a0ca168..eacfa7a7f0 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, 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_dark != Some(app.ui.dark) { - let tokens = if app.ui.dark { theme::Tokens::dark() } else { theme::Tokens::light() }; - theme::apply(ui.ctx(), &tokens); - self.applied_dark = Some(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(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(); @@ -194,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. diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index d3c0752172..cc0cf79693 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -667,7 +667,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). @@ -697,7 +697,11 @@ 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.themeFile", "Follow the System", "Settings › Theme"), + ("ui.themeLoad", "Load a Theme from File…", "Settings › Theme"), + ("ui.themeReload", "Reload Themes", "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"), @@ -993,8 +997,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/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/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 cd4e530806..23356536e4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -580,6 +580,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.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, /// The theme follows the system's light or dark setting until the user picks one. @@ -817,6 +821,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(), @@ -945,7 +951,18 @@ pub struct RustGisApp { fonts_frames: u32, /// When this frame's `logic` began, for the double-click delay `ui` sets when it ends. frame_start: Option, - applied_dark: Option, + applied_theme: Option<(String, bool)>, + /// 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 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, logo: Option, @@ -1137,7 +1154,14 @@ impl RustGisApp { assistant: assistantpane::AssistantState::default(), fonts_frames: 0, frame_start: None, - applied_dark: None, + applied_theme: None, + themes: theme::Theme::builtin(), + 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, logo: None, @@ -1184,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() @@ -1258,6 +1284,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() }; + // 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")))); 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 @@ -1694,6 +1723,190 @@ impl RustGisApp { } } + /// Reloads available theme files from the user folder, retaining built-ins when it is absent. + fn load_themes(&mut self) { + 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); + 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. + self.announce_theme_errors(&errors); + let fresh: Vec = notes.iter().filter(|note| !self.theme_notes.contains(note)).cloned().collect(); + self.announce_theme_notes(&fresh); + 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); + } + + /// Reports this read's adjustments; folder refreshes filter unchanged notes before calling. + fn announce_theme_notes(&mut self, notes: &[String]) { + if !notes.is_empty() { + let details = notes.iter().take(8).map(String::as_str).collect::>().join("; "); + self.session.notify( + i18n::fmt( + "{n} theme adjustment notice(s): {details}. Open Settings > Theme for all details.", + &[("n", ¬es.len().to_string()), ("details", &details)], + ), + 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() { + return; + } + if let Some(dark) = self.themes.iter().find(|t| t.name == self.ui.theme_name).map(|t| t.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; + } + } + + /// 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 }; + let now = ctx.input(|i| i.time); + if now >= self.themes_checked + 1.0 { + 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)); + } + } + + /// 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.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(), + notes: Vec::new(), + }) + }) + } + + /// 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()) + }; + let wanted = pref(self, "theme"); + 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 { + // 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_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 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 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, + ); + } + } + + /// Selects a loaded theme and saves its name and brightness; unknown names leave the choice unchanged. + 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(()) + } + + /// Validates a bounded theme file, preserves its source in the user folder, then selects it. + fn load_theme_file(&mut self, path: &std::path::Path) -> Result<(), String> { + 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) => 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()); + 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()); + } + } + 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 @@ -2365,10 +2578,84 @@ 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); + 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, + 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" }; + // 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); + save("dark", if dark { "true" } else { "false" }); + } + } + // 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(), + }; + 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", ""); + save("dark_fallback", if self.ui.dark { "true" } else { "false" }); + save("dark", "auto"); + } + } else { + self.use_theme(&name)?; + } } + "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))?; + } + "ui.scale" => { + if !p.is_null() && !p.as_object().is_some_and(|params| params.keys().all(|key| key == "factor")) { + return Err(i18n::fmt("ui.scale accepts only the factor parameter", &[])); + } + let factor = match p.get("factor") { + 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); + if self.ui.interface_scale != factor { + self.session.notify( + i18n::fmt("Interface scale held to {percent}%", &[("percent", &format!("{:.0}", self.ui.interface_scale * 100.0))]), + false, + ); + } + if let Some(save) = &self.services.save_pref { + save("ui_scale", &self.ui.interface_scale.to_string()); + } + } + "ui.themeReload" => self.load_themes(), "ui.measurementUnits" => { let imperial = match p.get("units") { None => !self.ui.measurement_imperial, @@ -4178,6 +4465,7 @@ impl RustGisApp { ctx.request_repaint(); } } + self.refresh_themes(ctx); if self.ui.dark_follows_system && let Some(system) = ctx.system_theme() { @@ -4185,14 +4473,42 @@ 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(); + } + // egui's own zoom keys would change the zoom behind the Interface Scale menu. + ctx.options_mut(|o| o.zoom_with_keyboard = false); + // 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.map.invalidate(); } } + /// 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 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. + theme::label(&drawn.name) + } else if self.ui.dark { + theme::label("Dark") + } else { + theme::label("Light") + }; + (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_revision + } + pub fn ui(&mut self, ui: &mut egui::Ui) { let _diagnostics = self.session.diagnostics.enter(); let ctx = ui.ctx().clone(); @@ -4827,3 +5143,411 @@ 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; + + /// 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 { + name: "Mine".to_string(), + 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 + } + + #[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")]); + 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_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_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_menu_owns_the_interface_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(); + }; + 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); + 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")); + 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"); + let before = app.ui.interface_scale; + assert!(app.run("ui.scale", serde_json::json!({"factr": 1.5})).is_err()); + assert_eq!(app.ui.interface_scale, before, "an unknown parameter does not reset the scale"); + // 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); + 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"); + } + + /// 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()); + 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] + 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.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(&[]); + 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(); + 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"); + } + + #[test] + fn the_fallback_takes_the_brightness_asked_for() { + let mut app = app_with(&[]); + // 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 = "Gone".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(&[]); + 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")]); + 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"); + assert!(!app.ui.dark); + } + + #[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"); + } + 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"); + 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(&[]); + 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")]); + app.take_saved_look(); + 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"); + } + + #[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"); + std::fs::write(dir.path().join("other.json"), text.replace("Mine", "Other")).expect("another file"); + let mut app = app_with(&[]); + let said = |app: &RustGisApp| app.session.notices.iter().filter(|n| n.text.contains("theme adjustment notice")).count(); + let before = said(&app); + app.load_themes_from(Some(dir.path())); + assert_eq!(said(&app) - before, 1, "the adjustments are reported together"); + assert!(app.session.notices.iter().any(|n| n.text.starts_with("2 theme adjustment notice"))); + app.load_themes_from(Some(dir.path())); + assert_eq!(said(&app) - before, 1, "and not again on the next watch tick"); + let notes = app.themes.iter().find(|t| t.name == "Mine").expect("the lossy theme loaded").notes.clone(); + for expected in [2, 3] { + app.announce_theme_notes(¬es); + assert_eq!(said(&app) - before, expected, "an explicit read reports even previously held adjustments"); + } + app.announce_theme_notes(&[]); + app.load_themes_from(Some(dir.path())); + assert_eq!(said(&app) - before, 3, "a clean read and unchanged folder refresh remain quiet"); + } + + 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(); + 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..efca5b1105 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, @@ -3440,8 +3438,12 @@ 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, scale, customization, language, start-up and 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 +3500,92 @@ fn autosave_menu(app: &mut RustGisApp, ui: &mut Ui) { }); } +/// Shows the actual drawn theme, including built-in fallback, and file-loading diagnostics. +fn theme_menu(app: &mut RustGisApp, ui: &mut Ui) { + // 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: 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 fallback = drawn.is_none().then(|| app.current_theme().name); + 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( + 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 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() { + run_notified(app, "ui.themeFile", Value::Null); + ui.close(); + } + if let Some(name) = &fallback { + let label = crate::i18n::fmt("{name} (built-in fallback)", &[("name", &crate::theme::label(name))]); + ui.add_enabled(false, egui::Button::selectable(!follows, label)); + } + for name in &themes { + 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(); + } + } + if folder { + ui.separator(); + if ui.add(egui::Button::selectable(false, tl!("Load a Theme from File…"))).clicked() { + run_notified(app, "ui.themeLoad", Value::Null); + ui.close(); + } + if ui.add(egui::Button::selectable(false, tl!("Reload Themes"))).clicked() { + run_notified(app, "ui.themeReload", Value::Null); + ui.close(); + } + } + if !errors.is_empty() || !notes.is_empty() { + ui.separator(); + let tokens = Tokens::get(ui.ctx()); + for error in &errors { + 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()); + } + } + }, + ); +} + +/// Runs a UI command; `run` reports a failure itself. +fn run_notified(app: &mut RustGisApp, id: &str, params: Value) { + let _ = app.run(id, params); +} + +/// 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")); + 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() { + run_notified(app, "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/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)); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 4d47c8a4cc..525e4dbfaa 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -1,17 +1,111 @@ -//! 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}; +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; + // Non-blocking open prevents a file replaced by a FIFO from hanging the UI thread. + #[cfg(unix)] + let file = std::fs::File::from( + rustix::fs::open( + path, + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NONBLOCK | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) + .map_err(|e| Over::Reason(e.to_string()))?, + ); + #[cfg(not(unix))] + let file = std::fs::File::open(path).map_err(|e| Over::Reason(e.to_string()))?; + let meta = file.metadata().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 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. +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; + +/// A larger file is refused before it is read. +pub const MAX_THEME_BYTES: u64 = 64 * 1024; + +/// 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. +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 +138,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 +176,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 +213,757 @@ 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), } } + /// Falls back to the brightness when no theme was applied to the context. 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() }) + } +} + +/// egui temp data key that lets every widget read the applied colours. +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)] +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(f64::from(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 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; + } + 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.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; + } + 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; + } + held + } +} + +#[derive(Clone, Copy, Debug, PartialEq, 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, + } + } + + /// 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(); + 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]), + ], + 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), + }; + (metrics, held_count(self, metrics)) + } +} + +/// 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.8, 2.0) } else { 1.0 } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Theme { + pub name: String, + 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)] +#[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")] + extends: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + dark: Option, + #[serde(default, deserialize_with = "read_colours")] + colours: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + metrics: Option, +} + +/// Rejects repeated colour names before a map could silently replace their first value. +fn read_colours<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + struct Colours; + impl<'de> serde::de::Visitor<'de> for Colours { + type Value = BTreeMap; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a map of unique colour names to colour strings") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut colours = BTreeMap::new(); + while let Some((name, value)) = map.next_entry::()? { + if colours.contains_key(&name) { + return Err(serde::de::Error::custom(i18n::fmt("duplicate colour {name}", &[("name", &name)]))); + } + colours.insert(name, value); + } + Ok(colours) + } + } + deserializer.deserialize_map(Colours) +} + +impl Theme { + /// `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() + .map(|(name, text, fallback)| { + Theme::parse(name, text).unwrap_or(Theme { + name: name.to_string(), + dark: fallback.dark, + tokens: fallback, + metrics: Metrics::standard(), + notes: Vec::new(), + }) + }) + .collect() + } + + /// Reads the schema and named tokens, reporting semantic errors or the JSON parser location. + 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 mut notes = Vec::new(); + let mut name = clean_name(&raw.name, &mut notes); + if name.is_empty() { + name = clean_name(fallback_name, &mut notes); + } + if name.is_empty() { + name = "Theme".to_string(); + } + if raw.schema != 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(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() { + 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() { + 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(), + 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 { + 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; + 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)); + } + Ok(Theme { name, dark, tokens, metrics, notes }) + } + + /// Serializes resolved tokens and metrics without inheritance; importing a file preserves its original source instead. + 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(MetricsFile::from(&self.metrics)), + }; + 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. + 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 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 = 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(); + 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) { + 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)), + Err(Over::Reason(reason)) => errors.push(why(&path, &reason)), + } + } + (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 }; + let Ok(read) = std::fs::read_dir(dir) else { return 0 }; + let mut stamps: Vec<(String, u64, u128)> = read + .flatten() + .filter(|e| is_theme_file(&e.path())) + .filter_map(|e| { + let path = e.path(); + // 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(web_time::UNIX_EPOCH).ok()?.as_nanos(); + 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")) + } + + /// 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 }; + 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); + } + } + } + for at in 1..=99 { + let name = if at == 1 { format!("{stem}.json") } else { format!("{stem}-{at}.json") }; + let path = dir.join(name); + // 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. + let own = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); + if let Ok(text) = read_text(&path) + && Theme::parse(&own, &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)]))) + } + + /// Preserves source tokens and inheritance, adding the resolved name when it came from the file stem. + fn source_text<'a>(&self, text: &'a str) -> Result, String> { + let mut value: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| e.to_string())?; + let has_name = value + .get("name") + .and_then(serde_json::Value::as_str) + .is_some_and(|name| name.chars().any(|c| !c.is_control() && !c.is_whitespace())); + if has_name { + return Ok(std::borrow::Cow::Borrowed(text)); + } + let object = value.as_object_mut().ok_or_else(|| i18n::fmt("A theme file must be a JSON object.", &[]))?; + object.insert("name".to_string(), serde_json::Value::String(self.name.clone())); + serde_json::to_string_pretty(&value).map(std::borrow::Cow::Owned).map_err(|e| e.to_string()) + } + + /// Keeps the picked source text, preserving inherited settings and exact colour values. + pub fn save_user(&self, text: &str) -> 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 = self.save_path(&dir)?; + let source = self.source_text(text)?; + save_theme_text(&path, &source)?; + 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, + }) +} + +/// 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) +} + +/// `#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, 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 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())]) + } +} + +/// 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(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => path.to_path_buf(), + Err(e) => return Err(why(path, &e.to_string())), + }; + let old = if target.exists() { + Some(read_text(&target).map_err(|e| match e { + Over::TooBig => too_big(&target), + Over::Reason(reason) => why(&target, &reason), + })?) + } else { + None + }; + let recovery = target.with_extension("json.recover"); + if old.as_deref() == Some(text) { + return match std::fs::symlink_metadata(&recovery) { + Ok(_) => Err(i18n::fmt( + "{path}: the theme is unchanged, but a recovery copy remains at {recovery}; compare the files before removing it and retrying.", + &[("path", &target.display().to_string()), ("recovery", &recovery.display().to_string())], + )), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(why(&recovery, &error.to_string())), + }; + } + let permissions = std::fs::metadata(&target).ok().map(|m| m.permissions()); + // 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. + 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)?; + } + 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> { + 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(&kept, old, permissions.clone()) { + let reason = why(&kept, &error.to_string()); + 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())], + )); + } + 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| incomplete_save(&target, &recovery, &e))?; + } + Ok(()) + })(); + saved?; + if old.is_some() { + 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)] + if let Some(parent) = path.parent() { + std::fs::File::open(parent)?.sync_all()?; + } + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + +/// Sets the temporary file's permissions before writing any theme content into it. +fn write_theme_text(path: &std::path::Path, text: &str, permissions: Option) -> std::io::Result<()> { + use std::io::Write; + rustgis_engine::data::io::write_atomic_with(path, |out| { + if let Some(permissions) = permissions { + out.get_ref().set_permissions(permissions)?; + } + out.write_all(text.as_bytes()) + }) +} + +/// 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(); + let stem = dashed.trim_matches('-').to_string(); + let reserved = matches!(stem.as_str(), "con" | "prn" | "aux" | "nul") + || 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" | "¹" | "²" | "³")); + if stem.is_empty() { + "theme".to_string() + } else if reserved { + format!("theme-{stem}") + } 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 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| { + 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)?)), + _ => Err(bad()), } } @@ -184,8 +1027,9 @@ pub fn install_fonts( ctx.set_fonts(fonts); } -pub fn apply(ctx: &egui::Context, t: &Tokens) { +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 +1042,39 @@ 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.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)); // 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 +1087,618 @@ 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 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() { + 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 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() { + 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": "Gone"}"#; + let err = Theme::parse("mine", text).expect_err("no theme called Gone ships"); + 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", "{}")]); + 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"); + } + + #[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"); + 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_repeated_colour_is_refused_by_name() { + let repeated = r##"{"schema":1,"extends":"Dark","colours":{"accent":"#111111","accent":"#222222"}}"##; + let error = Theme::parse("Mine", repeated).expect_err("a repeated colour cannot replace the first silently"); + assert!(error.contains("duplicate colour accent"), "{error}"); + let clean = r##"{"schema":1,"extends":"Dark","colours":{"accent":"#222222"}}"##; + let theme = Theme::parse("Mine", clean).expect("one value per colour"); + assert!(theme.notes.is_empty(), "{:?}", theme.notes); + } + + #[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("my-theme", &json.to_string()).expect("it parses"); + assert_eq!(theme.name, "my-theme"); + } + + #[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}"); + } + } + + 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.path().join(file), text).expect("the file"); + } + 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"); + let numbered = theme_folder(&[ + ("ocean.json", r#"{"schema":1,"extends":"Light","name":"Sea"}"#), + ("ocean-2.json", r#"{"schema":1,"extends":"Light"}"#), + ]); + let ocean = Theme::parse("ocean", r#"{"schema":1,"extends":"Light"}"#).expect("a nameless imported theme"); + let path = ocean.save_path(numbered.path()).expect("a free file"); + assert_eq!(path.file_name().and_then(|n| n.to_str()), Some("ocean-3.json"), "the numbered file owns its own fallback name"); + } + + #[test] + fn a_theme_in_the_user_folder_is_offered() { + let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); + 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"); + } + + #[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(&[("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"); + } + + #[test] + 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(&[("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"); + 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 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); + 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 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_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_two_files_claim_is_reported_once() { + let mine = light().to_json().expect("json").replace("\"Light\"", "\"Mine\""); + 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:?}"); + 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"); + 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"); + 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(&[("mine.json", &edited)]); + let path = dir.path().join("mine.json"); + save_theme_text(&path, &picked).expect("the backup"); + 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"), picked, "the new theme was saved"); + // 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.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. + save_theme_text(&path, &picked).expect("no backup needed"); + assert_eq!(std::fs::read_to_string(dir.path().join("mine.json.bak")).expect("the backup file"), edited); + } + + /// Missing names use the source stem and remain stable when the kept copy has another file name. + #[test] + fn a_missing_theme_name_keeps_its_fallback_when_saved() { + let source = r##"{"schema":1,"extends":"Dark","colours":{"accent":"#2563EB80"}}"##; + let theme = Theme::parse("My Theme", source).expect("the file stem supplies the name"); + assert_eq!(theme.name, "My Theme"); + let kept = theme.source_text(source).expect("the kept source"); + let raw: serde_json::Value = serde_json::from_str(&kept).expect("json"); + assert_eq!(raw["extends"], "Dark"); + assert_eq!(raw["colours"]["accent"], "#2563EB80"); + assert_eq!(Theme::parse("my-theme", &kept).expect("reload").name, "My Theme"); + assert!(theme.source_text("[]").is_err(), "a malformed source must not panic while inserting its name"); + } + + /// A picked named file keeps its exact source, rather than quantizing alpha colours on export. + #[test] + fn a_named_theme_preserves_its_source_text() { + 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", "COM¹", "COM²", "COM³", "LPT¹", "LPT²", "LPT³"] { + assert!(stem_of(name).starts_with("theme-"), "{name}"); + } + } + + /// Saving through a symlink updates its target and preserves restricted permissions. + #[cfg(unix)] + #[test] + fn a_theme_save_preserves_links_and_permissions() { + use std::os::unix::fs::PermissionsExt; + let dir = theme_folder(&[("real.json", "old")]); + let target = dir.path().join("real.json"); + let link = dir.path().join("mine.json"); + std::os::unix::fs::symlink(&target, &link).expect("link"); + std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600)).expect("permissions"); + save_theme_text(&link, "new").expect("save"); + assert!(std::fs::symlink_metadata(&link).expect("metadata").file_type().is_symlink()); + assert_eq!(std::fs::read_to_string(&target).expect("target"), "new"); + assert_eq!(std::fs::metadata(&target).expect("metadata").permissions().mode() & 0o777, 0o600); + assert_eq!(std::fs::read_to_string(dir.path().join("real.json.bak")).expect("backup"), "old"); + } + + /// Linux's FIFO test exercises the non-blocking open used before inspecting the file handle. + #[cfg(target_os = "linux")] + #[test] + fn a_theme_fifo_is_refused_without_blocking() { + let dir = theme_folder(&[]); + let fifo = dir.path().join("pipe.json"); + rustix::fs::mknodat(rustix::fs::CWD, &fifo, rustix::fs::FileType::Fifo, rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR, 0) + .expect("fifo"); + assert!(read_text(&fifo).is_err()); + } + + /// A failed atomic replacement leaves both the theme and its previous backup unchanged. + #[cfg(unix)] + #[test] + fn a_failed_theme_save_keeps_the_previous_backup() { + use std::os::unix::fs::PermissionsExt; + let dir = theme_folder(&[("mine.json", "old"), ("mine.json.bak", "older")]); + let path = dir.path().join("mine.json"); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o500)).expect("read-only folder"); + let result = save_theme_text(&path, "new"); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).expect("restore folder"); + assert!(result.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"); + } + + /// 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"); + } + + /// 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() { + let dir = theme_folder(&[("mine.json", "new"), ("mine.json.bak", "older"), ("mine.json.recover", "old")]); + let path = dir.path().join("mine.json"); + for attempted in ["new", "next"] { + let why = save_theme_text(&path, attempted).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(&[]); + let mut first = light(); + first.name = "Cobalt Blue".to_string(); + 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.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.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"); + } + + #[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(&[("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(&[]); + match read_text(dir.path()) { + // 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:?}"), + } + } + + #[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(&[]); + 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"); + } + + #[test] + fn a_theme_file_over_the_limit_is_not_read() { + 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"); + } + + #[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"); + json["metrics"]["body"] = serde_json::json!(1e9); + json["metrics"]["small"] = serde_json::json!(-5.0); + 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"); + 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"); + assert_eq!(theme.notes.len(), 1, "{:?}", theme.notes); + 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"); + assert!(clean.notes.is_empty(), "{:?}", clean.notes); + } + + #[test] + fn a_colour_that_is_not_hexadecimal_is_refused_without_panicking() { + // `#€€` 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"); + } + 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_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(&[("mine.json", &mine)]); + let huge = "x".repeat(MAX_THEME_BYTES as usize + 1); + 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/crates/ui-egui/tests/shortcut_customization.rs b/crates/ui-egui/tests/shortcut_customization.rs index 6d59745900..47aa1e8ba1 100644 --- a/crates/ui-egui/tests/shortcut_customization.rs +++ b/crates/ui-egui/tests/shortcut_customization.rs @@ -36,7 +36,7 @@ fn assigns_a_key_confirms_conflicts_and_restores_saved_preferences() { h.state_mut().run("ui.customizeShortcuts", Value::Null).unwrap(); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search commands").focus(); - h.event(egui::Event::Text("ui.theme".into())); + h.event(egui::Event::Text("Toggle Dark Mode".into())); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::Button, "Add…").click(); h.step(); @@ -66,7 +66,7 @@ fn tab_and_arrow_keys_can_be_captured() { h.state_mut().run("ui.customizeShortcuts", Value::Null).unwrap(); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search commands").focus(); - h.event(egui::Event::Text("ui.theme".into())); + h.event(egui::Event::Text("Toggle Dark Mode".into())); h.run_steps(3); for key in [egui::Key::Tab, egui::Key::ArrowLeft] { h.get_by_role_and_label(egui::accesskit::Role::Button, "Add…").click(); @@ -84,7 +84,7 @@ fn escape_cancels_capture_but_can_be_assigned_explicitly_and_reset() { h.state_mut().run("ui.customizeShortcuts", Value::Null).unwrap(); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search commands").focus(); - h.event(egui::Event::Text("ui.theme".into())); + h.event(egui::Event::Text("Toggle Dark Mode".into())); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::Button, "Add…").focus(); h.run_steps(3); @@ -115,10 +115,15 @@ 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); + // The command-id prefix also matches Choose Theme and Reload Themes; filter the intended row. + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search commands").focus(); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("Toggle Dark Mode".into())); + h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::Button, "Add…").click(); h.step(); h.key_press(egui::Key::T); @@ -136,7 +141,7 @@ fn unreadable_preferences_survive_edits_until_an_explicit_reset() { h.run_steps(3); assert!(h.query_by_label("Saved shortcuts are unreadable or exceed the limit. Changes apply only to this session; Reset All replaces the saved shortcuts.").is_some()); h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search commands").focus(); - h.event(egui::Event::Text("ui.theme".into())); + h.event(egui::Event::Text("Toggle Dark Mode".into())); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::Button, "Add…").click(); h.step(); 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 52ec18cfe0..355dbd046a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -68,6 +68,13 @@ Map operations are commands you can script from the command line, Python or the sandboxed in WebAssembly or as unsandboxed desktop processes. [Command Line](cli.md) · [Python](python.md) · [MCP](mcp.md) · [Plugins](plugins.md) +- **Themed** + + 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) + ## A tour diff --git a/docs/themes.md b/docs/themes.md new file mode 100644 index 0000000000..e7cd0f9ac3 --- /dev/null +++ b/docs/themes.md @@ -0,0 +1,177 @@ +# 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`, which is `~/.config/rustgis` when the variable is unset, +elsewhere. The default Linux themes folder is `~/.config/rustgis/themes`. +`RUSTGIS_CONFIG_DIR` overrides the config folder. + +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 +order is used, and the second is listed in red. + +## Picking one + +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, 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. + +## What the browser build does + +The browser has no config folder, so there is no themes folder there and **Load a Theme from File…** +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. + +On the desktop, to start from a theme you already have, use **Load a Theme from File…**. The app +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, 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 +the token; values of the wrong JSON type give a line and column. A notice says when a file was refused. + +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 +returns with the file. + +## A short theme + +`extends` names a theme that ships, and the file then sets only what it changes: + +```json +{ + "schema": 1, + "name": "Cobalt", + "extends": "Dark", + "colours": { + "accent": "#3B82F6", + "accent_text": "#93C5FD", + "on_accent": "#FFFFFF", + "hover": "#22314D", + "checked": "#1E3A8A" + } +} +``` + +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 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 +{ + "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 + } +} +``` + +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. +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. + +## 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` | Uses Light or Dark, the brightness asked for | +| `ui.scale` with `factor` | Interface scale, held between 80% and 200% | +| `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/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. diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 42a68ca77f..5cf4a33dcb 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -462,6 +462,10 @@ duplication and nudging have their own [layout shortcuts](layouts.md#layouts). - **Language**: **Settings › Language** switches the interface among [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 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 [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 diff --git a/zensical.toml b/zensical.toml index 4027aca256..280a01a42a 100644 --- a/zensical.toml +++ b/zensical.toml @@ -39,6 +39,7 @@ nav = [ { "Python" = "python.md" }, { "MCP Server" = "mcp.md" }, { "Plugins" = "plugins.md" }, + { "Themes" = "themes.md" }, { "30DayMapChallenge" = "https://jgregoriorincon.github.io/30DayMapChallenge-2026/" }, { "Languages" = "i18n.md" }, { "Architecture" = "architecture.md" },