From 65ccaebc1c2612749fdf84ac090b0fb02187e6b7 Mon Sep 17 00:00:00 2001 From: Willem Vanhulle Date: Wed, 21 Oct 2026 11:17:40 +0200 Subject: [PATCH] docs: improve documentation of settings using a subcommand --- Cargo.lock | 11 +++ Cargo.toml | 4 +- README.md | 47 ++++++------ demo/host.nix | 8 +- nixos-module.nix | 67 ++++++----------- src/colors.rs | 169 +++++++++++++++++++++++++++++++++++++++++++ src/config.rs | 91 +++++++++++++++++++---- src/lib.rs | 2 +- src/main.rs | 94 ++++++++++++++++++++---- src/palette.rs | 28 ------- src/run.rs | 6 +- src/script.rs | 4 +- src/view.rs | 31 ++++---- src/view/chrome.rs | 47 ++++++------ src/view/stages.rs | 26 +++---- src/view/timeline.rs | 34 ++++----- src/view/tree.rs | 68 +++++++++-------- 17 files changed, 514 insertions(+), 223 deletions(-) create mode 100644 src/colors.rs delete mode 100644 src/palette.rs diff --git a/Cargo.lock b/Cargo.lock index 689dddc..39f41f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -149,9 +149,11 @@ dependencies = [ "clap", "crossterm 0.29.0", "dbus", + "heck", "jiff", "ratatui", "rustix 1.1.5", + "ser_nix", "serde", "signal-hook 0.4.5", "toml", @@ -1459,6 +1461,15 @@ version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +[[package]] +name = "ser_nix" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15c4a28964fde1fd104730b0df327697c4e2adc0956d60a6514b832bb2df349d" +dependencies = [ + "serde", +] + [[package]] name = "serde" version = "1.0.229" diff --git a/Cargo.toml b/Cargo.toml index e999150..9ad0655 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,12 +15,14 @@ missing_errors_doc = "allow" clap = { version = "4.6.7", features = ["derive"] } crossterm = "0.29.0" dbus = "0.9.12" +heck = "0.5.0" jiff = { version = "0.2.38", default-features = false, features = ["serde", "std"] } ratatui = { version = "0.30.2", features = ["serde", "unstable-rendered-line-info"] } rustix = { version = "1.1.5", features = ["event", "fs", "process", "stdio", "system", "termios", "time"] } +ser_nix = "0.2.4" serde = { version = "1.0.229", features = ["derive"] } signal-hook = "0.4.5" -toml = "1.1.8" +toml = { version = "1.1.8", features = ["preserve_order"] } unicode-truncate = "2.0.1" unicode-width = "0.2.2" zeroize = "1.9.1" diff --git a/README.md b/README.md index 0bf4781..c8fb4cc 100644 --- a/README.md +++ b/README.md @@ -140,36 +140,41 @@ dracut module as above, or on mkinitcpio install ## Configure -`/etc/bootvine.toml`, or `services.bootvine.palette` and -`services.bootvine.timing` on NixOS. Every key is optional; these are the -defaults: +`/etc/bootvine.toml`. Every key is optional; `bootvine defaults` prints them +all with their defaults, and `bootvine defaults --format nix` prints the same as +a Nix attribute set. A file that changes two of them: ```toml -[palette] -text = "white" -muted = "dark-gray" -waiting = "gray" -running = "yellow" -done = "green" -failed = "light-red" -target = "cyan" +[colors.tree] +running-marker = "light-yellow" [timing] -keep_finished_units_for = "2s" -hide_runs_shorter_than = "1s" -keep_final_frame_for = "1s" +keep-final-frame-for = "500ms" ``` -Palette values are the 16 console colour names. To change how those look, set -the console palette: `console.colors` on NixOS, or the `vt.default_red`, `_grn` -and `_blu` kernel parameters elsewhere. +Each `[colors.*]` table covers one part of the screen: `header`, the finished +`stages`, the unit `tree`, the `timeline`, the `footer` tallies and the +`password` popup. Values are the 16 console colour names. To change how those look, set the console palette: `console.colors` on +NixOS, or the `vt.default_red`, `_grn` and `_blu` kernel parameters elsewhere. -`keep_finished_units_for` is how long a finished unit stays in the tree, faded, -before it leaves. Runs shorter than `hide_runs_shorter_than` get no timer and no -timeline bar. `keep_final_frame_for` is how long the last frame stays before the +`keep-finished-units-for` is how long a finished unit stays in the tree, faded, +before it leaves. Runs shorter than `hide-runs-shorter-than` get no timer and no +timeline bar. `keep-final-frame-for` is how long the last frame stays before the console is handed back; `--hold` overrides it. -The initrd hooks copy the file into the initramfs, so rebuild it after editing. +`bootvine check /etc/bootvine.toml` reports unknown keys and bad values; at +boot, bootvine ignores an invalid file and uses the defaults. The initrd hooks +copy the file into the initramfs, so rebuild it after editing. + +On NixOS, set the same tables under `services.bootvine.settings`; the rebuild +fails if `bootvine check` rejects them: + +```nix +services.bootvine.settings = { + colors.tree.running-marker = "light-yellow"; + timing.keep-final-frame-for = "500ms"; +}; +``` ## License diff --git a/demo/host.nix b/demo/host.nix index 1c332af..295dbd2 100644 --- a/demo/host.nix +++ b/demo/host.nix @@ -44,7 +44,13 @@ in services.bootvine = { enable = true; - palette.running = "light-yellow"; + settings.colors = { + tree.current-stage = "light-yellow"; + tree.running-marker = "light-yellow"; + timeline.running = "light-yellow"; + footer.running = "light-yellow"; + password.frame = "light-yellow"; + }; }; console = { diff --git a/nixos-module.nix b/nixos-module.nix index a7f9f8d..3958436 100644 --- a/nixos-module.nix +++ b/nixos-module.nix @@ -7,35 +7,14 @@ }: let cfg = config.services.bootvine; - chosen = lib.filterAttrs (_: value: value != null); - settings = lib.filterAttrs (_: table: table != { }) { - palette = chosen cfg.palette; - timing = chosen cfg.timing; - }; - configFile = (pkgs.formats.toml { }).generate "bootvine.toml" settings; - durationOption = - purpose: default: - lib.mkOption { - type = lib.types.nullOr lib.types.str; - default = null; - example = "500ms"; - description = '' - ${purpose}; unset keeps `${default}`. A duration such as `2s`, - `500ms` or `1m 30s`. - ''; - }; - colorOption = - role: default: - lib.mkOption { - type = lib.types.nullOr lib.types.str; - default = null; - example = "light-yellow"; - description = '' - Colour for ${role}; unset keeps `${default}`. One of the 16 console - colour names (`red`, `light-red`, `dark-gray`, …). What each name - looks like comes from the console palette, {option}`console.colors`. - ''; - }; + settingsFormat = pkgs.formats.toml { }; + uncheckedConfigFile = settingsFormat.generate "bootvine-unchecked.toml" cfg.settings; + canRunPackage = pkgs.stdenv.buildPlatform.canExecute pkgs.stdenv.hostPlatform; + configFile = pkgs.runCommand "bootvine.toml" { } '' + ${lib.optionalString canRunPackage "${lib.getExe cfg.package} check ${uncheckedConfigFile}"} + cp ${uncheckedConfigFile} $out + ''; + hasSettings = cfg.settings != { }; in { options.services.bootvine = { @@ -54,27 +33,25 @@ in description = "The bootvine package, which ships the systemd unit."; }; - palette = { - text = colorOption "running units and headings" "white"; - muted = colorOption "rules, tree lines and the time axis" "dark-gray"; - waiting = colorOption "queued units and finished-unit labels" "gray"; - running = colorOption "running units and their bars" "yellow"; - done = colorOption "finished units, stages and milestones" "green"; - failed = colorOption "failed units" "light-red"; - target = colorOption "targets in the tree" "cyan"; - }; - - timing = { - keep_finished_units_for = durationOption "How long a finished unit stays in the tree, faded, before it leaves" "2s"; - hide_runs_shorter_than = durationOption "Runs shorter than this get no timer in the tree and no bar on the timeline" "1s"; - keep_final_frame_for = durationOption "How long the last frame stays on screen before the console is handed back" "1s"; + settings = lib.mkOption { + inherit (settingsFormat) type; + default = { }; + example = { + colors.tree.running-marker = "light-yellow"; + timing.keep-final-frame-for = "500ms"; + }; + description = '' + Written to {file}`/etc/bootvine.toml`, in the real root and the + initrd. `bootvine defaults --format nix` prints every key with its + default; the build fails if `bootvine check` rejects the result. + ''; }; }; config = lib.mkIf cfg.enable { environment = { systemPackages = [ cfg.package ]; - etc."bootvine.toml" = lib.mkIf (settings != { }) { source = configFile; }; + etc."bootvine.toml" = lib.mkIf hasSettings { source = configFile; }; }; systemd = { @@ -87,7 +64,7 @@ in packages = [ cfg.package ]; storePaths = [ (lib.getExe cfg.package) ]; services.bootvine.wantedBy = [ "sysinit.target" ]; - contents."/etc/bootvine.toml" = lib.mkIf (settings != { }) { source = configFile; }; + contents."/etc/bootvine.toml" = lib.mkIf hasSettings { source = configFile; }; }; }; } diff --git a/src/colors.rs b/src/colors.rs new file mode 100644 index 0000000..226d102 --- /dev/null +++ b/src/colors.rs @@ -0,0 +1,169 @@ +use ratatui::style::Color; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] +pub struct Colors { + pub header: HeaderColors, + pub stages: StageColors, + pub tree: TreeColors, + pub timeline: TimelineColors, + pub footer: FooterColors, + pub password: PasswordColors, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] +pub struct HeaderColors { + pub origin: Color, + pub separators: Color, + pub total_time: Color, +} + +impl Default for HeaderColors { + fn default() -> Self { + Self { + origin: Color::White, + separators: Color::DarkGray, + total_time: Color::White, + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] +pub struct StageColors { + pub branches: Color, + pub finished_label: Color, + pub finished_time: Color, + pub unit_count: Color, + pub failed_count: Color, + pub current: Color, +} + +impl Default for StageColors { + fn default() -> Self { + Self { + branches: Color::DarkGray, + finished_label: Color::Gray, + finished_time: Color::Green, + unit_count: Color::Gray, + failed_count: Color::LightRed, + current: Color::White, + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] +pub struct TreeColors { + pub branches: Color, + pub columns: Color, + pub target: Color, + pub current_stage: Color, + pub reached_stage: Color, + pub running_unit: Color, + pub running_marker: Color, + pub waiting_unit: Color, + pub finished_unit: Color, + pub finished_marker: Color, + pub failed_unit: Color, + pub overflow: Color, +} + +impl Default for TreeColors { + fn default() -> Self { + Self { + branches: Color::DarkGray, + columns: Color::DarkGray, + target: Color::Cyan, + current_stage: Color::Yellow, + reached_stage: Color::Green, + running_unit: Color::White, + running_marker: Color::Yellow, + waiting_unit: Color::Gray, + finished_unit: Color::DarkGray, + finished_marker: Color::Green, + failed_unit: Color::LightRed, + overflow: Color::Gray, + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] +pub struct TimelineColors { + pub rule: Color, + pub title: Color, + pub axis: Color, + pub milestone: Color, + pub finished: Color, + pub finished_label: Color, + pub failed: Color, + pub queued_bar: Color, + pub running: Color, + pub running_label: Color, +} + +impl Default for TimelineColors { + fn default() -> Self { + Self { + rule: Color::DarkGray, + title: Color::Gray, + axis: Color::DarkGray, + milestone: Color::Green, + finished: Color::Green, + finished_label: Color::Gray, + failed: Color::LightRed, + queued_bar: Color::Gray, + running: Color::Yellow, + running_label: Color::White, + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] +pub struct FooterColors { + pub rule: Color, + pub done: Color, + pub running: Color, + pub waiting: Color, + pub failed: Color, + pub no_failures: Color, +} + +impl Default for FooterColors { + fn default() -> Self { + Self { + rule: Color::DarkGray, + done: Color::Green, + running: Color::Yellow, + waiting: Color::Gray, + failed: Color::LightRed, + no_failures: Color::Gray, + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] +pub struct PasswordColors { + pub frame: Color, + pub message: Color, + pub hint: Color, + pub checking: Color, + pub backdrop: Color, +} + +impl Default for PasswordColors { + fn default() -> Self { + Self { + frame: Color::Yellow, + message: Color::White, + hint: Color::DarkGray, + checking: Color::Gray, + backdrop: Color::DarkGray, + } + } +} diff --git a/src/config.rs b/src/config.rs index a1ac253..508a79b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,24 +1,27 @@ -use std::time::Duration; +use std::{error, fmt, fs, io, path::Path, time::Duration}; -use serde::Deserialize; +use heck::ToKebabCase; +use jiff::fmt::serde::unsigned_duration::friendly::compact::required as friendly_duration; +use serde::{Deserialize, Serialize}; +use toml::{Table, Value, de::Error as ParseError, ser::Error as SerializeError}; -use crate::palette::Palette; +use crate::colors::Colors; -#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] -#[serde(default, deny_unknown_fields)] +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] pub struct Config { - pub palette: Palette, + pub colors: Colors, pub timing: Timing, } -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] -#[serde(default, deny_unknown_fields)] +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] pub struct Timing { - #[serde(with = "jiff::fmt::serde::unsigned_duration::friendly::compact::required")] + #[serde(with = "friendly_duration")] pub keep_finished_units_for: Duration, - #[serde(with = "jiff::fmt::serde::unsigned_duration::friendly::compact::required")] + #[serde(with = "friendly_duration")] pub hide_runs_shorter_than: Duration, - #[serde(with = "jiff::fmt::serde::unsigned_duration::friendly::compact::required")] + #[serde(with = "friendly_duration")] pub keep_final_frame_for: Duration, } @@ -32,13 +35,60 @@ impl Default for Timing { } } +#[derive(Debug)] +pub enum ConfigError { + Unreadable(io::Error), + Invalid(ParseError), +} + +impl fmt::Display for ConfigError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unreadable(error) => write!(formatter, "cannot read: {error}"), + Self::Invalid(error) => write!(formatter, "invalid: {error}"), + } + } +} + +impl error::Error for ConfigError {} + +pub fn read_config_file(path: &Path) -> Result { + let text = fs::read_to_string(path).map_err(ConfigError::Unreadable)?; + toml::from_str(&text).map_err(ConfigError::Invalid) +} + +pub fn default_config_table() -> Result { + Table::try_from(Config::default()).map(kebab_color_names) +} + +fn kebab_color_names(table: Table) -> Table { + table + .into_iter() + .map(|(key, value)| { + let value = match value { + Value::Table(nested) => Value::Table(kebab_color_names(nested)), + Value::String(name) if name.starts_with(char::is_alphabetic) => { + Value::String(name.to_kebab_case()) + } + other => other, + }; + (key, value) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; + fn printed_defaults() -> String { + toml::to_string_pretty(&default_config_table().expect("serializable defaults")) + .expect("printable defaults") + } + #[test] fn timing_reads_friendly_durations_and_keeps_unset_defaults() { - let config: Config = toml::from_str("[timing]\nkeep_finished_units_for = \"500ms\"\n") + let config: Config = toml::from_str("[timing]\nkeep-finished-units-for = \"500ms\"\n") .expect("valid config"); assert_eq!( config.timing.keep_finished_units_for, @@ -52,6 +102,21 @@ mod tests { #[test] fn nonsense_durations_are_rejected() { - assert!(toml::from_str::("[timing]\nkeep_final_frame_for = \"soon\"\n").is_err()); + assert!(toml::from_str::("[timing]\nkeep-final-frame-for = \"soon\"\n").is_err()); + } + + #[test] + fn unknown_color_keys_are_rejected() { + assert!(toml::from_str::("[colors.tree]\nbogus = \"red\"\n").is_err()); + } + + #[test] + fn printed_defaults_read_back_unchanged() { + let printed = printed_defaults(); + assert!(printed.contains("failed-unit = \"light-red\""), "{printed}"); + assert_eq!( + toml::from_str::(&printed).expect("valid defaults"), + Config::default() + ); } } diff --git a/src/lib.rs b/src/lib.rs index 54f0f1e..802f05e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,8 @@ +pub mod colors; pub mod config; pub mod glyphs; pub mod model; pub mod origin; -pub mod palette; pub mod passphrase; pub mod script; pub mod view; diff --git a/src/main.rs b/src/main.rs index 5f12eda..0cd8b59 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,10 +7,16 @@ mod run; mod sysroot; mod systemd; -use std::{fs, io::ErrorKind, path::PathBuf, process::ExitCode, time::Duration}; +use std::{ + error::Error, + io::ErrorKind, + path::{Path, PathBuf}, + process::ExitCode, + time::Duration, +}; -use bootvine::config::{Config, Timing}; -use clap::Parser; +use bootvine::config::{Config, ConfigError, Timing, default_config_table, read_config_file}; +use clap::{Parser, Subcommand, ValueEnum}; use jiff::fmt::friendly::SpanParser; use crate::{ @@ -20,8 +26,13 @@ use crate::{ }; #[derive(Parser)] -#[command(about = "Live dependency tree of systemd jobs while the system boots")] +#[command( + about = "Live dependency tree of systemd jobs while the system boots", + args_conflicts_with_subcommands = true +)] struct Cli { + #[command(subcommand)] + command: Option, #[arg(long, help = "Watch the user service manager instead of PID 1")] user: bool, #[arg( @@ -38,27 +49,82 @@ struct Cli { long, value_parser = |raw: &str| SpanParser::new().parse_unsigned_duration(raw), help = "How long the final frame stays on screen, e.g. 1s or 500ms; overrides \ - timing.keep_final_frame_for" + timing.keep-final-frame-for" )] hold: Option, #[arg( long, default_value = "/etc/bootvine.toml", - help = "TOML file with [palette] and [timing] tables" + help = "TOML file with [colors] and [timing] tables; see `bootvine defaults`" )] config: PathBuf, } +#[derive(Subcommand)] +enum Command { + #[command(about = "Print every setting with its default value")] + Defaults { + #[arg(long, value_enum, default_value_t = DefaultsFormat::Toml)] + format: DefaultsFormat, + }, + #[command(about = "Exit with an error if a config file is unreadable or invalid")] + Check { path: PathBuf }, +} + +#[derive(Clone, Copy, ValueEnum)] +enum DefaultsFormat { + Toml, + Nix, +} + fn main() -> ExitCode { let cli = Cli::parse(); - let config = match fs::read_to_string(&cli.config) { - Ok(text) => toml::from_str(&text).unwrap_or_else(|error| { - eprintln!("bootvine: ignoring {}: {error}", cli.config.display()); - Config::default() - }), - Err(error) if error.kind() == ErrorKind::NotFound => Config::default(), + match cli.command { + Some(Command::Defaults { format }) => print_defaults(format), + Some(Command::Check { ref path }) => check_config_file(path), + None => watch_boot(cli), + } +} + +fn render_defaults(format: DefaultsFormat) -> Result> { + let defaults = default_config_table()?; + Ok(match format { + DefaultsFormat::Toml => toml::to_string_pretty(&defaults)?, + DefaultsFormat::Nix => ser_nix::to_string(&defaults)?, + }) +} + +fn print_defaults(format: DefaultsFormat) -> ExitCode { + match render_defaults(format) { + Ok(text) => { + println!("{}", text.trim_end()); + ExitCode::SUCCESS + } Err(error) => { - eprintln!("bootvine: cannot read {}: {error}", cli.config.display()); + eprintln!("bootvine: {error}"); + ExitCode::FAILURE + } + } +} + +fn check_config_file(path: &Path) -> ExitCode { + match read_config_file(path) { + Ok(_) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("bootvine: {}: {error}", path.display()); + ExitCode::FAILURE + } + } +} + +fn watch_boot(cli: Cli) -> ExitCode { + let config = match read_config_file(&cli.config) { + Ok(config) => config, + Err(ConfigError::Unreadable(error)) if error.kind() == ErrorKind::NotFound => { + Config::default() + } + Err(error) => { + eprintln!("bootvine: ignoring {}: {error}", cli.config.display()); Config::default() } }; @@ -72,7 +138,7 @@ fn main() -> ExitCode { keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for), ..config.timing }, - palette: config.palette, + colors: config.colors, }; match run(&settings) { Ok(()) => ExitCode::SUCCESS, diff --git a/src/palette.rs b/src/palette.rs deleted file mode 100644 index ee17ee1..0000000 --- a/src/palette.rs +++ /dev/null @@ -1,28 +0,0 @@ -use ratatui::style::Color; -use serde::Deserialize; - -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] -#[serde(default, deny_unknown_fields)] -pub struct Palette { - pub text: Color, - pub muted: Color, - pub waiting: Color, - pub running: Color, - pub done: Color, - pub failed: Color, - pub target: Color, -} - -impl Default for Palette { - fn default() -> Self { - Self { - text: Color::White, - muted: Color::DarkGray, - waiting: Color::Gray, - running: Color::Yellow, - done: Color::Green, - failed: Color::LightRed, - target: Color::Cyan, - } - } -} diff --git a/src/run.rs b/src/run.rs index 580371a..2fe0827 100644 --- a/src/run.rs +++ b/src/run.rs @@ -11,10 +11,10 @@ use std::{ }; use bootvine::{ + colors::Colors, config::Timing, model::{BootState, Phase}, origin::BootOrigin, - palette::Palette, view::BootView, }; use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers}; @@ -50,7 +50,7 @@ pub struct Settings { pub shutdown: bool, pub target: RootRequest, pub timing: Timing, - pub palette: Palette, + pub colors: Colors, } pub fn run(settings: &Settings) -> Result<(), Error> { @@ -176,7 +176,7 @@ fn watch( canvas.render_widget( BootView { state, - palette: &settings.palette, + colors: &settings.colors, timing: &settings.timing, glyphs: &console.glyphs, now: monotonic_now(), diff --git a/src/script.rs b/src/script.rs index ad95789..3535785 100644 --- a/src/script.rs +++ b/src/script.rs @@ -10,11 +10,11 @@ use ratatui::{ }; use crate::{ + colors::Colors, config::Timing, glyphs::Glyphs, model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts}, origin::BootOrigin, - palette::Palette, passphrase, view::{BootView, PasswordPrompt}, }; @@ -329,7 +329,7 @@ pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<( canvas.render_widget( BootView { state: &state, - palette: &Palette::default(), + colors: &Colors::default(), timing: &Timing::default(), glyphs: &Glyphs::default(), now: now(), diff --git a/src/view.rs b/src/view.rs index d345590..4975ddb 100644 --- a/src/view.rs +++ b/src/view.rs @@ -9,6 +9,7 @@ use jiff::fmt::friendly::{Designator, FractionalUnit, Spacing, SpanPrinter}; use ratatui::{ buffer::Buffer, layout::{Constraint, Layout, Rect}, + style::Color, text::Line, widgets::{Block, Borders, Widget}, }; @@ -23,11 +24,11 @@ use self::{ tree::UnitTree, }; use crate::{ + colors::Colors, config::Timing, glyphs::Glyphs, model::{BootState, RowStatus, TreeRow, UnitKind, fit_to_height, fold_chains}, origin::BootOrigin, - palette::Palette, }; const DURATION_WIDTH: u16 = 8; @@ -48,7 +49,7 @@ const ELAPSED: SpanPrinter = SpanPrinter::new() pub struct BootView<'a> { pub state: &'a BootState, - pub palette: &'a Palette, + pub colors: &'a Colors, pub timing: &'a Timing, pub glyphs: &'a Glyphs, pub now: Duration, @@ -92,7 +93,7 @@ impl BootView<'_> { }) .collect(), running, - palette: self.palette, + colors: &self.colors.timeline, glyphs: self.glyphs, } } @@ -108,18 +109,18 @@ impl Widget for BootView<'_> { origin: self.origin, total: (!self.state.finished_stages.is_empty()) .then(|| self.now.saturating_sub(self.state.origin)), - palette: self.palette, + colors: &self.colors.header, }; let stages = Stages { state: self.state, now: self.now, - palette: self.palette, + colors: &self.colors.stages, glyphs: self.glyphs, }; let timeline = self.timeline(&all_rows); let footer = Footer { tally: self.state.tally(), - palette: self.palette, + colors: &self.colors.footer, glyphs: self.glyphs, }; let fits_timeline = area.width >= timeline::LABEL_WIDTH + 1 + MIN_BAR_WIDTH @@ -144,7 +145,7 @@ impl Widget for BootView<'_> { now: self.now, hide_runs_shorter_than: self.timing.hide_runs_shorter_than, frame: self.frame, - palette: self.palette, + colors: &self.colors.tree, glyphs: self.glyphs, }; let tree_height = tree.height().min(heights.tree); @@ -176,7 +177,7 @@ impl Widget for BootView<'_> { if let Some(asking) = &self.password_prompt { PasswordPopup { asking, - palette: self.palette, + colors: &self.colors.password, glyphs: self.glyphs, } .render(area, buf); @@ -204,10 +205,10 @@ impl Heights { } } -fn rule(palette: &Palette, left: Line<'static>) -> Block<'static> { +fn rule(color: Color, left: Line<'static>) -> Block<'static> { Block::new() .borders(Borders::TOP) - .border_style(palette.muted) + .border_style(color) .title(left) } @@ -265,7 +266,7 @@ mod tests { frame.render_widget( BootView { state, - palette: &Palette::default(), + colors: &Colors::default(), timing: &Timing::default(), glyphs: &Glyphs::default(), now, @@ -513,13 +514,17 @@ mod tests { lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"), "{screen}" ); - assert_eq!(buffer[(0, 0)].fg, Palette::default().muted, "{screen}"); + assert_eq!( + buffer[(0, 0)].fg, + Colors::default().password.backdrop, + "{screen}" + ); let corner = buffer .content .iter() .find(|cell| cell.symbol() == "┌") .unwrap_or_else(|| panic!("{screen}")); - assert_eq!(corner.fg, Palette::default().running, "{screen}"); + assert_eq!(corner.fg, Colors::default().password.frame, "{screen}"); } #[test] diff --git a/src/view/chrome.rs b/src/view/chrome.rs index 9661090..e410132 100644 --- a/src/view/chrome.rs +++ b/src/view/chrome.rs @@ -9,7 +9,12 @@ use ratatui::{ }; use super::{DURATION_WIDTH, ELAPSED}; -use crate::{glyphs::Glyphs, model::Tally, origin::BootOrigin, palette::Palette}; +use crate::{ + colors::{FooterColors, HeaderColors, PasswordColors}, + glyphs::Glyphs, + model::Tally, + origin::BootOrigin, +}; pub const FOOTER_HEIGHT: u16 = 2; const SEPARATOR: &str = " · "; @@ -17,7 +22,7 @@ const SEPARATOR: &str = " · "; pub struct Header<'a> { pub origin: &'a BootOrigin, pub total: Option, - pub palette: &'a Palette, + pub colors: &'a HeaderColors, } impl Header<'_> { @@ -28,8 +33,8 @@ impl Header<'_> { .into_iter() .enumerate() .flat_map(|(index, part)| { - let separator = (index > 0).then(|| SEPARATOR.fg(self.palette.muted)); - let part = Span::from(part).fg(self.palette.text); + let separator = (index > 0).then(|| SEPARATOR.fg(self.colors.separators)); + let part = Span::from(part).fg(self.colors.origin); let part = if index == 0 { part.bold() } else { part }; separator.into_iter().chain(once(part)) }) @@ -49,7 +54,7 @@ impl Widget for Header<'_> { ); if let Some(total) = self.total { Line::from(ELAPSED.unsigned_duration_to_string(&total)) - .fg(self.palette.text) + .fg(self.colors.total_time) .bold() .right_aligned() .render(area, buf); @@ -59,7 +64,7 @@ impl Widget for Header<'_> { pub struct Footer<'a> { pub tally: Tally, - pub palette: &'a Palette, + pub colors: &'a FooterColors, pub glyphs: &'a Glyphs, } @@ -67,19 +72,19 @@ impl Widget for Footer<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let failed = format!(" {} {} failed", self.glyphs.failed, self.tally.failed); let failed = if self.tally.failed > 0 { - failed.fg(self.palette.failed).bold() + failed.fg(self.colors.failed).bold() } else { - failed.fg(self.palette.waiting) + failed.fg(self.colors.no_failures) }; let block = Block::new() .borders(Borders::TOP) - .border_style(self.palette.muted); + .border_style(self.colors.rule); let inner = block.inner(area); block.render(area, buf); Line::from(vec![ - format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.palette.done), - format!(" {} running", self.tally.running).fg(self.palette.running), - format!(" {} waiting", self.tally.waiting).fg(self.palette.waiting), + format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.colors.done), + format!(" {} running", self.tally.running).fg(self.colors.running), + format!(" {} waiting", self.tally.waiting).fg(self.colors.waiting), failed, ]) .render(inner, buf); @@ -94,7 +99,7 @@ pub struct PasswordPrompt<'a> { pub struct PasswordPopup<'a> { pub asking: &'a PasswordPrompt<'a>, - pub palette: &'a Palette, + pub colors: &'a PasswordColors, pub glyphs: &'a Glyphs, } @@ -103,29 +108,29 @@ impl PasswordPopup<'_> { fn input(&self) -> Line<'static> { if self.asking.sent { - Line::from(format!("Checking{}", self.glyphs.ellipsis).fg(self.palette.waiting)) + Line::from(format!("Checking{}", self.glyphs.ellipsis).fg(self.colors.checking)) } else { Line::from(vec![ - "> ".fg(self.palette.running), - format!("{}_", self.asking.input).fg(self.palette.text), + "> ".fg(self.colors.frame), + format!("{}_", self.asking.input).fg(self.colors.message), ]) } } fn paragraph(&self) -> Paragraph<'_> { Paragraph::new(vec![ - Line::from(self.asking.message.fg(self.palette.text).bold()), + Line::from(self.asking.message.fg(self.colors.message).bold()), Line::default(), self.input(), ]) .wrap(Wrap { trim: false }) .block( Block::bordered() - .border_style(self.palette.running) + .border_style(self.colors.frame) .padding(Padding::horizontal(2)) - .title(" Password ".fg(self.palette.running).bold()) + .title(" Password ".fg(self.colors.frame).bold()) .title_bottom( - Line::from(" Enter unlock · Ctrl+U clear ".fg(self.palette.muted)) + Line::from(" Enter unlock · Ctrl+U clear ".fg(self.colors.hint)) .right_aligned(), ), ) @@ -134,7 +139,7 @@ impl PasswordPopup<'_> { impl Widget for PasswordPopup<'_> { fn render(self, area: Rect, buf: &mut Buffer) { - buf.set_style(area, Style::new().fg(self.palette.muted)); + buf.set_style(area, Style::new().fg(self.colors.backdrop)); let paragraph = self.paragraph(); let width = u16::try_from(paragraph.line_width()) .unwrap_or(u16::MAX) diff --git a/src/view/stages.rs b/src/view/stages.rs index 02a7732..445418d 100644 --- a/src/view/stages.rs +++ b/src/view/stages.rs @@ -9,7 +9,7 @@ use ratatui::{ }; use super::{BRANCH, ELAPSED, LAST_BRANCH, unit_count}; -use crate::{glyphs::Glyphs, model::BootState, palette::Palette}; +use crate::{colors::StageColors, glyphs::Glyphs, model::BootState}; const SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown"; const PHASE_WIDTH: usize = 9; @@ -17,7 +17,7 @@ const PHASE_WIDTH: usize = 9; pub struct Stages<'a> { pub state: &'a BootState, pub now: Duration, - pub palette: &'a Palette, + pub colors: &'a StageColors, pub glyphs: &'a Glyphs, } @@ -55,8 +55,8 @@ impl Stages<'_> { fn finished_phases(&self) -> impl Iterator> + '_ { self.state.finished_stages.iter().map(|stage| { Line::from(vec![ - BRANCH.fg(self.palette.muted), - format!("{:PHASE_WIDTH$}", stage.label).fg(self.palette.waiting), + BRANCH.fg(self.colors.branches), + format!("{:PHASE_WIDTH$}", stage.label).fg(self.colors.finished_label), format!( "{} done in {}", self.glyphs.bead, @@ -64,11 +64,11 @@ impl Stages<'_> { &stage.reached_at.saturating_sub(stage.started_at) ) ) - .fg(self.palette.done), - format!(" · {}", unit_count(stage.finished_units)).fg(self.palette.waiting), + .fg(self.colors.finished_time), + format!(" · {}", unit_count(stage.finished_units)).fg(self.colors.unit_count), if stage.failed_units > 0 { format!(" · {} {} failed", self.glyphs.failed, stage.failed_units) - .fg(self.palette.failed) + .fg(self.colors.failed_count) .bold() } else { Span::default() @@ -79,16 +79,16 @@ impl Stages<'_> { fn concluded_phase(&self, conclusion: &Conclusion) -> Line<'static> { Line::from(vec![ - LAST_BRANCH.fg(self.palette.muted), + LAST_BRANCH.fg(self.colors.branches), format!( "{} {} finished in {}", self.glyphs.bead, conclusion.finished, ELAPSED.unsigned_duration_to_string(&conclusion.took) ) - .fg(self.palette.done) + .fg(self.colors.finished_time) .bold(), - format!(" · handing over to {}", conclusion.handed_to).fg(self.palette.text), + format!(" · handing over to {}", conclusion.handed_to).fg(self.colors.current), ]) } @@ -103,11 +103,11 @@ impl Stages<'_> { .map_or(self.state.origin, |stage| stage.reached_at); let elapsed = ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(started_at)); Line::from(vec![ - LAST_BRANCH.fg(self.palette.muted), + LAST_BRANCH.fg(self.colors.branches), format!("{:PHASE_WIDTH$}", self.state.phase.label()) - .fg(self.palette.text) + .fg(self.colors.current) .bold(), - elapsed.fg(self.palette.text), + elapsed.fg(self.colors.current), ]) } } diff --git a/src/view/timeline.rs b/src/view/timeline.rs index d4e4f52..5aa06ce 100644 --- a/src/view/timeline.rs +++ b/src/view/timeline.rs @@ -15,9 +15,9 @@ use ratatui::{ use super::{fit_width, rule, unit_count}; use crate::{ + colors::TimelineColors, glyphs::Glyphs, model::{FinishedRun, MilestoneRow}, - palette::Palette, }; pub const LABEL_WIDTH: u16 = 28; @@ -51,7 +51,7 @@ pub struct Timeline<'a> { pub milestones: Vec, pub finished: Vec<&'a FinishedRun>, pub running: Vec>, - pub palette: &'a Palette, + pub colors: &'a TimelineColors, pub glyphs: &'a Glyphs, } @@ -91,13 +91,13 @@ impl Timeline<'_> { row.label, unit_count(row.finished_units) ), - self.palette.done, + self.colors.milestone, ), segments: vec![Segment { from: row.started_at, to: row.reached_at, symbol: self.glyphs.bead, - color: self.palette.done, + color: self.colors.milestone, }], still_going: false, } @@ -110,14 +110,14 @@ impl Timeline<'_> { self.glyphs.done }; let outcome = if run.failed { - self.palette.failed + self.colors.failed } else { - self.palette.done + self.colors.finished }; TimelineEntry { label: Line::from(vec![ Span::styled(format!("{mark} "), outcome), - self.fitted(&run.label).fg(self.palette.waiting), + self.fitted(&run.label).fg(self.colors.finished_label), ]), segments: vec![Segment { from: run.started_at, @@ -142,18 +142,18 @@ impl Timeline<'_> { from: run.queued_at, to: run.since, symbol: self.glyphs.waiting_bead, - color: self.palette.waiting, + color: self.colors.queued_bar, }); let ran = Segment { from: run.since, to: self.now, symbol: self.glyphs.bead, - color: self.palette.running, + color: self.colors.running, }; TimelineEntry { label: Line::from(vec![ - format!("{} ", self.glyphs.running_mark).fg(self.palette.running), - self.fitted(run.label).fg(self.palette.text), + format!("{} ", self.glyphs.running_mark).fg(self.colors.running), + self.fitted(run.label).fg(self.colors.running_label), ]), segments: waited.into_iter().chain(once(ran)).collect(), still_going: true, @@ -164,8 +164,8 @@ impl Timeline<'_> { impl Widget for Timeline<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let block = rule( - self.palette, - Line::from(" Timeline ".fg(self.palette.waiting)), + self.colors.rule, + Line::from(" Timeline ".fg(self.colors.title)), ); let inner = block.inner(area); block.render(area, buf); @@ -192,7 +192,7 @@ impl Widget for Timeline<'_> { .render(label_area, buf); let axis = TimeAxis::new(self.origin, self.now, bar_area.width); let label_row = f64::from(bar_area.height.saturating_sub(1).max(1)); - let muted = self.palette.muted; + let axis_color = self.colors.axis; Canvas::default() .x_bounds(axis.bounds()) .y_bounds([0.0, label_row]) @@ -211,20 +211,20 @@ impl Widget for Timeline<'_> { }); if entry.still_going { ctx.marker(Marker::Custom(self.glyphs.still_going)); - ctx.draw(&Points::new(&[(self.now.as_secs_f64(), y)], muted)); + ctx.draw(&Points::new(&[(self.now.as_secs_f64(), y)], axis_color)); } }); ctx.marker(Marker::Custom(self.glyphs.root_switch_mark)); self.root_switches.iter().for_each(|at| { let x = at.as_secs_f64(); - ctx.draw(&Stroke::new(x, 0.0, x, label_row - 1.0, muted)); + ctx.draw(&Stroke::new(x, 0.0, x, label_row - 1.0, axis_color)); }); axis.tick_offsets().for_each(|offset| { let label = axis.label(offset); let x = (axis.origin + offset) .as_secs_f64() .min(axis.bounds()[1] - axis.columns_to_seconds(label.len() - 1)); - ctx.print(x, label_row, label.fg(muted)); + ctx.print(x, label_row, label.fg(axis_color)); }); }) .render(bar_area, buf); diff --git a/src/view/tree.rs b/src/view/tree.rs index 23a6247..164f76c 100644 --- a/src/view/tree.rs +++ b/src/view/tree.rs @@ -11,9 +11,9 @@ use unicode_width::UnicodeWidthStr; use super::{BRANCH, DURATION_WIDTH, ELAPSED, ENDED_TRUNK, LAST_BRANCH, PASSING_TRUNK, fit_width}; use crate::{ + colors::TreeColors, glyphs::Glyphs, model::{RowStatus, TreeRow, UnitKind}, - palette::Palette, }; const SPINNER: [char; 4] = ['|', '/', '-', '\\']; @@ -29,7 +29,7 @@ pub struct UnitTree<'a> { pub now: Duration, pub hide_runs_shorter_than: Duration, pub frame: u64, - pub palette: &'a Palette, + pub colors: &'a TreeColors, pub glyphs: &'a Glyphs, } @@ -74,7 +74,7 @@ impl UnitTree<'_> { if !self.phase_fits_its_column(columns) { return Row::default().height(HEADER_ROWS); } - let name = |text: &'static str| Line::from(text).fg(self.palette.muted); + let name = |text: &'static str| Line::from(text).fg(self.colors.columns); Row::new(columns.shown([ self.phase.clone(), name("Kind"), @@ -102,36 +102,44 @@ impl UnitTree<'_> { } fn label_style(&self, row: &TreeRow, stage: Stage) -> Style { - match (stage, row.kind, row.status) { - (Stage::Current, ..) => Style::from(self.palette.running).bold(), - (Stage::Reached, ..) => self.palette.done.into(), - (_, _, RowStatus::Failed) => Style::from(self.palette.failed).bold(), - (_, UnitKind::Target, _) => self.palette.target.into(), - (_, _, RowStatus::Running { .. }) => self.palette.text.into(), - (_, _, RowStatus::Waiting) => self.palette.waiting.into(), - (_, _, RowStatus::Done) => self.palette.muted.into(), + match stage { + Stage::Current => Style::from(self.colors.current_stage).bold(), + Stage::Reached => self.colors.reached_stage.into(), + Stage::Upcoming | Stage::Inside => self.unit_label_style(row), + } + } + + fn unit_label_style(&self, row: &TreeRow) -> Style { + match row.status { + RowStatus::Failed => Style::from(self.colors.failed_unit).bold(), + _ if row.kind == UnitKind::Target => self.colors.target.into(), + RowStatus::Running { .. } => self.colors.running_unit.into(), + RowStatus::Waiting => self.colors.waiting_unit.into(), + RowStatus::Done => self.colors.finished_unit.into(), } } fn status_marker(&self, row: &TreeRow, stage: Stage) -> Span<'static> { - match (stage, row.kind, row.status) { - (Stage::Current, ..) => { - format!("{} ", self.glyphs.stage_current).fg(self.palette.running) + match stage { + Stage::Current => { + format!("{} ", self.glyphs.stage_current).fg(self.colors.current_stage) } - (Stage::Upcoming, ..) => { - format!("{} ", self.glyphs.stage_upcoming).fg(self.palette.target) - } - (Stage::Reached, ..) => format!("{} ", self.glyphs.done).fg(self.palette.done), - (_, _, RowStatus::Failed) => { - format!("[{}] ", self.glyphs.failed).fg(self.palette.failed) - } - (_, UnitKind::Target, _) => Span::default(), - (_, _, RowStatus::Running { .. }) => { + Stage::Upcoming => format!("{} ", self.glyphs.stage_upcoming).fg(self.colors.target), + Stage::Reached => format!("{} ", self.glyphs.done).fg(self.colors.reached_stage), + Stage::Inside => self.unit_marker(row), + } + } + + fn unit_marker(&self, row: &TreeRow) -> Span<'static> { + match row.status { + RowStatus::Failed => format!("[{}] ", self.glyphs.failed).fg(self.colors.failed_unit), + _ if row.kind == UnitKind::Target => Span::default(), + RowStatus::Running { .. } => { let spinner = SPINNER[usize::try_from(self.frame % 4).unwrap_or_default()]; - format!("[{spinner}] ").fg(self.palette.running) + format!("[{spinner}] ").fg(self.colors.running_marker) } - (_, _, RowStatus::Waiting) => "[ ] ".fg(self.palette.waiting), - (_, _, RowStatus::Done) => format!("[{}] ", self.glyphs.done).fg(self.palette.done), + RowStatus::Waiting => "[ ] ".fg(self.colors.waiting_unit), + RowStatus::Done => format!("[{}] ", self.glyphs.done).fg(self.colors.finished_marker), } } @@ -203,12 +211,12 @@ impl UnitTree<'_> { let style = self.label_style(row, stage); Row::new(columns.shown([ Line::from(vec![ - prefix.fg(self.palette.muted), + prefix.fg(self.colors.branches), marker, Span::styled(self.chained_label(row, room), style), ]), - Line::from(annotation(row.kind.tag(), columns.tag)).fg(self.palette.muted), - Line::from(annotation(&row.description, columns.description)).fg(self.palette.muted), + Line::from(annotation(row.kind.tag(), columns.tag)).fg(self.colors.columns), + Line::from(annotation(&row.description, columns.description)).fg(self.colors.columns), Line::from(timer).style(style).right_aligned(), ])) } @@ -241,7 +249,7 @@ impl Widget for UnitTree<'_> { let overflow = (hidden > 0).then(|| { Row::new([ format!("{ENDED_TRUNK}{} {hidden} more", self.glyphs.ellipsis) - .fg(self.palette.waiting), + .fg(self.colors.overflow), ]) }); let columns = self.columns(area.width);