misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Themes: Base16 and pywal colour schemes imported as themes (part of #45) (#294)
Ahmed Nefzaoui40f25878a96e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d696d692..92de8be4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -61,8 +61,18 @@ choose. And Linux, checked on a real desktop with every change.set, and a theme can be a folder that brings its own icons. An icon set can mix PNG pictureswith SVG drawings, and one-colour icons (`-symbolic.svg`, `-symbolic.png`, drawn in thetheme's text colour) with coloured ones, and hold pictures at 32 and 48 pixels, used on a- screen scaled to 150 % and more: the style themes' pictures stay sharp there. Base16 and pywal- schemes come next.+ screen scaled to 150 % and more: the style themes' pictures stay sharp there.+ - **Base16 and pywal colour schemes as themes**: a Base16 or Base24 scheme (`.yaml`, the+ classic layout and tinted-theming's `palette:` one) or pywal's `colors.json` (wallust's+ pywal-shaped one too), added with **View → Theme → Add a theme file…** or put in the themes+ folder, is a theme on the classic look: only the colours change. base00 and base01 are the+ backgrounds, base05 and base04 the text, base0D the focus, the selection and the progress bar+ (pywal: its background and foreground, color4); text is kept at 4.5:1 or more against every+ background and the accent at 3:1, moved a little where a scheme falls short. Once `wal` has+ run, **View → Theme** lists **pywal**, read from where pywal writes it+ (`~/.cache/wal/colors.json`, `%USERPROFILE%\.cache\wal\colors.json` on Windows), and MDM+ follows each new wallpaper's colours within two seconds. A theme file can `inherits` a scheme+ to change more than its colours.- **View → Interface size** ([#262](https://github.com/anefzaoui/misterdownloadmanager/issues/262)):every window larger, 100 % to 200 %, on top of the system's display scale; **Ctrl +**,**Ctrl −** and **Ctrl 0** in any MDM window, as in a browser. Every open window follows at oncediff --git a/ROADMAP.md b/ROADMAP.mdindex 9e9f0b46..9f7d961b 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -197,6 +197,9 @@ Everything below ships together, in the next release.glossy buttons, their check boxes and progress bars, their title bars on Windows, icons drawnfor MDM); Metro, Adwaita and Breeze get MDM's own icons where theirs had none([#45](https://github.com/anefzaoui/misterdownloadmanager/issues/45))+- ✅ Themes: Base16 and pywal colour schemes imported as themes (View → Theme → Add a theme+ file…, or the themes folder); **pywal** follows `wal` as it writes new colours, text kept+ readable (4.5:1) ([#45](https://github.com/anefzaoui/misterdownloadmanager/issues/45))- ✅ Dark mode: grey notes and error texts readable (4.5:1), Options' failed checks no longer darkred on the dark dialog ([#45](https://github.com/anefzaoui/misterdownloadmanager/issues/45))- ✅ A minimized MDM keeps working: queues, the Scheduler, download limits, the kill switch and@@ -387,8 +390,8 @@ Everything below ships together, in the next release.Classic, Native (follows the system's accent and contrast on Windows, Linux and macOS) and Highcontrast; style themes with their own control shapes, a drawn title bar on Windows and their ownicons: Metro, Adwaita, Breeze, Luna, Aero and Aqua; and theme files anyone can make, try and- share, in TOML or JSON, built on any theme (`inherits`), with their own icons- ([the guide](docs/themes.md))+ share, in TOML or JSON, built on any theme (`inherits`), with their own icons; Base16 and+ pywal colour schemes read as themes ([the guide](docs/themes.md))- ✅ Linux, no longer experimental: every change is checked on Ubuntu (GNOME) as well as Windows,and on KDE Plasma, Cinnamon and Xfce; Wayland sessions (through XWayland, menus under theirtitles on sway too); the .deb and .rpm installed in clean Ubuntu, Debian and Fedora systems, the@@ -402,8 +405,6 @@ Everything below ships together, in the next release.### Being built-- 🔄 Themes: Base16 and pywal colour schemes imported as themes- ([#45](https://github.com/anefzaoui/misterdownloadmanager/issues/45))- 🔄 Linux, what's left ([#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164)):screen readers (Orca) reading MDM's windows; browsers installed as a Flatpak (Firefox fromFlathub may reach MDM through the desktop, as the Snap does: to check); native Wayland windowsdiff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex e16b60dc..a5e1b5ed 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -108,6 +108,9 @@ enum Cmd {Theme(&'static str),/// View → Theme → Open themes folder.OpenThemesFolder,+ /// View → Theme → Add a theme file: a theme or a Base16 or pywal colour scheme, copied+ /// into the themes folder and picked.+ AddThemeFile,/// View → Draw with → OpenGL / Direct3D, Vulkan or Metal (#89, #206), from the next start.#[cfg(gpu)]DrawWith(crate::renderer::Api),@@ -543,6 +546,8 @@ pub struct App {/// View → Theme's choices (#45), and when the themes folder last changed (read again then).theme_list: Vec<crate::themefile::Entry>,themes_changed: Option<std::time::SystemTime>,+ /// pywal's colours were there at the last check (View → Theme → pywal listed then).+ pywal_there: bool,/// When `logic`'s every-2-seconds work last ran (crash state, torrents, #174).ticked: Option<Instant>,/// The main window's caption matches the mode.@@ -1011,6 +1016,7 @@ impl App {fitted: false,theme_list: crate::themefile::list(),themes_changed: crate::themefile::changed(),+ pywal_there: crate::themefile::pywal_file().is_some_and(|p| p.is_file()),ticked: None,caption_set: false,// The system's title bar is the frame's own: nothing to apply for it.@@ -1921,6 +1927,11 @@ impl App {p.show_tab(tab);}}+ // View → Theme → Add a theme file, as its dialog answers (#45):+ // `theme-add:<path>` (tests of a scheme's import without the system's dialog).+ "theme-add" => {+ self.add_theme_file(std::path::Path::new(tab), ctx);+ }// View → Theme → a theme, as the menu picks it (#45): `theme:native` (tests of the// live switch without a click)."theme" => {@@ -4765,6 +4776,28 @@ impl App {crate::launch::open(dir);}}+ Cmd::AddThemeFile => {+ // i18n: title of the file dialog of View → Theme → Add a theme file+ let title = crate::i18n::t("Add a theme file").to_owned();+ // i18n: the kind of file View → Theme → Add a theme file lists: MDM's themes (TOML, JSON), Base16 schemes (YAML) and pywal's colors.json+ let kinds = crate::i18n::t("Themes and colour schemes").to_owned();+ let all = crate::i18n::t("All files").to_owned();+ // Where pywal writes its colours, when it has: the first place to look.+ let start = crate::themefile::pywal_file()+ .filter(|p| p.is_file())+ .and_then(|p| p.parent().map(std::path::Path::to_path_buf));+ winui::start_pick(&self.ui_ctx, "app-theme-file", move || {+ let dialog = rfd::FileDialog::new().set_title(title);+ let dialog = match start {+ Some(dir) => dialog.set_directory(dir),+ None => dialog,+ };+ dialog+ .add_filter(kinds, &["toml", "json", "yaml", "yml"])+ .add_filter(all, &["*"])+ .pick_file()+ });+ }// Every window at once (the frames after this one); saved by `follow_zoom`.Cmd::InterfaceSize(percent) => crate::scale::set(ctx, percent),#[cfg(gpu)]@@ -5454,16 +5487,25 @@ impl App {items.push(Radio("Aero", Cmd::Theme("aero"), true, on("aero")));// i18n: View → Theme: a style theme's name (Mac OS X's look), a name: keep "Aqua" as writtenitems.push(Radio("Aqua", Cmd::Theme("aqua"), true, on("aqua")));+ let wal = crate::themefile::PYWAL;for e in self.theme_list.iter().filter(|e| e.path.is_some()) {if !files {items.push(Sep);files = true;}+ // pywal's colours, where `wal` writes them, followed as it writes them again.+ if e.id == wal && e.name == wal {+ // i18n: View → Theme: the colours of pywal (a program making colour schemes from the wallpaper), followed as they change; a name: keep "pywal" as written+ items.push(Radio("pywal", Cmd::Theme(wal), true, chosen == wal));+ continue;+ }// A file's theme by its own name, untranslated.let (id, name) = (crate::chrome::label(&e.id), crate::chrome::label(&e.name));items.push(Radio(name, Cmd::Theme(id), true, e.id == chosen));}items.push(Sep);+ // i18n: View → Theme: picks a theme file or a Base16 or pywal colour scheme, copies it into the themes folder and uses it+ items.push(I("Add a theme file…", Cmd::AddThemeFile, true, false));// i18n: View → Theme: opens the folder where theme files go (TOML or JSON)items.push(I("Open themes folder", Cmd::OpenThemesFolder, true, false));// i18n: View menu: submenu choosing MDM's look (colours, sizes, icons): Classic, Native…@@ -7036,6 +7078,9 @@ impl App {if let Some(path) = winui::picked(ctx, "app-import") {self.import_file(&path);}+ if let Some(path) = winui::picked(ctx, "app-theme-file") {+ self.add_theme_file(&path, ctx);+ }if let Some(target) = winui::picked(ctx, "app-move-rename")&& let Some(id) = self.move_rename_for.take(){@@ -7043,6 +7088,30 @@ impl App {}}+ /// View → Theme → Add a theme file, answered: the file copied into the themes folder and+ /// picked, as clicking it in View → Theme does; a file that isn't a theme says why.+ fn add_theme_file(&mut self, path: &std::path::Path, ctx: &egui::Context) {+ match crate::themefile::add(path) {+ Ok(id) => {+ self.themes_changed = crate::themefile::changed();+ self.theme_list = crate::themefile::list();+ self.run(Cmd::Theme(crate::chrome::label(&id)), None, ctx);+ }+ Err(e) => {+ tracing::warn!("add a theme file: {e}");+ self.notice = Some((+ // i18n: title of the message when View → Theme → Add a theme file fails+ crate::i18n::mark("Add a theme file"),+ crate::i18n::fmt(+ // i18n: {error} is why, in English (a file that isn't a theme or a colour scheme, a colour missing)+ crate::i18n::t("This file can't be used as a theme: {error}"),+ &[("error", &e)],+ ),+ ));+ }+ }+ }+/// The addresses in a list file, shown in Import to tick before adding.fn import_file(&mut self, path: &std::path::Path) {let file = path@@ -8187,10 +8256,13 @@ impl App {.is_none_or(|t| t.elapsed() > Duration::from_secs(2)){self.theme_checked = Some(Instant::now());- // A theme file added, removed or renamed: View → Theme lists it.+ // A theme file added, removed or renamed, pywal's colours written or taken away:+ // View → Theme lists it.let changed = crate::themefile::changed();- if changed != self.themes_changed {+ let wal = crate::themefile::pywal_file().is_some_and(|p| p.is_file());+ if changed != self.themes_changed || wal != self.pywal_there {self.themes_changed = changed;+ self.pywal_there = wal;self.theme_list = crate::themefile::list();}let changed = crate::theme::update(@@ -8198,8 +8270,9 @@ impl App {self.settings.always_dark,&ctx,);- // Native follows the system's accent and contrast as they change.- let changed = if crate::theme::follow_system(&ctx) {+ // Native follows the system's accent and contrast as they change, a theme made from+ // pywal's colours the colours `wal` writes for each new wallpaper.+ let changed = if crate::theme::follow_system(&ctx) || crate::theme::follow_pywal() {crate::theme::apply_theme(&ctx);true} else {diff --git a/crates/app/src/main.rs b/crates/app/src/main.rsindex 5186a2b5..cbe9df53 100644--- a/crates/app/src/main.rs+++ b/crates/app/src/main.rs@@ -45,6 +45,7 @@ mod rss;mod rssdlg;mod scale;mod scheduler;+mod schemes;mod scrollbar;mod secrets;mod selection;diff --git a/crates/app/src/schemes.rs b/crates/app/src/schemes.rsnew file mode 100644index 00000000..26052a84--- /dev/null+++ b/crates/app/src/schemes.rs@@ -0,0 +1,685 @@+//! Colour schemes from other programs, read as themes (#45): a Base16 scheme (YAML, the classic+//! layout with `scheme:` and `base00`…`base0F` at the top, or tinted-theming's newer one with+//! `name:` and a `palette:` block; Base24's extra colours are passed over) and pywal's+//! `colors.json` (`special` and `color0`…`color15`; wallust's pywal-shaped file too).+//!+//! A scheme becomes the same value tree a theme file is read into: the classic look+//! `inherits`ed, a few `[seeds]` MDM spreads over every control (`crate::derive`), and the+//! secondary text's colour. Only colours change, never the layout. The text is checked against+//! every background it sits on (WCAG 2.1 AA, 4.5:1) and moved in lightness when a scheme falls+//! short, the accent the same at 3:1; each change is a warning, written to the log.++use egui::Color32;+use serde_json::{Map, Value};++use crate::derive::{contrast, mix, readable};+use crate::palette::to_hex;++/// Body text against what it sits on (WCAG 2.1, 1.4.3).+const TEXT_RATIO: f32 = 4.5;+/// The accent (focus lines, check boxes, the progress bar) against its background (1.4.11).+const ACCENT_RATIO: f32 = 3.0;++/// A scheme's colour: `#rgb` or `#rrggbb`, the `#` optional (Base16 writes none).+pub fn hex(s: &str) -> Option<Color32> {+ let h = s.trim().trim_start_matches('#');+ if !h.bytes().all(|b| b.is_ascii_hexdigit()) {+ return None;+ }+ let digit = |i: usize| u8::from_str_radix(&h[i..i + 1], 16).ok();+ let byte = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).ok();+ match h.len() {+ 3 => Some(Color32::from_rgb(+ digit(0)? * 17,+ digit(1)? * 17,+ digit(2)? * 17,+ )),+ 6 => Some(Color32::from_rgb(byte(0)?, byte(2)?, byte(4)?)),+ _ => None,+ }+}++/// The colours a scheme gives MDM, before its contrast is checked.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Mapped {+ /// Windows, dialogs and the toolbar's band.+ pub background: Color32,+ /// The download list, text boxes and menus.+ pub surface: Color32,+ /// The menu bar and column headers.+ pub header: Color32,+ pub text: Color32,+ /// Secondary text: notes, sizes, versions.+ pub muted: Color32,+ /// Focus lines, default buttons, check boxes, links, the progress bar and the selection.+ pub accent: Color32,+ pub error: Color32,+ pub warning: Color32,+ /// Success messages, the torrent pieces and the meters.+ pub success: Color32,+}++impl Mapped {+ /// Text readable on every background it sits on (4.5:1) and the accent seen on them (3:1):+ /// a colour that falls short is moved in lightness, away from them, until it passes. Says+ /// what it changed.+ pub fn fix_contrast(&mut self) -> Vec<String> {+ let grounds = [self.background, self.surface, self.header];+ let mut changed = Vec::new();+ for (what, c, ratio) in [+ ("text", &mut self.text, TEXT_RATIO),+ ("text.muted", &mut self.muted, TEXT_RATIO),+ ("accent", &mut self.accent, ACCENT_RATIO),+ ] {+ let was = *c;+ *c = readable_on(was, &grounds, ratio);+ if *c != was {+ changed.push(format!(+ "contrast: {what} {} made {} to read at {ratio}:1",+ to_hex(was),+ to_hex(*c)+ ));+ }+ }+ changed+ }++ /// The theme-file value tree of this scheme: the classic look, seeded with its colours.+ pub fn theme_value(&self, name: &str) -> Value {+ let mut seeds = Map::new();+ for (key, c) in [+ ("background", self.background),+ ("surface", self.surface),+ ("header", self.header),+ ("text", self.text),+ ("accent", self.accent),+ ("selection", self.accent),+ ("error", self.error),+ ("warning", self.warning),+ ("success", self.success),+ ] {+ seeds.insert(key.into(), Value::String(to_hex(c)));+ }+ let mut colors = Map::new();+ colors.insert("text.muted".into(), Value::String(to_hex(self.muted)));+ let mut top = Map::new();+ top.insert("name".into(), Value::String(name.to_owned()));+ top.insert("inherits".into(), Value::String("classic".into()));+ top.insert("seeds".into(), Value::Object(seeds));+ top.insert("colors".into(), Value::Object(colors));+ Value::Object(top)+ }+}++/// `fg` moved until it has `ratio` against each of `grounds` (they are close: a scheme's+/// backgrounds), or as near as lightness allows.+fn readable_on(fg: Color32, grounds: &[Color32], ratio: f32) -> Color32 {+ let mut c = fg;+ for _ in 0..4 {+ if grounds.iter().all(|g| contrast(c, *g) >= ratio) {+ break;+ }+ for g in grounds {+ c = readable(c, *g, ratio);+ }+ }+ c+}++// ---- Base16 ------------------------------------------------------------------------------------++/// A Base16 scheme: its name and its 16 colours, base00 (the background) to base0F.+#[derive(Clone, Debug, PartialEq)]+pub struct Base16 {+ pub name: Option<String>,+ pub base: [Option<Color32>; 16],+}++/// The colours MDM reads; a scheme without one of them isn't read.+const BASE16_USED: [usize; 8] = [0x0, 0x1, 0x4, 0x5, 0x8, 0xA, 0xB, 0xD];++/// A Base16 (or Base24) scheme file. Its YAML is flat `key: "value"` lines, `palette:`'s+/// indented under it in the newer layout, so it is read here, without a YAML library.+pub fn base16(text: &str) -> Result<Base16, String> {+ let mut name = None;+ let mut base = [None; 16];+ let mut in_palette = false;+ let mut found = false;+ for (n, raw) in text.trim_start_matches('\u{feff}').lines().enumerate() {+ let line = raw.trim_end();+ let body = line.trim_start();+ if body.is_empty() || body.starts_with('#') || body == "---" || body == "..." {+ continue;+ }+ let indented = body.len() != line.len();+ if indented && !in_palette {+ // Something else's nested lines (a newer field MDM doesn't use, a folded text).+ continue;+ }+ let Some((key, value)) = body.split_once(':') else {+ return Err(format!("line {}: not a key: value line", n + 1));+ };+ let key = unquote(key.trim()).to_ascii_lowercase();+ let value = yaml_scalar(value).map_err(|e| format!("line {}: {e}", n + 1))?;+ if !indented {+ in_palette = key == "palette" && value.is_empty();+ }+ if let Some(i) = key+ .strip_prefix("base")+ .filter(|d| d.len() == 2)+ .and_then(|d| usize::from_str_radix(d, 16).ok())+ {+ found = true;+ // Base24's base10 to base17 are passed over.+ if i < 16 {+ let c = hex(&value)+ .ok_or_else(|| format!("line {}: {key}: {value} is not a colour", n + 1))?;+ base[i] = Some(c);+ }+ continue;+ }+ if !indented && (key == "name" || key == "scheme") && !value.is_empty() {+ // The newer layout's `name` wins over a `scheme` left in for older builders.+ if key == "name" || name.is_none() {+ name = Some(value);+ }+ }+ }+ if !found {+ return Err("not a Base16 scheme: no base00 to base0F".into());+ }+ let missing: Vec<String> = BASE16_USED+ .iter()+ .filter(|&&i| base[i].is_none())+ .map(|i| format!("base{i:02X}"))+ .collect();+ if !missing.is_empty() {+ return Err(format!("the scheme lacks {}", missing.join(", ")));+ }+ Ok(Base16 { name, base })+}++/// A YAML value on a `key:` line: quoted (`"…"` or `'…'`, a comment after it) or plain (cut at+/// ` #`). A plain `#rrggbb` is read as the colour it means, though YAML would see a comment.+fn yaml_scalar(v: &str) -> Result<String, String> {+ let v = v.trim();+ if let Some(q) = v.chars().next().filter(|c| *c == '"' || *c == '\'') {+ let rest = &v[1..];+ let end = rest.find(q).ok_or("a quote isn't closed")?;+ let after = rest[end + 1..].trim();+ if !after.is_empty() && !after.starts_with('#') {+ return Err("text after a quoted value".into());+ }+ return Ok(rest[..end].to_owned());+ }+ if v.starts_with('#') {+ return Ok(v.split_whitespace().next().unwrap_or("").to_owned());+ }+ let plain = v.split(" #").next().unwrap_or("").trim();+ Ok(plain.to_owned())+}++fn unquote(s: &str) -> &str {+ s.trim_matches(|c| c == '"' || c == '\'')+}++/// Base16's colours in MDM (Stylix's guide to them: base00 the default background, base01 the+/// lighter one, base04 and base05 the foregrounds, base0D the focus colour). The list and boxes+/// take base00, as an editor's text does, and the window around them base01, as in the classic+/// look (white boxes on grey, darker ones on dark grey).+pub fn map_base16(s: &Base16) -> Mapped {+ let c = |i: usize| s.base[i].unwrap_or(Color32::BLACK);+ Mapped {+ background: c(0x1),+ surface: c(0x0),+ header: c(0x1),+ text: c(0x5),+ muted: c(0x4),+ accent: c(0xD),+ error: c(0x8),+ warning: c(0xA),+ success: c(0xB),+ }+}++// ---- pywal ------------------------------------------------------------------------------------++/// A pywal `colors.json`: `special` (background, foreground) and `colors` (color0 to color15).+pub fn is_pywal(v: &Value) -> bool {+ v.get("special").is_some_and(Value::is_object)+ || v.get("colors").and_then(|c| c.get("color0")).is_some()+}++/// The colours MDM reads from pywal's file, read; a file without one of them isn't read.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Pywal {+ pub background: Color32,+ pub foreground: Color32,+ /// color0 to color15: black, red, green, yellow, blue, magenta, cyan, white, then bright.+ pub colors: [Option<Color32>; 16],+}++pub fn pywal(v: &Value) -> Result<Pywal, String> {+ let mut missing = Vec::new();+ let mut get = |table: &str, key: &str| -> Result<Option<Color32>, String> {+ match v.get(table).and_then(|t| t.get(key)) {+ None => {+ missing.push(format!("{table}.{key}"));+ Ok(None)+ }+ Some(c) => c+ .as_str()+ .and_then(hex)+ .map(Some)+ .ok_or_else(|| format!("{table}.{key}: {c} is not a colour")),+ }+ };+ let background = get("special", "background")?;+ let foreground = get("special", "foreground")?;+ let mut colors = [None; 16];+ for (i, c) in colors.iter_mut().enumerate() {+ *c = match v.get("colors").and_then(|t| t.get(format!("color{i}"))) {+ None => None,+ Some(_) => get("colors", &format!("color{i}"))?,+ };+ }+ for i in [1, 2, 3, 4] {+ if colors[i].is_none() {+ missing.push(format!("colors.color{i}"));+ }+ }+ if !missing.is_empty() {+ return Err(format!("pywal's colours lack {}", missing.join(", ")));+ }+ Ok(Pywal {+ background: background.unwrap_or(Color32::BLACK),+ foreground: foreground.unwrap_or(Color32::WHITE),+ colors,+ })+}++/// pywal's colours in MDM: its background for the list and boxes, a step toward its foreground+/// for the window (pywal has no second background), color4 (blue) for the accent, color1, 3+/// and 2 for errors, warnings and success, color8 (bright black) for secondary text.+pub fn map_pywal(p: &Pywal) -> Mapped {+ let c = |i: usize| p.colors[i].unwrap_or(p.foreground);+ let background = mix(p.background, p.foreground, 0.06);+ Mapped {+ background,+ surface: p.background,+ header: background,+ text: p.foreground,+ muted: p.colors[8].unwrap_or_else(|| mix(p.foreground, p.background, 0.35)),+ accent: c(4),+ error: c(1),+ warning: c(3),+ success: c(2),+ }+}++/// The name a pywal file's theme takes: `pywal`, with its wallpaper's file name when it says.+pub fn pywal_name(v: &Value) -> String {+ let wall = v+ .get("wallpaper")+ .and_then(Value::as_str)+ .and_then(|w| w.rsplit(['/', '\\']).next())+ .filter(|w| !w.is_empty() && *w != "None");+ match wall {+ Some(w) => format!("pywal: {w}"),+ None => "pywal".into(),+ }+}++// ---- a scheme as a theme ----------------------------------------------------------------------++/// A Base16 YAML file's text as a theme's value tree (named after the scheme, else `stem`),+/// with what its contrast check changed.+pub fn base16_theme(text: &str, stem: &str) -> Result<(Value, Vec<String>), String> {+ let s = base16(text)?;+ let mut m = map_base16(&s);+ let warnings = m.fix_contrast();+ let name = s.name.unwrap_or_else(|| stem.to_owned());+ Ok((m.theme_value(&name), warnings))+}++/// A pywal `colors.json`'s value as a theme's value tree, with what its contrast check changed.+pub fn pywal_theme(v: &Value) -> Result<(Value, Vec<String>), String> {+ let p = pywal(v)?;+ let mut m = map_pywal(&p);+ let warnings = m.fix_contrast();+ Ok((m.theme_value(&pywal_name(v)), warnings))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rgb(h: u32) -> Color32 {+ Color32::from_rgb((h >> 16) as u8, (h >> 8) as u8, h as u8)+ }++ /// A dark scheme in the classic layout (Gruvbox-like, colours of our own picking).+ const DARK_CLASSIC: &str = r##"+scheme: "Test Dark Classic"+author: "MDM's tests"+base00: "282828" # ----+base01: "3c3836" # ---+base02: "504945"+base03: '665c54'+base04: bdae93+base05: "d5c4a1"+base06: "ebdbb2"+base07: "fbf1c7"+base08: "fb4934"+base09: "fe8019"+base0A: "fabd2f"+base0B: "b8bb26"+base0C: "8ec07c"+base0D: "83a598"+base0E: "d3869b"+base0F: "d65d0e"+"##;++ /// A light scheme in tinted-theming's layout (Solarized-like), with Base24's extras.+ const LIGHT_PALETTE: &str = r##"system: "base24"+name: "Test Light"+slug: "test-light"+scheme: "Old name"+author: "MDM's tests (https://example.org/tests)"+description: >+ A folded text over two lines,+ which MDM passes over.+variant: "light"+palette:+ base00: "#fdf6e3"+ base01: "#eee8d5"+ base02: "#93a1a1"+ base03: "#839496"+ base04: "#657b83"+ base05: "#586e75"+ base06: "#073642"+ base07: "#002b36"+ base08: "#dc322f"+ base09: "#cb4b16"+ base0A: "#b58900"+ base0B: "#859900"+ base0C: "#2aa198"+ base0D: "#268bd2"+ base0E: "#6c71c4"+ base0F: "#d33682"+ base10: "#ffffff"+ base17: "#000000"+"##;++ /// A file as an editor on Windows may save it: a byte-order mark, CR LF line ends.+ fn windows_file(text: &str) -> String {+ format!("\u{feff}{}", text.replace('\n', "\r\n"))+ }++ #[test]+ fn hex_reads_three_and_six_digits() {+ assert_eq!(hex("#0078d4"), Some(rgb(0x0078d4)));+ assert_eq!(hex("0078D4"), Some(rgb(0x0078d4)));+ assert_eq!(hex("#abc"), Some(rgb(0xaabbcc)));+ assert_eq!(hex("fff"), Some(Color32::WHITE));+ for bad in [+ "",+ "#",+ "#12",+ "#1234",+ "#12345",+ "#0078d4ff",+ "#ggg",+ "red",+ "#00 78d",+ ] {+ assert_eq!(hex(bad), None, "{bad}");+ }+ }++ #[test]+ fn base16_classic_layout() {+ let s = base16(DARK_CLASSIC).unwrap();+ assert_eq!(s.name.as_deref(), Some("Test Dark Classic"));+ assert_eq!(s.base[0x0], Some(rgb(0x282828)));+ assert_eq!(s.base[0x3], Some(rgb(0x665c54)));+ assert_eq!(s.base[0x4], Some(rgb(0xbdae93)));+ assert_eq!(s.base[0xD], Some(rgb(0x83a598)));+ assert_eq!(s.base[0xF], Some(rgb(0xd65d0e)));+ }++ #[test]+ fn base16_palette_layout_with_base24_extras() {+ let s = base16(&windows_file(LIGHT_PALETTE)).unwrap();+ assert_eq!(s.name.as_deref(), Some("Test Light"));+ assert_eq!(s.base[0x0], Some(rgb(0xfdf6e3)));+ assert_eq!(s.base[0xD], Some(rgb(0x268bd2)));+ assert!(s.base.iter().all(Option::is_some));+ }++ #[test]+ fn base16_palette_keys_outside_palette_are_passed_over() {+ let text = format!("{DARK_CLASSIC}\nextra:\n base00: \"#ffffff\"\n");+ assert_eq!(base16(&text).unwrap().base[0], Some(rgb(0x282828)));+ }++ #[test]+ fn base16_plain_hash_values_and_three_digits() {+ let text = DARK_CLASSIC+ .replace("\"282828\" # ----", "#222 # a comment")+ .replace("\"d5c4a1\"", "#ddd");+ let s = base16(&text).unwrap();+ assert_eq!(s.base[0], Some(rgb(0x222222)));+ assert_eq!(s.base[5], Some(rgb(0xdddddd)));+ }++ #[test]+ fn base16_malformed_and_missing() {+ // Not a scheme at all.+ assert!(base16("name: \"x\"\nauthor: \"y\"\n").is_err());+ assert!(base16("").is_err());+ // A line that isn't key: value, a quote left open, text after a quoted value.+ assert!(base16(&format!("{DARK_CLASSIC}\nwhat is this\n")).is_err());+ assert!(base16(&DARK_CLASSIC.replace("\"fb4934\"", "\"fb4934")).is_err());+ assert!(base16(&DARK_CLASSIC.replace("\"fb4934\"", "\"fb4934\" x")).is_err());+ // A colour that isn't one.+ let e = base16(&DARK_CLASSIC.replace("\"83a598\"", "\"83a5\"")).unwrap_err();+ assert!(e.contains("base0d"), "{e}");+ // Colours MDM needs, missing: named.+ let lacking: String = DARK_CLASSIC+ .lines()+ .filter(|l| !l.starts_with("base0D") && !l.starts_with("base05"))+ .collect::<Vec<_>>()+ .join("\n");+ let e = base16(&lacking).unwrap_err();+ assert!(e.contains("base05") && e.contains("base0D"), "{e}");+ // One MDM doesn't use, missing: still read.+ let no_0e: String = DARK_CLASSIC+ .lines()+ .filter(|l| !l.starts_with("base0E"))+ .collect::<Vec<_>>()+ .join("\n");+ assert_eq!(base16(&no_0e).unwrap().base[0xE], None);+ }++ #[test]+ fn base16_maps_backgrounds_text_and_accents() {+ let m = map_base16(&base16(DARK_CLASSIC).unwrap());+ assert_eq!(m.surface, rgb(0x282828));+ assert_eq!(m.background, rgb(0x3c3836));+ assert_eq!(m.header, rgb(0x3c3836));+ assert_eq!(m.text, rgb(0xd5c4a1));+ assert_eq!(m.muted, rgb(0xbdae93));+ assert_eq!(m.accent, rgb(0x83a598));+ assert_eq!(m.error, rgb(0xfb4934));+ assert_eq!(m.warning, rgb(0xfabd2f));+ assert_eq!(m.success, rgb(0xb8bb26));+ }++ const PYWAL: &str = r##"{+ "wallpaper": "/home/someone/Pictures/lake.jpg",+ "alpha": "100",+ "special": { "background": "#1b1d24", "foreground": "#c8ccd4", "cursor": "#c8ccd4" },+ "colors": {+ "color0": "#1b1d24", "color1": "#b7605e", "color2": "#7fa173", "color3": "#c9a95c",+ "color4": "#5f87b5", "color5": "#9d7bb0", "color6": "#5fa3a8", "color7": "#c8ccd4",+ "color8": "#5c6370", "color9": "#b7605e", "color10": "#7fa173", "color11": "#c9a95c",+ "color12": "#5f87b5", "color13": "#9d7bb0", "color14": "#5fa3a8", "color15": "#fff"+ }+ }"##;++ #[test]+ fn pywal_reads_and_maps() {+ let v: Value = serde_json::from_str(PYWAL).unwrap();+ assert!(is_pywal(&v));+ let p = pywal(&v).unwrap();+ assert_eq!(p.background, rgb(0x1b1d24));+ assert_eq!(p.colors[15], Some(Color32::WHITE));+ let m = map_pywal(&p);+ assert_eq!(m.surface, rgb(0x1b1d24));+ assert_eq!(m.text, rgb(0xc8ccd4));+ assert_eq!(m.accent, rgb(0x5f87b5));+ assert_eq!(+ (m.error, m.warning, m.success),+ (rgb(0xb7605e), rgb(0xc9a95c), rgb(0x7fa173))+ );+ assert_eq!(m.muted, rgb(0x5c6370));+ // The window a step toward the text: lighter on a dark scheme.+ assert!(crate::derive::luminance(m.background) > crate::derive::luminance(m.surface));+ assert_eq!(pywal_name(&v), "pywal: lake.jpg");+ }++ #[test]+ fn pywal_malformed_and_missing() {+ let v: Value = serde_json::from_str(r#"{ "name": "An MDM theme" }"#).unwrap();+ assert!(!is_pywal(&v));+ // MDM's own JSON theme files use `colors` too, for roles: not pywal's.+ let v: Value = serde_json::from_str(r##"{ "colors": { "accent": "#ff0000" } }"##).unwrap();+ assert!(!is_pywal(&v));+ let v: Value = serde_json::from_str(r##"{ "special": {}, "colors": {} }"##).unwrap();+ let e = pywal(&v).unwrap_err();+ assert!(+ e.contains("special.background") && e.contains("colors.color4"),+ "{e}"+ );+ let bad = PYWAL.replace("\"#5f87b5\", \"color5\"", "\"blue\", \"color5\"");+ let v: Value = serde_json::from_str(&bad).unwrap();+ assert!(pywal(&v).unwrap_err().contains("color4"));+ // color8 missing: secondary text mixed from the text instead.+ let v: Value =+ serde_json::from_str(&PYWAL.replace("\"color8\": \"#5c6370\",", "")).unwrap();+ assert!(map_pywal(&pywal(&v).unwrap()).muted != rgb(0x5c6370));+ let v: Value = serde_json::from_str(r#"{ "wallpaper": "None" }"#).unwrap();+ assert_eq!(pywal_name(&v), "pywal");+ }++ #[test]+ fn readable_schemes_are_left_as_they_are() {+ let mut m = map_base16(&base16(DARK_CLASSIC).unwrap());+ let before = m;+ assert!(m.fix_contrast().is_empty());+ assert_eq!(m, before);+ }++ #[test]+ fn a_scheme_short_of_aa_is_made_readable() {+ // Solarized-like light's text (base05) on its base01 is just under 4.5:1.+ let mut m = map_base16(&base16(LIGHT_PALETTE).unwrap());+ let before = m;+ assert!(contrast(before.text, before.background) < TEXT_RATIO);+ let changed = m.fix_contrast();+ assert!(+ changed.iter().any(|c| c.starts_with("contrast: text ")),+ "{changed:?}"+ );+ for g in [m.background, m.surface, m.header] {+ assert!(contrast(m.text, g) >= TEXT_RATIO);+ assert!(contrast(m.muted, g) >= TEXT_RATIO);+ assert!(contrast(m.accent, g) >= ACCENT_RATIO);+ }+ // Darker, and only a little: still the scheme's colour.+ assert!(crate::derive::luminance(m.text) < crate::derive::luminance(before.text));+ assert!(contrast(m.text, before.text) < 1.5);+ assert_eq!(+ (m.background, m.surface, m.error),+ (before.background, before.surface, before.error)+ );+ }++ #[test]+ fn contrast_fix_ups_reach_aa_on_every_background() {+ // A dark scheme whose text and accent are too dim, and a light one too pale.+ for (bg, surface, text, accent) in [+ (0x303030, 0x262626, 0x5a5a5a, 0x3a3a50),+ (0xf4f4f4, 0xffffff, 0xc0c0c0, 0xd0e0ff),+ ] {+ let mut m = Mapped {+ background: rgb(bg),+ surface: rgb(surface),+ header: rgb(bg),+ text: rgb(text),+ muted: rgb(text),+ accent: rgb(accent),+ error: rgb(0xff0000),+ warning: rgb(0xffff00),+ success: rgb(0x00ff00),+ };+ let changed = m.fix_contrast();+ assert_eq!(changed.len(), 3, "{changed:?}");+ for g in [m.background, m.surface, m.header] {+ assert!(contrast(m.text, g) >= TEXT_RATIO);+ assert!(contrast(m.muted, g) >= TEXT_RATIO);+ assert!(contrast(m.accent, g) >= ACCENT_RATIO);+ }+ // Backgrounds are never changed.+ assert_eq!((m.background, m.surface), (rgb(bg), rgb(surface)));+ }+ }++ #[test]+ fn a_scheme_is_a_theme_on_the_classic_look() {+ let (v, _) = base16_theme(DARK_CLASSIC, "file-name").unwrap();+ let l = crate::themefile::parse("gruv", &v, |_| {+ Ok(crate::themefile::Loaded {+ theme: crate::palette::CLASSIC.clone(),+ warnings: Vec::new(),+ })+ })+ .unwrap();+ assert!(l.warnings.is_empty(), "{:?}", l.warnings);+ let t = l.theme;+ assert_eq!(t.name, "Test Dark Classic");+ // Both sides take the scheme; the layout and sizes stay the classic look's.+ assert_eq!(t.light, t.dark);+ assert_eq!(t.metrics, crate::palette::CLASSIC.metrics);+ assert_eq!(t.controls, crate::palette::CLASSIC.controls);+ let p = &t.dark;+ assert!(p.dark);+ assert_eq!(p.window, rgb(0x3c3836));+ assert_eq!(p.field, rgb(0x282828));+ assert_eq!(p.list, rgb(0x282828));+ assert_eq!(p.text, rgb(0xd5c4a1));+ assert_eq!(p.accent, rgb(0x83a598));+ assert_eq!(p.selection, rgb(0x83a598));+ assert_eq!(p.progress_bar, rgb(0x83a598));+ assert!(contrast(p.selection_text, p.selection) >= TEXT_RATIO);+ assert!(contrast(p.muted, p.window) >= TEXT_RATIO);+ // A light scheme is a light theme; a nameless one is named after its file.+ let nameless: String = LIGHT_PALETTE+ .lines()+ .filter(|l| !l.starts_with("name") && !l.starts_with("scheme"))+ .collect::<Vec<_>>()+ .join("\n");+ let (v, _) = base16_theme(&nameless, "my-scheme").unwrap();+ assert_eq!(v["name"], "my-scheme");+ let l = crate::themefile::parse("light", &v, |_| {+ Ok(crate::themefile::Loaded {+ theme: crate::palette::CLASSIC.clone(),+ warnings: Vec::new(),+ })+ })+ .unwrap();+ assert!(!l.theme.light.dark);+ assert!(contrast(l.theme.light.text, l.theme.light.window) >= TEXT_RATIO);+ }+}diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rsindex 4b2945d4..c8f67f4b 100644--- a/crates/app/src/theme.rs+++ b/crates/app/src/theme.rs@@ -80,6 +80,9 @@ pub fn set(theme: Theme) {/// that can't be read leaves the classic look, logged. Returns what was skipped or went wrong.pub fn select(id: &str, ctx: &egui::Context) -> Vec<String> {let id = id.to_owned();+ // pywal's file is followed again only if this theme is made from it (`themefile::load_in`).+ crate::themefile::forget_pywal();+ *SELECTED.lock().unwrap_or_else(|e| e.into_inner()) = id.clone();if id.is_empty() || id == CLASSIC.id {set(CLASSIC.clone());return Vec::new();@@ -90,13 +93,7 @@ pub fn select(id: &str, ctx: &egui::Context) -> Vec<String> {set(crate::native::theme(&system));return Vec::new();}- let path = std::path::Path::new(&id);- let loaded = if path.is_file() {- crate::themefile::load_file(path)- } else {- crate::themefile::load(&id)- };- match loaded {+ match load(&id) {Ok(loaded) => {for w in &loaded.warnings {tracing::warn!("theme {id}: {w}");@@ -112,6 +109,42 @@ pub fn select(id: &str, ctx: &egui::Context) -> Vec<String> {}}+/// A theme file's theme, by its id or its path.+fn load(id: &str) -> Result<crate::themefile::Loaded, String> {+ let path = std::path::Path::new(id);+ if path.is_file() {+ crate::themefile::load_file(path)+ } else {+ crate::themefile::load(id)+ }+}++/// The id (or path) [`select`] was last given.+static SELECTED: std::sync::Mutex<String> = std::sync::Mutex::new(String::new());++/// While the theme is made from pywal's colours (#45): read again when `wal` wrote them anew,+/// as it does for each new wallpaper. A file that doesn't read (half written as it was read)+/// keeps the theme as it is, and is read again when it is next written. True when the theme+/// changed (the caller applies it: `apply_theme`, `apply_mode`).+pub fn follow_pywal() -> bool {+ if !crate::themefile::pywal_changed() {+ return false;+ }+ let id = SELECTED.lock().unwrap_or_else(|e| e.into_inner()).clone();+ match load(&id) {+ Ok(loaded) => {+ tracing::info!("theme {id}: pywal's colours changed, read again");+ set(loaded.theme);+ true+ }+ Err(e) => {+ tracing::warn!("theme {id}: {e}; the theme kept until pywal's file is written again");+ crate::themefile::pywal_seen();+ false+ }+ }+}+/// The theme to start with: `MDM_THEME` (tests and screenshots: an id or a theme file's path),/// else the setting.pub fn startup_id(setting: &str) -> String {diff --git a/crates/app/src/themefile.rs b/crates/app/src/themefile.rsindex ec419c8f..b2809527 100644--- a/crates/app/src/themefile.rs+++ b/crates/app/src/themefile.rs@@ -23,6 +23,10 @@//!//! Unknown keys and values that can't be read are skipped and reported as warnings, so a file//! written for a newer MDM still loads; a file that isn't TOML or JSON is an error.+//!+//! A Base16 scheme (`.yaml`, `.yml`) and pywal's `colors.json` are themes too: `crate::schemes`+//! reads them into the same value tree, on the classic look. pywal's own file, where `wal`+//! writes it, is the theme `pywal`, read again when `wal` changes it ([`pywal_changed`]).use std::path::{Path, PathBuf};@@ -52,8 +56,9 @@ pub struct Entry {pub path: Option<PathBuf>,}-/// The built-in themes, then the theme files in [`dir`] (by name), each once: a file named as a-/// built-in is skipped (the built-in keeps its id).+/// The built-in themes, then pywal's colours when `wal` has written them, then the theme files+/// in [`dir`] (by name), each once: a file named as a built-in is skipped (the built-in keeps+/// its id).pub fn list() -> Vec<Entry> {let mut out: Vec<Entry> = palette::builtins().iter()@@ -80,6 +85,16 @@ pub fn list() -> Vec<Entry> {}).collect();files.sort();+ // pywal's colours where `wal` keeps them, unless a file of the folder takes the name.+ if let Some(wal) = pywal_file().filter(|p| p.is_file())+ && !files.iter().any(|(id, _)| id == PYWAL)+ {+ out.push(Entry {+ id: PYWAL.into(),+ name: PYWAL.into(),+ path: Some(wal),+ });+ }for (id, path) in files {// Built-ins keep their ids (Native too, which is made, not read).if out.iter().any(|e| e.id == id) || id == "native" {@@ -89,7 +104,7 @@ pub fn list() -> Vec<Entry> {let name = std::fs::read_to_string(&path).ok().and_then(|t| read_value(&path, &t).ok())- .and_then(|v| v.get("name").and_then(Value::as_str).map(str::to_owned))+ .and_then(|(v, _)| v.get("name").and_then(Value::as_str).map(str::to_owned)).unwrap_or_else(|| id.clone());out.push(Entry {id,@@ -113,15 +128,80 @@ fn folder_file(dir: &Path) -> Option<PathBuf> {.find(|p| p.is_file())}-/// A theme file's id: its name without `.toml` or `.json`; None for any other file.+/// The file kinds a theme can be: MDM's own (TOML, JSON, pywal's JSON too) and Base16's YAML.+const EXTENSIONS: [&str; 4] = ["toml", "json", "yaml", "yml"];++/// A theme file's id: its name without its extension ([`EXTENSIONS`]); None for any other file.fn theme_id(path: &Path) -> Option<String> {let ext = path.extension()?.to_str()?.to_ascii_lowercase();- if ext != "toml" && ext != "json" {+ if !EXTENSIONS.contains(&ext.as_str()) {return None;}Some(path.file_stem()?.to_str()?.to_owned())}+/// The theme of pywal's own colours (`wal`'s `colors.json`).+pub const PYWAL: &str = "pywal";++/// Where pywal writes its colours, as pywal itself finds its cache: `$PYWAL_CACHE_DIR`, else+/// `$XDG_CACHE_HOME/wal`, else `.cache/wal` in the home folder (`$HOME`, else the user's+/// profile folder: `%USERPROFILE%\.cache\wal` on Windows, where winwal writes it too).+pub fn pywal_file() -> Option<PathBuf> {+ let var = |k: &str| {+ std::env::var_os(k)+ .filter(|v| !v.is_empty())+ .map(PathBuf::from)+ };+ let dir = var("PYWAL_CACHE_DIR")+ .or_else(|| var("XDG_CACHE_HOME").map(|c| c.join("wal")))+ .or_else(|| {+ var("HOME")+ .or_else(dirs::home_dir)+ .map(|h| h.join(".cache").join("wal"))+ })?;+ Some(dir.join("colors.json"))+}++/// The file's time and size: what says it was written again.+type Stamp = (Option<std::time::SystemTime>, u64);++/// pywal's file as last read for the active theme, with its stamp then: None when the active+/// theme isn't made from it.+static PYWAL_READ: std::sync::Mutex<Option<(PathBuf, Stamp)>> = std::sync::Mutex::new(None);++fn stamp(path: &Path) -> Stamp {+ let meta = std::fs::metadata(path).ok();+ (+ meta.as_ref().and_then(|m| m.modified().ok()),+ meta.map_or(0, |m| m.len()),+ )+}++/// The active theme stops following pywal's file (a theme is being chosen).+pub fn forget_pywal() {+ *PYWAL_READ.lock().unwrap_or_else(|e| e.into_inner()) = None;+}++/// pywal's file as it is now taken as seen: a file that didn't read is read again only once it+/// is written again.+pub fn pywal_seen() {+ if let Some((path, seen)) = PYWAL_READ+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_mut()+ {+ *seen = stamp(path);+ }+}++/// True when the active theme is made from pywal's file and `wal` has written it since (its+/// time or size changed): one look at the file's details, on the main loop's 2-second check.+pub fn pywal_changed() -> bool {+ let read = PYWAL_READ.lock().unwrap_or_else(|e| e.into_inner());+ read.as_ref()+ .is_some_and(|(path, seen)| stamp(path) != *seen)+}+/// The theme with this id: a built-in, or the file of that name in [`dir`].pub fn load(id: &str) -> Result<Loaded, String> {let folder = dir().unwrap_or_default();@@ -147,15 +227,31 @@ fn load_in(folder: &Path, id: &str, depth: usize) -> Result<Loaded, String> {return Err(format!("{id}: too many themes inherit one another"));}let own = folder.join(id);- let path = ["toml", "json"]+ let found = EXTENSIONS.iter().map(|ext| folder.join(format!("{id}.{ext}"))).find(|p| p.is_file())- .or_else(|| folder_file(&own))+ .or_else(|| folder_file(&own));+ // pywal's colours where `wal` writes them, when no file in the folder has the name.+ let wal = if found.is_none() && id == PYWAL {+ pywal_file().filter(|p| p.is_file())+ } else {+ None+ };+ let path = found+ .or_else(|| wal.clone()).ok_or_else(|| format!("{id}: no such theme"))?;+ // Its stamp from before it is read: a write while it was read is seen at the next check.+ let before = wal.as_deref().map(stamp);let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;- let value = read_value(&path, &text)?;+ let (value, mut warnings) = read_value(&path, &text)?;let mut loaded = parse(id, &value, |base| load_in(folder, base, depth + 1))?;+ warnings.append(&mut loaded.warnings);+ loaded.warnings = warnings;+ // Followed from now on: read again when `wal` writes it.+ if let (Some(wal), Some(seen)) = (wal, before) {+ *PYWAL_READ.lock().unwrap_or_else(|e| e.into_inner()) = Some((wal, seen));+ }// A theme folder's own icons (`<id>/icons/16`, `24`), unless the file names a set.let icons = own.join("icons");if value.get("icon-set").is_none() && icons.is_dir() {@@ -174,17 +270,122 @@ fn load_in(folder: &Path, id: &str, depth: usize) -> Result<Loaded, String> {Ok(loaded)}-/// A file's contents as one value tree: TOML, or JSON for a `.json` file.-fn read_value(path: &Path, text: &str) -> Result<Value, String> {- let json = path+/// A file's contents as one value tree: TOML, JSON for a `.json` file (pywal's colours made a+/// theme's), a Base16 scheme made a theme's for a `.yaml` or `.yml` one; with what reading a+/// scheme changed (its contrast).+fn read_value(path: &Path, text: &str) -> Result<(Value, Vec<String>), String> {+ let at = |e: String| format!("{}: {e}", path.display());+ let ext = path+ .extension()+ .and_then(|e| e.to_str())+ .unwrap_or("")+ .to_ascii_lowercase();+ match ext.as_str() {+ "json" => {+ let v: Value = serde_json::from_str(text).map_err(|e| at(e.to_string()))?;+ if crate::schemes::is_pywal(&v) {+ crate::schemes::pywal_theme(&v).map_err(at)+ } else {+ Ok((v, Vec::new()))+ }+ }+ "yaml" | "yml" => {+ let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");+ crate::schemes::base16_theme(text, stem).map_err(at)+ }+ _ => toml::from_str(text)+ .map(|v| (v, Vec::new()))+ .map_err(|e| at(e.to_string())),+ }+}++/// View → Theme → Add a theme file (#45): a theme file or a colour scheme copied into [`dir`]+/// (made the first time), under its own file name, or with a number added when another theme+/// has that name; the same file already there is used as it is. The copy must load (with the+/// themes it inherits, beside it), or it is taken out again. Returns the theme's id.+pub fn add(source: &Path) -> Result<String, String> {+ let folder = dir().ok_or("MDM has no data folder")?;+ add_in(&folder, source)+}++fn add_in(folder: &Path, source: &Path) -> Result<String, String> {+ let ext = source.extension().and_then(|e| e.to_str())- .is_some_and(|e| e.eq_ignore_ascii_case("json"));- if json {- serde_json::from_str(text).map_err(|e| format!("{}: {e}", path.display()))+ .map(str::to_ascii_lowercase)+ .filter(|e| EXTENSIONS.contains(&e.as_str()))+ .ok_or_else(|| {+ format!(+ "{}: not a theme file (.toml, .json, .yaml, .yml)",+ source.display()+ )+ })?;+ let bytes = std::fs::read(source).map_err(|e| format!("{}: {e}", source.display()))?;+ let text = String::from_utf8_lossy(&bytes);+ // Read before it is copied: a file that isn't a theme stays out of the folder.+ let (value, _) = read_value(source, &text)?;+ let raw: Option<Value> = (ext == "json")+ .then(|| serde_json::from_str(&text).ok())+ .flatten();+ // pywal's file is always `colors.json`: its copy is named after the wallpaper.+ let stem = match raw.filter(crate::schemes::is_pywal) {+ Some(_) => file_name_of(value.get("name").and_then(Value::as_str).unwrap_or("")),+ None => source+ .file_stem()+ .and_then(|s| s.to_str())+ .map(file_name_of)+ .unwrap_or_default(),+ };+ let stem = if stem.is_empty() {+ "theme".to_owned()} else {- toml::from_str(text).map_err(|e| format!("{}: {e}", path.display()))+ stem+ };+ std::fs::create_dir_all(folder).map_err(|e| format!("{}: {e}", folder.display()))?;+ // The built-ins' ids, Native's and pywal's are never a file's (the file would be passed over).+ let reserved =+ |id: &str| palette::builtins().iter().any(|t| t.id == id) || id == "native" || id == PYWAL;+ let taken = |id: &str| {+ folder.join(id).exists()+ || EXTENSIONS+ .iter()+ .any(|e| folder.join(format!("{id}.{e}")).exists())+ };+ let mut id = stem.clone();+ let mut n = 1;+ loop {+ if !reserved(&id) {+ if std::fs::read(folder.join(format!("{id}.{ext}"))).is_ok_and(|b| b == bytes) {+ return Ok(id);+ }+ if !taken(&id) {+ break;+ }+ }+ n += 1;+ id = format!("{stem}-{n}");+ }+ let target = folder.join(format!("{id}.{ext}"));+ std::fs::write(&target, &bytes).map_err(|e| format!("{}: {e}", target.display()))?;+ if let Err(e) = load_in(folder, &id, 0) {+ let _ = std::fs::remove_file(&target);+ return Err(e);}+ Ok(id)+}++/// A name as a file name: letters and digits kept, lower case, the rest one dash+/// (`pywal: lake.jpg` → `pywal-lake-jpg`).+fn file_name_of(name: &str) -> String {+ let mut out = String::new();+ for c in name.chars() {+ if c.is_alphanumeric() || c == '_' {+ out.extend(c.to_lowercase());+ } else if !out.is_empty() && !out.ends_with('-') {+ out.push('-');+ }+ }+ out.trim_end_matches('-').to_owned()}/// A built-in theme shipped as a theme file (inheriting the classic look at most): a file that@@ -549,4 +750,128 @@ mod tests {assert_eq!(load_in(&dir, "classic", 0).unwrap().theme, CLASSIC);let _ = std::fs::remove_dir_all(&dir);}++ fn temp_dir(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("mdm-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ const SCHEME: &str = "scheme: \"Test Scheme\"\nbase00: \"1d2021\"\nbase01: \"32302f\"\n\+ base02: \"504945\"\nbase03: \"665c54\"\nbase04: \"bdae93\"\nbase05: \"d5c4a1\"\n\+ base06: \"ebdbb2\"\nbase07: \"fbf1c7\"\nbase08: \"fb4934\"\nbase09: \"fe8019\"\n\+ base0A: \"fabd2f\"\nbase0B: \"b8bb26\"\nbase0C: \"8ec07c\"\nbase0D: \"83a598\"\n\+ base0E: \"d3869b\"\nbase0F: \"d65d0e\"\n";++ const WAL: &str = r##"{ "wallpaper": "C:\\Users\\someone\\Pictures\\dunes.png",+ "special": { "background": "#f2efe9", "foreground": "#3a3530" },+ "colors": { "color0": "#f2efe9", "color1": "#a8483c", "color2": "#4f7a3a",+ "color3": "#8a6a1e", "color4": "#3d6a9a", "color8": "#8c867c" } }"##;++ #[test]+ fn schemes_in_the_folder_are_themes() {+ let dir = temp_dir("schemes");+ std::fs::write(dir.join("gruvish.yaml"), SCHEME).unwrap();+ std::fs::write(dir.join("colors.json"), WAL).unwrap();+ std::fs::write(dir.join("broken.yml"), "base00: \"1d2021\"\n").unwrap();+ // A theme file built on a scheme: its colours, the file's own changes on top.+ std::fs::write(+ dir.join("mine.toml"),+ "inherits = \"gruvish\"\nicons = \"accent\"\n[sizes]\nradius = 6\n",+ )+ .unwrap();+ let t = load_in(&dir, "gruvish", 0).unwrap().theme;+ assert_eq!(t.name, "Test Scheme");+ assert_eq!(t.dark.field, Color32::from_rgb(0x1d, 0x20, 0x21));+ assert_eq!(t.light, t.dark);+ let mine = load_in(&dir, "mine", 0).unwrap().theme;+ assert_eq!(+ (mine.dark.field, mine.light.accent),+ (t.dark.field, t.light.accent)+ );+ assert_eq!(mine.icons, IconStyle::Accent);+ assert_eq!(mine.metrics.control_radius, 6.0);+ // pywal's file, here a light one: a light theme named after its wallpaper.+ let wal = load_in(&dir, "colors", 0).unwrap();+ assert_eq!(wal.theme.name, "pywal: dunes.png");+ assert!(!wal.theme.light.dark);+ assert_eq!(wal.theme.light.accent, Color32::from_rgb(0x3d, 0x6a, 0x9a));+ assert!(load_in(&dir, "broken", 0).unwrap_err().contains("base05"));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn adding_copies_into_the_folder_once() {+ let from = temp_dir("add-from");+ let to = from.join("themes");+ std::fs::write(from.join("gruvish.yaml"), SCHEME).unwrap();+ std::fs::write(from.join("colors.json"), WAL).unwrap();+ std::fs::write(from.join("metro.toml"), "[colors]\naccent = \"#123456\"\n").unwrap();+ std::fs::write(from.join("bad.yaml"), "just: words\n").unwrap();+ std::fs::write(from.join("lonely.toml"), "inherits = \"not-here\"\n").unwrap();+ std::fs::write(from.join("notes.txt"), "hi").unwrap();+ assert_eq!(add_in(&to, &from.join("gruvish.yaml")).unwrap(), "gruvish");+ // The same file again: the copy there; another of the same name: a number added.+ assert_eq!(add_in(&to, &from.join("gruvish.yaml")).unwrap(), "gruvish");+ let other = from.join("other").join("gruvish.yml");+ std::fs::create_dir_all(other.parent().unwrap()).unwrap();+ std::fs::write(&other, SCHEME.replace("83a598", "458588")).unwrap();+ assert_eq!(add_in(&to, &other).unwrap(), "gruvish-2");+ // pywal's colors.json: named after its wallpaper. A built-in's name: a number added.+ assert_eq!(+ add_in(&to, &from.join("colors.json")).unwrap(),+ "pywal-dunes-png"+ );+ assert_eq!(add_in(&to, &from.join("metro.toml")).unwrap(), "metro-2");+ assert_eq!(+ load_in(&to, "metro-2", 0).unwrap().theme.light.accent,+ Color32::from_rgb(0x12, 0x34, 0x56)+ );+ // Not themes, or not loading once copied: nothing left in the folder.+ for f in ["bad.yaml", "lonely.toml", "notes.txt", "missing.toml"] {+ assert!(add_in(&to, &from.join(f)).is_err(), "{f}");+ }+ let mut names: Vec<String> = std::fs::read_dir(&to)+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ names.sort();+ assert_eq!(+ names,+ [+ "gruvish-2.yml",+ "gruvish.yaml",+ "metro-2.toml",+ "pywal-dunes-png.json"+ ]+ );+ let _ = std::fs::remove_dir_all(&from);+ }++ #[test]+ fn a_rewritten_pywal_file_is_seen() {+ let dir = temp_dir("wal-follow");+ let file = dir.join("colors.json");+ std::fs::write(&file, WAL).unwrap();+ *PYWAL_READ.lock().unwrap() = Some((file.clone(), stamp(&file)));+ assert!(!pywal_changed());+ // `wal` run again: other colours, another size.+ std::fs::write(+ &file,+ WAL.replace("#3d6a9a", "#7b4d9e\", \"color5\": \"#000"),+ )+ .unwrap();+ assert!(pywal_changed());+ forget_pywal();+ assert!(!pywal_changed());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn file_names_from_names() {+ assert_eq!(file_name_of("pywal: lake.jpg"), "pywal-lake-jpg");+ assert_eq!(file_name_of("Gruvbox dark, medium"), "gruvbox-dark-medium");+ assert_eq!(file_name_of(" .. "), "");+ }}diff --git a/docs/getting-started.md b/docs/getting-started.mdindex c4003140..9303b7a7 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -227,8 +227,10 @@ MDM follows your system: when Windows (or your desktop's light/dark preference oEach has a light and a dark side: **Dark Mode support** and **Always dark** choose betweenthem as before. Theme files you put in the themes folder (**View → Theme → Open themes folder**)-are listed there too: [Themes](themes.md) says where that folder is, what a theme file holds-(`inherits`, colours, sizes, control shapes, icons) and how to make and share one.+are listed there too, and so are Base16 and pywal colour schemes (**View → Theme → Add a theme+file…**; **pywal** follows `wal` as it runs): [Themes](themes.md) says where that folder is, what+a theme file holds (`inherits`, colours, sizes, control shapes, icons), how a scheme's colours are+used, and how to make and share one.## The tray icondiff --git a/docs/themes.md b/docs/themes.mdindex 0782da39..cef54a1f 100644--- a/docs/themes.md+++ b/docs/themes.md@@ -37,10 +37,70 @@ it gives itself. After you edit a file, pick it again in **View → Theme** to sA theme can be one file (`harbour.toml`) or a folder of its own (`harbour/theme.toml`) when itbrings icons.+**View → Theme → Add a theme file…** does it for you: pick a file anywhere, and MDM copies it into+the themes folder and uses it at once. A file that isn't a theme stays out, and MDM says why.++## Base16 and pywal colour schemes++Colour schemes made for other programs are themes too, with nothing to convert:++- **A Base16 scheme**, the `.yaml` file the+ [Base16 and Base24 schemes](https://github.com/tinted-theming/schemes) come in: both the+ classic layout (`scheme:` and `base00` to `base0F` at the top) and the newer one (`name:` and a+ `palette:` block). A Base24 scheme reads as its first 16 colours.+- **pywal's `colors.json`**, or any program's file in pywal's shape (wallust's pywal template).++Add it with **View → Theme → Add a theme file…**, or put it in the themes folder yourself. It+shows in **View → Theme** under the scheme's name (`name:` or `scheme:`; pywal's is named after+the wallpaper).++**pywal itself:** once `wal` has run, **View → Theme** lists **pywal**, read straight from where+pywal writes its colours: `~/.cache/wal/colors.json` (on Windows+`%USERPROFILE%\.cache\wal\colors.json`, where winwal and pywal write it; `$PYWAL_CACHE_DIR` or+`$XDG_CACHE_HOME/wal` when you set them). Pick it and MDM follows your wallpaper: each time `wal`+writes new colours, MDM takes them within two seconds. It looks only at the file's date and size,+every two seconds, and only while pywal is the theme. A copy added with **Add a theme file…**+keeps the colours it had.++A scheme changes colours only, on the classic look: every window, button and menu stays where it+was. A dark scheme makes MDM dark and a light one light, whatever **View → Always dark** says. The+scheme's colours go where they mean the same:++| MDM | Base16 | pywal |+|---|---|---|+| The download list, text boxes and menus | `base00` (the background) | `special.background` |+| Windows, dialogs, the toolbar, the menu bar and column headers | `base01` (the lighter background) | the background a step toward the foreground |+| Text | `base05` (the foreground) | `special.foreground` |+| Secondary text (sizes, notes) | `base04` | `color8` |+| Focus, default buttons, check boxes, links, the selection and the progress bar | `base0D` (blue) | `color4` |+| Errors | `base08` (red) | `color1` |+| Warnings | `base0A` (yellow) | `color3` |+| Success, the meters and a torrent's pieces | `base0B` (green) | `color2` |++Borders and the hover and pressed shades are mixed from these, as for a theme file's `[seeds]`.+Text stays readable: text and secondary text at 4.5:1 or more against every background they sit+on (WCAG AA), the accent at 3:1. A scheme short of that has those colours moved a little darker+(lighter on a dark scheme) until they pass; MDM's log says which.++To change more than colours, make a theme file that inherits the scheme by its file name and adds+what you like:++```toml+name = "Gruvbox, my way"+inherits = "gruvbox-dark-medium" # gruvbox-dark-medium.yaml, beside it+icons = "accent"++[sizes]+radius = 6+```++`inherits = "pywal"` works the same way, and follows `wal` too.+## The file-A theme is one small text file in [TOML](https://toml.io/) (or JSON, `.json`). It names only what-it changes; everything else comes from the theme it `inherits`:+A theme is one small text file in [TOML](https://toml.io/) (or JSON, `.json`; or a+[colour scheme](#base16-and-pywal-colour-schemes), `.yaml`). It names only what it changes;+everything else comes from the theme it `inherits`:```tomlname = "Harbour"diff --git a/i18n/en.tsv b/i18n/en.tsvindex c275fcdc..15229d1b 100644--- a/i18n/en.tsv+++ b/i18n/en.tsv@@ -193,6 +193,10 @@Add Add#. what a keyboard shortcut does in the Help menu's windows (About, updates, shortcuts, Tell a friend)Add a download (Add URL) Add a download (Add URL)+#. message or event log entry in the main window+#. title of the file dialog of View → Theme → Add a theme file+#. title of the message when View → Theme → Add a theme file fails+ Add a theme file Add a theme file#. window title in the Options window#. window title: adding a debrid service account (Real-Debrid…)Add an account Add an account@@ -3269,6 +3273,9 @@The update is open in your system's package installer. The update is open in your system's package installer.#. text in a download's Properties windowThe web page from which this file was obtained: The web page from which this file was obtained:+#. message or event log entry in the main window+#. the kind of file View → Theme → Add a theme file lists: MDM's themes (TOML, JSON), Base16 schemes (YAML) and pywal's colors.json+ Themes and colour schemes Themes and colour schemes#. text in the Options window#. Options → Archives check boxThen move the archives to the Recycle Bin Then move the archives to the Recycle Bin@@ -3313,6 +3320,10 @@#. text in remote.rs#. remote control page (on a phone): label of the box naming this phone (shown in MDM's list of paired devices)This device's name This device's name+#. message or event log entry in the main window+#. {error} is why, in English (a file that isn't a theme or a colour scheme, a colour missing)+#. {error} = an error message (keep the braces as they are)+ This file can't be used as a theme: {error} This file can't be used as a theme: {error}#. text in remote.rs#. remote control page (on a phone): the file chosen is too large for a .torrent fileThis file is too large to be a torrent. This file is too large to be a torrent.@@ -4432,6 +4443,9 @@ menu Add &batch download Add &batch download#. the trailing ... means it opens a window: keep itmenu Add &magnet link... Add &magnet link...#. menu command in the main window+#. View → Theme: picks a theme file or a Base16 or pywal colour scheme, copies it into the themes folder and uses it+menu Add a theme file… Add a theme file…+#. menu command in the main window#. & marks the keyboard shortcut letter: keep one & before a letter of the translationmenu Add batch download from &clipboard Add batch download from &clipboard#. menu command in the main window@@ -4634,6 +4648,9 @@ menu OpenGL OpenGL#. noun: opens the category's propertiesmenu Properties Properties#. menu command in the main window+#. View → Theme: the colours of pywal (a program making colour schemes from the wallpaper), followed as they change; a name: keep "pywal" as written+menu pywal pywal+#. menu command in the main window#. verb: download the file again from the start#. & marks the keyboard shortcut letter: keep one & before a letter of the translationmenu R&edownload R&edownloaddiff --git a/tools/website/build.py b/tools/website/build.pyindex e5da5c9e..51f902cc 100644--- a/tools/website/build.py+++ b/tools/website/build.py@@ -1454,6 +1454,9 @@ def build_themes() -> None:<div><dt>Portable copy</dt><dd><code translate="no">data\\themes</code> beside the program</dd></div></dl><p>Within two seconds it shows in <b>View → Theme</b>, under the built-in themes, by the <code>name</code> it gives itself. Pick it and the whole window changes at once. After you edit the file, pick it again in <b>View → Theme</b> to see the change. <b>View → Dark Mode support</b> and <b>Always dark</b> switch between its light and dark side.</p>+ <p><b>View → Theme → Add a theme file…</b> does it for you: pick the file anywhere, and MDM copies it into the themes folder and uses it at once.</p>+ <h4 id="schemes">Already have a Base16 or pywal scheme?</h4>+ <p>It's a theme already. A <a href="https://github.com/tinted-theming/schemes">Base16 or Base24 scheme</a> (<code>.yaml</code>) or pywal's <code>colors.json</code>, added the same way, changes MDM's colours and nothing else: the scheme's backgrounds behind the list and the windows, its text kept readable (4.5:1 or more), its blue on the focus, the selection and the progress bar. Once <code>wal</code> has run, <b>View → Theme</b> lists <b>pywal</b>, read from <code>~/.cache/wal/colors.json</code> (<code translate="no">%USERPROFILE%\\.cache\\wal\\colors.json</code> on Windows), and MDM follows each new wallpaper's colours within two seconds. <a href="{REPO}/blob/main/docs/themes.md#base16-and-pywal-colour-schemes">The guide</a> shows which colour goes where.</p></li><li id="share-it"><h3>Share it</h3><p>Made something others would like? Open a <a href="{REPO}/pulls">pull request on GitHub</a> that adds it to <a href="{themes_dir}"><code>crates/app/assets/themes</code></a>, with:</p>