From fcba3760387e2523edb71350f8efea3bc851b21e Mon Sep 17 00:00:00 2001 From: Breadway Date: Sun, 16 Aug 2026 13:20:00 +0800 Subject: [PATCH 01/34] Add per-output palettes and window-scoped theme binding Each Hyprland/GDK connector can have its own palette and stylesheet under $XDG_RUNTIME_DIR/bread/{palettes,themes}/. GTK apps bind a widget-level provider so two windows in one process can follow different wallpapers. Bump workspace version to 0.7.4 for the tag. --- Cargo.toml | 2 +- bread-polkit/src/ui.rs | 1 + bread-theme/CHANGELOG.md | 45 +++- bread-theme/src/bin/bread-theme.rs | 160 +++++++++++++- bread-theme/src/gtk.rs | 331 +++++++++++++++++++++++++++- bread-theme/src/lib.rs | 184 +++++++++++++--- bread-theme/src/output.rs | 338 +++++++++++++++++++++++++++++ bread-theme/src/palette.rs | 13 +- 8 files changed, 1016 insertions(+), 58 deletions(-) create mode 100644 bread-theme/src/output.rs diff --git a/Cargo.toml b/Cargo.toml index edccbba..10d698a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["bakery", "bread-theme", "bread-utils", "bread-onnx", "bread-screensh resolver = "2" [workspace.package] -version = "0.7.2" +version = "0.7.4" edition = "2021" license = "MIT" authors = ["Breadway "] diff --git a/bread-polkit/src/ui.rs b/bread-polkit/src/ui.rs index 50275bd..033f171 100644 --- a/bread-polkit/src/ui.rs +++ b/bread-polkit/src/ui.rs @@ -135,6 +135,7 @@ pub fn show_prompt(app: &Application, prompt: Prompt) { panel.append(&buttons); window.set_child(Some(&panel)); + bread_theme::gtk::bind_window_auto_with_app_css(&window, |_| app_css()); let reply = prompt.reply.clone(); let cookie = prompt.cookie.clone(); diff --git a/bread-theme/CHANGELOG.md b/bread-theme/CHANGELOG.md index 2675e55..9b27493 100644 --- a/bread-theme/CHANGELOG.md +++ b/bread-theme/CHANGELOG.md @@ -1,11 +1,48 @@ # bread-theme changelog +## 0.7.4 + +Per-output (per-monitor) theming. Session-global `theme.css` remains the +fallback / focused-monitor sheet; each Hyprland/GDK connector can now have +its own palette and stylesheet. BOS still keeps bg/surface/overlay/fg +fixed — only color1–6 come from the wallpaper. + +On disk under `$XDG_RUNTIME_DIR/bread/` (same fallback as `shared_css_path`): + +- `palettes/.json` — accents only (round-trips through + `from_wal_json` / a color1–6 object; never persists pywal's light bg) +- `themes/.css` — `stylesheet()` for that palette + +New lib API: + +- `themes_dir`, `palettes_dir`, `output_css_path`, `output_palette_path`, + `sanitize_output` +- `load_palette_for`, `write_output_palette`, `write_output_css`, + `write_shared_css_from` +- `palette_from_image` (isolated `wal -i`, does not touch `~/.cache/wal`), + `generate_output`, `palette_from_json` +- `stylesheet_resolved` — inlines `@accent` / `@on-bg` / … to hex so GTK's + display-global `@define-color` cannot leak the wrong monitor's accent + +GTK (`gtk` feature): `bind_window`, `bind_window_with_app_css`, +`output_for_widget`, `bind_window_auto`, `bind_window_auto_with_app_css`. +Widget-scoped providers at `USER - 10` so they beat `apply_shared` but +lose to user CSS. Existing `apply_shared` / `apply_app_css` / +`apply_css` / `apply_user_css` are unchanged. + +CLI: `bread-theme generate-output --image | --from-json + [--shared]`. Does not write `theme.css` unless `--shared`. + ## Coordinated bump policy -`bread-theme` is consumed by `breadbar`, `breadbox`, and `breadpad` as a pinned -git dependency. A breaking change to `Palette`, `css_vars`, or the `gtk` feature -API requires all three dependents to bump their `Cargo.toml` git tag and cut a -release together. Note the impact in this file before tagging. +`bread-theme` is consumed by `breadbar`, `breadbox`, `breadpad`, and the other +GTK bread apps as a pinned git dependency. A breaking change to `Palette`, +`css_vars`, or the `gtk` feature API requires dependents to bump their +`Cargo.toml` git tag and cut a release together. Note the impact in this file +before tagging. + +**0.7.4** adds per-output bind APIs (`bind_window*`, `load_palette_for`, +`generate_output`). Apps that call those must pin `tag = "v0.7.4"`. --- diff --git a/bread-theme/src/bin/bread-theme.rs b/bread-theme/src/bin/bread-theme.rs index 266ea9c..3d7a862 100644 --- a/bread-theme/src/bin/bread-theme.rs +++ b/bread-theme/src/bin/bread-theme.rs @@ -9,6 +9,8 @@ //! # signal every running bread GUI to recolour //! bread-theme path # print the stylesheet path //! bread-theme print # render to stdout (no write) +//! bread-theme generate-output --image [--shared] +//! bread-theme generate-output --from-json [--shared] use std::process::ExitCode; @@ -25,6 +27,149 @@ fn write_and_report(verb: &str) -> ExitCode { } } +fn print_help() { + eprintln!( + "bread-theme — shared stylesheet generator\n\n\ + USAGE:\n\ + \x20 bread-theme [generate|reload|path|print]\n\ + \x20 bread-theme generate-output --image [--shared]\n\ + \x20 bread-theme generate-output --from-json [--shared]\n\n\ + generate render the pywal palette to the shared stylesheet (default)\n\ + reload re-render and signal running bread GUIs to recolour live\n\ + path print the stylesheet path ({})\n\ + print render to stdout without writing\n\ + generate-output write palettes/.json and themes/.css\n\ + \x20 --image isolated `wal -i` (does not touch ~/.cache/wal)\n\ + \x20 --from-json wal colors.json or a color1-6 object\n\ + \x20 --shared also write the session-global theme.css", + bread_theme::shared_css_path().display() + ); +} + +fn generate_output_cmd() -> ExitCode { + let args: Vec = std::env::args().skip(2).collect(); + if args.is_empty() + || args + .iter() + .any(|a| matches!(a.as_str(), "-h" | "--help" | "help")) + { + print_help(); + return if args.is_empty() { + ExitCode::FAILURE + } else { + ExitCode::SUCCESS + }; + } + + let output = args[0].as_str(); + if output.starts_with('-') { + eprintln!("bread-theme: generate-output requires an OUTPUT name (got '{output}')"); + return ExitCode::FAILURE; + } + + let mut image: Option<&str> = None; + let mut from_json: Option<&str> = None; + let mut shared = false; + let mut i = 1; + while i < args.len() { + match args[i].as_str() { + "--shared" => shared = true, + "--image" => { + i += 1; + match args.get(i) { + Some(p) => image = Some(p.as_str()), + None => { + eprintln!("bread-theme: --image requires a path"); + return ExitCode::FAILURE; + } + } + } + "--from-json" => { + i += 1; + match args.get(i) { + Some(p) => from_json = Some(p.as_str()), + None => { + eprintln!("bread-theme: --from-json requires a path"); + return ExitCode::FAILURE; + } + } + } + other => { + eprintln!("bread-theme: unknown generate-output flag '{other}'"); + return ExitCode::FAILURE; + } + } + i += 1; + } + + match (image, from_json) { + (Some(_), Some(_)) => { + eprintln!("bread-theme: pass only one of --image or --from-json"); + ExitCode::FAILURE + } + (None, None) => { + eprintln!("bread-theme: generate-output needs --image or --from-json "); + ExitCode::FAILURE + } + (Some(path), None) => { + match bread_theme::generate_output(output, std::path::Path::new(path)) { + Ok(css) => finish_generate_output(output, css, shared), + Err(e) => { + eprintln!("bread-theme: generate-output failed: {e}"); + ExitCode::FAILURE + } + } + } + (None, Some(path)) => match write_output_from_json(output, path, shared) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("bread-theme: generate-output failed: {e}"); + ExitCode::FAILURE + } + }, + } +} + +fn write_output_from_json(output: &str, json_path: &str, shared: bool) -> std::io::Result<()> { + let json = std::fs::read_to_string(json_path)?; + let palette = bread_theme::palette_from_json(&json).ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("could not parse palette JSON: {json_path}"), + ) + })?; + let pal_path = bread_theme::write_output_palette(output, &palette)?; + let css_path = bread_theme::write_output_css(output, &palette)?; + eprintln!( + "bread-theme: wrote {} and {}", + pal_path.display(), + css_path.display() + ); + if shared { + let shared_path = bread_theme::write_shared_css_from(&palette)?; + eprintln!("bread-theme: wrote shared {}", shared_path.display()); + } + Ok(()) +} + +fn finish_generate_output(output: &str, css: std::path::PathBuf, shared: bool) -> ExitCode { + eprintln!("bread-theme: wrote {}", css.display()); + if shared { + match bread_theme::write_shared_css_from(&bread_theme::load_palette_for(output)) { + Ok(path) => { + eprintln!("bread-theme: wrote shared {}", path.display()); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("bread-theme: failed to write shared stylesheet: {e}"); + ExitCode::FAILURE + } + } + } else { + ExitCode::SUCCESS + } +} + fn main() -> ExitCode { let cmd = std::env::args().nth(1).unwrap_or_else(|| "generate".into()); match cmd.as_str() { @@ -42,20 +187,15 @@ fn main() -> ExitCode { // the file monitor in every running bread GUI, so they all re-read the // palette and recolour live — shared widgets *and* each app's own rules. "reload" => write_and_report("reloaded"), + "generate-output" => generate_output_cmd(), "-h" | "--help" | "help" => { - eprintln!( - "bread-theme — shared stylesheet generator\n\n\ - USAGE:\n bread-theme [generate|reload|path|print]\n\n\ - generate render the pywal palette to the shared stylesheet (default)\n\ - reload re-render and signal running bread GUIs to recolour live\n\ - path print the stylesheet path ({})\n\ - print render to stdout without writing", - bread_theme::shared_css_path().display() - ); + print_help(); ExitCode::SUCCESS } other => { - eprintln!("bread-theme: unknown command '{other}' (try generate|reload|path|print)"); + eprintln!( + "bread-theme: unknown command '{other}' (try generate|reload|path|print|generate-output)" + ); ExitCode::FAILURE } } diff --git a/bread-theme/src/gtk.rs b/bread-theme/src/gtk.rs index fb759c7..43e450d 100644 --- a/bread-theme/src/gtk.rs +++ b/bread-theme/src/gtk.rs @@ -1,8 +1,18 @@ +use gtk4::gdk::prelude::*; use gtk4::gio; +use gtk4::glib::object::ObjectType; use gtk4::prelude::*; use gtk4::CssProvider; use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; use std::path::Path; +use std::rc::Rc; + +use crate::Palette; + +/// Above APPLICATION (600) so we beat [`apply_shared`], below USER (800) +/// so `apply_user_css` still wins. +const BIND_PRIORITY: u32 = gtk4::STYLE_PROVIDER_PRIORITY_USER - 10; thread_local! { static SHARED_PROVIDER: RefCell> = const { RefCell::new(None) }; @@ -14,8 +24,7 @@ thread_local! { } fn reload_shared() { - let css = std::fs::read_to_string(crate::shared_css_path()) - .unwrap_or_else(|_| crate::render()); + let css = std::fs::read_to_string(crate::shared_css_path()).unwrap_or_else(|_| crate::render()); SHARED_PROVIDER.with(|cell| apply_css(&css, cell)); } @@ -121,7 +130,10 @@ pub fn apply_css(css: &str, provider: &RefCell>) { /// breadpad, and breadman (both cream), none of which agreed with each /// other or with the shared token. pub fn chip(label: &str) -> gtk4::Button { - gtk4::Button::builder().label(label).css_classes(["chip"]).build() + gtk4::Button::builder() + .label(label) + .css_classes(["chip"]) + .build() } /// Toggles a chip's (or any widget's) `active` CSS class — the `.chip.active` @@ -137,6 +149,319 @@ pub fn set_chip_active(chip: &impl IsA, active: bool) { } } +/// Gdk connector for the monitor currently showing this widget, if any. +pub fn output_for_widget(widget: &impl IsA) -> Option { + let widget = widget.as_ref(); + let native = widget.native()?; + let surface = NativeExt::surface(&native)?; + let monitor = widget.display().monitor_at_surface(&surface)?; + monitor.connector().map(|c| c.to_string()) +} + +struct WidgetBind { + output: String, + theme: CssProvider, + app: Option, + app_build: Option String>>, + /// Keep the directory monitor + child model alive for this widget. + _watch: Option, +} + +thread_local! { + static BINDS: RefCell> = RefCell::new(HashMap::new()); + static THEMES_MONITOR: RefCell> = const { RefCell::new(None) }; + static DESTROY_HOOKED: RefCell> = RefCell::new(HashSet::new()); + static AUTO_HOOKED: RefCell> = RefCell::new(HashSet::new()); + static ENTER_HOOKED: RefCell> = RefCell::new(HashSet::new()); +} + +fn widget_key(widget: >k4::Widget) -> usize { + widget.as_ptr() as usize +} + +#[allow(deprecated)] +fn add_widget_provider(widget: >k4::Widget, provider: &CssProvider, prio: u32) { + widget.style_context().add_provider(provider, prio); +} + +/// Same `CssProvider` on the widget and its current descendants so component +/// rules actually reach buttons/labels (a style-context provider is not +/// inherited by children). +fn attach_tree(widget: >k4::Widget, theme: &CssProvider, app: Option<&CssProvider>) { + add_widget_provider(widget, theme, BIND_PRIORITY); + if let Some(app) = app { + add_widget_provider(widget, app, BIND_PRIORITY + 1); + } + let mut child = widget.first_child(); + while let Some(c) = child { + attach_tree(&c, theme, app); + child = c.next_sibling(); + } +} + +fn ensure_destroy_cleanup(widget: >k4::Widget) { + let key = widget_key(widget); + let inserted = DESTROY_HOOKED.with(|s| s.borrow_mut().insert(key)); + if !inserted { + return; + } + widget.connect_destroy(move |w| { + let key = widget_key(w); + BINDS.with(|b| { + b.borrow_mut().remove(&key); + }); + DESTROY_HOOKED.with(|s| { + s.borrow_mut().remove(&key); + }); + AUTO_HOOKED.with(|s| { + s.borrow_mut().remove(&key); + }); + }); +} + +fn ensure_themes_watch() { + THEMES_MONITOR.with(|cell| { + if cell.borrow().is_some() { + return; + } + let dir = crate::themes_dir(); + let _ = std::fs::create_dir_all(&dir); + let monitor = gio::File::for_path(&dir) + .monitor_directory(gio::FileMonitorFlags::WATCH_MOVES, gio::Cancellable::NONE) + .ok(); + if let Some(ref m) = monitor { + m.connect_changed(move |_, file, other, _event| { + let path = file.path().or_else(|| other.and_then(|f| f.path())); + let Some(path) = path else { + return; + }; + if path.extension().and_then(|e| e.to_str()) != Some("css") { + return; + } + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + return; + }; + reload_binds_for_sanitized(stem); + }); + } + *cell.borrow_mut() = monitor; + }); +} + +fn reload_binds_for_sanitized(sanitized: &str) { + BINDS.with(|binds| { + for bind in binds.borrow_mut().values_mut() { + if crate::sanitize_output(&bind.output) != sanitized { + continue; + } + let palette = crate::load_palette_for(&bind.output); + bind.theme + .load_from_string(&crate::stylesheet_resolved(&palette)); + if let (Some(build), Some(provider)) = (&bind.app_build, &bind.app) { + provider.load_from_string(&crate::resolve_color_names(&build(&palette), &palette)); + } + } + }); +} + +fn watch_root_children(widget: >k4::Widget) -> gio::ListModel { + let model = widget.observe_children(); + let root = widget.downgrade(); + model.connect_items_changed(move |_, _, _, _| { + let Some(root) = root.upgrade() else { + return; + }; + let key = widget_key(&root); + BINDS.with(|binds| { + if let Some(bind) = binds.borrow().get(&key) { + attach_tree(&root, &bind.theme, bind.app.as_ref()); + } + }); + }); + model +} + +fn bind_window_inner( + widget: >k4::Widget, + output: &str, + app_build: Option String>>, +) { + let key = widget_key(widget); + let palette = crate::load_palette_for(output); + let theme_css = crate::stylesheet_resolved(&palette); + let app_css = app_build + .as_ref() + .map(|build| crate::resolve_color_names(&build(&palette), &palette)); + + BINDS.with(|binds| { + let mut map = binds.borrow_mut(); + if let Some(existing) = map.get_mut(&key) { + existing.output = output.to_string(); + existing.theme.load_from_string(&theme_css); + existing.app_build = app_build.clone(); + match (&app_css, existing.app.as_ref()) { + (Some(css), Some(p)) => p.load_from_string(css), + (Some(css), None) => { + let p = CssProvider::new(); + p.load_from_string(css); + add_widget_provider(widget, &p, BIND_PRIORITY + 1); + existing.app = Some(p); + } + (None, Some(p)) => p.load_from_string(""), + (None, None) => {} + } + attach_tree(widget, &existing.theme, existing.app.as_ref()); + return; + } + + let theme = CssProvider::new(); + theme.load_from_string(&theme_css); + add_widget_provider(widget, &theme, BIND_PRIORITY); + + let app = app_css.map(|css| { + let p = CssProvider::new(); + p.load_from_string(&css); + add_widget_provider(widget, &p, BIND_PRIORITY + 1); + p + }); + + attach_tree(widget, &theme, app.as_ref()); + + let child_model = watch_root_children(widget); + map.insert( + key, + WidgetBind { + output: output.to_string(), + theme, + app, + app_build, + _watch: Some(child_model), + }, + ); + }); + + ensure_destroy_cleanup(widget); + ensure_themes_watch(); + ensure_map_reattach(widget); +} + +fn ensure_map_reattach(widget: >k4::Widget) { + // `connect_map` once per widget — re-bind already lives in BINDS. + thread_local! { + static MAP_HOOKED: RefCell> = RefCell::new(HashSet::new()); + } + let key = widget_key(widget); + let inserted = MAP_HOOKED.with(|s| s.borrow_mut().insert(key)); + if !inserted { + return; + } + widget.connect_map(|w| { + BINDS.with(|binds| { + if let Some(bind) = binds.borrow().get(&widget_key(w)) { + attach_tree(w, &bind.theme, bind.app.as_ref()); + } + }); + }); + widget.connect_destroy(move |_| { + MAP_HOOKED.with(|s| { + s.borrow_mut().remove(&key); + }); + }); +} + +/// Attach a widget-level `CssProvider` with +/// `stylesheet_resolved(load_palette_for(output))` above APPLICATION so it +/// beats [`apply_shared`] for this widget tree. User CSS still wins. +/// Calling again on the same widget replaces the provider; it does not stack. +pub fn bind_window(widget: &impl IsA, output: &str) { + bind_window_inner(widget.as_ref(), output, None); +} + +/// [`bind_window`], then also apply `build(&palette)` on the same widget. +/// App CSS may still use `@accent` etc.; those names are inlined against +/// the same palette before loading. +pub fn bind_window_with_app_css(widget: &impl IsA, output: &str, build: F) +where + F: Fn(&Palette) -> String + 'static, +{ + bind_window_inner(widget.as_ref(), output, Some(Rc::new(build))); +} + +fn attach_enter_monitor(widget: >k4::Widget, build: Option String>>) { + let Some(native) = widget.native() else { + return; + }; + let Some(surface) = NativeExt::surface(&native) else { + return; + }; + let surf_key = surface.as_ptr() as usize; + let already = ENTER_HOOKED.with(|s| !s.borrow_mut().insert(surf_key)); + if already { + return; + } + let widget = widget.clone(); + surface.connect_enter_monitor(move |_, monitor| { + let Some(conn) = monitor.connector() else { + return; + }; + bind_window_inner(&widget, conn.as_str(), build.clone()); + }); +} + +fn bind_auto(native: >k4::Native, build: Option String>>) { + let widget = native.upcast_ref::().clone(); + + let apply = { + let widget = widget.clone(); + let build = build.clone(); + Rc::new(move || { + if let Some(output) = output_for_widget(&widget) { + bind_window_inner(&widget, &output, build.clone()); + } + }) + }; + + apply(); + + let key = widget_key(&widget); + let inserted = AUTO_HOOKED.with(|s| s.borrow_mut().insert(key)); + if inserted { + widget.connect_realize({ + let apply = apply.clone(); + let widget = widget.clone(); + let build = build.clone(); + move |_| { + apply(); + attach_enter_monitor(&widget, build.clone()); + } + }); + widget.connect_map({ + let apply = apply.clone(); + move |_| apply() + }); + ensure_destroy_cleanup(&widget); + } + + if widget.is_realized() { + attach_enter_monitor(&widget, build); + } +} + +/// Realize + `GdkSurface::enter-monitor`: rebind when the window moves +/// outputs. If the connector is unknown, leave unbound (display fallback) +/// rather than guessing the wrong monitor. +pub fn bind_window_auto(window: &impl IsA) { + bind_auto(window.as_ref(), None); +} + +/// [`bind_window_auto`] plus per-output app CSS, resolved to hex. +pub fn bind_window_auto_with_app_css(window: &impl IsA, build: F) +where + F: Fn(&Palette) -> String + 'static, +{ + bind_auto(window.as_ref(), Some(Rc::new(build))); +} + /// Apply a user CSS override file at USER priority. Clears the provider if the /// file is absent so stale overrides don't persist across SIGHUP reloads. pub fn apply_user_css(path: &Path, provider: &RefCell>) { diff --git a/bread-theme/src/lib.rs b/bread-theme/src/lib.rs index 15058fb..f280027 100644 --- a/bread-theme/src/lib.rs +++ b/bread-theme/src/lib.rs @@ -1,9 +1,15 @@ -pub mod palette; -#[cfg(feature = "gtk")] -pub mod gtk; #[cfg(feature = "adw")] pub mod adw; +#[cfg(feature = "gtk")] +pub mod gtk; +mod output; +pub mod palette; +pub use output::{ + generate_output, load_palette_for, output_css_path, output_palette_path, palette_from_image, + palette_from_json, palettes_dir, sanitize_output, themes_dir, write_output_css, + write_output_palette, write_shared_css_from, +}; pub use palette::{load_palette, Palette}; /// Design tokens from BREAD_DESIGN_SYSTEM.md. @@ -53,7 +59,11 @@ pub fn luminance(hex: &str) -> f32 { let h = hex.trim_start_matches('#'); let lin = |i: usize| -> f32 { let c = u8::from_str_radix(h.get(i..i + 2).unwrap_or("00"), 16).unwrap_or(0) as f32 / 255.0; - if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } }; 0.2126 * lin(0) + 0.7152 * lin(2) + 0.0722 * lin(4) } @@ -64,7 +74,11 @@ pub fn luminance(hex: &str) -> f32 { /// text readable no matter how light or dark pywal makes a given palette slot, /// without altering the palette colours themselves. pub fn ink_on(hex: &str) -> &'static str { - if luminance(hex) > 0.179 { "#11111b" } else { "#f5f5f5" } + if luminance(hex) > 0.179 { + "#11111b" + } else { + "#f5f5f5" + } } /// Canonical (name, value) list: the single naming all bread apps share. @@ -143,9 +157,18 @@ pub fn css_tokens() -> String { \x20\x20--radius-tertiary: {r3}px;\n\ \x20\x20--radius-pill: {pill}px;\n\ }}\n", - font = FONT_FAMILY, base = FONT_SIZE_BASE, sec = FONT_SIZE_SECONDARY, - xs = SPACE_XS, sm = SPACE_SM, md = SPACE_MD, lg = SPACE_LG, xl = SPACE_XL, - r1 = RADIUS_PRIMARY, r2 = RADIUS_SECONDARY, r3 = RADIUS_TERTIARY, pill = RADIUS_PILL, + font = FONT_FAMILY, + base = FONT_SIZE_BASE, + sec = FONT_SIZE_SECONDARY, + xs = SPACE_XS, + sm = SPACE_SM, + md = SPACE_MD, + lg = SPACE_LG, + xl = SPACE_XL, + r1 = RADIUS_PRIMARY, + r2 = RADIUS_SECONDARY, + r3 = RADIUS_TERTIARY, + pill = RADIUS_PILL, ) } @@ -261,28 +284,33 @@ pub fn render() -> String { /// `bread-theme generate` CLI writes it. Per-session under `XDG_RUNTIME_DIR`, /// falling back to the cache dir. pub fn shared_css_path() -> std::path::PathBuf { - if let Ok(rt) = std::env::var("XDG_RUNTIME_DIR") { - if !rt.is_empty() { - return std::path::PathBuf::from(rt).join("bread").join("theme.css"); - } - } - dirs::cache_dir() - .unwrap_or_else(|| std::path::PathBuf::from("/tmp")) - .join("bread") - .join("theme.css") + output::runtime_bread_dir().join("theme.css") } /// Write the shared stylesheet to [`shared_css_path`] (atomic rename). Returns /// the path written. Used by the `bread-theme` CLI. pub fn write_shared_css() -> std::io::Result { - let path = shared_css_path(); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; + write_shared_css_from(&load_palette()) +} + +/// `stylesheet()` with `@name` references in rule bodies replaced by hex. +/// Longer names first (`on-surface` before `surface`, `on-bg` before `bg`) +/// so a prefix match cannot half-replace `@on-bg`. +pub fn stylesheet_resolved(p: &Palette) -> String { + resolve_color_names(&stylesheet(p), p) +} + +/// Replace `@define-color` names (`@accent`, `@on-bg`, …) with hex values. +/// Used by [`stylesheet_resolved`] and by GTK `bind_window` so display-global +/// named colors cannot leak the wrong monitor's accent. +pub(crate) fn resolve_color_names(css: &str, p: &Palette) -> String { + let mut pairs: Vec<(&str, String)> = color_pairs(p).into_iter().collect(); + pairs.sort_by(|a, b| b.0.len().cmp(&a.0.len())); + let mut out = css.to_string(); + for (name, value) in pairs { + out = out.replace(&format!("@{name}"), &value); } - let tmp = path.with_extension("css.tmp"); - std::fs::write(&tmp, render())?; - std::fs::rename(&tmp, &path)?; - Ok(path) + out } /// Convert a `#rrggbb` hex colour to `rgba(r, g, b, alpha)`. @@ -301,8 +329,13 @@ mod tests { #[test] fn css_vars_contains_all_define_color_names() { let css = css_vars(&Palette::default()); - for name in &["bg", "fg", "surface", "red", "green", "yellow", "blue", "pink", "teal", "overlay"] { - assert!(css.contains(&format!("@define-color {name} ")), "missing @define-color {name}"); + for name in &[ + "bg", "fg", "surface", "red", "green", "yellow", "blue", "pink", "teal", "overlay", + ] { + assert!( + css.contains(&format!("@define-color {name} ")), + "missing @define-color {name}" + ); } } @@ -322,8 +355,18 @@ mod tests { // color name — the illegible-text bug. css_vars() must now emit // exactly the same color set as the full stylesheet. let css = css_vars(&Palette::default()); - for name in &["accent", "on-bg", "on-surface", "on-accent", "on-red", "on-overlay"] { - assert!(css.contains(&format!("@define-color {name} ")), "missing @define-color {name}"); + for name in &[ + "accent", + "on-bg", + "on-surface", + "on-accent", + "on-red", + "on-overlay", + ] { + assert!( + css.contains(&format!("@define-color {name} ")), + "missing @define-color {name}" + ); } } @@ -334,7 +377,16 @@ mod tests { let p = Palette::default(); let vars = css_vars(&p); let sheet = stylesheet(&p); - for name in &["bg", "fg", "surface", "overlay", "accent", "on-bg", "on-surface", "on-accent"] { + for name in &[ + "bg", + "fg", + "surface", + "overlay", + "accent", + "on-bg", + "on-surface", + "on-accent", + ] { let needle = format!("@define-color {name} "); assert!(vars.contains(&needle) && sheet.contains(&needle)); } @@ -344,10 +396,21 @@ mod tests { fn stylesheet_defines_canonical_colors_and_components() { let css = stylesheet(&Palette::default()); for name in &["bg", "fg", "surface", "overlay", "accent", "red", "blue"] { - assert!(css.contains(&format!("@define-color {name} ")), "missing @define-color {name}"); + assert!( + css.contains(&format!("@define-color {name} ")), + "missing @define-color {name}" + ); } // a representative spread of the shared component selectors - for sel in &["button", "entry", "switch:checked", ".card", ".sidebar", "scrollbar slider", ".page-title"] { + for sel in &[ + "button", + "entry", + "switch:checked", + ".card", + ".sidebar", + "scrollbar slider", + ".page-title", + ] { assert!(css.contains(sel), "stylesheet missing selector: {sel}"); } assert!(css.contains("Varela Round")); @@ -362,7 +425,10 @@ mod tests { let gtk = define_colors(&p); let web = css_custom_properties(&p); for (name, _) in color_pairs(&p) { - assert!(gtk.contains(&format!("@define-color {name} ")), "gtk missing {name}"); + assert!( + gtk.contains(&format!("@define-color {name} ")), + "gtk missing {name}" + ); assert!(web.contains(&format!("--{name}: ")), "web missing {name}"); } } @@ -409,7 +475,10 @@ mod tests { fn stylesheet_defines_on_colors() { let css = stylesheet(&Palette::default()); for name in &["on-bg", "on-surface", "on-accent", "on-red", "on-overlay"] { - assert!(css.contains(&format!("@define-color {name} ")), "missing @define-color {name}"); + assert!( + css.contains(&format!("@define-color {name} ")), + "missing @define-color {name}" + ); } } @@ -418,13 +487,58 @@ mod tests { // A bare `label { color: ... }` would override container colours on child // labels — the bug that made coloured-background text illegible. let css = stylesheet(&Palette::default()); - assert!(!css.contains("label { color:"), "blanket label colour rule reintroduced"); + assert!( + !css.contains("label { color:"), + "blanket label colour rule reintroduced" + ); } #[test] fn shared_css_path_uses_runtime_dir() { + let _lock = crate::output::XDG_ENV_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); std::env::set_var("XDG_RUNTIME_DIR", "/run/user/1234"); - assert_eq!(shared_css_path(), std::path::PathBuf::from("/run/user/1234/bread/theme.css")); + assert_eq!( + shared_css_path(), + std::path::PathBuf::from("/run/user/1234/bread/theme.css") + ); + } + + #[test] + fn stylesheet_resolved_inlines_color4_and_drops_named_refs_in_rules() { + let mut p = Palette::default(); + p.color4 = "#7aa2f7".into(); + let css = stylesheet_resolved(&p); + assert!(css.contains("#7aa2f7"), "color4 must appear as hex: {css}"); + // Rule bodies must not keep named colors — GTK display-global + // @define-color would otherwise leak the wrong monitor's accent. + let rules = css + .lines() + .filter(|l| !l.trim_start().starts_with("@define-color")) + .collect::>() + .join("\n"); + assert!( + !rules.contains("@accent"), + "leftover @accent in rules:\n{rules}" + ); + assert!( + !rules.contains("@on-bg"), + "leftover @on-bg in rules:\n{rules}" + ); + assert!( + !rules.contains("@on-surface"), + "leftover @on-surface in rules:\n{rules}" + ); + assert!( + !rules.contains("@on-accent"), + "leftover @on-accent in rules:\n{rules}" + ); + // Longer names first: @on-bg must not become @on-#... + assert!( + !rules.contains("@on-#"), + "half-replaced on-* name:\n{rules}" + ); } #[test] diff --git a/bread-theme/src/output.rs b/bread-theme/src/output.rs new file mode 100644 index 0000000..4f2f069 --- /dev/null +++ b/bread-theme/src/output.rs @@ -0,0 +1,338 @@ +//! Per-output (per-monitor) palette and stylesheet paths under +//! `$XDG_RUNTIME_DIR/bread/{palettes,themes}/`. + +use serde::Serialize; +use std::path::{Path, PathBuf}; + +use crate::palette::{from_wal_json, Palette}; +use crate::{load_palette, stylesheet}; + +/// Session-scoped `$XDG_RUNTIME_DIR/bread`, same fallback as [`crate::shared_css_path`]. +pub(crate) fn runtime_bread_dir() -> PathBuf { + if let Ok(rt) = std::env::var("XDG_RUNTIME_DIR") { + if !rt.is_empty() { + return PathBuf::from(rt).join("bread"); + } + } + dirs::cache_dir() + .unwrap_or_else(|| PathBuf::from("/tmp")) + .join("bread") +} + +/// Keep `[A-Za-z0-9._-]`; replace everything else with `_`. +pub fn sanitize_output(output: &str) -> String { + let s: String = output + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { + c + } else { + '_' + } + }) + .collect(); + if s.is_empty() { + "_".into() + } else { + s + } +} + +pub fn themes_dir() -> PathBuf { + runtime_bread_dir().join("themes") +} + +pub fn palettes_dir() -> PathBuf { + runtime_bread_dir().join("palettes") +} + +pub fn output_css_path(output: &str) -> PathBuf { + themes_dir().join(format!("{}.css", sanitize_output(output))) +} + +pub fn output_palette_path(output: &str) -> PathBuf { + palettes_dir().join(format!("{}.json", sanitize_output(output))) +} + +fn atomic_write(path: &Path, contents: &str) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let tmp = match path.file_name().and_then(|n| n.to_str()) { + Some(name) => path.with_file_name(format!("{name}.tmp")), + None => path.with_extension("tmp"), + }; + std::fs::write(&tmp, contents)?; + std::fs::rename(&tmp, path)?; + Ok(()) +} + +/// Accents only — never persist pywal's light background/surface/overlay/fg. +#[derive(Serialize)] +struct StoredColors { + color1: String, + color2: String, + color3: String, + color4: String, + color5: String, + color6: String, +} + +#[derive(Serialize)] +struct StoredPalette { + colors: StoredColors, +} + +/// Parse on-disk JSON: wal `colors.json` shape, or a flat `{color1..color6}` object. +/// Always forces FIXED background/foreground/color0/color7 via [`from_wal_json`]. +pub fn palette_from_json(json: &str) -> Option { + let value: serde_json::Value = serde_json::from_str(json).ok()?; + if value + .get("colors") + .and_then(|c| c.as_object()) + .is_some_and(|o| !o.is_empty()) + { + return from_wal_json(json); + } + if value.get("color1").is_some() + || value.get("color2").is_some() + || value.get("color3").is_some() + || value.get("color4").is_some() + || value.get("color5").is_some() + || value.get("color6").is_some() + { + let wrapped = serde_json::json!({ "colors": value }); + return from_wal_json(&wrapped.to_string()); + } + from_wal_json(json) +} + +/// Load `palettes/.json`; fall back to [`load_palette`]. +pub fn load_palette_for(output: &str) -> Palette { + std::fs::read_to_string(output_palette_path(output)) + .ok() + .and_then(|s| palette_from_json(&s)) + .unwrap_or_else(load_palette) +} + +pub fn write_output_palette(output: &str, palette: &Palette) -> std::io::Result { + let path = output_palette_path(output); + let stored = StoredPalette { + colors: StoredColors { + color1: palette.color1.clone(), + color2: palette.color2.clone(), + color3: palette.color3.clone(), + color4: palette.color4.clone(), + color5: palette.color5.clone(), + color6: palette.color6.clone(), + }, + }; + let json = serde_json::to_string_pretty(&stored) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; + atomic_write(&path, &json)?; + Ok(path) +} + +pub fn write_output_css(output: &str, palette: &Palette) -> std::io::Result { + let path = output_css_path(output); + atomic_write(&path, &stylesheet(palette))?; + Ok(path) +} + +/// Like [`crate::write_shared_css`] but from an explicit palette. +pub fn write_shared_css_from(palette: &Palette) -> std::io::Result { + let path = crate::shared_css_path(); + atomic_write(&path, &stylesheet(palette))?; + Ok(path) +} + +/// Isolated `wal -i -n -q` with `XDG_CACHE_HOME` set to a unique temp +/// dir so the user's `~/.cache/wal` is not clobbered. +pub fn palette_from_image(path: &Path) -> std::io::Result { + let pid = std::process::id(); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + let tmp = std::env::temp_dir().join(format!("bread-theme-wal-{pid}-{nanos}")); + std::fs::create_dir_all(&tmp)?; + struct Rm(PathBuf); + impl Drop for Rm { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let _guard = Rm(tmp.clone()); + + // Classic pywal ignores XDG_CACHE_HOME and writes $HOME/.cache/wal. + // Point HOME at the temp dir so a per-output extract cannot clobber + // the session cache (or the other monitor's last `wal -i`). + let status = match std::process::Command::new("wal") + .arg("-i") + .arg(path) + .args(["-n", "-q"]) + .env("HOME", &tmp) + .env("XDG_CACHE_HOME", tmp.join(".cache")) + .status() + { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + "wal is not installed", + )); + } + Err(e) => return Err(e), + Ok(s) => s, + }; + if !status.success() { + return Err(std::io::Error::new( + std::io::ErrorKind::Other, + format!("wal failed with {status}"), + )); + } + + let json_path = [ + tmp.join(".cache").join("wal").join("colors.json"), + tmp.join("wal").join("colors.json"), + ] + .into_iter() + .find(|p| p.is_file()) + .ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::NotFound, + "wal did not write colors.json under the isolated cache", + ) + })?; + let json = std::fs::read_to_string(&json_path)?; + from_wal_json(&json).ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + "wal produced unparseable colors.json", + ) + }) +} + +/// [`palette_from_image`] + [`write_output_palette`] + [`write_output_css`]. +pub fn generate_output(output: &str, image: &Path) -> std::io::Result { + let palette = palette_from_image(image)?; + write_output_palette(output, &palette)?; + write_output_css(output, &palette) +} + +#[cfg(test)] +pub(crate) static XDG_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[cfg(test)] +mod tests { + use super::*; + use crate::palette::{FIXED_BACKGROUND, FIXED_FOREGROUND, FIXED_OVERLAY, FIXED_SURFACE}; + + fn lock_xdg() -> std::sync::MutexGuard<'static, ()> { + XDG_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn with_runtime_dir(f: impl FnOnce(&Path) -> T) -> T { + let _lock = lock_xdg(); + let dir = std::env::temp_dir().join(format!( + "bread-theme-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let old = std::env::var("XDG_RUNTIME_DIR").ok(); + std::env::set_var("XDG_RUNTIME_DIR", &dir); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&dir))); + match old { + Some(v) => std::env::set_var("XDG_RUNTIME_DIR", v), + None => std::env::remove_var("XDG_RUNTIME_DIR"), + } + let _ = std::fs::remove_dir_all(&dir); + match result { + Ok(v) => v, + Err(e) => std::panic::resume_unwind(e), + } + } + + #[test] + fn sanitize_output_keeps_hyprland_connectors() { + assert_eq!(sanitize_output("HDMI-A-1"), "HDMI-A-1"); + assert_eq!(sanitize_output("eDP-1"), "eDP-1"); + assert_eq!(sanitize_output("DP-2"), "DP-2"); + } + + #[test] + fn sanitize_output_replaces_unsafe_chars() { + assert_eq!(sanitize_output("HDMI A:1"), "HDMI_A_1"); + assert_eq!(sanitize_output("foo/bar"), "foo_bar"); + assert_eq!(sanitize_output(""), "_"); + assert_eq!(sanitize_output("..ok_name-1"), "..ok_name-1"); + } + + #[test] + fn output_paths_use_sanitize_and_sit_under_dirs() { + let _lock = lock_xdg(); + std::env::set_var("XDG_RUNTIME_DIR", "/run/user/1234"); + let css = output_css_path("HDMI A:1"); + let pal = output_palette_path("HDMI A:1"); + assert_eq!(css, themes_dir().join("HDMI_A_1.css")); + assert_eq!(pal, palettes_dir().join("HDMI_A_1.json")); + assert!(css.starts_with(themes_dir())); + assert!(pal.starts_with(palettes_dir())); + assert_eq!( + output_css_path("eDP-1"), + PathBuf::from("/run/user/1234/bread/themes/eDP-1.css") + ); + } + + #[test] + fn load_palette_for_missing_file_has_fixed_bg() { + with_runtime_dir(|_| { + let p = load_palette_for("no-such-output"); + assert_eq!(p.background, FIXED_BACKGROUND); + assert!(p.color4.starts_with('#')); + }); + } + + #[test] + fn write_output_palette_roundtrips_color4() { + with_runtime_dir(|_| { + let mut p = Palette::default(); + p.color4 = "#7aa2f7".into(); + p.background = "#ffffff".into(); + write_output_palette("HDMI-A-1", &p).unwrap(); + let loaded = load_palette_for("HDMI-A-1"); + assert_eq!(loaded.color4, "#7aa2f7"); + assert_eq!(loaded.background, FIXED_BACKGROUND); + assert_eq!(loaded.foreground, FIXED_FOREGROUND); + assert_eq!(loaded.color0, FIXED_SURFACE); + assert_eq!(loaded.color7, FIXED_OVERLAY); + }); + } + + #[test] + fn write_shared_css_from_writes_shared_css_path() { + with_runtime_dir(|rt| { + let path = write_shared_css_from(&Palette::default()).unwrap(); + assert_eq!(path, crate::shared_css_path()); + assert_eq!(path, rt.join("bread").join("theme.css")); + let css = std::fs::read_to_string(&path).unwrap(); + assert!(css.contains("@define-color accent ")); + }); + } + + #[test] + fn load_palette_for_accepts_flat_color_object() { + with_runtime_dir(|_| { + let path = output_palette_path("DP-1"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, r##"{"color4":"#112233","color1":"#abcdef"}"##).unwrap(); + let p = load_palette_for("DP-1"); + assert_eq!(p.color4, "#112233"); + assert_eq!(p.color1, "#abcdef"); + assert_eq!(p.background, FIXED_BACKGROUND); + }); + } +} diff --git a/bread-theme/src/palette.rs b/bread-theme/src/palette.rs index 85a8aa7..e51f6b0 100644 --- a/bread-theme/src/palette.rs +++ b/bread-theme/src/palette.rs @@ -9,10 +9,10 @@ use std::path::PathBuf; /// off-hue background, and every bread GUI's panels inherit it — the app /// stops looking like a dark BOS tool and starts looking like whatever colour /// the wallpaper happened to be. -const FIXED_BACKGROUND: &str = "#0c0c0c"; -const FIXED_FOREGROUND: &str = "#e8e8e8"; -const FIXED_SURFACE: &str = "#1a1a1a"; -const FIXED_OVERLAY: &str = "#d8d8d8"; +pub(crate) const FIXED_BACKGROUND: &str = "#0c0c0c"; +pub(crate) const FIXED_FOREGROUND: &str = "#e8e8e8"; +pub(crate) const FIXED_SURFACE: &str = "#1a1a1a"; +pub(crate) const FIXED_OVERLAY: &str = "#d8d8d8"; /// Accent fallback when no pywal palette exists yet (fresh install, before /// any wallpaper has been set for real) — BOS's own bread-toned accents, @@ -84,7 +84,10 @@ pub fn load_palette() -> Palette { pub(crate) fn from_wal_json(json: &str) -> Option { let wal: WalColors = serde_json::from_str(json).ok()?; let c = |k: &str, fallback: &str| -> String { - wal.colors.get(k).cloned().unwrap_or_else(|| fallback.into()) + wal.colors + .get(k) + .cloned() + .unwrap_or_else(|| fallback.into()) }; Some(Palette { background: FIXED_BACKGROUND.into(), From a9754d90ed32efcc26765abd01c9f441bfb01b1e Mon Sep 17 00:00:00 2001 From: Breadway Date: Sun, 16 Aug 2026 13:28:18 +0800 Subject: [PATCH 02/34] Lock workspace packages at 0.7.4 so --locked release builds match the tag --- Cargo.lock | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 070c24d..feaba0f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -138,7 +138,7 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "bakery" -version = "0.7.2" +version = "0.7.4" dependencies = [ "anyhow", "bread-utils", @@ -187,14 +187,14 @@ dependencies = [ [[package]] name = "bread-app" -version = "0.7.2" +version = "0.7.4" dependencies = [ "bread-utils", ] [[package]] name = "bread-capture" -version = "0.7.2" +version = "0.7.4" dependencies = [ "anyhow", "bread-utils", @@ -204,7 +204,7 @@ dependencies = [ [[package]] name = "bread-onnx" -version = "0.7.2" +version = "0.7.4" dependencies = [ "anyhow", "bread-utils", @@ -219,7 +219,7 @@ dependencies = [ [[package]] name = "bread-polkit" -version = "0.7.2" +version = "0.7.4" dependencies = [ "anyhow", "bread-app", @@ -234,7 +234,7 @@ dependencies = [ [[package]] name = "bread-screenshots" -version = "0.7.2" +version = "0.7.4" dependencies = [ "anyhow", "bread-utils", @@ -254,7 +254,7 @@ dependencies = [ [[package]] name = "bread-theme" -version = "0.7.2" +version = "0.7.4" dependencies = [ "dirs", "gtk4", @@ -265,7 +265,7 @@ dependencies = [ [[package]] name = "bread-utils" -version = "0.7.2" +version = "0.7.4" dependencies = [ "bread-shared", "dirs", From e2c6452e4f9166be6b057fbedce9796d0029d486 Mon Sep 17 00:00:00 2001 From: Breadway Date: Sun, 23 Aug 2026 14:37:08 +0800 Subject: [PATCH 03/34] ci: export VERSION for rc sign steps and drop unsafe tag path filters RC sign steps read ${VERSION} from the environment, but prepare only set it locally. Export it via GITHUB_ENV like dev-bakery.yml. Drop paths: filters on tag-triggered rc workflows (they pointed at the old beta-*.yml names and can skip an RC publish when the tag diff misses those paths); the job if: contains -rc. is the real gate. Skip -rc. tags in package.yml because PKGBUILD pkgver cannot contain a hyphen. Rebuild bakery on bread-utils changes (path dependency). --- .forgejo/workflows/dev-bakery.yml | 1 + .forgejo/workflows/package.yml | 3 +++ .forgejo/workflows/rc-bakery.yml | 9 ++++----- .forgejo/workflows/rc-bread-theme.yml | 9 ++++----- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/.forgejo/workflows/dev-bakery.yml b/.forgejo/workflows/dev-bakery.yml index f63769e..a7c4bde 100644 --- a/.forgejo/workflows/dev-bakery.yml +++ b/.forgejo/workflows/dev-bakery.yml @@ -8,6 +8,7 @@ on: branches: ['main'] paths: - 'bakery/**' + - 'bread-utils/**' - 'Cargo.toml' - 'Cargo.lock' - '.forgejo/workflows/dev-bakery.yml' diff --git a/.forgejo/workflows/package.yml b/.forgejo/workflows/package.yml index 6725e22..ca941f2 100644 --- a/.forgejo/workflows/package.yml +++ b/.forgejo/workflows/package.yml @@ -6,6 +6,9 @@ on: jobs: package: + # PKGBUILD pkgver cannot contain `-`; skip RC tags the same way + # release-bakery.yml does. + if: ${{ !contains(github.ref_name, '-rc.') }} runs-on: [self-hosted, hestia] container: image: archlinux:latest diff --git a/.forgejo/workflows/rc-bakery.yml b/.forgejo/workflows/rc-bakery.yml index dc7f695..d4e7853 100644 --- a/.forgejo/workflows/rc-bakery.yml +++ b/.forgejo/workflows/rc-bakery.yml @@ -7,11 +7,9 @@ name: beta (rc) bakery on: push: tags: ['v*'] - paths: - - 'bakery/**' - - 'Cargo.toml' - - 'Cargo.lock' - - '.forgejo/workflows/beta-bakery.yml' + # No paths: filter. Tag pushes compare against an unrelated commit and + # would skip the RC publish if bakery/** wasn't in that diff; the job + # `if: contains -rc.` is the real gate. jobs: build: @@ -35,6 +33,7 @@ jobs: run: | set -euo pipefail VERSION="${GITHUB_REF_NAME#v}" + echo "VERSION=${VERSION}" >> "$GITHUB_ENV" PKG_DIR="/srv/breadway-dl/beta/bakery/${VERSION}" mkdir -p "${PKG_DIR}" cp "src/target/release/bakery" "${PKG_DIR}/bakery-x86_64" diff --git a/.forgejo/workflows/rc-bread-theme.yml b/.forgejo/workflows/rc-bread-theme.yml index c364ce6..bd53ba1 100644 --- a/.forgejo/workflows/rc-bread-theme.yml +++ b/.forgejo/workflows/rc-bread-theme.yml @@ -7,11 +7,9 @@ name: beta (rc) bread-theme on: push: tags: ['v*'] - paths: - - 'bread-theme/**' - - 'Cargo.toml' - - 'Cargo.lock' - - '.forgejo/workflows/beta-bread-theme.yml' + # No paths: filter. Tag pushes compare against an unrelated commit and + # would skip the RC publish if bread-theme/** wasn't in that diff; the + # job `if: contains -rc.` is the real gate. jobs: build: @@ -32,6 +30,7 @@ jobs: run: | set -euo pipefail VERSION="${GITHUB_REF_NAME#v}" + echo "VERSION=${VERSION}" >> "$GITHUB_ENV" PKG_DIR="/srv/breadway-dl/beta/bread-theme/${VERSION}" mkdir -p "${PKG_DIR}" cp "src/target/release/bread-theme" "${PKG_DIR}/bread-theme-x86_64" From 4f8859527d0aab43912799528fef2af60574f334 Mon Sep 17 00:00:00 2001 From: Breadway Date: Sun, 23 Aug 2026 14:38:04 +0800 Subject: [PATCH 04/34] bread-utils: pin bread-shared to v0.8.0 The bread-client feature still resolved bread-shared from tag v0.7.0. Point the git dependency at v0.8.0 and refresh Cargo.lock. --- Cargo.lock | 50 +++++++++++++++++++++++++++++++++++------- bread-utils/Cargo.toml | 2 +- 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index feaba0f..0598260 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -145,7 +145,7 @@ dependencies = [ "chrono", "clap", "clap_complete", - "dirs", + "dirs 5.0.1", "fs4", "hex", "minisign-verify", @@ -243,20 +243,21 @@ dependencies = [ [[package]] name = "bread-shared" -version = "0.7.0" -source = "git+https://git.breadway.dev/Breadway/bread?tag=v0.7.0#22e34e2cf2202305d7960759dfccb54dc79f948b" +version = "0.8.0" +source = "git+https://git.breadway.dev/Breadway/bread?tag=v0.8.0#cdd5de8f58e437b3fc6d9b9087eb7b3d0fd09704" dependencies = [ - "dirs", + "dirs 6.0.0", "serde", "serde_json", "toml 0.8.23", + "uuid", ] [[package]] name = "bread-theme" version = "0.7.4" dependencies = [ - "dirs", + "dirs 5.0.1", "gtk4", "libadwaita", "serde", @@ -268,7 +269,7 @@ name = "bread-utils" version = "0.7.4" dependencies = [ "bread-shared", - "dirs", + "dirs 5.0.1", "gtk4", "gtk4-layer-shell", "serde", @@ -610,7 +611,16 @@ version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" dependencies = [ - "dirs-sys", + "dirs-sys 0.4.1", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys 0.5.0", ] [[package]] @@ -621,10 +631,22 @@ checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" dependencies = [ "libc", "option-ext", - "redox_users", + "redox_users 0.4.6", "windows-sys 0.48.0", ] +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.5.2", + "windows-sys 0.61.2", +] + [[package]] name = "displaydoc" version = "0.2.6" @@ -1966,6 +1988,17 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 2.0.18", +] + [[package]] name = "regex" version = "1.13.1" @@ -2703,6 +2736,7 @@ version = "1.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cefc03fd367c0c6d4305de1b312cf00248c4114f4a0418ce6a6af769e3b0bd9" dependencies = [ + "getrandom 0.4.3", "js-sys", "serde_core", "wasm-bindgen", diff --git a/bread-utils/Cargo.toml b/bread-utils/Cargo.toml index 69e2172..a0ab6c2 100644 --- a/bread-utils/Cargo.toml +++ b/bread-utils/Cargo.toml @@ -15,7 +15,7 @@ dirs = { workspace = true } gtk4 = { version = "0.11", features = ["v4_12"], optional = true } gtk4-layer-shell = { version = "0.8", optional = true } toml_edit = { version = "0.22", optional = true } -bread-shared = { git = "https://git.breadway.dev/Breadway/bread", tag = "v0.7.0", optional = true } +bread-shared = { git = "https://git.breadway.dev/Breadway/bread", tag = "v0.8.0", optional = true } [features] # Enable the layer-shell popup scaffold (breadbox, breadclip). Kept optional From f5a47490f70a66d201b38afa14814a2c45f127a7 Mon Sep 17 00:00:00 2001 From: Breadway Date: Sun, 23 Aug 2026 14:38:04 +0800 Subject: [PATCH 05/34] bread-theme: quote only the named font so sans-serif stays a fallback FONT_FAMILY is "Varela Round, sans-serif" but emission wrapped the whole string in quotes, so CSS looked up one family named that string. Emit 'Varela Round', sans-serif instead and lock that in the tests. --- bread-theme/src/lib.rs | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/bread-theme/src/lib.rs b/bread-theme/src/lib.rs index f280027..2111c17 100644 --- a/bread-theme/src/lib.rs +++ b/bread-theme/src/lib.rs @@ -32,6 +32,13 @@ pub mod tokens { pub const RADIUS_PILL: u16 = 999; } +/// CSS `font-family` list: quote the named face, leave the generic fallback +/// unquoted. Wrapping [`tokens::FONT_FAMILY`] in one pair of quotes would +/// make a single family named "Varela Round, sans-serif" and drop sans-serif. +fn css_font_family() -> &'static str { + "'Varela Round', sans-serif" +} + /// Emit the `@define-color` block that all bread apps use, plus the shared /// font rule. /// @@ -47,9 +54,9 @@ pub mod tokens { /// one color-block implementation and it cannot drift again. pub fn css_vars(p: &Palette) -> String { format!( - "{vars}* {{ font-family: '{font}'; font-size: {size}px; }}\n", + "{vars}* {{ font-family: {font}; font-size: {size}px; }}\n", vars = define_colors(p), - font = tokens::FONT_FAMILY, + font = css_font_family(), size = tokens::FONT_SIZE_BASE, ) } @@ -144,7 +151,7 @@ pub fn css_tokens() -> String { use tokens::*; format!( ":root {{\n\ - \x20\x20--font-family: '{font}';\n\ + \x20\x20--font-family: {font};\n\ \x20\x20--font-size-base: {base}px;\n\ \x20\x20--font-size-secondary: {sec}px;\n\ \x20\x20--space-xs: {xs}px;\n\ @@ -157,7 +164,7 @@ pub fn css_tokens() -> String { \x20\x20--radius-tertiary: {r3}px;\n\ \x20\x20--radius-pill: {pill}px;\n\ }}\n", - font = FONT_FAMILY, + font = css_font_family(), base = FONT_SIZE_BASE, sec = FONT_SIZE_SECONDARY, xs = SPACE_XS, @@ -182,7 +189,7 @@ pub fn stylesheet(p: &Palette) -> String { use tokens::*; format!( "{vars}\ - * {{ font-family: '{font}'; font-size: {base}px; }}\n\ + * {{ font-family: {font}; font-size: {base}px; }}\n\ /* Colour is set on containers; labels inherit it, so text on any panel,\ button, or accent is always the legible ink for that background. Bare\ `label {{ color }}` is deliberately avoided — as a type selector it\ @@ -265,7 +272,7 @@ pub fn stylesheet(p: &Palette) -> String { textview, .mono {{ font-family: monospace; }}\n\ textview text {{ background-color: @surface; color: @on-surface; }}\n", vars = define_colors(p), - font = FONT_FAMILY, + font = css_font_family(), base = FONT_SIZE_BASE, sec = FONT_SIZE_SECONDARY, xs = SPACE_XS, sm = SPACE_SM, md = SPACE_MD, lg = SPACE_LG, @@ -342,7 +349,11 @@ mod tests { #[test] fn css_vars_contains_font_rule() { let css = css_vars(&Palette::default()); - assert!(css.contains("Varela Round")); + assert!(css.contains("font-family: 'Varela Round', sans-serif;")); + assert!( + !css.contains("font-family: 'Varela Round, sans-serif'"), + "named face and generic fallback must not be one quoted family" + ); assert!(css.contains("14px")); } @@ -413,7 +424,11 @@ mod tests { ] { assert!(css.contains(sel), "stylesheet missing selector: {sel}"); } - assert!(css.contains("Varela Round")); + assert!(css.contains("font-family: 'Varela Round', sans-serif;")); + assert!( + !css.contains("font-family: 'Varela Round, sans-serif'"), + "named face and generic fallback must not be one quoted family" + ); } #[test] @@ -445,7 +460,11 @@ mod tests { #[test] fn css_tokens_contains_font_and_spacing_vars() { let css = css_tokens(); - assert!(css.contains("--font-family: 'Varela Round, sans-serif';")); + assert!(css.contains("--font-family: 'Varela Round', sans-serif;")); + assert!( + !css.contains("--font-family: 'Varela Round, sans-serif'"), + "named face and generic fallback must not be one quoted family" + ); assert!(css.contains("--font-size-base: 14px;")); assert!(css.contains("--space-md: 12px;")); assert!(css.contains("--radius-pill: 999px;")); From 347f356b1ddac442fe4b5dd7f23349a591351e74 Mon Sep 17 00:00:00 2001 From: Breadway Date: Sun, 23 Aug 2026 14:38:04 +0800 Subject: [PATCH 06/34] bread-polkit: add bakery.toml so the agent can be published later Not added to registry/bread-ecosystem.toml: that would put it on the bakery index (and risk the BOS ISO) without a lockfile update. bakery.toml declares the binary and contrib desktop file; README/CONTRIBUTING note that it stays unpublished. --- CONTRIBUTING.md | 4 +++- README.md | 8 +++++--- bread-polkit/bakery.toml | 11 +++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) create mode 100644 bread-polkit/bakery.toml diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cb4d0e1..349d06b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,9 @@ are `bakery` (the ecosystem package manager) and `bread-theme` (the shared theming crate). Shared crates that sibling apps pin — not bakery packages of their own — are `bread-utils`, `bread-app`, `bread-onnx`, `bread-screenshots`, and `bread-capture`. `bread-polkit` is an in-tree -session agent, also not a bakery product. Other ecosystem products +session agent: it has `bread-polkit/bakery.toml` so it *can* be published, +but it is not in `registry/bread-ecosystem.toml` (unpublished — not on +the bakery index, not on the BOS ISO). Other ecosystem products (`bread`, `breadbar`, `breadbox`, …) live in their own repos under `Breadway/` but follow the same workflow described here. The product list is `registry/bread-ecosystem.toml`. New GTK tools should depend on diff --git a/README.md b/README.md index 34ccf27..927c629 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ bread-ecosystem/ ├── bread-theme/ # shared pywal + fixed-dark-base theming crate ├── bread-utils/ # shared plumbing (Hyprland IPC, singleton, XDG, BreadClient, …) ├── bread-app/ # GTK bootstrap new tools should use (app id, singleton, overlay, command listen) -├── bread-polkit/ # themed PolicyKit authentication agent (not a bakery product) +├── bread-polkit/ # themed PolicyKit agent (bakery.toml present; unpublished) ├── bread-onnx/ # shared ONNX runtime helpers ├── bread-screenshots/ # grim capture primitive used by app `--screenshot` modes ├── bread-capture/ # orchestrator that drives those `--screenshot` modes @@ -179,8 +179,10 @@ tree; `bread-polkit` is the first in-tree consumer. ### bread-polkit A session PolicyKit authentication agent (password prompt, cancel, -identity). Not a wrapper around `polkit-gnome`. Not published via bakery -and not on the BOS ISO lockfile. +identity). Not a wrapper around `polkit-gnome`. `bread-polkit/bakery.toml` +exists so it can be published via bakery; it is not in +`registry/bread-ecosystem.toml` and is therefore unpublished — not on the +bakery index and not on the BOS ISO lockfile. ```sh cargo run -p bread-polkit diff --git a/bread-polkit/bakery.toml b/bread-polkit/bakery.toml new file mode 100644 index 0000000..4dd8e44 --- /dev/null +++ b/bread-polkit/bakery.toml @@ -0,0 +1,11 @@ +name = "bread-polkit" +description = "Themed PolicyKit authentication agent for the bread desktop" +binaries = ["bread-polkit"] +system_deps = ["gtk4", "gtk4-layer-shell", "polkit"] +optional_system_deps = ["hyprland"] +bread_deps = [] +license_file = "LICENSE" +desktop_file = "bread-polkit.desktop" + +[install] +post_install = [] From 96aa6a513b0fed5ff73ab9252907572032a7c482 Mon Sep 17 00:00:00 2001 From: Breadway Date: Sun, 23 Aug 2026 15:21:08 +0800 Subject: [PATCH 07/34] Add bread_theme::shell manifest system (Phase 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the shell theme manifest layer from THEME_SYSTEM_PLAN.md §4-5: ShellTheme/WindowSpec/Slots/Tokens/LayerRule types, TOML discovery (user -> system -> compiled-in builtin), one level of `extends` deep-merge, deny_unknown_fields validation naming the offending key, slot module-name validation, and css() token substitution with an extra.css overlay. load() never fails, falling back to the compiled-in builtin and logging once. Ships exactly one builtin manifest, liquid-motion, describing breadbar/breadbox as they exist today (not the design-doc demo, which disagrees with the code on bar side margin, launcher geometry, and the easing curves). Compositor rules and surface specs are keyed by layer-shell namespace and cover all five breadbar namespaces plus breadbox/breadbar-panel/breadbar-dismiss. watch() is gated behind the existing `gtk` feature (gio::FileMonitor is a gtk4 dependency); the rest of the module is gtk-free so bread and breadcrumbs can validate a theme without linking GTK. No consumer changes — breadbar/breadbox still use their own hardcoded values. --- Cargo.lock | 3 + bread-theme/Cargo.toml | 5 + .../shell/liquid-motion/liquid-motion.css | 104 ++ .../assets/shell/liquid-motion/theme.toml | 154 +++ bread-theme/src/lib.rs | 1 + bread-theme/src/shell/builtin.rs | 23 + bread-theme/src/shell/hotreload.rs | 32 + bread-theme/src/shell/manifest.rs | 518 ++++++++++ bread-theme/src/shell/mod.rs | 899 ++++++++++++++++++ bread-theme/src/shell/types.rs | 358 +++++++ 10 files changed, 2097 insertions(+) create mode 100644 bread-theme/assets/shell/liquid-motion/liquid-motion.css create mode 100644 bread-theme/assets/shell/liquid-motion/theme.toml create mode 100644 bread-theme/src/shell/builtin.rs create mode 100644 bread-theme/src/shell/hotreload.rs create mode 100644 bread-theme/src/shell/manifest.rs create mode 100644 bread-theme/src/shell/mod.rs create mode 100644 bread-theme/src/shell/types.rs diff --git a/Cargo.lock b/Cargo.lock index 0598260..5af4c11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,11 +257,14 @@ dependencies = [ name = "bread-theme" version = "0.7.4" dependencies = [ + "anyhow", "dirs 5.0.1", "gtk4", "libadwaita", "serde", "serde_json", + "toml 0.8.23", + "tracing", ] [[package]] diff --git a/bread-theme/Cargo.toml b/bread-theme/Cargo.toml index f5e1cda..7298837 100644 --- a/bread-theme/Cargo.toml +++ b/bread-theme/Cargo.toml @@ -12,6 +12,11 @@ keywords = ["theming", "pywal", "gtk4", "wayland"] serde = { workspace = true } serde_json = { workspace = true } dirs = { workspace = true } +# bread_theme::shell manifest parsing (theme.toml) — gtk-free, so `bread` +# (daemon) and `breadcrumbs` (CLI) can validate a theme without linking GTK. +toml = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } gtk4 = { version = "0.11", features = ["v4_12"], optional = true } # Rust bindings for libadwaita (GNOME's widget library on top of GTK4) — the # actual source of the modern GNOME look (grouped preference rows, real diff --git a/bread-theme/assets/shell/liquid-motion/liquid-motion.css b/bread-theme/assets/shell/liquid-motion/liquid-motion.css new file mode 100644 index 0000000..4d45d0e --- /dev/null +++ b/bread-theme/assets/shell/liquid-motion/liquid-motion.css @@ -0,0 +1,104 @@ +/* CSS template for the liquid-motion builtin (bread-theme/src/shell/builtin.rs). + * + * Curly-brace placeholders like {radius_bar} or {spring} are substituted + * from [tokens] by ShellTheme::css / Tokens::substitute; @-prefixed palette + * references (@accent, @on-bg, ...) pass through untouched, exactly like + * `bread_theme::stylesheet()` — GTK's own @define-color mechanism resolves + * them when the CSS provider is attached to a display/output. + * + * Scope: this is the window/workspace/clock chrome the manifest's own + * concepts (bar.window, modules.workspaces, modules.clock) actually model — + * not a byte-for-byte copy of breadbar/src/theme.rs::load_css's full ~250 + * lines (notification cards, wifi popover, control panel, media widget, ...). + * Those stay hand-written in breadbar for now; migrating them behind this + * same token-substitution mechanism is Phase 2/3 work (plan §6), once + * breadbar actually consumes ShellTheme and can verify pixel parity itself + * via --screenshot. Phase 1's job is the mechanism, exercised end-to-end + * here with a representative slice, not the full port. + */ + +@keyframes row-in { + from { opacity: 0; margin-top: 8px; } + to { opacity: 1; margin-top: 0; } +} +@keyframes digit-flip { + from { opacity: 0; margin-top: 7px; } + to { opacity: 1; margin-top: 0; } +} + +window.breadbar { + background-color: alpha(@bg, {bg_alpha}); + color: @on-bg; + border-radius: {radius_bar}px; + border: 1px solid alpha(@on-bg, 0.08); +} +window.breadbar > centerbox { padding: 0 8px 0 6px; } +window.breadbar button { min-height: 0; min-width: 0; } + +.workspace-trail { + background-image: linear-gradient(90deg, @{accent_from}, @{accent_to}); + background-color: @{accent_from}; + border-radius: {radius_card}px; +} +.workspace-btn { + background: transparent; + opacity: 0.36; + color: @on-bg; + border-radius: {radius_card}px; + border: none; + outline: none; + box-shadow: none; + min-width: 28px; + min-height: {chip_height}px; + margin: 0; + padding: 0 7px; + font-size: 22px; + font-weight: bold; + transition: opacity 0.22s {spring_settle}, background-color 0.22s {spring_settle}; +} +.workspace-btn:hover { opacity: 0.85; background: alpha(@on-bg, 0.08); } +.workspace-btn.occupied { opacity: 0.78; } +.workspace-btn.active { background: transparent; color: @on-accent; opacity: 1; } +.workspace-btn.active:hover { background: transparent; } +.workspace-btn.ws-in { animation: row-in 0.32s {spring_settle} both; } + +.clock-box { padding: 0 4px; } +.clock-label { + font-size: 24px; + font-weight: bold; + letter-spacing: 0.04em; + min-height: 0; + padding: 0; + margin-top: 3px; +} +.clock-digit { + font-size: 24px; + font-weight: bold; + letter-spacing: 0.04em; + min-width: 15px; + min-height: 0; + padding: 0; + margin: 0; +} +.clock-colon { min-width: 10px; opacity: 0.7; } +.clock-digit.flip { animation: digit-flip 0.45s {spring} both; } + +window.breadbar-osd { + background-color: alpha(@bg, 0.70); + color: @on-bg; + border-radius: {radius_pill}px; + border: 1px solid alpha(@on-bg, 0.10); +} + +window.breadbar-panel { + background-color: alpha(@bg, {bg_alpha}); + color: @on-bg; + border-radius: 14px; + border: 1px solid alpha(@on-bg, 0.12); +} + +window.breadbar-dismiss { + background-color: alpha(#000000, 0.02); +} + +.bread-widget-slot { margin-right: {pad}px; } diff --git a/bread-theme/assets/shell/liquid-motion/theme.toml b/bread-theme/assets/shell/liquid-motion/theme.toml new file mode 100644 index 0000000..72a8f4d --- /dev/null +++ b/bread-theme/assets/shell/liquid-motion/theme.toml @@ -0,0 +1,154 @@ +# The compiled-in builtin theme (bread-theme/src/shell/builtin.rs). Describes +# breadbar/breadbox AS THEY EXIST TODAY, not the 01-liquid-motion.html demo — +# where the two disagree (bar side margin, launcher width/top, the two easing +# curves), this file follows the current Rust source, since Phase 2's +# acceptance test is pixel-identical rendering against today's bar. +# +# Sources: breadbar/src/main.rs:16-22 (BAR_* / CHIP_HEIGHT / ICON_PX consts), +# breadbar/src/theme.rs (load_css's radius/pad/spring locals and the actual +# CSS selectors), breadbar/src/{panel,osd}.rs and +# breadbar/src/notifications/{popup,history}.rs (satellite window anchors, +# margins, namespaces), breadbox/breadbox/src/main.rs:341-344 (launcher +# geometry), ~/.config/hypr/scripts/ui/rules.lua (compositor rules). + +name = "Liquid Motion" +id = "liquid-motion" + +[tokens] +font_family = "Varela Round, sans-serif" +font_fallback = "sans-serif" +font_size_base = 14 +radius_bar = 16 +radius_card = 12 +radius_sm = 9 +# Not in the plan's §4 schema list, but a named local in theme.rs::load_css +# alongside radius_bar/radius_card/radius_sm (`radius_pill = "999px"`) — the +# OSD pill's corner radius. +radius_pill = 999 +pad = 12 +bg_alpha = 0.72 +# Two curves theme.rs actually uses, not one: `spring` is the overshoot/bounce +# curve (clock flips, pop-ins, the workspace caret draw); `spring_settle` is +# the flatter curve used for hovers and workspace/stat-pair transitions. The +# plan's §4 example names only `spring`. +spring = "cubic-bezier(0.22, 1.35, 0.36, 1)" +spring_settle = "cubic-bezier(0.22, 1.2, 0.36, 1)" +# "accent" flows through as @accent (the workspace-trail gradient's start); +# these are palette token NAMES, not hex - pywal still drives colour. +accent_from = "accent" +accent_to = "teal" +# Not in the plan's §4 schema list, but breadbar::CHIP_HEIGHT / ::ICON_PX +# today. +chip_height = 32 +icon_px = 24 + +[bar.window] +anchors = ["top", "left", "right"] +width = "fill" +height = 44 +margin = { top = 12, left = 16, right = 16 } +exclusive = "auto" +# breadbar never calls gtk4-layer-shell's set_keyboard_mode today, which +# defaults to KeyboardMode::None — spelled out explicitly here rather than +# left to omit-means-default, since "the shell must never fail to start +# because a theme file is malformed" cuts both ways: an explicit builtin +# value can't silently drift if the crate's own Default ever changes. +keyboard = "none" +layer = "top" + +[bar.slots] +left = ["workspaces"] +centre = ["media", "clock"] +right = ["volume", "wifi", "battery", "control"] +drawer = [] + +[modules.workspaces] +style = "trail" +show_empty = true + +[modules.clock] +style = "flip" +format = "%H:%M" +show_date = false + +[launcher] +# breadbox/breadbox/src/main.rs:341-344 sets vbox.set_margin_top(120) and +# vbox.set_size_request(600, -1) — the demo's "540px overlay, 16% top" is a +# design-doc approximation, not what the code does today. +mode = "overlay" +width = 600 +top = "120px" +radius = 20 +icon_px = 36 +row_anim = "flip" +rule = "gradient" +footer = "count_apps" +sections = false +modes = ["apps"] + +# Keyed by layer-shell namespace, matching [compositor.*] below, so the two +# tables share one keyspace and can be validated against each other. +# breadbar-notif's popup toast uses set_default_width(320) (its history +# sibling on the same namespace uses 360 — 320 is the live-toast surface, the +# one this positions). breadbar-panel sets no window width at all: its +# popovers size from their own CSS (.control-panel-inner / .wifi-popover-inner +# min-width), which is why its width is "auto" rather than a number. +[surfaces."breadbar-notif"] +anchor = "top_right" +offset = [16, 64] +width = 320 +layer = "overlay" + +[surfaces."breadbar-osd"] +anchor = "bottom_centre" +offset = 80 +width = 180 +layer = "overlay" + +[surfaces."breadbar-panel"] +anchor = "top_right" +offset = [16, 64] +width = "auto" +layer = "overlay" + +[surfaces."breadbar-dismiss"] +# Anchored to all four edges (a fullscreen click-away scrim) with only a top +# margin, so it starts below the bar rather than covering it. +anchor = "fill" +offset = 56 +width = "fill" +layer = "overlay" + +# Faithful to scripts/ui/rules.lua's five breadbar namespaces + breadbox. +[compositor."breadbar"] +blur = true +ignore_alpha = 0.2 +blur_popups = true +animation = "slide top" + +[compositor."breadbar-osd"] +blur = true +ignore_alpha = 0.2 +animation = "slide bottom" + +[compositor."breadbar-notif"] +blur = true +ignore_alpha = 0.2 +animation = "slide right" + +[compositor."breadbar-panel"] +blur = true +ignore_alpha = 0.2 +animation = "slide right" + +[compositor."breadbar-dismiss"] +no_anim = true + +[compositor."breadbox"] +blur = true +ignore_alpha = 0.2 + +# No `css = "..."` overlay: the builtin is compiled in via `include_str!` +# and has no on-disk directory to resolve a relative overlay path against. +# `extra.css` is for user/system themes, which do have one — see +# `resolve_theme` in mod.rs. diff --git a/bread-theme/src/lib.rs b/bread-theme/src/lib.rs index 2111c17..d20c955 100644 --- a/bread-theme/src/lib.rs +++ b/bread-theme/src/lib.rs @@ -4,6 +4,7 @@ pub mod adw; pub mod gtk; mod output; pub mod palette; +pub mod shell; pub use output::{ generate_output, load_palette_for, output_css_path, output_palette_path, palette_from_image, diff --git a/bread-theme/src/shell/builtin.rs b/bread-theme/src/shell/builtin.rs new file mode 100644 index 0000000..bd25560 --- /dev/null +++ b/bread-theme/src/shell/builtin.rs @@ -0,0 +1,23 @@ +//! The one compiled-in theme (plan §11 phase 1: "**One** built-in manifest +//! (`liquid-motion`) describing the bar as it exists today"). Both files are +//! plain data, not Rust — `theme.toml` is the manifest text a user override +//! would otherwise supply, and `liquid-motion.css` is the CSS template +//! `ShellTheme::css` substitutes tokens into (see that method's doc comment +//! for why this template is a representative subset of `breadbar::theme:: +//! load_css`'s full stylesheet rather than a byte-for-byte copy of it). +//! +//! Both are read with `include_str!` so a broken build can't ship without +//! them, and so [`super::builtin`] never touches the filesystem — it must +//! work identically whether or not `$XDG_CONFIG_HOME` exists at all. + +pub const LIQUID_MOTION_ID: &str = "liquid-motion"; + +pub const LIQUID_MOTION_TOML: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/assets/shell/liquid-motion/theme.toml" +)); + +pub const LIQUID_MOTION_CSS: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/assets/shell/liquid-motion/liquid-motion.css" +)); diff --git a/bread-theme/src/shell/hotreload.rs b/bread-theme/src/shell/hotreload.rs new file mode 100644 index 0000000..15e68a2 --- /dev/null +++ b/bread-theme/src/shell/hotreload.rs @@ -0,0 +1,32 @@ +//! `watch()` — only compiled under the `gtk` feature, since +//! `gio::FileMonitor` is a gtk4 dependency and the rest of `shell` is +//! deliberately gtk-free (`bread`/`breadcrumbs` link this crate without the +//! `gtk` feature at all). + +use gtk4::gio; +use gtk4::prelude::*; + +/// Fires `f` with a freshly-[`super::load`]ed [`super::ShellTheme`] whenever +/// the active theme's own directory changes on disk. Keep the returned +/// monitor alive — dropping it disarms the watch. +/// +/// Watches the *directory*, not the `theme.toml` file itself, for the same +/// reason `bread_theme::gtk::watch_theme_file` does (see that function's doc +/// comment): an editor or `bread-theme` doing an atomic write-tmp-then- +/// rename replaces the inode, and a monitor on the file itself dies after +/// the first replace (inotify reports `DELETE_SELF` and never re-arms). +pub fn watch(f: F) -> gio::FileMonitor { + let id = super::active_theme_id(); + let dir = super::user_theme_path(&id) + .parent() + .expect("user_theme_path always has a parent") + .to_path_buf(); + let _ = std::fs::create_dir_all(&dir); + let monitor = gio::File::for_path(&dir) + .monitor_directory(gio::FileMonitorFlags::WATCH_MOVES, gio::Cancellable::NONE) + .expect("failed to create a file monitor for the shell theme directory"); + monitor.connect_changed(move |_, _file, _other, _event| { + f(super::load()); + }); + monitor +} diff --git a/bread-theme/src/shell/manifest.rs b/bread-theme/src/shell/manifest.rs new file mode 100644 index 0000000..08be709 --- /dev/null +++ b/bread-theme/src/shell/manifest.rs @@ -0,0 +1,518 @@ +//! `theme.toml` deserialization, validation, and resolution into +//! [`crate::shell::ShellTheme`]. +//! +//! Two layers on purpose: `Raw*` types mirror the TOML shape exactly (every +//! field optional, `deny_unknown_fields` everywhere so a typo'd key is a +//! hard error naming that key rather than a silent no-op) and know nothing +//! about defaults; [`RawManifest::resolve`] is the one place defaults get +//! filled and string enums get validated, producing the fully-resolved +//! types in `types.rs`. + +use anyhow::{anyhow, bail, Context}; +use std::collections::{BTreeMap, HashMap}; + +use super::types::*; + +/// Module names a slot entry may reference without recompiling anything — +/// plan §2 tier 1/2 (declarative slots) plus the `widget:*` escape hatch +/// (tier 3, validated separately since its suffix is open-ended). This is +/// intentionally the set the *current* theme and the plan's own schema +/// example use; Phase 3 (breadbar's module registry) is the place a new +/// built-in module name gets added for real. +const KNOWN_MODULES: &[&str] = &[ + "workspaces", + "media", + "clock", + "volume", + "wifi", + "battery", + "control", + "launcher_entry", + "launcher_results", +]; + +pub(super) fn validate_module_name(theme_id: &str, slot: &str, module: &str) -> anyhow::Result<()> { + if module.starts_with("widget:") || KNOWN_MODULES.contains(&module) { + return Ok(()); + } + bail!( + "theme '{theme_id}': slot \"{slot}\" references unknown module \"{module}\" \ + (known modules: {}, or widget:)", + KNOWN_MODULES.join(", ") + ); +} + +pub(super) fn validate_slots(raw: &RawManifest, theme_id: &str) -> anyhow::Result<()> { + let Some(bar) = &raw.bar else { return Ok(()) }; + let Some(slots) = &bar.slots else { + return Ok(()); + }; + for (slot_name, list) in [ + ("left", &slots.left), + ("centre", &slots.centre), + ("right", &slots.right), + ("drawer", &slots.drawer), + ] { + for module in list { + validate_module_name(theme_id, slot_name, module)?; + } + } + Ok(()) +} + +#[derive(Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RawManifest { + pub(super) name: Option, + pub(super) id: Option, + /// Present only so `extends` deserializes as a *known* field (otherwise + /// `deny_unknown_fields` would reject every theme that sets it). The + /// value itself is read straight off the raw `toml::Value` in + /// `mod.rs::resolve_theme` — before this struct exists — since the + /// merge has to happen ahead of (and separately from) deserialization. + #[allow(dead_code)] + pub(super) extends: Option, + #[serde(default)] + pub(super) tokens: HashMap, + pub(super) bar: Option, + pub(super) modules: Option, + pub(super) launcher: Option, + pub(super) surfaces: Option>, + pub(super) compositor: Option>, + /// Overlay CSS path, resolved relative to the theme file's own + /// directory, appended last by `ShellTheme::css`. (Schema note: plan §4 + /// shows `css = "extra.css"` textually after the `[compositor]` table + /// with no table header of its own between them, which in real TOML + /// would nest it *inside* `[compositor]`. Treated here as a top-level + /// field per §5's `css()` doc — see this crate's implementation notes.) + pub(super) css: Option, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RawBar { + pub(super) window: Option, + pub(super) slots: Option, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RawWindow { + pub(super) anchors: Option>, + pub(super) width: Option, + pub(super) height: Option, + pub(super) margin: Option, + pub(super) exclusive: Option, + pub(super) keyboard: Option, + pub(super) layer: Option, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(untagged)] +pub(super) enum RawSize { + Named(String), + Px(i64), +} + +#[derive(Debug, serde::Deserialize)] +#[serde(untagged)] +pub(super) enum RawExclusive { + Named(String), + Px(i64), +} + +#[derive(Debug, Default, serde::Deserialize)] +#[serde(deny_unknown_fields, default)] +pub(super) struct RawMargin { + pub(super) top: i64, + pub(super) left: i64, + pub(super) right: i64, + pub(super) bottom: i64, +} + +#[derive(Debug, Default, serde::Deserialize)] +#[serde(deny_unknown_fields, default)] +pub(super) struct RawSlots { + pub(super) left: Vec, + pub(super) centre: Vec, + pub(super) right: Vec, + pub(super) drawer: Vec, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RawModules { + pub(super) workspaces: Option, + pub(super) clock: Option, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RawWorkspacesModule { + pub(super) style: Option, + pub(super) show_empty: Option, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RawClockModule { + pub(super) style: Option, + pub(super) format: Option, + pub(super) show_date: Option, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RawLauncher { + pub(super) mode: Option, + pub(super) width: Option, + pub(super) top: Option, + pub(super) radius: Option, + pub(super) icon_px: Option, + pub(super) row_anim: Option, + pub(super) rule: Option, + pub(super) footer: Option, + pub(super) sections: Option, + pub(super) modes: Option>, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RawSurface { + pub(super) anchor: Option, + pub(super) offset: Option, + pub(super) width: Option, + pub(super) layer: Option, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(untagged)] +pub(super) enum RawOffset { + Single(f64), + Pair([f64; 2]), +} + +#[derive(Debug, serde::Deserialize)] +#[serde(untagged)] +pub(super) enum RawSurfaceWidth { + Named(String), + Px(i64), +} + +#[derive(Debug, Default, serde::Deserialize)] +#[serde(deny_unknown_fields, default)] +pub(super) struct RawLayerRule { + pub(super) blur: Option, + pub(super) ignore_alpha: Option, + pub(super) blur_popups: Option, + pub(super) animation: Option, + pub(super) no_anim: Option, +} + +fn token_value(v: &toml::Value) -> anyhow::Result { + match v { + toml::Value::String(s) => Ok(TokenValue::Str(s.clone())), + toml::Value::Integer(i) => Ok(TokenValue::Int(*i)), + toml::Value::Float(f) => Ok(TokenValue::Float(*f)), + toml::Value::Boolean(b) => Ok(TokenValue::Bool(*b)), + other => Err(anyhow!("must be a string, number, or bool, got {other:?}")), + } +} + +fn resolve_window(theme_id: &str, w: &RawWindow) -> anyhow::Result { + let default = WindowSpec::default(); + + let anchors = match &w.anchors { + Some(list) => { + for a in list { + if !matches!(a.as_str(), "top" | "bottom" | "left" | "right") { + bail!( + "theme '{theme_id}': bar.window.anchors contains unknown anchor \"{a}\" \ + (expected top|bottom|left|right)" + ); + } + } + list.clone() + } + None => default.anchors, + }; + + let width = match &w.width { + Some(RawSize::Named(s)) if s == "fill" => Width::Fill, + Some(RawSize::Named(other)) => bail!( + "theme '{theme_id}': bar.window.width = \"{other}\" is not \"fill\" \ + (use a bare number for a fixed width)" + ), + Some(RawSize::Px(n)) => Width::Px(*n as i32), + None => default.width, + }; + + let height = w.height.map(|h| h as i32).unwrap_or(default.height); + + let margin = w + .margin + .as_ref() + .map(|m| Margin { + top: m.top as i32, + left: m.left as i32, + right: m.right as i32, + bottom: m.bottom as i32, + }) + .unwrap_or(default.margin); + + let exclusive = match &w.exclusive { + Some(RawExclusive::Named(s)) if s == "auto" => Exclusive::Auto, + Some(RawExclusive::Named(s)) if s == "none" => Exclusive::None, + Some(RawExclusive::Named(other)) => bail!( + "theme '{theme_id}': bar.window.exclusive = \"{other}\" is not \"auto\" or \"none\" \ + (use a bare number for a fixed exclusive zone)" + ), + Some(RawExclusive::Px(n)) => Exclusive::Px(*n as i32), + None => default.exclusive, + }; + + let keyboard = match w.keyboard.as_deref() { + None => default.keyboard, + Some("none") => Keyboard::None, + Some("on_demand") => Keyboard::OnDemand, + Some("exclusive") => Keyboard::Exclusive, + Some(other) => bail!( + "theme '{theme_id}': bar.window.keyboard = \"{other}\" is not none|on_demand|exclusive" + ), + }; + + let layer = match w.layer.as_deref() { + None => default.layer, + Some("top") => "top".to_string(), + Some("overlay") => "overlay".to_string(), + Some(other) => { + bail!("theme '{theme_id}': bar.window.layer = \"{other}\" is not top|overlay") + } + }; + + Ok(WindowSpec { + anchors, + width, + height, + margin, + exclusive, + keyboard, + layer, + }) +} + +fn resolve_modules(theme_id: &str, m: Option<&RawModules>) -> anyhow::Result { + let ws = m.and_then(|m| m.workspaces.as_ref()); + let style = match ws.and_then(|w| w.style.as_deref()) { + None => WorkspaceStyle::Trail, + Some("trail") => WorkspaceStyle::Trail, + Some("pill") => WorkspaceStyle::Pill, + Some("dots") => WorkspaceStyle::Dots, + Some(other) => bail!( + "theme '{theme_id}': modules.workspaces.style = \"{other}\" is not trail|pill|dots" + ), + }; + let show_empty = ws.and_then(|w| w.show_empty).unwrap_or(true); + + let ck = m.and_then(|m| m.clock.as_ref()); + let cstyle = match ck.and_then(|c| c.style.as_deref()) { + None => ClockStyle::Flip, + Some("flip") => ClockStyle::Flip, + Some("plain") => ClockStyle::Plain, + Some("none") => ClockStyle::None, + Some(other) => { + bail!("theme '{theme_id}': modules.clock.style = \"{other}\" is not flip|plain|none") + } + }; + let format = ck + .and_then(|c| c.format.clone()) + .unwrap_or_else(|| "%H:%M".to_string()); + let show_date = ck.and_then(|c| c.show_date).unwrap_or(false); + + Ok(Modules { + workspaces: WorkspacesModule { style, show_empty }, + clock: ClockModule { + style: cstyle, + format, + show_date, + }, + }) +} + +fn resolve_launcher(theme_id: &str, l: Option<&RawLauncher>) -> anyhow::Result { + let mode = match l.and_then(|l| l.mode.as_deref()) { + None => LauncherMode::Overlay, + Some("overlay") => LauncherMode::Overlay, + Some("embedded") => LauncherMode::Embedded, + Some(other) => { + bail!("theme '{theme_id}': launcher.mode = \"{other}\" is not overlay|embedded") + } + }; + Ok(Launcher { + mode, + width: l.and_then(|l| l.width).unwrap_or(540) as i32, + top: l + .and_then(|l| l.top.clone()) + .unwrap_or_else(|| "16%".to_string()), + radius: l.and_then(|l| l.radius).unwrap_or(20) as i32, + icon_px: l.and_then(|l| l.icon_px).unwrap_or(36) as i32, + row_anim: l + .and_then(|l| l.row_anim.clone()) + .unwrap_or_else(|| "flip".to_string()), + rule: l + .and_then(|l| l.rule.clone()) + .unwrap_or_else(|| "gradient".to_string()), + footer: l + .and_then(|l| l.footer.clone()) + .unwrap_or_else(|| "count_apps".to_string()), + sections: l.and_then(|l| l.sections).unwrap_or(false), + modes: l + .and_then(|l| l.modes.clone()) + .unwrap_or_else(|| vec!["apps".to_string()]), + }) +} + +fn resolve_surfaces( + theme_id: &str, + raw: Option<&HashMap>, +) -> anyhow::Result> { + let mut out = BTreeMap::new(); + let Some(raw) = raw else { return Ok(out) }; + for (namespace, s) in raw { + let offset = match &s.offset { + None => vec![], + Some(RawOffset::Single(v)) => vec![*v], + Some(RawOffset::Pair(v)) => v.to_vec(), + }; + let width = match &s.width { + None => SurfaceWidth::Auto, + Some(RawSurfaceWidth::Named(n)) if n == "fill" => SurfaceWidth::Fill, + Some(RawSurfaceWidth::Named(n)) if n == "auto" => SurfaceWidth::Auto, + Some(RawSurfaceWidth::Named(other)) => bail!( + "theme '{theme_id}': surfaces.{namespace}.width = \"{other}\" is not \"fill\" or \"auto\" \ + (use a bare number for a fixed width)" + ), + Some(RawSurfaceWidth::Px(n)) => SurfaceWidth::Px(*n as i32), + }; + let layer = match s.layer.as_deref() { + None | Some("overlay") => "overlay".to_string(), + Some("top") => "top".to_string(), + Some(other) => bail!( + "theme '{theme_id}': surfaces.{namespace}.layer = \"{other}\" is not top|overlay" + ), + }; + out.insert( + namespace.clone(), + Surface { + anchor: s.anchor.clone().unwrap_or_default(), + offset, + width, + layer, + }, + ); + } + Ok(out) +} + +fn resolve_compositor(raw: Option<&HashMap>) -> BTreeMap { + let mut out = BTreeMap::new(); + let Some(raw) = raw else { return out }; + for (namespace, r) in raw { + out.insert( + namespace.clone(), + LayerRule { + blur: r.blur.unwrap_or(false), + ignore_alpha: r.ignore_alpha, + blur_popups: r.blur_popups.unwrap_or(false), + animation: r.animation.clone(), + no_anim: r.no_anim.unwrap_or(false), + }, + ); + } + out +} + +impl RawManifest { + /// Fill every default and validate every enum-ish string, producing a + /// fully-resolved [`super::ShellTheme`]. `requested_id` is the id this + /// manifest was looked up under (used as the id/name fallback when the + /// TOML omits `id`/`name`); `css_template` and `extra_css` are threaded + /// in by the discovery/extends logic in `mod.rs` since neither is a + /// plain TOML field (extra_css is *read from* a TOML field, `css`, but + /// resolving that path against the theme's own directory happens in the + /// caller, which is the only place that still has the directory handy). + pub(super) fn resolve( + &self, + requested_id: &str, + css_template: String, + extra_css: Option, + ) -> anyhow::Result { + let id = self.id.clone().unwrap_or_else(|| requested_id.to_string()); + let name = self.name.clone().unwrap_or_else(|| id.clone()); + + let mut tokens_map = BTreeMap::new(); + for (k, v) in &self.tokens { + let tv = token_value(v).with_context(|| format!("theme '{id}': tokens.{k}"))?; + tokens_map.insert(k.clone(), tv); + } + let tokens = Tokens::from_map(tokens_map); + + let window = match self.bar.as_ref().and_then(|b| b.window.as_ref()) { + Some(w) => resolve_window(&id, w)?, + None => WindowSpec::default(), + }; + + let slots = self + .bar + .as_ref() + .and_then(|b| b.slots.as_ref()) + .map(|s| Slots { + left: s.left.clone(), + centre: s.centre.clone(), + right: s.right.clone(), + drawer: s.drawer.clone(), + }) + .unwrap_or_default(); + + let modules = resolve_modules(&id, self.modules.as_ref())?; + let launcher = resolve_launcher(&id, self.launcher.as_ref())?; + let surfaces = resolve_surfaces(&id, self.surfaces.as_ref())?; + let compositor = resolve_compositor(self.compositor.as_ref()); + + Ok(super::ShellTheme { + name, + id, + tokens, + window, + slots, + modules, + launcher, + surfaces, + compositor, + css_template, + extra_css, + }) + } +} + +/// Deep-merge `over` onto `base`: tables merge key-by-key recursively; +/// anything else (scalars, arrays — including slot lists) is a full +/// replacement. This is `extends`'s one-level merge (plan §4/§11): +/// `mod.rs` calls this exactly once per `load_named`, with the base's own +/// `extends` key already stripped by the caller so a chain can't go deeper +/// than one level. +pub(super) fn merge_values(base: toml::Value, over: toml::Value) -> toml::Value { + match (base, over) { + (toml::Value::Table(mut base_t), toml::Value::Table(over_t)) => { + for (k, v) in over_t { + let merged = match base_t.remove(&k) { + Some(existing) => merge_values(existing, v), + None => v, + }; + base_t.insert(k, merged); + } + toml::Value::Table(base_t) + } + (_, over) => over, + } +} diff --git a/bread-theme/src/shell/mod.rs b/bread-theme/src/shell/mod.rs new file mode 100644 index 0000000..526b87c --- /dev/null +++ b/bread-theme/src/shell/mod.rs @@ -0,0 +1,899 @@ +//! `bread_theme::shell` — the shell theme manifest system (Phase 1 of the +//! `THEME_SYSTEM_PLAN.md` design: manifest types, discovery, `extends` +//! merge, validation, `css()`, `watch()`, and the one compiled-in +//! `liquid-motion` builtin describing breadbar/breadbox as they exist +//! today). +//! +//! This module is intentionally gtk-free except for [`watch`] (only +//! compiled under the `gtk` feature, since `gio::FileMonitor` is a gtk4 +//! dependency) — `bread` (the daemon) and `breadcrumbs` (the CLI) can read +//! and validate a theme without linking GTK at all. +//! +//! ## Discovery (plan §4) +//! +//! A theme id resolves through, first hit wins: +//! 1. `$XDG_CONFIG_HOME/bread/themes//theme.toml` (user) +//! 2. `/usr/share/bread/themes//theme.toml` (system, BOS package) +//! 3. the compiled-in builtin (currently only `liquid-motion`) +//! +//! The *active* id comes from `~/.config/bread/shell.toml`'s `active = "..."` +//! key, overridden by `$BREAD_SHELL_THEME` (the `--theme` CLI flag mentioned +//! in the plan is a consumer-side concern — breadbar/breadbox would set +//! `$BREAD_SHELL_THEME` themselves before calling [`load`], rather than this +//! crate parsing argv). +//! +//! ## `extends` (plan §4/§11) +//! +//! One level, deep-merged: a theme's raw TOML is merged over its `extends` +//! target's raw TOML (child wins key-by-key, recursing into tables; arrays — +//! including slot lists — are replaced wholesale, not concatenated). If the +//! base itself declares `extends`, that second-level `extends` is dropped +//! before merging — chains longer than one level are not supported, by +//! design (plan explicitly scopes this to "one level"). +//! +//! ## Never fails (plan §4/§5) +//! +//! [`load`] cannot fail: a missing or malformed *active* theme falls back to +//! the compiled-in builtin, logging once via `tracing::warn!` +//! ([`load_named`] is the fallible primitive underneath, for callers that +//! want to know *why* — e.g. a "broken theme" banner in bos-settings). + +mod builtin; +mod manifest; +mod types; + +#[cfg(feature = "gtk")] +mod hotreload; +#[cfg(feature = "gtk")] +pub use hotreload::watch; + +pub use types::*; + +use anyhow::{anyhow, Context}; +use std::collections::BTreeMap; +use std::path::PathBuf; + +use manifest::RawManifest; + +/// A theme, fully resolved: every default filled, every enum validated. +/// Built once by [`load`]/[`load_named`] and handed to consumers as an +/// immutable snapshot — a theme *change* (edit, `extends` retarget, hot +/// reload) produces a new `ShellTheme` rather than mutating this one. +#[derive(Debug, Clone, PartialEq)] +pub struct ShellTheme { + name: String, + id: String, + tokens: Tokens, + window: WindowSpec, + slots: Slots, + modules: Modules, + launcher: Launcher, + surfaces: BTreeMap, + compositor: BTreeMap, + css_template: String, + extra_css: Option, +} + +impl ShellTheme { + pub fn name(&self) -> &str { + &self.name + } + pub fn id(&self) -> &str { + &self.id + } + pub fn tokens(&self) -> &Tokens { + &self.tokens + } + pub fn window(&self) -> &WindowSpec { + &self.window + } + pub fn slots(&self) -> &Slots { + &self.slots + } + pub fn modules(&self) -> &Modules { + &self.modules + } + pub fn launcher(&self) -> &Launcher { + &self.launcher + } + pub fn surfaces(&self) -> &BTreeMap { + &self.surfaces + } + pub fn compositor_rules(&self) -> &BTreeMap { + &self.compositor + } + + /// Token substitution into the theme's CSS template, plus the optional + /// `extra.css` overlay appended last — plan §5. + /// + /// `palette` is accepted to match the plan §5 signature and for parity + /// with [`crate::stylesheet_resolved`]-style consumers in the future, + /// but is deliberately unused today: per this task's brief, `@accent` / + /// `@on-bg` *pass through untouched* here, the same way + /// [`crate::stylesheet`] leaves them for GTK's own `@define-color` + /// mechanism to resolve once the CSS provider is attached + /// (`bgtk::bind_window_with_app_css` / `apply_app_css`). A caller that + /// wants hex-resolved CSS combines this with + /// [`crate::resolve_color_names`] itself, exactly as + /// `breadbar::theme::load_css_for` does today. + #[allow(unused_variables)] + pub fn css(&self, palette: &crate::Palette) -> String { + let mut out = self.tokens.substitute(&self.css_template); + if let Some(extra) = &self.extra_css { + if !out.is_empty() && !out.ends_with('\n') { + out.push('\n'); + } + out.push_str(&self.tokens.substitute(extra)); + } + out + } +} + +/// Where a discovered theme's manifest text came from — also [`ThemeSummary`]'s +/// `source` field for a picker UI (bos-settings, plan §5 `list()`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ThemeSource { + User, + System, + Builtin, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ThemeSummary { + pub id: String, + pub name: String, + pub source: ThemeSource, +} + +fn config_home() -> PathBuf { + if let Ok(v) = std::env::var("XDG_CONFIG_HOME") { + if !v.is_empty() { + return PathBuf::from(v); + } + } + dirs::home_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join(".config") +} + +fn user_themes_dir() -> PathBuf { + config_home().join("bread/themes") +} + +fn system_themes_dir() -> PathBuf { + PathBuf::from("/usr/share/bread/themes") +} + +fn user_theme_path(id: &str) -> PathBuf { + user_themes_dir().join(id).join("theme.toml") +} + +fn system_theme_path(id: &str) -> PathBuf { + system_themes_dir().join(id).join("theme.toml") +} + +enum Source { + User(PathBuf), + System(PathBuf), + Builtin, +} + +fn find_source(id: &str) -> Option { + let user = user_theme_path(id); + if user.is_file() { + return Some(Source::User(user)); + } + let system = system_theme_path(id); + if system.is_file() { + return Some(Source::System(system)); + } + if id == builtin::LIQUID_MOTION_ID { + return Some(Source::Builtin); + } + None +} + +/// Manifest text plus, for on-disk sources, the directory it lives in (used +/// to resolve a relative `css = "extra.css"` overlay path). +fn read_source(src: &Source) -> anyhow::Result<(String, Option)> { + match src { + Source::User(p) | Source::System(p) => { + let text = + std::fs::read_to_string(p).with_context(|| format!("reading {}", p.display()))?; + Ok((text, p.parent().map(|d| d.to_path_buf()))) + } + Source::Builtin => Ok((builtin::LIQUID_MOTION_TOML.to_string(), None)), + } +} + +fn css_template_for(id: &str) -> String { + if id == builtin::LIQUID_MOTION_ID { + builtin::LIQUID_MOTION_CSS.to_string() + } else { + String::new() + } +} + +/// The fallible primitive: look up `id` through discovery, apply one level +/// of `extends`, validate, and resolve. Returns `Err` (naming the offending +/// key/path) rather than falling back — [`load`] is the caller that turns a +/// failure into the builtin. +pub fn load_named(id: &str) -> anyhow::Result { + resolve_theme(id, 0) +} + +fn resolve_theme(id: &str, extends_depth: u8) -> anyhow::Result { + let src = find_source(id).ok_or_else(|| { + anyhow!("no theme named '{id}' (checked user config, system dir, and builtins)") + })?; + let (text, dir) = read_source(&src)?; + let mut value: toml::Value = + toml::from_str(&text).with_context(|| format!("parsing theme '{id}'"))?; + + let extends = value + .get("extends") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()); + let mut css_template = css_template_for(id); + + if let (Some(base_id), 0) = (&extends, extends_depth) { + let base_src = find_source(base_id) + .ok_or_else(|| anyhow!("theme '{id}' extends unknown theme '{base_id}'"))?; + let (base_text, _base_dir) = read_source(&base_src)?; + let mut base_value: toml::Value = toml::from_str(&base_text) + .with_context(|| format!("parsing base theme '{base_id}' (extended by '{id}')"))?; + // Cap at one level: drop the base's own `extends` so a chain can't + // go deeper (plan §4: "one level, deep-merged"). + if let toml::Value::Table(t) = &mut base_value { + t.remove("extends"); + } + css_template = css_template_for(base_id); + value = manifest::merge_values(base_value, value); + } + + let raw: RawManifest = value + .try_into() + .with_context(|| format!("theme '{id}' has an invalid or unrecognized field"))?; + + manifest::validate_slots(&raw, id)?; + + let extra_css = match &raw.css { + Some(rel) => { + let dir = dir.ok_or_else(|| { + anyhow!( + "theme '{id}' sets css = \"{rel}\" but has no on-disk directory to \ + resolve it against" + ) + })?; + let path = dir.join(rel); + Some( + std::fs::read_to_string(&path) + .with_context(|| format!("reading css overlay {}", path.display()))?, + ) + } + None => None, + }; + + raw.resolve(id, css_template, extra_css) +} + +/// Bypasses discovery entirely and resolves straight from the compiled-in +/// `LIQUID_MOTION_TOML`/`LIQUID_MOTION_CSS` constants — used as [`load`]'s +/// fallback specifically *because* it cannot be affected by a broken user +/// override file at the same id (unlike calling `load_named("liquid-motion")` +/// again, which would hit that same broken file first via discovery and +/// fail identically). +fn resolve_builtin() -> ShellTheme { + let value: toml::Value = toml::from_str(builtin::LIQUID_MOTION_TOML) + .expect("compiled-in builtin theme.toml must parse"); + let raw: RawManifest = value + .try_into() + .expect("compiled-in builtin theme.toml must satisfy the manifest schema"); + manifest::validate_slots(&raw, builtin::LIQUID_MOTION_ID) + .expect("compiled-in builtin theme.toml must use only known module names"); + raw.resolve( + builtin::LIQUID_MOTION_ID, + builtin::LIQUID_MOTION_CSS.to_string(), + None, + ) + .expect("compiled-in builtin theme.toml must resolve") +} + +static FALLBACK_LOGGED: std::sync::Once = std::sync::Once::new(); + +/// The active theme. Never fails: a missing or malformed active theme logs +/// once (`tracing::warn!`) and falls back to the compiled-in builtin — "the +/// shell must never fail to start because a theme file is malformed" (plan +/// §4). +pub fn load() -> ShellTheme { + let id = active_theme_id(); + match load_named(&id) { + Ok(theme) => theme, + Err(err) => { + FALLBACK_LOGGED.call_once(|| { + tracing::warn!( + "bread-theme: shell theme '{id}' failed to load ({err:#}); \ + falling back to builtin '{}'", + builtin::LIQUID_MOTION_ID + ); + }); + resolve_builtin() + } + } +} + +fn active_theme_id() -> String { + if let Ok(v) = std::env::var("BREAD_SHELL_THEME") { + if !v.trim().is_empty() { + return v; + } + } + let path = config_home().join("bread/shell.toml"); + if let Ok(text) = std::fs::read_to_string(&path) { + if let Ok(value) = toml::from_str::(&text) { + if let Some(active) = value.get("active").and_then(|v| v.as_str()) { + if !active.trim().is_empty() { + return active.to_string(); + } + } + } + } + builtin::LIQUID_MOTION_ID.to_string() +} + +fn scan_theme_dir( + dir: &std::path::Path, + source: ThemeSource, + out: &mut Vec, + seen: &mut std::collections::HashSet, +) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let toml_path = entry.path().join("theme.toml"); + let Ok(text) = std::fs::read_to_string(&toml_path) else { + continue; + }; + let Ok(value) = toml::from_str::(&text) else { + continue; + }; + let id = value + .get("id") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) + .or_else(|| entry.file_name().to_str().map(|s| s.to_string())); + let Some(id) = id else { continue }; + if !seen.insert(id.clone()) { + continue; + } + let name = value + .get("name") + .and_then(|v| v.as_str()) + .unwrap_or(&id) + .to_string(); + out.push(ThemeSummary { id, name, source }); + } +} + +/// Every theme discoverable across user config, system dir, and builtins — +/// for a picker UI (plan §5: "bos-settings picker"). User shadows system +/// shadows builtin for the same id, matching [`load_named`]'s discovery +/// order. +pub fn list() -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut out = Vec::new(); + scan_theme_dir(&user_themes_dir(), ThemeSource::User, &mut out, &mut seen); + scan_theme_dir( + &system_themes_dir(), + ThemeSource::System, + &mut out, + &mut seen, + ); + if seen.insert(builtin::LIQUID_MOTION_ID.to_string()) { + out.push(ThemeSummary { + id: builtin::LIQUID_MOTION_ID.to_string(), + name: "Liquid Motion".to_string(), + source: ThemeSource::Builtin, + }); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + // Guards mutation of XDG_CONFIG_HOME / BREAD_SHELL_THEME, which are + // process-global — mirrors bread_theme::output's XDG_ENV_LOCK pattern + // (a different env var, same reason: cargo test runs a module's tests + // in parallel by default). + static ENV_LOCK: Mutex<()> = Mutex::new(()); + + struct EnvGuard { + _lock: std::sync::MutexGuard<'static, ()>, + dir: PathBuf, + old_xdg: Option, + old_theme_var: Option, + } + + impl Drop for EnvGuard { + fn drop(&mut self) { + match &self.old_xdg { + Some(v) => std::env::set_var("XDG_CONFIG_HOME", v), + None => std::env::remove_var("XDG_CONFIG_HOME"), + } + match &self.old_theme_var { + Some(v) => std::env::set_var("BREAD_SHELL_THEME", v), + None => std::env::remove_var("BREAD_SHELL_THEME"), + } + let _ = std::fs::remove_dir_all(&self.dir); + } + } + + /// Isolated `$XDG_CONFIG_HOME` pointing at a fresh temp dir, with + /// `BREAD_SHELL_THEME` cleared so `active_theme_id()` can't pick up + /// whatever's set in the outer test-runner environment. Held for the + /// guard's lifetime. + fn isolated_xdg() -> EnvGuard { + let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!( + "bread-theme-shell-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let old_xdg = std::env::var("XDG_CONFIG_HOME").ok(); + let old_theme_var = std::env::var("BREAD_SHELL_THEME").ok(); + std::env::set_var("XDG_CONFIG_HOME", &dir); + std::env::remove_var("BREAD_SHELL_THEME"); + EnvGuard { + _lock: lock, + dir, + old_xdg, + old_theme_var, + } + } + + fn write_theme(xdg: &EnvGuard, id: &str, toml_body: &str) { + let dir = xdg.dir.join("bread/themes").join(id); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("theme.toml"), toml_body).unwrap(); + } + + // ---- builtin fidelity ------------------------------------------------- + + #[test] + fn builtin_window_spec_matches_current_breadbar_constants() { + // breadbar/src/main.rs:16-22: BAR_HEIGHT=44, BAR_MARGIN_TOP=12, + // BAR_MARGIN_SIDES=16, CHIP_HEIGHT=32, ICON_PX=24. The demo's + // 14px side margin is deliberately NOT what this asserts. + let theme = resolve_builtin(); + let w = theme.window(); + assert_eq!(w.height, 44); + assert_eq!(w.margin.top, 12); + assert_eq!(w.margin.left, 16); + assert_eq!(w.margin.right, 16); + assert_eq!(w.anchors, vec!["top", "left", "right"]); + assert!(matches!(w.width, Width::Fill)); + assert!(matches!(w.exclusive, Exclusive::Auto)); + assert!(matches!(w.keyboard, Keyboard::None)); + assert_eq!(w.layer, "top"); + + assert_eq!(theme.tokens().chip_height(), 32); + assert_eq!(theme.tokens().icon_px(), 24); + } + + #[test] + fn builtin_tokens_match_theme_rs_load_css_locals() { + // theme.rs::load_css: radius="12px", radius_bar="16px", + // radius_sm="9px", radius_pill="999px", pad="12px". + let theme = resolve_builtin(); + let t = theme.tokens(); + assert_eq!(t.radius_card(), 12); + assert_eq!(t.radius_bar(), 16); + assert_eq!(t.radius_sm(), 9); + assert_eq!(t.radius_pill(), 999); + assert_eq!(t.pad(), 12); + assert_eq!(t.spring(), "cubic-bezier(0.22, 1.35, 0.36, 1)"); + assert_eq!(t.spring_settle(), "cubic-bezier(0.22, 1.2, 0.36, 1)"); + } + + #[test] + fn builtin_covers_all_five_breadbar_namespaces_plus_breadbox() { + let theme = resolve_builtin(); + let rules = theme.compositor_rules(); + for ns in [ + "breadbar", + "breadbar-osd", + "breadbar-notif", + "breadbar-panel", + "breadbar-dismiss", + "breadbox", + ] { + assert!(rules.contains_key(ns), "missing compositor rule for {ns}"); + } + assert!(rules["breadbar"].blur); + assert!(rules["breadbar"].blur_popups); + assert_eq!(rules["breadbar"].animation.as_deref(), Some("slide top")); + assert!(rules["breadbar-dismiss"].no_anim); + assert!(!rules["breadbar-dismiss"].blur); + } + + #[test] + fn builtin_surfaces_are_keyed_by_namespace_and_cover_all_four() { + let theme = resolve_builtin(); + let surfaces = theme.surfaces(); + for ns in [ + "breadbar-notif", + "breadbar-osd", + "breadbar-panel", + "breadbar-dismiss", + ] { + assert!(surfaces.contains_key(ns), "missing surface spec for {ns}"); + } + assert_eq!(surfaces["breadbar-osd"].anchor, "bottom_centre"); + assert!(matches!( + surfaces["breadbar-panel"].width, + SurfaceWidth::Auto + )); + assert!(matches!( + surfaces["breadbar-dismiss"].width, + SurfaceWidth::Fill + )); + } + + #[test] + fn builtin_slots_and_modules_are_trail_and_flip() { + let theme = resolve_builtin(); + assert_eq!(theme.slots().left, vec!["workspaces"]); + assert_eq!(theme.slots().centre, vec!["media", "clock"]); + assert!(matches!( + theme.modules().workspaces.style, + WorkspaceStyle::Trail + )); + assert!(matches!(theme.modules().clock.style, ClockStyle::Flip)); + } + + #[test] + fn builtin_css_substitutes_tokens_and_leaves_palette_names_untouched() { + let theme = resolve_builtin(); + let css = theme.css(&crate::Palette::default()); + assert!( + css.contains("border-radius: 16px"), + "radius_bar not substituted:\n{css}" + ); + assert!( + css.contains("cubic-bezier(0.22, 1.35, 0.36, 1)"), + "spring not substituted:\n{css}" + ); + assert!( + css.contains("@accent, @teal"), + "accent_from/accent_to gradient not substituted:\n{css}" + ); + assert!( + css.contains("@on-bg"), + "palette name resolved when it should pass through:\n{css}" + ); + for placeholder in [ + "{radius_bar}", + "{radius_card}", + "{radius_sm}", + "{radius_pill}", + "{pad}", + "{spring}", + "{spring_settle}", + "{bg_alpha}", + "{accent_from}", + "{accent_to}", + "{chip_height}", + ] { + assert!( + !css.contains(placeholder), + "unsubstituted token placeholder {placeholder}:\n{css}" + ); + } + } + + // ---- extends merge ------------------------------------------------ + + #[test] + fn extends_deep_merges_one_level() { + let xdg = isolated_xdg(); + write_theme( + &xdg, + "base", + r#" + name = "Base" + id = "base" + [tokens] + radius_bar = 10 + pad = 8 + [bar.window] + height = 40 + [bar.slots] + left = ["workspaces"] + right = ["battery"] + "#, + ); + write_theme( + &xdg, + "child", + r#" + name = "Child" + id = "child" + extends = "base" + [tokens] + radius_bar = 99 + [bar.slots] + right = ["wifi", "battery"] + "#, + ); + + let theme = load_named("child").expect("child theme should resolve"); + // Overridden by the child. + assert_eq!(theme.tokens().radius_bar(), 99); + // Inherited from the base, untouched by the child. + assert_eq!(theme.tokens().pad(), 8); + assert_eq!(theme.window().height, 40); + // Arrays replace wholesale, not concatenate. + assert_eq!(theme.slots().right, vec!["wifi", "battery"]); + // A key the child never mentions at all stays inherited. + assert_eq!(theme.slots().left, vec!["workspaces"]); + } + + #[test] + fn extends_chain_is_capped_at_one_level() { + let xdg = isolated_xdg(); + write_theme( + &xdg, + "grandparent", + r#" + id = "grandparent" + [tokens] + pad = 1 + "#, + ); + write_theme( + &xdg, + "parent", + r#" + id = "parent" + extends = "grandparent" + [tokens] + pad = 2 + "#, + ); + write_theme( + &xdg, + "child", + r#" + id = "child" + extends = "parent" + "#, + ); + + let theme = load_named("child").expect("child theme should resolve"); + // Only one level is honored: child merges with parent (pad=2), and + // parent's own `extends = "grandparent"` is dropped rather than + // chased — the grandparent's pad=1 never applies. + assert_eq!(theme.tokens().pad(), 2); + } + + // ---- validation ------------------------------------------------------ + + #[test] + fn unknown_key_error_names_the_offending_key() { + let xdg = isolated_xdg(); + write_theme( + &xdg, + "typo", + r#" + id = "typo" + [bar.window] + heihgt = 44 + "#, + ); + let err = load_named("typo").expect_err("typo'd key must be a hard error"); + let msg = format!("{err:#}"); + assert!( + msg.contains("heihgt"), + "error should name the bad key, got: {msg}" + ); + } + + #[test] + fn unknown_top_level_key_is_an_error() { + let xdg = isolated_xdg(); + write_theme(&xdg, "typo2", "id = \"typo2\"\nfont = \"nope\"\n"); + let err = load_named("typo2").expect_err("unknown top-level key must be a hard error"); + assert!(format!("{err:#}").contains("font")); + } + + #[test] + fn unknown_slot_module_names_the_module() { + let xdg = isolated_xdg(); + write_theme( + &xdg, + "badmodule", + r#" + id = "badmodule" + [bar.slots] + left = ["teleporter"] + "#, + ); + let err = load_named("badmodule").expect_err("unknown module must be a hard error"); + let msg = format!("{err:#}"); + assert!( + msg.contains("teleporter"), + "error should name the module, got: {msg}" + ); + } + + #[test] + fn widget_prefixed_slot_entries_are_always_valid() { + let xdg = isolated_xdg(); + write_theme( + &xdg, + "widgetslot", + r#" + id = "widgetslot" + [bar.slots] + left = ["widget:my-lua-module"] + "#, + ); + let theme = load_named("widgetslot").expect("widget: entries should validate"); + assert_eq!(theme.slots().left, vec!["widget:my-lua-module"]); + } + + #[test] + fn invalid_enum_value_is_an_error() { + let xdg = isolated_xdg(); + write_theme( + &xdg, + "badstyle", + r#" + id = "badstyle" + [modules.workspaces] + style = "hexagon" + "#, + ); + let err = load_named("badstyle").expect_err("invalid style must be an error"); + assert!(format!("{err:#}").contains("hexagon")); + } + + // ---- fallback on broken theme ----------------------------------------- + + #[test] + fn malformed_active_theme_falls_back_to_builtin_without_panicking() { + let xdg = isolated_xdg(); + // A broken override sitting at the *active* id's own path — this is + // the case resolve_builtin() exists to survive without re-touching + // the same broken file. + write_theme(&xdg, "liquid-motion", "this is not [valid toml"); + + let theme = load(); // must not panic + assert_eq!(theme.window().height, 44); + assert_eq!(theme.id(), "liquid-motion"); + } + + #[test] + fn missing_active_theme_falls_back_to_builtin() { + let xdg = isolated_xdg(); + std::env::set_var("BREAD_SHELL_THEME", "does-not-exist"); + let theme = load(); + assert_eq!(theme.id(), "liquid-motion"); + drop(xdg); + } + + #[test] + fn load_named_on_broken_theme_returns_err_not_panic() { + let xdg = isolated_xdg(); + write_theme(&xdg, "broken", "not = [valid"); + assert!(load_named("broken").is_err()); + } + + // ---- css() / extra.css ------------------------------------------------- + + #[test] + fn extra_css_overlay_is_appended_and_token_substituted() { + let xdg = isolated_xdg(); + let dir = xdg.dir.join("bread/themes/overlaid"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("theme.toml"), + r#" + id = "overlaid" + extends = "liquid-motion" + css = "extra.css" + [tokens] + pad = 21 + "#, + ) + .unwrap(); + std::fs::write(dir.join("extra.css"), ".custom { margin: {pad}px; }\n").unwrap(); + + let theme = load_named("overlaid").expect("theme with extra.css should resolve"); + let css = theme.css(&crate::Palette::default()); + assert!( + css.contains(".custom { margin: 21px; }"), + "overlay not appended/substituted:\n{css}" + ); + // The inherited liquid-motion template should still be present too. + assert!(css.contains("window.breadbar")); + } + + // ---- active theme resolution ------------------------------------------- + + #[test] + fn env_var_overrides_shell_toml_active() { + let xdg = isolated_xdg(); + std::fs::create_dir_all(xdg.dir.join("bread")).unwrap(); + std::fs::write( + xdg.dir.join("bread/shell.toml"), + "active = \"liquid-motion\"\n", + ) + .unwrap(); + write_theme(&xdg, "envwins", "id = \"envwins\"\n"); + std::env::set_var("BREAD_SHELL_THEME", "envwins"); + assert_eq!(active_theme_id(), "envwins"); + } + + #[test] + fn shell_toml_active_used_when_no_env_var() { + let xdg = isolated_xdg(); + std::fs::create_dir_all(xdg.dir.join("bread")).unwrap(); + std::fs::write(xdg.dir.join("bread/shell.toml"), "active = \"from-file\"\n").unwrap(); + assert_eq!(active_theme_id(), "from-file"); + } + + #[test] + fn defaults_to_liquid_motion_with_nothing_configured() { + let _xdg = isolated_xdg(); + assert_eq!(active_theme_id(), "liquid-motion"); + } + + // ---- list() ------------------------------------------------------------ + + #[test] + fn list_includes_user_themes_and_the_builtin() { + let xdg = isolated_xdg(); + write_theme( + &xdg, + "custom-one", + "id = \"custom-one\"\nname = \"Custom One\"\n", + ); + let summaries = list(); + assert!(summaries + .iter() + .any(|s| s.id == "custom-one" && s.source == ThemeSource::User)); + assert!(summaries + .iter() + .any(|s| s.id == "liquid-motion" && s.source == ThemeSource::Builtin)); + } + + #[test] + fn list_user_theme_shadows_builtin_of_the_same_id() { + let xdg = isolated_xdg(); + write_theme( + &xdg, + "liquid-motion", + "id = \"liquid-motion\"\nname = \"User Override\"\n", + ); + let summaries = list(); + let matches: Vec<_> = summaries + .iter() + .filter(|s| s.id == "liquid-motion") + .collect(); + assert_eq!( + matches.len(), + 1, + "same id must not appear twice: {summaries:?}" + ); + assert_eq!(matches[0].source, ThemeSource::User); + } +} diff --git a/bread-theme/src/shell/types.rs b/bread-theme/src/shell/types.rs new file mode 100644 index 0000000..06982a2 --- /dev/null +++ b/bread-theme/src/shell/types.rs @@ -0,0 +1,358 @@ +//! Fully-resolved shell theme types — see `bread-theme/src/shell/mod.rs` for +//! the module overview and `manifest.rs` for how these are built from TOML. +//! +//! Every type here has all defaults filled in; there is no further "is this +//! set" branching once a `ShellTheme` exists. That resolution work happens +//! once, in `manifest.rs`, so consumers (breadbar, breadbox, bos-settings) +//! never have to know the manifest format at all. + +use std::collections::BTreeMap; + +/// Workspace strip rendering. Phase 1 ships only `Trail` (what breadbar draws +/// today); `Pill`/`Dots` exist now so 02/04 (plan §11 phases 5-6) are additive. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WorkspaceStyle { + Trail, + Pill, + Dots, +} + +/// Clock rendering. Phase 1 ships only `Flip` (today's per-digit flip clock). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClockStyle { + Flip, + Plain, + None, +} + +/// How the launcher attaches to the shell. Phase 1 ships only `Overlay` +/// (breadbox's own window); `Embedded` is theme 04's bar-drawer launcher. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LauncherMode { + Overlay, + Embedded, +} + +/// `gtk4_layer_shell::KeyboardMode` mirror, kept independent of the `gtk` +/// feature so the manifest types stay usable without GTK linked in (bread, +/// breadcrumbs). Values map 1:1 onto `KeyboardMode::{None,Exclusive,OnDemand}` +/// (verified against gtk4-layer-shell 0.8.1's `src/auto/enums.rs`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Keyboard { + None, + OnDemand, + Exclusive, +} + +/// `bar.window.width` / a surface's `width`: `"fill"` spans the anchored +/// edges, a bare number is a fixed/centred/hug width. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Width { + Fill, + Px(i32), +} + +/// `bar.window.exclusive`: `"auto"` reserves `height + margin.top`, `"none"` +/// reserves nothing (theme 04's capsule), or a literal pixel override. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Exclusive { + Auto, + None, + Px(i32), +} + +/// A satellite surface's width: unlike the bar window, a satellite can also +/// be `Auto` — sized by its own content/CSS with no `set_default_width` call +/// at all. `breadbar-panel` is exactly this today (popover content decides +/// its width via `.control-panel-inner`/`.wifi-popover-inner` min-width, not +/// the layer-shell window). +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum SurfaceWidth { + Fill, + Auto, + Px(i32), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Margin { + pub top: i32, + pub left: i32, + pub right: i32, + pub bottom: i32, +} + +/// `bar.window` — plan §2: window shape is data, not a closed layout enum. +/// Island/Edge/Capsule are three *values* of this struct, not three code +/// paths. +#[derive(Debug, Clone, PartialEq)] +pub struct WindowSpec { + pub anchors: Vec, + pub width: Width, + pub height: i32, + pub margin: Margin, + pub exclusive: Exclusive, + pub keyboard: Keyboard, + pub layer: String, +} + +impl Default for WindowSpec { + /// Generic baseline for a theme that omits `[bar.window]` entirely — + /// deliberately the plan §4 schema example's numbers, not necessarily + /// any particular shipped theme's. `liquid-motion` sets every field + /// explicitly, so it never falls through to this. + fn default() -> Self { + WindowSpec { + anchors: vec!["top".into(), "left".into(), "right".into()], + width: Width::Fill, + height: 44, + margin: Margin { + top: 12, + left: 14, + right: 14, + bottom: 0, + }, + exclusive: Exclusive::Auto, + keyboard: Keyboard::None, + layer: "top".into(), + } + } +} + +/// `bar.slots` — plan §2: structure is slots, not layout code. `drawer` is +/// the only thing Capsule/theme-04 adds over Island, and it's just an +/// (empty, for now) slot list, not a code path. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Slots { + pub left: Vec, + pub centre: Vec, + pub right: Vec, + pub drawer: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WorkspacesModule { + pub style: WorkspaceStyle, + pub show_empty: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClockModule { + pub style: ClockStyle, + pub format: String, + pub show_date: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Modules { + pub workspaces: WorkspacesModule, + pub clock: ClockModule, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Launcher { + pub mode: LauncherMode, + pub width: i32, + pub top: String, + pub radius: i32, + pub icon_px: i32, + pub row_anim: String, + pub rule: String, + pub footer: String, + pub sections: bool, + pub modes: Vec, +} + +/// A satellite surface, keyed by layer-shell namespace in `[surfaces.*]` — +/// deliberately the same keyspace as `[compositor.*]` (see module docs) +/// rather than a role name, so the two tables can be validated against each +/// other and a namespace's positioning and compositor treatment live under +/// one lookup. +#[derive(Debug, Clone, PartialEq)] +pub struct Surface { + pub anchor: String, + pub offset: Vec, + pub width: SurfaceWidth, + pub layer: String, +} + +/// One `[compositor.*]` entry — plan §9: the per-namespace layer-shell rule +/// an app ships as its default and a theme may override. Mirrors the field +/// set `hl.layer_rule` actually accepts in `scripts/ui/rules.lua` (blur, +/// ignore_alpha, blur_popups, animation, no_anim) — that Lua API isn't in +/// hyprland-api.lua's type annotations, so this field set is evidenced by +/// working usage, not documentation (plan §12 risk 3). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct LayerRule { + pub blur: bool, + pub ignore_alpha: Option, + pub blur_popups: bool, + /// Passed through verbatim to `hl.layer_rule`'s `animation` field + /// (`"slide top"`, `"slide bottom"`, …) — kept as a plain string rather + /// than a closed enum since `hl.layer_rule`'s own field set is only + /// evidenced by working usage in `rules.lua`, not documented (plan §12 + /// risk 3); a closed Rust enum here would need updating in lockstep + /// with Hyprland additions this crate has no way to know about. + pub animation: Option, + pub no_anim: bool, +} + +/// A raw TOML scalar carried through to [`Tokens`] for `{name}` substitution +/// in [`crate::shell::ShellTheme::css`]. Kept untyped (rather than forcing +/// every token into a `String`) so `css()` can format a number without a +/// theme author having to quote it, while `bg_alpha = 0.72` etc. still round +/// -trips as a real float for any future non-string consumer. +#[derive(Debug, Clone, PartialEq)] +pub enum TokenValue { + Str(String), + Int(i64), + Float(f64), + Bool(bool), +} + +impl TokenValue { + /// Textual form used both for `{name}` substitution in CSS and for the + /// typed accessors' fallback formatting. + pub fn as_css(&self) -> String { + match self { + TokenValue::Str(s) => s.clone(), + TokenValue::Int(i) => i.to_string(), + TokenValue::Float(f) => { + if f.fract() == 0.0 { + format!("{f:.0}") + } else { + f.to_string() + } + } + TokenValue::Bool(b) => b.to_string(), + } + } +} + +/// `[tokens]`, resolved. Deliberately an open bag (`BTreeMap`), not a fixed +/// struct: the schema (plan §4) names eleven fields, but a theme may define +/// arbitrary extra keys purely for `{name}` substitution in `extra.css` +/// (`radius_pill`, `chip_height`, `icon_px`, `spring_settle` below are all +/// exactly this — real values `theme.rs::load_css` uses today that the plan +/// text's `[tokens]` example didn't list). The named accessors below give +/// the documented fields typed access with sensible defaults; [`Tokens::get`] +/// and [`Tokens::substitute`] cover everything else. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Tokens { + pub(crate) map: BTreeMap, +} + +impl Tokens { + pub fn from_map(map: BTreeMap) -> Self { + Tokens { map } + } + + pub fn get(&self, key: &str) -> Option<&TokenValue> { + self.map.get(key) + } + + pub fn keys(&self) -> impl Iterator { + self.map.keys().map(|s| s.as_str()) + } + + fn str_or(&self, key: &str, default: &str) -> String { + match self.map.get(key) { + Some(v) => v.as_css(), + None => default.to_string(), + } + } + + fn int_or(&self, key: &str, default: i64) -> i64 { + match self.map.get(key) { + Some(TokenValue::Int(i)) => *i, + Some(TokenValue::Float(f)) => *f as i64, + Some(TokenValue::Str(s)) => s.parse().unwrap_or(default), + _ => default, + } + } + + fn float_or(&self, key: &str, default: f64) -> f64 { + match self.map.get(key) { + Some(TokenValue::Float(f)) => *f, + Some(TokenValue::Int(i)) => *i as f64, + Some(TokenValue::Str(s)) => s.parse().unwrap_or(default), + _ => default, + } + } + + pub fn font_family(&self) -> String { + self.str_or("font_family", crate::tokens::FONT_FAMILY) + } + pub fn font_fallback(&self) -> String { + self.str_or("font_fallback", "sans-serif") + } + pub fn font_size_base(&self) -> i64 { + self.int_or("font_size_base", crate::tokens::FONT_SIZE_BASE as i64) + } + pub fn radius_bar(&self) -> i64 { + self.int_or("radius_bar", crate::tokens::RADIUS_PRIMARY as i64) + } + pub fn radius_card(&self) -> i64 { + self.int_or("radius_card", crate::tokens::RADIUS_PRIMARY as i64) + } + pub fn radius_sm(&self) -> i64 { + self.int_or("radius_sm", crate::tokens::RADIUS_SECONDARY as i64) + } + /// Not in the plan §4 schema list, but a named local in + /// `theme.rs::load_css` (`radius_pill = "999px"`) alongside the three + /// siblings that are. See the [`Tokens`] doc comment. + pub fn radius_pill(&self) -> i64 { + self.int_or("radius_pill", crate::tokens::RADIUS_PILL as i64) + } + pub fn pad(&self) -> i64 { + self.int_or("pad", crate::tokens::SPACE_MD as i64) + } + pub fn bg_alpha(&self) -> f64 { + self.float_or("bg_alpha", 0.72) + } + /// The overshoot/bounce curve (`0.22, 1.35, 0.36, 1`) — clock flips, + /// pop-ins, the workspace caret draw. + pub fn spring(&self) -> String { + self.str_or("spring", "cubic-bezier(0.22, 1.35, 0.36, 1)") + } + /// The settle curve (`0.22, 1.2, 0.36, 1`) — hovers, workspace-btn + /// opacity/background transitions, OSD/notification slide-ins. Not in + /// the plan §4 schema (which names only `spring`), but `theme.rs` uses + /// it just as pervasively as the overshoot curve. See [`Tokens`] doc. + pub fn spring_settle(&self) -> String { + self.str_or("spring_settle", "cubic-bezier(0.22, 1.2, 0.36, 1)") + } + pub fn accent_from(&self) -> String { + self.str_or("accent_from", "accent") + } + pub fn accent_to(&self) -> String { + let from = self.accent_from(); + self.str_or("accent_to", &from) + } + /// Workspace-pill / chip height. Not in the plan §4 schema, but + /// `breadbar::CHIP_HEIGHT` (32) today. See [`Tokens`] doc. + pub fn chip_height(&self) -> i64 { + self.int_or("chip_height", 32) + } + /// Not in the plan §4 schema, but `breadbar::ICON_PX` (24) today. See + /// [`Tokens`] doc. + pub fn icon_px(&self) -> i64 { + self.int_or("icon_px", 24) + } + + /// Replace every `{name}` occurrence in `template` with that token's + /// [`TokenValue::as_css`] form. Longest names are substituted first + /// (mirrors [`crate::resolve_color_names`]) so `{radius}` cannot + /// half-consume `{radius_bar}` if a theme happens to define both. + /// `@name` palette references are untouched — this only ever looks at + /// `{...}` tokens. + pub fn substitute(&self, template: &str) -> String { + let mut keys: Vec<&String> = self.map.keys().collect(); + keys.sort_by_key(|k| std::cmp::Reverse(k.len())); + let mut out = template.to_string(); + for k in keys { + let value = self.map[k].as_css(); + out = out.replace(&format!("{{{k}}}"), &value); + } + out + } +} From 92d3362a6bf114518866dec1549ff625ba245043 Mon Sep 17 00:00:00 2001 From: Breadway Date: Mon, 24 Aug 2026 18:23:31 +0800 Subject: [PATCH 08/34] shell: add widget: entries to the builtin's [bar.slots] (Phase 3b) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reproduces breadbar's now-removed fixed Lua-widget interleave (right-of-workspaces, left/right-of-clock, left-of-stats) as explicit widget: slot entries, so the builtin theme still renders pixel-identical to today's bar under breadbar's new theme-driven widget placement. `tray` deliberately has no slot entry anywhere — it stays in the control-panel popover regardless of [bar.slots]. Updates the one test asserting the builtin's slot contents. --- bread-theme/assets/shell/liquid-motion/theme.toml | 13 ++++++++++--- bread-theme/src/shell/mod.rs | 10 ++++++++-- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/bread-theme/assets/shell/liquid-motion/theme.toml b/bread-theme/assets/shell/liquid-motion/theme.toml index 72a8f4d..d8bf1ec 100644 --- a/bread-theme/assets/shell/liquid-motion/theme.toml +++ b/bread-theme/assets/shell/liquid-motion/theme.toml @@ -57,9 +57,16 @@ keyboard = "none" layer = "top" [bar.slots] -left = ["workspaces"] -centre = ["media", "clock"] -right = ["volume", "wifi", "battery", "control"] +# The `widget:*` entries reproduce breadbar's pre-Phase-3b fixed Lua-widget +# interleave exactly (main.rs's now-removed widget_right_of_workspaces / +# widget_left_of_clock / widget_right_of_clock / widget_left_of_stats), so +# this manifest still renders pixel-identically to today's bar. `tray` +# deliberately has NO slot entry anywhere — it lives in the control-panel +# popover, not the bar, and is keyed directly by breadbar regardless of +# `[bar.slots]`. +left = ["workspaces", "widget:right_of_workspaces"] +centre = ["media", "widget:left_of_clock", "clock", "widget:right_of_clock"] +right = ["widget:left_of_stats", "volume", "wifi", "battery", "control"] drawer = [] [modules.workspaces] diff --git a/bread-theme/src/shell/mod.rs b/bread-theme/src/shell/mod.rs index 526b87c..a241ca9 100644 --- a/bread-theme/src/shell/mod.rs +++ b/bread-theme/src/shell/mod.rs @@ -550,8 +550,14 @@ mod tests { #[test] fn builtin_slots_and_modules_are_trail_and_flip() { let theme = resolve_builtin(); - assert_eq!(theme.slots().left, vec!["workspaces"]); - assert_eq!(theme.slots().centre, vec!["media", "clock"]); + assert_eq!( + theme.slots().left, + vec!["workspaces", "widget:right_of_workspaces"] + ); + assert_eq!( + theme.slots().centre, + vec!["media", "widget:left_of_clock", "clock", "widget:right_of_clock"] + ); assert!(matches!( theme.modules().workspaces.style, WorkspaceStyle::Trail From ea9758a5d5182653414d44cbe54ca47e3da0a7b6 Mon Sep 17 00:00:00 2001 From: Breadway Date: Mon, 24 Aug 2026 18:57:35 +0800 Subject: [PATCH 09/34] bread-theme: generate Hyprland layer rules from the shell theme (Phase 4a) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds `bread-theme layerrules`, which writes the active shell theme's [compositor] table to ~/.config/hypr/layerrules.json (atomic write). This lets ~/.config/hypr/scripts/ui/rules.lua read theme-driven blur/transparency/ animation for the breadbar/breadbox layer-shell namespaces instead of having them hardcoded, following THEME_SYSTEM_PLAN.md §9. rules.lua keeps its previous hardcoded rules as a pcall-guarded fallback for when the JSON is missing or malformed (lives outside this repo, so not part of this commit). Also fixes a pre-existing test race: shell::tests and the new layerrules::tests both mutate XDG_CONFIG_HOME in parallel `cargo test` threads but previously used separate, unrelated locks (or none), so they could observe each other's env var changes mid-test. Both now share bread_theme::test_support::XDG_CONFIG_HOME_LOCK. --- bread-theme/src/bin/bread-theme.rs | 30 ++++- bread-theme/src/layerrules.rs | 182 +++++++++++++++++++++++++++++ bread-theme/src/lib.rs | 15 +++ bread-theme/src/output.rs | 2 +- bread-theme/src/shell/mod.rs | 14 +-- bread-theme/src/shell/types.rs | 12 +- 6 files changed, 241 insertions(+), 14 deletions(-) create mode 100644 bread-theme/src/layerrules.rs diff --git a/bread-theme/src/bin/bread-theme.rs b/bread-theme/src/bin/bread-theme.rs index 3d7a862..a6d5b49 100644 --- a/bread-theme/src/bin/bread-theme.rs +++ b/bread-theme/src/bin/bread-theme.rs @@ -11,6 +11,8 @@ //! bread-theme print # render to stdout (no write) //! bread-theme generate-output --image [--shared] //! bread-theme generate-output --from-json [--shared] +//! bread-theme layerrules # write the active theme's [compositor] table +//! # to ~/.config/hypr/layerrules.json (plan §9) use std::process::ExitCode; @@ -31,7 +33,7 @@ fn print_help() { eprintln!( "bread-theme — shared stylesheet generator\n\n\ USAGE:\n\ - \x20 bread-theme [generate|reload|path|print]\n\ + \x20 bread-theme [generate|reload|path|print|layerrules]\n\ \x20 bread-theme generate-output --image [--shared]\n\ \x20 bread-theme generate-output --from-json [--shared]\n\n\ generate render the pywal palette to the shared stylesheet (default)\n\ @@ -41,8 +43,14 @@ fn print_help() { generate-output write palettes/.json and themes/.css\n\ \x20 --image isolated `wal -i` (does not touch ~/.cache/wal)\n\ \x20 --from-json wal colors.json or a color1-6 object\n\ - \x20 --shared also write the session-global theme.css", - bread_theme::shared_css_path().display() + \x20 --shared also write the session-global theme.css\n\ + layerrules write the active shell theme's [compositor] table to\n\ + \x20 {} —\n\ + \x20 scripts/ui/rules.lua reads it for per-namespace blur/\n\ + \x20 animation, falling back to its hardcoded rules if this\n\ + \x20 is missing or malformed", + bread_theme::shared_css_path().display(), + bread_theme::layerrules_path().display() ); } @@ -170,6 +178,19 @@ fn finish_generate_output(output: &str, css: std::path::PathBuf, shared: bool) - } } +fn layerrules_cmd() -> ExitCode { + match bread_theme::write_layerrules_active() { + Ok(path) => { + eprintln!("bread-theme: wrote {}", path.display()); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("bread-theme: failed to write layer rules: {e}"); + ExitCode::FAILURE + } + } +} + fn main() -> ExitCode { let cmd = std::env::args().nth(1).unwrap_or_else(|| "generate".into()); match cmd.as_str() { @@ -188,13 +209,14 @@ fn main() -> ExitCode { // palette and recolour live — shared widgets *and* each app's own rules. "reload" => write_and_report("reloaded"), "generate-output" => generate_output_cmd(), + "layerrules" => layerrules_cmd(), "-h" | "--help" | "help" => { print_help(); ExitCode::SUCCESS } other => { eprintln!( - "bread-theme: unknown command '{other}' (try generate|reload|path|print|generate-output)" + "bread-theme: unknown command '{other}' (try generate|reload|path|print|generate-output|layerrules)" ); ExitCode::FAILURE } diff --git a/bread-theme/src/layerrules.rs b/bread-theme/src/layerrules.rs new file mode 100644 index 0000000..76bcca8 --- /dev/null +++ b/bread-theme/src/layerrules.rs @@ -0,0 +1,182 @@ +//! Generates `~/.config/hypr/layerrules.json` from the active shell theme's +//! `[compositor]` table (`THEME_SYSTEM_PLAN.md` §9). `scripts/ui/rules.lua` +//! reads this file and emits `hl.layer_rule` calls from it, keeping its own +//! hardcoded rules as a pcall-guarded fallback for when this file is missing +//! or malformed — so generation here never has to be perfect, only present. +//! +//! Scope (plan §9's appearance/placement boundary): a theme's `[compositor]` +//! table owns per-namespace *appearance* only — blur, ignore_alpha, +//! blur_popups, animation, no_anim (the [`crate::shell::LayerRule`] field +//! set). It never owns placement, workspace-assignment, or focus rules — +//! those stay Lua-side user policy (`rules.lua`'s `hl.window_rule` calls) +//! that this generator does not touch. + +use std::path::PathBuf; + +use crate::shell::ShellTheme; + +fn config_home() -> PathBuf { + if let Ok(v) = std::env::var("XDG_CONFIG_HOME") { + if !v.is_empty() { + return PathBuf::from(v); + } + } + dirs::home_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join(".config") +} + +/// `~/.config/hypr/layerrules.json` (or under `$XDG_CONFIG_HOME` if set) — +/// alongside `binds.json`, `settings.json`, `monitors.json`, and +/// `autostart.json`, the established flat-JSON-under-`hypr/` convention +/// those files already use (see `~/.config/hypr/scripts/input/binds.lua` for +/// the read side of that pattern, which `scripts/ui/rules.lua` now mirrors). +pub fn layerrules_path() -> PathBuf { + config_home().join("hypr").join("layerrules.json") +} + +/// Render `theme`'s `[compositor]` table as the JSON object +/// `scripts/ui/rules.lua` expects: keyed by layer-shell namespace (e.g. +/// `"breadbar"`, `"breadbox"`), each value the namespace's +/// [`crate::shell::LayerRule`] fields. `compositor_rules()` returns a +/// `BTreeMap`, so namespace order is stable (alphabetical) across runs and a +/// rewritten file diffs cleanly. +pub fn layerrules_json(theme: &ShellTheme) -> String { + serde_json::to_string_pretty(theme.compositor_rules()) + .expect("LayerRule serialization is infallible (no maps/floats that can fail)") +} + +/// [`layerrules_json`] + atomic write (tmp + rename), the same durability +/// [`crate::write_shared_css_from`] uses so a reload can never observe a +/// half-written file. +pub fn write_layerrules(theme: &ShellTheme) -> std::io::Result { + let path = layerrules_path(); + let json = layerrules_json(theme); + crate::output::atomic_write(&path, &json)?; + Ok(path) +} + +/// [`write_layerrules`] from the active theme ([`crate::shell::load`], which +/// never fails — a broken active theme falls back to the builtin). Used by +/// the `bread-theme layerrules` CLI subcommand. +pub fn write_layerrules_active() -> std::io::Result { + write_layerrules(&crate::shell::load()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + fn lock_xdg() -> std::sync::MutexGuard<'static, ()> { + // Shared with `shell::tests::isolated_xdg`, which also mutates + // XDG_CONFIG_HOME — must be the *same* lock, not a look-alike one, + // or the two modules' parallel tests race each other's env var + // reads (see `crate::test_support`'s doc comment). + crate::test_support::XDG_CONFIG_HOME_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()) + } + + fn with_config_home(f: impl FnOnce(&Path) -> T) -> T { + let _lock = lock_xdg(); + let dir = std::env::temp_dir().join(format!( + "bread-theme-layerrules-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let old = std::env::var("XDG_CONFIG_HOME").ok(); + std::env::set_var("XDG_CONFIG_HOME", &dir); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&dir))); + match old { + Some(v) => std::env::set_var("XDG_CONFIG_HOME", v), + None => std::env::remove_var("XDG_CONFIG_HOME"), + } + let _ = std::fs::remove_dir_all(&dir); + match result { + Ok(v) => v, + Err(e) => std::panic::resume_unwind(e), + } + } + + #[test] + fn layerrules_path_sits_under_config_hypr() { + with_config_home(|dir| { + assert_eq!(layerrules_path(), dir.join("hypr").join("layerrules.json")); + }); + } + + /// `load_named("liquid-motion")` resolves through discovery (user dir, + /// then system dir, then the compiled-in builtin) — isolate + /// `XDG_CONFIG_HOME` to an empty dir so this can't pick up a real + /// `~/.config/bread/themes/liquid-motion/theme.toml` override and land + /// on a different `[compositor]` table than the builtin's. + fn builtin_theme() -> ShellTheme { + with_config_home(|_| crate::shell::load_named("liquid-motion").unwrap()) + } + + #[test] + fn layerrules_json_covers_all_six_builtin_namespaces() { + let theme = builtin_theme(); + let json = layerrules_json(&theme); + let value: serde_json::Value = serde_json::from_str(&json).unwrap(); + let obj = value.as_object().expect("top-level object"); + for ns in [ + "breadbar", + "breadbar-osd", + "breadbar-notif", + "breadbar-panel", + "breadbar-dismiss", + "breadbox", + ] { + assert!(obj.contains_key(ns), "missing namespace {ns} in JSON"); + } + } + + #[test] + fn layerrules_json_shape_matches_breadbar_rule() { + let theme = builtin_theme(); + let json = layerrules_json(&theme); + let value: serde_json::Value = serde_json::from_str(&json).unwrap(); + let bar = &value["breadbar"]; + assert_eq!(bar["blur"], true); + assert_eq!(bar["ignore_alpha"], 0.2); + assert_eq!(bar["blur_popups"], true); + assert_eq!(bar["animation"], "slide top"); + // no_anim is a plain bool (not Option), so it's always present, even + // when false — unlike ignore_alpha/animation which are omitted. + assert_eq!(bar["no_anim"], false); + + let dismiss = &value["breadbar-dismiss"]; + assert_eq!(dismiss["no_anim"], true); + // ignore_alpha/animation are unset for breadbar-dismiss, so the + // skip_serializing_if omits them entirely rather than writing null. + assert!(dismiss.get("ignore_alpha").is_none()); + assert!(dismiss.get("animation").is_none()); + } + + #[test] + fn write_layerrules_active_writes_atomically_and_is_reloadable() { + with_config_home(|dir| { + let path = write_layerrules_active().unwrap(); + assert_eq!(path, dir.join("hypr").join("layerrules.json")); + assert!(path.is_file()); + // No leftover .tmp file after the atomic rename. + assert!(!path.with_file_name("layerrules.json.tmp").exists()); + + let contents = std::fs::read_to_string(&path).unwrap(); + let value: serde_json::Value = serde_json::from_str(&contents).unwrap(); + assert!(value.as_object().unwrap().contains_key("breadbox")); + + // Rewriting (theme switch, pywal hook, etc.) must not fail or + // leave a stale temp file behind. + let path2 = write_layerrules_active().unwrap(); + assert_eq!(path, path2); + assert!(!path.with_file_name("layerrules.json.tmp").exists()); + }); + } +} diff --git a/bread-theme/src/lib.rs b/bread-theme/src/lib.rs index d20c955..12fa498 100644 --- a/bread-theme/src/lib.rs +++ b/bread-theme/src/lib.rs @@ -2,10 +2,12 @@ pub mod adw; #[cfg(feature = "gtk")] pub mod gtk; +mod layerrules; mod output; pub mod palette; pub mod shell; +pub use layerrules::{layerrules_json, layerrules_path, write_layerrules, write_layerrules_active}; pub use output::{ generate_output, load_palette_for, output_css_path, output_palette_path, palette_from_image, palette_from_json, palettes_dir, sanitize_output, themes_dir, write_output_css, @@ -13,6 +15,19 @@ pub use output::{ }; pub use palette::{load_palette, Palette}; +/// Env-var locks shared by any test module that mutates process-global +/// state (`std::env::set_var`) — `cargo test` runs a crate's tests in +/// parallel by default, so every module touching the *same* env var must +/// serialize through the *same* lock or their mutations race each other's +/// reads. `bread_theme::output`'s own `XDG_ENV_LOCK` guards `XDG_RUNTIME_DIR` +/// specifically and stays where it is; `XDG_CONFIG_HOME_LOCK` here is the +/// one shared by `shell::tests` and `layerrules::tests`, which both point +/// `XDG_CONFIG_HOME` at an isolated temp dir. +#[cfg(test)] +pub(crate) mod test_support { + pub(crate) static XDG_CONFIG_HOME_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +} + /// Design tokens from BREAD_DESIGN_SYSTEM.md. pub mod tokens { pub const FONT_FAMILY: &str = "Varela Round, sans-serif"; diff --git a/bread-theme/src/output.rs b/bread-theme/src/output.rs index 4f2f069..5389277 100644 --- a/bread-theme/src/output.rs +++ b/bread-theme/src/output.rs @@ -54,7 +54,7 @@ pub fn output_palette_path(output: &str) -> PathBuf { palettes_dir().join(format!("{}.json", sanitize_output(output))) } -fn atomic_write(path: &Path, contents: &str) -> std::io::Result<()> { +pub(crate) fn atomic_write(path: &Path, contents: &str) -> std::io::Result<()> { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } diff --git a/bread-theme/src/shell/mod.rs b/bread-theme/src/shell/mod.rs index a241ca9..dc48683 100644 --- a/bread-theme/src/shell/mod.rs +++ b/bread-theme/src/shell/mod.rs @@ -403,13 +403,6 @@ pub fn list() -> Vec { #[cfg(test)] mod tests { use super::*; - use std::sync::Mutex; - - // Guards mutation of XDG_CONFIG_HOME / BREAD_SHELL_THEME, which are - // process-global — mirrors bread_theme::output's XDG_ENV_LOCK pattern - // (a different env var, same reason: cargo test runs a module's tests - // in parallel by default). - static ENV_LOCK: Mutex<()> = Mutex::new(()); struct EnvGuard { _lock: std::sync::MutexGuard<'static, ()>, @@ -437,7 +430,12 @@ mod tests { /// whatever's set in the outer test-runner environment. Held for the /// guard's lifetime. fn isolated_xdg() -> EnvGuard { - let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + // Shared with `layerrules::tests`, which also isolates + // XDG_CONFIG_HOME — see `crate::test_support` for why this must be + // the *same* lock rather than a module-private one. + let lock = crate::test_support::XDG_CONFIG_HOME_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); let dir = std::env::temp_dir().join(format!( "bread-theme-shell-test-{}-{}", std::process::id(), diff --git a/bread-theme/src/shell/types.rs b/bread-theme/src/shell/types.rs index 06982a2..872ab40 100644 --- a/bread-theme/src/shell/types.rs +++ b/bread-theme/src/shell/types.rs @@ -181,9 +181,18 @@ pub struct Surface { /// ignore_alpha, blur_popups, animation, no_anim) — that Lua API isn't in /// hyprland-api.lua's type annotations, so this field set is evidenced by /// working usage, not documentation (plan §12 risk 3). -#[derive(Debug, Clone, PartialEq, Default)] +/// +/// Also `Serialize`: this is the per-namespace shape written to +/// `~/.config/hypr/layerrules.json` by `bread_theme::layerrules` (plan §9 +/// step 3-4), which `scripts/ui/rules.lua` parses back into `hl.layer_rule` +/// calls. `Option::None` fields are omitted rather than emitted as `null` — +/// the Lua JSON reader treats a missing key and a `null` value identically +/// (assigning `nil` into a table key is a no-op), so either encoding is +/// correct, but omitting keeps the file legible for hand inspection. +#[derive(Debug, Clone, PartialEq, Default, serde::Serialize)] pub struct LayerRule { pub blur: bool, + #[serde(skip_serializing_if = "Option::is_none")] pub ignore_alpha: Option, pub blur_popups: bool, /// Passed through verbatim to `hl.layer_rule`'s `animation` field @@ -192,6 +201,7 @@ pub struct LayerRule { /// evidenced by working usage in `rules.lua`, not documented (plan §12 /// risk 3); a closed Rust enum here would need updating in lockstep /// with Hyprland additions this crate has no way to know about. + #[serde(skip_serializing_if = "Option::is_none")] pub animation: Option, pub no_anim: bool, } From 53a6c59f2d8b89c6bd73e94e4d00fb94c632fd8a Mon Sep 17 00:00:00 2001 From: Breadway Date: Mon, 24 Aug 2026 19:13:36 +0800 Subject: [PATCH 10/34] bread-theme: correct [launcher] manifest to match breadbox's actual behaviour radius (20 -> 8) and icon_px (36 -> 32) were demo-derived aspirations, not what breadbox implements today (.launcher-bg's actual border-radius and make_icon's actual set_pixel_size). row_anim/rule/footer/sections/modes are kept but marked declared-but-not-yet-consumed: breadbox implements none of row animation, a rule/divider, a footer, sections, or query modes today, so the manifest should say so rather than imply they're live. Adds a builtin launcher test mirroring the existing window/tokens fidelity tests. --- .../assets/shell/liquid-motion/theme.toml | 26 ++++++++++++++++--- bread-theme/src/shell/mod.rs | 15 +++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/bread-theme/assets/shell/liquid-motion/theme.toml b/bread-theme/assets/shell/liquid-motion/theme.toml index d8bf1ec..5b3c8f5 100644 --- a/bread-theme/assets/shell/liquid-motion/theme.toml +++ b/bread-theme/assets/shell/liquid-motion/theme.toml @@ -8,8 +8,10 @@ # breadbar/src/theme.rs (load_css's radius/pad/spring locals and the actual # CSS selectors), breadbar/src/{panel,osd}.rs and # breadbar/src/notifications/{popup,history}.rs (satellite window anchors, -# margins, namespaces), breadbox/breadbox/src/main.rs:341-344 (launcher -# geometry), ~/.config/hypr/scripts/ui/rules.lua (compositor rules). +# margins, namespaces), breadbox/breadbox/src/main.rs:341-346 (launcher +# margin/size), :151 (build_css's .launcher-bg radius), :174-193 (make_icon's +# set_pixel_size calls), ~/.config/hypr/scripts/ui/rules.lua (compositor +# rules). name = "Liquid Motion" id = "liquid-motion" @@ -85,8 +87,24 @@ show_date = false mode = "overlay" width = 600 top = "120px" -radius = 20 -icon_px = 36 +# .launcher-bg { border-radius: 8px } (build_css, main.rs:151) — corrected +# from an earlier demo-derived 20px; breadbox does not implement the demo's +# 20px rounding. +radius = 8 +# make_icon() (main.rs:174-193) calls img.set_pixel_size(32) on both the +# cached-texture (gio::File/gdk::Texture) path and the GTK icon-theme +# fallback path — corrected from a demo-derived 36px. +icon_px = 32 +# Declared-but-not-yet-consumed: breadbox's Phase 4b-i wiring reads only +# mode/width/top/radius/icon_px above; it does not read any of the five keys +# below. row_anim/rule/footer are demo-derived aspirations breadbox +# implements not at all today (no row entrance/exit animation, no +# rule/divider element between the search entry and the list, no footer +# widget summarizing app count). sections/modes happen to already describe +# today's actual (trivial) behaviour — one flat unsectioned list, plain app +# search with no calc/command/url modes — but are likewise unread by any +# code path; a real sections/modes implementation is Phase 5/6, same as the +# other three. row_anim = "flip" rule = "gradient" footer = "count_apps" diff --git a/bread-theme/src/shell/mod.rs b/bread-theme/src/shell/mod.rs index dc48683..c847896 100644 --- a/bread-theme/src/shell/mod.rs +++ b/bread-theme/src/shell/mod.rs @@ -563,6 +563,21 @@ mod tests { assert!(matches!(theme.modules().clock.style, ClockStyle::Flip)); } + #[test] + fn builtin_launcher_matches_current_breadbox_geometry() { + // breadbox/breadbox/src/main.rs:341-346 (margin/size), :151 + // (build_css's .launcher-bg radius), :174-193 (make_icon's + // set_pixel_size calls). radius=8 and icon_px=32 are current CODE + // values, not the demo's 20/36 — see Phase 4b-i's manifest audit. + let theme = resolve_builtin(); + let l = theme.launcher(); + assert!(matches!(l.mode, LauncherMode::Overlay)); + assert_eq!(l.width, 600); + assert_eq!(l.top, "120px"); + assert_eq!(l.radius, 8); + assert_eq!(l.icon_px, 32); + } + #[test] fn builtin_css_substitutes_tokens_and_leaves_palette_names_untouched() { let theme = resolve_builtin(); From 96fa79c1d4e26c1dadc76fb89dde19fb7040d32e Mon Sep 17 00:00:00 2001 From: Breadway Date: Mon, 24 Aug 2026 23:13:22 +0800 Subject: [PATCH 11/34] shell theme: add glass-workbench as a second compiled-in theme MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 5 of the shell theme system (THEME_SYSTEM_PLAN.md §11): a second builtin, demo 02's flush edge-to-edge bar with pill workspaces, a plain date+time clock, and cpu/ram chips instead of the media widget. - bread-theme/assets/shell/glass-workbench/: theme.toml + CSS template, faithful to bos-ui-demos/02-glass-workbench.html. Accent maps to the `green` palette token (flat, not a gradient) rather than a hex literal, so pywal theming still works. - builtin.rs: generalized from a single hardcoded liquid-motion constant pair to a small BuiltinTheme registry (builtin::ALL / builtin::find), so mod.rs's discovery/list()/resolve_builtin no longer special-case one id. liquid-motion stays the pinned fallback in resolve_builtin(). - manifest.rs: KNOWN_MODULES gains "cpu"/"ram". - types.rs: new Tokens::bar_border() ("full" default vs "bottom") so a flush bar can ask for a single hairline instead of an island's full border. - Tests: builtin loads, appears in list() alongside liquid-motion, and its window spec is the flush/edge shape (36px, zero margin, radius 0). cargo test -p bread-theme --lib: 63 passing (59 prior + 4 new). --- .../shell/glass-workbench/glass-workbench.css | 86 +++++++++ .../assets/shell/glass-workbench/theme.toml | 169 ++++++++++++++++++ bread-theme/src/shell/builtin.rs | 78 ++++++-- bread-theme/src/shell/manifest.rs | 5 + bread-theme/src/shell/mod.rs | 159 +++++++++++++--- bread-theme/src/shell/types.rs | 10 ++ 6 files changed, 467 insertions(+), 40 deletions(-) create mode 100644 bread-theme/assets/shell/glass-workbench/glass-workbench.css create mode 100644 bread-theme/assets/shell/glass-workbench/theme.toml diff --git a/bread-theme/assets/shell/glass-workbench/glass-workbench.css b/bread-theme/assets/shell/glass-workbench/glass-workbench.css new file mode 100644 index 0000000..f34f33a --- /dev/null +++ b/bread-theme/assets/shell/glass-workbench/glass-workbench.css @@ -0,0 +1,86 @@ +/* CSS template for the glass-workbench builtin (bread-theme/src/shell/ + * builtin.rs). Same scope and substitution rules as liquid-motion.css: only + * the window/workspace/clock chrome the manifest's own concepts model, `{name}` + * tokens substituted, `@name` palette references passed through untouched. + * + * Source: bos-ui-demos/02-glass-workbench.html's