malevich 1.24.1

Terminal plotting: a small grammar of marks, honest axes, millions of points
Documentation
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! The subpixel surface: the grid marks draw on, and its string encoders.

use super::canvas::{Anchor, Canvas, PlotRect, PointShape};
use super::charset::Charset;
use super::color::{Color, ColorMode, Resolved};
use super::raster::{Raster, RasterCell};

/// One character cell: a subpixel pattern, a text slot, independent foreground
/// and background colors, and an optional colorless fallback glyph.
///
/// Text wins over pixels when the cell prints — labels are never corrupted by marks
/// drawing underneath them.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Cell {
    bits: u8,
    text: Text,
    foreground: Color,
    background: Color,
    /// `0..=3` is a final plain shade, `0x80..=0x83` is a pending top sample,
    /// and `u8::MAX` means the styled glyph is also its plain fallback.
    plain_shade: u8,
}

/// The text slot of a cell. A wide glyph (CJK) occupies its own cell plus a
/// `Continuation` to its right; the pair is kept consistent on every overwrite.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Text {
    None,
    Glyph(char),
    Continuation,
}

const EMPTY: Cell = Cell {
    bits: 0,
    text: Text::None,
    foreground: Color::Default,
    background: Color::Default,
    plain_shade: u8::MAX,
};

/// The shade ramp two-sample cells fall back to in plain output; only the
/// block-glyph charsets pack two samples, so this is their ramp.
const SHADE_RAMP: [char; 4] = Charset::Quadrants.shade_ramp();
const PENDING_TOP: u8 = 0x80;

/// A grid of character cells addressed in subpixel coordinates.
///
/// The surface is pure raster state: origin at the top-left, y growing downward,
/// `width * height` cells at the charset's subpixel density. Drawing is infallible —
/// coordinates outside the surface clip away, non-finite coordinates draw nothing.
/// Ordinary subpixel drawing retains last-write foreground semantics. Cell patches
/// can additionally use the background channel to carry a second vertical sample.
#[derive(Clone, PartialEq)]
pub struct Surface {
    width: usize,
    height: usize,
    charset: Charset,
    columns: usize,
    rows: usize,
    cells: Vec<Cell>,
    /// An optional drawing clip in subpixel coordinates `(x0, y0, x1, y1)`, upper
    /// bounds exclusive. When set, [`Surface::set`] and [`Surface::text`] draw only
    /// inside it — used to confine marks to the plot rectangle so their ink never
    /// escapes into the axes or gutter. Chrome is drawn with no clip.
    clip: Option<(i64, i64, i64, i64)>,
}

impl Surface {
    /// Creates an empty surface of `width * height` cells encoded with `charset`.
    ///
    /// A request beyond the renderer's defensive geometry limit degrades to a 0×0
    /// surface. Use [`Surface::try_new`] when the caller needs the typed error.
    pub fn new(width: usize, height: usize, charset: Charset) -> Surface {
        Surface::try_new(width, height, charset).unwrap_or_else(|_| Surface::empty(charset))
    }

    /// Creates an empty surface, rejecting dimensions that overflow or exceed the
    /// renderer's defensive cell budget.
    pub fn try_new(width: usize, height: usize, charset: Charset) -> crate::Result<Surface> {
        let (columns, rows) = charset.pixels_per_cell();
        let count = super::frame_cells(width, height)?;
        let mut cells = Vec::new();
        super::reserve_vec(&mut cells, count, "surface cells")?;
        cells.resize(count, EMPTY);
        Ok(Surface {
            width,
            height,
            charset,
            columns,
            rows,
            cells,
            clip: None,
        })
    }

    fn empty(charset: Charset) -> Surface {
        let (columns, rows) = charset.pixels_per_cell();
        Surface {
            width: 0,
            height: 0,
            charset,
            columns,
            rows,
            cells: Vec::new(),
            clip: None,
        }
    }

    /// Confines subsequent drawing to the subpixel rectangle `[x0, x1) x [y0, y1)`.
    pub(crate) fn set_clip(&mut self, x0: i64, y0: i64, x1: i64, y1: i64) {
        self.clip = Some((x0, y0, x1, y1));
    }

    /// Removes any drawing clip.
    pub(crate) fn clear_clip(&mut self) {
        self.clip = None;
    }

    /// The size in cells as `(width, height)`.
    pub fn size(&self) -> (usize, usize) {
        (self.width, self.height)
    }

    /// The size in subpixels as `(width, height)`.
    pub fn subpixel_size(&self) -> (usize, usize) {
        // Construction bounds each cell dimension to u16 and every charset density
        // to at most four, so these products cannot overflow. Keep saturating
        // arithmetic as a final defense if those internal constants ever change.
        (
            self.width.saturating_mul(self.columns),
            self.height.saturating_mul(self.rows),
        )
    }

    /// Sets the subpixel at `(x, y)`; outside the surface or the active clip this
    /// does nothing.
    pub fn set(&mut self, x: i64, y: i64, color: Color) {
        let (sw, sh) = self.subpixel_size();
        if x < 0 || y < 0 || x >= sw as i64 || y >= sh as i64 {
            return;
        }
        if let Some((x0, y0, x1, y1)) = self.clip
            && (x < x0 || y < y0 || x >= x1 || y >= y1)
        {
            return;
        }
        let (x, y) = (x as usize, y as usize);
        let index = (y / self.rows) * self.width + x / self.columns;
        let cell = &mut self.cells[index];
        cell.bits |= self.charset.bit(x % self.columns, y % self.rows);
        cell.foreground = color;
    }

    /// Sets the subpixel nearest to `(x, y)`; non-finite coordinates draw nothing.
    pub fn dot(&mut self, x: f64, y: f64, color: Color) {
        if x.is_finite() && y.is_finite() {
            self.set(x.round() as i64, y.round() as i64, color);
        }
    }

    /// Draws a line between two subpixel positions, clipped to the surface.
    ///
    /// Non-finite endpoints draw nothing (a gap breaks a polyline before it reaches
    /// this call, but the surface defends itself regardless).
    pub fn line(&mut self, from: (f64, f64), to: (f64, f64), color: Color) {
        if !(from.0.is_finite() && from.1.is_finite() && to.0.is_finite() && to.1.is_finite()) {
            return;
        }
        let (sw, sh) = self.subpixel_size();
        if sw == 0 || sh == 0 {
            return;
        }
        // Clip to the surface, tightened to the active clip rectangle: this bounds
        // the Bresenham walk to the drawable region, so even wildly out-of-range
        // finite endpoints cost only the pixels actually on screen.
        let (mut wx0, mut wy0, mut wx1, mut wy1) =
            (0.0f64, 0.0f64, (sw - 1) as f64, (sh - 1) as f64);
        if let Some((x0, y0, x1, y1)) = self.clip {
            wx0 = wx0.max(x0 as f64);
            wy0 = wy0.max(y0 as f64);
            wx1 = wx1.min((x1 - 1) as f64);
            wy1 = wy1.min((y1 - 1) as f64);
        }
        super::canvas::trace_line(from, to, (wx0, wy0, wx1, wy1), |x, y| {
            self.set(x, y, color);
        });
    }

    /// Writes text starting at the cell `(column, row)`; cells outside clip away.
    ///
    /// Text overrides any pixels in the same cells and is measured in display
    /// columns: a wide glyph (CJK) occupies two cells, and one that would straddle
    /// the surface edge is dropped whole. Zero-width characters (combining marks) do
    /// not survive the cell grid and are dropped. Overwriting half of a wide glyph
    /// blanks its other half — alignment is never corrupted.
    pub fn text(&mut self, column: i64, row: i64, text: &str, color: Color) {
        use unicode_width::UnicodeWidthChar;

        if row < 0 || row >= self.height as i64 {
            return;
        }
        let row = row as usize;
        let mut column = column;
        for glyph in text.chars() {
            let width = glyph.width().unwrap_or(0) as i64;
            if width == 0 {
                continue;
            }
            let fits = column >= 0 && column + width <= self.width as i64;
            if fits {
                self.place(row, column as usize, Text::Glyph(glyph), color);
                for offset in 1..width {
                    self.place(row, (column + offset) as usize, Text::Continuation, color);
                }
            }
            column += width;
        }
    }

    /// Like [`Surface::text`], but the ink keeps what it lands on: a glyph over
    /// a filled patch cell — a heatmap band, a bar body, a class region — takes
    /// the underlying color as its background, so an annotation reads *on* the
    /// field instead of punching a hole in it. Two-sample cells blend their
    /// halves. Cells without patch ink behave exactly like [`Surface::text`].
    fn annotate(&mut self, column: i64, row: i64, text: &str, color: Color) {
        use unicode_width::UnicodeWidthChar;

        if row < 0 || row >= self.height as i64 {
            return;
        }
        let row = row as usize;
        let mut column = column;
        for glyph in text.chars() {
            let width = glyph.width().unwrap_or(0) as i64;
            if width == 0 {
                continue;
            }
            let fits = column >= 0 && column + width <= self.width as i64;
            if fits {
                let background = self.under(row, column as usize);
                self.place_styled(
                    row,
                    column as usize,
                    Text::Glyph(glyph),
                    color,
                    background,
                    u8::MAX,
                );
                for offset in 1..width {
                    self.place_styled(
                        row,
                        (column + offset) as usize,
                        Text::Continuation,
                        color,
                        background,
                        u8::MAX,
                    );
                }
            }
            column += width;
        }
    }

    /// The color an annotation landing on this cell should carry as its
    /// background: filled patch glyphs promote their ink — a full block's
    /// foreground, both halves of a two-sample cell blended — and anything
    /// else (chrome, empty cells, subpixel marks, partial bar fills) yields
    /// the default, exactly as plain text placement would.
    fn under(&self, row: usize, column: usize) -> Color {
        let Some(index) = self.cell_index(row, column) else {
            return Color::Default;
        };
        let cell = self.cells[index];
        let filled = match cell.text {
            Text::Glyph(glyph @ ('\u{2588}' | '\u{2580}' | '\u{2584}')) => {
                // Half blocks are the two-sample cell on the block charsets;
                // ASCII never draws them, so on ASCII they are text.
                glyph == '\u{2588}' || self.charset != Charset::Ascii
            }
            Text::Glyph(glyph) => self.charset.shade_ramp().contains(&glyph),
            Text::None | Text::Continuation => false,
        };
        if !filled {
            return Color::Default;
        }
        match (cell.foreground, cell.background) {
            (Color::Default, background) => background,
            (foreground, Color::Default) => foreground,
            (foreground, background) => {
                // The two halves mixed where the eye mixes them, like every
                // other blend in the crate.
                let top = super::color::oklab(foreground.to_rgb());
                let bottom = super::color::oklab(background.to_rgb());
                let (r, g, b) = super::color::from_oklab((
                    crate::numeric::midpoint(top.0, bottom.0),
                    crate::numeric::midpoint(top.1, bottom.1),
                    crate::numeric::midpoint(top.2, bottom.2),
                ));
                Color::Rgb(r, g, b)
            }
        }
    }

    /// Puts one text slot into a cell, breaking any wide-glyph pair it overlaps.
    fn place(&mut self, row: usize, column: usize, text: Text, color: Color) {
        self.place_styled(row, column, text, color, Color::Default, u8::MAX);
    }

    fn place_styled(
        &mut self,
        row: usize,
        column: usize,
        text: Text,
        foreground: Color,
        background: Color,
        plain_shade: u8,
    ) {
        let Some(index) = self.cell_index(row, column) else {
            return;
        };
        let base = row * self.width;
        // Overwriting a continuation orphans the wide glyph to its left.
        if self.cells[index].text == Text::Continuation && column > 0 {
            self.blank(base + column - 1);
        }
        // Overwriting a wide glyph orphans its continuation to the right.
        if column + 1 < self.width && self.cells[base + column + 1].text == Text::Continuation {
            self.blank(base + column + 1);
        }
        let cell = &mut self.cells[index];
        cell.text = text;
        cell.foreground = foreground;
        cell.background = background;
        cell.plain_shade = plain_shade;
    }

    fn cell_index(&self, row: usize, column: usize) -> Option<usize> {
        if row >= self.height || column >= self.width {
            return None;
        }
        if let Some((x0, y0, x1, y1)) = self.clip {
            let (col, row) = (column as i64, row as i64);
            let (px, py) = (self.columns as i64, self.rows as i64);
            if col < x0 / px || col >= x1 / px || row < y0 / py || row >= y1 / py {
                return None;
            }
        }
        Some(row * self.width + column)
    }

    fn blank(&mut self, index: usize) {
        let bits = self.cells[index].bits;
        self.cells[index] = Cell {
            bits,
            text: Text::Glyph(' '),
            ..EMPTY
        };
    }

    /// Encodes this surface as a [`Raster`]: one cell per grid slot, glyphs
    /// already chosen, continuation cells marked `columns == 0`.
    pub fn to_raster(&self) -> Raster {
        use unicode_width::UnicodeWidthChar;

        let mut cells = Vec::with_capacity(self.width.saturating_mul(self.height));
        for cell in &self.cells {
            let (glyph, columns) = match cell.text {
                Text::Continuation => (' ', 0),
                Text::Glyph(glyph) => (glyph, glyph.width().unwrap_or(1).min(2) as u8),
                Text::None => (self.charset.glyph(cell.bits), 1),
            };
            cells.push(RasterCell {
                glyph,
                foreground: cell.foreground,
                background: cell.background,
                columns,
            });
        }
        Raster::from_cells(self.width, self.height, cells)
    }

    /// Encodes as plain text — no escape codes ever. Sugar for
    /// [`Surface::encode`] with [`ColorMode::Plain`].
    pub fn to_plain(&self) -> String {
        self.encode(ColorMode::Plain)
    }

    /// Encodes the surface at the color tier of `mode`.
    ///
    /// Colors resolve to what the mode can carry (RGB quantizes downhill; see
    /// [`Color`]); an SGR sequence is emitted only when a resolved foreground or
    /// background changes along a row, so colors that quantize identically share
    /// one sequence, and any colored row ends with a reset. Rows are joined by
    /// newlines with trailing spaces trimmed. In [`ColorMode::Plain`] the output
    /// carries no escapes at all.
    pub fn encode(&self, mode: ColorMode) -> String {
        self.try_encode(mode).unwrap_or_default()
    }

    /// Encodes the surface, rejecting a worst-case string beyond the defensive
    /// output budget or a failed reservation.
    pub fn try_encode(&self, mode: ColorMode) -> crate::Result<String> {
        self.encode_rows(mode, true)
    }

    /// The full-width sibling of [`Surface::try_encode`]: rows keep their
    /// trailing default-background spaces, so the encoded block covers every
    /// cell of the grid. The hybrid pixel path uses it so a block reprinted
    /// in place fully replaces its predecessor — a shorter title must erase
    /// the longer one under it. Ordinary renders keep trimming: scrollback
    /// and piped files want no trailing-space freight.
    #[cfg(feature = "pixel")]
    pub(crate) fn try_encode_full_width(&self, mode: ColorMode) -> crate::Result<String> {
        self.encode_rows(mode, false)
    }

    fn encode_rows(&self, mode: ColorMode, trim: bool) -> crate::Result<String> {
        let cells = super::frame_cells(self.width, self.height)?;
        // One UTF-8 scalar plus the longest possible color transition per cell.
        // The extra row bytes cover newlines and SGR resets.
        let bytes_per_cell = match mode {
            ColorMode::Plain => 4,
            ColorMode::Ansi16 => 16,
            ColorMode::Ansi256 => 32,
            ColorMode::TrueColor => 48,
        };
        let capacity = cells
            .checked_mul(bytes_per_cell)
            .and_then(|bytes| {
                self.height
                    .checked_mul(5)
                    .and_then(|rows| bytes.checked_add(rows))
            })
            .ok_or(crate::Error::DimensionTooLarge {
                what: "encoded output bytes",
                requested: usize::MAX,
                limit: super::MAX_OUTPUT_BYTES,
            })?;
        let mut out = String::new();
        super::reserve_string(&mut out, capacity, "encoded output bytes")?;
        if mode == ColorMode::Plain {
            for row in 0..self.height {
                if row > 0 {
                    out.push('\n');
                }
                let mut kept = out.len();
                for (_, glyph, _, _) in self.row(row) {
                    out.push(glyph);
                    if glyph != ' ' {
                        kept = out.len();
                    }
                }
                if trim {
                    out.truncate(kept);
                }
            }
            return Ok(out);
        }
        for row in 0..self.height {
            if row > 0 {
                out.push('\n');
            }
            let mut current_foreground = Resolved::Default;
            let mut current_background = Resolved::Default;
            let mut kept = out.len();
            let mut kept_foreground = Resolved::Default;
            let mut kept_background = Resolved::Default;
            for (styled, _, foreground, background) in self.row(row) {
                let glyph = styled;
                let next_foreground = foreground.resolve(mode);
                let next_background = background.resolve(mode);
                let foreground_change = (glyph != ' ' && next_foreground != current_foreground)
                    .then_some(next_foreground);
                let background_change =
                    (next_background != current_background).then_some(next_background);
                Resolved::write_transition(foreground_change, background_change, &mut out);
                if foreground_change.is_some() {
                    current_foreground = next_foreground;
                }
                current_background = next_background;
                out.push(glyph);
                // A background-colored space is visible; ordinary default spaces
                // remain trimmable and may inherit the current foreground.
                if glyph != ' ' || current_background != Resolved::Default {
                    kept = out.len();
                    kept_foreground = current_foreground;
                    kept_background = current_background;
                }
            }
            if trim {
                out.truncate(kept);
                if kept_foreground != Resolved::Default || kept_background != Resolved::Default {
                    out.push_str("\x1b[0m");
                }
            } else if current_foreground != Resolved::Default
                || current_background != Resolved::Default
            {
                out.push_str("\x1b[0m");
            }
        }
        Ok(out)
    }

    /// Every printable cell as `(column, row, glyph, foreground, background)`,
    /// skipping wide-glyph continuations (the glyph to their left covers them).
    /// For adapters that write into cell buffers instead of strings.
    #[cfg_attr(not(feature = "ratatui"), allow(dead_code))]
    pub(crate) fn cells(&self) -> impl Iterator<Item = (usize, usize, char, Color, Color)> + '_ {
        self.cells.iter().enumerate().filter_map(|(index, cell)| {
            let (row, column) = (index / self.width.max(1), index % self.width.max(1));
            match cell.text {
                Text::Continuation => None,
                Text::Glyph(glyph) => Some((column, row, glyph, cell.foreground, cell.background)),
                Text::None => Some((
                    column,
                    row,
                    self.charset.glyph(cell.bits),
                    cell.foreground,
                    cell.background,
                )),
            }
        })
    }

    /// The printable glyphs of one row, in order. Continuation cells emit nothing:
    /// the wide glyph to their left covers their column.
    fn row(&self, row: usize) -> impl Iterator<Item = (char, char, Color, Color)> + '_ {
        self.cells[row * self.width..(row + 1) * self.width]
            .iter()
            .filter_map(|cell| match cell.text {
                Text::Continuation => None,
                Text::Glyph(glyph) => Some((
                    glyph,
                    SHADE_RAMP
                        .get(cell.plain_shade as usize)
                        .copied()
                        .unwrap_or(glyph),
                    cell.foreground,
                    cell.background,
                )),
                Text::None => {
                    let glyph = self.charset.glyph(cell.bits);
                    Some((glyph, glyph, cell.foreground, cell.background))
                }
            })
    }
}

impl Canvas for Surface {
    fn set_clip(&mut self, x0: i64, y0: i64, x1: i64, y1: i64) {
        Surface::set_clip(self, x0, y0, x1, y1);
    }

    fn clear_clip(&mut self) {
        Surface::clear_clip(self);
    }

    fn point(&mut self, x: f64, y: f64, shape: PointShape, color: Color) {
        if shape == PointShape::Dot {
            Surface::dot(self, x, y, color);
            return;
        }
        if !x.is_finite() || !y.is_finite() {
            return;
        }
        let column = (x.round() as i64).div_euclid(self.columns as i64);
        let row = (y.round() as i64).div_euclid(self.rows as i64);
        let glyph = match shape {
            PointShape::Dot => unreachable!(),
            PointShape::Plus => "+",
            PointShape::Cross => "x",
            PointShape::Asterisk => "*",
            PointShape::Circle => "o",
        };
        Surface::text(self, column, row, glyph, color);
    }

    fn line(&mut self, from: (f64, f64), to: (f64, f64), color: Color) {
        Surface::line(self, from, to, color);
    }

    fn text(&mut self, column: i64, row: i64, text: &str, color: Color) {
        Surface::text(self, column, row, text, color);
    }

    /// A checkerboard of subpixels: every other one, so the wash reads as a
    /// texture — dots in braille, `▚` in quadrants — and a line drawn after it
    /// still shows as the denser path through it. Bounded by the surface and
    /// the clip before iterating, so a far-off span costs nothing.
    fn wash(&mut self, from: (f64, f64), to: (f64, f64), color: Color) {
        if !(from.0.is_finite() && from.1.is_finite() && to.0.is_finite() && to.1.is_finite()) {
            return;
        }
        let (sw, sh) = self.subpixel_size();
        if sw == 0 || sh == 0 {
            return;
        }
        let (mut x0, mut y0, mut x1, mut y1) = (0i64, 0i64, sw as i64 - 1, sh as i64 - 1);
        if let Some((cx0, cy0, cx1, cy1)) = self.clip {
            x0 = x0.max(cx0);
            y0 = y0.max(cy0);
            x1 = x1.min(cx1 - 1);
            y1 = y1.min(cy1 - 1);
        }
        let left = (from.0.min(to.0).round() as i64).max(x0);
        let right = (from.0.max(to.0).round() as i64).min(x1);
        let top = (from.1.min(to.1).round() as i64).max(y0);
        let bottom = (from.1.max(to.1).round() as i64).min(y1);
        for y in top..=bottom {
            for x in left..=right {
                if (x + y) % 2 == 0 {
                    self.set(x, y, color);
                }
            }
        }
    }

    /// Annotations keep the field they land on: same cell snapping and anchor
    /// shifts as the trait contract, placed through [`Surface::annotate`] so a
    /// glyph over patch ink takes the underlying color as its background.
    fn note(&mut self, x: f64, y: f64, cell: (f64, f64), anchor: Anchor, text: &str, color: Color) {
        use unicode_width::UnicodeWidthChar;

        if cell.0 <= 0.0 || cell.1 <= 0.0 {
            return;
        }
        let width: i64 = text
            .chars()
            .map(|glyph| glyph.width().unwrap_or(0) as i64)
            .sum();
        let column = (x / cell.0).round() as i64;
        let start = match anchor {
            Anchor::Start => column,
            Anchor::Middle => column - width / 2,
            Anchor::End => column - width + 1,
        };
        self.annotate(start, (y / cell.1).round() as i64, text, color);
    }

    /// One bar as cell-aligned columns from the zero baseline, with eighth-block
    /// partial fills at the value end (upward bars) or coarse upper-block fills
    /// (downward bars — Unicode has no lower-anchored upper ramp).
    ///
    /// Scales map values onto subpixel *centers*; a bar's ends are edges, so
    /// the ends are stretched from the center range `[0, n − 1]` onto the edge
    /// range `[0, n]` before the fill is quantized — the maximum reaches the
    /// panel's top edge and the baseline its bottom, which at one row is the
    /// difference between a sparkline and half of one.
    fn bar(
        &mut self,
        span: (f64, f64),
        end: f64,
        baseline: f64,
        positive: bool,
        rect: PlotRect,
        color: Color,
    ) {
        let (px, py) = (self.columns, self.rows);
        let ramp = self.charset.fill_ramp();
        let eighths = ramp.len() == 8;
        let mut buffer = [0u8; 4];
        let edge = center_to_edge(rect.rows * py);
        let baseline = edge(baseline) / py as f64;
        let end = edge(end) / py as f64;
        let left = (span.0 / px as f64).round() as i64;
        let right = ((span.1 / px as f64).round() as i64).max(left + 1);
        // Clamp to the plot columns before iterating: a bar whose span maps far
        // off-screen (distant data under a narrow domain) must not spin a giant
        // loop just to have every cell clipped away.
        let left = left.clamp(0, rect.columns as i64);
        let right = right.clamp(0, rect.columns as i64);

        for column in left..right {
            let cell_column = rect.gutter as i64 + column;
            if positive {
                // Upward: full cells from the (snapped-down) baseline, a
                // bottom-anchored partial at the top.
                let bottom = baseline.ceil().min(rect.rows as f64);
                let top = end.max(0.0);
                let mut row = top.floor();
                while row < bottom {
                    let coverage = ((row + 1.0 - top).min(1.0) * 8.0).round() as usize;
                    let glyph: Option<char> = if eighths {
                        (coverage >= 1).then(|| ramp[coverage.min(8) - 1])
                    } else {
                        (coverage >= 4).then(|| ramp[0])
                    };
                    if let Some(glyph) = glyph {
                        Surface::text(
                            self,
                            cell_column,
                            rect.top as i64 + row as i64,
                            glyph.encode_utf8(&mut buffer),
                            color,
                        );
                    }
                    row += 1.0;
                }
            } else {
                // Downward: full cells from the (snapped-up) baseline, a coarse
                // top-anchored partial at the bottom.
                let top = baseline.floor().max(0.0);
                let bottom = end.min(rect.rows as f64);
                let mut row = top;
                while row < bottom.ceil() {
                    let coverage = (bottom - row).min(1.0);
                    let glyph: Option<char> = if !eighths {
                        (coverage >= 0.5).then(|| ramp[0])
                    } else if coverage >= 7.0 / 8.0 {
                        Some('\u{2588}')
                    } else if coverage >= 0.5 {
                        Some('\u{2580}')
                    } else if coverage >= 1.0 / 8.0 {
                        Some('\u{2594}')
                    } else {
                        None
                    };
                    if let Some(glyph) = glyph {
                        Surface::text(
                            self,
                            cell_column,
                            rect.top as i64 + row as i64,
                            glyph.encode_utf8(&mut buffer),
                            color,
                        );
                    }
                    row += 1.0;
                }
            }
        }
    }

    fn bar_horizontal(
        &mut self,
        span: (f64, f64),
        end: f64,
        baseline: f64,
        positive: bool,
        rect: PlotRect,
        color: Color,
    ) {
        let (px, py) = (self.columns, self.rows);
        let ramp = self.charset.fill_ramp_left();
        let eighths = ramp.len() == 8;
        let mut buffer = [0u8; 4];
        let edge = center_to_edge(rect.columns * px);
        let baseline = edge(baseline) / px as f64;
        let end = edge(end) / px as f64;
        // A bar fills the rows whose centers fall inside its span, plus the row
        // chrome gives the span's center (the subpixel rounded, then its cell) —
        // the band label's row. Whenever a band is at least one cell tall the
        // label row is among the sampled rows already; when it is thinner, the
        // bar still lands on its label. Sampling by row centers keeps adjacent
        // bands on distinct rows, which rounding both edges does not. Clamp
        // before iterating, as the vertical fill does.
        let half = (py as f64 - 1.0) / 2.0;
        let center = (span.0 + span.1) / 2.0;
        let center_row = (center.round() as i64).div_euclid(py as i64);
        let first = ((span.0 - half) / py as f64).ceil() as i64;
        let last = ((span.1 - half) / py as f64).ceil() as i64 - 1;
        let (mut top, mut bottom) = (center_row, center_row + 1);
        if first <= last {
            top = top.min(first);
            bottom = bottom.max(last + 1);
        }
        let top = top.clamp(0, rect.rows as i64);
        let bottom = bottom.clamp(0, rect.rows as i64);

        for row in top..bottom {
            let cell_row = rect.top as i64 + row;
            if positive {
                // Rightward: full cells from the (snapped-left) baseline, a
                // left-anchored partial at the end.
                let left = baseline.floor().max(0.0);
                let right = end.min(rect.columns as f64);
                let mut column = left;
                while column < right.ceil() {
                    let coverage = ((right - column).min(1.0) * 8.0).round() as usize;
                    let glyph: Option<char> = if eighths {
                        (coverage >= 1).then(|| ramp[coverage.min(8) - 1])
                    } else {
                        (coverage >= 4).then(|| ramp[0])
                    };
                    if let Some(glyph) = glyph {
                        Surface::text(
                            self,
                            rect.gutter as i64 + column as i64,
                            cell_row,
                            glyph.encode_utf8(&mut buffer),
                            color,
                        );
                    }
                    column += 1.0;
                }
            } else {
                // Leftward: full cells from the (snapped-right) baseline, a coarse
                // right-anchored partial at the end — Unicode has no right eighths.
                let right = baseline.ceil().min(rect.columns as f64);
                let left = end.max(0.0);
                let mut column = left.floor();
                while column < right {
                    let coverage = (column + 1.0 - left).min(1.0);
                    let glyph: Option<char> = if !eighths {
                        (coverage >= 0.5).then(|| ramp[0])
                    } else if coverage >= 7.0 / 8.0 {
                        Some('\u{2588}')
                    } else if coverage >= 0.5 {
                        Some('\u{2590}')
                    } else if coverage >= 1.0 / 8.0 {
                        Some('\u{2595}')
                    } else {
                        None
                    };
                    if let Some(glyph) = glyph {
                        Surface::text(
                            self,
                            rect.gutter as i64 + column as i64,
                            cell_row,
                            glyph.encode_utf8(&mut buffer),
                            color,
                        );
                    }
                    column += 1.0;
                }
            }
        }
    }

    /// The marker crossbar as text: a run of the chrome marker glyph, which reads
    /// over a same-color fill because the glyph differs from the fill texture.
    fn marker(&mut self, sx: f64, half_width: f64, sy: f64, color: Color) {
        let (px, py) = (self.columns as f64, self.rows as f64);
        let row = (sy / py).round() as i64;
        let from_cell = ((sx - half_width) / px).round() as i64;
        let to_cell = ((sx + half_width) / px).round() as i64;
        let glyph = self.charset.chrome().marker;
        for cell in from_cell..=to_cell {
            Surface::text(self, cell, row, glyph, color);
        }
    }

    fn patch_density(&self) -> (usize, usize) {
        if self.charset == Charset::Ascii {
            (1, 1)
        } else {
            (1, 2)
        }
    }

    /// Two vertically adjacent cell samples share a terminal cell: the upper
    /// half-block foreground carries the top color and its background carries the
    /// bottom color. Plain output substitutes an averaged shade-ramp glyph.
    fn patch(&mut self, column: usize, row: usize, rect: PlotRect, sample: Option<(f64, Color)>) {
        let sample = sample.map(|(intensity, color)| (((intensity * 4.0) as u8).min(3), color));
        let cell_column = rect.gutter + column;

        if self.charset == Charset::Ascii {
            if let Some((shade, color)) = sample {
                let glyph = self.charset.shade_ramp()[shade as usize];
                self.place(rect.top + row, cell_column, Text::Glyph(glyph), color);
            }
            return;
        }

        let cell_row = rect.top + row / 2;
        if row.is_multiple_of(2) {
            if let Some((shade, color)) = sample {
                self.place_styled(
                    cell_row,
                    cell_column,
                    Text::Glyph('\u{2580}'),
                    color,
                    Color::Default,
                    PENDING_TOP + shade,
                );
            }
            return;
        }

        let Some(index) = self.cell_index(cell_row, cell_column) else {
            return;
        };
        let pending = self.cells[index]
            .plain_shade
            .checked_sub(PENDING_TOP)
            .filter(|shade| *shade < SHADE_RAMP.len() as u8)
            .map(|shade| (shade, self.cells[index].foreground));
        match (pending, sample) {
            (Some((top_shade, top_color)), Some((bottom_shade, bottom_color))) => {
                let shade = (u16::from(top_shade) + u16::from(bottom_shade)).div_ceil(2) as u8;
                let (glyph, foreground, background) = if top_color == bottom_color {
                    ('\u{2588}', top_color, Color::Default)
                } else {
                    ('\u{2580}', top_color, bottom_color)
                };
                self.place_styled(
                    cell_row,
                    cell_column,
                    Text::Glyph(glyph),
                    foreground,
                    background,
                    shade,
                );
            }
            (Some((top_shade, _)), None) => self.cells[index].plain_shade = top_shade,
            (None, Some((bottom_shade, bottom_color))) => self.place_styled(
                cell_row,
                cell_column,
                Text::Glyph('\u{2584}'),
                bottom_color,
                Color::Default,
                bottom_shade,
            ),
            (None, None) => {}
        }
    }
}

/// The map from a scale's subpixel-center range `[0, n − 1]` onto the edge
/// range `[0, n]` of the same `n` subpixels — what a fill's ends want.
fn center_to_edge(subpixels: usize) -> impl Fn(f64) -> f64 {
    let n = subpixels as f64;
    move |center: f64| {
        if n > 1.0 {
            center * n / (n - 1.0)
        } else {
            center
        }
    }
}

impl std::fmt::Debug for Surface {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Surface")
            .field("width", &self.width)
            .field("height", &self.height)
            .field("charset", &self.charset)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
#[path = "tests/surface_tests.rs"]
mod tests;