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 }
690 }
691
692 /// Enters live interactive PTY raw mode and attaches the RAII restoration guard to this backend.
693 ///
694 /// # Arguments
695 ///
696 /// - `&Self` - Mutable terminal platform backend.
697 pub fn enter_live_tui_session(&mut self) {
698 if self.get_resolved_mode() != TerminalHostMode::InteractiveTui {
699 return;
700 }
701 let guard: TerminalRawGuard = TerminalRawGuard::enter_live(true, true, true, true);
702 self.set_raw_guard(Some(guard));
703 }
704
705 /// Attaches a deterministic captured RAII guard for testing raw-mode entry and restore without touching real TTY handles.
706 ///
707 /// # Arguments
708 ///
709 /// - `&Self` - Mutable terminal platform backend.
710 /// - `Rc<RefCell<String>>` - Sink capturing enter/exit ANSI sequences.
711 pub fn enter_captured_tui_session(&mut self, sink: Rc<RefCell<String>>) {
712 let guard: TerminalRawGuard =
713 TerminalRawGuard::enter_captured(true, true, true, true, Some(sink));
714 self.set_raw_guard(Some(guard));
715 }
716
717 /// Explicitly restores and releases the active RAII terminal raw-mode guard, if entered.
718 ///
719 /// # Arguments
720 ///
721 /// - `&Self` - Mutable terminal platform backend.
722 pub fn leave_tui_session(&mut self) {
723 let Self { raw_guard, .. } = self;
724 if let Some(mut guard) = raw_guard.take() {
725 guard.restore();
726 }
727 }
728
729 /// Returns the primary terminal `WindowId` if one has been created.
730 ///
731 /// # Arguments
732 ///
733 /// - `&Self` - Terminal platform reference.
734 ///
735 /// # Returns
736 ///
737 /// - `Option<WindowId>` - Primary window handle.
738 #[must_use]
739 pub fn primary_window_id(&self) -> Option<WindowId> {
740 let Self { primary_window, .. } = self;
741 *primary_window
742 }
743
744 /// Feeds raw VT/xterm input bytes into the parser and enqueues all decoded `WindowEvent`s.
745 ///
746 /// # Arguments
747 ///
748 /// - `&Self` - Mutable terminal platform.
749 /// - `&[u8]` - Raw bytes read from PTY or injected by a test harness.
750 ///
751 /// # Returns
752 ///
753 /// - `usize` - Number of `WindowEvent`s enqueued.
754 pub fn push_raw_input(&mut self, bytes: &[u8]) -> usize {
755 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
756 let decoded: Vec<WindowEvent> = self.get_mut_parser().feed(wid, bytes);
757 let count: usize = decoded.len();
758 self.get_mut_pending_events().extend(decoded);
759 count
760 }
761
762 /// Updates terminal `(cols, rows)` and emits matching `WindowEvent::Resized` and `SystemEvent::Resize` events.
763 ///
764 /// # Arguments
765 ///
766 /// - `&Self` - Mutable terminal platform.
767 /// - `u16` - New terminal column count.
768 /// - `u16` - New terminal row count.
769 pub fn handle_terminal_resize(&mut self, cols: u16, rows: u16) {
770 let safe_cols: u16 = cols.max(1);
771 let safe_rows: u16 = rows.max(1);
772 let mut next_metrics: TerminalCellMetrics = self.get_metrics();
773 next_metrics.set_cols(safe_cols).set_rows(safe_rows);
774 self.set_metrics(next_metrics);
775 let log_w: u32 = next_metrics.logical_width();
776 let log_h: u32 = next_metrics.logical_height();
777 let mut resized_ids: Vec<WindowId> = Vec::with_capacity(self.get_windows().len());
778 for (&wid, rec) in self.get_mut_windows().iter_mut() {
779 rec.set_metrics(next_metrics);
780 rec.get_mut_config().set_width(log_w).set_height(log_h);
781 rec.get_mut_state()
782 .set_logical_width(log_w as f32)
783 .set_logical_height(log_h as f32)
784 .set_physical_width(log_w)
785 .set_physical_height(log_h);
786 resized_ids.push(wid);
787 }
788 for wid in resized_ids.into_iter() {
789 self.get_mut_pending_events()
790 .push(WindowEvent::Resized(wid, log_w, log_h, 1.0));
791 }
792 self.get_mut_pending_events()
793 .push(WindowEvent::System(SystemEvent::Resize {
794 width: log_w as f32,
795 height: log_h as f32,
796 scale_factor: 1.0,
797 }));
798 }
799
800 /// Writes clean result text to the `stdout` channel, stripping or suppressing ANSI automatically when piped.
801 ///
802 /// # Arguments
803 ///
804 /// - `&Self` - Mutable terminal platform.
805 /// - `&str` - UTF-8 output payload.
806 ///
807 /// # Returns
808 ///
809 /// - `Result<(), PlatformError>` - Write status (`Err` if pipe is broken).
810 pub fn write_stdout(&mut self, text: &str) -> Result<(), PlatformError> {
811 if self.get_broken_pipe() {
812 return Err(PlatformError::SurfaceError(
813 ERR_TERMINAL_BROKEN_PIPE.to_string(),
814 ));
815 }
816 self.get_mut_stdout_log().extend_from_slice(text.as_bytes());
817 if self.get_emit_os_streams() {
818 let ok: bool = terminal_write_os_stream(TerminalStreamKind::Stdout, text.as_bytes())?;
819 if !ok {
820 self.set_broken_pipe(true);
821 return Err(PlatformError::SurfaceError(
822 ERR_TERMINAL_BROKEN_PIPE.to_string(),
823 ));
824 }
825 }
826 Ok(())
827 }
828
829 /// Writes diagnostic or error text strictly to the `stderr` channel so `stdout` pipelines remain unpolluted.
830 ///
831 /// # Arguments
832 ///
833 /// - `&Self` - Mutable terminal platform.
834 /// - `&str` - UTF-8 diagnostic payload.
835 ///
836 /// # Returns
837 ///
838 /// - `Result<(), PlatformError>` - Write status.
839 pub fn write_stderr(&mut self, text: &str) -> Result<(), PlatformError> {
840 self.get_mut_stderr_log().extend_from_slice(text.as_bytes());
841 if self.get_emit_os_streams() {
842 let _: bool = terminal_write_os_stream(TerminalStreamKind::Stderr, text.as_bytes())?;
843 }
844 Ok(())
845 }
846
847 /// Records a terminal frame string (`TerminalRenderer` output) against `id` and writes it to `stdout`.
848 ///
849 /// # Arguments
850 ///
851 /// - `&Self` - Mutable terminal platform.
852 /// - `WindowId` - Target window handle.
853 /// - `&str` - Rendered ANSI cell-diff or static plain-text output.
854 ///
855 /// # Returns
856 ///
857 /// - `Result<(), PlatformError>` - Presentation status.
858 pub fn present_terminal_output(
859 &mut self,
860 id: WindowId,
861 output: &str,
862 ) -> Result<(), PlatformError> {
863 let rec: &mut TerminalWindowRecord = self
864 .get_mut_windows()
865 .get_mut(&id)
866 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
867 rec.set_last_output(output.to_string());
868 rec.set_present_count(rec.get_present_count().wrapping_add(1));
869 if !output.is_empty() {
870 self.write_stdout(output)?;
871 }
872 Ok(())
873 }
874
875 /// Returns captured standard output decoded as UTF-8.
876 ///
877 /// # Arguments
878 ///
879 /// - `&Self` - Terminal platform reference.
880 ///
881 /// # Returns
882 ///
883 /// - `String` - Captured `stdout` text.
884 #[must_use]
885 pub fn stdout_text(&self) -> String {
886 String::from_utf8_lossy(self.get_stdout_log().as_slice()).into_owned()
887 }
888
889 /// Returns captured standard error diagnostics decoded as UTF-8.
890 ///
891 /// # Arguments
892 ///
893 /// - `&Self` - Terminal platform reference.
894 ///
895 /// # Returns
896 ///
897 /// - `String` - Captured `stderr` text.
898 #[must_use]
899 pub fn stderr_text(&self) -> String {
900 String::from_utf8_lossy(self.get_stderr_log().as_slice()).into_owned()
901 }
902
903 /// Marks the session as exiting with `code` and enqueues `SystemEvent::Terminate`.
904 ///
905 /// # Arguments
906 ///
907 /// - `&Self` - Mutable terminal platform.
908 /// - `i32` - Process exit code to propagate.
909 pub fn request_exit_with_code(&mut self, code: i32) {
910 self.set_exit_code(code);
911 self.leave_tui_session();
912 if let Some(wid) = self.primary_window_id() {
913 self.get_mut_pending_events()
914 .push(WindowEvent::CloseRequested(wid));
915 }
916 self.get_mut_pending_events()
917 .push(WindowEvent::System(SystemEvent::Terminate));
918 }
919
920 /// Resolves the active `TerminalRenderMode` matching this host's resolved mode and TTY probe.
921 ///
922 /// # Arguments
923 ///
924 /// - `&Self` - Terminal platform reference.
925 ///
926 /// # Returns
927 ///
928 /// - `TerminalRenderMode` - `InteractiveTui` for live PTY sessions, `StaticPlainText` for piped/static CLI.
929 #[must_use]
930 pub fn render_mode(&self) -> TerminalRenderMode {
931 if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
932 TerminalRenderMode::InteractiveTui
933 } else {
934 TerminalRenderMode::StaticPlainText
935 }
936 }
937}
938
939/// `WindowController` implementation for `TerminalPlatform`.
940impl WindowController for TerminalPlatform {
941 /// Applies a `WindowCommand` against the terminal window record.
942 ///
943 /// # Arguments
944 ///
945 /// - `&Self` - Mutable terminal platform.
946 /// - `WindowCommand` - Command to apply.
947 ///
948 /// # Returns
949 ///
950 /// - `Result<(), PlatformError>` - Execution status.
951 fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
952 match command {
953 WindowCommand::SetTitle(id, title) => {
954 let rec: &mut TerminalWindowRecord = self
955 .get_mut_windows()
956 .get_mut(&id)
957 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
958 rec.get_mut_config().set_title(title);
959 Ok(())
960 }
961 WindowCommand::SetSize(id, width, height) => {
962 let rec: &mut TerminalWindowRecord = self
963 .get_mut_windows()
964 .get_mut(&id)
965 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
966 let cw: f32 = rec.get_metrics().get_cell_width_px().max(1.0);
967 let ch: f32 = rec.get_metrics().get_cell_height_px().max(1.0);
968 let cols: u16 = ((width.max(1) as f32) / cw).round().clamp(1.0, 1000.0) as u16;
969 let rows: u16 = ((height.max(1) as f32) / ch).round().clamp(1.0, 1000.0) as u16;
970 self.handle_terminal_resize(cols, rows);
971 Ok(())
972 }
973 WindowCommand::RequestRedraw(id) => {
974 if !self.get_windows().contains_key(&id) {
975 return Err(PlatformError::WindowNotFound(id.get_value()));
976 }
977 self.get_mut_pending_events()
978 .push(WindowEvent::RedrawRequested(id));
979 Ok(())
980 }
981 WindowCommand::Close(id) => {
982 if self.get_mut_windows().remove(&id).is_none() {
983 return Err(PlatformError::WindowNotFound(id.get_value()));
984 }
985 self.leave_tui_session();
986 Ok(())
987 }
988 WindowCommand::SetPosition(id, _, _)
989 | WindowCommand::SetResizable(id, _)
990 | WindowCommand::SetDecorations(id, _)
991 | WindowCommand::SetAlwaysOnTop(id, _)
992 | WindowCommand::SetFullscreen(id, _)
993 | WindowCommand::SetVisible(id, _)
994 | WindowCommand::SetCursor(id, _)
995 | WindowCommand::SetIme(id, _, _)
996 | WindowCommand::SetStatusBarStyle(id, _)
997 | WindowCommand::SetRenderMode(id, _) => {
998 if !self.get_windows().contains_key(&id) {
999 return Err(PlatformError::WindowNotFound(id.get_value()));
1000 }
1001 Ok(())
1002 }
1003 }
1004 }
1005}
1006
1007/// `PlatformBackend` implementation for `TerminalPlatform`.
1008impl PlatformBackend for TerminalPlatform {
1009 /// Returns `PlatformKind::Terminal` in interactive TUI mode or `PlatformKind::TerminalCli` in static/pipe CLI mode.
1010 ///
1011 /// # Arguments
1012 ///
1013 /// - `&Self` - Terminal platform reference.
1014 ///
1015 /// # Returns
1016 ///
1017 /// - `PlatformKind` - Concrete terminal platform kind.
1018 fn kind(&self) -> PlatformKind {
1019 if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1020 PlatformKind::Terminal
1021 } else {
1022 PlatformKind::TerminalCli
1023 }
1024 }
1025
1026 /// Returns normalized capabilities for this terminal mode.
1027 ///
1028 /// # Arguments
1029 ///
1030 /// - `&Self` - Terminal platform reference.
1031 ///
1032 /// # Returns
1033 ///
1034 /// - `PlatformCapabilities` - Terminal capabilities.
1035 fn capabilities(&self) -> PlatformCapabilities {
1036 PlatformCapabilities::for_platform(self.kind())
1037 }
1038
1039 /// Allocates a terminal viewport window mapped to the current `(cols, rows)` cell metrics.
1040 ///
1041 /// # Arguments
1042 ///
1043 /// - `&Self` - Mutable terminal platform.
1044 /// - `&WindowConfig` - Declarative window configuration.
1045 ///
1046 /// # Returns
1047 ///
1048 /// - `Result<WindowState, PlatformError>` - Created terminal window state.
1049 fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
1050 let id: WindowId = WindowId::new(self.get_next_id());
1051 self.set_next_id(self.get_next_id().wrapping_add(1));
1052 let metrics: TerminalCellMetrics = self.get_metrics();
1053 let mut adjusted: WindowConfig = config.clone();
1054 adjusted.set_size(metrics.logical_width(), metrics.logical_height());
1055 let mut state: WindowState = WindowState::from_config(id, &adjusted, 1.0);
1056 state.set_system_theme(self.get_theme());
1057 let record: TerminalWindowRecord = TerminalWindowRecord {
1058 config: adjusted,
1059 state,
1060 metrics,
1061 present_count: 0,
1062 last_output: String::new(),
1063 last_frame: Framebuffer::allocate(1, 1),
1064 };
1065 self.get_mut_windows().insert(id, record);
1066 if self.primary_window_id().is_none() {
1067 self.set_primary_window(Some(id));
1068 }
1069 Ok(state)
1070 }
1071
1072 /// Queries live `WindowState` for `id`.
1073 ///
1074 /// # Arguments
1075 ///
1076 /// - `&Self` - Terminal platform reference.
1077 /// - `WindowId` - Window identifier.
1078 ///
1079 /// # Returns
1080 ///
1081 /// - `Option<WindowState>` - Window state if alive.
1082 fn window_state(&self, id: WindowId) -> Option<WindowState> {
1083 self.get_windows()
1084 .get(&id)
1085 .map(TerminalWindowRecord::get_state)
1086 }
1087
1088 /// Returns `RawWindowHandle::TerminalPty` describing the attached PTY/console fd.
1089 ///
1090 /// # Arguments
1091 ///
1092 /// - `&Self` - Terminal platform reference.
1093 /// - `WindowId` - Window identifier.
1094 ///
1095 /// # Returns
1096 ///
1097 /// - `RawWindowHandle` - Terminal PTY raw handle.
1098 fn raw_window_handle(&self, _id: WindowId) -> RawWindowHandle {
1099 RawWindowHandle::TerminalPty {
1100 fd: UNIX_STDOUT_FD,
1101 is_tty: self.get_probe().get_stdout_is_tty(),
1102 }
1103 }
1104
1105 /// Polls pending `SIGWINCH` resizes, non-blocking live PTY bytes (when active), and drains queued `WindowEvent`s.
1106 ///
1107 /// # Arguments
1108 ///
1109 /// - `&Self` - Mutable terminal platform.
1110 ///
1111 /// # Returns
1112 ///
1113 /// - `Vec<WindowEvent>` - Ordered pending events.
1114 fn poll_events(&mut self) -> Vec<WindowEvent> {
1115 if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1116 if terminal_take_sigwinch_resized() {
1117 let (cols, rows): (u16, u16) = terminal_query_pty_size();
1118 self.handle_terminal_resize(cols, rows);
1119 }
1120 let live_raw: bool = {
1121 let Self { raw_guard, .. } = self;
1122 raw_guard
1123 .as_ref()
1124 .is_some_and(TerminalRawGuard::get_os_raw_active)
1125 };
1126 if live_raw {
1127 let bytes: Vec<u8> = terminal_read_pty_bytes(0);
1128 if !bytes.is_empty() {
1129 let _: usize = self.push_raw_input(&bytes);
1130 }
1131 }
1132 }
1133 take(self.get_mut_pending_events())
1134 }
1135
1136 /// Updates frame pump pause state for suspend/background freeze.
1137 ///
1138 /// # Arguments
1139 ///
1140 /// - `&Self` - Mutable terminal platform.
1141 /// - `bool` - `true` to pause frame pumping.
1142 fn set_frame_pump_paused(&mut self, paused: bool) {
1143 self.set_pump_paused(paused);
1144 }
1145
1146 /// Returns whether the terminal frame pump is paused.
1147 ///
1148 /// # Arguments
1149 ///
1150 /// - `&Self` - Terminal platform reference.
1151 ///
1152 /// # Returns
1153 ///
1154 /// - `bool` - Pause status.
1155 fn is_frame_pump_paused(&self) -> bool {
1156 self.get_pump_paused()
1157 }
1158
1159 /// Stores a fallback RGBA8 framebuffer snapshot without emitting raw pixel bytes to the terminal stream.
1160 ///
1161 /// # Arguments
1162 ///
1163 /// - `&Self` - Mutable terminal platform.
1164 /// - `WindowId` - Target window handle.
1165 /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1166 ///
1167 /// # Returns
1168 ///
1169 /// - `Result<(), PlatformError>` - Presentation status.
1170 fn present_framebuffer(
1171 &mut self,
1172 id: WindowId,
1173 framebuffer: &Framebuffer,
1174 ) -> Result<(), PlatformError> {
1175 let rec: &mut TerminalWindowRecord = self
1176 .get_mut_windows()
1177 .get_mut(&id)
1178 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1179 rec.set_last_frame(framebuffer.clone());
1180 rec.set_present_count(rec.get_present_count().wrapping_add(1));
1181 Ok(())
1182 }
1183
1184 /// Reads the terminal clipboard cache.
1185 ///
1186 /// # Arguments
1187 ///
1188 /// - `&Self` - Terminal platform reference.
1189 ///
1190 /// # Returns
1191 ///
1192 /// - `Option<String>` - Cached clipboard string.
1193 fn read_clipboard(&self) -> Option<String> {
1194 let Self { clipboard, .. } = self;
1195 clipboard.clone()
1196 }
1197
1198 /// Stores `text` into the terminal clipboard buffer.
1199 ///
1200 /// # Arguments
1201 ///
1202 /// - `&Self` - Mutable terminal platform.
1203 /// - `&str` - Clipboard text.
1204 ///
1205 /// # Returns
1206 ///
1207 /// - `Result<(), PlatformError>` - Always succeeds.
1208 fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
1209 self.set_clipboard(Some(text.to_string()));
1210 Ok(())
1211 }
1212
1213 /// Returns the terminal theme hint.
1214 ///
1215 /// # Arguments
1216 ///
1217 /// - `&Self` - Terminal platform reference.
1218 ///
1219 /// # Returns
1220 ///
1221 /// - `ThemeMode` - Active terminal theme mode.
1222 fn system_theme(&self) -> ThemeMode {
1223 self.get_theme()
1224 }
1225}
1226
1227/// `PlatformStorage` implementation for `TerminalPlatform`.
1228impl PlatformStorage for TerminalPlatform {
1229 /// Reads a key from in-memory terminal session storage.
1230 ///
1231 /// # Arguments
1232 ///
1233 /// - `&Self` - Terminal platform reference.
1234 /// - `&str` - Storage key.
1235 ///
1236 /// # Returns
1237 ///
1238 /// - `Option<String>` - Stored value, if present.
1239 fn storage_get(&self, key: &str) -> Option<String> {
1240 self.get_storage().get(key).cloned()
1241 }
1242
1243 /// Writes a key-value pair into terminal session storage.
1244 ///
1245 /// # Arguments
1246 ///
1247 /// - `&Self` - Mutable terminal platform.
1248 /// - `&str` - Storage key.
1249 /// - `&str` - Value to store.
1250 ///
1251 /// # Returns
1252 ///
1253 /// - `Result<(), PlatformError>` - Storage status.
1254 fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
1255 let _: Option<String> = self
1256 .get_mut_storage()
1257 .insert(key.to_string(), value.to_string());
1258 Ok(())
1259 }
1260
1261 /// Removes `key` from terminal session storage.
1262 ///
1263 /// # Arguments
1264 ///
1265 /// - `&Self` - Mutable terminal platform.
1266 /// - `&str` - Storage key.
1267 ///
1268 /// # Returns
1269 ///
1270 /// - `Result<(), PlatformError>` - Storage status.
1271 fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
1272 let _: Option<String> = self.get_mut_storage().remove(key);
1273 Ok(())
1274 }
1275
1276 /// Clears all keys from terminal session storage.
1277 ///
1278 /// # Arguments
1279 ///
1280 /// - `&Self` - Mutable terminal platform.
1281 ///
1282 /// # Returns
1283 ///
1284 /// - `Result<(), PlatformError>` - Storage status.
1285 fn storage_clear(&mut self) -> Result<(), PlatformError> {
1286 self.get_mut_storage().clear();
1287 Ok(())
1288 }
1289}
1290
1291/// `PlatformNavigation` implementation for `TerminalPlatform`.
1292impl PlatformNavigation for TerminalPlatform {
1293 /// Pushes `route` onto the terminal session navigation stack.
1294 ///
1295 /// # Arguments
1296 ///
1297 /// - `&Self` - Mutable terminal platform.
1298 /// - `&str` - Logical route path.
1299 ///
1300 /// # Returns
1301 ///
1302 /// - `Result<(), PlatformError>` - Navigation status.
1303 fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
1304 if !route.is_empty() {
1305 self.get_mut_route_stack().push(route.to_string());
1306 }
1307 Ok(())
1308 }
1309
1310 /// Pops `delta` entries from the terminal navigation stack, keeping the root route.
1311 ///
1312 /// # Arguments
1313 ///
1314 /// - `&Self` - Mutable terminal platform.
1315 /// - `u32` - Number of routes to pop.
1316 ///
1317 /// # Returns
1318 ///
1319 /// - `Result<(), PlatformError>` - Navigation status.
1320 fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1321 for _ in 0..delta.max(1) {
1322 if self.get_route_stack().len() > 1 {
1323 let _: Option<String> = self.get_mut_route_stack().pop();
1324 }
1325 }
1326 Ok(())
1327 }
1328
1329 /// Returns the currently active terminal route path.
1330 ///
1331 /// # Arguments
1332 ///
1333 /// - `&Self` - Terminal platform reference.
1334 ///
1335 /// # Returns
1336 ///
1337 /// - `&str` - Current route path.
1338 fn current_route(&self) -> &str {
1339 self.get_route_stack()
1340 .last()
1341 .map(String::as_str)
1342 .unwrap_or(TERMINAL_DEFAULT_ROUTE)
1343 }
1344}
1345
1346/// `PlatformLifecycleBridge` implementation for `TerminalPlatform`.
1347impl PlatformLifecycleBridge for TerminalPlatform {
1348 /// Pauses terminal frame pumping and emits `Disappear` + `Background`.
1349 ///
1350 /// # Arguments
1351 ///
1352 /// - `&Self` - Mutable terminal platform.
1353 ///
1354 /// # Returns
1355 ///
1356 /// - `Vec<WindowEvent>` - Normalized freeze lifecycle events.
1357 fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1358 self.set_pump_paused(true);
1359 vec![
1360 WindowEvent::System(SystemEvent::Disappear),
1361 WindowEvent::System(SystemEvent::Background),
1362 ]
1363 }
1364
1365 /// Resumes terminal frame pumping and emits `Appear` + `Foreground`.
1366 ///
1367 /// # Arguments
1368 ///
1369 /// - `&Self` - Mutable terminal platform.
1370 ///
1371 /// # Returns
1372 ///
1373 /// - `Vec<WindowEvent>` - Normalized resume lifecycle events.
1374 fn resume_surface(&mut self) -> Vec<WindowEvent> {
1375 self.set_pump_paused(false);
1376 vec![
1377 WindowEvent::System(SystemEvent::Appear),
1378 WindowEvent::System(SystemEvent::Foreground),
1379 ]
1380 }
1381
1382 /// Restores raw terminal state cleanly and emits `Terminate`.
1383 ///
1384 /// # Arguments
1385 ///
1386 /// - `&Self` - Mutable terminal platform.
1387 ///
1388 /// # Returns
1389 ///
1390 /// - `Vec<WindowEvent>` - Normalized destroy lifecycle events.
1391 fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1392 self.set_pump_paused(true);
1393 self.leave_tui_session();
1394 vec![WindowEvent::System(SystemEvent::Terminate)]
1395 }
1396}
1397
1398/// `PlatformHostAdapter` implementation for `TerminalPlatform`.
1399impl PlatformHostAdapter for TerminalPlatform {
1400 /// Returns `DeviceFormFactor::Terminal`.
1401 ///
1402 /// # Arguments
1403 ///
1404 /// - `&Self` - Terminal platform reference.
1405 ///
1406 /// # Returns
1407 ///
1408 /// - `DeviceFormFactor` - `DeviceFormFactor::Terminal`.
1409 fn device_form_factor(&self) -> DeviceFormFactor {
1410 DeviceFormFactor::Terminal
1411 }
1412
1413 /// Returns `"terminal-tui"` for interactive PTY sessions or `"terminal-cli"` for static/pipe CLI sessions.
1414 ///
1415 /// # Arguments
1416 ///
1417 /// - `&Self` - Terminal platform reference.
1418 ///
1419 /// # Returns
1420 ///
1421 /// - `&'static str` - Canonical host vendor identifier.
1422 fn host_vendor_name(&self) -> &'static str {
1423 if self.get_resolved_mode() == TerminalHostMode::InteractiveTui {
1424 TERMINAL_VENDOR_TUI
1425 } else {
1426 TERMINAL_VENDOR_CLI
1427 }
1428 }
1429}