diff --git a/src/tui.rs b/src/tui.rs index c6e5c28..0c5912c 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1,5 +1,5 @@ use std::collections::HashMap; -use std::io::{self, IsTerminal, Write}; +use std::io::{self, IsTerminal}; use std::sync::{Arc, mpsc}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -327,7 +327,6 @@ fn char_len(s: &str) -> usize { s.chars().count() } -/// Truncate `s` to `max` display cells, appending an ellipsis when it overflows. fn truncate_chars(s: &str, max: usize) -> String { if char_len(s) <= max { return s.to_string(); @@ -341,43 +340,6 @@ fn truncate_chars(s: &str, max: usize) -> String { format!("{head}{e}") } -/// OSC 52 escape sequence that asks the terminal to copy `text` into the -/// system clipboard. No clipboard crate is pulled in: the text is base64'd -/// by this minimal encoder and the raw byte sequence is returned so the -/// caller can `print!` / `io::stdout().write_all` it. -pub fn osc52_copy(text: &str) -> String { - const B64: &[u8] = - b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let bytes = text.as_bytes(); - let mut out = String::with_capacity(8 + bytes.len() * 4 / 3); - out.push_str("\x1b]52;c;"); - for (i, chunk) in bytes.chunks(3).enumerate() { - let mut quad = [0u8; 3]; - quad[..chunk.len()].copy_from_slice(chunk); - let v0 = (quad[0] >> 2) & 0x3f; - let v1 = ((quad[0] & 0x03) << 4) | (quad[1] >> 4); - let v2 = if chunk.len() > 1 { - ((quad[1] & 0x0f) << 2) | (quad[2] >> 6) - } else { - 64 - }; - let v3 = if chunk.len() > 2 { quad[2] & 0x3f } else { 64 }; - for v in [v0, v1, v2, v3] { - if v == 64 { - out.push('='); - } else { - out.push(B64[v as usize] as char); - } - } - if (i + 1) % 76 == 0 { - out.push_str("\x1b]52;c;"); - } - } - out.push('\x07'); - out -} - - fn style_fg(rgb: Color, ansi: Color) -> Style { match color_mode() { ColorMode::None => Style::default(), @@ -492,11 +454,9 @@ OnionWire keys\n\ F3 paste invite\n\ F4 rotate onion locator\n\ F5 selected friend's profile (/who)\n\ - F6 wallet (receive address, chain, balance, history)\n\ + F6 wallet (receive address, chain source)\n\ F6 s chain source: receive-only / local / remote\n\ F6 n start or stop the app-owned daemon\n\ - F6 r show / hide the receive-address QR\n\ - F6 y copy receive address to clipboard (OSC 52)\n\ /profile edit name, bio, Monero address\n\ /pay [memo] invoice to receive\n\ /tip [memo] pay selected friend\n\ @@ -1165,9 +1125,8 @@ enum Screen { entry: PassphraseEntry, }, Wallet { - view: Box, + view: WalletView, qr_modal: Option, - copy_note: Option, }, ChainSetup(ChainSetup), WalletSetup(WalletSetup), @@ -1334,9 +1293,6 @@ pub struct WalletView { pub balance: String, pub transfers: Vec, pub chain: ChainView, - /// `no_spend` — the wallet can receive but `/tip` is refused locally. - /// Shows a `view-only` badge (glyph + word), never color-only. - pub no_spend: bool, } /// Assemble the wallet screen, applying the one rule that matters: while the @@ -1346,7 +1302,6 @@ pub fn wallet_view( balance: String, transfers: Vec, chain: ChainView, - no_spend: bool, ) -> WalletView { if chain.ready { WalletView { @@ -1354,7 +1309,6 @@ pub fn wallet_view( balance, transfers, chain, - no_spend, } } else { WalletView { @@ -1362,7 +1316,6 @@ pub fn wallet_view( balance: "not synced — unavailable".to_string(), transfers: Vec::new(), chain, - no_spend, } } } @@ -1763,7 +1716,6 @@ impl App { buf: Zeroizing::new(String::new()), }); } - KeyCode::Char('y') => self.wallet_copy_address(), _ => {} }, Screen::ChainSetup(_) => self.handle_chain_setup(key)?, @@ -1973,9 +1925,8 @@ impl App { fn open_wallet(&mut self) -> Result<(), String> { self.screen = Screen::Wallet { - view: Box::new(self.build_wallet_view()), + view: self.build_wallet_view(), qr_modal: None, - copy_note: None, }; Ok(()) } @@ -2015,14 +1966,14 @@ impl App { .rt .block_on(self.node.wallet_recent_transfers(8)) .unwrap_or_default(); - wallet_view(receive_addr, balance, transfers, chain, no_spend) + wallet_view(receive_addr, balance, transfers, chain) } /// Re-read the wallet screen after something changed what it shows. fn refresh_wallet(&mut self) { let view = self.build_wallet_view(); if let Screen::Wallet { view: slot, .. } = &mut self.screen { - **slot = view; + *slot = view; } } @@ -2154,9 +2105,8 @@ impl App { } if back { self.screen = Screen::Wallet { - view: Box::new(self.build_wallet_view()), + view: self.build_wallet_view(), qr_modal: None, - copy_note: None, }; } Ok(()) @@ -2170,9 +2120,8 @@ impl App { Err(e) => format!("chain source not saved: {e}"), }); self.screen = Screen::Wallet { - view: Box::new(self.build_wallet_view()), + view: self.build_wallet_view(), qr_modal: None, - copy_note: None, }; } @@ -2228,30 +2177,6 @@ impl App { }); } - /// OSC 52 copy of the receive address. If there is an address it is - /// base64'd inline (no clipboard crate) and written through the terminal; - /// the fallback hint is shown on the next frame so the user can still - /// mouse-select if their emulator blocks OSC 52. - fn wallet_copy_address(&mut self) { - let addr = match &self.screen { - Screen::Wallet { view, .. } => view.receive_addr.clone(), - _ => return, - }; - if addr.is_empty() { - self.status_note = Some("no address to copy — create or import a wallet first".into()); - return; - } - // OSC 52 is emitted on the terminal, not the ratatui frame buffer. - print!("{}", osc52_copy(&addr)); - let _ = io::stdout().flush(); - self.status_note = Some( - "copied — if your terminal blocked it, select the address above".into(), - ); - if let Screen::Wallet { copy_note, .. } = &mut self.screen { - *copy_note = self.status_note.clone(); - } - } - fn handle_wallet_setup(&mut self, key: KeyEvent) -> Result<(), String> { let Screen::WalletSetup(setup) = &mut self.screen else { return Ok(()); @@ -2566,9 +2491,7 @@ impl App { draw_passphrase(f, *kind, entry.first().is_some(), entry.buf()) } Screen::Quit { prompt } => draw_quit(f, prompt.typed()), - Screen::Wallet { view, qr_modal, copy_note } => { - draw_wallet(f, view.as_ref(), qr_modal.as_ref(), copy_note.as_deref()) - } + Screen::Wallet { view, qr_modal } => draw_wallet(f, view, qr_modal.as_ref()), Screen::ChainSetup(setup) => draw_chain_setup(f, setup), Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), } @@ -2888,7 +2811,7 @@ match screen { BackupKind::Restore => "type RESTORE Esc cancel ? help", }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", - Screen::Wallet { .. } => "s chain n node c create i import r qr y copy Esc back ? help", + Screen::Wallet { .. } => "s chain n node c create i import r qr Esc back ? help", Screen::ChainSetup(_) => "Enter select/save Esc back ? help", Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { @@ -3142,52 +3065,36 @@ pub struct QrModal { uri: String, } -impl QrModal { - /// Public constructor so tests can build a modal to exercise `draw_wallet`'s - /// QR path without touching the private `App` / `Node`. - pub fn test_new(closed: bool, matrix_rows: Vec, uri: String) -> Self { - Self { - closed, - matrix_rows, - uri, - } - } -} - /// The F6 wallet screen. /// /// `pub` on purpose: the not-ready render is a spec of this card, so the test /// draws this for real at a fixed size rather than a stand-in. -/// The wallet screen: address, balance, chain state, transfer history, QR modal, -/// and address copy (OSC 52 + fallback hint). Pure draw — the not-ready rules -/// live in `wallet_view` / `chain_view`; this only renders what it is given. -pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>, copy_note: Option<&str>) { +pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>) { let area = f.area(); - - // --- QR modal (on top of everything) ----------------------------------- if let Some(m) = modal { + // Clear behind the popup so the body does not bleed through. f.render_widget(Clear, area); - // Cap the popup so it never clips at 80x24: a QR matrix is square, - // and one-cell-glyphs are double-width to the eye, so 46 chars is - // the largest matrix that fits in 80 with a border + title + margins. - let max_mat = 46u16; - let popup_w = max_mat.min(area.width.saturating_sub(4).max(1)).saturating_add(2); + let inner_w = area.width.saturating_sub(2).max(1); + let inner_h = area.height.saturating_sub(2).max(1); let rows = m.matrix_rows.len().max(1); - let popup_h = (rows as u16).min(area.height.saturating_sub(4).max(1)).saturating_add(2); + let content_h = rows.min(inner_h as usize); + let popup_h = content_h as u16 + 2; + let popup_w = inner_w.max(6); let x = area.x + (area.width.saturating_sub(popup_w)) / 2; let y = area.y + (area.height.saturating_sub(popup_h)) / 2; - let popup = Rect { x, y, width: popup_w, height: popup_h }; + let popup = Rect { + x, + y, + width: popup_w, + height: popup_h, + }; f.render_widget(Clear, popup); - - let mut body = String::from("receive address\nEsc or r closes\n\n"); + let mut body = String::from("receive address\nEsc or R closes\n\n"); if m.matrix_rows.is_empty() { body.push_str("(qr error)"); } else { - let inner_h = popup_h.saturating_sub(2).max(1) as usize; - for row in m.matrix_rows.iter().take(inner_h) { - // Each QR row may be wider than the popup; truncate to fit. - let row_str: String = row.chars().take(popup_w.saturating_sub(2) as usize).collect(); - body.push_str(&row_str); + for row in m.matrix_rows.iter().take(content_h) { + body.push_str(row); body.push('\n'); } } @@ -3205,22 +3112,13 @@ pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>, co return; } - // --- Five-row vertical layout: title, primary, chain, history, footer --- let cols = Layout::vertical([ - // 1. Title bar Constraint::Length(2), - // 2. Primary block: address + balance + readiness + view-only badge - Constraint::Length(8), - // 3. Chain block: 5 chain lines - Constraint::Length(7), - // 4. History block: up to 6 transfer rows (or "none") - Constraint::Max(8), - // 5. Footer: status note or action row + Constraint::Min(6), Constraint::Length(1), ]) .split(area); - // 1. Title f.render_widget( Paragraph::new("wallet") .style(style_accent()) @@ -3228,101 +3126,43 @@ pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>, co cols[0], ); - // 2. Primary block — address, balance, readiness, badge let addr_line = if view.receive_addr.is_empty() { "no address yet — /profile xmr, or create a wallet".to_string() } else { view.receive_addr.clone() }; - - // View-only badge: glyph + word, never colour-only, never emoji, and the - // same under NO_COLOR / ONIONWIRE_ASCII (the word carries the meaning). - let badge = if view.no_spend { - "[!] view-only — /tip off" + let mut lines: Vec = vec![ + format!("address {addr_line}"), + format!("balance {}", view.balance), + String::new(), + "chain".to_string(), + ]; + lines.extend(view.chain.lines()); + lines.push(PRUNED_NOTE.to_string()); + lines.push(String::new()); + lines.push("recent transfers".to_string()); + if view.transfers.is_empty() { + lines.push(" (none shown)".to_string()); } else { - "[ok] spend enabled" - }; - - let primary_lines: Vec = if view.receive_addr.is_empty() { - vec![ - format!("address {addr_line}"), - format!("balance {}", view.balance), - String::new(), - badge.to_string(), - String::new(), - view.chain.status_line.clone(), - ] - } else { - vec![ - format!("address {}", truncate_chars(&addr_line, 74)), - format!("balance {}", view.balance), - String::new(), - badge.to_string(), - String::new(), - view.chain.status_line.clone(), - ] - }; + for t in view.transfers.iter().take(4) { + let xmr = crate::pay::atomic_to_xmr_str(&t.amount); + lines.push(format!( + " {} {} XMR", + t.txid.chars().take(16).collect::(), + xmr + )); + } + } f.render_widget( - Paragraph::new(primary_lines.join("\n")) + Paragraph::new(lines.join("\n")) .style(style_text()) .wrap(Wrap { trim: false }) - .block( - apply_chrome_borders(Block::default()) - .border_style(style_border()) - .title("wallet"), - ), + .block(apply_chrome_borders(Block::default()).border_style(style_border())), cols[1], ); - // 3. Chain block - let chain_lines: Vec = view.chain.lines(); - f.render_widget( - Paragraph::new(chain_lines.join("\n")) - .style(style_text()) - .wrap(Wrap { trim: false }) - .block( - apply_chrome_borders(Block::default()) - .border_style(style_border()) - .title("chain"), - ), - cols[2], - ); - - // 4. History block - let mut history_lines: Vec = vec!["recent transfers".to_string()]; - if view.transfers.is_empty() { - history_lines.push(" (none shown)".to_string()); - } else { - for t in view.transfers.iter().take(6) { - let xmr = crate::pay::atomic_to_xmr_str(&t.amount); - let txid_short = truncate_chars(&t.txid, 12); - history_lines.push(format!(" {txid_short} {xmr} XMR")); - } - } - let history_text = history_lines.join("\n"); - f.render_widget( - Paragraph::new(history_text) - .style(style_text()) - .wrap(Wrap { trim: false }) - .block( - apply_chrome_borders(Block::default()) - .border_style(style_border()) - .title("history"), - ), - cols[3], - ); - - // 5. Footer — status note (from copy) or action hints - let footer_text = if let Some(note) = copy_note { - note.to_string() - } else { - "s chain n start/stop c create i import r qr y copy Esc back".to_string() - }; - f.render_widget( - Paragraph::new(footer_text) - .style(style_dim()), - cols[4], - ); + let help = "s chain n start/stop c create i import r qr"; + f.render_widget(Paragraph::new(help).style(style_dim()), cols[2]); } /// The chain-source picker and the remote-daemon trust shift, before anything diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index fee8951..75c1cab 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -48,8 +48,6 @@ fn help_overlay_lists_core_bindings() { "F6", "F6 s", "F6 n", - "F6 r", - "F6 y", "send chat", "/profile", "/pay", diff --git a/tests/tui_frames.rs b/tests/tui_frames.rs index bafdbe2..5b600eb 100644 --- a/tests/tui_frames.rs +++ b/tests/tui_frames.rs @@ -16,9 +16,9 @@ use onionwire::node::{DaemonSync, WalletChildState}; use onionwire::tui::{ backup_screen_text, banner_for_width, chain_view, compact_banner, draw_share, draw_wallet, fingerprint_mismatch_banner, help_overlay_text, main_footer_hints, onion_glyph, - osc52_copy, quit_screen_text, restore_screen_text, rotate_screen_text, status_footer, - wallet_readiness, wallet_view, who_overlay_text, wipe_screen_text, wordmark_banner, - ChainChoice, ProfileEditor, WalletReadiness, WALLET_LINE_MAX, WipeKind, + quit_screen_text, restore_screen_text, rotate_screen_text, status_footer, wallet_readiness, + wallet_view, who_overlay_text, wipe_screen_text, wordmark_banner, ChainChoice, ProfileEditor, + WalletReadiness, WALLET_LINE_MAX, WipeKind, }; use onionwire::wallet::ChainSource; use onionwire::FriendProfile; @@ -440,107 +440,6 @@ fn dump_audit_frames() { draw_to(w, h, "who copy (no profile)", |f| { draw_overlay_screen(f, "/who", &who_empty); }); - - // --- Wallet screen frames (real draw_wallet) --- - // receive-only - let receive_only = chain_view( - &ChainSource::None, - WalletChildState::Off, - &DaemonSync { - reachable: false, - height: 0, - target_height: 0, - note: Some("receive-only: no daemon".into()), - }, - None, - wallet_readiness(false, false, false), - ); - let view_ro = wallet_view(String::new(), "off".to_string(), Vec::new(), receive_only, false); - draw_to(w, h, "wallet receive-only", |f| { - draw_wallet(f, &view_ro, None, None); - }); - - // local synced - let synced = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, false), - ); - let view_synced = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), synced, false); - draw_to(w, h, "wallet local synced", |f| { - draw_wallet(f, &view_synced, None, None); - }); - - // local syncing - let syncing = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 1_500_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, false), - ); - let view_syncing = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), syncing, false); - draw_to(w, h, "wallet local syncing", |f| { - draw_wallet(f, &view_syncing, None, None); - }); - - // remote unreachable - let unreachable = chain_view( - &ChainSource::Remote { - host: "node.example.com".into(), - port: 18089, - }, - WalletChildState::Stopped, - &DaemonSync { - reachable: false, - height: 0, - target_height: 0, - note: Some("connect failed".into()), - }, - None, - wallet_readiness(true, false, false), - ); - let view_ru = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), unreachable, false); - draw_to(w, h, "wallet remote unreachable", |f| { - draw_wallet(f, &view_ru, None, None); - }); - - // view-only badge - let vo = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, true), - ); - let view_vo = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), vo, true); - draw_to(w, h, "wallet view-only badge", |f| { - draw_wallet(f, &view_vo, None, None); - }); - - // QR modal open - let qr_rows: Vec = (0..20).map(|_| "██".repeat(20)).collect(); - let modal = onionwire::tui::QrModal::test_new(false, qr_rows, address()); - draw_to(w, h, "wallet qr modal", |f| { - draw_wallet(f, &view_synced, Some(&modal), None); - }); } } @@ -661,20 +560,10 @@ fn chars_count_is_not_terminal_cells() { /// The F6 screen's not-ready state is a spec of this card, so this draws the /// **real** `draw_wallet` at a fixed size and reads the cells back. fn wallet_screen_at(w: u16, h: u16, view: &onionwire::tui::WalletView) -> String { - wallet_screen_at_with(w, h, view, None) -} - -/// Draw the wallet screen with an optional copy_note (the OSC 52 fallback hint). -fn wallet_screen_at_with( - w: u16, - h: u16, - view: &onionwire::tui::WalletView, - copy_note: Option<&str>, -) -> String { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); terminal - .draw(|f| draw_wallet(f, view, None, copy_note)) + .draw(|f| draw_wallet(f, view, None)) .expect("draw"); let buf = terminal.backend().buffer(); let mut screen = String::new(); @@ -712,7 +601,7 @@ fn wallet_screen_says_not_ready_and_never_a_balance_before_sync() { Some(412), wallet_readiness(true, false, false), ); - let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false); + let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain); assert_eq!( view.balance, "not synced — unavailable", @@ -734,6 +623,7 @@ fn wallet_screen_says_not_ready_and_never_a_balance_before_sync() { "sync: unknown — 127.0.0.1:18081: Connection refused", "storage: 412 GB free here", "not synced — unavailable", + "pruned nodes are not archives", ] { assert!(screen.contains(needle), "wallet screen missing {needle:?}:\n{screen}"); } @@ -757,7 +647,7 @@ fn wallet_screen_says_receive_only_when_nothing_is_configured() { None, wallet_readiness(false, false, false), ); - let view = wallet_view(String::new(), "off".to_string(), Vec::new(), chain, false); + let view = wallet_view(String::new(), "off".to_string(), Vec::new(), chain); let screen = wallet_screen_at(80, 24, &view); for needle in [ "chain: receive-only", @@ -788,7 +678,6 @@ fn wallet_screen_keeps_the_balance_when_the_wallet_is_ready() { "12.5 XMR".to_string(), Vec::new(), chain, - false, ); assert!(view.chain.ready); assert_eq!(view.balance, "12.5 XMR"); @@ -827,352 +716,3 @@ fn chain_choice_never_preselects_a_remote_daemon() { assert!(!choice.detail().is_empty()); } } - -/// A view-only wallet must show a badge that is a word + glyph, never -/// color-only. The badge survives NO_COLOR (glyph stays, word stays). -#[test] -fn wallet_view_only_badge_has_word_and_glyph() { - let chain = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, true), - ); - let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, true); - assert!(view.no_spend, "view-only wallet must carry no_spend=true"); - let screen = wallet_screen_at(80, 24, &view); - assert!( - screen.contains("view-only"), - "view-only badge must say 'view-only' as a word: {screen}" - ); - // Badge must be a glyph + word, never colour-only and never emoji. - // Under NO_COLOR / ONIONWIRE_ASCII the glyph is still ASCII `[!]`. - assert!( - screen.contains("[!]"), - "view-only badge must have an ASCII glyph: {screen}" - ); -} - -/// `no_spend=false` must NOT show the view-only badge — a spend-capable wallet -/// must not claim otherwise. -#[test] -fn wallet_spend_enabled_badge_does_not_say_view_only() { - let chain = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, false), - ); - let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false); - assert!(!view.no_spend); - let screen = wallet_screen_at(80, 24, &view); - assert!( - !screen.contains("view-only"), - "spend-capable wallet must not show view-only badge: {screen}" - ); -} - -/// OSC 52: the escape sequence wraps the base64 of the address between -/// ESC ] 52 ; c ; and BEL. -#[test] -fn osc52_copy_emits_valid_sequence() { - let addr = "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD"; - let seq = osc52_copy(addr); - assert!(seq.starts_with("\x1b]52;c;"), "sequence must start with OSC 52: {seq:?}"); - assert!(seq.ends_with("\x07"), "sequence must end with BEL: {seq:?}"); - // The middle is the base64 of the address. - let b64 = &seq["\x1b]52;c;".len()..seq.len() - "\x07".len()]; - assert!(!b64.contains('\n'), "no embedded newlines in single-line address: {b64:?}"); - assert!(b64.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '='), - "base64 payload must be clean: {b64:?}"); - // Round-trip: decode the base64 back to the original address. - let decoded = base64_decode(b64); - assert_eq!(decoded, addr.as_bytes(), "OSC 52 must round-trip the address"); -} - -/// Minimal base64 decoder for tests (no base64 crate in the dependency tree -/// — the production encoder `osc52_copy` is crate-free). -fn base64_decode(input: &str) -> Vec { - const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut out = Vec::new(); - let mut buf = 0u32; - let mut bits = 0; - for c in input.chars() { - if c == '=' { - break; - } - let val = B64.iter().position(|&b| b == c as u8).unwrap(); - buf = (buf << 6) | val as u32; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((buf >> bits) as u8); - } - } - out -} - -/// The fallback hint must appear on screen when `copy_note` is set. -#[test] -fn wallet_copy_fallback_hint_is_on_screen() { - let chain = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, false), - ); - let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false); - let note = "copied — if your terminal blocked it, select the address above"; - let screen = wallet_screen_at_with(80, 24, &view, Some(note)); - assert!( - screen.contains("copied — if your terminal blocked it"), - "fallback hint must be on screen: {screen}" - ); - assert!( - screen.contains("select the address above"), - "fallback hint must mention selecting the address: {screen}" - ); -} - -/// The QR modal must fit inside 80x24 without clipping — every row that is -/// drawn must be fully visible within the frame. -#[test] -fn wallet_qr_modal_fits_80x24_without_clipping() { - let chain = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, false), - ); - let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false); - - // Build a fake QR modal with a 46×46 matrix (the max we support). - let rows: Vec = (0..46) - .map(|_| "█".repeat(46)) - .collect(); - let modal = onionwire::tui::QrModal::test_new(false, rows, address()); - - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_wallet(f, &view, Some(&modal), None)) - .expect("draw"); - let buf = terminal.backend().buffer(); - - // Check every row in the popup area is within bounds — no content - // bleeds past the frame edges. - let mut screen = String::new(); - for y in 0..24u16 { - for x in 0..80u16 { - screen.push_str(buf[(x, y)].symbol()); - } - screen.push('\n'); - } - // The QR popup should be centered and fit within the 80x24 frame. - assert!( - screen.contains("qr — monero:receive"), - "QR modal title must appear: {screen}" - ); - // No QR row should be wider than 80 cells (no clipping on the right). - // The loop below walks every cell of the buffer — if any cell were out - // of bounds, ratatui panics, so reaching this point means nothing clipped. - for _y in 0..24u16 { - for _x in 0..80u16 { - // buffer access is bounds-checked by ratatui - } - } -} - -/// The restructured wallet screen must show at least 3 labelled blocks -/// (wallet, chain, history) at 80x24 — this replaces the old single-body -/// draw that had no block borders. -#[test] -fn wallet_screen_has_pane_structure_at_80x24() { - let chain = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, false), - ); - let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false); - let screen = wallet_screen_at(80, 24, &view); - for needle in [ - "wallet", - "chain", - "history", - "balance", - "address", - "sync: synced", - "y copy", - ] { - assert!( - screen.contains(needle), - "wallet screen missing {needle:?}: {screen}" - ); - } -} - -/// The receive-only wallet screen shows no balance, no chain traffic, -/// and still fits at 80x24. -#[test] -fn wallet_screen_receive_only_fits_80x24() { - let chain = chain_view( - &ChainSource::None, - WalletChildState::Off, - &DaemonSync { - reachable: false, - height: 0, - target_height: 0, - note: Some("receive-only: no daemon".into()), - }, - None, - wallet_readiness(false, false, false), - ); - let view = wallet_view(String::new(), "off".to_string(), Vec::new(), chain, false); - let screen = wallet_screen_at(80, 24, &view); - for needle in [ - "chain: receive-only", - "daemon: not configured", - "not ready: no wallet — receive-only", - "no address yet", - ] { - assert!( - screen.contains(needle), - "receive-only screen missing {needle:?}: {screen}" - ); - } -} - -/// The remote-unreachable wallet screen shows `sync: unknown` and -/// `not synced — unavailable` for the balance. -#[test] -fn wallet_screen_remote_unreachable_says_sync_unknown() { - let chain = chain_view( - &ChainSource::Remote { - host: "node.example.com".into(), - port: 18089, - }, - WalletChildState::Stopped, - &DaemonSync { - reachable: false, - height: 0, - target_height: 0, - note: Some("connect failed".into()), - }, - None, - wallet_readiness(true, false, false), - ); - let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false); - let screen = wallet_screen_at(80, 24, &view); - assert!( - screen.contains("sync: unknown"), - "must say sync: unknown: {screen}" - ); - assert!( - screen.contains("not synced — unavailable"), - "must suppress balance: {screen}" - ); - assert!( - screen.contains("remote daemon node.example.com:18089"), - "must name remote host:port: {screen}" - ); -} - -/// No line of the rendered wallet screen may exceed the frame width at -/// either the 80x24 floor or the 120x40 target. Width is measured by -/// `chars().count()` (the documented metric, see `chars_count_is_not_terminal_cells`). -#[test] -fn wallet_screen_no_line_exceeds_frame_at_80_and_120() { - let chain_ready = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, false), - ); - let transfers: Vec = vec![ - onionwire::wallet::TransferRow { - txid: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into(), - amount: "5000000000".into(), - address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(), - }, - ]; - let view = wallet_view(address(), "12.5 XMR".to_string(), transfers, chain_ready, false); - for (w, h) in [(80u16, 24u16), (120, 40)] { - let screen = wallet_screen_at(w, h, &view); - for (y, line) in screen.lines().enumerate() { - assert!( - line.chars().count() <= w as usize, - "wallet screen {w}x{h} row {y} exceeds width: {} {line:?}", - line.chars().count() - ); - } - } -} - -/// A view-only wallet renders its `[!]` badge at both sizes, never clipped. -#[test] -fn wallet_view_only_badge_renders_at_80_and_120() { - let chain = chain_view( - &local_source(), - WalletChildState::Running, - &DaemonSync { - reachable: true, - height: 3_210_000, - target_height: 3_210_000, - note: None, - }, - Some(412), - wallet_readiness(true, true, true), - ); - let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, true); - for (w, h) in [(80u16, 24u16), (120, 40)] { - let screen = wallet_screen_at(w, h, &view); - assert!( - screen.contains("[!] view-only"), - "view-only badge missing at {w}x{h}: {screen}" - ); - for (y, line) in screen.lines().enumerate() { - assert!( - line.chars().count() <= w as usize, - "badge frame {w}x{h} row {y} too wide: {} {line:?}", - line.chars().count() - ); - } - } -}