rio-vt 0.5.28

Embeddable terminal core extracted from Rio: VT state machine, grid, PTY driver, selection, search
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
//! Typed parsing helpers for OSC (Operating System Command) sequences.
//!
//! The Williams parser hands the dispatcher a `&[&[u8]]` of separator-split
//! parameter slices. Each helper here takes those raw slices and returns a
//! typed result for the corresponding OSC command, leaving the dispatcher in
//! `handler.rs` as a thin glue layer.

use std::str::FromStr;

use cursor_icon::CursorIcon;

use crate::ansi::CursorShape;
use crate::config::colors::{ColorRgb, NamedColor};
use crate::crosswords::square::Hyperlink;
use crate::event::{ProgressReport, ProgressState};
use crate::simd_utf8;

/// Either a concrete color value or a query for the current value.
pub(super) enum ColorSpec {
    Set(ColorRgb),
    Query,
}

pub(super) struct PaletteEntry {
    pub index: u8,
    pub spec: ColorSpec,
}

pub(super) struct DynamicColorEntry {
    pub index: NamedColor,
    pub dynamic_code: u16,
    pub spec: ColorSpec,
}

pub(super) enum ClipboardOp<'a> {
    Load { kind: u8 },
    Store { kind: u8, payload: &'a [u8] },
}

pub(super) enum PaletteReset {
    All,
    Indices(Vec<u8>),
}

/// Parse an OSC 133 semantic prompt sequence into the row mark it
/// should set, if any. `A` and `P` mark the cursor row as a prompt
/// (`P;k=c` / `P;k=s` as a continuation); the remaining subcommands
/// (`B`, `C`, `D`, `I`, `L`, `N`) and all `key=value` options are
/// accepted and ignored, matching the spec's leniency.
pub(super) fn parse_semantic_prompt(
    params: &[&[u8]],
) -> Option<crate::crosswords::grid::row::SemanticPrompt> {
    use crate::crosswords::grid::row::SemanticPrompt;

    let subcommand = *params.get(1)?.first()?;
    match subcommand {
        b'A' => Some(SemanticPrompt::Prompt),
        b'P' => {
            for option in &params[2..] {
                if let Some(kind) = option.strip_prefix(b"k=") {
                    if kind == b"c" || kind == b"s" {
                        return Some(SemanticPrompt::PromptContinuation);
                    }
                }
            }
            Some(SemanticPrompt::Prompt)
        }
        _ => None,
    }
}

/// Parse `OSC 1337 ; SetUserVar=name=<base64 value>`. The value is
/// base64 per iTerm2's spec; anything undecodable is dropped.
pub(super) fn parse_set_user_var(params: &[&[u8]]) -> Option<(String, String)> {
    let payload = params.get(1)?.strip_prefix(b"SetUserVar=")?;
    let mut parts = payload.splitn(2, |byte| *byte == b'=');
    let name = simd_utf8::from_utf8_fast(parts.next()?).ok()?;
    if name.is_empty() {
        return None;
    }
    let encoded = parts.next()?;
    let decoded = crate::simd_base64::decode(encoded)?;
    let value = String::from_utf8(decoded).ok()?;
    Some((name.to_string(), value))
}

/// Parse an `xterm`-style color value (`#rgb`, `#rrggbb`, `rgb:r/g/b`).
pub(super) fn xparse_color(color: &[u8]) -> Option<ColorRgb> {
    if !color.is_empty() && color[0] == b'#' {
        parse_legacy_color(&color[1..])
    } else if color.len() >= 4 && &color[..4] == b"rgb:" {
        parse_rgb_color(&color[4..])
    } else {
        None
    }
}

/// Parse colors in `rgb:r(rrr)/g(ggg)/b(bbb)` format.
fn parse_rgb_color(color: &[u8]) -> Option<ColorRgb> {
    let colors = simd_utf8::from_utf8_fast(color)
        .ok()?
        .split('/')
        .collect::<Vec<_>>();

    if colors.len() != 3 {
        return None;
    }

    // Scale values instead of filling with `0`s.
    let scale = |input: &str| {
        if input.len() > 4 {
            None
        } else {
            let max = u32::pow(16, input.len() as u32) - 1;
            let value = u32::from_str_radix(input, 16).ok()?;
            Some((255 * value / max) as u8)
        }
    };

    Some(ColorRgb {
        r: scale(colors[0])?,
        g: scale(colors[1])?,
        b: scale(colors[2])?,
    })
}

/// Parse colors in `#r(rrr)g(ggg)b(bbb)` format.
fn parse_legacy_color(color: &[u8]) -> Option<ColorRgb> {
    let item_len = color.len() / 3;

    // Truncate/Fill to two byte precision.
    let color_from_slice = |slice: &[u8]| {
        let col =
            usize::from_str_radix(simd_utf8::from_utf8_fast(slice).ok()?, 16).ok()? << 4;
        Some((col >> (4 * slice.len().saturating_sub(1))) as u8)
    };

    Some(ColorRgb {
        r: color_from_slice(&color[0..item_len])?,
        g: color_from_slice(&color[item_len..item_len * 2])?,
        b: color_from_slice(&color[item_len * 2..])?,
    })
}

pub(super) fn parse_number(input: &[u8]) -> Option<u8> {
    if input.is_empty() {
        return None;
    }
    let mut num: u8 = 0;
    for c in input {
        let c = *c as char;
        if let Some(digit) = c.to_digit(10) {
            num = num
                .checked_mul(10)
                .and_then(|v| v.checked_add(digit as u8))?
        } else {
            return None;
        }
    }
    Some(num)
}

/// OSC 0 / OSC 2: window title set as `;`-joined params.
pub(super) fn parse_title(params: &[&[u8]]) -> Option<String> {
    if params.len() < 2 {
        return None;
    }
    Some(
        params[1..]
            .iter()
            .flat_map(|x| simd_utf8::from_utf8_fast(x))
            .collect::<Vec<&str>>()
            .join(";")
            .trim()
            .to_owned(),
    )
}

/// OSC 4: a list of `(index, color | "?")` pairs in `params[1..]`.
pub(super) fn parse_palette_entries(params: &[&[u8]]) -> Option<Vec<PaletteEntry>> {
    if params.len() <= 1 || params.len().is_multiple_of(2) {
        return None;
    }

    let mut out = Vec::with_capacity(params.len() / 2);
    for chunk in params[1..].chunks(2) {
        let index = parse_number(chunk[0])?;
        let spec = if chunk[1] == b"?" {
            ColorSpec::Query
        } else {
            ColorSpec::Set(xparse_color(chunk[1])?)
        };
        out.push(PaletteEntry { index, spec });
    }
    Some(out)
}

/// The URL schemes rio-vt ever parses, both OSC 7 working-directory
/// carriers: RFC 8089 file URLs and the `kitty-shell-cwd` scheme
/// (a raw, unencoded path) that kitty defined and several shell
/// integrations emit.
const FILE_SCHEME: &str = "file://";
const KITTY_SHELL_CWD_SCHEME: &str = "kitty-shell-cwd://";

/// Strip `scheme` from the front of `s`, case-insensitively.
fn strip_scheme<'a>(s: &'a str, scheme: &str) -> Option<&'a str> {
    s.get(..scheme.len())
        .filter(|prefix| prefix.eq_ignore_ascii_case(scheme))
        .map(|_| &s[scheme.len()..])
}

/// OSC 7: working directory as a `file://` URL (percent-encoded path)
/// or a `kitty-shell-cwd://` payload (raw path, no encoding). Parsed
/// by hand rather than with a URL crate: these are the only URLs the
/// terminal core looks at, and a general parser costs an IDNA/Unicode
/// stack just to reach `.path()`.
///
/// Anything on the other end of the PTY can send this, including a shell on the
/// far side of an ssh session, so a directory that belongs to another machine is
/// refused rather than reported as ours.
pub(super) fn parse_current_directory(param: &[u8]) -> Option<String> {
    let s = simd_utf8::from_utf8_fast(param).ok()?;

    let (after_scheme, percent_encoded) = match strip_scheme(s, FILE_SCHEME) {
        Some(rest) => (rest, true),
        None => (strip_scheme(s, KITTY_SHELL_CWD_SCHEME)?, false),
    };

    // The path begins at the host's trailing slash. A payload with no path at
    // all leaves nothing to report.
    let path_start = after_scheme.find('/')?;
    let host = &after_scheme[..path_start];
    let path = &after_scheme[path_start..];

    if !host_is_local(host) {
        tracing::warn!("ignoring OSC 7 for non-local host {host:?}");
        return None;
    }

    // Windows paths arrive as `/C:/...` in both flavors; drop the
    // leading slash.
    #[cfg(windows)]
    let path = path.strip_prefix('/').unwrap_or(path);

    if !percent_encoded {
        // The kitty flavor is the path verbatim: `?`, `#` and `%` are
        // path bytes, not URL syntax.
        return Some(path.to_string());
    }

    // A query or fragment is not part of the path.
    let path = &path[..path.find(['?', '#']).unwrap_or(path.len())];

    percent_decode(path)
}

/// Whether an OSC 7 host names this machine.
///
/// An empty host is this machine by definition (RFC 8089), which is also the
/// form shells produce from a bare `file://$PWD`.
fn host_is_local(host: &str) -> bool {
    // Tolerate the FQDN root dot.
    let host = host.strip_suffix('.').unwrap_or(host);

    if host.is_empty() || host.eq_ignore_ascii_case("localhost") {
        return true;
    }

    match local_hostname() {
        Some(local) => host.eq_ignore_ascii_case(&local),
        // With no hostname to compare against, take the shell at its word
        // rather than dropping the directory outright.
        None => true,
    }
}

/// This machine's hostname, read per check: one syscall, where a
/// process-lifetime cache would keep rejecting a shell's cwd reports
/// after the hostname changes mid-session (macOS mDNS renames).
fn local_hostname() -> Option<String> {
    read_hostname()
}

#[cfg(unix)]
fn read_hostname() -> Option<String> {
    // `_POSIX_HOST_NAME_MAX` is 255; the extra byte is for the terminator,
    // which a truncating implementation is not required to write.
    let mut buffer = [0_u8; 256];
    // SAFETY: writing at most `buffer.len()` bytes into a buffer of that size.
    let result = unsafe {
        libc::gethostname(buffer.as_mut_ptr() as *mut libc::c_char, buffer.len())
    };
    if result != 0 {
        return None;
    }

    let end = buffer.iter().position(|byte| *byte == 0)?;
    std::str::from_utf8(&buffer[..end])
        .ok()
        .filter(|hostname| !hostname.is_empty())
        .map(str::to_owned)
}

#[cfg(not(unix))]
fn read_hostname() -> Option<String> {
    // No lookup here, so `host_is_local` falls back to accepting the payload,
    // which is what rio did on every platform before.
    None
}

/// Percent-decode a URL path. Invalid escapes are passed through as written,
/// which is friendlier than dropping the directory over one stray `%`.
fn percent_decode(path: &str) -> Option<String> {
    if !path.contains('%') {
        return Some(path.to_owned());
    }

    let bytes = path.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        // Only `%` followed by two hex digits is an escape. `from_str_radix`
        // would accept a leading `+` here, decoding `%+A` to a byte.
        let escape = (bytes[index] == b'%')
            .then(|| {
                let hex = bytes.get(index + 1..index + 3)?;
                let high = (hex[0] as char).to_digit(16)?;
                let low = (hex[1] as char).to_digit(16)?;
                Some((high * 16 + low) as u8)
            })
            .flatten();

        match escape {
            Some(byte) => {
                out.push(byte);
                index += 3;
            }
            None => {
                out.push(bytes[index]);
                index += 1;
            }
        }
    }

    String::from_utf8(out).ok()
}

/// OSC 8: extract `id=...` from `key=val:key=val` link params.
pub(super) fn parse_hyperlink_id(link_params: &[u8]) -> Option<&str> {
    link_params
        .split(|&b| b == b':')
        .find_map(|kv| kv.strip_prefix(b"id="))
        .and_then(|kv| simd_utf8::from_utf8_fast(kv).ok())
}

/// Construct a [`Hyperlink`] from the link params + URI bytes. Returns
/// `None` for an empty URI (caller should clear the active hyperlink).
pub(super) fn parse_hyperlink(link_params: &[u8], uri_param: &[u8]) -> Option<Hyperlink> {
    let uri = simd_utf8::from_utf8_fast(uri_param).unwrap_or_default();
    if uri.is_empty() {
        return None;
    }
    Some(Hyperlink::new(parse_hyperlink_id(link_params), uri))
}

/// OSC 9;4 — ConEmu/Windows-Terminal progress reporting.
/// Format: `9;4;<state>;<progress>` (progress optional).
pub(super) fn parse_progress_report(params: &[&[u8]]) -> Option<ProgressReport> {
    if params.len() < 3 || params[1] != b"4" {
        return None;
    }
    let state = match params[2] {
        b"0" => ProgressState::Remove,
        b"1" => ProgressState::Set,
        b"2" => ProgressState::Error,
        b"3" => ProgressState::Indeterminate,
        b"4" => ProgressState::Pause,
        _ => return None,
    };
    let progress = if params.len() >= 4 {
        parse_number(params[3]).map(|p| p.min(100))
    } else {
        None
    };
    Some(ProgressReport { state, progress })
}

/// Rejoin `params[from..]` with the `;` the OSC parser split on, so a
/// payload defined as verbatim text survives a `;` inside it.
pub(super) fn join_params(params: &[&[u8]], from: usize) -> Option<String> {
    Some(
        params
            .get(from..)?
            .iter()
            .map(|param| simd_utf8::from_utf8_fast(param).ok())
            .collect::<Option<Vec<_>>>()?
            .join(";"),
    )
}

/// OSC 9;9: ConEmu/Windows-Terminal working directory report, the
/// Windows counterpart of OSC 7. Format: `9;9;<path>`, with the path
/// optionally wrapped in double quotes and travelling verbatim (no URL
/// encoding), so everything after `9;9;` is rejoined.
///
/// The sequence carries no host field, so unlike OSC 7 a remote shell
/// cannot be told apart from a local one (ConEmu and Windows Terminal
/// accept the same). Requiring an absolute path at least drops
/// free-text payloads and relative garbage.
pub(super) fn parse_conemu_working_directory(params: &[&[u8]]) -> Option<String> {
    if params.len() < 3 || params[1] != b"9" {
        return None;
    }
    let path = join_params(params, 2)?;
    let path = path
        .strip_prefix('"')
        .and_then(|p| p.strip_suffix('"'))
        .unwrap_or(&path);
    if !is_absolute_path(path) {
        return None;
    }
    Some(path.to_string())
}

/// Whether `path` is absolute in either flavor a cwd report can carry:
/// a POSIX `/` root or a Windows drive-letter root. UNC (`\\server`)
/// is refused: it names another machine, which the host-checked OSC 7
/// flavors refuse too.
fn is_absolute_path(path: &str) -> bool {
    if path.starts_with('/') {
        return true;
    }
    let bytes = path.as_bytes();
    bytes.len() >= 3
        && bytes[0].is_ascii_alphabetic()
        && bytes[1] == b':'
        && (bytes[2] == b'\\' || bytes[2] == b'/')
}

/// OSC 10/11/12: dynamic color set/query, applied to consecutive named
/// colors starting at `dynamic_code - 10`.
pub(super) fn parse_dynamic_colors(params: &[&[u8]]) -> Option<Vec<DynamicColorEntry>> {
    if params.len() < 2 {
        return None;
    }
    let base_code = parse_number(params[0])? as u16;
    let mut out = Vec::with_capacity(params.len() - 1);
    for (dynamic_code, param) in (base_code..).zip(params[1..].iter()) {
        // 10 is the first dynamic color (foreground).
        let offset = (dynamic_code as usize).checked_sub(10)?;
        let index_usize = NamedColor::Foreground as usize + offset;
        if index_usize > NamedColor::Cursor as usize {
            return None;
        }
        let index = match offset {
            0 => NamedColor::Foreground,
            1 => NamedColor::Background,
            2 => NamedColor::Cursor,
            _ => return None,
        };
        let spec = if *param == b"?" {
            ColorSpec::Query
        } else if let Some(c) = xparse_color(param) {
            ColorSpec::Set(c)
        } else {
            return None;
        };
        out.push(DynamicColorEntry {
            index,
            dynamic_code,
            spec,
        });
    }
    Some(out)
}

/// OSC 22: mouse cursor icon name.
pub(super) fn parse_mouse_cursor_icon(param: &[u8]) -> Option<CursorIcon> {
    let shape = simd_utf8::from_utf8_lossy_fast(param);
    CursorIcon::from_str(&shape).ok()
}

/// OSC 50: `CursorShape=N` text cursor selector.
pub(super) fn parse_cursor_shape(params: &[&[u8]]) -> Option<CursorShape> {
    if params.len() < 2 || params[1].len() < 13 || params[1][0..12] != *b"CursorShape=" {
        return None;
    }
    match params[1][12] as char {
        '0' => Some(CursorShape::Block),
        '1' => Some(CursorShape::Beam),
        '2' => Some(CursorShape::Underline),
        _ => None,
    }
}

/// OSC 52: clipboard load (`?`) or store (base64 payload).
pub(super) fn parse_clipboard<'a>(params: &[&'a [u8]]) -> Option<ClipboardOp<'a>> {
    if params.len() < 3 {
        return None;
    }
    let kind = *params[1].first().unwrap_or(&b'c');
    Some(if params[2] == b"?" {
        ClipboardOp::Load { kind }
    } else {
        ClipboardOp::Store {
            kind,
            payload: params[2],
        }
    })
}

/// OSC 104: reset palette colors. Empty/omitted parameter list means "all".
pub(super) fn parse_palette_reset(params: &[&[u8]]) -> PaletteReset {
    if params.len() == 1 || params[1].is_empty() {
        return PaletteReset::All;
    }
    let indices = params[1..].iter().filter_map(|p| parse_number(p)).collect();
    PaletteReset::Indices(indices)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cwd(payload: &str) -> Option<String> {
        parse_current_directory(payload.as_bytes())
    }

    #[cfg(not(windows))]
    #[test]
    fn current_directory_from_file_url() {
        // Empty host is the common shape; a named host is informational.
        assert_eq!(cwd("file:///home/user"), Some("/home/user".into()));
        assert_eq!(cwd("file://localhost/home/user"), Some("/home/user".into()));
        assert_eq!(cwd("file:///"), Some("/".into()));

        // Schemes are case-insensitive.
        assert_eq!(cwd("FILE:///home/user"), Some("/home/user".into()));
    }

    #[cfg(windows)]
    #[test]
    fn current_directory_strips_windows_leading_slash() {
        assert_eq!(cwd("file:///C:/Users/user"), Some("C:/Users/user".into()));
    }

    #[cfg(unix)]
    #[test]
    fn current_directory_accepts_local_hosts() {
        // Empty host means this machine (RFC 8089), as does localhost.
        assert_eq!(cwd("file:///tmp"), Some("/tmp".into()));
        assert_eq!(cwd("file://localhost/tmp"), Some("/tmp".into()));
        assert_eq!(cwd("file://LOCALHOST/tmp"), Some("/tmp".into()));

        // Our own hostname, as sent by a local shell, in either case and with
        // the FQDN root dot.
        let local = local_hostname().expect("hostname");
        assert_eq!(cwd(&format!("file://{local}/tmp")), Some("/tmp".into()));
        assert_eq!(
            cwd(&format!("file://{}/tmp", local.to_uppercase())),
            Some("/tmp".into())
        );
        assert_eq!(cwd(&format!("file://{local}./tmp")), Some("/tmp".into()));
    }

    #[cfg(unix)]
    #[test]
    fn current_directory_rejects_remote_hosts() {
        // A shell on the far side of an ssh session must not move our cwd.
        assert_eq!(cwd("file://not-this-machine.invalid/tmp"), None);
    }

    #[test]
    fn current_directory_rejects_non_file_payloads() {
        // Another scheme is not a working directory, and a bare path has no
        // scheme to speak of.
        assert_eq!(cwd("http://example.com/home/user"), None);
        assert_eq!(cwd("/home/user"), None);
        assert_eq!(cwd(""), None);

        // No path component at all.
        assert_eq!(cwd("file://localhost"), None);
        assert_eq!(cwd("kitty-shell-cwd://localhost"), None);
    }

    #[test]
    fn conemu_working_directory() {
        let parse = parse_conemu_working_directory;
        assert_eq!(
            parse(&[b"9", b"9", b"C:\\Users\\rapha"]),
            Some("C:\\Users\\rapha".into())
        );
        // Windows Terminal profiles commonly quote the path.
        assert_eq!(
            parse(&[b"9", b"9", b"\"C:\\Program Files\""]),
            Some("C:\\Program Files".into())
        );
        // A `;` in the path arrives as extra params and is rejoined.
        assert_eq!(parse(&[b"9", b"9", b"C:\\a", b"b"]), Some("C:\\a;b".into()));

        // Progress reports and notifications are not directories.
        assert_eq!(parse(&[b"9", b"4", b"1", b"50"]), None);
        assert_eq!(parse(&[b"9", b"hello"]), None);
        assert_eq!(parse(&[b"9", b"9", b""]), None);
        assert_eq!(parse(&[b"9", b"9", b"\"\""]), None);

        // Only absolute paths: free text and relative paths are not a
        // cwd, and UNC names another machine like a remote OSC 7 host.
        assert_eq!(parse(&[b"9", b"9", b"Meeting at 5"]), None);
        assert_eq!(parse(&[b"9", b"9", b"..\\up"]), None);
        assert_eq!(parse(&[b"9", b"9", b"\\\\server\\share"]), None);
        assert_eq!(
            parse(&[b"9", b"9", b"/home/user"]),
            Some("/home/user".into())
        );
    }

    #[test]
    fn join_params_restores_split_semicolons() {
        assert_eq!(
            join_params(&[b"7", b"kitty-shell-cwd://h/tmp/a", b"b"], 1),
            Some("kitty-shell-cwd://h/tmp/a;b".into())
        );
        assert_eq!(join_params(&[b"7", b"x"], 1), Some("x".into()));
        assert_eq!(join_params(&[b"7"], 1), Some(String::new()));
    }

    #[cfg(not(windows))]
    #[test]
    fn current_directory_accepts_kitty_shell_cwd() {
        assert_eq!(
            cwd("kitty-shell-cwd:///home/user"),
            Some("/home/user".into())
        );
        assert_eq!(
            cwd("kitty-shell-cwd://localhost/home/user"),
            Some("/home/user".into())
        );
        // Scheme is case-insensitive, like file://.
        assert_eq!(
            cwd("KITTY-SHELL-CWD:///home/user"),
            Some("/home/user".into())
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn kitty_shell_cwd_keeps_semicolons_after_rejoin() {
        // The handler rejoins split params before calling the parser.
        let payload = join_params(&[b"7", b"kitty-shell-cwd:///tmp/a", b"b"], 1).unwrap();
        assert_eq!(cwd(&payload), Some("/tmp/a;b".into()));
    }

    #[cfg(not(windows))]
    #[test]
    fn kitty_shell_cwd_is_verbatim() {
        // Raw spaces pass through, and percent sequences are path
        // bytes rather than encodings.
        assert_eq!(cwd("kitty-shell-cwd:///tmp/a b"), Some("/tmp/a b".into()));
        assert_eq!(
            cwd("kitty-shell-cwd:///tmp/50%25 off?really"),
            Some("/tmp/50%25 off?really".into())
        );
    }

    #[cfg(windows)]
    #[test]
    fn kitty_shell_cwd_strips_windows_leading_slash() {
        // The PowerShell integration emits `/C:\...`; the drive letter
        // must come back without the URL-shaped leading slash, and the
        // path stays verbatim (spaces, `#`, `%` untouched).
        assert_eq!(
            cwd("kitty-shell-cwd:///C:\\Users\\a b"),
            Some("C:\\Users\\a b".into())
        );
        assert_eq!(
            cwd("kitty-shell-cwd://localhost/C:\\projects\\c#"),
            Some("C:\\projects\\c#".into())
        );
    }

    #[cfg(unix)]
    #[test]
    fn kitty_shell_cwd_rejects_remote_hosts() {
        assert_eq!(
            cwd("kitty-shell-cwd://other-machine.example/home/user"),
            None
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn current_directory_percent_decodes() {
        assert_eq!(
            cwd("file:///home/My%20Files"),
            Some("/home/My Files".into())
        );
        // Multi-byte UTF-8 arrives as a run of escapes.
        assert_eq!(
            cwd("file:///home/%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82"),
            Some("/home/Ῥόδος".into())
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn current_directory_keeps_malformed_escapes() {
        // A stray or truncated `%` is shown as sent rather than discarded.
        assert_eq!(cwd("file:///home/100%"), Some("/home/100%".into()));
        assert_eq!(cwd("file:///home/a%zz"), Some("/home/a%zz".into()));
        assert_eq!(cwd("file:///home/a%2"), Some("/home/a%2".into()));
    }

    #[cfg(not(windows))]
    #[test]
    fn current_directory_ignores_query_and_fragment() {
        assert_eq!(cwd("file:///home/user?x=1"), Some("/home/user".into()));
        assert_eq!(cwd("file:///home/user#frag"), Some("/home/user".into()));
    }

    #[cfg(not(windows))]
    #[test]
    fn current_directory_rejects_non_hex_escapes() {
        // `from_str_radix` accepts a leading sign, so `%+A` must not decode.
        assert_eq!(cwd("file:///home/a%+A"), Some("/home/a%+A".into()));
        assert_eq!(cwd("file:///home/a% 1"), Some("/home/a% 1".into()));
    }

    #[test]
    fn current_directory_rejects_invalid_utf8_escapes() {
        // Decoding must still yield valid UTF-8.
        assert_eq!(cwd("file:///home/%FF%FE"), None);
    }

    /// The unit tests above call the helper directly; this drives a real
    /// terminal through the parser so the OSC 7 wiring is covered too.
    #[cfg(not(windows))]
    #[test]
    fn osc7_sets_current_directory_end_to_end() {
        use crate::ansi::CursorShape;
        use crate::crosswords::{Crosswords, CrosswordsSize};
        use crate::event::{VoidListener, WindowId};
        use crate::performer::handler::Processor;

        let mut term = Crosswords::new(
            CrosswordsSize::new(20, 5),
            CursorShape::Block,
            VoidListener,
            WindowId::from(0),
            0,
            10,
        );
        let mut processor = Processor::default();

        processor.advance(&mut term, b"\x1b]7;file:///home/My%20Files\x1b\\");
        assert_eq!(
            term.current_directory.as_deref(),
            Some(std::path::Path::new("/home/My Files"))
        );

        // A directory on someone else's machine leaves ours in place.
        processor.advance(
            &mut term,
            b"\x1b]7;file://not-this-machine.invalid/tmp\x1b\\",
        );
        assert_eq!(
            term.current_directory.as_deref(),
            Some(std::path::Path::new("/home/My Files"))
        );
    }
}