diff --git a/Cargo.lock b/Cargo.lock index 8e3fa5d..8338184 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -155,6 +155,8 @@ dependencies = [ "serde", "signal-hook 0.4.5", "toml", + "unicode-truncate", + "unicode-width", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9b4d70d..8634706 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,8 @@ rustix = { version = "1", features = ["fs", "process", "stdio", "system", "termi serde = { version = "1.0.229", features = ["derive"] } signal-hook = "0.4" toml = "1.1.8" +unicode-truncate = "2.0" +unicode-width = "0.2" [profile.release] lto = "thin" diff --git a/demo/host.nix b/demo/host.nix index 4f53ca4..1c332af 100644 --- a/demo/host.nix +++ b/demo/host.nix @@ -6,6 +6,7 @@ }: let demoService = spec: { + inherit (spec) description; after = map (dependency: "${dependency}.service") (spec.after or [ ]); wantedBy = [ "multi-user.target" ]; serviceConfig = { @@ -30,7 +31,7 @@ in boot.initrd.systemd = { enable = true; services.demo-initrd-probe = { - description = "bootvine demo: slow initrd step"; + description = "Slow hardware probe"; wantedBy = [ "initrd.target" ]; before = [ "initrd.target" ]; unitConfig.DefaultDependencies = false; diff --git a/demo/units.nix b/demo/units.nix index 18767e8..d3408a1 100644 --- a/demo/units.nix +++ b/demo/units.nix @@ -3,19 +3,23 @@ initrdProbeSeconds = "6"; services = { demo-disk = { + description = "Scratch disk preparation"; seconds = "2"; stopSeconds = "2"; }; demo-db = { + description = "Demo database"; seconds = "3"; stopSeconds = "3"; after = [ "demo-disk" ]; }; demo-cache = { + description = "In-memory cache"; seconds = "1.5"; stopSeconds = "1"; }; demo-web = { + description = "Web frontend"; seconds = "2"; stopSeconds = "2"; after = [ @@ -23,13 +27,21 @@ "demo-cache" ]; }; - demo-fetch.seconds = "4"; + demo-fetch = { + description = "Remote content sync"; + seconds = "4"; + }; demo-flaky = { + description = "Flaky health check"; seconds = "1"; fails = true; }; - demo-slow.seconds = "8"; + demo-slow = { + description = "Slow warm-up job"; + seconds = "8"; + }; demo-report = { + description = "Startup report"; seconds = "1"; after = [ "demo-web" diff --git a/demo/user-units.nix b/demo/user-units.nix index 59cd4f3..a71b422 100644 --- a/demo/user-units.nix +++ b/demo/user-units.nix @@ -14,7 +14,7 @@ let name: spec: writeText "${name}.service" (toUnitFile { Unit = { - Description = "bootvine demo: ${name}"; + Description = spec.description; After = map (dependency: "${dependency}.service") (spec.after or [ ]); }; Service = { @@ -34,7 +34,7 @@ let targetFile = writeText "${demoUnits.target}.target" (toUnitFile { Unit = { - Description = "bootvine demo target"; + Description = "bootvine demo services"; Wants = serviceNames; After = serviceNames; }; diff --git a/docs/initrd.png b/docs/initrd.png index 979d784..374cbca 100644 Binary files a/docs/initrd.png and b/docs/initrd.png differ diff --git a/docs/shutdown.png b/docs/shutdown.png index f3d18ec..daad49a 100644 Binary files a/docs/shutdown.png and b/docs/shutdown.png differ diff --git a/docs/stage-2.png b/docs/stage-2.png index d353f5c..29bcb89 100644 Binary files a/docs/stage-2.png and b/docs/stage-2.png differ diff --git a/examples/demo.rs b/examples/demo.rs index d086d79..b3a7a70 100644 --- a/examples/demo.rs +++ b/examples/demo.rs @@ -7,6 +7,7 @@ use std::{ use bootvine::{ glyphs::Glyphs, model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts}, + origin::BootOrigin, palette::Palette, view::BootView, }; @@ -145,9 +146,20 @@ const HOST: &[Step] = &[ &["basic.target"], Duration::from_millis(800), ), + step( + "docker.socket", + &["basic.target"], + Duration::from_millis(200), + ), + step("var-lib-docker.mount", &[], Duration::from_millis(1800)), step( "docker.service", - &["containerd.service", "network-online.target"], + &[ + "containerd.service", + "docker.socket", + "var-lib-docker.mount", + "network-online.target", + ], Duration::from_millis(1500), ), failing( @@ -167,6 +179,38 @@ const HOST: &[Step] = &[ ), ]; +fn description(unit: &str) -> &'static str { + match unit { + "initrd.target" => "Initrd Default Target", + "initrd-fs.target" => "Initrd File Systems", + "initrd-root-device.target" => "Initrd Root Device", + "sysroot.mount" => "/sysroot", + "systemd-fsck-root.service" => "File System Check on Root Device", + "dev-disk-by\\x2dlabel-nixos.device" => "/dev/disk/by-label/nixos", + "systemd-udevd.service" => "Rule-based Manager for Device Events and Files", + "demo-initrd-probe.service" => "Slow hardware probe", + "graphical.target" => "Graphical Interface", + "display-manager.service" => "Display Manager", + "multi-user.target" => "Multi-User System", + "basic.target" => "Basic System", + "sysinit.target" => "System Initialization", + "systemd-tmpfiles-setup.service" => "Create System Files and Directories", + "systemd-udev-trigger.service" => "Coldplug All udev Devices", + "NetworkManager.service" => "Network Manager", + "NetworkManager-wait-online.service" => "Network Manager Wait Online", + "network-online.target" => "Network is Online", + "tailscaled.service" => "Tailscale node agent", + "containerd.service" => "containerd container runtime", + "docker.socket" => "Docker Socket for the API", + "docker.service" => "Docker Application Container Engine", + "var-lib-docker.mount" => "/var/lib/docker", + "nvidia-powerd.service" => "NVIDIA Dynamic Boost", + "sys-devices-virtual-misc-rfkill.device" => "/sys/devices/virtual/misc/rfkill", + "systemd-rfkill.service" => "Load/Save RF Kill Switch Status", + _ => "", + } +} + struct ScriptedJob { id: u32, step: &'static Step, @@ -176,7 +220,7 @@ impl ScriptedJob { fn facts(&self) -> UnitFacts { UnitFacts { name: self.step.unit.to_owned(), - description: self.step.unit.to_owned(), + description: description(self.step.unit).to_owned(), after: self.step.after.iter().map(ToString::to_string).collect(), before: Vec::new(), } @@ -297,6 +341,12 @@ fn wants_to_quit() -> io::Result { fn play(terminal: &mut DefaultTerminal) -> io::Result<()> { let clock = Instant::now(); let now = || clock.elapsed(); + let origin = BootOrigin { + host: "demo".to_owned(), + system: "NixOS 26.11.20261007.39ad350".to_owned(), + generation: "42".to_owned(), + kernel: "Linux 7.2.9".to_owned(), + }; let mut state = BootState::new(Phase::Initrd); let mut script = Script::begin(INITRD, 1, &mut state, now()); let mut frame = 0; @@ -314,7 +364,7 @@ fn play(terminal: &mut DefaultTerminal) -> io::Result<()> { palette: &Palette::default(), glyphs: &Glyphs::default(), now: now(), - host: "demo", + origin: &origin, frame, }, canvas.area(), diff --git a/src/glyphs.rs b/src/glyphs.rs index 91cab02..1d0d568 100644 --- a/src/glyphs.rs +++ b/src/glyphs.rs @@ -7,6 +7,8 @@ pub struct Glyphs { pub still_going: char, pub running_mark: char, pub root_switch_mark: char, + pub stage_current: char, + pub stage_upcoming: char, pub ellipsis: &'static str, pub chain_link: &'static str, } @@ -18,6 +20,7 @@ const WAITING_BEAD: [char; 2] = ['·', '.']; const STILL_GOING: [char; 2] = ['▶', '>']; const RUNNING_MARK: [char; 3] = ['►', '▶', '>']; const ROOT_SWITCH_MARK: [char; 2] = ['│', '|']; +const STAGE_MARKS: [&str; 3] = ["◆◇", "●○", "*o"]; const ELLIPSIS: [&str; 2] = ["…", "..."]; const CHAIN_LINK: [&str; 2] = ["─", "-"]; @@ -43,6 +46,7 @@ impl Glyphs { .find(|candidate| candidate.chars().all(&covers)) .unwrap_or(candidates[candidates.len() - 1]) }; + let stage_marks: Vec = text(&STAGE_MARKS).chars().collect(); Self { done: symbol(&DONE), failed: symbol(&FAILED), @@ -51,6 +55,8 @@ impl Glyphs { still_going: symbol(&STILL_GOING), running_mark: symbol(&RUNNING_MARK), root_switch_mark: symbol(&ROOT_SWITCH_MARK), + stage_current: stage_marks[0], + stage_upcoming: stage_marks[1], ellipsis: text(&ELLIPSIS), chain_link: text(&CHAIN_LINK), } @@ -75,6 +81,7 @@ mod tests { assert_eq!(glyphs.running_mark, '▶'); assert_eq!(glyphs.failed, '×'); assert_eq!(glyphs.ellipsis, "…"); + assert_eq!((glyphs.stage_current, glyphs.stage_upcoming), ('*', 'o')); } #[test] @@ -84,6 +91,7 @@ mod tests { assert_eq!(glyphs.failed, 'x'); assert_eq!(glyphs.ellipsis, "..."); assert_eq!(glyphs.chain_link, "─"); + assert_eq!((glyphs.stage_current, glyphs.stage_upcoming), ('*', 'o')); } #[test] diff --git a/src/lib.rs b/src/lib.rs index b023062..1dadba6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ pub mod glyphs; pub mod model; +pub mod origin; pub mod palette; pub mod view; diff --git a/src/model.rs b/src/model.rs index bafd069..2c5f594 100644 --- a/src/model.rs +++ b/src/model.rs @@ -158,18 +158,80 @@ impl UnitRecord { } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnitKind { + Service, + Target, + Socket, + Mount, + Automount, + Device, + Swap, + Path, + Timer, + Slice, + Scope, + Other, +} + +impl UnitKind { + #[must_use] + pub fn of(name: &str) -> Self { + match name.rsplit_once('.').map(|(_, suffix)| suffix) { + Some("service") => Self::Service, + Some("target") => Self::Target, + Some("socket") => Self::Socket, + Some("mount") => Self::Mount, + Some("automount") => Self::Automount, + Some("device") => Self::Device, + Some("swap") => Self::Swap, + Some("path") => Self::Path, + Some("timer") => Self::Timer, + Some("slice") => Self::Slice, + Some("scope") => Self::Scope, + _ => Self::Other, + } + } + + #[must_use] + pub fn tag(self) -> &'static str { + match self { + Self::Service | Self::Target | Self::Other => "", + Self::Socket => "socket", + Self::Mount => "mount", + Self::Automount => "automount", + Self::Device => "device", + Self::Swap => "swap", + Self::Path => "path", + Self::Timer => "timer", + Self::Slice => "slice", + Self::Scope => "scope", + } + } + + fn labelled_by_description(self) -> bool { + matches!( + self, + Self::Device | Self::Mount | Self::Swap | Self::Automount + ) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RowStatus { Waiting, Running, + Failed, + Done, } #[derive(Clone, Debug, PartialEq, Eq)] -pub struct PendingRow { +pub struct TreeRow { pub depth: usize, pub is_last_sibling: Vec, pub label: String, - pub is_target: bool, + pub description: String, + pub kind: UnitKind, pub status: RowStatus, pub queued_at: Duration, pub running_since: Option, @@ -204,6 +266,7 @@ pub struct FinishedRun { pub struct FinishedStage { pub label: &'static str, pub finished_units: usize, + pub failed_units: usize, pub started_at: Duration, pub reached_at: Duration, } @@ -351,7 +414,7 @@ impl BootState { record.job = None; } if let Some(started_at) = started_at - && !record.facts.name.ends_with(".target") + && UnitKind::of(&record.facts.name) != UnitKind::Target { self.finished_runs.push(FinishedRun { label: display_label(&record.facts), @@ -369,8 +432,9 @@ impl BootState { JobResult::Failed | JobResult::Timeout | JobResult::Dependency => Outcome::Failed, }; record.outcome = Some(outcome); - if outcome == Outcome::Failed && !self.failed.contains(&unit) { - self.failed.push(unit); + let label = display_label(&record.facts); + if outcome == Outcome::Failed && !self.failed.contains(&label) { + self.failed.push(label); } } @@ -383,6 +447,11 @@ impl BootState { self.finished_stages.push(FinishedStage { label: Phase::Initrd.label(), finished_units: finished_here + self.finished_before_reconnect, + failed_units: self + .units + .values() + .filter(|record| record.outcome == Some(Outcome::Failed)) + .count(), started_at: self.origin, reached_at: at, }); @@ -519,14 +588,25 @@ impl BootState { } #[must_use] - pub fn pending_rows(&self) -> Vec { + pub fn tree_rows(&self) -> Vec { let pending: HashSet<&str> = self .units .iter() - .filter(|(_, record)| record.job.is_some()) + .filter(|(name, record)| { + record.job.is_some() + || record.outcome == Some(Outcome::Failed) + || (self.is_milestone(name) && record.outcome.is_some()) + }) .map(|(name, _)| name.as_str()) .collect(); let root = self.root.as_deref().filter(|root| pending.contains(root)); + let stages: Vec<&str> = self + .milestone_targets + .iter() + .map(String::as_str) + .filter(|target| pending.contains(target)) + .chain(root.filter(|root| !self.is_milestone(root))) + .collect(); let blocked_by_pending: HashSet<&str> = pending .iter() .flat_map(|name| self.waits_for(name, &pending)) @@ -534,7 +614,7 @@ impl BootState { let mut unblocked: Vec<&str> = pending .iter() .copied() - .filter(|name| !blocked_by_pending.contains(name) && Some(*name) != root) + .filter(|name| !blocked_by_pending.contains(name) && !stages.contains(name)) .collect(); self.sort_siblings(&mut unblocked); let mut leftovers: Vec<&str> = pending.iter().copied().collect(); @@ -545,7 +625,9 @@ impl BootState { } let mut rows = Vec::new(); let mut visited = HashSet::new(); - root.into_iter() + stages + .iter() + .copied() .chain(unblocked) .chain(leftovers) .for_each(|top| { @@ -560,7 +642,12 @@ impl BootState { ); } }); - rows + let mut kept = Vec::new(); + grow_forest(&mut rows.into_iter().peekable(), 0) + .into_iter() + .filter(|stage| stage.row.status != RowStatus::Done || !stage.children.is_empty()) + .for_each(|stage| stage.flatten_into(0, &mut kept)); + relink_siblings(kept) } fn emit<'a>( @@ -570,32 +657,34 @@ impl BootState { visited: &mut HashSet<&'a str>, ancestry: &mut Vec, is_last: bool, - rows: &mut Vec, + rows: &mut Vec, ) { visited.insert(unit); let record = &self.units[unit]; - let job = record.job.expect("pending rows only hold units with a job"); let running_since = record.running_since(); + let status = match (record.job, running_since, record.outcome) { + (Some(_), Some(_), _) => RowStatus::Running, + (Some(_), None, _) => RowStatus::Waiting, + (None, _, Some(Outcome::Failed)) => RowStatus::Failed, + (None, ..) => RowStatus::Done, + }; let mut is_last_sibling = ancestry.clone(); is_last_sibling.push(is_last); - rows.push(PendingRow { + rows.push(TreeRow { depth: ancestry.len(), is_last_sibling, label: display_label(&record.facts), - is_target: record.facts.name.ends_with(".target"), - status: if running_since.is_some() { - RowStatus::Running - } else { - RowStatus::Waiting - }, - queued_at: job.queued_at, + description: summary(&record.facts), + kind: UnitKind::of(&record.facts.name), + status, + queued_at: record.job.map(|job| job.queued_at).unwrap_or_default(), running_since, chain: Vec::new(), }); let candidates: Vec<&str> = self .waits_for(unit, pending) .into_iter() - .filter(|dependency| !visited.contains(dependency)) + .filter(|dependency| !visited.contains(dependency) && !self.is_milestone(dependency)) .collect(); let mut children: Vec<&str> = candidates .iter() @@ -620,6 +709,10 @@ impl BootState { ancestry.pop(); } + fn is_milestone(&self, unit: &str) -> bool { + self.milestone_targets.iter().any(|target| target == unit) + } + fn waits_on(&self, waiter: &str, dependency: &str, pending: &HashSet<&str>) -> bool { let mut seen = HashSet::new(); let mut frontier = vec![waiter]; @@ -655,9 +748,13 @@ impl BootState { } fn sort_siblings(&self, names: &mut [&str]) { - let rank = |name: &str| match self.units[name].running_since() { - Some(since) => SiblingRank::RunningSince(since), - None => SiblingRank::Waiting, + let rank = |name: &str| { + let record = &self.units[name]; + match (record.running_since(), record.outcome) { + (Some(since), _) => SiblingRank::RunningSince(since), + (None, Some(Outcome::Failed)) => SiblingRank::Failed, + (None, _) => SiblingRank::Waiting, + } }; names.sort_by(|left, right| rank(left).cmp(&rank(right)).then_with(|| left.cmp(right))); } @@ -666,6 +763,7 @@ impl BootState { #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] enum SiblingRank { RunningSince(Duration), + Failed, Waiting, } @@ -695,8 +793,7 @@ impl MilestoneWalk { } } -#[must_use] -pub fn paths_to_running(rows: Vec) -> Vec { +fn on_paths_to_running(rows: &[TreeRow]) -> Vec { let mut kept_below: Vec = Vec::new(); let mut kept: Vec = rows .iter() @@ -704,14 +801,40 @@ pub fn paths_to_running(rows: Vec) -> Vec { .map(|row| { let descendant_kept = kept_below.iter().skip(row.depth + 1).any(|kept| *kept); kept_below.resize(row.depth + 1, false); - let anchors_the_tree = row.depth == 0 && row.is_target; - let keep = row.status == RowStatus::Running || descendant_kept || anchors_the_tree; + let anchors_the_tree = row.depth == 0 && row.kind == UnitKind::Target; + let keep = matches!(row.status, RowStatus::Running | RowStatus::Failed) + || descendant_kept + || anchors_the_tree; kept_below[row.depth] |= keep; keep }) .collect(); kept.reverse(); - let survivors: Vec = rows + kept +} + +fn with_spare_rows(essential: &[bool], budget: usize) -> Vec { + let essential_count = essential.iter().filter(|keep| **keep).count(); + let spare = budget.saturating_sub(essential_count + 1); + let earliest_optional: HashSet = essential + .iter() + .enumerate() + .filter(|(_, keep)| !**keep) + .map(|(index, _)| index) + .take(spare) + .collect(); + (0..essential.len()) + .map(|index| essential[index] || earliest_optional.contains(&index)) + .collect() +} + +#[must_use] +pub fn fit_to_height(rows: Vec, budget: usize) -> Vec { + if rows.len() <= budget { + return relink_siblings(rows); + } + let kept = with_spare_rows(&on_paths_to_running(&rows), budget); + let survivors: Vec = rows .into_iter() .zip(kept) .filter_map(|(row, keep)| keep.then_some(row)) @@ -722,7 +845,7 @@ pub fn paths_to_running(rows: Vec) -> Vec { const MIN_FOLDED_LINKS: usize = 2; struct TreeNode { - row: PendingRow, + row: TreeRow, children: Vec, } @@ -763,15 +886,15 @@ impl TreeNode { self } - fn flatten_into(self, depth: usize, rows: &mut Vec) { - rows.push(PendingRow { depth, ..self.row }); + fn flatten_into(self, depth: usize, rows: &mut Vec) { + rows.push(TreeRow { depth, ..self.row }); self.children .into_iter() .for_each(|child| child.flatten_into(depth + 1, rows)); } } -fn grow_forest(rows: &mut Peekable>, depth: usize) -> Vec { +fn grow_forest(rows: &mut Peekable>, depth: usize) -> Vec { iter::from_fn(|| { let row = rows.next_if(|row| row.depth == depth)?; Some(TreeNode { @@ -783,7 +906,7 @@ fn grow_forest(rows: &mut Peekable>, depth: usize) -> Vec) -> Vec { +pub fn fold_chains(rows: Vec) -> Vec { let mut flattened = Vec::new(); grow_forest(&mut rows.into_iter().peekable(), 0) .into_iter() @@ -791,7 +914,7 @@ pub fn fold_chains(rows: Vec) -> Vec { relink_siblings(flattened) } -fn relink_siblings(rows: Vec) -> Vec { +fn relink_siblings(rows: Vec) -> Vec { let mut later_sibling: Vec = Vec::new(); let mut is_last: Vec = rows .iter() @@ -810,7 +933,7 @@ fn relink_siblings(rows: Vec) -> Vec { .map(|(row, last)| { ancestry.truncate(row.depth); ancestry.push(last); - PendingRow { + TreeRow { is_last_sibling: ancestry.clone(), ..row } @@ -818,17 +941,32 @@ fn relink_siblings(rows: Vec) -> Vec { .collect() } +fn labelled_by_description(facts: &UnitFacts) -> bool { + !facts.description.is_empty() && UnitKind::of(&facts.name).labelled_by_description() +} + fn display_label(facts: &UnitFacts) -> String { - if let Some(stem) = facts.name.strip_suffix(".service") { - return stem.to_owned(); - } - let described_by_path = [".device", ".mount", ".swap", ".automount"] - .iter() - .any(|suffix| facts.name.ends_with(suffix)); - if described_by_path && !facts.description.is_empty() { + if labelled_by_description(facts) { return facts.description.clone(); } - facts.name.clone() + match UnitKind::of(&facts.name) { + UnitKind::Target | UnitKind::Other => facts.name.clone(), + _ => facts + .name + .rsplit_once('.') + .map_or_else(|| facts.name.clone(), |(stem, _)| stem.to_owned()), + } +} + +fn summary(facts: &UnitFacts) -> String { + let repeats_the_name = facts.description == facts.name + || facts + .description + .eq_ignore_ascii_case(&display_label(facts)); + if labelled_by_description(facts) || repeats_the_name { + return String::new(); + } + facts.description.clone() } #[cfg(test)] @@ -897,27 +1035,27 @@ mod tests { #[test] fn pending_units_nest_under_what_waits_on_them() { let outline: Vec = sample() - .pending_rows() + .tree_rows() .into_iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) .collect(); assert_eq!( outline, [ + "basic.target", + "multi-user.target", + " docker", + " containerd", + " nm-wait", + " nm", "graphical.target", - " multi-user.target", - " docker", - " containerd", - " basic.target", - " nm-wait", - " nm", ] ); } #[test] fn only_chains_leading_to_running_units_stay_in_view() { - let rows = paths_to_running(sample().pending_rows()); + let rows = fit_to_height(sample().tree_rows(), 0); let outline: Vec = rows .iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) @@ -925,18 +1063,106 @@ mod tests { assert_eq!( outline, [ + "basic.target", + "multi-user.target", + " docker", + " nm-wait", + " nm", "graphical.target", - " multi-user.target", - " docker", - " nm-wait", - " nm", ] ); let lasts: Vec = rows .iter() .map(|row| *row.is_last_sibling.last().unwrap()) .collect(); - assert_eq!(lasts, [true, true, false, true, true]); + assert_eq!(lasts, [false, false, false, true, true, true]); + } + + #[test] + fn spare_rows_bring_back_waiting_units_under_kept_parents() { + let state = chain_state( + &[ + ("root.target", &["a.service", "b.service"]), + ("a.service", &["a1.service"]), + ("a1.service", &["a2.service"]), + ("a2.service", &[]), + ("b.service", &[]), + ], + "b.service", + ); + let outline = |budget| -> Vec { + fit_to_height(state.tree_rows(), budget) + .into_iter() + .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) + .collect() + }; + assert_eq!(outline(4), ["root.target", " b", " a"]); + assert_eq!( + outline(5), + ["root.target", " b", " a", " a1", " a2"] + ); + } + + #[test] + fn a_unit_sits_in_the_earliest_stage_that_waits_on_it() { + let mut state = BootState::new(Phase::Host); + state.set_root("multi-user.target".to_owned()); + [ + facts( + "multi-user.target", + &["basic.target", "dbus.service", "web.service"], + ), + facts("basic.target", &["dbus.service"]), + facts("dbus.service", &[]), + facts("web.service", &[]), + ] + .into_iter() + .zip(1..) + .for_each(|(unit, id)| { + let name = unit.name.clone(); + state.track_unit(unit, Activity::default()); + state.queue_job(id, &name, JobKind::BringsUp, Duration::ZERO); + }); + let outline: Vec = state + .tree_rows() + .into_iter() + .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) + .collect(); + assert_eq!( + outline, + ["basic.target", " dbus", "multi-user.target", " web"] + ); + } + + #[test] + fn kinds_with_a_tag_drop_their_suffix() { + let socket = facts("docker.socket", &[]); + assert_eq!(UnitKind::of(&socket.name), UnitKind::Socket); + assert_eq!(UnitKind::Socket.tag(), "socket"); + assert_eq!(display_label(&socket), "docker"); + assert_eq!(display_label(&facts("sshd.service", &[])), "sshd"); + assert_eq!(display_label(&facts("basic.target", &[])), "basic.target"); + assert_eq!(UnitKind::Target.tag(), ""); + } + + #[test] + fn descriptions_that_repeat_the_label_are_dropped() { + let described = |name: &str, description: &str| { + summary(&UnitFacts { + name: name.to_owned(), + description: description.to_owned(), + after: Vec::new(), + before: Vec::new(), + }) + }; + assert_eq!( + described("multi-user.target", "Multi-User System"), + "Multi-User System" + ); + assert_eq!(described("greetd.service", "greetd.service"), ""); + assert_eq!(described("greetd.service", "Greetd"), ""); + assert_eq!(described("dev-sda.device", "Samsung SSD"), ""); + assert_eq!(described("demo.service", ""), ""); } fn chain_state(waits: &[(&str, &[&str])], running: &str) -> BootState { @@ -955,7 +1181,7 @@ mod tests { } fn folded_outline(state: &BootState) -> Vec { - fold_chains(paths_to_running(state.pending_rows())) + fold_chains(fit_to_height(state.tree_rows(), 0)) .into_iter() .map(|row| { let chain = once(row.label.as_str()) @@ -1011,7 +1237,7 @@ mod tests { folded_outline(&state), ["root.target", " a", " b", " d"] ); - let rows = fold_chains(paths_to_running(both.pending_rows())); + let rows = fold_chains(fit_to_height(both.tree_rows(), 0)); let lasts: Vec = rows .iter() .map(|row| *row.is_last_sibling.last().unwrap()) @@ -1027,7 +1253,7 @@ mod tests { state.track_unit(facts("idle.service", &[]), Activity::default()); state.queue_job(1, "demo.target", JobKind::BringsUp, Duration::ZERO); state.queue_job(2, "idle.service", JobKind::BringsUp, Duration::ZERO); - let rows = paths_to_running(state.pending_rows()); + let rows = fit_to_height(state.tree_rows(), 0); assert_eq!(rows.len(), 1); assert_eq!(rows[0].label, "demo.target"); } @@ -1046,7 +1272,7 @@ mod tests { active_exit: None, }, ); - let rows = state.pending_rows(); + let rows = state.tree_rows(); assert!( rows.iter() .all(|row| row.label != "containerd" && row.label != "basic.target") @@ -1061,7 +1287,7 @@ mod tests { fn failures_are_listed_and_not_counted_as_done() { let mut state = sample(); state.finish_job(4, JobResult::Failed, 2000 * MS); - assert_eq!(state.failed, ["nm.service"]); + assert_eq!(state.failed, ["nm"]); let tally = state.tally(); assert_eq!(tally.failed, 1); assert_eq!(tally.done, 0); @@ -1105,13 +1331,14 @@ mod tests { [FinishedStage { label: "initrd", finished_units: 2, + failed_units: 0, started_at: Duration::ZERO, reached_at: 2000 * MS, }] ); assert_eq!(state.milestones()[0].reached_at, Some(2000 * MS)); assert_eq!(state.tally().done, 2); - assert!(state.pending_rows().is_empty()); + assert!(state.tree_rows().is_empty()); } #[test] @@ -1127,7 +1354,7 @@ mod tests { Activity::default(), ); state.queue_job(1, "dev-nvme1n1.device", JobKind::BringsUp, Duration::ZERO); - assert_eq!(state.pending_rows()[0].label, "Lexar SSD NM790 2TB"); + assert_eq!(state.tree_rows()[0].label, "Lexar SSD NM790 2TB"); } #[test] @@ -1151,7 +1378,7 @@ mod tests { state.queue_job(id, &name, JobKind::BringsUp, Duration::ZERO); }); let outline: Vec = state - .pending_rows() + .tree_rows() .into_iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) .collect(); @@ -1167,7 +1394,7 @@ mod tests { fn outline(state: &BootState) -> Vec { state - .pending_rows() + .tree_rows() .into_iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) .collect() @@ -1205,8 +1432,8 @@ mod tests { assert_eq!( outline(&state), [ + "shutdown.target", "poweroff.target", - " shutdown.target", "network.target", " web", ] @@ -1251,7 +1478,7 @@ mod tests { ..Activity::default() }, ); - assert_eq!(state.pending_rows()[0].running_since, Some(1200 * MS)); + assert_eq!(state.tree_rows()[0].running_since, Some(1200 * MS)); state.finish_job(1, JobResult::Done, 1700 * MS); assert_eq!( state.finished_runs, @@ -1290,6 +1517,6 @@ mod tests { state.track_unit(facts("b.service", &["a.service"]), Activity::default()); state.queue_job(1, "a.service", JobKind::BringsUp, Duration::ZERO); state.queue_job(2, "b.service", JobKind::BringsUp, Duration::ZERO); - assert_eq!(state.pending_rows().len(), 2); + assert_eq!(state.tree_rows().len(), 2); } } diff --git a/src/origin.rs b/src/origin.rs new file mode 100644 index 0000000..91e7902 --- /dev/null +++ b/src/origin.rs @@ -0,0 +1,172 @@ +use std::{ + fs::{read_dir, read_link, read_to_string}, + path::{Path, PathBuf}, +}; + +use rustix::system::uname; + +const KERNEL_COMMAND_LINE: &str = "/proc/cmdline"; +const SYSTEM_PROFILES: &str = "/nix/var/nix/profiles"; +const OS_RELEASES: [&str; 2] = ["/etc/os-release", "/usr/lib/os-release"]; +const NIXOS_SYSTEM: &str = "nixos-system-"; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct BootOrigin { + pub host: String, + pub system: String, + pub generation: String, + pub kernel: String, +} + +impl BootOrigin { + #[must_use] + pub fn read() -> Self { + let names = uname(); + let host = names.nodename().to_string_lossy().into_owned(); + let command_line = read_to_string(KERNEL_COMMAND_LINE).unwrap_or_default(); + let system_path = init_system(&command_line); + let system = system_path + .and_then(|path| nixos_version(path, &host)) + .map(|version| format!("NixOS {version}")) + .or_else(|| { + OS_RELEASES + .iter() + .find_map(|path| read_to_string(path).ok()) + .and_then(|release| pretty_name(&release)) + }) + .unwrap_or_default(); + let generation = system_path + .map(|path| generation_of(Path::new(path), &system_links())) + .unwrap_or_default(); + Self { + kernel: format!("Linux {}", names.release().to_string_lossy()), + host, + system, + generation, + } + } + + #[must_use] + pub fn parts(&self) -> Vec { + [ + self.host.clone(), + self.system.clone(), + if self.generation.is_empty() { + String::new() + } else { + format!("generation {}", self.generation) + }, + self.kernel.clone(), + ] + .into_iter() + .filter(|part| !part.is_empty()) + .collect() + } +} + +fn init_system(command_line: &str) -> Option<&str> { + command_line + .split_whitespace() + .find_map(|argument| argument.strip_prefix("init=")) + .and_then(|init| init.strip_suffix("/init")) +} + +fn nixos_version<'a>(system_path: &'a str, host: &str) -> Option<&'a str> { + let (_, name) = system_path.rsplit_once('/')?; + let (_, rest) = name.split_once('-')?; + rest.strip_prefix(NIXOS_SYSTEM)? + .strip_prefix(host)? + .strip_prefix('-') +} + +fn pretty_name(os_release: &str) -> Option { + os_release + .lines() + .find_map(|line| line.strip_prefix("PRETTY_NAME=")) + .map(|value| value.trim_matches('"').to_owned()) +} + +struct SystemLink { + generation: String, + target: PathBuf, +} + +fn system_links() -> Vec { + read_dir(SYSTEM_PROFILES) + .into_iter() + .flatten() + .filter_map(Result::ok) + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + let generation = name.strip_prefix("system-")?.strip_suffix("-link")?; + Some(SystemLink { + generation: generation.to_owned(), + target: read_link(entry.path()).ok()?, + }) + }) + .collect() +} + +fn generation_of(system_path: &Path, links: &[SystemLink]) -> String { + links + .iter() + .find(|link| link.target == system_path) + .map(|link| link.generation.clone()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + const COMMAND_LINE: &str = "initrd=\\EFI\\nixos\\x-initrd.efi \ + init=/nix/store/\ + av1146s7ayap8zgrpindi641v1fmdxsf-nixos-system-ryzen-26.11.\ + 20261007.39ad350/init panic=10 root=fstab"; + + #[test] + fn the_nixos_version_comes_from_the_init_on_the_command_line() { + let system = init_system(COMMAND_LINE).expect("init system"); + assert_eq!( + nixos_version(system, "ryzen"), + Some("26.11.20261007.39ad350") + ); + assert_eq!(nixos_version(system, "other-host"), None); + } + + #[test] + fn the_generation_is_the_profile_link_to_the_booted_system() { + let system = init_system(COMMAND_LINE).expect("init system"); + let links = [ + SystemLink { + generation: "2770".to_owned(), + target: "/nix/store/x43q-nixos-system-ryzen-26.11".into(), + }, + SystemLink { + generation: "2771".to_owned(), + target: system.into(), + }, + ]; + assert_eq!(generation_of(Path::new(system), &links), "2771"); + assert_eq!(generation_of(Path::new(system), &links[..1]), ""); + } + + #[test] + fn other_distributions_use_their_pretty_name() { + assert_eq!( + pretty_name("NAME=Arch\nPRETTY_NAME=\"Arch Linux\"\n"), + Some("Arch Linux".to_owned()) + ); + } + + #[test] + fn unknown_parts_are_left_out() { + let origin = BootOrigin { + host: "ryzen".to_owned(), + system: "NixOS 26.11".to_owned(), + generation: String::new(), + kernel: "Linux 7.2.9".to_owned(), + }; + assert_eq!(origin.parts(), ["ryzen", "NixOS 26.11", "Linux 7.2.9"]); + } +} diff --git a/src/run.rs b/src/run.rs index 60b02a7..bac9353 100644 --- a/src/run.rs +++ b/src/run.rs @@ -10,6 +10,7 @@ use std::{ use bootvine::{ model::{BootState, Phase}, + origin::BootOrigin, palette::Palette, view::BootView, }; @@ -19,7 +20,6 @@ use ratatui::{ backend::Backend, buffer::{Buffer, CellDiffOption}, }; -use rustix::system::uname; use signal_hook::{consts::SIGTERM, flag}; use crate::{ @@ -112,12 +112,17 @@ fn watch( console: &mut Console, hold: Duration, ) -> Result<(), Error> { - let host = uname().nodename().to_string_lossy().into_owned(); + let mut origin = BootOrigin::read(); + let mut origin_phase = state.phase; let mut frame: u64 = 0; let mut painted_connections = feed.connections; let mut last_full_repaint = Instant::now(); loop { feed.pump(state, FRAME_INTERVAL)?; + if state.phase != origin_phase { + origin = BootOrigin::read(); + origin_phase = state.phase; + } console.make_way_for_password_prompts(); let repaint_due = feed.connections != painted_connections || last_full_repaint.elapsed() >= FULL_REPAINT_INTERVAL; @@ -131,7 +136,7 @@ fn watch( palette, glyphs: &console.glyphs, now: monotonic_now(), - host: &host, + origin: &origin, frame, }, canvas.area(), diff --git a/src/view.rs b/src/view.rs index 9687581..40b8ad1 100644 --- a/src/view.rs +++ b/src/view.rs @@ -1,4 +1,3 @@ -mod failures; mod footer; mod header; mod stages; @@ -14,24 +13,27 @@ use ratatui::{ text::Line, widgets::{Block, Borders, Widget}, }; +use unicode_truncate::UnicodeTruncateStr; +use unicode_width::UnicodeWidthStr; -use self::{ - failures::Failures, footer::Footer, header::Header, stages::Stages, timeline::Timeline, - tree::PendingTree, -}; +use self::{footer::Footer, header::Header, stages::Stages, timeline::Timeline, tree::UnitTree}; use crate::{ glyphs::Glyphs, - model::{BootState, PendingRow, RowStatus, fold_chains, paths_to_running}, + model::{BootState, RowStatus, TreeRow, UnitKind, fit_to_height, fold_chains}, + origin::BootOrigin, palette::Palette, }; -const RULE_STUB: &str = "──"; const DURATION_WIDTH: u16 = 8; const MIN_BAR_WIDTH: u16 = 12; const MIN_HEIGHT_FOR_TIMELINE: u16 = 12; const MIN_TIMELINE_HEIGHT: u16 = timeline::CHROME_HEIGHT + 4; const NOTEWORTHY_DURATION: Duration = Duration::from_secs(1); -const HEADER_HEIGHT: u16 = 2; +const HEADER_HEIGHT: u16 = 1; +const BRANCH: &str = "├─ "; +const LAST_BRANCH: &str = "└─ "; +const PASSING_TRUNK: &str = "│ "; +const ENDED_TRUNK: &str = " "; const ELAPSED: SpanPrinter = SpanPrinter::new() .designator(Designator::Compact) @@ -44,15 +46,15 @@ pub struct BootView<'a> { pub palette: &'a Palette, pub glyphs: &'a Glyphs, pub now: Duration, - pub host: &'a str, + pub origin: &'a BootOrigin, pub frame: u64, } impl BootView<'_> { - fn timeline<'a>(&'a self, rows: &'a [PendingRow]) -> Timeline<'a> { - let mut running: Vec<&PendingRow> = rows + fn timeline<'a>(&'a self, rows: &'a [TreeRow]) -> Timeline<'a> { + let mut running: Vec<&TreeRow> = rows .iter() - .filter(|row| !row.is_target && row.status == RowStatus::Running) + .filter(|row| row.kind != UnitKind::Target && row.status == RowStatus::Running) .collect(); running.sort_by_key(|row| row.running_since); Timeline { @@ -85,12 +87,11 @@ impl BootView<'_> { impl Widget for BootView<'_> { fn render(self, area: Rect, buf: &mut Buffer) { - let all_rows = self.state.pending_rows(); + let all_rows = self.state.tree_rows(); let pending_count = all_rows.len(); - let rows = fold_chains(paths_to_running(all_rows)); - let shown_units: usize = rows.iter().map(|row| 1 + row.chain.len()).sum(); + let pruned_rows = fold_chains(fit_to_height(all_rows.clone(), 0)); let header = Header { - host: self.host, + origin: self.origin, total: (!self.state.finished_stages.is_empty()) .then(|| self.now.saturating_sub(self.state.origin)), palette: self.palette, @@ -101,20 +102,16 @@ impl Widget for BootView<'_> { palette: self.palette, glyphs: self.glyphs, }; - let tree = PendingTree { - rows: &rows, - folded: pending_count - shown_units, + let pruned = UnitTree { + phase: stages.current_phase(), + rows: &pruned_rows, + hidden: pending_count - shown_units(&pruned_rows), now: self.now, frame: self.frame, palette: self.palette, glyphs: self.glyphs, }; - let failures = Failures { - units: &self.state.failed, - palette: self.palette, - glyphs: self.glyphs, - }; - let timeline = self.timeline(&rows); + let timeline = self.timeline(&pruned_rows); let footer = Footer { tally: self.state.tally(), shows_root_switch: !self.state.finished_stages.is_empty(), @@ -123,29 +120,38 @@ impl Widget for BootView<'_> { }; let fits_timeline = area.width >= timeline::LABEL_WIDTH + 1 + MIN_BAR_WIDTH && area.height >= MIN_HEIGHT_FOR_TIMELINE; + let free = area + .height + .saturating_sub(HEADER_HEIGHT + stages.height() + footer::HEIGHT); let heights = Heights::share( - area.height.saturating_sub( - HEADER_HEIGHT + stages.height() + failures.height() + footer::HEIGHT, - ), - tree.height(), + free, + pruned.height(), if fits_timeline { timeline.height() } else { 0 }, ); + let budget = usize::from(heights.tree.saturating_sub(1)); + let whole_tree = fit_to_height(all_rows.clone(), usize::MAX); + let rows = [whole_tree.clone(), fold_chains(whole_tree)] + .into_iter() + .find(|rows| rows.len() <= budget) + .unwrap_or_else(|| fold_chains(fit_to_height(all_rows, budget))); + let tree = UnitTree { + rows: &rows, + hidden: pending_count - shown_units(&rows), + ..pruned + }; + let tree_height = tree.height().min(heights.tree); let [ header_area, - _, stage_area, tree_area, - failed_area, _, timeline_area, footer_area, ] = Layout::vertical([ - Constraint::Length(1), - Constraint::Length(HEADER_HEIGHT - 1), + Constraint::Length(HEADER_HEIGHT), Constraint::Length(stages.height()), - Constraint::Length(heights.tree), - Constraint::Length(failures.height()), + Constraint::Length(tree_height), Constraint::Fill(1), Constraint::Length(heights.timeline), Constraint::Length(footer::HEIGHT), @@ -155,7 +161,6 @@ impl Widget for BootView<'_> { header.render(header_area, buf); stages.render(stage_area, buf); tree.render(tree_area, buf); - failures.render(failed_area, buf); if heights.timeline > 0 { timeline.render(timeline_area, buf); } @@ -170,12 +175,6 @@ struct Heights { impl Heights { fn share(free: u16, tree_need: u16, timeline_need: u16) -> Self { - if tree_need.saturating_add(timeline_need) <= free { - return Self { - tree: tree_need, - timeline: timeline_need, - }; - } let timeline = timeline_need .min(free.saturating_sub(tree_need).max(MIN_TIMELINE_HEIGHT)) .min(free); @@ -193,6 +192,18 @@ fn rule(palette: &Palette, left: Line<'static>) -> Block<'static> { .title(left) } +fn shown_units(rows: &[TreeRow]) -> usize { + rows.iter().map(|row| 1 + row.chain.len()).sum() +} + +fn fit_width(text: &str, room: usize, ellipsis: &str) -> String { + if text.width() <= room { + return text.to_owned(); + } + let (kept, _) = text.unicode_truncate(room.saturating_sub(ellipsis.width())); + format!("{kept}{ellipsis}") +} + fn unit_count(count: usize) -> String { match count { 1 => "1 unit".to_owned(), @@ -228,7 +239,12 @@ mod tests { palette: &Palette::default(), glyphs: &Glyphs::default(), now, - host: "ryzen", + origin: &BootOrigin { + host: "ryzen".to_owned(), + system: "NixOS 26.11".to_owned(), + generation: "2771".to_owned(), + kernel: "Linux 7.2.9".to_owned(), + }, frame: 1, }, frame.area(), @@ -297,18 +313,24 @@ mod tests { fn tree_on_top_timeline_below() { let lines = render(&boot_in_progress(), 12_400 * MS, 110, 24); let screen = lines.join("\n"); - assert_eq!(lines[0], "bootvine ryzen", "{screen}"); - assert!(lines[2].starts_with("── stage 2 ──"), "{screen}"); - assert!(lines[2].ends_with("12.4s ──"), "{screen}"); - assert!(lines[3].starts_with("graphical.target"), "{screen}"); - assert!(lines[4].starts_with("└─ multi-user.target"), "{screen}"); - assert!(lines[5].starts_with(" ├─ [/] systemd-rfkill"), "{screen}"); - assert!(lines[6].starts_with(" └─ [/] docker"), "{screen}"); - assert!(lines[7].starts_with("… 1 more"), "{screen}"); - assert!( - lines[8].starts_with("× nvidia-powerd.service failed"), + assert_eq!( + lines[0], "ryzen · NixOS 26.11 · generation 2771 · Linux 7.2.9", "{screen}" ); + assert!(lines[1].starts_with("└─ stage 2 12.4s"), "{screen}"); + assert!(lines[1].ends_with("running"), "{screen}"); + assert!( + lines[2].starts_with(" ├─ ◆ multi-user.target"), + "{screen}" + ); + assert!( + lines[3].starts_with(" │ ├─ [/] systemd-rfkill"), + "{screen}" + ); + assert!(lines[4].starts_with(" │ ├─ [/] docker"), "{screen}"); + assert!(lines[5].starts_with(" │ └─ [ ] web"), "{screen}"); + assert!(lines[6].starts_with(" ├─ ◇ graphical.target"), "{screen}"); + assert!(lines[7].starts_with(" └─ [×] nvidia-powerd"), "{screen}"); let timeline = lines .iter() .position(|line| line.contains(" timeline ")) @@ -343,15 +365,46 @@ mod tests { ); } + #[test] + fn failures_stay_in_the_stage_that_wanted_them() { + let mut state = BootState::new(Phase::Host); + state.set_root("multi-user.target".to_owned()); + [ + facts("multi-user.target", &["basic.target", "web.service"]), + facts("basic.target", &["flaky.service", "quick.service"]), + facts("flaky.service", &[]), + facts("quick.service", &[]), + facts("web.service", &[]), + ] + .into_iter() + .zip(1..) + .for_each(|(unit, id)| { + let name = unit.name.clone(); + state.track_unit(unit, Activity::default()); + state.queue_job(id, &name, JobKind::BringsUp, Duration::ZERO); + }); + state.finish_job(3, JobResult::Failed, 1000 * MS); + state.finish_job(4, JobResult::Done, 1000 * MS); + state.finish_job(2, JobResult::Done, 1500 * MS); + let lines = render(&state, 3000 * MS, 110, 24); + let screen = lines.join("\n"); + assert!(lines[2].starts_with(" ├─ √ basic.target"), "{screen}"); + assert!(lines[3].starts_with(" │ └─ [×] flaky"), "{screen}"); + assert!( + lines[4].starts_with(" └─ ◆ multi-user.target"), + "{screen}" + ); + assert!(lines[5].starts_with(" └─ [ ] web"), "{screen}"); + assert!(!screen.contains("quick"), "{screen}"); + } + #[test] fn only_running_units_carry_a_timer() { let lines = render(&boot_in_progress(), 12_400 * MS, 110, 24); let screen = lines.join("\n"); - assert!( - lines[3].trim_end().ends_with("graphical.target"), - "{screen}" - ); - assert!(lines[5].ends_with("6.4s"), "{screen}"); + assert!(lines[2].ends_with("multi-user.target"), "{screen}"); + assert!(lines[3].ends_with("6.4s"), "{screen}"); + assert!(lines[5].ends_with("web"), "{screen}"); } #[test] @@ -368,24 +421,22 @@ mod tests { ); } - #[test] - fn folded_chains_shorten_to_their_ends_when_narrow() { - let mut state = BootState::new(Phase::Shutdown); - state.set_root("poweroff.target".to_owned()); + fn chain_boot() -> BootState { + let mut state = BootState::new(Phase::Host); + state.set_root("graphical.target".to_owned()); [ - ("poweroff.target", "systemd-poweroff.service"), - ("systemd-poweroff.service", "final.target"), - ("final.target", "shutdown.target"), - ("shutdown.target", "local-fs.target"), - ("local-fs.target", "demo-disk.service"), - ("demo-disk.service", "demo-db.service"), - ("demo-db.service", ""), + ("graphical.target", "network-wait.service"), + ("network-wait.service", "network.target"), + ("network.target", "network-manager.service"), + ("network-manager.service", "dbus.service"), + ("dbus.service", "udev-settle.service"), + ("udev-settle.service", ""), ] .into_iter() .zip(1..) .for_each(|((name, waits_on), id)| { let after: Vec<&str> = [waits_on].into_iter().filter(|w| !w.is_empty()).collect(); - let activity = if name == "demo-db.service" { + let activity = if name == "udev-settle.service" { running_since(1000 * MS) } else { Activity::default() @@ -393,37 +444,168 @@ mod tests { state.track_unit(facts(name, &after), activity); state.queue_job(id, name, JobKind::BringsUp, Duration::ZERO); }); - let wide = render(&state, 5000 * MS, 110, 24); + state + } + + #[test] + fn chains_stay_unfolded_while_they_fit() { + let lines = render(&chain_boot(), 5000 * MS, 110, 24); + let screen = lines.join("\n"); assert!( - wide[4].starts_with( - "└─ [ ] systemd-poweroff ─ final.target ─ shutdown.target ─ local-fs.target ─ \ - demo-disk" - ), - "{}", - wide.join("\n") + lines[3].starts_with(" └─ [ ] network-wait"), + "{screen}" ); assert!( - wide[5].starts_with(" └─ [/] demo-db"), - "{}", - wide.join("\n") + lines[4].starts_with(" └─ network.target"), + "{screen}" ); - let narrow = render(&state, 5000 * MS, 60, 24); assert!( - narrow[4].starts_with("└─ [ ] systemd-poweroff ─ … ─ demo-disk"), + lines[7].starts_with(" └─ [/] udev-settle"), + "{screen}" + ); + } + + #[test] + fn chains_fold_when_short_and_shorten_to_their_ends_when_narrow() { + let short = render(&chain_boot(), 5000 * MS, 110, 13); + assert!( + short[3] + .starts_with(" └─ [ ] network-wait ─ network.target ─ network-manager ─ dbus"), + "{}", + short.join("\n") + ); + assert!( + short[4].starts_with(" └─ [/] udev-settle"), + "{}", + short.join("\n") + ); + let narrow = render(&chain_boot(), 5000 * MS, 45, 8); + assert!( + narrow[3].starts_with(" └─ [ ] network-wait ─ … ─ dbus"), "{}", narrow.join("\n") ); } + fn described_boot() -> BootState { + let mut state = BootState::new(Phase::Host); + state.set_root("multi-user.target".to_owned()); + [ + ( + "multi-user.target", + "Multi-User System", + &["docker.service", "systemd-rfkill.service"][..], + ), + ("docker.service", "Docker Application Container Engine", &[]), + ( + "systemd-rfkill.service", + "Load/Save RF Kill Switch Status", + &[], + ), + ] + .into_iter() + .zip(1..) + .for_each(|((name, description, after), id)| { + state.track_unit( + UnitFacts { + description: description.to_owned(), + ..facts(name, after) + }, + running_since(1000 * MS), + ); + state.queue_job(id, name, JobKind::BringsUp, Duration::ZERO); + }); + state + } + + #[test] + fn descriptions_line_up_in_a_column() { + let lines = render(&described_boot(), 3000 * MS, 110, 24); + let screen = lines.join("\n"); + let column_of = |text: &str| { + lines + .iter() + .find_map(|line| line.find(text).map(|at| line[..at].width())) + .unwrap_or_else(|| panic!("{text} missing\n{screen}")) + }; + assert_eq!(column_of("Multi-User System"), column_of("description")); + assert_eq!( + column_of("Multi-User System"), + column_of("Docker Application") + ); + assert_eq!( + column_of("Multi-User System"), + column_of("Load/Save RF Kill") + ); + assert!(column_of("Multi-User System") > column_of("systemd-rfkill")); + } + + #[test] + fn non_service_units_carry_their_kind() { + let mut state = described_boot(); + state.track_unit( + UnitFacts { + description: "Docker Socket for the API".to_owned(), + ..facts("docker.socket", &[]) + }, + running_since(1000 * MS), + ); + state.queue_job(9, "docker.socket", JobKind::BringsUp, Duration::ZERO); + let lines = render(&state, 3000 * MS, 110, 24); + let screen = lines.join("\n"); + let socket_row = lines + .iter() + .find(|line| line.contains("Docker Socket")) + .unwrap_or_else(|| panic!("{screen}")); + assert!(socket_row.contains("[/] docker "), "{screen}"); + assert!(socket_row.contains(" socket "), "{screen}"); + assert!( + render(&described_boot(), 3000 * MS, 110, 24) + .iter() + .all(|line| !line.contains(" socket ")), + "{screen}" + ); + } + + #[test] + fn narrow_screens_keep_names_and_drop_descriptions() { + let lines = render(&described_boot(), 3000 * MS, 40, 24); + let screen = lines.join("\n"); + assert!(screen.contains("systemd-rfkill"), "{screen}"); + assert!(!screen.contains("Docker"), "{screen}"); + } + + #[test] + fn long_timeline_labels_end_in_an_ellipsis() { + let mut state = boot_in_progress(); + state.track_unit( + UnitFacts { + description: "Kernel Configuration File System".to_owned(), + ..facts("sys-kernel-config.mount", &[]) + }, + running_since(2000 * MS), + ); + state.queue_job(30, "sys-kernel-config.mount", JobKind::BringsUp, 2000 * MS); + state.finish_job(30, JobResult::Done, 4000 * MS); + let lines = render(&state, 12_400 * MS, 110, 24); + assert!( + lines + .iter() + .any(|line| line.starts_with("√ Kernel Configuration File…")), + "{}", + lines.join("\n") + ); + } + #[test] fn narrow_screens_drop_the_timeline() { - let lines = render(&boot_in_progress(), 12_400 * MS, 36, 24); + let lines = render(&boot_in_progress(), 12_400 * MS, 40, 24); assert!( lines.iter().all(|line| !line.contains('■')), "{}", lines.join("\n") ); - assert!(lines[5].contains("systemd-rfkill")); + assert!(lines[3].contains("systemd-rfkill"), "{}", lines.join("\n")); } #[test] @@ -441,12 +623,11 @@ mod tests { let screen = lines.join("\n"); assert!(lines[0].ends_with("17.3s"), "{screen}"); assert!( - lines[2].starts_with("── initrd ── ■ done in 7.2s · 1 unit ──"), + lines[1].starts_with("├─ initrd ■ done in 7.2s · 1 unit"), "{screen}" ); - assert!(lines[3].starts_with("── stage 2 ──"), "{screen}"); - assert!(lines[3].ends_with("10.1s ──"), "{screen}"); - assert!(lines[4].starts_with("graphical.target"), "{screen}"); + assert!(lines[2].starts_with("└─ stage 2 10.1s"), "{screen}"); + assert!(lines[3].starts_with(" └─ ◆ graphical.target"), "{screen}"); let timeline = lines .iter() .position(|line| line.contains(" timeline ")) @@ -474,8 +655,8 @@ mod tests { state.finish_job(1, JobResult::Done, 9000 * MS); let lines = render(&state, 9500 * MS, 110, 24); assert!( - lines[2].starts_with( - "── ■ boot finished in 9.5s · handing over to display-manager.service ──" + lines[1].starts_with( + "└─ ■ boot finished in 9.5s · handing over to display-manager.service" ), "{}", lines.join("\n") @@ -491,7 +672,7 @@ mod tests { state.queue_job(1, "poweroff.target", JobKind::BringsUp, 20_000 * MS); let lines = render(&state, 21_500 * MS, 110, 24); assert!( - lines[2].starts_with("── shutdown ─") && lines[2].ends_with(" 1.5s ──"), + lines[1].starts_with("└─ shutdown 1.5s") && lines[1].ends_with("running"), "{}", lines.join("\n") ); @@ -504,9 +685,8 @@ mod tests { state.manager_exited_at = Some(24_200 * MS); let lines = render(&state, 30_000 * MS, 110, 24); assert!( - lines[2].starts_with( - "── ■ shutdown finished in 4.2s · handing over to systemd-shutdown ──" - ), + lines[1] + .starts_with("└─ ■ shutdown finished in 4.2s · handing over to systemd-shutdown"), "{}", lines.join("\n") ); @@ -531,7 +711,7 @@ mod tests { }); let lines = render(&state, 1000 * MS, 110, 20); assert!( - lines.iter().any(|line| line.starts_with("… ")), + lines.iter().any(|line| line.starts_with(" … ")), "{}", lines.join("\n") ); diff --git a/src/view/failures.rs b/src/view/failures.rs deleted file mode 100644 index 383acd3..0000000 --- a/src/view/failures.rs +++ /dev/null @@ -1,40 +0,0 @@ -use ratatui::{ - buffer::Buffer, - layout::Rect, - style::Stylize, - text::Line, - widgets::{Paragraph, Widget}, -}; - -use crate::{glyphs::Glyphs, palette::Palette}; - -const MAX_ROWS: usize = 3; - -pub struct Failures<'a> { - pub units: &'a [String], - pub palette: &'a Palette, - pub glyphs: &'a Glyphs, -} - -impl Failures<'_> { - pub fn height(&self) -> u16 { - u16::try_from(self.lines().len()).unwrap_or(u16::MAX) - } - - fn lines(&self) -> Vec> { - let hidden = self.units.len().saturating_sub(MAX_ROWS); - self.units - .iter() - .take(MAX_ROWS) - .map(|unit| format!("{} {unit} failed", self.glyphs.failed)) - .chain((hidden > 0).then(|| format!("{} {hidden} more failed", self.glyphs.failed))) - .map(|text| Line::from(text).fg(self.palette.failed).bold()) - .collect() - } -} - -impl Widget for Failures<'_> { - fn render(self, area: Rect, buf: &mut Buffer) { - Paragraph::new(self.lines()).render(area, buf); - } -} diff --git a/src/view/header.rs b/src/view/header.rs index 707ed90..058cf3d 100644 --- a/src/view/header.rs +++ b/src/view/header.rs @@ -1,22 +1,42 @@ -use std::time::Duration; +use std::{iter::once, time::Duration}; use ratatui::{ buffer::Buffer, layout::{Constraint, Rect}, style::Stylize, - text::Line, + text::{Line, Span}, widgets::{Row, Table, Widget}, }; use super::{DURATION_WIDTH, ELAPSED}; -use crate::palette::Palette; +use crate::{origin::BootOrigin, palette::Palette}; + +const SEPARATOR: &str = " · "; pub struct Header<'a> { - pub host: &'a str, + pub origin: &'a BootOrigin, pub total: Option, pub palette: &'a Palette, } +impl Header<'_> { + fn origin(&self) -> Line<'static> { + Line::from( + self.origin + .parts() + .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 part = if index == 0 { part.bold() } else { part }; + separator.into_iter().chain(once(part)) + }) + .collect::>(), + ) + } +} + impl Widget for Header<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let total = self @@ -25,13 +45,14 @@ impl Widget for Header<'_> { .unwrap_or_default(); Table::new( [Row::new([ - Line::from(format!("bootvine {}", self.host)), - Line::from(total).right_aligned(), + self.origin(), + Line::from(total) + .fg(self.palette.text) + .bold() + .right_aligned(), ])], [Constraint::Fill(1), Constraint::Length(DURATION_WIDTH)], ) - .fg(self.palette.text) - .bold() .render(area, buf); } } diff --git a/src/view/stages.rs b/src/view/stages.rs index 1bdb02e..3be765e 100644 --- a/src/view/stages.rs +++ b/src/view/stages.rs @@ -1,17 +1,18 @@ -use std::{iter::once, time::Duration}; +use std::time::Duration; use ratatui::{ buffer::Buffer, layout::Rect, style::Stylize, - text::Line, - widgets::{Block, Widget}, + text::{Line, Span}, + widgets::{Paragraph, Widget}, }; -use super::{ELAPSED, RULE_STUB, rule, unit_count}; +use super::{BRANCH, ELAPSED, LAST_BRANCH, unit_count}; use crate::{glyphs::Glyphs, model::BootState, palette::Palette}; const SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown"; +const PHASE_WIDTH: usize = 9; pub struct Stages<'a> { pub state: &'a BootState, @@ -28,7 +29,7 @@ struct Conclusion<'a> { impl Stages<'_> { pub fn height(&self) -> u16 { - u16::try_from(self.state.finished_stages.len() + 1).unwrap_or(u16::MAX) + u16::try_from(self.lines().len()).unwrap_or(u16::MAX) } fn conclusion(&self) -> Option> { @@ -51,78 +52,72 @@ impl Stages<'_> { }) } - fn finished_rules(&self) -> impl Iterator> + '_ { + fn finished_phases(&self) -> impl Iterator> + '_ { self.state.finished_stages.iter().map(|stage| { - rule( - self.palette, - Line::from(vec![ - format!("{RULE_STUB} {} {RULE_STUB} ", stage.label).fg(self.palette.muted), - format!( - "{} done in {}", - self.glyphs.bead, - ELAPSED.unsigned_duration_to_string( - &stage.reached_at.saturating_sub(stage.started_at) - ) + Line::from(vec![ + BRANCH.fg(self.palette.muted), + format!("{:PHASE_WIDTH$}", stage.label).fg(self.palette.waiting), + format!( + "{} done in {}", + self.glyphs.bead, + ELAPSED.unsigned_duration_to_string( + &stage.reached_at.saturating_sub(stage.started_at) ) - .fg(self.palette.done), - format!(" · {} ", unit_count(stage.finished_units)).fg(self.palette.waiting), - ]), - ) + ) + .fg(self.palette.done), + format!(" · {}", unit_count(stage.finished_units)).fg(self.palette.waiting), + if stage.failed_units > 0 { + format!(" · {} {} failed", self.glyphs.failed, stage.failed_units) + .fg(self.palette.failed) + .bold() + } else { + Span::default() + }, + ]) }) } - fn concluded_rule(&self, conclusion: &Conclusion) -> Block<'static> { - rule( - self.palette, - Line::from(vec![ - format!("{RULE_STUB} ").fg(self.palette.muted), - format!( - "{} {} finished in {}", - self.glyphs.bead, - conclusion.finished, - ELAPSED.unsigned_duration_to_string(&conclusion.took) - ) - .fg(self.palette.done) - .bold(), - format!(" · handing over to {} ", conclusion.handed_to).fg(self.palette.text), - ]), - ) + fn concluded_phase(&self, conclusion: &Conclusion) -> Line<'static> { + Line::from(vec![ + LAST_BRANCH.fg(self.palette.muted), + format!( + "{} {} finished in {}", + self.glyphs.bead, + conclusion.finished, + ELAPSED.unsigned_duration_to_string(&conclusion.took) + ) + .fg(self.palette.done) + .bold(), + format!(" · handing over to {}", conclusion.handed_to).fg(self.palette.text), + ]) } - fn current_rule(&self) -> Block<'static> { + pub fn current_phase(&self) -> Line<'static> { + if let Some(conclusion) = self.conclusion() { + return self.concluded_phase(&conclusion); + } let started_at = self .state .finished_stages .last() .map_or(self.state.origin, |stage| stage.reached_at); let elapsed = ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(started_at)); - rule( - self.palette, - Line::from(vec![ - format!("{RULE_STUB} ").fg(self.palette.muted), - self.state.phase.label().fg(self.palette.text).bold(), - " ".into(), - ]), - ) - .title( - Line::from(vec![ - " ".into(), - elapsed.fg(self.palette.text).bold(), - format!(" {RULE_STUB}").fg(self.palette.muted), - ]) - .right_aligned(), - ) + Line::from(vec![ + LAST_BRANCH.fg(self.palette.muted), + format!("{:PHASE_WIDTH$}", self.state.phase.label()) + .fg(self.palette.text) + .bold(), + elapsed.fg(self.palette.text), + ]) + } + + fn lines(&self) -> Vec> { + self.finished_phases().collect() } } impl Widget for Stages<'_> { fn render(self, area: Rect, buf: &mut Buffer) { - let last = self.conclusion().map_or_else( - || self.current_rule(), - |conclusion| self.concluded_rule(&conclusion), - ); - area.rows() - .zip(self.finished_rules().chain(once(last))) - .for_each(|(row, rule)| rule.render(row, buf)); + Paragraph::new(self.lines()).render(area, buf); } } diff --git a/src/view/timeline.rs b/src/view/timeline.rs index a94baa2..c62bd32 100644 --- a/src/view/timeline.rs +++ b/src/view/timeline.rs @@ -13,15 +13,16 @@ use ratatui::{ widgets::{Row, Table, Widget}, }; -use super::{rule, unit_count}; +use super::{fit_width, rule, unit_count}; use crate::{ glyphs::Glyphs, - model::{FinishedRun, MilestoneRow, PendingRow}, + model::{FinishedRun, MilestoneRow, TreeRow}, palette::Palette, }; pub const LABEL_WIDTH: u16 = 28; pub const CHROME_HEIGHT: u16 = 3; +const MARK_WIDTH: u16 = 2; const KERNEL_ORIGIN_LABEL: &str = "kernel"; const AXIS_LABEL_SPACING: u16 = 8; const AXIS_STEPS: [Duration; 12] = [ @@ -48,7 +49,7 @@ pub struct Timeline<'a> { pub root_switches: Vec, pub milestones: Vec, pub finished: Vec<&'a FinishedRun>, - pub running: Vec<&'a PendingRow>, + pub running: Vec<&'a TreeRow>, pub palette: &'a Palette, pub glyphs: &'a Glyphs, } @@ -112,7 +113,7 @@ impl Timeline<'_> { TimelineEntry { label: Line::from(vec![ Span::styled(format!("{mark} "), outcome), - run.label.as_str().fg(self.palette.waiting), + self.fitted(&run.label).fg(self.palette.waiting), ]), segments: vec![Segment { from: run.started_at, @@ -124,7 +125,15 @@ impl Timeline<'_> { } } - fn running_entry<'a>(&self, row: &'a PendingRow) -> TimelineEntry<'a> { + fn fitted(&self, label: &str) -> String { + fit_width( + label, + usize::from(LABEL_WIDTH - MARK_WIDTH), + self.glyphs.ellipsis, + ) + } + + fn running_entry<'a>(&self, row: &'a TreeRow) -> TimelineEntry<'a> { let since = row.running_since.unwrap_or(row.queued_at); let waited = (since > row.queued_at).then(|| Segment { from: row.queued_at, @@ -141,7 +150,7 @@ impl Timeline<'_> { TimelineEntry { label: Line::from(vec![ format!("{} ", self.glyphs.running_mark).fg(self.palette.running), - row.label.as_str().fg(self.palette.text), + self.fitted(&row.label).fg(self.palette.text), ]), segments: waited.into_iter().chain(once(ran)).collect(), still_going_at: Some(self.now), diff --git a/src/view/tree.rs b/src/view/tree.rs index 89c4a13..0507121 100644 --- a/src/view/tree.rs +++ b/src/view/tree.rs @@ -3,129 +3,289 @@ use std::{iter::once, time::Duration}; use ratatui::{ buffer::Buffer, layout::{Constraint, Rect}, - style::{Color, Stylize}, + style::{Style, Stylize}, text::{Line, Span}, widgets::{Row, Table, Widget}, }; +use unicode_width::UnicodeWidthStr; -use super::{DURATION_WIDTH, ELAPSED, NOTEWORTHY_DURATION}; +use super::{ + BRANCH, DURATION_WIDTH, ELAPSED, ENDED_TRUNK, LAST_BRANCH, NOTEWORTHY_DURATION, PASSING_TRUNK, + fit_width, +}; use crate::{ glyphs::Glyphs, - model::{PendingRow, RowStatus}, + model::{RowStatus, TreeRow, UnitKind}, palette::Palette, }; const SPINNER: [char; 4] = ['|', '/', '-', '\\']; +const DESCRIPTION_GAP: u16 = 1; +const MIN_DESCRIPTION_WIDTH: u16 = 12; +const HEADER_ROWS: u16 = 1; -pub struct PendingTree<'a> { - pub rows: &'a [PendingRow], - pub folded: usize, +pub struct UnitTree<'a> { + pub phase: Line<'static>, + pub rows: &'a [TreeRow], + pub hidden: usize, pub now: Duration, pub frame: u64, pub palette: &'a Palette, pub glyphs: &'a Glyphs, } -impl PendingTree<'_> { +struct Columns { + label: u16, + tag: u16, + description: u16, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Stage { + Reached, + Current, + Upcoming, + Inside, +} + +fn opens_a_stage(row: &TreeRow) -> bool { + row.depth == 0 && row.kind == UnitKind::Target +} + +fn width_of(text: &str) -> u16 { + u16::try_from(text.width()).unwrap_or(u16::MAX) +} + +impl UnitTree<'_> { pub fn height(&self) -> u16 { - u16::try_from(self.rows.len() + usize::from(self.folded > 0)).unwrap_or(u16::MAX) + u16::try_from(self.rows.len() + usize::from(self.hidden > 0)) + .unwrap_or(u16::MAX) + .saturating_add(HEADER_ROWS) } - fn label_color(&self, row: &PendingRow) -> Color { - if row.is_target { - return self.palette.target; + fn phase_fits_its_column(&self, columns: &Columns) -> bool { + self.phase.width() <= usize::from(columns.label) + } + + fn header(&self, columns: &Columns) -> Row<'static> { + if !self.phase_fits_its_column(columns) { + return Row::default().height(HEADER_ROWS); } - match row.status { - RowStatus::Running => self.palette.text, - RowStatus::Waiting => self.palette.waiting, + let name = |text: &'static str| Line::from(text).fg(self.palette.muted); + Row::new(columns.shown([ + self.phase.clone(), + name("kind"), + name("description"), + name("running").right_aligned(), + ])) + } + + fn stages(&self) -> impl Iterator + '_ { + let current = self + .rows + .iter() + .position(|row| opens_a_stage(row) && row.status != RowStatus::Done); + self.rows.iter().enumerate().map(move |(index, row)| { + if Some(index) == current { + Stage::Current + } else if opens_a_stage(row) && row.status == RowStatus::Done { + Stage::Reached + } else if opens_a_stage(row) { + Stage::Upcoming + } else { + Stage::Inside + } + }) + } + + 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 | RowStatus::Done) => self.palette.waiting.into(), } } - fn status_marker(&self, row: &PendingRow) -> Span<'static> { - if row.is_target { - return Span::default(); - } - match row.status { - RowStatus::Running => { + 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) + } + (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) => { let spinner = SPINNER[usize::try_from(self.frame % 4).unwrap_or_default()]; format!("[{spinner}] ").fg(self.palette.running) } - RowStatus::Waiting => "[ ] ".fg(self.palette.waiting), + (_, _, RowStatus::Waiting) => "[ ] ".fg(self.palette.waiting), + (_, _, RowStatus::Done) => format!("[{}] ", self.glyphs.done).fg(self.palette.done), } } - fn chained_label(&self, row: &PendingRow, room: usize) -> String { + fn lead_width(&self, row: &TreeRow, stage: Stage) -> usize { + tree_prefix(row).width() + self.status_marker(row, stage).width() + } + + fn chained_label(&self, row: &TreeRow, room: usize) -> String { let link = format!(" {} ", self.glyphs.chain_link); - let Some(last) = row.chain.last() else { - return row.label.clone(); - }; let full: String = once(row.label.as_str()) .chain(row.chain.iter().map(String::as_str)) .collect::>() .join(&link); - if full.chars().count() <= room || row.chain.len() == 1 { - return full; - } - format!("{}{link}{}{link}{last}", row.label, self.glyphs.ellipsis) + let label = match row.chain.as_slice() { + [_, .., last] if full.width() > room => { + format!("{}{link}{}{link}{last}", row.label, self.glyphs.ellipsis) + } + _ => full, + }; + fit_width(&label, room, self.glyphs.ellipsis) } - fn row(&self, row: &PendingRow, label_room: usize) -> Row<'static> { + fn columns(&self, width: u16) -> Columns { + let unannotated = width.saturating_sub(DURATION_WIDTH + 1); + let annotated: Vec<(&TreeRow, Stage)> = self + .rows + .iter() + .zip(self.stages()) + .filter(|(row, _)| { + row.chain.is_empty() && !(row.description.is_empty() && row.kind.tag().is_empty()) + }) + .collect(); + let tag = annotated + .iter() + .map(|(row, _)| width_of(row.kind.tag())) + .max() + .unwrap_or_default(); + let content = unannotated.saturating_sub(1 + u16::from(tag > 0)); + let label = annotated + .iter() + .map(|(row, stage)| { + width_of(&row.label) + .saturating_add(u16::try_from(self.lead_width(row, *stage)).unwrap_or(u16::MAX)) + }) + .max() + .map(|widest| widest.saturating_add(DESCRIPTION_GAP)) + .filter(|widest| widest.saturating_add(tag + MIN_DESCRIPTION_WIDTH) <= content); + label.map_or( + Columns { + label: unannotated, + tag: 0, + description: 0, + }, + |label| Columns { + label, + tag, + description: content - label - tag, + }, + ) + } + + fn row(&self, row: &TreeRow, stage: Stage, columns: &Columns) -> Row<'static> { let prefix = tree_prefix(row); - let marker = self.status_marker(row); - let room = label_room.saturating_sub(prefix.chars().count() + marker.width()); + let marker = self.status_marker(row, stage); + let room = usize::from(columns.label).saturating_sub(self.lead_width(row, stage)); + let annotation = |text: &str, width: u16| { + if row.chain.is_empty() { + fit_width(text, usize::from(width), self.glyphs.ellipsis) + } else { + String::new() + } + }; let timer = row .running_since .map(|since| self.now.saturating_sub(since)) .filter(|running_for| *running_for >= NOTEWORTHY_DURATION) .map(|running_for| ELAPSED.unsigned_duration_to_string(&running_for)) .unwrap_or_default(); - let color = self.label_color(row); - Row::new([ + let style = self.label_style(row, stage); + Row::new(columns.shown([ Line::from(vec![ prefix.fg(self.palette.muted), marker, - self.chained_label(row, room).fg(color), + Span::styled(self.chained_label(row, room), style), ]), - Line::from(timer).fg(color).right_aligned(), - ]) + 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(timer).style(style).right_aligned(), + ])) } } -impl Widget for PendingTree<'_> { +impl Columns { + fn shown(&self, cells: [T; 4]) -> impl Iterator { + let present = [true, self.tag > 0, self.description > 0, true]; + cells + .into_iter() + .zip(present) + .filter_map(|(cell, present)| present.then_some(cell)) + } + + fn widths(&self) -> impl Iterator { + self.shown([self.label, self.tag, self.description, DURATION_WIDTH]) + .map(Constraint::Length) + } +} + +impl Widget for UnitTree<'_> { fn render(self, area: Rect, buf: &mut Buffer) { - let capacity = usize::from(area.height); - let label_room = usize::from(area.width.saturating_sub(DURATION_WIDTH + 1)); - let shown = if usize::from(self.height()) > capacity { + let capacity = usize::from(area.height.saturating_sub(HEADER_ROWS)); + let shown = if usize::from(self.height() - HEADER_ROWS) > capacity { capacity.saturating_sub(1).min(self.rows.len()) } else { self.rows.len() }; - let hidden = self.rows.len() - shown + self.folded; + let hidden = self.rows.len() - shown + self.hidden; let overflow = (hidden > 0).then(|| { - Row::new([format!("{} {hidden} more", self.glyphs.ellipsis).fg(self.palette.waiting)]) + Row::new([ + format!("{ENDED_TRUNK}{} {hidden} more", self.glyphs.ellipsis) + .fg(self.palette.waiting), + ]) }); + let columns = self.columns(area.width); Table::new( self.rows .iter() + .zip(self.stages()) .take(shown) - .map(|row| self.row(row, label_room)) + .map(|(row, stage)| self.row(row, stage, &columns)) .chain(overflow), - [Constraint::Fill(1), Constraint::Length(DURATION_WIDTH)], + columns.widths(), ) + .header(self.header(&columns)) .render(area, buf); + if !self.phase_fits_its_column(&columns) { + self.phase.render(Rect { height: 1, ..area }, buf); + } } } -fn tree_prefix(row: &PendingRow) -> String { +fn tree_prefix(row: &TreeRow) -> String { let ancestors = row .is_last_sibling .iter() - .skip(1) - .take(row.depth.saturating_sub(1)) - .map(|ancestor_is_last| if *ancestor_is_last { " " } else { "│ " }); - let connector = (row.depth > 0).then(|| match row.is_last_sibling.last() { - Some(false) => "├─ ", - _ => "└─ ", - }); - ancestors.chain(connector).chain(once("")).collect() + .take(row.depth) + .map(|ancestor_is_last| { + if *ancestor_is_last { + ENDED_TRUNK + } else { + PASSING_TRUNK + } + }); + let connector = match row.is_last_sibling.last() { + Some(false) => BRANCH, + _ => LAST_BRANCH, + }; + once(ENDED_TRUNK) + .chain(ancestors) + .chain(once(connector)) + .collect() }