feat: font-aware glyphs, quieter tree and timeline

This commit is contained in:
Willem Vanhulle committed 2026-10-11 20:16:16 +02:00
1 parent 1c8affc827
commit 329307b27c
17 files changed
+1306 -671

No files matched your search

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

+2
View File
@@ -5,6 +5,7 @@ use std::{
};
use bootvine::{
glyphs::Glyphs,
model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts},
palette::Palette,
view::BootView,
@@ -311,6 +312,7 @@ fn play(terminal: &mut DefaultTerminal) -> io::Result<()> {
BootView {
state: &state,
palette: &Palette::default(),
glyphs: &Glyphs::default(),
now: now(),
host: "demo",
frame,
+44 -2
View File
@@ -1,12 +1,13 @@
use std::fs;
use std::{collections::HashSet, fs, ptr};
use rustix::{
io::Errno,
ioctl::{Getter, IntegerSetter, Opcode, ioctl},
ioctl::{Getter, IntegerSetter, Opcode, Updater, ioctl},
stdio::stdin,
termios::ttyname,
};
const GIO_UNIMAP: Opcode = 0x4B66;
const VT_GETSTATE: Opcode = 0x5603;
const VT_ACTIVATE: Opcode = 0x5606;
const VT_WAITACTIVE: Opcode = 0x5607;
@@ -33,6 +34,47 @@ impl Drop for QuietKernelConsole {
}
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct UnicodePair {
unicode: u16,
_font_position: u16,
}
#[repr(C)]
struct UnicodeMap {
count: u16,
pairs: *mut UnicodePair,
}
fn read_unicode_map(map: &mut UnicodeMap) -> Result<(), Errno> {
unsafe { ioctl(stdin(), Updater::<GIO_UNIMAP, UnicodeMap>::new(map)) }
}
pub fn font_characters() -> Option<HashSet<char>> {
let mut probe = UnicodeMap {
count: 0,
pairs: ptr::null_mut(),
};
let _ = read_unicode_map(&mut probe);
if probe.count == 0 {
return None;
}
let mut pairs = vec![UnicodePair::default(); usize::from(probe.count)];
let mut map = UnicodeMap {
count: probe.count,
pairs: pairs.as_mut_ptr(),
};
read_unicode_map(&mut map).ok()?;
Some(
pairs
.iter()
.take(usize::from(map.count))
.filter_map(|pair| char::from_u32(u32::from(pair.unicode)))
.collect(),
)
}
#[repr(C)]
struct VtState {
active: u16,
+94
View File
@@ -0,0 +1,94 @@
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Glyphs {
pub done: char,
pub failed: char,
pub bead: char,
pub waiting_bead: char,
pub still_going: char,
pub running_mark: char,
pub root_switch_mark: char,
pub ellipsis: &'static str,
pub chain_link: &'static str,
}
const DONE: [char; 2] = ['√', '+'];
const FAILED: [char; 2] = ['×', 'x'];
const BEAD: [char; 2] = ['■', '#'];
const WAITING_BEAD: [char; 2] = ['·', '.'];
const STILL_GOING: [char; 2] = ['▶', '>'];
const RUNNING_MARK: [char; 3] = ['►', '▶', '>'];
const ROOT_SWITCH_MARK: [char; 2] = ['│', '|'];
const ELLIPSIS: [&str; 2] = ["…", "..."];
const CHAIN_LINK: [&str; 2] = ["→", "->"];
impl Default for Glyphs {
fn default() -> Self {
Self::fitting(|_| true)
}
}
impl Glyphs {
pub fn fitting(covers: impl Fn(char) -> bool) -> Self {
let symbol = |candidates: &[char]| {
candidates
.iter()
.copied()
.find(|candidate| covers(*candidate))
.unwrap_or(candidates[candidates.len() - 1])
};
let text = |candidates: &[&'static str]| {
candidates
.iter()
.copied()
.find(|candidate| candidate.chars().all(&covers))
.unwrap_or(candidates[candidates.len() - 1])
};
Self {
done: symbol(&DONE),
failed: symbol(&FAILED),
bead: symbol(&BEAD),
waiting_bead: symbol(&WAITING_BEAD),
still_going: symbol(&STILL_GOING),
running_mark: symbol(&RUNNING_MARK),
root_switch_mark: symbol(&ROOT_SWITCH_MARK),
ellipsis: text(&ELLIPSIS),
chain_link: text(&CHAIN_LINK),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const LAT2_TERMINUS16: &str = "×■●▶·•…│├└─━█▒░↑↓←→≥";
const DEFAULT8X16: &str = "√■○►▶·•│├└─▌▐█▓▒░▀▄↑↓←→≥";
fn covered_by(font: &'static str) -> impl Fn(char) -> bool {
move |symbol| symbol.is_ascii() || font.contains(symbol)
}
#[test]
fn a_font_without_the_square_root_and_pointer_falls_back() {
let glyphs = Glyphs::fitting(covered_by(LAT2_TERMINUS16));
assert_eq!(glyphs.done, '+');
assert_eq!(glyphs.running_mark, '▶');
assert_eq!(glyphs.failed, '×');
assert_eq!(glyphs.ellipsis, "…");
}
#[test]
fn the_built_in_kernel_font_loses_the_cross_and_ellipsis() {
let glyphs = Glyphs::fitting(covered_by(DEFAULT8X16));
assert_eq!(glyphs.done, '√');
assert_eq!(glyphs.failed, 'x');
assert_eq!(glyphs.ellipsis, "...");
assert_eq!(glyphs.chain_link, "→");
}
#[test]
fn full_unicode_keeps_every_preferred_glyph() {
let glyphs = Glyphs::default();
assert_eq!((glyphs.done, glyphs.running_mark), ('√', '►'));
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod glyphs;
pub mod model;
pub mod palette;
pub mod view;
+169 -5
View File
@@ -1,6 +1,8 @@
use std::{
collections::{HashMap, HashSet},
iter::{self, Peekable},
time::Duration,
vec::IntoIter,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -171,6 +173,7 @@ pub struct PendingRow {
pub status: RowStatus,
pub queued_at: Duration,
pub running_since: Option<Duration>,
pub chain: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -437,11 +440,17 @@ impl BootState {
..Tally::default()
};
self.units.values().fold(carried, |mut tally, record| {
match (record.job, record.running_since(), record.outcome) {
(Some(_), Some(_), _) => tally.running += 1,
(Some(_), None, _) => tally.waiting += 1,
(None, _, Some(Outcome::Succeeded { .. } | Outcome::Abandoned)) => tally.done += 1,
_ => {}
if record.job.is_some() {
if record.running_since().is_some() {
tally.running += 1;
} else {
tally.waiting += 1;
}
} else if matches!(
record.outcome,
Some(Outcome::Succeeded { .. } | Outcome::Abandoned)
) {
tally.done += 1;
}
tally
})
@@ -581,6 +590,7 @@ impl BootState {
},
queued_at: job.queued_at,
running_since,
chain: Vec::new(),
});
let candidates: Vec<&str> = self
.waits_for(unit, pending)
@@ -709,6 +719,78 @@ pub fn paths_to_running(rows: Vec<PendingRow>) -> Vec<PendingRow> {
relink_siblings(survivors)
}
const MIN_FOLDED_LINKS: usize = 2;
struct TreeNode {
row: PendingRow,
children: Vec<TreeNode>,
}
impl TreeNode {
fn is_chain_link(&self) -> bool {
self.row.status == RowStatus::Waiting && self.children.len() == 1
}
fn foldable_links(&self) -> usize {
let mut links = 0;
let mut cursor = self;
while cursor.is_chain_link() && cursor.children[0].is_chain_link() {
links += 1;
cursor = &cursor.children[0];
}
links
}
fn fold(mut self, may_absorb: bool) -> Self {
let links = if may_absorb { self.foldable_links() } else { 0 };
if links >= MIN_FOLDED_LINKS {
let (chain, below) = (0..links).fold(
(Vec::new(), self.children),
|(mut chain, mut children), _| {
let only = children.remove(0);
chain.push(only.row.label);
(chain, only.children)
},
);
self.row.chain = chain;
self.children = below;
}
self.children = self
.children
.into_iter()
.map(|child| child.fold(true))
.collect();
self
}
fn flatten_into(self, depth: usize, rows: &mut Vec<PendingRow>) {
rows.push(PendingRow { depth, ..self.row });
self.children
.into_iter()
.for_each(|child| child.flatten_into(depth + 1, rows));
}
}
fn grow_forest(rows: &mut Peekable<IntoIter<PendingRow>>, depth: usize) -> Vec<TreeNode> {
iter::from_fn(|| {
let row = rows.next_if(|row| row.depth == depth)?;
Some(TreeNode {
row,
children: grow_forest(rows, depth + 1),
})
})
.collect()
}
#[must_use]
pub fn fold_chains(rows: Vec<PendingRow>) -> Vec<PendingRow> {
let mut flattened = Vec::new();
grow_forest(&mut rows.into_iter().peekable(), 0)
.into_iter()
.for_each(|root| root.fold(false).flatten_into(0, &mut flattened));
relink_siblings(flattened)
}
fn relink_siblings(rows: Vec<PendingRow>) -> Vec<PendingRow> {
let mut later_sibling: Vec<bool> = Vec::new();
let mut is_last: Vec<bool> = rows
@@ -751,6 +833,8 @@ fn display_label(facts: &UnitFacts) -> String {
#[cfg(test)]
mod tests {
use std::iter::once;
use super::*;
const MS: Duration = Duration::from_millis(1);
@@ -855,6 +939,86 @@ mod tests {
assert_eq!(lasts, [true, true, false, true, true]);
}
fn chain_state(waits: &[(&str, &[&str])], running: &str) -> BootState {
let mut state = BootState::new(Phase::Host);
state.set_root(waits[0].0.to_owned());
waits.iter().zip(1..).for_each(|((name, after), id)| {
let activity = if *name == running {
activating(Duration::ZERO)
} else {
Activity::default()
};
state.track_unit(facts(name, after), activity);
state.queue_job(id, name, JobKind::BringsUp, Duration::ZERO);
});
state
}
fn folded_outline(state: &BootState) -> Vec<String> {
fold_chains(paths_to_running(state.pending_rows()))
.into_iter()
.map(|row| {
let chain = once(row.label.as_str())
.chain(row.chain.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" > ");
format!("{}{chain}", " ".repeat(row.depth))
})
.collect()
}
#[test]
fn single_child_waiting_chains_fold_into_one_row() {
let state = chain_state(
&[
("root.target", &["a.service"]),
("a.service", &["b.target"]),
("b.target", &["c.service"]),
("c.service", &["d.service"]),
("d.service", &[]),
],
"d.service",
);
assert_eq!(
folded_outline(&state),
["root.target", " a > b.target > c", " d"]
);
}
#[test]
fn branches_and_short_chains_stay_unfolded() {
let state = chain_state(
&[
("root.target", &["a.service"]),
("a.service", &["b.service", "c.service"]),
("b.service", &["d.service"]),
("c.service", &[]),
("d.service", &[]),
],
"d.service",
);
let mut both = chain_state(
&[
("root.target", &["a.service"]),
("a.service", &["b.service", "c.service"]),
("b.service", &[]),
("c.service", &[]),
],
"b.service",
);
both.update_activity("c.service", activating(Duration::ZERO));
assert_eq!(
folded_outline(&state),
["root.target", " a", " b", " d"]
);
let rows = fold_chains(paths_to_running(both.pending_rows()));
let lasts: Vec<bool> = rows
.iter()
.map(|row| *row.is_last_sibling.last().unwrap())
.collect();
assert_eq!(lasts, [true, true, false, true]);
}
#[test]
fn with_nothing_running_only_the_root_target_stays_in_view() {
let mut state = BootState::new(Phase::Host);
+8 -1
View File
@@ -9,6 +9,7 @@ use std::{
};
use bootvine::{
glyphs::Glyphs,
model::{BootState, Phase},
palette::Palette,
view::BootView,
@@ -24,7 +25,7 @@ use signal_hook::{consts::SIGTERM, flag};
use crate::{
clock::monotonic_now,
console::{ForegroundVt, QuietKernelConsole},
console::{ForegroundVt, QuietKernelConsole, font_characters},
error::Error,
feed::Feed,
sysroot::INITRD_RELEASE,
@@ -66,6 +67,9 @@ pub fn run(options: &Options) -> Result<(), Error> {
.then(QuietKernelConsole::take)
.flatten();
let _foreground = ForegroundVt::take();
let glyphs = font_characters().map_or_else(Glyphs::default, |characters| {
Glyphs::fitting(|symbol| symbol.is_ascii() || characters.contains(&symbol))
});
let mut terminal = ratatui::try_init()?;
let watched = watch(
&mut state,
@@ -73,6 +77,7 @@ pub fn run(options: &Options) -> Result<(), Error> {
&mut terminal,
&terminate,
&options.palette,
&glyphs,
options.hold,
);
ratatui::restore();
@@ -111,6 +116,7 @@ fn watch(
terminal: &mut DefaultTerminal,
terminate: &AtomicBool,
palette: &Palette,
glyphs: &Glyphs,
hold: Duration,
) -> Result<(), Error> {
let host = uname().nodename().to_string_lossy().into_owned();
@@ -126,6 +132,7 @@ fn watch(
BootView {
state,
palette,
glyphs,
now: monotonic_now(),
host: &host,
frame,
+23 -14
View File
@@ -273,12 +273,20 @@ fn parse_signal(message: &Message) -> Option<Signal> {
}
let interface = message.interface()?;
let member = message.member()?;
match (&*interface, &*member) {
(MANAGER_INTERFACE, "JobNew") => {
match &*interface {
MANAGER_INTERFACE => parse_job_signal(message, &member),
PROPERTIES_INTERFACE if &*member == "PropertiesChanged" => parse_unit_change(message),
_ => None,
}
}
fn parse_job_signal(message: &Message, member: &str) -> Option<Signal> {
match member {
"JobNew" => {
let (id, job, unit): (u32, Path<'static>, String) = message.read3().ok()?;
Some(Signal::JobNew { id, job, unit })
}
(MANAGER_INTERFACE, "JobRemoved") => {
"JobRemoved" => {
let (id, _job, _unit, result): (u32, Path<'static>, String, String) =
message.read4().ok()?;
Some(Signal::JobRemoved {
@@ -286,21 +294,22 @@ fn parse_signal(message: &Message) -> Option<Signal> {
result: JobResult::parse(&result),
})
}
(PROPERTIES_INTERFACE, "PropertiesChanged") => {
let (changed_interface, changed, _invalidated): (String, PropMap, Vec<String>) =
message.read3().ok()?;
if changed_interface != UNIT_INTERFACE {
return None;
}
Some(Signal::UnitChanged {
path: message.path()?.into_static(),
activity: activity_from(&changed),
})
}
_ => None,
}
}
fn parse_unit_change(message: &Message) -> Option<Signal> {
let (changed_interface, changed, _invalidated): (String, PropMap, Vec<String>) =
message.read3().ok()?;
if changed_interface != UNIT_INTERFACE {
return None;
}
Some(Signal::UnitChanged {
path: message.path()?.into_static(),
activity: activity_from(&changed),
})
}
fn activity_from(properties: &PropMap) -> Activity {
let monotonic = |property: &str| {
properties
+189 -649
View File
@@ -1,165 +1,168 @@
use std::{
cmp::Reverse,
iter::{once, repeat_n},
time::Duration,
};
mod failures;
mod footer;
mod header;
mod stages;
mod timeline;
mod tree;
use std::time::Duration;
use jiff::fmt::friendly::{Designator, FractionalUnit, Spacing, SpanPrinter};
use ratatui::{
buffer::Buffer,
layout::{Constraint, Layout, Rect},
style::{Style, Stylize},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Row, Table, Widget},
text::Line,
widgets::{Block, Borders, Widget},
};
use self::{
failures::Failures, footer::Footer, header::Header, stages::Stages, timeline::Timeline,
tree::PendingTree,
};
use crate::{
model::{BootState, FinishedRun, MilestoneRow, PendingRow, RowStatus, Tally, paths_to_running},
glyphs::Glyphs,
model::{BootState, PendingRow, RowStatus, fold_chains, paths_to_running},
palette::Palette,
};
const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
const DONE: char = '√';
const FAILED: char = '×';
const BEAD: char = '■';
const WAITING_BEAD: char = '·';
const STILL_GOING: char = '▶';
const RUNNING_MARK: char = '►';
const ROOT_SWITCH_MARK: char = '│';
const RULE: char = '─';
const RULE_STUB: &str = "──";
const KERNEL_ORIGIN_LABEL: &str = "kernel";
const SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown";
const DURATION_WIDTH: u16 = 8;
const TIMELINE_LABEL_WIDTH: u16 = 28;
const MIN_BAR_WIDTH: u16 = 12;
const MIN_HEIGHT_FOR_TIMELINE: u16 = 12;
const TIMELINE_CHROME_HEIGHT: u16 = 3;
const MIN_TIMELINE_HEIGHT: u16 = TIMELINE_CHROME_HEIGHT + 4;
const MIN_TIMELINE_HEIGHT: u16 = timeline::CHROME_HEIGHT + 4;
const NOTEWORTHY_DURATION: Duration = Duration::from_secs(1);
const HEADER_HEIGHT: u16 = 2;
const FOOTER_HEIGHT: u16 = 2;
const MAX_FAILED_ROWS: usize = 3;
const AXIS_LABEL_SPACING: u16 = 8;
const AXIS_STEPS: [Duration; 12] = [
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(5),
Duration::from_secs(10),
Duration::from_secs(15),
Duration::from_secs(30),
Duration::from_mins(1),
Duration::from_mins(2),
Duration::from_mins(5),
Duration::from_mins(10),
Duration::from_mins(30),
Duration::from_hours(1),
];
const ELAPSED: SpanPrinter = SpanPrinter::new()
.designator(Designator::Compact)
.spacing(Spacing::None)
.fractional(Some(FractionalUnit::Second))
.precision(Some(1));
const AXIS_LABEL: SpanPrinter = SpanPrinter::new()
.designator(Designator::Compact)
.spacing(Spacing::None);
pub struct BootView<'a> {
pub state: &'a BootState,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
pub now: Duration,
pub host: &'a str,
pub frame: u64,
}
struct TimelineContent<'a> {
milestones: Vec<MilestoneRow>,
finished: Vec<&'a FinishedRun>,
running: Vec<&'a PendingRow>,
impl BootView<'_> {
fn timeline<'a>(&'a self, rows: &'a [PendingRow]) -> Timeline<'a> {
let mut running: Vec<&PendingRow> = rows
.iter()
.filter(|row| !row.is_target && row.status == RowStatus::Running)
.collect();
running.sort_by_key(|row| row.running_since);
Timeline {
origin: self.state.origin,
now: self.now,
root_switches: self
.state
.finished_stages
.iter()
.map(|stage| stage.reached_at)
.collect(),
milestones: self
.state
.milestones()
.into_iter()
.filter(|row| row.reached_at.is_some())
.collect(),
finished: self
.state
.finished_runs
.iter()
.filter(|run| run.finished_at.saturating_sub(run.started_at) >= NOTEWORTHY_DURATION)
.collect(),
running,
palette: self.palette,
glyphs: self.glyphs,
}
}
}
impl Widget for BootView<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let all_rows = self.state.pending_rows();
let pending_count = all_rows.len();
let rows = paths_to_running(all_rows);
let folded = pending_count - rows.len();
let mut running: Vec<&PendingRow> = rows
.iter()
.filter(|row| !row.is_target && row.status == RowStatus::Running)
.collect();
running.sort_by_key(|row| row.running_since);
let milestones: Vec<MilestoneRow> = self
.state
.milestones()
.into_iter()
.filter(|row| row.reached_at.is_some())
.collect();
let failures = self.failure_lines();
let stages = self.stage_lines(area.width);
let stages_height = u16::try_from(stages.len()).unwrap_or(u16::MAX);
let failures_height = u16::try_from(failures.len()).unwrap_or(u16::MAX);
let fits_timeline = area.width >= TIMELINE_LABEL_WIDTH + 1 + MIN_BAR_WIDTH
&& area.height >= MIN_HEIGHT_FOR_TIMELINE;
let timeline_entries = milestones.len() + self.state.finished_runs.len() + running.len();
let timeline_need = if fits_timeline && timeline_entries > 0 {
TIMELINE_CHROME_HEIGHT
.saturating_add(u16::try_from(timeline_entries).unwrap_or(u16::MAX))
} else {
0
let rows = fold_chains(paths_to_running(all_rows));
let shown_units: usize = rows.iter().map(|row| 1 + row.chain.len()).sum();
let header = Header {
host: self.host,
total: (!self.state.finished_stages.is_empty())
.then(|| self.now.saturating_sub(self.state.origin)),
palette: self.palette,
};
let stages = Stages {
state: self.state,
now: self.now,
palette: self.palette,
glyphs: self.glyphs,
};
let tree = PendingTree {
rows: &rows,
folded: pending_count - shown_units,
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 footer = Footer {
tally: self.state.tally(),
shows_root_switch: !self.state.finished_stages.is_empty(),
palette: self.palette,
glyphs: self.glyphs,
};
let fits_timeline = area.width >= timeline::LABEL_WIDTH + 1 + MIN_BAR_WIDTH
&& area.height >= MIN_HEIGHT_FOR_TIMELINE;
let heights = Heights::share(
area.height
.saturating_sub(HEADER_HEIGHT + stages_height + failures_height + FOOTER_HEIGHT),
u16::try_from(rows.len() + usize::from(folded > 0)).unwrap_or(u16::MAX),
timeline_need,
area.height.saturating_sub(
HEADER_HEIGHT + stages.height() + failures.height() + footer::HEIGHT,
),
tree.height(),
if fits_timeline { timeline.height() } else { 0 },
);
let [header, _, stage_area, tree, failed, _, timeline, footer] = Layout::vertical([
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(stages_height),
Constraint::Length(stages.height()),
Constraint::Length(heights.tree),
Constraint::Length(failures_height),
Constraint::Length(failures.height()),
Constraint::Fill(1),
Constraint::Length(heights.timeline),
Constraint::Length(FOOTER_HEIGHT),
Constraint::Length(footer::HEIGHT),
])
.areas(area);
self.header().render(header, buf);
Paragraph::new(stages).render(stage_area, buf);
self.tree(&rows, folded, tree.height).render(tree, buf);
Paragraph::new(failures).render(failed, buf);
header.render(header_area, buf);
stages.render(stage_area, buf);
tree.render(tree_area, buf);
failures.render(failed_area, buf);
if heights.timeline > 0 {
let bar_rows = usize::from(heights.timeline.saturating_sub(TIMELINE_CHROME_HEIGHT));
let finished_room = bar_rows.saturating_sub(milestones.len() + running.len());
let mut finished: Vec<&FinishedRun> = self.state.finished_runs.iter().collect();
finished.sort_by_key(|run| Reverse(run.finished_at.saturating_sub(run.started_at)));
finished.truncate(finished_room);
finished.sort_by_key(|run| run.started_at);
self.timeline(
&TimelineContent {
milestones,
finished,
running,
},
timeline.width,
)
.render(timeline, buf);
timeline.render(timeline_area, buf);
}
self.footer(self.state.tally(), footer.width)
.render(footer, buf);
footer.render(footer_area, buf);
}
}
struct Conclusion<'a> {
finished: &'static str,
took: Duration,
handed_to: &'a str,
}
struct Heights {
tree: u16,
timeline: u16,
@@ -183,547 +186,11 @@ impl Heights {
}
}
impl BootView<'_> {
fn rule_line(
&self,
width: u16,
left: Vec<Span<'static>>,
right: Vec<Span<'static>>,
) -> Line<'static> {
let used = Line::from(left.clone()).width() + Line::from(right.clone()).width();
let fill: String = repeat_n(RULE, usize::from(width).saturating_sub(used)).collect();
Line::from(
left.into_iter()
.chain(once(Span::styled(
fill,
Style::new().fg(self.palette.muted),
)))
.chain(right)
.collect::<Vec<_>>(),
)
}
fn header(&self) -> Table<'static> {
let total = (!self.state.finished_stages.is_empty()).then(|| {
ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(self.state.origin))
});
Table::new(
[Row::new([
Line::from(format!("bootvine {}", self.host)),
Line::from(total.unwrap_or_default()).right_aligned(),
])],
[Constraint::Fill(1), Constraint::Length(DURATION_WIDTH)],
)
.style(Style::new().fg(self.palette.text))
.bold()
}
fn stage_lines(&self, width: u16) -> Vec<Line<'static>> {
let finished = self.state.finished_stages.iter().map(|stage| {
self.rule_line(
width,
vec![
Span::styled(
format!("{RULE_STUB} {} {RULE_STUB} ", stage.label),
Style::new().fg(self.palette.muted),
),
Span::styled(
format!(
"{BEAD} done in {}",
ELAPSED.unsigned_duration_to_string(
&stage.reached_at.saturating_sub(stage.started_at)
)
),
Style::new().fg(self.palette.done),
),
Span::styled(
format!(" · {} ", unit_count(stage.finished_units)),
Style::new().fg(self.palette.waiting),
),
],
Vec::new(),
)
});
let current_started_at = self
.state
.finished_stages
.last()
.map_or(self.state.origin, |stage| stage.reached_at);
let conclusion = match self.state.manager_exited_at {
Some(exited_at) => Some(Conclusion {
finished: "shutdown",
took: exited_at.saturating_sub(self.state.origin),
handed_to: SHUTDOWN_SUCCESSOR,
}),
None => self.state.is_complete().then(|| Conclusion {
finished: "boot",
took: self.now.saturating_sub(self.state.origin),
handed_to: self
.state
.handoff_unit
.as_deref()
.or(self.state.root.as_deref())
.unwrap_or("the console"),
}),
};
let current = if let Some(conclusion) = conclusion {
self.rule_line(
width,
vec![
Span::styled(format!("{RULE_STUB} "), Style::new().fg(self.palette.muted)),
Span::styled(
format!(
"{BEAD} {} finished in {}",
conclusion.finished,
ELAPSED.unsigned_duration_to_string(&conclusion.took)
),
Style::new().fg(self.palette.done).bold(),
),
Span::styled(
format!(" · handing over to {} ", conclusion.handed_to),
Style::new().fg(self.palette.text),
),
],
Vec::new(),
)
} else {
self.rule_line(
width,
vec![
Span::styled(format!("{RULE_STUB} "), Style::new().fg(self.palette.muted)),
Span::styled(
self.state.phase.label(),
Style::new().fg(self.palette.text).bold(),
),
Span::raw(" "),
],
vec![
Span::raw(" "),
Span::styled(
ELAPSED.unsigned_duration_to_string(
&self.now.saturating_sub(current_started_at),
),
Style::new().fg(self.palette.text).bold(),
),
Span::styled(format!(" {RULE_STUB}"), Style::new().fg(self.palette.muted)),
],
)
};
finished.chain(once(current)).collect()
}
fn failure_lines(&self) -> Vec<Line<'static>> {
let units = &self.state.failed;
let hidden = units.len().saturating_sub(MAX_FAILED_ROWS);
units
.iter()
.take(MAX_FAILED_ROWS)
.map(|unit| format!("{FAILED} {unit} failed"))
.chain((hidden > 0).then(|| format!("{FAILED} {hidden} more failed")))
.map(|text| Line::styled(text, Style::new().fg(self.palette.failed).bold()))
.collect()
}
fn label_style(&self, row: &PendingRow) -> Style {
match (row.is_target, row.status) {
(true, _) => Style::new().fg(self.palette.target),
(false, RowStatus::Running) => Style::new().fg(self.palette.text),
(false, RowStatus::Waiting) => Style::new().fg(self.palette.waiting),
}
}
fn status_marker(&self, row: &PendingRow) -> Span<'static> {
match (row.is_target, row.status) {
(true, _) => Span::raw(""),
(false, RowStatus::Running) => {
let spinner = SPINNER[usize::try_from(self.frame % 4).unwrap_or_default()];
Span::styled(
format!("[{spinner}] "),
Style::new().fg(self.palette.running),
)
}
(false, RowStatus::Waiting) => {
Span::styled("[ ] ", Style::new().fg(self.palette.waiting))
}
}
}
fn tree<'a>(&self, rows: &'a [PendingRow], folded: usize, height: u16) -> Table<'a> {
let capacity = usize::from(height);
let shown = if rows.len() + usize::from(folded > 0) > capacity {
capacity.saturating_sub(1).min(rows.len())
} else {
rows.len()
};
let hidden = rows.len() - shown + folded;
let overflow = (hidden > 0).then(|| {
Row::new([Line::styled(
format!("… {hidden} more"),
Style::new().fg(self.palette.waiting),
)])
});
Table::new(
rows.iter()
.take(shown)
.map(|row| self.tree_row(row))
.chain(overflow),
[Constraint::Fill(1), Constraint::Length(DURATION_WIDTH)],
)
}
fn tree_row<'a>(&self, row: &'a PendingRow) -> Row<'a> {
let since = row.running_since.unwrap_or(row.queued_at);
Row::new([
Line::from(vec![
Span::styled(tree_prefix(row), Style::new().fg(self.palette.muted)),
self.status_marker(row),
Span::styled(row.label.as_str(), self.label_style(row)),
]),
Line::from(ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(since)))
.style(self.label_style(row))
.right_aligned(),
])
}
fn timeline<'a>(&self, content: &TimelineContent<'a>, width: u16) -> Table<'a> {
let axis = TimeAxis::new(
self.state.origin,
self.now,
width.saturating_sub(TIMELINE_LABEL_WIDTH + 1),
);
let root_switches: Vec<Duration> = self
.state
.finished_stages
.iter()
.map(|stage| stage.reached_at)
.collect();
let muted = Style::new().fg(self.palette.muted);
let axis_rows = [
Row::new([Line::default(), axis.labels(muted)]),
Row::new([Line::default(), axis.ticks_line(&root_switches, muted)]),
];
let entries = content
.milestones
.iter()
.map(|row| self.milestone_entry(row))
.chain(content.finished.iter().map(|run| self.finished_entry(run)))
.chain(content.running.iter().map(|row| self.running_entry(row)));
let bar_rows = entries.map(|entry| {
Row::new([
entry.label,
axis.bar(&entry.segments, entry.still_going_at, &root_switches, muted),
])
});
Table::new(
axis_rows.into_iter().chain(bar_rows),
[
Constraint::Length(TIMELINE_LABEL_WIDTH),
Constraint::Fill(1),
],
)
.block(
Block::new()
.borders(Borders::TOP)
.border_style(Style::new().fg(self.palette.muted))
.title(Line::styled(
" timeline ",
Style::new().fg(self.palette.waiting),
)),
)
}
fn milestone_entry(&self, row: &MilestoneRow) -> TimelineEntry<'static> {
let done = Style::new().fg(self.palette.done);
TimelineEntry {
label: Line::styled(
format!("{DONE} {} ({})", row.label, unit_count(row.finished_units)),
done,
),
segments: row
.reached_at
.map(|reached_at| Segment {
from: row.started_at,
to: reached_at,
symbol: BEAD,
style: done,
})
.into_iter()
.collect(),
still_going_at: None,
}
}
fn finished_entry<'a>(&self, run: &'a FinishedRun) -> TimelineEntry<'a> {
let (mark, outcome) = if run.failed {
(FAILED, Style::new().fg(self.palette.failed))
} else {
(DONE, Style::new().fg(self.palette.done))
};
TimelineEntry {
label: Line::from(vec![
Span::styled(format!("{mark} "), outcome),
Span::styled(run.label.as_str(), Style::new().fg(self.palette.waiting)),
]),
segments: vec![Segment {
from: run.started_at,
to: run.finished_at,
symbol: BEAD,
style: outcome,
}],
still_going_at: None,
}
}
fn running_entry<'a>(&self, row: &'a PendingRow) -> TimelineEntry<'a> {
let since = row.running_since.unwrap_or(row.queued_at);
let waited = (since > row.queued_at).then(|| Segment {
from: row.queued_at,
to: since,
symbol: WAITING_BEAD,
style: Style::new().fg(self.palette.waiting),
});
let ran = Segment {
from: since,
to: self.now,
symbol: BEAD,
style: Style::new().fg(self.palette.running),
};
TimelineEntry {
label: Line::from(vec![
Span::styled(
format!("{RUNNING_MARK} "),
Style::new().fg(self.palette.running),
),
Span::styled(row.label.as_str(), Style::new().fg(self.palette.text)),
]),
segments: waited.into_iter().chain(once(ran)).collect(),
still_going_at: Some(self.now),
}
}
fn footer(&self, tally: Tally, width: u16) -> Paragraph<'static> {
let failed_style = if tally.failed > 0 {
Style::new().fg(self.palette.failed).bold()
} else {
Style::new().fg(self.palette.waiting)
};
let counts = vec![
Span::styled(
format!("{DONE} {} done", tally.done),
Style::new().fg(self.palette.done),
),
Span::styled(
format!(" {} running", tally.running),
Style::new().fg(self.palette.running),
),
Span::styled(
format!(" {} waiting", tally.waiting),
Style::new().fg(self.palette.waiting),
),
Span::styled(format!(" {FAILED} {} failed", tally.failed), failed_style),
];
let switch_legend = if self.state.finished_stages.is_empty() {
String::new()
} else {
format!(" {ROOT_SWITCH_MARK} root switch")
};
let legend = format!("{BEAD} running {WAITING_BEAD} waiting{switch_legend}");
let used = Line::from(counts.clone()).width() + legend.chars().count();
let gap = usize::from(width).saturating_sub(used);
let spans = if gap >= 2 {
counts
.into_iter()
.chain([
Span::raw(" ".repeat(gap)),
Span::styled(legend, Style::new().fg(self.palette.waiting)),
])
.collect()
} else {
counts
};
Paragraph::new(Line::from(spans)).block(
Block::new()
.borders(Borders::TOP)
.border_style(Style::new().fg(self.palette.muted)),
)
}
}
struct TimelineEntry<'a> {
label: Line<'a>,
segments: Vec<Segment>,
still_going_at: Option<Duration>,
}
struct Segment {
from: Duration,
to: Duration,
symbol: char,
style: Style,
}
struct Stroke {
column: u16,
glyphs: String,
style: Style,
}
impl Stroke {
fn run(column: u16, length: u16, symbol: char, style: Style) -> Self {
Self {
column,
glyphs: repeat_n(symbol, usize::from(length)).collect(),
style,
}
}
}
#[derive(Clone, Copy, PartialEq)]
struct Glyph {
symbol: char,
style: Style,
}
const BLANK: Glyph = Glyph {
symbol: ' ',
style: Style::new(),
};
fn canvas_line(width: u16, strokes: impl IntoIterator<Item = Stroke>) -> Line<'static> {
let cells = strokes
.into_iter()
.fold(vec![BLANK; usize::from(width)], |mut cells, stroke| {
cells
.iter_mut()
.skip(usize::from(stroke.column))
.zip(stroke.glyphs.chars())
.for_each(|(cell, symbol)| {
*cell = Glyph {
symbol,
style: stroke.style,
};
});
cells
});
Line::from(
cells
.chunk_by(|left, right| left.style == right.style)
.map(|run| {
Span::styled(
run.iter().map(|glyph| glyph.symbol).collect::<String>(),
run[0].style,
)
})
.collect::<Vec<_>>(),
)
}
struct TimeAxis {
origin: Duration,
span: Duration,
step: Duration,
width: u16,
}
impl TimeAxis {
fn new(origin: Duration, now: Duration, width: u16) -> Self {
let elapsed = now.saturating_sub(origin).max(AXIS_STEPS[0]);
let max_labels = u128::from((width / AXIS_LABEL_SPACING).max(1));
let step = AXIS_STEPS
.into_iter()
.find(|step| elapsed.as_nanos().div_ceil(step.as_nanos()) <= max_labels)
.unwrap_or(AXIS_STEPS[AXIS_STEPS.len() - 1]);
let steps = u32::try_from(elapsed.as_nanos().div_ceil(step.as_nanos())).unwrap_or(u32::MAX);
Self {
origin,
span: step * steps.max(1),
step,
width,
}
}
fn column(&self, at: Duration) -> u16 {
let offset = at.saturating_sub(self.origin).min(self.span);
let column = offset.as_nanos() * u128::from(self.width) / self.span.as_nanos();
u16::try_from(column)
.unwrap_or(u16::MAX)
.min(self.width.saturating_sub(1))
}
fn tick_offsets(&self) -> impl Iterator<Item = Duration> + '_ {
(0..)
.map(|index: u32| self.step * index)
.take_while(|offset| *offset <= self.span)
}
fn labels(&self, style: Style) -> Line<'static> {
canvas_line(
self.width,
self.tick_offsets().map(|offset| {
let glyphs = if offset.is_zero() && self.origin.is_zero() {
KERNEL_ORIGIN_LABEL.to_owned()
} else {
AXIS_LABEL.unsigned_duration_to_string(&offset)
};
let label_width = u16::try_from(glyphs.len()).unwrap_or(self.width);
Stroke {
column: self
.column(self.origin + offset)
.min(self.width.saturating_sub(label_width)),
glyphs,
style,
}
}),
)
}
fn ticks_line(&self, root_switches: &[Duration], style: Style) -> Line<'static> {
canvas_line(
self.width,
root_switches
.iter()
.map(|at| Stroke::run(self.column(*at), 1, ROOT_SWITCH_MARK, style))
.chain(
self.tick_offsets().map(|offset| {
Stroke::run(self.column(self.origin + offset), 1, '|', style)
}),
),
)
}
fn bar(
&self,
segments: &[Segment],
still_going_at: Option<Duration>,
root_switches: &[Duration],
switch_style: Style,
) -> Line<'static> {
let switches = root_switches
.iter()
.map(|at| Stroke::run(self.column(*at), 1, ROOT_SWITCH_MARK, switch_style));
let bars = segments.iter().map(|segment| {
let start = self.column(segment.from);
let end = self.column(segment.to).max(start + 1);
Stroke::run(start, end - start, segment.symbol, segment.style)
});
let still_going =
still_going_at.map(|now| Stroke::run(self.column(now), 1, STILL_GOING, switch_style));
canvas_line(self.width, switches.chain(bars).chain(still_going))
}
}
fn tree_prefix(row: &PendingRow) -> 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()
fn rule(palette: &Palette, left: Line<'static>) -> Block<'static> {
Block::new()
.borders(Borders::TOP)
.border_style(palette.muted)
.title(left)
}
fn unit_count(count: usize) -> String {
@@ -759,6 +226,7 @@ mod tests {
BootView {
state,
palette: &Palette::default(),
glyphs: &Glyphs::default(),
now,
host: "ryzen",
frame: 1,
@@ -875,6 +343,78 @@ mod tests {
);
}
#[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}");
}
#[test]
fn sub_second_runs_stay_off_the_timeline() {
let mut state = boot_in_progress();
state.track_unit(facts("blink.service", &[]), running_since(4000 * MS));
state.queue_job(20, "blink.service", JobKind::BringsUp, 4000 * MS);
state.finish_job(20, JobResult::Done, 4400 * MS);
let lines = render(&state, 12_400 * MS, 110, 24);
assert!(
lines.iter().all(|line| !line.contains("blink")),
"{}",
lines.join("\n")
);
}
#[test]
fn folded_chains_shorten_to_their_ends_when_narrow() {
let mut state = BootState::new(Phase::Shutdown);
state.set_root("poweroff.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", ""),
]
.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" {
running_since(1000 * MS)
} else {
Activity::default()
};
state.track_unit(facts(name, &after), activity);
state.queue_job(id, name, JobKind::BringsUp, Duration::ZERO);
});
let wide = render(&state, 5000 * MS, 110, 24);
assert!(
wide[4].starts_with(
"└─ [ ] systemd-poweroff → final.target → shutdown.target → local-fs.target → \
demo-disk"
),
"{}",
wide.join("\n")
);
assert!(
wide[5].starts_with(" └─ [/] demo-db"),
"{}",
wide.join("\n")
);
let narrow = render(&state, 5000 * MS, 60, 24);
assert!(
narrow[4].starts_with("└─ [ ] systemd-poweroff → … → demo-disk"),
"{}",
narrow.join("\n")
);
}
#[test]
fn narrow_screens_drop_the_timeline() {
let lines = render(&boot_in_progress(), 12_400 * MS, 36, 24);
+40
View File
@@ -0,0 +1,40 @@
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<Line<'static>> {
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);
}
}
+73
View File
@@ -0,0 +1,73 @@
use ratatui::{
buffer::Buffer,
layout::{Constraint, Rect},
style::Stylize,
text::Line,
widgets::{Block, Borders, Row, Table, Widget},
};
use crate::{glyphs::Glyphs, model::Tally, palette::Palette};
pub const HEIGHT: u16 = 2;
const LEGEND_GAP: usize = 2;
pub struct Footer<'a> {
pub tally: Tally,
pub shows_root_switch: bool,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
impl Footer<'_> {
fn counts(&self) -> Line<'static> {
let failed = format!(" {} {} failed", self.glyphs.failed, self.tally.failed);
let failed = if self.tally.failed > 0 {
failed.fg(self.palette.failed).bold()
} else {
failed.fg(self.palette.waiting)
};
Line::from(vec![
format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.palette.done),
format!(" {} running", self.tally.running).fg(self.palette.running),
format!(" {} waiting", self.tally.waiting).fg(self.palette.waiting),
failed,
])
}
fn legend(&self) -> Line<'static> {
let root_switch = if self.shows_root_switch {
format!(" {} root switch", self.glyphs.root_switch_mark)
} else {
String::new()
};
Line::from(format!(
"{} running {} waiting{root_switch}",
self.glyphs.bead, self.glyphs.waiting_bead
))
.fg(self.palette.waiting)
.right_aligned()
}
}
impl Widget for Footer<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let counts = self.counts();
let legend = self.legend();
let legend_fits = counts.width() + legend.width() + LEGEND_GAP <= usize::from(area.width);
let legend_width = if legend_fits {
u16::try_from(legend.width()).unwrap_or(0)
} else {
0
};
Table::new(
[Row::new([counts, legend])],
[Constraint::Fill(1), Constraint::Length(legend_width)],
)
.block(
Block::new()
.borders(Borders::TOP)
.border_style(self.palette.muted),
)
.render(area, buf);
}
}
+37
View File
@@ -0,0 +1,37 @@
use std::time::Duration;
use ratatui::{
buffer::Buffer,
layout::{Constraint, Rect},
style::Stylize,
text::Line,
widgets::{Row, Table, Widget},
};
use super::{DURATION_WIDTH, ELAPSED};
use crate::palette::Palette;
pub struct Header<'a> {
pub host: &'a str,
pub total: Option<Duration>,
pub palette: &'a Palette,
}
impl Widget for Header<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let total = self
.total
.map(|total| ELAPSED.unsigned_duration_to_string(&total))
.unwrap_or_default();
Table::new(
[Row::new([
Line::from(format!("bootvine {}", self.host)),
Line::from(total).right_aligned(),
])],
[Constraint::Fill(1), Constraint::Length(DURATION_WIDTH)],
)
.fg(self.palette.text)
.bold()
.render(area, buf);
}
}
+128
View File
@@ -0,0 +1,128 @@
use std::{iter::once, time::Duration};
use ratatui::{
buffer::Buffer,
layout::Rect,
style::Stylize,
text::Line,
widgets::{Block, Widget},
};
use super::{ELAPSED, RULE_STUB, rule, unit_count};
use crate::{glyphs::Glyphs, model::BootState, palette::Palette};
const SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown";
pub struct Stages<'a> {
pub state: &'a BootState,
pub now: Duration,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
struct Conclusion<'a> {
finished: &'static str,
took: Duration,
handed_to: &'a str,
}
impl Stages<'_> {
pub fn height(&self) -> u16 {
u16::try_from(self.state.finished_stages.len() + 1).unwrap_or(u16::MAX)
}
fn conclusion(&self) -> Option<Conclusion<'_>> {
if let Some(exited_at) = self.state.manager_exited_at {
return Some(Conclusion {
finished: "shutdown",
took: exited_at.saturating_sub(self.state.origin),
handed_to: SHUTDOWN_SUCCESSOR,
});
}
self.state.is_complete().then(|| Conclusion {
finished: "boot",
took: self.now.saturating_sub(self.state.origin),
handed_to: self
.state
.handoff_unit
.as_deref()
.or(self.state.root.as_deref())
.unwrap_or("the console"),
})
}
fn finished_rules(&self) -> impl Iterator<Item = Block<'static>> + '_ {
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)
)
)
.fg(self.palette.done),
format!(" · {} ", unit_count(stage.finished_units)).fg(self.palette.waiting),
]),
)
})
}
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 current_rule(&self) -> Block<'static> {
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(),
)
}
}
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));
}
}
+367
View File
@@ -0,0 +1,367 @@
use std::{
cmp::Reverse,
iter::{once, repeat_n},
time::Duration,
};
use jiff::fmt::friendly::{Designator, Spacing, SpanPrinter};
use ratatui::{
buffer::Buffer,
layout::{Constraint, Rect},
style::{Style, Stylize},
text::{Line, Span},
widgets::{Row, Table, Widget},
};
use super::{rule, unit_count};
use crate::{
glyphs::Glyphs,
model::{FinishedRun, MilestoneRow, PendingRow},
palette::Palette,
};
pub const LABEL_WIDTH: u16 = 28;
pub const CHROME_HEIGHT: u16 = 3;
const KERNEL_ORIGIN_LABEL: &str = "kernel";
const AXIS_LABEL_SPACING: u16 = 8;
const AXIS_STEPS: [Duration; 12] = [
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(5),
Duration::from_secs(10),
Duration::from_secs(15),
Duration::from_secs(30),
Duration::from_mins(1),
Duration::from_mins(2),
Duration::from_mins(5),
Duration::from_mins(10),
Duration::from_mins(30),
Duration::from_hours(1),
];
const AXIS_LABEL: SpanPrinter = SpanPrinter::new()
.designator(Designator::Compact)
.spacing(Spacing::None);
pub struct Timeline<'a> {
pub origin: Duration,
pub now: Duration,
pub root_switches: Vec<Duration>,
pub milestones: Vec<MilestoneRow>,
pub finished: Vec<&'a FinishedRun>,
pub running: Vec<&'a PendingRow>,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
impl Timeline<'_> {
pub fn height(&self) -> u16 {
let entries = self.milestones.len() + self.finished.len() + self.running.len();
if entries == 0 {
return 0;
}
CHROME_HEIGHT.saturating_add(u16::try_from(entries).unwrap_or(u16::MAX))
}
fn finished_that_fit(&self, height: u16) -> Vec<&FinishedRun> {
let bar_rows = usize::from(height.saturating_sub(CHROME_HEIGHT));
let room = bar_rows.saturating_sub(self.milestones.len() + self.running.len());
let mut longest_first = self.finished.clone();
longest_first.sort_by_key(|run| Reverse(run.finished_at.saturating_sub(run.started_at)));
longest_first.truncate(room);
longest_first.sort_by_key(|run| run.started_at);
longest_first
}
fn milestone_entry(&self, row: &MilestoneRow) -> TimelineEntry<'static> {
let done = Style::from(self.palette.done);
TimelineEntry {
label: Line::styled(
format!(
"{} {} ({})",
self.glyphs.done,
row.label,
unit_count(row.finished_units)
),
done,
),
segments: row
.reached_at
.map(|reached_at| Segment {
from: row.started_at,
to: reached_at,
symbol: self.glyphs.bead,
style: done,
})
.into_iter()
.collect(),
still_going_at: None,
}
}
fn finished_entry<'a>(&self, run: &'a FinishedRun) -> TimelineEntry<'a> {
let mark = if run.failed {
self.glyphs.failed
} else {
self.glyphs.done
};
let outcome = Style::from(if run.failed {
self.palette.failed
} else {
self.palette.done
});
TimelineEntry {
label: Line::from(vec![
Span::styled(format!("{mark} "), outcome),
run.label.as_str().fg(self.palette.waiting),
]),
segments: vec![Segment {
from: run.started_at,
to: run.finished_at,
symbol: self.glyphs.bead,
style: outcome,
}],
still_going_at: None,
}
}
fn running_entry<'a>(&self, row: &'a PendingRow) -> TimelineEntry<'a> {
let since = row.running_since.unwrap_or(row.queued_at);
let waited = (since > row.queued_at).then(|| Segment {
from: row.queued_at,
to: since,
symbol: self.glyphs.waiting_bead,
style: self.palette.waiting.into(),
});
let ran = Segment {
from: since,
to: self.now,
symbol: self.glyphs.bead,
style: self.palette.running.into(),
};
TimelineEntry {
label: Line::from(vec![
format!("{} ", self.glyphs.running_mark).fg(self.palette.running),
row.label.as_str().fg(self.palette.text),
]),
segments: waited.into_iter().chain(once(ran)).collect(),
still_going_at: Some(self.now),
}
}
}
impl Widget for Timeline<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let axis = TimeAxis::new(
self.origin,
self.now,
area.width.saturating_sub(LABEL_WIDTH + 1),
*self.glyphs,
);
let muted = Style::from(self.palette.muted);
let axis_rows = [
Row::new([Line::default(), axis.labels(muted)]),
Row::new([Line::default(), axis.ticks_line(&self.root_switches, muted)]),
];
let entries: Vec<TimelineEntry> = self
.milestones
.iter()
.map(|row| self.milestone_entry(row))
.chain(
self.finished_that_fit(area.height)
.into_iter()
.map(|run| self.finished_entry(run)),
)
.chain(self.running.iter().map(|row| self.running_entry(row)))
.collect();
let bar_rows = entries.into_iter().map(|entry| {
Row::new([
entry.label,
axis.bar(
&entry.segments,
entry.still_going_at,
&self.root_switches,
muted,
),
])
});
Table::new(
axis_rows.into_iter().chain(bar_rows),
[Constraint::Length(LABEL_WIDTH), Constraint::Fill(1)],
)
.block(rule(
self.palette,
Line::from(" timeline ".fg(self.palette.waiting)),
))
.render(area, buf);
}
}
struct TimelineEntry<'a> {
label: Line<'a>,
segments: Vec<Segment>,
still_going_at: Option<Duration>,
}
struct Segment {
from: Duration,
to: Duration,
symbol: char,
style: Style,
}
struct Stroke {
column: u16,
glyphs: String,
style: Style,
}
impl Stroke {
fn run(column: u16, length: u16, symbol: char, style: Style) -> Self {
Self {
column,
glyphs: repeat_n(symbol, usize::from(length)).collect(),
style,
}
}
}
#[derive(Clone, Copy, PartialEq)]
struct Glyph {
symbol: char,
style: Style,
}
const BLANK: Glyph = Glyph {
symbol: ' ',
style: Style::new(),
};
fn canvas_line(width: u16, strokes: impl IntoIterator<Item = Stroke>) -> Line<'static> {
let cells = strokes
.into_iter()
.fold(vec![BLANK; usize::from(width)], |mut cells, stroke| {
cells
.iter_mut()
.skip(usize::from(stroke.column))
.zip(stroke.glyphs.chars())
.for_each(|(cell, symbol)| {
*cell = Glyph {
symbol,
style: stroke.style,
};
});
cells
});
Line::from(
cells
.chunk_by(|left, right| left.style == right.style)
.map(|run| {
Span::styled(
run.iter().map(|glyph| glyph.symbol).collect::<String>(),
run[0].style,
)
})
.collect::<Vec<_>>(),
)
}
struct TimeAxis {
origin: Duration,
span: Duration,
step: Duration,
width: u16,
glyphs: Glyphs,
}
impl TimeAxis {
fn new(origin: Duration, now: Duration, width: u16, glyphs: Glyphs) -> Self {
let elapsed = now.saturating_sub(origin).max(AXIS_STEPS[0]);
let max_labels = u128::from((width / AXIS_LABEL_SPACING).max(1));
let step = AXIS_STEPS
.into_iter()
.find(|step| elapsed.as_nanos().div_ceil(step.as_nanos()) <= max_labels)
.unwrap_or(AXIS_STEPS[AXIS_STEPS.len() - 1]);
let steps = u32::try_from(elapsed.as_nanos().div_ceil(step.as_nanos())).unwrap_or(u32::MAX);
Self {
origin,
span: step * steps.max(1),
step,
width,
glyphs,
}
}
fn column(&self, at: Duration) -> u16 {
let offset = at.saturating_sub(self.origin).min(self.span);
let column = offset.as_nanos() * u128::from(self.width) / self.span.as_nanos();
u16::try_from(column)
.unwrap_or(u16::MAX)
.min(self.width.saturating_sub(1))
}
fn tick_offsets(&self) -> impl Iterator<Item = Duration> + '_ {
(0..)
.map(|index: u32| self.step * index)
.take_while(|offset| *offset <= self.span)
}
fn labels(&self, style: Style) -> Line<'static> {
canvas_line(
self.width,
self.tick_offsets().map(|offset| {
let glyphs = if offset.is_zero() && self.origin.is_zero() {
KERNEL_ORIGIN_LABEL.to_owned()
} else {
AXIS_LABEL.unsigned_duration_to_string(&offset)
};
let label_width = u16::try_from(glyphs.len()).unwrap_or(self.width);
Stroke {
column: self
.column(self.origin + offset)
.min(self.width.saturating_sub(label_width)),
glyphs,
style,
}
}),
)
}
fn ticks_line(&self, root_switches: &[Duration], style: Style) -> Line<'static> {
canvas_line(
self.width,
root_switches
.iter()
.map(|at| Stroke::run(self.column(*at), 1, self.glyphs.root_switch_mark, style))
.chain(
self.tick_offsets().map(|offset| {
Stroke::run(self.column(self.origin + offset), 1, '|', style)
}),
),
)
}
fn bar(
&self,
segments: &[Segment],
still_going_at: Option<Duration>,
root_switches: &[Duration],
switch_style: Style,
) -> Line<'static> {
let switches = root_switches.iter().map(|at| {
Stroke::run(
self.column(*at),
1,
self.glyphs.root_switch_mark,
switch_style,
)
});
let bars = segments.iter().map(|segment| {
let start = self.column(segment.from);
let end = self.column(segment.to).max(start + 1);
Stroke::run(start, end - start, segment.symbol, segment.style)
});
let still_going = still_going_at
.map(|now| Stroke::run(self.column(now), 1, self.glyphs.still_going, switch_style));
canvas_line(self.width, switches.chain(bars).chain(still_going))
}
}
+131
View File
@@ -0,0 +1,131 @@
use std::{iter::once, time::Duration};
use ratatui::{
buffer::Buffer,
layout::{Constraint, Rect},
style::{Color, Stylize},
text::{Line, Span},
widgets::{Row, Table, Widget},
};
use super::{DURATION_WIDTH, ELAPSED, NOTEWORTHY_DURATION};
use crate::{
glyphs::Glyphs,
model::{PendingRow, RowStatus},
palette::Palette,
};
const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
pub struct PendingTree<'a> {
pub rows: &'a [PendingRow],
pub folded: usize,
pub now: Duration,
pub frame: u64,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
impl PendingTree<'_> {
pub fn height(&self) -> u16 {
u16::try_from(self.rows.len() + usize::from(self.folded > 0)).unwrap_or(u16::MAX)
}
fn label_color(&self, row: &PendingRow) -> Color {
if row.is_target {
return self.palette.target;
}
match row.status {
RowStatus::Running => self.palette.text,
RowStatus::Waiting => self.palette.waiting,
}
}
fn status_marker(&self, row: &PendingRow) -> Span<'static> {
if row.is_target {
return Span::default();
}
match row.status {
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),
}
}
fn chained_label(&self, row: &PendingRow, 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::<Vec<_>>()
.join(&link);
if full.chars().count() <= room || row.chain.len() == 1 {
return full;
}
format!("{}{link}{}{link}{last}", row.label, self.glyphs.ellipsis)
}
fn row(&self, row: &PendingRow, label_room: usize) -> 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 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([
Line::from(vec![
prefix.fg(self.palette.muted),
marker,
self.chained_label(row, room).fg(color),
]),
Line::from(timer).fg(color).right_aligned(),
])
}
}
impl Widget for PendingTree<'_> {
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 {
capacity.saturating_sub(1).min(self.rows.len())
} else {
self.rows.len()
};
let hidden = self.rows.len() - shown + self.folded;
let overflow = (hidden > 0).then(|| {
Row::new([format!("{} {hidden} more", self.glyphs.ellipsis).fg(self.palette.waiting)])
});
Table::new(
self.rows
.iter()
.take(shown)
.map(|row| self.row(row, label_room))
.chain(overflow),
[Constraint::Fill(1), Constraint::Length(DURATION_WIDTH)],
)
.render(area, buf);
}
}
fn tree_prefix(row: &PendingRow) -> 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()
}