spectral-m2 1.2.0

A syntax-aware terminal shell for Macaulay2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! Pictures in the transcript, drawn through the terminal's graphics protocol.
//!
//! What the terminal can draw is learned as it starts, and read from here as
//! the scheme is: it is a fact about the terminal, not state any element owns. A
//! picture is made while the value it shows is laid out, kept for every later
//! layout, and sent to the terminal after the frame that first places it.

pub mod kitty;
pub mod typeset;
mod typewriter;

use std::collections::HashMap;
use std::env;
use std::process::{Command, Stdio};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock};

use crossterm::terminal::window_size;
use ratatui::layout::Size;
use ratatui::text::Line;
use ratatui_image::picker::{Picker, ProtocolType};
use std::ops::Range;

use resvg::tiny_skia::{Pixmap, PixmapPaint, Transform};
use resvg::usvg::{Options, Tree};

use crate::ui::config::UI;
use kitty::{ImageId, KittyImage, Passthrough};
use typeset::{Break, Rgb, EM, PADDING};

const TMUX: &str = "tmux";
/// Set in every process tmux runs.
const TMUX_VARIABLE: &str = "TMUX";
/// Lets this pane's escape sequences through tmux to the terminal.
const TMUX_ALLOW_PASSTHROUGH: [&str; 4] = ["set", "-p", "allow-passthrough", "on"];
/// tmux's names for the terminal its client runs in, one a line: as the terminal
/// reports itself, then its `TERM`.
const TMUX_CLIENT_TERMINAL: &str = "#{client_termtype}\n#{client_termname}";
/// Variables naming the terminal outside tmux, most specific first.
const TERMINAL_VARIABLES: [&str; 2] = ["TERM_PROGRAM", "TERM"];
/// What a `TERM` puts before the terminal's own name, as in `xterm-ghostty`.
const TERM_FAMILY_PREFIX: &str = "xterm-";
/// Terminals drawing kitty pictures by Unicode placeholders, as they name themselves.
const PLACEHOLDER_TERMINALS: [&str; 2] = ["kitty", "ghostty"];

/// A terminal that shows pictures: the pixels in one of its cells, and how escape
/// sequences reach it.
#[derive(Clone, Copy, Debug)]
struct Canvas {
    cell: Size,
    passthrough: Passthrough,
}

/// Set only when the terminal answered that it shows kitty pictures.
static CANVAS: OnceLock<Mutex<Canvas>> = OnceLock::new();

static GALLERY: LazyLock<Mutex<Gallery>> = LazyLock::new(|| {
    Mutex::new(Gallery {
        formulas: HashMap::new(),
        images: HashMap::new(),
        // Starting at random keeps two shells drawing into one terminal, as tmux
        // panes do, from storing pictures under each other's ids.
        last_id: ImageId::from(rand::random::<u32>()),
        unsent: Vec::new(),
        sources: HashMap::new(),
    })
});

/// Learn what the terminal can draw. Runs on the alternate screen before any event
/// is read, since a terminal asked directly answers as input.
pub fn detect() {
    let canvas = match env::var_os(TMUX_VARIABLE).is_some() {
        true => tmux_canvas(),
        false => queried_canvas(),
    };
    if let Some(canvas) = canvas {
        let _ = CANVAS.set(Mutex::new(canvas));
    }
}

/// The canvas of a terminal asked directly, by escape sequences it answers on stdin.
fn queried_canvas() -> Option<Canvas> {
    let picker = Picker::from_query_stdio().ok()?;
    let font = picker.font_size();
    (picker.protocol_type() == ProtocolType::Kitty).then(|| Canvas {
        cell: Size::new(font.width, font.height),
        passthrough: Passthrough::Direct,
    })
}

/// The canvas of the terminal tmux runs in, learned without asking it anything:
/// tmux keeps the terminal's answer to a graphics query, and a query left
/// unanswered leaves a reader on stdin that takes the next keypress. The terminal
/// is known by the name tmux gives it, its cells by the pixels tmux reports.
fn tmux_canvas() -> Option<Canvas> {
    terminal().filter(|name| PLACEHOLDER_TERMINALS.contains(name))?;
    let window = window_size().ok()?;
    if window.columns == 0 || window.rows == 0 || window.width == 0 || window.height == 0 {
        return None;
    }
    let _ = Command::new(TMUX)
        .args(TMUX_ALLOW_PASSTHROUGH)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
    Some(Canvas {
        cell: Size::new(window.width / window.columns, window.height / window.rows),
        passthrough: Passthrough::Tmux,
    })
}

/// The terminal drawing the screen, as one lowercase word fit to print; inside
/// tmux, the terminal tmux runs in.
pub fn terminal() -> Option<&'static str> {
    static TERMINAL: LazyLock<Option<String>> = LazyLock::new(|| {
        let names = match env::var_os(TMUX_VARIABLE).is_some() {
            true => tmux_client_names(),
            false => TERMINAL_VARIABLES
                .iter()
                .filter_map(|variable| env::var(variable).ok())
                .collect(),
        };
        names.iter().find_map(|name| printable_name(name))
    });
    TERMINAL.as_deref()
}

fn tmux_client_names() -> Vec<String> {
    Command::new(TMUX)
        .args(["display-message", "-p", TMUX_CLIENT_TERMINAL])
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
        .map(|output| {
            String::from_utf8_lossy(&output.stdout)
                .lines()
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

/// `name` as one lowercase word: `ghostty 1.3.1` and `kitty(0.36.4)` lose their
/// versions, `xterm-ghostty` its family; none for what is not a name, such as
/// `xterm-256color`.
fn printable_name(name: &str) -> Option<String> {
    let name = name.split([' ', '(']).next()?;
    let name = name
        .strip_prefix(TERM_FAMILY_PREFIX)
        .unwrap_or(name)
        .to_lowercase();
    let is_word = name.starts_with(|c: char| c.is_ascii_alphabetic())
        && name.chars().all(|c| c.is_ascii_alphanumeric());
    is_word.then_some(name)
}

/// Whether this terminal shows pictures.
pub fn available() -> bool {
    CANVAS.get().is_some()
}

/// The pixel dimensions used to draw pictures in each terminal cell.
pub fn cell_size() -> Option<Size> {
    CANVAS.get()?.lock().ok().map(|canvas| canvas.cell)
}

/// Refresh the cell's pixel dimensions after terminal zoom or a display change.
/// Returns whether pictures need to be laid out again, keeping the last valid
/// dimensions when the terminal reports no pixel size.
pub fn refresh_cell_size() -> bool {
    let Some(canvas) = CANVAS.get() else {
        return false;
    };
    let Ok(window) = window_size() else {
        return false;
    };
    if window.columns == 0 || window.rows == 0 {
        return false;
    }
    let cell = Size::new(window.width / window.columns, window.height / window.rows);
    if cell.width == 0 || cell.height == 0 {
        return false;
    }
    let mut canvas = canvas
        .lock()
        .expect("the canvas lock is never held across a panic");
    if canvas.cell == cell {
        return false;
    }
    canvas.cell = cell;
    true
}

/// A formula to draw: its TeX, that TeX with theme colour scopes, the M2 code
/// a copy of its picture gives, and how far apart its matrix rows stand.
#[derive(Clone, Copy, Debug)]
pub struct Typesetting<'a> {
    pub tex: &'a str,
    pub painted: &'a str,
    pub code: &'a str,
    pub matrix_row_spacing_percent: u16,
}

/// A formula's placeholder lines and the one its baseline runs through.
#[derive(Clone, Debug)]
pub struct Pictured {
    pub lines: Vec<Line<'static>>,
    pub baseline: usize,
}

/// How a picture taller than a row takes up the rows it stands in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Placement {
    /// With nothing beside it: as few rows as hold it, its ink centred down them.
    Alone,
    /// Beside text: its baseline on the text baseline of a row, so that row lines
    /// up with what is beside it, at the cost of the rows that takes.
    AmongText,
}

/// Typeset `formula` in `colour` to stand beside text, retaining its code for
/// copying. Returns placeholder lines no wider than `width`, or none when pictures
/// are unavailable or the formula cannot be set legibly in that width.
pub fn typeset(formula: Typesetting, colour: Rgb, width: u16) -> Option<Pictured> {
    pictured(formula, colour, width, Placement::AmongText)
}

/// [`typeset`] for a formula with nothing beside it.
pub fn typeset_alone(formula: Typesetting, colour: Rgb, width: u16) -> Option<Pictured> {
    pictured(formula, colour, width, Placement::Alone)
}

fn pictured(
    formula: Typesetting,
    colour: Rgb,
    width: u16,
    placement: Placement,
) -> Option<Pictured> {
    let canvas = *CANVAS.get()?.lock().ok()?;
    gallery()
        .formula(formula, colour, canvas, width, placement)
        .map(|(image, baseline)| Pictured {
            lines: image.lines(),
            baseline,
        })
}

/// The M2 code the picture `id` shows.
pub fn source(id: ImageId) -> Option<String> {
    gallery().sources.get(&id).cloned()
}

/// Escape sequences storing every picture made since the last call.
pub fn unsent() -> String {
    let Some(canvas) = CANVAS
        .get()
        .and_then(|canvas| canvas.lock().ok().map(|canvas| *canvas))
    else {
        return String::new();
    };
    gallery()
        .unsent
        .drain(..)
        .map(|image| image.transmission(canvas.passthrough))
        .collect()
}

/// Send every picture again through tmux, which drops those sent while its pane
/// is hidden; called each time the pane regains focus.
pub fn resend_all() {
    if !CANVAS.get().is_some_and(|canvas| {
        canvas
            .lock()
            .is_ok_and(|canvas| canvas.passthrough == Passthrough::Tmux)
    }) {
        return;
    }
    let mut gallery = gallery();
    let images = gallery
        .images
        .values()
        .flatten()
        .cloned()
        .collect::<Vec<_>>();
    gallery.unsent = images;
}

fn gallery() -> MutexGuard<'static, Gallery> {
    GALLERY
        .lock()
        .expect("the gallery lock is never held across a panic")
}

/// A formula as set in one colour at one matrix row spacing.
type FormulaKey = (String, Rgb, u16);
/// A formula's picture at a column count and cell pixel size, for its copied code.
/// Values sharing TeX but not code each get their own picture to copy from.
type ImageKey = (FormulaKey, u16, Size, String, Placement);

/// A formula's vector picture and the places it may be cut into rows.
struct Formula {
    tree: Tree,
    breaks: Vec<Break>,
    /// Where the text baseline runs down the picture, as a share of its height.
    baseline: f32,
}

/// Every picture made, kept so a layout at another width or a resend reuses it.
struct Gallery {
    /// Each formula's vector picture, or none when RaTeX refused it.
    formulas: HashMap<FormulaKey, Option<Arc<Formula>>>,
    /// Each formula rasterised to a number of columns at a cell pixel size.
    images: HashMap<ImageKey, Option<Arc<KittyImage>>>,
    last_id: ImageId,
    unsent: Vec<Arc<KittyImage>>,
    /// The M2 code each picture shows, so copying it gives back what M2 reads.
    sources: HashMap<ImageId, String>,
}

impl Gallery {
    fn formula(
        &mut self,
        Typesetting {
            tex,
            painted,
            code,
            matrix_row_spacing_percent,
        }: Typesetting,
        colour: Rgb,
        canvas: Canvas,
        width: u16,
        placement: Placement,
    ) -> Option<(Arc<KittyImage>, usize)> {
        let key = (painted.to_string(), colour, matrix_row_spacing_percent);
        let formula = self
            .formulas
            .entry(key.clone())
            .or_insert_with(|| {
                let typeset =
                    typeset::svg_colored(tex, painted, colour, matrix_row_spacing_percent).ok()?;
                let tree = Tree::from_str(&typeset.svg, &Options::default()).ok()?;
                Some(Arc::new(Formula {
                    tree,
                    breaks: typeset.breaks,
                    baseline: typeset.baseline,
                }))
            })
            .clone()?;
        let raster = Raster::fitted(&formula, canvas, width, placement)?;
        let baseline = raster.baseline_row();
        let image_key = (
            key,
            raster.cells.width,
            canvas.cell,
            code.to_string(),
            placement,
        );
        if let Some(image) = self.images.get(&image_key) {
            return image.clone().map(|image| (image, baseline));
        }
        self.last_id = self.last_id.next();
        let image = raster
            .png(&formula.tree)
            .and_then(|png| KittyImage::new(self.last_id, raster.cells, png).ok())
            .map(Arc::new);
        self.unsent.extend(image.clone());
        if image.is_some() {
            self.sources.insert(self.last_id, code.to_string());
        }
        self.images.insert(image_key, image.clone());
        image.map(|image| (image, baseline))
    }
}

/// How a vector picture lands on the cell grid: its scale, the slices of it
/// stacked as rows, and the cells it covers.
struct Raster {
    scale: f32,
    top: f32,
    /// Where the picture's top edge lands within a row, in pixels.
    offset: f32,
    /// The picture's slices, left to right, each drawn below the one before.
    rows: Vec<Range<f32>>,
    /// Terminal rows each slice stands in.
    row_cells: u16,
    /// Which of a slice's rows its baseline runs through.
    slice_baseline: u16,
    cells: Size,
    cell: Size,
}

impl Raster {
    /// The picture at the terminal's text size, broken into rows of at most
    /// `width` columns where it may break, and shrunk to `width` when a row it
    /// cannot break is wider; none when shrinking would make it too small to read.
    fn fitted(formula: &Formula, canvas: Canvas, width: u16, placement: Placement) -> Option<Self> {
        let tree = &formula.tree;
        // Font ascender/descender metrics can reserve more space than the ink,
        // particularly for delimiters. Only visible bounds determine occupied rows.
        let bounds = tree.root().abs_stroke_bounding_box();
        let top = bounds.top() - PADDING;
        let height = bounds.height() + 2.0 * PADDING;
        let cell_width = f32::from(canvas.cell.width);
        let cell_height = f32::from(canvas.cell.height);
        let natural = cell_height * UI.typeset.em_per_cell_height / EM;
        let room = f32::from(width) * cell_width / natural;
        let across = tree.size().width();
        let breaks = formula
            .breaks
            .iter()
            .map(|cut| cut.across(across))
            .collect::<Vec<_>>();
        let rows = wrapped(across, &breaks, room);
        let widest = rows
            .iter()
            .map(|row| row.end - row.start)
            .fold(0.0, f32::max);
        let shrink = (room / widest).min(1.0);
        if shrink < UI.typeset.min_scale {
            return None;
        }
        let scale = natural * shrink;
        let cover = |extent: f32, cell: f32| ((extent * scale / cell).ceil() as u16).max(1);
        let above = (formula.baseline * tree.size().height() - top) * scale;
        let below = (height * scale - above).max(0.0);
        let padding = PADDING * scale;
        let text_baseline = UI.typeset.baseline_per_cell_height * cell_height;
        // The rows ink needs past its own, the padding being there to spend.
        let rows_past = |reach: f32, room: f32| {
            ((reach - 2.0 * padding - room) / cell_height)
                .ceil()
                .max(0.0) as u16
        };
        let covered = cover(height, cell_height);
        let (row_cells, slice_baseline) = match placement {
            _ if covered == 1 => (1, 0),
            Placement::Alone => (covered, (covered - 1) / 2),
            Placement::AmongText => {
                let rows_above = rows_past(above, text_baseline);
                let rows_below = rows_past(below, cell_height - text_baseline);
                (rows_above + 1 + rows_below, rows_above)
            }
        };
        let row_height = f32::from(row_cells) * cell_height;
        let offset = if placement == Placement::Alone && covered > 1 {
            (row_height - height * scale) / 2.0
        } else {
            // On the text baseline where the ink leaves room for it, else as close
            // as it can sit without its ink being cut off.
            (f32::from(slice_baseline) * cell_height + text_baseline)
                .min(row_height - below)
                .max(above - padding)
                - above
        };
        Some(Self {
            scale,
            top,
            offset,
            cells: Size::new(
                cover(widest, cell_width).min(width),
                row_cells * rows.len() as u16,
            ),
            rows,
            row_cells,
            slice_baseline,
            cell: canvas.cell,
        })
    }

    /// The row a neighbour lines up with: the baseline's in a picture of one slice,
    /// the middle one of several.
    fn baseline_row(&self) -> usize {
        match self.rows.len() {
            1 => usize::from(self.slice_baseline),
            _ => usize::from(self.cells.height.saturating_sub(1) / 2),
        }
    }

    /// The picture's rows drawn across exactly its cells, as PNG.
    fn png(&self, tree: &Tree) -> Option<Vec<u8>> {
        let width = u32::from(self.cells.width) * u32::from(self.cell.width);
        let row_height = u32::from(self.row_cells) * u32::from(self.cell.height);
        let mut pixmap = Pixmap::new(width, row_height * self.rows.len() as u32)?;
        for (index, row) in self.rows.iter().enumerate() {
            // A slice as wide as its row, so what follows its end is cut away.
            let slice = (((row.end - row.start) * self.scale).ceil() as u32).clamp(1, width);
            let mut strip = Pixmap::new(slice, row_height)?;
            let transform = Transform::from_scale(self.scale, self.scale)
                .post_translate(-row.start * self.scale, self.offset - self.top * self.scale);
            resvg::render(tree, transform, &mut strip.as_mut());
            pixmap.draw_pixmap(
                0,
                (row_height * index as u32) as i32,
                strip.as_ref(),
                &PixmapPaint::default(),
                Transform::identity(),
                None,
            );
        }
        pixmap.encode_png().ok()
    }
}

/// The slices of a picture `width` units wide, each at most `room` wide where
/// `breaks` allow: every row takes the last break that still fits, and a row
/// with none that fits runs on to the first it can.
fn wrapped(width: f32, breaks: &[Break], room: f32) -> Vec<Range<f32>> {
    let mut rows = Vec::new();
    let mut start = 0.0;
    while width - start > room {
        let ahead = || breaks.iter().filter(|cut| cut.start > start);
        let Some(cut) = ahead()
            .take_while(|cut| cut.end - start <= room)
            .last()
            .or_else(|| ahead().next())
        else {
            break;
        };
        rows.push(start..cut.end);
        start = cut.start;
    }
    rows.push(start..width);
    rows
}

#[cfg(test)]
mod tests {
    use resvg::tiny_skia::PremultipliedColorU8;

    use super::*;

    const CANVAS: Canvas = Canvas {
        cell: Size::new(10, 20),
        passthrough: Passthrough::Direct,
    };

    #[test]
    fn terminals_are_named_without_versions_or_families() {
        assert_eq!(printable_name("ghostty 1.3.1").as_deref(), Some("ghostty"));
        assert_eq!(printable_name("kitty(0.36.4)").as_deref(), Some("kitty"));
        assert_eq!(printable_name("xterm-ghostty").as_deref(), Some("ghostty"));
        assert_eq!(printable_name("WezTerm").as_deref(), Some("wezterm"));
        assert_eq!(printable_name("xterm-256color"), None);
        assert_eq!(printable_name(""), None);
    }

    #[test]
    fn a_type_annotation_of_words_and_rings_is_set() {
        let annotation = r"\textrm{Matrix}\ R^{1}\ \textrm{<--}\ \mathbb{Q}[x,y]^{2}";
        assert!(typeset::svg(annotation, Rgb([255, 255, 255])).is_ok());
    }

    fn formula(tex: &str) -> Formula {
        let typeset = typeset::svg_colored(
            tex,
            tex,
            Rgb([255, 255, 255]),
            UI.matrix_row_spacing_percent,
        )
        .unwrap();
        Formula {
            tree: Tree::from_str(&typeset.svg, &Options::default()).unwrap(),
            breaks: typeset.breaks,
            baseline: typeset.baseline,
        }
    }

    #[test]
    fn ordinary_delimiters_do_not_add_a_terminal_row() {
        for tex in [
            "1",
            "(1)",
            "[1]",
            r"\left(1\right)",
            r"\left[1\right]",
            r"\left\{1\right\}",
        ] {
            let formula = formula(tex);
            let raster = Raster::fitted(&formula, CANVAS, 80, Placement::AmongText).unwrap();
            assert_eq!(
                raster.cells.height,
                1,
                "{tex}: SVG height {}, scale {}",
                formula.tree.size().height(),
                raster.scale
            );
        }
    }

    #[test]
    fn one_row_formulas_rest_their_ink_on_the_text_baseline() {
        let cell = Size::new(20, 44);
        let canvas = Canvas { cell, ..CANVAS };
        let baseline = UI.typeset.baseline_per_cell_height * f32::from(cell.height);
        for tex in ["a", "c", "ab", "ac", "1", "x", r"a^{2}", r"a^{2}b"] {
            let formula = formula(tex);
            let raster = Raster::fitted(&formula, canvas, 80, Placement::AmongText).unwrap();
            assert_eq!(raster.cells.height, 1, "{tex}");
            let pixmap = Pixmap::decode_png(&raster.png(&formula.tree).unwrap()).unwrap();
            let last_inked_row = pixmap
                .pixels()
                .chunks(pixmap.width() as usize)
                .rposition(|row| row.iter().any(|pixel| pixel.alpha() > u8::MAX / 2))
                .unwrap();
            let below_baseline = last_inked_row as f32 + 1.0 - baseline;
            assert!(below_baseline.abs() <= 1.5, "{tex}: {below_baseline}");
        }
    }

    #[test]
    fn a_tall_formula_beside_text_stands_around_the_row_of_its_baseline() {
        let cell = Size::new(20, 44);
        let canvas = Canvas { cell, ..CANVAS };
        let formula = formula(r"\frac{1}{2}");
        let raster = Raster::fitted(&formula, canvas, 80, Placement::AmongText).unwrap();
        let pixmap = Pixmap::decode_png(&raster.png(&formula.tree).unwrap()).unwrap();
        let inked = |row: &[PremultipliedColorU8]| row.iter().any(|pixel| pixel.alpha() > 0);
        let row_of = |pixel_row: usize| pixel_row / usize::from(cell.height);
        let mut rows = pixmap.pixels().chunks(pixmap.width() as usize);
        let first = rows.clone().position(inked).unwrap();
        let last = rows.rposition(inked).unwrap();
        let baseline = raster.baseline_row();
        assert!(
            row_of(first) < baseline,
            "numerator above: {first}, {baseline}"
        );
        assert!(
            row_of(last) > baseline,
            "denominator below: {last}, {baseline}"
        );
        assert_eq!(usize::from(raster.cells.height), baseline * 2 + 1);

        let alone = Raster::fitted(&formula, canvas, 80, Placement::Alone).unwrap();
        assert!(alone.cells.height < raster.cells.height);
    }

    #[test]
    fn a_picture_covers_whole_cells_and_fills_them_exactly() {
        let formula = formula(r"\frac{x+y}{x-z}");

        let raster = Raster::fitted(&formula, CANVAS, 80, Placement::AmongText).unwrap();
        let png = raster.png(&formula.tree).unwrap();

        let pixmap = Pixmap::decode_png(&png).unwrap();
        assert_eq!(pixmap.width(), u32::from(raster.cells.width) * 10);
        assert_eq!(pixmap.height(), u32::from(raster.cells.height) * 20);
        assert!(
            raster.cells.height > 1,
            "a fraction stands taller than a row"
        );

        let enlarged = Canvas {
            cell: Size::new(CANVAS.cell.width * 2, CANVAS.cell.height * 2),
            ..CANVAS
        };
        let zoomed = Raster::fitted(&formula, enlarged, 80, Placement::AmongText).unwrap();
        let zoomed = Pixmap::decode_png(&zoomed.png(&formula.tree).unwrap()).unwrap();
        assert_eq!(zoomed.width(), pixmap.width() * 2);
        assert_eq!(zoomed.height(), pixmap.height() * 2);
    }

    #[test]
    fn a_wide_formula_shrinks_to_the_width_until_it_would_be_unreadable() {
        let formula = formula(r"1\,267\,650\,600\,228\,229\,401\,496\,703\,205\,376");
        let natural = Raster::fitted(&formula, CANVAS, u16::MAX, Placement::AmongText)
            .unwrap()
            .cells
            .width;

        let shrunk = Raster::fitted(&formula, CANVAS, natural - 1, Placement::AmongText).unwrap();
        let refused = Raster::fitted(&formula, CANVAS, 1, Placement::AmongText);

        assert!(shrunk.cells.width < natural);
        assert!(refused.is_none());
    }

    #[test]
    fn a_long_list_wraps_after_its_commas_at_full_size() {
        let entries = (1..=60).map(|n| n.to_string()).collect::<Vec<_>>();
        let formula = formula(&format!(r"\left\{{{}\right\}}", entries.join(r",\,")));
        let unbroken = Raster::fitted(&formula, CANVAS, u16::MAX, Placement::AmongText).unwrap();
        let width = unbroken.cells.width / 3;

        let wrapped = Raster::fitted(&formula, CANVAS, width, Placement::AmongText).unwrap();

        assert_eq!(unbroken.rows.len(), 1);
        assert!(wrapped.rows.len() >= 3, "{} rows", wrapped.rows.len());
        assert_eq!(wrapped.scale, unbroken.scale, "wrapping never shrinks");
        assert!(wrapped.cells.width <= width);
        assert_eq!(
            wrapped.cells.height,
            unbroken.cells.height * wrapped.rows.len() as u16
        );
    }

    #[test]
    fn a_fraction_bar_is_never_cut() {
        let formula = formula(r"\frac{1,\,2,\,3,\,4,\,5,\,6,\,7,\,8}{9}");
        assert!(formula.breaks.is_empty());
    }

    #[test]
    fn another_matrix_row_spacing_makes_another_picture() {
        let mut gallery = GALLERY.lock().unwrap();
        let tex = r"\begin{array}{c}x\\y\end{array}";
        let formula = |matrix_row_spacing_percent| Typesetting {
            tex,
            painted: tex,
            code: tex,
            matrix_row_spacing_percent,
        };
        let ink = Rgb([1, 2, 3]);
        let placement = Placement::Alone;

        let tight = gallery.formula(formula(100), ink, CANVAS, 80, placement);
        let spaced = gallery.formula(formula(200), ink, CANVAS, 80, placement);

        assert!(!Arc::ptr_eq(&tight.unwrap().0, &spaced.unwrap().0));
    }

    #[test]
    fn a_formula_is_made_once_and_sent_once_whatever_the_wider_width() {
        let mut gallery = GALLERY.lock().unwrap();
        gallery.unsent.clear();
        let ink = Rgb([1, 2, 3]);

        let square = Typesetting {
            tex: "x^2",
            painted: r"\textcolor{red}{x^2}",
            code: "x^2",
            matrix_row_spacing_percent: UI.matrix_row_spacing_percent,
        };

        let placement = Placement::AmongText;
        let first = gallery.formula(square, ink, CANVAS, 80, placement);
        let again = gallery.formula(square, ink, CANVAS, 120, placement);

        assert!(Arc::ptr_eq(&first.unwrap().0, &again.unwrap().0));
        assert_eq!(gallery.unsent.len(), 1);
        assert_eq!(
            gallery.sources.get(&gallery.last_id).map(String::as_str),
            Some(square.code)
        );

        let enlarged = Canvas {
            cell: Size::new(CANVAS.cell.width * 2, CANVAS.cell.height * 2),
            ..CANVAS
        };
        let (original, _) = gallery.formula(square, ink, CANVAS, 80, placement).unwrap();
        let (zoomed, _) = gallery
            .formula(square, ink, enlarged, 80, placement)
            .unwrap();
        assert!(!Arc::ptr_eq(&original, &zoomed));
        assert_eq!(original.lines().len(), zoomed.lines().len());
        assert_eq!(original.lines()[0].width(), zoomed.lines()[0].width());
        assert_eq!(gallery.unsent.len(), 2);

        let (restored, _) = gallery.formula(square, ink, CANVAS, 80, placement).unwrap();
        assert!(Arc::ptr_eq(&original, &restored));
        assert_eq!(gallery.unsent.len(), 2);
    }
}