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