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        let mut renderer: TerminalRenderer = TerminalRenderer::new();
670        renderer.set_sync_output_mode(
671            resolved == TerminalHostMode::InteractiveTui && probe.allows_ansi(),
672        );
673        #[cfg(not(target_arch = "wasm32"))]
674        let refresh_rate_hz: f32 = env::var(ENV_REFRESH_RATE_HZ)
675            .ok()
676            .and_then(|value_str: String| value_str.trim().parse::<f32>().ok())
677            .filter(|hz_val: &f32| hz_val.is_finite() && *hz_val >= MIN_REFRESH_RATE_HZ)
678            .unwrap_or(HIGH_REFRESH_DEFAULT_HZ);
679        #[cfg(target_arch = "wasm32")]
680        let refresh_rate_hz: f32 = HIGH_REFRESH_DEFAULT_HZ;
681        Self {
682            requested_mode: mode,
683            resolved_mode: resolved,
684            probe,
685            metrics,
686            next_id: 1,
687            primary_window: None,
688            windows: HashMap::new(),
689            pending_events: Vec::new(),
690            parser: TerminalInputParser::default(),
691            raw_guard: None,
692            stdout_log: Vec::new(),
693            stderr_log: Vec::new(),
694            emit_os_streams: false,
695            exit_code: 0,
696            broken_pipe: false,
697            clipboard: None,
698            storage: HashMap::new(),
699            route_stack: vec![TERMINAL_DEFAULT_ROUTE.to_string()],
700            theme: ThemeMode::Dark,
701            pump_paused: false,
702            #[cfg(not(target_arch = "wasm32"))]
703            last_input_at: None,
704            cli_batch_limit_bytes: TERMINAL_CLI_DEFAULT_BATCH_LIMIT,
705            renderer,
706            capture_last_frame: false,
707            wait_calls: 0,
708            stdout_flush_calls: 0,
709            last_telemetry: TerminalNonGpuTelemetry {
710                mode: if resolved == TerminalHostMode::InteractiveTui {
711                    TerminalRenderMode::InteractiveTui
712                } else {
713                    TerminalRenderMode::StaticPlainText
714                },
715                gpu_routing_opted_out: true,
716                uses_screen_hz: false,
717                input_to_output_ms: None,
718                flush_latency_ms: 0.0,
719                bytes_written: 0,
720                total_bytes_written: 0,
721                changed_cells: 0,
722                unchanged_frame_skipped: false,
723                backpressure_events: 0,
724                batched_flush_count: 0,
725            },
726            refresh_rate_hz,
727        }
728    }
729
730    /// Updates the terminal host display refresh rate without imposing any artificial upper ceiling.
731    ///
732    /// # Arguments
733    ///
734    /// - `&Self` - Mutable terminal platform.
735    /// - `f32` - Reported host hardware display refresh rate in Hertz.
736    pub fn update_refresh_rate_hz(&mut self, hz: f32) {
737        if !hz.is_finite() || hz < MIN_REFRESH_RATE_HZ {
738            return;
739        }
740        self.set_refresh_rate_hz(hz);
741        let rounded_hz: u32 = hz.round() as u32;
742        for rec in self.get_mut_windows().values_mut() {
743            rec.get_mut_state()
744                .get_mut_display()
745                .set_refresh_rate_hz(rounded_hz);
746        }
747    }
748
749    /// Enters live interactive PTY raw mode and attaches the RAII restoration guard to this backend.
750    ///
751    /// # Arguments
752    ///
753    /// - `&Self` - Mutable terminal platform backend.
754    pub fn enter_live_tui_session(&mut self) {
755        if self.get_resolved_mode() != TerminalHostMode::InteractiveTui {
756            return;
757        }
758        let guard: TerminalRawGuard = TerminalRawGuard::enter_live(true, true, true, true);
759        self.set_raw_guard(Some(guard));
760    }
761
762    /// Attaches a deterministic captured RAII guard for testing raw-mode entry and restore without touching real TTY handles.
763    ///
764    /// # Arguments
765    ///
766    /// - `&Self` - Mutable terminal platform backend.
767    /// - `Rc<RefCell<String>>` - Sink capturing enter/exit ANSI sequences.
768    pub fn enter_captured_tui_session(&mut self, sink: Rc<RefCell<String>>) {
769        let guard: TerminalRawGuard =
770            TerminalRawGuard::enter_captured(true, true, true, true, Some(sink));
771        self.set_raw_guard(Some(guard));
772    }
773
774    /// Explicitly restores and releases the active RAII terminal raw-mode guard, if entered.
775    ///
776    /// # Arguments
777    ///
778    /// - `&Self` - Mutable terminal platform backend.
779    pub fn leave_tui_session(&mut self) {
780        let Self { raw_guard, .. } = self;
781        if let Some(mut guard) = raw_guard.take() {
782            guard.restore();
783        }
784    }
785
786    /// Returns the primary terminal `WindowId` if one has been created.
787    ///
788    /// # Arguments
789    ///
790    /// - `&Self` - Terminal platform reference.
791    ///
792    /// # Returns
793    ///
794    /// - `Option<WindowId>` - Primary window handle.
795    #[must_use]
796    pub fn primary_window_id(&self) -> Option<WindowId> {
797        let Self { primary_window, .. } = self;
798        *primary_window
799    }
800
801    /// Feeds raw VT/xterm input bytes into the parser and enqueues all decoded `WindowEvent`s.
802    ///
803    /// # Arguments
804    ///
805    /// - `&Self` - Mutable terminal platform.
806    /// - `&[u8]` - Raw bytes read from PTY or injected by a test harness.
807    ///
808    /// # Returns
809    ///
810    /// - `usize` - Number of `WindowEvent`s enqueued.
811    pub fn push_raw_input(&mut self, bytes: &[u8]) -> usize {
812        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
813        let decoded: Vec<WindowEvent> = self.get_mut_parser().feed(wid, bytes);
814        let count: usize = decoded.len();
815        #[cfg(not(target_arch = "wasm32"))]
816        if count > 0 {
817            let Self { last_input_at, .. } = self;
818            *last_input_at = Some(Instant::now());
819        }
820        self.get_mut_pending_events().extend(decoded);
821        count
822    }
823
824    /// Updates terminal `(cols, rows)` and emits matching `WindowEvent::Resized` and `SystemEvent::Resize` events.
825    ///
826    /// # Arguments
827    ///
828    /// - `&Self` - Mutable terminal platform.
829    /// - `u16` - New terminal column count.
830    /// - `u16` - New terminal row count.
831    pub fn handle_terminal_resize(&mut self, cols: u16, rows: u16) {
832        let safe_cols: u16 = cols.max(1);
833        let safe_rows: u16 = rows.max(1);
834        let mut next_metrics: TerminalCellMetrics = self.get_metrics();
835        next_metrics.set_cols(safe_cols).set_rows(safe_rows);
836        self.set_metrics(next_metrics);
837        let log_w: u32 = next_metrics.logical_width();
838        let log_h: u32 = next_metrics.logical_height();
839        let mut resized_ids: Vec<WindowId> = Vec::with_capacity(self.get_windows().len());
840        for (&wid, rec) in self.get_mut_windows().iter_mut() {
841            rec.set_metrics(next_metrics);
842            rec.get_mut_config().set_width(log_w).set_height(log_h);
843            rec.get_mut_state()
844                .set_logical_width(log_w as f32)
845                .set_logical_height(log_h as f32)
846                .set_physical_width(log_w)
847                .set_physical_height(log_h);
848            resized_ids.push(wid);
849        }
850        for wid in resized_ids.into_iter() {
851            self.get_mut_pending_events()
852                .push(WindowEvent::Resized(wid, log_w, log_h, 1.0));
853        }
854        self.get_mut_pending_events()
855            .push(WindowEvent::System(SystemEvent::Resize {
856                width: log_w as f32,
857                height: log_h as f32,
858                scale_factor: 1.0,
859            }));
860    }
861
862    /// Writes clean result text to the `stdout` channel, stripping or suppressing ANSI automatically when piped.
863    ///
864    /// # Arguments
865    ///
866    /// - `&Self` - Mutable terminal platform.
867    /// - `&str` - UTF-8 output payload.
868    ///
869    /// # Returns
870    ///
871    /// - `Result<(), PlatformError>` - Write status (`Err` if pipe is broken).
872    pub fn write_stdout(&mut self, text: &str) -> Result<(), PlatformError> {
873        if self.get_broken_pipe() {
874            return Err(PlatformError::SurfaceError(
875                ERR_TERMINAL_BROKEN_PIPE.to_string(),
876            ));
877        }
878        self.get_mut_stdout_log().extend_from_slice(text.as_bytes());
879        if self.get_emit_os_streams() {
880            let ok: bool = terminal_write_os_stream(TerminalStreamKind::Stdout, text.as_bytes())?;
881            if !ok {
882                self.set_broken_pipe(true);
883                return Err(PlatformError::SurfaceError(
884                    ERR_TERMINAL_BROKEN_PIPE.to_string(),
885                ));
886            }
887        }
888        Ok(())
889    }
890
891    /// Writes diagnostic or error text strictly to the `stderr` channel so `stdout` pipelines remain unpolluted.
892    ///
893    /// # Arguments
894    ///
895    /// - `&Self` - Mutable terminal platform.
896    /// - `&str` - UTF-8 diagnostic payload.
897    ///
898    /// # Returns
899    ///
900    /// - `Result<(), PlatformError>` - Write status.
901    pub fn write_stderr(&mut self, text: &str) -> Result<(), PlatformError> {
902        self.get_mut_stderr_log().extend_from_slice(text.as_bytes());
903        if self.get_emit_os_streams() {
904            let _: bool = terminal_write_os_stream(TerminalStreamKind::Stderr, text.as_bytes())?;
905        }
906        Ok(())
907    }
908
909    /// Projects `tree` through the persistent double-buffered `TerminalRenderer` using DEC Mode 2026 differential cell-diffing and flushes changed bytes to `stdout` in a single buffered write (`0` bytes when unchanged).
910    ///
911    /// # Arguments
912    ///
913    /// - `&Self` - Mutable terminal platform.
914    /// - `WindowId` - Target terminal window handle.
915    /// - `&SceneTree` - Retained UI scene tree to present.
916    ///
917    /// # Returns
918    ///
919    /// - `Result<TerminalDiffStats, PlatformError>` - Cell-diff telemetry (`is_idle == true` and `output_bytes == 0` when unchanged).
920    pub fn present_scene_tree(
921        &mut self,
922        id: WindowId,
923        tree: &SceneTree,
924    ) -> Result<TerminalDiffStats, PlatformError> {
925        let mode: TerminalRenderMode = self.render_mode();
926        if self.get_broken_pipe() {
927            return Err(PlatformError::SurfaceError(
928                ERR_TERMINAL_BROKEN_PIPE.to_string(),
929            ));
930        }
931        let (cols, rows): (u16, u16) = self
932            .get_windows()
933            .get(&id)
934            .map(|rec: &TerminalWindowRecord| {
935                let metrics: TerminalCellMetrics = rec.get_metrics();
936                (metrics.get_cols(), metrics.get_rows())
937            })
938            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
939        #[cfg(not(target_arch = "wasm32"))]
940        let flush_start: Instant = Instant::now();
941        #[cfg(not(target_arch = "wasm32"))]
942        let Self {
943            windows,
944            stdout_log,
945            emit_os_streams,
946            broken_pipe,
947            last_input_at,
948            renderer,
949            stdout_flush_calls,
950            last_telemetry,
951            ..
952        } = self;
953        #[cfg(target_arch = "wasm32")]
954        let Self {
955            windows,
956            stdout_log,
957            emit_os_streams,
958            broken_pipe,
959            renderer,
960            stdout_flush_calls,
961            last_telemetry,
962            ..
963        } = self;
964        let (payload, stats): (&str, TerminalDiffStats) =
965            renderer.render_tree_borrowed(tree, cols, rows, mode);
966        if stats.get_is_idle() || payload.is_empty() {
967            let prev: TerminalNonGpuTelemetry = *last_telemetry;
968            *last_telemetry = TerminalNonGpuTelemetry {
969                mode,
970                gpu_routing_opted_out: true,
971                uses_screen_hz: false,
972                input_to_output_ms: None,
973                flush_latency_ms: 0.0,
974                bytes_written: 0,
975                total_bytes_written: prev.get_total_bytes_written(),
976                changed_cells: 0,
977                unchanged_frame_skipped: true,
978                backpressure_events: prev.get_backpressure_events(),
979                batched_flush_count: prev.get_batched_flush_count(),
980            };
981            return Ok(stats);
982        }
983        let payload_bytes: &[u8] = payload.as_bytes();
984        let written_len: u64 = payload_bytes.len() as u64;
985        let os_write_result: Result<bool, PlatformError> = if *emit_os_streams {
986            terminal_write_os_stream(TerminalStreamKind::Stdout, payload_bytes)
987        } else {
988            Ok(true)
989        };
990        let payload_owned: Option<String> = if matches!(os_write_result, Ok(true)) {
991            stdout_log.extend_from_slice(payload_bytes);
992            Some(payload.to_string())
993        } else {
994            None
995        };
996        match os_write_result {
997            Ok(true) => {}
998            Ok(false) => {
999                *broken_pipe = true;
1000                renderer.invalidate();
1001                let mut prev: TerminalNonGpuTelemetry = *last_telemetry;
1002                prev.set_mode(mode);
1003                prev.set_bytes_written(0);
1004                prev.set_backpressure_events(prev.get_backpressure_events().saturating_add(1));
1005                *last_telemetry = prev;
1006                return Err(PlatformError::SurfaceError(
1007                    ERR_TERMINAL_BROKEN_PIPE.to_string(),
1008                ));
1009            }
1010            Err(err) => {
1011                renderer.invalidate();
1012                let mut prev: TerminalNonGpuTelemetry = *last_telemetry;
1013                prev.set_mode(mode);
1014                prev.set_bytes_written(0);
1015                prev.set_backpressure_events(prev.get_backpressure_events().saturating_add(1));
1016                *last_telemetry = prev;
1017                return Err(err);
1018            }
1019        }
1020        if let Some(rec) = windows.get_mut(&id) {
1021            if let Some(out_text) = payload_owned {
1022                rec.set_last_output(out_text);
1023            }
1024            rec.set_present_count(rec.get_present_count().wrapping_add(1));
1025        }
1026        *stdout_flush_calls = stdout_flush_calls.saturating_add(1);
1027        #[cfg(not(target_arch = "wasm32"))]
1028        let flush_latency_ms: f64 = flush_start.elapsed().as_secs_f64() * 1000.0;
1029        #[cfg(target_arch = "wasm32")]
1030        let flush_latency_ms: f64 = 0.0;
1031        #[cfg(not(target_arch = "wasm32"))]
1032        let input_to_output_ms: Option<f64> = last_input_at
1033            .take()
1034            .map(|timestamp_val: Instant| timestamp_val.elapsed().as_secs_f64() * 1000.0);
1035        #[cfg(target_arch = "wasm32")]
1036        let input_to_output_ms: Option<f64> = None;
1037        let prev: TerminalNonGpuTelemetry = *last_telemetry;
1038        *last_telemetry = TerminalNonGpuTelemetry {
1039            mode,
1040            gpu_routing_opted_out: true,
1041            uses_screen_hz: false,
1042            input_to_output_ms,
1043            flush_latency_ms,
1044            bytes_written: written_len,
1045            total_bytes_written: prev.get_total_bytes_written().saturating_add(written_len),
1046            changed_cells: stats.get_changed_cells(),
1047            unchanged_frame_skipped: false,
1048            backpressure_events: prev.get_backpressure_events(),
1049            batched_flush_count: prev.get_batched_flush_count().saturating_add(1),
1050        };
1051        Ok(stats)
1052    }
1053
1054    /// Records a terminal frame string (`TerminalRenderer` output) against `id` and writes it to `stdout`.
1055    ///
1056    /// # Arguments
1057    ///
1058    /// - `&Self` - Mutable terminal platform.
1059    /// - `WindowId` - Target window handle.
1060    /// - `&str` - Rendered ANSI cell-diff or static plain-text output.
1061    ///
1062    /// # Returns
1063    ///
1064    /// - `Result<(), PlatformError>` - Presentation status.
1065    pub fn present_terminal_output(
1066        &mut self,
1067        id: WindowId,
1068        output: &str,
1069    ) -> Result<(), PlatformError> {
1070        let rec: &mut TerminalWindowRecord = self
1071            .get_mut_windows()
1072            .get_mut(&id)
1073            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1074        rec.set_last_output(output.to_string());
1075        rec.set_present_count(rec.get_present_count().wrapping_add(1));
1076        if !output.is_empty() {
1077            self.write_stdout(output)?;
1078        }
1079        Ok(())
1080    }
1081
1082    /// Returns captured standard output decoded as UTF-8.
1083    ///
1084    /// # Arguments
1085    ///
1086    /// - `&Self` - Terminal platform reference.
1087    ///
1088    /// # Returns
1089    ///
1090    /// - `String` - Captured `stdout` text.
1091    #[must_use]
1092    pub fn stdout_text(&self) -> String {
1093        String::from_utf8_lossy(self.get_stdout_log().as_slice()).into_owned()
1094    }
1095
1096    /// Returns captured standard error diagnostics decoded as UTF-8.
1097    ///
1098    /// # Arguments
1099    ///
1100    /// - `&Self` - Terminal platform reference.
1101    ///
1102    /// # Returns
1103    ///
1104    /// - `String` - Captured `stderr` text.
1105    #[must_use]
1106    pub fn stderr_text(&self) -> String {
1107        String::from_utf8_lossy(self.get_stderr_log().as_slice()).into_owned()
1108    }
1109
1110    /// Marks the session as exiting with `code` and enqueues `SystemEvent::Terminate`.
1111    ///
1112    /// # Arguments
1113    ///
1114    /// - `&Self` - Mutable terminal platform.
1115    /// - `i32` - Process exit code to propagate.
1116    pub fn request_exit_with_code(&mut self, code: i32) {
1117        self.set_exit_code(code);
1118        self.leave_tui_session();
1119        if let Some(wid) = self.primary_window_id() {
1120            self.get_mut_pending_events()
1121                .push(WindowEvent::CloseRequested(wid));
1122        }
1123        self.get_mut_pending_events()
1124            .push(WindowEvent::System(SystemEvent::Terminate));
1125    }
1126
1127    /// Resolves the active `TerminalRenderMode` matching this host's resolved mode and TTY probe.
1128    ///
1129    /// # Arguments
1130    ///
1131    /// - `&Self` - Terminal platform reference.
1132    ///
1133    /// # Returns
1134    ///
1135    /// - `TerminalRenderMode` - `InteractiveTui` for live PTY sessions, `StaticPlainText` for piped/static CLI.
1136    #[must_use]
1137    pub fn render_mode(&self) -> TerminalRenderMode {
1138        if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1139            TerminalRenderMode::InteractiveTui
1140        } else {
1141            TerminalRenderMode::StaticPlainText
1142        }
1143    }
1144}
1145
1146/// `WindowController` implementation for `TerminalPlatform`.
1147impl WindowController for TerminalPlatform {
1148    /// Applies a `WindowCommand` against the terminal window record.
1149    ///
1150    /// # Arguments
1151    ///
1152    /// - `&Self` - Mutable terminal platform.
1153    /// - `WindowCommand` - Command to apply.
1154    ///
1155    /// # Returns
1156    ///
1157    /// - `Result<(), PlatformError>` - Execution status.
1158    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
1159        match command {
1160            WindowCommand::SetTitle(id, title) => {
1161                let rec: &mut TerminalWindowRecord = self
1162                    .get_mut_windows()
1163                    .get_mut(&id)
1164                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1165                rec.get_mut_config().set_title(title);
1166                Ok(())
1167            }
1168            WindowCommand::SetSize(id, width, height) => {
1169                let rec: &mut TerminalWindowRecord = self
1170                    .get_mut_windows()
1171                    .get_mut(&id)
1172                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1173                let cw: f32 = rec.get_metrics().get_cell_width_px().max(1.0);
1174                let ch: f32 = rec.get_metrics().get_cell_height_px().max(1.0);
1175                let cols: u16 = ((width.max(1) as f32) / cw).round().clamp(1.0, 1000.0) as u16;
1176                let rows: u16 = ((height.max(1) as f32) / ch).round().clamp(1.0, 1000.0) as u16;
1177                self.handle_terminal_resize(cols, rows);
1178                Ok(())
1179            }
1180            WindowCommand::RequestRedraw(id) => {
1181                if !self.get_windows().contains_key(&id) {
1182                    return Err(PlatformError::WindowNotFound(id.get_value()));
1183                }
1184                self.get_mut_pending_events()
1185                    .push(WindowEvent::RedrawRequested(id));
1186                Ok(())
1187            }
1188            WindowCommand::Close(id) => {
1189                if self.get_mut_windows().remove(&id).is_none() {
1190                    return Err(PlatformError::WindowNotFound(id.get_value()));
1191                }
1192                self.leave_tui_session();
1193                Ok(())
1194            }
1195            WindowCommand::SetPosition(id, _, _)
1196            | WindowCommand::SetResizable(id, _)
1197            | WindowCommand::SetDecorations(id, _)
1198            | WindowCommand::SetAlwaysOnTop(id, _)
1199            | WindowCommand::SetFullscreen(id, _)
1200            | WindowCommand::SetVisible(id, _)
1201            | WindowCommand::SetCursor(id, _)
1202            | WindowCommand::SetIme(id, _, _)
1203            | WindowCommand::SetStatusBarStyle(id, _)
1204            | WindowCommand::SetRenderMode(id, _) => {
1205                if !self.get_windows().contains_key(&id) {
1206                    return Err(PlatformError::WindowNotFound(id.get_value()));
1207                }
1208                Ok(())
1209            }
1210        }
1211    }
1212}
1213
1214/// `PlatformBackend` implementation for `TerminalPlatform`.
1215impl PlatformBackend for TerminalPlatform {
1216    /// Returns `PlatformKind::Terminal` in interactive TUI mode or `PlatformKind::TerminalCli` in static/pipe CLI mode.
1217    ///
1218    /// # Arguments
1219    ///
1220    /// - `&Self` - Terminal platform reference.
1221    ///
1222    /// # Returns
1223    ///
1224    /// - `PlatformKind` - Concrete terminal platform kind.
1225    fn kind(&self) -> PlatformKind {
1226        if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1227            PlatformKind::Terminal
1228        } else {
1229            PlatformKind::TerminalCli
1230        }
1231    }
1232
1233    /// Returns normalized capabilities for this terminal mode.
1234    ///
1235    /// # Arguments
1236    ///
1237    /// - `&Self` - Terminal platform reference.
1238    ///
1239    /// # Returns
1240    ///
1241    /// - `PlatformCapabilities` - Terminal capabilities.
1242    fn capabilities(&self) -> PlatformCapabilities {
1243        PlatformCapabilities::for_platform(self.kind())
1244    }
1245
1246    /// Allocates a terminal viewport window mapped to the current `(cols, rows)` cell metrics.
1247    ///
1248    /// # Arguments
1249    ///
1250    /// - `&Self` - Mutable terminal platform.
1251    /// - `&WindowConfig` - Declarative window configuration.
1252    ///
1253    /// # Returns
1254    ///
1255    /// - `Result<WindowState, PlatformError>` - Created terminal window state.
1256    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
1257        let id: WindowId = WindowId::new(self.get_next_id());
1258        self.set_next_id(self.get_next_id().wrapping_add(1));
1259        let metrics: TerminalCellMetrics = self.get_metrics();
1260        let mut adjusted: WindowConfig = config.clone();
1261        adjusted.set_size(metrics.logical_width(), metrics.logical_height());
1262        let mut state: WindowState = WindowState::from_config(id, &adjusted, 1.0);
1263        state.set_system_theme(self.get_theme());
1264        state
1265            .get_mut_display()
1266            .set_refresh_rate_hz(self.get_refresh_rate_hz().round() as u32);
1267        let record: TerminalWindowRecord = TerminalWindowRecord {
1268            config: adjusted,
1269            state,
1270            metrics,
1271            present_count: 0,
1272            last_output: String::new(),
1273            last_frame: Framebuffer::allocate(1, 1),
1274        };
1275        self.get_mut_windows().insert(id, record);
1276        if self.primary_window_id().is_none() {
1277            self.set_primary_window(Some(id));
1278        }
1279        Ok(state)
1280    }
1281
1282    /// Queries live `WindowState` for `id`.
1283    ///
1284    /// # Arguments
1285    ///
1286    /// - `&Self` - Terminal platform reference.
1287    /// - `WindowId` - Window identifier.
1288    ///
1289    /// # Returns
1290    ///
1291    /// - `Option<WindowState>` - Window state if alive.
1292    fn window_state(&self, id: WindowId) -> Option<WindowState> {
1293        self.get_windows()
1294            .get(&id)
1295            .map(TerminalWindowRecord::get_state)
1296    }
1297
1298    /// Returns `RawWindowHandle::TerminalPty` describing the attached PTY/console fd.
1299    ///
1300    /// # Arguments
1301    ///
1302    /// - `&Self` - Terminal platform reference.
1303    /// - `WindowId` - Window identifier.
1304    ///
1305    /// # Returns
1306    ///
1307    /// - `RawWindowHandle` - Terminal PTY raw handle.
1308    fn raw_window_handle(&self, _id: WindowId) -> RawWindowHandle {
1309        RawWindowHandle::TerminalPty {
1310            fd: UNIX_STDOUT_FD,
1311            is_tty: self.get_probe().get_stdout_is_tty(),
1312        }
1313    }
1314
1315    /// Polls pending `SIGWINCH` resizes, non-blocking live PTY bytes (when active), and drains queued `WindowEvent`s.
1316    ///
1317    /// # Arguments
1318    ///
1319    /// - `&Self` - Mutable terminal platform.
1320    ///
1321    /// # Returns
1322    ///
1323    /// - `Vec<WindowEvent>` - Ordered pending events.
1324    fn poll_events(&mut self) -> Vec<WindowEvent> {
1325        if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1326            if terminal_take_sigwinch_resized() {
1327                let (cols, rows): (u16, u16) = terminal_query_pty_size();
1328                self.handle_terminal_resize(cols, rows);
1329            }
1330            let live_raw: bool = {
1331                let Self { raw_guard, .. } = self;
1332                raw_guard
1333                    .as_ref()
1334                    .is_some_and(TerminalRawGuard::get_os_raw_active)
1335            };
1336            if live_raw {
1337                let bytes: Vec<u8> = terminal_read_pty_bytes(0);
1338                if !bytes.is_empty() {
1339                    let _: usize = self.push_raw_input(&bytes);
1340                }
1341            }
1342        }
1343        take(self.get_mut_pending_events())
1344    }
1345
1346    /// Blocks in kernel `poll(stdin_fd, sigwinch_pipe)` at `0%` idle CPU until PTY input or `SIGWINCH` arrives, then drains events.
1347    ///
1348    /// # Arguments
1349    ///
1350    /// - `&Self` - Mutable terminal platform.
1351    ///
1352    /// # Returns
1353    ///
1354    /// - `Vec<WindowEvent>` - Ordered pending events upon wake.
1355    fn wait_for_events(&mut self) -> Vec<WindowEvent> {
1356        let next_calls: u64 = self.get_wait_calls().saturating_add(1);
1357        self.set_wait_calls(next_calls);
1358        if self.get_pending_events().is_empty()
1359            && self.get_resolved_mode() == TerminalHostMode::InteractiveTui
1360        {
1361            let live_raw: bool = {
1362                let Self { raw_guard, .. } = self;
1363                raw_guard
1364                    .as_ref()
1365                    .is_some_and(TerminalRawGuard::get_os_raw_active)
1366            };
1367            if live_raw && terminal_fd_is_tty(UNIX_STDIN_FD) {
1368                let _: bool = terminal_wait_pty_event(TERMINAL_POLL_INFINITE);
1369            }
1370        }
1371        self.poll_events()
1372    }
1373
1374    /// Updates frame pump pause state for suspend/background freeze.
1375    ///
1376    /// # Arguments
1377    ///
1378    /// - `&Self` - Mutable terminal platform.
1379    /// - `bool` - `true` to pause frame pumping.
1380    fn set_frame_pump_paused(&mut self, paused: bool) {
1381        self.set_pump_paused(paused);
1382    }
1383
1384    /// Returns whether the terminal frame pump is paused.
1385    ///
1386    /// # Arguments
1387    ///
1388    /// - `&Self` - Terminal platform reference.
1389    ///
1390    /// # Returns
1391    ///
1392    /// - `bool` - Pause status.
1393    fn is_frame_pump_paused(&self) -> bool {
1394        self.get_pump_paused()
1395    }
1396
1397    /// Records a graphical framebuffer presentation without cloning RGBA pixel buffers unless `capture_last_frame` is explicitly enabled.
1398    ///
1399    /// # Arguments
1400    ///
1401    /// - `&Self` - Mutable terminal platform.
1402    /// - `WindowId` - Target window handle.
1403    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1404    ///
1405    /// # Returns
1406    ///
1407    /// - `Result<(), PlatformError>` - Presentation status.
1408    fn present_framebuffer(
1409        &mut self,
1410        id: WindowId,
1411        framebuffer: &Framebuffer,
1412    ) -> Result<(), PlatformError> {
1413        let capture: bool = self.get_capture_last_frame();
1414        let rec: &mut TerminalWindowRecord = self
1415            .get_mut_windows()
1416            .get_mut(&id)
1417            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1418        if capture {
1419            rec.set_last_frame(framebuffer.clone());
1420        }
1421        rec.set_present_count(rec.get_present_count().wrapping_add(1));
1422        Ok(())
1423    }
1424
1425    /// Reads the terminal clipboard cache.
1426    ///
1427    /// # Arguments
1428    ///
1429    /// - `&Self` - Terminal platform reference.
1430    ///
1431    /// # Returns
1432    ///
1433    /// - `Option<String>` - Cached clipboard string.
1434    fn read_clipboard(&self) -> Option<String> {
1435        let Self { clipboard, .. } = self;
1436        clipboard.clone()
1437    }
1438
1439    /// Stores `text` into the terminal clipboard buffer.
1440    ///
1441    /// # Arguments
1442    ///
1443    /// - `&Self` - Mutable terminal platform.
1444    /// - `&str` - Clipboard text.
1445    ///
1446    /// # Returns
1447    ///
1448    /// - `Result<(), PlatformError>` - Always succeeds.
1449    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
1450        self.set_clipboard(Some(text.to_string()));
1451        Ok(())
1452    }
1453
1454    /// Returns the terminal theme hint.
1455    ///
1456    /// # Arguments
1457    ///
1458    /// - `&Self` - Terminal platform reference.
1459    ///
1460    /// # Returns
1461    ///
1462    /// - `ThemeMode` - Active terminal theme mode.
1463    fn system_theme(&self) -> ThemeMode {
1464        self.get_theme()
1465    }
1466
1467    /// Returns the uncapped terminal host display refresh rate in Hertz while keeping `poll(-1)` zero-wakeup idle semantics.
1468    ///
1469    /// # Arguments
1470    ///
1471    /// - `&Self` - Terminal platform reference.
1472    ///
1473    /// # Returns
1474    ///
1475    /// - `f32` - Active host display refresh rate in Hertz.
1476    fn display_refresh_rate_hz(&self) -> f32 {
1477        self.get_refresh_rate_hz()
1478    }
1479}
1480
1481/// `PlatformStorage` implementation for `TerminalPlatform`.
1482impl PlatformStorage for TerminalPlatform {
1483    /// Reads a key from in-memory terminal session storage.
1484    ///
1485    /// # Arguments
1486    ///
1487    /// - `&Self` - Terminal platform reference.
1488    /// - `&str` - Storage key.
1489    ///
1490    /// # Returns
1491    ///
1492    /// - `Option<String>` - Stored value, if present.
1493    fn storage_get(&self, key: &str) -> Option<String> {
1494        self.get_storage().get(key).cloned()
1495    }
1496
1497    /// Writes a key-value pair into terminal session storage.
1498    ///
1499    /// # Arguments
1500    ///
1501    /// - `&Self` - Mutable terminal platform.
1502    /// - `&str` - Storage key.
1503    /// - `&str` - Value to store.
1504    ///
1505    /// # Returns
1506    ///
1507    /// - `Result<(), PlatformError>` - Storage status.
1508    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
1509        let _: Option<String> = self
1510            .get_mut_storage()
1511            .insert(key.to_string(), value.to_string());
1512        Ok(())
1513    }
1514
1515    /// Removes `key` from terminal session storage.
1516    ///
1517    /// # Arguments
1518    ///
1519    /// - `&Self` - Mutable terminal platform.
1520    /// - `&str` - Storage key.
1521    ///
1522    /// # Returns
1523    ///
1524    /// - `Result<(), PlatformError>` - Storage status.
1525    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
1526        let _: Option<String> = self.get_mut_storage().remove(key);
1527        Ok(())
1528    }
1529
1530    /// Clears all keys from terminal session storage.
1531    ///
1532    /// # Arguments
1533    ///
1534    /// - `&Self` - Mutable terminal platform.
1535    ///
1536    /// # Returns
1537    ///
1538    /// - `Result<(), PlatformError>` - Storage status.
1539    fn storage_clear(&mut self) -> Result<(), PlatformError> {
1540        self.get_mut_storage().clear();
1541        Ok(())
1542    }
1543}
1544
1545/// `PlatformNavigation` implementation for `TerminalPlatform`.
1546impl PlatformNavigation for TerminalPlatform {
1547    /// Pushes `route` onto the terminal session navigation stack.
1548    ///
1549    /// # Arguments
1550    ///
1551    /// - `&Self` - Mutable terminal platform.
1552    /// - `&str` - Logical route path.
1553    ///
1554    /// # Returns
1555    ///
1556    /// - `Result<(), PlatformError>` - Navigation status.
1557    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
1558        if !route.is_empty() {
1559            self.get_mut_route_stack().push(route.to_string());
1560        }
1561        Ok(())
1562    }
1563
1564    /// Pops `delta` entries from the terminal navigation stack, keeping the root route.
1565    ///
1566    /// # Arguments
1567    ///
1568    /// - `&Self` - Mutable terminal platform.
1569    /// - `u32` - Number of routes to pop.
1570    ///
1571    /// # Returns
1572    ///
1573    /// - `Result<(), PlatformError>` - Navigation status.
1574    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1575        for _ in 0..delta.max(1) {
1576            if self.get_route_stack().len() > 1 {
1577                let _: Option<String> = self.get_mut_route_stack().pop();
1578            }
1579        }
1580        Ok(())
1581    }
1582
1583    /// Returns the currently active terminal route path.
1584    ///
1585    /// # Arguments
1586    ///
1587    /// - `&Self` - Terminal platform reference.
1588    ///
1589    /// # Returns
1590    ///
1591    /// - `&str` - Current route path.
1592    fn current_route(&self) -> &str {
1593        self.get_route_stack()
1594            .last()
1595            .map(String::as_str)
1596            .unwrap_or(TERMINAL_DEFAULT_ROUTE)
1597    }
1598}
1599
1600/// `PlatformLifecycleBridge` implementation for `TerminalPlatform`.
1601impl PlatformLifecycleBridge for TerminalPlatform {
1602    /// Pauses terminal frame pumping and emits `Disappear` + `Background`.
1603    ///
1604    /// # Arguments
1605    ///
1606    /// - `&Self` - Mutable terminal platform.
1607    ///
1608    /// # Returns
1609    ///
1610    /// - `Vec<WindowEvent>` - Normalized freeze lifecycle events.
1611    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1612        self.set_pump_paused(true);
1613        vec![
1614            WindowEvent::System(SystemEvent::Disappear),
1615            WindowEvent::System(SystemEvent::Background),
1616        ]
1617    }
1618
1619    /// Resumes terminal frame pumping and emits `Appear` + `Foreground`.
1620    ///
1621    /// # Arguments
1622    ///
1623    /// - `&Self` - Mutable terminal platform.
1624    ///
1625    /// # Returns
1626    ///
1627    /// - `Vec<WindowEvent>` - Normalized resume lifecycle events.
1628    fn resume_surface(&mut self) -> Vec<WindowEvent> {
1629        self.set_pump_paused(false);
1630        vec![
1631            WindowEvent::System(SystemEvent::Appear),
1632            WindowEvent::System(SystemEvent::Foreground),
1633        ]
1634    }
1635
1636    /// Restores raw terminal state cleanly and emits `Terminate`.
1637    ///
1638    /// # Arguments
1639    ///
1640    /// - `&Self` - Mutable terminal platform.
1641    ///
1642    /// # Returns
1643    ///
1644    /// - `Vec<WindowEvent>` - Normalized destroy lifecycle events.
1645    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1646        self.set_pump_paused(true);
1647        self.leave_tui_session();
1648        vec![WindowEvent::System(SystemEvent::Terminate)]
1649    }
1650}
1651
1652/// `PlatformHostAdapter` implementation for `TerminalPlatform`.
1653impl PlatformHostAdapter for TerminalPlatform {
1654    /// Returns `DeviceFormFactor::Terminal`.
1655    ///
1656    /// # Arguments
1657    ///
1658    /// - `&Self` - Terminal platform reference.
1659    ///
1660    /// # Returns
1661    ///
1662    /// - `DeviceFormFactor` - `DeviceFormFactor::Terminal`.
1663    fn device_form_factor(&self) -> DeviceFormFactor {
1664        DeviceFormFactor::Terminal
1665    }
1666
1667    /// Returns `"terminal-tui"` for interactive PTY sessions or `"terminal-cli"` for static/pipe CLI sessions.
1668    ///
1669    /// # Arguments
1670    ///
1671    /// - `&Self` - Terminal platform reference.
1672    ///
1673    /// # Returns
1674    ///
1675    /// - `&'static str` - Canonical host vendor identifier.
1676    fn host_vendor_name(&self) -> &'static str {
1677        if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1678            TERMINAL_VENDOR_TUI
1679        } else {
1680            TERMINAL_VENDOR_CLI
1681        }
1682    }
1683}
1684
1685/// Explicit non-GPU routing contract and batched CLI output with backpressure telemetry for `TerminalPlatform`.
1686impl TerminalPlatform {
1687    /// Explicitly signals that TUI and CLI hosts opt out of graphical GPU routing and screen-Hz pacing.
1688    ///
1689    /// # Returns
1690    ///
1691    /// - `bool` - Always `true`.
1692    #[must_use]
1693    pub fn opts_out_of_gpu_routing(&self) -> bool {
1694        true
1695    }
1696
1697    /// Returns the most recent non-GPU, non-Hz terminal telemetry report (`input_to_output_ms`, `flush_latency_ms`, `bytes_written`).
1698    ///
1699    /// # Returns
1700    ///
1701    /// - `TerminalNonGpuTelemetry` - Latest terminal telemetry snapshot.
1702    #[must_use]
1703    pub fn telemetry_report(&self) -> TerminalNonGpuTelemetry {
1704        self.get_last_telemetry()
1705    }
1706
1707    /// Writes `chunks` to `stdout` as bounded coalesced batches respecting `cli_batch_limit_bytes` and backpressure, updating non-Hz telemetry.
1708    ///
1709    /// # Arguments
1710    ///
1711    /// - `&[&str]` - Ordered UTF-8 CLI output chunks to coalesce and flush.
1712    ///
1713    /// # Returns
1714    ///
1715    /// - `Result<TerminalNonGpuTelemetry, PlatformError>` - Updated non-GPU telemetry on success, or `Err` on broken pipe.
1716    pub fn write_stdout_batched(
1717        &mut self,
1718        chunks: &[&str],
1719    ) -> Result<TerminalNonGpuTelemetry, PlatformError> {
1720        let mode: TerminalRenderMode = self.render_mode();
1721        if self.get_broken_pipe() {
1722            let mut prev: TerminalNonGpuTelemetry = self.get_last_telemetry();
1723            prev.set_mode(mode);
1724            prev.set_gpu_routing_opted_out(true);
1725            prev.set_uses_screen_hz(false);
1726            prev.set_bytes_written(0);
1727            prev.set_backpressure_events(prev.get_backpressure_events().saturating_add(1));
1728            self.set_last_telemetry(prev);
1729            return Err(PlatformError::SurfaceError(
1730                ERR_TERMINAL_BROKEN_PIPE.to_string(),
1731            ));
1732        }
1733        #[cfg(not(target_arch = "wasm32"))]
1734        let flush_start: Instant = Instant::now();
1735        let batch_limit: usize = self.get_cli_batch_limit_bytes().max(1);
1736        let mut coalesced: String = String::new();
1737        let mut written_this_call: u64 = 0;
1738        let mut flush_count: u64 = 0;
1739        let mut bp_events: u64 = 0;
1740        for chunk in chunks.iter() {
1741            if chunk.is_empty() {
1742                continue;
1743            }
1744            if !coalesced.is_empty() && coalesced.len().saturating_add(chunk.len()) > batch_limit {
1745                let batch_len: u64 = coalesced.len() as u64;
1746                self.write_stdout(&coalesced)?;
1747                written_this_call = written_this_call.saturating_add(batch_len);
1748                flush_count = flush_count.saturating_add(1);
1749                bp_events = bp_events.saturating_add(1);
1750                coalesced.clear();
1751            }
1752            if chunk.len() > batch_limit {
1753                let mut start_idx: usize = 0;
1754                while start_idx < chunk.len() {
1755                    let mut end_idx: usize = (start_idx + batch_limit).min(chunk.len());
1756                    while end_idx > start_idx && !chunk.is_char_boundary(end_idx) {
1757                        end_idx -= 1;
1758                    }
1759                    if end_idx == start_idx {
1760                        end_idx = chunk.len();
1761                    }
1762                    let slice: &str = &chunk[start_idx..end_idx];
1763                    self.write_stdout(slice)?;
1764                    written_this_call = written_this_call.saturating_add(slice.len() as u64);
1765                    flush_count = flush_count.saturating_add(1);
1766                    if end_idx < chunk.len() {
1767                        bp_events = bp_events.saturating_add(1);
1768                    }
1769                    start_idx = end_idx;
1770                }
1771            } else {
1772                coalesced.push_str(chunk);
1773            }
1774        }
1775        if !coalesced.is_empty() {
1776            let batch_len: u64 = coalesced.len() as u64;
1777            self.write_stdout(&coalesced)?;
1778            written_this_call = written_this_call.saturating_add(batch_len);
1779            flush_count = flush_count.saturating_add(1);
1780        }
1781        #[cfg(not(target_arch = "wasm32"))]
1782        let flush_latency_ms: f64 = flush_start.elapsed().as_secs_f64() * 1000.0;
1783        #[cfg(target_arch = "wasm32")]
1784        let flush_latency_ms: f64 = 0.0;
1785        #[cfg(not(target_arch = "wasm32"))]
1786        let input_to_output_ms: Option<f64> = {
1787            let Self { last_input_at, .. } = self;
1788            last_input_at
1789                .take()
1790                .map(|timestamp_val: Instant| timestamp_val.elapsed().as_secs_f64() * 1000.0)
1791        };
1792        #[cfg(target_arch = "wasm32")]
1793        let input_to_output_ms: Option<f64> = None;
1794        let prev: TerminalNonGpuTelemetry = self.get_last_telemetry();
1795        let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
1796            mode,
1797            gpu_routing_opted_out: true,
1798            uses_screen_hz: false,
1799            input_to_output_ms,
1800            flush_latency_ms,
1801            bytes_written: written_this_call,
1802            total_bytes_written: prev
1803                .get_total_bytes_written()
1804                .saturating_add(written_this_call),
1805            changed_cells: 0,
1806            unchanged_frame_skipped: written_this_call == 0,
1807            backpressure_events: prev.get_backpressure_events().saturating_add(bp_events),
1808            batched_flush_count: prev.get_batched_flush_count().saturating_add(flush_count),
1809        };
1810        self.set_last_telemetry(telemetry);
1811        Ok(telemetry)
1812    }
1813}