diff --git a/docs/TUI.md b/docs/TUI.md index 89af4a0..ee82596 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -829,3 +829,55 @@ pane can drop the fingerprint without changing the row's meaning). `chars().count()`. The roster row spends its budget on the name first, then the `stale` word, then whatever is left on a fingerprint prefix — a 22-cell pane reads `bob-the-sta… stale`, not `… bbbbbbbb… stale`. + +## Invite screen: the payload region (mouse-copy) + +OnionWire never turns on mouse capture (`grep -rn EnableMouseCapture src/` is +empty), so sharing an invite means the terminal's own drag-select. A drag copies +every cell it crosses — and `draw_share` used to render the payload inside +`themed_block("(o) invite")`, which is `Borders::ALL`: every payload row sat +between `│` at column 0 and `│` at the last column, so the pasted string carried +border glyphs. + +The payload now gets its own region: **flush at column 0, full frame width, no +block, no title, no gutter on any row it occupies**. Everything that is not the +payload — why it exists, `fp`, `onion`, the copy key — lives in the bordered +block *above* it. The layout is `Layout::vertical([Length(body + 2), Min(0)])`, +so the chrome block grows with its own content and the payload always starts on +the row after its bottom border. + +``` +===== draw_share (real) 80x24 ===== +┌(o) invite────────────────────────────────────────────────────────────────────┐ +│give this string to a friend; they F3 paste it │ +│fp ea4a6c63… │ +│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ +│select the link below with the mouse, or press C to copy │ +└──────────────────────────────────────────────────────────────────────────────┘ +onionwire:v1:k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: +o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: +spk=0101010101010101010101010101010101010101010101010101010101010101: +sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e054 +01b0af934cefea617f71466f406af4bef956847200a8e915190b +``` + +At 120x40 and 200x60 `fp` and `onion` share one row (the block is one line +shorter); the payload region is unchanged. `wrap_invite` still breaks on `:`, so +joining the payload rows (trailing pad cells aside) is the payload byte for byte. +`tests/tui_chrome.rs` renders `draw_share` at 80x24, 120x40, 200x60 and 60x20 and +asserts exactly that, and that no row carrying payload carries `│`, `|`, `┃`, +`+`, `-` or `┄`. + +### `C` — the explicit copy affordance + +`C` on the invite screen writes the payload to the terminal's own clipboard with +OSC 52 (`osc52_copy_sequence`, the same sequence the F9 menu uses for the receive +address — no crate, no clipboard daemon, works over SSH). A terminal that does +not implement OSC 52 ignores the sequence, so the screen names the mouse +selection too; the line reads `select the link below with the mouse, or press C +to copy` whenever the block is wide enough, and `press C to copy, or select the +link below` otherwise. `?` lists the key as `F2 share invite (C copies it)`. + +The copy has no transient confirmation of its own: `draw_share` takes only the +payload, and `status_note` is not rendered on this screen. The mouse remains the +path that always works. diff --git a/src/tui.rs b/src/tui.rs index 42e75bb..fa51df4 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -533,7 +533,7 @@ OnionWire keys\n\ g / G jump to top / bottom\n\ Enter send chat to selected friend, or a /command\n\ Esc close overlay, go back, clear composer\n\ - F2 share invite\n\ + F2 share invite (C copies it)\n\ F3 paste invite\n\ F4 rotate onion locator\n\ F5 selected friend's profile (/who)\n\ @@ -1513,11 +1513,15 @@ impl App { } _ => {} }, - Screen::Share { .. } => { - if key.code == KeyCode::Esc { - self.screen = Screen::Main; + Screen::Share { .. } => match key.code { + KeyCode::Esc => self.screen = Screen::Main, + KeyCode::Char('c') | KeyCode::Char('C') + if !key.modifiers.contains(KeyModifiers::CONTROL) => + { + self.copy_invite(); } - } + _ => {} + }, Screen::Paste { buf, err } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => { @@ -1958,6 +1962,26 @@ impl App { }); } + /// `C` on the invite screen: the same OSC 52 handoff as the receive address, + /// so a terminal that blocks the write still leaves the mouse selection as + /// the way out. The payload never touches a file. + fn copy_invite(&mut self) { + let payload = match &self.screen { + Screen::Share { payload } => payload.clone(), + _ => return, + }; + let seq = osc52_copy_sequence(&payload); + 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 invite".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 @@ -3077,23 +3101,71 @@ fn themed_block(title: &str) -> Block<'_> { .title_style(style_accent().add_modifier(Modifier::BOLD)) } +/// The invite screen: chrome above the payload, nothing beside it. +/// +/// Sharing is a copy job, and OnionWire never turns on mouse capture — no +/// `EnableMouseCapture` anywhere in `src/` — so the terminal's own drag-select +/// is what copies an invite. A drag copies every cell it crosses, pane borders +/// included, so a bordered pane around the payload splices `│` into the string +/// the user pastes. The payload therefore gets its own region: flush at column +/// 0, the full frame width, no block, no title, no gutter on any row it +/// occupies. The title, the identity lines and the copy key sit in a bordered +/// block *above* it, and `wrap_invite` breaks on `:` so the payload rows join +/// back to the payload byte for byte +/// (`tests/tui_chrome.rs::share_payload_rebuilds_from_the_frame_at_80x24_and_120x40`). pub fn draw_share(f: &mut Frame, payload: &str) { let (fp, onion) = match qr::decode(payload) { Ok(p) => (truncate_fp(&to_hex(&p.pubkey)), p.onion), Err(_) => ("?".into(), "?".into()), }; - let inner = f.area().width.saturating_sub(2) as usize; - let invite = wrap_invite(payload, inner.max(1)); - let body = format!( - "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{invite}" - ); + let area = f.area(); + let body = share_body_lines(&fp, &onion, area.width.saturating_sub(2) as usize); + // Border top + body + border bottom. The payload region below gets no + // block: it is the selection, so nothing may sit beside it. + let header_h = (body.len() as u16).saturating_add(2).min(area.height); + let rows = Layout::vertical([Constraint::Length(header_h), Constraint::Min(0)]).split(area); f.render_widget( Paragraph::new(body) .style(style_text()) - .wrap(Wrap { trim: false }) .block(themed_block("(o) invite")), - f.area(), + rows[0], ); + + if rows[1].height == 0 { + return; + } + // Flush at column 0, full frame width, one wrapped row per payload row. + let wrapped = wrap_invite(payload, rows[1].width as usize); + f.render_widget(Paragraph::new(wrapped).style(style_text()), rows[1]); +} + +/// Everything about the invite that is not the invite: why it exists, whose it +/// is, and how to copy it. All of it lives in the bordered block *above* the +/// payload, so no row of the payload region carries chrome. +fn share_body_lines(fp: &str, onion: &str, inner: usize) -> Vec> { + let identity = format!("fp {fp} onion {onion}"); + let mut lines = vec![Line::from(fit_cells( + "give this string to a friend; they F3 paste it", + inner, + ))]; + if cell_width(&identity) <= inner { + lines.push(Line::from(identity)); + } else { + lines.push(Line::from(fit_cells(&format!("fp {fp}"), inner))); + lines.push(Line::from(fit_cells(&format!("onion {onion}"), inner))); + } + // `C` is the escape hatch for terminals that block OSC 52; the mouse is the + // path that works everywhere, so both are named. + let copy_hint = if inner >= 48 { + "select the link below with the mouse, or press C to copy" + } else { + "press C to copy, or select the link below" + }; + lines.push(Line::from(Span::styled( + fit_cells(copy_hint, inner), + style_dim(), + ))); + lines } fn draw_paste(f: &mut Frame, buf: &str, err: Option<&str>) { diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index e4d7fb7..13bf224 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -7,6 +7,7 @@ use onionwire::tui::{ main_footer_hints, onion_glyph, pane_footer_hints, status_footer, status_footer_compact, status_footer_phased, tor_token, wordmark_banner, }; +use ratatui::buffer::Buffer; #[test] fn wordmark_banner_is_nonempty_and_fits_80() { @@ -338,7 +339,177 @@ fn share_screen_shows_invite_not_qr_at_80x24() { for ch in ['█', '▀', '▄'] { assert!( !screen.contains(ch), - "share screen still has QR block {ch:?}:\n{screen}" + "share screen still has QR block {ch:?}:\\n{screen}" ); } } + +// --------------------------------------------------------------------------- +// Mouse-copy: the invite must be selectable without chrome (card t_af8b509e) +// +// OnionWire never enables mouse capture (no `EnableMouseCapture` anywhere in +// `src/`), so the terminal's own drag-select is what copies an invite. A drag +// copies exactly the cells it crosses — including the `│` columns of any pane +// that spans the payload rows. The payload therefore has to live in a region +// no chrome crosses, and these tests reconstruct it out of the rendered frame +// the same way the terminal hands it to the clipboard. +// --------------------------------------------------------------------------- + +/// Every glyph a border can be drawn with, unicode chrome and `ASCII_BORDERS`. +const BORDER_GLYPHS: [char; 6] = ['│', '|', '┃', '+', '-', '┄']; + +fn share_frame(width: u16, height: u16, payload: &str) -> Buffer { + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + let backend = TestBackend::new(width, height); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, payload)).expect("draw"); + terminal.backend().buffer().clone() +} + +fn frame_row(buf: &Buffer, width: u16, y: u16) -> String { + (0..width).map(|x| buf[(x, y)].symbol()).collect() +} + +fn frame_text(buf: &Buffer, width: u16, height: u16) -> String { + (0..height) + .map(|y| frame_row(buf, width, y)) + .collect::>() + .join("\n") +} + +/// True when the row, read from column 0, is payload: the invite's own alphabet +/// and nothing else. A row that starts with a border cell, a space, or any +/// character the payload cannot contain is not a payload row — it is payload +/// with chrome in front of it, and a drag would copy that chrome. +fn row_is_payload(row: &str) -> bool { + let trimmed = row.trim_end(); + !trimmed.is_empty() + && trimmed + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, ':' | '=' | '.')) +} + +/// The same row classification, but tolerant of a gutter: used to find the rows +/// that *carry* payload even when something else is drawn on them. +fn row_carries_payload(row: &str) -> bool { + row_is_payload(row.trim_matches([' ', '│', '|', '┃', '+', '-'])) +} + +#[test] +fn share_payload_rebuilds_from_the_frame_at_80x24_and_120x40() { + let payload = qr::encode( + &[7u8; 32], + "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", + &[1u8; 32], + ) + .expect("encode"); + + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60), (60, 20)] { + let buf = share_frame(w, h, &payload); + let rows: Vec = (0..h) + .map(|y| frame_row(&buf, w, y)) + .filter(|row| row_is_payload(row)) + .collect(); + assert!( + !rows.is_empty(), + "no chrome-free payload row at column 0 on the {w}x{h} share screen; \ + a mouse drag across the invite would copy the pane borders:\n{}", + frame_text(&buf, w, h) + ); + // Trailing cells are the frame's pad, not the payload; nothing else is + // removed — no gutter is allowed to be there in the first place. + let rebuilt: String = rows.iter().map(|r| r.trim_end()).collect(); + assert_eq!( + rebuilt, + payload, + "mouse-selecting the invite at {w}x{h} does not rebuild the payload:\n\ + got {rebuilt:?}\nwant {payload:?}\nframe:\n{}", + frame_text(&buf, w, h) + ); + } +} + +#[test] +fn share_payload_rows_carry_no_border_glyph() { + let payload = qr::encode( + &[7u8; 32], + "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", + &[1u8; 32], + ) + .expect("encode"); + + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60), (60, 20)] { + let buf = share_frame(w, h, &payload); + let mut carrying = 0; + for y in 0..h { + let row = frame_row(&buf, w, y); + if !row_carries_payload(&row) { + continue; + } + carrying += 1; + for glyph in BORDER_GLYPHS { + assert!( + !row.contains(glyph), + "row {y} carries invite payload AND the border glyph {glyph:?} \ + at {w}x{h}: {row:?}\nframe:\n{}", + frame_text(&buf, w, h) + ); + } + } + assert!( + carrying > 0, + "no payload rows found at {w}x{h}:\n{}", + frame_text(&buf, w, h) + ); + } +} + +/// (b) the explicit affordance: `C` hands the payload to the terminal's own +/// clipboard (OSC 52) and the screen names that key, so the escape sequence has +/// to carry the invite byte for byte and nothing else. +#[test] +fn share_copy_key_sequence_carries_the_payload_exactly() { + use onionwire::tui::osc52_copy_sequence; + + let payload = qr::encode( + &[7u8; 32], + "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", + &[1u8; 32], + ) + .expect("encode"); + let seq = osc52_copy_sequence(&payload); + assert!(seq.starts_with("\u{1b}]52;c;"), "{seq:?}"); + assert!(seq.ends_with('\u{7}'), "{seq:?}"); + let b64 = &seq["\u{1b}]52;c;".len()..seq.len() - 1]; + assert_eq!(b64_decode(b64), payload.as_bytes()); + + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let buf = share_frame(w, h, &payload); + let screen = frame_text(&buf, w, h); + assert!( + screen.contains("press C") && screen.contains("copy"), + "the {w}x{h} share screen does not name the copy key:\n{screen}" + ); + } +} + +/// Minimal RFC 4648 decoder, so the copy path is checked end to end rather than +/// against a hardcoded string. +fn b64_decode(text: &str) -> Vec { + const ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = Vec::new(); + let mut acc: u32 = 0; + let mut bits = 0; + for ch in text.chars().filter(|c| *c != '=') { + let v = ALPHABET.find(ch).expect("base64 alphabet") as u32; + acc = (acc << 6) | v; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + out +}