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, stage 1: every colour and size from one theme, the classic look unchanged (part of #45) (#174)
Ahmed Nefzaoui5f5a581f8113
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fefb7cc8..6907ecd9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -310,6 +310,12 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, seeaddress (a server without ranges was fixed earlier). Each now waits for the state it checks. The lab servercan hold a connection slot for a test (`hold_slot`), and `settled()` now also means everyslot is free.+- **Themes, the groundwork** ([#45](https://github.com/anefzaoui/misterdownloadmanager/issues/45)):+ every colour and size MDM's controls are drawn with (corner radii, borders, font sizes, the+ list's row height, the icons' ink) now comes from one theme, by role. The classic look is that+ theme, unchanged pixel for pixel. Theme files (TOML or JSON in the data folder's `themes`+ folder) can already change any role; choosing one in the app, more built-in themes, pywal and+ Base16 come next.- **A smaller download** ([#158](https://github.com/anefzaoui/misterdownloadmanager/issues/158)):the program is built for size, which takes the installer from 16.1 to 13.6 MB and the zipsfrom 19.3 to 15.6 MB, with the same features and the same download speed.diff --git a/Cargo.lock b/Cargo.lockindex 51212133..c9c0f6ab 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4458,6 +4458,7 @@ dependencies = ["serde_json","tempfile","tokio",+ "toml 1.1.8+spec-1.1.0","tracing","tray-icon","unicode-segmentation",@@ -4584,7 +4585,7 @@ dependencies = [[[package]]name = "mdm-geo"-version = "0.2.4"+version = "0.3.0"dependencies = ["lzma-rust2","png 0.18.1",diff --git a/Cargo.toml b/Cargo.tomlindex 84ab0f16..39b2c35e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -112,6 +112,7 @@ tokio-rustls = { version = "0.26.6", default-features = false, features = ["aws-rcgen = { version = "0.14", default-features = false, features = ["crypto", "aws_lc_rs", "pem"] }serde = { version = "1.0.229", features = ["derive"] }serde_json = "1.0.154"+toml = { version = "1.1.2", default-features = false, features = ["std", "parse", "serde"] }serde_urlencoded = "0.7.1"sha2 = "0.11.1"tempfile = "3.27.0"diff --git a/ROADMAP.md b/ROADMAP.mdindex 5f90637a..e760d8c2 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -39,6 +39,9 @@ Everything below ships together, in one release, as version 0.3.0.on the website, in the help, the FAQ and the README; MDM's **Add Mister Download Manager toyour browser** window opens the store in Chrome, Edge, Brave, Opera and Vivaldi, with themanual install as the fallback+- ✅ Themes, the groundwork: every colour and size the controls are drawn with comes from one+ theme, and theme files can change them; the classic look is unchanged+ ([#45](https://github.com/anefzaoui/misterdownloadmanager/issues/45))- ✅ A minimized MDM keeps working: queues, the Scheduler, download limits, the kill switch andsaving the list no longer wait for the window to be restored- ✅ Download video: every button fits its text in every language (German **ffmpeg installieren**diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.tomlindex 600859a3..8a760d55 100644--- a/crates/app/Cargo.toml+++ b/crates/app/Cargo.toml@@ -35,6 +35,7 @@ open.workspace = truereqwest.workspace = trueserde.workspace = trueserde_json.workspace = true+toml.workspace = truetokio.workspace = trueurl.workspace = truepercent-encoding.workspace = truediff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex fd1f284c..4cec486c 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -686,6 +686,8 @@ impl App {commands: std::sync::mpsc::Receiver<ipc::Incoming>,loaded: store::Loaded,) -> Self {+ // The look (#45): the chosen theme before anything is drawn.+ crate::theme::select(&loaded.settings.theme);crate::theme::apply(&cc.egui_ctx);let mut settings = loaded.settings;if settings.limiter_on_startup {@@ -7174,7 +7176,7 @@ impl eframe::App for App {#[cfg(windows)]{self.caption_set =- crate::win32::caption_dark(crate::MAIN_TITLE, crate::theme::dark());+ crate::win32::caption_dark(crate::MAIN_TITLE, crate::theme::dark_surface());}#[cfg(not(windows))]{diff --git a/crates/app/src/chrome.rs b/crates/app/src/chrome.rsindex 1cda312a..d8de7e80 100644--- a/crates/app/src/chrome.rs+++ b/crates/app/src/chrome.rs@@ -17,37 +17,39 @@ pub const MENU_H: f32 = 20.0;const fn rgb(r: u8, g: u8, b: u8) -> Color32 {Color32::from_rgb(r, g, b)}-fn grey(v: u8) -> Color32 {- rgb(v, v, v)-}use crate::theme::themed;+// The active theme's colours (crate::palette, #45).themed! {- pub WINDOW_BG = rgb(0x39, 0x39, 0x39), grey(0xf0);- MENUBAR_BG = rgb(0x20, 0x20, 0x20), grey(0xff);+ pub WINDOW_BG => window;+ MENUBAR_BG => menubar;+ /// The bar's last row (light: #f2f2f2).+ MENUBAR_BOTTOM => menubar_bottom;/// The open menu's item. Light: #f9f9f9, the popup's own background (captured 2026-10-30).- MENUBAR_OPEN = rgb(0x50, 0x50, 0x50), grey(0xf9);+ MENUBAR_OPEN => menubar_open;/// An item under the pointer, no menu open (captured 2026-10-30): dark #505050 from 1 px/// below the bar's top; light #f5f5f5, 1 px inside the bar's top and bottom.- MENUBAR_HOT = rgb(0x50, 0x50, 0x50), grey(0xf5);- MENUBAR_LINE = rgb(0xf0, 0xf0, 0xf0), grey(0xf0);- POPUP_BG = rgb(0x2b, 0x2b, 0x2b), grey(0xf9);+ MENUBAR_HOT => menubar_hot;+ MENUBAR_LINE => menubar_line;+ POPUP_BG => menu;// The native menu window's frame (Windows draws menus in their own window), and every// in-window popup's (popup_surface).- POPUP_BORDER = rgb(0x3e, 0x3e, 0x3e), grey(0xe5);- POPUP_SEP = rgb(0x3e, 0x3e, 0x3e), grey(0xd7);+ POPUP_BORDER => menu_border;+ POPUP_SEP => menu_sep;/// Light: #f0f0f0, rounded, captured 2026-10-30.- POPUP_HOVER = rgb(0x35, 0x35, 0x35), grey(0xf0);- POPUP_ITEM = rgb(0x2c, 0x2c, 0x2c), grey(0xf9);- TEXT = rgb(0xff, 0xff, 0xff), grey(0x00);+ POPUP_HOVER => menu_hot;+ POPUP_ITEM => menu_item;+ TEXT => menu_text;/// Bullets and submenu arrows (light: dark cores #1a1a1a / #282828).- GLYPH = rgb(0xff, 0xff, 0xff), grey(0x1a);- TEXT_DISABLED_MENU = rgb(0x6d, 0x6d, 0x6d), grey(0x9f);- TB_DISABLED = rgb(0xa0, 0xa0, 0xa0), grey(0xa0);+ GLYPH => menu_glyph;+ TEXT_DISABLED_MENU => menu_text_disabled;+ TB_DISABLED => toolbar_text_disabled;/// A drop-down's arrow (dark: light on the dark band, where #282828 could not be seen).- TB_ARROW = rgb(0xd0, 0xd0, 0xd0), grey(0x28);- CAT_FRAME = rgb(0xdc, 0xdc, 0xdc), grey(0xdc);- TREE_BG = rgb(0x20, 0x20, 0x20), grey(0xff);- TREE_LINES = rgb(0x6d, 0x6d, 0x6d), grey(0x6d);+ TB_ARROW => toolbar_arrow;+ CAT_FRAME => tree_frame;+ TREE_BG => tree;+ TREE_LINES => tree_lines;+ /// The tree's chevrons (dark look).+ TREE_EXPANDER => tree_expander;}use crate::winui::{fill, px};@@ -201,17 +203,15 @@ pub fn menu_bar(ui: &mut Ui, o: Pos2, width: f32, open: Option<usize>) -> Optiono.y + MENU_H - 2.0,MENUBAR_BG(),);- if !crate::theme::dark() {- // Light: the bar's last row is #f2f2f2.- fill(- &p,- o.x,- o.y + MENU_H - 2.0,- o.x + width - 1.0,- o.y + MENU_H - 2.0,- grey(0xf2),- );- }+ // The bar's last row (light: #f2f2f2; dark: the bar's own).+ fill(+ &p,+ o.x,+ o.y + MENU_H - 2.0,+ o.x + width - 1.0,+ o.y + MENU_H - 2.0,+ MENUBAR_BOTTOM(),+ );fill(&p,o.x,@@ -406,7 +406,7 @@ pub fn show_cues(ctx: &egui::Context) {/// Whether access letters are underlined: always in dark mode, after [`show_cues`] in light.pub fn cues(ctx: &egui::Context) -> bool {- crate::theme::dark()+ crate::theme::colors().access_keys_always|| ctx.data(|d| {d.get_temp::<bool>(egui::Id::unique("keyboard-cues")).unwrap_or(false)@@ -716,10 +716,11 @@ pub fn open_sub_at(ctx: &egui::Context, id: &str, i: usize) {/// The surface of a popup drawn inside a window (the date picker's calendar, a column's filter/// box): the menus' colours and border, rounded as Windows 11's flyouts (they had their own).pub fn popup_surface(p: &egui::Painter, rc: egui::Rect) {- p.rect_filled(rc, 6.0, POPUP_BG());+ let radius = crate::theme::metrics().flyout_radius;+ p.rect_filled(rc, radius, POPUP_BG());p.rect_stroke(rc,- 6.0,+ radius,egui::Stroke::new(1.0, POPUP_BORDER()),egui::StrokeKind::Inside,);@@ -956,7 +957,11 @@ fn popup_level<C: Clone>(None => hovered,};if lit || open_sub == Some(i) {- painter.rect_filled(slot, 4.0, POPUP_HOVER());+ painter.rect_filled(+ slot,+ crate::theme::metrics().menu_item_radius,+ POPUP_HOVER(),+ );} else {// Spec: an item's normal background is one level lighter than the padding.fill(@@ -1191,11 +1196,18 @@ pub fn toolbar() -> Option<ToolbarEvent> {let p = ui.painter().clone();let top = o.y + MENU_H;- fill(&p, o.x, top, o.x + width - 1.0, top, grey(0xa0));- fill(&p, o.x, top + 1.0, o.x + width - 1.0, top + 1.0, grey(0xff));+ let c = crate::theme::colors();+ fill(&p, o.x, top, o.x + width - 1.0, top, c.toolbar_line);+ fill(+ &p,+ o.x,+ top + 1.0,+ o.x + width - 1.0,+ top + 1.0,+ c.toolbar_line_light,+ );// Both modes (light-main.md; dark changes only colours): Tahoma labels, 66 px buttons, a// 68 px band.- let dark = crate::theme::dark();let (font, base_w, band_h) = (winui::tahoma(), 66.0f32, 68.0);let band = Rect::from_min_size(pos2(o.x, top + 2.0), vec2(width, band_h));p.rect_filled(band, 0.0, WINDOW_BG());@@ -1247,21 +1259,13 @@ pub fn toolbar(// request 2026-10-29): a drop-down is a split button — the part under the pointer is// lit (pressed while the mouse is down), the other part faintly, a 1 px divider between.let h = 65.0;- let (hot_c, faint_c, down_c, edge_c) = if dark {- (- rgb(0x33, 0x41, 0x4d),- rgb(0x37, 0x3b, 0x3f),- rgb(0x2a, 0x36, 0x40),- rgb(0x4d, 0x5f, 0x6e),- )- } else {- (- rgb(0xe5, 0xf3, 0xff),- rgb(0xf3, 0xf9, 0xff),- rgb(0xcc, 0xe8, 0xff),- rgb(0xcc, 0xe8, 0xff),- )- };+ let (hot_c, faint_c, down_c, edge_c, border_c) = (+ c.toolbar_hot,+ c.toolbar_hot_faint,+ c.toolbar_pressed,+ c.toolbar_hot_edge,+ c.toolbar_hot_border,+ );let on_arrow = dropdown && resp.hover_pos().is_some_and(past_button);let down = resp.is_pointer_button_down_on();let main = winui::rect(Rect::from_min_size(pos2(x, band.top()), vec2(bw, h)));@@ -1277,14 +1281,13 @@ pub fn toolbar((false, _) => faint_c,};p.rect_filled(r, 0.0, c);- if !dark {- p.rect_stroke(- r,- 0.0,- egui::Stroke::new(1.0, edge_c),- egui::StrokeKind::Inside,- );- }+ // None in the dark look (a transparent border isn't drawn).+ p.rect_stroke(+ r,+ 0.0,+ egui::Stroke::new(1.0, border_c),+ egui::StrokeKind::Inside,+ );};lit(main, !on_arrow);if dropdown {@@ -1331,11 +1334,7 @@ pub fn toolbar(// toolbar separator — a shadow line and a highlight beside it — 24 px tall, centred// on the arrow; the hover draws the full divider instead.if !(*enabled && resp.hovered()) {- let (shadow, light) = if dark {- (grey(0x26), grey(0x4d))- } else {- (grey(0xc6), grey(0xff))- };+ let (shadow, light) = (c.toolbar_split_shadow, c.toolbar_split_light);let (y0, y1) = (ay - 10.0, ay + 13.0);winui::fill_l(&p, x + bw - 1.0, y0, x + bw - 1.0, y1, shadow);winui::fill_l(&p, x + bw, y0, x + bw, y1, light);@@ -1496,8 +1495,8 @@ pub fn categories(.interact(close, egui::Id::unique("cat-close"), winui::pointer_only())// i18n: tooltip of the × that closes the Categories pane.on_hover_text(crate::i18n::t("Close"));- if let Some(c) = winui::subtle_fill(winui::State::of(&cr, true), crate::theme::dark()) {- p.rect_filled(close, 2.0, c);+ if let Some(c) = winui::subtle_fill(winui::State::of(&cr, true), crate::theme::colors()) {+ p.rect_filled(close, crate::theme::metrics().part_radius, c);}text_font(&p,@@ -1636,7 +1635,6 @@ pub fn categories(let icon_x = o.x + if r.level == 0 { 30.0 } else { 49.0 };let text_x = o.x + if r.level == 0 { 51.0 } else { 70.0 };let ext = text_width_font(&p, winui::tahoma(), crate::i18n::t(&r.label));- let dark = crate::theme::dark();if r.selected {// The inactive selection grey behind the label, in both modes (#f0f0f0 on the white// tree could not be seen).@@ -1650,7 +1648,7 @@ pub fn categories();}if let Some(open) = r.expander {- if dark {+ if crate::theme::colors().tree_chevrons {winui::fill_l(&tp, o.x + 11.0, top, o.x + 26.0, top + 15.0, TREE_BG());chevron(&tp, o.x, top, open, r.selected);} else {@@ -1937,6 +1935,17 @@ fn chevron(p: &egui::Painter, ox: f32, top: f32, open: bool, bright: bool) {[0x20, 0x20, 0x20, 0x21, 0x53, 0x21, 0x20, 0x20, 0x20],];let _ = bright;+ // Measured over the dark tree (#20) in white: coverage, so the theme's tree and ink show.+ let (bg, ink) = (TREE_BG(), TREE_EXPANDER());+ let grey = |v: u8| {+ let a = (v as f32 - 32.0) / 223.0;+ let mix = |b: u8, i: u8| (b as f32 + (i as f32 - b as f32) * a).round() as u8;+ rgb(+ mix(bg.r(), ink.r()),+ mix(bg.g(), ink.g()),+ mix(bg.b(), ink.b()),+ )+ };if open {for (dy, row) in EXPANDED.iter().enumerate() {for (dx, v) in row.iter().enumerate() {diff --git a/crates/app/src/crashui.rs b/crates/app/src/crashui.rsindex cd851f67..fb5577d2 100644--- a/crates/app/src/crashui.rs+++ b/crates/app/src/crashui.rs@@ -107,6 +107,7 @@ pub fn monitor_main(m: MonitorArgs) -> eframe::Result {plan.watched = false;let data = m.data.clone();crate::renderer::run("misterdownloadmanager-crash", &plan, options, move |cc| {+ crate::theme::select(&settings.theme);crate::theme::apply(&cc.egui_ctx);crate::i18n::set_lang(settings.language.as_deref());crate::theme::language_fonts(&cc.egui_ctx);@@ -297,7 +298,7 @@ impl eframe::App for ReportWindow {// As the app logs its windows (crash.rs), for the log and the tests.tracing::info!("window opened: crash-report");ui.ctx().send_viewport_cmd(egui::ViewportCommand::SetTheme(- crate::theme::system_theme(crate::theme::dark()),+ crate::theme::system_theme(crate::theme::dark_surface()),));self.caption_set = true;}@@ -305,7 +306,7 @@ impl eframe::App for ReportWindow {#[cfg(windows)]crate::win32::caption_dark(crate::i18n::t("Mister Download Manager crash report"),- crate::theme::dark(),+ crate::theme::dark_surface(),);while let Ok(e) = self.events.try_recv() {if matches!(e, Event::Recovered) {diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rsindex 9de383b8..c1aa340d 100644--- a/crates/app/src/dialogs.rs+++ b/crates/app/src/dialogs.rs@@ -227,7 +227,7 @@ fn dialog_window<T>(let framed = key.with("framed");let scale = ctx.input_for(ViewportId::from_hash_of(id), |i| i.pixels_per_point);if ctx.data(|d| d.get_temp::<[f32; 2]>(framed)) != Some(client)- && crate::win32::dialog_frame(title, client, !crate::theme::dark(), scale)+ && crate::win32::dialog_frame(title, client, !crate::theme::dark_surface(), scale){ctx.data_mut(|d| d.insert_temp(framed, client));}@@ -237,8 +237,8 @@ fn dialog_window<T>(ViewportId::from_hash_of(id),key,title,- // Every dialog follows the mode (the light dialogs too).- crate::theme::dark(),+ // Every dialog follows the mode (the light dialogs too), its caption the theme's surface.+ crate::theme::dark_surface(),matches!(out, Outcome::Open),);// A question takes the focus once it is shown (not while hidden for its theme).diff --git a/crates/app/src/droptarget.rs b/crates/app/src/droptarget.rsindex 3708ac14..3b130090 100644--- a/crates/app/src/droptarget.rs+++ b/crates/app/src/droptarget.rs@@ -116,15 +116,12 @@ impl DropTarget {let (fill, edge) = if over {(// Something dragged over it: the shared highlight and accent, in the mode.- crate::winui::highlight_fill(crate::winui::State::Hot, crate::theme::dark())+ crate::winui::highlight_fill(crate::winui::State::Hot, crate::theme::colors()).unwrap_or(crate::winui::BG()),crate::winui::accent(),)} else {- (- crate::winui::BG(),- egui::Color32::from_rgb(0x8d, 0x8d, 0x8d),- )+ (crate::winui::BG(), crate::theme::colors().drop_edge)};p.rect_filled(rect, 0.0, fill);p.rect_stroke(diff --git a/crates/app/src/grabber.rs b/crates/app/src/grabber.rsindex c06e9f60..bd1d5311 100644--- a/crates/app/src/grabber.rs+++ b/crates/app/src/grabber.rs@@ -9,7 +9,7 @@use std::path::PathBuf;use std::sync::{Arc, Mutex};-use egui::{Color32, Pos2, Rect, Ui, pos2, vec2};+use egui::{Pos2, Rect, Ui, pos2, vec2};use url::Url;use crate::dialogs::{Outcome, window};@@ -26,12 +26,8 @@ const CHECKS_PER_HOST: usize = 4;crate::theme::themed! {// The lists' header colour (winui::LIST_HEADER), as Add torrent's file list.- LIST_HEAD = rgb(0x19, 0x19, 0x19), rgb(0xff, 0xff, 0xff);- LIST_LINE = rgb(0x4a, 0x4a, 0x4a), rgb(0xe5, 0xe5, 0xe5);-}--const fn rgb(r: u8, g: u8, b: u8) -> Color32 {- Color32::from_rgb(r, g, b)+ LIST_HEAD => header;+ LIST_LINE => table_line;}/// What looking a link up found.diff --git a/crates/app/src/icons.rs b/crates/app/src/icons.rsindex 8cd1b915..bf7ceee8 100644--- a/crates/app/src/icons.rs+++ b/crates/app/src/icons.rs@@ -219,13 +219,26 @@ impl Icon {}}- /// The SVG for this icon, enabled (gradient) or disabled (flat grey, as IDM).- fn svg(self, enabled: bool) -> String {- let (a, b) = if enabled {- self.gradient()- } else {- ("#9f9f9f", "#9a9a9a")- };+ /// The ink's two stops, top-left to bottom-right: enabled, its gradient, one colour or+ /// the accent as the theme's icon style says; disabled, the theme's flat grey (as IDM).+ fn stops(self, enabled: bool) -> (String, String) {+ use crate::palette::{IconStyle, to_hex};+ let c = crate::theme::colors();+ if !enabled {+ return (to_hex(c.icon_disabled), to_hex(c.icon_disabled_end));+ }+ match crate::theme::current().icons {+ IconStyle::Color => {+ let (a, b) = self.gradient();+ (a.to_owned(), b.to_owned())+ }+ IconStyle::Mono => (to_hex(c.text), to_hex(c.text)),+ IconStyle::Accent => (to_hex(c.accent), to_hex(c.accent)),+ }+ }++ /// The SVG for this icon, inked from `a` to `b`.+ fn svg(self, a: &str, b: &str) -> String {format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="url(#g)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><defs><linearGradient id="g" gradientUnits="userSpaceOnUse" x1="2" y1="2" x2="22" y2="22"><stop offset="0" stop-color="{a}"/><stop offset="1" stop-color="{b}"/></linearGradient></defs>{}</svg>"#,self.body()@@ -237,15 +250,48 @@ impl Icon {}/// The icon as an image source (fileicons.rs shows Add Torrent's magnet for a .torrent).+ /// Made once per icon and ink (a theme's change makes new ones): drawing it again each frame+ /// allocates nothing.pub fn source(self, enabled: bool) -> ImageSource<'static> {- let uri = format!(- "bytes://mdm/toolbar/{}-{}.svg",- self.name(),- if enabled { "on" } else { "off" }- );- ImageSource::Bytes {- uri: uri.into(),- bytes: self.svg(enabled).into_bytes().into(),+ use crate::palette::IconStyle;+ use std::cell::RefCell;+ use std::collections::HashMap;+ type Key = (Icon, bool, IconStyle, [u8; 4], [u8; 4]);+ thread_local! {+ static MADE: RefCell<HashMap<Key, ImageSource<'static>>> = RefCell::default();}+ let c = crate::theme::colors();+ let style = crate::theme::current().icons;+ let (x, y) = match (enabled, style) {+ (false, _) => (c.icon_disabled, c.icon_disabled_end),+ (true, IconStyle::Color) => (egui::Color32::TRANSPARENT, egui::Color32::TRANSPARENT),+ (true, IconStyle::Mono) => (c.text, c.text),+ (true, IconStyle::Accent) => (c.accent, c.accent),+ };+ let key = (self, enabled, style, x.to_array(), y.to_array());+ MADE.with(|made| {+ made.borrow_mut()+ .entry(key)+ .or_insert_with(|| {+ let (a, b) = self.stops(enabled);+ // Keyed by its ink too: another theme's icon is another texture. Kept for+ // the program's life, as its texture is (a few per theme).+ let uri: &'static str = Box::leak(+ format!(+ "bytes://mdm/toolbar/{}-{}-{}{}.svg",+ self.name(),+ if enabled { "on" } else { "off" },+ a.trim_start_matches('#'),+ b.trim_start_matches('#'),+ )+ .into_boxed_str(),+ );+ ImageSource::Bytes {+ uri: uri.into(),+ bytes: egui::load::Bytes::Shared(self.svg(&a, &b).into_bytes().into()),+ }+ })+ .clone()+ })}}diff --git a/crates/app/src/langpick.rs b/crates/app/src/langpick.rsindex 04456c8a..21087bfc 100644--- a/crates/app/src/langpick.rs+++ b/crates/app/src/langpick.rs@@ -4,7 +4,7 @@//! name; typing filters the list; the arrows, Page Up/Down, Home/End move; Enter or a double//! click chooses.-use egui::{Color32, Rect, pos2, vec2};+use egui::{Rect, pos2, vec2};use crate::dialogs::{Outcome, window};use crate::winui::{self, ButtonKind, r};@@ -316,12 +316,15 @@ impl Picker {if on {clip.rect_filled(winui::rect(row), 0.0, winui::ROW_SELECTED());} else if let Some(c) =- winui::subtle_fill(winui::State::of(&resp, true), crate::theme::dark())+ winui::subtle_fill(winui::State::of(&resp, true), crate::theme::colors()){clip.rect_filled(winui::rect(row), 0.0, c);}let (fg, muted) = if on {- (Color32::WHITE, Color32::from_gray(0xe0))+ (+ winui::SELECTION_TEXT(),+ crate::theme::colors().selection_muted,+ )} else {(ink, winui::MUTED())};diff --git a/crates/app/src/list.rs b/crates/app/src/list.rsindex 7f3f971d..44b90cd2 100644--- a/crates/app/src/list.rs+++ b/crates/app/src/list.rs@@ -12,31 +12,35 @@ use crate::theme::themed;// first column at the right in a right-to-left interface).use crate::winui::{self, fill_l as fill, text_font};-pub const HEADER_H: f32 = 24.0;-pub const ROW_H: f32 = 17.0;--const fn rgb(r: u8, g: u8, b: u8) -> Color32 {- Color32::from_rgb(r, g, b)+/// The column headers' height (the theme's size; 24 in the classic look).+pub fn header_h() -> f32 {+ crate::theme::metrics().list_header+}+/// A row's height (the theme's size; 17 in the classic look).+pub fn row_h() -> f32 {+ crate::theme::metrics().list_row}++// The active theme's colours (crate::palette, #45).themed! {/// The list's border (it was #828790 in dark too): the lists' and tables' one edge.- FRAME = rgb(0x5a, 0x5a, 0x5a), rgb(0x82, 0x87, 0x90);+ FRAME => list_frame;/// Inner ring and row background.- BG = rgb(0x39, 0x39, 0x39), rgb(0xff, 0xff, 0xff);- HEADER_BG = rgb(0x19, 0x19, 0x19), rgb(0xff, 0xff, 0xff); // = winui::LIST_HEADER- HEADER_SEP = rgb(0x63, 0x63, 0x63), rgb(0xe5, 0xe5, 0xe5);+ BG => list;+ HEADER_BG => header;+ HEADER_SEP => header_sep;/// Sort indicator (an addition: IDM's header shows none).- SORTED_BG = rgb(0x26, 0x26, 0x26), rgb(0xf0, 0xf0, 0xf0);- SORT_ARROW = rgb(0xc8, 0xc8, 0xc8), rgb(0x60, 0x60, 0x60);+ SORTED_BG => sorted;+ SORT_ARROW => sort_arrow;/// Light: the one grid colour, 1 px lines (light-main.md).- GRID_H = rgb(0x55, 0x55, 0x55), rgb(0xf0, 0xf0, 0xf0);- GRID_V_RIGHT = rgb(0x55, 0x55, 0x55), rgb(0xf0, 0xf0, 0xf0);+ GRID_H => list_grid;+ GRID_V_RIGHT => list_grid;/// Selected row (list focused): Windows' accent, as every list's (one blue across MDM), with/// white text and a dotted focus outline in its inverse, #ff9933.- SELECTED = rgb(0x00, 0x78, 0xd4), rgb(0x00, 0x78, 0xd4);- TEXT = rgb(0xff, 0xff, 0xff), rgb(0x00, 0x00, 0x00);+ SELECTED => selection;+ TEXT => text;/// A filtered column's funnel.- FILTER_ON = rgb(0x60, 0xcd, 0xff), rgb(0x00, 0x78, 0xd4);+ FILTER_ON => accent;}/// Columns, by their fixed data slot in [`Row::cells`]: IDM's eight, then the user's additions:@@ -73,9 +77,6 @@ pub const DEFAULT_WIDTHS: [f32; COLS] = [/// Default display order: Source first, then IDM's, with Added after Last Try Date.const DEFAULT_ORDER: [usize; COLS] = [SOURCE, 0, 1, 2, 3, 4, 5, 6, ADDED, 7];-/// The chips' colours (white text on both).-const WEB_CHIP: Color32 = rgb(0x2e, 0x9d, 0x52);-const TORRENT_CHIP: Color32 = rgb(0x7e, 0x4f, 0xd0);const MIN_WIDTH: f32 = 16.0;/// How far from a separator a press grabs it for resizing.const GRIP: f32 = 4.0;@@ -336,9 +337,9 @@ fn keyboard(if !st.focused {return false;}- let page = ((client_h - ROW_H) / ROW_H).floor().max(1.0) as isize;+ let page = ((client_h - row_h()) / row_h()).floor().max(1.0) as isize;// The first row in view (the list scrolls by whole rows).- let top = (st.scroll / ROW_H).round() as isize;+ let top = (st.scroll / row_h()).round() as isize;let last = n as isize - 1;let cur = focus.map(|s| s as isize);let (to, mods) = ui.input(|i| {@@ -480,14 +481,14 @@ pub fn show(// content overflows the room the other one leaves.let content_w: f32 = st.shown().iter().map(|c| st.widths[*c]).sum();let (client_w, client_h) = (cr - cl + 1.0, cb - ct + 1.0);- let rows_h = rows.len() as f32 * ROW_H;+ let rows_h = rows.len() as f32 * row_h();let menu_key = keyboard(ui, st, rows, focus, client_h, &mut out);let (mut need_v, mut need_h) = (false, false);for _ in 0..2 {// An empty list has nothing to scroll to (its empty state is centred in the view).need_h =!rows.is_empty() && content_w > client_w - if need_v { scrollbar::THICK } else { 0.0 };- need_v = rows_h > client_h - HEADER_H - if need_h { scrollbar::THICK } else { 0.0 };+ need_v = rows_h > client_h - header_h() - if need_h { scrollbar::THICK } else { 0.0 };}// Inclusive right edge of the header and rows, and bottom of the rows.let rr = cr - if need_v { scrollbar::THICK } else { 0.0 };@@ -507,7 +508,7 @@ pub fn show(};// ---- header interaction ----------------------------------------------------------------- let header = Rect::from_min_max(pos2(cl, ct), pos2(rr + 1.0, ct + HEADER_H));+ let header = Rect::from_min_max(pos2(cl, ct), pos2(rr + 1.0, ct + header_h()));let hresp = ui.interact(screen(header),egui::Id::unique("list-header"),@@ -593,7 +594,10 @@ pub fn show(if let Some((col, at, _)) = funnel_click {st.filter_open = match st.filter_open {Some((c, _)) if c == col => None,- _ => Some((col, pos2(at.x.min(outer.right() - FILTER_W), ct + HEADER_H))),+ _ => Some((+ col,+ pos2(at.x.min(outer.right() - FILTER_W), ct + header_h()),+ )),};st.filter_hscroll = st.hscroll;}@@ -619,7 +623,7 @@ pub fn show(let cols = spans(st);let p_all = p.clone();let p = p.with_clip_rect(screen(header));- fill(&p, cl, ct, rr, ct + HEADER_H - 1.0, HEADER_BG());+ fill(&p, cl, ct, rr, ct + header_h() - 1.0, HEADER_BG());for (c, x0, x1) in &cols {let hovered = hresp.hover_pos()@@ -632,7 +636,7 @@ pub fn show((true, false) => winui::State::Hot,(true, true) => winui::State::Pressed,};- let tint = winui::subtle_fill(state, crate::theme::dark());+ let tint = winui::subtle_fill(state, crate::theme::colors());// The sorted column: highlighted header and a chevron at its right edge (▲ ascending,// ▼ descending).if let Some((sc, asc)) = st.sort@@ -643,21 +647,21 @@ pub fn show(*x0,ct,x1 - 1.0,- ct + HEADER_H - 1.0,+ ct + header_h() - 1.0,tint.unwrap_or(SORTED_BG()),);// At the cell's right edge, vertically centred in the header.let cx = x1 - 9.0;- let mid = ct + (HEADER_H / 2.0).floor() - 2.0;+ let mid = ct + (header_h() / 2.0).floor() - 2.0;for i in 0..4 {let y = mid + if asc { i as f32 } else { 3.0 - i as f32 };let half = i as f32;fill(&p, cx - half, y, cx + half, y, SORT_ARROW());}} else if let Some(t) = tint {- fill(&p, *x0, ct, x1 - 1.0, ct + HEADER_H - 1.0, t);+ fill(&p, *x0, ct, x1 - 1.0, ct + header_h() - 1.0, t);}- fill(&p, *x1, ct, *x1, ct + HEADER_H - 1.0, HEADER_SEP());+ fill(&p, *x1, ct, *x1, ct + header_h() - 1.0, HEADER_SEP());let mut arrow_room = if st.sort.is_some_and(|(sc, _)| sc == *c) {14.0} else {@@ -679,7 +683,7 @@ pub fn show(SORT_ARROW().gamma_multiply(0.45)};if !roomy {- p.rect_filled(screen(fr), 2.0, HEADER_BG());+ p.rect_filled(screen(fr), crate::theme::metrics().part_radius, HEADER_BG());}funnel(&p, fr, color);if roomy {@@ -700,13 +704,16 @@ pub fn show(hresp.clone().on_hover_text_at_pointer(tip);}}- let clip = p.with_clip_rect(screen(Rect::from_x_y_ranges(*x0..=*x1, ct..=ct + HEADER_H)));+ let clip = p.with_clip_rect(screen(Rect::from_x_y_ranges(+ *x0..=*x1,+ ct..=ct + header_h(),+ )));text_font(&clip, font.clone(), x0 + 6.0, ct + 15.0, &label, TEXT());}// ---- body ------------------------------------------------------------------------------let p = p_all;- let body_top = ct + HEADER_H;+ let body_top = ct + header_h();let body = Rect::from_min_max(pos2(cl, body_top), pos2(rr + 1.0, rb + 1.0));out.body = Some(body);let resp = ui.interact(@@ -730,10 +737,10 @@ pub fn show(}let bp = p.with_clip_rect(screen(body));// Fully visible rows; the list scrolls by whole rows until the last one is fully shown.- let page_rows = (body.height() / ROW_H).floor().max(1.0);- let max_scroll = (rows.len() as f32 - page_rows).max(0.0) * ROW_H;+ let page_rows = (body.height() / row_h()).floor().max(1.0);+ let max_scroll = (rows.len() as f32 - page_rows).max(0.0) * row_h();if resp.hovered() {- st.scroll += winui::wheel_rows(ui, ROW_H, page_rows) * ROW_H;+ st.scroll += winui::wheel_rows(ui, row_h(), page_rows) * row_h();st.hscroll -= ui.input(|i| i.smooth_scroll_delta.x);}// Rows out of view are there for screen readers too (#111), as many as `reachable_rows`@@ -744,25 +751,25 @@ pub fn show(.ctx().accesskit_node_builder(resp.id, |n| n.set_size_of_set(rows.len())).is_some();- let page = (body.height() / ROW_H).floor().max(1.0) as usize;- let reach = winui::reachable_rows(rows.len(), (st.scroll / ROW_H).round() as usize, page);+ let page = (body.height() / row_h()).floor().max(1.0) as usize;+ let reach = winui::reachable_rows(rows.len(), (st.scroll / row_h()).round() as usize, page);if a11y && let Some(idx) = winui::row_asked_for(ui, reach.clone(), row_id) {st.scroll_to = Some(idx);}if let Some(row) = st.scroll_to.take() {- let top = row as f32 * ROW_H;+ let top = row as f32 * row_h();if top < st.scroll {st.scroll = top;- } else if top + ROW_H > st.scroll + page_rows * ROW_H {- st.scroll = top + ROW_H - page_rows * ROW_H;+ } else if top + row_h() > st.scroll + page_rows * row_h() {+ st.scroll = top + row_h() - page_rows * row_h();}}st.scroll = st.scroll.clamp(0.0, max_scroll);st.hscroll = st.hscroll.clamp(0.0, (content_w - row_w).max(0.0)).round();- let shown_scroll = (st.scroll / ROW_H).round() * ROW_H;- let first = (shown_scroll / ROW_H).floor() as usize;+ let shown_scroll = (st.scroll / row_h()).round() * row_h();+ let first = (shown_scroll / row_h()).floor() as usize;let offset = 0.0;- let visible = (body.height() / ROW_H).ceil() as usize + 1;+ let visible = (body.height() / row_h()).ceil() as usize + 1;let last_right = cols.last().map_or(cl, |s| s.2);let mut cut_under_pointer = None;let keys_in_use = winui::keyboard_in_use(ui.ctx());@@ -779,10 +786,10 @@ pub fn show();rows_ui.set_clip_rect(Rect::NOTHING);let expose_row = |idx: usize, row: &Row, picked: bool| {- let top = body_top + (idx as f32 - first as f32) * ROW_H - offset;+ let top = body_top + (idx as f32 - first as f32) * row_h() - offset;let bounds = screen(Rect::from_min_size(pos2(cl, top),- egui::vec2(rr - cl, ROW_H),+ egui::vec2(rr - cl, row_h()),));rows_ui.interact(bounds, row_id(idx), egui::Sense::hover());let spoken = [0usize, 3, 2]@@ -824,7 +831,7 @@ pub fn show(expose_out_of_view(reach.start..reach.end.min(first));for k in 0..visible {let idx = first + k;- let top = body_top + k as f32 * ROW_H - offset;+ let top = body_top + k as f32 * row_h() - offset;if let Some(row) = rows.get(idx) {let picked = selected.get(idx).copied().unwrap_or(false);expose_row(idx, row, picked);@@ -835,18 +842,22 @@ pub fn show(if sel || has_focus {// The row above its grid line; the focused row has a dotted outline (every other// pixel), in the fill's inverse on a selected row. Both modes alike.- let (right, bottom) = (last_right - 1.0, top + ROW_H - 2.0);+ let (right, bottom) = (last_right - 1.0, top + row_h() - 2.0);if sel {fill(&bp, cl, top, right, bottom, SELECTED());}if has_focus {- let dot = if sel { rgb(0xff, 0x99, 0x33) } else { TEXT() };+ let dot = if sel {+ crate::theme::colors().selection_focus+ } else {+ TEXT()+ };dotted(&bp, cl, top, right, bottom, dot);}} else if picked {// Unfocused (Find, Properties, a menu has the keys): still shown, in the inactive// selection grey, as Explorer shows it, so what a command acts on stays visible.- let bottom = top + ROW_H - 2.0;+ let bottom = top + row_h() - 2.0;fill(&bp,cl,@@ -872,7 +883,7 @@ pub fn show(pos2(x0 + 2.0, top),);}- let cell = Rect::from_min_max(pos2(*x0, top), pos2(*x1 - 1.0, top + ROW_H));+ let cell = Rect::from_min_max(pos2(*x0, top), pos2(*x1 - 1.0, top + row_h()));if *c == SOURCE {let cut = chip(&bp.with_clip_rect(screen(cell.intersect(body))),@@ -914,7 +925,7 @@ pub fn show(// A failed download's Status and Description (the reason) in the error colour.let failed = row.status_group == "Error" && (*c == 3 || *c == 7);let ink = if sel {- Color32::WHITE+ winui::SELECTION_TEXT()} else if failed {winui::ERROR()} else {@@ -925,7 +936,7 @@ pub fn show(}// The grid line is the item's own last row (top + 16), so icons are not clipped; in// both modes (dark changes only colours).- let gy = top + ROW_H - 1.0;+ let gy = top + row_h() - 1.0;// An empty list has no grid (the empty state stands alone).if !rows.is_empty() {fill(&bp, cl, gy, rr, gy, GRID_H());@@ -946,16 +957,12 @@ pub fn show(// 2 px mark shows where it will land.if let (Some(HeaderDrag::Move { col, grab }), Some(pp)) = (st.drag, pointer) {let w = st.widths[col];- let ghost = Rect::from_min_size(pos2(pp.x - grab, ct), egui::vec2(w, HEADER_H));+ let ghost = Rect::from_min_size(pos2(pp.x - grab, ct), egui::vec2(w, header_h()));let top = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip,egui::Id::unique("col-ghost"),));- top.rect_filled(- screen(ghost),- 0.0,- Color32::from_rgba_unmultiplied(0x60, 0x60, 0x60, 160),- );+ top.rect_filled(screen(ghost), 0.0, crate::theme::colors().drag_ghost);text_font(&top,font.clone(),@@ -970,7 +977,7 @@ pub fn show(mark - 1.0,ct,mark,- ct + HEADER_H - 1.0,+ ct + header_h() - 1.0,winui::accent(),);}@@ -983,7 +990,7 @@ pub fn show(pos2(rr + 1.0, ct),pos2(cr + 1.0, rb + 1.0),));- let mut pos_rows = shown_scroll / ROW_H;+ let mut pos_rows = shown_scroll / row_h();if scrollbar::bar(ui,egui::Id::unique("list-vbar"),@@ -994,7 +1001,7 @@ pub fn show(1.0,&mut pos_rows,) {- st.scroll = pos_rows.round() * ROW_H;+ st.scroll = pos_rows.round() * row_h();ui.ctx().request_repaint();}}@@ -1028,7 +1035,7 @@ pub fn show(if !body.contains(pos) || pos.x > last_right {return None;}- let idx = ((pos.y - body_top + shown_scroll) / ROW_H).floor() as usize;+ let idx = ((pos.y - body_top + shown_scroll) / row_h()).floor() as usize;(idx < rows.len()).then_some(idx)};let mods = ui.input(|i| i.modifiers);@@ -1068,7 +1075,7 @@ pub fn show(let at = focus.map_or(body.left_top() + egui::vec2(20.0, 4.0), |f| {pos2(cl + 20.0,- (body_top + (f as f32 + 1.0) * ROW_H - shown_scroll)+ (body_top + (f as f32 + 1.0) * row_h() - shown_scroll).clamp(body.top(), body.bottom()),)});@@ -1092,7 +1099,7 @@ pub fn show(if let Some((start, add)) = st.marquee {if let Some(pp) = pointer {let dt = ui.input(|i| i.stable_dt).min(0.1);- let step = 30.0 * ROW_H * dt;+ let step = 30.0 * row_h() * dt;if pp.y < body.top() {st.scroll = (st.scroll - step).max(0.0);ui.ctx().request_repaint();@@ -1105,8 +1112,8 @@ pub fn show(let (x0, x1) = (start.x.min(now.x), start.x.max(now.x));let touches_columns = x0 <= last_right + st.hscroll && x1 >= cl + st.hscroll;let picked: Vec<usize> = if touches_columns {- let first = (y0.max(0.0) / ROW_H).floor() as usize;- let last = (y1.max(0.0) / ROW_H).floor() as usize;+ let first = (y0.max(0.0) / row_h()).floor() as usize;+ let last = (y1.max(0.0) / row_h()).floor() as usize;(first..=last.min(rows.len().saturating_sub(1))).filter(|i| *i < rows.len()).collect()@@ -1120,15 +1127,11 @@ pub fn show();let bp = p.with_clip_rect(winui::rect(body));let screen = winui::rect(screen);- bp.rect_filled(- screen,- 0.0,- Color32::from_rgba_unmultiplied(0x33, 0x99, 0xff, 0x40),- );+ bp.rect_filled(screen, 0.0, crate::theme::colors().marquee);bp.rect_stroke(screen,0.0,- egui::Stroke::new(1.0, rgb(0x33, 0x99, 0xff)),+ egui::Stroke::new(1.0, crate::theme::colors().marquee_border),egui::StrokeKind::Inside,);}@@ -1199,24 +1202,27 @@ fn chip(return false;}let fill = if label == "Torrent" {- TORRENT_CHIP+ crate::theme::colors().chip_torrent} else {- WEB_CHIP+ crate::theme::colors().chip_web};// The cell holds the English key (filters match on it); the chip shows it translated.let full = crate::i18n::t(label);// Room: the pill starts 5 px in, pads its text 6 px each side, and ends 3 px before the cell.let label = &winui::ellipsize(p, font, full, (x1 - x0 - 5.0 - 12.0 - 3.0).max(0.0));let w = winui::text_width_font(p, font.clone(), label).round();- let pill = Rect::from_min_size(pos2(x0 + 5.0, top + 2.0), egui::vec2(w + 12.0, ROW_H - 4.0));- p.rect_filled(winui::rect(pill), (ROW_H - 4.0) / 2.0, fill);+ let pill = Rect::from_min_size(+ pos2(x0 + 5.0, top + 2.0),+ egui::vec2(w + 12.0, row_h() - 4.0),+ );+ p.rect_filled(winui::rect(pill), (row_h() - 4.0) / 2.0, fill);text_font(p,font.clone(),pill.left() + 6.0,top + 12.0,label,- Color32::WHITE,+ crate::theme::colors().chip_text,);label != full}@@ -1226,7 +1232,7 @@ fn funnel_rect(st: &ListState, col: usize, x0: f32, x1: f32, ct: f32) -> Rect {let sorted = st.sort.is_some_and(|(sc, _)| sc == col);let right = x1 - if sorted { 18.0 } else { 4.0 };let left = (right - 12.0).max(x0 + 2.0);- Rect::from_min_max(pos2(left, ct + 6.0), pos2(right, ct + HEADER_H - 6.0))+ Rect::from_min_max(pos2(left, ct + 6.0), pos2(right, ct + header_h() - 6.0))}/// A small funnel: a triangle over a stem, in English rect `rc`.@@ -1268,7 +1274,7 @@ fn filter_box(ui: &mut Ui, st: &mut ListState) {// on its own funnel, whose click toggles it; so does the list scrolling sideways (it// stayed where the column was).let on_funnel =- |pp: Pos2| pp.y <= at.y && pp.y >= at.y - HEADER_H && (pp.x - at.x).abs() <= 24.0;+ |pp: Pos2| pp.y <= at.y && pp.y >= at.y - header_h() && (pp.x - at.x).abs() <= 24.0;if ui.input(|i| i.pointer.any_pressed())&& ui.ctx()diff --git a/crates/app/src/main.rs b/crates/app/src/main.rsindex cdce4f99..4f0abe12 100644--- a/crates/app/src/main.rs+++ b/crates/app/src/main.rs@@ -28,6 +28,7 @@ mod model;mod netwatch;mod options;mod pacfetch;+mod palette;mod playlistdlg;mod progress;mod properties;@@ -43,6 +44,7 @@ mod selection;mod settings;mod store;mod theme;+mod themefile;mod torrentdlg;mod torrents;mod transfer;diff --git a/crates/app/src/options.rs b/crates/app/src/options.rsindex cb981f25..8684ad92 100644--- a/crates/app/src/options.rs+++ b/crates/app/src/options.rs@@ -1498,7 +1498,7 @@ impl OptionsDialog {let color = if ok {LIGHT_TEXT()} else {- egui::Color32::from_rgb(0xC4, 0x2B, 0x1C)+ crate::theme::colors().error_strong};// Up to two lines, each cut with "..." (whole on hover) when a translation is longer.for (row, part) in line.lines().take(2).enumerate() {@@ -1635,7 +1635,7 @@ impl OptionsDialog {o.x + 21.0,o.y + 308.0,note,- egui::Color32::from_rgb(0x9D, 0x5D, 0x00),+ crate::theme::colors().warning,o.x + 404.0,14.0,);@@ -2794,7 +2794,7 @@ fn dns_dialog(ui: &mut Ui, o: Pos2, e: &mut DnsEdit) -> Outcome<()> {let color = if ok {LIGHT_TEXT()} else {- egui::Color32::from_rgb(0xC4, 0x2B, 0x1C)+ crate::theme::colors().error_strong};let (rect, cut) = winui::label_into(&p,@@ -2882,7 +2882,7 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingso + vec2(14.0, 78.0),egui::Align2::LEFT_TOP,code,- egui::FontId::monospace(22.0),+ egui::FontId::monospace(crate::theme::metrics().font_code),LIGHT_TEXT(),);// i18n: button: copy the sign-in code@@ -2982,7 +2982,7 @@ fn account_dialog(ui: &mut Ui, o: Pos2, e: &mut AccountEdit) -> Outcome<settingslet color = if ok {LIGHT_TEXT()} else {- egui::Color32::from_rgb(0xC4, 0x2B, 0x1C)+ crate::theme::colors().error_strong};let (rect, cut) = winui::label_into(&p,diff --git a/crates/app/src/palette.rs b/crates/app/src/palette.rsnew file mode 100644index 00000000..7883e838--- /dev/null+++ b/crates/app/src/palette.rs@@ -0,0 +1,521 @@+//! A theme: every colour, size and icon style the painters draw with (#45). The painters read+//! the active theme through `crate::theme::colors()` and `crate::theme::metrics()`; nothing in+//! the painting code holds a colour or a control's size of its own.+//!+//! - [`Palette`]: one variant's colours (a theme has a light and a dark one; the mode picks+//! which), by role. Each role has a stable key (`"button.hot"`), which theme files use.+//! - [`Metrics`]: the sizes a control painter owns (corner radii, border and focus widths, font+//! sizes, row heights). Where a window puts its controls stays the window's layout.+//! - [`IconStyle`]: how the toolbar's and Options' outline icons are inked.+//!+//! [`CLASSIC`] is MDM's own look (IDM's classic layout, Windows 11 controls, accent #0078D4),+//! written out with the exact values the painters had before themes: the default, unchanged.++use std::borrow::Cow;++use egui::Color32;++const fn rgb(r: u8, g: u8, b: u8) -> Color32 {+ Color32::from_rgb(r, g, b)+}+const fn grey(v: u8) -> Color32 {+ rgb(v, v, v)+}+const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color32 {+ Color32::from_rgba_unmultiplied_const(r, g, b, a)+}++/// The progress window's segment bar: 13 rows top to bottom, each row's colour for the parts+/// not downloaded yet, downloaded, and a connection's start marker.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Segments {+ pub missing: [Color32; 13],+ pub done: [Color32; 13],+ pub start: [Color32; 13],+}++/// The classic bar, measured from IDM's (spec "Segment bar"), as (missing, done, start) rows.+const SEG_ROWS: [(u32, u32, u32); 13] = [+ (0xfafafc, 0xbfc6f3, 0xf67566),+ (0xf7f8fa, 0xa4aae7, 0xf46a5e),+ (0xf5f6fa, 0x898edd, 0xf25e56),+ (0xf2f4f9, 0x7176d3, 0xef514c),+ (0xecf0f6, 0x686bcf, 0xea4240),+ (0xdbe0ee, 0x1a3cb7, 0xbb0205),+ (0xdce1f0, 0x0f43b8, 0xbe0205),+ (0xdee3f1, 0x1155bf, 0xc60b09),+ (0xdfe4f1, 0x1267c7, 0xd21913),+ (0xe1e5f1, 0x117acd, 0xde281b),+ (0xe2e7f3, 0x128ed6, 0xeb3724),+ (0xe4e8f4, 0x1aafe3, 0xf1462c),+ (0xe6e9f5, 0x2dd3f1, 0xf64f30),+];++const fn hex(v: u32) -> Color32 {+ rgb((v >> 16) as u8, (v >> 8) as u8, v as u8)+}++/// The classic segment bar; in dark mode its "not here yet" rows are the same gradient dimmed+/// (they were a bright white strip in the dark window).+const fn classic_segments(dark: bool) -> Segments {+ const fn dim(x: u8) -> u8 {+ (x as f32 * 0.22 + 22.0) as u8+ }+ let mut s = Segments {+ missing: [Color32::BLACK; 13],+ done: [Color32::BLACK; 13],+ start: [Color32::BLACK; 13],+ };+ let mut i = 0;+ while i < 13 {+ let (m, d, st) = SEG_ROWS[i];+ let m = hex(m);+ s.missing[i] = if dark {+ rgb(dim(m.r()), dim(m.g()), dim(m.b()))+ } else {+ m+ };+ s.done[i] = hex(d);+ s.start[i] = hex(st);+ i += 1;+ }+ s+}++/// Declares [`Palette`]: one `Color32` field per role, its theme-file key and what it colours,+/// with the classic dark and light values.+macro_rules! palette {+ ($($field:ident: $key:literal, $doc:literal = $dark:expr, $light:expr;)*) => {+ /// One variant's colours (light or dark), by role, plus the few switches that differ+ /// between IDM's light and dark looks.+ #[derive(Clone, Copy, Debug, PartialEq)]+ pub struct Palette {+ /// A dark surface: light-on-dark glyph rendering and the dark window caption.+ pub dark: bool,+ /// A focused text box's accent line: straight (IDM's dark look) or curving into the+ /// box's rounded corners (Windows 11's).+ pub focus_line_straight: bool,+ /// Access letters are always underlined (IDM's dark look), not only once the keyboard+ /// is in use (Windows' rule).+ pub access_keys_always: bool,+ /// The category tree's expanders: chevrons (dark look) or classic +/- boxes.+ pub tree_chevrons: bool,+ /// The progress window's segment bar.+ pub segments: Segments,+ $(#[doc = $doc] pub $field: Color32,)*+ }++ /// Every role: its key in a theme file and what it colours, in declaration order.+ // The theme picker and the themes help page (#45, next) list them.+ #[allow(dead_code)]+ pub const ROLES: &[(&str, &str)] = &[$(($key, $doc),)*];++ impl Palette {+ /// The colour of the role with this key.+ #[allow(dead_code)]+ pub fn role(&self, key: &str) -> Option<Color32> {+ match key {+ $($key => Some(self.$field),)*+ _ => None,+ }+ }++ /// Sets the role with this key; false when there is no such role.+ pub fn set_role(&mut self, key: &str, c: Color32) -> bool {+ match key {+ $($key => { self.$field = c; true })*+ _ => false,+ }+ }++ /// The classic look's dark or light variant.+ const fn classic(dark: bool) -> Self {+ Self {+ dark,+ focus_line_straight: dark,+ access_keys_always: dark,+ tree_chevrons: dark,+ segments: classic_segments(dark),+ $($field: if dark { $dark } else { $light },)*+ }+ }+ }+ };+}++palette! {+ // ---- window and text ----+ window: "window", "Windows' and dialogs' background" = grey(0x39), grey(0xf0);+ text: "text", "Text and glyphs" = grey(0xff), grey(0x00);+ text_disabled: "text.disabled", "Disabled text, the one grey of every greyed control and label" = grey(0x8a), grey(0x8a);+ muted: "text.muted", "Secondary text: notes, sizes, versions" = grey(0xa0), grey(0x6d);+ link: "link", "Text that opens something" = rgb(0x99, 0xc8, 0xff), rgb(0x00, 0x66, 0xcc);+ error: "error", "Error text" = rgb(0xff, 0x80, 0x80), rgb(0xc4, 0x2b, 0x1c);+ error_strong: "error.strong", "A failed check's message in Options (connection, browser and helper tests)" = rgb(0xc4, 0x2b, 0x1c), rgb(0xc4, 0x2b, 0x1c);+ warning: "warning", "Warning text" = rgb(0x9d, 0x5d, 0x00), rgb(0x9d, 0x5d, 0x00);+ success: "success", "Success text (a matching checksum)" = rgb(0x6c, 0xcb, 0x5f), rgb(0x0f, 0x7b, 0x0f);+ reach_near: "reach.near", "A download's server near by its round trip (under 60 ms), in Properties" = rgb(0x6c, 0xcb, 0x5f), rgb(0x10, 0x7c, 0x10);+ reach_medium: "reach.medium", "A server at a medium round trip (60 to 150 ms)" = rgb(0xf7, 0xb0, 0x40), rgb(0x9d, 0x5d, 0x00);+ reach_far: "reach.far", "A server far by its round trip (over 150 ms)" = rgb(0xff, 0x99, 0xa4), rgb(0xc4, 0x2b, 0x1c);+ flag_edge: "flag.edge", "The thin edge around a country's flag" = rgba(0x00, 0x00, 0x00, 40), rgba(0x00, 0x00, 0x00, 40);+ accent: "accent", "The accent: focus lines, open and default controls, filters, links' focus" = rgb(0x60, 0xcd, 0xff), rgb(0x00, 0x78, 0xd4);+ focus_ring: "focus.ring", "The dotted keyboard focus rectangle" = grey(0xcc), grey(0x0d);+ // ---- selection ----+ selection: "selection", "A selection's fill: rows, a chosen day, selected text" = rgb(0x00, 0x78, 0xd4), rgb(0x00, 0x78, 0xd4);+ selection_text: "selection.text", "Text on the selection" = grey(0xff), grey(0xff);+ selection_muted: "selection.muted", "Secondary text on the selection" = grey(0xe0), grey(0xe0);+ selection_inactive: "selection.inactive", "A selected row in a list without the focus" = grey(0x4a), grey(0xd9);+ selection_focus: "selection.focus", "The focused row's dotted outline on a selected row" = rgb(0xff, 0x99, 0x33), rgb(0xff, 0x99, 0x33);+ // ---- group boxes, separators, tabs ----+ group_line: "group.line", "A group box's frame" = grey(0x50), grey(0xdc);+ etch_shadow: "etch.shadow", "An etched separator's shadow line" = grey(0x22), grey(0xa0);+ etch_light: "etch.light", "An etched separator's highlight line" = grey(0x50), grey(0xff);+ tab_page: "tab.page", "A tab page's body" = grey(0x40), grey(0xf9);+ tab: "tab", "An unselected tab, and the page's shadow" = grey(0x33), grey(0xf3);+ tab_hot: "tab.hot", "A tab under the pointer" = grey(0x46), grey(0xfd);+ chevron: "chevron", "A drop-down's or spin box's arrow" = grey(0xc8), grey(0x6f);+ chevron_disabled: "chevron.disabled", "A greyed arrow" = grey(0x6a), grey(0xbe);+ // ---- parts without a face of their own ----+ subtle_hot: "subtle.hot", "A part with no face of its own (an arrow, a column header) under the pointer" = grey(0x45), grey(0xf3);+ subtle_pressed: "subtle.pressed", "Such a part pressed or open" = grey(0x26), grey(0xe8);+ highlight_hot: "highlight.hot", "A calendar's day or arrow under the pointer, a drop target" = rgb(0x2d, 0x4a, 0x60), rgb(0xe5, 0xf1, 0xfb);+ highlight_pressed: "highlight.pressed", "A calendar's day or arrow pressed" = rgb(0x23, 0x3d, 0x52), rgb(0xcc, 0xe4, 0xf7);+ // ---- text boxes ----+ field: "field", "A text box's or a list's inside" = grey(0x2b), grey(0xff);+ field_border: "field.border", "A text box's border" = grey(0x4b), grey(0xe5);+ field_bottom: "field.bottom", "A text box's bottom line while it can be typed in" = grey(0x9a), grey(0x86);+ field_disabled: "field.disabled", "A greyed text box's inside" = grey(0x33), grey(0xf9);+ field_disabled_border: "field.disabled.border", "A greyed text box's border" = grey(0x44), grey(0xe9);+ field_readonly: "field.readonly", "A read-only text box's inside" = grey(0x30), grey(0xf3);+ field_readonly_border: "field.readonly.border", "A read-only text box's border" = grey(0x4b), grey(0xe2);+ combo_chevron: "combo.chevron", "A drop-down's chevron" = grey(0x6f), grey(0x6f);+ combo_arrow_hot: "combo.arrow.hot", "An editable drop-down's arrow zone under the pointer" = grey(0xf3), grey(0xf3);+ combo_arrow_pressed: "combo.arrow.pressed", "An editable drop-down's arrow zone pressed or open" = grey(0xe8), grey(0xe8);+ // ---- buttons ----+ button: "button", "A button's face" = grey(0x44), grey(0xfd);+ button_hot: "button.hot", "A button's face under the pointer" = grey(0x4b), grey(0xf6);+ button_pressed: "button.pressed", "A button's face pressed" = grey(0x3c), grey(0xf5);+ button_border: "button.border", "A button's border" = grey(0x55), grey(0xd0);+ button_bottom: "button.bottom", "A button's bottom edge" = grey(0x4b), grey(0xba);+ button_text: "button.text", "A button's text" = grey(0xff), grey(0x00);+ button_text_pressed: "button.text.pressed", "A button's text pressed" = grey(0xc8), grey(0x5d);+ button_default_border: "button.default.border", "The default button's border" = rgb(0x60, 0xcd, 0xff), rgb(0x00, 0x78, 0xd4);+ button_default_bottom: "button.default.bottom", "The default button's bottom edge" = rgb(0x4f, 0xb5, 0xe4), rgb(0x00, 0x6b, 0xbe);+ button_disabled: "button.disabled", "A greyed button's face" = grey(0x3d), grey(0xf9);+ button_disabled_border: "button.disabled.border", "A greyed button's border" = grey(0x46), grey(0xe9);+ button_accent: "button.accent", "An accent button's face" = rgb(0x60, 0xcd, 0xff), rgb(0x00, 0x78, 0xd4);+ button_accent_hot: "button.accent.hot", "An accent button's face under the pointer" = rgb(0x5a, 0xb9, 0xe5), rgb(0x1a, 0x86, 0xd9);+ button_accent_pressed: "button.accent.pressed", "An accent button's face pressed" = rgb(0x52, 0xa6, 0xd0), rgb(0x00, 0x6c, 0xbe);+ button_accent_bottom: "button.accent.bottom", "An accent button's bottom edge" = rgb(0x4f, 0xb5, 0xe4), rgb(0x00, 0x5a, 0x9e);+ button_accent_text: "button.accent.text", "An accent button's text" = grey(0x00), grey(0xff);+ button_accent_text_pressed: "button.accent.text.pressed", "An accent button's text pressed" = grey(0x1a), rgb(0xe6, 0xf0, 0xfa);+ // ---- check boxes and radios ----+ check: "check", "An unchecked box's or radio's inside" = grey(0x2b), grey(0xf3);+ check_hot: "check.hot", "Its inside under the pointer" = grey(0x3a), grey(0xea);+ check_pressed: "check.pressed", "Its inside pressed" = grey(0x47), grey(0xdd);+ check_border: "check.border", "An unchecked box's or radio's border" = grey(0x9b), grey(0x62);+ check_border_hot: "check.border.hot", "Its border under the pointer" = grey(0xa0), grey(0x62);+ check_border_pressed: "check.border.pressed", "Its border pressed" = grey(0x70), grey(0x9a);+ check_border_disabled: "check.border.disabled", "A greyed unchecked box's border" = grey(0x5a), grey(0xc3);+ check_on: "check.on", "A checked box's or radio's accent" = rgb(0x60, 0xcd, 0xff), rgb(0x00, 0x78, 0xd4);+ check_on_hot: "check.on.hot", "The checked accent under the pointer" = rgb(0x5a, 0xbc, 0xe8), rgb(0x1a, 0x86, 0xd9);+ check_on_pressed: "check.on.pressed", "The checked accent pressed" = rgb(0x52, 0xa6, 0xcc), rgb(0x33, 0x92, 0xdc);+ check_on_disabled: "check.on.disabled", "A greyed checked box's fill" = grey(0x5a), grey(0xc3);+ check_mark: "check.mark", "The tick or dot on the checked accent" = grey(0x00), grey(0xff);+ // ---- progress and meters ----+ progress_track: "progress.track", "A progress bar's track" = grey(0x9a), grey(0x86);+ progress_bar: "progress.bar", "A progress bar's fill" = rgb(0x60, 0xcd, 0xff), rgb(0x00, 0x78, 0xd4);+ meter_track: "meter.track", "A meter's track (a download's part done)" = grey(0x2b), grey(0xe6);+ meter_edge: "meter.edge", "A meter's edge" = grey(0x4b), grey(0xbc);+ meter_fill: "meter.fill", "A meter's fill" = rgb(0x0f, 0x7b, 0x0f), rgb(0x0f, 0x7b, 0x0f);+ // ---- lists and tables ----+ list: "list", "The download list's background" = grey(0x39), grey(0xff);+ list_frame: "list.frame", "A list's, a table's or a box's outline" = grey(0x5a), rgb(0x82, 0x87, 0x90);+ grid: "grid", "Grid lines between a list's rows in dialogs" = grey(0x40), grey(0xf0);+ list_grid: "list.grid", "The download list's grid lines" = grey(0x55), grey(0xf0);+ header: "header", "Every list's and table's column headers" = grey(0x19), grey(0xff);+ header_line: "header.line", "A header's bottom line in dialogs' lists" = grey(0x4e), grey(0xe5);+ header_sep: "header.sep", "The dividers between column headers" = grey(0x63), grey(0xe5);+ table_line: "table.line", "The dividers in the link grabber's and Add torrent's tables" = grey(0x4a), grey(0xe5);+ sorted: "header.sorted", "The sorted column's header" = grey(0x26), grey(0xf0);+ sort_arrow: "header.sort-arrow", "The sort chevron" = grey(0xc8), grey(0x60);+ row_pressed: "row.pressed", "A list row pressed" = grey(0x4f), grey(0xe8);+ chip_web: "chip.web", "The download list's Web chip" = rgb(0x2e, 0x9d, 0x52), rgb(0x2e, 0x9d, 0x52);+ chip_torrent: "chip.torrent", "The download list's Torrent chip" = rgb(0x7e, 0x4f, 0xd0), rgb(0x7e, 0x4f, 0xd0);+ chip_text: "chip.text", "Text on a chip" = grey(0xff), grey(0xff);+ drag_ghost: "list.drag-ghost", "A column header being dragged" = rgba(0x60, 0x60, 0x60, 160), rgba(0x60, 0x60, 0x60, 160);+ marquee: "list.marquee", "The rubber band that selects rows" = rgba(0x33, 0x99, 0xff, 0x40), rgba(0x33, 0x99, 0xff, 0x40);+ marquee_border: "list.marquee.border", "The rubber band's edge" = rgb(0x33, 0x99, 0xff), rgb(0x33, 0x99, 0xff);+ // ---- scroll bars ----+ scroll_track: "scroll.track", "A scroll bar's track" = grey(0x17), grey(0xf0);+ scroll_corner: "scroll.corner", "Where two scroll bars meet" = grey(0x38), grey(0xf0);+ scroll_thumb: "scroll.thumb", "A scroll bar's thumb and arrows" = grey(0x95), grey(0x85);+ scroll_thumb_hot: "scroll.thumb.hot", "The thumb or an arrow under the pointer" = grey(0xb0), grey(0x70);+ scroll_thumb_pressed: "scroll.thumb.pressed", "The thumb or an arrow pressed or dragged" = grey(0xc8), grey(0x5c);+ // ---- menu bar and menus ----+ menubar: "menubar", "The menu bar" = grey(0x20), grey(0xff);+ menubar_bottom: "menubar.bottom", "The menu bar's last row" = grey(0x20), grey(0xf2);+ menubar_line: "menubar.line", "The line under the menu bar" = grey(0xf0), grey(0xf0);+ menubar_hot: "menubar.hot", "A menu title under the pointer" = grey(0x50), grey(0xf5);+ menubar_open: "menubar.open", "The open menu's title" = grey(0x50), grey(0xf9);+ menu: "menu", "A menu's background" = grey(0x2b), grey(0xf9);+ menu_item: "menu.item", "A menu item" = grey(0x2c), grey(0xf9);+ menu_hot: "menu.hot", "A menu item under the pointer" = grey(0x35), grey(0xf0);+ menu_border: "menu.border", "A menu's and a popup's frame" = grey(0x3e), grey(0xe5);+ menu_sep: "menu.sep", "A menu's separators" = grey(0x3e), grey(0xd7);+ menu_text: "menu.text", "A menu's text" = grey(0xff), grey(0x00);+ menu_glyph: "menu.glyph", "Bullets, ticks and submenu arrows" = grey(0xff), grey(0x1a);+ menu_text_disabled: "menu.text.disabled", "A greyed menu item" = grey(0x6d), grey(0x9f);+ // ---- toolbar ----+ toolbar_line: "toolbar.line", "The toolbar's top line" = grey(0xa0), grey(0xa0);+ toolbar_line_light: "toolbar.line.light", "The highlight under it" = grey(0xff), grey(0xff);+ toolbar_hot: "toolbar.hot", "A toolbar button under the pointer" = rgb(0x33, 0x41, 0x4d), rgb(0xe5, 0xf3, 0xff);+ toolbar_hot_faint: "toolbar.hot.faint", "A split button's other part while one is under the pointer" = rgb(0x37, 0x3b, 0x3f), rgb(0xf3, 0xf9, 0xff);+ toolbar_pressed: "toolbar.pressed", "A toolbar button pressed" = rgb(0x2a, 0x36, 0x40), rgb(0xcc, 0xe8, 0xff);+ toolbar_hot_edge: "toolbar.hot.edge", "A hot toolbar button's edge" = rgb(0x4d, 0x5f, 0x6e), rgb(0xcc, 0xe8, 0xff);+ toolbar_hot_border: "toolbar.hot.border", "A hot toolbar button's border (transparent: none)" = Color32::TRANSPARENT, rgb(0xcc, 0xe8, 0xff);+ toolbar_split_shadow: "toolbar.split.shadow", "A split button's divider at rest: its shadow" = grey(0x26), grey(0xc6);+ toolbar_split_light: "toolbar.split.light", "The divider's highlight" = grey(0x4d), grey(0xff);+ toolbar_text_disabled: "toolbar.text.disabled", "A greyed toolbar label" = grey(0xa0), grey(0xa0);+ toolbar_arrow: "toolbar.arrow", "A drop-down button's arrow" = grey(0xd0), grey(0x28);+ icon_disabled: "icon.disabled", "A greyed icon's ink (its start)" = grey(0x9f), grey(0x9f);+ icon_disabled_end: "icon.disabled.end", "A greyed icon's ink (its end)" = grey(0x9a), grey(0x9a);+ // ---- categories tree ----+ tree: "tree", "The categories tree's background" = grey(0x20), grey(0xff);+ tree_lines: "tree.lines", "The tree's dotted connectors" = grey(0x6d), grey(0x6d);+ tree_expander: "tree.expander", "The tree's chevrons, where the variant draws them" = grey(0xff), grey(0x1a);+ tree_frame: "tree.frame", "The categories pane's frame" = grey(0xdc), grey(0xdc);+ // ---- progress window ----+ status_value: "progress.status", "The progress window's Status value" = grey(0xff), rgb(0x00, 0x00, 0xff);+ progress_label_disabled: "progress.label.disabled", "A greyed label in the progress window" = grey(0x80), grey(0x80);+ segment_border: "segments.border", "The segment bar's frame" = rgb(0x65, 0x6b, 0x7b), rgb(0x65, 0x6b, 0x7b);+ segment_corner: "segments.corner", "The segment bar's corner pixels" = rgb(0xa2, 0xa5, 0xaf), rgb(0xa2, 0xa5, 0xaf);+ piece: "pieces.have", "A torrent piece that is here" = rgb(0x2e, 0x9d, 0x52), rgb(0x2e, 0x9d, 0x52);+ piece_partial: "pieces.partial", "A square standing for pieces partly here" = rgb(0x3a, 0x6e, 0x4b), rgb(0x9c, 0xd2, 0xae);+ piece_missing: "pieces.missing", "A piece not here yet" = grey(0x45), grey(0xd6);+ // ---- title bars we draw ----+ caption: "caption", "A title bar MDM draws itself" = grey(0x20), grey(0xff);+ caption_text: "caption.text", "Its title and glyphs" = grey(0xff), grey(0x00);+ caption_hot: "caption.hot", "A caption button under the pointer (a tint over the bar)" = rgba(0xff, 0xff, 0xff, 0x0f), rgba(0x00, 0x00, 0x00, 0x09);+ caption_pressed: "caption.pressed", "A caption button pressed (a tint over the bar)" = rgba(0xff, 0xff, 0xff, 0x0a), rgba(0x00, 0x00, 0x00, 0x06);+ caption_close: "caption.close", "Close under the pointer" = rgb(0xc4, 0x2b, 0x1c), rgb(0xc4, 0x2b, 0x1c);+ caption_close_text: "caption.close.text", "Close's glyph under the pointer" = grey(0xff), grey(0xff);+ // ---- other ----+ drop_edge: "drop-target.edge", "The drop target's edge at rest" = grey(0x8d), grey(0x8d);+ // ---- egui's own widgets (tooltips, multi-line boxes' scroll bars) ----+ egui_panel: "egui.panel", "egui's panel background" = grey(0x2b), grey(0xf0);+ egui_window: "egui.window", "Tooltips' background" = grey(0x2b), grey(0xf9);+ egui_window_border: "egui.window.border", "Tooltips' border" = grey(0x1a), grey(0xe5);+ egui_text: "egui.text", "Tooltips' text" = grey(0xf0), grey(0x00);+ egui_selection_text: "egui.selection.text", "Selected text's ink in egui's boxes" = grey(0xf0), grey(0xff);+ egui_extreme: "egui.extreme", "egui's darkest (or lightest) background" = grey(0x1a), grey(0xff);+ // Light: egui's own light values (the classic look set only the dark ones).+ egui_faint: "egui.faint", "egui's faint background" = grey(0x3e), Color32::from_rgba_premultiplied(5, 5, 5, 0);+ egui_widget: "egui.widget", "egui's widgets at rest" = grey(0x3a), grey(0xe6);+ egui_widget_border: "egui.widget.border", "Their border (transparent: none)" = grey(0x6a), Color32::TRANSPARENT;+}++/// Declares [`Metrics`]: one `f32` field per size, its theme-file key and what it sizes, with+/// the classic value.+macro_rules! metrics {+ ($($field:ident: $key:literal, $doc:literal = $value:expr;)*) => {+ /// The sizes the control painters own, in points.+ #[derive(Clone, Copy, Debug, PartialEq)]+ pub struct Metrics {+ $(#[doc = $doc] pub $field: f32,)*+ }++ /// Every size: its key in a theme file and what it sizes.+ #[allow(dead_code)]+ pub const SIZES: &[(&str, &str)] = &[$(($key, $doc),)*];++ impl Metrics {+ pub const CLASSIC: Self = Self { $($field: $value,)* };++ #[allow(dead_code)]+ pub fn get(&self, key: &str) -> Option<f32> {+ match key {+ $($key => Some(self.$field),)*+ _ => None,+ }+ }++ /// Sets the size with this key; false when there is no such size.+ pub fn set(&mut self, key: &str, v: f32) -> bool {+ match key {+ $($key => { self.$field = v; true })*+ _ => false,+ }+ }+ }+ };+}++metrics! {+ control_radius: "radius", "Corner radius of buttons, text boxes and drop-downs" = 3.0;+ part_radius: "radius.part", "Corner radius of a tinted part (an arrow zone, a spin button)" = 2.0;+ check_radius: "radius.check", "Corner radius of a check box" = 2.0;+ flyout_radius: "radius.flyout", "Corner radius of a popup in a window (a calendar, a filter box)" = 6.0;+ menu_item_radius: "radius.menu-item", "Corner radius of a menu item under the pointer" = 4.0;+ widget_radius: "radius.egui", "Corner radius of egui's own widgets" = 2.0;+ popup_radius: "radius.popup", "Corner radius of tooltips" = 4.0;+ border: "border", "Width of a control's border" = 1.0;+ focus_line: "focus-line", "Height of a focused text box's accent line" = 2.0;+ chevron_width: "chevron.width", "Stroke width of a drop-down's chevron" = 1.2;+ font_dialog: "font.dialog", "Dialog text (Tahoma in IDM's dialogs)" = 11.0;+ font_dialog_bold: "font.dialog.bold", "Options pages' titles" = 13.0;+ font_title: "font.title", "A window's headline (Tahoma Bold): the browser extension's, the helpers'" = 16.0;+ font_code: "font.code", "A sign-in code to type at a service's page" = 22.0;+ font_ui: "font.ui", "Menus and the main window's text (Segoe UI)" = 12.0;+ font_ui_bold: "font.ui.bold", "Bold headings in the main window" = 13.0;+ font_small: "font.small", "egui's small text" = 11.0;+ font_body: "font.body", "egui's body text: tooltips, multi-line boxes" = 12.0;+ font_heading: "font.heading", "egui's headings" = 16.0;+ list_row: "list.row", "Height of a row in the download list" = 17.0;+ list_header: "list.header", "Height of the download list's column headers" = 24.0;+ tooltip_width: "tooltip.width", "Where a tooltip's text wraps" = 320.0;+ tooltip_margin_x: "tooltip.margin-x", "A tooltip's left and right padding" = 9.0;+ tooltip_margin_top: "tooltip.margin-top", "A tooltip's top padding" = 6.0;+ tooltip_margin_bottom: "tooltip.margin-bottom", "A tooltip's bottom padding" = 7.0;+}++/// How the outline icons (toolbar, Options pages, helpers) are inked.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]+pub enum IconStyle {+ /// Each icon's own two-colour gradient (the classic toolbar).+ #[default]+ Color,+ /// The text colour.+ Mono,+ /// The accent.+ Accent,+}++impl IconStyle {+ pub fn from_key(s: &str) -> Option<Self> {+ match s {+ "color" | "colour" => Some(IconStyle::Color),+ "mono" => Some(IconStyle::Mono),+ "accent" => Some(IconStyle::Accent),+ _ => None,+ }+ }+}++/// A whole theme: its two variants, its sizes and its icons.+#[derive(Clone, Debug, PartialEq)]+pub struct Theme {+ /// Built-in: its fixed id; from a file: the file's name without its extension.+ pub id: Cow<'static, str>,+ /// What the theme calls itself.+ pub name: Cow<'static, str>,+ pub light: Palette,+ pub dark: Palette,+ pub metrics: Metrics,+ pub icons: IconStyle,+}++impl Theme {+ /// The variant for the mode: dark or light.+ pub fn palette(&self, dark: bool) -> &Palette {+ if dark { &self.dark } else { &self.light }+ }+}++/// The classic look, MDM's default.+pub static CLASSIC: Theme = Theme {+ id: Cow::Borrowed("classic"),+ name: Cow::Borrowed("Classic"),+ light: Palette::classic(false),+ dark: Palette::classic(true),+ metrics: Metrics::CLASSIC,+ icons: IconStyle::Color,+};++/// The built-in themes, the default first.+pub fn builtins() -> [&'static Theme; 1] {+ [&CLASSIC]+}++/// `#rrggbb` or `#rrggbbaa` (the `#` optional, as Base16 writes them) as a colour.+pub fn parse_hex(s: &str) -> Option<Color32> {+ let h = s.trim().trim_start_matches('#');+ if !h.is_ascii() || !(h.len() == 6 || h.len() == 8) {+ return None;+ }+ let byte = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).ok();+ let (r, g, b) = (byte(0)?, byte(2)?, byte(4)?);+ let a = if h.len() == 8 { byte(6)? } else { 0xff };+ Some(Color32::from_rgba_unmultiplied(r, g, b, a))+}++/// A colour as `#rrggbb`, or `#rrggbbaa` when it isn't opaque.+pub fn to_hex(c: Color32) -> String {+ let [r, g, b, a] = c.to_srgba_unmultiplied();+ if a == 0xff {+ format!("#{r:02x}{g:02x}{b:02x}")+ } else {+ format!("#{r:02x}{g:02x}{b:02x}{a:02x}")+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_role_and_size_has_one_key() {+ let mut keys: Vec<&str> = ROLES.iter().map(|(k, _)| *k).collect();+ keys.sort_unstable();+ let n = keys.len();+ keys.dedup();+ assert_eq!(keys.len(), n, "a role key is used twice");+ let mut sizes: Vec<&str> = SIZES.iter().map(|(k, _)| *k).collect();+ sizes.sort_unstable();+ let n = sizes.len();+ sizes.dedup();+ assert_eq!(sizes.len(), n, "a size key is used twice");+ for (k, _) in ROLES {+ assert!(CLASSIC.light.role(k).is_some());+ let mut p = CLASSIC.dark;+ assert!(p.set_role(k, Color32::RED));+ assert_eq!(p.role(k), Some(Color32::RED));+ }+ }++ #[test]+ fn hex_round_trips() {+ assert_eq!(parse_hex("#0078d4"), Some(rgb(0x00, 0x78, 0xd4)));+ assert_eq!(parse_hex("0078D4"), Some(rgb(0x00, 0x78, 0xd4)));+ assert_eq!(parse_hex("#33"), None);+ assert_eq!(parse_hex("#gg0000"), None);+ let c = parse_hex("#3399ff40").unwrap();+ assert_eq!(c, rgba(0x33, 0x99, 0xff, 0x40));+ assert_eq!(to_hex(rgb(0x00, 0x78, 0xd4)), "#0078d4");+ }++ /// The classic look keeps the values the painters had before themes (#45): a few anchors+ /// of each kind, so a slip in the table shows here as well as in the pixel comparison.+ #[test]+ fn classic_keeps_the_old_values() {+ let (l, d) = (&CLASSIC.light, &CLASSIC.dark);+ assert_eq!(+ (l.accent, d.accent),+ (rgb(0x00, 0x78, 0xd4), rgb(0x60, 0xcd, 0xff))+ );+ assert_eq!((l.window, d.window), (grey(0xf0), grey(0x39)));+ assert_eq!(+ (l.selection, d.selection),+ (rgb(0x00, 0x78, 0xd4), rgb(0x00, 0x78, 0xd4))+ );+ assert_eq!(+ (l.field_readonly, d.field_readonly),+ (grey(0xf3), grey(0x30))+ );+ assert_eq!(l.segments.missing[0], hex(0xfafafc));+ assert_eq!(d.segments.missing[0], rgb(77, 77, 77));+ assert!(d.dark && !l.dark);+ assert_eq!(CLASSIC.metrics.control_radius, 3.0);+ assert_eq!(CLASSIC.metrics.list_row, 17.0);+ }+}diff --git a/crates/app/src/progress.rs b/crates/app/src/progress.rsindex d75a7ff3..75641e70 100644--- a/crates/app/src/progress.rs+++ b/crates/app/src/progress.rs@@ -86,42 +86,17 @@ fn draw_caption(bar.pressed}-const fn rgb(r: u8, g: u8, b: u8) -> Color32 {- Color32::from_rgb(r, g, b)+/// A greyed label (the limits' captions while off).+fn disabled() -> Color32 {+ crate::theme::colors().progress_label_disabled}-const DISABLED: Color32 = rgb(0x80, 0x80, 0x80);-/// Segment bar interior rows (top → bottom): not downloaded, downloaded, start marker.-const SEG_ROWS: [(u32, u32, u32); 13] = [- (0xfafafc, 0xbfc6f3, 0xf67566),- (0xf7f8fa, 0xa4aae7, 0xf46a5e),- (0xf5f6fa, 0x898edd, 0xf25e56),- (0xf2f4f9, 0x7176d3, 0xef514c),- (0xecf0f6, 0x686bcf, 0xea4240),- (0xdbe0ee, 0x1a3cb7, 0xbb0205),- (0xdce1f0, 0x0f43b8, 0xbe0205),- (0xdee3f1, 0x1155bf, 0xc60b09),- (0xdfe4f1, 0x1267c7, 0xd21913),- (0xe1e5f1, 0x117acd, 0xde281b),- (0xe2e7f3, 0x128ed6, 0xeb3724),- (0xe4e8f4, 0x1aafe3, 0xf1462c),- (0xe6e9f5, 0x2dd3f1, 0xf64f30),-];--fn hex(v: u32) -> Color32 {- rgb((v >> 16) as u8, (v >> 8) as u8, v as u8)-}--/// A segment / piece bar row's colour: IDM's; in dark mode its "not here yet" rows are the-/// same gradient dimmed (they were a bright white strip in the dark window).-fn seg(v: u32, missing: bool) -> Color32 {- let c = hex(v);- if missing && crate::theme::dark() {- let dim = |x: u8| (x as f32 * 0.22 + 22.0) as u8;- rgb(dim(c.r()), dim(c.g()), dim(c.b()))- } else {- c- }+/// The segment / piece bar's 13 rows, top to bottom: (not here yet, here, a connection's+/// start), from the theme (IDM's gradients in the classic look; its dark variant dims the+/// "not here yet" rows, a bright white strip in the dark window).+fn seg_rows() -> impl Iterator<Item = (Color32, Color32, Color32)> {+ let s = &crate::theme::colors().segments;+ (0..13).map(|i| (s.missing[i], s.done[i], s.start[i]))}#[derive(Clone, Copy, PartialEq, Eq)]@@ -389,7 +364,7 @@ impl Progress {ViewportId::from_hash_of(("progress", self.id)),key,&title_now,- crate::theme::dark(),+ crate::theme::dark_surface(),!closing,);let action = match (action, self.pending_limit.take()) {@@ -628,7 +603,7 @@ impl Progress {let label = if self.limiter {winui::TEXT()} else {- DISABLED+ disabled()};winui::fit(ui,@@ -727,7 +702,11 @@ impl Progress {true,Some(525.0),);- let label = if self.up_on { winui::TEXT() } else { DISABLED };+ let label = if self.up_on {+ winui::TEXT()+ } else {+ disabled()+ };winui::fit(ui,p,@@ -1015,8 +994,8 @@ fn status_page(ui: &Ui, o: Pos2, item: &Item, snap: Option<&Snapshot>, frac: f64winui::TEXT(),);// Light mode shows the status value in pure blue (light-dialogs.md).- let vc = if label == "Status" && !crate::theme::dark() {- rgb(0x00, 0x00, 0xff)+ let vc = if label == "Status" {+ crate::theme::colors().status_value} else {winui::TEXT()};@@ -1328,7 +1307,7 @@ impl Progress {/// The segment bar as a piece map: a column is filled when the pieces under it are there.fn piece_bar(p: &egui::Painter, o: Pos2, pieces: &[bool]) {let (x0, y0) = (o.x + 17.0, o.y + 249.0);- let border = rgb(0x65, 0x6b, 0x7b);+ let border = crate::theme::colors().segment_border;fill(p, x0, y0, x0 + 512.0, y0, border);fill(p, x0, y0 + 14.0, x0 + 512.0, y0 + 14.0, border);fill(p, x0, y0, x0, y0 + 14.0, border);@@ -1350,10 +1329,10 @@ fn piece_bar(p: &egui::Painter, o: Pos2, pieces: &[bool]) {while e + 1 < 511 && have(e + 1) == on {e += 1;}- for (row, cols) in SEG_ROWS.iter().enumerate() {+ for (row, cols) in seg_rows().enumerate() {let v = if on { cols.1 } else { cols.0 };let y = y0 + 1.0 + row as f32;- fill(p, ix + c as f32, y, ix + e as f32, y, seg(v, !on));+ fill(p, ix + c as f32, y, ix + e as f32, y, v);}c = e + 1;}@@ -1389,19 +1368,8 @@ fn piece_legend(p: &egui::Painter, o: Pos2) {/// Pieces there, partly there (a square standing for several), missing.fn piece_colors() -> (Color32, Color32, Color32) {- if crate::theme::dark() {- (- rgb(0x2e, 0x9d, 0x52),- rgb(0x3a, 0x6e, 0x4b),- rgb(0x45, 0x45, 0x45),- )- } else {- (- rgb(0x2e, 0x9d, 0x52),- rgb(0x9c, 0xd2, 0xae),- rgb(0xd6, 0xd6, 0xd6),- )- }+ let c = crate::theme::colors();+ (c.piece, c.piece_partial, c.piece_missing)}/// The Pieces tab: one square per piece (or per group of pieces when there are many).@@ -1460,16 +1428,11 @@ fn table(let mut clicked = None;let outer = r(o, 17.0, 273.0, 513.0, 128.0);winui::solid(p, outer, winui::FIELD_EDGE());- let dark = crate::theme::dark();- let (bg, head, line) = if dark {- (winui::FIELD(), winui::LIST_HEADER(), rgb(0x63, 0x63, 0x63))- } else {- (- rgb(0xff, 0xff, 0xff),- winui::LIST_HEADER(),- rgb(0xe5, 0xe5, 0xe5),- )- };+ let (bg, head, line) = (+ winui::FIELD(),+ winui::LIST_HEADER(),+ crate::theme::colors().header_sep,+ );fill(p, o.x + 18.0, o.y + 274.0, o.x + 528.0, o.y + 399.0, bg);fill(p, o.x + 19.0, o.y + 275.0, o.x + 527.0, o.y + 298.0, head);for x in seps {@@ -1552,7 +1515,7 @@ fn table(/// The custom-drawn segment bar (spec "Segment bar"): 13-row gradients, red start columns.fn segment_bar(p: &egui::Painter, o: Pos2, item: &Item, snap: Option<&Snapshot>) {let (x0, y0) = (o.x + 17.0, o.y + 249.0);- let border = rgb(0x65, 0x6b, 0x7b);+ let border = crate::theme::colors().segment_border;fill(p, x0, y0, x0 + 512.0, y0, border);fill(p, x0, y0 + 14.0, x0 + 512.0, y0 + 14.0, border);fill(p, x0, y0, x0, y0 + 14.0, border);@@ -1563,27 +1526,20 @@ fn segment_bar(p: &egui::Painter, o: Pos2, item: &Item, snap: Option<&Snapshot>)(x0, y0 + 14.0),(x0 + 512.0, y0 + 14.0),] {- px(p, x, y, rgb(0xa2, 0xa5, 0xaf));+ px(p, x, y, crate::theme::colors().segment_corner);}// Paint a run of columns [a, b] with one of the three row profiles.let run = |a: f32, b: f32, which: usize| {if b < a {return;}- for (row, cols) in SEG_ROWS.iter().enumerate() {+ for (row, cols) in seg_rows().enumerate() {let c = match which {0 => cols.0,1 => cols.1,_ => cols.2,};- fill(- p,- a,- y0 + 1.0 + row as f32,- b,- y0 + 1.0 + row as f32,- seg(c, which == 0),- );+ fill(p, a, y0 + 1.0 + row as f32, b, y0 + 1.0 + row as f32, c);}};let ix = o.x + 18.0;@@ -1638,11 +1594,7 @@ fn connections(ui: &mut Ui, p: &egui::Painter, o: Pos2, snap: Option<&Snapshot>)o.y + 275.0,o.x + x,o.y + 298.0,- if crate::theme::dark() {- rgb(0x63, 0x63, 0x63)- } else {- rgb(0xe5, 0xe5, 0xe5)- },+ crate::theme::colors().header_sep,);}// Column titles end in "..." before their column's line, whole on hover; a long "N." startsdiff --git a/crates/app/src/scheduler.rs b/crates/app/src/scheduler.rsindex 2300b9d4..1c2b40ae 100644--- a/crates/app/src/scheduler.rs+++ b/crates/app/src/scheduler.rs@@ -1216,11 +1216,11 @@ fn field(p: &egui::Painter, x: f32, base: f32, s: &str, selected: bool, enabled:pos2(x + w + 1.0, base + 3.0),));if selected && enabled {- p.rect_filled(rc, 0.0, winui::SELECTION);+ p.rect_filled(rc, 0.0, winui::SELECTION());}let c = match (enabled, selected) {(false, _) => LIGHT_DISABLED(),- (true, true) => Color32::WHITE,+ (true, true) => winui::SELECTION_TEXT(),(true, false) => LIGHT_TEXT(),};text(p, x, base, s, c);@@ -1662,8 +1662,10 @@ fn date_picker(winui::tint_part(&p,drop.shrink(1.0),- winui::State::of(&drop_resp, true).open_if(open),- crate::theme::dark(),+ winui::subtle_fill(+ winui::State::of(&drop_resp, true).open_if(open),+ crate::theme::colors(),+ ),|p| winui::chevron_light(p, chevron, true),);if drop_resp.clicked() {@@ -1820,9 +1822,9 @@ fn calendar(ui: &mut Ui, key: egui::Id, under: Rect, date: NaiveDate) -> (Optionwinui::pointer_only(),);if let Some(c) =- winui::highlight_fill(winui::State::of(&r, true), crate::theme::dark())+ winui::highlight_fill(winui::State::of(&r, true), crate::theme::colors()){- p.rect_filled(winui::rect(b), 2.0, c);+ p.rect_filled(winui::rect(b), crate::theme::metrics().part_radius, c);}text(&p, b.left() + 4.0, b.top() + 12.0, glyph, LIGHT_TEXT());if r.clicked() {@@ -1861,17 +1863,17 @@ fn calendar(ui: &mut Ui, key: egui::Id, under: Rect, date: NaiveDate) -> (Optionlet chosen = day == date;let mark = winui::rect(cell.shrink(1.0));if chosen {- p.rect_filled(mark, 3.0, winui::SELECTION);+ p.rect_filled(mark, winui::control_radius(), winui::SELECTION());} else if let Some(c) =- winui::highlight_fill(winui::State::of(&r, true), crate::theme::dark())+ winui::highlight_fill(winui::State::of(&r, true), crate::theme::colors()){- p.rect_filled(mark, 3.0, c);+ p.rect_filled(mark, winui::control_radius(), c);}if day == today && !chosen {p.rect_stroke(mark,3.0,- egui::Stroke::new(1.0, winui::SELECTION),+ egui::Stroke::new(1.0, winui::SELECTION()),egui::StrokeKind::Inside,);}@@ -1879,7 +1881,7 @@ fn calendar(ui: &mut Ui, key: egui::Id, under: Rect, date: NaiveDate) -> (Optionwinui::focus_ring(&p, mark);}let c = if chosen {- Color32::WHITE+ winui::SELECTION_TEXT()} else if day.month() != month.month() {winui::TEXT_DISABLED()} else {diff --git a/crates/app/src/scrollbar.rs b/crates/app/src/scrollbar.rsindex 8e9859c2..ccb88c1f 100644--- a/crates/app/src/scrollbar.rs+++ b/crates/app/src/scrollbar.rs@@ -19,17 +19,18 @@ enum Part {pub const THICK: f32 = 17.0;use crate::theme::themed;+// The active theme's colours (crate::palette, #45).themed! {/// Light values from the light progress dialog's table (light-dialogs.md): track #f0f0f0,/// thumb #858585; corner not captured [?].- TRACK = Color32::from_gray(0x17), Color32::from_gray(0xf0);- pub CORNER = Color32::from_gray(0x38), Color32::from_gray(0xf0);- INK_C = Color32::from_gray(0x95), Color32::from_gray(0x85);+ TRACK => scroll_track;+ pub CORNER => scroll_corner;+ INK_C => scroll_thumb;/// A pressed arrow or thumb (a dragged thumb too): brighter on the dark track, darker on/// the light one, as Windows 11's bars answer a press.- INK_PRESSED = Color32::from_gray(0xc8), Color32::from_gray(0x5c);+ INK_PRESSED => scroll_thumb_pressed;/// The arrow or thumb under the pointer: between rest and pressed.- INK_HOT = Color32::from_gray(0xb0), Color32::from_gray(0x70);+ INK_HOT => scroll_thumb_hot;}/// Measured glyphs over the #17 track, columns = across the bar from v 5 (up/down) or rows =diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rsindex ef8bd448..fe77580e 100644--- a/crates/app/src/settings.rs+++ b/crates/app/src/settings.rs@@ -102,6 +102,9 @@ pub struct Settings {/// View → Always dark (#60): dark whatever the system says (a desktop that reports no/// preference, or a dark MDM on a light desktop).pub always_dark: bool,+ /// The look (#45): a built-in theme's id ("classic", the default) or a theme file's name in+ /// the data folder's `themes` folder (crate::themefile).+ pub theme: String,/// View → Draw with (#89): OpenGL or Direct3D (Windows only), used from the next start./// None: MDM's default (`renderer::DEFAULT`), which may change.pub renderer: Option<crate::renderer::Api>,@@ -338,6 +341,7 @@ impl Default for Settings {view: None,dark_mode_support: true,always_dark: false,+ theme: "classic".into(),renderer: None,limits_on: false,limits_mb: 200,diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rsindex 92a82024..6ed99752 100644--- a/crates/app/src/theme.rs+++ b/crates/app/src/theme.rs@@ -1,29 +1,129 @@-//! IDM 6.42's dark look (notes/UI.md "Live reference"), as egui visuals.+//! The look: light or dark (the mode), the active theme's colours and sizes (#45), the fonts,+//! and egui's own visuals built from them.-use egui::{Color32, CornerRadius, Stroke, Visuals};+use egui::{CornerRadius, Stroke, Visuals};-use std::sync::atomic::{AtomicBool, Ordering};+use std::cell::Cell;+use std::sync::RwLock;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};++use crate::palette::{CLASSIC, Metrics, Palette, Theme};static DARK: AtomicBool = AtomicBool::new(true);/// Is the UI in dark mode? IDM: dark when "View → Dark Mode support" is on and Windows' app-/// mode is dark (IDM 6.37); light otherwise. Painting code reads this every frame.+/// mode is dark (IDM 6.37); light otherwise. It picks the active theme's dark or light variant+/// ([`colors`]); whether that variant is a dark surface is [`dark_surface`].pub fn dark() -> bool {DARK.load(Ordering::Relaxed)}-/// Match egui's glyph rendering to the mode: dark mode thickens light-on-dark text-/// (`TwoCoverageMinusCoverageSq`), which makes black-on-white text look heavy, so light mode-/// uses plain coverage. The glyph atlas is shared, so this follows the main window's mode.+// ---- the active theme ------------------------------------------------------------------------+//+// Painters read colours and sizes hundreds of times a frame, from every window's thread: each+// thread keeps a reference to the active theme and looks again only when the generation moved+// (one atomic load per read, no lock, no allocation). A theme set from a file is leaked: it+// lives as long as the program (a few KB per change), so a reference to it never dangles.++static ACTIVE: RwLock<&'static Theme> = RwLock::new(&CLASSIC);+static GENERATION: AtomicU64 = AtomicU64::new(0);++thread_local! {+ static SEEN: Cell<(u64, &'static Theme)> = const { Cell::new((0, &CLASSIC)) };+}++/// The active theme.+pub fn current() -> &'static Theme {+ let generation = GENERATION.load(Ordering::Acquire);+ SEEN.with(|seen| {+ let (at, theme) = seen.get();+ if at == generation {+ return theme;+ }+ let theme = *ACTIVE.read().unwrap_or_else(|e| e.into_inner());+ seen.set((generation, theme));+ theme+ })+}++/// The active theme's colours in the current mode.+pub fn colors() -> &'static Palette {+ current().palette(dark())+}++/// The active theme's sizes.+pub fn metrics() -> &'static Metrics {+ ¤t().metrics+}++/// Is what is drawn now a dark surface (light text on dark)? The classic look's dark variant+/// is; a theme says for each of its variants. Glyph rendering and the window captions follow it.+pub fn dark_surface() -> bool {+ colors().dark+}++/// Makes `theme` the active one.+pub fn set(theme: Theme) {+ let theme: &'static Theme = match crate::palette::builtins()+ .into_iter()+ .find(|b| **b == theme)+ {+ Some(builtin) => builtin,+ None => Box::leak(Box::new(theme)),+ };+ *ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = theme;+ GENERATION.fetch_add(1, Ordering::AcqRel);+}++/// Makes the theme with this id the active one: a built-in, or a file in the themes folder+/// (`themefile`). `MDM_THEME`, for tests and screenshots, names one instead (an id, or a theme+/// file's path). A theme that can't be read leaves the classic look, logged. Returns what was+/// skipped or went wrong.+pub fn select(id: &str) -> Vec<String> {+ let id = std::env::var("MDM_THEME")+ .ok()+ .filter(|s| !s.is_empty())+ .unwrap_or_else(|| id.to_owned());+ if id.is_empty() || id == CLASSIC.id {+ set(CLASSIC.clone());+ 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 {+ Ok(loaded) => {+ for w in &loaded.warnings {+ tracing::warn!("theme {id}: {w}");+ }+ set(loaded.theme);+ loaded.warnings+ }+ Err(e) => {+ tracing::warn!("theme {id}: {e}; the classic look instead");+ set(CLASSIC.clone());+ vec![e]+ }+ }+}++/// Match egui's glyph rendering to the surface: a dark one thickens light-on-dark text+/// (`TwoCoverageMinusCoverageSq`), which makes black-on-white text look heavy, so a light one+/// uses plain coverage. The glyph atlas is shared, so this follows the main window's.pub fn apply_mode(ctx: &egui::Context) {- let tf = if dark() {+ let dark_surface = dark_surface();+ let tf = if dark_surface {egui::epaint::FontColorTransferFunction::DARK_MODE_DEFAULT} else {egui::epaint::FontColorTransferFunction::LIGHT_MODE_DEFAULT};ctx.all_styles_mut(|s| s.visuals.text_options.color_transfer_function = tf);// eframe applies egui's theme preference to every window's caption; keep it in step so it- // doesn't reset the captions to the system theme.+ // doesn't reset the captions to the system theme. egui's dark or light style is the mode's+ // variant (`apply_theme` puts each variant into its egui theme).ctx.set_theme(if dark() {egui::ThemePreference::Dark} else {@@ -32,7 +132,7 @@ pub fn apply_mode(ctx: &egui::Context) {// The window's own theme (caption, DWM): otherwise winit follows the system theme.ctx.send_viewport_cmd_to(egui::ViewportId::ROOT,- egui::ViewportCommand::SetTheme(system_theme(dark())),+ egui::ViewportCommand::SetTheme(system_theme(dark_surface)),);}@@ -70,23 +170,19 @@ fn wanted(dark_mode_support: bool, always_dark: bool, system_dark: bool) -> boolalways_dark || (dark_mode_support && system_dark)}-/// Colours that differ between IDM's dark and light modes: each becomes a function of the-/// current mode, `dark()` (main-window.md, menus.md; light-main.md, light-dialogs.md).+/// A module's names for the active theme's colours: `pub NAME => role;` becomes `NAME()`, the+/// role's colour in the current mode ([`colors`]).macro_rules! themed {- ($($(#[$m:meta])* $vis:vis $name:ident = $dark:expr, $light:expr;)*) => {$(+ ($($(#[$m:meta])* $vis:vis $name:ident => $role:ident;)*) => {$($(#[$m])*#[allow(non_snake_case)]- $vis fn $name() -> Color32 {- if $crate::theme::dark() { $dark } else { $light }+ $vis fn $name() -> egui::Color32 {+ $crate::theme::colors().$role})*};}pub(crate) use themed;-pub const WINDOW: Color32 = Color32::from_rgb(0x2b, 0x2b, 0x2b);-pub const LIST_ALT: Color32 = Color32::from_rgb(0x3e, 0x3e, 0x3e);-pub const TEXT: Color32 = Color32::from_rgb(0xf0, 0xf0, 0xf0);-/// The system's fonts for the scripts the UI font lacks (D-019; nothing bundled): a key, the/// files to try (in the fonts folder), the interface languages that need it. CJK fonts are large/// (13–20 MB), so only the interface language's are loaded, and all of them while the language@@ -423,14 +519,20 @@ fn fonts(ctx: &egui::Context, code: &str, all: bool) {}}ctx.set_fonts(defs);+ text_styles(ctx);+}++/// egui's text sizes from the theme (tooltips, multi-line boxes).+fn text_styles(ctx: &egui::Context) {+ let m = metrics();ctx.all_styles_mut(|s| {use egui::{FontId, TextStyle};s.text_styles = [- (TextStyle::Small, FontId::proportional(11.0)),- (TextStyle::Body, FontId::proportional(12.0)),- (TextStyle::Button, FontId::proportional(12.0)),- (TextStyle::Monospace, FontId::monospace(12.0)),- (TextStyle::Heading, FontId::proportional(16.0)),+ (TextStyle::Small, FontId::proportional(m.font_small)),+ (TextStyle::Body, FontId::proportional(m.font_body)),+ (TextStyle::Button, FontId::proportional(m.font_body)),+ (TextStyle::Monospace, FontId::monospace(m.font_body)),+ (TextStyle::Heading, FontId::proportional(m.font_heading)),].into();});@@ -442,67 +544,59 @@ pub fn apply(ctx: &egui::Context) {// (egui gives it up after 0.8 s).ctx.options_mut(|o| o.input_options.max_click_duration = f64::INFINITY);egui_extras::install_image_loaders(ctx);- let mut v = Visuals::dark();- v.panel_fill = WINDOW;- v.window_fill = WINDOW;- v.extreme_bg_color = Color32::from_rgb(0x1a, 0x1a, 0x1a);- v.faint_bg_color = LIST_ALT;- v.override_text_color = Some(TEXT);- v.selection.bg_fill = crate::winui::SELECTION;- v.selection.stroke = Stroke::new(1.0, TEXT);- // Square-ish Windows controls rather than egui's rounded ones.- let r = CornerRadius::same(2);- for w in [- &mut v.widgets.noninteractive,- &mut v.widgets.inactive,- &mut v.widgets.hovered,- &mut v.widgets.active,- &mut v.widgets.open,- ] {- w.corner_radius = r;- }- v.widgets.inactive.bg_fill = Color32::from_rgb(0x3a, 0x3a, 0x3a);- v.widgets.inactive.weak_bg_fill = Color32::from_rgb(0x3a, 0x3a, 0x3a);- v.widgets.inactive.bg_stroke = Stroke::new(1.0, Color32::from_rgb(0x6a, 0x6a, 0x6a));- v.window_corner_radius = CornerRadius::same(0);- // Each egui theme its own visuals (the mode switches between them): set into the theme- // current at start only, the other side kept egui's stock look, and which one depended on- // the system's mode at launch (tooltips, a multi-line box's scroll bar).- ctx.set_visuals_of(egui::Theme::Dark, v);- let mut l = Visuals::light();- l.panel_fill = Color32::from_gray(0xf0);- l.window_fill = Color32::from_gray(0xf9);- l.override_text_color = Some(Color32::BLACK);- l.selection.bg_fill = crate::winui::SELECTION;- l.selection.stroke = Stroke::new(1.0, Color32::WHITE);- for w in [- &mut l.widgets.noninteractive,- &mut l.widgets.inactive,- &mut l.widgets.hovered,- &mut l.widgets.active,- &mut l.widgets.open,- ] {- w.corner_radius = r;- }- l.window_corner_radius = CornerRadius::same(0);- // Tooltips as Windows 11's: 4 px corners, a hairline border, roomy padding, wrapped at- // 320 px.- l.menu_corner_radius = CornerRadius::same(4);- l.window_stroke = Stroke::new(1.0, Color32::from_gray(0xe5));- ctx.set_visuals_of(egui::Theme::Light, l);- ctx.style_mut_of(egui::Theme::Dark, |s| {- s.visuals.menu_corner_radius = CornerRadius::same(4);- s.visuals.window_stroke = Stroke::new(1.0, Color32::from_gray(0x1a));- });+ apply_theme(ctx);+}++/// egui's own visuals from the active theme: each variant into its egui theme (the mode+/// switches between them), so tooltips and a multi-line box's scroll bar follow the theme too.+pub fn apply_theme(ctx: &egui::Context) {+ let theme = current();+ let m = &theme.metrics;+ let radius = |r: f32| CornerRadius::same(r.round().clamp(0.0, 255.0) as u8);+ let visuals = |base: Visuals, c: &Palette| {+ let mut v = base;+ v.panel_fill = c.egui_panel;+ v.window_fill = c.egui_window;+ v.extreme_bg_color = c.egui_extreme;+ v.faint_bg_color = c.egui_faint;+ v.override_text_color = Some(c.egui_text);+ v.selection.bg_fill = c.selection;+ v.selection.stroke = Stroke::new(1.0, c.egui_selection_text);+ // Square-ish Windows controls rather than egui's rounded ones.+ for w in [+ &mut v.widgets.noninteractive,+ &mut v.widgets.inactive,+ &mut v.widgets.hovered,+ &mut v.widgets.active,+ &mut v.widgets.open,+ ] {+ w.corner_radius = radius(m.widget_radius);+ }+ v.widgets.inactive.bg_fill = c.egui_widget;+ v.widgets.inactive.weak_bg_fill = c.egui_widget;+ // Transparent: egui's own (light widgets have none).+ if c.egui_widget_border != egui::Color32::TRANSPARENT {+ v.widgets.inactive.bg_stroke = Stroke::new(1.0, c.egui_widget_border);+ }+ v.window_corner_radius = CornerRadius::same(0);+ // Tooltips as Windows 11's: rounded corners, a hairline border, roomy padding.+ v.menu_corner_radius = radius(m.popup_radius);+ v.window_stroke = Stroke::new(1.0, c.egui_window_border);+ v+ };+ ctx.set_visuals_of(egui::Theme::Dark, visuals(Visuals::dark(), &theme.dark));+ ctx.set_visuals_of(egui::Theme::Light, visuals(Visuals::light(), &theme.light));+ let margin = |v: f32| v.round().clamp(0.0, 127.0) as i8;ctx.all_styles_mut(|s| {- s.spacing.tooltip_width = 320.0;+ s.spacing.tooltip_width = m.tooltip_width;s.spacing.menu_margin = egui::Margin {- left: 9,- right: 9,- top: 6,- bottom: 7,+ left: margin(m.tooltip_margin_x),+ right: margin(m.tooltip_margin_x),+ top: margin(m.tooltip_margin_top),+ bottom: margin(m.tooltip_margin_bottom),};});+ text_styles(ctx);}#[cfg(test)]diff --git a/crates/app/src/themefile.rs b/crates/app/src/themefile.rsnew file mode 100644index 00000000..aff7a23d--- /dev/null+++ b/crates/app/src/themefile.rs@@ -0,0 +1,401 @@+//! Theme files (#45): TOML or JSON in the data folder's `themes` folder, read into a+//! [`Theme`](crate::palette::Theme). A file names only what it changes; the rest comes from the+//! theme it `inherits` (a built-in's id or another file's name; the classic look by default).+//!+//! ```toml+//! name = "My theme"+//! inherits = "classic"+//! icons = "mono" # color | mono | accent+//!+//! [sizes]+//! radius = 4+//!+//! [colors] # both variants+//! accent = "#2f7d32"+//!+//! [light] # the light variant only+//! window = "#f3f3f3"+//!+//! [dark] # the dark variant only+//! window = "#202020"+//! "segments.done" = "#3fa864" # one colour, or a list of 13 (top to bottom)+//! ```+//!+//! 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.++use std::path::{Path, PathBuf};++use serde_json::Value;++use crate::palette::{self, IconStyle, Palette, Theme};++/// A theme read from a file, with what in it was skipped.+#[derive(Debug)]+pub struct Loaded {+ pub theme: Theme,+ pub warnings: Vec<String>,+}++/// Where theme files are: the data folder's `themes` (portable copies' next to the program,+/// `MDM_DATA_DIR`'s in tests). None when there is no data folder (built-ins only).+pub fn dir() -> Option<PathBuf> {+ mdm_ipc::data_dir().map(|d| d.join("themes"))+}++/// A theme the user can pick: a built-in, or a file in [`dir`].+// The theme picker (#45, next) lists them.+#[allow(dead_code)]+#[derive(Clone, Debug, PartialEq)]+pub struct Entry {+ pub id: String,+ pub name: String,+ /// The file, for a theme from one.+ 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).+#[allow(dead_code)]+pub fn list() -> Vec<Entry> {+ let mut out: Vec<Entry> = palette::builtins()+ .iter()+ .map(|t| Entry {+ id: t.id.to_string(),+ name: t.name.to_string(),+ path: None,+ })+ .collect();+ let mut files: Vec<(String, PathBuf)> = dir()+ .and_then(|d| std::fs::read_dir(d).ok())+ .into_iter()+ .flatten()+ .flatten()+ .filter_map(|e| {+ let path = e.path();+ let id = theme_id(&path)?;+ Some((id, path))+ })+ .collect();+ files.sort();+ for (id, path) in files {+ if out.iter().any(|e| e.id == id) {+ continue;+ }+ // The name the file gives itself, else its file name.+ 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))+ .unwrap_or_else(|| id.clone());+ out.push(Entry {+ id,+ name,+ path: Some(path),+ });+ }+ out+}++/// A theme file's id: its name without `.toml` or `.json`; 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" {+ return None;+ }+ Some(path.file_stem()?.to_str()?.to_owned())+}++/// 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();+ load_in(&folder, id, 0)+}++/// The theme in this file (the themes it inherits from beside it).+pub fn load_file(path: &Path) -> Result<Loaded, String> {+ let id =+ theme_id(path).ok_or_else(|| format!("{}: not a .toml or .json file", path.display()))?;+ load_in(path.parent().unwrap_or(Path::new(".")), &id, 0)+}++/// [`load`] from `folder`, `depth` themes down an `inherits` chain.+fn load_in(folder: &Path, id: &str, depth: usize) -> Result<Loaded, String> {+ if let Some(t) = palette::builtins().into_iter().find(|t| t.id == id) {+ return Ok(Loaded {+ theme: t.clone(),+ warnings: Vec::new(),+ });+ }+ if depth > 8 {+ return Err(format!("{id}: too many themes inherit one another"));+ }+ let path = ["toml", "json"]+ .iter()+ .map(|ext| folder.join(format!("{id}.{ext}")))+ .find(|p| p.is_file())+ .ok_or_else(|| format!("{id}: no such theme"))?;+ let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;+ let value = read_value(&path, &text)?;+ parse(id, &value, |base| load_in(folder, base, depth + 1))+}++/// 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+ .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()))+ } else {+ toml::from_str(text).map_err(|e| format!("{}: {e}", path.display()))+ }+}++/// A theme from a file's value tree; `base` loads the theme it inherits.+pub fn parse(+ id: &str,+ v: &Value,+ base: impl FnOnce(&str) -> Result<Loaded, String>,+) -> Result<Loaded, String> {+ let top = v+ .as_object()+ .ok_or_else(|| format!("{id}: a theme is a table of keys"))?;+ let mut warnings = Vec::new();+ let inherits = match top.get("inherits") {+ None => "classic",+ Some(Value::String(s)) => s.as_str(),+ Some(_) => return Err(format!("{id}: inherits names a theme")),+ };+ if inherits == id {+ return Err(format!("{id}: a theme can't inherit itself"));+ }+ let Loaded {+ mut theme,+ warnings: inherited,+ } = base(inherits)?;+ warnings.extend(inherited);+ theme.id = id.to_owned().into();+ theme.name = match top.get("name").and_then(Value::as_str) {+ Some(n) => n.to_owned().into(),+ None => id.to_owned().into(),+ };+ for (key, value) in top {+ match key.as_str() {+ "name" | "inherits" => {}+ "icons" => match value.as_str().and_then(IconStyle::from_key) {+ Some(s) => theme.icons = s,+ None => warnings.push(format!("icons: {value} is not color, mono or accent")),+ },+ "sizes" => sizes(value, &mut theme, &mut warnings),+ "colors" | "colours" => {+ colors(key, value, &mut theme.light, &mut warnings);+ colors(key, value, &mut theme.dark, &mut warnings);+ }+ "light" => colors(key, value, &mut theme.light, &mut warnings),+ "dark" => colors(key, value, &mut theme.dark, &mut warnings),+ _ => warnings.push(format!("{key}: not a theme key")),+ }+ }+ Ok(Loaded { theme, warnings })+}++fn sizes(v: &Value, theme: &mut Theme, warnings: &mut Vec<String>) {+ let Some(table) = v.as_object() else {+ warnings.push("sizes: not a table".into());+ return;+ };+ for (key, value) in table {+ match value.as_f64() {+ // A size from 0 to 400 points (a tooltip's width is the largest).+ Some(n) if (0.0..=400.0).contains(&n) => {+ if !theme.metrics.set(key, n as f32) {+ warnings.push(format!("sizes.{key}: not a size"));+ }+ }+ _ => warnings.push(format!("sizes.{key}: {value} is not a size")),+ }+ }+}++/// A `[colors]`, `[light]` or `[dark]` table into `pal`.+fn colors(table_name: &str, v: &Value, pal: &mut Palette, warnings: &mut Vec<String>) {+ let Some(table) = v.as_object() else {+ warnings.push(format!("{table_name}: not a table"));+ return;+ };+ for (key, value) in table {+ let flag = match key.as_str() {+ "dark" => Some(&mut pal.dark),+ "focus-line-straight" => Some(&mut pal.focus_line_straight),+ "access-keys-always" => Some(&mut pal.access_keys_always),+ "tree-chevrons" => Some(&mut pal.tree_chevrons),+ _ => None,+ };+ if let Some(flag) = flag {+ match value.as_bool() {+ Some(b) => *flag = b,+ None => warnings.push(format!("{table_name}.{key}: true or false")),+ }+ continue;+ }+ let rows = match key.as_str() {+ "segments.missing" => Some(&mut pal.segments.missing),+ "segments.done" => Some(&mut pal.segments.done),+ "segments.start" => Some(&mut pal.segments.start),+ _ => None,+ };+ if let Some(rows) = rows {+ if !gradient(value, rows) {+ warnings.push(format!(+ "{table_name}.{key}: one colour or a list of 13 colours"+ ));+ }+ continue;+ }+ match value.as_str().and_then(palette::parse_hex) {+ Some(c) => {+ if !pal.set_role(key, c) {+ warnings.push(format!("{table_name}.{key}: not a colour role"));+ }+ }+ None => warnings.push(format!(+ "{table_name}.{key}: {value} is not a colour (#rrggbb or #rrggbbaa)"+ )),+ }+ }+}++/// One colour for every row, or 13 colours top to bottom.+fn gradient(v: &Value, rows: &mut [egui::Color32; 13]) -> bool {+ if let Some(c) = v.as_str().and_then(palette::parse_hex) {+ *rows = [c; 13];+ return true;+ }+ let Some(list) = v.as_array().filter(|l| l.len() == 13) else {+ return false;+ };+ let parsed: Option<Vec<_>> = list+ .iter()+ .map(|c| c.as_str().and_then(palette::parse_hex))+ .collect();+ match parsed {+ Some(cs) => {+ rows.copy_from_slice(&cs);+ true+ }+ None => false,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::palette::CLASSIC;+ use egui::Color32;++ fn toml_theme(id: &str, text: &str) -> Result<Loaded, String> {+ let v: Value = toml::from_str(text).map_err(|e| e.to_string())?;+ parse(id, &v, |base| load_in(Path::new("nowhere"), base, 1))+ }++ #[test]+ fn a_file_changes_only_what_it_names() {+ let l = toml_theme(+ "mine",+ r##"+ name = "Mine"+ icons = "mono"+ [sizes]+ radius = 5+ "list.row" = 20+ [colors]+ accent = "#2f7d32"+ [dark]+ window = "202020"+ "segments.done" = "#3fa864"+ "##,+ )+ .unwrap();+ assert!(l.warnings.is_empty(), "{:?}", l.warnings);+ let t = l.theme;+ assert_eq!((t.id.as_ref(), t.name.as_ref()), ("mine", "Mine"));+ assert_eq!(t.icons, IconStyle::Mono);+ assert_eq!(t.metrics.control_radius, 5.0);+ assert_eq!(t.metrics.list_row, 20.0);+ assert_eq!(t.metrics.font_dialog, CLASSIC.metrics.font_dialog);+ let green = Color32::from_rgb(0x2f, 0x7d, 0x32);+ assert_eq!((t.light.accent, t.dark.accent), (green, green));+ assert_eq!(t.dark.window, Color32::from_gray(0x20));+ assert_eq!(t.light.window, CLASSIC.light.window);+ assert_eq!(+ t.dark.segments.done,+ [Color32::from_rgb(0x3f, 0xa8, 0x64); 13]+ );+ assert_eq!(t.dark.text, CLASSIC.dark.text);+ }++ #[test]+ fn json_reads_the_same() {+ let v: Value = serde_json::from_str(+ r##"{ "name": "J", "light": { "accent": "#ff0000", "dark": true } }"##,+ )+ .unwrap();+ let l = parse("j", &v, |b| load_in(Path::new("nowhere"), b, 1)).unwrap();+ assert_eq!(l.theme.light.accent, Color32::RED);+ assert!(l.theme.light.dark);+ }++ #[test]+ fn unknown_keys_and_bad_values_are_warnings() {+ let l = toml_theme(+ "w",+ r##"+ future = 1+ icons = "sparkly"+ [sizes]+ nope = 3+ radius = -1+ [light]+ "no.such.role" = "#000000"+ text = "black"+ "segments.missing" = ["#000000"]+ dark = "yes"+ "##,+ )+ .unwrap();+ assert_eq!(l.warnings.len(), 8, "{:?}", l.warnings);+ assert_eq!(l.theme.light, CLASSIC.light);+ assert_eq!(l.theme.metrics, CLASSIC.metrics);+ }++ #[test]+ fn broken_files_and_loops_are_errors() {+ assert!(toml_theme("x", "name = ").is_err());+ assert!(toml_theme("x", r#"inherits = "x""#).is_err());+ assert!(toml_theme("x", r#"inherits = "not-there""#).is_err());+ }++ #[test]+ fn files_in_the_folder_inherit_one_another() {+ let dir = std::env::temp_dir().join(format!("mdm-themes-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("base.toml"), "[colors]\naccent = \"#112233\"\n").unwrap();+ std::fs::write(+ dir.join("child.json"),+ r##"{ "inherits": "base", "dark": { "text": "#eeeeee" } }"##,+ )+ .unwrap();+ std::fs::write(dir.join("a.toml"), "inherits = \"b\"").unwrap();+ std::fs::write(dir.join("b.toml"), "inherits = \"a\"").unwrap();+ let t = load_in(&dir, "child", 0).unwrap().theme;+ assert_eq!(t.light.accent, Color32::from_rgb(0x11, 0x22, 0x33));+ assert_eq!(t.dark.text, Color32::from_gray(0xee));+ assert_eq!(load_file(&dir.join("child.json")).unwrap().theme, t);+ assert!(load_file(&dir.join("child.txt")).is_err());+ assert!(load_in(&dir, "a", 0).is_err());+ assert_eq!(load_in(&dir, "classic", 0).unwrap().theme, CLASSIC);+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/app/src/torrentdlg.rs b/crates/app/src/torrentdlg.rsindex 4a62ce0a..b041fa4f 100644--- a/crates/app/src/torrentdlg.rs+++ b/crates/app/src/torrentdlg.rs@@ -25,12 +25,8 @@ type Slot = Arc<Mutex<Option<Result<Meta, String>>>>;crate::theme::themed! {// The lists' header colour (winui::LIST_HEADER).- LIST_HEAD = rgb(0x19, 0x19, 0x19), rgb(0xff, 0xff, 0xff);- LIST_LINE = rgb(0x4a, 0x4a, 0x4a), rgb(0xe5, 0xe5, 0xe5);-}--const fn rgb(r: u8, g: u8, b: u8) -> Color32 {- Color32::from_rgb(r, g, b)+ LIST_HEAD => header;+ LIST_LINE => table_line;}/// What Download Now / Later adds.diff --git a/crates/app/src/whereis.rs b/crates/app/src/whereis.rsindex 974e7a7c..ffe6b556 100644--- a/crates/app/src/whereis.rs+++ b/crates/app/src/whereis.rs@@ -67,14 +67,11 @@ fn reach_word(r: Reach) -> &'static str {}fn reach_colour(r: Reach) -> Color32 {- let dark = crate::theme::dark();- match (r, dark) {- (Reach::Near, false) => Color32::from_rgb(0x10, 0x7C, 0x10),- (Reach::Near, true) => Color32::from_rgb(0x6C, 0xCB, 0x5F),- (Reach::Medium, false) => Color32::from_rgb(0x9D, 0x5D, 0x00),- (Reach::Medium, true) => Color32::from_rgb(0xF7, 0xB0, 0x40),- (Reach::Far, false) => Color32::from_rgb(0xC4, 0x2B, 0x1C),- (Reach::Far, true) => Color32::from_rgb(0xFF, 0x99, 0xA4),+ let c = crate::theme::colors();+ match r {+ Reach::Near => c.reach_near,+ Reach::Medium => c.reach_medium,+ Reach::Far => c.reach_far,}}@@ -219,7 +216,7 @@ pub fn line(ui: &Ui, x: f32, baseline: f32, right: f32, seen: Option<&Seen>, id:p.rect_stroke(rc,0.0,- egui::Stroke::new(1.0, Color32::from_black_alpha(40)),+ egui::Stroke::new(1.0, crate::theme::colors().flag_edge),egui::StrokeKind::Inside,);shown = Some(rc);diff --git a/crates/app/src/winui.rs b/crates/app/src/winui.rsindex 38d0f124..260a24f6 100644--- a/crates/app/src/winui.rs+++ b/crates/app/src/winui.rs@@ -8,37 +8,48 @@ use egui::{};use unicode_segmentation::UnicodeSegmentation;-const fn rgb(r: u8, g: u8, b: u8) -> Color32 {- Color32::from_rgb(r, g, b)-}-+// Every colour comes from the active theme (crate::palette, #45): these names are its roles.crate::theme::themed! {/// Dialog background (light: light-dialogs.md).- pub BG = rgb(0x39, 0x39, 0x39), rgb(0xf0, 0xf0, 0xf0);- pub TEXT = rgb(0xff, 0xff, 0xff), rgb(0x00, 0x00, 0x00);+ pub BG => window;+ pub TEXT => text;/// A group box's frame (it was #dcdcdc in dark too: brighter than the separators in it).- pub GROUP_LINE = rgb(0x50, 0x50, 0x50), rgb(0xdc, 0xdc, 0xdc);+ pub GROUP_LINE => group_line;/// A list's column headers (the main list's): every list and table has the same (they had/// four: none, #f3f3f3, white).- pub LIST_HEADER = rgb(0x19, 0x19, 0x19), rgb(0xff, 0xff, 0xff);- /// Light: embossed #a0a0a0 statics (drawn flat here).+ pub LIST_HEADER => header;/// Disabled text, the one grey of every control and label (there were five).- pub TEXT_DISABLED = rgb(0x8a, 0x8a, 0x8a), rgb(0x8a, 0x8a, 0x8a);- /// A greyed text box's text (dark: #8a8a8a, readable on the dark dialog; #6d6d6d was not).- pub EDIT_TEXT_DISABLED = rgb(0x8a, 0x8a, 0x8a), rgb(0x8a, 0x8a, 0x8a);+ pub TEXT_DISABLED => text_disabled;+ /// A greyed text box's text.+ pub EDIT_TEXT_DISABLED => text_disabled;+ /// A selection's fill (rows, a chosen day, selected text): Windows' accent by default.+ pub SELECTION => selection;+ /// Text on the selection.+ pub SELECTION_TEXT => selection_text;}-/// A selection's fill (rows, a chosen day, selected text): Windows' accent, white text on it.-pub const SELECTION: Color32 = rgb(0x00, 0x78, 0xd4);-/// Tahoma −11 ("MS Shell Dlg 2", 8 pt): every dialog body text.pub fn tahoma() -> FontId {- FontId::new(11.0, FontFamily::Name("tahoma".into()))+ FontId::new(+ crate::theme::metrics().font_dialog,+ FontFamily::Name("tahoma".into()),+ )}/// Tahoma Bold −13: the Options pages' header titles.pub fn tahoma_bold() -> FontId {- FontId::new(13.0, FontFamily::Name("tahoma-bold".into()))+ FontId::new(+ crate::theme::metrics().font_dialog_bold,+ FontFamily::Name("tahoma-bold".into()),+ )+}++/// Tahoma Bold −16: a window's headline (the browser extension's, the helpers').+pub fn tahoma_title() -> FontId {+ FontId::new(+ crate::theme::metrics().font_title,+ FontFamily::Name("tahoma-bold".into()),+ )}/// Tahoma (IDM's dialogs), Tahoma Bold and Arial Bold from Windows' fonts folder. A family@@ -240,7 +251,7 @@ pub fn banner(.paint_at(ui, r(o, 18.0, 18.0, 48.0, 48.0));// The headline on one line: cut with "..." at the far edge (a long translation), whole on// hover.- let bold = FontId::new(16.0, FontFamily::Name("tahoma-bold".into()));+ let bold = tahoma_title();let shown = ellipsize(p, &bold, headline, w - 18.0 - 80.0);let drawn = text_font(p, bold, o.x + 80.0, o.y + 36.0, &shown, TEXT());if shown != headline {@@ -315,12 +326,15 @@ fn name_from_caption(resp: &Response) {/// Segoe UI −12: menu bar, toolbar labels.pub fn segoe() -> FontId {- FontId::proportional(12.0)+ FontId::proportional(crate::theme::metrics().font_ui)}/// Arial Bold −13: the Categories close "x".pub fn arial_bold() -> FontId {- FontId::new(13.0, FontFamily::Name("arial-bold".into()))+ FontId::new(+ crate::theme::metrics().font_ui_bold,+ FontFamily::Name("arial-bold".into()),+ )}/// Like [`text`] in any font.@@ -680,12 +694,8 @@ fn no_line_start(c: char) -> bool {/// `fraction`; while the total is unknown (`None`) a segment runs along it (`time`: seconds,/// for its place).pub fn progress_bar(p: &Painter, rc: Rect, fraction: Option<f32>, time: f64) {- let dark = crate::theme::dark();- let (track, accent) = if dark {- (rgb(0x9a, 0x9a, 0x9a), rgb(0x60, 0xcd, 0xff))- } else {- (rgb(0x86, 0x86, 0x86), rgb(0x00, 0x78, 0xd4))- };+ let c = crate::theme::colors();+ let (track, accent) = (c.progress_track, c.progress_bar);let r = rc.height() / 2.0;// The track is a 1 px line through the middle, as Windows 11 draws it.let mid = rc.center().y;@@ -1345,9 +1355,10 @@ pub fn row_list(} else {// Hot, and pressed lighter still on a dark field (subtle_fill's pressed grey was the// dark field's own).- match (State::of(&r, true), crate::theme::dark()) {- (State::Pressed, true) => Some(rgb(0x4f, 0x4f, 0x4f)),- (state, dark) => subtle_fill(state, dark),+ let c = crate::theme::colors();+ match State::of(&r, true) {+ State::Pressed => Some(c.row_pressed),+ state => subtle_fill(state, c),}};if let Some(f) = fill {@@ -1376,7 +1387,7 @@ pub fn row_list(let mut look = RowLook {selected,ink: if selected && focused {- Color32::WHITE+ SELECTION_TEXT()} else {TEXT()},@@ -1586,7 +1597,7 @@ fn vline(p: &Painter, x: f32, y0: f32, y1: f32, c: Color32) {/// The rounding of a control's corners (buttons, text boxes, drop-downs), in both modes.pub fn control_radius() -> f32 {- 3.0+ crate::theme::metrics().control_radius}/// What a text box allows: typing, nothing (greyed), or reading and copying.@@ -1605,34 +1616,28 @@ pub enum FieldLook {/// and dark mode drew IDM's bright 2 px border round every box, disabled ones included).pub fn field_frame(p: &Painter, rc: Rect, look: FieldLook) {let radius = control_radius();- let (inside, border, bottom) = match (crate::theme::dark(), look) {- (false, FieldLook::Editable) => {- (Color32::WHITE, rgb(0xe5, 0xe5, 0xe5), rgb(0x86, 0x86, 0x86))- }- (false, FieldLook::Disabled) => (- rgb(0xf9, 0xf9, 0xf9),- rgb(0xe9, 0xe9, 0xe9),- rgb(0xe9, 0xe9, 0xe9),- ),- (false, FieldLook::ReadOnly) => (- rgb(0xf3, 0xf3, 0xf3),- rgb(0xe2, 0xe2, 0xe2),- rgb(0xe2, 0xe2, 0xe2),+ let c = crate::theme::colors();+ // Disabled and read-only boxes are flat: their bottom line is their border.+ let (inside, border, bottom) = match look {+ FieldLook::Editable => (c.field, c.field_border, c.field_bottom),+ FieldLook::Disabled => (+ c.field_disabled,+ c.field_disabled_border,+ c.field_disabled_border,),- (true, FieldLook::Editable) => (FIELD(), rgb(0x4b, 0x4b, 0x4b), rgb(0x9a, 0x9a, 0x9a)),- (true, FieldLook::Disabled) => (- rgb(0x33, 0x33, 0x33),- rgb(0x44, 0x44, 0x44),- rgb(0x44, 0x44, 0x44),- ),- (true, FieldLook::ReadOnly) => (- rgb(0x30, 0x30, 0x30),- rgb(0x4b, 0x4b, 0x4b),- rgb(0x4b, 0x4b, 0x4b),+ FieldLook::ReadOnly => (+ c.field_readonly,+ c.field_readonly_border,+ c.field_readonly_border,),};p.rect_filled(rc, radius, inside);- p.rect_stroke(rc, radius, Stroke::new(1.0, border), StrokeKind::Inside);+ p.rect_stroke(+ rc,+ radius,+ Stroke::new(crate::theme::metrics().border, border),+ StrokeKind::Inside,+ );hline(p,rc.left() + radius,@@ -1646,19 +1651,21 @@ pub fn field_frame(p: &Painter, rc: Rect, look: FieldLook) {/// track was light in dark mode too), the controls' rounded corners. `fraction` in 0..=1.pub fn meter(p: &Painter, rc: Rect, fraction: f32) {let radius = control_radius().min(rc.height() / 4.0).floor();- let (track, edge) = if crate::theme::dark() {- (rgb(0x2b, 0x2b, 0x2b), rgb(0x4b, 0x4b, 0x4b))- } else {- (rgb(0xe6, 0xe6, 0xe6), rgb(0xbc, 0xbc, 0xbc))- };- p.rect_filled(rc, radius, track);- let inner = rc.shrink(1.0);+ let c = crate::theme::colors();+ let border = crate::theme::metrics().border;+ p.rect_filled(rc, radius, c.meter_track);+ let inner = rc.shrink(border);let w = (fraction.clamp(0.0, 1.0) * inner.width()).floor();if w > 0.0 {let done = Rect::from_min_size(inner.min, vec2(w, inner.height()));- p.rect_filled(done, (radius - 1.0).max(0.0), rgb(0x0f, 0x7b, 0x0f));+ p.rect_filled(done, (radius - border).max(0.0), c.meter_fill);}- p.rect_stroke(rc, radius, Stroke::new(1.0, edge), StrokeKind::Inside);+ p.rect_stroke(+ rc,+ radius,+ Stroke::new(border, c.meter_edge),+ StrokeKind::Inside,+ );}/// A box whose value is wrong (a number out of range, an address that isn't one, a schedule@@ -1668,7 +1675,7 @@ pub fn error_frame(p: &Painter, rc: Rect) {p.rect_stroke(rc,control_radius(),- Stroke::new(1.0, ERROR()),+ Stroke::new(crate::theme::metrics().border, ERROR()),StrokeKind::Inside,);}@@ -1721,17 +1728,18 @@ pub fn edit_focus_line(ui: &Ui, resp: &Response, rc: Rect) {/// The 2 px accent along a focused box's bottom edge. Light: the bottom of its rounded/// frame, curving into the corners as Windows 11 draws it; dark: IDM's straight line.pub fn focus_bottom(p: &Painter, rc: Rect) {- if crate::theme::dark() {+ let h = crate::theme::metrics().focus_line;+ if crate::theme::colors().focus_line_straight {fill(p,rc.left() + 1.0,- rc.bottom() - 2.0,+ rc.bottom() - h,rc.right() - 2.0,rc.bottom() - 1.0,accent(),);} else {- let strip = Rect::from_min_max(pos2(rc.left(), rc.bottom() - 2.0), rc.max);+ let strip = Rect::from_min_max(pos2(rc.left(), rc.bottom() - h), rc.max);p.with_clip_rect(strip).rect_filled(rc, control_radius(), accent());}@@ -2191,40 +2199,30 @@ impl State {/// The fill of a part with no face of its own (a combo's arrow, a glyph button, a column/// header) in `state`: none at rest, a tint under the pointer, a deeper one pressed or open.-/// `dark_surface`: the part sits on a dark background (the dark buttons' greys), else the light-/// icon buttons' greys.-pub fn subtle_fill(state: State, dark_surface: bool) -> Option<Color32> {- match (state, dark_surface) {- (State::Hot, false) => Some(rgb(0xf3, 0xf3, 0xf3)),- (State::Pressed | State::Open, false) => Some(rgb(0xe8, 0xe8, 0xe8)),- (State::Hot, true) => Some(rgb(0x45, 0x45, 0x45)),- (State::Pressed | State::Open, true) => Some(rgb(0x26, 0x26, 0x26)),+/// Colours from `c`, a theme's variant (the active one: `crate::theme::colors()`).+pub fn subtle_fill(state: State, c: &crate::palette::Palette) -> Option<Color32> {+ match state {+ State::Hot => Some(c.subtle_hot),+ State::Pressed | State::Open => Some(c.subtle_pressed),_ => None,}}/// The blue highlight of a calendar's days and arrows (Win32's month calendar) in `state`:-/// #e5f1fb under the pointer, #cce4f7 pressed; deep blues on a dark surface.-pub fn highlight_fill(state: State, dark_surface: bool) -> Option<Color32> {- match (state, dark_surface) {- (State::Hot, false) => Some(rgb(0xe5, 0xf1, 0xfb)),- (State::Pressed | State::Open, false) => Some(rgb(0xcc, 0xe4, 0xf7)),- (State::Hot, true) => Some(rgb(0x2d, 0x4a, 0x60)),- (State::Pressed | State::Open, true) => Some(rgb(0x23, 0x3d, 0x52)),+/// a light accent tint under the pointer, a deeper one pressed (from `c`).+pub fn highlight_fill(state: State, c: &crate::palette::Palette) -> Option<Color32> {+ match state {+ State::Hot => Some(c.highlight_hot),+ State::Pressed | State::Open => Some(c.highlight_pressed),_ => None,}}-/// Tints `zone` (a part already drawn at rest) for `state` and draws its glyph again on top.-pub fn tint_part(- p: &Painter,- zone: Rect,- state: State,- dark_surface: bool,- glyph: impl FnOnce(&Painter),-) {- if let Some(c) = subtle_fill(state, dark_surface) {- p.rect_filled(zone, 2.0, c);+/// Tints `zone` (a part already drawn at rest) with `tint` (none at rest: [`subtle_fill`]) and+/// draws its glyph again on top.+pub fn tint_part(p: &Painter, zone: Rect, tint: Option<Color32>, glyph: impl FnOnce(&Painter)) {+ if let Some(c) = tint {+ p.rect_filled(zone, crate::theme::metrics().part_radius, c);glyph(p);}}@@ -2258,7 +2256,10 @@ fn combo_chevron(p: &Painter, rc: Rect) {pos2(cx + 4.0, cy + 4.5),pos2(cx + 8.0, cy + 0.5),],- Stroke::new(1.2, rgb(0x6f, 0x6f, 0x6f)),+ Stroke::new(+ crate::theme::metrics().chevron_width,+ crate::theme::colors().combo_chevron,+ ),);}@@ -2335,7 +2336,13 @@ pub fn combo_arrow(ui: &mut Ui, rc: Rect, id: &str, open: bool) -> Response {let resp = ui.interact(zone, widget_id(ui, ("combo-arrow", id)), pointer_only());let resp = opener_click(ui, resp);let state = State::of(&resp, true).open_if(open);- tint_part(ui.painter(), zone, state, false, |p| combo_chevron(p, rc));+ let c = crate::theme::colors();+ let tint = match state {+ State::Hot => Some(c.combo_arrow_hot),+ State::Pressed | State::Open => Some(c.combo_arrow_pressed),+ _ => None,+ };+ tint_part(ui.painter(), zone, tint, |p| combo_chevron(p, rc));resp}@@ -2654,32 +2661,32 @@ pub fn small_button(ui: &mut Ui, rc: Rect, glyph: &str) -> Response {crate::theme::themed! {/// The "light dialogs" (Options, Scheduler, File Properties…): IDM draws them light in both/// modes; here they follow the mode, dark the dark dialogs' colours.- pub LIGHT_BG = rgb(0x39, 0x39, 0x39), rgb(0xf0, 0xf0, 0xf0);- pub LIGHT_TEXT = rgb(0xff, 0xff, 0xff), rgb(0x00, 0x00, 0x00);- pub LIGHT_DISABLED = rgb(0x8a, 0x8a, 0x8a), rgb(0x8a, 0x8a, 0x8a);+ pub LIGHT_BG => window;+ pub LIGHT_TEXT => text;+ pub LIGHT_DISABLED => text_disabled;/// A text box's or a list's inside.- pub FIELD = rgb(0x2b, 0x2b, 0x2b), rgb(0xff, 0xff, 0xff);+ pub FIELD => field;/// A list's or a box's outline.- pub FIELD_EDGE = rgb(0x5a, 0x5a, 0x5a), rgb(0x82, 0x87, 0x90);+ pub FIELD_EDGE => list_frame;/// Grid lines between a list's rows, and header dividers.- pub GRID = rgb(0x40, 0x40, 0x40), rgb(0xf0, 0xf0, 0xf0);- pub HEADER_LINE = rgb(0x4e, 0x4e, 0x4e), rgb(0xe5, 0xe5, 0xe5);+ pub GRID => grid;+ pub HEADER_LINE => header_line;/// Etched separators: the shadow line and the highlight beside it.- pub ETCH_SHADOW = rgb(0x22, 0x22, 0x22), rgb(0xa0, 0xa0, 0xa0);- pub ETCH_LIGHT = rgb(0x50, 0x50, 0x50), rgb(0xff, 0xff, 0xff);+ pub ETCH_SHADOW => etch_shadow;+ pub ETCH_LIGHT => etch_light;/// A selected row in a focused list ([`row_list`]; the download list's colours), white/// text on it.- pub ROW_SELECTED = rgb(0x00, 0x78, 0xd4), rgb(0x00, 0x78, 0xd4);+ pub ROW_SELECTED => selection;/// Text that opens something ([`link`]).- pub LINK = rgb(0x99, 0xc8, 0xff), rgb(0x00, 0x66, 0xcc);+ pub LINK => link;/// A selected row in a list without the focus.- pub SELECTED_INACTIVE = rgb(0x4a, 0x4a, 0x4a), rgb(0xd9, 0xd9, 0xd9);+ pub SELECTED_INACTIVE => selection_inactive;/// Error text.- pub ERROR = rgb(0xff, 0x80, 0x80), rgb(0xc4, 0x2b, 0x1c);+ pub ERROR => error;/// Secondary text (notes, sizes, versions).- pub MUTED = rgb(0xa0, 0xa0, 0xa0), rgb(0x6d, 0x6d, 0x6d);+ pub MUTED => muted;/// Success text (a matching checksum).- pub SUCCESS = rgb(0x6c, 0xcb, 0x5f), rgb(0x0f, 0x7b, 0x0f);+ pub SUCCESS => success;}/// Light edit: the same Win11 border, white fill, black text.@@ -3061,7 +3068,6 @@ fn button_face(kind: ButtonKind,default_focus: bool,) -> Response {- let dark = crate::theme::dark();let enabled = kind != ButtonKind::Disabled;let sense = if enabled {Sense::click()@@ -3090,13 +3096,13 @@ fn button_face(}let state = State::of(&resp, enabled);let p = ui.painter();- let face = button_colors(kind, state, dark);+ let face = button_colors(kind, state, crate::theme::colors());let rounding = control_radius();p.rect_filled(rc, rounding, face.fill);p.rect_stroke(rc,rounding,- Stroke::new(1.0, face.border),+ Stroke::new(crate::theme::metrics().border, face.border),StrokeKind::Inside,);let inset = 3.0;@@ -3164,79 +3170,51 @@ struct Face {text: Color32,}-/// A button's colours for `kind` in `state`: dark, IDM's dark buttons; light, Windows 11's.-fn button_colors(kind: ButtonKind, state: State, dark: bool) -> Face {+/// A button's colours for `kind` in `state`, from `c` (a theme's variant). The states are+/// decided here, once for every button: the pressed one flattens its bottom edge.+fn button_colors(kind: ButtonKind, state: State, c: &crate::palette::Palette) -> Face {let pressed = state == State::Pressed;if kind == ButtonKind::Accent {- // The accent filled, a shade lighter under the pointer and darker pressed; light text- // on the light mode's blue, dark text on the dark mode's.- let (fill, text) = match (dark, state) {- (false, State::Pressed) => (rgb(0x00, 0x6c, 0xbe), rgb(0xe6, 0xf0, 0xfa)),- (false, State::Hot) => (rgb(0x1a, 0x86, 0xd9), Color32::WHITE),- (false, _) => (rgb(0x00, 0x78, 0xd4), Color32::WHITE),- (true, State::Pressed) => (rgb(0x52, 0xa6, 0xd0), rgb(0x1a, 0x1a, 0x1a)),- (true, State::Hot) => (rgb(0x5a, 0xb9, 0xe5), Color32::BLACK),- (true, _) => (rgb(0x60, 0xcd, 0xff), Color32::BLACK),- };- let bottom = if dark {- rgb(0x4f, 0xb5, 0xe4)- } else {- rgb(0x00, 0x5a, 0x9e)+ // The accent filled, a shade lighter under the pointer and darker pressed.+ let (fill, text) = match state {+ State::Pressed => (c.button_accent_pressed, c.button_accent_text_pressed),+ State::Hot => (c.button_accent_hot, c.button_accent_text),+ _ => (c.button_accent, c.button_accent_text),};return Face {fill,border: fill,- bottom: if pressed { fill } else { bottom },+ bottom: if pressed {+ fill+ } else {+ c.button_accent_bottom+ },text,};}- let face = if dark {- // Windows 11's dark buttons: a face a little lighter than the window, a quiet border (it- // was IDM's bright one, white round the default button), the default button outlined in- // the accent as in light mode.- let (border, bottom) = match kind {- ButtonKind::Normal => (rgb(0x55, 0x55, 0x55), rgb(0x4b, 0x4b, 0x4b)),- ButtonKind::Default | ButtonKind::Accent => (accent(), rgb(0x4f, 0xb5, 0xe4)),- ButtonKind::Disabled => (rgb(0x46, 0x46, 0x46), rgb(0x46, 0x46, 0x46)),- };- Face {- fill: match state {- State::Disabled => rgb(0x3d, 0x3d, 0x3d),- State::Pressed => rgb(0x3c, 0x3c, 0x3c),- State::Hot => rgb(0x4b, 0x4b, 0x4b),- _ => rgb(0x44, 0x44, 0x44),- },- border,- bottom,- text: match state {- State::Disabled => TEXT_DISABLED(),- State::Pressed => rgb(0xc8, 0xc8, 0xc8),- _ => TEXT(),- },- }- } else {- let (border, bottom) = match kind {- ButtonKind::Normal => (rgb(0xd0, 0xd0, 0xd0), rgb(0xba, 0xba, 0xba)),- ButtonKind::Default | ButtonKind::Accent => {- (rgb(0x00, 0x78, 0xd4), rgb(0x00, 0x6b, 0xbe))- }- ButtonKind::Disabled => (rgb(0xe9, 0xe9, 0xe9), rgb(0xe9, 0xe9, 0xe9)),- };- Face {- fill: match state {- State::Disabled => rgb(0xf9, 0xf9, 0xf9),- State::Pressed => rgb(0xf5, 0xf5, 0xf5),- State::Hot => rgb(0xf6, 0xf6, 0xf6),- _ => rgb(0xfd, 0xfd, 0xfd),- },- border,- bottom,- text: match state {- State::Disabled => TEXT_DISABLED(),- State::Pressed => rgb(0x5d, 0x5d, 0x5d),- _ => LIGHT_TEXT(),- },+ // Windows 11's buttons: a face a little lighter than the window in dark, a quiet border,+ // the default button outlined in the accent.+ let (border, bottom) = match kind {+ ButtonKind::Normal => (c.button_border, c.button_bottom),+ ButtonKind::Default | ButtonKind::Accent => {+ (c.button_default_border, c.button_default_bottom)}+ ButtonKind::Disabled => (c.button_disabled_border, c.button_disabled_border),+ };+ let face = Face {+ fill: match state {+ State::Disabled => c.button_disabled,+ State::Pressed => c.button_pressed,+ State::Hot => c.button_hot,+ _ => c.button,+ },+ border,+ bottom,+ text: match state {+ State::Disabled => c.text_disabled,+ State::Pressed => c.button_text_pressed,+ _ => c.button_text,+ },};if pressed {Face {@@ -3351,11 +3329,7 @@ pub fn focus_ring(p: &Painter, rc: Rect) {if !keyboard_in_use(p.ctx()) {return;}- let ink = if crate::theme::dark() {- rgb(0xcc, 0xcc, 0xcc)- } else {- rgb(0x0d, 0x0d, 0x0d)- };+ let ink = crate::theme::colors().focus_ring;let (l, t, r, b) = (rc.left(), rc.top(), rc.right() - 1.0, rc.bottom() - 1.0);let mut x = l;while x <= r {@@ -3442,12 +3416,12 @@ pub fn checkbox_light_until(crate::theme::themed! {/// Tab page body.- pub LIGHT_PAGE = rgb(0x40, 0x40, 0x40), rgb(0xf9, 0xf9, 0xf9);+ pub LIGHT_PAGE => tab_page;/// An unselected tab, and the page's shadow.- pub TAB_UNSELECTED = rgb(0x33, 0x33, 0x33), rgb(0xf3, 0xf3, 0xf3);- pub TAB_HOT = rgb(0x46, 0x46, 0x46), rgb(0xfd, 0xfd, 0xfd);- CHEVRON = rgb(0xc8, 0xc8, 0xc8), rgb(0x6f, 0x6f, 0x6f);- CHEVRON_DISABLED = rgb(0x6a, 0x6a, 0x6a), rgb(0xbe, 0xbe, 0xbe);+ pub TAB_UNSELECTED => tab;+ pub TAB_HOT => tab_hot;+ CHEVRON => chevron;+ CHEVRON_DISABLED => chevron_disabled;}/// A Windows 11 check box's 13 × 13 box in `rc`, ticked or not, in `state`: the one look of@@ -3481,7 +3455,11 @@ pub fn row_check(pub fn check_box_glyph(p: &Painter, rc: Rect, checked: bool, state: State) {if checked {- p.rect_filled(rc, 2.0, fluent_accent(state));+ p.rect_filled(+ rc,+ crate::theme::metrics().check_radius,+ fluent_accent(state),+ );p.line(vec![pos2(rc.left() + 3.0, rc.top() + 6.5),@@ -3492,17 +3470,27 @@ pub fn check_box_glyph(p: &Painter, rc: Rect, checked: bool, state: State) {);} else {let (fill_c, border) = fluent_box(state);+ let m = crate::theme::metrics();if let Some(f) = fill_c {- p.rect_filled(rc, 2.0, f);+ p.rect_filled(rc, m.check_radius, f);}- p.rect_stroke(rc, 2.0, Stroke::new(1.0, border), StrokeKind::Inside);+ p.rect_stroke(+ rc,+ m.check_radius,+ Stroke::new(m.border, border),+ StrokeKind::Inside,+ );}}/// A Windows 11 check box that is partly ticked (a folder with some of its files chosen): the/// accent box with a dash, as Windows draws it (a square sat on the unticked box before).pub fn check_box_mixed(p: &Painter, rc: Rect, state: State) {- p.rect_filled(rc, 2.0, fluent_accent(state));+ p.rect_filled(+ rc,+ crate::theme::metrics().check_radius,+ fluent_accent(state),+ );let y = rc.center().y.floor() + 0.5;p.line_segment([pos2(rc.left() + 3.0, y), pos2(rc.right() - 3.0, y)],@@ -3540,44 +3528,32 @@ pub fn tree_expander(p: &Painter, at: Pos2, open: bool) {/// A checked Windows 11 check box's or radio's accent in `state`: lighter under the pointer,/// lighter still while pressed, grey when disabled.fn fluent_accent(state: State) -> Color32 {- match (state, crate::theme::dark()) {- (State::Disabled, false) => rgb(0xc3, 0xc3, 0xc3),- (State::Hot, false) => rgb(0x1a, 0x86, 0xd9),- (State::Pressed, false) => rgb(0x33, 0x92, 0xdc),- (_, false) => rgb(0x00, 0x78, 0xd4),- (State::Disabled, true) => rgb(0x5a, 0x5a, 0x5a),- (State::Hot, true) => rgb(0x5a, 0xbc, 0xe8),- (State::Pressed, true) => rgb(0x52, 0xa6, 0xcc),- (_, true) => rgb(0x60, 0xcd, 0xff),+ let c = crate::theme::colors();+ match state {+ State::Disabled => c.check_on_disabled,+ State::Hot => c.check_on_hot,+ State::Pressed => c.check_on_pressed,+ _ => c.check_on,}}/// The mark on a checked box or radio (white on the light accent's blue, dark on the dark's).fn fluent_mark() -> Color32 {- if crate::theme::dark() {- rgb(0x00, 0x00, 0x00)- } else {- Color32::WHITE- }+ crate::theme::colors().check_mark}/// An unchecked Windows 11 check box's or radio's fill (none when disabled) and border in/// `state`: darker fill under the pointer, darker still and a fainter border while pressed.fn fluent_box(state: State) -> (Option<Color32>, Color32) {- fluent_box_in(state, crate::theme::dark())+ fluent_box_in(state, crate::theme::colors())}-fn fluent_box_in(state: State, dark: bool) -> (Option<Color32>, Color32) {- match (state, dark) {- (State::Disabled, false) => (None, rgb(0xc3, 0xc3, 0xc3)),- (State::Hot, false) => (Some(rgb(0xea, 0xea, 0xea)), rgb(0x62, 0x62, 0x62)),- (State::Pressed, false) => (Some(rgb(0xdd, 0xdd, 0xdd)), rgb(0x9a, 0x9a, 0x9a)),- (_, false) => (Some(rgb(0xf3, 0xf3, 0xf3)), rgb(0x62, 0x62, 0x62)),- (State::Disabled, true) => (None, rgb(0x5a, 0x5a, 0x5a)),- (State::Hot, true) => (Some(rgb(0x3a, 0x3a, 0x3a)), rgb(0xa0, 0xa0, 0xa0)),- // Pressed lighter still, as Windows 11's dark boxes (it went darker, the wrong way).- (State::Pressed, true) => (Some(rgb(0x47, 0x47, 0x47)), rgb(0x70, 0x70, 0x70)),- (_, true) => (Some(rgb(0x2b, 0x2b, 0x2b)), rgb(0x9b, 0x9b, 0x9b)),+fn fluent_box_in(state: State, c: &crate::palette::Palette) -> (Option<Color32>, Color32) {+ match state {+ State::Disabled => (None, c.check_border_disabled),+ State::Hot => (Some(c.check_hot), c.check_border_hot),+ State::Pressed => (Some(c.check_pressed), c.check_border_pressed),+ _ => (Some(c.check), c.check_border),}}@@ -4277,13 +4253,13 @@ pub fn button_like(p: &Painter, rc: Rect, state: State) {} else {ButtonKind::Normal};- let face = button_colors(kind, state, crate::theme::dark());+ let face = button_colors(kind, state, crate::theme::colors());let radius = control_radius().min((rc.height() / 3.0).floor());p.rect_filled(rc, radius, face.fill);p.rect_stroke(rc,radius,- Stroke::new(1.0, face.border),+ Stroke::new(crate::theme::metrics().border, face.border),StrokeKind::Inside,);if rc.height() >= 14.0 {@@ -4300,18 +4276,26 @@ pub fn button_like(p: &Painter, rc: Rect, state: State) {pub fn dropdown_frame_light(p: &Painter, rc: Rect, state: State) {// Drawn as a button (Windows 11 draws its drop-downs so): the same faces and states, in// the current theme; open, the accent border and no bottom edge (its list is out).- let dark = crate::theme::dark();let open = state == State::Open;let kind = if state == State::Disabled {ButtonKind::Disabled} else {ButtonKind::Normal};- let face = button_colors(kind, if open { State::Hot } else { state }, dark);+ let face = button_colors(+ kind,+ if open { State::Hot } else { state },+ crate::theme::colors(),+ );let border = if open { accent() } else { face.border };let rounding = control_radius();p.rect_filled(rc, rounding, face.fill);- p.rect_stroke(rc, rounding, Stroke::new(1.0, border), StrokeKind::Inside);+ p.rect_stroke(+ rc,+ rounding,+ Stroke::new(crate::theme::metrics().border, border),+ StrokeKind::Inside,+ );if !open {hline(p,@@ -4325,11 +4309,7 @@ pub fn dropdown_frame_light(p: &Painter, rc: Rect, state: State) {/// The accent (Windows' blue): borders of open and focused controls.pub fn accent() -> Color32 {- if crate::theme::dark() {- rgb(0x60, 0xcd, 0xff)- } else {- rgb(0x00, 0x78, 0xd4)- }+ crate::theme::colors().accent}/// Light drop-down list (CBS_DROPDOWNLIST): the chosen item and a chevron; a click opens the@@ -4498,8 +4478,8 @@ pub fn spin_arrows(ui: &mut Ui, rc: Rect, enabled: bool, id: &str) -> i32 {} else {State::Normal};- if let Some(tint) = subtle_fill(state, crate::theme::dark()) {- p.rect_filled(part.shrink(1.0), 2.0, tint);+ if let Some(tint) = subtle_fill(state, crate::theme::colors()) {+ p.rect_filled(part.shrink(1.0), crate::theme::metrics().part_radius, tint);}let c = part.center();let arrow = if enabled {@@ -4596,14 +4576,15 @@ pub mod caption {crate::theme::themed! {/// A title bar we draw ourselves (Windows 11's caption, both themes).- pub CAPTION_BG = rgb(0x20, 0x20, 0x20), rgb(0xff, 0xff, 0xff);- pub CAPTION_INK = rgb(0xff, 0xff, 0xff), rgb(0x00, 0x00, 0x00);+ pub CAPTION_BG => caption;+ pub CAPTION_INK => caption_text;/// A caption button's hover and pressed tints over the bar: WinUI's caption tokens, as/// Windows Terminal ships them (#0FFFFFFF / #09000000, #0AFFFFFF / #06000000).- pub CAPTION_HOVER = Color32::from_rgba_unmultiplied(0xff, 0xff, 0xff, 0x0f),- Color32::from_rgba_unmultiplied(0x00, 0x00, 0x00, 0x09);- pub CAPTION_PRESSED = Color32::from_rgba_unmultiplied(0xff, 0xff, 0xff, 0x0a),- Color32::from_rgba_unmultiplied(0x00, 0x00, 0x00, 0x06);+ pub CAPTION_HOVER => caption_hot;+ pub CAPTION_PRESSED => caption_pressed;+ /// Close's hover red, and its glyph on it.+ CLOSE_HOVER => caption_close;+ CLOSE_INK => caption_close_text;}/// The title and glyphs while the window isn't the active one, and a greyed button's: the/// one disabled ink of every control.@@ -4612,9 +4593,8 @@ pub mod caption {}/// Close's hover red with a white glyph; pressed, the red at 0.9 and the glyph at 0.7/// (WinUI's, both themes).- const CLOSE_HOVER: Color32 = rgb(0xc4, 0x2b, 0x1c);fn close_pressed() -> Color32 {- CLOSE_HOVER.gamma_multiply(0.9)+ CLOSE_HOVER().gamma_multiply(0.9)}/// A drawn title bar's height and one caption button's width, in points (Windows 11's).@@ -4714,7 +4694,7 @@ pub mod caption {let close = b == CaptionButton::Close;let fill = match (pressed, hover, close) {(true, _, true) => Some(close_pressed()),- (false, true, true) => Some(CLOSE_HOVER),+ (false, true, true) => Some(CLOSE_HOVER()),(true, _, false) => Some(CAPTION_PRESSED()),(false, true, false) => Some(CAPTION_HOVER()),_ => None,@@ -4723,9 +4703,9 @@ pub mod caption {p.rect_filled(rc, 0.0, f);}let ink = if close && pressed {- Color32::WHITE.gamma_multiply(0.7)+ CLOSE_INK().gamma_multiply(0.7)} else if close && hover {- Color32::WHITE+ CLOSE_INK()} else if !enabled || !active {caption_ink_inactive()} else {@@ -5300,11 +5280,19 @@ mod tests {#[test]fn a_pressed_button_looks_pressed_in_both_themes() {// Issue #7: pressed was #f5f5f5 against hot #f6f6f6, the same to the eye.- for dark in [false, true] {+ for theme in crate::palette::builtins() {+ for c in [&theme.light, &theme.dark] {+ button_states_differ(c);+ }+ }+ }++ fn button_states_differ(c: &crate::palette::Palette) {+ {for kind in [ButtonKind::Normal, ButtonKind::Default] {- let rest = button_colors(kind, State::Normal, dark);- let hot = button_colors(kind, State::Hot, dark);- let pressed = button_colors(kind, State::Pressed, dark);+ let rest = button_colors(kind, State::Normal, c);+ let hot = button_colors(kind, State::Hot, c);+ let pressed = button_colors(kind, State::Pressed, c);assert_ne!(pressed.text, rest.text, "pressed dims the label");assert_eq!(pressed.bottom, pressed.border,@@ -5316,8 +5304,8 @@ mod tests {);assert_ne!(hot.fill, rest.fill, "hot differs from rest");}- let disabled = button_colors(ButtonKind::Disabled, State::Disabled, dark);- let enabled = button_colors(ButtonKind::Normal, State::Normal, dark);+ let disabled = button_colors(ButtonKind::Disabled, State::Disabled, c);+ let enabled = button_colors(ButtonKind::Normal, State::Normal, c);let gap = |a: Color32, b: Color32| (a.r() as i32 - b.r() as i32).abs();assert!(gap(disabled.text, enabled.text) >= 0x50,@@ -5333,35 +5321,36 @@ mod tests {assert_eq!(State::Pressed.open_if(true), State::Pressed);assert_eq!(State::Disabled.open_if(true), State::Disabled);assert_eq!(State::Hot.open_if(false), State::Hot);- for dark in [false, true] {- assert_eq!(subtle_fill(State::Normal, dark), None);- assert_eq!(subtle_fill(State::Disabled, dark), None);- let grey = |s| subtle_fill(s, dark).unwrap().r();+ let (light, dark) = (+ &crate::palette::CLASSIC.light,+ &crate::palette::CLASSIC.dark,+ );+ for c in [light, dark] {+ assert_eq!(subtle_fill(State::Normal, c), None);+ assert_eq!(subtle_fill(State::Disabled, c), None);+ let grey = |s| subtle_fill(s, c).unwrap().r();// Pressed (and open) is deeper than hot, on either surface.assert!(grey(State::Pressed) < grey(State::Hot));- assert_eq!(- subtle_fill(State::Open, dark),- subtle_fill(State::Pressed, dark)- );+ assert_eq!(subtle_fill(State::Open, c), subtle_fill(State::Pressed, c));}assert!(- highlight_fill(State::Pressed, false).unwrap().r()- < highlight_fill(State::Hot, false).unwrap().r()+ highlight_fill(State::Pressed, light).unwrap().r()+ < highlight_fill(State::Hot, light).unwrap().r());// Windows 11 boxes: deeper under the pointer, deeper still pressed.// Light: darker under the pointer, darker still pressed. Dark: lighter under the// pointer, lighter still pressed (Windows 11). The three differ; disabled is empty.- let fill = |s, dark| fluent_box_in(s, dark).0.unwrap().r();+ let fill = |s, c| fluent_box_in(s, c).0.unwrap().r();assert!(- fill(State::Pressed, false) < fill(State::Hot, false)- && fill(State::Hot, false) < fill(State::Normal, false)+ fill(State::Pressed, light) < fill(State::Hot, light)+ && fill(State::Hot, light) < fill(State::Normal, light));assert!(- fill(State::Normal, true) < fill(State::Hot, true)- && fill(State::Hot, true) < fill(State::Pressed, true)+ fill(State::Normal, dark) < fill(State::Hot, dark)+ && fill(State::Hot, dark) < fill(State::Pressed, dark));- for dark in [false, true] {- assert_eq!(fluent_box_in(State::Disabled, dark).0, None);+ for c in [light, dark] {+ assert_eq!(fluent_box_in(State::Disabled, c).0, None);}}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex fcf75361..3bec5ed3 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -62,7 +62,14 @@ toolbar, key and IPC commands into actions. Each dialog is its own module and re`Outcome` (open, closed, done with a value). Windows-only calls are confined to `win32.rs` andtheir Linux and macOS counterparts to `unix.rs` (starting with the session, the browsers' host,sounds, show in folder, the crash handler); every other file is safe, portable Rust. Fonts come from the system:-Windows' Fonts folder, macOS's system fonts, fontconfig on Linux (`theme.rs`). So do the icons+Windows' Fonts folder, macOS's system fonts, fontconfig on Linux (`theme.rs`).++Every colour and size a control is drawn with comes from the active theme (#45): `palette.rs`+declares its roles (`"button.hot"`, `"list.row"`…) with the classic look's values, the shared+painters (`winui.rs`, `chrome.rs`, `list.rs`, `scrollbar.rs`) read them through+`theme::colors()` and `theme::metrics()` and decide each control's states from them, and+`themefile.rs` reads theme files (TOML or JSON in the data folder's `themes`) that change any of+them. Where a window puts its controls stays its layout. So do the iconsbefore file names (`fileicons.rs`): the Windows shell's system image lists, macOS Finder's(NSWorkspace), the Linux desktop's icon theme (`xdgicons.rs`, shared-mime-info and the IconTheme Specification). Each type is looked up once per pixel size, on a background thread. Tango's