onionwire/tests/tui_frames.rs

555 lines
19 KiB
Rust
Raw Normal View History

//! Visual audit dumps of the current OnionWire TUI.
//!
//! This crate cannot construct `App` (private, needs `Node` / Arti). Public
//! draw path used where it exists (`draw_share`, chrome helpers, overlay copy).
//! Main / profile / confirm screens labeled RECONSTRUCTED copy the layout
//! constants and copy from `src/tui.rs` so a reviewer can see the shape.
//!
//! Print frames:
//! cargo test --locked --test tui_frames -- --nocapture dump_audit_frames
//!
//! `chars().count()` width checks here match `tests/tui_chrome.rs` on purpose.
//! They are the known-wrong metric (see `chars_count_is_not_terminal_cells`).
use onionwire::qr;
use onionwire::tui::{
backup_screen_text, banner_for_width, compact_banner, draw_share, fingerprint_mismatch_banner,
help_overlay_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text,
rotate_screen_text, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner,
ProfileEditor, WipeKind,
};
use onionwire::FriendProfile;
use ratatui::backend::TestBackend;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::Frame;
use ratatui::Terminal;
const SIZES: [(u16, u16); 3] = [(80, 24), (120, 40), (200, 60)];
const FP: &str = "abcdef0123456789deadbeefcafebabe";
const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
const LONG_MSG: &str = "them: this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
struct FriendRow {
name: &'static str,
fp: &'static str,
last_ok: bool,
}
fn fp8(s: &str) -> String {
s.chars().take(8).collect()
}
struct MainStandin<'a> {
friends: &'a [FriendRow],
selected: usize,
chat_lines: &'a [&'a str],
composer: &'a str,
alert: Option<&'a str>,
status_note: Option<&'a str>,
}
fn dump_buffer(label: &str, w: u16, h: u16, buf: &ratatui::buffer::Buffer) {
println!();
println!("===== {label} {w}x{h} =====");
for y in 0..h {
let mut row = String::new();
for x in 0..w {
row.push_str(buf[(x, y)].symbol());
}
let cells = row.chars().count();
assert!(
cells <= w as usize,
"{label} row {y} chars().count()={cells} > {w}: {row:?}"
);
println!("{row}");
}
}
fn draw_to(w: u16, h: u16, label: &str, render: impl FnOnce(&mut Frame)) {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(render).expect("draw");
dump_buffer(label, w, h, terminal.backend().buffer());
}
fn pane_block(title: &str) -> Block<'_> {
// Real `App::pane_block` only changes border/title color. TestBackend
// dumps are glyphs, so focused chat/composer look identical to unfocused.
Block::default().borders(Borders::ALL).title(title)
}
/// Layout constants copied from `App::draw_main` (`src/tui.rs`).
impl MainStandin<'_> {
fn draw(self, f: &mut Frame) {
let friends = self.friends;
let selected = self.selected;
let chat_lines = self.chat_lines;
let composer = self.composer;
let alert = self.alert;
let status_note = self.status_note;
let area = f.area();
let banner = banner_for_width(area.width);
let banner_h = banner.lines().count() as u16;
let alert_h = u16::from(alert.is_some());
let cols = Layout::vertical([
Constraint::Length(banner_h),
Constraint::Length(alert_h),
Constraint::Min(3),
Constraint::Length(3),
Constraint::Length(1),
])
.split(area);
f.render_widget(Paragraph::new(banner), cols[0]);
if let Some(msg) = alert {
f.render_widget(Paragraph::new(msg), cols[1]);
}
let panes =
Layout::horizontal([Constraint::Percentage(36), Constraint::Min(10)]).split(cols[2]);
let stale_n = friends.iter().filter(|fr| !fr.last_ok).count();
let roster_title = if stale_n > 0 {
format!("roster {} {stale_n} stale", friends.len())
} else {
format!("roster {}", friends.len())
};
let items: Vec<ListItem> = friends
.iter()
.map(|friend| {
let mut line = format!("{} {}…", friend.name, fp8(friend.fp));
if !friend.last_ok {
line.push_str(" stale");
}
ListItem::new(line)
})
.collect();
let roster = List::new(items)
.highlight_symbol("> ")
.block(pane_block(&roster_title));
let mut roster_state = ListState::default();
if !friends.is_empty() {
roster_state.select(Some(selected));
}
f.render_stateful_widget(roster, panes[0], &mut roster_state);
let inner_h = panes[1].height.saturating_sub(2);
let nlines = chat_lines.len();
let overflow = nlines > inner_h as usize && inner_h > 0;
let chat_title = {
let mut t = match friends.get(selected) {
Some(fr) => format!("chat {}", fr.name),
None => "chat".to_string(),
};
if overflow {
let end = inner_h as usize;
t.push_str(&format!(" 1-{end}/{nlines}"));
}
t
};
f.render_widget(
Paragraph::new(chat_lines.join("\n"))
.wrap(Wrap { trim: false })
.block(pane_block(&chat_title)),
panes[1],
);
let cmd = if composer.is_empty() {
"/wipe /wipe-all /profile /who /pay /tip /file".to_string()
} else {
composer.to_string()
};
f.render_widget(Paragraph::new(cmd).block(pane_block("composer")), cols[3]);
let footer = status_footer(area.width, FP, ONION, status_note, main_footer_hints());
f.render_widget(Paragraph::new(footer), cols[4]);
}
}
/// Rect math copied from private `draw_text_overlay` (`src/tui.rs`).
fn draw_text_overlay_standin(f: &mut Frame, title: &str, text: &str) {
let area = f.area();
let lines = text.lines().count() as u16 + 2;
let text_w = text
.lines()
.map(|l| l.chars().count() as u16)
.max()
.unwrap_or(40)
.saturating_add(4);
let width = text_w.min(area.width.saturating_sub(2)).max(10);
let height = lines.min(area.height.saturating_sub(2)).max(3);
let popup = Rect {
x: area.x + (area.width.saturating_sub(width)) / 2,
y: area.y + (area.height.saturating_sub(height)) / 2,
width,
height,
};
f.render_widget(Clear, popup);
f.render_widget(
Paragraph::new(text).block(Block::default().borders(Borders::ALL).title(title)),
popup,
);
}
fn draw_overlay_screen(f: &mut Frame, title: &str, body: &str) {
f.render_widget(
Paragraph::new(body)
.wrap(Wrap { trim: false })
.block(Block::default().borders(Borders::ALL).title(title)),
f.area(),
);
}
fn sample_invite() -> String {
qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode")
}
fn empty_chat_lines() -> &'static [&'static str] {
&["no friends yet", "F3 paste an invite to add one"]
}
#[test]
fn dump_audit_frames() {
let invite = sample_invite();
let friends = [
FriendRow {
name: "alice",
fp: "aaaaaaaaaaaaaaaa",
last_ok: true,
},
FriendRow {
name: "bob-the-stale-peer",
fp: "bbbbbbbbbbbbbbbb",
last_ok: false,
},
];
let chat_ok: [&str; 3] = ["you: ping", "them: pong", LONG_MSG];
let editor = ProfileEditor::new("lance", "tor messenger", "");
let profile_body = {
let labels = ["name", "bio", "xmr"];
let values = [editor.display_name(), editor.bio(), editor.xmr_addr()];
let mut body = String::from(
"Your profile (friend-visible)\nEnter saves Esc cancels Tab next field\n",
);
for (i, (label, value)) in labels.iter().zip(values).enumerate() {
let mark = if editor.field() == i { ">" } else { " " };
body.push_str(&format!("\n{mark} {label}: {value}"));
}
body
};
let who = who_overlay_text(
FP,
ONION,
Some(&FriendProfile {
display_name: "alice".into(),
bio: "hi".into(),
xmr_addr: String::new(),
updated_at: 0,
}),
);
let who_empty = who_overlay_text(FP, ONION, None);
println!("invite payload length (chars) = {}", invite.chars().count());
println!("wordmark:\n{}", wordmark_banner());
println!("compact: {}", compact_banner());
println!("onion_glyph:\n{}", onion_glyph());
println!(
"fingerprint_mismatch_banner: {}",
fingerprint_mismatch_banner()
);
for (w, h) in SIZES {
draw_to(w, h, "chrome banner+footer", |f| {
let banner = banner_for_width(f.area().width);
let banner_h = banner.lines().count() as u16;
let chunks = Layout::vertical([
Constraint::Length(banner_h),
Constraint::Min(3),
Constraint::Length(1),
])
.split(f.area());
f.render_widget(Paragraph::new(banner), chunks[0]);
let footer = status_footer(f.area().width, FP, ONION, None, main_footer_hints());
f.render_widget(Paragraph::new(footer), chunks[2]);
});
draw_to(w, h, "chrome long-onion + send-failed", |f| {
let banner = banner_for_width(f.area().width);
let banner_h = banner.lines().count() as u16;
let chunks = Layout::vertical([
Constraint::Length(banner_h),
Constraint::Min(3),
Constraint::Length(1),
])
.split(f.area());
f.render_widget(Paragraph::new(banner), chunks[0]);
let footer = status_footer(
f.area().width,
FP,
ONION,
Some("send failed: connection timed out"),
main_footer_hints(),
);
f.render_widget(Paragraph::new(footer), chunks[2]);
});
draw_to(w, h, "RECONSTRUCTED main empty", |f| {
MainStandin {
friends: &[],
selected: 0,
chat_lines: empty_chat_lines(),
composer: "",
alert: None,
status_note: None,
}
.draw(f);
});
draw_to(w, h, "RECONSTRUCTED main chat+stale", |f| {
MainStandin {
friends: &friends,
selected: 0,
chat_lines: &chat_ok,
composer: "hello from composer",
alert: Some("passphrases do not match"),
status_note: Some("sent"),
}
.draw(f);
});
draw_to(w, h, "RECONSTRUCTED main pay/file footer only", |f| {
MainStandin {
friends: &friends,
selected: 0,
chat_lines: &["you: /pay 0.1 coffee", "them: (no invoice pane exists)"],
composer: "",
alert: None,
status_note: Some("invoice sent"),
}
.draw(f);
});
draw_to(w, h, "RECONSTRUCTED main file-send-failed", |f| {
MainStandin {
friends: &friends,
selected: 1,
chat_lines: &["no messages"],
composer: "",
alert: None,
status_note: Some("send failed: peer onion down"),
}
.draw(f);
});
draw_to(w, h, "draw_share (real)", |f| draw_share(f, &invite));
draw_to(w, h, "RECONSTRUCTED help overlay on empty main", |f| {
MainStandin {
friends: &[],
selected: 0,
chat_lines: empty_chat_lines(),
composer: "",
alert: None,
status_note: None,
}
.draw(f);
draw_text_overlay_standin(f, "? help", help_overlay_text());
});
draw_to(w, h, "RECONSTRUCTED /who overlay", |f| {
MainStandin {
friends: &friends,
selected: 0,
chat_lines: &chat_ok,
composer: "",
alert: None,
status_note: None,
}
.draw(f);
draw_text_overlay_standin(f, "/who", &who);
});
draw_to(w, h, "RECONSTRUCTED profile", |f| {
draw_overlay_screen(f, "(o) profile", &profile_body);
});
draw_to(w, h, "RECONSTRUCTED paste", |f| {
draw_overlay_screen(
f,
"(o) paste invite",
&format!("paste onionwire:v1 payload, Enter to submit\n\n{invite}"),
);
});
draw_to(w, h, "RECONSTRUCTED paste error", |f| {
draw_overlay_screen(f, "(o) paste invite", "bad invite\n\nnot-a-payload");
});
draw_to(w, h, "RECONSTRUCTED approve", |f| {
draw_overlay_screen(
f,
"(o) approve",
&format!(
"Unknown key. Add this friend?\n\nfp {}…\nonion {ONION}\n\ny accept n / Esc reject",
fp8(FP)
),
);
});
draw_to(w, h, "RECONSTRUCTED rotate", |f| {
draw_overlay_screen(
f,
"(o) rotate locator",
&format!("{}\n\nROT", rotate_screen_text()),
);
});
draw_to(w, h, "RECONSTRUCTED wipe", |f| {
draw_overlay_screen(
f,
"(o) wipe",
&format!("{}\n\nWI", wipe_screen_text(WipeKind::Messages)),
);
});
draw_to(w, h, "RECONSTRUCTED wipe-all", |f| {
draw_overlay_screen(
f,
"(o) wipe all",
&format!("{}\n\n", wipe_screen_text(WipeKind::All)),
);
});
draw_to(w, h, "RECONSTRUCTED quit", |f| {
draw_overlay_screen(f, "(o) quit", &format!("{}\n\nQUI", quit_screen_text()));
});
draw_to(w, h, "RECONSTRUCTED backup", |f| {
draw_overlay_screen(
f,
"(o) backup",
&format!("{}\n\nBACK", backup_screen_text()),
);
});
draw_to(w, h, "RECONSTRUCTED restore", |f| {
draw_overlay_screen(f, "(o) restore", &format!("{}\n\n", restore_screen_text()));
});
draw_to(w, h, "RECONSTRUCTED passphrase", |f| {
draw_overlay_screen(
f,
"(o) passphrase",
"Enter passphrase\n\n****\n\nEnter submit Esc cancel",
);
});
draw_to(w, h, "who copy (no profile)", |f| {
draw_overlay_screen(f, "/who", &who_empty);
});
}
}
#[test]
fn public_copy_fits_80_by_chars_count() {
for (name, text) in [
("wordmark", wordmark_banner()),
("help", help_overlay_text()),
("rotate", rotate_screen_text()),
("quit", quit_screen_text()),
("wipe", wipe_screen_text(WipeKind::Messages)),
("wipe-all", wipe_screen_text(WipeKind::All)),
("backup", backup_screen_text()),
("restore", restore_screen_text()),
] {
for line in text.lines() {
assert!(
line.chars().count() <= 80,
"{name} line exceeds 80 by chars().count(): {line:?}"
);
}
}
assert!(compact_banner().chars().count() <= 40);
assert!(!onion_glyph().is_empty());
assert_eq!(fingerprint_mismatch_banner(), "fingerprint mismatch");
}
#[test]
fn footer_drops_full_onion_at_80_keeps_it_at_120() {
let at_80 = status_footer(80, FP, ONION, None, main_footer_hints());
let at_120 = status_footer(120, FP, ONION, None, main_footer_hints());
let at_200 = status_footer(200, FP, ONION, None, main_footer_hints());
assert!(at_80.chars().count() <= 80, "{at_80:?}");
assert!(at_120.chars().count() <= 120, "{at_120:?}");
assert!(at_200.chars().count() <= 200, "{at_200:?}");
assert!(
!at_80.contains(ONION),
"80-col footer should truncate onion: {at_80}"
);
assert!(
at_120.contains(ONION),
"120-col footer should keep full onion: {at_120}"
);
assert!(at_80.contains("? help") && at_120.contains("? help"));
}
/// Spec: never drop `send failed`. Keep `TOR` / `me:` / `? help` at 80 and 120.
#[test]
fn status_footer_drops_send_failed_when_crowded() {
let note = "send failed: peer onion down";
for (w, line) in [
(
80u16,
status_footer(80, FP, ONION, Some(note), main_footer_hints()),
),
(
120,
status_footer(120, FP, ONION, Some(note), main_footer_hints()),
),
(
200,
status_footer(200, FP, ONION, Some(note), main_footer_hints()),
),
] {
assert!(
line.chars().count() <= w as usize,
"{w} footer wider than frame: {} {line:?}",
line.chars().count()
);
assert!(
line.contains("send failed"),
"{w} dropped fail-closed note: {line:?}"
);
assert!(line.contains("TOR"), "{w} missing TOR: {line:?}");
assert!(line.contains("me:"), "{w} missing me:: {line:?}");
assert!(line.contains("? help"), "{w} missing ? help: {line:?}");
}
}
#[test]
fn share_invite_wraps_at_three_sizes() {
let invite = sample_invite();
for (w, h) in SIZES {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
let buf = terminal.backend().buffer();
let mut screen = String::new();
for y in 0..h {
for x in 0..w {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
assert!(screen.contains("onionwire:v1:"), "{w}x{h}\n{screen}");
assert!(screen.contains("(o) invite"), "{w}x{h}\n{screen}");
}
}
/// Documented defect in `tests/tui_chrome.rs`: `chars().count()` is not cells.
/// Do not add `unicode-width` on this card.
#[test]
fn chars_count_is_not_terminal_cells() {
let cjk = "你好";
assert_eq!(cjk.chars().count(), 2, "CJK under-counts vs 4 wide cells");
let combining = "e\u{0301}";
assert_eq!(
combining.chars().count(),
2,
"combining mark over-counts vs 1 cell"
);
let emoji = "🧅";
assert_eq!(emoji.chars().count(), 1, "emoji under-counts vs 2 cells");
let ellipsis = "…";
assert_eq!(ellipsis.chars().count(), 1);
}