euv-core 0.48.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Single character cell inside a `TerminalCellGrid` supporting wide CJK glyphs, Extended Grapheme Clusters (combining marks & ZWJ emoji), and truecolor styling with zero heap allocation.
#[derive(Clone, Copy, Data, Debug, Eq, Hash, PartialEq)]
pub struct TerminalCell {
    /// Leading Unicode scalar value (`' '` when empty, `'\0'` on trailing wide-char continuation cells).
    #[get(type(copy))]
    pub(crate) ch: char,
    /// Display column width: `1` for narrow, `2` for wide lead cell, `0` for wide continuation cell.
    #[get(type(copy))]
    pub(crate) width: u8,
    /// Optional 24-bit foreground text color.
    #[get(skip)]
    pub(crate) fg: Option<Color>,
    /// Optional 24-bit cell background color.
    #[get(skip)]
    pub(crate) bg: Option<Color>,
    /// Whether bold SGR emphasis is active.
    #[get(type(copy))]
    pub(crate) bold: bool,
    /// Whether reverse-video SGR highlight (used for focus indicators) is active.
    #[get(type(copy))]
    pub(crate) reverse: bool,
    /// Whether underline SGR decoration is active.
    #[get(type(copy))]
    pub(crate) underline: bool,
    /// Length in UTF-8 bytes of trailing scalars in the same Extended Grapheme Cluster (`0..=28`).
    #[get(type(copy))]
    pub(crate) tail_len: u8,
    /// Inline UTF-8 byte buffer holding combining marks, variation selectors, or ZWJ emoji sequences.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) tail_utf8: [u8; TERMINAL_CELL_TAIL_CAPACITY],
}

/// Dense `cols x rows` character cell surface with per-row dirty tracking and row hashes for O(1) unchanged-row diff skipping.
#[derive(Clone, Data, Debug, Default, Eq, PartialEq)]
pub struct TerminalCellGrid {
    /// Terminal grid width in character columns.
    #[get(type(copy))]
    pub(crate) cols: u16,
    /// Terminal grid height in character rows.
    #[get(type(copy))]
    pub(crate) rows: u16,
    /// Row-major cell buffer of length `cols as usize * rows as usize`.
    pub(crate) cells: Vec<TerminalCell>,
    /// Cached FNV-1a hash per row enabling O(1) clean-row skipping during incremental diff encoding.
    pub(crate) row_hashes: Vec<u64>,
    /// Per-row dirty mask recording which rows were mutated since the last `reset()`.
    pub(crate) dirty_rows: Vec<bool>,
    /// Precomputed FNV-1a hash of a completely blank row of length `cols`.
    #[get(type(copy))]
    pub(crate) blank_row_hash: u64,
}

/// Per-frame terminal cell-diff and bandwidth telemetry produced by `TerminalRenderer::render_tree`.
#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, New, PartialEq)]
pub struct TerminalDiffStats {
    /// Total cells in the active `cols x rows` terminal grid.
    #[get(type(copy))]
    pub(crate) total_cells: usize,
    /// Number of cells that differed from the previous frame (equals `total_cells` on full sync).
    #[get(type(copy))]
    pub(crate) changed_cells: usize,
    /// Number of UTF-8 bytes emitted in the rendered output payload.
    #[get(type(copy))]
    pub(crate) output_bytes: usize,
    /// `true` when zero cells changed in interactive mode and zero bytes were flushed.
    #[get(type(copy))]
    pub(crate) is_idle: bool,
    /// `true` when the frame performed a full screen synchronization (first frame, resize, or post-error recovery).
    #[get(type(copy))]
    pub(crate) full_sync: bool,
}

/// Compact O(1) frame state fingerprint governing zero-work idle short-circuiting in interactive TUI mode.
#[derive(Clone, Copy, Data, Debug, Eq, Hash, PartialEq)]
pub struct TerminalFrameFingerprint {
    /// Scene tree revision counter.
    #[get(type(copy))]
    pub(crate) scene_revision: u64,
    /// Currently focused scene node identifier, if any.
    #[get(skip)]
    pub(crate) focused: Option<NodeId>,
    /// Current caret blinking visibility phase.
    #[get(type(copy))]
    pub(crate) caret_visible: bool,
    /// Caret byte offset within the focused text input, if any.
    #[get(type(copy))]
    pub(crate) focused_caret_offset: usize,
    /// Hash across active scroll container offsets.
    #[get(type(copy))]
    pub(crate) scroll_hash: u64,
    /// Terminal viewport width in columns.
    #[get(type(copy))]
    pub(crate) cols: u16,
    /// Terminal viewport height in rows.
    #[get(type(copy))]
    pub(crate) rows: u16,
    /// Render mode (`InteractiveTui` vs `StaticPlainText`).
    #[get(type(copy))]
    pub(crate) mode: TerminalRenderMode,
}

/// Explicit non-GPU, non-Hz telemetry report emitted by TUI and CLI pipelines (`input_to_output_ms`, `flush_latency_ms`, `bytes_written`, backpressure).
#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
pub struct TerminalNonGpuTelemetry {
    /// Active terminal mode (`InteractiveTui` vs `StaticPlainText`).
    #[get(type(copy))]
    pub(crate) mode: TerminalRenderMode,
    /// Always `true`: TUI/CLI explicitly opts out of graphical GPU routing.
    #[get(type(copy))]
    pub(crate) gpu_routing_opted_out: bool,
    /// Always `false`: TUI/CLI metrics are NOT evaluated against screen refresh Hz.
    #[get(type(copy))]
    pub(crate) uses_screen_hz: bool,
    /// Measured input-to-output latency in milliseconds (`None` when no input preceded this flush).
    #[get(skip)]
    pub(crate) input_to_output_ms: Option<f64>,
    /// Measured write+flush latency in milliseconds for this batched output.
    #[get(type(copy))]
    pub(crate) flush_latency_ms: f64,
    /// Exact UTF-8 bytes written during this flush (`0` on unchanged-frame skip).
    #[get(type(copy))]
    pub(crate) bytes_written: u64,
    /// Cumulative UTF-8 bytes written across the terminal session.
    #[get(type(copy))]
    pub(crate) total_bytes_written: u64,
    /// Number of character cells changed on this frame (`0` on unchanged skip).
    #[get(type(copy))]
    pub(crate) changed_cells: usize,
    /// True when an unchanged interactive TUI frame was skipped with zero bytes emitted.
    #[get(type(copy))]
    pub(crate) unchanged_frame_skipped: bool,
    /// Cumulative count of backpressure events (`WouldBlock`, `Interrupted`, partial writes, or `BrokenPipe`).
    #[get(type(copy))]
    pub(crate) backpressure_events: u64,
    /// Cumulative count of coalesced batched output flushes.
    #[get(type(copy))]
    pub(crate) batched_flush_count: u64,
}

/// Outcome of a batched `TerminalRenderer::render_tree_to_writer` call including swap commit status and non-Hz telemetry.
#[derive(Clone, Data, Debug, Default, PartialEq)]
pub struct TerminalWriteResult {
    /// Write status (`Written`, `BrokenPipe`, or `IoError`).
    #[get(type(copy))]
    pub(crate) status: CliWriteStatus,
    /// Per-frame diff and bandwidth telemetry.
    #[get(type(copy))]
    pub(crate) stats: TerminalDiffStats,
    /// `true` when double-buffer ownership was swapped after a confirmed successful write.
    #[get(type(copy))]
    pub(crate) swapped: bool,
    /// Optional human-readable error message when `status != CliWriteStatus::Written`.
    #[get(skip)]
    pub(crate) error_message: Option<String>,
    /// Explicit non-GPU, non-Hz TUI/CLI telemetry (`input_to_output_ms`, `flush_latency_ms`, `bytes_written`, backpressure).
    #[get(type(copy))]
    pub(crate) telemetry: TerminalNonGpuTelemetry,
}

/// RAII terminal session guard restoring cursor visibility, raw mode flags, and alternate screen on drop.
#[derive(CustomDebug, Data)]
pub struct TerminalSessionGuard {
    /// Whether alternate screen mode was entered and must be exited on drop.
    #[get(type(copy))]
    pub(crate) alt_screen: bool,
    /// Whether cursor visibility was hidden and must be restored on drop.
    #[get(type(copy))]
    pub(crate) cursor_hidden: bool,
    /// Whether terminal raw/bracketed input modes were enabled and must be reset on drop.
    #[get(type(copy))]
    pub(crate) raw_mode: bool,
    /// Whether terminal restoration has already completed.
    #[get(type(copy))]
    pub(crate) restored: bool,
    /// Whether enter/restore sequences should also be flushed directly to standard output on native targets.
    #[get(type(copy))]
    pub(crate) write_to_stdout: bool,
    /// Optional capture buffer recording emitted enter and restore escape sequences for deterministic testing.
    #[debug(skip)]
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) sink: Option<Rc<RefCell<String>>>,
}

/// Stateful double-buffered terminal renderer projecting a retained `SceneTree` into coalesced ANSI TUI diffs or zero-ANSI static CLI plain text.
#[derive(Clone, Data, Debug, Default, PartialEq)]
pub struct TerminalRenderer {
    /// Persistent previously presented cell grid swapped in-place with `current` via `swap` (zero per-frame full-grid clones; unallocated in `StaticPlainText` mode).
    pub(crate) previous: TerminalCellGrid,
    /// `true` iff `previous` holds a confirmed committed interactive frame matching `last_cols x last_rows`.
    #[get(type(copy))]
    pub(crate) previous_valid: bool,
    /// Working character grid populated during the current frame.
    pub(crate) current: TerminalCellGrid,
    /// Cached frame fingerprint enabling zero-work idle short-circuiting.
    #[get(skip)]
    pub(crate) last_fingerprint: Option<TerminalFrameFingerprint>,
    /// Scroll container handles observed during the last projection for O(#scrolls) scroll-offset hashing.
    pub(crate) tracked_scroll_nodes: Vec<NodeId>,
    /// Reusable ANSI output scratch buffer reducing steady-state heap churn.
    pub(crate) ansi_scratch: String,
    /// Last rendered terminal column count for resize detection.
    #[get(type(copy))]
    pub(crate) last_cols: u16,
    /// Last rendered terminal row count for resize detection.
    #[get(type(copy))]
    pub(crate) last_rows: u16,
    /// Total non-skipped frames projected through this renderer.
    #[get(type(copy))]
    pub(crate) frames_rendered: u64,
    /// Total interactive frames short-circuited in O(1) with zero projection and zero output bytes.
    #[get(type(copy))]
    pub(crate) skipped_idle_frames: u64,
    /// Number of rows actually projected during the most recent frame (`0` on short-circuited idle frames).
    #[get(type(copy))]
    pub(crate) last_projected_rows: usize,
    /// Whether DEC Mode 2026 synchronized update sequences wrap non-empty interactive ANSI payloads.
    #[get(type(copy))]
    pub(crate) sync_output_mode: bool,
    /// Whether keyboard navigation has requested terminal session exit.
    #[get(type(copy))]
    pub(crate) exit_requested: bool,
    #[cfg(not(target_arch = "wasm32"))]
    /// Timestamp of the latest input event used to measure truthful `input_to_output_ms`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) last_input_at: Option<Instant>,
    /// Cumulative UTF-8 bytes written across all terminal flushes.
    #[get(type(copy))]
    pub(crate) total_bytes_written: u64,
    /// Cumulative backpressure events observed during batched writes.
    #[get(type(copy))]
    pub(crate) backpressure_events: u64,
    /// Cumulative batched output flushes executed.
    #[get(type(copy))]
    pub(crate) batched_flush_count: u64,
    /// Most recent non-GPU, non-Hz TUI/CLI telemetry snapshot.
    #[get(type(copy))]
    pub(crate) last_telemetry: TerminalNonGpuTelemetry,
}

/// Internal character-grid layout viewport passed recursively while projecting scene nodes.
#[derive(Clone, Copy, Data, Debug, Default, Eq, New, PartialEq)]
pub(crate) struct TerminalRegion {
    /// Left column bound of the active character region.
    #[get(type(copy))]
    pub(crate) x: u16,
    /// Available horizontal width in terminal columns.
    #[get(type(copy))]
    pub(crate) width: u16,
    /// Exclusive bottom row limit of the active character region.
    #[get(type(copy))]
    pub(crate) max_y: u16,
    /// Currently focused scene node handle, if any.
    #[get(type(copy))]
    pub(crate) focused: Option<NodeId>,
}