termzzz 0.0.2

Screen savers and visual effects for terminal
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
//! A dot grid at 2x4 sub-cell resolution, encoded into braille characters.
//!
//! One terminal cell holds eight braille dots, so a full-screen braille grid
//! carries 8x the density of a character grid: 2 across, 4 down. That is the
//! cheapest resolution win available, and it needs no change to
//! [`crate::buffer::Cell`] -- a braille cell is one glyph in one colour, which
//! is exactly what a cell already is.
//!
//! The trade is colour. All eight dots in a cell share the cell's foreground
//! colour, so braille carries *density* and not *hue*. An effect that wants
//! smooth colour wants [`super::halfblock`] instead, which gives up half the
//! vertical resolution for two colours per cell.
//!
//! # Coordinate systems
//!
//! Two, and confusing them is the usual bug:
//!
//! - *dot* coordinates run `0..2*width` by `0..4*height`, and are what
//!   [`BrailleGrid::set_dot`] takes.
//! - *cell* coordinates run `0..width` by `0..height`, and are what
//!   [`Canvas::set`] takes.
//!
//! [`BrailleGrid::write_to`] is the only place the two meet.

use crate::buffer::Cell;
use crate::canvas::Canvas;
use crossterm::style::{self, Attribute, Color};

/// Dots across per cell.
pub const DOTS_X: usize = 2;
/// Dots down per cell.
pub const DOTS_Y: usize = 4;
/// Dots per cell, and so the number of bits in one cell's pattern.
pub const DOTS_PER_CELL: usize = DOTS_X * DOTS_Y;

/// First codepoint of the Unicode braille block. Every pattern is this plus the
/// cell's bit mask.
const BRAILLE_BASE: u32 = 0x2800;

/// A grid of braille patterns, addressable by dot.
#[derive(Clone)]
pub struct BrailleGrid {
    width: usize,
    height: usize,
    /// One byte of dot bits per cell, row-major.
    dots: Vec<u8>,
}

impl BrailleGrid {
    /// An all-blank grid of `width` by `height` cells.
    ///
    /// Both dimensions are floored at 1, because a cell with no dots has no
    /// coordinates to address.
    pub fn new(width: usize, height: usize) -> Self {
        let (width, height) = (width.max(1), height.max(1));
        Self {
            width,
            height,
            dots: vec![0; width * height],
        }
    }

    /// Width in cells.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Height in cells.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Width in dots.
    pub fn dot_width(&self) -> usize {
        self.width * DOTS_X
    }

    /// Height in dots.
    pub fn dot_height(&self) -> usize {
        self.height * DOTS_Y
    }

    /// Blanks every dot.
    pub fn clear(&mut self) {
        self.dots.fill(0);
    }

    /// Resizes, discarding the contents.
    pub fn resize(&mut self, width: usize, height: usize) {
        let (width, height) = (width.max(1), height.max(1));
        if (width, height) == (self.width, self.height) {
            return;
        }
        *self = Self::new(width, height);
    }

    /// Raises or lowers a single dot.
    ///
    /// Coordinates outside the grid are ignored. A line rasteriser walking
    /// diagonally will step outside briefly at the edges, and dropping those
    /// dots is the correct result rather than an error.
    #[inline]
    pub fn set_dot(&mut self, dot_x: usize, dot_y: usize, raised: bool) {
        let Some(index) = self.cell_index(dot_x, dot_y) else {
            return;
        };
        let bit = 1u8 << Self::dot_index(dot_x, dot_y);
        if raised {
            self.dots[index] |= bit;
        } else {
            self.dots[index] &= !bit;
        }
    }

    #[inline]
    pub fn raise_dot(&mut self, dot_x: usize, dot_y: usize) {
        self.set_dot(dot_x, dot_y, true);
    }

    #[inline]
    pub fn lower_dot(&mut self, dot_x: usize, dot_y: usize) {
        self.set_dot(dot_x, dot_y, false);
    }

    /// Whether a dot is raised. Out-of-grid reads as lowered.
    #[inline]
    pub fn dot(&self, dot_x: usize, dot_y: usize) -> bool {
        let Some(index) = self.cell_index(dot_x, dot_y) else {
            return false;
        };
        self.dots[index] & (1u8 << Self::dot_index(dot_x, dot_y)) != 0
    }

    /// The character for one cell, or a space when the cell is blank.
    pub fn cell_char(&self, cell_x: usize, cell_y: usize) -> char {
        if cell_x >= self.width || cell_y >= self.height {
            return ' ';
        }
        let bits = self.dots[cell_y * self.width + cell_x];
        if bits == 0 {
            // U+2800 is the blank pattern, but a space is one byte narrower on
            // the wire and every terminal renders it identically.
            return ' ';
        }
        char::from_u32(BRAILLE_BASE + bits as u32).unwrap_or('?')
    }

    /// The raw bit pattern for one cell, for callers assembling their own glyph.
    pub fn cell_bits(&self, cell_x: usize, cell_y: usize) -> u8 {
        if cell_x >= self.width || cell_y >= self.height {
            return 0;
        }
        self.dots[cell_y * self.width + cell_x]
    }

    /// Calls `f(dot_x, dot_y, raised)` for every dot, row-major.
    pub fn for_each_dot(&self, mut f: impl FnMut(usize, usize, bool)) {
        for cell_y in 0..self.height {
            for cell_x in 0..self.width {
                let bits = self.dots[cell_y * self.width + cell_x];
                for sub in 0..DOTS_PER_CELL {
                    let (dx, dy) = Self::dot_position(sub);
                    f(
                        cell_x * DOTS_X + dx,
                        cell_y * DOTS_Y + dy,
                        bits & (1u8 << sub) != 0,
                    );
                }
            }
        }
    }

    /// Writes the grid into a canvas, one cell per braille glyph.
    ///
    /// Every cell gets the same colour, because a braille cell cannot carry
    /// two: the dots are a single glyph.
    pub fn write_to(&self, canvas: &mut Canvas, color: Color, attr: Attribute) {
        for cell_y in 0..self.height.min(canvas.height()) {
            for cell_x in 0..self.width.min(canvas.width()) {
                let symbol = self.cell_char(cell_x, cell_y);
                canvas.set(cell_x, cell_y, Cell::new(symbol, color, attr));
            }
        }
    }

    /// Writes the grid, leaving cells that are blank untouched.
    ///
    /// For an effect that composites braille over something else already on the
    /// canvas. A blank braille cell is a space, and painting it would erase
    /// whatever is underneath.
    pub fn overlay_onto(&self, canvas: &mut Canvas, color: Color, attr: Attribute) {
        for cell_y in 0..self.height.min(canvas.height()) {
            for cell_x in 0..self.width.min(canvas.width()) {
                let symbol = self.cell_char(cell_x, cell_y);
                if symbol == ' ' {
                    continue;
                }
                canvas.set(cell_x, cell_y, Cell::new(symbol, color, attr));
            }
        }
    }

    /// Lifts dots from a scalar field, comparing against a threshold that
    /// varies per dot so a gradient survives as intermediate density.
    ///
    /// `values` is row-major over the *dot* grid and is read with clamping, so
    /// a field sized for cells rather than dots still produces a picture rather
    /// than a panic.
    pub fn draw_field(
        &mut self,
        values: &[f32],
        threshold: f32,
        spread: f32,
        dither: super::dither::Dither,
    ) {
        let (dw, dh) = (self.dot_width(), self.dot_height());
        for dot_y in 0..dh {
            for dot_x in 0..dw {
                let index = dot_y * dw + dot_x;
                let value = values.get(index).copied().unwrap_or(0.0);
                // The dither offset turns one hard threshold into a moving
                // boundary, so values within `spread` of the threshold land on
                // a stable fraction of the dots instead of all-or-nothing.
                let jitter = (dither.at(dot_x, dot_y) - 0.5) * spread;
                self.set_dot(dot_x, dot_y, value > threshold + jitter);
            }
        }
    }

    #[inline]
    fn cell_index(&self, dot_x: usize, dot_y: usize) -> Option<usize> {
        if dot_x >= self.dot_width() || dot_y >= self.dot_height() {
            return None;
        }
        let cell_x = dot_x / DOTS_X;
        let cell_y = dot_y / DOTS_Y;
        Some(cell_y * self.width + cell_x)
    }

    /// Which bit a dot occupies within its cell.
    ///
    /// The Unicode braille block is **not** row-major. Its dots are numbered in
    /// two columns of three and then a detached bottom row:
    ///
    /// ```text
    /// bit 0  bit 3      1 4
    /// bit 1  bit 4      2 5
    /// bit 2  bit 5      3 6
    /// bit 6  bit 7      7 8
    /// ```
    ///
    /// Bits 0-2 walk *down* the left column, 3-5 walk down the right, and 6-7
    /// are the bottom row. Reading it as `row * 2 + col` puts four of the eight
    /// dots on the wrong bit, which produces a pattern of the right density and
    /// the wrong shape: a horizontal run of two dots renders as a vertical pair,
    /// and the two halves of every cell are drawn from different source rows.
    ///
    /// This was wrong for the whole life of the module and no test could see it,
    /// because every test round-tripped through [`BrailleGrid::dot_position`],
    /// which was wrong in exactly the matching way. A round trip through a
    /// permutation only proves the permutation is an involution on its own
    /// image; it says nothing about where the image belongs. The tests below pin
    /// the *physical* layout instead -- a named codepoint for a named dot column
    /// -- and they are written out rather than looped, because the expectation
    /// has to be external to this function for the assertion to mean anything.
    #[inline]
    fn dot_index(dot_x: usize, dot_y: usize) -> usize {
        let (dx, dy) = (dot_x % DOTS_X, dot_y % DOTS_Y);
        // Three rows carry the two columns (bits 0-2 and 3-5); the fourth is the
        // detached bottom row (bits 6-7). Both counts fall out of DOTS_Y - 1, and
        // getting either wrong silently misplaces dots rather than failing.
        let main_rows = DOTS_Y - 1;
        if dy == main_rows {
            DOTS_X * main_rows + dx
        } else {
            dy + main_rows * dx
        }
    }

    /// The inverse of [`BrailleGrid::dot_index`].
    #[inline]
    fn dot_position(index: usize) -> (usize, usize) {
        let main_rows = DOTS_Y - 1;
        if index < DOTS_X * main_rows {
            (index / main_rows, index % main_rows)
        } else {
            (index - DOTS_X * main_rows, main_rows)
        }
    }
}

/// The bit a dot occupies within its cell's pattern, as `1 << index`.
///
/// The block's layout is `1 4 / 2 5 / 3 6 / 7 8`, so it is **not** row-major;
/// see [`BrailleGrid`] for why that is easy to get wrong and hard to notice.
///
/// A caller assembling a cell's own glyph from its own geometry wants this, and
/// should call it rather than restate the mapping. Three places in the crate did
/// restate it, and they disagreed with the grid they were checking against -- so
/// the tests using them reported the *effects* as broken instead of noticing
/// that the expectation and the implementation were two different functions.
#[inline]
pub fn braille_bit(dot_x: usize, dot_y: usize) -> u8 {
    1u8 << BrailleGrid::dot_index(dot_x, dot_y)
}

/// The `(dot_x, dot_y)` a bit index names -- the inverse of [`braille_bit`].
///
/// Exposed for the same reason as [`braille_bit`]: a caller that reads a cell's
/// pattern back out as a set of dots needs the layout in the other direction,
/// and one test in this crate carried a hand-written copy of it with the bottom
/// two dots transposed.
#[inline]
pub fn braille_dot_position(index: usize) -> (usize, usize) {
    BrailleGrid::dot_position(index)
}

/// The colour a braille grid is written in when nothing else is specified.
pub fn default_color() -> Color {
    style::Color::White
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_blank_grid_is_spaces() {
        let grid = BrailleGrid::new(4, 3);
        for y in 0..3 {
            for x in 0..4 {
                assert_eq!(grid.cell_char(x, y), ' ');
            }
        }
    }

    #[test]
    fn dot_dimensions_are_eight_times_the_cells() {
        let grid = BrailleGrid::new(10, 5);
        assert_eq!(grid.dot_width(), 20);
        assert_eq!(grid.dot_height(), 20);
        assert_eq!(grid.dot_width() * grid.dot_height(), 10 * 5 * 8);
    }

    #[test]
    fn the_first_dot_is_the_top_left_of_the_pattern() {
        // U+2801 is dot 1 alone: the top-left dot of the cell.
        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(0, 0);
        assert_eq!(grid.cell_char(0, 0), '\u{2801}');

        // U+2880 is dot 8 alone: the bottom-right, which is bit 7 rather than
        // bit 3. The block numbers down a column before moving right, so the
        // last dot of a cell lands high in the byte, not next to U+2801.
        // (U+2888 is dots 4 and 8 together, which is an easy thing to reach for
        // by mistake.)
        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(1, 3);
        assert_eq!(grid.cell_char(0, 0), '\u{2880}');
    }

    #[test]
    fn every_dot_maps_to_its_own_unicode_pattern() {
        // The whole point of the bit layout: each of the eight dots alone is a
        // distinct codepoint, U+2801 through U+2808.
        //
        // This cannot fail for a permutation error -- it walks the bit indices
        // through `dot_position` and expects `1 << sub` back, which holds for
        // any self-consistent pair. `each_dot_is_the_codepoint_the_block_names_
        // for_it` below is the one that carries the layout.
        for sub in 0..DOTS_PER_CELL {
            let (dx, dy) = BrailleGrid::dot_position(sub);
            let mut grid = BrailleGrid::new(1, 1);
            grid.raise_dot(dx, dy);
            let expected = char::from_u32(0x2800 + (1u32 << sub)).unwrap();
            assert_eq!(
                grid.cell_char(0, 0),
                expected,
                "dot {sub} at ({dx},{dy}) encoded wrongly"
            );
        }
    }

    /// The layout, pinned to *named* codepoints rather than to
    /// [`BrailleGrid::dot_position`].
    ///
    /// `U+2807` is DOTS-1-2-3, the left-hand column of the top three rows, and
    /// it is a different glyph from `U+2801 | U+2802 | U+2804` under any reading
    /// of the block. The left column and the right column of a cell are also
    /// different glyphs from each other, which is exactly what a row-major
    /// `dy * 2 + dx` collapses into one.
    #[test]
    fn a_dot_column_is_the_codepoint_for_that_column() {
        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(0, 0);
        grid.raise_dot(0, 1);
        grid.raise_dot(0, 2);
        assert_eq!(
            grid.cell_char(0, 0),
            '\u{2807}',
            "the left column is not DOTS-123"
        );

        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(1, 0);
        grid.raise_dot(1, 1);
        grid.raise_dot(1, 2);
        assert_eq!(
            grid.cell_char(0, 0),
            '\u{2838}',
            "the right column is not DOTS-456"
        );
    }

    /// A run of dots across the top of a cell is dots 1 and 4 -- the two dots a
    /// reader sees as a horizontal stroke -- and the block spells that as bits 0
    /// and 3. Under `dy * 2 + dx` it came out as bits 0 and 1, which is dots 1
    /// and 2 and renders as a *vertical* pair, so a horizontal stroke in an
    /// effect's source art turned into a vertical one on screen.
    #[test]
    fn a_horizontal_run_is_the_two_top_dots() {
        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(0, 0);
        grid.raise_dot(1, 0);
        assert_eq!(
            grid.cell_char(0, 0),
            '\u{2809}',
            "the top row is not DOTS-14"
        );

        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(0, 1);
        grid.raise_dot(1, 1);
        assert_eq!(
            grid.cell_char(0, 0),
            '\u{2812}',
            "the second row is not DOTS-25"
        );
    }

    /// Every single dot, by the codepoint the block names for it.
    ///
    /// Dot `n` in the block's own numbering is codepoint `0x2800 + (1 << (n-1))`,
    /// and the block's numbering is `1 4 / 2 5 / 3 6 / 7 8`. Written out rather
    /// than looped, because the whole value of this test is that the expectation
    /// comes from outside this module.
    #[test]
    fn each_dot_is_the_codepoint_the_block_names_for_it() {
        const CASES: [(usize, usize, u32); 8] = [
            (0, 0, 0x2801), // dot 1  top-left
            (0, 1, 0x2802), // dot 2  middle-left
            (0, 2, 0x2804), // dot 3  bottom-left
            (1, 0, 0x2808), // dot 4  top-right
            (1, 1, 0x2810), // dot 5  middle-right
            (1, 2, 0x2820), // dot 6  bottom-right
            (0, 3, 0x2840), // dot 7  bottom row, left
            (1, 3, 0x2880), // dot 8  bottom row, right
        ];
        for (dx, dy, codepoint) in CASES {
            let mut grid = BrailleGrid::new(1, 1);
            grid.raise_dot(dx, dy);
            assert_eq!(
                grid.cell_char(0, 0),
                char::from_u32(codepoint).unwrap(),
                "dot ({dx},{dy}) is not U+{codepoint:04X}"
            );
        }
    }

    /// The bottom row is detached, which is the part a "two columns of four"
    /// reading cannot express.
    ///
    /// Dots 7 and 8 sit *below* dots 3 and 6 rather than continuing their
    /// columns, so the cell is 3+3+1+1 in row order and not 2+2+2+2. A layout
    /// that assumed four even rows would put the bottom two dots in the wrong
    /// columns, and the glyph would still have the right number of dots raised.
    #[test]
    fn the_bottom_row_is_detached_from_the_columns() {
        // Dots 7 and 8 alone.
        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(0, 3);
        grid.raise_dot(1, 3);
        assert_eq!(
            grid.cell_char(0, 0),
            '\u{28c0}',
            "the bottom row is not DOTS-78"
        );

        // Dots 3 and 6 are the bottoms of the two columns; dots 7 and 8 sit
        // below them. All four is a different glyph from either pair alone.
        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(0, 2);
        grid.raise_dot(1, 2);
        grid.raise_dot(0, 3);
        grid.raise_dot(1, 3);
        assert_eq!(grid.cell_char(0, 0), '\u{28e4}', "dots 3, 6, 7 and 8");
    }

    #[test]
    fn all_eight_dots_make_the_full_block() {
        // U+28FF is every dot raised.
        let mut grid = BrailleGrid::new(1, 1);
        for dy in 0..DOTS_Y {
            for dx in 0..DOTS_X {
                grid.raise_dot(dx, dy);
            }
        }
        assert_eq!(grid.cell_char(0, 0), '\u{28ff}');
    }

    #[test]
    fn dots_in_different_cells_do_not_merge() {
        let mut grid = BrailleGrid::new(2, 1);
        grid.raise_dot(0, 0);
        grid.raise_dot(2, 0); // cell 1, its left dot

        assert_eq!(grid.cell_char(0, 0), '\u{2801}');
        assert_eq!(grid.cell_char(1, 0), '\u{2801}');
    }

    #[test]
    fn lowering_a_dot_clears_only_that_bit() {
        let mut grid = BrailleGrid::new(1, 1);
        grid.raise_dot(0, 0); // dot 1, bit 0
        grid.raise_dot(1, 0); // dot 4, bit 3
        grid.lower_dot(0, 0);
        assert_eq!(grid.cell_char(0, 0), '\u{2808}');
    }

    /// `raise_dot` and `dot` must agree, because an effect that rasterises into
    /// a grid and an effect that reads it back are otherwise free to disagree.
    #[test]
    fn reading_a_dot_back_matches_writing_it() {
        for dy in 0..DOTS_Y {
            for dx in 0..DOTS_X {
                let mut grid = BrailleGrid::new(1, 1);
                grid.raise_dot(dx, dy);
                assert!(grid.dot(dx, dy), "dot ({dx},{dy}) did not read back");
                // And the dot's own bit is the one the cell carries.
                assert_eq!(
                    grid.cell_bits(0, 0),
                    braille_bit(dx, dy),
                    "dot ({dx},{dy}) landed on the wrong bit"
                );
            }
        }
    }

    #[test]
    fn dots_outside_the_grid_are_ignored_rather_than_panicking() {
        let mut grid = BrailleGrid::new(2, 2); // 4x8 dots
        grid.raise_dot(4, 0);
        grid.raise_dot(0, 8);
        grid.raise_dot(usize::MAX, usize::MAX);
        assert!(!grid.dot(4, 0));
        assert!(!grid.dot(usize::MAX, 0));
    }

    #[test]
    fn for_each_dot_visits_every_dot_once() {
        let grid = BrailleGrid::new(3, 2);
        let mut seen = Vec::new();
        grid.for_each_dot(|x, y, _| seen.push((x, y)));
        assert_eq!(seen.len(), 3 * 2 * 8);
        let mut unique = seen.clone();
        unique.sort_unstable();
        unique.dedup();
        assert_eq!(unique.len(), seen.len(), "a dot was visited twice");
    }

    #[test]
    fn writing_produces_one_cell_per_braille_glyph() {
        let mut grid = BrailleGrid::new(3, 2);
        grid.raise_dot(5, 7);

        let mut canvas = Canvas::new(3, 2);
        canvas.clear();
        grid.write_to(&mut canvas, Color::Red, Attribute::Bold);

        assert_eq!(canvas.get(2, 1).symbol, '\u{2880}');
        assert_eq!(canvas.get(2, 1).color, Color::Red);
        assert_eq!(canvas.get(0, 0).symbol, ' ');
    }

    #[test]
    fn overlaying_leaves_blank_cells_alone() {
        let mut grid = BrailleGrid::new(2, 1);
        grid.raise_dot(0, 0);

        let mut canvas = Canvas::new(2, 1);
        canvas.clear();
        canvas.set(1, 0, Cell::new('X', Color::Blue, Attribute::Reset));

        grid.overlay_onto(&mut canvas, Color::Red, Attribute::Reset);

        assert_eq!(canvas.get(0, 0).symbol, '\u{2801}');
        assert_eq!(
            canvas.get(1, 0).symbol,
            'X',
            "a blank braille cell painted over what was underneath"
        );
    }

    #[test]
    fn a_field_above_the_threshold_lifts_the_dot() {
        let mut grid = BrailleGrid::new(1, 1);
        let values = vec![1.0; 8];
        grid.draw_field(&values, 0.5, 0.0, super::super::dither::Dither::None);
        assert_eq!(grid.cell_char(0, 0), '\u{28ff}');
    }

    #[test]
    fn a_field_below_the_threshold_lifts_nothing() {
        let mut grid = BrailleGrid::new(1, 1);
        let values = vec![0.0; 8];
        grid.draw_field(&values, 0.5, 0.0, super::super::dither::Dither::None);
        assert_eq!(grid.cell_char(0, 0), ' ');
    }

    #[test]
    fn a_short_field_is_read_with_clamping_not_a_panic() {
        // A field sized for cells rather than dots is a plausible mistake, and
        // it should still draw rather than index past the end.
        let mut grid = BrailleGrid::new(4, 4); // 8x16 dots = 128 entries
        grid.draw_field(&[1.0; 16], 0.5, 0.0, super::super::dither::Dither::None);
        // The first 16 dots came from the field, the rest defaulted to 0.
        assert!(grid.dot(0, 0));
        assert!(!grid.dot(7, 15));
    }

    #[test]
    fn resizing_to_the_same_size_keeps_the_dots() {
        let mut grid = BrailleGrid::new(2, 2);
        grid.raise_dot(1, 1);
        grid.resize(2, 2);
        assert!(grid.dot(1, 1));
    }
}