docs: improve documentation of settings using a subcommand

This commit is contained in:
Willem Vanhulle committed 2026-10-21 11:27:58 +02:00
1 parent 4e943f578a
commit 65ccaebc1c
17 files changed
+514 -223

No files matched your search

Generated
+11
View File
@@ -149,9 +149,11 @@ dependencies = [
"clap", "clap",
"crossterm 0.29.0", "crossterm 0.29.0",
"dbus", "dbus",
"heck",
"jiff", "jiff",
"ratatui", "ratatui",
"rustix 1.1.5", "rustix 1.1.5",
"ser_nix",
"serde", "serde",
"signal-hook 0.4.5", "signal-hook 0.4.5",
"toml", "toml",
@@ -1459,6 +1461,15 @@ version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" 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]] [[package]]
name = "serde" name = "serde"
version = "1.0.229" version = "1.0.229"
+3 -1
View File
@@ -15,12 +15,14 @@ missing_errors_doc = "allow"
clap = { version = "4.6.7", features = ["derive"] } clap = { version = "4.6.7", features = ["derive"] }
crossterm = "0.29.0" crossterm = "0.29.0"
dbus = "0.9.12" dbus = "0.9.12"
heck = "0.5.0"
jiff = { version = "0.2.38", default-features = false, features = ["serde", "std"] } jiff = { version = "0.2.38", default-features = false, features = ["serde", "std"] }
ratatui = { version = "0.30.2", features = ["serde", "unstable-rendered-line-info"] } ratatui = { version = "0.30.2", features = ["serde", "unstable-rendered-line-info"] }
rustix = { version = "1.1.5", features = ["event", "fs", "process", "stdio", "system", "termios", "time"] } 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"] } serde = { version = "1.0.229", features = ["derive"] }
signal-hook = "0.4.5" signal-hook = "0.4.5"
toml = "1.1.8" toml = { version = "1.1.8", features = ["preserve_order"] }
unicode-truncate = "2.0.1" unicode-truncate = "2.0.1"
unicode-width = "0.2.2" unicode-width = "0.2.2"
zeroize = "1.9.1" zeroize = "1.9.1"
+26 -21
View File
@@ -140,36 +140,41 @@ dracut module as above, or on mkinitcpio install
## Configure ## Configure
`/etc/bootvine.toml`, or `services.bootvine.palette` and `/etc/bootvine.toml`. Every key is optional; `bootvine defaults` prints them
`services.bootvine.timing` on NixOS. Every key is optional; these are the all with their defaults, and `bootvine defaults --format nix` prints the same as
defaults: a Nix attribute set. A file that changes two of them:
```toml ```toml
[palette] [colors.tree]
text = "white" running-marker = "light-yellow"
muted = "dark-gray"
waiting = "gray"
running = "yellow"
done = "green"
failed = "light-red"
target = "cyan"
[timing] [timing]
keep_finished_units_for = "2s" keep-final-frame-for = "500ms"
hide_runs_shorter_than = "1s"
keep_final_frame_for = "1s"
``` ```
Palette values are the 16 console colour names. To change how those look, set Each `[colors.*]` table covers one part of the screen: `header`, the finished
the console palette: `console.colors` on NixOS, or the `vt.default_red`, `_grn` `stages`, the unit `tree`, the `timeline`, the `footer` tallies and the
and `_blu` kernel parameters elsewhere. `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, `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 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 timeline bar. `keep-final-frame-for` is how long the last frame stays before the
console is handed back; `--hold` overrides it. 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 ## License
+7 -1
View File
@@ -44,7 +44,13 @@ in
services.bootvine = { services.bootvine = {
enable = true; 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 = { console = {
+22 -45
View File
@@ -7,35 +7,14 @@
}: }:
let let
cfg = config.services.bootvine; cfg = config.services.bootvine;
chosen = lib.filterAttrs (_: value: value != null); settingsFormat = pkgs.formats.toml { };
settings = lib.filterAttrs (_: table: table != { }) { uncheckedConfigFile = settingsFormat.generate "bootvine-unchecked.toml" cfg.settings;
palette = chosen cfg.palette; canRunPackage = pkgs.stdenv.buildPlatform.canExecute pkgs.stdenv.hostPlatform;
timing = chosen cfg.timing; configFile = pkgs.runCommand "bootvine.toml" { } ''
}; ${lib.optionalString canRunPackage "${lib.getExe cfg.package} check ${uncheckedConfigFile}"}
configFile = (pkgs.formats.toml { }).generate "bootvine.toml" settings; cp ${uncheckedConfigFile} $out
durationOption = '';
purpose: default: hasSettings = cfg.settings != { };
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`.
'';
};
in in
{ {
options.services.bootvine = { options.services.bootvine = {
@@ -54,27 +33,25 @@ in
description = "The bootvine package, which ships the systemd unit."; description = "The bootvine package, which ships the systemd unit.";
}; };
palette = { settings = lib.mkOption {
text = colorOption "running units and headings" "white"; inherit (settingsFormat) type;
muted = colorOption "rules, tree lines and the time axis" "dark-gray"; default = { };
waiting = colorOption "queued units and finished-unit labels" "gray"; example = {
running = colorOption "running units and their bars" "yellow"; colors.tree.running-marker = "light-yellow";
done = colorOption "finished units, stages and milestones" "green"; timing.keep-final-frame-for = "500ms";
failed = colorOption "failed units" "light-red"; };
target = colorOption "targets in the tree" "cyan"; description = ''
}; Written to {file}`/etc/bootvine.toml`, in the real root and the
initrd. `bootvine defaults --format nix` prints every key with its
timing = { default; the build fails if `bootvine check` rejects the result.
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";
}; };
}; };
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
environment = { environment = {
systemPackages = [ cfg.package ]; systemPackages = [ cfg.package ];
etc."bootvine.toml" = lib.mkIf (settings != { }) { source = configFile; }; etc."bootvine.toml" = lib.mkIf hasSettings { source = configFile; };
}; };
systemd = { systemd = {
@@ -87,7 +64,7 @@ in
packages = [ cfg.package ]; packages = [ cfg.package ];
storePaths = [ (lib.getExe cfg.package) ]; storePaths = [ (lib.getExe cfg.package) ];
services.bootvine.wantedBy = [ "sysinit.target" ]; services.bootvine.wantedBy = [ "sysinit.target" ];
contents."/etc/bootvine.toml" = lib.mkIf (settings != { }) { source = configFile; }; contents."/etc/bootvine.toml" = lib.mkIf hasSettings { source = configFile; };
}; };
}; };
} }
+169
View File
@@ -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,
}
}
}
+78 -13
View File
@@ -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)] #[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)] #[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
pub struct Config { pub struct Config {
pub palette: Palette, pub colors: Colors,
pub timing: Timing, pub timing: Timing,
} }
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] #[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)] #[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
pub struct Timing { pub struct Timing {
#[serde(with = "jiff::fmt::serde::unsigned_duration::friendly::compact::required")] #[serde(with = "friendly_duration")]
pub keep_finished_units_for: 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, 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, 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<Config, ConfigError> {
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, SerializeError> {
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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
fn printed_defaults() -> String {
toml::to_string_pretty(&default_config_table().expect("serializable defaults"))
.expect("printable defaults")
}
#[test] #[test]
fn timing_reads_friendly_durations_and_keeps_unset_defaults() { 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"); .expect("valid config");
assert_eq!( assert_eq!(
config.timing.keep_finished_units_for, config.timing.keep_finished_units_for,
@@ -52,6 +102,21 @@ mod tests {
#[test] #[test]
fn nonsense_durations_are_rejected() { fn nonsense_durations_are_rejected() {
assert!(toml::from_str::<Config>("[timing]\nkeep_final_frame_for = \"soon\"\n").is_err()); assert!(toml::from_str::<Config>("[timing]\nkeep-final-frame-for = \"soon\"\n").is_err());
}
#[test]
fn unknown_color_keys_are_rejected() {
assert!(toml::from_str::<Config>("[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::<Config>(&printed).expect("valid defaults"),
Config::default()
);
} }
} }
+1 -1
View File
@@ -1,8 +1,8 @@
pub mod colors;
pub mod config; pub mod config;
pub mod glyphs; pub mod glyphs;
pub mod model; pub mod model;
pub mod origin; pub mod origin;
pub mod palette;
pub mod passphrase; pub mod passphrase;
pub mod script; pub mod script;
pub mod view; pub mod view;
+80 -14
View File
@@ -7,10 +7,16 @@ mod run;
mod sysroot; mod sysroot;
mod systemd; 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 bootvine::config::{Config, ConfigError, Timing, default_config_table, read_config_file};
use clap::Parser; use clap::{Parser, Subcommand, ValueEnum};
use jiff::fmt::friendly::SpanParser; use jiff::fmt::friendly::SpanParser;
use crate::{ use crate::{
@@ -20,8 +26,13 @@ use crate::{
}; };
#[derive(Parser)] #[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 { struct Cli {
#[command(subcommand)]
command: Option<Command>,
#[arg(long, help = "Watch the user service manager instead of PID 1")] #[arg(long, help = "Watch the user service manager instead of PID 1")]
user: bool, user: bool,
#[arg( #[arg(
@@ -38,27 +49,82 @@ struct Cli {
long, long,
value_parser = |raw: &str| SpanParser::new().parse_unsigned_duration(raw), 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 \ 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<Duration>, hold: Option<Duration>,
#[arg( #[arg(
long, long,
default_value = "/etc/bootvine.toml", 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, 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 { fn main() -> ExitCode {
let cli = Cli::parse(); let cli = Cli::parse();
let config = match fs::read_to_string(&cli.config) { match cli.command {
Ok(text) => toml::from_str(&text).unwrap_or_else(|error| { Some(Command::Defaults { format }) => print_defaults(format),
eprintln!("bootvine: ignoring {}: {error}", cli.config.display()); Some(Command::Check { ref path }) => check_config_file(path),
Config::default() None => watch_boot(cli),
}), }
Err(error) if error.kind() == ErrorKind::NotFound => Config::default(), }
fn render_defaults(format: DefaultsFormat) -> Result<String, Box<dyn Error>> {
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) => { 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() Config::default()
} }
}; };
@@ -72,7 +138,7 @@ fn main() -> ExitCode {
keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for), keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for),
..config.timing ..config.timing
}, },
palette: config.palette, colors: config.colors,
}; };
match run(&settings) { match run(&settings) {
Ok(()) => ExitCode::SUCCESS, Ok(()) => ExitCode::SUCCESS,
-28
View File
@@ -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,
}
}
}
+3 -3
View File
@@ -11,10 +11,10 @@ use std::{
}; };
use bootvine::{ use bootvine::{
colors::Colors,
config::Timing, config::Timing,
model::{BootState, Phase}, model::{BootState, Phase},
origin::BootOrigin, origin::BootOrigin,
palette::Palette,
view::BootView, view::BootView,
}; };
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
@@ -50,7 +50,7 @@ pub struct Settings {
pub shutdown: bool, pub shutdown: bool,
pub target: RootRequest, pub target: RootRequest,
pub timing: Timing, pub timing: Timing,
pub palette: Palette, pub colors: Colors,
} }
pub fn run(settings: &Settings) -> Result<(), Error> { pub fn run(settings: &Settings) -> Result<(), Error> {
@@ -176,7 +176,7 @@ fn watch(
canvas.render_widget( canvas.render_widget(
BootView { BootView {
state, state,
palette: &settings.palette, colors: &settings.colors,
timing: &settings.timing, timing: &settings.timing,
glyphs: &console.glyphs, glyphs: &console.glyphs,
now: monotonic_now(), now: monotonic_now(),
+2 -2
View File
@@ -10,11 +10,11 @@ use ratatui::{
}; };
use crate::{ use crate::{
colors::Colors,
config::Timing, config::Timing,
glyphs::Glyphs, glyphs::Glyphs,
model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts}, model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts},
origin::BootOrigin, origin::BootOrigin,
palette::Palette,
passphrase, passphrase,
view::{BootView, PasswordPrompt}, view::{BootView, PasswordPrompt},
}; };
@@ -329,7 +329,7 @@ pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<(
canvas.render_widget( canvas.render_widget(
BootView { BootView {
state: &state, state: &state,
palette: &Palette::default(), colors: &Colors::default(),
timing: &Timing::default(), timing: &Timing::default(),
glyphs: &Glyphs::default(), glyphs: &Glyphs::default(),
now: now(), now: now(),
+18 -13
View File
@@ -9,6 +9,7 @@ use jiff::fmt::friendly::{Designator, FractionalUnit, Spacing, SpanPrinter};
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
style::Color,
text::Line, text::Line,
widgets::{Block, Borders, Widget}, widgets::{Block, Borders, Widget},
}; };
@@ -23,11 +24,11 @@ use self::{
tree::UnitTree, tree::UnitTree,
}; };
use crate::{ use crate::{
colors::Colors,
config::Timing, config::Timing,
glyphs::Glyphs, glyphs::Glyphs,
model::{BootState, RowStatus, TreeRow, UnitKind, fit_to_height, fold_chains}, model::{BootState, RowStatus, TreeRow, UnitKind, fit_to_height, fold_chains},
origin::BootOrigin, origin::BootOrigin,
palette::Palette,
}; };
const DURATION_WIDTH: u16 = 8; const DURATION_WIDTH: u16 = 8;
@@ -48,7 +49,7 @@ const ELAPSED: SpanPrinter = SpanPrinter::new()
pub struct BootView<'a> { pub struct BootView<'a> {
pub state: &'a BootState, pub state: &'a BootState,
pub palette: &'a Palette, pub colors: &'a Colors,
pub timing: &'a Timing, pub timing: &'a Timing,
pub glyphs: &'a Glyphs, pub glyphs: &'a Glyphs,
pub now: Duration, pub now: Duration,
@@ -92,7 +93,7 @@ impl BootView<'_> {
}) })
.collect(), .collect(),
running, running,
palette: self.palette, colors: &self.colors.timeline,
glyphs: self.glyphs, glyphs: self.glyphs,
} }
} }
@@ -108,18 +109,18 @@ impl Widget for BootView<'_> {
origin: self.origin, origin: self.origin,
total: (!self.state.finished_stages.is_empty()) total: (!self.state.finished_stages.is_empty())
.then(|| self.now.saturating_sub(self.state.origin)), .then(|| self.now.saturating_sub(self.state.origin)),
palette: self.palette, colors: &self.colors.header,
}; };
let stages = Stages { let stages = Stages {
state: self.state, state: self.state,
now: self.now, now: self.now,
palette: self.palette, colors: &self.colors.stages,
glyphs: self.glyphs, glyphs: self.glyphs,
}; };
let timeline = self.timeline(&all_rows); let timeline = self.timeline(&all_rows);
let footer = Footer { let footer = Footer {
tally: self.state.tally(), tally: self.state.tally(),
palette: self.palette, colors: &self.colors.footer,
glyphs: self.glyphs, glyphs: self.glyphs,
}; };
let fits_timeline = area.width >= timeline::LABEL_WIDTH + 1 + MIN_BAR_WIDTH let fits_timeline = area.width >= timeline::LABEL_WIDTH + 1 + MIN_BAR_WIDTH
@@ -144,7 +145,7 @@ impl Widget for BootView<'_> {
now: self.now, now: self.now,
hide_runs_shorter_than: self.timing.hide_runs_shorter_than, hide_runs_shorter_than: self.timing.hide_runs_shorter_than,
frame: self.frame, frame: self.frame,
palette: self.palette, colors: &self.colors.tree,
glyphs: self.glyphs, glyphs: self.glyphs,
}; };
let tree_height = tree.height().min(heights.tree); let tree_height = tree.height().min(heights.tree);
@@ -176,7 +177,7 @@ impl Widget for BootView<'_> {
if let Some(asking) = &self.password_prompt { if let Some(asking) = &self.password_prompt {
PasswordPopup { PasswordPopup {
asking, asking,
palette: self.palette, colors: &self.colors.password,
glyphs: self.glyphs, glyphs: self.glyphs,
} }
.render(area, buf); .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() Block::new()
.borders(Borders::TOP) .borders(Borders::TOP)
.border_style(palette.muted) .border_style(color)
.title(left) .title(left)
} }
@@ -265,7 +266,7 @@ mod tests {
frame.render_widget( frame.render_widget(
BootView { BootView {
state, state,
palette: &Palette::default(), colors: &Colors::default(),
timing: &Timing::default(), timing: &Timing::default(),
glyphs: &Glyphs::default(), glyphs: &Glyphs::default(),
now, now,
@@ -513,13 +514,17 @@ mod tests {
lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"), lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"),
"{screen}" "{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 let corner = buffer
.content .content
.iter() .iter()
.find(|cell| cell.symbol() == "┌") .find(|cell| cell.symbol() == "┌")
.unwrap_or_else(|| panic!("{screen}")); .unwrap_or_else(|| panic!("{screen}"));
assert_eq!(corner.fg, Palette::default().running, "{screen}"); assert_eq!(corner.fg, Colors::default().password.frame, "{screen}");
} }
#[test] #[test]
+26 -21
View File
@@ -9,7 +9,12 @@ use ratatui::{
}; };
use super::{DURATION_WIDTH, ELAPSED}; 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; pub const FOOTER_HEIGHT: u16 = 2;
const SEPARATOR: &str = " · "; const SEPARATOR: &str = " · ";
@@ -17,7 +22,7 @@ const SEPARATOR: &str = " · ";
pub struct Header<'a> { pub struct Header<'a> {
pub origin: &'a BootOrigin, pub origin: &'a BootOrigin,
pub total: Option<Duration>, pub total: Option<Duration>,
pub palette: &'a Palette, pub colors: &'a HeaderColors,
} }
impl Header<'_> { impl Header<'_> {
@@ -28,8 +33,8 @@ impl Header<'_> {
.into_iter() .into_iter()
.enumerate() .enumerate()
.flat_map(|(index, part)| { .flat_map(|(index, part)| {
let separator = (index > 0).then(|| SEPARATOR.fg(self.palette.muted)); let separator = (index > 0).then(|| SEPARATOR.fg(self.colors.separators));
let part = Span::from(part).fg(self.palette.text); let part = Span::from(part).fg(self.colors.origin);
let part = if index == 0 { part.bold() } else { part }; let part = if index == 0 { part.bold() } else { part };
separator.into_iter().chain(once(part)) separator.into_iter().chain(once(part))
}) })
@@ -49,7 +54,7 @@ impl Widget for Header<'_> {
); );
if let Some(total) = self.total { if let Some(total) = self.total {
Line::from(ELAPSED.unsigned_duration_to_string(&total)) Line::from(ELAPSED.unsigned_duration_to_string(&total))
.fg(self.palette.text) .fg(self.colors.total_time)
.bold() .bold()
.right_aligned() .right_aligned()
.render(area, buf); .render(area, buf);
@@ -59,7 +64,7 @@ impl Widget for Header<'_> {
pub struct Footer<'a> { pub struct Footer<'a> {
pub tally: Tally, pub tally: Tally,
pub palette: &'a Palette, pub colors: &'a FooterColors,
pub glyphs: &'a Glyphs, pub glyphs: &'a Glyphs,
} }
@@ -67,19 +72,19 @@ impl Widget for Footer<'_> {
fn render(self, area: Rect, buf: &mut Buffer) { fn render(self, area: Rect, buf: &mut Buffer) {
let failed = format!(" {} {} failed", self.glyphs.failed, self.tally.failed); let failed = format!(" {} {} failed", self.glyphs.failed, self.tally.failed);
let failed = if self.tally.failed > 0 { let failed = if self.tally.failed > 0 {
failed.fg(self.palette.failed).bold() failed.fg(self.colors.failed).bold()
} else { } else {
failed.fg(self.palette.waiting) failed.fg(self.colors.no_failures)
}; };
let block = Block::new() let block = Block::new()
.borders(Borders::TOP) .borders(Borders::TOP)
.border_style(self.palette.muted); .border_style(self.colors.rule);
let inner = block.inner(area); let inner = block.inner(area);
block.render(area, buf); block.render(area, buf);
Line::from(vec![ Line::from(vec![
format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.palette.done), format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.colors.done),
format!(" {} running", self.tally.running).fg(self.palette.running), format!(" {} running", self.tally.running).fg(self.colors.running),
format!(" {} waiting", self.tally.waiting).fg(self.palette.waiting), format!(" {} waiting", self.tally.waiting).fg(self.colors.waiting),
failed, failed,
]) ])
.render(inner, buf); .render(inner, buf);
@@ -94,7 +99,7 @@ pub struct PasswordPrompt<'a> {
pub struct PasswordPopup<'a> { pub struct PasswordPopup<'a> {
pub asking: &'a PasswordPrompt<'a>, pub asking: &'a PasswordPrompt<'a>,
pub palette: &'a Palette, pub colors: &'a PasswordColors,
pub glyphs: &'a Glyphs, pub glyphs: &'a Glyphs,
} }
@@ -103,29 +108,29 @@ impl PasswordPopup<'_> {
fn input(&self) -> Line<'static> { fn input(&self) -> Line<'static> {
if self.asking.sent { 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 { } else {
Line::from(vec![ Line::from(vec![
"> ".fg(self.palette.running), "> ".fg(self.colors.frame),
format!("{}_", self.asking.input).fg(self.palette.text), format!("{}_", self.asking.input).fg(self.colors.message),
]) ])
} }
} }
fn paragraph(&self) -> Paragraph<'_> { fn paragraph(&self) -> Paragraph<'_> {
Paragraph::new(vec![ 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(), Line::default(),
self.input(), self.input(),
]) ])
.wrap(Wrap { trim: false }) .wrap(Wrap { trim: false })
.block( .block(
Block::bordered() Block::bordered()
.border_style(self.palette.running) .border_style(self.colors.frame)
.padding(Padding::horizontal(2)) .padding(Padding::horizontal(2))
.title(" Password ".fg(self.palette.running).bold()) .title(" Password ".fg(self.colors.frame).bold())
.title_bottom( .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(), .right_aligned(),
), ),
) )
@@ -134,7 +139,7 @@ impl PasswordPopup<'_> {
impl Widget for PasswordPopup<'_> { impl Widget for PasswordPopup<'_> {
fn render(self, area: Rect, buf: &mut Buffer) { 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 paragraph = self.paragraph();
let width = u16::try_from(paragraph.line_width()) let width = u16::try_from(paragraph.line_width())
.unwrap_or(u16::MAX) .unwrap_or(u16::MAX)
+13 -13
View File
@@ -9,7 +9,7 @@ use ratatui::{
}; };
use super::{BRANCH, ELAPSED, LAST_BRANCH, unit_count}; 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 SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown";
const PHASE_WIDTH: usize = 9; const PHASE_WIDTH: usize = 9;
@@ -17,7 +17,7 @@ const PHASE_WIDTH: usize = 9;
pub struct Stages<'a> { pub struct Stages<'a> {
pub state: &'a BootState, pub state: &'a BootState,
pub now: Duration, pub now: Duration,
pub palette: &'a Palette, pub colors: &'a StageColors,
pub glyphs: &'a Glyphs, pub glyphs: &'a Glyphs,
} }
@@ -55,8 +55,8 @@ impl Stages<'_> {
fn finished_phases(&self) -> impl Iterator<Item = Line<'static>> + '_ { fn finished_phases(&self) -> impl Iterator<Item = Line<'static>> + '_ {
self.state.finished_stages.iter().map(|stage| { self.state.finished_stages.iter().map(|stage| {
Line::from(vec![ Line::from(vec![
BRANCH.fg(self.palette.muted), BRANCH.fg(self.colors.branches),
format!("{:PHASE_WIDTH$}", stage.label).fg(self.palette.waiting), format!("{:PHASE_WIDTH$}", stage.label).fg(self.colors.finished_label),
format!( format!(
"{} done in {}", "{} done in {}",
self.glyphs.bead, self.glyphs.bead,
@@ -64,11 +64,11 @@ impl Stages<'_> {
&stage.reached_at.saturating_sub(stage.started_at) &stage.reached_at.saturating_sub(stage.started_at)
) )
) )
.fg(self.palette.done), .fg(self.colors.finished_time),
format!(" · {}", unit_count(stage.finished_units)).fg(self.palette.waiting), format!(" · {}", unit_count(stage.finished_units)).fg(self.colors.unit_count),
if stage.failed_units > 0 { if stage.failed_units > 0 {
format!(" · {} {} failed", self.glyphs.failed, stage.failed_units) format!(" · {} {} failed", self.glyphs.failed, stage.failed_units)
.fg(self.palette.failed) .fg(self.colors.failed_count)
.bold() .bold()
} else { } else {
Span::default() Span::default()
@@ -79,16 +79,16 @@ impl Stages<'_> {
fn concluded_phase(&self, conclusion: &Conclusion) -> Line<'static> { fn concluded_phase(&self, conclusion: &Conclusion) -> Line<'static> {
Line::from(vec![ Line::from(vec![
LAST_BRANCH.fg(self.palette.muted), LAST_BRANCH.fg(self.colors.branches),
format!( format!(
"{} {} finished in {}", "{} {} finished in {}",
self.glyphs.bead, self.glyphs.bead,
conclusion.finished, conclusion.finished,
ELAPSED.unsigned_duration_to_string(&conclusion.took) ELAPSED.unsigned_duration_to_string(&conclusion.took)
) )
.fg(self.palette.done) .fg(self.colors.finished_time)
.bold(), .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); .map_or(self.state.origin, |stage| stage.reached_at);
let elapsed = ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(started_at)); let elapsed = ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(started_at));
Line::from(vec![ Line::from(vec![
LAST_BRANCH.fg(self.palette.muted), LAST_BRANCH.fg(self.colors.branches),
format!("{:PHASE_WIDTH$}", self.state.phase.label()) format!("{:PHASE_WIDTH$}", self.state.phase.label())
.fg(self.palette.text) .fg(self.colors.current)
.bold(), .bold(),
elapsed.fg(self.palette.text), elapsed.fg(self.colors.current),
]) ])
} }
} }
+17 -17
View File
@@ -15,9 +15,9 @@ use ratatui::{
use super::{fit_width, rule, unit_count}; use super::{fit_width, rule, unit_count};
use crate::{ use crate::{
colors::TimelineColors,
glyphs::Glyphs, glyphs::Glyphs,
model::{FinishedRun, MilestoneRow}, model::{FinishedRun, MilestoneRow},
palette::Palette,
}; };
pub const LABEL_WIDTH: u16 = 28; pub const LABEL_WIDTH: u16 = 28;
@@ -51,7 +51,7 @@ pub struct Timeline<'a> {
pub milestones: Vec<MilestoneRow>, pub milestones: Vec<MilestoneRow>,
pub finished: Vec<&'a FinishedRun>, pub finished: Vec<&'a FinishedRun>,
pub running: Vec<RunningRun<'a>>, pub running: Vec<RunningRun<'a>>,
pub palette: &'a Palette, pub colors: &'a TimelineColors,
pub glyphs: &'a Glyphs, pub glyphs: &'a Glyphs,
} }
@@ -91,13 +91,13 @@ impl Timeline<'_> {
row.label, row.label,
unit_count(row.finished_units) unit_count(row.finished_units)
), ),
self.palette.done, self.colors.milestone,
), ),
segments: vec![Segment { segments: vec![Segment {
from: row.started_at, from: row.started_at,
to: row.reached_at, to: row.reached_at,
symbol: self.glyphs.bead, symbol: self.glyphs.bead,
color: self.palette.done, color: self.colors.milestone,
}], }],
still_going: false, still_going: false,
} }
@@ -110,14 +110,14 @@ impl Timeline<'_> {
self.glyphs.done self.glyphs.done
}; };
let outcome = if run.failed { let outcome = if run.failed {
self.palette.failed self.colors.failed
} else { } else {
self.palette.done self.colors.finished
}; };
TimelineEntry { TimelineEntry {
label: Line::from(vec![ label: Line::from(vec![
Span::styled(format!("{mark} "), outcome), 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 { segments: vec![Segment {
from: run.started_at, from: run.started_at,
@@ -142,18 +142,18 @@ impl Timeline<'_> {
from: run.queued_at, from: run.queued_at,
to: run.since, to: run.since,
symbol: self.glyphs.waiting_bead, symbol: self.glyphs.waiting_bead,
color: self.palette.waiting, color: self.colors.queued_bar,
}); });
let ran = Segment { let ran = Segment {
from: run.since, from: run.since,
to: self.now, to: self.now,
symbol: self.glyphs.bead, symbol: self.glyphs.bead,
color: self.palette.running, color: self.colors.running,
}; };
TimelineEntry { TimelineEntry {
label: Line::from(vec![ label: Line::from(vec![
format!("{} ", self.glyphs.running_mark).fg(self.palette.running), format!("{} ", self.glyphs.running_mark).fg(self.colors.running),
self.fitted(run.label).fg(self.palette.text), self.fitted(run.label).fg(self.colors.running_label),
]), ]),
segments: waited.into_iter().chain(once(ran)).collect(), segments: waited.into_iter().chain(once(ran)).collect(),
still_going: true, still_going: true,
@@ -164,8 +164,8 @@ impl Timeline<'_> {
impl Widget for Timeline<'_> { impl Widget for Timeline<'_> {
fn render(self, area: Rect, buf: &mut Buffer) { fn render(self, area: Rect, buf: &mut Buffer) {
let block = rule( let block = rule(
self.palette, self.colors.rule,
Line::from(" Timeline ".fg(self.palette.waiting)), Line::from(" Timeline ".fg(self.colors.title)),
); );
let inner = block.inner(area); let inner = block.inner(area);
block.render(area, buf); block.render(area, buf);
@@ -192,7 +192,7 @@ impl Widget for Timeline<'_> {
.render(label_area, buf); .render(label_area, buf);
let axis = TimeAxis::new(self.origin, self.now, bar_area.width); 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 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() Canvas::default()
.x_bounds(axis.bounds()) .x_bounds(axis.bounds())
.y_bounds([0.0, label_row]) .y_bounds([0.0, label_row])
@@ -211,20 +211,20 @@ impl Widget for Timeline<'_> {
}); });
if entry.still_going { if entry.still_going {
ctx.marker(Marker::Custom(self.glyphs.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)); ctx.marker(Marker::Custom(self.glyphs.root_switch_mark));
self.root_switches.iter().for_each(|at| { self.root_switches.iter().for_each(|at| {
let x = at.as_secs_f64(); 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| { axis.tick_offsets().for_each(|offset| {
let label = axis.label(offset); let label = axis.label(offset);
let x = (axis.origin + offset) let x = (axis.origin + offset)
.as_secs_f64() .as_secs_f64()
.min(axis.bounds()[1] - axis.columns_to_seconds(label.len() - 1)); .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); .render(bar_area, buf);
+38 -30
View File
@@ -11,9 +11,9 @@ use unicode_width::UnicodeWidthStr;
use super::{BRANCH, DURATION_WIDTH, ELAPSED, ENDED_TRUNK, LAST_BRANCH, PASSING_TRUNK, fit_width}; use super::{BRANCH, DURATION_WIDTH, ELAPSED, ENDED_TRUNK, LAST_BRANCH, PASSING_TRUNK, fit_width};
use crate::{ use crate::{
colors::TreeColors,
glyphs::Glyphs, glyphs::Glyphs,
model::{RowStatus, TreeRow, UnitKind}, model::{RowStatus, TreeRow, UnitKind},
palette::Palette,
}; };
const SPINNER: [char; 4] = ['|', '/', '-', '\\']; const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
@@ -29,7 +29,7 @@ pub struct UnitTree<'a> {
pub now: Duration, pub now: Duration,
pub hide_runs_shorter_than: Duration, pub hide_runs_shorter_than: Duration,
pub frame: u64, pub frame: u64,
pub palette: &'a Palette, pub colors: &'a TreeColors,
pub glyphs: &'a Glyphs, pub glyphs: &'a Glyphs,
} }
@@ -74,7 +74,7 @@ impl UnitTree<'_> {
if !self.phase_fits_its_column(columns) { if !self.phase_fits_its_column(columns) {
return Row::default().height(HEADER_ROWS); 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([ Row::new(columns.shown([
self.phase.clone(), self.phase.clone(),
name("Kind"), name("Kind"),
@@ -102,36 +102,44 @@ impl UnitTree<'_> {
} }
fn label_style(&self, row: &TreeRow, stage: Stage) -> Style { fn label_style(&self, row: &TreeRow, stage: Stage) -> Style {
match (stage, row.kind, row.status) { match stage {
(Stage::Current, ..) => Style::from(self.palette.running).bold(), Stage::Current => Style::from(self.colors.current_stage).bold(),
(Stage::Reached, ..) => self.palette.done.into(), Stage::Reached => self.colors.reached_stage.into(),
(_, _, RowStatus::Failed) => Style::from(self.palette.failed).bold(), Stage::Upcoming | Stage::Inside => self.unit_label_style(row),
(_, UnitKind::Target, _) => self.palette.target.into(), }
(_, _, RowStatus::Running { .. }) => self.palette.text.into(), }
(_, _, RowStatus::Waiting) => self.palette.waiting.into(),
(_, _, RowStatus::Done) => self.palette.muted.into(), 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> { fn status_marker(&self, row: &TreeRow, stage: Stage) -> Span<'static> {
match (stage, row.kind, row.status) { match stage {
(Stage::Current, ..) => { Stage::Current => {
format!("{} ", self.glyphs.stage_current).fg(self.palette.running) format!("{} ", self.glyphs.stage_current).fg(self.colors.current_stage)
} }
(Stage::Upcoming, ..) => { Stage::Upcoming => format!("{} ", self.glyphs.stage_upcoming).fg(self.colors.target),
format!("{} ", self.glyphs.stage_upcoming).fg(self.palette.target) Stage::Reached => format!("{} ", self.glyphs.done).fg(self.colors.reached_stage),
} Stage::Inside => self.unit_marker(row),
(Stage::Reached, ..) => format!("{} ", self.glyphs.done).fg(self.palette.done), }
(_, _, RowStatus::Failed) => { }
format!("[{}] ", self.glyphs.failed).fg(self.palette.failed)
} fn unit_marker(&self, row: &TreeRow) -> Span<'static> {
(_, UnitKind::Target, _) => Span::default(), match row.status {
(_, _, RowStatus::Running { .. }) => { 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()]; 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::Waiting => "[ ] ".fg(self.colors.waiting_unit),
(_, _, RowStatus::Done) => format!("[{}] ", self.glyphs.done).fg(self.palette.done), RowStatus::Done => format!("[{}] ", self.glyphs.done).fg(self.colors.finished_marker),
} }
} }
@@ -203,12 +211,12 @@ impl UnitTree<'_> {
let style = self.label_style(row, stage); let style = self.label_style(row, stage);
Row::new(columns.shown([ Row::new(columns.shown([
Line::from(vec![ Line::from(vec![
prefix.fg(self.palette.muted), prefix.fg(self.colors.branches),
marker, marker,
Span::styled(self.chained_label(row, room), style), Span::styled(self.chained_label(row, room), style),
]), ]),
Line::from(annotation(row.kind.tag(), columns.tag)).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.palette.muted), Line::from(annotation(&row.description, columns.description)).fg(self.colors.columns),
Line::from(timer).style(style).right_aligned(), Line::from(timer).style(style).right_aligned(),
])) ]))
} }
@@ -241,7 +249,7 @@ impl Widget for UnitTree<'_> {
let overflow = (hidden > 0).then(|| { let overflow = (hidden > 0).then(|| {
Row::new([ Row::new([
format!("{ENDED_TRUNK}{} {hidden} more", self.glyphs.ellipsis) format!("{ENDED_TRUNK}{} {hidden} more", self.glyphs.ellipsis)
.fg(self.palette.waiting), .fg(self.colors.overflow),
]) ])
}); });
let columns = self.columns(area.width); let columns = self.columns(area.width);