Skip to main content

vta_cli_common/
render.rs

1use ratatui::{
2    buffer::Buffer,
3    layout::Rect,
4    style::{Color, Modifier},
5    widgets::Widget,
6};
7use std::sync::OnceLock;
8use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
9
10// ── Bin-name registration ───────────────────────────────────────────
11//
12// pnm-cli and cnm-cli both consume this crate's shared command
13// handlers. When one of those handlers needs to point the operator at a
14// follow-up command (e.g. context-create → "did you mean to run X
15// instead?"), it must use the binary the operator actually invoked,
16// not a hard-coded `pnm`. Each CLI binary calls `set_bin_name("pnm")`
17// or `set_bin_name("cnm")` at startup; handlers read via `bin_name()`
18// and fall back to "vta" if neither was registered (the offline `vta
19// bootstrap …` path also calls into shared modules).
20
21static BIN_NAME: OnceLock<&'static str> = OnceLock::new();
22
23/// Register the binary name used in operator-facing hints. Call once at
24/// CLI startup. Only the first call sticks; later calls are ignored so
25/// that nested invocations (e.g. unit tests) don't clobber it.
26pub fn set_bin_name(name: &'static str) {
27    let _ = BIN_NAME.set(name);
28}
29
30/// The binary name registered via [`set_bin_name`]. Defaults to `"vta"`
31/// (the offline binary's name) when nothing has been registered, so
32/// shared handlers still produce a syntactically valid command string.
33pub fn bin_name() -> &'static str {
34    BIN_NAME.get().copied().unwrap_or("vta")
35}
36
37// ── Full-display toggle ─────────────────────────────────────────────
38//
39// CLI global `--full-display` flag. When enabled, list commands emit
40// every identifier in full (no ratatui-Table truncation) as a sequence
41// of key-value blocks. Default rendering stays as the compact table
42// for a readable overview; full display is the escape hatch for
43// copying complete DIDs, key ids, template names, etc.
44
45static FULL_DISPLAY: AtomicBool = AtomicBool::new(false);
46
47/// Enable or disable full-display output. Called once at CLI startup
48/// from the global flag.
49pub fn set_full_display(enabled: bool) {
50    FULL_DISPLAY.store(enabled, Ordering::Relaxed);
51}
52
53/// Current full-display mode. List commands check this to choose
54/// between table and full-form output.
55pub fn is_full_display() -> bool {
56    FULL_DISPLAY.load(Ordering::Relaxed)
57}
58
59/// Emit a list entry as aligned `label: value` lines. Used in
60/// full-display mode where ratatui-Table truncation would hide full
61/// identifiers.
62///
63/// `pairs` is `[(label, value)]`. Labels are padded to the widest so
64/// values line up vertically. A trailing blank line separates entries.
65pub fn print_full_entry(pairs: &[(&str, &str)]) {
66    let widest = pairs.iter().map(|(l, _)| l.len()).max().unwrap_or(0);
67    for (label, value) in pairs {
68        let pad = " ".repeat(widest.saturating_sub(label.len()));
69        println!("  {label}:{pad}  {DIM}{value}{RESET}");
70    }
71    println!();
72}
73
74/// Print a bold section heading used above a list of full-display
75/// entries. Matches the title style of the table-mode block borders.
76pub fn print_full_list_title(title: &str, count: usize) {
77    println!();
78    println!("{BOLD}{title} ({count}){RESET}");
79    println!();
80}
81
82// ── Output format ───────────────────────────────────────────────────
83//
84// Global `--json` flag. When enabled, list commands emit a single JSON
85// document instead of the ratatui table / full-display rendering. This
86// is the automation entry point — scripts piping `pnm acl list --json`
87// into `jq` get a stable shape, while interactive operators get the
88// human-readable default.
89
90/// Output format selected by the operator.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum OutputFormat {
93    Human,
94    Json,
95}
96
97static OUTPUT_FORMAT: AtomicU8 = AtomicU8::new(0); // 0 = Human, 1 = Json
98
99/// Register the output format. Called once at CLI startup from the
100/// global `--json` flag.
101pub fn set_output_format(format: OutputFormat) {
102    OUTPUT_FORMAT.store(
103        match format {
104            OutputFormat::Human => 0,
105            OutputFormat::Json => 1,
106        },
107        Ordering::Relaxed,
108    );
109}
110
111/// Current output format. Default `Human`.
112pub fn output_format() -> OutputFormat {
113    if OUTPUT_FORMAT.load(Ordering::Relaxed) == 1 {
114        OutputFormat::Json
115    } else {
116        OutputFormat::Human
117    }
118}
119
120/// Returns true when the operator passed `--json`. List commands check
121/// this and dispatch to a JSON serializer instead of their human-
122/// readable renderer.
123#[must_use]
124pub fn is_json_output() -> bool {
125    output_format() == OutputFormat::Json
126}
127
128/// Pretty-print a serializable value as JSON to stdout. Used by list
129/// commands when [`is_json_output`] is true. Errors here are surfaced
130/// as a CLI error rather than a panic so the caller can render via
131/// `print_cli_error`.
132pub fn print_json<T: serde::Serialize>(value: &T) -> Result<(), serde_json::Error> {
133    let text = serde_json::to_string_pretty(value)?;
134    println!("{text}");
135    Ok(())
136}
137
138// ── ANSI constants ──────────────────────────────────────────────────
139
140pub const BOLD: &str = "\x1b[1m";
141pub const DIM: &str = "\x1b[2m";
142pub const GREEN: &str = "\x1b[32m";
143pub const RED: &str = "\x1b[31m";
144pub const CYAN: &str = "\x1b[36m";
145pub const YELLOW: &str = "\x1b[33m";
146pub const RESET: &str = "\x1b[0m";
147
148// ── Error reporting ─────────────────────────────────────────────────
149
150/// Print a CLI error to stderr in a form an operator can act on.
151///
152/// Downcasts to [`vta_sdk::error::VtaError`] when possible and emits a
153/// tailored remediation hint for the common failure modes (auth, network,
154/// forbidden, validation). Falls back to the raw error message + source
155/// chain for anything else, so unknown failures still get their underlying
156/// cause surfaced.
157///
158/// Call this from the top-level CLI match instead of `eprintln!("Error:
159/// {e}")` — the raw form loses auth/network context that operators need
160/// to fix things themselves.
161pub fn print_cli_error(err: &(dyn std::error::Error + 'static)) {
162    use vta_sdk::error::VtaError;
163    if let Some(vta_err) = err.downcast_ref::<VtaError>() {
164        match vta_err {
165            VtaError::Auth(msg) => {
166                eprintln!("{RED}\u{2717}{RESET} Authentication failed: {msg}");
167                eprintln!(
168                    "  {DIM}Token may be expired. Try `pnm setup` to re-authenticate, or check \
169                     that the VTA's `/auth` endpoint is reachable.{RESET}"
170                );
171            }
172            VtaError::Forbidden(msg) => {
173                eprintln!("{RED}\u{2717}{RESET} Forbidden: {msg}");
174                eprintln!(
175                    "  {DIM}Your role or context access doesn't permit this operation. \
176                     Inspect with `pnm acl get <your-did>`.{RESET}"
177                );
178            }
179            VtaError::NotFound(msg) => {
180                eprintln!("{RED}\u{2717}{RESET} Not found: {msg}");
181            }
182            VtaError::Conflict(msg) => {
183                eprintln!("{RED}\u{2717}{RESET} Conflict: {msg}");
184            }
185            VtaError::Gone(msg) => {
186                let bin = bin_name();
187                eprintln!("{RED}\u{2717}{RESET} Resource is gone: {msg}");
188                eprintln!(
189                    "  {DIM}This usually means the bootstrap carve-out has already been used. \
190                     For a second admin, run `{bin} bootstrap provision-request` from the new \
191                     operator's host and have an existing admin run \
192                     `{bin} bootstrap provision-integration` against this VTA.{RESET}"
193                );
194            }
195            VtaError::Validation(msg) => {
196                eprintln!("{RED}\u{2717}{RESET} Invalid request: {msg}");
197            }
198            VtaError::Network(e) => {
199                eprintln!("{RED}\u{2717}{RESET} Network error: {e}");
200                eprintln!("  {DIM}Is the VTA reachable? Check its URL with `pnm vta info`.{RESET}");
201            }
202            VtaError::Server { status, body } => {
203                eprintln!("{RED}\u{2717}{RESET} Server error (HTTP {status}): {body}");
204                eprintln!(
205                    "  {DIM}This is a VTA-side failure. Check server logs or contact the operator.{RESET}"
206                );
207            }
208            VtaError::UnsupportedTransport(msg) => {
209                eprintln!("{RED}\u{2717}{RESET} Unsupported transport: {msg}");
210                eprintln!(
211                    "  {DIM}This operation requires a specific transport (REST or DIDComm). \
212                     Check which mode your CLI is in and whether the endpoint supports it.{RESET}"
213                );
214            }
215            VtaError::DidcommTransport(msg) => {
216                eprintln!("{RED}\u{2717}{RESET} DIDComm transport error: {msg}");
217                eprintln!(
218                    "  {DIM}Mediator or peer unreachable. Retry after checking mediator \
219                     connectivity.{RESET}"
220                );
221            }
222            VtaError::DidcommRemote { code, comment } => {
223                eprintln!("{RED}\u{2717}{RESET} Remote error ({code}): {comment}");
224            }
225            VtaError::Protocol(msg) => {
226                eprintln!("{RED}\u{2717}{RESET} Protocol error: {msg}");
227            }
228            other => eprintln!("{RED}\u{2717}{RESET} Error: {other}"),
229        }
230        return;
231    }
232    eprintln!("{RED}\u{2717}{RESET} Error: {err}");
233    let mut source = err.source();
234    while let Some(s) = source {
235        eprintln!("  {DIM}caused by: {s}{RESET}");
236        source = s.source();
237    }
238}
239
240// ── Ratatui rendering helpers ───────────────────────────────────────
241
242pub fn print_widget(widget: impl Widget, height: u16) {
243    let width = ratatui::crossterm::terminal::size().map_or(120, |(w, _)| w);
244    let area = Rect::new(0, 0, width, height);
245    let mut buf = Buffer::empty(area);
246    widget.render(area, &mut buf);
247
248    let mut out = String::new();
249    for y in 0..height {
250        let mut cur_fg = Color::Reset;
251        let mut cur_bg = Color::Reset;
252        let mut cur_mod = Modifier::empty();
253
254        for x in 0..width {
255            let cell = &buf[(x, y)];
256            if cell.skip {
257                continue;
258            }
259
260            if cell.fg != cur_fg || cell.bg != cur_bg || cell.modifier != cur_mod {
261                out.push_str("\x1b[0m");
262                push_ansi_fg(&mut out, cell.fg);
263                push_ansi_bg(&mut out, cell.bg);
264                push_ansi_mod(&mut out, cell.modifier);
265                cur_fg = cell.fg;
266                cur_bg = cell.bg;
267                cur_mod = cell.modifier;
268            }
269
270            out.push_str(cell.symbol());
271        }
272        out.push_str("\x1b[0m\n");
273    }
274
275    print!("{out}");
276}
277
278pub fn push_ansi_fg(out: &mut String, color: Color) {
279    use std::fmt::Write as _;
280    match color {
281        Color::Reset => {}
282        Color::Black => out.push_str("\x1b[30m"),
283        Color::Red => out.push_str("\x1b[31m"),
284        Color::Green => out.push_str("\x1b[32m"),
285        Color::Yellow => out.push_str("\x1b[33m"),
286        Color::Blue => out.push_str("\x1b[34m"),
287        Color::Magenta => out.push_str("\x1b[35m"),
288        Color::Cyan => out.push_str("\x1b[36m"),
289        Color::Gray => out.push_str("\x1b[37m"),
290        Color::DarkGray => out.push_str("\x1b[90m"),
291        Color::LightRed => out.push_str("\x1b[91m"),
292        Color::LightGreen => out.push_str("\x1b[92m"),
293        Color::LightYellow => out.push_str("\x1b[93m"),
294        Color::LightBlue => out.push_str("\x1b[94m"),
295        Color::LightMagenta => out.push_str("\x1b[95m"),
296        Color::LightCyan => out.push_str("\x1b[96m"),
297        Color::White => out.push_str("\x1b[97m"),
298        Color::Rgb(r, g, b) => {
299            let _ = write!(out, "\x1b[38;2;{r};{g};{b}m");
300        }
301        Color::Indexed(i) => {
302            let _ = write!(out, "\x1b[38;5;{i}m");
303        }
304    }
305}
306
307pub fn push_ansi_bg(out: &mut String, color: Color) {
308    use std::fmt::Write as _;
309    match color {
310        Color::Reset => {}
311        Color::Black => out.push_str("\x1b[40m"),
312        Color::Red => out.push_str("\x1b[41m"),
313        Color::Green => out.push_str("\x1b[42m"),
314        Color::Yellow => out.push_str("\x1b[43m"),
315        Color::Blue => out.push_str("\x1b[44m"),
316        Color::Magenta => out.push_str("\x1b[45m"),
317        Color::Cyan => out.push_str("\x1b[46m"),
318        Color::Gray => out.push_str("\x1b[47m"),
319        Color::DarkGray => out.push_str("\x1b[100m"),
320        Color::LightRed => out.push_str("\x1b[101m"),
321        Color::LightGreen => out.push_str("\x1b[102m"),
322        Color::LightYellow => out.push_str("\x1b[103m"),
323        Color::LightBlue => out.push_str("\x1b[104m"),
324        Color::LightMagenta => out.push_str("\x1b[105m"),
325        Color::LightCyan => out.push_str("\x1b[106m"),
326        Color::White => out.push_str("\x1b[107m"),
327        Color::Rgb(r, g, b) => {
328            let _ = write!(out, "\x1b[48;2;{r};{g};{b}m");
329        }
330        Color::Indexed(i) => {
331            let _ = write!(out, "\x1b[48;5;{i}m");
332        }
333    }
334}
335
336pub fn push_ansi_mod(out: &mut String, modifier: Modifier) {
337    if modifier.contains(Modifier::BOLD) {
338        out.push_str("\x1b[1m");
339    }
340    if modifier.contains(Modifier::DIM) {
341        out.push_str("\x1b[2m");
342    }
343    if modifier.contains(Modifier::ITALIC) {
344        out.push_str("\x1b[3m");
345    }
346    if modifier.contains(Modifier::UNDERLINED) {
347        out.push_str("\x1b[4m");
348    }
349    if modifier.contains(Modifier::REVERSED) {
350        out.push_str("\x1b[7m");
351    }
352    if modifier.contains(Modifier::CROSSED_OUT) {
353        out.push_str("\x1b[9m");
354    }
355}
356
357pub fn print_section(title: &str) {
358    let pad = 46usize.saturating_sub(title.len());
359    println!(
360        "\n{DIM}──{RESET} {BOLD}{title}{RESET} {DIM}{}{RESET}",
361        "─".repeat(pad)
362    );
363}