test: shutdown demo

This commit is contained in:
Willem Vanhulle committed 2026-10-14 21:27:50 +02:00
1 parent 140bbe0e84
commit b0521193a4
14 files changed
+870 -779

No files matched your search

+1
View File
@@ -7,6 +7,7 @@ version = "0.1.0"
absolute_paths = "warn"
pedantic = { priority = -1, level = "warn" }
needless_for_each = "allow"
missing_errors_doc = "allow"
[dependencies]
clap = { version = "4.6.7", features = ["derive"] }
+8 -6
View File
@@ -2,11 +2,10 @@
A live tree of systemd jobs on the boot console, in the spirit of
nix-output-monitor. It replaces the scrolling kernel and systemd lines with the
units still pending and a timeline of the ones that ran.
units still pending and, in the room the tree leaves, a timeline of the slowest
ones that ran.
![The initrd: pending units on top, the timeline below](docs/initrd.png)
![Stage 2: the initrd collapsed, a failed unit, three still running](docs/stage-2.png)
![Shutdown: the unit still stopping at the end of the chain waiting on it](docs/shutdown.png)
![A boot through the initrd into stage 2, with one failed unit](docs/boot.gif)
It needs systemd ≥ 246 as PID 1, libdbus and a virtual terminal (it draws on
tty12). With a systemd initrd it starts about a second after the kernel and
@@ -20,13 +19,16 @@ It also follows shutdowns and reboots: the units being stopped, nested under
the units that have to stop first, until systemd hands over to
`systemd-shutdown`.
![A poweroff: units stopping under the targets waiting on them](docs/shutdown.gif)
## Try
```sh
cargo run --example demo
cargo run --example boot
cargo run --example shutdown
```
plays a scripted boot without systemd; `q` quits. `nix run .#vm` boots a demo
play a scripted boot or poweroff without systemd; `q` quits. `nix run .#vm` boots a demo
VM in a window.
## Install
+187
View File
@@ -0,0 +1,187 @@
use std::{io, time::Duration};
use bootvine::{
model::Phase,
script::{Scenario, Step, failing, play, step},
};
const INITRD: &[Step] = &[
step(
"initrd.target",
&["initrd-fs.target", "initrd-root-device.target"],
Duration::ZERO,
),
step("initrd-fs.target", &["sysroot.mount"], Duration::ZERO),
step(
"initrd-root-device.target",
&["dev-disk-by\\x2dlabel-nixos.device"],
Duration::ZERO,
),
step(
"sysroot.mount",
&["systemd-fsck-root.service"],
Duration::from_millis(300),
),
step(
"systemd-fsck-root.service",
&["dev-disk-by\\x2dlabel-nixos.device"],
Duration::from_millis(500),
),
step(
"dev-disk-by\\x2dlabel-nixos.device",
&[],
Duration::from_millis(1200),
),
step("systemd-udevd.service", &[], Duration::from_millis(400)),
step(
"demo-initrd-probe.service",
&[],
Duration::from_millis(2500),
),
];
const HOST: &[Step] = &[
step(
"graphical.target",
&["multi-user.target", "display-manager.service"],
Duration::ZERO,
),
step(
"display-manager.service",
&["multi-user.target"],
Duration::from_millis(400),
),
step(
"multi-user.target",
&[
"basic.target",
"NetworkManager-wait-online.service",
"docker.service",
"tailscaled.service",
"nvidia-powerd.service",
"systemd-rfkill.service",
],
Duration::ZERO,
),
step("basic.target", &["sysinit.target"], Duration::ZERO),
step(
"sysinit.target",
&[
"systemd-tmpfiles-setup.service",
"systemd-udev-trigger.service",
],
Duration::ZERO,
),
step(
"systemd-tmpfiles-setup.service",
&[],
Duration::from_millis(600),
),
step(
"systemd-udev-trigger.service",
&[],
Duration::from_millis(900),
),
step(
"NetworkManager.service",
&["basic.target"],
Duration::from_millis(1500),
),
step(
"NetworkManager-wait-online.service",
&["NetworkManager.service"],
Duration::from_millis(3500),
),
step(
"network-online.target",
&["NetworkManager-wait-online.service"],
Duration::ZERO,
),
step(
"tailscaled.service",
&["network-online.target"],
Duration::from_millis(1200),
),
step(
"containerd.service",
&["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",
"docker.socket",
"var-lib-docker.mount",
"network-online.target",
],
Duration::from_millis(1500),
),
failing(
"nvidia-powerd.service",
&["basic.target"],
Duration::from_millis(700),
),
step(
"sys-devices-virtual-misc-rfkill.device",
&[],
Duration::from_millis(4000),
),
step(
"systemd-rfkill.service",
&["sys-devices-virtual-misc-rfkill.device"],
Duration::from_millis(300),
),
];
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",
_ => "",
}
}
fn main() -> io::Result<()> {
ratatui::run(|terminal| {
play(
terminal,
&Scenario {
phase: Phase::Initrd,
steps: INITRD,
after_switch_root: HOST,
describe: description,
},
)
})
}
-391
View File
@@ -1,391 +0,0 @@
use std::{
collections::{HashMap, HashSet},
io,
time::{Duration, Instant},
};
use bootvine::{
config::Timing,
glyphs::Glyphs,
model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts},
origin::BootOrigin,
palette::Palette,
view::BootView,
};
use ratatui::{
DefaultTerminal,
crossterm::event::{self, Event, KeyCode},
};
const FRAME_INTERVAL: Duration = Duration::from_millis(100);
const FINAL_FRAME: Duration = Duration::from_secs(3);
struct Step {
unit: &'static str,
after: &'static [&'static str],
work: Duration,
fails: bool,
}
const fn step(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work,
fails: false,
}
}
const fn failing(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work,
fails: true,
}
}
const INITRD: &[Step] = &[
step(
"initrd.target",
&["initrd-fs.target", "initrd-root-device.target"],
Duration::ZERO,
),
step("initrd-fs.target", &["sysroot.mount"], Duration::ZERO),
step(
"initrd-root-device.target",
&["dev-disk-by\\x2dlabel-nixos.device"],
Duration::ZERO,
),
step(
"sysroot.mount",
&["systemd-fsck-root.service"],
Duration::from_millis(300),
),
step(
"systemd-fsck-root.service",
&["dev-disk-by\\x2dlabel-nixos.device"],
Duration::from_millis(500),
),
step(
"dev-disk-by\\x2dlabel-nixos.device",
&[],
Duration::from_millis(1200),
),
step("systemd-udevd.service", &[], Duration::from_millis(400)),
step(
"demo-initrd-probe.service",
&[],
Duration::from_millis(2500),
),
];
const HOST: &[Step] = &[
step(
"graphical.target",
&["multi-user.target", "display-manager.service"],
Duration::ZERO,
),
step(
"display-manager.service",
&["multi-user.target"],
Duration::from_millis(400),
),
step(
"multi-user.target",
&[
"basic.target",
"NetworkManager-wait-online.service",
"docker.service",
"tailscaled.service",
"nvidia-powerd.service",
"systemd-rfkill.service",
],
Duration::ZERO,
),
step("basic.target", &["sysinit.target"], Duration::ZERO),
step(
"sysinit.target",
&[
"systemd-tmpfiles-setup.service",
"systemd-udev-trigger.service",
],
Duration::ZERO,
),
step(
"systemd-tmpfiles-setup.service",
&[],
Duration::from_millis(600),
),
step(
"systemd-udev-trigger.service",
&[],
Duration::from_millis(900),
),
step(
"NetworkManager.service",
&["basic.target"],
Duration::from_millis(1500),
),
step(
"NetworkManager-wait-online.service",
&["NetworkManager.service"],
Duration::from_millis(3500),
),
step(
"network-online.target",
&["NetworkManager-wait-online.service"],
Duration::ZERO,
),
step(
"tailscaled.service",
&["network-online.target"],
Duration::from_millis(1200),
),
step(
"containerd.service",
&["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",
"docker.socket",
"var-lib-docker.mount",
"network-online.target",
],
Duration::from_millis(1500),
),
failing(
"nvidia-powerd.service",
&["basic.target"],
Duration::from_millis(700),
),
step(
"sys-devices-virtual-misc-rfkill.device",
&[],
Duration::from_millis(4000),
),
step(
"systemd-rfkill.service",
&["sys-devices-virtual-misc-rfkill.device"],
Duration::from_millis(300),
),
];
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,
}
impl ScriptedJob {
fn facts(&self) -> UnitFacts {
UnitFacts {
name: 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(),
}
}
fn outcome(&self) -> JobResult {
if self.step.fails {
JobResult::Failed
} else {
JobResult::Done
}
}
fn settled_state(&self) -> ActiveState {
if self.step.fails {
ActiveState::Failed
} else {
ActiveState::Active
}
}
}
struct Script {
jobs: Vec<ScriptedJob>,
started: HashMap<&'static str, Duration>,
finished: HashSet<&'static str>,
}
impl Script {
fn begin(steps: &'static [Step], first_job: u32, state: &mut BootState, now: Duration) -> Self {
let jobs: Vec<ScriptedJob> = steps
.iter()
.zip(first_job..)
.map(|(step, id)| ScriptedJob { id, step })
.collect();
state.set_root(steps[0].unit.to_owned());
jobs.iter()
.for_each(|job| state.track_unit(job.facts(), Activity::default()));
jobs.iter()
.for_each(|job| state.queue_job(job.id, job.step.unit, JobKind::BringsUp, now));
Self {
jobs,
started: HashMap::new(),
finished: HashSet::new(),
}
}
fn is_ready(&self, job: &ScriptedJob) -> bool {
!self.started.contains_key(job.step.unit)
&& job
.step
.after
.iter()
.all(|dependency| self.finished.contains(dependency))
}
fn is_due(&self, job: &ScriptedJob, now: Duration) -> bool {
!self.finished.contains(job.step.unit)
&& self
.started
.get(job.step.unit)
.is_some_and(|started| now >= *started + job.step.work)
}
fn advance(&mut self, state: &mut BootState, now: Duration) {
let starting: Vec<&'static str> = self
.jobs
.iter()
.filter(|job| self.is_ready(job))
.map(|job| job.step.unit)
.collect();
starting.iter().for_each(|unit| {
self.started.insert(unit, now);
state.update_activity(
unit,
Activity {
state: Some(ActiveState::Activating),
inactive_exit: Some(now),
active_enter: None,
active_exit: None,
},
);
});
let due: HashSet<&'static str> = self
.jobs
.iter()
.filter(|job| self.is_due(job, now))
.map(|job| job.step.unit)
.collect();
self.jobs
.iter()
.filter(|job| due.contains(job.step.unit))
.for_each(|job| {
state.update_activity(
job.step.unit,
Activity {
state: Some(job.settled_state()),
inactive_exit: None,
active_enter: Some(now),
active_exit: None,
},
);
state.finish_job(job.id, job.outcome(), now);
});
self.finished.extend(due);
}
}
fn wants_to_quit() -> io::Result<bool> {
if !event::poll(FRAME_INTERVAL)? {
return Ok(false);
}
Ok(
matches!(event::read()?, Event::Key(key) if matches!(key.code, KeyCode::Char('q') | KeyCode::Esc)),
)
}
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;
let mut completed_at = None;
loop {
script.advance(&mut state, now());
if state.phase == Phase::Initrd && script.finished.len() == script.jobs.len() {
state.switch_root(now());
script = Script::begin(HOST, 1000, &mut state, now());
}
terminal.draw(|canvas| {
canvas.render_widget(
BootView {
state: &state,
palette: &Palette::default(),
timing: &Timing::default(),
glyphs: &Glyphs::default(),
now: now(),
origin: &origin,
frame,
password_prompt: None,
},
canvas.area(),
);
})?;
if state.is_complete() {
let completed = *completed_at.get_or_insert_with(Instant::now);
if completed.elapsed() >= FINAL_FRAME {
return Ok(());
}
}
if wants_to_quit()? {
return Ok(());
}
frame += 1;
}
}
fn main() -> io::Result<()> {
ratatui::run(play)
}
+97
View File
@@ -0,0 +1,97 @@
use std::{io, time::Duration};
use bootvine::{
model::Phase,
script::{Scenario, Step, play, step, stopping},
};
const SHUTDOWN: &[Step] = &[
step(
"poweroff.target",
&["systemd-poweroff.service"],
Duration::ZERO,
),
step(
"systemd-poweroff.service",
&["final.target"],
Duration::from_millis(300),
),
step("final.target", &["umount.target"], Duration::ZERO),
step(
"umount.target",
&["shutdown.target", "var-lib-docker.mount", "home.mount"],
Duration::ZERO,
),
step(
"shutdown.target",
&[
"display-manager.service",
"user@1000.service",
"docker.service",
"containerd.service",
"tailscaled.service",
"NetworkManager.service",
],
Duration::ZERO,
),
stopping("display-manager.service", &[], Duration::from_millis(900)),
stopping(
"user@1000.service",
&["display-manager.service"],
Duration::from_millis(1600),
),
stopping("docker.service", &[], Duration::from_millis(3200)),
stopping(
"containerd.service",
&["docker.service"],
Duration::from_millis(700),
),
stopping("tailscaled.service", &[], Duration::from_millis(1100)),
stopping(
"NetworkManager.service",
&["tailscaled.service", "docker.service"],
Duration::from_millis(600),
),
stopping(
"var-lib-docker.mount",
&["docker.service", "containerd.service"],
Duration::from_millis(400),
),
stopping(
"home.mount",
&["user@1000.service"],
Duration::from_millis(500),
),
];
fn description(unit: &str) -> &'static str {
match unit {
"poweroff.target" | "systemd-poweroff.service" => "System Power Off",
"final.target" => "Late Shutdown Services",
"umount.target" => "Unmount All Filesystems",
"shutdown.target" => "System Shutdown",
"display-manager.service" => "Display Manager",
"user@1000.service" => "User Manager for UID 1000",
"docker.service" => "Docker Application Container Engine",
"containerd.service" => "containerd container runtime",
"tailscaled.service" => "Tailscale node agent",
"NetworkManager.service" => "Network Manager",
"var-lib-docker.mount" => "/var/lib/docker",
"home.mount" => "/home",
_ => "",
}
}
fn main() -> io::Result<()> {
ratatui::run(|terminal| {
play(
terminal,
&Scenario {
phase: Phase::Shutdown,
steps: SHUTDOWN,
after_switch_root: &[],
describe: description,
},
)
})
}
+1 -2
View File
@@ -159,8 +159,7 @@ struct ForegroundVt {
}
fn active_vt() -> Option<u16> {
let state: VtState =
unsafe { ioctl(stdin(), Getter::<VT_GETSTATE, VtState>::new()) }.ok()?;
let state: VtState = unsafe { ioctl(stdin(), Getter::<VT_GETSTATE, VtState>::new()) }.ok()?;
Some(state.active)
}
+1
View File
@@ -3,4 +3,5 @@ pub mod glyphs;
pub mod model;
pub mod origin;
pub mod palette;
pub mod script;
pub mod view;
+287
View File
@@ -0,0 +1,287 @@
use std::{
collections::{HashMap, HashSet},
io,
time::{Duration, Instant},
};
use ratatui::{
DefaultTerminal,
crossterm::event::{self, Event, KeyCode},
};
use crate::{
config::Timing,
glyphs::Glyphs,
model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts},
origin::BootOrigin,
palette::Palette,
view::BootView,
};
const FRAME_INTERVAL: Duration = Duration::from_millis(100);
const FINAL_FRAME: Duration = Duration::from_secs(3);
pub struct Step {
unit: &'static str,
after: &'static [&'static str],
work: Duration,
fails: bool,
stops: bool,
}
#[must_use]
pub const fn step(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work,
fails: false,
stops: false,
}
}
#[must_use]
pub const fn failing(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work,
fails: true,
stops: false,
}
}
#[must_use]
pub const fn stopping(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work,
fails: false,
stops: true,
}
}
pub struct Scenario {
pub phase: Phase,
pub steps: &'static [Step],
pub after_switch_root: &'static [Step],
pub describe: fn(&str) -> &'static str,
}
struct ScriptedJob {
id: u32,
step: &'static Step,
}
impl ScriptedJob {
fn facts(&self, steps: &[Step], describe: fn(&str) -> &'static str) -> UnitFacts {
let is_stopping = |unit: &&str| steps.iter().any(|step| step.unit == *unit && step.stops);
let (before, after): (Vec<&str>, Vec<&str>) =
self.step.after.iter().copied().partition(is_stopping);
UnitFacts {
name: self.step.unit.to_owned(),
description: describe(self.step.unit).to_owned(),
after: after.into_iter().map(ToString::to_string).collect(),
before: before.into_iter().map(ToString::to_string).collect(),
}
}
fn kind(&self) -> JobKind {
if self.step.stops {
JobKind::TakesDown
} else {
JobKind::BringsUp
}
}
fn outcome(&self) -> JobResult {
if self.step.fails {
JobResult::Failed
} else {
JobResult::Done
}
}
fn initial_activity(&self) -> Activity {
Activity {
state: self.step.stops.then_some(ActiveState::Active),
..Activity::default()
}
}
fn started_activity(&self, now: Duration) -> Activity {
if self.step.stops {
Activity {
state: Some(ActiveState::Deactivating),
active_exit: Some(now),
..Activity::default()
}
} else {
Activity {
state: Some(ActiveState::Activating),
inactive_exit: Some(now),
..Activity::default()
}
}
}
fn settled_activity(&self, now: Duration) -> Activity {
let state = match (self.step.fails, self.step.stops) {
(true, _) => ActiveState::Failed,
(false, true) => ActiveState::Inactive,
(false, false) => ActiveState::Active,
};
Activity {
state: Some(state),
active_enter: (!self.step.stops).then_some(now),
..Activity::default()
}
}
}
struct Script {
jobs: Vec<ScriptedJob>,
started: HashMap<&'static str, Duration>,
finished: HashSet<&'static str>,
}
impl Script {
fn begin(
steps: &'static [Step],
describe: fn(&str) -> &'static str,
first_job: u32,
state: &mut BootState,
now: Duration,
) -> Self {
let jobs: Vec<ScriptedJob> = steps
.iter()
.zip(first_job..)
.map(|(step, id)| ScriptedJob { id, step })
.collect();
state.set_root(steps[0].unit.to_owned());
jobs.iter().for_each(|job| {
state.track_unit(job.facts(steps, describe), job.initial_activity());
});
jobs.iter()
.for_each(|job| state.queue_job(job.id, job.step.unit, job.kind(), now));
Self {
jobs,
started: HashMap::new(),
finished: HashSet::new(),
}
}
fn is_ready(&self, job: &ScriptedJob) -> bool {
!self.started.contains_key(job.step.unit)
&& job
.step
.after
.iter()
.all(|dependency| self.finished.contains(dependency))
}
fn is_done(&self) -> bool {
self.finished.len() == self.jobs.len()
}
fn is_due(&self, job: &ScriptedJob, now: Duration) -> bool {
!self.finished.contains(job.step.unit)
&& self
.started
.get(job.step.unit)
.is_some_and(|started| now >= *started + job.step.work)
}
fn advance(&mut self, state: &mut BootState, now: Duration) {
let starting: HashSet<&'static str> = self
.jobs
.iter()
.filter(|job| self.is_ready(job))
.map(|job| job.step.unit)
.collect();
self.jobs
.iter()
.filter(|job| starting.contains(job.step.unit))
.for_each(|job| {
self.started.insert(job.step.unit, now);
state.update_activity(job.step.unit, job.started_activity(now));
});
let due: HashSet<&'static str> = self
.jobs
.iter()
.filter(|job| self.is_due(job, now))
.map(|job| job.step.unit)
.collect();
self.jobs
.iter()
.filter(|job| due.contains(job.step.unit))
.for_each(|job| {
state.update_activity(job.step.unit, job.settled_activity(now));
state.finish_job(job.id, job.outcome(), now);
});
self.finished.extend(due);
}
}
fn wants_to_quit() -> io::Result<bool> {
if !event::poll(FRAME_INTERVAL)? {
return Ok(false);
}
Ok(
matches!(event::read()?, Event::Key(key) if matches!(key.code, KeyCode::Char('q') | KeyCode::Esc)),
)
}
pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> 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(scenario.phase);
let mut script = Script::begin(scenario.steps, scenario.describe, 1, &mut state, now());
let mut switched_root = scenario.after_switch_root.is_empty();
let mut settled_at = None;
let mut frame = 0;
loop {
script.advance(&mut state, now());
if script.is_done() && !switched_root {
state.switch_root(now());
script = Script::begin(
scenario.after_switch_root,
scenario.describe,
1000,
&mut state,
now(),
);
switched_root = true;
}
terminal.draw(|canvas| {
canvas.render_widget(
BootView {
state: &state,
palette: &Palette::default(),
timing: &Timing::default(),
glyphs: &Glyphs::default(),
now: now(),
origin: &origin,
frame,
password_prompt: None,
},
canvas.area(),
);
})?;
if script.is_done() && settled_at.get_or_insert_with(Instant::now).elapsed() >= FINAL_FRAME
{
return Ok(());
}
if wants_to_quit()? {
return Ok(());
}
frame += 1;
}
}
+77 -35
View File
@@ -1,6 +1,4 @@
mod footer;
mod header;
mod prompt;
mod chrome;
mod stages;
mod timeline;
mod tree;
@@ -17,9 +15,11 @@ use ratatui::{
use unicode_truncate::UnicodeTruncateStr;
use unicode_width::UnicodeWidthStr;
pub use self::prompt::PasswordPrompt;
pub use self::chrome::PasswordPrompt;
use self::{
footer::Footer, header::Header, prompt::PasswordBar, stages::Stages, timeline::Timeline,
chrome::{FOOTER_HEIGHT, Footer, Header, PasswordBar},
stages::Stages,
timeline::Timeline,
tree::UnitTree,
};
use crate::{
@@ -127,7 +127,6 @@ impl Widget for BootView<'_> {
let timeline = self.timeline(&pruned_rows);
let footer = Footer {
tally: self.state.tally(),
shows_root_switch: !self.state.finished_stages.is_empty(),
palette: self.palette,
glyphs: self.glyphs,
};
@@ -135,14 +134,21 @@ impl Widget for BootView<'_> {
&& area.height >= MIN_HEIGHT_FOR_TIMELINE;
let free = area
.height
.saturating_sub(HEADER_HEIGHT + stages.height() + footer::HEIGHT);
.saturating_sub(HEADER_HEIGHT + stages.height() + FOOTER_HEIGHT);
let whole_tree = fit_to_height(all_rows.clone(), usize::MAX);
let whole_tree_height = UnitTree {
phase: pruned.phase.clone(),
rows: &whole_tree,
hidden: 0,
..pruned
}
.height();
let heights = Heights::share(
free,
pruned.height(),
whole_tree_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)
@@ -167,7 +173,7 @@ impl Widget for BootView<'_> {
Constraint::Length(tree_height),
Constraint::Fill(1),
Constraint::Length(heights.timeline),
Constraint::Length(footer::HEIGHT),
Constraint::Length(FOOTER_HEIGHT),
])
.areas(area);
@@ -196,9 +202,12 @@ struct Heights {
impl Heights {
fn share(free: u16, tree_need: u16, timeline_need: u16) -> Self {
let timeline = timeline_need
.min(free.saturating_sub(tree_need).max(MIN_TIMELINE_HEIGHT))
.min(free);
let leftover = free.saturating_sub(tree_need);
let timeline = if leftover >= MIN_TIMELINE_HEIGHT {
timeline_need.min(leftover)
} else {
0
};
Self {
tree: free - timeline,
timeline,
@@ -363,20 +372,20 @@ mod tests {
"{screen}"
);
assert!(
lines[timeline + 3].starts_with("√ sysinit.target (2 units)"),
lines[timeline + 2].starts_with("√ sysinit.target (2 units)"),
"{screen}"
);
assert!(lines[timeline + 4].starts_with("√ udev-settle"), "{screen}");
assert!(lines[timeline + 4].contains('■'), "{screen}");
assert!(lines[timeline + 3].starts_with("√ udev-settle"), "{screen}");
assert!(lines[timeline + 3].contains('■'), "{screen}");
assert!(
lines[timeline + 5].starts_with("► systemd-rfkill"),
lines[timeline + 4].starts_with("► systemd-rfkill"),
"{screen}"
);
assert!(
lines[timeline + 5].contains("·■") && lines[timeline + 5].ends_with('▶'),
lines[timeline + 4].contains("·■") && lines[timeline + 4].ends_with('▶'),
"{screen}"
);
assert!(lines[timeline + 6].starts_with("► docker"), "{screen}");
assert!(lines[timeline + 5].starts_with("► docker"), "{screen}");
assert!(
lines[timeline..].iter().all(|line| !line.contains(" web")),
"{screen}"
@@ -528,7 +537,7 @@ mod tests {
#[test]
fn chains_fold_when_short_and_shorten_to_their_ends_when_narrow() {
let short = render(&chain_boot(), 5000 * MS, 110, 13);
let short = render(&chain_boot(), 5000 * MS, 110, 9);
assert!(
short[3]
.starts_with(" └─ [ ] network-wait ─ network.target ─ network-manager ─ dbus"),
@@ -693,18 +702,9 @@ mod tests {
.iter()
.position(|line| line.contains(" timeline "))
.expect("timeline panel");
let marker_column = |line: &str| line.chars().position(|symbol| symbol == '│');
let switch_column = marker_column(&lines[timeline + 2]).expect("root switch marker");
assert!(
lines[timeline + 3].starts_with("√ initrd (1 unit)"),
"{screen}"
);
assert_eq!(
marker_column(&lines[timeline + 3]),
Some(switch_column),
"{screen}"
);
assert!(screen.contains("│ root switch"), "{screen}");
let initrd_bar = &lines[timeline + 2];
assert!(initrd_bar.starts_with("√ initrd (1 unit)"), "{screen}");
assert!(initrd_bar.ends_with("■│"), "{screen}");
}
#[test]
@@ -754,12 +754,54 @@ mod tests {
}
#[test]
fn a_long_tree_keeps_the_room_and_leaves_the_timeline_a_strip() {
fn the_tree_takes_the_room_and_the_timeline_only_what_is_left() {
let heights = Heights::share(30, 40, 50);
assert_eq!(heights.timeline, MIN_TIMELINE_HEIGHT);
assert_eq!(heights.tree, 30 - MIN_TIMELINE_HEIGHT);
assert_eq!((heights.tree, heights.timeline), (30, 0));
let heights = Heights::share(30, 12, 50);
assert_eq!((heights.tree, heights.timeline), (12, 18));
let heights = Heights::share(30, 25, 50);
assert_eq!((heights.tree, heights.timeline), (30, 0));
let heights = Heights::share(30, 12, 8);
assert_eq!((heights.tree, heights.timeline), (22, 8));
}
#[test]
fn the_timeline_keeps_only_the_slowest_finished_runs() {
let mut state = BootState::new(Phase::Host);
state.set_root("multi-user.target".to_owned());
let quick_units: Vec<String> = (0..10).map(|n| format!("run{n:02}.service")).collect();
let after: Vec<&str> = quick_units
.iter()
.map(String::as_str)
.chain(["slow.service"])
.collect();
state.track_unit(facts("multi-user.target", &after), Activity::default());
state.queue_job(100, "multi-user.target", JobKind::BringsUp, Duration::ZERO);
state.track_unit(facts("slow.service", &[]), running_since(Duration::ZERO));
state.queue_job(101, "slow.service", JobKind::BringsUp, Duration::ZERO);
quick_units.iter().zip(0..).for_each(|(name, id)| {
state.track_unit(facts(name, &[]), running_since(Duration::ZERO));
state.queue_job(id, name, JobKind::BringsUp, Duration::ZERO);
state.finish_job(id, JobResult::Done, (1000 + 1000 * id) * MS);
});
let lines = render(&state, 20_000 * MS, 110, 40);
let screen = lines.join("\n");
let timeline = lines
.iter()
.position(|line| line.contains(" timeline "))
.expect("timeline panel");
let (tree, panel) = lines.split_at(timeline);
assert!(tree.iter().all(|line| !line.contains('…')), "{screen}");
let shown: Vec<&str> = quick_units
.iter()
.map(|name| name.trim_end_matches(".service"))
.filter(|label| panel.iter().any(|line| line.contains(label)))
.collect();
assert_eq!(
shown,
["run05", "run06", "run07", "run08", "run09"],
"{screen}"
);
}
#[test]
+118
View File
@@ -0,0 +1,118 @@
use std::{iter::once, time::Duration};
use ratatui::{
buffer::Buffer,
layout::Rect,
style::Stylize,
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Widget},
};
use super::{DURATION_WIDTH, ELAPSED, rule};
use crate::{glyphs::Glyphs, model::Tally, origin::BootOrigin, palette::Palette};
pub const FOOTER_HEIGHT: u16 = 2;
const SEPARATOR: &str = " · ";
pub struct Header<'a> {
pub origin: &'a BootOrigin,
pub total: Option<Duration>,
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::<Vec<_>>(),
)
}
}
impl Widget for Header<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
self.origin().render(
Rect {
width: area.width.saturating_sub(DURATION_WIDTH),
..area
},
buf,
);
if let Some(total) = self.total {
Line::from(ELAPSED.unsigned_duration_to_string(&total))
.fg(self.palette.text)
.bold()
.right_aligned()
.render(area, buf);
}
}
}
pub struct Footer<'a> {
pub tally: Tally,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
impl Widget for Footer<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let failed = format!(" {} {} failed", self.glyphs.failed, self.tally.failed);
let failed = if self.tally.failed > 0 {
failed.fg(self.palette.failed).bold()
} else {
failed.fg(self.palette.waiting)
};
let block = Block::new()
.borders(Borders::TOP)
.border_style(self.palette.muted);
let inner = block.inner(area);
block.render(area, buf);
Line::from(vec![
format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.palette.done),
format!(" {} running", self.tally.running).fg(self.palette.running),
format!(" {} waiting", self.tally.waiting).fg(self.palette.waiting),
failed,
])
.render(inner, buf);
}
}
pub struct PasswordPrompt<'a> {
pub message: &'a str,
pub input: String,
pub sent: bool,
}
pub struct PasswordBar<'a> {
pub asking: &'a PasswordPrompt<'a>,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
impl Widget for PasswordBar<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let status = if self.asking.sent {
format!(" checking{}", self.glyphs.ellipsis).fg(self.palette.waiting)
} else {
format!(" {}_", self.asking.input).fg(self.palette.text)
};
Paragraph::new(Line::from(vec![
self.asking.message.fg(self.palette.running).bold(),
status,
]))
.block(rule(
self.palette,
Line::from(" password ".fg(self.palette.running)),
))
.render(area, buf);
}
}
-73
View File
@@ -1,73 +0,0 @@
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);
}
}
-58
View File
@@ -1,58 +0,0 @@
use std::{iter::once, time::Duration};
use ratatui::{
buffer::Buffer,
layout::{Constraint, Rect},
style::Stylize,
text::{Line, Span},
widgets::{Row, Table, Widget},
};
use super::{DURATION_WIDTH, ELAPSED};
use crate::{origin::BootOrigin, palette::Palette};
const SEPARATOR: &str = " · ";
pub struct Header<'a> {
pub origin: &'a BootOrigin,
pub total: Option<Duration>,
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::<Vec<_>>(),
)
}
}
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([
self.origin(),
Line::from(total)
.fg(self.palette.text)
.bold()
.right_aligned(),
])],
[Constraint::Fill(1), Constraint::Length(DURATION_WIDTH)],
)
.render(area, buf);
}
}
-41
View File
@@ -1,41 +0,0 @@
use ratatui::{
buffer::Buffer,
layout::Rect,
style::Stylize,
text::Line,
widgets::{Paragraph, Widget},
};
use super::rule;
use crate::{glyphs::Glyphs, palette::Palette};
pub struct PasswordPrompt<'a> {
pub message: &'a str,
pub input: String,
pub sent: bool,
}
pub struct PasswordBar<'a> {
pub asking: &'a PasswordPrompt<'a>,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
impl Widget for PasswordBar<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let status = if self.asking.sent {
format!(" checking{}", self.glyphs.ellipsis).fg(self.palette.waiting)
} else {
format!(" {}_", self.asking.input).fg(self.palette.text)
};
Paragraph::new(Line::from(vec![
self.asking.message.fg(self.palette.running).bold(),
status,
]))
.block(rule(
self.palette,
Line::from(" password ".fg(self.palette.running)),
))
.render(area, buf);
}
}
+93 -173
View File
@@ -1,16 +1,16 @@
use std::{
cmp::Reverse,
iter::{once, repeat_n},
time::Duration,
};
use std::{cmp::Reverse, iter::once, time::Duration};
use jiff::fmt::friendly::{Designator, Spacing, SpanPrinter};
use ratatui::{
buffer::Buffer,
layout::{Constraint, Rect},
style::{Style, Stylize},
layout::{Constraint, Layout, Rect},
style::{Color, Stylize},
symbols::Marker,
text::{Line, Span},
widgets::{Row, Table, Widget},
widgets::{
Paragraph, Widget,
canvas::{Canvas, Line as Stroke, Points},
},
};
use super::{fit_width, rule, unit_count};
@@ -21,8 +21,9 @@ use crate::{
};
pub const LABEL_WIDTH: u16 = 28;
pub const CHROME_HEIGHT: u16 = 3;
pub const CHROME_HEIGHT: u16 = 2;
const MARK_WIDTH: u16 = 2;
const SLOWEST_RUNS_SHOWN: usize = 5;
const KERNEL_ORIGIN_LABEL: &str = "kernel";
const AXIS_LABEL_SPACING: u16 = 8;
const AXIS_STEPS: [Duration; 12] = [
@@ -56,7 +57,9 @@ pub struct Timeline<'a> {
impl Timeline<'_> {
pub fn height(&self) -> u16 {
let entries = self.milestones.len() + self.finished.len() + self.running.len();
let entries = self.milestones.len()
+ self.finished.len().min(SLOWEST_RUNS_SHOWN)
+ self.running.len();
if entries == 0 {
return 0;
}
@@ -68,13 +71,12 @@ impl Timeline<'_> {
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.truncate(room.min(SLOWEST_RUNS_SHOWN));
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!(
@@ -83,7 +85,7 @@ impl Timeline<'_> {
row.label,
unit_count(row.finished_units)
),
done,
self.palette.done,
),
segments: row
.reached_at
@@ -91,7 +93,7 @@ impl Timeline<'_> {
from: row.started_at,
to: reached_at,
symbol: self.glyphs.bead,
style: done,
color: self.palette.done,
})
.into_iter()
.collect(),
@@ -105,11 +107,11 @@ impl Timeline<'_> {
} else {
self.glyphs.done
};
let outcome = Style::from(if run.failed {
let outcome = if run.failed {
self.palette.failed
} else {
self.palette.done
});
};
TimelineEntry {
label: Line::from(vec![
Span::styled(format!("{mark} "), outcome),
@@ -119,7 +121,7 @@ impl Timeline<'_> {
from: run.started_at,
to: run.finished_at,
symbol: self.glyphs.bead,
style: outcome,
color: outcome,
}],
still_going_at: None,
}
@@ -135,17 +137,17 @@ impl Timeline<'_> {
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 {
let waited = (since > row.queued_at).then_some(Segment {
from: row.queued_at,
to: since,
symbol: self.glyphs.waiting_bead,
style: self.palette.waiting.into(),
color: self.palette.waiting,
});
let ran = Segment {
from: since,
to: self.now,
symbol: self.glyphs.bead,
style: self.palette.running.into(),
color: self.palette.running,
};
TimelineEntry {
label: Line::from(vec![
@@ -160,17 +162,16 @@ impl Timeline<'_> {
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 block = rule(
self.palette,
Line::from(" timeline ".fg(self.palette.waiting)),
);
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 inner = block.inner(area);
block.render(area, buf);
let [label_area, bar_area] =
Layout::horizontal([Constraint::Length(LABEL_WIDTH), Constraint::Fill(1)])
.spacing(1)
.areas(inner);
let entries: Vec<TimelineEntry> = self
.milestones
.iter()
@@ -182,26 +183,50 @@ impl Widget for Timeline<'_> {
)
.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)],
Paragraph::new(
once(Line::default())
.chain(entries.iter().map(|entry| entry.label.clone()))
.collect::<Vec<_>>(),
)
.block(rule(
self.palette,
Line::from(" timeline ".fg(self.palette.waiting)),
))
.render(area, buf);
.render(label_area, buf);
let axis = TimeAxis::new(self.origin, self.now, bar_area.width);
let label_row = f64::from(bar_area.height.saturating_sub(1).max(1));
let muted = self.palette.muted;
Canvas::default()
.x_bounds(axis.bounds())
.y_bounds([0.0, label_row])
.paint(|ctx| {
entries.iter().zip(1_u16..).for_each(|(entry, row)| {
let y = label_row - f64::from(row);
entry.segments.iter().for_each(|segment| {
ctx.marker(Marker::Custom(segment.symbol));
ctx.draw(&Stroke::new(
segment.from.as_secs_f64(),
y,
segment.to.as_secs_f64(),
y,
segment.color,
));
});
if let Some(now) = entry.still_going_at {
ctx.marker(Marker::Custom(self.glyphs.still_going));
ctx.draw(&Points::new(&[(now.as_secs_f64(), y)], muted));
}
});
ctx.marker(Marker::Custom(self.glyphs.root_switch_mark));
self.root_switches.iter().for_each(|at| {
let x = at.as_secs_f64();
ctx.draw(&Stroke::new(x, 0.0, x, label_row - 1.0, muted));
});
axis.tick_offsets().for_each(|offset| {
let label = axis.label(offset);
let x = (axis.origin + offset)
.as_secs_f64()
.min(axis.bounds()[1] - axis.columns_to_seconds(label.len() - 1));
ctx.print(x, label_row, label.fg(muted));
});
})
.render(bar_area, buf);
}
}
@@ -215,63 +240,7 @@ 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<_>>(),
)
color: Color,
}
struct TimeAxis {
@@ -279,11 +248,10 @@ struct TimeAxis {
span: Duration,
step: Duration,
width: u16,
glyphs: Glyphs,
}
impl TimeAxis {
fn new(origin: Duration, now: Duration, width: u16, glyphs: Glyphs) -> Self {
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
@@ -296,16 +264,20 @@ impl TimeAxis {
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 bounds(&self) -> [f64; 2] {
[
self.origin.as_secs_f64(),
(self.origin + self.span).as_secs_f64(),
]
}
fn columns_to_seconds(&self, columns: usize) -> f64 {
let last_column = self.width.saturating_sub(1).max(1);
let columns = u16::try_from(columns).unwrap_or(last_column);
self.span.as_secs_f64() * f64::from(columns) / f64::from(last_column)
}
fn tick_offsets(&self) -> impl Iterator<Item = Duration> + '_ {
@@ -314,63 +286,11 @@ impl TimeAxis {
.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))
fn label(&self, offset: Duration) -> String {
if offset.is_zero() && self.origin.is_zero() {
KERNEL_ORIGIN_LABEL.to_owned()
} else {
AXIS_LABEL.unsigned_duration_to_string(&offset)
}
}
}