Skip to main content

mira/tui/
rata.rs

1//! Every screen row in the TUI, drawn by ratatui.
2//!
3//! The seam is `Term::draw`, which takes one ANSI string per
4//! screen row. `Term` keeps the pty, the raw mode, the resize handling and the
5//! key decoding; only content generation lives here. A widget renders into a
6//! [`Buffer`] and [`flatten`] turns that buffer back into the rows `draw`
7//! already paints, so the port cost nothing at the boundary — `term::Row`, the
8//! hand-rolled width-tracking line builder this replaces, is gone rather than
9//! wrapped.
10//!
11//! **No backend is linked.** ratatui's `CrosstermBackend` would bring crossterm,
12//! mio, signal-hook and parking_lot to do what `term.rs` already does, so the
13//! dependency is `ratatui` with `default-features = false`: the widgets and the
14//! layout solver, nothing that touches a terminal. That is most of why the
15//! measured cost is +26 crates rather than the +48 a default build wanted.
16
17use ratatui::buffer::Buffer;
18use ratatui::layout::{Constraint, Layout, Rect};
19use ratatui::style::{Color, Modifier, Style, Stylize};
20use ratatui::text::{Line as TLine, Span};
21use ratatui::widgets::{
22    Cell, Paragraph, Row, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, Table,
23    Widget,
24};
25use yaml_rust2::Yaml;
26
27use super::{clip, dur, hms, i64_of, kind, pairs, service, stamp};
28use crate::term;
29
30/// Render into a fresh `w × h` buffer and flatten it to rows.
31fn paint(w: usize, h: usize, f: impl FnOnce(Rect, &mut Buffer)) -> Vec<String> {
32    let area = Rect::new(0, 0, w as u16, h as u16);
33    let mut buf = Buffer::empty(area);
34    f(area, &mut buf);
35    flatten(&buf, area)
36}
37
38/// One ANSI string per buffer line, coalescing runs that share a style.
39///
40/// Per cell would be correct and unreadable on the wire: a 200-column row would
41/// carry 200 escapes for a line that changes colour twice. `Term::draw` writes
42/// whatever it is handed, so the coalescing has to happen here.
43fn flatten(buf: &Buffer, area: Rect) -> Vec<String> {
44    let mut out = Vec::with_capacity(area.height as usize);
45    for y in area.top()..area.bottom() {
46        let mut line = String::new();
47        let mut open: Option<(Color, Modifier)> = None;
48        for x in area.left()..area.right() {
49            let Some(c) = buf.cell((x, y)) else { continue };
50            let key = (c.fg, c.modifier);
51            if open != Some(key) {
52                line.push_str(term::RESET);
53                line.push_str(&sgr(c.fg, c.modifier));
54                open = Some(key);
55            }
56            line.push_str(c.symbol());
57        }
58        line.push_str(term::RESET);
59        out.push(line);
60    }
61    out
62}
63
64/// The SGR run for one cell's style, in the escapes `term` already declares.
65///
66/// Only the palette Mira uses is mapped, and background colour is not part of
67/// it — the one thing drawn on a coloured field is the selection, and that is
68/// reverse video so it inherits whatever the terminal's own scheme is. A
69/// migration that invented a 256-colour theme on the way past would be changing
70/// the program rather than porting it.
71fn sgr(fg: Color, m: Modifier) -> String {
72    let mut s = String::new();
73    if m.contains(Modifier::BOLD) {
74        s.push_str(term::BOLD);
75    }
76    if m.contains(Modifier::DIM) {
77        s.push_str(term::DIM);
78    }
79    if m.contains(Modifier::REVERSED) {
80        s.push_str(term::REV);
81    }
82    s.push_str(match fg {
83        Color::Red => term::RED,
84        Color::Green => term::GREEN,
85        Color::Yellow => term::YELLOW,
86        Color::Blue => term::BLUE,
87        Color::Magenta => term::MAGENTA,
88        Color::Cyan => term::CYAN,
89        _ => "",
90    });
91    s
92}
93
94/// The style a severity is drawn in: the OTLP number bands, not a guess at
95/// `severity_text`, which is free-form and frequently absent.
96pub fn sev(n: i64) -> Style {
97    match n {
98        17.. => Style::default().fg(Color::Red),
99        13..=16 => Style::default().fg(Color::Yellow),
100        9..=12 => Style::default().fg(Color::Green),
101        _ => Style::default().add_modifier(Modifier::DIM),
102    }
103}
104
105/// One screen row from spans, clipped and padded to `w`.
106///
107/// The replacement for `term::Row`. Width there was tracked by hand, separately
108/// from the byte length, because inline ANSI makes `len()` a lie — that was the
109/// entire reason the type existed. Here the escapes are applied on the way out
110/// of the buffer, so every truncation and pad is over plain graphemes and
111/// belongs to the library.
112pub fn row(w: usize, spans: Vec<Span<'_>>) -> String {
113    row_styled(w, Style::default(), spans)
114}
115
116/// [`row`], with a style under the whole width rather than under the text.
117///
118/// This is what `Row::fill` was for: a reverse-video row that stops at its last
119/// character reads as a ragged highlight, so the selection has to cover the
120/// padding too. Cell styles merge rather than replace, so a span that sets a
121/// colour keeps it and inherits the reverse.
122pub fn row_styled(w: usize, base: Style, spans: Vec<Span<'_>>) -> String {
123    paint(w, 1, |area, buf| {
124        Paragraph::new(TLine::from(spans))
125            .style(base)
126            .render(area, buf);
127    })
128    .pop()
129    .unwrap_or_default()
130}
131
132/// The style a selected row is drawn in.
133pub fn hl(on: bool) -> Style {
134    match on {
135        true => Style::default().add_modifier(Modifier::REVERSED),
136        false => Style::default(),
137    }
138}
139
140/// One row laid out in fixed columns, each clipped to its own column.
141///
142/// The hand-rolled version did this with a `cap`/`pad_to` pair around every
143/// write, and the reason was worth keeping: an over-long span name has to eat
144/// into its own column rather than push the duration off the right-hand edge.
145/// A `Layout` states the same thing once, in the units the columns are in.
146pub fn columns(w: usize, base: Style, cells: Vec<(u16, Vec<Span<'_>>)>) -> String {
147    paint(w, 1, |area, buf| {
148        buf.set_style(area, base);
149        let widths: Vec<Constraint> = cells.iter().map(|(n, _)| Constraint::Length(*n)).collect();
150        let areas = Layout::horizontal(widths).split(area);
151        for (a, (_, spans)) in areas.iter().zip(cells) {
152            Paragraph::new(TLine::from(spans)).render(*a, buf);
153        }
154    })
155    .pop()
156    .unwrap_or_default()
157}
158
159/// A bar with one group pinned left and one pinned right.
160///
161/// A `Layout` reserves the right group's width before the left group is drawn,
162/// so a narrow terminal clips the left. For every bar here that is the right
163/// way round: the window and the limit say what the filter was applied to, and
164/// losing them to a long filter string is what the hand-rolled `pad_to` did.
165pub fn bar(w: usize, left: Vec<Span<'_>>, right: Vec<Span<'_>>) -> String {
166    let rw = right.iter().map(Span::width).sum::<usize>() as u16;
167    paint(w, 1, |area, buf| {
168        let [l, r] = Layout::horizontal([Constraint::Min(0), Constraint::Length(rw)]).areas(area);
169        Paragraph::new(TLine::from(left)).render(l, buf);
170        Paragraph::new(TLine::from(right)).render(r, buf);
171    })
172    .pop()
173    .unwrap_or_default()
174}
175
176/// A full-width rule with a title set into it.
177pub fn rule(w: usize, title: &str) -> String {
178    let used = 2 + title.chars().count();
179    row(
180        w,
181        vec![
182            "──".dim(),
183            title.to_string().dim(),
184            "─".repeat(w.saturating_sub(used)).dim(),
185        ],
186    )
187}
188
189/// The log list: one `Table` of four columns, with a scrollbar in the gutter.
190///
191/// The gutter is what the hand-rolled list does not have. `window_start` tells
192/// the reader which rows are on screen and nothing tells them where that window
193/// sits in the result — a scrollbar is the answer, and it is four lines here
194/// because `Scrollbar` is a widget rather than something to draw.
195pub fn log_list(rows: &[Yaml], w: usize, h: usize, sel: usize, start: usize) -> Vec<String> {
196    let visible: Vec<Row> = rows
197        .iter()
198        .skip(start)
199        .take(h)
200        .enumerate()
201        .map(|(i, row)| {
202            // Under the selection the per-cell styles are dropped rather than
203            // merged: reverse video over a dim service name renders as a faded
204            // patch in the middle of the highlight.
205            let picked = start + i == sel;
206            let dim = match picked {
207                true => Style::default(),
208                false => Style::default().add_modifier(Modifier::DIM),
209            };
210            let n = row["severity_number"].as_i64().unwrap_or(0);
211            Row::new(vec![
212                Cell::from(format!(" {}", hms(i64_of(&row["time_unix_nano"])))),
213                Cell::from(clip(row["severity_text"].as_str().unwrap_or("-"), 6))
214                    .style(if picked { Style::default() } else { sev(n) }),
215                Cell::from(clip(service(row), 16)).style(dim),
216                Cell::from(row["body"].as_str().unwrap_or("").to_owned()),
217            ])
218            .style(hl(picked))
219        })
220        .collect();
221
222    paint(w, h, |area, buf| {
223        // One column short, so the scrollbar has a gutter to live in.
224        let body = Rect {
225            width: area.width.saturating_sub(1),
226            ..area
227        };
228        let table = Table::new(
229            visible,
230            [
231                Constraint::Length(13),
232                Constraint::Length(6),
233                Constraint::Length(16),
234                Constraint::Min(0),
235            ],
236        )
237        .column_spacing(1);
238        Widget::render(table, body, buf);
239
240        let mut state = ScrollbarState::new(rows.len()).position(sel);
241        Scrollbar::new(ScrollbarOrientation::VerticalRight)
242            .begin_symbol(None)
243            .end_symbol(None)
244            .render(area, buf, &mut state);
245    })
246}
247
248/// One record's fields, its attributes, then its events and links — each
249/// section a two-column `Table` under a rule.
250///
251/// The key column is measured from the data rather than fixed, and measured
252/// across every section so the values line up down the whole pane. That is the
253/// bug this fixes: the hand-rolled version wrote `{k:<26}`, which pads a short
254/// key and does nothing at all to a long one, so `deployment.environment.name`
255/// — 27 characters — rendered as `deployment.environment.nameprod`.
256pub fn detail(row: &Yaml, w: usize) -> Vec<String> {
257    let mut fields: Vec<(String, String, Color)> = Vec::new();
258    for (k, v) in pairs(row) {
259        if matches!(k.as_str(), "attributes" | "events" | "links" | "points") {
260            continue;
261        }
262        let pretty = match k.as_str() {
263            "time_unix_nano" | "observed_time_unix_nano" | "start_time_unix_nano" => {
264                v.parse::<i64>().map(stamp).unwrap_or_else(|_| v.clone())
265            }
266            "duration_nano" => v.parse::<i64>().map(dur).unwrap_or_else(|_| v.clone()),
267            "kind" => v
268                .parse::<i64>()
269                .map(|k| kind(k).to_owned())
270                .unwrap_or_else(|_| v.clone()),
271            _ => v.clone(),
272        };
273        fields.push((k, pretty, Color::Reset));
274    }
275
276    let mut groups = vec![("", fields)];
277    let attrs = pairs(&row["attributes"]);
278    if !attrs.is_empty() {
279        groups.push((
280            " attributes ",
281            attrs
282                .into_iter()
283                .map(|(k, v)| (k, v, Color::Cyan))
284                .collect(),
285        ));
286    }
287    // An event's own attributes are the payload of the event — an exception's
288    // type and stacktrace live nowhere else — and this is the only screen that
289    // ever shows them, so they are indented under it rather than dropped.
290    for (label, key) in [(" events ", "events"), (" links ", "links")] {
291        let items = row[key].as_vec().map_or(&[][..], |v| v.as_slice());
292        if items.is_empty() {
293            continue;
294        }
295        let mut rows = Vec::new();
296        for it in items {
297            for (k, v) in pairs(it) {
298                if k == "attributes" {
299                    continue;
300                }
301                rows.push((k, v, Color::Reset));
302            }
303            for (k, v) in pairs(&it["attributes"]) {
304                rows.push((format!("  {k}"), v, Color::Cyan));
305            }
306        }
307        groups.push((label, rows));
308    }
309
310    // The widest key anywhere in the pane, capped at a third of the screen so
311    // one pathological attribute name cannot squeeze every value off the edge.
312    let keyw = groups
313        .iter()
314        .flat_map(|(_, rows)| rows.iter())
315        .map(|(k, _, _)| k.chars().count())
316        .max()
317        .unwrap_or(0)
318        .min(w / 3) as u16;
319
320    let mut out = Vec::new();
321    for (label, rows) in groups {
322        // Nothing under it is nothing to announce. A metrics row is attributes
323        // and points, both of which are drawn elsewhere, so its field section
324        // is empty — and the rule would be a heading over blank space.
325        if rows.is_empty() {
326            continue;
327        }
328        if !label.is_empty() {
329            out.push(rule(w, label));
330        }
331        let table: Vec<Row> = rows
332            .iter()
333            .map(|(k, v, c)| {
334                Row::new(vec![
335                    Cell::from(k.clone()).style(Style::default().add_modifier(Modifier::DIM)),
336                    Cell::from(v.clone()).style(Style::default().fg(*c)),
337                ])
338            })
339            .collect();
340        out.extend(paint(w, rows.len(), |area, buf| {
341            // Two columns of gutter, as the hand-rolled pane had — a key hard
342            // against the left edge reads as part of the rule above it.
343            let body = Rect {
344                x: 2,
345                width: area.width.saturating_sub(2),
346                ..area
347            };
348            let t =
349                Table::new(table, [Constraint::Length(keyw), Constraint::Min(0)]).column_spacing(2);
350            Widget::render(t, body, buf);
351        }));
352    }
353    out
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359    use crate::tui::tests::strip;
360
361    /// The bug this pane is being ported to fix: a key at or past the old fixed
362    /// 26-column pad ran straight into its value. Measuring the column from the
363    /// data keeps a gap whatever the key is.
364    #[test]
365    fn a_long_attribute_key_does_not_abut_its_value() {
366        let y = yaml_rust2::YamlLoader::load_from_str(
367            "body: hi\nattributes:\n  deployment.environment.name: prod\n",
368        )
369        .unwrap()
370        .remove(0);
371        let out = detail(&y, 100);
372        let line = out
373            .iter()
374            .map(|l| strip(l))
375            .find(|l| l.contains("prod"))
376            .expect("the attribute is rendered");
377        assert!(
378            line.contains("name  prod") || line.contains("name prod"),
379            "key and value must not run together: {line:?}"
380        );
381    }
382
383    /// A section with no rows draws neither the rows nor the rule over them.
384    ///
385    /// Both halves are reachable: a metrics row is `attributes` and `points`,
386    /// so every field is filtered and the first section is empty, and an event
387    /// carrying nothing but an empty attribute map empties a labelled one.
388    #[test]
389    fn an_empty_section_is_not_a_heading_over_nothing() {
390        let y = yaml_rust2::YamlLoader::load_from_str(
391            "attributes:\n  service.name: api\npoints:\n  - 1\nevents:\n  - attributes: {}\n",
392        )
393        .unwrap()
394        .remove(0);
395        let out: Vec<String> = detail(&y, 80).iter().map(|l| strip(l)).collect();
396        assert!(out[0].contains("attributes"), "{out:?}");
397        assert!(out.iter().any(|l| l.contains("api")), "{out:?}");
398        assert!(!out.iter().any(|l| l.contains("events")), "{out:?}");
399    }
400}