Skip to main content

euv_core/render/terminal/
struct.rs

1use super::*;
2
3/// Single character cell inside a `TerminalCellGrid` supporting wide CJK glyphs, Extended Grapheme Clusters (combining marks & ZWJ emoji), and truecolor styling with zero heap allocation.
4#[derive(Clone, Copy, Data, Debug, Eq, Hash, PartialEq)]
5pub struct TerminalCell {
6    /// Leading Unicode scalar value (`' '` when empty, `'\0'` on trailing wide-char continuation cells).
7    #[get(type(copy))]
8    pub(crate) ch: char,
9    /// Display column width: `1` for narrow, `2` for wide lead cell, `0` for wide continuation cell.
10    #[get(type(copy))]
11    pub(crate) width: u8,
12    /// Optional 24-bit foreground text color.
13    #[get(skip)]
14    pub(crate) fg: Option<Color>,
15    /// Optional 24-bit cell background color.
16    #[get(skip)]
17    pub(crate) bg: Option<Color>,
18    /// Whether bold SGR emphasis is active.
19    #[get(type(copy))]
20    pub(crate) bold: bool,
21    /// Whether reverse-video SGR highlight (used for focus indicators) is active.
22    #[get(type(copy))]
23    pub(crate) reverse: bool,
24    /// Whether underline SGR decoration is active.
25    #[get(type(copy))]
26    pub(crate) underline: bool,
27    /// Length in UTF-8 bytes of trailing scalars in the same Extended Grapheme Cluster (`0..=28`).
28    #[get(type(copy))]
29    pub(crate) tail_len: u8,
30    /// Inline UTF-8 byte buffer holding combining marks, variation selectors, or ZWJ emoji sequences.
31    #[get(skip)]
32    #[get_mut(skip)]
33    #[set(skip)]
34    pub(crate) tail_utf8: [u8; TERMINAL_CELL_TAIL_CAPACITY],
35}
36
37/// Dense `cols x rows` character cell surface with per-row dirty tracking and row hashes for O(1) unchanged-row diff skipping.
38#[derive(Clone, Data, Debug, Default, Eq, PartialEq)]
39pub struct TerminalCellGrid {
40    /// Terminal grid width in character columns.
41    #[get(type(copy))]
42    pub(crate) cols: u16,
43    /// Terminal grid height in character rows.
44    #[get(type(copy))]
45    pub(crate) rows: u16,
46    /// Row-major cell buffer of length `cols as usize * rows as usize`.
47    pub(crate) cells: Vec<TerminalCell>,
48    /// Cached FNV-1a hash per row enabling O(1) clean-row skipping during incremental diff encoding.
49    pub(crate) row_hashes: Vec<u64>,
50    /// Per-row dirty mask recording which rows were mutated since the last `reset()`.
51    pub(crate) dirty_rows: Vec<bool>,
52    /// Precomputed FNV-1a hash of a completely blank row of length `cols`.
53    #[get(type(copy))]
54    pub(crate) blank_row_hash: u64,
55}
56
57/// Per-frame terminal cell-diff and bandwidth telemetry produced by `TerminalRenderer::render_tree`.
58#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, New, PartialEq)]
59pub struct TerminalDiffStats {
60    /// Total cells in the active `cols x rows` terminal grid.
61    #[get(type(copy))]
62    pub(crate) total_cells: usize,
63    /// Number of cells that differed from the previous frame (equals `total_cells` on full sync).
64    #[get(type(copy))]
65    pub(crate) changed_cells: usize,
66    /// Number of UTF-8 bytes emitted in the rendered output payload.
67    #[get(type(copy))]
68    pub(crate) output_bytes: usize,
69    /// `true` when zero cells changed in interactive mode and zero bytes were flushed.
70    #[get(type(copy))]
71    pub(crate) is_idle: bool,
72    /// `true` when the frame performed a full screen synchronization (first frame, resize, or post-error recovery).
73    #[get(type(copy))]
74    pub(crate) full_sync: bool,
75}
76
77/// Compact O(1) frame state fingerprint governing zero-work idle short-circuiting in interactive TUI mode.
78#[derive(Clone, Copy, Data, Debug, Eq, Hash, PartialEq)]
79pub struct TerminalFrameFingerprint {
80    /// Scene tree revision counter.
81    #[get(type(copy))]
82    pub(crate) scene_revision: u64,
83    /// Currently focused scene node identifier, if any.
84    #[get(skip)]
85    pub(crate) focused: Option<NodeId>,
86    /// Current caret blinking visibility phase.
87    #[get(type(copy))]
88    pub(crate) caret_visible: bool,
89    /// Caret byte offset within the focused text input, if any.
90    #[get(type(copy))]
91    pub(crate) focused_caret_offset: usize,
92    /// Hash across active scroll container offsets.
93    #[get(type(copy))]
94    pub(crate) scroll_hash: u64,
95    /// Terminal viewport width in columns.
96    #[get(type(copy))]
97    pub(crate) cols: u16,
98    /// Terminal viewport height in rows.
99    #[get(type(copy))]
100    pub(crate) rows: u16,
101    /// Render mode (`InteractiveTui` vs `StaticPlainText`).
102    #[get(type(copy))]
103    pub(crate) mode: TerminalRenderMode,
104}
105
106/// Explicit non-GPU, non-Hz telemetry report emitted by TUI and CLI pipelines (`input_to_output_ms`, `flush_latency_ms`, `bytes_written`, backpressure).
107#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
108pub struct TerminalNonGpuTelemetry {
109    /// Active terminal mode (`InteractiveTui` vs `StaticPlainText`).
110    #[get(type(copy))]
111    pub(crate) mode: TerminalRenderMode,
112    /// Always `true`: TUI/CLI explicitly opts out of graphical GPU routing.
113    #[get(type(copy))]
114    pub(crate) gpu_routing_opted_out: bool,
115    /// Always `false`: TUI/CLI metrics are NOT evaluated against screen refresh Hz.
116    #[get(type(copy))]
117    pub(crate) uses_screen_hz: bool,
118    /// Measured input-to-output latency in milliseconds (`None` when no input preceded this flush).
119    #[get(skip)]
120    pub(crate) input_to_output_ms: Option<f64>,
121    /// Measured write+flush latency in milliseconds for this batched output.
122    #[get(type(copy))]
123    pub(crate) flush_latency_ms: f64,
124    /// Exact UTF-8 bytes written during this flush (`0` on unchanged-frame skip).
125    #[get(type(copy))]
126    pub(crate) bytes_written: u64,
127    /// Cumulative UTF-8 bytes written across the terminal session.
128    #[get(type(copy))]
129    pub(crate) total_bytes_written: u64,
130    /// Number of character cells changed on this frame (`0` on unchanged skip).
131    #[get(type(copy))]
132    pub(crate) changed_cells: usize,
133    /// True when an unchanged interactive TUI frame was skipped with zero bytes emitted.
134    #[get(type(copy))]
135    pub(crate) unchanged_frame_skipped: bool,
136    /// Cumulative count of backpressure events (`WouldBlock`, `Interrupted`, partial writes, or `BrokenPipe`).
137    #[get(type(copy))]
138    pub(crate) backpressure_events: u64,
139    /// Cumulative count of coalesced batched output flushes.
140    #[get(type(copy))]
141    pub(crate) batched_flush_count: u64,
142}
143
144/// Outcome of a batched `TerminalRenderer::render_tree_to_writer` call including swap commit status and non-Hz telemetry.
145#[derive(Clone, Data, Debug, Default, PartialEq)]
146pub struct TerminalWriteResult {
147    /// Write status (`Written`, `BrokenPipe`, or `IoError`).
148    #[get(type(copy))]
149    pub(crate) status: CliWriteStatus,
150    /// Per-frame diff and bandwidth telemetry.
151    #[get(type(copy))]
152    pub(crate) stats: TerminalDiffStats,
153    /// `true` when double-buffer ownership was swapped after a confirmed successful write.
154    #[get(type(copy))]
155    pub(crate) swapped: bool,
156    /// Optional human-readable error message when `status != CliWriteStatus::Written`.
157    #[get(skip)]
158    pub(crate) error_message: Option<String>,
159    /// Explicit non-GPU, non-Hz TUI/CLI telemetry (`input_to_output_ms`, `flush_latency_ms`, `bytes_written`, backpressure).
160    #[get(type(copy))]
161    pub(crate) telemetry: TerminalNonGpuTelemetry,
162}
163
164/// RAII terminal session guard restoring cursor visibility, raw mode flags, and alternate screen on drop.
165#[derive(CustomDebug, Data)]
166pub struct TerminalSessionGuard {
167    /// Whether alternate screen mode was entered and must be exited on drop.
168    #[get(type(copy))]
169    pub(crate) alt_screen: bool,
170    /// Whether cursor visibility was hidden and must be restored on drop.
171    #[get(type(copy))]
172    pub(crate) cursor_hidden: bool,
173    /// Whether terminal raw/bracketed input modes were enabled and must be reset on drop.
174    #[get(type(copy))]
175    pub(crate) raw_mode: bool,
176    /// Whether terminal restoration has already completed.
177    #[get(type(copy))]
178    pub(crate) restored: bool,
179    /// Whether enter/restore sequences should also be flushed directly to standard output on native targets.
180    #[get(type(copy))]
181    pub(crate) write_to_stdout: bool,
182    /// Optional capture buffer recording emitted enter and restore escape sequences for deterministic testing.
183    #[debug(skip)]
184    #[get(skip)]
185    #[get_mut(skip)]
186    #[set(skip)]
187    pub(crate) sink: Option<Rc<RefCell<String>>>,
188}
189
190/// Stateful double-buffered terminal renderer projecting a retained `SceneTree` into coalesced ANSI TUI diffs or zero-ANSI static CLI plain text.
191#[derive(Clone, Data, Debug, Default, PartialEq)]
192pub struct TerminalRenderer {
193    /// Persistent previously presented cell grid swapped in-place with `current` via `swap` (zero per-frame full-grid clones; unallocated in `StaticPlainText` mode).
194    pub(crate) previous: TerminalCellGrid,
195    /// `true` iff `previous` holds a confirmed committed interactive frame matching `last_cols x last_rows`.
196    #[get(type(copy))]
197    pub(crate) previous_valid: bool,
198    /// Working character grid populated during the current frame.
199    pub(crate) current: TerminalCellGrid,
200    /// Cached frame fingerprint enabling zero-work idle short-circuiting.
201    #[get(skip)]
202    pub(crate) last_fingerprint: Option<TerminalFrameFingerprint>,
203    /// Scroll container handles observed during the last projection for O(#scrolls) scroll-offset hashing.
204    pub(crate) tracked_scroll_nodes: Vec<NodeId>,
205    /// Reusable ANSI output scratch buffer reducing steady-state heap churn.
206    pub(crate) ansi_scratch: String,
207    /// Last rendered terminal column count for resize detection.
208    #[get(type(copy))]
209    pub(crate) last_cols: u16,
210    /// Last rendered terminal row count for resize detection.
211    #[get(type(copy))]
212    pub(crate) last_rows: u16,
213    /// Total non-skipped frames projected through this renderer.
214    #[get(type(copy))]
215    pub(crate) frames_rendered: u64,
216    /// Total interactive frames short-circuited in O(1) with zero projection and zero output bytes.
217    #[get(type(copy))]
218    pub(crate) skipped_idle_frames: u64,
219    /// Number of rows actually projected during the most recent frame (`0` on short-circuited idle frames).
220    #[get(type(copy))]
221    pub(crate) last_projected_rows: usize,
222    /// Whether DEC Mode 2026 synchronized update sequences wrap non-empty interactive ANSI payloads.
223    #[get(type(copy))]
224    pub(crate) sync_output_mode: bool,
225    /// Whether keyboard navigation has requested terminal session exit.
226    #[get(type(copy))]
227    pub(crate) exit_requested: bool,
228    #[cfg(not(target_arch = "wasm32"))]
229    /// Timestamp of the latest input event used to measure truthful `input_to_output_ms`.
230    #[get(skip)]
231    #[get_mut(skip)]
232    #[set(skip)]
233    pub(crate) last_input_at: Option<Instant>,
234    /// Cumulative UTF-8 bytes written across all terminal flushes.
235    #[get(type(copy))]
236    pub(crate) total_bytes_written: u64,
237    /// Cumulative backpressure events observed during batched writes.
238    #[get(type(copy))]
239    pub(crate) backpressure_events: u64,
240    /// Cumulative batched output flushes executed.
241    #[get(type(copy))]
242    pub(crate) batched_flush_count: u64,
243    /// Most recent non-GPU, non-Hz TUI/CLI telemetry snapshot.
244    #[get(type(copy))]
245    pub(crate) last_telemetry: TerminalNonGpuTelemetry,
246}
247
248/// Internal character-grid layout viewport passed recursively while projecting scene nodes.
249#[derive(Clone, Copy, Data, Debug, Default, Eq, New, PartialEq)]
250pub(crate) struct TerminalRegion {
251    /// Left column bound of the active character region.
252    #[get(type(copy))]
253    pub(crate) x: u16,
254    /// Available horizontal width in terminal columns.
255    #[get(type(copy))]
256    pub(crate) width: u16,
257    /// Exclusive bottom row limit of the active character region.
258    #[get(type(copy))]
259    pub(crate) max_y: u16,
260    /// Currently focused scene node handle, if any.
261    #[get(type(copy))]
262    pub(crate) focused: Option<NodeId>,
263}