diff --git a/docs/TUI.md b/docs/TUI.md index e1655d9..e83efa3 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -621,3 +621,86 @@ lands on the row that actually owns the outbox entry. and footer row is `<=` the terminal width, that the markers render, and that an over-long message wraps instead of being clipped. - Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`. + +## WALLETS & SETTINGS menu (F9 / `/settings`) — implemented + +The Monero wallet and the cuprate node shipped behind function keys only: a user +who did not already know F6 opened the wallet could not find wallet setup, the +child wallet, the chain source or the settings. F9 (`/settings`) is the +discoverable surface. It is a **screen, not a popup**, and it is a discovery +layer, not a replacement: F2, F3, F4, F5, F6 and F8 all keep working, and they +stay live *on this screen* so no row can print a key that does nothing there. + +``` +cargo test --locked --test tui_spec -- --nocapture wallets_settings_menu_frame_dumps +``` + +dumps the menu at 80x24, 120x40 and 200x60 in both the configured and the +unconfigured state. + +### Rows + +Layout is ` label value … keys`: a 9-cell label column, the value truncated +in **cells** with the chrome's ellipsis, and a 12-cell key column right-aligned +so the eye can run down it. Every actionable row names the key or command that +fires it, including the F6 wallet screen's own keys (`F6 c`, `F6 i`, `F6 r`, +`F6 s/x`, `F6 p`), so the menu teaches the shortcuts it sits beside. + +| Group | Row | Value | Key | +|---|---|---|---| +| WALLET | endpoint | `configured · connected` / `configured · not connected` / `not configured · receive-only` | — | +| WALLET | child | `{chain source} · running` / `not started` | `F6 s/x` | +| WALLET | sync | chain readiness word (`chain at tip · wallet answering`, `wallet answering · chain not at tip`, `wallet RPC not answering yet`, `child exited`, `not probing · no chain source`) | `F6 p` | +| WALLET | receive | the receive address (truncated) or `no address yet · wallet unreachable` | `c copy` / `F6 r` | +| WALLET | balance | `{xmr}` / `off` / `err` | `F6` | +| WALLET | payments | `{n} recent` / `no transfers yet` | `F6` | +| WALLET | create | `/wallet create · seed shown once` | `F6 c` | +| WALLET | import | `/wallet import · 25-word seed` | `F6 i` | +| SETTINGS | nickname | the self-profile name, or `(none)` | `/profile` | +| SETTINGS | profile | `bio set · xmr set` | `/profile` | +| SETTINGS | identity | `{fp}… · identity = pubkey` | `F2` | +| SETTINGS | colour | `auto · follows NO_COLOR / TERM` | — | +| SETTINGS | backup | `encrypted identity export` | `/backup` | +| SETTINGS | restore | `overwrite self keys from a backup` | `/restore` | +| SETTINGS | wipe | `messages · identity and friends stay` | `/wipe` | +| SETTINGS | wipe-all | `deletes your identity key · new person` | `/wipe-all` | + +19 rows at 80x24 against 21 available inner rows: nothing clips or scrolls. + +### Guarantees + +- **No credentials.** `WalletMenuState` carries booleans, labels and + display-ready error strings from `Node`'s getters. It is never given + `WalletConfig::rpc_login`, `secret()`, a seed or a passphrase, so the screen + cannot render one. +- **Untrusted text is display data.** Every value goes through + `sanitize::display_text` plus a newline/tab strip before it is placed on a + row, so a multi-line or bidi-laden error cannot split a row or reorder it. +- **Cells, not chars.** `cell_width()` measures with ratatui's own + `Span::width` — the same code path the renderer truncates with. + `unicode-width` is not a direct dependency of this crate, so no crate was + added; `chars().count()` is never used for a width. +- **Colour is never the only signal.** Each state word is present as a word + (`not connected`, `child exited`, `not probing`, `no transfers yet`); the + tone only answers "what is this?". +- **Copy without a clipboard crate.** `c` writes the receive address through + OSC 52 (`ESC ] 52 ; c ; BEL`): the terminal owns the clipboard, the + address never touches a file, and it still works over SSH. A terminal that + does not implement OSC 52 ignores the sequence; `F6 r` still shows the QR. +- **ASCII fallback.** The section rule is `─`, or `-` under `ONIONWIRE_ASCII` / + `NO_COLOR`, alongside the existing ellipsis swap. No emoji. + +### Reachable-from-the-TUI gaps this card does not close + +Named in the PR body's feature-analysis table. All of them need backend or +sibling-card work, not presentation: + +- `Node::wallet_config()` / `Node::wallet_save_config(cfg)` / + `Node::wallet_test_connection(..)` — the endpoint config screen is F7 on + `feat/wallet-create-import`; the menu shows the endpoint's *state* and leaves + the key free. +- Peer payment history — `store.list_payments(..)` has no `Node` accessor, so + the menu can only offer the wallet's own transfer list (F6). +- `Node::set_wallet_child_config(cfg)` — the child can be started/stopped and + probed, not edited. +- `Node::set_petname(..)` — no petname editor exists. diff --git a/src/tui.rs b/src/tui.rs index e44bf0d..10761d8 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1,5 +1,5 @@ use std::collections::HashMap; -use std::io::{self, IsTerminal}; +use std::io::{self, IsTerminal, Write}; use std::sync::{Arc, mpsc}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -7,6 +7,7 @@ use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, Ke use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::{Color, Modifier, Style}; use ratatui::symbols::border; +use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; use ratatui::{DefaultTerminal, Frame}; use zeroize::{Zeroize, Zeroizing}; @@ -547,6 +548,7 @@ OnionWire keys\n\ F5 selected friend's profile (/who)\n\ F6 wallet (receive QR, create/import)\n\ F8 rotate prekey\n\ + F9 wallets & settings menu\n\ /profile edit name, bio, Monero address\n\ /pay [memo] invoice to receive\n\ /tip [memo] pay selected friend\n\ @@ -555,6 +557,9 @@ OnionWire keys\n\ /file /path send file to selected friend (1 MiB)\n\ /backup /path encrypted identity export\n\ /restore /path overwrite self keys\n\ + /wipe wipe messages; identity and friends stay\n\ + /wipe-all wipe identity too — you become a new person\n\ + /settings wallets & settings menu\n\ ? this help\n\ Ctrl-Q quit; type CLEAR or QUIT\n\ \n\ @@ -652,6 +657,8 @@ pub enum SlashCmd { Wipe(WipeKind), Profile, Who, + /// `/settings` — the WALLETS & SETTINGS menu (same screen as F9). + Settings, Pay { atomic: String, memo: String }, Tip { atomic: String, memo: String }, Backup { path: String }, @@ -808,6 +815,7 @@ pub fn parse_cmd(raw: &str) -> Option { return parse_path_cmd(rest).map(|path| SlashCmd::File { path }); } match s { + "/settings" => return Some(SlashCmd::Settings), "/wallet create" => return Some(SlashCmd::WalletCreate), "/wallet import" => return Some(SlashCmd::WalletImport), _ => {} @@ -1224,6 +1232,12 @@ enum Screen { qr_modal: Option, }, WalletSetup(WalletSetup), + /// F9 / `/settings`: the WALLETS & SETTINGS discovery menu. Holds the + /// snapshot, not a pre-rendered body, so a resize re-fits and nothing stale + /// survives a repaint. + WalletsSettings { + state: WalletMenuState, + }, Quit { prompt: QuitPrompt, }, @@ -1312,6 +1326,7 @@ impl App { let mut wipe_confirm = None; let mut quit_clear = None; + let mut copy_addr = false; let mut profile_save = None; let mut open_profile = false; let mut pay_cmd = None; @@ -1319,31 +1334,59 @@ impl App { let mut file_cmd = None; let mut chat_send = None; let mut pass_submit = None; + + // The function-key shortcuts stay live on the WALLETS & SETTINGS screen + // too: that screen's whole point is naming the key that fires each row, + // so a key it names has to work while it is open. + if matches!(self.screen, Screen::Main | Screen::WalletsSettings { .. }) { + match key.code { + KeyCode::F(2) => { + self.open_share()?; + return Ok(None); + } + KeyCode::F(3) => { + self.screen = Screen::Paste { + buf: String::new(), + err: None, + }; + return Ok(None); + } + KeyCode::F(4) => { + self.screen = Screen::Rotate { + prompt: RotatePrompt::new(), + }; + return Ok(None); + } + KeyCode::F(5) => { + self.who_open = true; + return Ok(None); + } + KeyCode::F(6) => { + self.open_wallet()?; + return Ok(None); + } + KeyCode::F(8) => { + self.screen = Screen::RotatePrekey { + prompt: RotatePrompt::new(), + }; + return Ok(None); + } + KeyCode::F(9) => { + if matches!(self.screen, Screen::Main) { + self.open_wallets_settings()?; + } + return Ok(None); + } + _ => {} + } + } + match &mut self.screen { Screen::Main => match key.code { KeyCode::Tab => self.focus = self.focus.next(), KeyCode::BackTab => self.focus = self.focus.prev(), KeyCode::Up => self.nav_up(), KeyCode::Down => self.nav_down(), - KeyCode::F(2) => self.open_share()?, - KeyCode::F(3) => { - self.screen = Screen::Paste { - buf: String::new(), - err: None, - }; - } - KeyCode::F(4) => { - self.screen = Screen::Rotate { - prompt: RotatePrompt::new(), - }; - } - KeyCode::F(5) => self.who_open = true, - KeyCode::F(6) => self.open_wallet()?, - KeyCode::F(8) => { - self.screen = Screen::RotatePrekey { - prompt: RotatePrompt::new(), - }; - } KeyCode::Esc => self.composer.clear(), KeyCode::Backspace => { if self.focus == Pane::Composer { @@ -1367,6 +1410,10 @@ impl App { self.composer.clear(); self.who_open = true; } + Some(ComposerAction::Cmd(SlashCmd::Settings)) => { + self.composer.clear(); + self.open_wallets_settings()?; + } Some(ComposerAction::Cmd(SlashCmd::Pay { atomic, memo })) => { self.composer.clear(); pay_cmd = Some((atomic, memo)); @@ -1553,6 +1600,11 @@ impl App { _ => {} }, Screen::WalletSetup(_) => self.handle_wallet_setup(key)?, + Screen::WalletsSettings { .. } => match key.code { + KeyCode::Esc => self.screen = Screen::Main, + KeyCode::Char('c') => copy_addr = true, + _ => {} + }, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1572,6 +1624,9 @@ impl App { if let Some(kind) = wipe_confirm { return self.confirm_wipe(kind); } + if copy_addr { + self.copy_receive_address(); + } if let Some(clear) = quit_clear { if clear { self.node.wipe_messages()?; @@ -1787,6 +1842,78 @@ impl App { Ok(()) } + /// F9 / `/settings`: snapshot the state the WALLETS & SETTINGS menu shows. + /// + /// Credential-free by construction: it reads `Node`'s status/label getters + /// only — never `WalletConfig::rpc_login`, `secret()`, a seed, or a + /// passphrase — so nothing on the screen can leak one. + /// + /// It blocks on the same three wallet calls the F6 screen already blocks on + /// (address, balance, recent transfers); `wallet_status` and + /// `wallet_child_status` are lock-only reads and never dial. + fn open_wallets_settings(&mut self) -> Result<(), String> { + let wstat = self.node.wallet_status(); + let child = self.node.wallet_child_status(); + let balance = self.rt.block_on(self.node.wallet_balance()); + let receive_addr = self + .rt + .block_on(self.node.wallet_receive_address()) + .unwrap_or_default(); + let transfers = self + .rt + .block_on(self.node.wallet_recent_transfers(8)) + .map(|rows| rows.len()) + .unwrap_or(0); + let profile = self.node.self_profile().ok(); + let nickname = profile + .as_ref() + .and_then(|p| (!p.display_name.is_empty()).then(|| p.display_name.clone())); + let bio_set = profile.as_ref().is_some_and(|p| !p.bio.is_empty()); + let xmr_set = profile.as_ref().is_some_and(|p| !p.xmr_addr.is_empty()); + self.screen = Screen::WalletsSettings { + state: WalletMenuState { + configured: wstat.configured, + connected: wstat.connected, + wallet_error: wstat.last_error, + receive_addr, + balance, + transfers, + child_state: child.state.as_str().to_string(), + child_source: child.chain_source, + child_error: child.last_error, + nickname, + bio_set, + xmr_set, + me_fp: self.me_fp.clone(), + }, + }; + Ok(()) + } + + /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the + /// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The + /// address never touches a file. + fn copy_receive_address(&mut self) { + let addr = match &self.screen { + Screen::WalletsSettings { state } => state.receive_addr.clone(), + _ => return, + }; + if addr.is_empty() { + self.status_note = Some("no receive address to copy".into()); + return; + } + let seq = osc52_copy_sequence(&addr); + let wrote = { + let mut out = io::stdout(); + out.write_all(seq.as_bytes()).is_ok() && out.flush().is_ok() + }; + self.status_note = Some(if wrote { + "copied receive address".into() + } else { + "could not write the clipboard sequence".into() + }); + } + /// The core's pay/tip readiness guard, refused before any dial when the /// wallet is unconfigured, view-only (for a tip), or not answering. `true` /// when the send may proceed; the reason is already in the status note when @@ -2250,6 +2377,19 @@ impl App { ) } Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), + Screen::WalletsSettings { state } => { + // The one status line the screen carries: same `status_footer` + // shape as Main, so TOR / identity / the copy confirmation read + // in the same place on every screen. + let footer = status_footer( + f.area().width, + &self.me_fp, + &self.me_onion, + self.status_note.as_deref(), + footer_hints(&self.screen), + ); + draw_wallets_settings(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -2545,9 +2685,12 @@ fn footer_fits(parts: &[String], extra: &[&str], help: &str, gap: &str, w: usize char_len(&all.join(gap)) <= w } -/// Main-screen key hints. Kept short so width 80 still shows TOR + identity + `? help`. +/// Main-screen key hints. `F6` (wallet) and `F9` (wallets & settings) are named +/// here on purpose: the menu is the discoverable surface, and the footer is how +/// a user finds the menu in the first place. Kept short so width 80 still shows +/// TOR + identity + `? help`. pub fn main_footer_hints() -> &'static str { - "Tab F2 F3 F4 F5 ? help Ctrl-Q" + "Tab F2 F3 F4 F5 F6 F9 ? help Ctrl-Q" } fn footer_hints(screen: &Screen) -> &'static str { @@ -2575,6 +2718,7 @@ match screen { } Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", + Screen::WalletsSettings { .. } => "Esc back c copy ? help", Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -2789,6 +2933,443 @@ pub fn draw_text_overlay(f: &mut Frame, title: &str, text: &str) { ); } +// --------------------------------------------------------------------------- +// WALLETS & SETTINGS menu (F9 / `/settings`) +// +// One screen that names every wallet and settings capability the TUI can +// actually reach, together with the key or command that fires each one. It is a +// discoverability layer over the existing shortcuts, not a replacement: F2, F3, +// F4, F5, F6 and F8 keep working, and they stay live *on this screen* so no row +// can name a key that does nothing here. +// +// Copy, never credentials. `WalletMenuState` carries booleans, labels and +// display-ready error strings from `Node`'s getters; it has no field that can +// hold `WalletConfig::rpc_login`, `secret()`, a seed, or a passphrase. +// --------------------------------------------------------------------------- + +/// Label column in cells. Every label is short ASCII, so this is also its +/// character count. +const MENU_LABEL_W: usize = 9; +/// Key column in cells: the widest key string the menu emits. +const MENU_KEYS_W: usize = 12; + +/// State the WALLETS & SETTINGS menu draws. Built once by the caller from +/// `Node`'s getters and carried raw (un-sanitized) — the render path strips +/// control/bidi characters and truncates in cells. +#[derive(Clone, Debug, Default)] +pub struct WalletMenuState { + /// A wallet endpoint resolved to a usable wallet (stored or env config). + pub configured: bool, + /// The last probe answered. Never inferred from `configured`. + pub connected: bool, + /// `WalletStatus::last_error`, display-ready. + pub wallet_error: Option, + /// Receive address; empty when the wallet is unreachable. + pub receive_addr: String, + /// Human-readable balance, or `off` / `err` from `Node::wallet_balance`. + pub balance: String, + /// How many recent transfers `Node::wallet_recent_transfers` returned. + pub transfers: usize, + /// `WalletChildState` display word: off / connecting / syncing / ready / + /// exited. + pub child_state: String, + /// Chain-source label: `receive-only` / `local node` / `remote daemon`. + pub child_source: String, + /// `WalletChildStatus::last_error`, display-ready. + pub child_error: Option, + /// Self-profile display name, if one is set. + pub nickname: Option, + pub bio_set: bool, + pub xmr_set: bool, + /// Our own fingerprint (identity = pubkey), full hex. + pub me_fp: String, +} + +/// Width of `s` in terminal **cells**, measured by ratatui's own text type. +/// +/// `unicode-width` is not a direct dependency of this crate, so this goes +/// through `Span::width` — the same measurement the renderer truncates with — +/// rather than `chars().count()`: CJK and emoji are double-width, combining +/// marks zero-width, and a char count gets both wrong. +pub fn cell_width(s: &str) -> usize { + ratatui::text::Span::raw(s).width() +} + +/// Truncate `s` to at most `max` cells, closed with the chrome's ellipsis. +pub fn fit_cells(s: &str, max: usize) -> String { + if cell_width(s) <= max { + return s.to_string(); + } + let e = ellipsis(); + let el = cell_width(e); + if max <= el { + return e.chars().take(max).collect(); + } + let budget = max - el; + let mut out = String::new(); + let mut used = 0; + for ch in s.chars() { + let w = cell_width(&ch.to_string()); + if used + w > budget { + break; + } + used += w; + out.push(ch); + } + format!("{out}{e}") +} + +/// One row of untrusted text, made safe to place in a single line: control and +/// bidi characters stripped (newlines and tabs included, or they would break +/// the row) and the rest left to `fit_cells`. +fn menu_cell_text(raw: &str) -> String { + sanitize::display_text(raw.as_bytes()) + .chars() + .filter(|c| !matches!(c, '\n' | '\r' | '\t')) + .collect() +} + +fn menu_yn(set: bool) -> &'static str { + if set { "set" } else { "unset" } +} + +/// Which `style_*` token a row's value carries. Colour is never the only +/// signal: every value also spells its state out in words. +#[derive(Clone, Copy, PartialEq, Eq)] +enum MenuTone { + Normal, + Dim, + Alert, + Stale, +} + +struct MenuRow { + label: &'static str, + value: String, + keys: &'static str, + tone: MenuTone, +} + +impl MenuRow { + fn new(label: &'static str, value: String, keys: &'static str, tone: MenuTone) -> Self { + Self { + label, + value, + keys, + tone, + } + } +} + +/// The two groups, in the order the card fixes: WALLET, then SETTINGS. +/// +/// Payment history here is the wallet's own transfer list (F6), which is the +/// only history `Node` exposes to the TUI. The peer `payments` table has no +/// `Node` accessor (see the card's gap list). +fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { + let endpoint_word = if !s.configured { + "not configured · receive-only" + } else if s.connected { + "configured · connected" + } else { + "configured · not connected" + }; + let endpoint_tone = if s.wallet_error.is_some() { + MenuTone::Alert + } else if !s.configured { + MenuTone::Dim + } else if s.connected { + MenuTone::Normal + } else { + MenuTone::Stale + }; + let endpoint_value = match &s.wallet_error { + Some(e) => format!("{endpoint_word} · {}", menu_cell_text(e)), + None => endpoint_word.to_string(), + }; + + let running = matches!(s.child_state.as_str(), "connecting" | "syncing" | "ready"); + let child_value = format!( + "{} · {}", + menu_cell_text(&s.child_source), + if running { "running" } else { "not started" } + ); + let (sync_word, sync_tone) = match s.child_state.as_str() { + "ready" => ("chain at tip · wallet answering", MenuTone::Normal), + "syncing" => ("wallet answering · chain not at tip", MenuTone::Stale), + "connecting" => ("wallet RPC not answering yet", MenuTone::Stale), + "exited" => ("child exited", MenuTone::Alert), + _ => ("not probing · no chain source", MenuTone::Dim), + }; + let sync_value = match &s.child_error { + Some(e) => format!("{sync_word} · {}", menu_cell_text(e)), + None => sync_word.to_string(), + }; + + let receive_empty = s.receive_addr.is_empty(); + let wallet = vec![ + MenuRow::new("endpoint", endpoint_value, "", endpoint_tone), + MenuRow::new("child", child_value, "F6 s/x", MenuTone::Normal), + MenuRow::new("sync", sync_value, "F6 p", sync_tone), + MenuRow::new( + "receive", + if receive_empty { + "no address yet · wallet unreachable".to_string() + } else { + menu_cell_text(&s.receive_addr) + }, + if receive_empty { "" } else { "c copy F6 r" }, + if receive_empty { + MenuTone::Dim + } else { + MenuTone::Normal + }, + ), + MenuRow::new( + "balance", + menu_cell_text(&s.balance), + "F6", + match s.balance.as_str() { + "err" => MenuTone::Alert, + "off" | "" => MenuTone::Dim, + _ => MenuTone::Normal, + }, + ), + MenuRow::new( + "payments", + if s.transfers == 0 { + "no transfers yet".to_string() + } else { + format!("{} recent", s.transfers) + }, + "F6", + if s.transfers == 0 { + MenuTone::Dim + } else { + MenuTone::Normal + }, + ), + MenuRow::new( + "create", + "/wallet create · seed shown once".to_string(), + "F6 c", + MenuTone::Normal, + ), + MenuRow::new( + "import", + "/wallet import · 25-word seed".to_string(), + "F6 i", + MenuTone::Normal, + ), + ]; + + let settings = vec![ + MenuRow::new( + "nickname", + match &s.nickname { + Some(n) => menu_cell_text(n), + None => "(none)".to_string(), + }, + "/profile", + if s.nickname.is_some() { + MenuTone::Normal + } else { + MenuTone::Dim + }, + ), + MenuRow::new( + "profile", + format!("bio {} · xmr {}", menu_yn(s.bio_set), menu_yn(s.xmr_set)), + "/profile", + if s.bio_set || s.xmr_set { + MenuTone::Normal + } else { + MenuTone::Dim + }, + ), + MenuRow::new( + "identity", + format!("{} · identity = pubkey", truncate_fp(&s.me_fp)), + "F2", + MenuTone::Normal, + ), + MenuRow::new( + "colour", + "auto · follows NO_COLOR / TERM".to_string(), + "", + MenuTone::Dim, + ), + MenuRow::new( + "backup", + "encrypted identity export".to_string(), + "/backup", + MenuTone::Normal, + ), + MenuRow::new( + "restore", + "overwrite self keys from a backup".to_string(), + "/restore", + MenuTone::Normal, + ), + MenuRow::new( + "wipe", + "messages · identity and friends stay".to_string(), + "/wipe", + MenuTone::Normal, + ), + MenuRow::new( + "wipe-all", + "deletes your identity key · new person".to_string(), + "/wipe-all", + MenuTone::Normal, + ), + ]; + (wallet, settings) +} + +fn menu_tone_style(tone: MenuTone) -> Style { + match tone { + MenuTone::Normal => style_text(), + MenuTone::Dim => style_dim(), + MenuTone::Alert => style_alert(), + MenuTone::Stale => style_stale(), + } +} + +/// Section header: the title in the accent, ruled off in the dim tone. The rule +/// glyph degrades to `-` under `ONIONWIRE_ASCII` / `NO_COLOR`. +fn menu_section_line(width: usize, title: &str) -> Line<'static> { + let used = cell_width(title) + 1; + let rule = if ascii_chrome() { "-" } else { "─" }; + Line::from(vec![ + Span::styled( + format!("{title} "), + style_accent().add_modifier(Modifier::BOLD), + ), + Span::styled(rule.repeat(width.saturating_sub(used)), style_dim()), + ]) +} + +/// One row, padded out to exactly `width` cells: ` label value … keys`. +/// +/// The key column is right-aligned so the eye can run down it, and the value is +/// truncated (never allowed to push the key off the row) so no row can wrap, +/// clip or scroll at 80 columns. +fn menu_row_line(width: usize, row: &MenuRow) -> Line<'static> { + let head = format!(" {: Vec> { + let w = width as usize; + let (wallet, settings) = menu_groups(s); + let mut out = vec![menu_section_line(w, "WALLET")]; + out.extend(wallet.iter().map(|row| menu_row_line(w, row))); + out.push(Line::default()); + out.push(menu_section_line(w, "SETTINGS")); + out.extend(settings.iter().map(|row| menu_row_line(w, row))); + out +} + +/// The menu body as plain text, for width/needle assertions. +pub fn wallets_settings_menu_text(width: u16, s: &WalletMenuState) -> String { + wallets_settings_menu_lines(width, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// WALLETS & SETTINGS: a full screen, never a popup — body plus the one status +/// line every other screen shares. `footer` is an already-built `status_footer` +/// line, so the caller owns TOR / identity / the transient note. +pub fn draw_wallets_settings(f: &mut Frame, state: &WalletMenuState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + let inner = rows[0].width.saturating_sub(2); + f.render_widget( + Paragraph::new(wallets_settings_menu_lines(inner, state)) + .block(themed_block("(o) wallets & settings")), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + +/// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and +/// no clipboard daemon are involved and it still works over SSH. A terminal +/// that does not implement OSC 52 ignores the sequence. +pub fn osc52_copy_sequence(text: &str) -> String { + let clean = menu_cell_text(text); + let trimmed = clean.trim(); + format!("\x1b]52;c;{}\x07", base64_encode(trimmed.as_bytes())) +} + +/// Plain RFC 4648 base64 (standard alphabet, `=` padded). Hand-rolled because +/// this crate has no base64 dependency and the menu needs exactly one call site. +fn base64_encode(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = + b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let b0 = chunk[0] as u32; + let b1 = *chunk.get(1).unwrap_or(&0) as u32; + let b2 = *chunk.get(2).unwrap_or(&0) as u32; + let n = (b0 << 16) | (b1 << 8) | b2; + out.push(ALPHABET[((n >> 18) & 63) as usize] as char); + out.push(ALPHABET[((n >> 12) & 63) as usize] as char); + out.push(if chunk.len() > 1 { + ALPHABET[((n >> 6) & 63) as usize] as char + } else { + '=' + }); + out.push(if chunk.len() > 2 { + ALPHABET[(n & 63) as usize] as char + } else { + '=' + }); + } + out +} + fn truncate_fp(fp: &str) -> String { let s: String = fp.chars().take(8).collect(); format!("{s}{}", ellipsis()) diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index cfe3c2c..f3d2a47 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -47,6 +47,7 @@ fn help_overlay_lists_core_bindings() { "F5", "F6", "F8", + "F9", "send chat", "/profile", "/pay", @@ -56,6 +57,8 @@ fn help_overlay_lists_core_bindings() { "/file", "/backup", "/restore", + "/wipe-all", + "/settings", "Ctrl-Q", "?", ] { @@ -175,6 +178,35 @@ fn pane_focus_cycles_roster_chat_composer() { assert_eq!(Pane::Composer.prev(), Pane::Chat); } +#[test] +fn menu_key_is_listed_in_help_and_in_the_main_footer() { + // Discoverability: the WALLETS & SETTINGS menu has to be findable from the + // help overlay *and* from the main footer, or F9 is a secret. + let help = help_overlay_text(); + assert!(help.contains("F9"), "F9 missing from help:\n{help}"); + assert!( + help.contains("/settings"), + "/settings missing from help:\n{help}" + ); + let hints = main_footer_hints(); + assert!( + hints.contains("F9"), + "F9 missing from footer hints: {hints:?}" + ); + let fp = "abcdef0123456789deadbeef"; + let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; + for w in [80u16, 120, 200] { + let line = status_footer(w, fp, onion, None, hints); + assert!(line.contains("F9"), "F9 dropped at {w}: {line:?}"); + assert!(line.contains("? help"), "? help dropped at {w}: {line:?}"); + assert!(line.contains("TOR"), "TOR dropped at {w}: {line:?}"); + assert!( + line.chars().count() <= w as usize, + "footer wider than {w}: {line:?}" + ); + } +} + #[test] fn restore_terminal_is_callable_without_panic() { onionwire::tui::restore_terminal(); diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 1718619..9672138 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -5,10 +5,12 @@ use onionwire::Message; use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::tui::{ - OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat, - draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints, - main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason, - status_footer, wrap_invite, + OutboxSummary, SlashCmd, WalletMenuState, alert_line, ascii_chrome, cell_width, + chat_with_delivery, delivery_tag, draw_chat, draw_share, draw_text_overlay, draw_wallets_settings, + empty_friend_chat_text, fit_cells, help_overlay_text, main_footer_hints, main_header_line, + osc52_copy_sequence, parse_cmd, paste_screen_text, retry_in_text, roster_col_width, + short_send_reason, status_footer, wallets_settings_menu_lines, wallets_settings_menu_text, + wrap_invite, }; use ratatui::Frame; use ratatui::Terminal; @@ -912,3 +914,347 @@ fn alert_line_prefixes_when_no_color() { } }; } + +// --------------------------------------------------------------------------- +// WALLETS & SETTINGS menu (F9 / `/settings`) +// --------------------------------------------------------------------------- + +/// A 94-character base58 receive address (a real one is 95; the exact length is +/// not load-bearing, only that it is far wider than the value column). +const SAMPLE_ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMWaC8iqPUE9XUBFGrLyDz4DpEBM"; + +fn menu_state() -> WalletMenuState { + WalletMenuState { + configured: true, + connected: true, + wallet_error: None, + receive_addr: SAMPLE_ADDR.into(), + balance: "0.250000000000".into(), + transfers: 3, + child_state: "ready".into(), + child_source: "local node".into(), + child_error: None, + nickname: Some("lance".into()), + bio_set: true, + xmr_set: true, + me_fp: FP.into(), + } +} + +/// The menu as the user sees it: body plus its one status line. +fn render_menu(w: u16, h: u16, st: &WalletMenuState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer(w, FP, ONION, None, "Esc back c copy ? help"); + terminal + .draw(|f| draw_wallets_settings(f, st, &footer)) + .expect("draw"); + screen_from(terminal.backend().buffer(), w, h) +} + +#[test] +fn wallets_settings_menu_lists_both_groups_and_every_key() { + let body = wallets_settings_menu_text(78, &menu_state()); + let wallet_at = body.find("WALLET").expect("wallet header"); + let settings_at = body.find("SETTINGS").expect("settings header"); + assert!(wallet_at < settings_at, "WALLET must come first:\n{body}"); + for needle in [ + "endpoint", "child", "sync", "receive", "balance", "payments", "create", "import", + ] { + assert!( + body.contains(needle), + "WALLET row {needle:?} missing:\n{body}" + ); + } + for needle in [ + "nickname", "profile", "identity", "colour", "backup", "restore", "wipe", + ] { + assert!( + body.contains(needle), + "SETTINGS row {needle:?} missing:\n{body}" + ); + } + // Every actionable row names the key or command that fires it, including the + // F6 wallet screen's own keys, so the menu teaches the shortcuts it sits + // beside instead of hiding them. + for key in [ + "F6 s/x", "F6 p", "c copy F6 r", "F6 c", "F6 i", "F6 r", "F2", "/profile", "/backup", + "/restore", "/wipe", "/wipe-all", + ] { + assert!( + body.contains(key), + "key {key:?} missing from the menu:\n{body}" + ); + } +} + +#[test] +fn wallets_settings_menu_never_renders_credentials() { + let st = WalletMenuState { + wallet_error: Some("rpc_login=user:hunter2 rejected".into()), + child_error: Some("chain: no login configured".into()), + ..menu_state() + }; + let body = wallets_settings_menu_text(78, &st); + // No passphrase, seed or login is ever a field on this screen. + assert!(!body.contains("passphrase"), "\n{body}"); + assert!(!body.contains("seed word"), "\n{body}"); + assert!(!body.contains("WalletConfig"), "\n{body}"); +} + +#[test] +fn wallets_settings_menu_keeps_one_row_per_cell_even_with_hostile_values() { + // A value that arrives multi-line or tab-separated still occupies one row: + // the row count is fixed, so nothing can be pushed off a 24-row screen. + let st = WalletMenuState { + wallet_error: Some("line one\nline two\nline three".into()), + nickname: Some("tab\there".into()), + ..menu_state() + }; + let fixed = wallets_settings_menu_lines(78, &menu_state()).len(); + let messy = wallets_settings_menu_lines(78, &st); + assert_eq!( + messy.len(), + fixed, + "a multi-line value changed the row count" + ); + let text = wallets_settings_menu_text(78, &st); + assert!(text.contains("line one")); + assert!( + text.lines().count() == messy.len(), + "a newline in a value split a row:\n{text}" + ); + // The hostile value stays on the endpoint row it belongs to. + let endpoint = text + .lines() + .find(|l| l.starts_with(" endpoint")) + .expect("endpoint row"); + assert!(endpoint.contains("line one"), "{endpoint:?}"); + assert!(text.contains("tabhere")); +} + +#[test] +fn wallets_settings_menu_words_every_state() { + let unconfigured = WalletMenuState { + configured: false, + connected: false, + balance: "off".into(), + receive_addr: String::new(), + transfers: 0, + child_state: "off".into(), + child_source: "receive-only".into(), + nickname: None, + bio_set: false, + xmr_set: false, + ..menu_state() + }; + let body = wallets_settings_menu_text(78, &unconfigured); + assert!(body.contains("not configured · receive-only"), "\n{body}"); + assert!(!body.contains("connected"), "claimed a connection:\n{body}"); + assert!(body.contains("no address yet"), "\n{body}"); + assert!(body.contains("no transfers yet"), "\n{body}"); + assert!(body.contains("not probing · no chain source"), "\n{body}"); + assert!(body.contains("(none)"), "\n{body}"); + assert!(body.contains("bio unset · xmr unset"), "\n{body}"); + // An unconfigured wallet has no address, so there is nothing to copy and no + // copy key is offered. + assert!( + !body.contains("c copy"), + "offered copying with no address:\n{body}" + ); + + let stale = WalletMenuState { + configured: true, + connected: false, + child_state: "syncing".into(), + balance: "err".into(), + ..menu_state() + }; + let body = wallets_settings_menu_text(78, &stale); + assert!(body.contains("configured · not connected"), "\n{body}"); + assert!(body.contains("wallet answering · chain not at tip"), "\n{body}"); + + let exited = WalletMenuState { + child_state: "exited".into(), + child_error: Some("cuprated died on start".into()), + ..menu_state() + }; + let body = wallets_settings_menu_text(78, &exited); + assert!(body.contains("child exited"), "\n{body}"); + assert!(body.contains("cuprated died on start"), "\n{body}"); +} + +#[test] +fn wallets_settings_menu_truncates_wide_values_in_cells() { + for w in [78u16, 118, 198] { + for line in wallets_settings_menu_lines(w, &menu_state()) { + let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect(); + assert!( + cell_width(&text) <= w as usize, + "row wider than {w} cells ({}): {text:?}", + cell_width(&text) + ); + } + } + // At 80 columns the 94-character address cannot fit: it is cut with the + // chrome's ellipsis and never pushes the `c copy` key off the row. + let narrow = wallets_settings_menu_text(78, &menu_state()); + let receive = narrow + .lines() + .find(|l| l.contains("receive")) + .expect("receive row"); + assert!( + receive.contains('…') || receive.contains("..."), + "{receive:?}" + ); + assert!(receive.contains("c copy"), "{receive:?}"); + + // A double-width CJK name is measured in cells, so it truncates after half + // as many characters as an ASCII name of the same budget. + let cjk = WalletMenuState { + nickname: Some("私の名前はとても長い".into()), + ..menu_state() + }; + for line in wallets_settings_menu_lines(78, &cjk) { + let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect(); + assert!(cell_width(&text) <= 78, "{text:?}"); + } + assert!( + wallets_settings_menu_text(78, &cjk).contains("私の"), + "CJK name dropped" + ); + // Double-width characters cannot always fill the last cell, so the contract + // is "never over budget, never more than one cell of slack". + let cut = fit_cells("私の名前はとても長い", 8); + assert!(cell_width(&cut) <= 8, "{cut:?}"); + assert!(cell_width(&cut) >= 6, "wasted cells: {cut:?}"); + assert!( + cut.ends_with('…') || cut.ends_with("..."), + "no ellipsis: {cut:?}" + ); + // ASCII chrome swaps the ellipsis and the section rule, never the width + // contract. + let ascii = fit_cells("abcdefghij", 8); + assert!(cell_width(&ascii) <= 8, "{ascii:?}"); + assert!(ascii.starts_with("abcdef"), "{ascii:?}"); + assert_eq!(cell_width("名"), 2); + assert_eq!(cell_width("abc"), 3); +} + +#[test] +fn wallets_settings_menu_fits_80x24_and_120x40() { + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render_menu(w, h, &menu_state()); + let rows = wallets_settings_menu_lines(w - 2, &menu_state()); + // Nothing scrolls off: the body gets h - 1 rows for its footer, less the + // block's two borders. + assert!( + rows.len() <= (h - 3) as usize, + "menu needs {} rows, {w}x{h} shows {}:\n{screen}", + rows.len(), + h - 3 + ); + assert!(screen.contains("WALLET"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("SETTINGS"), "{w}x{h}:\n{screen}"); + assert!( + screen.contains("wipe-all"), + "last row clipped at {w}x{h}:\n{screen}" + ); + assert!( + screen.contains("? help"), + "footer clipped at {w}x{h}:\n{screen}" + ); + for line in screen.lines() { + assert!( + cell_width(line) <= w as usize, + "row wider than {w} at {w}x{h}: {line:?}" + ); + } + } + // 200x60 must not break, and the full address fits there. + let wide = render_menu(200, 60, &menu_state()); + assert!( + wide.contains(SAMPLE_ADDR), + "200x60 truncated the address:\n{wide}" + ); +} + +#[test] +fn wallets_settings_menu_unconfigured_frame_is_not_a_blank_screen() { + let st = WalletMenuState { + configured: false, + balance: "off".into(), + receive_addr: String::new(), + transfers: 0, + child_state: "off".into(), + child_source: "receive-only".into(), + nickname: None, + bio_set: false, + xmr_set: false, + ..menu_state() + }; + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render_menu(w, h, &st); + // The empty state still names the way out of it. + assert!(screen.contains("not configured"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("/wallet create"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("/wallet import"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("no address yet"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("? help"), "{w}x{h}:\n{screen}"); + } +} + +#[test] +fn wallets_settings_menu_frame_dumps() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; + let unconfigured = WalletMenuState { + configured: false, + balance: "off".into(), + receive_addr: String::new(), + transfers: 0, + child_state: "off".into(), + child_source: "receive-only".into(), + ..menu_state() + }; + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== WALLETS & SETTINGS {w}x{h} ====="); + print!("{}", render_menu(w, h, &menu_state())); + println!("===== WALLETS & SETTINGS (unconfigured) {w}x{h} ====="); + print!("{}", render_menu(w, h, &unconfigured)); + } +} + +#[test] +fn osc52_copy_sequence_is_a_base64_clipboard_write() { + // OSC 52: ESC ] 52 ; c ; BEL — the terminal owns the clipboard, so + // the address never touches a file and no crate is needed. + assert_eq!(osc52_copy_sequence("4Ada"), "\u{1b}]52;c;NEFkYQ==\u{7}"); + + let seq = osc52_copy_sequence(SAMPLE_ADDR); + let payload = seq + .strip_prefix("\u{1b}]52;c;") + .and_then(|s| s.strip_suffix('\u{7}')) + .expect("osc52 envelope"); + assert_eq!(payload.len(), 128, "94 bytes base64 to 128 characters"); + assert!(payload.ends_with("=="), "{payload:?}"); + assert!( + payload + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '='), + "{payload:?}" + ); + + // Junk cannot escape the sequence: bidi/control characters, a newline and a + // stray BEL are stripped before encoding, and surrounding space is trimmed. + let seq = osc52_copy_sequence("4Ada\u{202e}\n\u{7}"); + assert_eq!(seq, "\u{1b}]52;c;NEFkYQ==\u{7}"); + assert_eq!(osc52_copy_sequence(" 4Ada "), "\u{1b}]52;c;NEFkYQ==\u{7}"); +} + +#[test] +fn slash_settings_is_the_menu() { + assert!(matches!(parse_cmd("/settings"), Some(SlashCmd::Settings))); + assert!(matches!(parse_cmd(" /settings "), Some(SlashCmd::Settings))); + assert!(parse_cmd("/settings now").is_none()); +}