fix(tui): invite payload gets a chrome-free region so mouse-copy is exact #122
7 changed files with 1435 additions and 52 deletions
Merge branch 'main' into onionwire/t_af8b509e-onionwire-tui-invite-mouse-copy-must-not
commit
87196e2297
|
|
@ -367,7 +367,13 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
|||
* the system refuses anyway, [NodeHost] records why and the roster says so.
|
||||
*/
|
||||
private suspend fun startKeepAlive(w: Wire) {
|
||||
if (NodeHost.keepAlive.value is KeepAliveStatus.On) return
|
||||
// Announced even when the keep-alive is already `On`: it was anchored at
|
||||
// the Open tap with an empty locator, so the notice says "OnionWire is
|
||||
// starting". The POST_NOTIFICATIONS callback happens to re-announce on a
|
||||
// fresh install, but on a device that already granted notifications
|
||||
// there is no callback at all — the notice would then claim bootstrap
|
||||
// forever. Same notification id, so this replaces it with the address
|
||||
// the user can actually hand out.
|
||||
KeepAliveService.start(getApplication(), w.onion())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -118,7 +118,28 @@ val ndkClangLibDir: File = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/
|
|||
*/
|
||||
fun linkFlags(target: AndroidTarget): String {
|
||||
val sysrootLib = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/sysroot/usr/lib/${target.sysrootLib}")
|
||||
// The *dynamic* libc/libm/libdl stubs live in a per-API subdirectory; the
|
||||
// arch directory above holds the static `libc.a` and the libc++ archives.
|
||||
// Both must be on the search path, and this one must come first: `-lc`
|
||||
// resolves to whichever the linker finds first, and bionic linked
|
||||
// statically into a shared object is a landmine — its `getauxval` reads an
|
||||
// auxv vector only the dynamic linker fills in, so the first C++ static
|
||||
// initializer that asks for it (RandomX's, from `cuprate-daemon`) null-derefs
|
||||
// inside `dlopen` and takes the process with it.
|
||||
val sysrootStubLib = sysrootLib.resolve(onionwireApiLevel.toString())
|
||||
require(sysrootStubLib.resolve("libc.so").isFile) {
|
||||
"no dynamic libc stub at $sysrootStubLib/libc.so — NDK $onionwireNdkVersion layout changed? " +
|
||||
"Linking the arch dir alone would pull in the static libc.a."
|
||||
}
|
||||
return listOf(
|
||||
// Hygiene on a hand-written link line: lld defaults to --no-as-needed,
|
||||
// which records a DT_NEEDED for every `-l` mentioned even when nothing
|
||||
// is taken from it. (`libstdc++.so` survives this anyway — randomx-rs's
|
||||
// cmake half asks for it and it satisfies symbols the static libc++
|
||||
// archives were already scanned for. That shim is present on every
|
||||
// Android release to date; the device run in the PR loads it.)
|
||||
"-C", "link-arg=-Wl,--as-needed",
|
||||
"-C", "link-arg=-L$sysrootStubLib",
|
||||
"-C", "link-arg=-L$sysrootLib",
|
||||
"-C", "link-arg=-L$ndkClangLibDir",
|
||||
"-C", "link-arg=-lclang_rt.builtins-${target.builtins}",
|
||||
|
|
@ -294,6 +315,42 @@ tasks.withType<KotlinCompile>().configureEach {
|
|||
dependsOn(uniffiBindgen)
|
||||
}
|
||||
|
||||
tasks.matching { it.name == "preBuild" }.configureEach {
|
||||
dependsOn(cargoBuildAndroid, uniffiBindgen)
|
||||
/**
|
||||
* Fails the build if the SDK's shared object did not link bionic dynamically.
|
||||
*
|
||||
* `linkFlags()` spells the NDK search path out by hand, and `-L` order decides
|
||||
* whether `-lc` resolves to the per-API `libc.so` stub or to the arch
|
||||
* directory's `libc.a`. Static bionic inside a `.so` leaves `getauxval` reading
|
||||
* an auxv vector only the dynamic linker fills in, so the first C++ static
|
||||
* initializer that asks for CPU features null-derefs inside `dlopen` — a crash
|
||||
* with no Java stack, at the first SDK call, on every ABI. Reading the built
|
||||
* ELF is the only check that catches it before a device does.
|
||||
*/
|
||||
val verifyDynamicLibc by tasks.registering {
|
||||
group = "verification"
|
||||
description = "Asserts libonionwire_sdk.so links libc.so dynamically (no static bionic)."
|
||||
dependsOn(cargoBuildAndroid)
|
||||
val libsDir = jniLibsDir
|
||||
val abis = onionwireAbis
|
||||
val readelf = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/bin/llvm-readelf")
|
||||
doLast {
|
||||
abis.forEach { abi ->
|
||||
val so = libsDir.get().asFile.resolve(abi).resolve("libonionwire_sdk.so")
|
||||
check(so.isFile) { "no $so to verify — did cargoBuildAndroid run for $abi?" }
|
||||
val proc = ProcessBuilder(readelf.absolutePath, "-d", so.absolutePath)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
val dump = proc.inputStream.bufferedReader().use { it.readText() }
|
||||
check(proc.waitFor() == 0) { "$readelf failed on $so:\n$dump" }
|
||||
check(dump.lineSequence().any { it.contains("(NEEDED)") && it.contains("libc.so") }) {
|
||||
"$so has no libc.so in DT_NEEDED — it linked the static libc.a. " +
|
||||
"That is the `-L` order in linkFlags() regressing; a device crashes " +
|
||||
"with a null deref in getauxval the first time the SDK is dlopen'd.\n$dump"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.matching { it.name == "preBuild" }.configureEach {
|
||||
dependsOn(cargoBuildAndroid, uniffiBindgen, verifyDynamicLibc)
|
||||
}
|
||||
|
|
|
|||
89
docs/TUI.md
89
docs/TUI.md
|
|
@ -653,7 +653,8 @@ fires it, including the F6 wallet screen's own keys (`F6 c`, `F6 i`, `F6 r`,
|
|||
| 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 | transfers | `{n} recent` / `no transfers yet` — the wallet's **own** transfer list | `F6` |
|
||||
| WALLET | payments | `{n} with {peer}` / `no history with {peer}` / `no friend selected` / `history unreadable · {peer}` — the **peer's** payment rows | `p` |
|
||||
| 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` |
|
||||
|
|
@ -665,7 +666,13 @@ fires it, including the F6 wallet screen's own keys (`F6 c`, `F6 i`, `F6 r`,
|
|||
| 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.
|
||||
20 rows at 80x24 against 21 available inner rows: nothing clips or scrolls.
|
||||
|
||||
`transfers` and `payments` are deliberately two rows: `transfers` is the
|
||||
wallet's own list (`Node::wallet_recent_transfers`, F6), `payments` is the
|
||||
peer-scoped history (`Node::list_payments`, `p`). Signed `/pay` invoices and
|
||||
`/tip` receipts a peer sent never appear in the wallet's own transfers, so the
|
||||
two histories are not interchangeable and the menu names both.
|
||||
|
||||
### Guarantees
|
||||
|
||||
|
|
@ -699,12 +706,86 @@ sibling-card work, not presentation:
|
|||
`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).
|
||||
- Peer payment history — **closed by this screen.** `Node::list_payments` exists
|
||||
on `main`; the `payments` row (key `p`) opens the peer-scoped history, and the
|
||||
row is distinct from the wallet's own transfer list (`transfers`, F6).
|
||||
- `Node::set_wallet_child_config(cfg)` — the child can be started/stopped and
|
||||
probed, not edited.
|
||||
- `Node::set_petname(..)` — no petname editor exists.
|
||||
|
||||
## Peer payment history (F9 → `payments`, key `p`)
|
||||
|
||||
A screen, not a popup, and peer-scoped: it renders what
|
||||
`Node::list_payments(&friend_pk)` returns for the chat's selected friend, so the
|
||||
signed `/pay` invoices and `/tip` receipts a peer sent are visible even though
|
||||
they never appear in the wallet's own transfer list (F6). The call takes the
|
||||
store lock only — no Tor dial, no wallet RPC — so it is safe while offline or
|
||||
while Arti is still bootstrapping, and an empty result (`Ok(vec![])`) is the
|
||||
**no history** state, never an error.
|
||||
|
||||
```
|
||||
cargo test --locked --test tui_payments -- --nocapture peer_payments_frame_dumps
|
||||
```
|
||||
|
||||
dumps the screen at 80x24, 120x40 and 200x60, populated and empty.
|
||||
|
||||
### Layout
|
||||
|
||||
```
|
||||
dir kind amount XMR receipt memo
|
||||
> in receipt 0.025 verified lunch money
|
||||
out tip 0.005 coffee
|
||||
out invoice 0.1 rent
|
||||
|
||||
tx 3f2a91c0d9e4b7a2c1f0e8d7b6a5948372615041324758697a8b9c0d1e2f3041
|
||||
addr 4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMW
|
||||
aC8iqPUE9XUBFGrLyDz4DpEBM
|
||||
```
|
||||
|
||||
- Rows are **newest first**: `payments.id` ascending is oldest first, so
|
||||
`PeerPaymentsState::from_payments` reverses it and the render path windows the
|
||||
result. Rows outside the window are counted in an explicit `… N older` /
|
||||
`… N newer` line — nothing is dropped silently.
|
||||
- The focused row is marked with `>` **and** bold, so focus survives a
|
||||
monochrome terminal. `up`/`down` (or `k`/`j`) move it, `Esc` returns to the
|
||||
main screen, `F9` reopens the menu.
|
||||
- `F9` is honoured **while this screen is open**, not only from the main screen:
|
||||
the function-key table (`function_key_for`) answers it from `Main`,
|
||||
`WalletsSettings` and `PeerPayments` alike, so the hint the screen prints
|
||||
cannot be a no-op there. `peer_payments_footer_hint()` is the single place that
|
||||
hint string is written, and the frame-dump fixture is driven from it — a dumped
|
||||
frame cannot show a footer the app does not render.
|
||||
- The selected row's `tx` and `addr` are spelled out under the rows: a 64-hex
|
||||
txid is unusable truncated, and a 95-character base58 address is **wrapped**
|
||||
over two lines rather than clipped to a prefix.
|
||||
- Amounts use `pay::atomic_to_xmr_str`, the same piconero formatter the chat
|
||||
lines use; the XMR unit is stated once, in the column header.
|
||||
- Columns are dropped from the right when the pane is narrower than they need,
|
||||
so no row can wrap or overrun at any width — not just at 80.
|
||||
|
||||
### States
|
||||
|
||||
| State | Frame |
|
||||
|---|---|
|
||||
| populated | the rows, plus the selected row's `tx` / `addr` |
|
||||
| empty | `no payments with {peer}` and `invoices, receipts and tips from this peer land here` |
|
||||
| read failed | `could not read payments` plus the sanitized reason — never a blank pane |
|
||||
| no friend selected | the menu row refuses before the screen opens (`no friend selected` in the status line) |
|
||||
|
||||
### Guarantees
|
||||
|
||||
- **Memo is peer-signed text, sanitized at draw time.** `Node::list_payments`
|
||||
returns `memo` as stored; the row goes through the same
|
||||
`menu_cell_text`-then-`fit_cells` path the F9 menu uses, so C0/C1 controls,
|
||||
ESC, bidi marks and newlines cannot reach the frame buffer or split a row.
|
||||
`tests/tui_payments.rs` asserts a hostile memo (ESC, BEL, C1, bidi, newline)
|
||||
never appears in a rendered frame.
|
||||
- **Only receipts carry `verified`.** The flag column prints `verified` /
|
||||
`unverified` for receipts and stays blank for invoices and tips, which have no
|
||||
signature to check; `unverified` also takes the warn tone, so colour is never
|
||||
the only signal.
|
||||
- **Read-only.** The screen reads one getter and draws; it cannot send, sign or
|
||||
dial.
|
||||
## Clean-look chrome redesign — implemented
|
||||
|
||||
The main screen was restructured around one accent, one primary pane and honest
|
||||
|
|
|
|||
83
src/node.rs
83
src/node.rs
|
|
@ -28,7 +28,7 @@ use crate::ratchet::{RatchetKeyPair, RatchetState};
|
|||
use crate::ratelimit::TokenBucket;
|
||||
use crate::sanitize;
|
||||
use crate::session::{self, Keys};
|
||||
use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store};
|
||||
use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store};
|
||||
use crate::wallet::{self, Readiness, Wallet, WalletConfig, WalletStatus};
|
||||
use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus};
|
||||
|
||||
|
|
@ -500,6 +500,23 @@ impl Node {
|
|||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The signed `/pay` invoices and `/tip` receipts that came from one peer,
|
||||
/// oldest row first. A friend with no payment rows is an empty vector, not
|
||||
/// an error.
|
||||
///
|
||||
/// Read-only and fail-closed: it locks the store and nothing else — no Tor
|
||||
/// dial, no wallet RPC. `memo` is the text the peer signed, stored and
|
||||
/// returned as it arrived; a renderer sanitizes it with
|
||||
/// [`crate::sanitize::display_text`] at draw time, exactly as the chat
|
||||
/// bodies from [`Self::list_messages`] are.
|
||||
pub fn list_payments(&self, friend_pk: &[u8]) -> Result<Vec<Payment>, String> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.list_payments(friend_pk)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The live wallet, cloned out of its lock. Every wallet call goes through
|
||||
/// this so a `std::sync::Mutex` guard never lives across an `.await`, and so
|
||||
/// the F7 screen can re-point the wallet mid-session.
|
||||
|
|
@ -2314,6 +2331,70 @@ mod tests {
|
|||
assert_eq!(rows[0].kind, "tip");
|
||||
}
|
||||
|
||||
/// The peer payment history the TUI needs: `Store::list_payments` existed but
|
||||
/// nothing on `Node` reached it, so the signed invoice/receipt frames a peer
|
||||
/// sent were invisible to the app. One row per stored frame, oldest first,
|
||||
/// and a friend with no rows is an empty vector, not an error.
|
||||
#[tokio::test]
|
||||
async fn list_payments_round_trips_a_peers_invoice_and_receipt() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||||
let peer = Keys::generate();
|
||||
let stranger = Keys::generate();
|
||||
let addr = xmr_addr();
|
||||
befriend(
|
||||
&node.store.lock().unwrap(),
|
||||
&peer.identity_pk,
|
||||
&peer.prekey_pk,
|
||||
"peer.onion",
|
||||
);
|
||||
{
|
||||
let store = node.store.lock().unwrap();
|
||||
store
|
||||
.insert_payment(
|
||||
&peer.identity_pk,
|
||||
PaymentWrite {
|
||||
dir: "in",
|
||||
kind: "invoice",
|
||||
amount_atomic: "500000000000",
|
||||
address: &addr,
|
||||
memo: "rent",
|
||||
txid: None,
|
||||
verified: false,
|
||||
},
|
||||
)
|
||||
.expect("store inbound invoice");
|
||||
store
|
||||
.insert_payment(
|
||||
&peer.identity_pk,
|
||||
PaymentWrite {
|
||||
dir: "in",
|
||||
kind: "receipt",
|
||||
amount_atomic: "250000000000",
|
||||
address: &addr,
|
||||
memo: "",
|
||||
txid: Some("deadbeef"),
|
||||
verified: false,
|
||||
},
|
||||
)
|
||||
.expect("store inbound receipt");
|
||||
}
|
||||
|
||||
let rows = node.list_payments(&peer.identity_pk).expect("payments");
|
||||
assert_eq!(rows.len(), 2, "one row per stored frame");
|
||||
assert_eq!(rows[0].kind, "invoice", "oldest row first");
|
||||
assert_eq!(rows[0].dir, "in");
|
||||
assert_eq!(rows[0].amount_atomic, "500000000000");
|
||||
assert_eq!(rows[0].memo, "rent");
|
||||
assert_eq!(rows[1].kind, "receipt");
|
||||
assert_eq!(rows[1].txid.as_deref(), Some("deadbeef"));
|
||||
|
||||
let none = node
|
||||
.list_payments(&stranger.identity_pk)
|
||||
.expect("a friend with no rows is an empty vector, not an error");
|
||||
assert!(none.is_empty());
|
||||
}
|
||||
|
||||
/// A stand-in for `monero-wallet-rpc`: it records its argv, then does what
|
||||
/// the test needs. The wallet child spawns a real process, so this is the
|
||||
/// only honest way to drive the start path offline.
|
||||
|
|
|
|||
741
src/tui.rs
741
src/tui.rs
|
|
@ -17,7 +17,7 @@ use crate::node::Node;
|
|||
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
|
||||
use crate::qr::{self, QrPayload};
|
||||
use crate::sanitize;
|
||||
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
|
||||
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment};
|
||||
use crate::wallet::{self, ChainSource};
|
||||
|
||||
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
|
||||
|
|
@ -1282,6 +1282,12 @@ enum Screen {
|
|||
WalletsSettings {
|
||||
state: WalletMenuState,
|
||||
},
|
||||
/// F9 → `payments`: the peer-scoped history from `Node::list_payments`.
|
||||
/// Holds the same kind of snapshot as the menu (a resize re-fits it), so a
|
||||
/// repaint never re-reads the store mid-frame.
|
||||
PeerPayments {
|
||||
state: PeerPaymentsState,
|
||||
},
|
||||
Quit {
|
||||
prompt: QuitPrompt,
|
||||
},
|
||||
|
|
@ -1295,6 +1301,44 @@ enum WalletSetup {
|
|||
ImportPass { seed: Zeroizing<String>, entry: PassphraseEntry },
|
||||
}
|
||||
|
||||
/// A function key the TUI answers before the per-screen `match`; the screen's
|
||||
/// own key handler never sees it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum FunctionKey {
|
||||
Share,
|
||||
Paste,
|
||||
Rotate,
|
||||
Who,
|
||||
Wallet,
|
||||
RotatePrekey,
|
||||
OpenMenu,
|
||||
}
|
||||
|
||||
/// The function key `screen` answers, or `None` when the key belongs to the
|
||||
/// per-screen handler.
|
||||
///
|
||||
/// The function keys stay live on every screen that names one — in its footer
|
||||
/// or in its body: a shortcut the user can read has to work while that screen
|
||||
/// is open.
|
||||
fn function_key_for(screen: &Screen, code: KeyCode) -> Option<FunctionKey> {
|
||||
if !matches!(
|
||||
screen,
|
||||
Screen::Main | Screen::WalletsSettings { .. } | Screen::PeerPayments { .. }
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
match code {
|
||||
KeyCode::F(2) => Some(FunctionKey::Share),
|
||||
KeyCode::F(3) => Some(FunctionKey::Paste),
|
||||
KeyCode::F(4) => Some(FunctionKey::Rotate),
|
||||
KeyCode::F(5) => Some(FunctionKey::Who),
|
||||
KeyCode::F(6) => Some(FunctionKey::Wallet),
|
||||
KeyCode::F(8) => Some(FunctionKey::RotatePrekey),
|
||||
KeyCode::F(9) => Some(FunctionKey::OpenMenu),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new(node: Arc<Node>, rt: tokio::runtime::Handle) -> Result<Self, String> {
|
||||
let friends = node.list_friends()?;
|
||||
|
|
@ -1378,51 +1422,41 @@ impl App {
|
|||
let mut file_cmd = None;
|
||||
let mut chat_send = None;
|
||||
let mut pass_submit = None;
|
||||
let mut open_payments = false;
|
||||
let mut payments_back = false;
|
||||
let mut payments_move = 0i32;
|
||||
|
||||
// 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) => {
|
||||
// and the peer history too: the settings screen's whole point is naming
|
||||
// the key that fires each row, and the history's footer names `F9
|
||||
// menu`, so a key a screen names has to work while it is open.
|
||||
if let Some(fk) = function_key_for(&self.screen, key.code) {
|
||||
match fk {
|
||||
FunctionKey::Share => self.open_share()?,
|
||||
FunctionKey::Paste => {
|
||||
self.screen = Screen::Paste {
|
||||
buf: String::new(),
|
||||
err: None,
|
||||
};
|
||||
return Ok(None);
|
||||
}
|
||||
KeyCode::F(4) => {
|
||||
FunctionKey::Rotate => {
|
||||
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) => {
|
||||
FunctionKey::Who => self.who_open = true,
|
||||
FunctionKey::Wallet => self.open_wallet()?,
|
||||
FunctionKey::RotatePrekey => {
|
||||
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);
|
||||
}
|
||||
_ => {}
|
||||
// One level above the screen it is pressed on: F9 from Main
|
||||
// opens the menu, and from the menu or the peer history it
|
||||
// reopens it rather than silently doing nothing.
|
||||
FunctionKey::OpenMenu => self.open_wallets_settings()?,
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
match &mut self.screen {
|
||||
|
|
@ -1651,6 +1685,14 @@ impl App {
|
|||
Screen::WalletsSettings { .. } => match key.code {
|
||||
KeyCode::Esc => self.screen = Screen::Main,
|
||||
KeyCode::Char('c') => copy_addr = true,
|
||||
// `p` is the key the menu's `payments` row prints.
|
||||
KeyCode::Char('p') => open_payments = true,
|
||||
_ => {}
|
||||
},
|
||||
Screen::PeerPayments { .. } => match key.code {
|
||||
KeyCode::Esc => payments_back = true,
|
||||
KeyCode::Up | KeyCode::Char('k') => payments_move = -1,
|
||||
KeyCode::Down | KeyCode::Char('j') => payments_move = 1,
|
||||
_ => {}
|
||||
},
|
||||
Screen::Quit { prompt } => match key.code {
|
||||
|
|
@ -1672,6 +1714,21 @@ impl App {
|
|||
if let Some(kind) = wipe_confirm {
|
||||
return self.confirm_wipe(kind);
|
||||
}
|
||||
if payments_move != 0
|
||||
&& let Screen::PeerPayments { state } = &mut self.screen
|
||||
{
|
||||
if payments_move < 0 {
|
||||
state.select_prev();
|
||||
} else {
|
||||
state.select_next();
|
||||
}
|
||||
}
|
||||
if payments_back {
|
||||
self.screen = Screen::Main;
|
||||
}
|
||||
if open_payments {
|
||||
self.open_peer_payments()?;
|
||||
}
|
||||
if copy_addr {
|
||||
self.copy_receive_address();
|
||||
}
|
||||
|
|
@ -1918,6 +1975,19 @@ impl App {
|
|||
.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());
|
||||
// The friend the rest of the TUI acts on is the chat's selected friend.
|
||||
// `list_payments` is a lock-only read: no dial, no RPC, so this snapshot
|
||||
// stays cheap and works while Tor is still bootstrapping.
|
||||
let friend = self.friends.get(self.selected);
|
||||
let peer = friend
|
||||
.map(|f| f.petname.clone().unwrap_or_else(|| f.fingerprint.clone()))
|
||||
.unwrap_or_default();
|
||||
let peer_payments = friend.and_then(|f| {
|
||||
self.node
|
||||
.list_payments(&f.pubkey)
|
||||
.ok()
|
||||
.map(|rows| rows.len())
|
||||
});
|
||||
self.screen = Screen::WalletsSettings {
|
||||
state: WalletMenuState {
|
||||
configured: wstat.configured,
|
||||
|
|
@ -1933,11 +2003,37 @@ impl App {
|
|||
bio_set,
|
||||
xmr_set,
|
||||
me_fp: self.me_fp.clone(),
|
||||
peer,
|
||||
peer_payments,
|
||||
},
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The F9 menu's `payments` row: the selected friend's payment history from
|
||||
/// `Node::list_payments`.
|
||||
///
|
||||
/// Read-only and fail-closed: the call takes the store lock and nothing
|
||||
/// else, so it never dials and is safe while offline. A friend with no rows
|
||||
/// is `Ok(vec![])` — an empty history, not an error.
|
||||
fn open_peer_payments(&mut self) -> Result<(), String> {
|
||||
let Some(friend) = self.friends.get(self.selected) else {
|
||||
self.status_note = Some("no friend selected".into());
|
||||
return Ok(());
|
||||
};
|
||||
let peer = friend
|
||||
.petname
|
||||
.clone()
|
||||
.unwrap_or_else(|| friend.fingerprint.clone());
|
||||
let pk = friend.pubkey.clone();
|
||||
let state = match self.node.list_payments(&pk) {
|
||||
Ok(rows) => PeerPaymentsState::from_payments(peer, &rows),
|
||||
Err(e) => PeerPaymentsState::error(peer, e),
|
||||
};
|
||||
self.screen = Screen::PeerPayments { state };
|
||||
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.
|
||||
|
|
@ -2459,6 +2555,16 @@ impl App {
|
|||
);
|
||||
draw_wallets_settings(f, state, &footer)
|
||||
}
|
||||
Screen::PeerPayments { state } => {
|
||||
let footer = status_footer(
|
||||
f.area().width,
|
||||
&self.me_fp,
|
||||
&self.me_onion,
|
||||
self.status_note.as_deref(),
|
||||
footer_hints(&self.screen),
|
||||
);
|
||||
draw_peer_payments(f, state, &footer)
|
||||
}
|
||||
}
|
||||
if self.help_open {
|
||||
draw_text_overlay(f, "? help", help_overlay_text());
|
||||
|
|
@ -3080,11 +3186,31 @@ 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::WalletsSettings { .. } => wallets_settings_footer_hint(),
|
||||
Screen::PeerPayments { .. } => peer_payments_footer_hint(),
|
||||
Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help",
|
||||
}
|
||||
}
|
||||
|
||||
/// The hint line the peer-payment-history screen prints. One source only: the
|
||||
/// screen's frame tests build their fixture from this, so a dumped frame can
|
||||
/// never show a footer the app does not render.
|
||||
pub fn peer_payments_footer_hint() -> &'static str {
|
||||
PEER_PAYMENTS_FOOTER_HINT
|
||||
}
|
||||
|
||||
const PEER_PAYMENTS_FOOTER_HINT: &str = "Esc back up/down select F9 menu ? help";
|
||||
|
||||
/// The hint line the WALLETS & SETTINGS menu prints, single-sourced for the
|
||||
/// same reason as [`peer_payments_footer_hint`]: the menu's frame-dump fixture
|
||||
/// must not hand-copy it (and must not pair it with the phase-free footer the
|
||||
/// app stopped using when the chrome redesign landed).
|
||||
pub fn wallets_settings_footer_hint() -> &'static str {
|
||||
WALLETS_SETTINGS_FOOTER_HINT
|
||||
}
|
||||
|
||||
const WALLETS_SETTINGS_FOOTER_HINT: &str = "Esc back c copy ? help";
|
||||
|
||||
fn apply_chrome_borders(block: Block<'_>) -> Block<'_> {
|
||||
let block = block.borders(Borders::ALL);
|
||||
if ascii_chrome() {
|
||||
|
|
@ -3406,6 +3532,12 @@ pub struct WalletMenuState {
|
|||
pub xmr_set: bool,
|
||||
/// Our own fingerprint (identity = pubkey), full hex.
|
||||
pub me_fp: String,
|
||||
/// Display name of the friend the F9 screen's friend-scoped rows act on (the
|
||||
/// chat's selected friend), or empty when there is none.
|
||||
pub peer: String,
|
||||
/// `Some(rows)` when `Node::list_payments` answered for that friend;
|
||||
/// `None` when the read itself failed (which is not "no history").
|
||||
pub peer_payments: Option<usize>,
|
||||
}
|
||||
|
||||
/// Width of `s` in terminal **cells**, measured by ratatui's own text type.
|
||||
|
|
@ -3486,9 +3618,9 @@ impl MenuRow {
|
|||
|
||||
/// 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).
|
||||
/// Two payment-ish rows, and they are not the same thing: `transfers` is the
|
||||
/// wallet's own list (F6, `wallet_recent_transfers`), `payments` is the
|
||||
/// peer-scoped history (`Node::list_payments`) opened by `p`.
|
||||
fn menu_groups(s: &WalletMenuState) -> (Vec<MenuRow>, Vec<MenuRow>) {
|
||||
let endpoint_word = if !s.configured {
|
||||
"not configured · receive-only"
|
||||
|
|
@ -3559,7 +3691,7 @@ fn menu_groups(s: &WalletMenuState) -> (Vec<MenuRow>, Vec<MenuRow>) {
|
|||
},
|
||||
),
|
||||
MenuRow::new(
|
||||
"payments",
|
||||
"transfers",
|
||||
if s.transfers == 0 {
|
||||
"no transfers yet".to_string()
|
||||
} else {
|
||||
|
|
@ -3572,6 +3704,29 @@ fn menu_groups(s: &WalletMenuState) -> (Vec<MenuRow>, Vec<MenuRow>) {
|
|||
MenuTone::Normal
|
||||
},
|
||||
),
|
||||
// The peer-scoped history: signed `/pay` invoices and `/tip` receipts
|
||||
// that peer sent. Distinct from the wallet's own transfer list above,
|
||||
// and labelled so — `Payments` here means `payments` rows, not the
|
||||
// wallet's `transfers`.
|
||||
MenuRow::new(
|
||||
"payments",
|
||||
if s.peer.is_empty() {
|
||||
"no friend selected".to_string()
|
||||
} else {
|
||||
let peer = menu_cell_text(&s.peer);
|
||||
match s.peer_payments {
|
||||
None => format!("history unreadable {}{peer}", "\u{b7} "),
|
||||
Some(0) => format!("no history with {peer}"),
|
||||
Some(n) => format!("{n} with {peer}"),
|
||||
}
|
||||
},
|
||||
if s.peer.is_empty() { "" } else { "p" },
|
||||
if s.peer.is_empty() || s.peer_payments == Some(0) {
|
||||
MenuTone::Dim
|
||||
} else {
|
||||
MenuTone::Normal
|
||||
},
|
||||
),
|
||||
MenuRow::new(
|
||||
"create",
|
||||
"/wallet create · seed shown once".to_string(),
|
||||
|
|
@ -3757,6 +3912,430 @@ pub fn draw_wallets_settings(f: &mut Frame, state: &WalletMenuState, footer: &st
|
|||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Peer payment history: the F9 menu's `payments` row.
|
||||
//
|
||||
// This is the *other* history. The F6 screen shows the wallet's own transfer
|
||||
// list (`Node::wallet_recent_transfers`); this one shows the peer-scoped rows
|
||||
// `Node::list_payments` returns — the signed `/pay` invoices and `/tip`
|
||||
// receipts that peer sent, which never appear in the wallet's own transfers.
|
||||
//
|
||||
// Everything here is display data: `memo` is peer-signed text returned as
|
||||
// stored, so it goes through `menu_cell_text` (control + bidi stripped, no
|
||||
// newlines) and `fit_cells` (truncated in cells) before it can reach a frame.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Direction column in cells: `in` / `out`.
|
||||
const PAY_DIR_W: usize = 3;
|
||||
/// Kind column in cells: `invoice` / `receipt` / `tip`.
|
||||
const PAY_KIND_W: usize = 7;
|
||||
/// Amount column in cells, right-aligned: `0.025000000000` is 14, so 15 holds
|
||||
/// every XMR string `pay::atomic_to_xmr_str` can produce from a u128 piconero.
|
||||
const PAY_AMOUNT_W: usize = 15;
|
||||
/// Receipt flag column in cells: `unverified` is the widest word.
|
||||
const PAY_FLAG_W: usize = 10;
|
||||
|
||||
/// One payment row, display-ready except for `memo`/`txid`/`address`, which the
|
||||
/// render path sanitizes.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PeerPaymentRow {
|
||||
/// `"in"` or `"out"` — the peer's direction, not ours.
|
||||
pub dir: String,
|
||||
/// `"invoice"`, `"receipt"` or `"tip"`.
|
||||
pub kind: String,
|
||||
/// `pay::atomic_to_xmr_str(amount_atomic)` — the same formatter the chat
|
||||
/// lines use, not a second piconero formatter.
|
||||
pub amount_xmr: String,
|
||||
/// Peer-signed memo, as stored. Sanitized at draw time.
|
||||
pub memo: String,
|
||||
/// Chain txid, when the payment has one.
|
||||
pub txid: Option<String>,
|
||||
/// Destination address.
|
||||
pub address: String,
|
||||
/// Receipt signature check. Only receipts carry a meaningful flag.
|
||||
pub verified: bool,
|
||||
}
|
||||
|
||||
/// What the peer payment screen draws. Rows are **newest first** — the store
|
||||
/// returns `payments.id` ascending, so `from_payments` reverses them here and
|
||||
/// the render path windows the result. `error` is display-ready and only set
|
||||
/// when the store read itself failed; an empty history is not an error.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PeerPaymentsState {
|
||||
/// Display name of the peer this history belongs to.
|
||||
pub peer: String,
|
||||
pub rows: Vec<PeerPaymentRow>,
|
||||
pub error: Option<String>,
|
||||
/// Index into `rows` (display order, 0 = newest).
|
||||
pub selected: usize,
|
||||
}
|
||||
|
||||
impl PeerPaymentsState {
|
||||
/// Build the screen state from `Node::list_payments`' rows.
|
||||
pub fn from_payments(peer: String, rows: &[Payment]) -> Self {
|
||||
let mut out: Vec<PeerPaymentRow> = rows
|
||||
.iter()
|
||||
.map(|p| PeerPaymentRow {
|
||||
dir: p.dir.clone(),
|
||||
kind: p.kind.clone(),
|
||||
amount_xmr: crate::pay::atomic_to_xmr_str(&p.amount_atomic),
|
||||
memo: p.memo.clone(),
|
||||
txid: p.txid.clone(),
|
||||
address: p.address.clone(),
|
||||
verified: p.verified,
|
||||
})
|
||||
.collect();
|
||||
// `payments.id` ascending is oldest first; a history reads newest first.
|
||||
out.reverse();
|
||||
Self {
|
||||
peer,
|
||||
rows: out,
|
||||
error: None,
|
||||
selected: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The read failed. The screen says so instead of pretending "no history".
|
||||
pub fn error(peer: String, why: String) -> Self {
|
||||
Self {
|
||||
peer,
|
||||
rows: Vec::new(),
|
||||
error: Some(why),
|
||||
selected: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select_next(&mut self) {
|
||||
if !self.rows.is_empty() {
|
||||
self.selected = (self.selected + 1).min(self.rows.len() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select_prev(&mut self) {
|
||||
self.selected = self.selected.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pad `s` out to `cells` terminal cells on the right.
|
||||
fn pad_right(s: &str, cells: usize) -> String {
|
||||
let mut out = s.to_string();
|
||||
let w = cell_width(&out);
|
||||
if w < cells {
|
||||
out.push_str(&" ".repeat(cells - w));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Pad `s` out to `cells` terminal cells on the left (numbers line up).
|
||||
fn pad_left(s: &str, cells: usize) -> String {
|
||||
let w = cell_width(s);
|
||||
if w >= cells {
|
||||
return s.to_string();
|
||||
}
|
||||
let mut out = " ".repeat(cells - w);
|
||||
out.push_str(s);
|
||||
out
|
||||
}
|
||||
|
||||
/// Split `s` into a prefix of at most `max` cells and the (possibly empty)
|
||||
/// remainder, so a long display value can be wrapped instead of clipped.
|
||||
fn split_cells(s: &str, max: usize) -> (String, String) {
|
||||
let mut head = String::new();
|
||||
let mut used = 0;
|
||||
for (i, ch) in s.char_indices() {
|
||||
let w = cell_width(&ch.to_string());
|
||||
if used + w > max {
|
||||
return (head, s[i..].to_string());
|
||||
}
|
||||
used += w;
|
||||
head.push(ch);
|
||||
}
|
||||
(head, String::new())
|
||||
}
|
||||
|
||||
/// Which style a laid-out span carries.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PaySlot {
|
||||
Head,
|
||||
Amount,
|
||||
Flag,
|
||||
Memo,
|
||||
}
|
||||
|
||||
/// Lay out one payment line for `w` cells: `head`, then the amount, the receipt
|
||||
/// flag and a flexible memo. Trailing columns are **dropped** when the pane is
|
||||
/// too narrow, so no row can ever wrap or overrun — the 80-column floor holds
|
||||
/// even if a terminal is smaller than the floor.
|
||||
fn pay_columns(
|
||||
w: usize,
|
||||
head: &str,
|
||||
amount: &str,
|
||||
flag: &str,
|
||||
memo: &str,
|
||||
) -> Vec<(PaySlot, String)> {
|
||||
let mut out: Vec<(PaySlot, String)> = Vec::new();
|
||||
let head = if cell_width(head) > w {
|
||||
fit_cells(head, w)
|
||||
} else {
|
||||
head.to_string()
|
||||
};
|
||||
let mut used = cell_width(&head);
|
||||
out.push((PaySlot::Head, head));
|
||||
|
||||
if !amount.is_empty() && w >= used + 2 + PAY_AMOUNT_W {
|
||||
let amount = fit_cells(amount, PAY_AMOUNT_W);
|
||||
out.push((PaySlot::Head, " ".to_string()));
|
||||
out.push((PaySlot::Amount, pad_left(&amount, PAY_AMOUNT_W)));
|
||||
used += 2 + PAY_AMOUNT_W;
|
||||
}
|
||||
if !flag.is_empty() && w >= used + 2 + PAY_FLAG_W {
|
||||
let flag = fit_cells(flag, PAY_FLAG_W);
|
||||
out.push((PaySlot::Head, " ".to_string()));
|
||||
out.push((PaySlot::Flag, pad_right(&flag, PAY_FLAG_W)));
|
||||
used += 2 + PAY_FLAG_W;
|
||||
}
|
||||
if w > used + 2 {
|
||||
let memo = fit_cells(memo, w - used - 2);
|
||||
if !memo.is_empty() {
|
||||
out.push((PaySlot::Head, " ".to_string()));
|
||||
out.push((PaySlot::Memo, memo));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The column header, so an `in`/`out` and a `receipt`/`invoice` need no legend
|
||||
/// and the XMR unit is stated once instead of on every row.
|
||||
fn payment_header_line(w: usize) -> Line<'static> {
|
||||
let head = format!(
|
||||
"{} {}",
|
||||
pad_right("dir", PAY_DIR_W),
|
||||
pad_right("kind", PAY_KIND_W)
|
||||
);
|
||||
let mut spans = vec![Span::raw(" ".to_string())];
|
||||
spans.extend(
|
||||
pay_columns(w.saturating_sub(2), &head, "amount XMR", "receipt", "memo")
|
||||
.into_iter()
|
||||
.map(|(_, text)| Span::styled(text, style_dim())),
|
||||
);
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// One payment row. The focused row is marked with `>` **and** bold, so focus
|
||||
/// survives a monochrome terminal; an unverified receipt says `unverified` as
|
||||
/// well as taking the warn tone, so the state is never colour-only.
|
||||
fn payment_row_line(w: usize, row: &PeerPaymentRow, selected: bool) -> Line<'static> {
|
||||
let dir = fit_cells(&menu_cell_text(&row.dir), PAY_DIR_W);
|
||||
let kind = fit_cells(&menu_cell_text(&row.kind), PAY_KIND_W);
|
||||
let head = format!(
|
||||
"{} {}",
|
||||
pad_right(&dir, PAY_DIR_W),
|
||||
pad_right(&kind, PAY_KIND_W)
|
||||
);
|
||||
let amount = menu_cell_text(&row.amount_xmr);
|
||||
let (flag, flag_tone) = if row.kind == "receipt" {
|
||||
if row.verified {
|
||||
("verified".to_string(), style_text())
|
||||
} else {
|
||||
("unverified".to_string(), style_stale())
|
||||
}
|
||||
} else {
|
||||
// A blank flag column, not an absent one: the memo column has to line
|
||||
// up down the pane or the rows read as ragged.
|
||||
(" ".repeat(PAY_FLAG_W), style_text())
|
||||
};
|
||||
let memo = menu_cell_text(&row.memo);
|
||||
|
||||
let mark_style = if selected {
|
||||
style_accent().add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
style_dim()
|
||||
};
|
||||
let mut spans = vec![Span::styled(
|
||||
if selected { "> " } else { " " }.to_string(),
|
||||
mark_style,
|
||||
)];
|
||||
for (slot, text) in pay_columns(w.saturating_sub(2), &head, &amount, &flag, &memo) {
|
||||
let style = match slot {
|
||||
PaySlot::Head => style_dim(),
|
||||
PaySlot::Amount => style_text(),
|
||||
PaySlot::Flag => flag_tone,
|
||||
PaySlot::Memo => {
|
||||
if selected {
|
||||
style_text()
|
||||
} else {
|
||||
style_dim()
|
||||
}
|
||||
}
|
||||
};
|
||||
let style = if selected {
|
||||
style.add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
style
|
||||
};
|
||||
spans.push(Span::styled(text, style));
|
||||
}
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// The peer payment body as styled lines for a `width` × `height` **inner**
|
||||
/// pane. `height` matters: the window is sized so the selected row and the tx /
|
||||
/// address strip always fit, and the rows that fall outside it are counted in
|
||||
/// an explicit `… N older` / `… N newer` line rather than silently dropped.
|
||||
pub fn peer_payments_lines(width: u16, height: u16, s: &PeerPaymentsState) -> Vec<Line<'static>> {
|
||||
let w = width as usize;
|
||||
let h = height as usize;
|
||||
if let Some(err) = &s.error {
|
||||
return vec![
|
||||
Line::from(vec![Span::styled(
|
||||
" could not read payments",
|
||||
style_alert(),
|
||||
)]),
|
||||
Line::from(vec![Span::styled(
|
||||
fit_cells(&format!(" {}", menu_cell_text(err)), w.max(1)),
|
||||
style_dim(),
|
||||
)]),
|
||||
];
|
||||
}
|
||||
let peer = menu_cell_text(&s.peer);
|
||||
if s.rows.is_empty() {
|
||||
return vec![
|
||||
Line::from(vec![Span::styled(
|
||||
fit_cells(&format!(" no payments with {peer}"), w.max(1)),
|
||||
style_dim(),
|
||||
)]),
|
||||
Line::from(vec![Span::styled(
|
||||
fit_cells(
|
||||
" invoices, receipts and tips from this peer land here",
|
||||
w.max(1),
|
||||
),
|
||||
style_dim(),
|
||||
)]),
|
||||
];
|
||||
}
|
||||
if h < 3 {
|
||||
// Degenerate pane: the header alone is still an honest frame.
|
||||
return vec![payment_header_line(w)];
|
||||
}
|
||||
|
||||
let total = s.rows.len();
|
||||
let selected = s.selected.min(total - 1);
|
||||
// The selected row's detail: the txid, and the address wrapped over at most
|
||||
// two lines so a 95-character base58 address is readable at 80 columns
|
||||
// instead of clipped to a prefix.
|
||||
let txid = s.rows[selected]
|
||||
.txid
|
||||
.as_deref()
|
||||
.map(menu_cell_text)
|
||||
.unwrap_or_else(|| "(no txid yet)".to_string());
|
||||
let addr = menu_cell_text(&s.rows[selected].address);
|
||||
let (addr_head, addr_rest) = {
|
||||
let budget = w.saturating_sub(8).max(1);
|
||||
if cell_width(&addr) > budget {
|
||||
let (head, rest) = split_cells(&addr, budget);
|
||||
(head, fit_cells(&rest, budget))
|
||||
} else {
|
||||
(addr, String::new())
|
||||
}
|
||||
};
|
||||
let detail = w >= 40 && h >= 8;
|
||||
let detail_h = if detail {
|
||||
3 + usize::from(!addr_rest.is_empty())
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let budget0 = h - (1 + detail_h);
|
||||
let windowed = total > budget0 && budget0 >= 3;
|
||||
let budget = if windowed { budget0 - 2 } else { budget0 };
|
||||
let visible = budget.max(1).min(total);
|
||||
let start = if total <= visible {
|
||||
0
|
||||
} else {
|
||||
selected.saturating_sub(visible - 1).min(total - visible)
|
||||
};
|
||||
let end = (start + visible).min(total);
|
||||
|
||||
let mut out: Vec<Line<'static>> = vec![payment_header_line(w)];
|
||||
if windowed && start > 0 {
|
||||
out.push(Line::from(vec![Span::styled(
|
||||
fit_cells(&format!(" {} {start} newer", ellipsis()), w.max(1)),
|
||||
style_dim(),
|
||||
)]));
|
||||
}
|
||||
for (i, row) in s.rows.iter().enumerate().take(end).skip(start) {
|
||||
out.push(payment_row_line(w, row, i == selected));
|
||||
}
|
||||
if windowed && end < total {
|
||||
out.push(Line::from(vec![Span::styled(
|
||||
fit_cells(&format!(" {} {} older", ellipsis(), total - end), w.max(1)),
|
||||
style_dim(),
|
||||
)]));
|
||||
}
|
||||
if detail {
|
||||
out.push(Line::default());
|
||||
out.push(Line::from(vec![Span::styled(
|
||||
fit_cells(&format!(" tx {txid}"), w.max(1)),
|
||||
style_dim(),
|
||||
)]));
|
||||
out.push(Line::from(vec![Span::styled(
|
||||
fit_cells(&format!(" addr {addr_head}"), w.max(1)),
|
||||
style_dim(),
|
||||
)]));
|
||||
if !addr_rest.is_empty() {
|
||||
out.push(Line::from(vec![Span::styled(
|
||||
fit_cells(&format!(" {addr_rest}"), w.max(1)),
|
||||
style_dim(),
|
||||
)]));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body as plain text, for width/needle assertions.
|
||||
pub fn peer_payments_text(width: u16, height: u16, s: &PeerPaymentsState) -> String {
|
||||
peer_payments_lines(width, height, s)
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// Block title: the screen is peer-scoped, so the peer is named in the frame
|
||||
/// itself and not only in the rows.
|
||||
pub fn peer_payments_title(s: &PeerPaymentsState) -> String {
|
||||
let peer = menu_cell_text(&s.peer);
|
||||
if peer.is_empty() {
|
||||
"(o) payments".to_string()
|
||||
} else {
|
||||
format!("(o) payments {}{peer}", "\u{b7} ")
|
||||
}
|
||||
}
|
||||
|
||||
/// Peer payment history: a full screen like the F9 menu, with the same single
|
||||
/// status line. `footer` is an already-built `status_footer` row.
|
||||
pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str) {
|
||||
let area = f.area();
|
||||
let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
|
||||
f.render_widget(
|
||||
Paragraph::new(peer_payments_lines(
|
||||
rows[0].width.saturating_sub(2),
|
||||
rows[0].height.saturating_sub(2),
|
||||
state,
|
||||
))
|
||||
.block(themed_block(&peer_payments_title(state))),
|
||||
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.
|
||||
|
|
@ -3988,6 +4567,98 @@ fn io_err(e: io::Error) -> String {
|
|||
e.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod function_key_tests {
|
||||
use super::*;
|
||||
|
||||
fn peer_payments_screen() -> Screen {
|
||||
Screen::PeerPayments {
|
||||
state: PeerPaymentsState::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The peer history's footer prints `F9 menu`, so F9 has to reach the menu
|
||||
/// while that screen is open — not only from Main.
|
||||
#[test]
|
||||
fn f9_opens_the_menu_from_the_peer_payments_screen() {
|
||||
assert_eq!(
|
||||
function_key_for(&peer_payments_screen(), KeyCode::F(9)),
|
||||
Some(FunctionKey::OpenMenu),
|
||||
"the screen's footer names F9 but F9 does nothing there"
|
||||
);
|
||||
}
|
||||
|
||||
/// Copy and behaviour agree: every `F<n>` the screen's own hint names must
|
||||
/// be a key the screen answers. This is the test the defect class needs —
|
||||
/// the hint string and the routing table are the two halves of the claim.
|
||||
#[test]
|
||||
fn every_function_key_named_by_the_peer_payments_hint_is_answered_there() {
|
||||
let hint = peer_payments_footer_hint();
|
||||
let screen = peer_payments_screen();
|
||||
let mut named = 0;
|
||||
for (at, _) in hint.match_indices('F') {
|
||||
let digits: String = hint[at + 1..]
|
||||
.chars()
|
||||
.take_while(char::is_ascii_digit)
|
||||
.collect();
|
||||
let Ok(number) = digits.parse::<u8>() else {
|
||||
continue;
|
||||
};
|
||||
named += 1;
|
||||
assert!(
|
||||
function_key_for(&screen, KeyCode::F(number)).is_some(),
|
||||
"hint names F{number} ({hint:?}) but the screen does not answer it"
|
||||
);
|
||||
}
|
||||
assert!(named > 0, "the hint names no function key: {hint:?}");
|
||||
}
|
||||
|
||||
/// The menu screen names `c` and `Esc`, not the function keys, but it is
|
||||
/// the screen the `payments` row came from — its own keys stay its own.
|
||||
#[test]
|
||||
fn function_keys_stay_live_on_the_wallets_settings_screen() {
|
||||
let screen = Screen::WalletsSettings {
|
||||
state: WalletMenuState::default(),
|
||||
};
|
||||
for key in [
|
||||
KeyCode::F(2),
|
||||
KeyCode::F(3),
|
||||
KeyCode::F(4),
|
||||
KeyCode::F(5),
|
||||
KeyCode::F(6),
|
||||
KeyCode::F(8),
|
||||
KeyCode::F(9),
|
||||
] {
|
||||
assert!(
|
||||
function_key_for(&screen, key).is_some(),
|
||||
"{key:?} is named on the menu but is not answered there"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A screen that names no function key keeps the key to itself: the
|
||||
/// composer's `F`-less screens must not steal F-keys they never advertise.
|
||||
#[test]
|
||||
fn screens_that_name_no_function_key_do_not_answer_one() {
|
||||
for screen in [
|
||||
Screen::Paste {
|
||||
buf: String::new(),
|
||||
err: None,
|
||||
},
|
||||
Screen::WalletSetup(WalletSetup::ImportSeed {
|
||||
buf: Zeroizing::new(String::new()),
|
||||
}),
|
||||
] {
|
||||
for key in [KeyCode::F(9), KeyCode::F(6)] {
|
||||
assert!(
|
||||
function_key_for(&screen, key).is_none(),
|
||||
"{key:?} was answered on a screen that never names it"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod passphrase_buffer_tests {
|
||||
use super::*;
|
||||
|
|
|
|||
435
tests/tui_payments.rs
Normal file
435
tests/tui_payments.rs
Normal file
|
|
@ -0,0 +1,435 @@
|
|||
//! Peer payment history screen (F9 → `payments` row).
|
||||
//!
|
||||
//! The screen renders what `Node::list_payments` returns for the friend the rest
|
||||
//! of the TUI acts on: signed `/pay` invoices, `/tip` receipts and tips, with
|
||||
//! direction, kind, amount, memo, txid and the receipt's verified flag.
|
||||
//!
|
||||
//! Assertions measure in terminal **cells** (`cell_width`, which goes through
|
||||
//! `Span::width`) and accept either ellipsis form / rule glyph, because
|
||||
//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the two TUI test
|
||||
//! binaries run in parallel.
|
||||
|
||||
use onionwire::Payment;
|
||||
use onionwire::tui::{
|
||||
PeerPaymentRow, PeerPaymentsState, WalletMenuState, cell_width, draw_peer_payments,
|
||||
peer_payments_footer_hint, peer_payments_lines, peer_payments_text, status_footer,
|
||||
wallets_settings_menu_text,
|
||||
};
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
const FP: &str = "abcdef0123456789deadbeefcafebabe";
|
||||
const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
|
||||
const TXID: &str = "3f2a91c0d9e4b7a2c1f0e8d7b6a5948372615041324758697a8b9c0d1e2f3041";
|
||||
const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMWaC8iqPUE9XUBFGrLyDz4DpEBM";
|
||||
|
||||
fn row(
|
||||
dir: &str,
|
||||
kind: &str,
|
||||
xmr: &str,
|
||||
memo: &str,
|
||||
txid: Option<&str>,
|
||||
verified: bool,
|
||||
) -> PeerPaymentRow {
|
||||
PeerPaymentRow {
|
||||
dir: dir.into(),
|
||||
kind: kind.into(),
|
||||
amount_xmr: xmr.into(),
|
||||
memo: memo.into(),
|
||||
txid: txid.map(str::to_string),
|
||||
address: ADDR.into(),
|
||||
verified,
|
||||
}
|
||||
}
|
||||
|
||||
/// A peer with three rows: a receipt for a signed invoice, a tip, and the
|
||||
/// invoice itself. Newest first, the way the card orders the window.
|
||||
fn peer_state() -> PeerPaymentsState {
|
||||
PeerPaymentsState {
|
||||
peer: "lance".into(),
|
||||
rows: vec![
|
||||
row("in", "receipt", "0.025", "lunch money", Some(TXID), true),
|
||||
row("out", "tip", "0.005", "coffee", None, false),
|
||||
row("out", "invoice", "0.1", "rent", None, false),
|
||||
],
|
||||
error: None,
|
||||
selected: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn render(w: u16, h: u16, st: &PeerPaymentsState) -> String {
|
||||
let backend = TestBackend::new(w, h);
|
||||
let mut terminal = Terminal::new(backend).expect("terminal");
|
||||
// The same two calls the app makes, so a dumped frame can never show a
|
||||
// footer (or a hint) the app does not render.
|
||||
let footer = status_footer(w, FP, ONION, None, peer_payments_footer_hint());
|
||||
terminal
|
||||
.draw(|f| draw_peer_payments(f, st, &footer))
|
||||
.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');
|
||||
}
|
||||
screen
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_frame_shows_the_shipped_footer() {
|
||||
let shipped = status_footer(80, FP, ONION, None, peer_payments_footer_hint());
|
||||
let frame = render(80, 24, &peer_state());
|
||||
let last = frame.lines().nth(23).unwrap_or_default();
|
||||
assert_eq!(
|
||||
last.trim_end(),
|
||||
shipped.trim_end(),
|
||||
"the dumped frame's footer is not the one the app renders"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_lists_every_required_field() {
|
||||
let body = peer_payments_text(78, 21, &peer_state());
|
||||
for needle in [
|
||||
"dir",
|
||||
"kind",
|
||||
"amount",
|
||||
"receipt",
|
||||
"memo", // column header
|
||||
"in",
|
||||
"out", // direction
|
||||
"invoice",
|
||||
"receipt",
|
||||
"tip", // kind
|
||||
"0.025",
|
||||
"0.1",
|
||||
"0.005", // amount
|
||||
"lunch money",
|
||||
"rent",
|
||||
"coffee", // memo
|
||||
"verified", // receipt flag
|
||||
"tx",
|
||||
TXID, // txid when present
|
||||
"addr",
|
||||
// destination address of the selected row (see the wrap assertions below)
|
||||
] {
|
||||
assert!(body.contains(needle), "missing {needle:?}:\n{body}");
|
||||
}
|
||||
// The address is wrapped over two lines at 80 columns, not clipped: the head
|
||||
// starts on the `addr` row and the tail survives on the continuation line.
|
||||
assert!(body.contains(&ADDR[..40]), "\n{body}");
|
||||
assert!(
|
||||
body.contains(&ADDR[ADDR.len() - 20..]),
|
||||
"the address tail was clipped, not wrapped:\n{body}"
|
||||
);
|
||||
// Amounts carry the shared piconero formatter's units once, in the header.
|
||||
assert!(body.contains("amount XMR"), "\n{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_amount_is_the_shared_formatter_not_a_second_one() {
|
||||
let rows = vec![Payment {
|
||||
id: 1,
|
||||
dir: "in".into(),
|
||||
kind: "receipt".into(),
|
||||
amount_atomic: "25000000000".into(),
|
||||
address: ADDR.into(),
|
||||
memo: "lunch".into(),
|
||||
txid: Some(TXID.into()),
|
||||
verified: true,
|
||||
created_at: 0,
|
||||
}];
|
||||
let st = PeerPaymentsState::from_payments("lance".into(), &rows);
|
||||
assert_eq!(st.rows[0].amount_xmr, "0.025", "piconero -> XMR");
|
||||
assert!(
|
||||
peer_payments_text(78, 21, &st).contains("0.025"),
|
||||
"{}",
|
||||
peer_payments_text(78, 21, &st)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_empty_history_is_an_explicit_line() {
|
||||
let st = PeerPaymentsState {
|
||||
peer: "lance".into(),
|
||||
rows: Vec::new(),
|
||||
error: None,
|
||||
selected: 0,
|
||||
};
|
||||
let body = peer_payments_text(78, 21, &st);
|
||||
assert!(
|
||||
body.contains("no payments"),
|
||||
"empty state not named:\n{body}"
|
||||
);
|
||||
assert!(body.contains("lance"), "\n{body}");
|
||||
// Empty is a state, never an error.
|
||||
assert!(!body.to_lowercase().contains("error"), "\n{body}");
|
||||
assert!(!body.to_lowercase().contains("failed"), "\n{body}");
|
||||
for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] {
|
||||
let screen = render(w, h, &st);
|
||||
assert!(
|
||||
screen.contains("no payments"),
|
||||
"{w}x{h} blank panel:\n{screen}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_error_is_named_not_blank() {
|
||||
let st = PeerPaymentsState::error("lance".into(), "store lock poisoned".into());
|
||||
let body = peer_payments_text(78, 21, &st);
|
||||
assert!(body.contains("could not read payments"), "\n{body}");
|
||||
assert!(body.contains("store lock poisoned"), "\n{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_selection_uses_a_marker_not_colour_alone() {
|
||||
let mut st = peer_state();
|
||||
let first = peer_payments_text(78, 21, &st);
|
||||
let marked = first
|
||||
.lines()
|
||||
.find(|l| l.starts_with('>'))
|
||||
.expect("a selection marker");
|
||||
assert!(marked.contains("0.025"), "{marked:?}");
|
||||
st.select_next();
|
||||
let second = peer_payments_text(78, 21, &st);
|
||||
let now = second
|
||||
.lines()
|
||||
.find(|l| l.starts_with('>'))
|
||||
.expect("a selection marker");
|
||||
assert!(now.contains("0.005"), "{now:?}");
|
||||
assert_eq!(
|
||||
second.lines().filter(|l| l.starts_with('>')).count(),
|
||||
1,
|
||||
"exactly one row is focused:\n{second}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_windows_a_long_history_and_says_so() {
|
||||
let rows: Vec<PeerPaymentRow> = (0..40)
|
||||
.map(|i| {
|
||||
row(
|
||||
"in",
|
||||
"receipt",
|
||||
"0.001",
|
||||
&format!("row {i}"),
|
||||
Some(TXID),
|
||||
true,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let st = PeerPaymentsState {
|
||||
peer: "lance".into(),
|
||||
rows,
|
||||
error: None,
|
||||
selected: 0,
|
||||
};
|
||||
let lines = peer_payments_lines(78, 21, &st);
|
||||
assert!(
|
||||
lines.len() <= 21,
|
||||
"body needs {} rows for a 21-row pane",
|
||||
lines.len()
|
||||
);
|
||||
let body = peer_payments_text(78, 21, &st);
|
||||
assert!(body.contains("older"), "window not disclosed:\n{body}");
|
||||
// The newest row is the one on screen, not the oldest.
|
||||
assert!(body.contains("row 0"), "\n{body}");
|
||||
assert!(!body.contains("row 39"), "\n{body}");
|
||||
// Scrolling to the end brings the oldest row into view.
|
||||
let mut st = st;
|
||||
for _ in 0..39 {
|
||||
st.select_next();
|
||||
}
|
||||
let body = peer_payments_text(78, 21, &st);
|
||||
assert!(body.contains("row 39"), "\n{body}");
|
||||
assert!(body.contains("newer"), "window not disclosed:\n{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_hostile_memo_cannot_reach_the_terminal() {
|
||||
// A peer-signed memo is untrusted display data: ESC/BEL/C1 controls, bidi
|
||||
// overrides and newlines must not survive into the frame buffer.
|
||||
let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow";
|
||||
let st = PeerPaymentsState {
|
||||
peer: "lance".into(),
|
||||
rows: vec![row("in", "receipt", "0.025", hostile, Some(hostile), true)],
|
||||
error: None,
|
||||
selected: 0,
|
||||
};
|
||||
for (w, h) in [(80u16, 24u16), (120, 40)] {
|
||||
let screen = render(w, h, &st);
|
||||
assert!(!screen.contains('\u{1b}'), "{w}x{h} ESC reached the frame");
|
||||
assert!(!screen.contains('\u{7}'), "{w}x{h} BEL reached the frame");
|
||||
assert!(!screen.contains('\u{9b}'), "{w}x{h} C1 reached the frame");
|
||||
assert!(
|
||||
!screen.contains('\u{202e}') && !screen.contains('\u{2066}'),
|
||||
"{w}x{h} bidi reached the frame"
|
||||
);
|
||||
assert!(screen.contains("safe"), "{w}x{h}:\n{screen}");
|
||||
}
|
||||
// The control byte itself is dropped, so the rest is inert text: `[31m` can
|
||||
// only ever be printed, never interpreted.
|
||||
let body = peer_payments_text(78, 21, &st);
|
||||
assert!(body.contains("safe[31mred"), "\n{body}");
|
||||
assert!(!body.contains('\u{1b}'), "\n{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_frames_fit_at_the_three_sizes() {
|
||||
for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] {
|
||||
let screen = render(w, h, &peer_state());
|
||||
assert!(screen.contains("payments"), "{w}x{h}:\n{screen}");
|
||||
assert!(screen.contains("lance"), "{w}x{h}:\n{screen}");
|
||||
assert!(screen.contains("? help"), "footer clipped:\n{screen}");
|
||||
assert!(
|
||||
screen.contains("lunch money"),
|
||||
"memo clipped at {w}x{h}:\n{screen}"
|
||||
);
|
||||
for line in screen.lines() {
|
||||
assert!(
|
||||
cell_width(line) <= w as usize,
|
||||
"line wider than {w} at {w}x{h}: {line:?}"
|
||||
);
|
||||
}
|
||||
let lines = peer_payments_lines(w - 2, h - 3, &peer_state());
|
||||
assert!(
|
||||
lines.len() <= (h - 3) as usize,
|
||||
"body needs {} rows, {w}x{h} shows {}",
|
||||
lines.len(),
|
||||
h - 3
|
||||
);
|
||||
}
|
||||
// 200x60 has room for the whole txid and address, untruncated.
|
||||
let wide = render(200, 60, &peer_state());
|
||||
assert!(wide.contains(TXID), "200x60 truncated the txid:\n{wide}");
|
||||
assert!(wide.contains(ADDR), "200x60 truncated the address:\n{wide}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_columns_drop_before_they_wrap() {
|
||||
// 80 columns is the floor, but a narrow terminal must still produce rows
|
||||
// that never overrun the pane: trailing columns are dropped, not wrapped.
|
||||
for w in 20u16..=200 {
|
||||
for line in peer_payments_lines(w, 21, &peer_state()) {
|
||||
let width: usize = line
|
||||
.spans
|
||||
.iter()
|
||||
.map(|s| cell_width(s.content.as_ref()))
|
||||
.sum();
|
||||
assert!(width <= w as usize, "width {w}: {width} cells: {line:?}");
|
||||
}
|
||||
for line in peer_payments_lines(
|
||||
w,
|
||||
21,
|
||||
&PeerPaymentsState {
|
||||
peer: "lance".into(),
|
||||
rows: Vec::new(),
|
||||
error: None,
|
||||
selected: 0,
|
||||
},
|
||||
) {
|
||||
let width: usize = line
|
||||
.spans
|
||||
.iter()
|
||||
.map(|s| cell_width(s.content.as_ref()))
|
||||
.sum();
|
||||
assert!(width <= w as usize, "empty state width {w}: {line:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallets_settings_menu_offers_the_peer_payments_row() {
|
||||
let st = WalletMenuState {
|
||||
transfers: 3,
|
||||
peer: "lance".into(),
|
||||
peer_payments: Some(3),
|
||||
..menu_state_defaults()
|
||||
};
|
||||
let body = wallets_settings_menu_text(78, &st);
|
||||
let row = body
|
||||
.lines()
|
||||
.find(|l| l.contains("payments"))
|
||||
.expect("payments row");
|
||||
assert!(row.contains("lance"), "row does not name the peer: {row:?}");
|
||||
assert!(row.contains('p'), "row does not name its key: {row:?}");
|
||||
// The wallet's own transfer list keeps its F6 row; it is retitled so the
|
||||
// two histories cannot be mistaken for each other.
|
||||
assert!(
|
||||
body.lines().any(|l| l.contains("transfers")),
|
||||
"wallet transfer row lost:\n{body}"
|
||||
);
|
||||
|
||||
// No friend selected: the row is dim and offers no key that would do
|
||||
// nothing.
|
||||
let st = WalletMenuState {
|
||||
peer: String::new(),
|
||||
peer_payments: None,
|
||||
..menu_state_defaults()
|
||||
};
|
||||
let body = wallets_settings_menu_text(78, &st);
|
||||
let row = body
|
||||
.lines()
|
||||
.find(|l| l.contains("payments"))
|
||||
.expect("payments row");
|
||||
assert!(row.contains("no friend"), "{row:?}");
|
||||
|
||||
// A friend with no payment rows is the empty state, not an error.
|
||||
let st = WalletMenuState {
|
||||
peer: "lance".into(),
|
||||
peer_payments: Some(0),
|
||||
..menu_state_defaults()
|
||||
};
|
||||
let body = wallets_settings_menu_text(78, &st);
|
||||
let row = body
|
||||
.lines()
|
||||
.find(|l| l.contains("payments"))
|
||||
.expect("payments row");
|
||||
assert!(row.contains("no history"), "{row:?}");
|
||||
}
|
||||
|
||||
/// The F9 menu state with a healthy wallet, as `tests/tui_spec.rs` builds it.
|
||||
fn menu_state_defaults() -> WalletMenuState {
|
||||
WalletMenuState {
|
||||
configured: true,
|
||||
connected: true,
|
||||
wallet_error: None,
|
||||
receive_addr: 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(),
|
||||
peer: String::new(),
|
||||
peer_payments: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_payments_frame_dumps() {
|
||||
for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] {
|
||||
println!("===== PEER PAYMENTS {w}x{h} =====");
|
||||
print!("{}", render(w, h, &peer_state()));
|
||||
println!("===== PEER PAYMENTS (empty) {w}x{h} =====");
|
||||
print!(
|
||||
"{}",
|
||||
render(
|
||||
w,
|
||||
h,
|
||||
&PeerPaymentsState {
|
||||
peer: "lance".into(),
|
||||
rows: Vec::new(),
|
||||
error: None,
|
||||
selected: 0,
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,11 +5,12 @@ use onionwire::Message;
|
|||
use onionwire::outbox::{OutboxEntry, OutboxStatus};
|
||||
use onionwire::qr;
|
||||
use onionwire::tui::{
|
||||
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,
|
||||
OutboxSummary, SlashCmd, TorPhase, 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, status_footer_phased,
|
||||
wallets_settings_footer_hint, wallets_settings_menu_lines, wallets_settings_menu_text,
|
||||
wrap_invite,
|
||||
};
|
||||
use ratatui::Frame;
|
||||
|
|
@ -945,6 +946,8 @@ fn menu_state() -> WalletMenuState {
|
|||
bio_set: true,
|
||||
xmr_set: true,
|
||||
me_fp: FP.into(),
|
||||
peer: "lance".into(),
|
||||
peer_payments: Some(3),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -952,13 +955,46 @@ fn menu_state() -> WalletMenuState {
|
|||
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");
|
||||
// The app's own two calls for this screen (see `App::draw`): the phased
|
||||
// footer with the hint `footer_hints` returns. A phase-free footer here
|
||||
// would be a footer the app never renders.
|
||||
let footer = status_footer_phased(
|
||||
w,
|
||||
FP,
|
||||
ONION,
|
||||
Some(TorPhase::Ready),
|
||||
None,
|
||||
wallets_settings_footer_hint(),
|
||||
);
|
||||
terminal
|
||||
.draw(|f| draw_wallets_settings(f, st, &footer))
|
||||
.expect("draw");
|
||||
screen_from(terminal.backend().buffer(), w, h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallets_settings_menu_frame_shows_the_shipped_footer() {
|
||||
// The app renders this screen's one status line with `status_footer_phased`
|
||||
// (the chrome redesign put the Tor phase in it) and the hint from
|
||||
// `footer_hints`; the fixture has to do the same or every menu frame in the
|
||||
// PR is a frame the app never draws.
|
||||
let shipped = status_footer_phased(
|
||||
80,
|
||||
FP,
|
||||
ONION,
|
||||
Some(TorPhase::Ready),
|
||||
None,
|
||||
wallets_settings_footer_hint(),
|
||||
);
|
||||
let frame = render_menu(80, 24, &menu_state());
|
||||
let last = frame.lines().nth(23).unwrap_or_default();
|
||||
assert_eq!(
|
||||
last.trim_end(),
|
||||
shipped.trim_end(),
|
||||
"the dumped menu frame's footer is not the one the app renders"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallets_settings_menu_lists_both_groups_and_every_key() {
|
||||
let body = wallets_settings_menu_text(78, &menu_state());
|
||||
|
|
@ -985,8 +1021,18 @@ fn wallets_settings_menu_lists_both_groups_and_every_key() {
|
|||
// 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",
|
||||
"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),
|
||||
|
|
@ -1079,7 +1125,10 @@ fn wallets_settings_menu_words_every_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}");
|
||||
assert!(
|
||||
body.contains("wallet answering · chain not at tip"),
|
||||
"\n{body}"
|
||||
);
|
||||
|
||||
let exited = WalletMenuState {
|
||||
child_state: "exited".into(),
|
||||
|
|
@ -1271,6 +1320,9 @@ fn osc52_copy_sequence_is_a_base64_clipboard_write() {
|
|||
#[test]
|
||||
fn slash_settings_is_the_menu() {
|
||||
assert!(matches!(parse_cmd("/settings"), Some(SlashCmd::Settings)));
|
||||
assert!(matches!(parse_cmd(" /settings "), Some(SlashCmd::Settings)));
|
||||
assert!(matches!(
|
||||
parse_cmd(" /settings "),
|
||||
Some(SlashCmd::Settings)
|
||||
));
|
||||
assert!(parse_cmd("/settings now").is_none());
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue