bmrk 0.4.0

A fast TUI for directory navigation and bookmark management
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
use anyhow::Result;
use crossterm::{
    cursor::MoveTo,
    event::{
        self, DisableMouseCapture, EnableMouseCapture, Event, KeyEventKind, MouseEvent,
        MouseEventKind,
    },
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    ExecutableCommand,
};
use ratatui::{backend::CrosstermBackend, layout::Rect, Terminal, TerminalOptions, Viewport};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};

use crate::app::App;

/// RAII guard that runs a cleanup closure on drop unless explicitly disarmed.
/// Used to ensure terminal state (raw mode, flags) is restored when setup fails partway through.
struct OnErrGuard<F: FnMut()> {
    armed: bool,
    cleanup: F,
}

impl<F: FnMut()> OnErrGuard<F> {
    fn new(cleanup: F) -> Self {
        Self {
            armed: true,
            cleanup,
        }
    }

    /// Disarm the guard — cleanup will NOT run on drop (setup succeeded).
    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl<F: FnMut()> Drop for OnErrGuard<F> {
    fn drop(&mut self) {
        if self.armed {
            (self.cleanup)();
        }
    }
}

/// Compact mode height in rows (1 header + content rows)
pub const COMPACT_HEIGHT: u16 = 8;

/// Global flag: true when compact inline mode is active (used by panic hook)
static IS_COMPACT_MODE: AtomicBool = AtomicBool::new(false);

/// Row where compact viewport starts (absolute screen row, 0-indexed)
static COMPACT_START_ROW: AtomicU16 = AtomicU16::new(0);

/// Install panic hook to ensure terminal is always cleaned up
pub fn install_panic_hook() {
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        // Clean up whichever terminal mode is active
        if IS_COMPACT_MODE.load(Ordering::Relaxed) {
            let _ = cleanup_terminal_compact();
        } else {
            let _ = cleanup_terminal();
        }
        original_hook(panic_info);
    }));
}

#[allow(dead_code)]
pub fn setup_terminal() -> Result<Terminal<CrosstermBackend<std::io::Stderr>>> {
    // Install panic hook before any terminal modifications
    install_panic_hook();
    IS_COMPACT_MODE.store(false, Ordering::Relaxed);

    enable_raw_mode()?;
    std::io::stderr().execute(EnterAlternateScreen)?;
    std::io::stderr().execute(EnableMouseCapture)?;

    let backend = CrosstermBackend::new(std::io::stderr());
    let terminal = Terminal::new(backend)?;

    Ok(terminal)
}

/// Set up a compact inline terminal that occupies only COMPACT_HEIGHT rows.
/// The inline viewport appears at the current cursor position without taking
/// over the full screen. On cleanup, the area is erased and the terminal
/// returns to its pre-launch state.
pub fn setup_terminal_compact() -> Result<Terminal<CrosstermBackend<std::io::Stderr>>> {
    install_panic_hook();

    // Enable raw mode first (needed for cursor position query on Unix).
    // If this fails we return immediately — nothing to clean up yet.
    enable_raw_mode()?;

    // From here any `?` would leak raw mode (and, once EnableMouseCapture is sent below,
    // mouse tracking too). The guard ensures both are cleaned up on every error path;
    // disarm() is called on success. DisableMouseCapture is safe to send even before
    // EnableMouseCapture has run — crossterm's disable sequence is a no-op on a terminal
    // that never received the enable sequence (see .debug/BDP.md Part 5, Finding #1).
    IS_COMPACT_MODE.store(true, Ordering::Relaxed);
    let mut raw_guard = OnErrGuard::new(|| {
        let _ = std::io::stderr().execute(DisableMouseCapture);
        let _ = disable_raw_mode();
        IS_COMPACT_MODE.store(false, Ordering::Relaxed);
    });

    // Query cursor position via /dev/tty so it works even when stdout is a pipe
    // (e.g. when launched from a shell subshell: result=$(bmrk "$@")).
    // crossterm::cursor::position() writes \x1B[6n to stdout, which fails when
    // stdout is piped. We write to stderr instead and read from /dev/tty directly.
    let (_, cursor_row) = query_cursor_position();
    let (term_width, term_height) = crossterm::terminal::size().unwrap_or((80, 24));

    // Replicate ratatui's compute_inline_size logic:
    //   1. Scroll the terminal to make room below the cursor.
    //   2. Compute the fixed viewport rect (adjusting start row if terminal scrolled).
    // Using Viewport::Fixed avoids any further cursor::position() calls during draws.
    let max_height = term_height.min(COMPACT_HEIGHT);
    let lines_after_cursor = COMPACT_HEIGHT.saturating_sub(1);
    let available_lines = term_height.saturating_sub(cursor_row).saturating_sub(1);
    let missing_lines = lines_after_cursor.saturating_sub(available_lines);

    {
        use std::io::Write;
        for _ in 0..lines_after_cursor {
            let _ = writeln!(std::io::stderr());
        }
        let _ = std::io::stderr().flush();
    }

    let start_row = cursor_row.saturating_sub(missing_lines);
    COMPACT_START_ROW.store(start_row, Ordering::Relaxed);

    let viewport_area = Rect {
        x: 0,
        y: start_row,
        width: term_width,
        height: max_height,
    };

    std::io::stderr().execute(EnableMouseCapture)?;

    let backend = CrosstermBackend::new(std::io::stderr());
    let terminal = Terminal::with_options(
        backend,
        TerminalOptions {
            viewport: Viewport::Fixed(viewport_area),
        },
    )?;

    raw_guard.disarm(); // setup complete — cleanup_terminal_compact() owns teardown from here
    Ok(terminal)
}

/// How often the background CPR reader thread pauses its blocking read to check whether it's
/// been cancelled. Keeps the thread's lifetime bounded to roughly this long past cancellation,
/// instead of blocking on the tty fd indefinitely when no reply ever arrives.
#[cfg(unix)]
const CPR_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);

/// Query cursor position by writing the CPR escape sequence to stderr and
/// reading the response from /dev/tty. Works even when stdout is a pipe.
/// Returns (col, row) zero-based, or (0, 0) on failure.
#[cfg(unix)]
fn query_cursor_position() -> (u16, u16) {
    use std::io::Write;
    use std::sync::Arc;
    use std::time::Duration;

    if std::io::stderr().write_all(b"\x1B[6n").is_err() || std::io::stderr().flush().is_err() {
        return (0, 0);
    }

    // Read the CPR response in a thread so we can enforce a timeout.
    let Ok(tty) = std::fs::OpenOptions::new().read(true).open("/dev/tty") else {
        return (0, 0);
    };

    let cancelled = Arc::new(AtomicBool::new(false));
    let cancelled_thread = Arc::clone(&cancelled);
    let (tx, rx) = std::sync::mpsc::channel::<Vec<u8>>();
    std::thread::spawn(move || {
        let data = read_cpr_reply(tty, &cancelled_thread, CPR_POLL_INTERVAL);
        let _ = tx.send(data);
    });

    let data = rx
        .recv_timeout(Duration::from_millis(500))
        .unwrap_or_default();

    // No reply (real terminal replies in ~1ms; nothing did here) — tell the reader thread to
    // stop. It notices within one CPR_POLL_INTERVAL instead of blocking on /dev/tty, racing the
    // main input loop for bytes, for the rest of the process's lifetime.
    cancelled.store(true, Ordering::Relaxed);

    parse_cpr_response(&data).unwrap_or((0, 0))
}

/// Read bytes one at a time from `reader` until a trailing `'R'` (end of a CPR reply) is seen,
/// `reader` hits EOF/error, or `cancelled` is set. Waits at most `poll_interval` between checks
/// of `cancelled`, so — unlike a plain blocking `read()` loop — this always returns in bounded
/// time after cancellation even if the other end of `reader` never sends anything.
#[cfg(unix)]
fn read_cpr_reply<R: std::io::Read + std::os::fd::AsRawFd>(
    mut reader: R,
    cancelled: &std::sync::atomic::AtomicBool,
    poll_interval: std::time::Duration,
) -> Vec<u8> {
    let fd = reader.as_raw_fd();
    let mut buf = Vec::with_capacity(16);
    let mut byte = [0u8; 1];

    loop {
        if cancelled.load(Ordering::Relaxed) {
            return buf;
        }
        match poll_readable(fd, poll_interval) {
            Ok(true) => {}
            Ok(false) => continue, // timed out waiting for data — recheck cancellation
            Err(_) => return buf,
        }
        match reader.read(&mut byte) {
            Ok(1) => {
                buf.push(byte[0]);
                if byte[0] == b'R' {
                    return buf;
                }
            }
            _ => return buf,
        }
    }
}

/// Block for up to `timeout` waiting for `fd` to become readable. Returns `Ok(true)` if data
/// (or EOF) is available, `Ok(false)` on timeout.
#[cfg(unix)]
fn poll_readable(fd: std::os::fd::RawFd, timeout: std::time::Duration) -> std::io::Result<bool> {
    let mut fds = [libc::pollfd {
        fd,
        events: libc::POLLIN,
        revents: 0,
    }];
    let timeout_ms = i32::try_from(timeout.as_millis()).unwrap_or(i32::MAX);
    let ready = unsafe { libc::poll(fds.as_mut_ptr(), 1, timeout_ms) };
    if ready < 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(fds[0].revents & libc::POLLIN != 0)
}

/// Parse a VT100 cursor position report `ESC [ row ; col R` (1-based) into
/// zero-based (col, row).
#[cfg(unix)]
fn parse_cpr_response(data: &[u8]) -> Option<(u16, u16)> {
    let s = std::str::from_utf8(data).ok()?;
    // Find the last ESC[ to skip any preceding input noise
    let after_esc = s.rsplit("\x1B[").next()?;
    let inner = after_esc.strip_suffix('R')?;
    let (row_s, col_s) = inner.split_once(';')?;
    let row: u16 = row_s.parse().ok()?;
    let col: u16 = col_s.parse().ok()?;
    Some((col.saturating_sub(1), row.saturating_sub(1)))
}

#[cfg(not(unix))]
fn query_cursor_position() -> (u16, u16) {
    crossterm::cursor::position().unwrap_or((0, 0))
}

/// Clean up after compact inline mode.
/// Erases the COMPACT_HEIGHT rows that were drawn and restores the cursor to
/// its position before the program launched — leaving the terminal clean.
pub fn cleanup_terminal_compact() -> Result<()> {
    use std::io::Write;

    IS_COMPACT_MODE.store(false, Ordering::Relaxed);

    // 1. Disable all mouse tracking modes
    let _ = write!(std::io::stderr(), "\x1b[?1000l");
    let _ = write!(std::io::stderr(), "\x1b[?1002l");
    let _ = write!(std::io::stderr(), "\x1b[?1003l");
    let _ = write!(std::io::stderr(), "\x1b[?1006l");
    let _ = write!(std::io::stderr(), "\x1b[?1015l");
    let _ = std::io::stderr().execute(DisableMouseCapture);
    let _ = std::io::stderr().flush();

    // 2. Give terminal time to process mouse-disable commands
    std::thread::sleep(std::time::Duration::from_millis(20));

    // 3. Drain any queued input events
    let mut drain_count = 0;
    while event::poll(std::time::Duration::from_millis(0)).unwrap_or(false) && drain_count < 100 {
        let _ = event::read();
        drain_count += 1;
    }

    // 4. Disable raw mode
    let _ = disable_raw_mode();

    // 5. Move cursor to the first row of our inline viewport and erase downward.
    //    This removes every line we drew, leaving no visual artifacts.
    let start_row = COMPACT_START_ROW.load(Ordering::Relaxed);
    let _ = std::io::stderr().execute(MoveTo(0, start_row));
    let _ = write!(std::io::stderr(), "\x1b[0J"); // clear from cursor to end of screen

    // 6. Second event drain after mode changes
    std::thread::sleep(std::time::Duration::from_millis(10));
    let mut drain_count2 = 0;
    while event::poll(std::time::Duration::from_millis(0)).unwrap_or(false) && drain_count2 < 50 {
        let _ = event::read();
        drain_count2 += 1;
    }

    // 7. Reset attributes and show cursor
    let _ = write!(std::io::stderr(), "\x1b[0m\x1b[?25h");
    let _ = std::io::stderr().flush();

    Ok(())
}

pub fn cleanup_terminal() -> Result<()> {
    use crossterm::terminal::{Clear, ClearType};
    use std::io::Write;

    // Restore terminal state in reverse order of setup

    // 1. CRITICAL: Explicitly disable ALL mouse tracking modes
    //    This is more thorough than just DisableMouseCapture
    let _ = write!(std::io::stderr(), "\x1b[?1000l"); // Disable X10 mouse
    let _ = write!(std::io::stderr(), "\x1b[?1002l"); // Disable cell motion
    let _ = write!(std::io::stderr(), "\x1b[?1003l"); // Disable all motion
    let _ = write!(std::io::stderr(), "\x1b[?1006l"); // Disable SGR mode
    let _ = write!(std::io::stderr(), "\x1b[?1015l"); // Disable urxvt mode
    let _ = std::io::stderr().execute(DisableMouseCapture);
    let _ = std::io::stderr().flush();

    // 2. Give terminal MORE time to process mouse disable commands
    //    Increased to 20ms to handle slow terminals
    std::thread::sleep(std::time::Duration::from_millis(20));

    // 3. First aggressive drain of pending events
    let mut drain_count = 0;
    while event::poll(std::time::Duration::from_millis(0)).unwrap_or(false) && drain_count < 100 {
        let _ = event::read();
        drain_count += 1;
    }

    // 4. Clear alternate screen before leaving it
    let _ = std::io::stderr().execute(Clear(ClearType::All));
    let _ = std::io::stderr().flush();

    // 5. Leave alternate screen
    let _ = std::io::stderr().execute(LeaveAlternateScreen);
    let _ = std::io::stderr().flush();

    // 6. IMPORTANT: Another delay + drain AFTER leaving alternate screen
    //    Sometimes events leak during the screen transition
    std::thread::sleep(std::time::Duration::from_millis(10));

    let mut drain_count2 = 0;
    while event::poll(std::time::Duration::from_millis(0)).unwrap_or(false) && drain_count2 < 50 {
        let _ = event::read();
        drain_count2 += 1;
    }

    // 7. Disable raw mode (this should stop all special terminal modes)
    let _ = disable_raw_mode();

    // 8. Send minimal reset sequences (no screen clearing!)
    //    Reset character attributes (SGR 0)
    let _ = write!(std::io::stderr(), "\x1b[0m");
    //    Show cursor
    let _ = write!(std::io::stderr(), "\x1b[?25h");
    let _ = std::io::stderr().flush();

    // 9. Final delay to ensure terminal processes everything
    std::thread::sleep(std::time::Duration::from_millis(10));

    Ok(())
}

pub fn run_app(
    terminal: &mut Terminal<CrosstermBackend<std::io::Stderr>>,
    app: &mut App,
) -> Result<Option<PathBuf>> {
    loop {
        // Only render when needed (dirty flag optimization)
        if app.needs_redraw() {
            terminal.draw(|f| app.render(f))?;
            app.clear_dirty();
        }

        // Wait up to 8ms for the first event; on timeout poll async updates and continue
        if !event::poll(std::time::Duration::from_millis(8))? {
            let _ = app.poll_search();
            let _ = app.poll_quick_jump();
            let _ = app.poll_dir_index_build();
            let _ = app.poll_disks();
            continue;
        }

        // Drain all accumulated events before next render.
        // Scroll events are coalesced: only the last scroll event per direction
        // is applied, preventing jumpy navigation when the OS buffers multiple
        // wheel ticks before the next render frame.
        let mut scroll_up_event: Option<MouseEvent> = None;
        let mut scroll_down_event: Option<MouseEvent> = None;
        loop {
            if event::poll(std::time::Duration::from_millis(0))? {
                match event::read()? {
                    Event::Key(key) => {
                        if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
                            match app.handle_key(key)? {
                                Some(path) if !path.as_os_str().is_empty() => {
                                    return Ok(Some(path));
                                }
                                None => {
                                    return Ok(None);
                                }
                                _ => {}
                            }
                        }
                    }
                    Event::Mouse(mouse) => match mouse.kind {
                        MouseEventKind::ScrollUp => scroll_up_event = Some(mouse),
                        MouseEventKind::ScrollDown => scroll_down_event = Some(mouse),
                        _ => {
                            let _ = app.handle_mouse(mouse);
                        }
                    },
                    Event::Resize(_width, _height) => {
                        app.mark_dirty();
                    }
                    _ => {}
                }
            } else {
                break;
            }
        }
        if let Some(mouse) = scroll_up_event {
            let _ = app.handle_mouse(mouse);
        }
        if let Some(mouse) = scroll_down_event {
            let _ = app.handle_mouse(mouse);
        }
    }
}

// `setup_terminal_compact`'s error-cleanup guard also sends `DisableMouseCapture` on drop
// (see .debug/BDP.md Part 5, Finding #1: a leaked EnableMouseCapture on a failed setup left
// mouse tracking on with no cleanup). That line has no dedicated test — it needs a real
// tty/backend to observe — so the guard mechanism itself (below) is what's covered; don't
// drop the DisableMouseCapture call from the closure without noticing it has no other guard.
#[cfg(test)]
mod tests {
    use super::OnErrGuard;

    #[test]
    fn on_err_guard_fires_cleanup_when_dropped_armed() {
        let mut calls = 0;
        {
            let _g = OnErrGuard::new(|| calls += 1);
            // dropped here without disarm → cleanup must run
        }
        assert_eq!(calls, 1, "cleanup should run exactly once on armed drop");
    }

    #[test]
    fn on_err_guard_skips_cleanup_when_disarmed() {
        let mut calls = 0;
        {
            let mut g = OnErrGuard::new(|| calls += 1);
            g.disarm();
            // dropped here after disarm → cleanup must NOT run
        }
        assert_eq!(calls, 0, "cleanup must not run after disarm");
    }

    #[test]
    fn on_err_guard_fires_on_early_question_mark() {
        // Simulates the `?` path in setup_terminal_compact: armed guard drops when
        // the enclosing function returns Err.
        fn setup_that_fails(calls: &mut i32) -> Result<(), String> {
            let mut guard = OnErrGuard::new(|| *calls += 1);
            Err("injected failure".to_string())?; // guard drops here (armed)
            guard.disarm();
            Ok(())
        }

        let mut n = 0;
        assert!(setup_that_fails(&mut n).is_err());
        assert_eq!(n, 1, "cleanup must run when setup returns Err");
    }

    // --- CPR reader thread cancellation (regression: .debug/orphaned-cpr-thread-bug.md) ---
    //
    // Before the fix, `read_cpr_reply`'s predecessor blocked on a plain `read()` call with no
    // way to notice cancellation, so it could run for the lifetime of the process if the other
    // end of the fd never sent a reply — racing the main input loop for bytes indefinitely.
    // These tests use a real pipe (no /dev/tty required) to verify the fixed version always
    // returns promptly once cancelled, and still reads normally when data does arrive.

    #[cfg(unix)]
    #[test]
    fn poll_readable_times_out_with_no_data() {
        use super::poll_readable;
        use std::time::Duration;

        let (reader, _writer) = std::io::pipe().unwrap();
        let ready = poll_readable(
            std::os::fd::AsRawFd::as_raw_fd(&reader),
            Duration::from_millis(20),
        )
        .unwrap();
        assert!(!ready, "must time out when nothing was written");
    }

    #[cfg(unix)]
    #[test]
    fn poll_readable_detects_available_data() {
        use super::poll_readable;
        use std::io::Write;
        use std::time::Duration;

        let (reader, mut writer) = std::io::pipe().unwrap();
        writer.write_all(b"x").unwrap();
        let ready = poll_readable(
            std::os::fd::AsRawFd::as_raw_fd(&reader),
            Duration::from_millis(200),
        )
        .unwrap();
        assert!(ready, "must report readable once data has been written");
    }

    #[cfg(unix)]
    #[test]
    fn read_cpr_reply_exits_promptly_when_cancelled_with_no_data() {
        use super::read_cpr_reply;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;
        use std::time::{Duration, Instant};

        let (reader, _writer) = std::io::pipe().unwrap();
        let cancelled = Arc::new(AtomicBool::new(false));
        let cancelled_thread = Arc::clone(&cancelled);

        let handle = std::thread::spawn(move || {
            read_cpr_reply(reader, &cancelled_thread, Duration::from_millis(20))
        });

        // Give the reader thread time to start polling before cancelling it.
        std::thread::sleep(Duration::from_millis(50));
        cancelled.store(true, Ordering::Relaxed);

        let start = Instant::now();
        let result = handle.join().expect("reader thread must not panic");
        let elapsed = start.elapsed();

        assert!(
            result.is_empty(),
            "no data was ever written, buffer must be empty"
        );
        assert!(
            elapsed < Duration::from_millis(500),
            "reader thread must exit within a couple of poll intervals of cancellation, took {:?}",
            elapsed
        );
    }

    #[cfg(unix)]
    #[test]
    fn read_cpr_reply_returns_data_up_to_trailing_r() {
        use super::read_cpr_reply;
        use std::io::Write;
        use std::sync::atomic::AtomicBool;
        use std::sync::Arc;
        use std::time::Duration;

        let (reader, mut writer) = std::io::pipe().unwrap();
        let cancelled = Arc::new(AtomicBool::new(false));
        let cancelled_thread = Arc::clone(&cancelled);

        let handle = std::thread::spawn(move || {
            read_cpr_reply(reader, &cancelled_thread, Duration::from_millis(20))
        });

        writer.write_all(b"\x1b[24;80R").unwrap();

        let result = handle.join().expect("reader thread must not panic");
        assert_eq!(result, b"\x1b[24;80R");
    }
}