uncurses-ratatui 0.0.4

Integration adapter for the uncurses terminal rendering library
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
1037
1038
1039
1040
use std::io::{self, Write};
use std::time::{Duration, Instant};

use ratatui::Viewport;
use ratatui::backend::{Backend, ClearType, WindowSize};
use ratatui::buffer::Cell as RtCell;
use ratatui::layout::{Position as RtPosition, Size as RtSize};
use uncurses::buffer::SurfaceMut;
use uncurses::cell::Cell as CzCell;
use uncurses::event::{Event, Input};
use uncurses::layout::Position;
use uncurses::program::{Program, ProgramOptions};
use uncurses::terminal::{Stdin, Stdout, TtyInput, TtyOutput};

use crate::convert::cell_from_ratatui;

/// Platform bound required for an output handle usable by the backend.
///
/// The handle must be writable, cheaply copyable, and expose the platform OS
/// handle used by terminal mode and window-size operations. Process stdio and
/// controlling-terminal output handles satisfy this bound.
///
/// This trait is sealed only by its bounds: any type that implements the listed
/// platform traits implements `Output` automatically. It is the output
/// counterpart to the `Input` bound on the backend's input handle.
#[cfg(unix)]
pub trait Output: Write + Copy + std::os::fd::AsFd {}
#[cfg(unix)]
impl<T: Write + Copy + std::os::fd::AsFd> Output for T {}
/// Platform bound required for an output handle usable by the backend.
///
/// The handle must be writable, cheaply copyable, and expose the platform OS
/// handle used by terminal mode and window-size operations. Process stdio and
/// controlling-terminal output handles satisfy this bound.
///
/// This trait is sealed only by its bounds: any type that implements the listed
/// platform traits implements `Output` automatically. It is the output
/// counterpart to the `Input` bound on the backend's input handle.
#[cfg(windows)]
pub trait Output: Write + Copy + std::os::windows::io::AsHandle {}
#[cfg(windows)]
impl<T: Write + Copy + std::os::windows::io::AsHandle> Output for T {}

/// How long [`Backend::get_cursor_position`] waits for a cursor-position
/// report before falling back to the origin. The widget library calls it at
/// most once per inline-viewport setup, so a small budget keeps setup
/// responsive on terminals that never answer.
const CURSOR_QUERY_TIMEOUT: Duration = Duration::from_millis(100);

/// Extract a cursor-position report from a reply event. The report is the
/// [`Event::CursorPosition`] variant, but at terminal row 1 the wire form
/// collides with a modified-F3 key and is decoded as an [`Event::Multi`]
/// carrying both; unwrap that case too.
fn cursor_position_report(ev: &Event) -> Option<Position> {
    match ev {
        Event::CursorPosition(pos) => Some(*pos),
        Event::Multi(events) => events.iter().find_map(|e| match e {
            Event::CursorPosition(pos) => Some(*pos),
            _ => None,
        }),
        _ => None,
    }
}

/// Backend implementation that drives rendering, input, and lifecycle through
/// one [`Program`].
///
/// ## What it wraps
///
/// The wrapped screen owns the terminal handle, the cell buffer, and the event
/// source. Keeping those pieces behind one backend means frame rendering,
/// cursor movement, clearing, size tracking, raw-mode setup, and input reads all
/// observe the same terminal state.
///
/// ## Rendering
///
/// [`Backend::draw`] converts each concrete buffer cell to an uncurses cell and
/// writes it into the screen's buffer, staging the frame without any I/O.
/// [`Backend::flush`] then calls [`Screen::render`](uncurses::screen::Screen::render), which diffs the buffer,
/// stages the minimal escape bytes, and flushes them through the screen.
///
/// ```text
/// ┌─────────────────────┐
/// │ Frame buffer        │
/// └─────────┬───────────┘
///           │ buffer cells
///           ▼
/// ┌─────────────────────┐
/// │ UncursesBackend     │
/// │ draw + conversion   │
/// └─────────┬───────────┘
///           │ Screen::set_cell
///           ▼
/// ┌─────────────────────┐
/// │ Screen (diff render) │
/// │ diff against output │
/// └─────────┬───────────┘
///           │ flush → Screen::render
///           ▼
///       terminal
/// ```
///
/// ## Viewports
///
/// The default viewport is [`Viewport::Fullscreen`]. The init helpers call
/// [`set_viewport`](Self::set_viewport) with the viewport stored in
/// terminal options. Inline viewports keep an absolute origin in
/// `inline_origin`; drawing subtracts that origin so the screen buffer contains
/// only the inline region.
///
/// ## Events
///
/// Use [`poll_event`](Self::poll_event),
/// [`try_read_event`](Self::try_read_event), and [`read_event`](Self::read_event)
/// for synchronous loops, or [`event_stream`](Self::event_stream) with the
/// `async` feature. The synchronous reads keep capability tracking alive on
/// their own; only the stream needs
/// [`observe_event`](Self::observe_event) called by hand.
///
/// ## Setup
///
/// Construction is inert: it does not enter raw mode, enter the alternate
/// screen, hide the cursor, or choose a non-default viewport. Call
/// [`init`](Self::init) or [`init_with`](Self::init_with) for manual setup, or
/// use the crate-level setup helpers for process stdio. Call
/// [`restore`](Self::restore) when the session ends.
pub struct UncursesBackend<I: Input, O: Write> {
    program: Program<I, O>,
    /// The widget-library viewport, set via [`set_viewport`](Self::set_viewport)
    /// (by `init_with_options`). Determines the screen buffer height
    /// (inline height vs full terminal height) and whether `draw` /
    /// `set_cursor_position` translate absolute rows into the inline
    /// region.
    viewport: Viewport,
    /// Top row of an inline viewport. Seeded at initial setup from
    /// [`get_cursor_position`](Backend::get_cursor_position), then kept
    /// exact across resizes by [`clear_region`](Backend::clear_region),
    /// which observes the cursor the widget library parks at the recomputed
    /// viewport top before clearing. Absolute rows are translated down by this when
    /// rendering an inline viewport.
    inline_origin: u16,
    /// Last full terminal size observed by [`size`](Backend::size) /
    /// [`window_size`](Backend::window_size). When it changes the screen
    /// is marked stale (`size_dirty`) so the next [`draw`](Backend::draw)
    /// repaints in full. Tracked behind `Cell` because `size` takes
    /// `&self`.
    last_size: std::cell::Cell<(u16, u16)>,
    /// Set when `last_size` changes; consumed by `draw` to invalidate the
    /// screen.
    size_dirty: std::cell::Cell<bool>,
    /// Absolute row last requested by
    /// [`set_cursor_position`](Backend::set_cursor_position). When the widget
    /// library recomputes an inline viewport (initial setup and every resize) it
    /// positions the cursor at the viewport's top row before clearing it,
    /// so [`clear_region`](Backend::clear_region) reads this back as the
    /// fresh `inline_origin` — the only place the *true* viewport top is
    /// observable (the cursor reported by `get_cursor_position` sits at the
    /// app's cursor, which need not be the viewport top).
    last_cursor_row: u16,
}

impl UncursesBackend<Stdin, Stdout> {
    /// Build a backend over process standard input and output.
    ///
    /// This constructs a [`Program`] with `stdin` and `stdout`, then wraps it in
    /// [`UncursesBackend::new`]. It does not enter raw mode, hide the cursor,
    /// enter the alternate screen, or apply screen options.
    ///
    /// ## Returns
    ///
    /// A backend ready for manual setup or for construction of a widget-library
    /// terminal.
    ///
    /// ## Errors
    ///
    /// Returns errors from [`Program::stdio`], including failures to inspect the
    /// terminal size or initialize the input event source.
    ///
    /// ## Panics
    ///
    /// Does not intentionally panic.
    ///
    /// ## Usage note
    ///
    /// Prefer crate-level setup helpers when process stdio and conventional
    /// setup are sufficient.
    pub fn stdio() -> io::Result<Self> {
        Ok(Self::new(Program::stdio()?))
    }
}

impl UncursesBackend<TtyInput, TtyOutput> {
    /// Build a backend over the controlling terminal instead of process stdio.
    ///
    /// This opens the platform controlling terminal (`/dev/tty` on Unix,
    /// console handles on Windows), constructs a [`Program`], and wraps it in
    /// [`UncursesBackend::new`]. It is useful when standard input or output is
    /// redirected but the application still needs an interactive terminal.
    ///
    /// ## Returns
    ///
    /// A backend ready for manual setup or for construction of a widget-library
    /// terminal.
    ///
    /// ## Errors
    ///
    /// Returns errors from opening or initializing the controlling terminal,
    /// sizing the buffer, or creating the input event source.
    ///
    /// ## Panics
    ///
    /// Does not intentionally panic.
    ///
    /// ## Usage note
    ///
    /// Like [`stdio`](UncursesBackend::stdio), this constructor is inert; call
    /// [`init`](UncursesBackend::init) or
    /// [`init_with`](UncursesBackend::init_with) before interactive use.
    pub fn open() -> io::Result<Self> {
        Ok(Self::new(Program::open()?))
    }
}

impl<I, O> UncursesBackend<I, O>
where
    I: Input,
    O: Write,
{
    /// Build a backend over an existing [`Program`].
    ///
    /// Use this when the screen has been constructed by the caller, or when the
    /// terminal handles are not process stdio or the controlling terminal. The
    /// backend starts with [`Viewport::Fullscreen`], an inline origin of `0`,
    /// no remembered terminal size, and no dirty-size flag.
    ///
    /// ## Parameters
    ///
    /// * `screen` - the screen facade that will own rendering, input, and
    ///   terminal lifecycle for this backend.
    ///
    /// ## Returns
    ///
    /// A backend wrapping `screen`.
    ///
    /// ## Panics
    ///
    /// Does not panic.
    ///
    /// ## Usage note
    ///
    /// This does not call [`Program::init`]. Initialize the screen through the
    /// backend or manually before starting an interactive session.
    pub fn new(program: Program<I, O>) -> Self {
        Self {
            program,
            viewport: Viewport::Fullscreen,
            inline_origin: 0,
            last_size: std::cell::Cell::new((0, 0)),
            size_dirty: std::cell::Cell::new(false),
            last_cursor_row: 0,
        }
    }

    /// Record an observed full terminal size; if it differs from the last,
    /// flag the screen stale so the next [`draw`](Backend::draw) repaints
    /// in full. Takes `&self` so `size`/`window_size` can call it.
    fn note_size(&self, size: (u16, u16)) {
        if self.last_size.get() != size {
            self.last_size.set(size);
            self.size_dirty.set(true);
        }
    }

    /// Record the viewport used by the surrounding terminal.
    ///
    /// The setup helpers call this with the viewport from terminal options. The
    /// backend uses it to size the screen buffer and, for inline viewports,
    /// translate absolute frame rows into the inline buffer region. The default before this method is called is
    /// [`Viewport::Fullscreen`].
    ///
    /// ## Parameters
    ///
    /// * `viewport` - the viewport selected for the terminal.
    ///
    /// ## Panics
    ///
    /// Does not panic.
    ///
    /// ## Usage note
    ///
    /// For [`Viewport::Inline`], the screen buffer is resized immediately to
    /// the requested height clamped to the current terminal height. Fullscreen
    /// and fixed viewports are stored without resizing here; drawing keeps the
    /// screen in step with the current full size.
    pub fn set_viewport(&mut self, viewport: Viewport) {
        if let Viewport::Inline(height) = viewport {
            let size = self.program.screen().size();
            let h = height.min(size.height);
            self.program.screen_mut().resize((size.width, h));
        }
        self.viewport = viewport;
    }

    /// Borrow the wrapped [`Program`] facade.
    ///
    /// Use this for read-only access to screen state such as cached capability
    /// or size information. Rendering and input operations that mutate the
    /// screen require [`program_mut`](Self::program_mut).
    ///
    /// ## Returns
    ///
    /// A shared reference to the screen owned by this backend.
    ///
    /// ## Panics
    ///
    /// Does not panic.
    pub fn program(&self) -> &Program<I, O> {
        &self.program
    }

    /// Mutably borrow the wrapped [`Program`] facade.
    ///
    /// Use this for screen operations not surfaced by the backend: setting
    /// screen modes, using the alternate screen directly, configuring renderer
    /// options, or manual rendering. For the async event stream, prefer the
    /// backend's own [`event_stream`](Self::event_stream) paired with
    /// [`observe_event`](Self::observe_event).
    ///
    /// ## Returns
    ///
    /// A mutable reference to the screen owned by this backend.
    ///
    /// ## Panics
    ///
    /// Does not panic.
    ///
    /// ## Usage note
    ///
    /// Avoid mixing manual buffer writes with normal backend drawing unless the
    /// ordering is deliberate; both paths affect the same buffer.
    pub fn program_mut(&mut self) -> &mut Program<I, O> {
        &mut self.program
    }

    /// Poll the wrapped screen's input source.
    ///
    /// This delegates to [`Program::poll_event`], which drives the underlying
    /// event source for at most `timeout`. It does not remove an event from the
    /// queue; call [`try_read_event`](Self::try_read_event) or
    /// [`read_event`](Self::read_event) after it reports availability.
    ///
    /// ## Parameters
    ///
    /// * `timeout` - `Some(duration)` to wait up to that duration, or `None` to
    ///   use the event source's blocking poll behavior.
    ///
    /// ## Returns
    ///
    /// `Ok(true)` if an event is available, `Ok(false)` if the poll timed out.
    ///
    /// ## Errors
    ///
    /// Returns I/O errors from the input source.
    ///
    /// ## Panics
    ///
    /// Panics if the screen's internal event-source lock is poisoned.
    ///
    /// ## Usage note
    ///
    /// Polling through the backend keeps capability detection and application
    /// input on the same event source.
    pub fn poll_event(&self, timeout: Option<Duration>) -> io::Result<bool> {
        self.program.poll_event(timeout)
    }

    /// Try to read the next queued event without blocking.
    ///
    /// This delegates to the wrapped [`Program`], which tracks capabilities as
    /// the event passes through. Do not also pass the event to
    /// [`observe_event`](Self::observe_event); it would count twice.
    ///
    /// ## Returns
    ///
    /// `Some(event)` when an event was already queued; `None` when reading would
    /// require blocking or additional I/O.
    ///
    /// ## Panics
    ///
    /// Panics if the screen's internal event-source lock is poisoned.
    ///
    /// ## Usage note
    ///
    /// Pair this with [`poll_event`](Self::poll_event) for timeout-based loops.
    pub fn try_read_event(&mut self) -> io::Result<Option<Event>> {
        self.program.try_read_event()
    }

    /// Block until the next event is available.
    ///
    /// This delegates to the wrapped [`Program`], which tracks capabilities as
    /// the event passes through. Do not also pass the event to
    /// [`observe_event`](Self::observe_event); it would count twice.
    ///
    /// ## Returns
    ///
    /// The next decoded terminal [`Event`].
    ///
    /// ## Errors
    ///
    /// Returns I/O errors from the input source.
    ///
    /// ## Panics
    ///
    /// Panics if the screen's internal event-source lock is poisoned.
    ///
    /// ## Usage note
    ///
    /// Use this for simple blocking event loops. Use
    /// [`event_stream`](Self::event_stream) instead when the `async` feature is
    /// enabled and the application is already asynchronous.
    pub fn read_event(&mut self) -> io::Result<Event> {
        self.program.read_event()
    }

    /// Feed an event back through the wrapped [`Program`] for capability
    /// tracking.
    ///
    /// Only the async [`event_stream`](Self::event_stream) needs this: it
    /// bypasses the backend, so nothing has observed what it yields. The
    /// synchronous reads ([`read_event`](Self::read_event),
    /// [`try_read_event`](Self::try_read_event)) already observe on your
    /// behalf, and observing one of their events again would count it twice.
    ///
    /// ## Errors
    ///
    /// Returns the errors [`Program::observe_event`] reports.
    pub fn observe_event(&mut self, event: &Event) -> io::Result<()> {
        self.program.observe_event(event)
    }

    /// Build an async [`EventStream`](uncurses::event::EventStream) over the
    /// wrapped screen's input.
    ///
    /// The stream shares the screen's decoder, so it does not race the sync read
    /// methods on the same file descriptor. Unlike those, it yields events
    /// without observing them; pair it with
    /// [`observe_event`](Self::observe_event) in your `select!` loop to keep
    /// capability tracking alive.
    ///
    /// ## Returns
    ///
    /// An owned `EventStream` you can hold alongside `&mut self` (it shares the
    /// source by handle rather than borrowing the backend).
    #[cfg(feature = "async")]
    pub fn event_stream(&self) -> uncurses::event::EventStream<I>
    where
        I: 'static,
    {
        self.program.event_stream()
    }
}

impl<I, O> UncursesBackend<I, O>
where
    I: Input + Copy,
    O: Output,
{
    /// Begin an interactive session with default [`ProgramOptions`].
    ///
    /// This delegates to [`Program::init`]: the program enters raw mode and
    /// applies the always-on defaults. It sends no capability query, and does
    /// not enter the alternate screen or hide the cursor by itself; the
    /// crate-level setup helpers perform those additional steps.
    ///
    /// ## Returns
    ///
    /// `Ok(())` after raw mode and screen initialization have been staged.
    ///
    /// ## Errors
    ///
    /// Returns errors from raw-mode setup, autoresizing, or bracketed paste
    /// setup.
    ///
    /// ## Panics
    ///
    /// Does not intentionally panic.
    ///
    /// ## Usage note
    ///
    /// Pair successful manual initialization with [`restore`](Self::restore).
    pub fn init(&mut self) -> io::Result<()> {
        self.program.init()
    }

    /// Begin an interactive session with explicit [`ProgramOptions`].
    ///
    /// This delegates to [`Program::init_with`], allowing the caller to choose
    /// bracketed paste and mouse tracking. It sends no capability queries, and
    /// does not enter the alternate screen or hide the cursor by itself.
    ///
    /// ## Parameters
    ///
    /// * `options` - screen defaults to apply during initialization.
    ///
    /// ## Returns
    ///
    /// `Ok(())` after raw mode and screen initialization have been staged.
    ///
    /// ## Errors
    ///
    /// Returns errors from raw-mode setup, autoresizing, or always-on mode
    /// setup.
    ///
    /// ## Panics
    ///
    /// Does not intentionally panic.
    ///
    /// ## Usage note
    ///
    /// Pair successful manual initialization with [`restore`](Self::restore).
    pub fn init_with(&mut self, options: ProgramOptions) -> io::Result<()> {
        self.program.init_with(options)
    }

    /// Restore terminal state after a backend-managed session.
    ///
    /// This delegates to [`Program::pause`]. It tears down staged modes, resets
    /// buffer-controlled state such as alternate screen and cursor visibility,
    /// flushes pending output, and restores the terminal mode while keeping the
    /// screen available for future use.
    ///
    /// ## Returns
    ///
    /// `Ok(())` after teardown and terminal-mode restoration complete.
    ///
    /// ## Errors
    ///
    /// Returns errors from mode teardown, flushing, or terminal restoration.
    ///
    /// ## Panics
    ///
    /// Does not intentionally panic.
    ///
    /// ## Usage note
    ///
    /// Treat this as the single teardown entry point for backend-managed setup.
    pub fn restore(&mut self) -> io::Result<()> {
        self.program.pause()
    }
}

impl<I, O> Write for UncursesBackend<I, O>
where
    I: Input,
    O: Write,
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.program.screen_mut().write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        Write::flush(self.program.screen_mut())
    }
}

impl<I, O> Backend for UncursesBackend<I, O>
where
    I: Input + Copy,
    O: Output,
{
    type Error = io::Error;

    /// Stage a frame's cells into the wrapped screen buffer.
    ///
    /// The iterator supplies absolute buffer coordinates and concrete cells.
    /// Each cell is converted to an uncurses cell and written to the screen.
    /// This method only stages into the buffer; the buffer diff is computed
    /// and written when the surrounding terminal calls [`Backend::flush`].
    ///
    /// ## Parameters
    ///
    /// * `content` - visible frame cells as `(x, y, cell)` triples.
    ///
    /// ## Errors
    ///
    /// This implementation performs no I/O and returns `Ok(())`; renderer and
    /// output errors surface from [`Backend::flush`].
    ///
    /// ## Usage note
    ///
    /// Inline viewports translate `y` by the stored inline origin. A detected
    /// terminal-size change invalidates the screen so this frame repaints in
    /// full.
    fn draw<'a, J>(&mut self, content: J) -> io::Result<()>
    where
        J: Iterator<Item = (u16, u16, &'a RtCell)>,
    {
        // Keep the screen buffer in step with what the widget library draws into.
        // For an inline viewport the buffer is only the inline height and
        // the widget library's absolute rows are translated down by the viewport top;
        // otherwise it tracks the full terminal size.
        let size = self.program.screen().size();
        let (full_w, full_h) = self
            .program
            .get_window_size()
            .ok()
            .map(|s| (s.col, s.row))
            .filter(|&(c, r)| c != 0 && r != 0)
            .unwrap_or((size.width, size.height));
        let (w, h, top) = match self.viewport {
            Viewport::Inline(height) => {
                let h = height.min(full_h);
                let top = self.inline_origin.min(full_h.saturating_sub(h));
                (full_w, h, top)
            }
            _ => (full_w, full_h, 0),
        };
        // Repaint in full if the terminal size changed since the last
        // observation (covers cases where the buffer dimensions stay the
        // same, e.g. an inline viewport on a vertical-only resize).
        self.note_size((full_w, full_h));
        if self.size_dirty.take() {
            self.program.screen_mut().invalidate();
        }
        if (w, h) != (size.width, size.height) {
            self.program.screen_mut().resize((w, h));
        }
        for (x, y, rc) in content {
            let cell = cell_from_ratatui(rc);
            self.program
                .screen_mut()
                .set_cell((x, y.saturating_sub(top)), &cell);
        }
        Ok(())
    }

    /// Hide the terminal cursor immediately.
    ///
    /// Delegates to [`Program::hide_cursor`], which stages cursor visibility on
    /// the buffer and flushes before returning.
    ///
    /// ## Errors
    ///
    /// Returns output errors from flushing the visibility change.
    fn hide_cursor(&mut self) -> io::Result<()> {
        self.program.hide_cursor()
    }

    /// Show the terminal cursor immediately.
    ///
    /// Delegates to [`Program::show_cursor`], which stages cursor visibility on
    /// the buffer and flushes before returning.
    ///
    /// ## Errors
    ///
    /// Returns output errors from flushing the visibility change.
    fn show_cursor(&mut self) -> io::Result<()> {
        self.program.show_cursor()
    }

    /// Query the terminal for its current cursor position.
    ///
    /// This sends a cursor-position request, then polls input until a
    /// [`Event::CursorPosition`] report arrives or the short setup timeout
    /// expires. Non-report events read while waiting are unread back into the
    /// screen in their original order so the application can still consume them.
    /// If no report arrives, the backend returns the origin.
    ///
    /// ## Returns
    ///
    /// The zero-based cursor position reported by the terminal, or `(0, 0)` on
    /// timeout. Inline viewports also seed their initial origin from this row.
    ///
    /// ## Errors
    ///
    /// Returns errors from writing the cursor-position request or polling the
    /// input source.
    ///
    /// ## Usage note
    ///
    /// The reply parser also accepts the multi-event ambiguity that occurs when
    /// the row-1 CPR wire form collides with a modified function key sequence.
    fn get_cursor_position(&mut self) -> io::Result<RtPosition> {
        // Query the terminal for its cursor position (CPR): write the
        // request, then read events until the report arrives or the timeout
        // elapses. The reply is absolute, zero-based, and matches the widget library's
        // coordinate space (the same space `set_cursor_position` writes
        // absolute moves into), so it needs no translation. Fall back to the
        // origin if the terminal does not answer.
        self.program.request_cursor_position()?;
        let deadline = Instant::now() + CURSOR_QUERY_TIMEOUT;
        // Events read while waiting for the report are not ours to consume;
        // stash them and put them back (in original order) so the app's loop
        // still sees them.
        let mut stash: Vec<Event> = Vec::new();
        let found = loop {
            let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
                break None;
            };
            if !self.program.poll_event(Some(remaining))? {
                break None;
            }
            match self.program.try_read_event()? {
                Some(ev) => match cursor_position_report(&ev) {
                    Some(pos) => break Some(pos),
                    None => stash.push(ev),
                },
                None => continue,
            }
        };
        for ev in stash.into_iter().rev() {
            self.program.unread_event(ev);
        }
        let pos = found.unwrap_or(Position::new(0, 0));
        // the widget library calls this to anchor an inline viewport at the cursor row,
        // then draws content at absolute rows starting there. Seed the
        // inline origin so the very first `draw` translates those absolute
        // rows into the inline buffer; before this the origin defaulted to 0
        // and a cursor below the top clipped the first frame. The exact top
        // is still re-derived by `clear_region` on later resizes.
        if matches!(self.viewport, Viewport::Inline(_)) {
            self.inline_origin = pos.y;
            self.last_cursor_row = pos.y;
        }
        Ok(RtPosition { x: pos.x, y: pos.y })
    }

    /// Move the terminal cursor to an absolute position immediately.
    ///
    /// The backend writes an absolute CUP escape directly, records the row for
    /// inline-viewport bookkeeping, updates the renderer's tracked cursor
    /// position in buffer-relative coordinates, and flushes.
    ///
    /// ## Parameters
    ///
    /// * `position` - zero-based absolute cursor position requested by the
    ///   surrounding terminal.
    ///
    /// ## Errors
    ///
    /// Returns output errors from writing or flushing the cursor movement.
    ///
    /// ## Usage note
    ///
    /// Direct absolute movement keeps the renderer and inline viewport aligned;
    /// it intentionally bypasses the renderer's cost-optimized relative moves.
    fn set_cursor_position<P: Into<RtPosition>>(&mut self, position: P) -> io::Result<()> {
        let p = position.into();
        // Remember the requested row: when the widget library clears an inline
        // viewport it places the cursor at the viewport top first, letting
        // `clear_region` recover the (possibly shifted) origin on resize.
        self.last_cursor_row = p.y;
        // Emit an absolute CUP directly rather than going through the
        // renderer's cost-optimized (possibly relative) move: ratatui calls
        // this to place its own cursor, so the move must be unconditional
        // and absolute.
        uncurses::ansi::cursor::write_cup(self.program.screen_mut(), p.y, p.x)?;
        // Keep the renderer's cursor bookkeeping in step with the move we
        // just made, translated into the (inline) buffer. In relative-cursor
        // mode merely invalidating would lose the absolute row — the next
        // frame's vertical moves would drift the viewport — so assert the
        // exact buffer-relative position instead. For a non-inline viewport
        // `inline_origin` is 0, so this is the absolute position unchanged.
        let top = match self.viewport {
            Viewport::Inline(_) => self.inline_origin,
            _ => 0,
        };
        self.program
            .screen_mut()
            .set_tracked_cursor((p.x, p.y.saturating_sub(top)));
        Write::flush(self.program.screen_mut())
    }

    /// Clear the entire backend surface immediately.
    ///
    /// This delegates to [`Backend::clear_region`] with [`ClearType::All`].
    ///
    /// ## Errors
    ///
    /// Returns output errors from rendering and flushing the staged blank cells.
    fn clear(&mut self) -> io::Result<()> {
        self.clear_region(ClearType::All)
    }

    /// Clear part of the backend surface immediately.
    ///
    /// The implementation blanks only the cells covered by `clear_type` in the
    /// screen's staging buffer, invalidates tracked cursor state, renders the
    /// diff, and flushes before returning. For inline viewports,
    /// [`ClearType::AfterCursor`] is also the resize/viewport-reanchor path: the
    /// last absolute cursor row becomes the new inline origin and the full
    /// inline buffer is blanked.
    ///
    /// ## Parameters
    ///
    /// * `clear_type` - the clear region requested by the surrounding terminal.
    ///
    /// ## Errors
    ///
    /// Returns output errors from rendering or flushing the clear operation.
    ///
    /// ## Usage note
    ///
    /// Clearing is immediate by backend contract; unlike [`Backend::draw`], this
    /// method does not wait for a later flush call to make output visible.
    fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {
        let size = self.program.screen().size();
        let w = size.width;
        let h = size.height;
        let cursor = self.program.screen().tracked_cursor().unwrap_or_default();
        if w == 0 || h == 0 {
            return Ok(());
        }
        let region = match clear_type {
            ClearType::All => Some(uncurses::layout::Rect::new(0, 0, w, h)),
            ClearType::AfterCursor if matches!(self.viewport, Viewport::Inline(_)) => {
                // Inline-viewport resize/clear path. ratatui homes the
                // cursor to the viewport's (recomputed) top row, then erases
                // to the end of the screen — for our inline buffer that is
                // the whole thing. Adopt the fresh origin (the app cursor
                // reported by `get_cursor_position` may sit anywhere in the
                // viewport, so this is the authoritative top), and blank the
                // entire staging buffer so the upcoming full repaint starts
                // clean: the staging buffer preserves overlapping cells
                // across a grow, which a diff-style painter never overwrites,
                // and would otherwise duplicate the previous frame's right
                // edge.
                self.inline_origin = self.last_cursor_row;
                Some(uncurses::layout::Rect::new(0, 0, w, h))
            }
            ClearType::AfterCursor => {
                if cursor.y < h {
                    let tail_x = cursor.x.min(w);
                    self.program.screen_mut().fill_rect(
                        uncurses::layout::Rect::new(tail_x, cursor.y, w - tail_x, 1),
                        &CzCell::BLANK,
                    );
                }
                (cursor.y + 1 < h)
                    .then(|| uncurses::layout::Rect::new(0, cursor.y + 1, w, h - cursor.y - 1))
            }
            ClearType::BeforeCursor => {
                if cursor.y > 0 {
                    self.program.screen_mut().fill_rect(
                        uncurses::layout::Rect::new(0, 0, w, cursor.y),
                        &CzCell::BLANK,
                    );
                }
                (cursor.y < h).then(|| {
                    let head_w = (cursor.x.min(w).saturating_add(1)).min(w);
                    uncurses::layout::Rect::new(0, cursor.y, head_w, 1)
                })
            }
            ClearType::CurrentLine => {
                (cursor.y < h).then(|| uncurses::layout::Rect::new(0, cursor.y, w, 1))
            }
            ClearType::UntilNewLine => (cursor.y < h && cursor.x < w)
                .then(|| uncurses::layout::Rect::new(cursor.x, cursor.y, w - cursor.x, 1)),
        };
        if let Some(region) = region {
            self.program.screen_mut().fill_rect(region, &CzCell::BLANK);
        }
        self.program.screen_mut().invalidate_tracked_cursor();
        // Push the staged blanks to the wire so the clear takes effect
        // before this call returns, matching the immediate-clear contract.
        self.program.screen_mut().render()
    }

    /// Return the current terminal size in cells.
    ///
    /// This queries the live window size through the screen. If that query fails
    /// or returns zero dimensions, it falls back to the current screen buffer
    /// size. Size changes are recorded so the next draw can invalidate and
    /// repaint.
    ///
    /// ## Returns
    ///
    /// The full terminal width and height in cells.
    ///
    /// ## Errors
    ///
    /// This implementation falls back on query failure and currently returns
    /// `Ok` with the best available size.
    fn size(&self) -> io::Result<RtSize> {
        // The full terminal size: the widget library needs it to anchor inline
        // viewports and to detect resizes. Fall back to the screen's
        // buffer size if the query fails (e.g. output is not a tty).
        let size = self.program.screen().size();
        let (width, height) = self
            .program
            .get_window_size()
            .ok()
            .map(|s| (s.col, s.row))
            .filter(|&(c, r)| c != 0 && r != 0)
            .unwrap_or((size.width, size.height));
        self.note_size((width, height));
        Ok(RtSize { width, height })
    }

    /// Return the current terminal size in cells and pixels.
    ///
    /// This uses the screen's live window-size query when available. Cell
    /// dimensions fall back to the buffer size on failure or zero reports; pixel
    /// dimensions fall back to zero when unavailable. Size changes are recorded
    /// so the next draw can invalidate and repaint.
    ///
    /// ## Returns
    ///
    /// A [`WindowSize`] with `columns_rows` populated from the best available
    /// cell size and `pixels` populated from the query when reported.
    ///
    /// ## Errors
    ///
    /// This implementation falls back on query failure and currently returns
    /// `Ok` with the best available size.
    fn window_size(&mut self) -> io::Result<WindowSize> {
        // One query reports both cell and pixel dimensions; fall back to
        // the screen's buffer size for cells if it fails.
        let size = self.program.screen().size();
        let ws = self.program.get_window_size().ok();
        let (width, height) = ws
            .as_ref()
            .map(|w| (w.col, w.row))
            .filter(|&(c, r)| c != 0 && r != 0)
            .unwrap_or((size.width, size.height));
        self.note_size((width, height));
        Ok(WindowSize {
            columns_rows: RtSize { width, height },
            pixels: RtSize {
                width: ws.as_ref().map(|w| w.xpixel).unwrap_or(0),
                height: ws.as_ref().map(|w| w.ypixel).unwrap_or(0),
            },
        })
    }

    /// Diff the staged buffer and write the frame to the output handle.
    ///
    /// [`Backend::draw`] only stages cells into the buffer; this is where the
    /// renderer computes the minimal diff against the tracked terminal and
    /// flushes the resulting bytes through the wrapped screen.
    ///
    /// ## Errors
    ///
    /// Returns renderer or output errors from the wrapped screen.
    fn flush(&mut self) -> io::Result<()> {
        self.program.screen_mut().render()
    }

    /// Append blank lines to the underlying output.
    ///
    /// The backend writes `n` newline-terminated blank lines through the screen
    /// and flushes immediately.
    ///
    /// ## Parameters
    ///
    /// * `n` - number of lines to append.
    ///
    /// ## Errors
    ///
    /// Returns output errors from writing or flushing the lines.
    fn append_lines(&mut self, n: u16) -> io::Result<()> {
        for _ in 0..n {
            let _ = writeln!(self.program.screen_mut());
        }
        Write::flush(self.program.screen_mut())
    }

    /// Handle a request to scroll a region upward.
    ///
    /// This backend does not use terminal scrolling for region updates; drawing
    /// and buffer diffing repaint the resulting cells instead. The method is a
    /// no-op that satisfies the backend trait.
    ///
    /// ## Parameters
    ///
    /// * `_region` - ignored requested row range.
    /// * `_amount` - ignored scroll amount.
    ///
    /// ## Errors
    ///
    /// This implementation is infallible and returns `Ok(())`.
    fn scroll_region_up(&mut self, _region: std::ops::Range<u16>, _amount: u16) -> io::Result<()> {
        Ok(())
    }

    /// Handle a request to scroll a region downward.
    ///
    /// This backend does not use terminal scrolling for region updates; drawing
    /// and buffer diffing repaint the resulting cells instead. The method is a
    /// no-op that satisfies the backend trait.
    ///
    /// ## Parameters
    ///
    /// * `_region` - ignored requested row range.
    /// * `_amount` - ignored scroll amount.
    ///
    /// ## Errors
    ///
    /// This implementation is infallible and returns `Ok(())`.
    fn scroll_region_down(
        &mut self,
        _region: std::ops::Range<u16>,
        _amount: u16,
    ) -> io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::cursor_position_report;
    use uncurses::event::{Event, Key, KeyCode, KeyModifiers};
    use uncurses::layout::Position;

    #[test]
    fn report_from_plain_cursor_position() {
        let ev = Event::CursorPosition(Position::new(4, 9));
        assert_eq!(cursor_position_report(&ev), Some(Position::new(4, 9)));
    }

    #[test]
    fn report_unwraps_multi_for_row1_f3_ambiguity() {
        // At terminal row 1 the CPR wire form collides with modified-F3, so
        // the decoder emits both inside a Multi; the report is still found.
        let ev = Event::Multi(vec![
            Event::KeyPress(Key::new(KeyCode::F(3), KeyModifiers::empty())),
            Event::CursorPosition(Position::new(2, 0)),
        ]);
        assert_eq!(cursor_position_report(&ev), Some(Position::new(2, 0)));
    }

    #[test]
    fn report_ignores_unrelated_events() {
        let ev = Event::KeyPress(Key::new(KeyCode::Char('x'), KeyModifiers::empty()));
        assert_eq!(cursor_position_report(&ev), None);
        let multi = Event::Multi(vec![Event::FocusIn, Event::FocusOut]);
        assert_eq!(cursor_position_report(&multi), None);
    }
}