Skip to main content

mrk/terminal/
mod.rs

1mod ansi;
2mod color;
3mod crop;
4mod detect;
5mod environment;
6mod kitty;
7pub mod pager;
8mod query;
9mod reply;
10mod sixel;
11mod tmux;
12#[cfg(unix)]
13mod tty;
14
15use std::io::Write;
16
17pub use detect::{Preferences, detect};
18
19use self::ansi::Half;
20use self::crop::Crop;
21use self::sixel::Image;
22use crate::document::{Block, CellSize, Document, JumboTitle, Picture};
23use crate::sanitize;
24use crate::theme::Appearance;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum ColorDepth {
29    None,
30    Ansi256,
31    TrueColor,
32}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct Capabilities {
37    pub color: ColorDepth,
38    pub hyperlinks: bool,
39    /// Set when the terminal draws pictures and pictures are wanted.
40    pub graphics: Option<Graphics>,
41    /// Whether the terminal draws DEC double-height lines.
42    pub double_height: bool,
43    pub background: Option<Appearance>,
44    pub columns: u16,
45    pub rows: u16,
46    pub is_terminal: bool,
47}
48
49/// How the terminal draws pictures; kitty when it speaks both.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum Protocol {
53    Kitty,
54    /// Kitty graphics from inside tmux: passed through it and shown by Unicode placeholder cells.
55    KittyThroughTmux,
56    Sixel,
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct Graphics {
62    pub protocol: Protocol,
63    pub cell: CellSize,
64}
65
66#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
67pub enum ColorChoice {
68    #[default]
69    Auto,
70    Always,
71    Never,
72}
73
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
75pub enum ImagesMode {
76    #[default]
77    Auto,
78    Always,
79    Never,
80}
81
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
83pub enum Align {
84    Left,
85    #[default]
86    Center,
87}
88
89pub const LEFT_MARGIN: usize = 2;
90
91/// Columns left of the text: centred in the window when asked and stdout is a terminal, the fixed margin otherwise.
92pub fn margin(align: Align, capabilities: &Capabilities, width: usize) -> usize {
93    let centred = usize::from(capabilities.columns).saturating_sub(width) / 2;
94    let is_centred = align == Align::Center && capabilities.is_terminal;
95    if is_centred { centred.max(LEFT_MARGIN) } else { LEFT_MARGIN }
96}
97
98/// How this terminal draws a jumbo title: a picture where kitty graphics reach it straight, double-height text where
99/// it draws that, `None` otherwise.
100pub fn jumbo_title(capabilities: &Capabilities) -> Option<JumboTitle> {
101    match capabilities.graphics.map(|graphics| graphics.protocol) {
102        Some(Protocol::Kitty) => Some(JumboTitle::Picture),
103        _ if capabilities.double_height => Some(JumboTitle::DoubleHeight),
104        _ => None,
105    }
106}
107
108/// What stands left of each row of a picture: the margin, then its indent.
109fn picture_indent(picture: &Picture, capabilities: &Capabilities, margin: usize) -> String {
110    format!("{}{}", " ".repeat(margin), ansi::line(&picture.indent, capabilities, 0))
111}
112
113/// What stands in for a picture, after `indent`, when the terminal cannot draw it.
114fn placeholder(picture: &Picture, indent: &str) -> String {
115    format!("{indent}[picture: {}]\n", sanitize::text(&picture.alt))
116}
117
118/// Rows of a picture drawn together, and the part of its PNG behind them; `None` when they are the whole picture.
119struct Run {
120    rows: u16,
121    crop: Option<Crop>,
122}
123
124/// The picture's rows in runs one row shorter than the screen, so the cursor can climb back to a run's first row
125/// once its rows scrolled into view: a single run when the picture fits. `None` when a cut is needed and the PNG
126/// cannot be read.
127fn runs(picture: &Picture, screen_rows: u16) -> Option<Vec<Run>> {
128    let rows = picture.rows.max(1);
129    let longest = screen_rows.saturating_sub(1).max(1);
130    if rows <= longest {
131        return Some(vec![Run { rows, crop: None }]);
132    }
133    let run = |start: u16| {
134        let end = rows.min(start + longest);
135        Some(Run { rows: end - start, crop: Some(Crop::behind(start..end, rows, &picture.png)?) })
136    };
137    (0..rows).step_by(usize::from(longest)).map(run).collect()
138}
139
140/// Run after run, the rows written first, after `indent` on each and the concealed text on the picture's first,
141/// scrolling them into view; then `draw` of the run at its first row, which leaves the cursor where it found it; then
142/// the cursor at the start of the line below. Drawing at the bottom of the screen must not clip the picture.
143fn over_rows(picture: &Picture, indent: &str, screen_rows: u16, draw: impl Fn(&Run) -> String) -> Option<String> {
144    let drawn = |(index, run): (usize, &Run)| {
145        let concealed = if index == 0 { ansi::concealed(picture) } else { String::new() };
146        let rest = format!("{indent}\n").repeat(usize::from(run.rows - 1));
147        format!("{indent}{concealed}\n{rest}\x1b[{0}A\r{indent}{1}\x1b[{0}B\r", run.rows, draw(run))
148    };
149    Some(runs(picture, screen_rows)?.iter().enumerate().map(drawn).collect())
150}
151
152fn picture(picture: &Picture, capabilities: &Capabilities, margin: usize) -> String {
153    let indent = picture_indent(picture, capabilities, margin);
154    let screen_rows = capabilities.rows;
155    let drawn = capabilities.graphics.and_then(|graphics| match graphics.protocol {
156        Protocol::Kitty => over_rows(picture, &indent, screen_rows, |run| kitty::draw(picture, run.rows, run.crop)),
157        Protocol::KittyThroughTmux => kitty::draw_through_tmux(picture, &indent),
158        Protocol::Sixel => {
159            let image = Image::from_png(&picture.png)?;
160            over_rows(picture, &indent, screen_rows, |run| sixel::draw(&image, run.crop.map(Crop::pixel_rows)))
161        }
162    });
163    drawn.unwrap_or_else(|| placeholder(picture, &indent))
164}
165
166/// The block as the strings to write, one per row (a picture is one), so a long block is never held whole as text.
167fn rows<'a>(block: &'a Block, capabilities: &'a Capabilities, margin: usize) -> Box<dyn Iterator<Item = String> + 'a> {
168    match block {
169        Block::Lines(lines) => Box::new(lines.iter().map(move |line| ansi::line(line, capabilities, margin) + "\n")),
170        Block::Picture(each) => Box::new(std::iter::once(picture(each, capabilities, margin))),
171        Block::DoubleHeight(lines) => Box::new(
172            lines.iter().flat_map(move |line| [Half::Top, Half::Bottom].map(|half| ansi::half(line, half, capabilities, margin) + "\n")),
173        ),
174    }
175}
176
177/// Writes the document for this terminal, `margin` columns from the left.
178pub fn write(document: &Document, capabilities: &Capabilities, margin: usize, out: &mut impl Write) -> std::io::Result<()> {
179    document.blocks.iter().flat_map(|each| rows(each, capabilities, margin)).try_for_each(|row| out.write_all(row.as_bytes()))
180}
181
182fn cleaned(message: &dyn std::fmt::Display) -> String {
183    sanitize::lines(message.to_string().trim_end())
184}
185
186fn indented(message: &str, (dim, reset): (&str, &str)) -> String {
187    message.lines().map(|line| format!("  {dim}{line}{reset}\n")).collect()
188}
189
190/// An error and its causes for stderr, sanitized, every line after the first indented, causes dimmed when `is_styled`.
191pub fn error_report(error: &dyn std::error::Error, is_styled: bool) -> String {
192    let dimmed = if is_styled { ("\x1b[2m", "\x1b[0m") } else { ("", "") };
193    let message = cleaned(error);
194    let (first, rest) = message.split_once('\n').unwrap_or((&message, ""));
195    let causes: String =
196        std::iter::successors(error.source(), |cause| cause.source()).map(|cause| indented(&cleaned(cause), dimmed)).collect();
197    format!("✗ {first}\n{}{causes}", indented(rest, ("", "")))
198}
199
200/// The bytes `write` produces, as a string.
201#[cfg(test)]
202pub fn ansi(document: &Document, capabilities: &Capabilities, margin: usize) -> String {
203    document.blocks.iter().flat_map(|each| rows(each, capabilities, margin)).collect()
204}
205
206#[cfg(test)]
207mod tests {
208    #![allow(clippy::unwrap_used)]
209    use super::*;
210
211    #[test]
212    fn centring_splits_the_spare_columns_on_a_terminal_only() {
213        let wide = Capabilities { columns: 200, ..capabilities(ColorDepth::TrueColor, None) };
214        let piped = Capabilities { is_terminal: false, ..wide };
215        let narrow = Capabilities { columns: 82, ..wide };
216
217        assert_eq!(margin(Align::Center, &wide, 100), 50);
218        assert_eq!(margin(Align::Left, &wide, 100), LEFT_MARGIN);
219        assert_eq!(margin(Align::Center, &piped, 100), LEFT_MARGIN);
220        assert_eq!(margin(Align::Center, &narrow, 80), LEFT_MARGIN);
221    }
222
223    #[test]
224    fn an_error_report_strips_escapes_and_dims_causes_only_when_styled() {
225        let error = anyhow::anyhow!("inner \x1b]52;c;AAAA\x07").context("cannot read \x1b[31mfile");
226
227        assert_eq!(error_report(error.as_ref(), false), "✗ cannot read [31mfile\n  inner ]52;c;AAAA\n");
228        assert_eq!(error_report(error.as_ref(), true), "✗ cannot read [31mfile\n  \x1b[2minner ]52;c;AAAA\x1b[0m\n");
229    }
230
231    #[test]
232    fn an_error_report_keeps_every_line_of_a_message_indented() {
233        let error = anyhow::anyhow!("fatal: no remote\r\nhint: add one\n").context("update failed\nfor the tag");
234
235        assert_eq!(
236            error_report(error.as_ref(), true),
237            "✗ update failed\n  for the tag\n  \x1b[2mfatal: no remote\x1b[0m\n  \x1b[2mhint: add one\x1b[0m\n"
238        );
239    }
240
241    use crate::document::{Line, Span, Style};
242    use crate::theme::MRK_DARK;
243
244    fn sample() -> Document {
245        let palette = MRK_DARK.palette;
246        let heading = Line::new(vec![Span::new("Title", Style::fg(palette.h1).bold())]);
247        let prose = Line::new(vec![
248            Span::new("Read ", Style::fg(palette.text)),
249            Span::new("the docs", Style::fg(palette.link).underline()).linked("https://example.com/docs"),
250            Span::new(" or run ", Style::fg(palette.text)),
251            Span::new(" mrk ", Style::fg(palette.code).on(palette.surface)),
252            Span::new(".", Style::fg(palette.text)),
253        ]);
254        let picture = Picture {
255            png: vec![0x89, b'P', b'N', b'G'],
256            cols: 20,
257            rows: 2,
258            alt: "flow".to_owned(),
259            indent: Line::blank(),
260            concealed_text: None,
261        };
262        Document { blocks: vec![Block::Lines(vec![heading, Line::blank(), prose]), Block::Picture(picture)] }
263    }
264
265    const CELL: CellSize = CellSize { width_px: 10, height_px: 20 };
266    const KITTY: Option<Graphics> = Some(Graphics { protocol: Protocol::Kitty, cell: CELL });
267
268    fn capabilities(color: ColorDepth, graphics: Option<Graphics>) -> Capabilities {
269        Capabilities {
270            color,
271            hyperlinks: color != ColorDepth::None,
272            graphics,
273            double_height: false,
274            background: None,
275            columns: 80,
276            rows: 24,
277            is_terminal: true,
278        }
279    }
280
281    fn readable(ansi: &str) -> String {
282        ansi.replace('\x1b', "␛").replace('\r', "␍")
283    }
284
285    #[test]
286    fn truecolor_with_links_and_pictures() {
287        insta::assert_snapshot!(readable(&ansi(&sample(), &capabilities(ColorDepth::TrueColor, KITTY), LEFT_MARGIN)));
288    }
289
290    #[test]
291    fn ansi256_without_pictures() {
292        insta::assert_snapshot!(readable(&ansi(&sample(), &capabilities(ColorDepth::Ansi256, None), LEFT_MARGIN)));
293    }
294
295    #[test]
296    fn no_colour_is_plain_text() {
297        assert_eq!(
298            ansi(&sample(), &capabilities(ColorDepth::None, None), LEFT_MARGIN),
299            "  Title\n\n  Read the docs or run  mrk .\n  [picture: flow]\n"
300        );
301    }
302
303    #[test]
304    fn a_picture_is_drawn_after_its_indent_on_every_row() {
305        let indent = Line::new(vec![Span::plain("│ ")]);
306        let picture = Picture { png: vec![1, 2, 3], cols: 20, rows: 2, alt: "flow".to_owned(), indent, concealed_text: None };
307        let document = Document { blocks: vec![Block::Picture(picture)] };
308
309        assert_eq!(
310            ansi(&document, &capabilities(ColorDepth::None, KITTY), LEFT_MARGIN),
311            "  │ \n  │ \n\x1b[2A\r  │ \x1b_Ga=T,f=100,q=2,C=1,c=20,r=2,z=0,m=0;AQID\x1b\\\x1b[2B\r"
312        );
313        assert_eq!(ansi(&document, &capabilities(ColorDepth::None, None), LEFT_MARGIN), "  │ [picture: flow]\n");
314    }
315
316    #[test]
317    fn a_picture_taller_than_the_screen_is_drawn_in_runs_the_cursor_can_climb_back_over() {
318        let png = sixel::test_png(10, 50, &[[255, 0, 0, 255]; 500]);
319        let picture = Picture { png, cols: 1, rows: 5, alt: "flow".to_owned(), indent: Line::blank(), concealed_text: None };
320        let short_screen = Capabilities { rows: 3, ..capabilities(ColorDepth::None, KITTY) };
321
322        let drawn = ansi(&Document { blocks: vec![Block::Picture(picture)] }, &short_screen, 0);
323        let runs: Vec<&str> = drawn.split_inclusive("B\r").collect();
324
325        assert_eq!(runs.len(), 3, "{drawn:?}");
326        assert!(runs[0].starts_with("\n\n\x1b[2A\r\x1b_Ga=T,f=100,q=2,C=1,x=0,y=0,w=10,h=20,c=1,r=2,"), "{drawn:?}");
327        assert!(runs[1].starts_with("\n\n\x1b[2A\r\x1b_Ga=T,f=100,q=2,C=1,x=0,y=20,w=10,h=20,c=1,r=2,"), "{drawn:?}");
328        assert!(runs[2].starts_with("\n\x1b[1A\r\x1b_Ga=T,f=100,q=2,C=1,x=0,y=40,w=10,h=10,c=1,r=1,"), "{drawn:?}");
329        assert!(drawn.ends_with("\x1b[1B\r"), "{drawn:?}");
330    }
331
332    const SIXEL: Option<Graphics> = Some(Graphics { protocol: Protocol::Sixel, cell: CELL });
333
334    #[test]
335    fn a_tall_sixel_picture_sends_every_pixel_row_once_across_its_runs() {
336        let png = sixel::test_png(1, 100, &[[255, 0, 0, 255]; 100]);
337        let picture = Picture { png, cols: 1, rows: 5, alt: "flow".to_owned(), indent: Line::blank(), concealed_text: None };
338        let short_screen = Capabilities { rows: 3, ..capabilities(ColorDepth::None, SIXEL) };
339
340        let drawn = ansi(&Document { blocks: vec![Block::Picture(picture)] }, &short_screen, 0);
341        let heights: Vec<&str> = drawn.split("\"1;1;1;").skip(1).filter_map(|rest| rest.split('#').next()).collect();
342
343        assert_eq!(heights, ["40", "40", "20"], "{drawn:?}");
344    }
345
346    #[test]
347    fn a_sixel_picture_is_drawn_after_its_indent_and_the_cursor_put_back() {
348        let picture = Picture {
349            png: sixel::test_png(1, 6, &[[255, 0, 0, 255]; 6]),
350            cols: 1,
351            rows: 1,
352            alt: "flow".to_owned(),
353            indent: Line::new(vec![Span::plain("│ ")]),
354            concealed_text: None,
355        };
356        let document = Document { blocks: vec![Block::Picture(picture)] };
357
358        assert_eq!(
359            ansi(&document, &capabilities(ColorDepth::None, SIXEL), LEFT_MARGIN),
360            "  │ \n\x1b[1A\r  │ \x1b7\x1bP0;1;0q\"1;1;1;6#0;2;100;0;0#0~-\x1b\\\x1b8\x1b[1B\r"
361        );
362    }
363
364    #[test]
365    fn inside_tmux_a_picture_is_rows_of_placeholder_cells_after_its_indent() {
366        let picture = Picture {
367            png: vec![1, 2, 3],
368            cols: 2,
369            rows: 2,
370            alt: "flow".to_owned(),
371            indent: Line::new(vec![Span::plain("│ ")]),
372            concealed_text: None,
373        };
374        let document = Document { blocks: vec![Block::Picture(picture)] };
375        let through_tmux = Some(Graphics { protocol: Protocol::KittyThroughTmux, cell: CELL });
376
377        let drawn = ansi(&document, &capabilities(ColorDepth::None, through_tmux), LEFT_MARGIN);
378        let rows: Vec<&str> = drawn.lines().collect();
379
380        assert!(rows[0].starts_with("\x1bPtmux;") && rows[0].contains("  │ \x1b[38;5;"), "{drawn:?}");
381        assert!(rows[1].starts_with("  │ \x1b[38;5;") && rows[1].ends_with("\u{10eeee}\x1b[39m"), "{drawn:?}");
382        assert_eq!(rows.len(), 2);
383    }
384
385    #[test]
386    fn an_unreadable_png_shows_the_placeholder_on_a_sixel_terminal() {
387        let picture =
388            Picture { png: vec![1, 2, 3], cols: 20, rows: 2, alt: "flow".to_owned(), indent: Line::blank(), concealed_text: None };
389
390        assert_eq!(
391            ansi(&Document { blocks: vec![Block::Picture(picture)] }, &capabilities(ColorDepth::None, SIXEL), 2),
392            "  [picture: flow]\n"
393        );
394    }
395
396    #[test]
397    fn the_placeholder_sanitizes_the_alt_text() {
398        let picture =
399            Picture { png: vec![], cols: 20, rows: 2, alt: "a\x1b]0;x\x07".to_owned(), indent: Line::blank(), concealed_text: None };
400
401        assert_eq!(placeholder(&picture, "  "), "  [picture: a]0;x]\n");
402    }
403
404    #[test]
405    fn a_jumbo_title_is_a_picture_with_kitty_double_height_text_where_drawn_and_normal_elsewhere() {
406        let double_height = |graphics| Capabilities { double_height: true, ..capabilities(ColorDepth::TrueColor, graphics) };
407        let through_tmux = Some(Graphics { protocol: Protocol::KittyThroughTmux, cell: CELL });
408
409        assert_eq!(jumbo_title(&capabilities(ColorDepth::TrueColor, KITTY)), Some(JumboTitle::Picture));
410        assert_eq!(jumbo_title(&double_height(KITTY)), Some(JumboTitle::Picture));
411        assert_eq!(jumbo_title(&double_height(SIXEL)), Some(JumboTitle::DoubleHeight));
412        assert_eq!(jumbo_title(&double_height(None)), Some(JumboTitle::DoubleHeight));
413        for graphics in [None, SIXEL, through_tmux] {
414            assert_eq!(jumbo_title(&capabilities(ColorDepth::TrueColor, graphics)), None, "{graphics:?}");
415        }
416    }
417
418    fn jumbo_sample(jumbo_title: Option<JumboTitle>) -> Document {
419        let settings = crate::document::Settings { width: 30, jumbo_title, ..crate::document::test_settings() };
420        crate::markdown::render("# Big title\n\nText", &settings)
421    }
422
423    #[test]
424    fn a_double_height_title_writes_each_line_as_its_two_halves_at_half_the_margin() {
425        let capabilities = Capabilities { double_height: true, ..capabilities(ColorDepth::TrueColor, None) };
426
427        insta::assert_snapshot!(readable(&ansi(&jumbo_sample(Some(JumboTitle::DoubleHeight)), &capabilities, 5)));
428    }
429
430    #[test]
431    fn without_a_jumbo_title_the_heading_is_one_row() {
432        insta::assert_snapshot!(readable(&ansi(&jumbo_sample(None), &capabilities(ColorDepth::TrueColor, None), 5)));
433    }
434
435    #[test]
436    fn a_title_picture_has_its_text_concealed_on_its_first_row_and_is_drawn_under_it() {
437        let picture = Picture {
438            png: vec![1, 2, 3],
439            cols: 20,
440            rows: 2,
441            alt: "T".to_owned(),
442            indent: Line::blank(),
443            concealed_text: Some("T\x1b]0;x\x07".to_owned()),
444        };
445
446        assert_eq!(
447            ansi(&Document { blocks: vec![Block::Picture(picture)] }, &capabilities(ColorDepth::TrueColor, KITTY), LEFT_MARGIN),
448            "  \x1b[8mT]0;x\x1b[28m\n  \n\x1b[2A\r  \x1b_Ga=T,f=100,q=2,C=1,c=20,r=2,z=-1,m=0;AQID\x1b\\\x1b[2B\r"
449        );
450    }
451
452    #[test]
453    fn write_produces_the_same_bytes_as_ansi() {
454        let capabilities = capabilities(ColorDepth::TrueColor, None);
455        let mut out = Vec::new();
456        write(&sample(), &capabilities, LEFT_MARGIN, &mut out).unwrap();
457
458        assert_eq!(String::from_utf8(out).unwrap(), ansi(&sample(), &capabilities, LEFT_MARGIN));
459    }
460}