Skip to main content

uncurses/screen/
mod.rs

1//! [`Screen`] — the cell-diff renderer you draw into.
2//!
3//! `Screen<W>` owns a desired cell grid, a diff renderer, and a writer. You
4//! paint cells into it and call [`render`](Screen::render); it works out the
5//! minimal escape sequence that turns what the terminal is showing into what
6//! you asked for, and writes it.
7//!
8//! That is the whole job. `Screen` reads no input, tracks no capabilities,
9//! and manages no session — [`Program`](crate::program::Program) does all of
10//! that and owns a `Screen` to render with. A `Screen` on its own is enough
11//! for output-only programs, tests, and offscreen rendering, since `W` is any
12//! [`Write`]: a terminal handle, a `Vec<u8>`, a file.
13//!
14//! ```
15//! use uncurses::screen::Screen;
16//! use uncurses::style::Style;
17//! use uncurses::text::TextSurface;
18//!
19//! # fn main() -> std::io::Result<()> {
20//! let mut screen = Screen::new(Vec::new(), (20, 3));
21//! screen.set_str((0, 0), "hello", Style::default());
22//! screen.render()?;
23//! assert!(!screen.writer().is_empty());
24//! # Ok(())
25//! # }
26//! ```
27//!
28//! # Render properties
29//!
30//! A `Screen` holds only the state that changes how a frame is drawn:
31//!
32//! * [`fullscreen`](Screen::fullscreen) — whether the managed area is the
33//!   whole viewport (the alternate screen buffer, addressed with absolute
34//!   moves) or a band in the normal buffer (the default, addressed
35//!   relatively so scrollback above and the shell prompt below survive).
36//! * Cursor visibility and the declarative resting
37//!   [position](Screen::set_cursor_position).
38//! * [Synchronized output](Screen::set_synchronized_output), grapheme-cluster
39//!   [width mode](Screen::set_grapheme_clusters), the
40//!   [color profile](Screen::set_color_profile), and the renderer
41//!   [optimizations](Screen::set_optimizations).
42//!
43//! Every one of these is a plain setter: it cannot fail and it writes nothing.
44//! A `Screen` never *persists* a terminal mode: the only modes it emits are
45//! the synchronized-output and cursor-visibility markers it wraps a single
46//! frame in, and it closes both before [`render`](Screen::render) returns.
47//! Leaving a mode on is
48//! [`Program`](crate::program::Program)'s job, and it pushes the render
49//! consequence down here with the matching setter — so
50//! [`Program::enter_alt_screen`](crate::program::Program::enter_alt_screen)
51//! emits DECSET 1049 and calls [`set_fullscreen`](Screen::set_fullscreen), and
52//! [`Program::hide_cursor`](crate::program::Program::hide_cursor) emits DECTCEM
53//! and calls [`set_cursor_visible`](Screen::set_cursor_visible). Drive a
54//! `Screen` yourself and you own both halves.
55//!
56//! ```text
57//!  Inline (default): the surface lives in the normal buffer, only as
58//!  many rows as you draw; scrollback and the shell prompt stay intact.
59//!
60//!    $ earlier shell output
61//!    $ ... scrollback ...
62//!    ┌─────────────────────────┐
63//!    │ managed surface         │  <- only the rows you draw, full width
64//!    └─────────────────────────┘
65//!    $ shell prompt resumes
66//!
67//!  Fullscreen: the whole viewport is the surface, addressed with
68//!  absolute moves, and restored on exit.
69//!
70//!    ┌─────────────────────────────┐
71//!    │                             │
72//!    │  the whole terminal         │
73//!    │  viewport is the surface    │
74//!    │                             │
75//!    └─────────────────────────────┘
76//! ```
77
78mod commit;
79#[cfg(test)]
80mod tests;
81
82/// Cell-diff capability flags controlling which optimized escape
83/// sequences the screen's renderer may emit. Re-exported from the
84/// renderer so applications can configure rendering with
85/// [`Screen::set_optimizations`] without depending on renderer internals.
86pub use crate::renderer::Optimizations;
87
88use std::{
89    borrow::Cow,
90    io::{self, Write},
91};
92
93use crate::ansi::mode;
94use crate::buffer::{Bounded, Surface, SurfaceMut};
95use crate::cell::Cell;
96use crate::layout::{Position, Rect, Size};
97use crate::renderer::{RenderBuffer, Renderer};
98use crate::text::{TextSurface, WidthMode};
99
100/// A cell-diff renderer over a writer. See the [module documentation](self).
101///
102/// `Screen` is [`Send`] and [`Sync`] whenever its writer is, so it can be
103/// moved onto another thread or held across an `.await` point.
104pub struct Screen<W: Write> {
105    /// Where rendered bytes go.
106    writer: W,
107    /// Caller-facing desired cell grid. Touched spans record where the
108    /// application wrote since the last sync; the renderer filters them
109    /// again against its staging buffer before diffing the terminal.
110    front_buf: RenderBuffer,
111    /// The diff renderer holding the tracked on-screen buffer, cursor model,
112    /// color profile, and optimizations.
113    renderer: Renderer,
114    /// Scratch byte buffer that drawing and property methods stage escape
115    /// bytes into before [`io::Write::flush`] drains them to the writer.
116    out_buf: Vec<u8>,
117    /// Managed area width in cells.
118    width: u16,
119    /// Managed area height in cells.
120    height: u16,
121    /// East-Asian Ambiguous width policy used when measuring strings: when
122    /// `true`, code points whose East-Asian-Width property is `Ambiguous`
123    /// are measured as 2 cells instead of 1. See [`crate::text::char_width`].
124    eaw_wide: bool,
125    /// Whether the managed area is the whole viewport or an inline band.
126    fullscreen: bool,
127    /// Cursor visibility (DECTCEM). Render-coupled: a frame hides a *visible*
128    /// cursor around the cell diff, and bracketing a cursor the caller
129    /// deliberately hid would turn it back on.
130    cursor_visible: bool,
131    /// Synchronized updates: when `true`, each non-empty frame is wrapped in
132    /// synchronized-output begin/end sequences.
133    sync_updates: bool,
134    /// Unicode core / grapheme cluster mode (DEC 2027). When `true`, width is
135    /// calculated per grapheme cluster (UTS-29 + emoji rules); when `false`,
136    /// per code point (wcwidth-style).
137    grapheme_clusters: bool,
138    /// Declarative resting position for the cursor, applied at the end of
139    /// every [`render`](Screen::render) via
140    /// [`set_cursor_position`](Screen::set_cursor_position). Sticky: it
141    /// persists across frames and is re-applied each render (a no-op when the
142    /// cursor is already there) until changed or cleared. `None` means no
143    /// declarative resting position, so the cursor is left wherever the cell
144    /// diff ended.
145    desired_cursor: Option<Position>,
146    /// The resting position the last frame walked the cursor to, when the
147    /// walk ended on a column only the terminal can name.
148    ///
149    /// Paired with [`Renderer::cursor_placed_on_row`] this says "the cursor
150    /// is already resting here", which the tracked position alone cannot,
151    /// because the walk deliberately forgets the column. An immediate move
152    /// clears this record: another walk can leave the same row known while
153    /// it places the cursor at a different logical position.
154    cursor_rested_at: Option<Position>,
155}
156
157impl<W: Write> Screen<W> {
158    // --- Construction ---------------------------------------------------
159
160    /// Build a screen rendering into `writer`, with a managed area of `size`.
161    ///
162    /// Nothing is written and no terminal state is touched. The color profile
163    /// defaults to [`Profile::Ansi`](crate::color::Profile::Ansi) and the
164    /// optimizations to [`Optimizations::default`]; set them with
165    /// [`set_color_profile`](Self::set_color_profile) and
166    /// [`set_optimizations`](Self::set_optimizations), or let
167    /// [`Program`](crate::program::Program) detect both from the environment.
168    pub fn new(writer: W, size: impl Into<Size>) -> Self {
169        let mut renderer = Renderer::new();
170        // Defaults match inline: the surface is anchored wherever the cursor
171        // sits, so moves stay relative.
172        renderer.set_fullscreen(false);
173        renderer.set_relative_cursor(true);
174        let mut screen = Self {
175            writer,
176            front_buf: RenderBuffer::new(0, 0),
177            renderer,
178            out_buf: Vec::with_capacity(4096),
179            width: 0,
180            height: 0,
181            eaw_wide: false,
182            fullscreen: false,
183            cursor_visible: true,
184            sync_updates: false,
185            grapheme_clusters: false,
186            desired_cursor: None,
187            cursor_rested_at: None,
188        };
189        let size = size.into();
190        if size.width != 0 || size.height != 0 {
191            screen.resize(size);
192        }
193        screen
194    }
195
196    /// Borrow the writer frames are rendered into.
197    pub fn writer(&self) -> &W {
198        &self.writer
199    }
200
201    /// Borrow the writer mutably.
202    ///
203    /// Bytes written straight to the writer bypass the staging buffer, so they
204    /// can land *before* escapes already staged by drawing or property
205    /// methods. Prefer writing through the screen itself (it implements
206    /// [`Write`]), which keeps everything in order.
207    pub fn writer_mut(&mut self) -> &mut W {
208        &mut self.writer
209    }
210
211    /// Consume the screen and return its writer, discarding anything still
212    /// staged and unflushed.
213    pub fn into_writer(self) -> W {
214        self.writer
215    }
216
217    // --- Drawing -------------------------------------------------------
218
219    /// Write `cell` at `pos` in the desired frame.
220    /// A continuation is placed by the wide cell that owns it, so one passed
221    /// here is ignored and the column keeps the value its owner gave it.
222    pub fn set_cell(&mut self, pos: impl Into<Position>, cell: &Cell) {
223        self.front_buf.set_cell(pos.into(), cell);
224    }
225
226    /// Borrow the cell at `pos` mutably, marking its columns touched.
227    pub fn cell_mut(&mut self, pos: impl Into<Position>) -> Option<&mut Cell> {
228        self.front_buf.cell_mut(pos.into())
229    }
230
231    /// The managed area size in cells.
232    pub fn size(&self) -> Size {
233        Size::new(self.width, self.height)
234    }
235
236    /// Diff the staged frame against the tracked terminal, stage the
237    /// minimal escape bytes, and flush them to the writer.
238    ///
239    /// When a declarative cursor rest position has been staged with
240    /// [`set_cursor_position`](Self::set_cursor_position), the cursor is moved
241    /// there at the end of the frame, inside the same hide/synchronized-output
242    /// bracket as the cell diff, so it lands atomically and without flicker.
243    pub fn render(&mut self) -> io::Result<()> {
244        let changed = self.renderer.sync_front(&mut self.front_buf);
245        if changed || self.cursor_move_pending() {
246            self.write_frame();
247        }
248        self.flush()
249    }
250
251    /// Force a full redraw on the next [`render`](Self::render).
252    pub fn invalidate(&mut self) {
253        self.renderer.request_clear();
254    }
255
256    /// Resize the managed area. In fullscreen pass the terminal viewport
257    /// size; inline, the terminal width and the application surface height.
258    ///
259    /// Resizing discards the tracked terminal contents, so the next
260    /// [`render`](Self::render) is a full repaint. That holds even when the
261    /// size is unchanged: a resize report can follow a font or window change
262    /// that keeps the cell grid but moves where those cells land, and the
263    /// tracked contents are then wrong in a way no diff can see. An explicit
264    /// resize says the caller wants the area re-established, so it is.
265    ///
266    /// [`Program::autoresize`](crate::program::Program::autoresize) runs on
267    /// every resize report, including ones that change nothing, so it skips
268    /// the call when the size already matches rather than repainting on each.
269    pub fn resize(&mut self, size: impl Into<Size>) {
270        let size = size.into();
271        self.width = size.width;
272        self.height = size.height;
273        self.front_buf.resize(size.width, size.height);
274        self.renderer.request_clear();
275    }
276
277    /// Change the managed height while preserving the displayed row cache.
278    ///
279    /// The next render draws changed cells and erases removed inline rows.
280    /// Added blank rows extend the managed area. Use [`resize`](Self::resize)
281    /// after a terminal resize to re-establish its geometry.
282    pub fn resize_height(&mut self, height: u16) {
283        if height != self.height {
284            self.height = height;
285            self.front_buf.resize_height(height);
286        }
287    }
288
289    /// Insert `content` into the scrollback above the managed area and flush
290    /// it to the writer. Inline this pushes the lines into the terminal's
291    /// scrollback; in fullscreen they go into the alternate screen's hidden
292    /// scrollback. Styled text preserves the managed area in place, so no
293    /// redraw is needed and a following [`render`](Self::render) sees no change.
294    /// An empty string is a no-op.
295    ///
296    /// # Input
297    ///
298    /// Content must contain only text, newlines, tabs, complete SGR style
299    /// sequences, and OSC 8 hyperlinks. The caller must ensure that the content
300    /// satisfies this input requirement.
301    ///
302    /// Keep other controls and escapes out of the input. Cursor movement,
303    /// erasure, scrolling, and mode changes fall outside this contract and can
304    /// overwrite the managed area or preceding output. This includes standalone
305    /// NEL, IND, and RI controls and their equivalent escape sequences.
306    ///
307    /// Wrapped rows follow the screen's width policy. ANSI escapes contribute
308    /// no width. A full final row skips erasure to preserve its last column.
309    ///
310    /// Tabs use stops every eight columns and clamp at the right edge.
311    /// [`Program`](crate::program::Program) establishes these stops. A caller
312    /// that drives `Screen` directly must establish the same terminal stops.
313    /// A pending height change takes effect on the next render. Insertion
314    /// uses the last rendered height and leaves pending cell edits staged.
315    ///
316    /// Supported UTF-8 C1 style and hyperlink sequences use their 7-bit
317    /// terminal forms for both measurement and output. Hyperlink payloads
318    /// retain their original UTF-8 bytes.
319    ///
320    /// # Errors
321    ///
322    /// Returns any error from flushing the inserted lines to the writer.
323    pub fn insert_above(&mut self, content: &str) -> io::Result<()> {
324        if content.is_empty() {
325            return Ok(());
326        }
327        let content = normalize_insert_above(content, self.width_mode(), self.eaw_wide);
328
329        let height = self
330            .renderer
331            .last_size()
332            .map_or(self.height, |(_, height)| height);
333        let y = self.renderer.cursor_position().y;
334
335        self.out_buf.write_all(b"\r").unwrap();
336        let bottom = height.saturating_sub(1);
337        if y < bottom {
338            crate::ansi::cursor::write_cud(&mut self.out_buf, bottom - y).unwrap();
339        } else if y > bottom {
340            // An immediate cursor move can enter rows of a pending growth.
341            crate::ansi::cursor::write_cuu(&mut self.out_buf, y - bottom).unwrap();
342        }
343
344        let lines: Vec<&str> = content.split('\n').collect();
345        let sizes: Vec<_> = lines
346            .iter()
347            .map(|line| self.insert_above_size(line))
348            .collect();
349        let offset = sizes
350            .iter()
351            .fold(0u16, |sum, &(rows, _)| sum.saturating_add(rows));
352
353        for _ in 0..offset {
354            self.out_buf.write_all(b"\n").unwrap();
355        }
356
357        let up = offset.saturating_add(height).saturating_sub(1);
358        if up > 0 {
359            crate::ansi::cursor::write_cuu(&mut self.out_buf, up).unwrap();
360        }
361        crate::ansi::screen::write_insert_lines(&mut self.out_buf, offset).unwrap();
362        for (line, &(_, column)) in lines.iter().zip(&sizes) {
363            self.out_buf.write_all(line.as_bytes()).unwrap();
364            if self.width == 0 || column != usize::from(self.width) {
365                self.out_buf
366                    .write_all(crate::ansi::screen::ERASE_LINE_RIGHT)
367                    .unwrap();
368            }
369            self.out_buf.write_all(b"\r\n").unwrap();
370        }
371
372        self.renderer.set_cursor_position(Position { y: 0, x: 0 });
373        self.flush()
374    }
375
376    fn insert_above_size(&self, line: &str) -> (u16, usize) {
377        let mut rows = 1u16;
378        let mut column = 0usize;
379        let width = usize::from(self.width);
380        let mut advance = |mut column: usize, cells: usize| {
381            if cells == 0 {
382                return column;
383            }
384            if width > 0 && column > 0 && column + cells > width {
385                rows = rows.saturating_add(1);
386                column = 0;
387            }
388            column += cells;
389            if width > 0 && column > width {
390                rows = rows.saturating_add(((column - 1) / width) as u16);
391                column = (column - 1) % width + 1;
392            }
393            column
394        };
395        let mode = self.width_mode();
396        for token in crate::ansi::text::tokenize(line.as_bytes(), mode, self.eaw_wide) {
397            match token.kind {
398                // A tab preserves pending wrap instead of starting a new row.
399                crate::ansi::text::TokenKind::Control
400                    if token.control == b'\t' && width > 0 && column < width =>
401                {
402                    let interval = usize::from(crate::renderer::tabstops::DEFAULT_TAB_INTERVAL);
403                    column = ((column / interval + 1) * interval).min(width - 1);
404                }
405                crate::ansi::text::TokenKind::Text => {
406                    if mode == WidthMode::Grapheme {
407                        column = advance(column, usize::from(token.width));
408                    } else {
409                        // Code-point terminals can wrap within a joined cluster.
410                        for ch in std::str::from_utf8(token.bytes).unwrap().chars() {
411                            column = advance(
412                                column,
413                                usize::from(crate::text::char_width(ch, self.eaw_wide)),
414                            );
415                        }
416                    }
417                }
418                _ => {}
419            }
420        }
421        (rows, column)
422    }
423
424    // --- Cursor position ------------------------------------------------
425
426    /// Immediately move the terminal cursor to a buffer-relative position and
427    /// flush.
428    ///
429    /// The target is normalized against the managed area first: a column at or
430    /// past the width wraps into the following row, and the row is clamped to
431    /// the last row. The move is a no-op once the cursor already sits at that
432    /// normalized position, so asking for a column one past the last is a
433    /// request to wrap and is honored as one, even when the renderer is
434    /// already tracking the cursor there with its wrap pending.
435    ///
436    /// Past a cluster whose terminal width is uncertain, the move re-emits
437    /// cells from the last rendered row until it reaches the logical target.
438    /// It leaves staged edits for `render`. A target inside that cluster
439    /// rests on its primary cell. The tracked column becomes unknown because
440    /// the terminal decides how far each cluster advances.
441    ///
442    /// After a resize, screen switch, or invalidation, the move uses control
443    /// sequences until `render` establishes the displayed cells again.
444    ///
445    /// This is imperative: the move is emitted and flushed now, independent of
446    /// [`render`](Self::render). It does **not** affect the declarative resting
447    /// position staged with [`set_cursor_position`](Self::set_cursor_position);
448    /// a subsequent `render` will snap the cursor back to that sticky position
449    /// if one is set. To change where frames leave the cursor, use
450    /// `set_cursor_position` instead.
451    pub fn move_cursor_to(&mut self, pos: impl Into<Position>) -> io::Result<()> {
452        self.stage_move_cursor_to(pos.into());
453        self.flush()
454    }
455
456    /// Immediately move the terminal cursor relative to the
457    /// [tracked cursor](Self::tracked_cursor) and flush.
458    ///
459    /// Convenience over [`move_cursor_to`](Self::move_cursor_to): the target
460    /// is the tracked cursor offset by `(dx, dy)`, saturating at the buffer
461    /// origin and then normalized the same way, so a column past the width
462    /// wraps into the following row and the row is clamped to the surface. An
463    /// unknown tracked cursor is treated as the origin.
464    pub fn move_cursor_by(&mut self, dx: i16, dy: i16) -> io::Result<()> {
465        let cur = self.tracked_cursor().unwrap_or(Position::ORIGIN);
466        let x = cur.x.saturating_add_signed(dx);
467        let y = cur.y.saturating_add_signed(dy);
468        self.move_cursor_to((x, y))
469    }
470
471    /// Stage a declarative resting position for the cursor, applied at the end
472    /// of every [`render`](Self::render).
473    ///
474    /// This is the cursor analogue of [`set_cell`](Self::set_cell): it stages
475    /// intent rather than emitting now. `render` leaves the terminal cursor at
476    /// the buffer-relative `pos` after each frame's cell diff. Call
477    /// [`clear_cursor_position`](Self::clear_cursor_position) to stop steering
478    /// it and leave the cursor wherever the diff ended.
479    ///
480    /// The position is **sticky** — it persists across frames and is re-applied
481    /// on every `render` (cheaply, as a no-op when the cursor is already there)
482    /// until you change or clear it. An app whose cursor follows content
483    /// (e.g. a text field) should call this each time that content moves.
484    ///
485    /// Cursor visibility is orthogonal: this never shows or hides the cursor.
486    /// Use [`set_cursor_visible`](Self::set_cursor_visible) for that (or
487    /// [`Program::show_cursor`](crate::program::Program::show_cursor) /
488    /// [`hide_cursor`](crate::program::Program::hide_cursor), which also emit
489    /// DECTCEM). A position outside the managed area is clamped to its edges.
490    ///
491    /// The argument is anything that converts into a [`Position`], so a bare
492    /// `(x, y)` works:
493    ///
494    /// ```
495    /// # fn main() -> std::io::Result<()> {
496    /// let mut screen = uncurses::screen::Screen::new(Vec::new(), (20, 3));
497    /// screen.set_cursor_position((4, 0)); // stage
498    /// screen.clear_cursor_position();     // stop steering it
499    /// # Ok(())
500    /// # }
501    /// ```
502    pub fn set_cursor_position(&mut self, pos: impl Into<Position>) {
503        self.desired_cursor = Some(pos.into());
504    }
505
506    /// Clear the staged cursor [resting position](Self::set_cursor_position),
507    /// leaving the cursor wherever each frame's cell diff ends.
508    pub fn clear_cursor_position(&mut self) {
509        self.desired_cursor = None;
510    }
511
512    /// The renderer's tracked cursor: the buffer-relative cell where the
513    /// renderer believes the terminal cursor currently sits, or `None` when
514    /// that position is unknown (initially, after a screen reset, or after
515    /// [`invalidate_tracked_cursor`](Self::invalidate_tracked_cursor)). This
516    /// is bookkeeping, not a live cursor-position query.
517    ///
518    /// A cursor move past a cluster the
519    /// terminal may measure differently also reads as unknown. The cursor is
520    /// where it was asked to go, and the terminal is the only one that can
521    /// say which column that is. See
522    /// [`set_grapheme_clusters`](Self::set_grapheme_clusters) for what makes
523    /// a cluster uncertain and how to settle it.
524    pub fn tracked_cursor(&self) -> Option<Position> {
525        self.renderer
526            .cursor_known()
527            .then(|| self.renderer.cursor_position())
528    }
529
530    /// Mark the tracked cursor position unknown, so the next staged move
531    /// always emits rather than short-circuiting on a matching tracked
532    /// position. Use after moving the terminal cursor by a means the
533    /// renderer cannot see (e.g. a raw escape written directly).
534    pub fn invalidate_tracked_cursor(&mut self) {
535        self.renderer.invalidate_cursor();
536    }
537
538    /// Set the tracked cursor to buffer-relative `pos`, with both axes
539    /// known, *without* emitting any move. This only updates the renderer's
540    /// belief; the caller must have already placed the terminal cursor there
541    /// (e.g. with a raw escape the renderer cannot see). For an actual cursor
542    /// move use [`move_cursor_to`](Self::move_cursor_to).
543    pub fn set_tracked_cursor(&mut self, pos: impl Into<Position>) {
544        self.renderer.set_cursor_position(pos.into());
545    }
546
547    /// Clamp a buffer-relative position to the managed area's edges.
548    fn clamp_to_surface(&self, pos: Position) -> Position {
549        Position {
550            x: pos.x.min(self.width.saturating_sub(1)),
551            y: pos.y.min(self.height.saturating_sub(1)),
552        }
553    }
554
555    /// Whether a declarative cursor rest position is staged and the renderer's
556    /// tracked cursor isn't already there, so [`render`](Self::render) must
557    /// emit a move even when no cells changed.
558    fn cursor_move_pending(&self) -> bool {
559        match self.desired_cursor {
560            Some(pos) => {
561                let pos = self.clamp_to_surface(pos);
562                // A walk past an uncertain cluster ends on a column only the
563                // terminal can name, so the tracked position reads as "not
564                // there" even though the cursor is exactly where it was asked
565                // to go. Take the recorded rest as the answer while the
566                // cursor still sits where that walk left it.
567                if self.cursor_rested_at == Some(pos) && self.renderer.cursor_placed_on_row(pos.y) {
568                    return false;
569                }
570                !self.renderer.cursor_known() || self.renderer.cursor_position() != pos
571            }
572            None => false,
573        }
574    }
575
576    // --- Render properties ----------------------------------------------
577
578    /// Set whether the managed area is the whole viewport.
579    ///
580    /// `true` means the managed area covers the whole terminal and is
581    /// addressed with absolute moves — what you want on the alternate screen
582    /// buffer. `false` (the default) makes it a band in the normal buffer, as
583    /// tall as you draw and addressed with relative moves, leaving the
584    /// scrollback above and the shell prompt below intact.
585    ///
586    /// This only sets state — it emits nothing. Switching screen buffers is a
587    /// terminal mode (DECSET/DECRST 1049) and belongs to whoever owns the
588    /// terminal: [`Program::enter_alt_screen`] and
589    /// [`Program::exit_alt_screen`] emit it and set this for you. Driving a
590    /// bare `Screen`, emit the mode yourself and keep this in step, or the
591    /// renderer will address the wrong buffer.
592    ///
593    /// An actual change discards the tracked contents, so the next
594    /// [`render`](Self::render) is a full repaint.
595    ///
596    /// [`Program::enter_alt_screen`]: crate::program::Program::enter_alt_screen
597    /// [`Program::exit_alt_screen`]: crate::program::Program::exit_alt_screen
598    pub fn set_fullscreen(&mut self, fullscreen: bool) {
599        if self.fullscreen == fullscreen {
600            return;
601        }
602        self.fullscreen = fullscreen;
603        self.renderer.set_fullscreen(fullscreen);
604        self.renderer.set_relative_cursor(!fullscreen);
605        if fullscreen {
606            self.renderer.save_cursor();
607        } else {
608            self.renderer.restore_cursor();
609        }
610        // Either direction swaps which screen buffer the managed area lives
611        // on, and the other buffer holds something this renderer never wrote.
612        // Diffing against the record from the buffer being left would skip
613        // every cell the two happen to agree on, so discard it and repaint.
614        self.renderer.request_clear();
615    }
616
617    /// Whether the managed area is the whole viewport rather than a band in
618    /// the normal buffer. See [`set_fullscreen`](Self::set_fullscreen).
619    pub fn fullscreen(&self) -> bool {
620        self.fullscreen
621    }
622
623    /// Record whether the terminal cursor is visible.
624    ///
625    /// This only sets state — it emits nothing. DECTCEM is a terminal mode
626    /// and belongs to whoever owns the terminal:
627    /// [`Program::show_cursor`](crate::program::Program::show_cursor) and
628    /// [`Program::hide_cursor`](crate::program::Program::hide_cursor) emit it
629    /// and set this for you.
630    ///
631    /// The renderer needs to know only so it can bracket a frame correctly: a
632    /// *visible* cursor is hidden around the cell diff so it does not dance
633    /// across cells as the renderer repositions it, and shown again after. If
634    /// this said `true` while the cursor was actually hidden, that closing
635    /// show would turn it back on.
636    pub fn set_cursor_visible(&mut self, visible: bool) {
637        self.cursor_visible = visible;
638    }
639
640    /// Whether the terminal cursor is recorded as visible. See
641    /// [`set_cursor_visible`](Self::set_cursor_visible).
642    pub fn cursor_visible(&self) -> bool {
643        self.cursor_visible
644    }
645
646    /// Set whether text is measured per extended grapheme cluster (UTS-29
647    /// plus emoji presentation rules) rather than per code point
648    /// (wcwidth-style). Affects [`set_str`](crate::text::TextSurface::set_str)
649    /// and [`insert_above`](Self::insert_above).
650    ///
651    /// This only sets state — it emits nothing. Unicode core (DECSET 2027) is
652    /// a terminal mode and belongs to whoever owns the terminal:
653    /// [`Program::enable_grapheme_clusters`] and
654    /// [`Program::disable_grapheme_clusters`] emit it and set this for you.
655    /// Measuring differently from the terminal misplaces every cell after the
656    /// first cluster on a line, so the two must agree.
657    ///
658    /// Under the per-code-point model the renderer covers the one difference
659    /// it can predict: a cluster of several code points, which a terminal
660    /// draws as a single glyph of its own choosing. That glyph may be
661    /// narrower than the parts add up to, as with a ligated family emoji, or
662    /// wider, as with a heart that an emoji selector promotes to two columns.
663    /// Either way the renderer stops diffing that row at the cluster and
664    /// repaints the rest of it in one run, which asks nothing about where the
665    /// terminal put the glyph. That keeps the row honest on such a terminal
666    /// while measurement is per code point. Measuring whole clusters asserts
667    /// that the terminal counts them the same way, so every row takes the
668    /// ordinary path, and it is on you to have put the terminal in that mode.
669    ///
670    /// Changing the mode discards the tracked terminal contents, so the next
671    /// [`render`](Self::render) is a full repaint: what is already on screen
672    /// was measured the other way. Setting the current value is a no-op.
673    ///
674    /// The repaint clears the screen, but buffered cells keep the width they
675    /// were measured with, so re-write any text whose measurement changes.
676    /// Applications that redraw their content each frame get that for free.
677    ///
678    /// [`Program::enable_grapheme_clusters`]: crate::program::Program::enable_grapheme_clusters
679    /// [`Program::disable_grapheme_clusters`]: crate::program::Program::disable_grapheme_clusters
680    pub fn set_grapheme_clusters(&mut self, enabled: bool) {
681        if self.grapheme_clusters == enabled {
682            return;
683        }
684        self.grapheme_clusters = enabled;
685        self.renderer.set_width_mode(self.width_mode());
686        // Whatever is on screen was measured under the old model, so the
687        // tracked terminal contents no longer describe it. Diffing against
688        // that record would leave the two disagreeing about which column
689        // holds what, so discard it and repaint.
690        self.invalidate();
691    }
692
693    /// Whether text is measured per extended grapheme cluster. See
694    /// [`set_grapheme_clusters`](Self::set_grapheme_clusters).
695    pub fn grapheme_clusters(&self) -> bool {
696        self.grapheme_clusters
697    }
698
699    /// Set whether East Asian Ambiguous characters occupy two columns.
700    ///
701    /// A changed policy invalidates the displayed frame. Rewrite text whose
702    /// measured width changes before the next render.
703    pub fn set_ambiguous_wide(&mut self, wide: bool) {
704        if self.eaw_wide != wide {
705            self.eaw_wide = wide;
706            self.invalidate();
707        }
708    }
709
710    /// Enable or disable synchronized-output frame wrapping.
711    ///
712    /// When enabled, each non-empty [`render`](Self::render) is wrapped in
713    /// begin/end synchronized-output sequences (DEC mode 2026) so terminals
714    /// that support it present the frame atomically, with no mid-frame
715    /// repaint. Terminals that don't support 2026 ignore the markers.
716    ///
717    /// This setter directly controls frame wrapping.
718    /// [`Program::apply_defaults`](crate::program::Program::apply_defaults)
719    /// also enables it when the record reports mode 2026 support and
720    /// [`ProgramOptions::prefer_synchronized_output`](crate::program::ProgramOptions::prefer_synchronized_output)
721    /// is `true`. Call this setter afterward to choose another value.
722    ///
723    /// Enabling it also changes how the cursor is handled per frame. With sync
724    /// off, a visible cursor is hidden around the cell diff so it doesn't dance
725    /// across cells as the renderer repositions it. With sync on, the frame is
726    /// presented in one step, so that hide/show pair is dropped: it is
727    /// redundant, and toggling the cursor every frame resets its blink phase,
728    /// which reads as flicker.
729    ///
730    /// This only sets state; the markers are emitted on the next `render`.
731    /// Scroll detection is gated on this, so enabling it is what lets
732    /// [`set_scroll_optimize`](Self::set_scroll_optimize) take effect; that
733    /// setting still has to be on, and the screen still has to be
734    /// [fullscreen](Self::set_fullscreen). A terminal that advertises DEC
735    /// 2026 but does not honour it therefore gets both the markers and the
736    /// scroll plans that rely on them, and a scroll's corrective repaint may
737    /// be visible. Disable scroll optimization on such a terminal.
738    ///
739    pub fn set_synchronized_output(&mut self, enabled: bool) {
740        self.sync_updates = enabled;
741        // Scroll detection is gated on this: a scroll the renderer emits can
742        // move cells that should have stayed put, and the repaint that fixes
743        // them is only invisible inside a synchronized frame.
744        self.renderer.set_sync_output(enabled);
745    }
746
747    /// Whether [synchronized output](Self::set_synchronized_output) frame
748    /// wrapping is enabled.
749    pub fn synchronized_output(&self) -> bool {
750        self.sync_updates
751    }
752
753    /// Enable or disable the renderer's scroll-detection pass.
754    ///
755    /// On by default, and best left on: when a run of rows has simply moved,
756    /// telling the terminal to move them costs a handful of bytes instead of
757    /// a repaint.
758    ///
759    /// Detection additionally requires [synchronized
760    /// output](Self::set_synchronized_output); see below. Turning this off
761    /// gives up scrolling entirely, including on frames where it would have
762    /// been safe.
763    ///
764    /// A fixed column is why that requirement exists. The scrolls uncurses
765    /// emits are always full width: rows move with `SU`, `IL`/`DL` or a bare
766    /// line feed,
767    /// and the renderer does not set the left/right margins
768    /// ([DECLRMM](crate::ansi::mode::Mode::LEFT_RIGHT_MARGIN) and
769    /// [DECSLRM](crate::ansi::screen::write_set_left_right_margins)) that
770    /// would confine them to a column range on a terminal supporting those.
771    /// So a detected scroll moves that region too, and the renderer paints it
772    /// back within the same frame. The end state is correct either way —
773    /// which is why a test that compares the finished screen sees nothing
774    /// wrong — but what the user sees is that region jumping and being put
775    /// back, on every frame, for as long as they keep scrolling.
776    ///
777    /// Because that intermediate state is only hidden when the frame is
778    /// presented in one step, detection runs **only** under
779    /// [synchronized output](Self::set_synchronized_output), which wraps the
780    /// frame in DEC 2026. Without it no scroll is emitted at all, whatever
781    /// this setting says, and rows are redrawn directly instead.
782    ///
783    /// Synchronized output is off by default, and a
784    /// [`Program`](crate::program::Program) turns it on only once the
785    /// terminal has reported 2026 support, which takes an explicit
786    /// [`Probe::query_capabilities`](crate::program::Probe::query_capabilities)
787    /// and [`apply_defaults`](crate::program::Program::apply_defaults).
788    /// An application that never asks never gets scroll optimization,
789    /// whatever its terminal supports.
790    ///
791    /// Detection is skipped outside [fullscreen](Self::set_fullscreen)
792    /// regardless of this setting.
793    ///
794    /// This only sets state; it takes effect on the next
795    /// [`render`](Self::render).
796    pub fn set_scroll_optimize(&mut self, enabled: bool) {
797        self.renderer.set_scroll_optimize(enabled);
798    }
799
800    /// Set the color profile used when emitting styled cells.
801    pub fn set_color_profile(&mut self, profile: crate::color::Profile) {
802        self.renderer.set_color_profile(profile);
803    }
804
805    /// Return the color profile used when emitting styled cells.
806    ///
807    /// This is the profile the renderer downsamples colors to, set by
808    /// [`set_color_profile`](Self::set_color_profile) or detected from the
809    /// environment by [`Program`](crate::program::Program). Pass it to
810    /// [`Encode::encode_with`](crate::text::Encode::encode_with) to serialize
811    /// a surface the same way this screen renders it.
812    pub fn color_profile(&self) -> crate::color::Profile {
813        self.renderer.color_profile()
814    }
815
816    /// Set the renderer optimization flags.
817    ///
818    /// [`TABS`](Optimizations::TABS) and [`BS`](Optimizations::BS) take
819    /// effect immediately but do not persist across a raw-mode entry:
820    /// [`Program::init`](crate::program::Program::init) and
821    /// [`Program::resume`](crate::program::Program::resume) enable both,
822    /// since raw mode is what makes them safe. Every other flag —
823    /// including [`ONLCR`](Optimizations::ONLCR), which is opt-in and
824    /// never granted — is left exactly as set here.
825    pub fn set_optimizations(&mut self, optimizations: Optimizations) {
826        self.renderer.set_optimizations(optimizations);
827    }
828
829    /// Return the renderer optimization flags currently in effect.
830    pub fn optimizations(&self) -> Optimizations {
831        self.renderer.optimizations()
832    }
833
834    // --- Render staging internals ---------------------------------------
835
836    /// Stage a single rendered frame into [`out_buf`](Self::out_buf):
837    /// synchronized-output begin, the renderer's cell diff, the optional
838    /// declarative cursor move, synchronized-output end. Assumes the front
839    /// buffer was synced.
840    ///
841    /// A visible cursor is hidden around the diff so it doesn't dance across
842    /// cells as the renderer repositions it, *unless* synchronized output is
843    /// enabled. A synchronized frame is presented in one step, so the cursor
844    /// never visibly moves mid-frame; the hide/show pair is then skipped, both
845    /// because it is redundant and because toggling DECTCEM every frame resets
846    /// the cursor's blink phase, which reads as flicker. Whether to trust
847    /// synchronized output is the caller's choice via
848    /// [`set_synchronized_output`](Self::set_synchronized_output), not gated on
849    /// detected capabilities.
850    fn write_frame(&mut self) {
851        let bracket_cursor = self.cursor_visible && !self.sync_updates;
852
853        if self.sync_updates {
854            mode::Mode::SYNCHRONIZED_OUTPUT
855                .set(&mut self.out_buf)
856                .unwrap();
857        }
858        if bracket_cursor {
859            mode::Mode::CURSOR_VISIBLE.reset(&mut self.out_buf).unwrap();
860        }
861
862        self.renderer.render_back(&mut self.out_buf).unwrap();
863
864        // Apply the declarative resting position (if any) inside the same
865        // bracket as the cell diff, so the cursor lands atomically.
866        // Sticky: re-applied every frame; move_to no-ops when already there.
867        if let Some(pos) = self.desired_cursor {
868            let pos = self.clamp_to_surface(pos);
869            self.renderer
870                .move_to_resting(&mut self.out_buf, &self.front_buf, pos.y, pos.x)
871                .unwrap();
872            self.cursor_rested_at = Some(pos);
873        }
874
875        if bracket_cursor {
876            mode::Mode::CURSOR_VISIBLE.set(&mut self.out_buf).unwrap();
877        }
878        if self.sync_updates {
879            mode::Mode::SYNCHRONIZED_OUTPUT
880                .reset(&mut self.out_buf)
881                .unwrap();
882        }
883    }
884
885    /// Stage a cursor move without flushing. See
886    /// [`move_cursor_to`](Self::move_cursor_to).
887    pub(crate) fn stage_move_cursor_to(&mut self, target: Position) {
888        self.cursor_rested_at = None;
889        let size = self.size();
890        self.renderer
891            .move_to_between_frames(&mut self.out_buf, size, target.y, target.x)
892            .unwrap();
893    }
894
895    // --- Session handoff (driven by Program) -----------------------------
896
897    /// Stage a move to the bottom row of the *last rendered* surface.
898    ///
899    /// Used before a shell handoff so the cursor lands below the managed
900    /// area. Deliberately uses the last-render height rather than the live
901    /// height, so a terminal that grew between the last render and the
902    /// handoff does not push the cursor below where the user started.
903    pub(crate) fn park_cursor(&mut self) -> io::Result<()> {
904        if let Some((last_width, last_height)) = self.renderer.last_size()
905            && last_height > 0
906        {
907            let last = Size::new(last_width, last_height);
908            self.renderer
909                .move_to_between_frames(&mut self.out_buf, last, last_height - 1, 0)?;
910        }
911        Ok(())
912    }
913
914    /// Save the renderer's inline cursor anchor before the terminal switches
915    /// to the alternate screen, so leaving it can restore the anchor.
916    pub(crate) fn save_cursor(&mut self) {
917        self.renderer.save_cursor();
918    }
919
920    /// Restore the inline cursor anchor saved by
921    /// [`save_cursor`](Self::save_cursor).
922    pub(crate) fn restore_cursor(&mut self) {
923        self.renderer.restore_cursor();
924    }
925
926    /// Forget where the cursor is.
927    ///
928    /// The terminal is being handed back to the shell. Once it returns (e.g.
929    /// after a suspend/resume, possibly with a resize that reflowed the
930    /// surface), the tracked position is void; forget it so the next frame
931    /// re-anchors at the current physical position instead of stepping up
932    /// from a stale row and overwriting content above the surface.
933    pub(crate) fn invalidate_cursor(&mut self) {
934        self.renderer.invalidate_cursor();
935    }
936}
937
938impl<W: Write> Write for Screen<W> {
939    /// Append raw bytes to the staging buffer, ordered with any staged mode
940    /// or frame bytes. They reach the writer on the next [`flush`](Self::flush).
941    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
942        self.out_buf.extend_from_slice(buf);
943        Ok(buf.len())
944    }
945
946    /// Drain the staging buffer to the writer and flush it.
947    ///
948    /// A write error retains only unsent bytes for the next flush.
949    /// A writer flush error leaves the staging buffer empty.
950    fn flush(&mut self) -> io::Result<()> {
951        if !self.out_buf.is_empty() {
952            #[cfg(debug_assertions)]
953            crate::trace::tee_output(&self.out_buf);
954            let mut written = 0;
955            let result = loop {
956                if written == self.out_buf.len() {
957                    break Ok(());
958                }
959                match self.writer.write(&self.out_buf[written..]) {
960                    Ok(0) => {
961                        break Err(io::Error::new(
962                            io::ErrorKind::WriteZero,
963                            "writer returned 0 with non-empty buffer",
964                        ));
965                    }
966                    Ok(count) => written += count,
967                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
968                    Err(error) => break Err(error),
969                }
970            };
971            self.out_buf.drain(..written);
972            result?;
973        }
974        self.writer.flush()
975    }
976}
977
978fn normalize_insert_above(content: &str, mode: WidthMode, eaw_wide: bool) -> Cow<'_, str> {
979    use crate::ansi::text::{TokenKind, tokenize};
980
981    if !content
982        .chars()
983        .any(|ch| ('\u{80}'..='\u{9f}').contains(&ch))
984    {
985        return Cow::Borrowed(content);
986    }
987    let mut output = Vec::with_capacity(content.len());
988    for token in tokenize(content.as_bytes(), mode, eaw_wide) {
989        match token.kind {
990            TokenKind::Text => output.extend_from_slice(token.bytes),
991            TokenKind::Control if token.bytes.len() == 2 => {
992                output.extend_from_slice(&[0x1b, token.control - 0x40]);
993            }
994            TokenKind::Control => output.extend_from_slice(token.bytes),
995            TokenKind::Escape => {
996                let mut sequence = token.bytes;
997                let string = matches!(
998                    sequence,
999                    [0xc2, 0x90 | 0x98 | 0x9d | 0x9e | 0x9f, ..]
1000                        | [0x1b, b'P' | b'X' | b']' | b'^' | b'_', ..]
1001                );
1002                if let [0xc2, control @ 0x80..=0x9f, rest @ ..] = sequence {
1003                    output.extend_from_slice(&[0x1b, control - 0x40]);
1004                    sequence = rest;
1005                }
1006                // Only string framing changes; encoded controls inside the payload stay opaque.
1007                if string && let Some(payload) = sequence.strip_suffix(&[0xc2, 0x9c]) {
1008                    output.extend_from_slice(payload);
1009                    output.extend_from_slice(b"\x1b\\");
1010                } else {
1011                    output.extend_from_slice(sequence);
1012                }
1013            }
1014        }
1015    }
1016    Cow::Owned(String::from_utf8(output).unwrap())
1017}
1018
1019impl<W: Write> Bounded for Screen<W> {
1020    fn bounds(&self) -> Rect {
1021        self.front_buf.bounds()
1022    }
1023}
1024
1025impl<W: Write> Surface for Screen<W> {
1026    fn cell(&self, pos: Position) -> Option<&Cell> {
1027        self.front_buf.cell(pos)
1028    }
1029}
1030
1031impl<W: Write> SurfaceMut for Screen<W> {
1032    fn set_cell(&mut self, pos: Position, cell: &Cell) {
1033        self.front_buf.set_cell(pos, cell);
1034    }
1035
1036    fn cell_mut(&mut self, pos: Position) -> Option<&mut Cell> {
1037        self.front_buf.cell_mut(pos)
1038    }
1039
1040    fn clear(&mut self) {
1041        self.front_buf.clear_changed();
1042    }
1043
1044    fn insert_lines(&mut self, y: u16, n: u16, bounds_bottom: u16, fill: &Cell) {
1045        self.front_buf.insert_lines(y, n, bounds_bottom, fill);
1046    }
1047
1048    fn delete_lines(&mut self, y: u16, n: u16, bounds_bottom: u16, fill: &Cell) {
1049        self.front_buf.delete_lines(y, n, bounds_bottom, fill);
1050    }
1051
1052    fn insert_cells(&mut self, pos: Position, n: u16, bounds_right: u16, fill: &Cell) {
1053        self.front_buf.insert_cells(pos, n, bounds_right, fill);
1054    }
1055
1056    fn delete_cells(&mut self, pos: Position, n: u16, bounds_right: u16, fill: &Cell) {
1057        self.front_buf.delete_cells(pos, n, bounds_right, fill);
1058    }
1059}
1060
1061impl<W: Write> TextSurface for Screen<W> {
1062    fn width_mode(&self) -> WidthMode {
1063        if self.grapheme_clusters {
1064            WidthMode::Grapheme
1065        } else {
1066            WidthMode::Wc
1067        }
1068    }
1069
1070    fn eaw_wide(&self) -> bool {
1071        self.eaw_wide
1072    }
1073}