diff --git a/Cargo.toml b/Cargo.toml index eb6cdd5..7d41f85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ clap = { version = "4.6.7", features = ["derive"] } crossterm = "0.29.0" dbus = "0.9.12" jiff = { version = "0.2.38", default-features = false, features = ["serde", "std"] } -ratatui = { version = "0.30.2", features = ["serde"] } +ratatui = { version = "0.30.2", features = ["serde", "unstable-rendered-line-info"] } rustix = { version = "1.1.5", features = ["fs", "process", "stdio", "system", "termios", "time"] } serde = { version = "1.0.229", features = ["derive"] } signal-hook = "0.4.5" diff --git a/README.md b/README.md index 50f4d75..655895f 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,12 @@ the units that have to stop first, until systemd hands over to ```sh cargo run --example boot cargo run --example shutdown +cargo run --example luks ``` -play a scripted boot or poweroff without systemd; `q` quits. `nix run .#vm` boots a demo +play a scripted boot, poweroff or boot from an encrypted root without systemd; +`q` quits. The encrypted root unlocks with the passphrase `demo`; `Esc` quits +while it asks. `nix run .#vm` boots a demo VM in a window. ## Install diff --git a/examples/luks.rs b/examples/luks.rs new file mode 100644 index 0000000..55b4f1d --- /dev/null +++ b/examples/luks.rs @@ -0,0 +1,204 @@ +use std::{io, time::Duration}; + +use bootvine::{ + model::Phase, + script::{Scenario, Step, play, step, unlocking}, +}; + +const ROOT_PARTITION: &str = + "dev-disk-by\\x2duuid-7c2e9f4a\\x2d1b3d\\x2d4e8f\\x2d9a6c\\x2d2d5b8e1f0c3a.device"; + +const INITRD: &[Step] = &[ + step( + "initrd.target", + &["initrd-fs.target", "initrd-root-fs.target"], + Duration::ZERO, + ), + step( + "initrd-fs.target", + &["initrd-root-fs.target"], + Duration::ZERO, + ), + step("initrd-root-fs.target", &["sysroot.mount"], Duration::ZERO), + step( + "sysroot.mount", + &["systemd-fsck-root.service"], + Duration::from_millis(400), + ), + step( + "systemd-fsck-root.service", + &["initrd-root-device.target"], + Duration::from_millis(600), + ), + step( + "initrd-root-device.target", + &["dev-mapper-cryptroot.device"], + Duration::ZERO, + ), + step( + "dev-mapper-cryptroot.device", + &["cryptsetup.target"], + Duration::from_millis(100), + ), + step( + "cryptsetup.target", + &["systemd-cryptsetup@cryptroot.service"], + Duration::ZERO, + ), + unlocking( + "systemd-cryptsetup@cryptroot.service", + &["cryptsetup-pre.target", ROOT_PARTITION], + "Please enter passphrase for disk Samsung SSD 980 PRO 1TB (cryptroot):", + Duration::from_millis(2000), + ), + step( + "cryptsetup-pre.target", + &["systemd-udevd.service"], + Duration::ZERO, + ), + step( + ROOT_PARTITION, + &["systemd-udev-trigger.service"], + Duration::from_millis(1100), + ), + step( + "systemd-udev-trigger.service", + &["systemd-udevd.service"], + Duration::from_millis(500), + ), + step( + "systemd-udevd.service", + &["systemd-tmpfiles-setup-dev.service"], + Duration::from_millis(200), + ), + step( + "systemd-tmpfiles-setup-dev.service", + &["kmod-static-nodes.service"], + Duration::from_millis(100), + ), + step("kmod-static-nodes.service", &[], Duration::from_millis(100)), + step("systemd-journald.service", &[], Duration::from_millis(300)), + step( + "systemd-modules-load.service", + &[], + Duration::from_millis(900), + ), + step( + "systemd-vconsole-setup.service", + &["systemd-modules-load.service"], + Duration::from_millis(200), + ), + step( + "systemd-sysctl.service", + &["systemd-modules-load.service"], + Duration::from_millis(100), + ), +]; + +const HOST: &[Step] = &[ + step( + "graphical.target", + &["multi-user.target", "display-manager.service"], + Duration::ZERO, + ), + step( + "display-manager.service", + &["systemd-logind.service"], + Duration::from_millis(600), + ), + step( + "multi-user.target", + &[ + "basic.target", + "NetworkManager.service", + "systemd-logind.service", + "systemd-timesyncd.service", + ], + Duration::ZERO, + ), + step("basic.target", &["sysinit.target"], Duration::ZERO), + step( + "sysinit.target", + &[ + "systemd-tmpfiles-setup.service", + "systemd-udev-trigger.service", + "home.mount", + ], + Duration::ZERO, + ), + step( + "systemd-tmpfiles-setup.service", + &[], + Duration::from_millis(400), + ), + step( + "systemd-udev-trigger.service", + &[], + Duration::from_millis(800), + ), + step("home.mount", &[], Duration::from_millis(300)), + step( + "systemd-logind.service", + &["basic.target"], + Duration::from_millis(300), + ), + step( + "NetworkManager.service", + &["basic.target"], + Duration::from_millis(1400), + ), + step( + "systemd-timesyncd.service", + &["basic.target"], + Duration::from_millis(500), + ), +]; + +fn description(unit: &str) -> &'static str { + match unit { + "initrd.target" => "Initrd Default Target", + "initrd-fs.target" => "Initrd File Systems", + "initrd-root-fs.target" => "Initrd Root File System", + "initrd-root-device.target" => "Initrd Root Device", + "sysroot.mount" => "/sysroot", + "systemd-fsck-root.service" => "File System Check on /dev/mapper/cryptroot", + "dev-mapper-cryptroot.device" => "/dev/mapper/cryptroot", + "cryptsetup.target" => "Local Encrypted Volumes", + "cryptsetup-pre.target" => "Local Encrypted Volumes (Pre)", + "systemd-cryptsetup@cryptroot.service" => "Cryptography Setup for cryptroot", + ROOT_PARTITION => "Samsung SSD 980 PRO 1TB cryptroot", + "systemd-udev-trigger.service" => "Coldplug All udev Devices", + "systemd-udevd.service" => "Rule-based Manager for Device Events and Files", + "systemd-tmpfiles-setup-dev.service" => "Create Static Device Nodes in /dev", + "kmod-static-nodes.service" => "Create List of Static Device Nodes", + "systemd-journald.service" => "Journal Service", + "systemd-modules-load.service" => "Load Kernel Modules", + "systemd-vconsole-setup.service" => "Virtual Console Setup", + "systemd-sysctl.service" => "Apply Kernel Variables", + "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", + "home.mount" => "/home", + "systemd-logind.service" => "User Login Management", + "NetworkManager.service" => "Network Manager", + "systemd-timesyncd.service" => "Network Time Synchronization", + _ => "", + } +} + +fn main() -> io::Result<()> { + ratatui::run(|terminal| { + play( + terminal, + &Scenario { + phase: Phase::Initrd, + steps: INITRD, + after_switch_root: HOST, + describe: description, + }, + ) + }) +} diff --git a/src/lib.rs b/src/lib.rs index df963c6..54f0f1e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,5 +3,6 @@ pub mod glyphs; pub mod model; pub mod origin; pub mod palette; +pub mod passphrase; pub mod script; pub mod view; diff --git a/src/passphrase.rs b/src/passphrase.rs new file mode 100644 index 0000000..9a16cf0 --- /dev/null +++ b/src/passphrase.rs @@ -0,0 +1,81 @@ +use std::mem::take; + +use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; +use zeroize::Zeroizing; + +const ROOM_FOR_TYPING: usize = 512; + +#[must_use] +pub fn empty() -> Zeroizing { + Zeroizing::new(String::with_capacity(ROOM_FOR_TYPING)) +} + +#[must_use] +pub fn masked(typed: &str) -> String { + "*".repeat(typed.chars().count()) +} + +pub fn type_key(typed: &mut Zeroizing, event: &Event) -> Option> { + let Event::Key(KeyEvent { + code, + modifiers, + kind: KeyEventKind::Press, + .. + }) = event + else { + return None; + }; + match code { + KeyCode::Enter => return Some(Zeroizing::new(take(&mut **typed))), + KeyCode::Backspace => { + typed.pop(); + } + KeyCode::Char('u') if modifiers.contains(KeyModifiers::CONTROL) => typed.clear(), + KeyCode::Char(_) if modifiers.contains(KeyModifiers::CONTROL) => {} + KeyCode::Char(character) if typed.len() + character.len_utf8() <= ROOM_FOR_TYPING => { + typed.push(*character); + } + _ => {} + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn press(code: KeyCode) -> Event { + Event::Key(KeyEvent::from(code)) + } + + fn typed(text: &str) -> Zeroizing { + let mut typed = empty(); + text.chars() + .map(KeyCode::Char) + .for_each(|code| assert_eq!(type_key(&mut typed, &press(code)), None)); + typed + } + + #[test] + fn hides_what_is_typed() { + let mut typed = typed("secret"); + type_key(&mut typed, &press(KeyCode::Backspace)); + assert_eq!(masked(&typed), "*****"); + } + + #[test] + fn control_u_clears() { + let mut typed = typed("secret"); + let control_u = Event::Key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)); + type_key(&mut typed, &control_u); + assert_eq!(typed.as_str(), ""); + } + + #[test] + fn enter_hands_over_what_was_typed() { + let mut typed = typed("secret"); + let submitted = type_key(&mut typed, &press(KeyCode::Enter)); + assert_eq!(submitted.as_deref().map(String::as_str), Some("secret")); + assert_eq!(typed.as_str(), ""); + } +} diff --git a/src/password.rs b/src/password.rs index 7831f06..46530d6 100644 --- a/src/password.rs +++ b/src/password.rs @@ -5,8 +5,8 @@ use std::{ time::Duration, }; -use bootvine::view::PasswordPrompt; -use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; +use bootvine::{passphrase, view::PasswordPrompt}; +use crossterm::event::Event; use rustix::process::{Pid, test_kill_process}; use zeroize::Zeroizing; @@ -15,7 +15,6 @@ use crate::clock::monotonic_now; const REQUESTS: &str = "/run/systemd/ask-password"; const REQUEST_PREFIX: &str = "ask."; const ASK_SECTION: &str = "[Ask]"; -const ROOM_FOR_TYPING: usize = 512; #[derive(Debug, PartialEq, Eq)] pub struct PasswordRequest { @@ -137,16 +136,18 @@ impl PasswordEntry { ); Some(Self { request, - typed: Zeroizing::new(String::with_capacity(ROOM_FOR_TYPING)), + typed: passphrase::empty(), sent: false, }) } pub fn prompt(&self) -> PasswordPrompt<'_> { - let input = match (self.sent, self.request.echo, self.request.silent) { - (true, _, _) | (false, _, true) => String::new(), - (false, true, false) => self.typed.as_str().to_owned(), - (false, false, false) => "*".repeat(self.typed.chars().count()), + let input = if self.request.silent { + String::new() + } else if self.request.echo { + self.typed.to_string() + } else { + passphrase::masked(&self.typed) }; PasswordPrompt { message: &self.request.message, @@ -156,43 +157,23 @@ impl PasswordEntry { } pub fn type_key(&mut self, event: &Event) -> io::Result<()> { - let Event::Key(KeyEvent { - code, - modifiers, - kind: KeyEventKind::Press, - .. - }) = event - else { - return Ok(()); - }; if self.sent { return Ok(()); } - match code { - KeyCode::Enter => { - self.request.answer(&self.typed)?; - self.sent = true; - self.typed.clear(); - eprintln!("bootvine: answered a password prompt"); - } - KeyCode::Backspace => { - self.typed.pop(); - } - KeyCode::Char('u') if modifiers.contains(KeyModifiers::CONTROL) => self.typed.clear(), - KeyCode::Char(_) if modifiers.contains(KeyModifiers::CONTROL) => {} - KeyCode::Char(character) - if self.typed.len() + character.len_utf8() <= ROOM_FOR_TYPING => - { - self.typed.push(*character); - } - _ => {} - } + let Some(submitted) = passphrase::type_key(&mut self.typed, event) else { + return Ok(()); + }; + self.request.answer(&submitted)?; + self.sent = true; + eprintln!("bootvine: answered a password prompt"); Ok(()) } } #[cfg(test)] mod tests { + use crossterm::event::{KeyCode, KeyEvent}; + use super::*; const CRYPTSETUP_ASK: &str = concat!( @@ -236,7 +217,7 @@ mod tests { fn hides_what_is_typed() { let mut entry = PasswordEntry { request: PasswordRequest::parse(Path::new("ask.x"), CRYPTSETUP_ASK).expect("parsed"), - typed: Zeroizing::new(String::new()), + typed: passphrase::empty(), sent: false, }; "secret".chars().for_each(|character| { diff --git a/src/script.rs b/src/script.rs index 069629b..ad95789 100644 --- a/src/script.rs +++ b/src/script.rs @@ -15,18 +15,22 @@ use crate::{ model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts}, origin::BootOrigin, palette::Palette, - view::BootView, + passphrase, + view::{BootView, PasswordPrompt}, }; const FRAME_INTERVAL: Duration = Duration::from_millis(100); const FINAL_FRAME: Duration = Duration::from_secs(3); +pub const DEMO_PASSPHRASE: &str = "demo"; + pub struct Step { unit: &'static str, after: &'static [&'static str], work: Duration, fails: bool, stops: bool, + asks: Option<&'static str>, } #[must_use] @@ -37,28 +41,36 @@ pub const fn step(unit: &'static str, after: &'static [&'static str], work: Dura work, fails: false, stops: false, + asks: None, } } #[must_use] pub const fn failing(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step { Step { - unit, - after, - work, fails: true, - stops: false, + ..step(unit, after, work) } } #[must_use] pub const fn stopping(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step { Step { - unit, - after, - work, - fails: false, stops: true, + ..step(unit, after, work) + } +} + +#[must_use] +pub const fn unlocking( + unit: &'static str, + after: &'static [&'static str], + message: &'static str, + key_derivation: Duration, +) -> Step { + Step { + asks: Some(message), + ..step(unit, after, key_derivation) } } @@ -127,10 +139,12 @@ impl ScriptedJob { } 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, + let state = if self.step.fails { + ActiveState::Failed + } else if self.step.stops { + ActiveState::Inactive + } else { + ActiveState::Active }; Activity { state: Some(state), @@ -144,6 +158,13 @@ struct Script { jobs: Vec, started: HashMap<&'static str, Duration>, finished: HashSet<&'static str>, + answer: Option, +} + +#[derive(Clone, Copy)] +struct Answer { + checked_at: Duration, + unlocks: bool, } impl Script { @@ -169,9 +190,40 @@ impl Script { jobs, started: HashMap::new(), finished: HashSet::new(), + answer: None, } } + fn asking(&self) -> Option<&'static Step> { + self.jobs.iter().map(|job| job.step).find(|step| { + step.asks.is_some() + && self.started.contains_key(step.unit) + && !self.finished.contains(step.unit) + }) + } + + fn is_checking(&self, now: Duration) -> bool { + self.answer.is_some_and(|answer| now < answer.checked_at) + } + + fn prompt(&self, typed: &str, now: Duration) -> Option> { + Some(PasswordPrompt { + message: self.asking()?.asks?, + input: passphrase::masked(typed), + sent: self.is_checking(now), + }) + } + + fn answer(&mut self, submitted: &str, now: Duration) { + let Some(step) = self.asking() else { + return; + }; + self.answer = Some(Answer { + checked_at: now + step.work, + unlocks: submitted == DEMO_PASSPHRASE, + }); + } + fn is_ready(&self, job: &ScriptedJob) -> bool { !self.started.contains_key(job.step.unit) && job @@ -186,11 +238,17 @@ impl Script { } fn is_due(&self, job: &ScriptedJob, now: Duration) -> bool { - !self.finished.contains(job.step.unit) - && self + let done_at = match job.step.asks { + Some(_) => self + .answer + .filter(|answer| answer.unlocks) + .map(|answer| answer.checked_at), + None => self .started .get(job.step.unit) - .is_some_and(|started| now >= *started + job.step.work) + .map(|started| *started + job.step.work), + }; + !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) { @@ -224,12 +282,18 @@ impl Script { } } -fn wants_to_quit() -> io::Result { - if !event::poll(FRAME_INTERVAL)? { - return Ok(false); +fn next_event() -> io::Result> { + if event::poll(FRAME_INTERVAL)? { + event::read().map(Some) + } else { + Ok(None) } - Ok( - matches!(event::read()?, Event::Key(key) if matches!(key.code, KeyCode::Char('q') | KeyCode::Esc)), +} + +fn quits(event: &Event, typing: bool) -> bool { + matches!( + event, + Event::Key(key) if key.code == KeyCode::Esc || (!typing && key.code == KeyCode::Char('q')) ) } @@ -247,6 +311,7 @@ pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<( let mut switched_root = scenario.after_switch_root.is_empty(); let mut settled_at = None; let mut frame = 0; + let mut typed = passphrase::empty(); loop { script.advance(&mut state, now()); if script.is_done() && !switched_root { @@ -270,7 +335,7 @@ pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<( now: now(), origin: &origin, frame, - password_prompt: None, + password_prompt: script.prompt(&typed, now()), }, canvas.area(), ); @@ -279,8 +344,17 @@ pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<( { return Ok(()); } - if wants_to_quit()? { - return Ok(()); + if let Some(event) = next_event()? { + let asking = script.asking().is_some(); + if quits(&event, asking) { + return Ok(()); + } + if asking + && !script.is_checking(now()) + && let Some(submitted) = passphrase::type_key(&mut typed, &event) + { + script.answer(&submitted, now()); + } } frame += 1; } diff --git a/src/view.rs b/src/view.rs index b845c88..d0019cb 100644 --- a/src/view.rs +++ b/src/view.rs @@ -17,7 +17,7 @@ use unicode_width::UnicodeWidthStr; pub use self::chrome::PasswordPrompt; use self::{ - chrome::{FOOTER_HEIGHT, Footer, Header, PasswordBar}, + chrome::{FOOTER_HEIGHT, Footer, Header, PasswordPopup}, stages::Stages, timeline::Timeline, tree::UnitTree, @@ -183,14 +183,14 @@ impl Widget for BootView<'_> { if heights.timeline > 0 { timeline.render(timeline_area, buf); } - match &self.password_prompt { - Some(asking) => PasswordBar { + footer.render(footer_area, buf); + if let Some(asking) = &self.password_prompt { + PasswordPopup { asking, palette: self.palette, glyphs: self.glyphs, } - .render(footer_area, buf), - None => footer.render(footer_area, buf), + .render(area, buf); } } } @@ -260,6 +260,16 @@ mod tests { } fn render(state: &BootState, now: Duration, width: u16, height: u16) -> Vec { + screen_lines(&render_prompted(state, now, width, height, None)) + } + + fn render_prompted( + state: &BootState, + now: Duration, + width: u16, + height: u16, + password_prompt: Option, + ) -> Buffer { let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend"); terminal .draw(|frame| { @@ -277,16 +287,20 @@ mod tests { kernel: "Linux 7.2.9".to_owned(), }, frame: 1, - password_prompt: None, + password_prompt, }, frame.area(), ); }) .expect("draw"); - let buffer = terminal.backend().buffer().clone(); - (0..height) + terminal.backend().buffer().clone() + } + + fn screen_lines(buffer: &Buffer) -> Vec { + let area = buffer.area; + (0..area.height) .map(|y| { - let line: String = (0..width) + let line: String = (0..area.width) .map(|x| buffer[(x, y)].symbol().to_owned()) .collect(); line.trim_end().to_owned() @@ -477,6 +491,89 @@ mod tests { assert!(lines[5].ends_with("web"), "{screen}"); } + const CRYPTSETUP_MESSAGE: &str = + "Please enter passphrase for disk Samsung SSD 980 PRO 1TB (cryptroot):"; + + #[test] + fn password_prompt_floats_over_a_dimmed_view() { + let buffer = render_prompted( + &boot_in_progress(), + 12_400 * MS, + 110, + 24, + Some(PasswordPrompt { + message: CRYPTSETUP_MESSAGE, + input: "***".to_owned(), + sent: false, + }), + ); + let lines = screen_lines(&buffer); + let screen = lines.join("\n"); + let title_row = lines + .iter() + .position(|line| line.contains("┌ Password ")) + .unwrap_or_else(|| panic!("{screen}")); + assert!(lines[title_row].starts_with(' '), "{screen}"); + assert!( + lines[title_row + 1].contains(&format!("│ {CRYPTSETUP_MESSAGE}")), + "{screen}" + ); + assert!(lines[title_row + 3].contains("│ > ***_"), "{screen}"); + assert!(lines[title_row + 4].contains("Enter unlock"), "{screen}"); + assert!( + lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"), + "{screen}" + ); + assert_eq!(buffer[(0, 0)].fg, Palette::default().muted, "{screen}"); + let corner = buffer + .content + .iter() + .find(|cell| cell.symbol() == "┌") + .unwrap_or_else(|| panic!("{screen}")); + assert_eq!(corner.fg, Palette::default().running, "{screen}"); + } + + #[test] + fn answered_password_prompt_shows_it_is_checking() { + let lines = screen_lines(&render_prompted( + &boot_in_progress(), + 12_400 * MS, + 110, + 24, + Some(PasswordPrompt { + message: CRYPTSETUP_MESSAGE, + input: String::new(), + sent: true, + }), + )); + assert!( + lines.iter().any(|line| line.contains("│ Checking…")), + "{}", + lines.join("\n") + ); + } + + #[test] + fn long_password_messages_wrap_inside_narrow_screens() { + let lines = screen_lines(&render_prompted( + &boot_in_progress(), + 12_400 * MS, + 50, + 24, + Some(PasswordPrompt { + message: CRYPTSETUP_MESSAGE, + input: String::new(), + sent: false, + }), + )); + let screen = lines.join("\n"); + assert!( + lines.iter().any(|line| line.contains("(cryptroot):")), + "{screen}" + ); + assert!(lines.iter().any(|line| line.contains("> _")), "{screen}"); + } + #[test] fn sub_second_runs_stay_off_the_timeline() { let mut state = boot_in_progress(); diff --git a/src/view/chrome.rs b/src/view/chrome.rs index c8d443b..9661090 100644 --- a/src/view/chrome.rs +++ b/src/view/chrome.rs @@ -2,13 +2,13 @@ use std::{iter::once, time::Duration}; use ratatui::{ buffer::Buffer, - layout::Rect, - style::Stylize, + layout::{Constraint, Rect}, + style::{Style, Stylize}, text::{Line, Span}, - widgets::{Block, Borders, Paragraph, Widget}, + widgets::{Block, Borders, Clear, Padding, Paragraph, Widget, Wrap}, }; -use super::{DURATION_WIDTH, ELAPSED, rule}; +use super::{DURATION_WIDTH, ELAPSED}; use crate::{glyphs::Glyphs, model::Tally, origin::BootOrigin, palette::Palette}; pub const FOOTER_HEIGHT: u16 = 2; @@ -92,27 +92,57 @@ pub struct PasswordPrompt<'a> { pub sent: bool, } -pub struct PasswordBar<'a> { +pub struct PasswordPopup<'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) +impl PasswordPopup<'_> { + const MIN_WIDTH: u16 = 40; + + fn input(&self) -> Line<'static> { + if self.asking.sent { + Line::from(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); + Line::from(vec![ + "> ".fg(self.palette.running), + format!("{}_", self.asking.input).fg(self.palette.text), + ]) + } + } + + fn paragraph(&self) -> Paragraph<'_> { + Paragraph::new(vec![ + Line::from(self.asking.message.fg(self.palette.text).bold()), + Line::default(), + self.input(), + ]) + .wrap(Wrap { trim: false }) + .block( + Block::bordered() + .border_style(self.palette.running) + .padding(Padding::horizontal(2)) + .title(" Password ".fg(self.palette.running).bold()) + .title_bottom( + Line::from(" Enter unlock · Ctrl+U clear ".fg(self.palette.muted)) + .right_aligned(), + ), + ) + } +} + +impl Widget for PasswordPopup<'_> { + fn render(self, area: Rect, buf: &mut Buffer) { + buf.set_style(area, Style::new().fg(self.palette.muted)); + let paragraph = self.paragraph(); + let width = u16::try_from(paragraph.line_width()) + .unwrap_or(u16::MAX) + .max(Self::MIN_WIDTH) + .min(area.width); + let height = u16::try_from(paragraph.line_count(width)).unwrap_or(u16::MAX); + let popup = area.centered(Constraint::Length(width), Constraint::Length(height)); + Clear.render(popup, buf); + paragraph.render(popup, buf); } }