rs-rich-ext 0.0.21

Extensions for the `rich` Rust port: diagnostics, structured data, clap and tracing integration, diffs, workflow renderables and a plugin registry
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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! Positioned drawing: render any rich renderable into a rectangle of the
//! terminal, and write only the cells that changed.
//!
//! A [`Surface`] keeps a [`Screen`] of cells between frames. Each
//! [`draw`](Surface::draw) hands a [`Drawing`] to a closure that renders
//! into rectangles of it; the surface then writes what changed inside those
//! rectangles and nothing else, so a clock ticking in one corner sends a few
//! bytes rather than the whole screen. It is the drawing half of
//! `rs-rich-intuituive`, which builds on the same [`Screen`] and [`Painter`],
//! without the widget tree or the event loop: input stays yours.
//!
//! ```
//! use rich::Text;
//! use rich_ext::surface::{Rect, Surface};
//!
//! let mut surface = Surface::new(Vec::new(), 20, 2);
//! surface
//!     .draw(|s| {
//!         s.render(Rect::new(0, 0, 20, 1), &Text::new("tick 1"));
//!     })
//!     .unwrap();
//! surface.writer_mut().clear();
//! surface
//!     .draw(|s| {
//!         s.render(Rect::new(0, 0, 20, 1), &Text::new("tick 2"));
//!     })
//!     .unwrap();
//! // One cell changed: move there and write it.
//! let out = String::from_utf8(surface.writer().clone()).unwrap();
//! assert_eq!(out, "\x1b[1;6H\x1b[0m2");
//! ```
//!
//! The surface fills the terminal on the alternate screen
//! ([`Viewport::Fullscreen`], the default), or takes a fixed number of rows
//! below the cursor and leaves the scrollback alone ([`Viewport::Inline`]).
//! A [`resize`](Surface::resize) keeps what was drawn and writes everything
//! once. Graphics (micro assets drawn with Kitty, iTerm2 or Sixel) come
//! through a [`PlacementSource`], as they do for [`frame`](crate::frame)s.

mod screen;

use std::io::{self, Write};
use std::sync::Arc;

use rich::{Console, ConsoleOptions, Renderable, Segment};

use crate::frame::{Change, Frame, Placement, PlacementSource, plan_graphics};

pub(crate) use screen::char_width;
pub use screen::{Cell, PaintStats, PaintStrategy, Painter, Rect, Screen, TextRun};

/// Drawing straight into a [`Screen`]'s cells: rs-rich-ext's fast path.
///
/// rich renders to [`Segment`]s, each owning its text and a [`Style`]
/// (whose colours own their names), and a [`Screen`] turns those back into
/// cells. rich's path is the faithful one, and stays the reference: rich's
/// public types are unchanged. A renderable that also implements `Draw`
/// writes the same cells without building them: its own data goes into
/// the screen's cells with each style interned once
/// ([`Screen::write_runs`], [`Screen::put_rgb`], [`Screen::put`]).
/// rs-rich-ext's charts implement it, and intuiTUIve draws with it by
/// default.
///
/// rich's path is [`draw_rendered`]: render, then [`Screen::write_lines`].
/// An implementation must give the same cells as it (the tests compare the
/// two for every chart that has one).
///
/// ```
/// use rich::Console;
/// use rich_ext::chart::{Dataset, Chart};
/// use rich_ext::surface::{Draw, Rect, Screen};
///
/// let console = Console::builder().width(30).build();
/// let options = console.options().update_width(30).update_height(8);
/// let chart = Chart::new([Dataset::new([(0.0, 0.0), (1.0, 1.0), (2.0, 0.5)])]);
/// let rect = Rect::new(0, 0, 30, 8);
///
/// let mut fast = Screen::new(30, 8);
/// chart.draw(&console, &options, &mut fast, rect);
///
/// let mut rich_path = Screen::new(30, 8);
/// rich_path.write_lines(rect, &console.render_lines(&chart, &options, false));
/// assert_eq!(fast.lines(), rich_path.lines());
/// ```
pub trait Draw: Renderable {
    /// Draw into `rect` of `screen`, rendered with `options` (its width and
    /// height are the rectangle's): the cells `screen.write_lines(rect,
    /// &console.render_lines(self, options, false))` would give.
    fn draw(&self, console: &Console, options: &ConsoleOptions, screen: &mut Screen, rect: Rect);
}

/// rich's path, the reference [`Draw`] is held to: `renderable` rendered
/// with `options`, its lines written into `rect` of `screen`.
pub fn draw_rendered(
    console: &Console,
    renderable: &dyn Renderable,
    options: &ConsoleOptions,
    screen: &mut Screen,
    rect: Rect,
) {
    let lines = console.render_lines(renderable, options, false);
    screen.write_lines(rect, &lines);
}

/// Begins a synchronized update (DEC private mode 2026): the terminal holds
/// the screen until [`END_SYNCHRONIZED_UPDATE`].
pub const BEGIN_SYNCHRONIZED_UPDATE: &str = "\x1b[?2026h";
/// Ends a synchronized update: the terminal shows what was written since
/// [`BEGIN_SYNCHRONIZED_UPDATE`] in one go.
pub const END_SYNCHRONIZED_UPDATE: &str = "\x1b[?2026l";

/// The visible stand-in for a terminal control, or `None` for any other
/// character. One character for one, in the style of
/// [`sanitize_terminal_controls`](crate::sanitize_terminal_controls): C0
/// controls as their control pictures (`␛`, `␇`), DEL as `␡`, a tab as a
/// space (it would move the cursor), and C1 controls (8-bit CSI and OSC
/// among them) as `�`.
pub fn control_picture(c: char) -> Option<char> {
    match c {
        '\t' => Some(' '),
        '\u{1b}' => Some('␛'),
        '\u{7f}' => Some('␡'),
        '\0'..='\u{1f}' => char::from_u32(0x2400 + c as u32),
        '\u{80}'..='\u{9f}' => Some('\u{fffd}'),
        _ => None,
    }
}

/// Make the terminal controls in `line`'s text visible, so nothing drawn
/// can drive the terminal: styles are already [`Style`](rich::Style)s, and
/// whatever is left in the text would otherwise reach it raw. Each control
/// becomes one character (see [`control_picture`]), so character offsets
/// into the text still hold. Control segments are left alone; frames skip
/// them.
pub fn sanitize_line(line: &mut [Segment]) {
    for segment in line.iter_mut().filter(|segment| !segment.control) {
        if segment.text.chars().any(|c| control_picture(c).is_some()) {
            segment.text = segment
                .text
                .chars()
                .map(|c| control_picture(c).unwrap_or(c))
                .collect();
        }
    }
}

/// Where a [`Surface`] draws.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Viewport {
    /// The whole terminal, on the alternate screen: what was there before
    /// comes back when the surface finishes.
    #[default]
    Fullscreen,
    /// This many rows from the cursor's row down, scrolling the terminal if
    /// they pass its bottom. The rows above (the shell's scrollback) are
    /// left alone, and the last frame stays on screen when the surface
    /// finishes, with the cursor below it.
    Inline(u16),
}

/// A drawing handle on the terminal: a screen of cells kept between frames,
/// the painter that writes the difference, and where it writes. See the
/// [module docs](self).
pub struct Surface<W: Write> {
    writer: W,
    console: Console,
    screen: Screen,
    painter: Painter,
    viewport: Viewport,
    synchronized: bool,
    started: bool,
    finished: bool,
    cursor_shown: bool,
    /// The next draw writes every cell.
    full: bool,
    graphics: Option<Arc<dyn PlacementSource>>,
    placements: Vec<Placement>,
    /// [`paint_strategy`](Surface::paint_strategy), when chosen.
    strategy: Option<PaintStrategy>,
    /// [`terminal_scroll`](Surface::terminal_scroll), when chosen.
    terminal_scroll: Option<bool>,
    /// `TMUX` was set when the surface was made.
    under_tmux: bool,
}

impl Surface<io::Stdout> {
    /// A surface on standard output, as large as the terminal (inline, as
    /// wide as it), with the colours `Console::new()` detects.
    pub fn stdout(viewport: Viewport) -> Surface<io::Stdout> {
        let console = Console::new();
        let size = console.size();
        let width = clamp(size.width);
        let height = match viewport {
            Viewport::Fullscreen => clamp(size.height),
            // No taller than the terminal: relative moves stop at its edges.
            Viewport::Inline(rows) => rows.min(clamp(size.height)),
        };
        Surface::new(io::stdout(), width, height)
            .viewport(viewport)
            .console(console)
    }
}

impl<W: Write> Surface<W> {
    /// A full-screen surface of `width` by `height` cells writing to
    /// `writer`, in truecolor. [`console`](Self::console) sets the colours
    /// and how renderables are rendered. It paints with
    /// [`PaintStrategy::Best`] unless [`paint_strategy`](Self::paint_strategy)
    /// or `RICH_PAINT_STRATEGY` says otherwise.
    pub fn new(writer: W, width: u16, height: u16) -> Surface<W> {
        let console = Console::builder()
            .width(width.max(1) as usize)
            .height(height.max(1) as usize)
            .force_terminal(true)
            .color_system(Some(rich::ColorSystem::Truecolor))
            .build();
        let system = console.color_system();
        Surface {
            writer,
            console,
            screen: Screen::new(width, height),
            painter: Painter::new(system),
            viewport: Viewport::Fullscreen,
            synchronized: false,
            started: false,
            finished: false,
            cursor_shown: true,
            full: true,
            graphics: None,
            placements: Vec::new(),
            strategy: None,
            terminal_scroll: None,
            under_tmux: std::env::var_os("TMUX").is_some(),
        }
        .configured()
    }

    /// The painter set up as the surface asks: its strategy, and whether it
    /// may scroll (not on Windows, nor under tmux, unless
    /// [`terminal_scroll`](Self::terminal_scroll) says so; an inline
    /// painter never does).
    fn configured(mut self) -> Surface<W> {
        self.painter.set_strategy(
            self.strategy
                .or_else(PaintStrategy::from_env)
                .unwrap_or_default(),
        );
        // tmux redraws a scrolled region itself, so moving rows there saves
        // little; as intuiTUIve's apps, the surface paints there instead.
        let scroll = self
            .terminal_scroll
            .unwrap_or(!cfg!(windows) && !self.under_tmux);
        self.painter.set_scroll(scroll);
        self
    }

    /// How each frame's changes become bytes (see [`PaintStrategy`]):
    /// [`Best`](PaintStrategy::Best) by default, or what the
    /// `RICH_PAINT_STRATEGY` environment variable names (`cells`, `rows`,
    /// `full`, `scroll` or `best`) when the surface does not choose. `best`
    /// scrolls rows that moved and otherwise paints cells. Scrolling is off
    /// on Windows, under tmux, inline and over graphics, and
    /// [`terminal_scroll`](Self::terminal_scroll) overrides it. Every
    /// strategy shows the same screen.
    ///
    /// ```
    /// use rich::Text;
    /// use rich_ext::surface::{PaintStrategy, Rect, Surface};
    ///
    /// let mut surface = Surface::new(Vec::new(), 10, 1).paint_strategy(PaintStrategy::Full);
    /// surface
    ///     .draw(|s| s.render(Rect::new(0, 0, 10, 1), &Text::new("hello")))
    ///     .unwrap();
    /// assert_eq!(surface.screen().plain()[0].trim_end(), "hello");
    /// ```
    #[must_use]
    pub fn paint_strategy(mut self, strategy: PaintStrategy) -> Surface<W> {
        self.strategy = Some(strategy);
        self.configured()
    }

    /// Whether [`PaintStrategy::Scroll`] and [`PaintStrategy::Best`] may
    /// move rows with the terminal's own scrolling. Unset, it is on, but
    /// off on Windows (whose consoles have been seen to scroll the wrong
    /// rows) and under tmux; set, it holds wherever the surface runs. An
    /// inline surface never scrolls.
    #[must_use]
    pub fn terminal_scroll(mut self, on: bool) -> Surface<W> {
        self.terminal_scroll = Some(on);
        self.configured()
    }

    /// Draw inline or full screen. An inline viewport's row count replaces
    /// the surface's height, up to that height (the terminal's).
    #[must_use]
    pub fn viewport(mut self, viewport: Viewport) -> Surface<W> {
        self.viewport = viewport;
        if let Viewport::Inline(rows) = viewport {
            // The surface's height is the terminal's: a region taller than
            // that would lose rows at its edges.
            let area = self.screen.area();
            self.screen = Screen::new(area.width, rows.min(area.height.max(1)));
        }
        let system = self.console.color_system();
        self.painter = match viewport {
            Viewport::Fullscreen => Painter::new(system),
            Viewport::Inline(_) => Painter::new(system).inline(),
        };
        self.full = true;
        self.configured()
    }

    /// Render with `console`: its colour system is the one written (`None`
    /// writes no colour at all), and its theme and highlighting apply.
    #[must_use]
    pub fn console(mut self, console: Console) -> Surface<W> {
        self.painter.set_color_system(console.color_system());
        self.console = console;
        self
    }

    /// Write each frame as one synchronized update (DEC private mode 2026),
    /// which a terminal that has it shows whole and one that does not
    /// ignores (off by default).
    #[must_use]
    pub fn synchronized(mut self, on: bool) -> Surface<W> {
        self.synchronized = on;
        self
    }

    /// Draw the graphics `source` places on the screen's cells, after the
    /// cells, and redraw them when the cells under them are repainted.
    #[must_use]
    pub fn graphics(mut self, source: Option<Arc<dyn PlacementSource>>) -> Surface<W> {
        self.graphics = source;
        self
    }

    /// The whole surface, at `(0, 0)`.
    pub fn area(&self) -> Rect {
        self.screen.area()
    }

    /// What is on the surface now.
    pub fn screen(&self) -> &Screen {
        &self.screen
    }

    pub fn writer(&self) -> &W {
        &self.writer
    }

    pub fn writer_mut(&mut self) -> &mut W {
        &mut self.writer
    }

    /// The terminal changed size: keep what was drawn (cut to the new
    /// size), and write everything on the next [`draw`](Self::draw). An
    /// inline viewport keeps its row count, up to the terminal's height,
    /// and takes the new width.
    pub fn resize(&mut self, width: u16, height: u16) {
        let height = match self.viewport {
            Viewport::Fullscreen => height,
            Viewport::Inline(rows) => rows.min(height.max(1)),
        };
        if (width, height) == (self.screen.area().width, self.screen.area().height) {
            return;
        }
        let mut screen = Screen::new(width, height);
        let old = self.screen.area();
        screen.blit(&self.screen, old, 0, 0);
        self.screen = screen;
        self.full = true;
    }

    /// Blank the surface; the next [`draw`](Self::draw) writes everything.
    pub fn clear(&mut self) {
        let area = self.screen.area();
        self.screen.clear(area);
        self.full = true;
    }

    /// Draw a frame: `f` renders into rectangles of the [`Drawing`], then
    /// what changed inside them is written and flushed. Cells nothing drew
    /// keep what they showed. The cursor is hidden unless `f` placed it
    /// with [`Drawing::set_cursor`].
    pub fn draw(&mut self, f: impl FnOnce(&mut Drawing<'_>)) -> io::Result<()> {
        let mut drawing = Drawing {
            screen: &mut self.screen,
            console: &self.console,
            graphics: self.graphics.as_deref(),
            damage: Vec::new(),
            cursor: None,
        };
        f(&mut drawing);
        let Drawing { damage, cursor, .. } = drawing;
        let out = self.frame(damage, cursor);
        self.writer.write_all(out.as_bytes())?;
        self.writer.flush()
    }

    /// The bytes for one frame.
    fn frame(&mut self, damage: Vec<Rect>, cursor: Option<(u16, u16)>) -> String {
        let mut out = String::new();
        if !self.started {
            if self.viewport == Viewport::Fullscreen {
                out.push_str("\x1b[?1049h");
            }
            self.started = true;
        }
        let full = std::mem::take(&mut self.full);
        if full {
            self.painter.invalidate();
        }
        let damage = if full {
            vec![self.screen.area()]
        } else {
            damage
        };
        // No scroll may move a graphic on screen: the terminal would move
        // it, and the graphics' plan would not know.
        let fixed: Vec<Rect> = self
            .placements
            .iter()
            .map(|p| Rect::new(p.column as u16, p.row as u16, p.cols as u16, p.rows as u16))
            .collect();
        self.painter.set_fixed(&fixed);
        let painted = self.painter.paint(&self.screen, &damage);
        let written = self.painter.written().to_vec();
        if self.cursor_shown && !painted.is_empty() {
            // Hidden while the frame is written, so it does not flicker
            // across the screen.
            out.push_str("\x1b[?25l");
            self.cursor_shown = false;
        }
        out.push_str(&painted);
        if self.graphics.is_some() {
            out.push_str(&self.draw_graphics(&written));
        }
        let area = self.screen.area();
        match cursor.filter(|&(x, y)| x < area.width && y < area.height) {
            Some((x, y)) => {
                out.push_str(&self.painter.move_to(x, y));
                if !self.cursor_shown {
                    out.push_str("\x1b[?25h");
                    self.cursor_shown = true;
                }
            }
            None => {
                if self.cursor_shown {
                    out.push_str("\x1b[?25l");
                    self.cursor_shown = false;
                }
            }
        }
        // Styles no cell uses any more go, once they pile up.
        self.painter.compact(&mut self.screen);
        if self.synchronized && !out.is_empty() {
            out = format!("{BEGIN_SYNCHRONIZED_UPDATE}{out}{END_SYNCHRONIZED_UPDATE}");
        }
        out
    }

    /// After the cells: the graphics that moved, went away or had their
    /// cells repainted under them. `written` is what the painter actually
    /// wrote: a damaged cell that did not change was not written, so a
    /// graphic over it was not wiped.
    fn draw_graphics(&mut self, written: &[Rect]) -> String {
        let Some(source) = self.graphics.clone() else {
            return String::new();
        };
        let frame = screen_frame(&self.screen);
        let height = frame.height();
        let next: Vec<Placement> = source
            .placements(&frame)
            .into_iter()
            .filter(|p| p.row + p.rows <= height)
            .collect();
        let changes: Vec<Change> = written
            .iter()
            .flat_map(|rect| {
                (rect.y..rect.bottom()).map(move |row| Change {
                    row: row as usize,
                    columns: rect.x as usize..rect.right() as usize,
                })
            })
            .collect();
        let plan = plan_graphics(&self.placements, &next, &changes);
        let mut out = String::new();
        let repaint: Vec<Rect> = plan
            .repaint
            .iter()
            .map(|(row, columns)| {
                Rect::new(
                    columns.start as u16,
                    *row as u16,
                    (columns.end - columns.start) as u16,
                    1,
                )
            })
            .collect();
        if !repaint.is_empty() {
            out.push_str(&self.painter.repaint(&self.screen, &repaint));
        }
        for placement in &plan.draw {
            out.push_str(
                &self
                    .painter
                    .move_to(placement.column as u16, placement.row as u16),
            );
            out.push_str(&placement.graphic.draw(placement.frame));
        }
        self.placements = next;
        out
    }

    /// Give the terminal back: the alternate screen is left (full screen),
    /// or the cursor goes below the last frame (inline); styles are reset
    /// and the cursor shown. Called by `Drop` if not before.
    pub fn finish(&mut self) -> io::Result<()> {
        if self.finished || !self.started {
            self.finished = true;
            return Ok(());
        }
        let mut out = String::new();
        if let Some(source) = &self.graphics {
            let retained = match self.viewport {
                Viewport::Inline(_) => self.placements.clone(),
                Viewport::Fullscreen => Vec::new(),
            };
            out.push_str(&source.release(&retained));
        }
        out.push_str(&self.painter.finish());
        out.push_str("\x1b[0m\x1b[?25h");
        if self.viewport == Viewport::Fullscreen {
            out.push_str("\x1b[?1049l");
        }
        self.writer.write_all(out.as_bytes())?;
        self.writer.flush()?;
        // Only now: a failed write leaves `finish` (and `Drop`) to try again.
        self.finished = true;
        Ok(())
    }
}

impl<W: Write> Drop for Surface<W> {
    fn drop(&mut self) {
        let _ = self.finish();
    }
}

/// One frame being drawn: render into rectangles of the surface. See
/// [`Surface::draw`].
pub struct Drawing<'a> {
    screen: &'a mut Screen,
    console: &'a Console,
    graphics: Option<&'a dyn PlacementSource>,
    damage: Vec<Rect>,
    cursor: Option<(u16, u16)>,
}

impl Drawing<'_> {
    /// The whole surface, at `(0, 0)`.
    pub fn area(&self) -> Rect {
        self.screen.area()
    }

    /// The console renderables are rendered with.
    pub fn console(&self) -> &Console {
        self.console
    }

    /// Render `renderable` into `rect`, `rect.width` cells wide and at most
    /// `rect.height` rows tall, replacing what was there: the cells it does
    /// not reach are cleared.
    pub fn render(&mut self, rect: Rect, renderable: &dyn Renderable) {
        let options = self
            .console
            .options()
            .update_width(rect.width.max(1) as usize)
            .update_height(rect.height.max(1) as usize);
        let lines = self.console.render_lines(renderable, &options, false);
        self.write_lines(rect, lines);
    }

    /// [`render`](Self::render) through rs-rich-ext's fast path
    /// ([`Draw`]): the same cells. With graphics to place, rich's path, which
    /// they are found in.
    pub fn draw(&mut self, rect: Rect, drawable: &dyn Draw) {
        if self.graphics.is_some() {
            return self.render(rect, drawable);
        }
        let options = self
            .console
            .options()
            .update_width(rect.width.max(1) as usize)
            .update_height(rect.height.max(1) as usize);
        drawable.draw(self.console, &options, self.screen, rect);
        self.damage.push(rect);
    }

    /// Write rendered `lines` into `rect`, replacing what was there (see
    /// [`Screen::write_lines`]).
    pub fn write_lines(&mut self, rect: Rect, lines: Vec<Vec<Segment>>) {
        let lines: Vec<Vec<Segment>> = match self.graphics {
            Some(source) => lines.into_iter().map(|l| source.prepare(l)).collect(),
            None => lines,
        };
        self.screen.write_lines(rect, &lines);
        self.damage.push(rect);
    }

    /// Clear `rect` to blank cells.
    pub fn clear(&mut self, rect: Rect) {
        self.screen.clear(rect);
        self.damage.push(rect);
    }

    /// Show the cursor at `x`, `y` once the frame is written.
    pub fn set_cursor(&mut self, x: u16, y: u16) {
        self.cursor = Some((x, y));
    }

    /// The screen itself, for what rendering does not cover (laying a
    /// style over cells with [`Screen::restyle`], copying with
    /// [`Screen::blit`]). Everything is compared with what was sent.
    pub fn screen_mut(&mut self) -> &mut Screen {
        let area = self.screen.area();
        self.damage.push(area);
        self.screen
    }
}

/// The screen as a frame, for finding the graphics placed on its cells.
fn screen_frame(screen: &Screen) -> Frame {
    let mut segments = Vec::new();
    for line in screen.lines() {
        segments.extend(line);
        segments.push(Segment::line());
    }
    Frame::from_segments(&segments)
}

fn clamp(cells: usize) -> u16 {
    cells.clamp(1, u16::MAX as usize) as u16
}

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

    fn output(surface: &mut Surface<Vec<u8>>) -> String {
        String::from_utf8(std::mem::take(surface.writer_mut())).unwrap()
    }

    /// A surface painting with `strategy`, as if `TMUX` were set or not
    /// (whatever the environment running the tests says).
    fn painting(strategy: PaintStrategy, tmux: bool, width: u16, height: u16) -> Surface<Vec<u8>> {
        let mut surface = Surface::new(Vec::new(), width, height);
        surface.under_tmux = tmux;
        surface.paint_strategy(strategy)
    }

    /// Whether `out` moves rows with the terminal's scrolling: SU or SD,
    /// or DECSTBM margins.
    fn scrolls(out: &str) -> bool {
        let bytes = out.as_bytes();
        bytes.iter().enumerate().any(|(i, &b)| {
            if b != 0x1b || bytes.get(i + 1) != Some(&b'[') {
                return false;
            }
            let rest = &bytes[i + 2..];
            let digits = rest
                .iter()
                .take_while(|c| c.is_ascii_digit() || **c == b';')
                .count();
            matches!(rest.get(digits), Some(b'S' | b'T' | b'r'))
        })
    }

    /// Where two vt100 screens differ, cell by cell: text, colours and
    /// attributes.
    fn differences(a: &vt100::Screen, b: &vt100::Screen, width: u16, height: u16) -> Vec<String> {
        let mut found = Vec::new();
        for row in 0..height {
            for col in 0..width {
                let (Some(x), Some(y)) = (a.cell(row, col), b.cell(row, col)) else {
                    continue;
                };
                let look = |c: &vt100::Cell| {
                    (
                        // An erased cell and a written space look the same.
                        match c.contents() {
                            "" => " ".to_string(),
                            text => text.to_string(),
                        },
                        c.fgcolor(),
                        c.bgcolor(),
                        c.bold(),
                        c.italic(),
                        c.underline(),
                        c.inverse(),
                    )
                };
                if look(x) != look(y) {
                    found.push(format!("({col}, {row}): {:?} != {:?}", look(x), look(y)));
                }
            }
        }
        found
    }

    /// Draw each of `frames` with `best` and with `full`, replay both
    /// through vt100 after every frame, and require the same screen.
    /// Returns `best`'s bytes after the first frame.
    fn best_matches_full(frames: &[Vec<String>], width: u16, height: u16, tmux: bool) -> String {
        let mut best = painting(PaintStrategy::Best, tmux, width, height);
        let mut full = painting(PaintStrategy::Full, tmux, width, height);
        let mut best_term = vt100::Parser::new(height, width, 0);
        let mut full_term = vt100::Parser::new(height, width, 0);
        let mut later = String::new();
        for (n, lines) in frames.iter().enumerate() {
            for (is_best, surface, term) in [
                (true, &mut best, &mut best_term),
                (false, &mut full, &mut full_term),
            ] {
                surface
                    .draw(|s| {
                        for (y, line) in lines.iter().enumerate() {
                            let text = Text::from_markup(line).unwrap();
                            s.render(Rect::new(0, y as u16, width, 1), &text);
                        }
                    })
                    .unwrap();
                term.process(surface.writer());
                if n > 0 && is_best {
                    later.push_str(std::str::from_utf8(surface.writer()).unwrap());
                }
                surface.writer_mut().clear();
            }
            let wrong = differences(best_term.screen(), full_term.screen(), width, height);
            assert!(wrong.is_empty(), "frame {n}: {wrong:?}");
        }
        later
    }

    /// A log that scrolls: each frame shows the rows one further on, in
    /// colours that move with them.
    fn scrolling_log(frames: usize, rows: usize) -> Vec<Vec<String>> {
        const STYLES: [&str; 4] = ["red", "bold green", "italic", "on blue"];
        (0..frames)
            .map(|frame| {
                (frame..frame + rows)
                    .map(|i| format!("[{}]entry {i}[/] of the log", STYLES[i % STYLES.len()]))
                    .collect()
            })
            .collect()
    }

    #[test]
    fn surfaces_paint_with_best_by_default() {
        if PaintStrategy::from_env().is_none() {
            let surface = Surface::new(Vec::new(), 4, 1);
            assert_eq!(surface.painter.strategy(), PaintStrategy::Best);
        }
        let surface = Surface::new(Vec::new(), 4, 1).paint_strategy(PaintStrategy::Rows);
        assert_eq!(surface.painter.strategy(), PaintStrategy::Rows);
        // A new viewport keeps the strategy chosen.
        let surface = surface.viewport(Viewport::Inline(1));
        assert_eq!(surface.painter.strategy(), PaintStrategy::Rows);
    }

    #[test]
    fn best_replayed_equals_a_full_repaint_when_rows_scroll() {
        let later = best_matches_full(&scrolling_log(8, 6), 30, 6, false);
        if cfg!(windows) {
            assert!(!scrolls(&later), "{later:?}");
        } else {
            assert!(scrolls(&later), "best should have scrolled: {later:?}");
        }
    }

    #[test]
    fn best_replayed_equals_a_full_repaint_when_nothing_scrolls() {
        let frames: Vec<Vec<String>> = (0..6)
            .map(|t| {
                vec![
                    "[bold]a clock[/]".to_string(),
                    format!("tick [cyan]{t}[/] of [red]{}[/]", 10 - t),
                    "#".repeat(t + 1),
                ]
            })
            .collect();
        let later = best_matches_full(&frames, 20, 3, false);
        assert!(!scrolls(&later), "{later:?}");
    }

    #[test]
    fn under_tmux_best_does_not_scroll() {
        let later = best_matches_full(&scrolling_log(8, 6), 30, 6, true);
        assert!(!scrolls(&later), "{later:?}");
        // Unless the surface says it may.
        let mut surface =
            painting(PaintStrategy::Best, true, 30, 6).terminal_scroll(!cfg!(windows));
        let mut out = String::new();
        for (n, lines) in scrolling_log(4, 6).iter().enumerate() {
            surface
                .draw(|s| {
                    for (y, line) in lines.iter().enumerate() {
                        let text = Text::from_markup(line).unwrap();
                        s.render(Rect::new(0, y as u16, 30, 1), &text);
                    }
                })
                .unwrap();
            let frame = output(&mut surface);
            if n > 0 {
                out.push_str(&frame);
            }
        }
        assert_eq!(scrolls(&out), !cfg!(windows), "{out:?}");
    }

    #[test]
    fn an_inline_surface_does_not_scroll() {
        let mut surface = painting(PaintStrategy::Best, false, 30, 6)
            .viewport(Viewport::Inline(6))
            .terminal_scroll(true);
        let mut out = String::new();
        for (n, lines) in scrolling_log(4, 6).iter().enumerate() {
            surface
                .draw(|s| {
                    for (y, line) in lines.iter().enumerate() {
                        let text = Text::from_markup(line).unwrap();
                        s.render(Rect::new(0, y as u16, 30, 1), &text);
                    }
                })
                .unwrap();
            let frame = output(&mut surface);
            if n > 0 {
                out.push_str(&frame);
            }
        }
        assert!(!scrolls(&out), "{out:?}");
    }

    #[test]
    fn the_first_draw_enters_the_alternate_screen_and_writes_everything() {
        let mut surface = Surface::new(Vec::new(), 10, 2);
        surface
            .draw(|s| s.render(Rect::new(0, 0, 10, 1), &Text::new("hello")))
            .unwrap();
        let out = output(&mut surface);
        assert!(out.starts_with("\x1b[?1049h\x1b[?25l"), "{out:?}");
        assert!(out.contains("\x1b[2J") && out.contains("hello"), "{out:?}");
        surface.finish().unwrap();
        let out = output(&mut surface);
        assert!(out.ends_with("\x1b[0m\x1b[?25h\x1b[?1049l"), "{out:?}");
    }

    #[test]
    fn an_unchanged_frame_writes_nothing() {
        let mut surface = Surface::new(Vec::new(), 10, 2);
        let draw = |s: &mut Drawing<'_>| s.render(Rect::new(0, 0, 10, 1), &Text::new("same"));
        surface.draw(draw).unwrap();
        output(&mut surface);
        surface.draw(draw).unwrap();
        assert_eq!(output(&mut surface), "");
    }

    #[test]
    fn a_resize_keeps_the_cells_and_writes_everything_once() {
        let mut surface = Surface::new(Vec::new(), 10, 2);
        surface
            .draw(|s| s.render(Rect::new(0, 0, 10, 1), &Text::new("kept")))
            .unwrap();
        output(&mut surface);
        surface.resize(6, 3);
        assert_eq!(surface.screen().plain()[0], "kept  ");
        surface.draw(|_| {}).unwrap();
        let out = output(&mut surface);
        assert!(out.contains("\x1b[2J") && out.contains("kept"), "{out:?}");
        surface.draw(|_| {}).unwrap();
        assert_eq!(output(&mut surface), "");
    }

    #[test]
    fn inline_draws_below_the_cursor_and_leaves_the_frame_on_finish() {
        let mut surface = Surface::new(Vec::new(), 8, 24).viewport(Viewport::Inline(2));
        assert_eq!(surface.area(), Rect::new(0, 0, 8, 2));
        surface
            .draw(|s| s.render(s.area(), &Text::new("one\ntwo")))
            .unwrap();
        let out = output(&mut surface);
        assert!(!out.contains("\x1b[?1049h"), "{out:?}");
        assert!(!out.contains("\x1b[2J"), "{out:?}");
        assert!(out.contains("one") && out.contains("two"), "{out:?}");
        surface.finish().unwrap();
        let out = output(&mut surface);
        assert!(out.ends_with("\r\n\x1b[0m\x1b[?25h"), "{out:?}");
    }

    #[test]
    fn the_cursor_shows_only_where_a_frame_puts_it() {
        let mut surface = Surface::new(Vec::new(), 10, 2);
        surface
            .draw(|s| {
                s.render(Rect::new(0, 0, 10, 1), &Text::new("> "));
                s.set_cursor(2, 0);
            })
            .unwrap();
        let out = output(&mut surface);
        assert!(out.ends_with("\x1b[1;3H\x1b[?25h"), "{out:?}");
        surface.draw(|_| {}).unwrap();
        assert_eq!(output(&mut surface), "\x1b[?25l");
    }

    #[test]
    fn a_synchronized_surface_wraps_each_frame() {
        let mut surface = Surface::new(Vec::new(), 10, 1).synchronized(true);
        surface
            .draw(|s| s.render(s.area(), &Text::new("x")))
            .unwrap();
        let out = output(&mut surface);
        assert!(out.starts_with(BEGIN_SYNCHRONIZED_UPDATE), "{out:?}");
        assert!(out.ends_with(END_SYNCHRONIZED_UPDATE), "{out:?}");
        surface.draw(|_| {}).unwrap();
        assert_eq!(output(&mut surface), "", "nothing to write, no wrapper");
    }

    #[test]
    fn controls_in_rendered_text_become_visible() {
        let mut surface = Surface::new(Vec::new(), 10, 1);
        surface
            .draw(|s| s.render(s.area(), &Text::new("a\x1b[2Jb")))
            .unwrap();
        assert_eq!(surface.screen().plain()[0], "a␛[2Jb    ");
    }

    /// A writer whose next `fails` writes fail.
    struct Flaky {
        fails: usize,
        out: Vec<u8>,
    }

    impl Write for Flaky {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if self.fails > 0 {
                self.fails -= 1;
                return Err(io::Error::other("full"));
            }
            self.out.write(buf)
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn a_failed_finish_can_be_retried() {
        let mut surface = Surface::new(
            Flaky {
                fails: 0,
                out: Vec::new(),
            },
            4,
            1,
        );
        surface
            .draw(|s| s.render(s.area(), &Text::new("x")))
            .unwrap();
        surface.writer_mut().fails = 1;
        assert!(surface.finish().is_err());
        surface.finish().unwrap();
        let out = String::from_utf8(surface.writer().out.clone()).unwrap();
        assert!(out.ends_with("\x1b[?1049l"), "{out:?}");
    }

    /// A one-cell graphic on every `*`.
    #[derive(Debug)]
    struct Star;

    impl crate::frame::Graphic for Star {
        fn key(&self) -> u64 {
            1
        }
        fn draw(&self, _frame: usize) -> String {
            "<star>".into()
        }
    }

    /// One star at a column it is told, whatever the cells say.
    struct Moving(std::sync::Mutex<usize>);

    impl PlacementSource for Moving {
        fn placements(&self, _frame: &Frame) -> Vec<Placement> {
            vec![Placement {
                row: 0,
                column: *self.0.lock().unwrap(),
                cols: 1,
                rows: 1,
                graphic: Arc::new(Star),
                frame: 0,
            }]
        }
    }

    #[test]
    fn a_graphic_that_moves_off_unchanged_cells_leaves_no_ghost() {
        let source = Arc::new(Moving(std::sync::Mutex::new(1)));
        let mut surface = Surface::new(Vec::new(), 6, 1)
            .graphics(Some(source.clone() as Arc<dyn PlacementSource>));
        let draw = |s: &mut Drawing<'_>| s.render(s.area(), &Text::new("abcdef"));
        surface.draw(draw).unwrap();
        output(&mut surface);
        *source.0.lock().unwrap() = 3;
        // The row is drawn again with the same cells: none is written by the
        // diff, so the cell under the old star must be repainted on purpose.
        surface.draw(draw).unwrap();
        let out = output(&mut surface);
        assert_eq!(out, "\x1b[1;2H\x1b[0mb\x1b[1;4H<star>", "{out:?}");
    }

    #[test]
    fn dropping_a_started_surface_gives_the_terminal_back() {
        let mut sink = Vec::new();
        {
            let mut surface = Surface::new(&mut sink, 4, 1);
            surface
                .draw(|s| s.render(s.area(), &Text::new("x")))
                .unwrap();
        }
        let out = String::from_utf8(sink).unwrap();
        assert!(out.ends_with("\x1b[?1049l"), "{out:?}");
    }
}