8447
Co
conveyor / files
conveyor / templates / library / widgets / theme.rs
17.4 KB
1//! Theme: set the app's colours to anything (a swatch, lightness, chroma and hue sliders, or a 2//! hex code), roll random ones, set how see-through, blurred and shadowed floating cards are, 3//! and pick the font, the mono font and the text size from dropdowns. 4//! 5//! It all lives in the shared value "theme" (see `look`), so every widget follows at once and it 6//! survives restarts. The font dropdowns list installed families, with a filter. 7use super::{api::*, canvas, look::{self, Look, Settings}, ui}; 8use rune::{Align, Color, Drag, El, Phase, ScrollSpec, Side, TextEdit, TextStyle, Tx, col, el, oklch, row, text}; 9use std::{f32::consts::FRAC_PI_2, sync::{Arc, Mutex}}; 10 11pub const WIDGET: Widget = Widget { title: "Theme", size: (400.0, 720.0), new: |cx| Box::new(Theme::new(cx)) }; 12 13#[derive(Clone, Copy, PartialEq)] 14enum Menu { Font, Mono, Size } 15 16pub struct Theme { 17 /// The colour whose picker is open, with its hue (kept here, so a grey keeps one too). 18 open: Option<(usize, f32)>, 19 /// Each colour's hex field, and the colour it last showed. 20 hex: [(TextEdit, String); 5], 21 /// The open dropdown, and what's typed in its filter. 22 menu: Option<Menu>, 23 filter: TextEdit, 24 /// Installed families, all and monospaced, as fontconfig lists them off the UI thread. 25 families: Arc<Mutex<(Vec<String>, Vec<String>)>>, 26} 27 28/// Each colour: its settings key, its name, and its swatches' lightness, chroma and the 29/// lightness of the one swatch from the other side (light for a dark role, and back). 30const ROLES: [(&str, &str, f32, f32, f32); 5] = [ 31 ("bg", "Background", 0.185, 0.02, 0.96), 32 ("card", "Surface", 0.235, 0.025, 0.995), 33 ("text", "Text", 0.955, 0.012, 0.225), 34 ("muted", "Muted text", 0.72, 0.03, 0.5), 35 ("accent", "Accent", 0.72, 0.14, 0.0), 36]; 37const HUES: [f32; 9] = [265.0, 250.0, 200.0, 150.0, 95.0, 60.0, 25.0, 340.0, 295.0]; 38const SIZES: [f32; 13] = [9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 20.0, 22.0, 24.0]; 39/// The most chroma the chroma slider gives: about what sRGB holds at its most vivid. 40const MAX_CHROMA: f32 = 0.32; 41 42impl Theme { 43 fn new(cx: &Cx) -> Self { 44 let s = Settings::read(cx.shared("theme")); 45 let families = Arc::<Mutex<_>>::default(); 46 let out = families.clone(); 47 std::thread::spawn(move || { let all = (fc_list(":"), fc_list(":spacing=100")); *out.lock().unwrap() = all }); 48 let hex = std::array::from_fn(|i| { let v = slot(&mut s.clone(), i).clone(); (TextEdit::new(v.clone()), v) }); 49 Theme { open: None, hex, menu: None, filter: TextEdit::new(""), families } 50 } 51} 52 53impl View for Theme { 54 /// A valid hex typed in a field applies it; a colour changed elsewhere refills its field. 55 fn update(&mut self, cx: &Cx) { 56 let mut s = Settings::read(cx.shared("theme")); 57 let mut typed = false; 58 for (i, (e, shown)) in self.hex.iter_mut().enumerate() { 59 let now = slot(&mut s, i); 60 if *now != *shown { (*e, *shown) = (TextEdit::new(now.clone()), now.clone()) } 61 else if let Some(v) = parse_hex(&e.text) && v != *now { (*now, *shown, typed) = (v.clone(), v, true) } 62 } 63 if typed { let json = s.json(); cx.act(move |l| l.share("theme", &json)) } 64 } 65 66 fn view(&self, cx: &Cx) -> El { 67 let t = look::of(cx); 68 let s = Settings::read(cx.shared("theme")); 69 let mut colors = col().key("colors").w_full().gap(8.0); 70 for i in 0..ROLES.len() { colors = colors.child(self.role(cx, &t, &s, i)) } 71 let fill = |f: f32| bar(t, f); 72 let size = format!("{} pt", s.size); 73 let body = col().w_full().gap(16.0).pr(8.0) 74 .child(heading(&t, "Colors")).child(colors) 75 .child(heading(&t, "Cards")) 76 .child(slider(&t, "transparency", "Transparency", format!("{:.0}%", s.transparency * 100.0), s.transparency / 0.9, fill, |h, f| set(h, |s| s.transparency = f * 0.9))) 77 .child(slider(&t, "blur", "Blur", format!("{:.0} pt", s.blur), s.blur / 40.0, fill, |h, f| set(h, |s| s.blur = (f * 40.0).round()))) 78 .child(slider(&t, "shadow", "Shadows", format!("{:.0}%", s.shadow * 100.0), s.shadow, fill, |h, f| set(h, |s| s.shadow = (f * 20.0).round() / 20.0))) 79 .child(heading(&t, "Text")) 80 .child(self.trigger(cx, &t, Menu::Font, "Font", or(&s.font, "App default"), t.body)) 81 .child(self.trigger(cx, &t, Menu::Mono, "Mono font", or(&s.mono, "System monospace"), t.mono)) 82 .child(self.trigger(cx, &t, Menu::Size, "Text size", &size, t.body)); 83 col().w_full().h_full().gap(8.0) 84 .child(row().key("header").w_full().center_y().gap(8.0) 85 .child(text("Theme").font(t.title).color(t.text)) 86 .child(el().grow(1.0)) 87 .child(ui::button(&t, "random", "⚄ Random", true, |h, _| set(h, random))) 88 .child(ui::button(&t, "reset", "Reset", true, |h, _| set(h, |s| *s = Settings::default()))) 89 .child(canvas::maximize(cx)) 90 .child(canvas::close(cx, "Close theme"))) 91 .child(el().w_full().h(1.0).fill(t.separator)) 92 .child(col().key("settings").w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(body)) 93 // Last, so it draws over the settings. 94 .child(self.menu.map_or_else(el, |m| self.menu(cx, &t, &s, m))) 95 } 96} 97 98impl Theme { 99 /// Colour `i` of `ROLES`: its swatch and name (a press opens its picker), and its hex field. 100 fn role(&self, cx: &Cx, t: &Look, s: &Settings, i: usize) -> El { 101 let (key, label, ..) = ROLES[i]; 102 let now = slot(&mut s.clone(), i).clone(); 103 let color = rune::color::hex(&now).unwrap_or(Color::BLACK); 104 let open = self.open.filter(|(r, _)| *r == i); 105 let hue = open.map_or_else(|| lch(color).2, |(_, h)| h); 106 let head = row().w_full().gap(10.0).center_y() 107 .child(row().key(format!("{key}-pick")).grow(1.0).min_w(0.0).gap(10.0).py(2.0).center_y().radius(6.0) 108 .role("button").label(format!("Pick {label}")).hover(t.hover) 109 .on_press_tx(on(cx.id, move |w: &mut Theme, _| w.open = if open.is_some() { None } else { Some((i, hue)) })) 110 .child(el().w(28.0).h(28.0).radius(6.0).fill(color).border(1.0, t.card_border)) 111 .child(text(label).font(t.label).color(t.text).grow(1.0).min_w(0.0).truncate()) 112 .child(text(if open.is_some() { "▴" } else { "▾" }).font(t.label).color(t.text_secondary))) 113 .child(ui::field(t, &self.hex[i].0, t.mono, "#rrggbb").key(format!("{key}-hex")).single_line().w(t.mono.size * 4.6 + 16.0) 114 .on_edit(edit(cx.id, move |w: &mut Theme| &mut w.hex[i].0))); 115 let mut out = col().key(format!("role-{key}")).w_full().gap(6.0).child(head); 116 if open.is_some() { out = out.child(picker(cx, t, i, color, hue, &now)) } 117 out 118 } 119 120 /// A dropdown's field: its label, and what's picked in `font`, opening `menu`. 121 fn trigger(&self, cx: &Cx, t: &Look, menu: Menu, label: &str, shown: &str, font: TextStyle) -> El { 122 let open = self.menu == Some(menu); 123 col().key(menu_key(menu)).w_full().gap(6.0) 124 .child(text(label).font(t.label).color(t.text)) 125 .child(row().key(ui::anchor(cx, menu_key(menu))).w_full().min_h(32.0).px(10.0).py(4.0).gap(8.0).center_y().radius(6.0) 126 .fill(t.bg).border(1.0, if open { t.accent } else { t.card_border }).hover(t.hover) 127 .role("button").label(format!("{label}: {shown}")) 128 .on_press_tx(on(cx.id, move |w: &mut Theme, _| { w.menu = if open { None } else { Some(menu) }; w.filter = TextEdit::new("") })) 129 .child(text(shown).font(font).color(t.text).grow(1.0).min_w(0.0).truncate()) 130 .child(text(if open { "▴" } else { "▾" }).font(t.label).color(t.text_secondary))) 131 } 132 133 /// The open dropdown under its field: a filter for fonts, then every option, a check on the 134 /// picked one. A pick, Escape or a click outside closes it; Enter picks the first match. 135 fn menu(&self, cx: &Cx, t: &Look, s: &Settings, menu: Menu) -> El { 136 let families = self.families.lock().unwrap(); 137 let typed = self.filter.text.trim().to_owned(); 138 let (picked, options): (String, Vec<(String, String)>) = match menu { 139 Menu::Size => (s.size.to_string(), SIZES.iter().map(|n| (n.to_string(), format!("{n} pt"))).collect()), 140 Menu::Font => (s.font.clone(), fonts("App default", &families.0, &typed)), 141 Menu::Mono => (s.mono.clone(), fonts("System monospace", &families.1, &typed)), 142 }; 143 let id = cx.id.to_owned(); 144 let close = |h: &mut HostState, id: &str| if let Some(w) = get::<Theme>(h, id) { w.menu = None }; 145 let pick = move |id: String, value: String| move |h: &mut HostState, _: &mut Tx| { set(h, |s| apply(menu, s, &value)); close(h, &id) }; 146 let mut list = col().key("options").w_full().gap(2.0); 147 for (value, shown) in &options { 148 let font = if menu == Menu::Size { TextStyle { size: value.parse().unwrap_or(13.0), ..t.body } } else { t.label }; 149 list = list.child(row().key(format!("option-{value}")).w_full().min_h(28.0).px(8.0).gap(8.0).center_y().radius(5.0) 150 .role("button").label(shown.as_str()).hover(t.hover).on_press_tx(pick(id.clone(), value.clone())) 151 .child(text(shown.as_str()).font(font).color(t.text).grow(1.0).min_w(0.0).truncate()) 152 .child(text(if *value == picked { "✓" } else { "" }).font(t.label).color(t.accent))); 153 } 154 if options.is_empty() { list = list.child(text(format!("No installed font matches. Enter uses “{typed}”.")).font(t.label).color(t.text_secondary).wrap().padding(8.0)) } 155 let mut out = ui::popover(t, col().key(format!("{}-menu", menu_key(menu))).w(if menu == Menu::Size { 160.0 } else { 320.0 }).max_h(420.0) 156 .padding(4.0).gap(4.0)) 157 .anchored_fit(ui::anchor(cx, menu_key(menu)), Side::Bottom, Align::Start, 4.0) 158 .modal(true, { let id = id.clone(); move |h: &mut HostState| close(h, &id) }); 159 if menu != Menu::Size { 160 let first = options.iter().find(|(v, _)| !v.is_empty()).map_or(typed, |(v, _)| v.clone()); 161 out = out.child(ui::field(t, &self.filter, t.label, "Filter fonts…").key("filter").single_line() 162 .on_edit(edit(cx.id, |w: &mut Theme| &mut w.filter)) 163 .on_submit(pick(id, first))); 164 } 165 out.child(col().w_full().shrink().min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(list)) 166 } 167} 168 169/// The picker under colour `i`: lightness, chroma and hue sliders drawn in the colours they 170/// give, and preset swatches. 171fn picker(cx: &Cx, t: &Look, i: usize, color: Color, hue: f32, now: &str) -> El { 172 let (key, label, l0, c0, flip) = ROLES[i]; 173 let (l, c, _) = lch(color); 174 let id = cx.id.to_owned(); 175 let put = move |h: &mut HostState, c: Color| set(h, |s| *slot(s, i) = look::rgb(c)); 176 // A neutral role's first swatch is the app's own colour. 177 let own = rune::color::hex(slot(&mut Settings::default(), i)).unwrap_or(Color::BLACK); 178 let mut picks: Vec<Color> = HUES.iter().enumerate().map(|(n, h)| if n == 0 && flip > 0.0 { own } else { oklch(l0, c0, *h) }).collect(); 179 if flip > 0.0 { picks.push(oklch(flip, 0.005, 265.0)) } 180 let mut swatches = row().w_full().gap(6.0).flex_wrap(); 181 for (n, pick) in picks.into_iter().enumerate() { 182 let hex = look::rgb(pick); 183 let border = if hex == now { (2.0, t.text) } else { (1.0, t.card_border) }; 184 swatches = swatches.child(el().key(format!("{key}-{n}")).w(22.0).h(22.0).radius(5.0).fill(pick).border(border.0, border.1) 185 .role("button").label(format!("{label} {hex}")).help(hex.clone()) 186 .on_press_tx(move |h: &mut HostState, _: &mut Tx| put(h, pick))); 187 } 188 col().key(format!("{key}-picker")).w_full().gap(10.0).padding(10.0).radius(8.0).fill(t.bg) 189 .child(slider(t, &format!("{key}-lightness"), "Lightness", format!("{:.0}%", l * 100.0), l, 190 |_| gradient(|x| oklch(x, c, hue)), move |h, f| put(h, oklch(f, c, hue)))) 191 .child(slider(t, &format!("{key}-chroma"), "Chroma", format!("{:.0}%", c / MAX_CHROMA * 100.0), c / MAX_CHROMA, 192 |_| gradient(|x| oklch(l, x * MAX_CHROMA, hue)), move |h, f| put(h, oklch(l, f * MAX_CHROMA, hue)))) 193 .child(slider(t, &format!("{key}-hue"), "Hue", format!("{hue:.0}°"), hue / 360.0, 194 |_| gradient(|x| oklch(l.clamp(0.4, 0.85), c.max(0.1), x * 360.0)), move |h, f| { 195 if let Some(w) = get::<Theme>(h, &id) { w.open = Some((i, f * 360.0)) } 196 put(h, oklch(l, c, f * 360.0)) 197 })) 198 .child(swatches) 199} 200 201/// A slider: its label and `shown` value over a `track`, its knob `frac` of the way along. A 202/// press or drag hands `apply` the fraction it's at. 203fn slider(t: &Look, key: &str, label: &str, shown: String, frac: f32, track: impl Fn(f32) -> El, apply: impl Fn(&mut HostState, f32) + 'static) -> El { 204 let frac = frac.clamp(0.0, 1.0); 205 let bar = row().key(key).w_full().h(20.0).center_y().role("slider").label(label) 206 .on_drag(move |h: &mut HostState, d: &mut Drag, _: &mut Tx| if d.phase != Phase::Up { apply(h, ((d.x - 8.0) / (d.w - 16.0).max(1.0)).clamp(0.0, 1.0)) }) 207 .child(track(frac).pin(Some(8.0), Some(6.0), Some(8.0), Some(6.0)).radius(4.0)) 208 .child(el().grow(frac)) 209 .child(el().w(16.0).h(16.0).radius(8.0).fill(t.knob).border(1.0, t.card_border).shadow(1.0, 3.0, t.knob_shadow)) 210 .child(el().grow(1.0 - frac)); 211 col().w_full().gap(4.0) 212 .child(row().w_full().gap(8.0).center_y() 213 .child(text(label).font(t.label).color(t.text).grow(1.0).min_w(0.0).truncate()) 214 .child(text(shown).font(t.label).color(t.text_secondary))) 215 .child(bar) 216} 217 218/// A track filled with the accent up to `frac`. 219fn bar(t: Look, frac: f32) -> El { 220 el().fill(t.control_off).linear_gradient(FRAC_PI_2, [(0.0, t.accent), (frac, t.accent), (frac, t.control_off), (1.0, t.control_off)]) 221} 222 223/// A track running left to right through `f(0.0)` .. `f(1.0)`. 224fn gradient(f: impl Fn(f32) -> Color) -> El { 225 el().linear_gradient(FRAC_PI_2, (0..8).map(|n| (n as f32 / 7.0, f(n as f32 / 7.0))).collect::<Vec<_>>()) 226} 227 228/// A colour's OKLCH lightness, chroma and hue in degrees. 229fn lch(c: Color) -> (f32, f32, f32) { 230 let [l, a, b, _] = c.to_oklab(); 231 (l, a.hypot(b), b.atan2(a).to_degrees().rem_euclid(360.0)) 232} 233 234/// `#rrggbb` from what's typed, with or without `#`, when it's six hex digits. 235fn parse_hex(s: &str) -> Option<String> { 236 let s = s.trim().trim_start_matches('#'); 237 (s.len() == 6 && s.chars().all(|c| c.is_ascii_hexdigit())).then(|| format!("#{}", s.to_lowercase())) 238} 239 240/// The default option named `default`, then the `families` that contain what's `typed`. 241fn fonts(default: &str, families: &[String], typed: &str) -> Vec<(String, String)> { 242 let typed = typed.to_lowercase(); 243 let matches = families.iter().filter(|f| f.to_lowercase().contains(&typed)).map(|f| (f.clone(), f.clone())); 244 (typed.is_empty().then(|| (String::new(), default.to_owned()))).into_iter().chain(matches).collect() 245} 246 247fn apply(menu: Menu, s: &mut Settings, value: &str) { 248 match menu { 249 Menu::Font => s.font = value.to_owned(), 250 Menu::Mono => s.mono = value.to_owned(), 251 Menu::Size => s.size = value.parse().unwrap_or(s.size), 252 } 253} 254 255fn menu_key(menu: Menu) -> &'static str { 256 match menu { Menu::Font => "font", Menu::Mono => "mono", Menu::Size => "size" } 257} 258 259fn or<'a>(v: &'a str, default: &'a str) -> &'a str { 260 if v.is_empty() { default } else { v } 261} 262 263fn heading(t: &Look, s: &str) -> El { 264 text(s).font(t.label).color(t.text_secondary) 265} 266 267/// The setting colour `i` of `ROLES` is kept in. 268fn slot(s: &mut Settings, i: usize) -> &mut String { 269 match i { 0 => &mut s.bg, 1 => &mut s.card, 2 => &mut s.text, 3 => &mut s.muted, _ => &mut s.accent } 270} 271 272/// Changes the shared theme with `f`. 273fn set(h: &mut HostState, f: impl FnOnce(&mut Settings)) { 274 let mut s = Settings::read(Host::live(h).shared("theme")); 275 f(&mut s); 276 share(h, "theme", &s.json()); 277} 278 279/// A random palette around one hue, light one time in four, with an accent from another part of the wheel. 280fn random(s: &mut Settings) { 281 let mut seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |d| d.as_nanos() as u64) | 1; 282 let mut r = move || { seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17; (seed >> 40) as f32 / (1u64 << 24) as f32 }; 283 let (h, c, light) = (r() * 360.0, 0.01 + r() * 0.04, r() < 0.25); 284 let accent = (h + 90.0 + r() * 180.0) % 360.0; 285 let l = 0.14 + r() * 0.08; 286 let [bg, card, text, muted, accent] = if light { 287 [oklch(0.95, c * 0.6, h), oklch(0.99, c * 0.3, h), oklch(0.23, c, h), oklch(0.5, c, h), oklch(0.6, 0.12 + r() * 0.06, accent)] 288 } else { 289 [oklch(l, c, h), oklch(l + 0.05, c, h), oklch(0.95, 0.01, h), oklch(0.72, c, h), oklch(0.72, 0.12 + r() * 0.06, accent)] 290 }; 291 (s.bg, s.card, s.text, s.muted, s.accent) = (look::rgb(bg), look::rgb(card), look::rgb(text), look::rgb(muted), look::rgb(accent)); 292} 293 294/// Installed font families matching a fontconfig pattern, sorted, each once. 295fn fc_list(pattern: &str) -> Vec<String> { 296 let out = std::process::Command::new("fc-list").args([pattern, "family"]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default(); 297 let mut v: Vec<String> = out.lines().filter_map(|l| l.split(',').next()).map(|f| f.trim().to_owned()).filter(|f| !f.is_empty()).collect(); 298 v.sort(); 299 v.dedup(); 300 v 301}