euv-core 0.53.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use super::*;

#[cfg(unix)]
unsafe extern "C" {
    /// Checks whether a POSIX file descriptor refers to a terminal device.
    ///
    /// # Arguments
    ///
    /// - `i32` - POSIX file descriptor.
    ///
    /// # Returns
    ///
    /// - `i32` - `1` when attached to a TTY, `0` otherwise.
    fn isatty(fd: i32) -> i32;
    /// Reads current POSIX terminal attributes into `termios`.
    ///
    /// # Arguments
    ///
    /// - `i32` - POSIX terminal file descriptor.
    /// - `*mut UnixTermios` - Output `termios` buffer.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    fn tcgetattr(fd: i32, termios: *mut UnixTermios) -> i32;
    /// Applies POSIX terminal attributes from `termios`.
    ///
    /// # Arguments
    ///
    /// - `i32` - POSIX terminal file descriptor.
    /// - `i32` - Optional actions constant (`TCSANOW`).
    /// - `*const UnixTermios` - New `termios` configuration.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    fn tcsetattr(fd: i32, optional_actions: i32, termios: *const UnixTermios) -> i32;
    /// Queries terminal window dimensions via POSIX `ioctl(fd, TIOCGWINSZ, &ws)`.
    ///
    /// # Arguments
    ///
    /// - `i32` - POSIX terminal file descriptor.
    /// - `usize` - Platform-specific `TIOCGWINSZ` ioctl request code.
    /// - `...` - Variadic ioctl output pointer (`*mut UnixWinsize`).
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    fn ioctl(fd: i32, request: usize, ...) -> i32;
    /// Registers a POSIX signal handler function pointer for `sig`.
    ///
    /// # Arguments
    ///
    /// - `i32` - Signal number (`SIGWINCH`).
    /// - `extern "C" fn(i32)` - Signal handler function pointer.
    ///
    /// # Returns
    ///
    /// - `usize` - Previous signal handler address.
    fn signal(sig: i32, handler: extern "C" fn(i32)) -> usize;
    /// Polls POSIX file descriptors with a millisecond timeout.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Array of `pollfd` descriptors.
    /// - `usize` - Number of descriptors.
    /// - `i32` - Timeout in milliseconds (`0` for non-blocking).
    ///
    /// # Returns
    ///
    /// - `i32` - Number of ready descriptors, `0` on timeout, or `-1` on error.
    fn poll(fds: *mut c_void, nfds: usize, timeout: i32) -> i32;
    /// Reads up to `count` bytes from POSIX file descriptor `fd`.
    ///
    /// # Arguments
    ///
    /// - `i32` - File descriptor.
    /// - `*mut c_void` - Output byte buffer.
    /// - `usize` - Buffer capacity in bytes.
    ///
    /// # Returns
    ///
    /// - `isize` - Bytes read, `0` on EOF, or `-1` on error.
    fn read(fd: i32, buf: *mut c_void, count: usize) -> isize;
    /// Writes up to `count` bytes to POSIX file descriptor `fd` (async-signal-safe).
    ///
    /// # Arguments
    ///
    /// - `i32` - File descriptor.
    /// - `*const c_void` - Source byte buffer.
    /// - `usize` - Number of bytes to write.
    ///
    /// # Returns
    ///
    /// - `isize` - Bytes written or `-1` on error.
    fn write(fd: i32, buf: *const c_void, count: usize) -> isize;
    /// Creates an anonymous unidirectional POSIX pipe `[read_fd, write_fd]`.
    ///
    /// # Arguments
    ///
    /// - `*mut i32` - Two-element output file descriptor array.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success, `-1` on error.
    fn pipe(fds: *mut i32) -> i32;
    /// Performs POSIX file descriptor control commands (`F_GETFL`, `F_SETFL`, `F_SETFD`).
    ///
    /// # Arguments
    ///
    /// - `i32` - File descriptor.
    /// - `i32` - Control command identifier.
    /// - `...` - Optional integer flag argument.
    ///
    /// # Returns
    ///
    /// - `i32` - Command result or `-1` on error.
    fn fcntl(fd: i32, cmd: i32, ...) -> i32;
    /// Closes a POSIX file descriptor.
    ///
    /// # Arguments
    ///
    /// - `i32` - File descriptor to close.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success, `-1` on error.
    fn close(fd: i32) -> i32;
}

#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
    /// Retrieves a Win32 standard console handle (`STD_INPUT_HANDLE`, `STD_OUTPUT_HANDLE`, `STD_ERROR_HANDLE`).
    ///
    /// # Arguments
    ///
    /// - `u32` - Standard handle constant.
    ///
    /// # Returns
    ///
    /// - `isize` - Console handle or `INVALID_HANDLE_VALUE`.
    fn GetStdHandle(n_std_handle: u32) -> isize;
    /// Queries the Win32 file type of `h_file` (`FILE_TYPE_CHAR` for consoles).
    ///
    /// # Arguments
    ///
    /// - `isize` - Win32 handle.
    ///
    /// # Returns
    ///
    /// - `u32` - File type code.
    fn GetFileType(h_file: isize) -> u32;
    /// Retrieves current Win32 console mode flags.
    ///
    /// # Arguments
    ///
    /// - `isize` - Console handle.
    /// - `*mut u32` - Output mode bitmask.
    ///
    /// # Returns
    ///
    /// - `i32` - Non-zero on success.
    fn GetConsoleMode(h_console_handle: isize, lp_mode: *mut u32) -> i32;
    /// Updates Win32 console mode flags (e.g. enabling VT processing and VT input).
    ///
    /// # Arguments
    ///
    /// - `isize` - Console handle.
    /// - `u32` - Mode bitmask to apply.
    ///
    /// # Returns
    ///
    /// - `i32` - Non-zero on success.
    fn SetConsoleMode(h_console_handle: isize, dw_mode: u32) -> i32;
    /// Retrieves Win32 console screen buffer dimensions and visible window bounds.
    ///
    /// # Arguments
    ///
    /// - `isize` - Console output handle.
    /// - `*mut Win32ConsoleScreenBufferInfo` - Output screen buffer info struct.
    ///
    /// # Returns
    ///
    /// - `i32` - Non-zero on success.
    fn GetConsoleScreenBufferInfo(
        h_console_output: isize,
        lp_console_screen_buffer_info: *mut Win32ConsoleScreenBufferInfo,
    ) -> i32;
}

#[cfg(unix)]
/// Lazily creates the non-blocking Unix self-pipe used to wake `poll()` on `SIGWINCH`.
///
/// # Returns
///
/// - `(i32, i32)` - `(read_fd, write_fd)` pair, or `(-1, -1)` if pipe creation fails.
fn terminal_ensure_sigwinch_pipe() -> (i32, i32) {
    let existing_read: i32 = TERMINAL_SIGWINCH_PIPE_READ.load(Ordering::Acquire);
    let existing_write: i32 = TERMINAL_SIGWINCH_PIPE_WRITE.load(Ordering::Acquire);
    if existing_read >= 0 && existing_write >= 0 {
        return (existing_read, existing_write);
    }
    let mut fds: [i32; 2] = [UNIX_INVALID_FD, UNIX_INVALID_FD];
    // SAFETY: Creates a valid POSIX pipe and configures `FD_CLOEXEC` and `O_NONBLOCK` on both ends.
    unsafe {
        if pipe(fds.as_mut_ptr()) != 0 {
            return (UNIX_INVALID_FD, UNIX_INVALID_FD);
        }
        for fd in fds {
            let _: i32 = fcntl(fd, UNIX_F_SETFD, UNIX_FD_CLOEXEC);
            let cur_flags: i32 = fcntl(fd, UNIX_F_GETFL);
            if cur_flags >= 0 {
                let _: i32 = fcntl(fd, UNIX_F_SETFL, cur_flags | UNIX_O_NONBLOCK);
            }
        }
        if TERMINAL_SIGWINCH_PIPE_READ
            .compare_exchange(UNIX_INVALID_FD, fds[0], Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
        {
            TERMINAL_SIGWINCH_PIPE_WRITE.store(fds[1], Ordering::Release);
            (fds[0], fds[1])
        } else {
            let _: i32 = close(fds[0]);
            let _: i32 = close(fds[1]);
            (
                TERMINAL_SIGWINCH_PIPE_READ.load(Ordering::Acquire),
                TERMINAL_SIGWINCH_PIPE_WRITE.load(Ordering::Acquire),
            )
        }
    }
}

#[cfg(unix)]
/// Drains all pending wakeup bytes from the non-blocking `SIGWINCH` self-pipe read descriptor.
///
/// # Arguments
///
/// - `i32` - Non-blocking pipe read file descriptor.
fn terminal_drain_sigwinch_pipe(read_fd: i32) {
    if read_fd < 0 {
        return;
    }
    let mut drain_buf: [u8; 64] = [0; 64];
    // SAFETY: `read_fd` is configured `O_NONBLOCK`, so draining returns immediately once empty.
    unsafe {
        while read(
            read_fd,
            drain_buf.as_mut_ptr().cast::<c_void>(),
            drain_buf.len(),
        ) > 0
        {}
    }
}

#[cfg(unix)]
/// Async-signal-safe `SIGWINCH` signal handler marking the global resize flag and waking `poll()` via the self-pipe.
///
/// # Arguments
///
/// - `i32` - Delivered POSIX signal number.
extern "C" fn terminal_sigwinch_handler(_sig: i32) {
    TERMINAL_SIGWINCH_FLAG.store(true, Ordering::Release);
    let write_fd: i32 = TERMINAL_SIGWINCH_PIPE_WRITE.load(Ordering::Acquire);
    if write_fd >= 0 {
        let wake: u8 = UNIX_WAKE_BYTE;
        // SAFETY: POSIX `write(2)` on a non-blocking pipe fd is async-signal-safe.
        unsafe {
            let _: isize = write(write_fd, (&wake as *const u8).cast::<c_void>(), 1);
        }
    }
}

/// Signals a `SIGWINCH` resize wakeup across both the atomic flag and the Unix self-pipe.
pub fn terminal_signal_sigwinch_wakeup() {
    #[cfg(unix)]
    {
        let (_, write_fd): (i32, i32) = terminal_ensure_sigwinch_pipe();
        TERMINAL_SIGWINCH_FLAG.store(true, Ordering::Release);
        if write_fd >= 0 {
            let wake: u8 = UNIX_WAKE_BYTE;
            // SAFETY: Non-blocking 1-byte write wakes any thread blocked in `terminal_wait_pty_event`.
            unsafe {
                let _: isize = write(write_fd, (&wake as *const u8).cast::<c_void>(), 1);
            }
        }
    }
    #[cfg(not(unix))]
    {
        TERMINAL_SIGWINCH_FLAG.store(true, Ordering::Release);
    }
}

/// Installs the Unix `SIGWINCH` signal handler and wakeup self-pipe once per process (no-op on non-Unix targets).
pub fn terminal_install_sigwinch_handler() {
    #[cfg(unix)]
    {
        let _: (i32, i32) = terminal_ensure_sigwinch_pipe();
        if !TERMINAL_SIGWINCH_INSTALLED.swap(true, Ordering::AcqRel) {
            // SAFETY: `terminal_sigwinch_handler` only performs async-signal-safe atomic and non-blocking `write` operations.
            unsafe {
                let _: usize = signal(UNIX_SIGWINCH, terminal_sigwinch_handler);
            }
        }
    }
}

/// Consumes and clears any pending `SIGWINCH` resize signal notification and drains the wakeup pipe.
///
/// # Returns
///
/// - `bool` - `true` if a `SIGWINCH` signal arrived since the last check.
#[must_use]
pub fn terminal_take_sigwinch_resized() -> bool {
    #[cfg(unix)]
    {
        let read_fd: i32 = TERMINAL_SIGWINCH_PIPE_READ.load(Ordering::Acquire);
        terminal_drain_sigwinch_pipe(read_fd);
    }
    TERMINAL_SIGWINCH_FLAG.swap(false, Ordering::AcqRel)
}

/// Blocks on POSIX `poll(stdin_fd, sigwinch_pipe)` until terminal input or `SIGWINCH` arrives, consuming `0%` CPU while idle.
///
/// # Arguments
///
/// - `i32` - Poll timeout in milliseconds (`-1` for infinite kernel sleep on an interactive TTY, `>= 0` for bounded wait).
///
/// # Returns
///
/// - `bool` - `true` when input or a `SIGWINCH` wakeup became ready before timeout.
#[must_use]
pub fn terminal_wait_pty_event(timeout_ms: i32) -> bool {
    #[cfg(unix)]
    {
        let (pipe_read_fd, _): (i32, i32) = terminal_ensure_sigwinch_pipe();
        if TERMINAL_SIGWINCH_FLAG.load(Ordering::Acquire) {
            terminal_drain_sigwinch_pipe(pipe_read_fd);
            return true;
        }
        let stdin_tty: bool = terminal_fd_is_tty(UNIX_STDIN_FD);
        if !stdin_tty {
            if timeout_ms < 0 || pipe_read_fd < 0 {
                return false;
            }
            let mut pipe_pfd: UnixPollFd = UnixPollFd {
                fd: pipe_read_fd,
                events: UNIX_POLLIN,
                revents: 0,
            };
            // SAFETY: Standard POSIX `poll` over the valid non-blocking self-pipe read descriptor.
            let ready: i32 = unsafe {
                poll(
                    (&mut pipe_pfd as *mut UnixPollFd).cast::<c_void>(),
                    1,
                    timeout_ms,
                )
            };
            if (pipe_pfd.revents & UNIX_POLLIN) != 0 {
                terminal_drain_sigwinch_pipe(pipe_read_fd);
            }
            return ready > 0 || TERMINAL_SIGWINCH_FLAG.load(Ordering::Acquire);
        }
        let mut poll_fds: [UnixPollFd; 2] = [
            UnixPollFd {
                fd: UNIX_STDIN_FD,
                events: UNIX_POLLIN,
                revents: 0,
            },
            UnixPollFd {
                fd: pipe_read_fd,
                events: UNIX_POLLIN,
                revents: 0,
            },
        ];
        let fd_count: usize = if pipe_read_fd >= 0 { 2 } else { 1 };
        // SAFETY: Standard POSIX `poll` over `STDIN_FILENO` and the optional `SIGWINCH` wakeup self-pipe.
        let ready: i32 =
            unsafe { poll(poll_fds.as_mut_ptr().cast::<c_void>(), fd_count, timeout_ms) };
        if fd_count == 2 && (poll_fds[1].revents & UNIX_POLLIN) != 0 {
            terminal_drain_sigwinch_pipe(pipe_read_fd);
        }
        ready > 0 || TERMINAL_SIGWINCH_FLAG.load(Ordering::Acquire)
    }
    #[cfg(not(unix))]
    {
        let _: i32 = timeout_ms;
        TERMINAL_SIGWINCH_FLAG.load(Ordering::Acquire)
    }
}

/// Checks whether the given standard file descriptor (`0`=stdin, `1`=stdout, `2`=stderr) is attached to a TTY.
///
/// # Arguments
///
/// - `i32` - Standard stream descriptor index (`0`, `1`, or `2`).
///
/// # Returns
///
/// - `bool` - `true` when connected to a live terminal device.
#[must_use]
pub fn terminal_fd_is_tty(fd: i32) -> bool {
    #[cfg(unix)]
    {
        // SAFETY: `isatty` is safe for any integer file descriptor.
        unsafe { isatty(fd) == 1 }
    }
    #[cfg(target_os = "windows")]
    {
        let std_id: u32 = match fd {
            0 => WIN32_STD_INPUT_HANDLE,
            2 => WIN32_STD_ERROR_HANDLE,
            _ => WIN32_STD_OUTPUT_HANDLE,
        };
        // SAFETY: Queries standard Win32 handle type and console mode without mutating state.
        unsafe {
            let handle: isize = GetStdHandle(std_id);
            if handle == 0 || handle == -1 {
                return false;
            }
            if GetFileType(handle) != WIN32_FILE_TYPE_CHAR {
                return false;
            }
            let mut mode: u32 = 0;
            GetConsoleMode(handle, &mut mode) != 0
        }
    }
    #[cfg(not(any(unix, target_os = "windows")))]
    {
        let _: i32 = fd;
        false
    }
}

/// Queries live terminal `(cols, rows)` from OS PTY ioctl, Win32 console info, or `COLUMNS`/`LINES` environment variables.
///
/// # Returns
///
/// - `(u16, u16)` - Clamped `(cols, rows)` with at least `(1, 1)`.
#[must_use]
pub fn terminal_query_pty_size() -> (u16, u16) {
    #[cfg(unix)]
    {
        // SAFETY: Zero-initialized `UnixWinsize` populated by standard POSIX `TIOCGWINSZ` ioctl.
        unsafe {
            let mut ws: UnixWinsize = zeroed();
            if ioctl(UNIX_STDOUT_FD, UNIX_TIOCGWINSZ, &mut ws) == 0
                && ws.ws_col > 0
                && ws.ws_row > 0
            {
                return (ws.ws_col, ws.ws_row);
            }
            if ioctl(UNIX_STDIN_FD, UNIX_TIOCGWINSZ, &mut ws) == 0 && ws.ws_col > 0 && ws.ws_row > 0
            {
                return (ws.ws_col, ws.ws_row);
            }
        }
    }
    #[cfg(target_os = "windows")]
    {
        // SAFETY: Queries standard Win32 output handle window dimensions.
        unsafe {
            let handle: isize = GetStdHandle(WIN32_STD_OUTPUT_HANDLE);
            if handle != 0 && handle != -1 {
                let mut info: Win32ConsoleScreenBufferInfo =
                    Win32ConsoleScreenBufferInfo::default();
                if GetConsoleScreenBufferInfo(handle, &mut info) != 0 {
                    let cols: i32 =
                        i32::from(info.sr_window.right) - i32::from(info.sr_window.left) + 1;
                    let rows: i32 =
                        i32::from(info.sr_window.bottom) - i32::from(info.sr_window.top) + 1;
                    if cols > 0 && rows > 0 {
                        return (cols as u16, rows as u16);
                    }
                }
            }
        }
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        let env_cols: u16 = env::var(ENV_COLUMNS)
            .ok()
            .and_then(|text_value: String| text_value.trim().parse::<u16>().ok())
            .filter(|item_val: &u16| *item_val > 0)
            .unwrap_or(TERMINAL_DEFAULT_COLS);
        let env_rows: u16 = env::var(ENV_LINES)
            .ok()
            .and_then(|label_str: String| label_str.trim().parse::<u16>().ok())
            .filter(|tex_v: &u16| *tex_v > 0)
            .unwrap_or(TERMINAL_DEFAULT_ROWS);
        (env_cols, env_rows)
    }
    #[cfg(target_arch = "wasm32")]
    {
        (TERMINAL_DEFAULT_COLS, TERMINAL_DEFAULT_ROWS)
    }
}

/// Probes host TTY attachment, `NO_COLOR` / `COLORTERM` / `TERM` capabilities, and live PTY dimensions.
///
/// # Returns
///
/// - `TerminalTtyProbe` - Normalized terminal environment probe.
#[must_use]
pub fn terminal_probe_tty() -> TerminalTtyProbe {
    let stdin_tty: bool = terminal_fd_is_tty(UNIX_STDIN_FD);
    let stdout_tty: bool = terminal_fd_is_tty(UNIX_STDOUT_FD);
    let stderr_tty: bool = terminal_fd_is_tty(UNIX_STDERR_FD);
    let (cols, rows): (u16, u16) = terminal_query_pty_size();
    #[cfg(not(target_arch = "wasm32"))]
    let (no_color, color): (bool, TerminalColorCapability) = {
        let no_col: bool = env::var(ENV_NO_COLOR).is_ok();
        let term_val: String = env::var(ENV_TERM).unwrap_or_default().to_ascii_lowercase();
        let colorterm_val: String = env::var(ENV_COLORTERM)
            .unwrap_or_default()
            .to_ascii_lowercase();
        let cap: TerminalColorCapability = if !stdout_tty || term_val == TERM_VAL_DUMB || no_col {
            TerminalColorCapability::None
        } else if colorterm_val.contains(TERM_VAL_TRUECOLOR)
            || colorterm_val.contains(TERM_VAL_24BIT)
        {
            TerminalColorCapability::TrueColor
        } else if term_val.contains(TERM_VAL_256COLOR) {
            TerminalColorCapability::Ansi256
        } else {
            TerminalColorCapability::Ansi16
        };
        (no_col, cap)
    };
    #[cfg(target_arch = "wasm32")]
    let (no_color, color): (bool, TerminalColorCapability) = (true, TerminalColorCapability::None);
    TerminalTtyProbe::new(
        stdin_tty, stdout_tty, stderr_tty, color, no_color, cols, rows,
    )
}

#[cfg(unix)]
/// Enters POSIX raw terminal mode on `STDIN_FILENO` and returns the original `UnixTermios` for RAII restoration.
///
/// # Returns
///
/// - `Option<UnixTermios>` - Original terminal attributes when raw mode was activated.
pub(crate) fn terminal_unix_enter_raw_mode() -> Option<UnixTermios> {
    if !terminal_fd_is_tty(UNIX_STDIN_FD) {
        return None;
    }
    // SAFETY: Queries and updates POSIX `termios` on live TTY `STDIN_FILENO`.
    unsafe {
        let mut orig: UnixTermios = zeroed();
        if tcgetattr(UNIX_STDIN_FD, &mut orig) != 0 {
            return None;
        }
        let mut raw: UnixTermios = orig;
        raw.c_iflag &= !UNIX_TERMIOS_IFLAG_RAW_MASK;
        raw.c_oflag &= !UNIX_TERMIOS_OFLAG_OPOST;
        raw.c_cflag |= UNIX_TERMIOS_CFLAG_CS8;
        raw.c_lflag &= !UNIX_TERMIOS_LFLAG_RAW_MASK;
        raw.c_cc[UNIX_TERMIOS_VMIN_IDX] = 0;
        raw.c_cc[UNIX_TERMIOS_VTIME_IDX] = 0;
        if tcsetattr(UNIX_STDIN_FD, UNIX_TCSANOW, &raw) != 0 {
            return None;
        }
        Some(orig)
    }
}

#[cfg(unix)]
/// Restores previously saved POSIX `termios` attributes on `STDIN_FILENO`.
///
/// # Arguments
///
/// - `&UnixTermios` - Saved original `termios` structure.
pub(crate) fn terminal_unix_restore_raw_mode(orig: &UnixTermios) {
    // SAFETY: Restores valid `UnixTermios` previously returned by `tcgetattr`.
    unsafe {
        let _: i32 = tcsetattr(UNIX_STDIN_FD, UNIX_TCSANOW, orig);
    }
}

#[cfg(target_os = "windows")]
/// Enables Win32 Console VT input and output processing, returning original `(stdin_mode, stdout_mode)`.
///
/// # Returns
///
/// - `Option<(u32, u32)>` - Saved console modes on success.
pub(crate) fn terminal_win32_enter_vt_mode() -> Option<(u32, u32)> {
    // SAFETY: Queries and sets Win32 console modes on standard input/output handles.
    unsafe {
        let h_in: isize = GetStdHandle(WIN32_STD_INPUT_HANDLE);
        let h_out: isize = GetStdHandle(WIN32_STD_OUTPUT_HANDLE);
        if h_in == 0 || h_in == -1 || h_out == 0 || h_out == -1 {
            return None;
        }
        let mut orig_in: u32 = 0;
        let mut orig_out: u32 = 0;
        if GetConsoleMode(h_in, &mut orig_in) == 0 || GetConsoleMode(h_out, &mut orig_out) == 0 {
            return None;
        }
        let clear_mask: u32 =
            WIN32_ENABLE_LINE_INPUT + WIN32_ENABLE_ECHO_INPUT + WIN32_ENABLE_PROCESSED_INPUT;
        let enable_mask: u32 = WIN32_ENABLE_VIRTUAL_TERMINAL_INPUT
            + WIN32_ENABLE_WINDOW_INPUT
            + WIN32_ENABLE_MOUSE_INPUT;
        let raw_in: u32 = (orig_in & !clear_mask) | enable_mask;
        let raw_out: u32 = orig_out | WIN32_ENABLE_VIRTUAL_TERMINAL_PROCESSING;
        let _: i32 = SetConsoleMode(h_in, raw_in);
        let _: i32 = SetConsoleMode(h_out, raw_out);
        Some((orig_in, orig_out))
    }
}

#[cfg(target_os = "windows")]
/// Restores previously saved Win32 console input/output mode bitmasks.
///
/// # Arguments
///
/// - `(u32, u32)` - Saved `(stdin_mode, stdout_mode)` pair.
pub(crate) fn terminal_win32_restore_vt_mode(modes: (u32, u32)) {
    // SAFETY: Restores saved standard console modes.
    unsafe {
        let h_in: isize = GetStdHandle(WIN32_STD_INPUT_HANDLE);
        let h_out: isize = GetStdHandle(WIN32_STD_OUTPUT_HANDLE);
        if h_in != 0 && h_in != -1 {
            let _: i32 = SetConsoleMode(h_in, modes.0);
        }
        if h_out != 0 && h_out != -1 {
            let _: i32 = SetConsoleMode(h_out, modes.1);
        }
    }
}

/// Non-blockingly reads available raw input bytes from the attached PTY (`STDIN_FILENO` on Unix).
///
/// # Arguments
///
/// - `i32` - Poll timeout in milliseconds (`0` for immediate non-blocking poll).
///
/// # Returns
///
/// - `Vec<u8>` - Raw bytes read from the terminal input stream (empty when no input ready).
#[must_use]
pub fn terminal_read_pty_bytes(timeout_ms: i32) -> Vec<u8> {
    #[cfg(unix)]
    {
        if !terminal_fd_is_tty(UNIX_STDIN_FD) {
            return Vec::new();
        }
        let mut pfd: UnixPollFd = UnixPollFd {
            fd: UNIX_STDIN_FD,
            events: UNIX_POLLIN,
            revents: 0,
        };
        // SAFETY: Standard non-blocking POSIX `poll` and `read` on `STDIN_FILENO`.
        unsafe {
            let ready: i32 = poll(
                (&mut pfd as *mut UnixPollFd).cast::<c_void>(),
                1,
                timeout_ms.max(0),
            );
            if ready <= 0 || (pfd.revents & UNIX_POLLIN) == 0 {
                return Vec::new();
            }
            let mut buf: [u8; 256] = [0; 256];
            let item_count: isize =
                read(UNIX_STDIN_FD, buf.as_mut_ptr().cast::<c_void>(), buf.len());
            if item_count > 0 {
                buf[..(item_count as usize)].to_vec()
            } else {
                Vec::new()
            }
        }
    }
    #[cfg(not(unix))]
    {
        let _: i32 = timeout_ms;
        Vec::new()
    }
}

/// Writes raw UTF-8 bytes directly to OS `stdout` or `stderr`, reporting broken pipe cleanly without panicking.
///
/// # Arguments
///
/// - `TerminalStreamKind` - Destination standard stream (`Stdout` or `Stderr`).
/// - `&[u8]` - Bytes to flush.
///
/// # Returns
///
/// - `Result<bool, PlatformError>` - `Ok(true)` if written, `Ok(false)` on broken pipe, or `Err` on I/O error.
pub(crate) fn terminal_write_os_stream(
    stream: TerminalStreamKind,
    bytes: &[u8],
) -> Result<bool, PlatformError> {
    #[cfg(not(target_arch = "wasm32"))]
    {
        let write_res: io::Result<()> = match stream {
            TerminalStreamKind::Stdout => {
                let mut handle: io::StdoutLock<'_> = stdout().lock();
                handle.write_all(bytes).and_then(|_: ()| handle.flush())
            }
            TerminalStreamKind::Stderr => {
                let mut handle: io::StderrLock<'_> = stderr().lock();
                handle.write_all(bytes).and_then(|_: ()| handle.flush())
            }
        };
        match write_res {
            Ok(()) => Ok(true),
            Err(err) if err.kind() == ErrorKind::BrokenPipe => Ok(false),
            Err(_) => Err(PlatformError::SurfaceError(
                ERR_TERMINAL_IO_WRITE.to_string(),
            )),
        }
    }
    #[cfg(target_arch = "wasm32")]
    {
        let _: (TerminalStreamKind, &[u8]) = (stream, bytes);
        Ok(true)
    }
}

/// Decodes xterm CSI modifier parameter `(1 + bitmask)` into platform-neutral `Modifiers`.
///
/// # Arguments
///
/// - `u32` - CSI numeric modifier parameter (e.g. `2`=Shift, `3`=Alt, `5`=Ctrl, `6`=Shift+Ctrl).
///
/// # Returns
///
/// - `Modifiers` - Decoded modifier bit flags.
#[must_use]
pub(crate) fn terminal_decode_csi_modifiers(param: u32) -> Modifiers {
    let bits: u32 = param.saturating_sub(1);
    Modifiers::new(
        (bits & 1) != 0,
        (bits & 4) != 0,
        (bits & 2) != 0,
        (bits & 8) != 0,
    )
}

/// Parses an SGR 1006 mouse sequence payload (`btn;col;row` + final `'M'` or `'m'`) into a `WindowEvent`.
///
/// # Arguments
///
/// - `WindowId` - Target terminal window identifier.
/// - `&str` - Semicolon-delimited SGR numeric parameters (`"0;12;5"`).
/// - `bool` - `true` when terminated by `'M'` (press/motion/wheel), `false` when terminated by `'m'` (release).
/// - `f32` - Logical cell width in pixels.
/// - `f32` - Logical cell height in pixels.
///
/// # Returns
///
/// - `Option<WindowEvent>` - Translated pointer or scroll event.
#[must_use]
pub(crate) fn terminal_parse_sgr_mouse(
    wid: WindowId,
    params: &str,
    pressed: bool,
    cell_w: f32,
    cell_h: f32,
) -> Option<WindowEvent> {
    let mut parts: Vec<u32> = Vec::with_capacity(3);
    for token in params.split(';') {
        if let Ok(val) = token.parse::<u32>() {
            parts.push(val);
        }
    }
    if parts.len() < 3 {
        return None;
    }
    let code: u32 = parts[0];
    let col: u32 = parts[1].saturating_sub(1);
    let row: u32 = parts[2].saturating_sub(1);
    let pos: Point = Point::new(
        ((col as f32) + 0.5) * cell_w.max(1.0),
        ((row as f32) + 0.5) * cell_h.max(1.0),
    );
    let mods: Modifiers = Modifiers::new((code & 4) != 0, (code & 16) != 0, (code & 8) != 0, false);
    if (code & 64) != 0 {
        let dir: f32 = if (code & 1) == 0 {
            -TERMINAL_WHEEL_SCROLL_STEP_PX
        } else {
            TERMINAL_WHEEL_SCROLL_STEP_PX
        };
        let delta: Point = if mods.get_shift() {
            Point::new(dir, 0.0)
        } else {
            Point::new(0.0, dir)
        };
        return Some(WindowEvent::Scroll(wid, delta));
    }
    let button: PointerButton = match code & 3 {
        1 => PointerButton::Auxiliary,
        2 => PointerButton::Secondary,
        _ => PointerButton::Primary,
    };
    let is_motion: bool = (code & 32) != 0;
    let point_coords: PointerEvent = PointerEvent::new(
        1,
        PointerDevice::Mouse,
        pos,
        button,
        if pressed { 1.0 } else { 0.0 },
        mods,
    );
    if is_motion {
        Some(WindowEvent::PointerMove(wid, point_coords))
    } else if pressed {
        Some(WindowEvent::PointerDown(wid, point_coords))
    } else {
        Some(WindowEvent::PointerUp(wid, point_coords))
    }
}

/// Finds the starting byte offset of `needle` inside `haystack`.
///
/// # Arguments
///
/// - `&[u8]` - Byte slice to search.
/// - `&[u8]` - Subslice pattern to find.
///
/// # Returns
///
/// - `Option<usize>` - First matching byte index, if found.
#[must_use]
pub(crate) fn terminal_find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || haystack.len() < needle.len() {
        return None;
    }
    haystack
        .windows(needle.len())
        .position(|window: &[u8]| window == needle)
}