refactor: merge the console into the live desk and shrink the desk trait to what screens differ in

This commit is contained in:
Willem Vanhulle committed 2026-10-25 13:55:26 +01:00
1 parent 734988247d
commit f8f1b54d75
6 files changed
+298 -344

No files matched your search

+10 -10
View File
@@ -3,23 +3,23 @@ use ratatui::{
style::{Color, Modifier}, style::{Color, Modifier},
}; };
#[derive(Clone, Copy, Debug, PartialEq, Eq)] use crate::screen_settings::font_glyphs::Glyphs;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ConsolePalette { pub enum ConsolePalette {
#[default]
Terminal, Terminal,
SixteenColorVt, SixteenColorVt,
EightColorVt, EightColorVt,
} }
impl ConsolePalette { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[must_use] pub struct ConsoleLook {
pub fn of_virtual_terminal(font_uses_high_glyphs: bool) -> Self { pub glyphs: Glyphs,
if font_uses_high_glyphs { pub palette: ConsolePalette,
Self::EightColorVt }
} else {
Self::SixteenColorVt
}
}
impl ConsolePalette {
pub fn fit_frame(self, frame: &mut Buffer) { pub fn fit_frame(self, frame: &mut Buffer) {
if self == Self::Terminal { if self == Self::Terminal {
return; return;
+31 -118
View File
@@ -1,4 +1,4 @@
use std::{collections::HashSet, fs, ptr}; use std::{collections::HashSet, fs, mem, ptr};
use rustix::{ use rustix::{
io::Errno, io::Errno,
@@ -8,7 +8,10 @@ use rustix::{
}; };
use crate::{ use crate::{
console_session::{ask_password, console_palette::ConsolePalette}, console_session::{
ask_password,
console_palette::{ConsoleLook, ConsolePalette},
},
screen_settings::font_glyphs::Glyphs, screen_settings::font_glyphs::Glyphs,
}; };
@@ -19,89 +22,8 @@ const VIRTUAL_TERMINAL_PREFIX: &str = "/dev/tty";
const KERNEL_PRINTK: &str = "/proc/sys/kernel/printk"; const KERNEL_PRINTK: &str = "/proc/sys/kernel/printk";
const ALERTS_ONLY: &str = "1"; const ALERTS_ONLY: &str = "1";
const HIGHEST_LOW_GLYPH: u16 = 255; const HIGHEST_LOW_GLYPH: u16 = 255;
pub struct Console {
quiet_kernel: Option<QuietKernelConsole>,
foreground: Option<ForegroundVt>,
for_system: bool,
own_vt: Option<u16>,
pub glyphs: Glyphs,
pub palette: ConsolePalette,
}
impl Console { pub(super) struct QuietKernelConsole {
pub fn take(for_system: bool) -> Self {
let prompt_elsewhere = for_system && ask_password::requested();
if prompt_elsewhere {
eprintln!("bootvine: a password prompt is already showing, staying behind it");
}
let own_vt = vt_of_stdin();
let font = loaded_font();
Self {
quiet_kernel: for_system.then(QuietKernelConsole::take).flatten(),
foreground: own_vt
.filter(|_| !prompt_elsewhere)
.and_then(ForegroundVt::take),
for_system,
own_vt,
glyphs: font_glyphs(font.as_ref()),
palette: console_palette(own_vt, font.as_ref()),
}
}
#[must_use]
pub fn answers_password_prompts(&self) -> bool {
self.for_system && self.foreground.is_some()
}
pub fn come_forward_once_prompts_are_gone(&mut self) -> bool {
if !self.for_system || self.foreground.is_some() || ask_password::requested() {
return false;
}
self.foreground = self.own_vt.and_then(ForegroundVt::take);
if self.foreground.is_some() {
eprintln!("bootvine: password prompt answered, taking the console back");
}
self.foreground.is_some()
}
pub fn keep_up(&mut self) -> bool {
let kernel_got_loud = self
.quiet_kernel
.as_mut()
.is_some_and(QuietKernelConsole::keep_quiet);
let terminal_was_taken = self.foreground.as_ref().is_some_and(ForegroundVt::insist);
let font = loaded_font();
let glyphs = font_glyphs(font.as_ref());
let palette = console_palette(self.own_vt, font.as_ref());
let font_changed = glyphs != self.glyphs || palette != self.palette;
self.glyphs = glyphs;
self.palette = palette;
kernel_got_loud || terminal_was_taken || font_changed
}
pub fn begin_handover(&mut self) {
self.set_grip(TerminalGrip::Yielding);
}
#[must_use]
pub fn console_was_taken(&self) -> bool {
self.foreground
.as_ref()
.is_some_and(ForegroundVt::taken_away)
}
pub fn leave_console(&mut self) {
self.set_grip(TerminalGrip::Surrendered);
}
fn set_grip(&mut self, grip: TerminalGrip) {
if let Some(foreground) = &mut self.foreground {
foreground.grip = grip;
}
}
}
struct QuietKernelConsole {
previous_level: String, previous_level: String,
} }
@@ -111,13 +33,13 @@ fn console_level() -> Option<String> {
} }
impl QuietKernelConsole { impl QuietKernelConsole {
fn take() -> Option<Self> { pub(super) fn take() -> Option<Self> {
let previous_level = console_level()?; let previous_level = console_level()?;
fs::write(KERNEL_PRINTK, ALERTS_ONLY).ok()?; fs::write(KERNEL_PRINTK, ALERTS_ONLY).ok()?;
Some(Self { previous_level }) Some(Self { previous_level })
} }
fn keep_quiet(&mut self) -> bool { pub(super) fn keep_quiet(&mut self) -> bool {
let Some(level) = console_level() else { let Some(level) = console_level() else {
return false; return false;
}; };
@@ -134,17 +56,19 @@ struct LoadedFont {
uses_high_glyphs: bool, uses_high_glyphs: bool,
} }
fn font_glyphs(font: Option<&LoadedFont>) -> Glyphs { pub(super) fn console_look(own_vt: Option<u16>) -> ConsoleLook {
font.map_or_else(Glyphs::default, |font| { let font = loaded_font();
let glyphs = font.as_ref().map_or_else(Glyphs::default, |font| {
Glyphs::fitting(|symbol| symbol.is_ascii() || font.characters.contains(&symbol)) Glyphs::fitting(|symbol| symbol.is_ascii() || font.characters.contains(&symbol))
}) });
} let palette = match own_vt {
None => ConsolePalette::Terminal,
fn console_palette(own_vt: Option<u16>, font: Option<&LoadedFont>) -> ConsolePalette { Some(_) if font.as_ref().is_some_and(|font| font.uses_high_glyphs) => {
if own_vt.is_none() { ConsolePalette::EightColorVt
return ConsolePalette::Terminal; }
} Some(_) => ConsolePalette::SixteenColorVt,
ConsolePalette::of_virtual_terminal(font.is_some_and(|font| font.uses_high_glyphs)) };
ConsoleLook { glyphs, palette }
} }
impl Drop for QuietKernelConsole { impl Drop for QuietKernelConsole {
@@ -204,17 +128,9 @@ struct VtState {
_state: u16, _state: u16,
} }
#[derive(Clone, Copy, PartialEq, Eq)] pub(super) struct ForegroundVt {
enum TerminalGrip {
Insisting,
Yielding,
Surrendered,
}
struct ForegroundVt {
own: u16, own: u16,
previous: u16, previous: u16,
grip: TerminalGrip,
} }
fn active_vt() -> Option<u16> { fn active_vt() -> Option<u16> {
@@ -222,7 +138,7 @@ fn active_vt() -> Option<u16> {
Some(state.active) Some(state.active)
} }
fn vt_of_stdin() -> Option<u16> { pub(super) fn vt_of_stdin() -> Option<u16> {
let name = ttyname(stdin(), Vec::new()).ok()?; let name = ttyname(stdin(), Vec::new()).ok()?;
name.to_str() name.to_str()
.ok()? .ok()?
@@ -233,25 +149,25 @@ fn vt_of_stdin() -> Option<u16> {
} }
impl ForegroundVt { impl ForegroundVt {
fn take(own: u16) -> Option<Self> { pub(super) fn take(own: u16) -> Option<Self> {
let previous = active_vt()?; let previous = active_vt()?;
if previous != own { if previous != own {
activate(own).ok()?; activate(own).ok()?;
} }
Some(Self { Some(Self { own, previous })
own,
previous,
grip: TerminalGrip::Insisting,
})
} }
fn insist(&self) -> bool { pub(super) fn insist(&self) -> bool {
self.grip == TerminalGrip::Insisting && self.taken_away() && activate(self.own).is_ok() self.taken_away() && activate(self.own).is_ok()
} }
fn taken_away(&self) -> bool { pub(super) fn taken_away(&self) -> bool {
active_vt().is_some_and(|active| active != self.own) active_vt().is_some_and(|active| active != self.own)
} }
pub(super) fn stay_switched(self) {
mem::forget(self);
}
} }
impl Drop for ForegroundVt { impl Drop for ForegroundVt {
@@ -260,9 +176,6 @@ impl Drop for ForegroundVt {
eprintln!("bootvine: leaving a password prompt to the console agent on this terminal"); eprintln!("bootvine: leaving a password prompt to the console agent on this terminal");
return; return;
} }
if self.grip == TerminalGrip::Surrendered {
return;
}
let _ = activate(self.previous); let _ = activate(self.previous);
} }
} }
+75 -58
View File
@@ -1,62 +1,81 @@
use std::{future::ready, io, mem, ops::ControlFlow, time::Duration}; use std::{future::ready, io, ops::ControlFlow, time::Duration};
use crossterm::event::Event; use crossterm::event::Event;
use futures::{Stream, StreamExt}; use futures::{Stream, StreamExt};
use crate::{ use crate::{
boot_model::{BootState, boot_origin::BootOrigin}, boot_model::BootChange,
boot_view::PasswordPrompt, boot_view::PasswordPrompt,
console_session::{ console_session::{
ask_password::{PasswordEntry, RequestWatch}, ask_password::{self, PasswordEntry, RequestWatch},
console_palette::ConsolePalette, console_palette::ConsoleLook,
console_takeover::Console, console_takeover::{ForegroundVt, QuietKernelConsole, console_look, vt_of_stdin},
passphrase_input::asks_to_quit, passphrase_input::asks_to_quit,
stream_sources::{BACKGROUND_CHECK_INTERVAL, items_when_readable, periodic_inputs}, stream_sources::items_when_readable,
watch_screen::{ConsoleDesk, ScreenInput, WatchEnding}, watch_screen::{ConsoleDesk, Refresh, ScreenInput, WatchEnding},
}, },
screen_settings::font_glyphs::Glyphs,
}; };
const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(5);
pub struct LiveDesk { pub struct LiveDesk {
console: Console, quiet_kernel: Option<QuietKernelConsole>,
foreground: Option<ForegroundVt>,
for_system: bool,
own_vt: Option<u16>,
look: ConsoleLook,
entry: Option<PasswordEntry>, entry: Option<PasswordEntry>,
requests_watched: bool,
clear_requested: bool,
handover_deadline: Option<Duration>, handover_deadline: Option<Duration>,
} }
impl LiveDesk { impl LiveDesk {
#[must_use] #[must_use]
pub fn new(console: Console, requests_watched: bool) -> Self { pub fn take_console(for_system: bool) -> Self {
let prompt_elsewhere = for_system && ask_password::requested();
if prompt_elsewhere {
eprintln!("bootvine: a password prompt is already showing, staying behind it");
}
let own_vt = vt_of_stdin();
Self { Self {
console, quiet_kernel: for_system.then(QuietKernelConsole::take).flatten(),
foreground: own_vt
.filter(|_| !prompt_elsewhere)
.and_then(ForegroundVt::take),
for_system,
own_vt,
look: console_look(own_vt),
entry: None, entry: None,
requests_watched,
clear_requested: false,
handover_deadline: None, handover_deadline: None,
} }
} }
fn follow_requests(&mut self, requests_changed: bool) { fn come_forward_once_prompts_are_gone(&mut self) -> bool {
self.clear_requested |= if !self.for_system || self.foreground.is_some() || ask_password::requested() {
requests_changed && self.console.come_forward_once_prompts_are_gone(); return false;
self.entry = if self.console.answers_password_prompts() { }
self.foreground = self.own_vt.and_then(ForegroundVt::take);
if self.foreground.is_some() {
eprintln!("bootvine: password prompt answered, taking the console back");
}
self.foreground.is_some()
}
fn follow_requests(&mut self, requests_changed: bool) -> Refresh {
let came_forward = requests_changed && self.come_forward_once_prompts_are_gone();
self.entry = if self.for_system && self.foreground.is_some() {
PasswordEntry::follow(self.entry.take(), requests_changed) PasswordEntry::follow(self.entry.take(), requests_changed)
} else { } else {
None None
}; };
if came_forward {
Refresh::Clear
} else {
Refresh::Steady
}
} }
} }
impl ConsoleDesk for LiveDesk { impl ConsoleDesk for LiveDesk {
fn glyphs(&self) -> &Glyphs { fn look(&self) -> ConsoleLook {
&self.console.glyphs self.look
}
fn palette(&self) -> ConsolePalette {
self.console.palette
} }
fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> { fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> {
@@ -82,57 +101,55 @@ impl ConsoleDesk for LiveDesk {
return; return;
} }
eprintln!("bootvine: {reached} reached, handing the console over"); eprintln!("bootvine: {reached} reached, handing the console over");
self.console.begin_handover();
self.handover_deadline = Some(deadline); self.handover_deadline = Some(deadline);
} }
fn frame_passed(&mut self, _state: &mut BootState, now: Duration) -> ControlFlow<WatchEnding> { fn frame_passed(&mut self, now: Duration) -> ControlFlow<WatchEnding, Vec<BootChange>> {
let Some(deadline) = self.handover_deadline else { let Some(deadline) = self.handover_deadline else {
return ControlFlow::Continue(()); return ControlFlow::Continue(Vec::new());
}; };
if self.console.console_was_taken() { if self
.foreground
.as_ref()
.is_some_and(ForegroundVt::taken_away)
{
eprintln!("bootvine: another program took the console, leaving it there"); eprintln!("bootvine: another program took the console, leaving it there");
self.console.leave_console(); if let Some(foreground) = self.foreground.take() {
foreground.stay_switched();
}
ControlFlow::Break(WatchEnding::BootCompleted) ControlFlow::Break(WatchEnding::BootCompleted)
} else if now >= deadline { } else if now >= deadline {
eprintln!("bootvine: nothing took the console, switching back"); eprintln!("bootvine: nothing took the console, switching back");
ControlFlow::Break(WatchEnding::BootCompleted) ControlFlow::Break(WatchEnding::BootCompleted)
} else { } else {
ControlFlow::Continue(()) ControlFlow::Continue(Vec::new())
} }
} }
fn password_requests_changed(&mut self) { fn password_requests_changed(&mut self) -> Refresh {
self.follow_requests(true); self.follow_requests(true)
} }
fn check_prompts(&mut self) { fn check_prompts(&mut self) {
self.follow_requests(!self.requests_watched); self.follow_requests(false);
} }
fn keep_console_up(&mut self) -> bool { fn keep_console_up(&mut self) -> Refresh {
self.console.keep_up() let kernel_got_loud = self
.quiet_kernel
.as_mut()
.is_some_and(QuietKernelConsole::keep_quiet);
let terminal_was_taken = self.handover_deadline.is_none()
&& self.foreground.as_ref().is_some_and(ForegroundVt::insist);
let look = console_look(self.own_vt);
let restyled = look != self.look;
self.look = look;
if kernel_got_loud || terminal_was_taken || restyled {
Refresh::Repaint
} else {
Refresh::Steady
}
} }
fn take_clear_request(&mut self) -> bool {
mem::take(&mut self.clear_requested)
}
fn refreshed_origin(&self) -> Option<BootOrigin> {
Some(BootOrigin::read())
}
}
pub fn prompt_check_inputs() -> impl Stream<Item = ScreenInput> {
periodic_inputs(BACKGROUND_CHECK_INTERVAL, || ScreenInput::PromptCheck)
}
pub fn console_upkeep_inputs() -> impl Stream<Item = ScreenInput> {
periodic_inputs(BACKGROUND_CHECK_INTERVAL, || ScreenInput::ConsoleUpkeep)
}
pub fn full_repaint_inputs() -> impl Stream<Item = ScreenInput> {
periodic_inputs(FULL_REPAINT_INTERVAL, || ScreenInput::FullRepaint)
} }
pub fn password_request_inputs(watch: RequestWatch) -> io::Result<impl Stream<Item = ScreenInput>> { pub fn password_request_inputs(watch: RequestWatch) -> io::Result<impl Stream<Item = ScreenInput>> {
+26 -22
View File
@@ -7,13 +7,12 @@ use crate::{
boot_model::{BootState, Phase, boot_origin::BootOrigin}, boot_model::{BootState, Phase, boot_origin::BootOrigin},
console_session::{ console_session::{
ask_password::RequestWatch, ask_password::RequestWatch,
console_takeover::Console, live_desk::{LiveDesk, password_request_inputs},
live_desk::{ stream_sources::{
LiveDesk, console_upkeep_inputs, full_repaint_inputs, password_request_inputs, BACKGROUND_CHECK_INTERVAL, frame_inputs, key_inputs, periodic_inputs,
prompt_check_inputs, termination_inputs,
}, },
stream_sources::{frame_inputs, key_inputs, termination_inputs}, watch_screen::{ScreenInput, WatchEnding, WatchScreen, watch_until_ending},
watch_screen::{WatchEnding, WatchScreen, watch_until_ending},
}, },
screen_settings::{color_scheme::Colors, config_file::Timing}, screen_settings::{color_scheme::Colors, config_file::Timing},
systemd_link::{ systemd_link::{
@@ -32,15 +31,13 @@ pub struct Settings {
pub colors: Colors, pub colors: Colors,
} }
struct ConfiguredStatusOnExit { const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(5);
scope: Scope,
} struct ConfiguredStatusOnExit;
impl Drop for ConfiguredStatusOnExit { impl Drop for ConfiguredStatusOnExit {
fn drop(&mut self) { fn drop(&mut self) {
if self.scope == Scope::System if let Ok(session) = Session::open(Scope::System) {
&& let Ok(session) = Session::open(Scope::System)
{
session.set_show_status(StatusOutput::Configured).ok(); session.set_show_status(StatusOutput::Configured).ok();
} }
} }
@@ -76,14 +73,15 @@ pub fn run(settings: &Settings) -> Result<(), Error> {
} }
async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> { async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> {
let _restores_status = ConfiguredStatusOnExit { let for_system = settings.scope == Scope::System;
scope: settings.scope, let _restores_status = for_system.then_some(ConfiguredStatusOnExit);
};
let requests = RequestWatch::open(); let requests = RequestWatch::open();
let desk = LiveDesk::new( let prompt_check: fn() -> ScreenInput = if requests.is_some() {
Console::take(settings.scope == Scope::System), || ScreenInput::PromptCheck
requests.is_some(), } else {
); || ScreenInput::PasswordRequests
};
let desk = LiveDesk::take_console(for_system);
let password_inputs = requests.map(password_request_inputs).transpose()?; let password_inputs = requests.map(password_request_inputs).transpose()?;
let event_inputs = stream::select( let event_inputs = stream::select(
stream::select( stream::select(
@@ -96,14 +94,20 @@ async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error>
), ),
); );
let timer_inputs = stream::select( let timer_inputs = stream::select(
stream::select(frame_inputs(), prompt_check_inputs()), stream::select(
stream::select(console_upkeep_inputs(), full_repaint_inputs()), frame_inputs(),
periodic_inputs(BACKGROUND_CHECK_INTERVAL, prompt_check),
),
stream::select(
periodic_inputs(BACKGROUND_CHECK_INTERVAL, || ScreenInput::ConsoleUpkeep),
periodic_inputs(FULL_REPAINT_INTERVAL, || ScreenInput::FullRepaint),
),
); );
let inputs = stream::select(event_inputs, timer_inputs); let inputs = stream::select(event_inputs, timer_inputs);
let mut screen = WatchScreen::new( let mut screen = WatchScreen::new(
BootState::new(phase), BootState::new(phase),
desk, desk,
BootOrigin::read(), BootOrigin::read,
settings.colors, settings.colors,
settings.timing, settings.timing,
Duration::ZERO, Duration::ZERO,
+58 -52
View File
@@ -11,8 +11,8 @@ use ratatui::{
use crate::{ use crate::{
boot_model::{BootChange, BootProjection, BootState, boot_origin::BootOrigin}, boot_model::{BootChange, BootProjection, BootState, boot_origin::BootOrigin},
boot_view::{BootView, PasswordPrompt, project_boot}, boot_view::{BootView, PasswordPrompt, project_boot},
console_session::console_palette::ConsolePalette, console_session::console_palette::ConsoleLook,
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs}, screen_settings::{color_scheme::Colors, config_file::Timing},
systemd_link::{link_error::Error, monotonic_clock::monotonic_now}, systemd_link::{link_error::Error, monotonic_clock::monotonic_now},
}; };
@@ -37,27 +37,30 @@ pub enum WatchEnding {
Failed(Error), Failed(Error),
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Refresh {
Steady,
Repaint,
Clear,
}
pub trait ConsoleDesk { pub trait ConsoleDesk {
fn glyphs(&self) -> &Glyphs;
fn palette(&self) -> ConsolePalette;
fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>>; fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>>;
fn press_key(&mut self, event: &Event, now: Duration) -> ControlFlow<WatchEnding>; fn press_key(&mut self, event: &Event, now: Duration) -> ControlFlow<WatchEnding>;
fn frame_passed(&mut self, state: &mut BootState, now: Duration) -> ControlFlow<WatchEnding>; fn frame_passed(&mut self, now: Duration) -> ControlFlow<WatchEnding, Vec<BootChange>>;
fn password_requests_changed(&mut self) {} fn look(&self) -> ConsoleLook {
ConsoleLook::default()
}
fn password_requests_changed(&mut self) -> Refresh {
Refresh::Steady
}
fn check_prompts(&mut self) {} fn check_prompts(&mut self) {}
fn keep_console_up(&mut self) -> bool { fn keep_console_up(&mut self) -> Refresh {
false Refresh::Steady
}
fn take_clear_request(&mut self) -> bool {
false
}
fn refreshed_origin(&self) -> Option<BootOrigin> {
None
} }
fn begin_handover(&mut self, _reached: &str, _deadline: Duration) {} fn begin_handover(&mut self, _reached: &str, _deadline: Duration) {}
@@ -71,8 +74,9 @@ struct CachedProjection {
pub struct WatchScreen<Desk> { pub struct WatchScreen<Desk> {
pub state: BootState, pub state: BootState,
pub desk: Desk, pub desk: Desk,
read_origin: fn() -> BootOrigin,
origin: BootOrigin, origin: BootOrigin,
full_repaint_due: bool, refresh_due: Refresh,
colors: Colors, colors: Colors,
timing: Timing, timing: Timing,
epoch: Duration, epoch: Duration,
@@ -83,7 +87,7 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
pub fn new( pub fn new(
state: BootState, state: BootState,
desk: Desk, desk: Desk,
origin: BootOrigin, read_origin: fn() -> BootOrigin,
colors: Colors, colors: Colors,
timing: Timing, timing: Timing,
epoch: Duration, epoch: Duration,
@@ -91,8 +95,9 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
Self { Self {
state, state,
desk, desk,
origin, read_origin,
full_repaint_due: false, origin: read_origin(),
refresh_due: Refresh::Steady,
colors, colors,
timing, timing,
epoch, epoch,
@@ -100,6 +105,10 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
} }
} }
fn request_refresh(&mut self, refresh: Refresh) {
self.refresh_due = self.refresh_due.max(refresh);
}
#[must_use] #[must_use]
pub fn now(&self) -> Duration { pub fn now(&self) -> Duration {
monotonic_now().saturating_sub(self.epoch) monotonic_now().saturating_sub(self.epoch)
@@ -110,21 +119,29 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
match input { match input {
ScreenInput::Boot(changes) => self.apply_boot_changes(changes, now), ScreenInput::Boot(changes) => self.apply_boot_changes(changes, now),
ScreenInput::Key(event) => self.desk.press_key(&event, now), ScreenInput::Key(event) => self.desk.press_key(&event, now),
ScreenInput::Frame => self.desk.frame_passed(&mut self.state, now), ScreenInput::Frame => {
let changes = self.desk.frame_passed(now)?;
if changes.is_empty() {
return ControlFlow::Continue(());
}
self.apply_boot_changes(changes, now)
}
ScreenInput::PromptCheck => { ScreenInput::PromptCheck => {
self.desk.check_prompts(); self.desk.check_prompts();
ControlFlow::Continue(()) ControlFlow::Continue(())
} }
ScreenInput::ConsoleUpkeep => { ScreenInput::ConsoleUpkeep => {
self.full_repaint_due |= self.desk.keep_console_up(); let refresh = self.desk.keep_console_up();
self.request_refresh(refresh);
ControlFlow::Continue(()) ControlFlow::Continue(())
} }
ScreenInput::FullRepaint => { ScreenInput::FullRepaint => {
self.full_repaint_due = true; self.request_refresh(Refresh::Repaint);
ControlFlow::Continue(()) ControlFlow::Continue(())
} }
ScreenInput::PasswordRequests => { ScreenInput::PasswordRequests => {
self.desk.password_requests_changed(); let refresh = self.desk.password_requests_changed();
self.request_refresh(refresh);
ControlFlow::Continue(()) ControlFlow::Continue(())
} }
ScreenInput::Terminate => ControlFlow::Break(WatchEnding::ViewerLeft), ScreenInput::Terminate => ControlFlow::Break(WatchEnding::ViewerLeft),
@@ -142,10 +159,8 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
.into_iter() .into_iter()
.for_each(|change| self.state.apply(change)); .for_each(|change| self.state.apply(change));
self.projection = None; self.projection = None;
if self.state.phase != phase_before if self.state.phase != phase_before {
&& let Some(origin) = self.desk.refreshed_origin() self.origin = (self.read_origin)();
{
self.origin = origin;
} }
if self.state.display_manager_started() { if self.state.display_manager_started() {
let display_manager = self let display_manager = self
@@ -183,10 +198,11 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
where where
Error: From<B::Error>, Error: From<B::Error>,
{ {
if self.desk.take_clear_request() { if self.refresh_due == Refresh::Clear {
terminal.clear()?; terminal.clear()?;
} }
let now = self.now(); let now = self.now();
let look = self.desk.look();
if self if self
.projection .projection
.as_ref() .as_ref()
@@ -208,20 +224,20 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
projection, projection,
colors: &self.colors, colors: &self.colors,
timing: &self.timing, timing: &self.timing,
glyphs: self.desk.glyphs(), glyphs: &look.glyphs,
now, now,
origin: &self.origin, origin: &self.origin,
password_prompt: self.desk.prompt(now), password_prompt: self.desk.prompt(now),
}, },
canvas.area(), canvas.area(),
); );
self.desk.palette().fit_frame(canvas.buffer_mut()); look.palette.fit_frame(canvas.buffer_mut());
})?; })?;
if self.full_repaint_due { if self.refresh_due == Refresh::Repaint {
let painted = completed.buffer.clone(); let painted = completed.buffer.clone();
overwrite_every_cell(terminal.backend_mut(), &painted)?; overwrite_every_cell(terminal.backend_mut(), &painted)?;
self.full_repaint_due = false;
} }
self.refresh_due = Refresh::Steady;
Ok(()) Ok(())
} }
} }
@@ -267,19 +283,10 @@ mod tests {
#[derive(Default)] #[derive(Default)]
struct HandoverRecorder { struct HandoverRecorder {
glyphs: Glyphs,
handovers: Vec<String>, handovers: Vec<String>,
} }
impl ConsoleDesk for HandoverRecorder { impl ConsoleDesk for HandoverRecorder {
fn glyphs(&self) -> &Glyphs {
&self.glyphs
}
fn palette(&self) -> ConsolePalette {
ConsolePalette::Terminal
}
fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> { fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> {
None None
} }
@@ -288,12 +295,8 @@ mod tests {
ControlFlow::Continue(()) ControlFlow::Continue(())
} }
fn frame_passed( fn frame_passed(&mut self, _now: Duration) -> ControlFlow<WatchEnding, Vec<BootChange>> {
&mut self, ControlFlow::Continue(Vec::new())
_state: &mut BootState,
_now: Duration,
) -> ControlFlow<WatchEnding> {
ControlFlow::Continue(())
} }
fn begin_handover(&mut self, reached: &str, _deadline: Duration) { fn begin_handover(&mut self, reached: &str, _deadline: Duration) {
@@ -301,17 +304,20 @@ mod tests {
} }
} }
fn screen_watching(state: BootState) -> WatchScreen<HandoverRecorder> { fn test_origin() -> BootOrigin {
let origin = BootOrigin { BootOrigin {
host: "test".to_owned(), host: "test".to_owned(),
system: None, system: None,
generation: None, generation: None,
kernel: "Linux".to_owned(), kernel: "Linux".to_owned(),
}; }
}
fn screen_watching(state: BootState) -> WatchScreen<HandoverRecorder> {
WatchScreen::new( WatchScreen::new(
state, state,
HandoverRecorder::default(), HandoverRecorder::default(),
origin, test_origin,
Colors::default(), Colors::default(),
Timing::default(), Timing::default(),
Duration::ZERO, Duration::ZERO,
+98 -84
View File
@@ -1,6 +1,8 @@
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
io, io,
iter::once,
mem,
ops::ControlFlow, ops::ControlFlow,
time::Duration, time::Duration,
}; };
@@ -12,17 +14,16 @@ use zeroize::Zeroizing;
use crate::{ use crate::{
boot_model::{ boot_model::{
ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts, UnitTimeouts, ActiveState, Activity, BootChange, BootState, JobKind, JobResult, Phase, UnitFacts,
boot_origin::BootOrigin, UnitTimeouts, boot_origin::BootOrigin,
}, },
boot_view::PasswordPrompt, boot_view::PasswordPrompt,
console_session::{ console_session::{
console_palette::ConsolePalette,
passphrase_input, passphrase_input,
stream_sources::{frame_inputs, key_inputs}, stream_sources::{frame_inputs, key_inputs},
watch_screen::{ConsoleDesk, WatchEnding, WatchScreen, watch_until_ending}, watch_screen::{ConsoleDesk, WatchEnding, WatchScreen, watch_until_ending},
}, },
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs}, screen_settings::{color_scheme::Colors, config_file::Timing},
systemd_link::monotonic_clock::monotonic_now, systemd_link::monotonic_clock::monotonic_now,
}; };
@@ -178,6 +179,7 @@ impl ScriptedJob {
} }
struct Script { struct Script {
steps: &'static [Step],
jobs: Vec<ScriptedJob>, jobs: Vec<ScriptedJob>,
started: HashMap<&'static str, Duration>, started: HashMap<&'static str, Duration>,
finished: HashSet<&'static str>, finished: HashSet<&'static str>,
@@ -191,32 +193,39 @@ struct Answer {
} }
impl Script { impl Script {
fn begin( fn begin(steps: &'static [Step], first_job: u32) -> Self {
steps: &'static [Step],
describe: fn(&str) -> Option<&'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 { Self {
jobs, steps,
jobs: steps
.iter()
.zip(first_job..)
.map(|(step, id)| ScriptedJob { id, step })
.collect(),
started: HashMap::new(), started: HashMap::new(),
finished: HashSet::new(), finished: HashSet::new(),
answer: None, answer: None,
} }
} }
fn opening_changes(
&self,
describe: fn(&str) -> Option<&'static str>,
now: Duration,
) -> Vec<BootChange> {
once(BootChange::SetRoot(self.steps[0].unit.to_owned()))
.chain(self.jobs.iter().map(|job| BootChange::TrackUnit {
facts: job.facts(self.steps, describe),
activity: job.initial_activity(),
}))
.chain(self.jobs.iter().map(|job| BootChange::QueueJob {
id: job.id,
unit: job.step.unit.to_owned(),
kind: job.kind(),
at: now,
}))
.collect()
}
fn asking(&self) -> Option<&'static Step> { fn asking(&self) -> Option<&'static Step> {
self.jobs.iter().map(|job| job.step).find(|step| { self.jobs.iter().map(|job| job.step).find(|step| {
step.asks.is_some() step.asks.is_some()
@@ -281,74 +290,92 @@ impl Script {
!self.finished.contains(job.step.unit) && done_at.is_some_and(|done_at| now >= done_at) !self.finished.contains(job.step.unit) && done_at.is_some_and(|done_at| now >= done_at)
} }
fn advance(&mut self, state: &mut BootState, now: Duration) { fn advance(&mut self, now: Duration) -> Vec<BootChange> {
let starting: HashSet<&'static str> = self let starting: HashSet<&'static str> = self
.jobs .jobs
.iter() .iter()
.filter(|job| self.is_ready(job)) .filter(|job| self.is_ready(job))
.map(|job| job.step.unit) .map(|job| job.step.unit)
.collect(); .collect();
self.jobs self.started
.iter() .extend(starting.iter().map(|unit| (*unit, now)));
.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 let due: HashSet<&'static str> = self
.jobs .jobs
.iter() .iter()
.filter(|job| self.is_due(job, now)) .filter(|job| self.is_due(job, now))
.map(|job| job.step.unit) .map(|job| job.step.unit)
.collect(); .collect();
self.jobs let changes = self
.jobs
.iter() .iter()
.filter(|job| due.contains(job.step.unit)) .filter(|job| starting.contains(job.step.unit))
.for_each(|job| { .map(|job| BootChange::UpdateActivity {
state.update_activity(job.step.unit, job.settled_activity(now)); unit: job.step.unit.to_owned(),
state.finish_job(job.id, job.outcome(), now); activity: job.started_activity(now),
}); })
.chain(
self.jobs
.iter()
.filter(|job| due.contains(job.step.unit))
.flat_map(|job| {
[
BootChange::UpdateActivity {
unit: job.step.unit.to_owned(),
activity: job.settled_activity(now),
},
BootChange::FinishJob {
id: job.id,
result: job.outcome(),
at: now,
},
]
}),
)
.collect();
self.finished.extend(due); self.finished.extend(due);
changes
} }
} }
struct DemoDesk { struct DemoDesk {
script: Script, script: Script,
after_switch_root: Option<&'static [Step]>,
describe: fn(&str) -> Option<&'static str>, describe: fn(&str) -> Option<&'static str>,
next_stage: &'static [Step],
settled_at: Option<Duration>, settled_at: Option<Duration>,
typed: Zeroizing<String>, typed: Zeroizing<String>,
glyphs: Glyphs, }
impl DemoDesk {
fn enter_next_stage(&mut self, now: Duration) -> Vec<BootChange> {
if !self.script.is_done() || self.next_stage.is_empty() {
return Vec::new();
}
self.script = Script::begin(mem::take(&mut self.next_stage), 1000);
once(BootChange::SwitchRoot { at: now })
.chain(self.script.opening_changes(self.describe, now))
.collect()
}
} }
impl ConsoleDesk for DemoDesk { impl ConsoleDesk for DemoDesk {
fn frame_passed(&mut self, state: &mut BootState, now: Duration) -> ControlFlow<WatchEnding> { fn frame_passed(&mut self, now: Duration) -> ControlFlow<WatchEnding, Vec<BootChange>> {
self.script.advance(state, now); let changes: Vec<BootChange> = self
if self.script.is_done() .script
&& let Some(steps) = self.after_switch_root.take() .advance(now)
{ .into_iter()
state.switch_root(now); .chain(self.enter_next_stage(now))
self.script = Script::begin(steps, self.describe, 1000, state, now); .collect();
}
if !self.script.is_done() { if !self.script.is_done() {
return ControlFlow::Continue(()); return ControlFlow::Continue(changes);
} }
let settled_at = *self.settled_at.get_or_insert(now); let settled_at = *self.settled_at.get_or_insert(now);
if now.saturating_sub(settled_at) >= FINAL_FRAME { if now.saturating_sub(settled_at) >= FINAL_FRAME {
ControlFlow::Break(WatchEnding::BootCompleted) ControlFlow::Break(WatchEnding::BootCompleted)
} else { } else {
ControlFlow::Continue(()) ControlFlow::Continue(changes)
} }
} }
fn glyphs(&self) -> &Glyphs {
&self.glyphs
}
fn palette(&self) -> ConsolePalette {
ConsolePalette::Terminal
}
fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>> { fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>> {
self.script.prompt(&self.typed, now) self.script.prompt(&self.typed, now)
} }
@@ -378,27 +405,23 @@ fn demo_origin() -> BootOrigin {
} }
async fn play_scenario(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<()> { async fn play_scenario(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<()> {
let script = Script::begin(scenario.steps, 1);
let mut state = BootState::new(scenario.phase); let mut state = BootState::new(scenario.phase);
let script = Script::begin( script
scenario.steps, .opening_changes(scenario.describe, Duration::ZERO)
scenario.describe, .into_iter()
1, .for_each(|change| state.apply(change));
&mut state,
Duration::ZERO,
);
let desk = DemoDesk { let desk = DemoDesk {
script, script,
after_switch_root: (!scenario.after_switch_root.is_empty())
.then_some(scenario.after_switch_root),
describe: scenario.describe, describe: scenario.describe,
next_stage: scenario.after_switch_root,
settled_at: None, settled_at: None,
typed: passphrase_input::empty(), typed: passphrase_input::empty(),
glyphs: Glyphs::default(),
}; };
let mut screen = WatchScreen::new( let mut screen = WatchScreen::new(
state, state,
desk, desk,
demo_origin(), demo_origin,
Colors::default(), Colors::default(),
Timing::default(), Timing::default(),
monotonic_now(), monotonic_now(),
@@ -430,16 +453,10 @@ mod tests {
KEY_DERIVATION, KEY_DERIVATION,
)]; )];
struct AskingDemo { fn asking_demo() -> Script {
script: Script, let mut script = Script::begin(UNLOCK_ONLY, 1);
state: BootState, script.advance(Duration::ZERO);
} script
fn asking_demo() -> AskingDemo {
let mut state = BootState::new(Phase::Initrd);
let mut script = Script::begin(UNLOCK_ONLY, |_| None, 1, &mut state, Duration::ZERO);
script.advance(&mut state, Duration::ZERO);
AskingDemo { script, state }
} }
#[test] #[test]
@@ -449,7 +466,7 @@ mod tests {
#[test] #[test]
fn a_wrong_answer_is_checked_then_called_out() { fn a_wrong_answer_is_checked_then_called_out() {
let AskingDemo { mut script, .. } = asking_demo(); let mut script = asking_demo();
let asked = script.prompt("", Duration::ZERO).expect("asking"); let asked = script.prompt("", Duration::ZERO).expect("asking");
assert_eq!(asked.hint, Some(DEMO_PASSPHRASE_HINT)); assert_eq!(asked.hint, Some(DEMO_PASSPHRASE_HINT));
assert!(!asked.rejected); assert!(!asked.rejected);
@@ -462,12 +479,9 @@ mod tests {
#[test] #[test]
fn the_right_answer_unlocks_and_closes_the_prompt() { fn the_right_answer_unlocks_and_closes_the_prompt() {
let AskingDemo { let mut script = asking_demo();
mut script,
mut state,
} = asking_demo();
script.answer(DEMO_PASSPHRASE, Duration::ZERO); script.answer(DEMO_PASSPHRASE, Duration::ZERO);
script.advance(&mut state, KEY_DERIVATION); script.advance(KEY_DERIVATION);
assert!(script.is_done()); assert!(script.is_done());
assert!(script.prompt("", KEY_DERIVATION).is_none()); assert!(script.prompt("", KEY_DERIVATION).is_none());
} }