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