Skip to main content

turul_ai_catalog_tui/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4use std::fmt;
5use std::io::{self, IsTerminal};
6
7use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
8use ratatui::Frame;
9use ratatui::layout::{Constraint, Layout};
10use ratatui::style::{Color, Modifier, Style};
11use ratatui::text::{Line, Span};
12use ratatui::widgets::{Block, Paragraph, Wrap};
13use turul_ai_catalog::canonical::CanonicalError;
14use turul_ai_catalog::json::{self, Json};
15use turul_ai_catalog::model::ArtifactSource;
16use turul_ai_catalog_client::{Child, DisplayText, EntryRow, ResolvedCatalog, SkipReason};
17
18const DETAIL_HEIGHT: u16 = 12;
19/// A string longer than this many characters is shortened in the formatted artifact view.
20const LONG_STRING: usize = 120;
21/// How many leading characters of a shortened string stay visible.
22const KEPT: usize = 60;
23
24/// What the session does after a key press.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum Action {
28    /// Keep the session running.
29    Continue,
30    /// End the session.
31    Quit,
32    /// Open the selected entry's artifact: the session retrieves it and passes the result to
33    /// [`ViewState::show`].
34    Open,
35}
36
37/// How an opened artifact's bytes compare with its entry's `digest`.
38#[derive(Clone, Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum Integrity {
41    /// The bytes hash to the entry's digest.
42    Matches,
43    /// The bytes were not compared; carries why (for example, the entry has no digest).
44    Unchecked(String),
45    /// The comparison failed; carries why (for example, a digest mismatch).
46    Failed(String),
47}
48
49/// What the entry's trust manifests came to when the artifact was opened.
50#[derive(Clone, Debug, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum Signature {
53    /// The entry has no trust manifest.
54    Unsigned,
55    /// An accepted signature covers the entry release: its identifier, type, version and digest.
56    Endorsed {
57        /// The signer's DID.
58        signer: String,
59        /// Whether the signer is the entry's `urn:air` publisher.
60        publisher: bool,
61    },
62    /// No signature can be relied on; carries why.
63    NotRelied(String),
64}
65
66/// The result of opening an entry's artifact.
67#[derive(Clone, Debug, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum Opened {
70    /// The artifact bytes and how they compare with the entry's digest.
71    Artifact {
72        /// The bytes as retrieved.
73        body: Vec<u8>,
74        /// The digest comparison.
75        integrity: Integrity,
76        /// What the entry's trust manifests came to.
77        signature: Signature,
78    },
79    /// The artifact could not be retrieved; carries why.
80    Failed(String),
81}
82
83/// Holds the selection over every entry row of the tree, in the order [`render`] draws them,
84/// and the artifact shown in place of the list, if any.
85#[derive(Clone, Debug, Default)]
86pub struct ViewState {
87    selected: usize,
88    opened: Option<Shown>,
89}
90
91/// An artifact shown in place of the list: how far it is scrolled, and whether its exact text
92/// or its formatted JSON is drawn.
93#[derive(Clone, Debug)]
94struct Shown {
95    opened: Opened,
96    scroll: u16,
97    raw: bool,
98}
99
100impl ViewState {
101    /// Creates a state with the first entry selected.
102    pub fn new() -> Self {
103        Self::default()
104    }
105
106    /// Applies a key press and returns what the session does next.
107    ///
108    /// In the list, Up/Down and `k`/`j` move the selection within bounds, Enter gives
109    /// [`Action::Open`] when there is an entry, and `q`, Esc and Ctrl-C quit. While an artifact is
110    /// shown, Up/Down and `k`/`j` scroll it, Esc returns to the list, and `q` and Ctrl-C quit.
111    /// Every other key changes nothing.
112    pub fn on_key(&mut self, key: KeyEvent, catalog: &ResolvedCatalog) -> Action {
113        if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
114            return Action::Quit;
115        }
116        if let Some(shown) = &mut self.opened {
117            match key.code {
118                KeyCode::Char('q') => return Action::Quit,
119                KeyCode::Esc => self.opened = None,
120                KeyCode::Char('r') => {
121                    shown.raw = !shown.raw;
122                    shown.scroll = 0;
123                }
124                KeyCode::Up | KeyCode::Char('k') => shown.scroll = shown.scroll.saturating_sub(1),
125                KeyCode::Down | KeyCode::Char('j') => {
126                    let lines = body_lines(&shown.opened, shown.raw).len();
127                    let last = u16::try_from(lines.saturating_sub(1)).unwrap_or(u16::MAX);
128                    shown.scroll = (shown.scroll + 1).min(last);
129                }
130                _ => {}
131            }
132            return Action::Continue;
133        }
134        match key.code {
135            KeyCode::Enter if count_rows(catalog) > 0 => Action::Open,
136            KeyCode::Char('q') | KeyCode::Esc => Action::Quit,
137            KeyCode::Up | KeyCode::Char('k') => {
138                self.selected = self.selected.saturating_sub(1);
139                Action::Continue
140            }
141            KeyCode::Down | KeyCode::Char('j') => {
142                let last = count_rows(catalog).saturating_sub(1);
143                self.selected = (self.selected + 1).min(last);
144                Action::Continue
145            }
146            _ => Action::Continue,
147        }
148    }
149
150    /// Returns the selected entry row and the catalog node that holds it.
151    pub fn selected<'a>(
152        &self,
153        catalog: &'a ResolvedCatalog,
154    ) -> Option<(&'a ResolvedCatalog, &'a EntryRow)> {
155        nth_row(catalog, &mut self.selected.clone())
156    }
157
158    /// Shows `opened` in place of the list, scrolled to its top and formatted, until Esc.
159    pub fn show(&mut self, opened: Opened) {
160        self.opened = Some(Shown {
161            opened,
162            scroll: 0,
163            raw: false,
164        });
165    }
166}
167
168fn nth_row<'a>(
169    node: &'a ResolvedCatalog,
170    n: &mut usize,
171) -> Option<(&'a ResolvedCatalog, &'a EntryRow)> {
172    if let Some(row) = node.rows.get(*n) {
173        return Some((node, row));
174    }
175    *n -= node.rows.len();
176    node.children.iter().find_map(|nested| match &nested.child {
177        Child::Catalog(c) => nth_row(c, n),
178        _ => None,
179    })
180}
181
182/// The artifact body as display lines. Formatted (the default): a JSON body is drawn indented,
183/// one member or element per line, with strings longer than `LONG_STRING` characters shortened
184/// and their length named. Raw, or a body that is not JSON: its UTF-8 text (invalid sequences as
185/// U+FFFD), split at line breaks. Every document-derived string goes through `DisplayText`.
186fn body_lines(opened: &Opened, raw: bool) -> Vec<Line<'static>> {
187    let Opened::Artifact { body, .. } = opened else {
188        return Vec::new();
189    };
190    if !raw && let Ok(value) = json::read(body) {
191        let mut out = Vec::new();
192        formatted(&value, 0, Vec::new(), false, &mut out);
193        return out;
194    }
195    String::from_utf8_lossy(body)
196        .lines()
197        .map(|l| Line::raw(shown(l)))
198        .collect()
199}
200
201fn key_style() -> Style {
202    Style::new().fg(Color::Cyan)
203}
204
205fn quoted(text: &str) -> String {
206    shown(&format!(
207        "\"{}\"",
208        text.replace('\\', "\\\\").replace('"', "\\\"")
209    ))
210}
211
212fn scalar(value: &Json) -> Vec<Span<'static>> {
213    match value {
214        Json::String(text) => {
215            let count = text.chars().count();
216            if count > LONG_STRING {
217                let kept: String = text.chars().take(KEPT).collect();
218                vec![
219                    Span::styled(quoted(&format!("{kept}…")), Style::new().fg(Color::Green)),
220                    Span::styled(
221                        format!(" ({count} characters; r shows all)"),
222                        Style::new().add_modifier(Modifier::DIM),
223                    ),
224                ]
225            } else {
226                vec![Span::styled(quoted(text), Style::new().fg(Color::Green))]
227            }
228        }
229        Json::Number(n) => vec![Span::styled(
230            shown(n.as_str()),
231            Style::new().fg(Color::Yellow),
232        )],
233        Json::Bool(b) => vec![Span::styled(b.to_string(), Style::new().fg(Color::Magenta))],
234        Json::Null => vec![Span::styled("null", Style::new().fg(Color::Magenta))],
235        Json::Array(_) | Json::Object(_) => Vec::new(),
236    }
237}
238
239/// Appends `value` as indented lines: `prefix` (a member name) leads its first line, and a comma
240/// follows its last when `comma`.
241fn formatted(
242    value: &Json,
243    depth: usize,
244    prefix: Vec<Span<'static>>,
245    comma: bool,
246    out: &mut Vec<Line<'static>>,
247) {
248    let pad = Span::raw("  ".repeat(depth));
249    let tail = if comma { "," } else { "" };
250    let line = |mut spans: Vec<Span<'static>>, end: String| {
251        let mut all = vec![pad.clone()];
252        all.append(&mut prefix.clone());
253        all.append(&mut spans);
254        all.push(Span::raw(end));
255        Line::from(all)
256    };
257    match value {
258        Json::Array(items) if !items.is_empty() => {
259            out.push(line(Vec::new(), "[".into()));
260            for (i, item) in items.iter().enumerate() {
261                formatted(item, depth + 1, Vec::new(), i + 1 < items.len(), out);
262            }
263            out.push(Line::from(vec![pad.clone(), Span::raw(format!("]{tail}"))]));
264        }
265        Json::Object(members) if !members.is_empty() => {
266            out.push(line(Vec::new(), "{".into()));
267            let last = members.len();
268            for (i, (name, member)) in members.iter().enumerate() {
269                let key = vec![Span::styled(quoted(name), key_style()), Span::raw(": ")];
270                formatted(member, depth + 1, key, i + 1 < last, out);
271            }
272            out.push(Line::from(vec![
273                pad.clone(),
274                Span::raw(format!("}}{tail}")),
275            ]));
276        }
277        Json::Array(_) => out.push(line(Vec::new(), format!("[]{tail}"))),
278        Json::Object(_) => out.push(line(Vec::new(), format!("{{}}{tail}"))),
279        _ => out.push(line(scalar(value), tail.to_string())),
280    }
281}
282
283fn artifact_header(
284    selected: Option<(&ResolvedCatalog, &EntryRow)>,
285    opened: &Opened,
286) -> Vec<Line<'static>> {
287    let mut lines = Vec::new();
288    if let Some((node, row)) = selected {
289        let entry = &node.document.entries[row.index];
290        lines.push(Line::raw(format!(
291            "identifier: {}",
292            shown(entry.identifier.as_str())
293        )));
294        if let ArtifactSource::Url(u) = &entry.source {
295            lines.push(Line::raw(format!("url: {}", shown(u))));
296        }
297    }
298    let bold = Style::new().add_modifier(Modifier::BOLD);
299    let Opened::Artifact {
300        integrity,
301        signature,
302        ..
303    } = opened
304    else {
305        if let Opened::Failed(why) = opened {
306            lines.push(Line::styled(format!("not opened: {}", shown(why)), bold));
307        }
308        return lines;
309    };
310    // A signature is relied on only for the bytes shown: they must match the digest it covers.
311    let endorsed = match (integrity, signature) {
312        (Integrity::Matches, Signature::Endorsed { signer, publisher }) => {
313            Some((signer, *publisher))
314        }
315        _ => None,
316    };
317    lines.push(Line::styled(
318        match integrity {
319            Integrity::Matches if endorsed.is_some() => "digest matches".to_string(),
320            Integrity::Matches => "digest matches (source not authenticated)".to_string(),
321            Integrity::Unchecked(why) => format!("digest not checked: {}", shown(why)),
322            Integrity::Failed(why) => format!("digest check failed: {}", shown(why)),
323        },
324        bold,
325    ));
326    lines.push(Line::styled(
327        match (endorsed, signature) {
328            (Some((signer, true)), _) => {
329                format!("signed by {}, the entry's publisher", shown(signer))
330            }
331            (Some((signer, false)), _) => {
332                format!("signed by {}, not the entry's publisher", shown(signer))
333            }
334            (None, Signature::Endorsed { .. }) => {
335                "signature not relied on: the artifact shown does not match the digest".to_string()
336            }
337            (None, Signature::NotRelied(why)) => {
338                format!("signature not relied on: {}", shown(why))
339            }
340            (None, _) => "not signed".to_string(),
341        },
342        bold,
343    ));
344    lines
345}
346
347fn count_rows(node: &ResolvedCatalog) -> usize {
348    node.rows.len()
349        + node
350            .children
351            .iter()
352            .map(|n| match &n.child {
353                Child::Catalog(c) => count_rows(c),
354                _ => 0,
355            })
356            .sum::<usize>()
357}
358
359struct Drawn<'a> {
360    lines: Vec<Line<'a>>,
361    selected_line: usize,
362    detail: Option<(&'a ResolvedCatalog, &'a EntryRow)>,
363    next_row: usize,
364}
365
366fn skip_label(reason: &SkipReason) -> &'static str {
367    match reason {
368        SkipReason::Budget => "budget",
369        SkipReason::Depth => "depth",
370        SkipReason::Cycle => "cycle",
371        SkipReason::Unresolvable => "unresolvable",
372        SkipReason::Fetch(_) => "fetch",
373        _ => "other",
374    }
375}
376
377fn shown(text: &str) -> String {
378    DisplayText::new(text).to_string()
379}
380
381fn draw_node<'a>(node: &'a ResolvedCatalog, depth: usize, selected: usize, out: &mut Drawn<'a>) {
382    let pad = "  ".repeat(depth);
383    let source = node.base.as_deref().map_or("file".to_string(), shown);
384    let host = node.document.host.as_ref().map_or(String::new(), |h| {
385        format!("  host: {}", shown(&h.display_name))
386    });
387    out.lines.push(Line::styled(
388        format!(
389            "{pad}catalog {source}{host}  conformance: {:?}",
390            node.report.conformance()
391        ),
392        Style::new().add_modifier(Modifier::BOLD),
393    ));
394    for row in &node.rows {
395        let version = row
396            .version
397            .as_deref()
398            .map_or(String::new(), |v| format!("  {}", shown(v)));
399        let is_selected = out.next_row == selected;
400        let marker = if is_selected { ">" } else { " " };
401        let style = if is_selected {
402            out.selected_line = out.lines.len();
403            out.detail = Some((node, row));
404            Style::new().add_modifier(Modifier::REVERSED)
405        } else {
406            Style::new()
407        };
408        out.lines.push(Line::styled(
409            format!("{pad}{marker} {}{version}", shown(&row.name)),
410            style,
411        ));
412        out.next_row += 1;
413    }
414    for nested in &node.children {
415        if let Child::Skipped { url, reason } = &nested.child {
416            let cause = match reason {
417                SkipReason::Fetch(e) => format!(": {}", shown(&e.to_string())),
418                _ => String::new(),
419            };
420            out.lines.push(Line::raw(format!(
421                "{pad}  skipped {} {}{cause}",
422                skip_label(reason),
423                shown(url)
424            )));
425        }
426    }
427    for w in &node.warnings {
428        out.lines.push(Line::raw(format!(
429            "{pad}  warning {}: {}",
430            w.code(),
431            shown(&w.to_string())
432        )));
433    }
434    for d in node.report.diagnostics() {
435        out.lines.push(Line::raw(format!(
436            "{pad}  {} {} {}",
437            format!("{:?}", d.severity).to_lowercase(),
438            d.code,
439            shown(&d.path.to_string())
440        )));
441    }
442    for nested in &node.children {
443        if let Child::Catalog(c) = &nested.child {
444            draw_node(c, depth + 1, selected, out);
445        }
446    }
447}
448
449fn detail_lines(node: &ResolvedCatalog, row: &EntryRow) -> Vec<Line<'static>> {
450    let entry = &node.document.entries[row.index];
451    let none = || "-".to_string();
452    let mut lines = vec![
453        Line::raw(format!("identifier: {}", shown(entry.identifier.as_str()))),
454        Line::raw(format!("type: {}", shown(entry.artifact_type.as_str()))),
455        Line::raw(format!(
456            "version: {}",
457            row.version.as_deref().map_or_else(none, shown)
458        )),
459        Line::raw(format!("display name: {}", shown(&row.name))),
460        Line::raw(format!(
461            "description: {}",
462            row.description.as_deref().map_or_else(none, shown)
463        )),
464    ];
465    lines.push(match &entry.source {
466        ArtifactSource::Url(u) => Line::raw(format!("url: {}", shown(u))),
467        ArtifactSource::Data(j) => match j.to_canonical_vec() {
468            Ok(bytes) => Line::raw(format!("data: {}", shown(&String::from_utf8_lossy(&bytes)))),
469            Err(CanonicalError::NotIJson { pointer }) => Line::raw(format!(
470                "data not shown: not I-JSON at {}",
471                shown(&pointer.to_string())
472            )),
473            Err(e) => Line::raw(format!("data not shown: {}", shown(&e.to_string()))),
474        },
475    });
476    lines.push(Line::raw(format!(
477        "trust manifests (not verified): {}",
478        entry.trust_manifests.as_ref().map_or(0, Vec::len)
479    )));
480    lines
481}
482
483/// Draws the whole tree and the selected entry's detail into `frame`, or, while an artifact is
484/// shown, that artifact: the entry's identifier and `url`, how it compares with the digest, and
485/// its text.
486///
487/// Reads only its arguments: the same catalog and state always draw the same buffer.
488pub fn render(catalog: &ResolvedCatalog, state: &ViewState, frame: &mut Frame) {
489    if let Some(view) = &state.opened {
490        // The header lines stay; the scroll moves the body.
491        let header = artifact_header(state.selected(catalog), &view.opened);
492        let [head_area, body_area] = Layout::vertical([
493            Constraint::Length(u16::try_from(header.len()).unwrap_or(u16::MAX)),
494            Constraint::Min(1),
495        ])
496        .areas(frame.area());
497        let title = if view.raw {
498            "artifact, exact text (Esc: back, r: formatted)"
499        } else {
500            "artifact (Esc: back, r: exact text)"
501        };
502        frame.render_widget(Paragraph::new(header), head_area);
503        frame.render_widget(
504            Paragraph::new(body_lines(&view.opened, view.raw))
505                .wrap(Wrap { trim: false })
506                .scroll((view.scroll, 0))
507                .block(Block::bordered().title(title)),
508            body_area,
509        );
510        return;
511    }
512    let mut out = Drawn {
513        lines: Vec::new(),
514        selected_line: 0,
515        detail: None,
516        next_row: 0,
517    };
518    draw_node(catalog, 0, state.selected, &mut out);
519
520    let [list_area, detail_area] =
521        Layout::vertical([Constraint::Min(3), Constraint::Length(DETAIL_HEIGHT)])
522            .areas(frame.area());
523    let height = usize::from(list_area.height);
524    let scroll = (out.selected_line + 1).saturating_sub(height);
525    let scroll = u16::try_from(scroll).unwrap_or(u16::MAX);
526    frame.render_widget(Paragraph::new(out.lines).scroll((scroll, 0)), list_area);
527
528    let detail = out
529        .detail
530        .map_or_else(Vec::new, |(node, row)| detail_lines(node, row));
531    frame.render_widget(
532        Paragraph::new(detail).block(Block::bordered().title("entry")),
533        detail_area,
534    );
535}
536
537/// Describes why a terminal session did not run or failed.
538#[derive(Debug)]
539#[non_exhaustive]
540pub enum RunError {
541    /// Stdin or stdout is not a terminal.
542    NotATerminal,
543    /// Reading events or drawing to the terminal failed.
544    Io(io::Error),
545}
546
547impl fmt::Display for RunError {
548    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549        match self {
550            RunError::NotATerminal => f.write_str("stdin and stdout must both be terminals"),
551            RunError::Io(_) => f.write_str("terminal error"),
552        }
553    }
554}
555
556impl std::error::Error for RunError {
557    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
558        match self {
559            RunError::Io(e) => Some(e),
560            RunError::NotATerminal => None,
561        }
562    }
563}
564
565impl From<io::Error> for RunError {
566    fn from(e: io::Error) -> Self {
567        RunError::Io(e)
568    }
569}
570
571/// Shows the catalog until a quit key, then restores the terminal. On Enter, `open` retrieves
572/// the selected entry's artifact and its result is shown until Esc.
573///
574/// # Errors
575///
576/// Returns [`RunError::NotATerminal`], before touching the terminal, unless stdin and stdout are
577/// both terminals. Returns [`RunError::Io`] if reading events or drawing fails.
578pub fn run(
579    catalog: ResolvedCatalog,
580    open: impl FnMut(&ResolvedCatalog, &EntryRow) -> Opened,
581) -> Result<(), RunError> {
582    if !io::stdin().is_terminal() || !io::stdout().is_terminal() {
583        return Err(RunError::NotATerminal);
584    }
585    let mut terminal = ratatui::init();
586    let result = session(&mut terminal, &catalog, open);
587    ratatui::restore();
588    result
589}
590
591fn session(
592    terminal: &mut ratatui::DefaultTerminal,
593    catalog: &ResolvedCatalog,
594    mut open: impl FnMut(&ResolvedCatalog, &EntryRow) -> Opened,
595) -> Result<(), RunError> {
596    let mut state = ViewState::new();
597    loop {
598        terminal.draw(|f| render(catalog, &state, f))?;
599        if let Event::Key(key) = crossterm::event::read()?
600            && key.kind == KeyEventKind::Press
601        {
602            match state.on_key(key, catalog) {
603                Action::Quit => return Ok(()),
604                Action::Open => {
605                    if let Some((node, row)) = state.selected(catalog) {
606                        state.show(open(node, row));
607                    }
608                }
609                Action::Continue => {}
610            }
611        }
612    }
613}