euv-core 0.46.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
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 UnixPollFd` - 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 UnixPollFd, 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;
}

#[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)]
/// Async-signal-safe `SIGWINCH` signal handler marking the global terminal resize flag.
///
/// # Arguments
///
/// - `i32` - Delivered POSIX signal number.
extern "C" fn terminal_sigwinch_handler(_sig: i32) {
    TERMINAL_SIGWINCH_FLAG.store(true, Ordering::Release);
}

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

/// Consumes and clears any pending `SIGWINCH` resize signal notification.
///
/// # Returns
///
/// - `bool` - `true` if a `SIGWINCH` signal arrived since the last check.
#[must_use]
pub fn terminal_take_sigwinch_resized() -> bool {
    TERMINAL_SIGWINCH_FLAG.swap(false, Ordering::AcqRel)
}

/// 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(|v: String| v.trim().parse::<u16>().ok())
            .filter(|v: &u16| *v > 0)
            .unwrap_or(TERMINAL_DEFAULT_COLS);
        let env_rows: u16 = env::var(ENV_LINES)
            .ok()
            .and_then(|v: String| v.trim().parse::<u16>().ok())
            .filter(|v: &u16| *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, 1, timeout_ms.max(0));
            if ready <= 0 || (pfd.revents & UNIX_POLLIN) == 0 {
                return Vec::new();
            }
            let mut buf: [u8; 256] = [0; 256];
            let n: isize = read(UNIX_STDIN_FD, buf.as_mut_ptr().cast::<c_void>(), buf.len());
            if n > 0 {
                buf[..(n 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 ev: PointerEvent = PointerEvent::new(
        1,
        PointerDevice::Mouse,
        pos,
        button,
        if pressed { 1.0 } else { 0.0 },
        mods,
    );
    if is_motion {
        Some(WindowEvent::PointerMove(wid, ev))
    } else if pressed {
        Some(WindowEvent::PointerDown(wid, ev))
    } else {
        Some(WindowEvent::PointerUp(wid, ev))
    }
}

/// 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)
}