Skip to main content

euv_core/platform/terminal/
impl.rs

1use super::*;
2
3/// Default cell metrics (`80x24`, `8x16` logical pixels per cell).
4impl Default for TerminalCellMetrics {
5    /// Creates standard 80x24 terminal cell metrics.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default `TerminalCellMetrics`.
10    fn default() -> Self {
11        Self::new(
12            TERMINAL_DEFAULT_COLS,
13            TERMINAL_DEFAULT_ROWS,
14            TERMINAL_DEFAULT_CELL_WIDTH,
15            TERMINAL_DEFAULT_CELL_HEIGHT,
16        )
17    }
18}
19
20/// Logical geometry conversion helpers for `TerminalCellMetrics`.
21impl TerminalCellMetrics {
22    /// Computes equivalent logical viewport width in pixels (`cols * cell_width_px`).
23    ///
24    /// # Arguments
25    ///
26    /// - `&Self` - Cell metrics reference.
27    ///
28    /// # Returns
29    ///
30    /// - `u32` - Logical viewport width in pixels (`>= 1`).
31    #[must_use]
32    pub fn logical_width(&self) -> u32 {
33        let width_val: f32 = f32::from(self.get_cols().max(1)) * self.get_cell_width_px().max(1.0);
34        width_val.round().max(1.0) as u32
35    }
36
37    /// Computes equivalent logical viewport height in pixels (`rows * cell_height_px`).
38    ///
39    /// # Arguments
40    ///
41    /// - `&Self` - Cell metrics reference.
42    ///
43    /// # Returns
44    ///
45    /// - `u32` - Logical viewport height in pixels (`>= 1`).
46    #[must_use]
47    pub fn logical_height(&self) -> u32 {
48        let height_val: f32 =
49            f32::from(self.get_rows().max(1)) * self.get_cell_height_px().max(1.0);
50        height_val.round().max(1.0) as u32
51    }
52}
53
54/// Host mode resolution helpers for `TerminalTtyProbe`.
55impl TerminalTtyProbe {
56    /// Resolves `TerminalHostMode::Auto` into a concrete `InteractiveTui` or `StaticCli` mode.
57    ///
58    /// # Arguments
59    ///
60    /// - `&Self` - TTY probe reference.
61    /// - `TerminalHostMode` - Requested operating mode.
62    ///
63    /// # Returns
64    ///
65    /// - `TerminalHostMode` - Concrete `InteractiveTui` or `StaticCli` mode.
66    #[must_use]
67    pub fn resolve_mode(&self, requested: TerminalHostMode) -> TerminalHostMode {
68        match requested {
69            TerminalHostMode::Auto => {
70                if self.get_stdin_is_tty() && self.get_stdout_is_tty() {
71                    TerminalHostMode::InteractiveTui
72                } else {
73                    TerminalHostMode::StaticCli
74                }
75            }
76            explicit => explicit,
77        }
78    }
79
80    /// Returns whether ANSI color escapes should be emitted in static/pipe CLI mode.
81    ///
82    /// # Arguments
83    ///
84    /// - `&Self` - TTY probe reference.
85    ///
86    /// # Returns
87    ///
88    /// - `bool` - `true` only when stdout is a TTY, `NO_COLOR` is unset, and color depth is non-none.
89    #[must_use]
90    pub fn allows_ansi(&self) -> bool {
91        self.get_stdout_is_tty()
92            && !self.get_no_color()
93            && self.get_color() != TerminalColorCapability::None
94    }
95}
96
97/// RAII terminal mode entry and idempotent restoration methods for `TerminalRawGuard`.
98impl TerminalRawGuard {
99    /// Enters live OS terminal raw mode (Unix termios / Windows VT console), installs `SIGWINCH`, and emits enter sequences.
100    ///
101    /// # Arguments
102    ///
103    /// - `bool` - Enter alternate screen buffer.
104    /// - `bool` - Enable SGR 1006 mouse tracking.
105    /// - `bool` - Enable bracketed paste mode.
106    /// - `bool` - Hide terminal cursor.
107    ///
108    /// # Returns
109    ///
110    /// - `Self` - Active RAII guard restoring terminal state on drop.
111    #[must_use]
112    pub fn enter_live(
113        alt_screen: bool,
114        mouse_enabled: bool,
115        paste_enabled: bool,
116        cursor_hidden: bool,
117    ) -> Self {
118        terminal_install_sigwinch_handler();
119        #[cfg(unix)]
120        let saved_termios: Option<UnixTermios> = terminal_unix_enter_raw_mode();
121        #[cfg(unix)]
122        let os_raw_active: bool = saved_termios.is_some();
123        #[cfg(target_os = "windows")]
124        let saved_win_modes: Option<(u32, u32)> = terminal_win32_enter_vt_mode();
125        #[cfg(target_os = "windows")]
126        let os_raw_active: bool = saved_win_modes.is_some();
127        #[cfg(not(any(unix, target_os = "windows")))]
128        let os_raw_active: bool = false;
129        let guard: Self = Self {
130            os_raw_active,
131            alt_screen,
132            mouse_enabled,
133            paste_enabled,
134            cursor_hidden,
135            restored: false,
136            write_to_stdout: os_raw_active,
137            #[cfg(unix)]
138            saved_termios,
139            #[cfg(target_os = "windows")]
140            saved_win_modes,
141            sink: None,
142        };
143        if os_raw_active {
144            set_terminal_panic_restore_enabled(true);
145        }
146        guard.emit_enter_sequences();
147        guard
148    }
149
150    /// Creates a deterministic captured RAII guard writing enter/restore sequences into `sink` without mutating host TTY state.
151    ///
152    /// # Arguments
153    ///
154    /// - `bool` - Emit alternate screen enter/leave sequences.
155    /// - `bool` - Emit mouse enable/disable sequences.
156    /// - `bool` - Emit bracketed paste enable/disable sequences.
157    /// - `bool` - Emit cursor hide/show sequences.
158    /// - `Option<Rc<RefCell<String>>>` - Optional capture sink recording emitted ANSI sequences.
159    ///
160    /// # Returns
161    ///
162    /// - `Self` - Captured RAII terminal guard.
163    #[must_use]
164    pub fn enter_captured(
165        alt_screen: bool,
166        mouse_enabled: bool,
167        paste_enabled: bool,
168        cursor_hidden: bool,
169        sink: Option<Rc<RefCell<String>>>,
170    ) -> Self {
171        let guard: Self = Self {
172            os_raw_active: false,
173            alt_screen,
174            mouse_enabled,
175            paste_enabled,
176            cursor_hidden,
177            restored: false,
178            write_to_stdout: false,
179            #[cfg(unix)]
180            saved_termios: None,
181            #[cfg(target_os = "windows")]
182            saved_win_modes: None,
183            sink,
184        };
185        guard.emit_enter_sequences();
186        guard
187    }
188
189    /// Writes `seq` to the configured capture sink and/or OS `stdout`.
190    ///
191    /// # Arguments
192    ///
193    /// - `&Self` - Guard reference.
194    /// - `&str` - ANSI escape sequence slice.
195    fn write_seq(&self, seq: &str) {
196        let Self { sink, .. } = self;
197        if let Some(buf) = sink
198            && let Ok(mut guard) = buf.try_borrow_mut()
199        {
200            guard.push_str(seq);
201        }
202        if self.get_write_to_stdout() {
203            let _: Result<bool, PlatformError> =
204                terminal_write_os_stream(TerminalStreamKind::Stdout, seq.as_bytes());
205        }
206    }
207
208    /// Emits all enabled terminal initialization escape sequences.
209    ///
210    /// # Arguments
211    ///
212    /// - `&Self` - Guard reference.
213    fn emit_enter_sequences(&self) {
214        if self.get_alt_screen() {
215            self.write_seq(TERMINAL_SEQ_ENTER_ALT_SCREEN);
216        }
217        if self.get_cursor_hidden() {
218            self.write_seq(TERMINAL_SEQ_HIDE_CURSOR);
219        }
220        if self.get_mouse_enabled() {
221            self.write_seq(TERMINAL_SEQ_ENABLE_MOUSE);
222        }
223        if self.get_paste_enabled() {
224            self.write_seq(TERMINAL_SEQ_ENABLE_PASTE);
225        }
226    }
227
228    /// Idempotently restores terminal raw mode, SGR attributes, mouse/paste tracking, cursor visibility, and primary screen.
229    ///
230    /// # Arguments
231    ///
232    /// - `&Self` - Mutable guard reference.
233    pub fn restore(&mut self) {
234        if self.get_restored() {
235            return;
236        }
237        self.set_restored(true);
238        self.write_seq(TERMINAL_SEQ_RESET_SGR);
239        if self.get_paste_enabled() {
240            self.write_seq(TERMINAL_SEQ_DISABLE_PASTE);
241        }
242        if self.get_mouse_enabled() {
243            self.write_seq(TERMINAL_SEQ_DISABLE_MOUSE);
244        }
245        if self.get_cursor_hidden() {
246            self.write_seq(TERMINAL_SEQ_SHOW_CURSOR);
247        }
248        if self.get_alt_screen() {
249            self.write_seq(TERMINAL_SEQ_LEAVE_ALT_SCREEN);
250        }
251        #[cfg(unix)]
252        {
253            let Self { saved_termios, .. } = self;
254            if let Some(orig) = saved_termios.take() {
255                terminal_unix_restore_raw_mode(&orig);
256            }
257        }
258        #[cfg(target_os = "windows")]
259        {
260            let Self {
261                saved_win_modes, ..
262            } = self;
263            if let Some(orig) = saved_win_modes.take() {
264                terminal_win32_restore_vt_mode(orig);
265            }
266        }
267        self.set_os_raw_active(false);
268        set_terminal_panic_restore_enabled(false);
269    }
270}
271
272/// Guaranteed RAII terminal restoration on normal scope exit and panic unwind.
273impl Drop for TerminalRawGuard {
274    /// Restores terminal state unconditionally when `TerminalRawGuard` drops.
275    ///
276    /// # Arguments
277    ///
278    /// - `&Self` - Mutable guard being dropped.
279    fn drop(&mut self) {
280        self.restore();
281    }
282}
283
284/// Default `TerminalInputParser` using standard `8x16` cell metrics.
285impl Default for TerminalInputParser {
286    /// Creates an empty VT/xterm input parser.
287    ///
288    /// # Returns
289    ///
290    /// - `Self` - Default parser instance.
291    fn default() -> Self {
292        Self {
293            pending: Vec::new(),
294            in_paste: false,
295            paste_buffer: String::new(),
296            cell_width_px: TERMINAL_DEFAULT_CELL_WIDTH,
297            cell_height_px: TERMINAL_DEFAULT_CELL_HEIGHT,
298        }
299    }
300}
301
302/// VT/xterm keyboard, mouse, and bracketed-paste stream decoding for `TerminalInputParser`.
303impl TerminalInputParser {
304    /// Parses incoming raw terminal bytes `bytes` into ordered EUV `WindowEvent`s, buffering incomplete sequences across chunks.
305    ///
306    /// # Arguments
307    ///
308    /// - `&Self` - Mutable parser state.
309    /// - `WindowId` - Target window identifier.
310    /// - `&[u8]` - Newly received raw terminal input bytes.
311    ///
312    /// # Returns
313    ///
314    /// - `Vec<WindowEvent>` - Decoded keyboard, text, mouse, scroll, and terminate events.
315    pub fn feed(&mut self, wid: WindowId, bytes: &[u8]) -> Vec<WindowEvent> {
316        let mut events: Vec<WindowEvent> = Vec::new();
317        let mut buf: Vec<u8> = take(self.get_mut_pending());
318        buf.extend_from_slice(bytes);
319        let mut idx: usize = 0;
320        let len: usize = buf.len();
321        while idx < len {
322            if self.get_in_paste() {
323                let slice: &[u8] = &buf[idx..];
324                if let Some(end_off) = terminal_find_bytes(slice, PASTE_END_BYTES) {
325                    if let Ok(chunk) = from_utf8(&slice[..end_off]) {
326                        self.get_mut_paste_buffer().push_str(chunk);
327                    }
328                    let pasted: String = take(self.get_mut_paste_buffer());
329                    self.set_in_paste(false);
330                    if !pasted.is_empty() {
331                        events.push(WindowEvent::TextInput(wid, pasted));
332                    }
333                    idx += end_off + PASTE_END_BYTES.len();
334                    continue;
335                }
336                let keep_tail: usize = PASTE_END_BYTES.len().saturating_sub(1);
337                if slice.len() > keep_tail {
338                    let flush_len: usize = slice.len() - keep_tail;
339                    if let Ok(chunk) = from_utf8(&slice[..flush_len]) {
340                        self.get_mut_paste_buffer().push_str(chunk);
341                        idx += flush_len;
342                    }
343                }
344                self.set_pending(buf[idx..].to_vec());
345                return events;
346            }
347            let blue_val: u8 = buf[idx];
348            if blue_val == 0x1B {
349                if idx + 1 >= len {
350                    events.push(WindowEvent::KeyDown(
351                        wid,
352                        KeyEvent::new(KeyCode::Escape, Modifiers::default(), false),
353                    ));
354                    idx += 1;
355                    continue;
356                }
357                let next: u8 = buf[idx + 1];
358                if next == VT_BYTE_LBRACKET {
359                    if buf[idx..].starts_with(PASTE_START_BYTES) {
360                        self.set_in_paste(true);
361                        self.get_mut_paste_buffer().clear();
362                        idx += PASTE_START_BYTES.len();
363                        continue;
364                    }
365                    let mut end_idx: Option<usize> = None;
366                    let mut scan: usize = idx + 2;
367                    while scan < len {
368                        let ch: u8 = buf[scan];
369                        if (0x40..=0x7E).contains(&ch) {
370                            end_idx = Some(scan);
371                            break;
372                        }
373                        scan += 1;
374                    }
375                    let Some(fin) = end_idx else {
376                        self.set_pending(buf[idx..].to_vec());
377                        return events;
378                    };
379                    let body: &[u8] = &buf[(idx + 2)..fin];
380                    let final_byte: u8 = buf[fin];
381                    self.decode_csi(wid, body, final_byte, &mut events);
382                    idx = fin + 1;
383                    continue;
384                }
385                if next == VT_BYTE_SS3_O {
386                    if idx + 2 >= len {
387                        self.set_pending(buf[idx..].to_vec());
388                        return events;
389                    }
390                    let ss3_code: KeyCode = match buf[idx + 2] {
391                        VT_BYTE_UP => KeyCode::ArrowUp,
392                        VT_BYTE_DOWN => KeyCode::ArrowDown,
393                        VT_BYTE_RIGHT => KeyCode::ArrowRight,
394                        VT_BYTE_LEFT => KeyCode::ArrowLeft,
395                        VT_BYTE_HOME => KeyCode::Home,
396                        VT_BYTE_END => KeyCode::End,
397                        _ => KeyCode::Unknown,
398                    };
399                    if ss3_code != KeyCode::Unknown {
400                        events.push(WindowEvent::KeyDown(
401                            wid,
402                            KeyEvent::new(ss3_code, Modifiers::default(), false),
403                        ));
404                    }
405                    idx += 3;
406                    continue;
407                }
408                if (0x20..=0x7E).contains(&next) {
409                    let alt_mods: Modifiers = Modifiers::new(false, false, true, false);
410                    events.push(WindowEvent::KeyDown(
411                        wid,
412                        KeyEvent::new(KeyCode::Character(next as char), alt_mods, false),
413                    ));
414                    idx += 2;
415                    continue;
416                }
417                events.push(WindowEvent::KeyDown(
418                    wid,
419                    KeyEvent::new(KeyCode::Escape, Modifiers::default(), false),
420                ));
421                idx += 1;
422                continue;
423            }
424            if blue_val == 0x03 {
425                let ctrl: Modifiers = Modifiers::new(false, true, false, false);
426                events.push(WindowEvent::KeyDown(
427                    wid,
428                    KeyEvent::new(KeyCode::Character('c'), ctrl, false),
429                ));
430                events.push(WindowEvent::CloseRequested(wid));
431                events.push(WindowEvent::System(SystemEvent::Terminate));
432                idx += 1;
433                continue;
434            }
435            if blue_val == 0x0D || blue_val == 0x0A {
436                events.push(WindowEvent::KeyDown(
437                    wid,
438                    KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
439                ));
440                idx += 1;
441                continue;
442            }
443            if blue_val == 0x09 {
444                events.push(WindowEvent::KeyDown(
445                    wid,
446                    KeyEvent::new(KeyCode::Tab, Modifiers::default(), false),
447                ));
448                idx += 1;
449                continue;
450            }
451            if blue_val == 0x7F || blue_val == 0x08 {
452                events.push(WindowEvent::KeyDown(
453                    wid,
454                    KeyEvent::new(KeyCode::Backspace, Modifiers::default(), false),
455                ));
456                idx += 1;
457                continue;
458            }
459            if (0x01..=0x1A).contains(&blue_val) {
460                let ch: char = (blue_val + VT_BYTE_LOWER_A - 1) as char;
461                let ctrl: Modifiers = Modifiers::new(false, true, false, false);
462                events.push(WindowEvent::KeyDown(
463                    wid,
464                    KeyEvent::new(KeyCode::Character(ch), ctrl, false),
465                ));
466                idx += 1;
467                continue;
468            }
469            let seq_len: usize = if blue_val < 0x80 {
470                1
471            } else if (blue_val & 0xE0) == 0xC0 {
472                2
473            } else if (blue_val & 0xF0) == 0xE0 {
474                3
475            } else if (blue_val & 0xF8) == 0xF0 {
476                4
477            } else {
478                idx += 1;
479                continue;
480            };
481            if idx + seq_len > len {
482                self.set_pending(buf[idx..].to_vec());
483                return events;
484            }
485            if let Ok(text) = from_utf8(&buf[idx..(idx + seq_len)])
486                && let Some(ch) = text.chars().next()
487            {
488                let code: KeyCode = if ch == ' ' {
489                    KeyCode::Space
490                } else {
491                    KeyCode::Character(ch)
492                };
493                events.push(WindowEvent::KeyDown(
494                    wid,
495                    KeyEvent::new(code, Modifiers::default(), false),
496                ));
497                events.push(WindowEvent::TextInput(wid, text.to_string()));
498            }
499            idx += seq_len;
500        }
501        events
502    }
503
504    /// Decodes a complete CSI escape sequence (`ESC [` `body` `final_byte`) into `WindowEvent`s.
505    ///
506    /// # Arguments
507    ///
508    /// - `&Self` - Parser reference.
509    /// - `WindowId` - Target window identifier.
510    /// - `&[u8]` - CSI parameter bytes between `[` and the final byte.
511    /// - `u8` - Final CSI command byte (`0x40..=0x7E`).
512    /// - `&mut Vec<WindowEvent>` - Output event queue.
513    fn decode_csi(&self, wid: WindowId, body: &[u8], final_byte: u8, out: &mut Vec<WindowEvent>) {
514        if body.first() == Some(&VT_BYTE_SGR_PREFIX)
515            && (final_byte == VT_BYTE_SGR_PRESS || final_byte == VT_BYTE_SGR_RELEASE)
516        {
517            if let Ok(params) = from_utf8(&body[1..])
518                && let Some(mouse_ev) = terminal_parse_sgr_mouse(
519                    wid,
520                    params,
521                    final_byte == VT_BYTE_SGR_PRESS,
522                    self.get_cell_width_px(),
523                    self.get_cell_height_px(),
524                )
525            {
526                out.push(mouse_ev);
527            }
528            return;
529        }
530        let body_str: &str = from_utf8(body).unwrap_or("");
531        let mut nums: Vec<u32> = Vec::with_capacity(2);
532        for seg in body_str.split(';') {
533            if let Ok(val) = seg.parse::<u32>() {
534                nums.push(val);
535            }
536        }
537        let mods: Modifiers = if nums.len() >= 2 {
538            terminal_decode_csi_modifiers(nums[1])
539        } else {
540            Modifiers::default()
541        };
542        let (code, final_mods): (KeyCode, Modifiers) = match final_byte {
543            VT_BYTE_UP => (KeyCode::ArrowUp, mods),
544            VT_BYTE_DOWN => (KeyCode::ArrowDown, mods),
545            VT_BYTE_RIGHT => (KeyCode::ArrowRight, mods),
546            VT_BYTE_LEFT => (KeyCode::ArrowLeft, mods),
547            VT_BYTE_HOME => (KeyCode::Home, mods),
548            VT_BYTE_END => (KeyCode::End, mods),
549            VT_BYTE_BACKTAB => (
550                KeyCode::Tab,
551                Modifiers::new(true, mods.get_ctrl(), mods.get_alt(), mods.get_meta()),
552            ),
553            VT_BYTE_TILDE => match nums.first().copied().unwrap_or(0) {
554                1 | 7 => (KeyCode::Home, mods),
555                3 => (KeyCode::Delete, mods),
556                4 | 8 => (KeyCode::End, mods),
557                5 => (KeyCode::PageUp, mods),
558                6 => (KeyCode::PageDown, mods),
559                _ => (KeyCode::Unknown, mods),
560            },
561            _ => (KeyCode::Unknown, mods),
562        };
563        if code != KeyCode::Unknown {
564            out.push(WindowEvent::KeyDown(
565                wid,
566                KeyEvent::new(code, final_mods, false),
567            ));
568        }
569    }
570}
571
572/// Default `TerminalPlatform` auto-probing the host process TTY state.
573impl Default for TerminalPlatform {
574    /// Creates a `TerminalPlatform` in `TerminalHostMode::Auto`.
575    ///
576    /// # Returns
577    ///
578    /// - `Self` - Auto-configured terminal host backend.
579    fn default() -> Self {
580        Self::with_mode(TerminalHostMode::Auto)
581    }
582}
583
584/// Mode builders, PTY input injection, resize sync, and CLI stdout/stderr helpers for `TerminalPlatform`.
585impl TerminalPlatform {
586    /// Creates a `TerminalPlatform` configured for `mode` using a live host TTY probe.
587    ///
588    /// # Arguments
589    ///
590    /// - `TerminalHostMode` - Desired host operating mode (`Auto`, `InteractiveTui`, or `StaticCli`).
591    ///
592    /// # Returns
593    ///
594    /// - `Self` - Initialized terminal platform backend.
595    #[must_use]
596    pub fn with_mode(mode: TerminalHostMode) -> Self {
597        let probe: TerminalTtyProbe = terminal_probe_tty();
598        Self::from_probe(mode, probe)
599    }
600
601    /// Creates a `TerminalPlatform` explicitly in interactive PTY TUI mode with custom `(cols, rows)`.
602    ///
603    /// # Arguments
604    ///
605    /// - `u16` - Terminal width in character columns.
606    /// - `u16` - Terminal height in character rows.
607    ///
608    /// # Returns
609    ///
610    /// - `Self` - Interactive TUI platform backend.
611    #[must_use]
612    pub fn interactive(cols: u16, rows: u16) -> Self {
613        let probe: TerminalTtyProbe = TerminalTtyProbe::new(
614            true,
615            true,
616            true,
617            TerminalColorCapability::TrueColor,
618            false,
619            cols.max(1),
620            rows.max(1),
621        );
622        Self::from_probe(TerminalHostMode::InteractiveTui, probe)
623    }
624
625    /// Creates a `TerminalPlatform` explicitly in non-interactive static/pipe CLI mode.
626    ///
627    /// # Arguments
628    ///
629    /// - `bool` - Whether standard output is attached to a TTY (`false` when piped).
630    /// - `bool` - Whether `NO_COLOR` override is active.
631    ///
632    /// # Returns
633    ///
634    /// - `Self` - Static/pipe CLI platform backend.
635    #[must_use]
636    pub fn static_cli(stdout_is_tty: bool, no_color: bool) -> Self {
637        let color: TerminalColorCapability = if stdout_is_tty && !no_color {
638            TerminalColorCapability::Ansi256
639        } else {
640            TerminalColorCapability::None
641        };
642        let probe: TerminalTtyProbe = TerminalTtyProbe::new(
643            false,
644            stdout_is_tty,
645            false,
646            color,
647            no_color,
648            TERMINAL_DEFAULT_COLS,
649            TERMINAL_DEFAULT_ROWS,
650        );
651        Self::from_probe(TerminalHostMode::StaticCli, probe)
652    }
653
654    /// Constructs a `TerminalPlatform` deterministically from a precomputed `TerminalTtyProbe`.
655    ///
656    /// # Arguments
657    ///
658    /// - `TerminalHostMode` - Requested mode.
659    /// - `TerminalTtyProbe` - Precomputed TTY and color capability probe.
660    ///
661    /// # Returns
662    ///
663    /// - `Self` - Configured terminal backend.
664    #[must_use]
665    pub fn from_probe(mode: TerminalHostMode, probe: TerminalTtyProbe) -> Self {
666        let resolved: TerminalHostMode = probe.resolve_mode(mode);
667        let metrics: TerminalCellMetrics = TerminalCellMetrics::new(
668            probe.get_cols().max(1),
669            probe.get_rows().max(1),
670            TERMINAL_DEFAULT_CELL_WIDTH,
671            TERMINAL_DEFAULT_CELL_HEIGHT,
672        );
673        let mut renderer: TerminalRenderer = TerminalRenderer::new();
674        renderer.set_sync_output_mode(
675            resolved == TerminalHostMode::InteractiveTui && probe.allows_ansi(),
676        );
677        #[cfg(not(target_arch = "wasm32"))]
678        let refresh_rate_hz: f32 = env::var(ENV_REFRESH_RATE_HZ)
679            .ok()
680            .and_then(|value_str: String| value_str.trim().parse::<f32>().ok())
681            .filter(|hz_val: &f32| hz_val.is_finite() && *hz_val >= MIN_REFRESH_RATE_HZ)
682            .unwrap_or(HIGH_REFRESH_DEFAULT_HZ);
683        #[cfg(target_arch = "wasm32")]
684        let refresh_rate_hz: f32 = HIGH_REFRESH_DEFAULT_HZ;
685        Self {
686            requested_mode: mode,
687            resolved_mode: resolved,
688            probe,
689            metrics,
690            next_id: 1,
691            primary_window: None,
692            windows: HashMap::new(),
693            pending_events: Vec::new(),
694            parser: TerminalInputParser::default(),
695            raw_guard: None,
696            stdout_log: Vec::new(),
697            stderr_log: Vec::new(),
698            emit_os_streams: false,
699            exit_code: 0,
700            broken_pipe: false,
701            clipboard: None,
702            storage: HashMap::new(),
703            route_stack: vec![TERMINAL_DEFAULT_ROUTE.to_string()],
704            theme: ThemeMode::Dark,
705            pump_paused: false,
706            #[cfg(not(target_arch = "wasm32"))]
707            last_input_at: None,
708            cli_batch_limit_bytes: TERMINAL_CLI_DEFAULT_BATCH_LIMIT,
709            renderer,
710            capture_last_frame: false,
711            wait_calls: 0,
712            stdout_flush_calls: 0,
713            last_telemetry: TerminalNonGpuTelemetry {
714                mode: if resolved == TerminalHostMode::InteractiveTui {
715                    TerminalRenderMode::InteractiveTui
716                } else {
717                    TerminalRenderMode::StaticPlainText
718                },
719                gpu_routing_opted_out: true,
720                uses_screen_hz: false,
721                input_to_output_ms: None,
722                flush_latency_ms: 0.0,
723                bytes_written: 0,
724                total_bytes_written: 0,
725                changed_cells: 0,
726                unchanged_frame_skipped: false,
727                backpressure_events: 0,
728                batched_flush_count: 0,
729            },
730            refresh_rate_hz,
731        }
732    }
733
734    /// Updates the terminal host display refresh rate without imposing any artificial upper ceiling.
735    ///
736    /// # Arguments
737    ///
738    /// - `&Self` - Mutable terminal platform.
739    /// - `f32` - Reported host hardware display refresh rate in Hertz.
740    pub fn update_refresh_rate_hz(&mut self, hz: f32) {
741        if !hz.is_finite() || hz < MIN_REFRESH_RATE_HZ {
742            return;
743        }
744        self.set_refresh_rate_hz(hz);
745        let rounded_hz: u32 = hz.round() as u32;
746        for rec in self.get_mut_windows().values_mut() {
747            rec.get_mut_state()
748                .get_mut_display()
749                .set_refresh_rate_hz(rounded_hz);
750        }
751    }
752
753    /// Enters live interactive PTY raw mode and attaches the RAII restoration guard to this backend.
754    ///
755    /// # Arguments
756    ///
757    /// - `&Self` - Mutable terminal platform backend.
758    pub fn enter_live_tui_session(&mut self) {
759        if self.get_resolved_mode() != TerminalHostMode::InteractiveTui {
760            return;
761        }
762        let guard: TerminalRawGuard = TerminalRawGuard::enter_live(true, true, true, true);
763        self.set_raw_guard(Some(guard));
764    }
765
766    /// Attaches a deterministic captured RAII guard for testing raw-mode entry and restore without touching real TTY handles.
767    ///
768    /// # Arguments
769    ///
770    /// - `&Self` - Mutable terminal platform backend.
771    /// - `Rc<RefCell<String>>` - Sink capturing enter/exit ANSI sequences.
772    pub fn enter_captured_tui_session(&mut self, sink: Rc<RefCell<String>>) {
773        let guard: TerminalRawGuard =
774            TerminalRawGuard::enter_captured(true, true, true, true, Some(sink));
775        self.set_raw_guard(Some(guard));
776    }
777
778    /// Explicitly restores and releases the active RAII terminal raw-mode guard, if entered.
779    ///
780    /// # Arguments
781    ///
782    /// - `&Self` - Mutable terminal platform backend.
783    pub fn leave_tui_session(&mut self) {
784        let Self { raw_guard, .. } = self;
785        if let Some(mut guard) = raw_guard.take() {
786            guard.restore();
787        }
788    }
789
790    /// Returns the primary terminal `WindowId` if one has been created.
791    ///
792    /// # Arguments
793    ///
794    /// - `&Self` - Terminal platform reference.
795    ///
796    /// # Returns
797    ///
798    /// - `Option<WindowId>` - Primary window handle.
799    #[must_use]
800    pub fn primary_window_id(&self) -> Option<WindowId> {
801        let Self { primary_window, .. } = self;
802        *primary_window
803    }
804
805    /// Feeds raw VT/xterm input bytes into the parser and enqueues all decoded `WindowEvent`s.
806    ///
807    /// # Arguments
808    ///
809    /// - `&Self` - Mutable terminal platform.
810    /// - `&[u8]` - Raw bytes read from PTY or injected by a test harness.
811    ///
812    /// # Returns
813    ///
814    /// - `usize` - Number of `WindowEvent`s enqueued.
815    pub fn push_raw_input(&mut self, bytes: &[u8]) -> usize {
816        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
817        let decoded: Vec<WindowEvent> = self.get_mut_parser().feed(wid, bytes);
818        let count: usize = decoded.len();
819        #[cfg(not(target_arch = "wasm32"))]
820        if count > 0 {
821            let Self { last_input_at, .. } = self;
822            *last_input_at = Some(Instant::now());
823        }
824        self.get_mut_pending_events().extend(decoded);
825        count
826    }
827
828    /// Updates terminal `(cols, rows)` and emits matching `WindowEvent::Resized` and `SystemEvent::Resize` events.
829    ///
830    /// # Arguments
831    ///
832    /// - `&Self` - Mutable terminal platform.
833    /// - `u16` - New terminal column count.
834    /// - `u16` - New terminal row count.
835    pub fn handle_terminal_resize(&mut self, cols: u16, rows: u16) {
836        let safe_cols: u16 = cols.max(1);
837        let safe_rows: u16 = rows.max(1);
838        let mut next_metrics: TerminalCellMetrics = self.get_metrics();
839        next_metrics.set_cols(safe_cols).set_rows(safe_rows);
840        self.set_metrics(next_metrics);
841        let log_w: u32 = next_metrics.logical_width();
842        let log_h: u32 = next_metrics.logical_height();
843        let mut resized_ids: Vec<WindowId> = Vec::with_capacity(self.get_windows().len());
844        for (&wid, rec) in self.get_mut_windows().iter_mut() {
845            rec.set_metrics(next_metrics);
846            rec.get_mut_config().set_width(log_w).set_height(log_h);
847            rec.get_mut_state()
848                .set_logical_width(log_w as f32)
849                .set_logical_height(log_h as f32)
850                .set_physical_width(log_w)
851                .set_physical_height(log_h);
852            resized_ids.push(wid);
853        }
854        for wid in resized_ids.into_iter() {
855            self.get_mut_pending_events()
856                .push(WindowEvent::Resized(wid, log_w, log_h, 1.0));
857        }
858        self.get_mut_pending_events()
859            .push(WindowEvent::System(SystemEvent::Resize {
860                width: log_w as f32,
861                height: log_h as f32,
862                scale_factor: 1.0,
863            }));
864    }
865
866    /// Writes clean result text to the `stdout` channel, stripping or suppressing ANSI automatically when piped.
867    ///
868    /// # Arguments
869    ///
870    /// - `&Self` - Mutable terminal platform.
871    /// - `&str` - UTF-8 output payload.
872    ///
873    /// # Returns
874    ///
875    /// - `Result<(), PlatformError>` - Write status (`Err` if pipe is broken).
876    pub fn write_stdout(&mut self, text: &str) -> Result<(), PlatformError> {
877        if self.get_broken_pipe() {
878            return Err(PlatformError::SurfaceError(
879                ERR_TERMINAL_BROKEN_PIPE.to_string(),
880            ));
881        }
882        self.get_mut_stdout_log().extend_from_slice(text.as_bytes());
883        if self.get_emit_os_streams() {
884            let ok: bool = terminal_write_os_stream(TerminalStreamKind::Stdout, text.as_bytes())?;
885            if !ok {
886                self.set_broken_pipe(true);
887                return Err(PlatformError::SurfaceError(
888                    ERR_TERMINAL_BROKEN_PIPE.to_string(),
889                ));
890            }
891        }
892        Ok(())
893    }
894
895    /// Writes diagnostic or error text strictly to the `stderr` channel so `stdout` pipelines remain unpolluted.
896    ///
897    /// # Arguments
898    ///
899    /// - `&Self` - Mutable terminal platform.
900    /// - `&str` - UTF-8 diagnostic payload.
901    ///
902    /// # Returns
903    ///
904    /// - `Result<(), PlatformError>` - Write status.
905    pub fn write_stderr(&mut self, text: &str) -> Result<(), PlatformError> {
906        self.get_mut_stderr_log().extend_from_slice(text.as_bytes());
907        if self.get_emit_os_streams() {
908            let _: bool = terminal_write_os_stream(TerminalStreamKind::Stderr, text.as_bytes())?;
909        }
910        Ok(())
911    }
912
913    /// Projects `tree` through the persistent double-buffered `TerminalRenderer` using DEC Mode 2026 differential cell-diffing and flushes changed bytes to `stdout` in a single buffered write (`0` bytes when unchanged).
914    ///
915    /// # Arguments
916    ///
917    /// - `&Self` - Mutable terminal platform.
918    /// - `WindowId` - Target terminal window handle.
919    /// - `&SceneTree` - Retained UI scene tree to present.
920    ///
921    /// # Returns
922    ///
923    /// - `Result<TerminalDiffStats, PlatformError>` - Cell-diff telemetry (`is_idle == true` and `output_bytes == 0` when unchanged).
924    pub fn present_scene_tree(
925        &mut self,
926        id: WindowId,
927        tree: &SceneTree,
928    ) -> Result<TerminalDiffStats, PlatformError> {
929        let mode: TerminalRenderMode = self.render_mode();
930        if self.get_broken_pipe() {
931            return Err(PlatformError::SurfaceError(
932                ERR_TERMINAL_BROKEN_PIPE.to_string(),
933            ));
934        }
935        let (cols, rows): (u16, u16) = self
936            .get_windows()
937            .get(&id)
938            .map(|rec: &TerminalWindowRecord| {
939                let metrics: TerminalCellMetrics = rec.get_metrics();
940                (metrics.get_cols(), metrics.get_rows())
941            })
942            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
943        #[cfg(not(target_arch = "wasm32"))]
944        let flush_start: Instant = Instant::now();
945        #[cfg(not(target_arch = "wasm32"))]
946        let Self {
947            windows,
948            stdout_log,
949            emit_os_streams,
950            broken_pipe,
951            last_input_at,
952            renderer,
953            stdout_flush_calls,
954            last_telemetry,
955            ..
956        } = self;
957        #[cfg(target_arch = "wasm32")]
958        let Self {
959            windows,
960            stdout_log,
961            emit_os_streams,
962            broken_pipe,
963            renderer,
964            stdout_flush_calls,
965            last_telemetry,
966            ..
967        } = self;
968        let (payload, stats): (&str, TerminalDiffStats) =
969            renderer.render_tree_borrowed(tree, cols, rows, mode);
970        if stats.get_is_idle() || payload.is_empty() {
971            let prev: TerminalNonGpuTelemetry = *last_telemetry;
972            *last_telemetry = TerminalNonGpuTelemetry {
973                mode,
974                gpu_routing_opted_out: true,
975                uses_screen_hz: false,
976                input_to_output_ms: None,
977                flush_latency_ms: 0.0,
978                bytes_written: 0,
979                total_bytes_written: prev.get_total_bytes_written(),
980                changed_cells: 0,
981                unchanged_frame_skipped: true,
982                backpressure_events: prev.get_backpressure_events(),
983                batched_flush_count: prev.get_batched_flush_count(),
984            };
985            return Ok(stats);
986        }
987        let payload_bytes: &[u8] = payload.as_bytes();
988        let written_len: u64 = payload_bytes.len() as u64;
989        let os_write_result: Result<bool, PlatformError> = if *emit_os_streams {
990            terminal_write_os_stream(TerminalStreamKind::Stdout, payload_bytes)
991        } else {
992            Ok(true)
993        };
994        let payload_owned: Option<String> = if matches!(os_write_result, Ok(true)) {
995            stdout_log.extend_from_slice(payload_bytes);
996            Some(payload.to_string())
997        } else {
998            None
999        };
1000        match os_write_result {
1001            Ok(true) => {}
1002            Ok(false) => {
1003                *broken_pipe = true;
1004                renderer.invalidate();
1005                let mut prev: TerminalNonGpuTelemetry = *last_telemetry;
1006                prev.set_mode(mode);
1007                prev.set_bytes_written(0);
1008                prev.set_backpressure_events(prev.get_backpressure_events().saturating_add(1));
1009                *last_telemetry = prev;
1010                return Err(PlatformError::SurfaceError(
1011                    ERR_TERMINAL_BROKEN_PIPE.to_string(),
1012                ));
1013            }
1014            Err(err) => {
1015                renderer.invalidate();
1016                let mut prev: TerminalNonGpuTelemetry = *last_telemetry;
1017                prev.set_mode(mode);
1018                prev.set_bytes_written(0);
1019                prev.set_backpressure_events(prev.get_backpressure_events().saturating_add(1));
1020                *last_telemetry = prev;
1021                return Err(err);
1022            }
1023        }
1024        if let Some(rec) = windows.get_mut(&id) {
1025            if let Some(out_text) = payload_owned {
1026                rec.set_last_output(out_text);
1027            }
1028            rec.set_present_count(rec.get_present_count().wrapping_add(1));
1029        }
1030        *stdout_flush_calls = stdout_flush_calls.saturating_add(1);
1031        #[cfg(not(target_arch = "wasm32"))]
1032        let flush_latency_ms: f64 = flush_start.elapsed().as_secs_f64() * 1000.0;
1033        #[cfg(target_arch = "wasm32")]
1034        let flush_latency_ms: f64 = 0.0;
1035        #[cfg(not(target_arch = "wasm32"))]
1036        let input_to_output_ms: Option<f64> = last_input_at
1037            .take()
1038            .map(|timestamp_val: Instant| timestamp_val.elapsed().as_secs_f64() * 1000.0);
1039        #[cfg(target_arch = "wasm32")]
1040        let input_to_output_ms: Option<f64> = None;
1041        let prev: TerminalNonGpuTelemetry = *last_telemetry;
1042        *last_telemetry = TerminalNonGpuTelemetry {
1043            mode,
1044            gpu_routing_opted_out: true,
1045            uses_screen_hz: false,
1046            input_to_output_ms,
1047            flush_latency_ms,
1048            bytes_written: written_len,
1049            total_bytes_written: prev.get_total_bytes_written().saturating_add(written_len),
1050            changed_cells: stats.get_changed_cells(),
1051            unchanged_frame_skipped: false,
1052            backpressure_events: prev.get_backpressure_events(),
1053            batched_flush_count: prev.get_batched_flush_count().saturating_add(1),
1054        };
1055        Ok(stats)
1056    }
1057
1058    /// Records a terminal frame string (`TerminalRenderer` output) against `id` and writes it to `stdout`.
1059    ///
1060    /// # Arguments
1061    ///
1062    /// - `&Self` - Mutable terminal platform.
1063    /// - `WindowId` - Target window handle.
1064    /// - `&str` - Rendered ANSI cell-diff or static plain-text output.
1065    ///
1066    /// # Returns
1067    ///
1068    /// - `Result<(), PlatformError>` - Presentation status.
1069    pub fn present_terminal_output(
1070        &mut self,
1071        id: WindowId,
1072        output: &str,
1073    ) -> Result<(), PlatformError> {
1074        let rec: &mut TerminalWindowRecord = self
1075            .get_mut_windows()
1076            .get_mut(&id)
1077            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1078        rec.set_last_output(output.to_string());
1079        rec.set_present_count(rec.get_present_count().wrapping_add(1));
1080        if !output.is_empty() {
1081            self.write_stdout(output)?;
1082        }
1083        Ok(())
1084    }
1085
1086    /// Returns captured standard output decoded as UTF-8.
1087    ///
1088    /// # Arguments
1089    ///
1090    /// - `&Self` - Terminal platform reference.
1091    ///
1092    /// # Returns
1093    ///
1094    /// - `String` - Captured `stdout` text.
1095    #[must_use]
1096    pub fn stdout_text(&self) -> String {
1097        String::from_utf8_lossy(self.get_stdout_log().as_slice()).into_owned()
1098    }
1099
1100    /// Returns captured standard error diagnostics decoded as UTF-8.
1101    ///
1102    /// # Arguments
1103    ///
1104    /// - `&Self` - Terminal platform reference.
1105    ///
1106    /// # Returns
1107    ///
1108    /// - `String` - Captured `stderr` text.
1109    #[must_use]
1110    pub fn stderr_text(&self) -> String {
1111        String::from_utf8_lossy(self.get_stderr_log().as_slice()).into_owned()
1112    }
1113
1114    /// Marks the session as exiting with `code` and enqueues `SystemEvent::Terminate`.
1115    ///
1116    /// # Arguments
1117    ///
1118    /// - `&Self` - Mutable terminal platform.
1119    /// - `i32` - Process exit code to propagate.
1120    pub fn request_exit_with_code(&mut self, code: i32) {
1121        self.set_exit_code(code);
1122        self.leave_tui_session();
1123        if let Some(wid) = self.primary_window_id() {
1124            self.get_mut_pending_events()
1125                .push(WindowEvent::CloseRequested(wid));
1126        }
1127        self.get_mut_pending_events()
1128            .push(WindowEvent::System(SystemEvent::Terminate));
1129    }
1130
1131    /// Resolves the active `TerminalRenderMode` matching this host's resolved mode and TTY probe.
1132    ///
1133    /// # Arguments
1134    ///
1135    /// - `&Self` - Terminal platform reference.
1136    ///
1137    /// # Returns
1138    ///
1139    /// - `TerminalRenderMode` - `InteractiveTui` for live PTY sessions, `StaticPlainText` for piped/static CLI.
1140    #[must_use]
1141    pub fn render_mode(&self) -> TerminalRenderMode {
1142        if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1143            TerminalRenderMode::InteractiveTui
1144        } else {
1145            TerminalRenderMode::StaticPlainText
1146        }
1147    }
1148}
1149
1150/// `WindowController` implementation for `TerminalPlatform`.
1151impl WindowController for TerminalPlatform {
1152    /// Applies a `WindowCommand` against the terminal window record.
1153    ///
1154    /// # Arguments
1155    ///
1156    /// - `&Self` - Mutable terminal platform.
1157    /// - `WindowCommand` - Command to apply.
1158    ///
1159    /// # Returns
1160    ///
1161    /// - `Result<(), PlatformError>` - Execution status.
1162    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
1163        match command {
1164            WindowCommand::SetTitle(id, title) => {
1165                let rec: &mut TerminalWindowRecord = self
1166                    .get_mut_windows()
1167                    .get_mut(&id)
1168                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1169                rec.get_mut_config().set_title(title);
1170                Ok(())
1171            }
1172            WindowCommand::SetSize(id, width, height) => {
1173                let rec: &mut TerminalWindowRecord = self
1174                    .get_mut_windows()
1175                    .get_mut(&id)
1176                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1177                let cw: f32 = rec.get_metrics().get_cell_width_px().max(1.0);
1178                let ch: f32 = rec.get_metrics().get_cell_height_px().max(1.0);
1179                let cols: u16 = ((width.max(1) as f32) / cw).round().clamp(1.0, 1000.0) as u16;
1180                let rows: u16 = ((height.max(1) as f32) / ch).round().clamp(1.0, 1000.0) as u16;
1181                self.handle_terminal_resize(cols, rows);
1182                Ok(())
1183            }
1184            WindowCommand::RequestRedraw(id) => {
1185                if !self.get_windows().contains_key(&id) {
1186                    return Err(PlatformError::WindowNotFound(id.get_value()));
1187                }
1188                self.get_mut_pending_events()
1189                    .push(WindowEvent::RedrawRequested(id));
1190                Ok(())
1191            }
1192            WindowCommand::Close(id) => {
1193                if self.get_mut_windows().remove(&id).is_none() {
1194                    return Err(PlatformError::WindowNotFound(id.get_value()));
1195                }
1196                self.leave_tui_session();
1197                Ok(())
1198            }
1199            WindowCommand::SetPosition(id, _, _)
1200            | WindowCommand::SetResizable(id, _)
1201            | WindowCommand::SetDecorations(id, _)
1202            | WindowCommand::SetAlwaysOnTop(id, _)
1203            | WindowCommand::SetFullscreen(id, _)
1204            | WindowCommand::SetVisible(id, _)
1205            | WindowCommand::SetCursor(id, _)
1206            | WindowCommand::SetIme(id, _, _)
1207            | WindowCommand::SetStatusBarStyle(id, _)
1208            | WindowCommand::SetRenderMode(id, _) => {
1209                if !self.get_windows().contains_key(&id) {
1210                    return Err(PlatformError::WindowNotFound(id.get_value()));
1211                }
1212                Ok(())
1213            }
1214        }
1215    }
1216}
1217
1218/// `PlatformBackend` implementation for `TerminalPlatform`.
1219impl PlatformBackend for TerminalPlatform {
1220    /// Returns `PlatformKind::Terminal` in interactive TUI mode or `PlatformKind::TerminalCli` in static/pipe CLI mode.
1221    ///
1222    /// # Arguments
1223    ///
1224    /// - `&Self` - Terminal platform reference.
1225    ///
1226    /// # Returns
1227    ///
1228    /// - `PlatformKind` - Concrete terminal platform kind.
1229    fn kind(&self) -> PlatformKind {
1230        if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1231            PlatformKind::Terminal
1232        } else {
1233            PlatformKind::TerminalCli
1234        }
1235    }
1236
1237    /// Returns normalized capabilities for this terminal mode.
1238    ///
1239    /// # Arguments
1240    ///
1241    /// - `&Self` - Terminal platform reference.
1242    ///
1243    /// # Returns
1244    ///
1245    /// - `PlatformCapabilities` - Terminal capabilities.
1246    fn capabilities(&self) -> PlatformCapabilities {
1247        PlatformCapabilities::for_platform(self.kind())
1248    }
1249
1250    /// Allocates a terminal viewport window mapped to the current `(cols, rows)` cell metrics.
1251    ///
1252    /// # Arguments
1253    ///
1254    /// - `&Self` - Mutable terminal platform.
1255    /// - `&WindowConfig` - Declarative window configuration.
1256    ///
1257    /// # Returns
1258    ///
1259    /// - `Result<WindowState, PlatformError>` - Created terminal window state.
1260    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
1261        let id: WindowId = WindowId::new(self.get_next_id());
1262        self.set_next_id(self.get_next_id().wrapping_add(1));
1263        let metrics: TerminalCellMetrics = self.get_metrics();
1264        let mut adjusted: WindowConfig = config.clone();
1265        adjusted.set_size(metrics.logical_width(), metrics.logical_height());
1266        let mut state: WindowState = WindowState::from_config(id, &adjusted, 1.0);
1267        state.set_system_theme(self.get_theme());
1268        state
1269            .get_mut_display()
1270            .set_refresh_rate_hz(self.get_refresh_rate_hz().round() as u32);
1271        let record: TerminalWindowRecord = TerminalWindowRecord {
1272            config: adjusted,
1273            state,
1274            metrics,
1275            present_count: 0,
1276            last_output: String::new(),
1277            last_frame: Framebuffer::allocate(1, 1),
1278        };
1279        self.get_mut_windows().insert(id, record);
1280        if self.primary_window_id().is_none() {
1281            self.set_primary_window(Some(id));
1282        }
1283        Ok(state)
1284    }
1285
1286    /// Queries live `WindowState` for `id`.
1287    ///
1288    /// # Arguments
1289    ///
1290    /// - `&Self` - Terminal platform reference.
1291    /// - `WindowId` - Window identifier.
1292    ///
1293    /// # Returns
1294    ///
1295    /// - `Option<WindowState>` - Window state if alive.
1296    fn window_state(&self, id: WindowId) -> Option<WindowState> {
1297        self.get_windows()
1298            .get(&id)
1299            .map(TerminalWindowRecord::get_state)
1300    }
1301
1302    /// Returns `RawWindowHandle::TerminalPty` describing the attached PTY/console fd.
1303    ///
1304    /// # Arguments
1305    ///
1306    /// - `&Self` - Terminal platform reference.
1307    /// - `WindowId` - Window identifier.
1308    ///
1309    /// # Returns
1310    ///
1311    /// - `RawWindowHandle` - Terminal PTY raw handle.
1312    fn raw_window_handle(&self, _id: WindowId) -> RawWindowHandle {
1313        RawWindowHandle::TerminalPty {
1314            fd: UNIX_STDOUT_FD,
1315            is_tty: self.get_probe().get_stdout_is_tty(),
1316        }
1317    }
1318
1319    /// Polls pending `SIGWINCH` resizes, non-blocking live PTY bytes (when active), and drains queued `WindowEvent`s.
1320    ///
1321    /// # Arguments
1322    ///
1323    /// - `&Self` - Mutable terminal platform.
1324    ///
1325    /// # Returns
1326    ///
1327    /// - `Vec<WindowEvent>` - Ordered pending events.
1328    fn poll_events(&mut self) -> Vec<WindowEvent> {
1329        if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1330            if terminal_take_sigwinch_resized() {
1331                let (cols, rows): (u16, u16) = terminal_query_pty_size();
1332                self.handle_terminal_resize(cols, rows);
1333            }
1334            let live_raw: bool = {
1335                let Self { raw_guard, .. } = self;
1336                raw_guard
1337                    .as_ref()
1338                    .is_some_and(TerminalRawGuard::get_os_raw_active)
1339            };
1340            if live_raw {
1341                let bytes: Vec<u8> = terminal_read_pty_bytes(0);
1342                if !bytes.is_empty() {
1343                    let _: usize = self.push_raw_input(&bytes);
1344                }
1345            }
1346        }
1347        take(self.get_mut_pending_events())
1348    }
1349
1350    /// Blocks in kernel `poll(stdin_fd, sigwinch_pipe)` at `0%` idle CPU until PTY input or `SIGWINCH` arrives, then drains events.
1351    ///
1352    /// # Arguments
1353    ///
1354    /// - `&Self` - Mutable terminal platform.
1355    ///
1356    /// # Returns
1357    ///
1358    /// - `Vec<WindowEvent>` - Ordered pending events upon wake.
1359    fn wait_for_events(&mut self) -> Vec<WindowEvent> {
1360        let next_calls: u64 = self.get_wait_calls().saturating_add(1);
1361        self.set_wait_calls(next_calls);
1362        if self.get_pending_events().is_empty()
1363            && self.get_resolved_mode() == TerminalHostMode::InteractiveTui
1364        {
1365            let live_raw: bool = {
1366                let Self { raw_guard, .. } = self;
1367                raw_guard
1368                    .as_ref()
1369                    .is_some_and(TerminalRawGuard::get_os_raw_active)
1370            };
1371            if live_raw && terminal_fd_is_tty(UNIX_STDIN_FD) {
1372                let _: bool = terminal_wait_pty_event(TERMINAL_POLL_INFINITE);
1373            }
1374        }
1375        self.poll_events()
1376    }
1377
1378    /// Updates frame pump pause state for suspend/background freeze.
1379    ///
1380    /// # Arguments
1381    ///
1382    /// - `&Self` - Mutable terminal platform.
1383    /// - `bool` - `true` to pause frame pumping.
1384    fn set_frame_pump_paused(&mut self, paused: bool) {
1385        self.set_pump_paused(paused);
1386    }
1387
1388    /// Returns whether the terminal frame pump is paused.
1389    ///
1390    /// # Arguments
1391    ///
1392    /// - `&Self` - Terminal platform reference.
1393    ///
1394    /// # Returns
1395    ///
1396    /// - `bool` - Pause status.
1397    fn is_frame_pump_paused(&self) -> bool {
1398        self.get_pump_paused()
1399    }
1400
1401    /// Records a graphical framebuffer presentation without cloning RGBA pixel buffers unless `capture_last_frame` is explicitly enabled.
1402    ///
1403    /// # Arguments
1404    ///
1405    /// - `&Self` - Mutable terminal platform.
1406    /// - `WindowId` - Target window handle.
1407    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1408    ///
1409    /// # Returns
1410    ///
1411    /// - `Result<(), PlatformError>` - Presentation status.
1412    fn present_framebuffer(
1413        &mut self,
1414        id: WindowId,
1415        framebuffer: &Framebuffer,
1416    ) -> Result<(), PlatformError> {
1417        let capture: bool = self.get_capture_last_frame();
1418        let rec: &mut TerminalWindowRecord = self
1419            .get_mut_windows()
1420            .get_mut(&id)
1421            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1422        if capture {
1423            rec.set_last_frame(framebuffer.clone());
1424        }
1425        rec.set_present_count(rec.get_present_count().wrapping_add(1));
1426        Ok(())
1427    }
1428
1429    /// Reads the terminal clipboard cache.
1430    ///
1431    /// # Arguments
1432    ///
1433    /// - `&Self` - Terminal platform reference.
1434    ///
1435    /// # Returns
1436    ///
1437    /// - `Option<String>` - Cached clipboard string.
1438    fn read_clipboard(&self) -> Option<String> {
1439        let Self { clipboard, .. } = self;
1440        clipboard.clone()
1441    }
1442
1443    /// Stores `text` into the terminal clipboard buffer.
1444    ///
1445    /// # Arguments
1446    ///
1447    /// - `&Self` - Mutable terminal platform.
1448    /// - `&str` - Clipboard text.
1449    ///
1450    /// # Returns
1451    ///
1452    /// - `Result<(), PlatformError>` - Always succeeds.
1453    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
1454        self.set_clipboard(Some(text.to_string()));
1455        Ok(())
1456    }
1457
1458    /// Returns the terminal theme hint.
1459    ///
1460    /// # Arguments
1461    ///
1462    /// - `&Self` - Terminal platform reference.
1463    ///
1464    /// # Returns
1465    ///
1466    /// - `ThemeMode` - Active terminal theme mode.
1467    fn system_theme(&self) -> ThemeMode {
1468        self.get_theme()
1469    }
1470
1471    /// Returns the uncapped terminal host display refresh rate in Hertz while keeping `poll(-1)` zero-wakeup idle semantics.
1472    ///
1473    /// # Arguments
1474    ///
1475    /// - `&Self` - Terminal platform reference.
1476    ///
1477    /// # Returns
1478    ///
1479    /// - `f32` - Active host display refresh rate in Hertz.
1480    fn display_refresh_rate_hz(&self) -> f32 {
1481        self.get_refresh_rate_hz()
1482    }
1483}
1484
1485/// `PlatformStorage` implementation for `TerminalPlatform`.
1486impl PlatformStorage for TerminalPlatform {
1487    /// Reads a key from in-memory terminal session storage.
1488    ///
1489    /// # Arguments
1490    ///
1491    /// - `&Self` - Terminal platform reference.
1492    /// - `&str` - Storage key.
1493    ///
1494    /// # Returns
1495    ///
1496    /// - `Option<String>` - Stored value, if present.
1497    fn storage_get(&self, key: &str) -> Option<String> {
1498        self.get_storage().get(key).cloned()
1499    }
1500
1501    /// Writes a key-value pair into terminal session storage.
1502    ///
1503    /// # Arguments
1504    ///
1505    /// - `&Self` - Mutable terminal platform.
1506    /// - `&str` - Storage key.
1507    /// - `&str` - Value to store.
1508    ///
1509    /// # Returns
1510    ///
1511    /// - `Result<(), PlatformError>` - Storage status.
1512    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
1513        let _: Option<String> = self
1514            .get_mut_storage()
1515            .insert(key.to_string(), value.to_string());
1516        Ok(())
1517    }
1518
1519    /// Removes `key` from terminal session storage.
1520    ///
1521    /// # Arguments
1522    ///
1523    /// - `&Self` - Mutable terminal platform.
1524    /// - `&str` - Storage key.
1525    ///
1526    /// # Returns
1527    ///
1528    /// - `Result<(), PlatformError>` - Storage status.
1529    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
1530        let _: Option<String> = self.get_mut_storage().remove(key);
1531        Ok(())
1532    }
1533
1534    /// Clears all keys from terminal session storage.
1535    ///
1536    /// # Arguments
1537    ///
1538    /// - `&Self` - Mutable terminal platform.
1539    ///
1540    /// # Returns
1541    ///
1542    /// - `Result<(), PlatformError>` - Storage status.
1543    fn storage_clear(&mut self) -> Result<(), PlatformError> {
1544        self.get_mut_storage().clear();
1545        Ok(())
1546    }
1547}
1548
1549/// `PlatformNavigation` implementation for `TerminalPlatform`.
1550impl PlatformNavigation for TerminalPlatform {
1551    /// Pushes `route` onto the terminal session navigation stack.
1552    ///
1553    /// # Arguments
1554    ///
1555    /// - `&Self` - Mutable terminal platform.
1556    /// - `&str` - Logical route path.
1557    ///
1558    /// # Returns
1559    ///
1560    /// - `Result<(), PlatformError>` - Navigation status.
1561    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
1562        if !route.is_empty() {
1563            self.get_mut_route_stack().push(route.to_string());
1564        }
1565        Ok(())
1566    }
1567
1568    /// Pops `delta` entries from the terminal navigation stack, keeping the root route.
1569    ///
1570    /// # Arguments
1571    ///
1572    /// - `&Self` - Mutable terminal platform.
1573    /// - `u32` - Number of routes to pop.
1574    ///
1575    /// # Returns
1576    ///
1577    /// - `Result<(), PlatformError>` - Navigation status.
1578    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1579        for _ in 0..delta.max(1) {
1580            if self.get_route_stack().len() > 1 {
1581                let _: Option<String> = self.get_mut_route_stack().pop();
1582            }
1583        }
1584        Ok(())
1585    }
1586
1587    /// Returns the currently active terminal route path.
1588    ///
1589    /// # Arguments
1590    ///
1591    /// - `&Self` - Terminal platform reference.
1592    ///
1593    /// # Returns
1594    ///
1595    /// - `&str` - Current route path.
1596    fn current_route(&self) -> &str {
1597        self.get_route_stack()
1598            .last()
1599            .map(String::as_str)
1600            .unwrap_or(TERMINAL_DEFAULT_ROUTE)
1601    }
1602}
1603
1604/// `PlatformLifecycleBridge` implementation for `TerminalPlatform`.
1605impl PlatformLifecycleBridge for TerminalPlatform {
1606    /// Pauses terminal frame pumping and emits `Disappear` + `Background`.
1607    ///
1608    /// # Arguments
1609    ///
1610    /// - `&Self` - Mutable terminal platform.
1611    ///
1612    /// # Returns
1613    ///
1614    /// - `Vec<WindowEvent>` - Normalized freeze lifecycle events.
1615    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1616        self.set_pump_paused(true);
1617        vec![
1618            WindowEvent::System(SystemEvent::Disappear),
1619            WindowEvent::System(SystemEvent::Background),
1620        ]
1621    }
1622
1623    /// Resumes terminal frame pumping and emits `Appear` + `Foreground`.
1624    ///
1625    /// # Arguments
1626    ///
1627    /// - `&Self` - Mutable terminal platform.
1628    ///
1629    /// # Returns
1630    ///
1631    /// - `Vec<WindowEvent>` - Normalized resume lifecycle events.
1632    fn resume_surface(&mut self) -> Vec<WindowEvent> {
1633        self.set_pump_paused(false);
1634        vec![
1635            WindowEvent::System(SystemEvent::Appear),
1636            WindowEvent::System(SystemEvent::Foreground),
1637        ]
1638    }
1639
1640    /// Restores raw terminal state cleanly and emits `Terminate`.
1641    ///
1642    /// # Arguments
1643    ///
1644    /// - `&Self` - Mutable terminal platform.
1645    ///
1646    /// # Returns
1647    ///
1648    /// - `Vec<WindowEvent>` - Normalized destroy lifecycle events.
1649    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1650        self.set_pump_paused(true);
1651        self.leave_tui_session();
1652        vec![WindowEvent::System(SystemEvent::Terminate)]
1653    }
1654}
1655
1656/// `PlatformHostAdapter` implementation for `TerminalPlatform`.
1657impl PlatformHostAdapter for TerminalPlatform {
1658    /// Returns `DeviceFormFactor::Terminal`.
1659    ///
1660    /// # Arguments
1661    ///
1662    /// - `&Self` - Terminal platform reference.
1663    ///
1664    /// # Returns
1665    ///
1666    /// - `DeviceFormFactor` - `DeviceFormFactor::Terminal`.
1667    fn device_form_factor(&self) -> DeviceFormFactor {
1668        DeviceFormFactor::Terminal
1669    }
1670
1671    /// Returns `"terminal-tui"` for interactive PTY sessions or `"terminal-cli"` for static/pipe CLI sessions.
1672    ///
1673    /// # Arguments
1674    ///
1675    /// - `&Self` - Terminal platform reference.
1676    ///
1677    /// # Returns
1678    ///
1679    /// - `&'static str` - Canonical host vendor identifier.
1680    fn host_vendor_name(&self) -> &'static str {
1681        if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1682            TERMINAL_VENDOR_TUI
1683        } else {
1684            TERMINAL_VENDOR_CLI
1685        }
1686    }
1687}
1688
1689/// Explicit non-GPU routing contract and batched CLI output with backpressure telemetry for `TerminalPlatform`.
1690impl TerminalPlatform {
1691    /// Explicitly signals that TUI and CLI hosts opt out of graphical GPU routing and screen-Hz pacing.
1692    ///
1693    /// # Returns
1694    ///
1695    /// - `bool` - Always `true`.
1696    #[must_use]
1697    pub fn opts_out_of_gpu_routing(&self) -> bool {
1698        true
1699    }
1700
1701    /// Returns the most recent non-GPU, non-Hz terminal telemetry report (`input_to_output_ms`, `flush_latency_ms`, `bytes_written`).
1702    ///
1703    /// # Returns
1704    ///
1705    /// - `TerminalNonGpuTelemetry` - Latest terminal telemetry snapshot.
1706    #[must_use]
1707    pub fn telemetry_report(&self) -> TerminalNonGpuTelemetry {
1708        self.get_last_telemetry()
1709    }
1710
1711    /// Writes `chunks` to `stdout` as bounded coalesced batches respecting `cli_batch_limit_bytes` and backpressure, updating non-Hz telemetry.
1712    ///
1713    /// # Arguments
1714    ///
1715    /// - `&[&str]` - Ordered UTF-8 CLI output chunks to coalesce and flush.
1716    ///
1717    /// # Returns
1718    ///
1719    /// - `Result<TerminalNonGpuTelemetry, PlatformError>` - Updated non-GPU telemetry on success, or `Err` on broken pipe.
1720    pub fn write_stdout_batched(
1721        &mut self,
1722        chunks: &[&str],
1723    ) -> Result<TerminalNonGpuTelemetry, PlatformError> {
1724        let mode: TerminalRenderMode = self.render_mode();
1725        if self.get_broken_pipe() {
1726            let mut prev: TerminalNonGpuTelemetry = self.get_last_telemetry();
1727            prev.set_mode(mode);
1728            prev.set_gpu_routing_opted_out(true);
1729            prev.set_uses_screen_hz(false);
1730            prev.set_bytes_written(0);
1731            prev.set_backpressure_events(prev.get_backpressure_events().saturating_add(1));
1732            self.set_last_telemetry(prev);
1733            return Err(PlatformError::SurfaceError(
1734                ERR_TERMINAL_BROKEN_PIPE.to_string(),
1735            ));
1736        }
1737        #[cfg(not(target_arch = "wasm32"))]
1738        let flush_start: Instant = Instant::now();
1739        let batch_limit: usize = self.get_cli_batch_limit_bytes().max(1);
1740        let mut coalesced: String = String::new();
1741        let mut written_this_call: u64 = 0;
1742        let mut flush_count: u64 = 0;
1743        let mut bp_events: u64 = 0;
1744        for chunk in chunks.iter() {
1745            if chunk.is_empty() {
1746                continue;
1747            }
1748            if !coalesced.is_empty() && coalesced.len().saturating_add(chunk.len()) > batch_limit {
1749                let batch_len: u64 = coalesced.len() as u64;
1750                self.write_stdout(&coalesced)?;
1751                written_this_call = written_this_call.saturating_add(batch_len);
1752                flush_count = flush_count.saturating_add(1);
1753                bp_events = bp_events.saturating_add(1);
1754                coalesced.clear();
1755            }
1756            if chunk.len() > batch_limit {
1757                let mut start_idx: usize = 0;
1758                while start_idx < chunk.len() {
1759                    let mut end_idx: usize = (start_idx + batch_limit).min(chunk.len());
1760                    while end_idx > start_idx && !chunk.is_char_boundary(end_idx) {
1761                        end_idx -= 1;
1762                    }
1763                    if end_idx == start_idx {
1764                        end_idx = chunk.len();
1765                    }
1766                    let slice: &str = &chunk[start_idx..end_idx];
1767                    self.write_stdout(slice)?;
1768                    written_this_call = written_this_call.saturating_add(slice.len() as u64);
1769                    flush_count = flush_count.saturating_add(1);
1770                    if end_idx < chunk.len() {
1771                        bp_events = bp_events.saturating_add(1);
1772                    }
1773                    start_idx = end_idx;
1774                }
1775            } else {
1776                coalesced.push_str(chunk);
1777            }
1778        }
1779        if !coalesced.is_empty() {
1780            let batch_len: u64 = coalesced.len() as u64;
1781            self.write_stdout(&coalesced)?;
1782            written_this_call = written_this_call.saturating_add(batch_len);
1783            flush_count = flush_count.saturating_add(1);
1784        }
1785        #[cfg(not(target_arch = "wasm32"))]
1786        let flush_latency_ms: f64 = flush_start.elapsed().as_secs_f64() * 1000.0;
1787        #[cfg(target_arch = "wasm32")]
1788        let flush_latency_ms: f64 = 0.0;
1789        #[cfg(not(target_arch = "wasm32"))]
1790        let input_to_output_ms: Option<f64> = {
1791            let Self { last_input_at, .. } = self;
1792            last_input_at
1793                .take()
1794                .map(|timestamp_val: Instant| timestamp_val.elapsed().as_secs_f64() * 1000.0)
1795        };
1796        #[cfg(target_arch = "wasm32")]
1797        let input_to_output_ms: Option<f64> = None;
1798        let prev: TerminalNonGpuTelemetry = self.get_last_telemetry();
1799        let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
1800            mode,
1801            gpu_routing_opted_out: true,
1802            uses_screen_hz: false,
1803            input_to_output_ms,
1804            flush_latency_ms,
1805            bytes_written: written_this_call,
1806            total_bytes_written: prev
1807                .get_total_bytes_written()
1808                .saturating_add(written_this_call),
1809            changed_cells: 0,
1810            unchanged_frame_skipped: written_this_call == 0,
1811            backpressure_events: prev.get_backpressure_events().saturating_add(bp_events),
1812            batched_flush_count: prev.get_batched_flush_count().saturating_add(flush_count),
1813        };
1814        self.set_last_telemetry(telemetry);
1815        Ok(telemetry)
1816    }
1817}