croft-software 0.1.942

VSCode-style TUI written in Rust
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
/// Read the host system clipboard as text.
///
/// On macOS, prefer NSPasteboard directly. That avoids spawning `pbpaste`
/// from croft's already-threaded TUI process, which is both slower and more
/// brittle under macOS's fork-safety rules.
///
/// On Linux, tries `wl-paste`, `xclip`, then `xsel` in that fixed order.
pub fn read_string() -> Option<String> {
    #[cfg(test)]
    {
        if !test_clip::real_clipboard_opt_in() {
            return test_clip::mock_read();
        }
    }
    #[cfg(target_os = "macos")]
    {
        if let Some(s) = macos::read_string_native() {
            return Some(s);
        }
        read_pbpaste()
    }
    #[cfg(target_os = "linux")]
    {
        linux::read_string()
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        None
    }
}

#[cfg(target_os = "macos")]
fn read_pbpaste() -> Option<String> {
    let out = std::process::Command::new("pbpaste").output().ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).to_string())
}

/// Put `text` on the host system clipboard as UTF-8 plain text. Returns
/// `true` when the write was acknowledged by the OS pasteboard.
///
/// On macOS we go straight to `NSPasteboard.setString:forType:` so the
/// embedded TUI's Cmd+C lands on the system clipboard with the same
/// guarantees as a native Cocoa app — independent of whether the host
/// terminal (iTerm2 etc.) chooses to honour OSC 52, which empirically
/// it does not in every environment even with `AllowClipboardAccess` set.
/// `pbcopy` is the second fall-back so we cover the case where the
/// objc runtime resolves but `NSPasteboard` rejects the write for some
/// sandboxing reason.
///
/// On Linux, tries `wl-copy`, `xclip`, then `xsel` in that fixed order.
/// Returns `false` only when none of those tools are available, in which
/// case the caller falls back to OSC 52 (useful for remote SSH sessions).
pub fn write_string(text: &str) -> bool {
    // NSPasteboard / NSString cannot carry an embedded NUL — `stringWithUTF8String:`
    // truncates at the first 0x00 — and silently truncating user data is far
    // worse than refusing the write. Reject up front so the caller can decide
    // what to do (terminal selection text already maps NUL to space in
    // `extract_selection_text`, so this branch is defensive, not load-bearing).
    if text.as_bytes().contains(&0) {
        return false;
    }
    #[cfg(test)]
    {
        if !test_clip::real_clipboard_opt_in() {
            return test_clip::mock_write(text);
        }
    }
    #[cfg(target_os = "macos")]
    {
        if macos::write_string_native(text) {
            return true;
        }
        write_pbcopy(text)
    }
    #[cfg(target_os = "linux")]
    {
        linux::write_string(text)
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        false
    }
}

#[cfg(target_os = "linux")]
mod linux {
    use std::io::Write;
    use std::process::{Command, Stdio};

    /// Write `text` to the system clipboard on Linux.
    ///
    /// Tries `wl-copy`, then `xclip`, then `xsel`. Returns `true`
    /// when one of them succeeded. Returns `false` when none are installed,
    /// which happens in headless SSH sessions — the caller sends OSC 52 then.
    pub fn write_string(text: &str) -> bool {
        write_via(&["wl-copy"], text)
            || write_via(&["xclip", "-selection", "clipboard"], text)
            || write_via(&["xsel", "--clipboard", "--input"], text)
    }

    fn write_via(argv: &[&str], text: &str) -> bool {
        let Ok(mut child) = Command::new(argv[0])
            .args(&argv[1..])
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
        else {
            return false;
        };
        let Some(mut stdin) = child.stdin.take() else {
            let _ = child.wait();
            return false;
        };
        if stdin.write_all(text.as_bytes()).is_err() {
            let _ = child.wait();
            return false;
        }
        drop(stdin);
        child.wait().map(|s| s.success()).unwrap_or(false)
    }

    /// Read text from the system clipboard on Linux.
    ///
    /// Tries `wl-paste`, then `xclip`, then `xsel`.
    pub fn read_string() -> Option<String> {
        read_via(&["wl-paste"])
            .or_else(|| read_via(&["xclip", "-selection", "clipboard", "-o"]))
            .or_else(|| read_via(&["xsel", "--clipboard", "--output"]))
    }

    fn read_via(argv: &[&str]) -> Option<String> {
        let out = Command::new(argv[0])
            .args(&argv[1..])
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        Some(String::from_utf8_lossy(&out.stdout).to_string())
    }
}

#[cfg(target_os = "macos")]
fn write_pbcopy(text: &str) -> bool {
    use std::io::Write;
    use std::process::{Command, Stdio};
    let Ok(mut child) = Command::new("pbcopy")
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return false;
    };
    let Some(mut stdin) = child.stdin.take() else {
        let _ = child.wait();
        return false;
    };
    if stdin.write_all(text.as_bytes()).is_err() {
        let _ = child.wait();
        return false;
    }
    drop(stdin);
    child.wait().map(|st| st.success()).unwrap_or(false)
}

#[cfg(target_os = "macos")]
pub(crate) mod macos {
    use std::ffi::CStr;
    use std::os::raw::{c_char, c_void};

    type ObjcId = *mut c_void;
    type Sel = *mut c_void;

    #[link(name = "objc")]
    unsafe extern "C" {
        fn objc_getClass(name: *const c_char) -> ObjcId;
        fn sel_registerName(name: *const c_char) -> Sel;
        fn objc_autoreleasePoolPush() -> *mut c_void;
        fn objc_autoreleasePoolPop(pool: *mut c_void);
        fn objc_msgSend();
    }

    #[link(name = "AppKit", kind = "framework")]
    unsafe extern "C" {}

    pub fn read_string_native() -> Option<String> {
        unsafe {
            let pool = objc_autoreleasePoolPush();
            let result = read_string_native_inner();
            objc_autoreleasePoolPop(pool);
            result
        }
    }

    unsafe fn read_string_native_inner() -> Option<String> {
        unsafe {
            let pasteboard_class = class(b"NSPasteboard\0")?;
            let pasteboard = msg_send_id(pasteboard_class, sel(b"generalPasteboard\0")?);
            if pasteboard.is_null() {
                return None;
            }

            for type_name in [
                b"public.utf8-plain-text\0".as_slice(),
                b"public.plain-text\0".as_slice(),
                b"public.text\0".as_slice(),
                b"NSStringPboardType\0".as_slice(),
            ] {
                if let Some(value) = pasteboard_string_for_type(pasteboard, type_name) {
                    return Some(value);
                }
            }

            None
        }
    }

    unsafe fn pasteboard_string_for_type(
        pasteboard: ObjcId,
        type_name: &'static [u8],
    ) -> Option<String> {
        unsafe {
            let string_class = class(b"NSString\0")?;
            let pasteboard_type = msg_send_id_ptr(
                string_class,
                sel(b"stringWithUTF8String:\0")?,
                type_name.as_ptr().cast(),
            );
            if pasteboard_type.is_null() {
                return None;
            }

            let value = msg_send_id_id(pasteboard, sel(b"stringForType:\0")?, pasteboard_type);
            if value.is_null() {
                return None;
            }
            let utf8 = msg_send_ptr(value, sel(b"UTF8String\0")?);
            if utf8.is_null() {
                return None;
            }

            Some(CStr::from_ptr(utf8).to_string_lossy().into_owned())
        }
    }

    unsafe fn class(name: &'static [u8]) -> Option<ObjcId> {
        let c = unsafe { objc_getClass(name.as_ptr().cast()) };
        (!c.is_null()).then_some(c)
    }

    unsafe fn sel(name: &'static [u8]) -> Option<Sel> {
        let s = unsafe { sel_registerName(name.as_ptr().cast()) };
        (!s.is_null()).then_some(s)
    }

    unsafe fn msg_send_id(receiver: ObjcId, selector: Sel) -> ObjcId {
        unsafe {
            let f: unsafe extern "C" fn(ObjcId, Sel) -> ObjcId =
                std::mem::transmute(objc_msgSend as *const ());
            f(receiver, selector)
        }
    }

    unsafe fn msg_send_id_ptr(receiver: ObjcId, selector: Sel, arg: *const c_char) -> ObjcId {
        unsafe {
            let f: unsafe extern "C" fn(ObjcId, Sel, *const c_char) -> ObjcId =
                std::mem::transmute(objc_msgSend as *const ());
            f(receiver, selector, arg)
        }
    }

    unsafe fn msg_send_id_id(receiver: ObjcId, selector: Sel, arg: ObjcId) -> ObjcId {
        unsafe {
            let f: unsafe extern "C" fn(ObjcId, Sel, ObjcId) -> ObjcId =
                std::mem::transmute(objc_msgSend as *const ());
            f(receiver, selector, arg)
        }
    }

    unsafe fn msg_send_ptr(receiver: ObjcId, selector: Sel) -> *const c_char {
        unsafe {
            let f: unsafe extern "C" fn(ObjcId, Sel) -> *const c_char =
                std::mem::transmute(objc_msgSend as *const ());
            f(receiver, selector)
        }
    }

    pub fn write_string_native(text: &str) -> bool {
        unsafe {
            let pool = objc_autoreleasePoolPush();
            let ok = write_string_inner(text);
            objc_autoreleasePoolPop(pool);
            ok
        }
    }

    /// Wipe NSPasteboard's contents. Used by the test guard's drop path
    /// to wipe a leftover test sentinel when no prior clipboard text was
    /// snapshotted at acquire-time.
    #[cfg(test)]
    pub fn clear_native() {
        unsafe {
            let pool = objc_autoreleasePoolPush();
            clear_inner();
            objc_autoreleasePoolPop(pool);
        }
    }

    #[cfg(test)]
    unsafe fn clear_inner() {
        unsafe {
            let Some(pb_class) = class(b"NSPasteboard\0") else {
                return;
            };
            let Some(general_sel) = sel(b"generalPasteboard\0") else {
                return;
            };
            let pasteboard = msg_send_id(pb_class, general_sel);
            if pasteboard.is_null() {
                return;
            }
            let Some(clear_sel) = sel(b"clearContents\0") else {
                return;
            };
            let _ = msg_send_isize(pasteboard, clear_sel);
        }
    }

    unsafe fn write_string_inner(text: &str) -> bool {
        unsafe {
            let Some(pb_class) = class(b"NSPasteboard\0") else {
                return false;
            };
            let Some(general_sel) = sel(b"generalPasteboard\0") else {
                return false;
            };
            let pasteboard = msg_send_id(pb_class, general_sel);
            if pasteboard.is_null() {
                return false;
            }

            let Some(clear_sel) = sel(b"clearContents\0") else {
                return false;
            };
            let _ = msg_send_isize(pasteboard, clear_sel);

            let Some(nsstring_class) = class(b"NSString\0") else {
                return false;
            };
            let Some(utf8_sel) = sel(b"stringWithUTF8String:\0") else {
                return false;
            };

            let Ok(payload) = std::ffi::CString::new(text) else {
                return false;
            };
            let value = msg_send_id_ptr(nsstring_class, utf8_sel, payload.as_ptr());
            if value.is_null() {
                return false;
            }

            let Ok(type_cstr) = std::ffi::CString::new("public.utf8-plain-text") else {
                return false;
            };
            let type_nsstr = msg_send_id_ptr(nsstring_class, utf8_sel, type_cstr.as_ptr());
            if type_nsstr.is_null() {
                return false;
            }

            let Some(set_string_sel) = sel(b"setString:forType:\0") else {
                return false;
            };
            msg_send_bool_id_id(pasteboard, set_string_sel, value, type_nsstr)
        }
    }

    unsafe fn msg_send_isize(receiver: ObjcId, selector: Sel) -> isize {
        unsafe {
            let f: unsafe extern "C" fn(ObjcId, Sel) -> isize =
                std::mem::transmute(objc_msgSend as *const ());
            f(receiver, selector)
        }
    }

    unsafe fn msg_send_bool_id_id(
        receiver: ObjcId,
        selector: Sel,
        arg1: ObjcId,
        arg2: ObjcId,
    ) -> bool {
        unsafe {
            let f: unsafe extern "C" fn(ObjcId, Sel, ObjcId, ObjcId) -> u8 =
                std::mem::transmute(objc_msgSend as *const ());
            f(receiver, selector, arg1, arg2) != 0
        }
    }
}

/// Test-only support for keeping clipboard tests deterministic.
///
/// Under `cargo test` the binary's tests run on a shared thread pool. If
/// `write_string` always went to the real `NSPasteboard`, every test in
/// the crate that exercises a copy gesture (terminal copy, editor copy,
/// editor cut, kill-to-EOL, ring-yank, …) would stomp on the host
/// clipboard concurrently with the clipboard regression tests, and the
/// round-trip assertions would flake on whichever write landed last.
///
/// The chosen design: `write_string` and `read_string` route to a
/// per-thread mock by default during tests. Tests that need to prove the
/// real macOS pasteboard path (the FFI bridge in `mod macos`) opt in
/// explicitly via `lock_clipboard_for_test`, which:
///   * Acquires a process-global `Mutex` so only one test at a time
///     drives the real OS clipboard.
///   * Flips the per-thread `REAL_OPT_IN` cell to `true` so
///     `write_string` / `read_string` skip the mock for the duration
///     of the guard.
#[cfg(test)]
pub(crate) mod test_clip {
    use std::cell::{Cell, RefCell};
    use std::sync::{Mutex, MutexGuard};

    pub(crate) static CLIP_LOCK: Mutex<()> = Mutex::new(());

    thread_local! {
        static REAL_OPT_IN: Cell<bool> = const { Cell::new(false) };
        static MOCK: RefCell<Option<String>> = const { RefCell::new(None) };
    }

    pub(crate) fn real_clipboard_opt_in() -> bool {
        REAL_OPT_IN.with(|c| c.get())
    }

    pub(crate) fn mock_write(text: &str) -> bool {
        MOCK.with(|b| *b.borrow_mut() = Some(text.to_string()));
        true
    }

    pub(crate) fn mock_read() -> Option<String> {
        MOCK.with(|b| b.borrow().clone())
    }

    /// Read the host clipboard through the platform-native backend, bypassing
    /// the opt-in routing. Used to snapshot the real clipboard before a
    /// real-clipboard test runs so it can be restored afterwards.
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    fn native_read() -> Option<String> {
        #[cfg(target_os = "macos")]
        {
            super::macos::read_string_native()
        }
        #[cfg(target_os = "linux")]
        {
            super::linux::read_string()
        }
    }

    /// Restore the host clipboard to `prev` (or wipe it if there was nothing),
    /// through the platform-native backend.
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    fn native_restore(prev: Option<String>) {
        match prev {
            Some(text) => {
                #[cfg(target_os = "macos")]
                {
                    let _ = super::macos::write_string_native(&text);
                }
                #[cfg(target_os = "linux")]
                {
                    let _ = super::linux::write_string(&text);
                }
            }
            None => {
                #[cfg(target_os = "macos")]
                {
                    super::macos::clear_native();
                }
                #[cfg(target_os = "linux")]
                {
                    // Linux has no "clear"; overwriting with empty is the
                    // closest equivalent and a no-op when no backend exists.
                    let _ = super::linux::write_string("");
                }
            }
        }
    }

    /// Guard returned by `lock_clipboard_for_test`. While held, the
    /// current thread's `write_string` / `read_string` calls bypass the
    /// per-thread mock and exercise the real OS clipboard, and no
    /// other test — in this process or any other — drives the clipboard
    /// concurrently.
    ///
    /// On macOS and Linux the guard also snapshots the system clipboard at
    /// acquire-time and restores it on drop, so a `cargo test` run never
    /// leaves a test sentinel (e.g. `croft-terminal-cmdc-<pid>`) sitting
    /// on the developer's real clipboard for the next paste to surface.
    /// (On a headless box with no clipboard backend the snapshot is `None`
    /// and restore is a harmless no-op.)
    pub(crate) struct ClipboardTestGuard {
        _mutex: MutexGuard<'static, ()>,
        /// Cross-process exclusion: a process-per-test runner
        /// (cargo-nextest) gives every test its own process, so
        /// `CLIP_LOCK` alone cannot keep two tests off the ONE system
        /// pasteboard. An exclusive advisory lock on a well-known file
        /// extends the exclusion across processes; the kernel releases
        /// it when the file closes on drop — including when a test
        /// process dies, so a killed test can never wedge the rest.
        ///
        /// The lock file lives under the checkout's own `target/`, not
        /// the shared temp dir: every test process of a run compiles
        /// from the same checkout (so they agree on the path), and a
        /// user-owned directory means no other local user can pre-plant
        /// a symlink at the predictable name and have `open` clobber
        /// its target.
        _file_lock: std::fs::File,
        #[cfg(any(target_os = "macos", target_os = "linux"))]
        snapshot: Option<String>,
    }

    impl ClipboardTestGuard {
        pub(crate) fn acquire() -> Self {
            let mutex = CLIP_LOCK
                .lock()
                .unwrap_or_else(|poison| poison.into_inner());
            let lock_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("target");
            std::fs::create_dir_all(&lock_dir).expect("clipboard test lock dir must exist");
            let file_lock = std::fs::OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(lock_dir.join("croft-clipboard-test.lock"))
                .expect("clipboard test lock file must open");
            loop {
                match file_lock.lock() {
                    Ok(()) => break,
                    Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                    Err(e) => panic!("clipboard test file lock failed: {e}"),
                }
            }
            // Snapshot only once BOTH locks are held: until then the
            // pasteboard may hold another test process's sentinel, and
            // restoring that on drop would hand it to the next paste.
            #[cfg(any(target_os = "macos", target_os = "linux"))]
            let snapshot = native_read();
            REAL_OPT_IN.with(|c| c.set(true));
            Self {
                _mutex: mutex,
                _file_lock: file_lock,
                #[cfg(any(target_os = "macos", target_os = "linux"))]
                snapshot,
            }
        }
    }

    impl Drop for ClipboardTestGuard {
        fn drop(&mut self) {
            #[cfg(any(target_os = "macos", target_os = "linux"))]
            native_restore(self.snapshot.take());
            REAL_OPT_IN.with(|c| c.set(false));
        }
    }
}

#[cfg(test)]
pub(crate) fn lock_clipboard_for_test() -> test_clip::ClipboardTestGuard {
    test_clip::ClipboardTestGuard::acquire()
}

#[cfg(all(test, target_os = "macos"))]
mod tests {
    use super::*;

    fn lock_clipboard() -> test_clip::ClipboardTestGuard {
        lock_clipboard_for_test()
    }

    fn unique_sentinel(label: &str) -> String {
        format!(
            "croft-clip-{label}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        )
    }

    #[test]
    fn write_string_lands_text_on_nspasteboard_for_pbpaste_to_read() {
        let _g = lock_clipboard();
        let sentinel = unique_sentinel("plain");
        assert!(
            write_string(&sentinel),
            "write_string must succeed on macOS via NSPasteboard"
        );
        let got = read_string().expect("read_string must surface clipboard text");
        assert_eq!(
            got, sentinel,
            "what we just wrote with NSPasteboard.setString:forType: must be exactly what NSPasteboard.stringForType: returns next - if this ever drifts, Cmd+C in the croft terminal silently fails for the user"
        );
    }

    #[test]
    fn write_string_overwrites_previous_clipboard_contents() {
        let _g = lock_clipboard();
        let first = unique_sentinel("first");
        let second = unique_sentinel("second");
        assert!(write_string(&first));
        assert!(write_string(&second));
        assert_eq!(
            read_string().as_deref(),
            Some(second.as_str()),
            "the second copy must overwrite the first - clearContents+setString:forType: must not append"
        );
    }

    #[test]
    fn write_string_round_trips_unicode_payloads() {
        let _g = lock_clipboard();
        let sentinel = format!("héllo · 世界 · 🦀 · {}", unique_sentinel("unicode"));
        assert!(write_string(&sentinel));
        assert_eq!(
            read_string().as_deref(),
            Some(sentinel.as_str()),
            "multi-byte UTF-8 must round-trip - the embedded shell happily produces emoji and CJK and the clipboard must not mangle them"
        );
    }

    #[test]
    fn write_string_round_trips_multi_line_payloads() {
        let _g = lock_clipboard();
        let body = "first\nsecond\nthird";
        let sentinel = format!("{body}-{}", unique_sentinel("multiline"));
        assert!(write_string(&sentinel));
        let got = read_string().expect("clipboard read");
        assert_eq!(
            got, sentinel,
            "newline-separated terminal selections must round-trip verbatim"
        );
    }

    #[test]
    fn write_string_rejects_payloads_containing_a_nul_byte_without_panicking() {
        let _g = lock_clipboard();
        let baseline = unique_sentinel("baseline");
        assert!(write_string(&baseline));
        let with_nul = "before\0after";
        assert!(
            !write_string(with_nul),
            "embedded nul byte must surface as a clean false from write_string instead of panicking inside the FFI bridge"
        );
        assert_eq!(
            read_string().as_deref(),
            Some(baseline.as_str()),
            "a failed write must not clobber the previous clipboard contents"
        );
    }

    #[test]
    fn macos_native_write_string_succeeds_directly() {
        let _g = lock_clipboard();
        let sentinel = unique_sentinel("native-direct");
        assert!(
            macos::write_string_native(&sentinel),
            "the NSPasteboard FFI bridge itself must succeed on macOS - if this fails, pbcopy will be the production fallback and we'll know the bridge regressed"
        );
        assert_eq!(read_string().as_deref(), Some(sentinel.as_str()));
    }
}

/// Linux-backend parity for the clipboard round-trip the macOS tests above
/// cover via NSPasteboard. Exercises the real `wl-copy`/`xclip`/`xsel` path
/// through `write_string`/`read_string` (the test guard snapshots and restores
/// the developer's clipboard, so no sentinel leaks). On a headless box with
/// none of those tools installed, `write_string` returns `false` and the test
/// skips cleanly rather than failing — the same graceful degradation the
/// production OSC-52 fallback relies on.
#[cfg(all(test, target_os = "linux"))]
mod linux_backend_tests {
    use super::*;

    #[test]
    fn write_then_read_round_trips_when_a_clipboard_backend_is_available() {
        let _g = lock_clipboard_for_test();
        let sentinel = format!(
            "croft-linux-clip-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        );
        if !write_string(&sentinel) {
            // No wl-copy/xclip/xsel on this box (headless CI/SSH): nothing to
            // assert against. Treat as skipped, not failed.
            eprintln!(
                "linux_backend_tests: no clipboard backend (wl-copy/xclip/xsel) available — skipping"
            );
            return;
        }
        assert_eq!(
            read_string().as_deref(),
            Some(sentinel.as_str()),
            "a Linux clipboard backend must return exactly what write_string just put on it"
        );
    }
}

/// Parity for platforms with no integrated clipboard backend (e.g. Android,
/// where the freedesktop tools don't exist): `write_string`/`read_string` must
/// fail soft — `false` / `None`, never a panic — so the caller's OSC-52
/// fallback can take over. Mirrors the macOS and Linux coverage above for the
/// "no native backend" arm of the cfg cascade.
#[cfg(all(test, not(any(target_os = "macos", target_os = "linux"))))]
mod other_os_backend_tests {
    use super::*;

    #[test]
    fn clipboard_is_a_graceful_no_op_without_a_native_backend() {
        let _g = lock_clipboard_for_test();
        assert!(
            !write_string("croft-no-backend-probe"),
            "without a native backend, write_string must report false so the caller falls back to OSC 52"
        );
        assert_eq!(
            read_string(),
            None,
            "without a native backend, read_string must yield None rather than panic"
        );
    }
}