uncurses_ratatui/backend.rs
1use std::io::{self, Write};
2use std::time::{Duration, Instant};
3
4use ratatui::Viewport;
5use ratatui::backend::{Backend, ClearType, WindowSize};
6use ratatui::buffer::Cell as RtCell;
7use ratatui::layout::{Position as RtPosition, Size as RtSize};
8use uncurses::buffer::SurfaceMut;
9use uncurses::cell::Cell as CzCell;
10use uncurses::event::{Event, Input, KeyCode};
11use uncurses::layout::Position;
12use uncurses::program::Program;
13use uncurses::terminal::{Stdin, Stdout, TtyInput, TtyOutput};
14
15use crate::convert::cell_from_ratatui;
16
17/// Platform bound required for an output handle usable by the backend.
18///
19/// The handle must be writable, cheaply copyable, and expose the platform OS
20/// handle used by terminal mode and window-size operations. Process stdio and
21/// controlling-terminal output handles satisfy this bound.
22///
23/// This trait is sealed only by its bounds: any type that implements the listed
24/// platform traits implements `Output` automatically. It is the output
25/// counterpart to the `Input` bound on the backend's input handle.
26#[cfg(unix)]
27pub trait Output: Write + Copy + std::os::fd::AsFd {}
28#[cfg(unix)]
29impl<T: Write + Copy + std::os::fd::AsFd> Output for T {}
30/// Platform bound required for an output handle usable by the backend.
31///
32/// The handle must be writable, cheaply copyable, and expose the platform OS
33/// handle used by terminal mode and window-size operations. Process stdio and
34/// controlling-terminal output handles satisfy this bound.
35///
36/// This trait is sealed only by its bounds: any type that implements the listed
37/// platform traits implements `Output` automatically. It is the output
38/// counterpart to the `Input` bound on the backend's input handle.
39#[cfg(windows)]
40pub trait Output: Write + Copy + std::os::windows::io::AsHandle {}
41#[cfg(windows)]
42impl<T: Write + Copy + std::os::windows::io::AsHandle> Output for T {}
43
44/// How long [`Backend::get_cursor_position`] waits for a cursor-position
45/// report before falling back to the origin. The widget library calls it at
46/// most once per inline-viewport setup, so a small budget keeps setup
47/// responsive on terminals that never answer.
48const CURSOR_QUERY_TIMEOUT: Duration = Duration::from_millis(100);
49
50/// Backend implementation that drives rendering, input, and lifecycle through
51/// one [`Program`].
52///
53/// ## What it wraps
54///
55/// The wrapped program owns the terminal handle, the screen, and the event
56/// source. Keeping those pieces behind one backend means frame rendering,
57/// cursor movement, clearing, size tracking, raw-mode setup, and input reads all
58/// observe the same terminal state.
59///
60/// ## Rendering
61///
62/// [`Backend::draw`] converts each concrete buffer cell to an uncurses cell and
63/// writes it into the screen's buffer, staging the frame without any I/O.
64/// [`Backend::flush`] then calls [`Screen::render`](uncurses::screen::Screen::render), which diffs the buffer,
65/// stages the minimal escape bytes, and flushes them through the screen.
66///
67/// ```text
68/// ┌─────────────────────┐
69/// │ Frame buffer │
70/// └─────────┬───────────┘
71/// │ buffer cells
72/// ▼
73/// ┌─────────────────────┐
74/// │ UncursesBackend │
75/// │ draw + conversion │
76/// └─────────┬───────────┘
77/// │ Screen::set_cell
78/// ▼
79/// ┌─────────────────────┐
80/// │ Screen (diff render) │
81/// │ diff against output │
82/// └─────────┬───────────┘
83/// │ flush → Screen::render
84/// ▼
85/// terminal
86/// ```
87///
88/// ## Viewports
89///
90/// The default viewport is [`Viewport::Fullscreen`]. The init helpers call
91/// [`set_viewport`](Self::set_viewport) with the viewport stored in
92/// terminal options. Inline viewports keep an absolute origin in
93/// `inline_origin`; drawing subtracts that origin so the screen buffer contains
94/// only the inline region.
95///
96/// ## Events
97///
98/// Use [`poll_event`](Self::poll_event),
99/// [`try_read_event`](Self::try_read_event), and [`read_event`](Self::read_event)
100/// for synchronous loops, or [`event_stream`](Self::event_stream) with the
101/// `async` feature. Both paths yield the same events.
102///
103/// ## Setup
104///
105/// Construction is inert: it does not enter raw mode, enter the alternate
106/// screen, hide the cursor, or choose a non-default viewport. Call
107/// [`init`](Self::init) for manual setup, or
108/// use the crate-level setup helpers for process stdio. Call
109/// [`restore`](Self::restore) when the session ends.
110pub struct UncursesBackend<I: Input, O: Write> {
111 program: Program<I, O>,
112 /// The widget-library viewport, set via [`set_viewport`](Self::set_viewport)
113 /// (by `init_with_options`). Determines the screen buffer height
114 /// (inline height vs full terminal height) and whether `draw` /
115 /// `set_cursor_position` translate absolute rows into the inline
116 /// region.
117 viewport: Viewport,
118 /// Top row of an inline viewport. Seeded at initial setup from
119 /// [`get_cursor_position`](Backend::get_cursor_position), then kept
120 /// exact across resizes by [`clear_region`](Backend::clear_region),
121 /// which observes the cursor the widget library parks at the recomputed
122 /// viewport top before clearing. Absolute rows are translated down by this when
123 /// rendering an inline viewport.
124 inline_origin: u16,
125 /// Last full terminal size observed by [`size`](Backend::size) /
126 /// [`window_size`](Backend::window_size). When it changes the screen
127 /// is marked stale (`size_dirty`) so the next [`draw`](Backend::draw)
128 /// repaints in full. Tracked behind `Cell` because `size` takes
129 /// `&self`.
130 last_size: std::cell::Cell<(u16, u16)>,
131 /// Set when `last_size` changes; consumed by `draw` to invalidate the
132 /// screen.
133 size_dirty: std::cell::Cell<bool>,
134 /// Absolute row last requested by
135 /// [`set_cursor_position`](Backend::set_cursor_position). When the widget
136 /// library recomputes an inline viewport (initial setup and every resize) it
137 /// positions the cursor at the viewport's top row before clearing it,
138 /// so [`clear_region`](Backend::clear_region) reads this back as the
139 /// fresh `inline_origin` — the only place the *true* viewport top is
140 /// observable (the cursor reported by `get_cursor_position` sits at the
141 /// app's cursor, which need not be the viewport top).
142 last_cursor_row: u16,
143}
144
145impl UncursesBackend<Stdin, Stdout> {
146 /// Build a backend over process standard input and output.
147 ///
148 /// This constructs a [`Program`] with `stdin` and `stdout`, then wraps it in
149 /// [`UncursesBackend::new`]. It does not enter raw mode, hide the cursor,
150 /// enter the alternate screen, or apply screen options.
151 ///
152 /// ## Returns
153 ///
154 /// A backend ready for manual setup or for construction of a widget-library
155 /// terminal.
156 ///
157 /// ## Errors
158 ///
159 /// Returns errors from [`Program::stdio`], including failures to inspect the
160 /// terminal size or initialize the input event source.
161 ///
162 /// ## Panics
163 ///
164 /// Does not intentionally panic.
165 ///
166 /// ## Usage note
167 ///
168 /// Prefer crate-level setup helpers when process stdio and conventional
169 /// setup are sufficient.
170 pub fn stdio() -> io::Result<Self> {
171 Ok(Self::new(Program::stdio()?))
172 }
173}
174
175impl UncursesBackend<TtyInput, TtyOutput> {
176 /// Build a backend over the controlling terminal instead of process stdio.
177 ///
178 /// This opens the platform controlling terminal (`/dev/tty` on Unix,
179 /// console handles on Windows), constructs a [`Program`], and wraps it in
180 /// [`UncursesBackend::new`]. It is useful when standard input or output is
181 /// redirected but the application still needs an interactive terminal.
182 ///
183 /// ## Returns
184 ///
185 /// A backend ready for manual setup or for construction of a widget-library
186 /// terminal.
187 ///
188 /// ## Errors
189 ///
190 /// Returns errors from opening or initializing the controlling terminal,
191 /// sizing the buffer, or creating the input event source.
192 ///
193 /// ## Panics
194 ///
195 /// Does not intentionally panic.
196 ///
197 /// ## Usage note
198 ///
199 /// Like [`stdio`](UncursesBackend::stdio), this constructor is inert; call
200 /// [`init`](UncursesBackend::init) before interactive use.
201 pub fn open() -> io::Result<Self> {
202 Ok(Self::new(Program::open()?))
203 }
204}
205
206impl<I, O> UncursesBackend<I, O>
207where
208 I: Input,
209 O: Write,
210{
211 /// Build a backend over an existing [`Program`].
212 ///
213 /// Use this when the screen has been constructed by the caller, or when the
214 /// terminal handles are not process stdio or the controlling terminal. The
215 /// backend starts with [`Viewport::Fullscreen`], an inline origin of `0`,
216 /// no remembered terminal size, and no dirty-size flag.
217 ///
218 /// ## Parameters
219 ///
220 /// * `screen` - the screen facade that will own rendering, input, and
221 /// terminal lifecycle for this backend.
222 ///
223 /// ## Returns
224 ///
225 /// A backend wrapping `screen`.
226 ///
227 /// ## Panics
228 ///
229 /// Does not panic.
230 ///
231 /// ## Usage note
232 ///
233 /// This does not call [`Program::init`]. Initialize the screen through the
234 /// backend or manually before starting an interactive session.
235 pub fn new(program: Program<I, O>) -> Self {
236 Self {
237 program,
238 viewport: Viewport::Fullscreen,
239 inline_origin: 0,
240 last_size: std::cell::Cell::new((0, 0)),
241 size_dirty: std::cell::Cell::new(false),
242 last_cursor_row: 0,
243 }
244 }
245
246 /// Record an observed full terminal size; if it differs from the last,
247 /// flag the screen stale so the next [`draw`](Backend::draw) repaints
248 /// in full. Takes `&self` so `size`/`window_size` can call it.
249 fn note_size(&self, size: (u16, u16)) {
250 if self.last_size.get() != size {
251 self.last_size.set(size);
252 self.size_dirty.set(true);
253 }
254 }
255
256 /// Record the viewport used by the surrounding terminal.
257 ///
258 /// The setup helpers call this with the viewport from terminal options. The
259 /// backend uses it to size the screen buffer and, for inline viewports,
260 /// translate absolute frame rows into the inline buffer region. The default before this method is called is
261 /// [`Viewport::Fullscreen`].
262 ///
263 /// ## Parameters
264 ///
265 /// * `viewport` - the viewport selected for the terminal.
266 ///
267 /// ## Panics
268 ///
269 /// Does not panic.
270 ///
271 /// ## Usage note
272 ///
273 /// For [`Viewport::Inline`], the screen buffer is resized immediately to
274 /// the requested height clamped to the current terminal height. Fullscreen
275 /// and fixed viewports are stored without resizing here; drawing keeps the
276 /// screen in step with the current full size.
277 pub fn set_viewport(&mut self, viewport: Viewport) {
278 if let Viewport::Inline(height) = viewport {
279 let size = self.program.screen().size();
280 let h = height.min(size.height);
281 self.program.screen_mut().resize((size.width, h));
282 }
283 self.viewport = viewport;
284 }
285
286 /// Borrow the wrapped [`Program`] facade.
287 ///
288 /// Use this for read-only access to screen state such as cached size
289 /// information. Rendering and input operations that mutate the
290 /// screen require [`program_mut`](Self::program_mut).
291 ///
292 /// ## Returns
293 ///
294 /// A shared reference to the screen owned by this backend.
295 ///
296 /// ## Panics
297 ///
298 /// Does not panic.
299 pub fn program(&self) -> &Program<I, O> {
300 &self.program
301 }
302
303 /// Mutably borrow the wrapped [`Program`] facade.
304 ///
305 /// Use this for screen operations not surfaced by the backend: setting
306 /// screen modes, using the alternate screen directly, configuring renderer
307 /// options, or manual rendering. For the async event stream, prefer the
308 /// backend's own [`event_stream`](Self::event_stream).
309 ///
310 /// ## Returns
311 ///
312 /// A mutable reference to the screen owned by this backend.
313 ///
314 /// ## Panics
315 ///
316 /// Does not panic.
317 ///
318 /// ## Usage note
319 ///
320 /// Avoid mixing manual buffer writes with normal backend drawing unless the
321 /// ordering is deliberate; both paths affect the same buffer.
322 pub fn program_mut(&mut self) -> &mut Program<I, O> {
323 &mut self.program
324 }
325
326 /// Poll the wrapped screen's input source.
327 ///
328 /// This delegates to [`Program::poll_event`], which drives the underlying
329 /// event source for at most `timeout`. It does not remove an event from the
330 /// queue; call [`try_read_event`](Self::try_read_event) or
331 /// [`read_event`](Self::read_event) after it reports availability.
332 ///
333 /// ## Parameters
334 ///
335 /// * `timeout` - `Some(duration)` to wait up to that duration, or `None` to
336 /// use the event source's blocking poll behavior.
337 ///
338 /// ## Returns
339 ///
340 /// `Ok(true)` if an event is available, `Ok(false)` if the poll timed out.
341 ///
342 /// ## Errors
343 ///
344 /// Returns I/O errors from the input source.
345 ///
346 /// ## Panics
347 ///
348 /// Panics if the screen's internal event-source lock is poisoned.
349 ///
350 /// ## Usage note
351 ///
352 /// Polling through the backend keeps capability replies and application
353 /// input on the same event source.
354 pub fn poll_event(&self, timeout: Option<Duration>) -> io::Result<bool> {
355 self.program.poll_event(timeout)
356 }
357
358 /// Try to read the next queued event without blocking.
359 ///
360 /// This delegates to the wrapped [`Program`].
361 ///
362 /// ## Returns
363 ///
364 /// `Some(event)` when an event was already queued; `None` when reading would
365 /// require blocking or additional I/O.
366 ///
367 /// ## Panics
368 ///
369 /// Panics if the screen's internal event-source lock is poisoned.
370 ///
371 /// ## Usage note
372 ///
373 /// Pair this with [`poll_event`](Self::poll_event) for timeout-based loops.
374 pub fn try_read_event(&mut self) -> io::Result<Option<Event>> {
375 self.program.try_read_event()
376 }
377
378 /// Block until the next event is available.
379 ///
380 /// This delegates to the wrapped [`Program`].
381 ///
382 /// ## Returns
383 ///
384 /// The next decoded terminal [`Event`].
385 ///
386 /// ## Errors
387 ///
388 /// Returns I/O errors from the input source.
389 ///
390 /// ## Panics
391 ///
392 /// Panics if the screen's internal event-source lock is poisoned.
393 ///
394 /// ## Usage note
395 ///
396 /// Use this for simple blocking event loops. Use
397 /// [`event_stream`](Self::event_stream) instead when the `async` feature is
398 /// enabled and the application is already asynchronous.
399 pub fn read_event(&mut self) -> io::Result<Event> {
400 self.program.read_event()
401 }
402
403 /// Build an async [`EventStream`](uncurses::event::EventStream) over the
404 /// wrapped screen's input.
405 ///
406 /// The stream shares the screen's decoder, so it does not race the sync read
407 /// methods on the same file descriptor. It yields the same events.
408 ///
409 /// ## Returns
410 ///
411 /// An owned `EventStream` you can hold alongside `&mut self` (it shares the
412 /// source by handle rather than borrowing the backend).
413 #[cfg(feature = "async")]
414 pub fn event_stream(&self) -> uncurses::event::EventStream<I>
415 where
416 I: 'static,
417 {
418 self.program.event_stream()
419 }
420}
421
422impl<I, O> UncursesBackend<I, O>
423where
424 I: Input + Copy,
425 O: Output,
426{
427 /// Begin an interactive session using the stored program options.
428 ///
429 /// This delegates to [`Program::init`]: the program enters raw mode and
430 /// applies its stored startup settings. It sends no capability query, and does
431 /// not enter the alternate screen or hide the cursor by itself; the
432 /// crate-level setup helpers perform those additional steps.
433 ///
434 /// ## Returns
435 ///
436 /// `Ok(())` after raw mode and screen initialization have been staged.
437 ///
438 /// ## Errors
439 ///
440 /// Returns errors from raw-mode setup, autoresizing, or bracketed paste
441 /// setup.
442 ///
443 /// ## Panics
444 ///
445 /// Does not intentionally panic.
446 ///
447 /// ## Usage note
448 ///
449 /// Pair successful manual initialization with [`restore`](Self::restore).
450 pub fn init(&mut self) -> io::Result<()> {
451 self.program.init()
452 }
453
454 /// Restore terminal state after a backend-managed session.
455 ///
456 /// This delegates to [`Program::pause`]. It tears down staged modes, resets
457 /// buffer-controlled state such as alternate screen and cursor visibility,
458 /// flushes pending output, and restores the terminal mode while keeping the
459 /// screen available for future use.
460 ///
461 /// ## Returns
462 ///
463 /// `Ok(())` after teardown and terminal-mode restoration complete.
464 ///
465 /// ## Errors
466 ///
467 /// Returns errors from mode teardown, flushing, or terminal restoration.
468 ///
469 /// ## Panics
470 ///
471 /// Does not intentionally panic.
472 ///
473 /// ## Usage note
474 ///
475 /// Treat this as the single teardown entry point for backend-managed setup.
476 pub fn restore(&mut self) -> io::Result<()> {
477 self.program.pause()
478 }
479}
480
481impl<I, O> Write for UncursesBackend<I, O>
482where
483 I: Input,
484 O: Write,
485{
486 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
487 self.program.screen_mut().write(buf)
488 }
489
490 fn flush(&mut self) -> io::Result<()> {
491 Write::flush(self.program.screen_mut())
492 }
493}
494
495impl<I, O> Backend for UncursesBackend<I, O>
496where
497 I: Input + Copy,
498 O: Output,
499{
500 type Error = io::Error;
501
502 /// Stage a frame's cells into the wrapped screen buffer.
503 ///
504 /// The iterator supplies absolute buffer coordinates and concrete cells.
505 /// Each cell is converted to an uncurses cell and written to the screen.
506 /// This method only stages into the buffer; the buffer diff is computed
507 /// and written when the surrounding terminal calls [`Backend::flush`].
508 ///
509 /// ## Parameters
510 ///
511 /// * `content` - visible frame cells as `(x, y, cell)` triples.
512 ///
513 /// ## Errors
514 ///
515 /// This implementation performs no I/O and returns `Ok(())`; renderer and
516 /// output errors surface from [`Backend::flush`].
517 ///
518 /// ## Usage note
519 ///
520 /// Inline viewports translate `y` by the stored inline origin. A detected
521 /// terminal-size change invalidates the screen so this frame repaints in
522 /// full.
523 fn draw<'a, J>(&mut self, content: J) -> io::Result<()>
524 where
525 J: Iterator<Item = (u16, u16, &'a RtCell)>,
526 {
527 // Keep the screen buffer in step with what the widget library draws into.
528 // For an inline viewport the buffer is only the inline height and
529 // the widget library's absolute rows are translated down by the viewport top;
530 // otherwise it tracks the full terminal size.
531 let size = self.program.screen().size();
532 let (full_w, full_h) = self
533 .program
534 .get_window_size()
535 .ok()
536 .map(|s| (s.col, s.row))
537 .filter(|&(c, r)| c != 0 && r != 0)
538 .unwrap_or((size.width, size.height));
539 let (w, h, top) = match self.viewport {
540 Viewport::Inline(height) => {
541 let h = height.min(full_h);
542 let top = self.inline_origin.min(full_h.saturating_sub(h));
543 (full_w, h, top)
544 }
545 _ => (full_w, full_h, 0),
546 };
547 // Repaint in full if the terminal size changed since the last
548 // observation (covers cases where the buffer dimensions stay the
549 // same, e.g. an inline viewport on a vertical-only resize).
550 self.note_size((full_w, full_h));
551 if self.size_dirty.take() {
552 self.program.screen_mut().invalidate();
553 }
554 if (w, h) != (size.width, size.height) {
555 self.program.screen_mut().resize((w, h));
556 }
557 for (x, y, rc) in content {
558 let cell = cell_from_ratatui(rc);
559 self.program
560 .screen_mut()
561 .set_cell((x, y.saturating_sub(top)), &cell);
562 }
563 Ok(())
564 }
565
566 /// Hide the terminal cursor immediately.
567 ///
568 /// When the program records a visible cursor, this delegates to
569 /// [`Program::hide_cursor`], which emits the mode and flushes. Ratatui
570 /// calls this on every frame without a cursor, so a cursor already
571 /// recorded as hidden emits no new mode. It flushes staged output
572 /// instead, which delivers a mode left by an earlier failed flush.
573 ///
574 /// ## Errors
575 ///
576 /// Returns output errors from flushing the visibility change.
577 fn hide_cursor(&mut self) -> io::Result<()> {
578 if self.program.state().cursor_visible() {
579 self.program.hide_cursor()
580 } else {
581 Write::flush(self.program.screen_mut())
582 }
583 }
584
585 /// Show the terminal cursor immediately.
586 ///
587 /// When the program records a hidden cursor, this delegates to
588 /// [`Program::show_cursor`], which emits the mode and flushes. Ratatui
589 /// calls this on every frame with a cursor, so a cursor already recorded
590 /// as visible emits no new mode. It flushes staged output instead, which
591 /// delivers a mode left by an earlier failed flush.
592 ///
593 /// ## Errors
594 ///
595 /// Returns output errors from flushing the visibility change.
596 fn show_cursor(&mut self) -> io::Result<()> {
597 if self.program.state().cursor_visible() {
598 Write::flush(self.program.screen_mut())
599 } else {
600 self.program.show_cursor()
601 }
602 }
603
604 /// Query the terminal for its current cursor position.
605 ///
606 /// This sends a cursor-position request, then polls input until a
607 /// [`Event::CursorPosition`] report arrives or the short setup timeout
608 /// expires. Non-report events read while waiting are unread back into the
609 /// screen in their original order so the application can still consume them.
610 /// If no report arrives, the backend returns the origin.
611 ///
612 /// ## Returns
613 ///
614 /// The zero-based cursor position reported by the terminal, or `(0, 0)` on
615 /// timeout. Inline viewports also seed their initial origin from this row.
616 ///
617 /// ## Errors
618 ///
619 /// Returns errors from writing the cursor-position request or polling the
620 /// input source.
621 ///
622 /// ## Usage note
623 ///
624 /// The reply parser also accepts the multi-event ambiguity that occurs when
625 /// the row-1 CPR wire form collides with a modified function key sequence.
626 ///
627 /// Cursor reports carry no request ID, and this method takes the first
628 /// report it reads. Read the replies to your own cursor requests before
629 /// ratatui calls this method. Ratatui calls it when it builds an inline
630 /// terminal and when a draw finds a new size. Selecting
631 /// [`Probe::eaw_width`](uncurses::program::Probe::eaw_width) adds a cursor
632 /// request to a capability batch. Use queries without cursor measurements
633 /// for a bounded startup wait before drawing. A timeout leaves cursor
634 /// replies pending.
635 fn get_cursor_position(&mut self) -> io::Result<RtPosition> {
636 // Query the terminal for its cursor position (CPR): write the
637 // request, then read events until the report arrives or the timeout
638 // elapses. The reply is absolute, zero-based, and matches the widget library's
639 // coordinate space (the same space `set_cursor_position` writes
640 // absolute moves into), so it needs no translation. Fall back to the
641 // origin if the terminal does not answer.
642 self.program.request_cursor_position()?;
643 let deadline = Instant::now() + CURSOR_QUERY_TIMEOUT;
644 // Events read while waiting for the report are not ours to consume;
645 // stash them and put them back (in original order) so the app's loop
646 // still sees them.
647 let mut stash: Vec<Event> = Vec::new();
648 // Queued events are read before the deadline check, so the report
649 // that the decoder queues behind its F3 is never left behind.
650 let found = loop {
651 match self.program.try_read_event()? {
652 Some(Event::CursorPosition { position, .. }) => {
653 // A standard report on row 1, column 1 to 16, also spells
654 // modified F3, and the decoder emits that key just before
655 // the report. It belongs to this request, so drop it.
656 if position.y == 0
657 && position.x <= 15
658 && matches!(stash.last(), Some(Event::KeyPress(key))
659 if key.code == KeyCode::F(3) && !key.repeat)
660 {
661 stash.pop();
662 }
663 break Some(position);
664 }
665 Some(ev) => stash.push(ev),
666 None => {
667 let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
668 break None;
669 };
670 if !self.program.poll_event(Some(remaining))? {
671 break None;
672 }
673 }
674 }
675 };
676 for ev in stash.into_iter().rev() {
677 self.program.unread_event(ev);
678 }
679 let pos = found.unwrap_or(Position::new(0, 0));
680 // the widget library calls this to anchor an inline viewport at the cursor row,
681 // then draws content at absolute rows starting there. Seed the
682 // inline origin so the very first `draw` translates those absolute
683 // rows into the inline buffer; before this the origin defaulted to 0
684 // and a cursor below the top clipped the first frame. The exact top
685 // is still re-derived by `clear_region` on later resizes.
686 if matches!(self.viewport, Viewport::Inline(_)) {
687 self.inline_origin = pos.y;
688 self.last_cursor_row = pos.y;
689 }
690 Ok(RtPosition { x: pos.x, y: pos.y })
691 }
692
693 /// Move the terminal cursor to an absolute position immediately.
694 ///
695 /// The backend writes an absolute CUP escape directly, records the row for
696 /// inline-viewport bookkeeping, updates the renderer's tracked cursor
697 /// position in buffer-relative coordinates, and flushes.
698 ///
699 /// ## Parameters
700 ///
701 /// * `position` - zero-based absolute cursor position requested by the
702 /// surrounding terminal.
703 ///
704 /// ## Errors
705 ///
706 /// Returns output errors from writing or flushing the cursor movement.
707 ///
708 /// ## Usage note
709 ///
710 /// Direct absolute movement keeps the renderer and inline viewport aligned;
711 /// it intentionally bypasses the renderer's cost-optimized relative moves.
712 fn set_cursor_position<P: Into<RtPosition>>(&mut self, position: P) -> io::Result<()> {
713 let p = position.into();
714 // Remember the requested row: when the widget library clears an inline
715 // viewport it places the cursor at the viewport top first, letting
716 // `clear_region` recover the (possibly shifted) origin on resize.
717 self.last_cursor_row = p.y;
718 // Emit an absolute CUP directly rather than going through the
719 // renderer's cost-optimized (possibly relative) move: ratatui calls
720 // this to place its own cursor, so the move must be unconditional
721 // and absolute.
722 uncurses::ansi::cursor::write_cup(self.program.screen_mut(), p.y, p.x)?;
723 // Keep the renderer's cursor bookkeeping in step with the move we
724 // just made, translated into the (inline) buffer. In relative-cursor
725 // mode merely invalidating would lose the absolute row — the next
726 // frame's vertical moves would drift the viewport — so assert the
727 // exact buffer-relative position instead. For a non-inline viewport
728 // `inline_origin` is 0, so this is the absolute position unchanged.
729 let top = match self.viewport {
730 Viewport::Inline(_) => self.inline_origin,
731 _ => 0,
732 };
733 self.program
734 .screen_mut()
735 .set_tracked_cursor((p.x, p.y.saturating_sub(top)));
736 Write::flush(self.program.screen_mut())
737 }
738
739 /// Clear the entire backend surface immediately.
740 ///
741 /// This delegates to [`Backend::clear_region`] with [`ClearType::All`].
742 ///
743 /// ## Errors
744 ///
745 /// Returns output errors from rendering and flushing the staged blank cells.
746 fn clear(&mut self) -> io::Result<()> {
747 self.clear_region(ClearType::All)
748 }
749
750 /// Clear part of the backend surface immediately.
751 ///
752 /// The implementation blanks only the cells covered by `clear_type` in the
753 /// screen's staging buffer, invalidates tracked cursor state, renders the
754 /// diff, and flushes before returning. For inline viewports,
755 /// [`ClearType::AfterCursor`] is also the resize/viewport-reanchor path: the
756 /// last absolute cursor row becomes the new inline origin and the full
757 /// inline buffer is blanked.
758 ///
759 /// ## Parameters
760 ///
761 /// * `clear_type` - the clear region requested by the surrounding terminal.
762 ///
763 /// ## Errors
764 ///
765 /// Returns output errors from rendering or flushing the clear operation.
766 ///
767 /// ## Usage note
768 ///
769 /// Clearing is immediate by backend contract; unlike [`Backend::draw`], this
770 /// method does not wait for a later flush call to make output visible.
771 fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {
772 let size = self.program.screen().size();
773 let w = size.width;
774 let h = size.height;
775 let cursor = self.program.screen().tracked_cursor().unwrap_or_default();
776 if w == 0 || h == 0 {
777 return Ok(());
778 }
779 let region = match clear_type {
780 ClearType::All => Some(uncurses::layout::Rect::new(0, 0, w, h)),
781 ClearType::AfterCursor if matches!(self.viewport, Viewport::Inline(_)) => {
782 // Inline-viewport resize/clear path. ratatui homes the
783 // cursor to the viewport's (recomputed) top row, then erases
784 // to the end of the screen — for our inline buffer that is
785 // the whole thing. Adopt the fresh origin (the app cursor
786 // reported by `get_cursor_position` may sit anywhere in the
787 // viewport, so this is the authoritative top), and blank the
788 // entire staging buffer so the upcoming full repaint starts
789 // clean: the staging buffer preserves overlapping cells
790 // across a grow, which a diff-style painter never overwrites,
791 // and would otherwise duplicate the previous frame's right
792 // edge.
793 self.inline_origin = self.last_cursor_row;
794 Some(uncurses::layout::Rect::new(0, 0, w, h))
795 }
796 ClearType::AfterCursor => {
797 if cursor.y < h {
798 let tail_x = cursor.x.min(w);
799 self.program.screen_mut().fill_rect(
800 uncurses::layout::Rect::new(tail_x, cursor.y, w - tail_x, 1),
801 &CzCell::BLANK,
802 );
803 }
804 (cursor.y + 1 < h)
805 .then(|| uncurses::layout::Rect::new(0, cursor.y + 1, w, h - cursor.y - 1))
806 }
807 ClearType::BeforeCursor => {
808 if cursor.y > 0 {
809 self.program.screen_mut().fill_rect(
810 uncurses::layout::Rect::new(0, 0, w, cursor.y),
811 &CzCell::BLANK,
812 );
813 }
814 (cursor.y < h).then(|| {
815 let head_w = (cursor.x.min(w).saturating_add(1)).min(w);
816 uncurses::layout::Rect::new(0, cursor.y, head_w, 1)
817 })
818 }
819 ClearType::CurrentLine => {
820 (cursor.y < h).then(|| uncurses::layout::Rect::new(0, cursor.y, w, 1))
821 }
822 ClearType::UntilNewLine => (cursor.y < h && cursor.x < w)
823 .then(|| uncurses::layout::Rect::new(cursor.x, cursor.y, w - cursor.x, 1)),
824 };
825 if let Some(region) = region {
826 self.program.screen_mut().fill_rect(region, &CzCell::BLANK);
827 }
828 self.program.screen_mut().invalidate_tracked_cursor();
829 // Push the staged blanks to the wire so the clear takes effect
830 // before this call returns, matching the immediate-clear contract.
831 self.program.screen_mut().render()
832 }
833
834 /// Return the current terminal size in cells.
835 ///
836 /// This queries the live window size through the screen. If that query fails
837 /// or returns zero dimensions, it falls back to the current screen buffer
838 /// size. Size changes are recorded so the next draw can invalidate and
839 /// repaint.
840 ///
841 /// ## Returns
842 ///
843 /// The full terminal width and height in cells.
844 ///
845 /// ## Errors
846 ///
847 /// This implementation falls back on query failure and currently returns
848 /// `Ok` with the best available size.
849 fn size(&self) -> io::Result<RtSize> {
850 // The full terminal size: the widget library needs it to anchor inline
851 // viewports and to detect resizes. Fall back to the screen's
852 // buffer size if the query fails (e.g. output is not a tty).
853 let size = self.program.screen().size();
854 let (width, height) = self
855 .program
856 .get_window_size()
857 .ok()
858 .map(|s| (s.col, s.row))
859 .filter(|&(c, r)| c != 0 && r != 0)
860 .unwrap_or((size.width, size.height));
861 self.note_size((width, height));
862 Ok(RtSize { width, height })
863 }
864
865 /// Return the current terminal size in cells and pixels.
866 ///
867 /// This uses the screen's live window-size query when available. Cell
868 /// dimensions fall back to the buffer size on failure or zero reports; pixel
869 /// dimensions fall back to zero when unavailable. Size changes are recorded
870 /// so the next draw can invalidate and repaint.
871 ///
872 /// ## Returns
873 ///
874 /// A [`WindowSize`] with `columns_rows` populated from the best available
875 /// cell size and `pixels` populated from the query when reported.
876 ///
877 /// ## Errors
878 ///
879 /// This implementation falls back on query failure and currently returns
880 /// `Ok` with the best available size.
881 fn window_size(&mut self) -> io::Result<WindowSize> {
882 // One query reports both cell and pixel dimensions; fall back to
883 // the screen's buffer size for cells if it fails.
884 let size = self.program.screen().size();
885 let ws = self.program.get_window_size().ok();
886 let (width, height) = ws
887 .as_ref()
888 .map(|w| (w.col, w.row))
889 .filter(|&(c, r)| c != 0 && r != 0)
890 .unwrap_or((size.width, size.height));
891 self.note_size((width, height));
892 Ok(WindowSize {
893 columns_rows: RtSize { width, height },
894 pixels: RtSize {
895 width: ws.as_ref().map(|w| w.xpixel).unwrap_or(0),
896 height: ws.as_ref().map(|w| w.ypixel).unwrap_or(0),
897 },
898 })
899 }
900
901 /// Diff the staged buffer and write the frame to the output handle.
902 ///
903 /// [`Backend::draw`] only stages cells into the buffer; this is where the
904 /// renderer computes the minimal diff against the tracked terminal and
905 /// flushes the resulting bytes through the wrapped screen.
906 ///
907 /// ## Errors
908 ///
909 /// Returns renderer or output errors from the wrapped screen.
910 fn flush(&mut self) -> io::Result<()> {
911 self.program.screen_mut().render()
912 }
913
914 /// Append blank lines to the underlying output.
915 ///
916 /// The backend writes `n` newline-terminated blank lines through the screen
917 /// and flushes immediately.
918 ///
919 /// ## Parameters
920 ///
921 /// * `n` - number of lines to append.
922 ///
923 /// ## Errors
924 ///
925 /// Returns output errors from writing or flushing the lines.
926 fn append_lines(&mut self, n: u16) -> io::Result<()> {
927 for _ in 0..n {
928 let _ = writeln!(self.program.screen_mut());
929 }
930 Write::flush(self.program.screen_mut())
931 }
932
933 /// Handle a request to scroll a region upward.
934 ///
935 /// This backend does not use terminal scrolling for region updates; drawing
936 /// and buffer diffing repaint the resulting cells instead. The method is a
937 /// no-op that satisfies the backend trait.
938 ///
939 /// ## Parameters
940 ///
941 /// * `_region` - ignored requested row range.
942 /// * `_amount` - ignored scroll amount.
943 ///
944 /// ## Errors
945 ///
946 /// This implementation is infallible and returns `Ok(())`.
947 fn scroll_region_up(&mut self, _region: std::ops::Range<u16>, _amount: u16) -> io::Result<()> {
948 Ok(())
949 }
950
951 /// Handle a request to scroll a region downward.
952 ///
953 /// This backend does not use terminal scrolling for region updates; drawing
954 /// and buffer diffing repaint the resulting cells instead. The method is a
955 /// no-op that satisfies the backend trait.
956 ///
957 /// ## Parameters
958 ///
959 /// * `_region` - ignored requested row range.
960 /// * `_amount` - ignored scroll amount.
961 ///
962 /// ## Errors
963 ///
964 /// This implementation is infallible and returns `Ok(())`.
965 fn scroll_region_down(
966 &mut self,
967 _region: std::ops::Range<u16>,
968 _amount: u16,
969 ) -> io::Result<()> {
970 Ok(())
971 }
972}
973
974#[cfg(all(test, unix))]
975mod tests {
976 use std::fs::File;
977 use std::io::{self, Write};
978 use std::os::fd::{AsFd, BorrowedFd, FromRawFd};
979 use std::sync::Mutex;
980 use std::sync::atomic::{AtomicBool, Ordering};
981
982 use ratatui::backend::Backend;
983 use uncurses::libc;
984 use uncurses::program::Program;
985 use uncurses::terminal::{EnvList, Terminal};
986
987 use super::UncursesBackend;
988
989 /// Output recorded by one test, with a switch that fails the next write.
990 struct Recorded {
991 tty: &'static File,
992 bytes: Mutex<Vec<u8>>,
993 fail_next: AtomicBool,
994 }
995
996 impl Recorded {
997 fn take(&self) -> Vec<u8> {
998 std::mem::take(&mut self.bytes.lock().unwrap())
999 }
1000 }
1001
1002 /// Copyable output that records bytes and borrows the PTY for size queries.
1003 #[derive(Clone, Copy)]
1004 struct Recorder(&'static Recorded);
1005
1006 impl Write for Recorder {
1007 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1008 if self.0.fail_next.swap(false, Ordering::Relaxed) {
1009 return Err(io::Error::other("injected write failure"));
1010 }
1011 self.0.bytes.lock().unwrap().extend_from_slice(buf);
1012 Ok(buf.len())
1013 }
1014
1015 fn flush(&mut self) -> io::Result<()> {
1016 Ok(())
1017 }
1018 }
1019
1020 impl AsFd for Recorder {
1021 fn as_fd(&self) -> BorrowedFd<'_> {
1022 self.0.tty.as_fd()
1023 }
1024 }
1025
1026 /// Open a PTY and return its slave side, or `None` where none is usable.
1027 /// Both sides stay open for the rest of the test process.
1028 fn pty_slave() -> Option<&'static File> {
1029 // `ptsname` returns static storage, so concurrent tests take turns.
1030 static PTSNAME: Mutex<()> = Mutex::new(());
1031 let _guard = PTSNAME.lock().unwrap_or_else(|e| e.into_inner());
1032 unsafe {
1033 let master = libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY);
1034 if master < 0 {
1035 return None;
1036 }
1037 if libc::grantpt(master) != 0 || libc::unlockpt(master) != 0 {
1038 libc::close(master);
1039 return None;
1040 }
1041 let name = libc::ptsname(master);
1042 let slave = if name.is_null() {
1043 -1
1044 } else {
1045 libc::open(name, libc::O_RDWR | libc::O_NOCTTY)
1046 };
1047 let mut probe: libc::termios = std::mem::zeroed();
1048 if slave < 0 || libc::tcgetattr(slave, &mut probe) != 0 {
1049 if slave >= 0 {
1050 libc::close(slave);
1051 }
1052 libc::close(master);
1053 return None;
1054 }
1055 Box::leak(Box::new(File::from_raw_fd(master)));
1056 Some(Box::leak(Box::new(File::from_raw_fd(slave))))
1057 }
1058 }
1059
1060 fn backend() -> Option<(UncursesBackend<&'static File, Recorder>, &'static Recorded)> {
1061 let tty = pty_slave()?;
1062 let recorded = Box::leak(Box::new(Recorded {
1063 tty,
1064 bytes: Mutex::new(Vec::new()),
1065 fail_next: AtomicBool::new(false),
1066 }));
1067 let terminal = Terminal::new(tty, Recorder(recorded), EnvList::new());
1068 let program = Program::new(terminal).expect("program over a PTY");
1069 Some((UncursesBackend::new(program), recorded))
1070 }
1071
1072 #[test]
1073 fn repeated_cursor_visibility_writes_only_changes() {
1074 let Some((mut backend, out)) = backend() else {
1075 return;
1076 };
1077 backend.hide_cursor().unwrap();
1078 backend.hide_cursor().unwrap();
1079 backend.show_cursor().unwrap();
1080 backend.show_cursor().unwrap();
1081 assert_eq!(out.take(), b"\x1b[?25l\x1b[?25h");
1082 }
1083
1084 #[test]
1085 fn repeated_cursor_visibility_delivers_output_left_by_a_failed_flush() {
1086 let Some((mut backend, out)) = backend() else {
1087 return;
1088 };
1089 out.fail_next.store(true, Ordering::Relaxed);
1090 assert!(backend.hide_cursor().is_err());
1091 assert_eq!(out.take(), b"");
1092
1093 backend.hide_cursor().unwrap();
1094 assert_eq!(out.take(), b"\x1b[?25l");
1095 }
1096
1097 #[test]
1098 fn cursor_query_keeps_repeated_f3() {
1099 use uncurses::event::{Event, Key, KeyCode, KeyModifiers};
1100 use uncurses::layout::Position;
1101
1102 let Some((mut backend, _)) = backend() else {
1103 return;
1104 };
1105 backend.program.unread_event(Event::CursorPosition {
1106 position: Position::new(0, 0),
1107 page: 0,
1108 });
1109 let mut repeat = Key::new(KeyCode::F(3), KeyModifiers::empty());
1110 repeat.repeat = true;
1111 backend.program.unread_event(Event::KeyPress(repeat));
1112
1113 assert_eq!(
1114 backend.get_cursor_position().unwrap(),
1115 ratatui::layout::Position::new(0, 0)
1116 );
1117 assert!(matches!(
1118 backend.program.try_read_event().unwrap(),
1119 Some(Event::KeyPress(key)) if key.code == KeyCode::F(3) && key.repeat
1120 ));
1121 }
1122}