uncurses 0.0.7

A Rust terminal rendering library
Documentation
//! Cursor/glyph emission helpers.
//!
//! Routines that the diff loop and other phases use to
//! relocate the cursor and to push glyph bytes through the right-margin
//! phantom and lower-right corner edge cases.

use std::io;

use crate::ansi;
use crate::layout::{Position, Size};
use crate::renderer::Renderer;
use crate::renderer::buffer::RenderBuffer;

/// What a cursor move is allowed to do to the active pen.
///
/// An inline downward move is emitted as literal `\n`, which scrolls the
/// host when the target row does not exist yet. Under back-color erase
/// that scroll paints the freshly exposed row with the pen's background.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PenPolicy {
    /// Reset the pen before a `\n` that can scroll, so the exposed row
    /// is erased with the terminal's default background — which is what
    /// an untouched row in `cur_buf` claims. The default.
    ResetBeforeScroll,
    /// Leave the pen alone: the caller is about to erase or scroll with
    /// it deliberately and records the resulting fill itself.
    Keep,
}

impl Renderer {
    /// Move cursor to the given position. Runs all the pre-move
    /// bookkeeping (width autowrap, phantom-cell snap, height clamp,
    /// no-op shortcut), then defers the actual emission to
    /// [`Renderer::move_cursor`] so the destination row is available
    /// for overwrite consideration.
    ///
    /// May reset the pen: an inline downward move is emitted as a
    /// literal `\n` that can scroll the host, and under back-color
    /// erase the exposed row would otherwise keep the active
    /// background. Callers that erase or scroll with the active pen
    /// deliberately want [`Renderer::move_to_keeping_pen`].
    ///
    /// Most callers want this. Callers that have already done the
    /// bookkeeping and need to skip it can call
    /// [`Renderer::move_cursor`] or [`Renderer::move_cursor_to`]
    /// directly.
    pub(crate) fn move_to(
        &mut self,
        out: &mut Vec<u8>,
        buf: &RenderBuffer,
        y: u16,
        x: u16,
    ) -> io::Result<()> {
        self.move_to_with_pen(out, Some(buf), y, x, PenPolicy::ResetBeforeScroll)
    }

    /// Move between frames, measured against the current managed `size`.
    ///
    /// Ordinary moves use control sequences rather than the planner's
    /// overwrite candidate. The desired grid can contain unrendered edits,
    /// so it must not supply cells for a move between frames.
    ///
    /// Past an uncertain cluster, the move instead walks the last rendered
    /// row. Those cells describe what the terminal already shows. A pending
    /// clear invalidates that snapshot, as after a resize or screen switch,
    /// and restricts the move to control sequences until the next render.
    ///
    /// `size` is the surface the wrap and the clamp are measured against. The
    /// renderer's own size is whatever it last rendered, which is what a move
    /// inside a frame wants; between a resize and the frame that answers it
    /// the caller's is the newer one, and measuring against the stale one
    /// wraps a column that now fits and clamps to a row that no longer
    /// exists, landing somewhere the caller never named.
    pub(crate) fn move_to_between_frames(
        &mut self,
        out: &mut Vec<u8>,
        size: Size,
        y: u16,
        x: u16,
    ) -> io::Result<()> {
        self.move_to_sized(
            out,
            None,
            size.width,
            size.height,
            y,
            x,
            PenPolicy::ResetBeforeScroll,
        )
    }

    /// Like [`Renderer::move_to`], but leaves the pen alone.
    ///
    /// For callers that immediately follow the move with an erase or
    /// scroll which is *meant* to fill with the active pen, and which
    /// record that fill in `cur_buf` themselves — the scroll emitters in
    /// [`crate::renderer::scroll`] and
    /// [`Renderer::clear_to_bottom`]. Resetting the pen underneath them
    /// would erase with the default background while the frame model
    /// recorded the styled one, which is the very divergence
    /// [`PenPolicy::ResetBeforeScroll`] exists to prevent.
    pub(crate) fn move_to_keeping_pen(
        &mut self,
        out: &mut Vec<u8>,
        buf: &RenderBuffer,
        y: u16,
        x: u16,
    ) -> io::Result<()> {
        self.move_to_with_pen(out, Some(buf), y, x, PenPolicy::Keep)
    }

    /// Measures the move against the last rendered size, which is what a
    /// caller inside a frame wants: the frame being diffed is that size.
    fn move_to_with_pen(
        &mut self,
        out: &mut Vec<u8>,
        buf: Option<&RenderBuffer>,
        y: u16,
        x: u16,
        pen: PenPolicy,
    ) -> io::Result<()> {
        self.move_to_sized(out, buf, self.last_width, self.last_height, y, x, pen)
    }

    #[allow(clippy::too_many_arguments)]
    fn move_to_sized(
        &mut self,
        out: &mut Vec<u8>,
        buf: Option<&RenderBuffer>,
        width: u16,
        height: u16,
        y: u16,
        x: u16,
        pen: PenPolicy,
    ) -> io::Result<()> {
        let mut y = y;
        let mut x = x;

        // A target that exceeds the surface width is treated as a
        // wrap: y += x / width, x %= width. Keeps the cursor model
        // consistent with autowrap-on terminals.
        if width > 0 && x >= width {
            y = y.saturating_add(x / width);
            x %= width;
        }

        // Right-margin phantom: the terminal cursor is in the last
        // column with the pending-wrap flag set, but our tracked
        // column is one past the last column. A bare `\r` resyncs.
        if self.cur.at_phantom {
            out.push(b'\r');
            self.cur.x = Some(0);
            self.cur.at_phantom = false;
        }

        // Clamp the target to the surface height: we may be mid-resize
        // and `height` could already reflect the new size. The
        // tracked source position is left untouched — when it sits
        // outside the new bounds (e.g. a finalize-snapped cursor at
        // the bottom of the previous, taller surface), the relative
        // move planner must still emit the full CUU back to the new
        // bounds. Clamping the source would silently drop those rows
        // and leave the physical cursor below where the renderer
        // believes it is, leaving stale content above the new surface
        // on inline shrinks.
        if height > 0 {
            let max_y = height - 1;
            if y > max_y {
                y = max_y;
            }
        }

        if buf.is_none() && !self.force_clear {
            // Use the displayed snapshot, never the desired or staging grid.
            // Restore it even if the walk reports an output error.
            let current = self.cur_buf.take();
            let walked = current.as_ref().map_or(Ok(false), |current| {
                self.walk_to_uncertain(out, current, y, x)
            });
            self.cur_buf = current;
            if walked? {
                return Ok(());
            }
        }

        if self.cur.x == Some(x) && self.cur.y == Some(y) {
            return Ok(());
        }

        self.move_cursor_with_pen(out, buf, y, x, pen)
    }

    /// Emit a cursor move using the destination row's cells from
    /// `buf` for overwrite consideration. The bare wrapper for
    /// `move_to`: handles only the inline-mode initial `\r` snap,
    /// then defers to the optimal-move planner. Use
    /// [`Renderer::move_to`] unless you already handled the
    /// pre-move bookkeeping yourself.
    ///
    /// Test-only convenience wrapper: production callers reach the
    /// planner through [`Renderer::move_to`] so the pen policy is
    /// always stated explicitly.
    #[cfg(test)]
    pub(crate) fn move_cursor(
        &mut self,
        out: &mut Vec<u8>,
        buf: &RenderBuffer,
        y: u16,
        x: u16,
    ) -> io::Result<()> {
        self.move_cursor_with_pen(out, Some(buf), y, x, PenPolicy::ResetBeforeScroll)
    }

    fn move_cursor_with_pen(
        &mut self,
        out: &mut Vec<u8>,
        buf: Option<&RenderBuffer>,
        y: u16,
        x: u16,
        pen: PenPolicy,
    ) -> io::Result<()> {
        // Inline mode with an unknown column: snap to column 0 with a
        // bare `\r` so the relative move below has a deterministic
        // starting column. Without it the planner would start from the
        // `0` that `Cursor::pos` substitutes for the unknown and step
        // relatively from a column the cursor is not on. Fullscreen mode
        // handles the same condition by emitting absolute CUP from the
        // planner.
        if !self.fullscreen && self.relative_cursor && self.cur.x.is_none() {
            self.reanchor_to_row_start(out);
            // With the row unknown as well, assume the current physical row
            // is the top of the surface, so the relative move below only
            // ever steps downward — it can never CUU above a
            // reflowed/handed-off cursor.
            if self.cur.y.is_none() {
                self.cur.y = Some(0);
            }
        }

        let target = Position { x, y };
        let line = buf.and_then(|buf| buf.line(y));
        self.write_optimal_move_with_pen(out, self.cur.pos(), target, line, pen)?;
        self.cur.set_pos(target);
        Ok(())
    }

    /// Mark the tracked cursor position as no longer matching the
    /// terminal on either axis. The next [`Renderer::move_to`]
    /// reasserts position.
    pub(crate) fn invalidate_cursor(&mut self) {
        self.cur.x = None;
        self.cur.y = None;
    }

    /// Park the cursor on the left edge of the row it is already on.
    ///
    /// A carriage return is the one horizontal move whose outcome does not
    /// depend on the current column, which is what makes it the way back to
    /// a known column after the terminal advanced by an amount the renderer
    /// did not predict. The row it lands on is the row it started on, so
    /// this recovers the column only, and the caller owns keeping the row
    /// trustworthy.
    pub(crate) fn reanchor_to_row_start(&mut self, out: &mut Vec<u8>) {
        out.push(b'\r');
        self.cur.x = Some(0);
        self.cur.at_phantom = false;
    }

    /// Write a single grapheme to the output buffer, handling the
    /// right-margin auto-wrap "phantom" state and protecting the lower
    /// right corner from triggering an unwanted scroll in fullscreen mode.
    ///
    /// Returns whether the cell was written. `width` here is the buffer
    /// width — the column count of the surface we render into.
    pub(crate) fn put_glyph_bytes(
        &mut self,
        out: &mut Vec<u8>,
        content: &[u8],
        cell_width: u16,
        surface_width: u16,
        surface_height: u16,
    ) -> io::Result<()> {
        if cell_width == 0 {
            return Ok(());
        }

        // If we are sitting in the right-margin phantom cell from a prior
        // write, advancing the cursor before writing this glyph would
        // happen via terminal auto-wrap. We don't want to depend on that
        // implicit behavior — emit an explicit move to the start of the
        // next row so the result is the same on every terminal.
        if self.cur.at_phantom {
            let next_y = self.cur.pos().y.saturating_add(1);
            if next_y < surface_height {
                let target = Position { y: next_y, x: 0 };
                self.write_optimal_move(out, self.cur.pos(), target, None)?;
                self.cur.set_pos(target);
            }
            self.cur.at_phantom = false;
        }

        // True lower-right corner: cursor sitting at (width-1, height-1)
        // with a single-column cell about to be written. Multi-column
        // cells that merely *reach* the last column don't apply — a
        // width-2 cell starting at width-2 occupies the last column but
        // the cursor itself is at width-2, not width-1, so writing it
        // doesn't trigger the bottom-right scroll quirk.
        let is_lower_right_corner = self.fullscreen
            && cell_width == 1
            && self.cur.pos().x + 1 == surface_width
            && self.cur.pos().y + 1 == surface_height;

        if is_lower_right_corner {
            // Writing the bottom-right corner in alt-screen normally pushes
            // the cursor into pending-wrap. The very next emission (or
            // sometimes even the next CSI) can then provoke an auto-wrap
            // that scrolls the alt screen up by one row. Disable auto-wrap
            // for just this glyph and restore it immediately.
            ansi::mode::Mode::AUTO_WRAP.reset(out)?;
            out.extend_from_slice(content);
            ansi::mode::Mode::AUTO_WRAP.set(out)?;
            // Cursor stays at the corner — explicitly. No phantom.
            // (Some terminals leave it at width-1, others at width; treat
            // it as width-1 since auto-wrap is now off and a subsequent
            // print would just overwrite the same cell.)
            self.cur.x = Some(surface_width.saturating_sub(1));
            self.cur.at_phantom = false;
            return Ok(());
        }

        out.extend_from_slice(content);
        let new_x = self.cur.pos().x.saturating_add(cell_width);
        if new_x >= surface_width {
            // Park at the right-margin phantom; clamp tracked column so it
            // doesn't drift past `surface_width` over successive writes.
            self.cur.x = Some(surface_width);
            self.cur.at_phantom = true;
        } else {
            self.cur.x = Some(new_x);
        }
        Ok(())
    }
}